@adhdev/mesh-shared 1.0.82-rc.13 → 1.0.82-rc.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/assistant-protocol.d.ts +158 -6
  2. package/dist/decision-push-relay.d.ts +20 -0
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.js +1524 -110
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1391 -110
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/launch-defaults.d.ts +196 -0
  9. package/dist/light-task.d.ts +96 -0
  10. package/dist/mesh-tool-names.d.ts +2 -2
  11. package/dist/mesh-vocabulary.d.ts +6 -4
  12. package/dist/mission-git-state.d.ts +83 -0
  13. package/dist/mission-items.d.ts +202 -0
  14. package/dist/node-facts.d.ts +35 -1
  15. package/dist/outbound-message.d.ts +9 -2
  16. package/dist/protocol/daemon-server.d.ts +42 -2
  17. package/dist/protocol/dashboard-daemon-p2p.d.ts +1 -1
  18. package/dist/protocol/dashboard-server.d.ts +20 -2
  19. package/dist/quota-freshness.d.ts +4 -4
  20. package/dist/relay-reprobe.d.ts +52 -0
  21. package/dist/release.d.ts +90 -0
  22. package/dist/role-launch.d.ts +11 -0
  23. package/dist/session-launch.d.ts +10 -22
  24. package/dist/slot-proposal.d.ts +14 -0
  25. package/dist/task-source-phase.d.ts +83 -0
  26. package/dist/task-stages.d.ts +210 -0
  27. package/dist/turn-evidence.d.ts +26 -8
  28. package/dist/turn-ipc-mission.d.ts +72 -1
  29. package/dist/turn-ipc-queue.d.ts +30 -0
  30. package/dist/turn-ipc.d.ts +2 -2
  31. package/dist/worker-protocol.d.ts +41 -1
  32. package/package.json +1 -1
  33. package/src/assistant-protocol.ts +294 -6
  34. package/src/daemon-normalize.ts +7 -5
  35. package/src/decision-push-relay.ts +23 -0
  36. package/src/index.ts +11 -0
  37. package/src/launch-defaults.ts +170 -0
  38. package/src/light-task.ts +116 -0
  39. package/src/mesh-tool-names.ts +22 -0
  40. package/src/mesh-vocabulary.ts +4 -2
  41. package/src/mission-git-state.ts +112 -0
  42. package/src/mission-items.ts +421 -0
  43. package/src/node-facts.ts +35 -1
  44. package/src/outbound-message.ts +19 -0
  45. package/src/protocol/daemon-server.ts +37 -2
  46. package/src/protocol/dashboard-server.ts +13 -2
  47. package/src/quota-freshness.ts +22 -11
  48. package/src/relay-reprobe.ts +117 -0
  49. package/src/release.ts +121 -0
  50. package/src/role-launch.ts +51 -0
  51. package/src/session-launch.ts +17 -1
  52. package/src/slot-proposal.ts +61 -2
  53. package/src/task-source-phase.ts +70 -0
  54. package/src/task-stages.ts +459 -0
  55. package/src/turn-evidence.ts +42 -4
  56. package/src/turn-ipc-mission.ts +127 -11
  57. package/src/turn-ipc-queue.ts +45 -2
  58. package/src/turn-ipc-turn.ts +1 -1
  59. package/src/turn-ipc.ts +1 -0
  60. package/src/worker-protocol.ts +94 -0
@@ -19,7 +19,7 @@ export interface QuotaFreshness {
19
19
  cue?: QuotaFreshnessCue
20
20
  /**
21
21
  * Only the USER can produce a new reading (aged-out Claude statusline;
22
- * antigravity expired token — the daemon never redeems it). The surface
22
+ * expired CLI access token — the daemon never redeems it). The surface
23
23
  * should say what to run, not promise a self-heal.
24
24
  */
25
25
  userMustAct: boolean
@@ -88,9 +88,9 @@ function backfillCheckAt(quota: MeshNodeFactsProviderQuota, now: number): number
88
88
  * a session must run). Codex's `no-data` is the daemon re-reading the
89
89
  * rollout files itself (≈60s while a CLI is active, ≤60 min idle), so it
90
90
  * is `stale` WITHOUT userMustAct;
91
- * · antigravity `expired-token` — the daemon deliberately does not redeem
92
- * the refresh token. Kimi's expired-token is NOT here: its CLI refreshes
93
- * the token on its own cadence.
91
+ * · `expired-token` on Grok/Kimi/antigravity — only the owning CLI
92
+ * renews it on use. An idle CLI has no background renewal cadence.
93
+ * A scheduled quota retry does not itself renew credentials.
94
94
  * - `refreshing` — retained numbers after a transient failure with a retry
95
95
  * actually pending. ★Honest about the end of the retry budget: once the
96
96
  * daemon has stopped retrying (`metadata.retryExhausted`, or `retryAtMs`
@@ -102,13 +102,24 @@ function backfillCheckAt(quota: MeshNodeFactsProviderQuota, now: number): number
102
102
  export function assessQuotaFreshness(quota: MeshNodeFactsProviderQuota, now: number = Date.now()): QuotaFreshness {
103
103
  const meta = quota.metadata
104
104
  const kind = meta?.failureKind
105
- const userMustAct = (kind === 'no-data' && quota.provider !== 'codex-cli')
106
- || (kind === 'expired-token' && quota.provider === 'antigravity-cli')
107
- // Order matters: the aged-out Claude shape and the retained antigravity
108
- // shape both ALSO mark lastGoodWindows (mesh routing trusts retained numbers
109
- // until their reset), so they must be classified before the generic branch.
110
- if (userMustAct && hasReading(quota)) return { cue: 'stale', userMustAct: true }
111
- if (meta?.lastGoodWindows !== true) return { userMustAct }
105
+ const userMustAct = kind === 'no-data' && quota.provider !== 'codex-cli'
106
+ const awaitsCliUse = kind === 'expired-token' && ['grok-cli', 'kimi', 'antigravity-cli'].includes(quota.provider)
107
+ // Order matters: the aged-out Claude shape and the retained expired-token
108
+ // shape both ALSO mark lastGoodWindows, so they must be classified before
109
+ // the generic branch. An expired short-lived access token that the CLI
110
+ // renews itself is NOT an auth failure requiring user action (userMustAct:
111
+ // false), while any retained lastGood numbers are marked stale.
112
+ if (userMustAct) return hasReading(quota) ? { cue: 'stale', userMustAct: true } : { userMustAct: true }
113
+ if (awaitsCliUse) return hasReading(quota) ? { cue: 'stale', userMustAct: false } : { userMustAct: false }
114
+ if (meta?.lastGoodWindows !== true) {
115
+ // A successful fetch is not a perpetual live reading. Use the DATA
116
+ // clock; a recent failed attempt must never rejuvenate old numbers.
117
+ const measuredAt = finiteMs(quota.updatedAt)
118
+ if (hasReading(quota) && (measuredAt === undefined || now - measuredAt >= QUOTA_BACKFILL_HORIZON_MS)) {
119
+ return { cue: 'stale', userMustAct }
120
+ }
121
+ return { userMustAct }
122
+ }
112
123
 
113
124
  const retryAtMs = finiteMs(meta?.retryAtMs)
114
125
  const retryStopped = meta?.retryExhausted === true
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Relay -> direct re-probe scheduler (pure, dependency-free).
3
+ *
4
+ * A P2P connection that settled on a TURN relay never looks for a direct path
5
+ * again. The owning transport (dashboard `P2PConnection`, daemon peer manager)
6
+ * uses this scheduler to periodically attempt a make-before-break probe: a
7
+ * SECOND peer connection (STUN-only) is built next to the working relay one and
8
+ * only swapped in once it is verified direct. The scheduler owns nothing but
9
+ * timing: backoff 60s -> 5min (doubling), jitter, and the stop conditions. The
10
+ * transport supplies `shouldProbe` (open + idle + visible) and `probe`.
11
+ */
12
+
13
+ export type RelayReprobeOutcome = 'direct' | 'relay' | 'failed' | 'skipped'
14
+
15
+ export interface RelayReprobeTiming {
16
+ /** First delay and the unit of growth (default 60s). */
17
+ baseDelayMs?: number
18
+ /** Backoff ceiling before jitter (default 5min). */
19
+ maxDelayMs?: number
20
+ /** +/- fraction applied to every delay (default 0.2). */
21
+ jitterRatio?: number
22
+ }
23
+
24
+ export const RELAY_REPROBE_BASE_DELAY_MS = 60_000
25
+ export const RELAY_REPROBE_MAX_DELAY_MS = 5 * 60_000
26
+ export const RELAY_REPROBE_JITTER_RATIO = 0.2
27
+
28
+ /** Delay before the next attempt after `failures` consecutive non-direct outcomes. */
29
+ export function computeRelayReprobeDelay(
30
+ failures: number,
31
+ random: () => number,
32
+ timing: RelayReprobeTiming = {},
33
+ ): number {
34
+ const base = timing.baseDelayMs ?? RELAY_REPROBE_BASE_DELAY_MS
35
+ const max = timing.maxDelayMs ?? RELAY_REPROBE_MAX_DELAY_MS
36
+ const jitter = timing.jitterRatio ?? RELAY_REPROBE_JITTER_RATIO
37
+ const grown = Math.min(max, base * 2 ** Math.max(0, failures))
38
+ const factor = 1 + jitter * (Math.min(1, Math.max(0, random())) * 2 - 1)
39
+ return Math.round(grown * factor)
40
+ }
41
+
42
+ export interface RelayReprobeSchedulerOptions extends RelayReprobeTiming {
43
+ random: () => number
44
+ setTimer: (callback: () => void, ms: number) => unknown
45
+ clearTimer: (handle: unknown) => void
46
+ /** Connected over relay, idle, tab visible, auth epoch unchanged... Re-checked on every tick. */
47
+ shouldProbe: () => boolean
48
+ /** One make-before-break attempt. Must never throw into the scheduler; a rejection counts as 'failed'. */
49
+ probe: () => Promise<RelayReprobeOutcome>
50
+ }
51
+
52
+ export class RelayReprobeScheduler {
53
+ private handle: unknown = null
54
+ private running = false
55
+ private inFlight = false
56
+ private failureCount = 0
57
+ private generation = 0
58
+
59
+ constructor(private readonly options: RelayReprobeSchedulerOptions) {}
60
+
61
+ get isRunning(): boolean { return this.running }
62
+ get failures(): number { return this.failureCount }
63
+ get probing(): boolean { return this.inFlight }
64
+
65
+ /** Begin probing (idempotent). Call when a connection is selected as relay. */
66
+ start(): void {
67
+ if (this.running) return
68
+ this.running = true
69
+ this.failureCount = 0
70
+ this.generation++
71
+ this.schedule()
72
+ }
73
+
74
+ /** Stop for good (direct path found, connection closed, auth epoch changed). */
75
+ stop(): void {
76
+ this.running = false
77
+ this.generation++
78
+ if (this.handle !== null) {
79
+ this.options.clearTimer(this.handle)
80
+ this.handle = null
81
+ }
82
+ }
83
+
84
+ private schedule(): void {
85
+ if (!this.running) return
86
+ const generation = this.generation
87
+ const delay = computeRelayReprobeDelay(this.failureCount, this.options.random, this.options)
88
+ this.handle = this.options.setTimer(() => {
89
+ this.handle = null
90
+ void this.tick(generation)
91
+ }, delay)
92
+ }
93
+
94
+ private async tick(generation: number): Promise<void> {
95
+ if (!this.running || generation !== this.generation) return
96
+ if (this.inFlight || !this.options.shouldProbe()) {
97
+ this.schedule()
98
+ return
99
+ }
100
+ this.inFlight = true
101
+ let outcome: RelayReprobeOutcome
102
+ try {
103
+ outcome = await this.options.probe()
104
+ } catch {
105
+ outcome = 'failed'
106
+ }
107
+ this.inFlight = false
108
+ // stop()/restart while the probe was in flight: the verdict is stale.
109
+ if (!this.running || generation !== this.generation) return
110
+ if (outcome === 'direct') {
111
+ this.stop()
112
+ return
113
+ }
114
+ if (outcome !== 'skipped') this.failureCount++
115
+ this.schedule()
116
+ }
117
+ }
package/src/release.ts ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * release — types, limits and pure helpers for release objects
3
+ * (docs/design/2026-11-01-release-objects.md).
4
+ *
5
+ * A release is a mesh-scoped entity that groups MISSIONS (explicit membership) and records
6
+ * deploy facts. It is distinct from the vendor release stamp (a build channel stamp) and
7
+ * from `.adhdev/preview-deploy.json` (the per-checkout deploy record it snapshots).
8
+ * Membership is only ever created by an explicit call; git evaluation and deploy heads
9
+ * produce suggestions, never members. Dependency-free leaf.
10
+ */
11
+
12
+ export const MESH_RELEASE_CHANNELS = ['preview', 'stable'] as const
13
+ export type MeshReleaseChannel = typeof MESH_RELEASE_CHANNELS[number]
14
+ export function isMeshReleaseChannel(value: unknown): value is MeshReleaseChannel {
15
+ return typeof value === 'string' && (MESH_RELEASE_CHANNELS as readonly string[]).includes(value)
16
+ }
17
+
18
+ export const MESH_RELEASE_STATUSES = ['planned', 'frozen', 'deployed', 'verified', 'superseded', 'cancelled'] as const
19
+ export type ReleaseStatus = typeof MESH_RELEASE_STATUSES[number]
20
+ export function isReleaseStatus(value: unknown): value is ReleaseStatus {
21
+ return typeof value === 'string' && (MESH_RELEASE_STATUSES as readonly string[]).includes(value)
22
+ }
23
+
24
+ export const RELEASE_MEMBER_STATES = ['member', 'moved_out', 'removed'] as const
25
+ export type ReleaseMemberState = typeof RELEASE_MEMBER_STATES[number]
26
+
27
+ /** Who may write release membership. The daemon never adds a member on its own. */
28
+ export const RELEASE_ACTORS = ['coordinator', 'owner', 'assistant', 'script'] as const
29
+ export type ReleaseActor = typeof RELEASE_ACTORS[number]
30
+
31
+ export const RELEASE_EVENT_TYPES = [
32
+ 'created', 'status_changed', 'scope_added', 'scope_moved', 'scope_removed',
33
+ 'deploy_recorded', 'changelog_drafted', 'changelog_applied',
34
+ ] as const
35
+ export type ReleaseEventType = typeof RELEASE_EVENT_TYPES[number]
36
+
37
+ /** Mission-side events recorded when membership changes (so the mission history shows it). */
38
+ export const MISSION_RELEASE_EVENT_TYPES = ['release_attached', 'release_moved', 'release_detached'] as const
39
+
40
+ export const RELEASE_LIMITS = {
41
+ name: 80,
42
+ note: 500,
43
+ /** `mesh_missions.release_note`: one user/operator-visible sentence. */
44
+ releaseNote: 400,
45
+ missionsPerCall: 100,
46
+ changelogEntries: 300,
47
+ } as const
48
+
49
+ /** Deploy targets snapshot (a copy of `.adhdev/preview-deploy.json` `targets`). */
50
+ export interface ReleaseDeployTarget {
51
+ commit?: string
52
+ deployedAt?: string
53
+ previewVersion?: string
54
+ [key: string]: unknown
55
+ }
56
+ export type ReleaseTargets = Partial<Record<'npm' | 'server' | 'web', ReleaseDeployTarget>> & Record<string, ReleaseDeployTarget | undefined>
57
+
58
+ export const CHANGELOG_SECTIONS = ['Added', 'Fixed', 'Changed'] as const
59
+ export type ChangelogSection = typeof CHANGELOG_SECTIONS[number]
60
+
61
+ export interface ChangelogDraftEntry {
62
+ missionId: string
63
+ /** `<!-- m:<id8> -->` — the idempotency marker `--apply` writes after the line. */
64
+ marker: string
65
+ section: ChangelogSection
66
+ /** The sentence that would be written to CHANGELOG.md. */
67
+ text: string
68
+ source: 'release_note' | 'summary'
69
+ /** True when `text` is not user-facing wording yet (carries the needs-wording marker). */
70
+ needsWording?: boolean
71
+ /** Evidence kept in the draft JSON only; never written to CHANGELOG.md. */
72
+ evidence?: { gitState?: string; outcome?: string; shas?: string[] }
73
+ /** Non-blocking lint warnings (internal ids / wave numbers / forbidden phrases). */
74
+ lint?: string[]
75
+ }
76
+
77
+ export interface ChangelogDraftExcluded {
78
+ missionId: string
79
+ reason: string
80
+ }
81
+
82
+ export interface ChangelogDraft {
83
+ generatedAt: string
84
+ entries: ChangelogDraftEntry[]
85
+ /** Member missions without a `release_note` (target 0 at deploy time). */
86
+ needsNote: string[]
87
+ excluded: ChangelogDraftExcluded[]
88
+ /** Member missions whose refs are not confirmed on the default branch (`not_landed` / `unknown`). */
89
+ warnings: Array<{ missionId: string; gitState: string; message: string }>
90
+ appliedAt?: string
91
+ }
92
+
93
+ export const NEEDS_WORDING_MARKER = '[needs user-facing wording]'
94
+
95
+ /** Marker that makes `--apply` idempotent: one per mission entry inside CHANGELOG.md. */
96
+ export function changelogMissionMarker(missionId: string): string {
97
+ return `<!-- m:${missionId.slice(0, 8)} -->`
98
+ }
99
+
100
+ /** Default section for an entry; `[Fixed]`/`[Added]`/`[Changed]` prefixes on the note pin it. */
101
+ export function classifyChangelogSection(text: string, hint?: string): { section: ChangelogSection; text: string } {
102
+ const m = /^\s*\[(added|fixed|changed)\]\s*/i.exec(text)
103
+ if (m) {
104
+ const key = m[1].toLowerCase()
105
+ return { section: key === 'added' ? 'Added' : key === 'fixed' ? 'Fixed' : 'Changed', text: text.slice(m[0].length).trim() }
106
+ }
107
+ const probe = `${hint ?? ''} ${text}`.toLowerCase()
108
+ if (/\b(fix|fixes|fixed|bug|regression|crash|error)\b|오류|결함|버그|수정/.test(probe)) return { section: 'Fixed', text }
109
+ if (/\b(add|adds|added|new|introduc\w*|support\w*)\b|신규|추가/.test(probe)) return { section: 'Added', text }
110
+ return { section: 'Changed', text }
111
+ }
112
+
113
+ /** Phrases that must not reach a public CHANGELOG (internal waves, rc numbering, ids). Warning-only. */
114
+ export function lintChangelogText(text: string): string[] {
115
+ const out: string[] = []
116
+ if (/\bwave[\s-]*\d+/i.test(text) || /웨이브\s*\d+/.test(text)) out.push('mentions an internal wave number')
117
+ if (/\brc[.\s-]?\d+\b/i.test(text)) out.push('mentions an internal rc number')
118
+ if (/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.test(text) || /\bmi_[0-9a-f]{12}\b/.test(text) || /\brel_[0-9a-f]{12}\b/.test(text)) out.push('contains an internal id')
119
+ if (/\bmission\b/i.test(text)) out.push('mentions "mission" (internal vocabulary)')
120
+ return out
121
+ }
@@ -0,0 +1,51 @@
1
+ /** Persisted role-launch intent. Restart replays this selection rather than
2
+ * consulting newer machine defaults; restore preserves its original provenance. */
3
+ import { isLaunchDefaultRole, isLaunchDefaultSource, type LaunchDefaultRole,
4
+ type LaunchDefaultSelection, type LaunchDefaultAxis, type LaunchDefaultRef } from './launch-defaults';
5
+ export interface RoleLaunchSelection {
6
+ role: LaunchDefaultRole;
7
+ selection: LaunchDefaultSelection;
8
+ applied: Record<keyof LaunchDefaultSelection, LaunchDefaultAxis>;
9
+ defaultRef?: LaunchDefaultRef;
10
+ documentRevision: number;
11
+ }
12
+ function record(value: unknown): Record<string, unknown> | undefined {
13
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
14
+ ? value as Record<string, unknown> : undefined;
15
+ }
16
+ function ref(value: unknown): LaunchDefaultRef | undefined {
17
+ const r = record(value);
18
+ if (!r || !isLaunchDefaultRole(r.role) || (r.scope !== 'global' && r.scope !== 'project')
19
+ || !Number.isSafeInteger(r.revision) || (r.revision as number) < 1
20
+ || (r.scope === 'project' && (typeof r.projectId !== 'string' || !r.projectId))) return undefined;
21
+ return { role: r.role, scope: r.scope, revision: r.revision as number,
22
+ ...(r.scope === 'project' ? { projectId: r.projectId as string } : {}) };
23
+ }
24
+ function axis(value: unknown): LaunchDefaultAxis | undefined {
25
+ const a = record(value);
26
+ if (!a || !isLaunchDefaultSource(a.source) || (a.value !== null && typeof a.value !== 'string')) return undefined;
27
+ const defaultRef = ref(a.defaultRef);
28
+ if (a.source === 'stored_default' && defaultRef?.scope !== 'global'
29
+ || a.source === 'project_default' && defaultRef?.scope !== 'project'
30
+ || (a.source === 'user' || a.source === 'provider_default') && a.defaultRef !== undefined) return undefined;
31
+ return { value: a.value as string | null, source: a.source, ...(defaultRef ? { defaultRef } : {}) };
32
+ }
33
+ export function parseRoleLaunchSelection(value: unknown): RoleLaunchSelection | undefined {
34
+ const r = record(value), s = record(r?.selection), a = record(r?.applied);
35
+ if (!r || !isLaunchDefaultRole(r.role) || !s || typeof s.provider !== 'string' || !s.provider
36
+ || !Number.isSafeInteger(r.documentRevision) || (r.documentRevision as number) < 1
37
+ || (s.model !== undefined && typeof s.model !== 'string')
38
+ || (s.thinkingLevel !== undefined && typeof s.thinkingLevel !== 'string')) return undefined;
39
+ const provider = axis(a?.provider), model = axis(a?.model), thinkingLevel = axis(a?.thinkingLevel);
40
+ if (!provider || !model || !thinkingLevel
41
+ || [provider, model, thinkingLevel].some(axis => axis.defaultRef && (axis.defaultRef.role !== r.role
42
+ || axis.defaultRef.scope === 'global' && axis.defaultRef.revision > (r.documentRevision as number)))
43
+ || provider.value !== s.provider
44
+ || model.value !== (s.model ?? null) || thinkingLevel.value !== (s.thinkingLevel ?? null)) return undefined;
45
+ const defaultRef = ref(r.defaultRef);
46
+ return { role: r.role, selection: { provider: s.provider,
47
+ ...(typeof s.model === 'string' ? { model: s.model } : {}),
48
+ ...(typeof s.thinkingLevel === 'string' ? { thinkingLevel: s.thinkingLevel } : {}) },
49
+ applied: { provider, model, thinkingLevel }, ...(defaultRef ? { defaultRef } : {}),
50
+ documentRevision: r.documentRevision as number };
51
+ }
@@ -1,3 +1,4 @@
1
+ import { parseRoleLaunchSelection, type RoleLaunchSelection } from './role-launch'
1
2
  /**
2
3
  * session-launch — how a session was launched: provider, model and thinking
3
4
  * level, and WHERE each value came from.
@@ -35,11 +36,14 @@ export const MODEL_AXIS_SOURCES = [
35
36
  'user',
36
37
  /** The dashboard dialog restored it from the last launch (browser-local memory). */
37
38
  'remembered',
39
+ /** The authoritative daemon role default or host project override. */
40
+ 'stored_default',
41
+ 'project_default',
38
42
  /** A mesh capability slot supplied it (or a difficulty preset the slot outranked). */
39
43
  'mesh_slot',
40
44
  /** An explicit per-task model / thinking level on a mesh queue task. */
41
45
  'task_override',
42
- /** Nothing was requested; the provider's default is known (discovery / manifest). */
46
+ /** Nothing requested: the provider chooses; resolvedDefault records it when known. */
43
47
  'provider_default',
44
48
  /** A value was requested without saying where it came from, or nothing is known. */
45
49
  'unspecified',
@@ -97,11 +101,19 @@ export interface ModelSelection {
97
101
  /** Last value the provider itself reported (statusline, native history). */
98
102
  observed?: string
99
103
  observedAt?: number
104
+ /**
105
+ * The provider SILENTLY substituted another model for the requested one
106
+ * (antigravity: `model X is not recognized … Using "Y" instead`). `observed`
107
+ * then holds the model actually running. P2P/launch-record only — the
108
+ * server path never carries it (see the content boundary above).
109
+ */
110
+ fallback?: boolean
100
111
  /** Every value change in order. The last entry is the value in force. */
101
112
  history: ModelSelectionHistoryEntry[]
102
113
  }
103
114
 
104
115
  export interface SessionLaunchRecord {
116
+ roleLaunch?: RoleLaunchSelection
105
117
  sessionId: string
106
118
  providerType: string
107
119
  providerVersion?: string
@@ -201,6 +213,7 @@ function parseModelSelection(raw: unknown): ModelSelection | undefined {
201
213
  const current = readString(record.current)
202
214
  const observed = readString(record.observed)
203
215
  const observedAt = readFiniteNumber(record.observedAt)
216
+ const fallback = record.fallback === true
204
217
  return {
205
218
  source: isModelAxisSource(record.source) ? record.source : 'unspecified',
206
219
  ...(requested ? { requested } : {}),
@@ -209,6 +222,7 @@ function parseModelSelection(raw: unknown): ModelSelection | undefined {
209
222
  ...(current ? { current } : {}),
210
223
  ...(observed ? { observed } : {}),
211
224
  ...(observedAt !== undefined ? { observedAt } : {}),
225
+ ...(fallback ? { fallback } : {}),
212
226
  history: history.slice(-MODEL_SELECTION_HISTORY_LIMIT),
213
227
  }
214
228
  }
@@ -230,7 +244,9 @@ export function parseSessionLaunchRecord(raw: unknown): SessionLaunchRecord | un
230
244
  const providerVersion = readString(record.providerVersion)
231
245
  const workspace = readString(record.workspace)
232
246
  const autoApproveModeId = readString(record.autoApproveModeId)
247
+ const roleLaunch = parseRoleLaunchSelection(record.roleLaunch)
233
248
  return {
249
+ ...(roleLaunch ? { roleLaunch } : {}),
234
250
  sessionId,
235
251
  providerType,
236
252
  ...(providerVersion ? { providerVersion } : {}),
@@ -40,6 +40,13 @@ import {
40
40
  export interface CliSlotRecipe {
41
41
  /** Optional model to pin on the slot. Best-effort at launch. */
42
42
  model?: string
43
+ /**
44
+ * Optional ordered candidate models to prefer when the provider's live
45
+ * `modelOptions` (from model discovery) is present on `DetectedCliProvider`.
46
+ * The first candidate present in `modelOptions` wins; falls back to `model`
47
+ * when `modelOptions` is absent or contains none of the candidates.
48
+ */
49
+ modelCandidates?: readonly string[]
43
50
  /** Optional thinking level, in the provider's own vocabulary. */
44
51
  thinkingLevel?: string
45
52
  /** Difficulty range this slot handles. Empty = general-purpose. */
@@ -101,11 +108,26 @@ export const CLI_SLOT_RECIPES: Readonly<Record<string, readonly CliSlotRecipe[]>
101
108
  ],
102
109
  'antigravity-cli': [
103
110
  {
104
- model: 'Gemini 3.1 Pro (High)',
111
+ model: 'Gemini 3.8 Flash (High)',
112
+ modelCandidates: ['Gemini 3.8 Flash (High)', 'Gemini 4 Argon (Low)', 'Gemini 3.7 Flash (High)', 'Gemini 3.1 Pro (High)'],
105
113
  difficulty: ['easy'],
106
114
  maxParallel: 2,
107
115
  rationale: 'Cheap capacity for easy tasks.',
108
116
  },
117
+ {
118
+ model: 'Gemini 4 Argon (Medium)',
119
+ modelCandidates: ['Gemini 4 Argon (Medium)', 'Gemini 3.8 Flash (High)', 'Gemini 3.7 Flash (High)', 'Gemini 3.1 Pro (High)'],
120
+ difficulty: ['medium'],
121
+ maxParallel: 2,
122
+ rationale: 'Balanced Argon tier for medium tasks.',
123
+ },
124
+ {
125
+ model: 'Gemini 4 Argon (High)',
126
+ modelCandidates: ['Gemini 4 Argon (High)', 'Gemini 3.8 Flash (High)', 'Gemini 3.1 Pro (High)'],
127
+ difficulty: ['difficult'],
128
+ maxParallel: 1,
129
+ rationale: 'Reserved for hard tasks; capped at 1 to bound cost.',
130
+ },
109
131
  ],
110
132
  'cursor-cli': [
111
133
  {
@@ -137,6 +159,13 @@ export interface DetectedCliProvider {
137
159
  displayName?: string
138
160
  /** Detected version, when known. Display only — never affects the mapping. */
139
161
  version?: string
162
+ /**
163
+ * Live discovered / resolved `modelOptions` for this provider on the node,
164
+ * when available on the status catalog. When present and non-empty, recipes
165
+ * prefer the first matching model from `[recipe.model, ...recipe.modelCandidates]`
166
+ * that exists in `modelOptions`.
167
+ */
168
+ modelOptions?: readonly string[]
140
169
  }
141
170
 
142
171
  /** One proposed slot plus why it was proposed. */
@@ -197,6 +226,36 @@ function dedupeDetected(detected: readonly DetectedCliProvider[]): DetectedCliPr
197
226
  return out
198
227
  }
199
228
 
229
+ /**
230
+ * Resolve a recipe's pinned model against the provider's live `modelOptions`
231
+ * (populated from the daemon's model-discovery overlay when available). If
232
+ * `modelOptions` is absent or none of the recipe's candidates appear in it,
233
+ * falls back to `recipe.model`.
234
+ */
235
+ function resolveRecipeModel(
236
+ recipe: CliSlotRecipe,
237
+ modelOptions: readonly string[] | undefined,
238
+ ): string | undefined {
239
+ if (!Array.isArray(modelOptions) || modelOptions.length === 0) {
240
+ return recipe.model
241
+ }
242
+ const available = new Set(
243
+ modelOptions
244
+ .filter((m): m is string => typeof m === 'string' && m.trim().length > 0)
245
+ .map(m => m.trim()),
246
+ )
247
+ if (available.size === 0) return recipe.model
248
+ const candidates = [
249
+ ...(recipe.model ? [recipe.model] : []),
250
+ ...(recipe.modelCandidates ?? []),
251
+ ]
252
+ for (const candidate of candidates) {
253
+ const trimmed = typeof candidate === 'string' ? candidate.trim() : ''
254
+ if (trimmed && available.has(trimmed)) return trimmed
255
+ }
256
+ return recipe.model
257
+ }
258
+
200
259
  /**
201
260
  * Build a capability-slot proposal from a node's detected CLI providers.
202
261
  *
@@ -229,7 +288,7 @@ export function buildSlotProposal(
229
288
  // a proposal can never preview a shape the write would reshape.
230
289
  const slot = normalizeNodeCapabilitySlot({
231
290
  provider: provider.type,
232
- model: recipe.model,
291
+ model: resolveRecipeModel(recipe, provider.modelOptions),
233
292
  thinkingLevel: recipe.thinkingLevel,
234
293
  difficulty: recipe.difficulty,
235
294
  maxParallel: recipe.maxParallel,
@@ -0,0 +1,70 @@
1
+ import type { OwnedPathEntry } from './path-ownership'
2
+
3
+ export type MeshTaskPhase = 'source' | 'integration'
4
+
5
+ /** Host-produced evidence. Never accepted from MCP/peer-supplied paths or branch labels. */
6
+ export interface PhysicalOwnershipScope {
7
+ version: 1
8
+ repoIdentity: string
9
+ machineId: string
10
+ nodeId: string
11
+ worktree: string
12
+ worktreeIdentity: string
13
+ gitDir: string
14
+ commonGitDir: string
15
+ phase: MeshTaskPhase
16
+ gitResources: { index: string; refs: string; hooks: string; config: string }
17
+ resources: Array<{ path: string; identity?: string; subtree: boolean }>
18
+ declaration: readonly OwnedPathEntry[]
19
+ }
20
+
21
+ /** A source packet is an input to integration, never release/feature acceptance. */
22
+ export interface MeshSourceCandidate {
23
+ version: 1
24
+ readiness: 'uncommitted' | 'verified_source_candidate'
25
+ taskId: string
26
+ missionId: string
27
+ revision: number
28
+ repoIdentity: string
29
+ machineId: string
30
+ canonicalWorktree: string
31
+ rootBaseSha: string
32
+ ossBaseSha: string
33
+ rootCandidateSha?: string
34
+ ossCandidateSha?: string
35
+ patchSha256: string
36
+ manifestSha256: string
37
+ touchedPaths: string[]
38
+ tests: Array<{ command: string; exit: number; logSha256: string }>
39
+ settledCommands: boolean
40
+ integrationTaskId: string
41
+ logicalOverlapTaskIds: string[]
42
+ }
43
+
44
+ /** Product B consumes one frozen batch; normal hooks/parity/gates remain required. */
45
+ export interface MeshIntegrationBatchContract {
46
+ version: 1
47
+ batchId: string
48
+ candidates: MeshSourceCandidate[]
49
+ integrationOrder: string[]
50
+ approvedRootSha: string
51
+ approvedOssSha: string
52
+ bundleInvocationCount: 1
53
+ requiredGates: string[]
54
+ normalHooksRequired: true
55
+ independentReviewRequired: true
56
+ ownerLandingApprovalRequired: true
57
+ }
58
+
59
+ /** These only rank legal targets; targetNodeId/SessionId and requiredTags remain hard. */
60
+ export interface MeshRoutingPreferences { nodeIds?: string[]; providers?: string[] }
61
+ export type MeshReviewIndependence = 'different_provider' | 'fresh_session'
62
+ /**
63
+ * Review row constraint. `differentProvider: true` is the legacy spelling of
64
+ * `independence: 'different_provider'`; `independence: 'fresh_session'` is the stage pipeline's
65
+ * fallback (same provider allowed, but never the implementer's session).
66
+ */
67
+ export interface MeshReviewConstraint { sourceTaskId: string; differentProvider?: true; independence?: MeshReviewIndependence }
68
+ export function reviewIndependenceOf(review: Pick<MeshReviewConstraint, 'differentProvider' | 'independence'>): MeshReviewIndependence {
69
+ return review.independence ?? 'different_provider'
70
+ }