@yunhozz/arc 0.3.5 → 0.4.1

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 (135) hide show
  1. package/MANIFEST.sha256 +133 -94
  2. package/README.md +56 -21
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/commit.md +10 -8
  5. package/claude/skill/references/coordination.md +6 -4
  6. package/claude/skill/references/handoff-prep.md +12 -12
  7. package/claude/skill/references/handoff.md +2 -0
  8. package/claude/skill/references/planning.md +8 -8
  9. package/claude/skill/references/verification.md +6 -6
  10. package/codex/skill/SKILL.md +1 -1
  11. package/codex/skill/references/commit.md +10 -8
  12. package/codex/skill/references/coordination.md +6 -4
  13. package/codex/skill/references/handoff-prep.md +12 -12
  14. package/codex/skill/references/handoff.md +2 -0
  15. package/codex/skill/references/planning.md +8 -8
  16. package/codex/skill/references/verification.md +6 -6
  17. package/gemini/GEMINI.md +8 -0
  18. package/gemini/agents/arc-implementer.md +37 -0
  19. package/gemini/agents/arc-planner.md +47 -0
  20. package/gemini/agents/arc-qa.md +37 -0
  21. package/gemini/agents/arc-reviewer.md +39 -0
  22. package/gemini/agents/arc-scouter.md +38 -0
  23. package/gemini/instructions.md +4 -0
  24. package/gemini/skill/SKILL.md +78 -0
  25. package/gemini/skill/models.toml +23 -0
  26. package/gemini/skill/references/arc-visual-companion.md +28 -0
  27. package/gemini/skill/references/commit.md +55 -0
  28. package/gemini/skill/references/coordination.md +149 -0
  29. package/gemini/skill/references/git-recovery.md +34 -0
  30. package/gemini/skill/references/handoff-prep.md +110 -0
  31. package/gemini/skill/references/handoff.md +227 -0
  32. package/gemini/skill/references/limits.md +31 -0
  33. package/gemini/skill/references/planning.md +168 -0
  34. package/gemini/skill/references/verification.md +155 -0
  35. package/gemini/skill/references/worktree-creation.md +8 -0
  36. package/lib/color/palette.mjs +6 -0
  37. package/lib/installer/acquisition.mjs +7 -5
  38. package/lib/installer/install-mode.mjs +49 -26
  39. package/lib/installer/install.mjs +3 -2
  40. package/lib/installer/manifest.mjs +20 -14
  41. package/lib/installer/plan.mjs +24 -21
  42. package/lib/installer/preset.mjs +9 -8
  43. package/lib/installer/role-routing.mjs +160 -81
  44. package/lib/installer/runtime-assets.mjs +2 -0
  45. package/lib/installer/runtime-config.mjs +3 -0
  46. package/lib/installer/skill-sources.mjs +4 -3
  47. package/lib/installer/superpowers.mjs +2 -1
  48. package/lib/installer/target-errors.mjs +1 -0
  49. package/lib/installer/targets.mjs +14 -6
  50. package/lib/installer/uninstall.mjs +5 -4
  51. package/lib/installer/upgrade-state.mjs +14 -10
  52. package/lib/installer/upgrade.mjs +9 -5
  53. package/lib/management/operations.mjs +96 -48
  54. package/lib/management/status.mjs +10 -8
  55. package/lib/management/update.mjs +8 -7
  56. package/lib/models/catalog-gemini.mjs +48 -0
  57. package/lib/models/catalog.mjs +27 -12
  58. package/lib/models/config.mjs +23 -22
  59. package/lib/models/gemini-models.json +12 -0
  60. package/lib/models/profiles.mjs +7 -5
  61. package/lib/models/static-catalog.mjs +13 -14
  62. package/lib/npm/upgrade.mjs +2 -2
  63. package/lib/platforms/availability.mjs +98 -0
  64. package/lib/platforms/claude.mjs +14 -0
  65. package/lib/platforms/codex.mjs +16 -0
  66. package/lib/platforms/formats/gemini-markdown.mjs +48 -0
  67. package/lib/platforms/formats/markdown.mjs +39 -0
  68. package/lib/platforms/formats/toml.mjs +39 -0
  69. package/lib/platforms/gemini.mjs +14 -0
  70. package/lib/platforms/index.mjs +27 -0
  71. package/lib/policy/placement.mjs +4 -4
  72. package/lib/policy/render.mjs +13 -8
  73. package/lib/policy/role-policy.json +40 -21
  74. package/lib/prompts/agent-fragments.json +71 -1
  75. package/lib/prompts/render.mjs +32 -11
  76. package/lib/runtime/bootstrap.mjs +1 -1
  77. package/lib/runtime/cooperative-schema.mjs +0 -23
  78. package/lib/runtime/cooperative.mjs +13 -34
  79. package/lib/runtime/evaluate.mjs +3 -69
  80. package/lib/runtime/gemini-stream.mjs +32 -0
  81. package/lib/runtime/git-evidence.mjs +0 -98
  82. package/lib/runtime/identity.mjs +2 -1
  83. package/lib/runtime/local-cli.mjs +14 -24
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/platform-registry.mjs +130 -0
  86. package/lib/runtime/role-bridge-args.mjs +57 -2
  87. package/lib/runtime/role-bridge.mjs +86 -65
  88. package/lib/runtime/role-dispatch-policy.mjs +17 -7
  89. package/lib/runtime/role-dispatch-store.mjs +20 -14
  90. package/lib/runtime/role-observe.mjs +1 -0
  91. package/lib/runtime/role-routing-config.mjs +36 -9
  92. package/lib/runtime/role-routing.mjs +62 -29
  93. package/lib/runtime/role-supervisor.mjs +114 -49
  94. package/lib/runtime/schema.mjs +5 -4
  95. package/lib/tui/app.mjs +84 -35
  96. package/lib/tui/custom-preset.mjs +114 -68
  97. package/lib/tui/derive-install-plan.mjs +19 -0
  98. package/lib/tui/diagram.mjs +68 -0
  99. package/lib/tui/mode.mjs +77 -0
  100. package/lib/tui/render.mjs +47 -16
  101. package/lib/tui/setup.mjs +168 -100
  102. package/lib/tui/terminal.mjs +9 -6
  103. package/lib/watch/anchor-store.mjs +44 -0
  104. package/lib/watch/dispatch.mjs +3 -3
  105. package/lib/watch/index.mjs +37 -24
  106. package/lib/watch/model.mjs +1 -0
  107. package/lib/watch/normalize-claude.mjs +50 -10
  108. package/lib/watch/normalize-codex.mjs +79 -5
  109. package/lib/watch/render.mjs +30 -13
  110. package/lib/watch/scope.mjs +2 -1
  111. package/lib/watch/status-line.mjs +51 -0
  112. package/lib/watch/tail.mjs +27 -0
  113. package/lib/watch/watcher.mjs +193 -53
  114. package/package.json +2 -1
  115. package/scripts/update-manifest.mjs +2 -2
  116. package/shared/skill/runtime/bootstrap.mjs +1 -1
  117. package/shared/skill/runtime/cooperative-schema.mjs +0 -23
  118. package/shared/skill/runtime/cooperative.mjs +13 -34
  119. package/shared/skill/runtime/evaluate.mjs +3 -69
  120. package/shared/skill/runtime/gemini-stream.mjs +32 -0
  121. package/shared/skill/runtime/git-evidence.mjs +0 -98
  122. package/shared/skill/runtime/identity.mjs +2 -1
  123. package/shared/skill/runtime/local-cli.mjs +14 -24
  124. package/shared/skill/runtime/operations.mjs +2 -2
  125. package/shared/skill/runtime/platform-registry.mjs +130 -0
  126. package/shared/skill/runtime/role-bridge-args.mjs +57 -2
  127. package/shared/skill/runtime/role-bridge.mjs +86 -65
  128. package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
  129. package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
  130. package/shared/skill/runtime/role-observe.mjs +1 -0
  131. package/shared/skill/runtime/role-policy.json +40 -21
  132. package/shared/skill/runtime/role-routing-config.mjs +36 -9
  133. package/shared/skill/runtime/role-routing.mjs +62 -29
  134. package/shared/skill/runtime/role-supervisor.mjs +114 -49
  135. package/shared/skill/runtime/schema.mjs +5 -4
@@ -6,18 +6,63 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import {spawn, spawnSync} from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
- import {DEFAULT_POLICY, reason} from './role-dispatch-policy.mjs';
9
+ import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
10
+ import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
10
11
  import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
11
- import {withRoutingLock, readActivation} from './role-routing.mjs';
12
+ import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
12
13
  import {observeCooperativeTarget} from './scope.mjs';
13
- import {resolveConfigHome, resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
14
- import {parseCompositeProfile, buildClaudeArgs, buildCodexArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
14
+ import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
15
+ import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
15
16
  import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} from './role-observe.mjs';
17
+ import {getPlatform, routingProfileFile} from './platform-registry.mjs';
16
18
 
17
19
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
18
20
  const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
19
21
  const STDERR_LIMIT = 65536;
20
22
 
23
+ export const SUPERVISOR_IMPLEMENTATIONS = new Map([
24
+ ['claude', {
25
+ normalize: normalizeClaudeStreamEvent,
26
+ async observe({state, invocation, homes, requested, terminalClaim, lease}) {
27
+ const evaluation = state.initEval ?? evaluateClaudeInit({init: null, expected: invocation.expected});
28
+ const observed = await readClaudeTranscriptEffort({claudeHome: homes.claude, sessionId: state.init?.sessionId});
29
+ const effort = observed === null ? {level: 'unverified', source: 'none', requested: requested.effort, observed: null, label: 'model_effort_unverified'}
30
+ : {level: observed === requested.effort ? 'runtime-observed' : 'unverified', source: 'claude-transcript', requested: requested.effort, observed};
31
+ return {claims: {...evaluation.claims, effort, terminal: terminalClaim}, effortMismatch: observed !== null && observed !== requested.effort, sessionId: state.init?.sessionId ?? lease.sessionId};
32
+ },
33
+ async resultPath(state, resultFile) {
34
+ if (state.terminal && !state.terminalError && typeof state.resultText === 'string') { await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); return resultFile; }
35
+ return null;
36
+ },
37
+ session: state => state.init?.sessionId,
38
+ }],
39
+ ['gemini', {
40
+ resume: 'off',
41
+ normalize: normalizeGeminiStreamEvent,
42
+ async observe({state, invocation, terminalClaim, lease}) {
43
+ const evaluation = evaluateGeminiObservation({state, expected: invocation.expected, sessionId: lease.sessionId});
44
+ return {...evaluation, claims: {...evaluation.claims, terminal: terminalClaim}, effortMismatch: false, sessionId: lease.sessionId};
45
+ },
46
+ async resultPath(state, resultFile) {
47
+ if (!state.terminal || state.terminalError || typeof state.resultText !== 'string' || !state.resultText.trim()) return null;
48
+ await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); return resultFile;
49
+ },
50
+ session: state => state.geminiSessionId ?? state.init?.sessionId,
51
+ }],
52
+ ['codex', {
53
+ normalize: normalizeCodexStreamEvent,
54
+ async observe({state, invocation, readContext, policy, terminalClaim, lease}) {
55
+ let finalContext = null;
56
+ if (state.threadId) finalContext = await readContext().catch(() => null);
57
+ const evaluation = finalContext ? evaluateCodexContext({context: finalContext, expected: invocation.expected, policy}) : state.codexEval ?? evaluateCodexContext({context: null, expected: invocation.expected, policy});
58
+ return {claims: {identity: state.threadId ? {level: 'runtime-observed', source: 'codex-stream-thread', observed: state.threadId} : {level: 'unverified', source: 'none'}, ...evaluation.claims, terminal: terminalClaim}, reason: evaluation.reason, effortMismatch: false, sessionId: state.threadId ?? lease.sessionId};
59
+ },
60
+ async resultPath(state, resultFile) { return fs.existsSync(resultFile) ? resultFile : null; },
61
+ session: state => state.threadId,
62
+ }],
63
+ ]);
64
+ export const SUPERVISOR_PLATFORM_IDS = Object.freeze([...SUPERVISOR_IMPLEMENTATIONS.keys()]);
65
+
21
66
  /** `ps -o lstart=` start time; used with the pid to tell a live process from a reused pid. Null when ps is unavailable or the pid is gone. */
22
67
  export function processStartTime(pid) {
23
68
  if (!Number.isInteger(pid) || pid <= 0) return null;
@@ -41,24 +86,36 @@ export const artifactDirectory = (target, workflowId, dispatchId) => path.join(t
41
86
  /** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
42
87
  export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
43
88
 
89
+ // U-P1: reserved path only; policy contents and installation await live format verification.
90
+ export const geminiPolicyFile = (homes, role) => path.join(homes.gemini ?? '', 'skills', 'arc', 'policies', `${role}.toml`);
91
+
44
92
  /** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
45
- export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY}) {
93
+ export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS}) {
46
94
  const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
47
- const requested = config.roles[lease.role], platform = requested.platform;
48
- const file = path.join(homes[platform], 'agents', `arc-routing-${lease.role.slice('arc_'.length)}.${platform === 'codex' ? 'toml' : 'md'}`);
95
+ const requested = config.roles[lease.role], platform = lease.version === 2 ? lease.targetPlatform : requested.platform;
96
+ if (platform !== requested.platform) throw fail('activation_unverified', 'Lease target differs from the active role target');
97
+ const implementation = supervisorImplementations.get(platform);
98
+ if (platform === 'gemini' || lease.hostPlatform === 'gemini') {
99
+ const gates = bridgeGateReasons({platform, role: lease.role, hostPlatform: lease.hostPlatform, policy});
100
+ if (gates.length) throw fail(gates[0], 'Gemini bridge gates are not verified');
101
+ }
102
+ if (platform === 'gemini' && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', 'Gemini resume is not verified');
103
+ if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
104
+ const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
49
105
  let bytes;
50
106
  try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
51
107
  if (sha256(bytes) !== lease.profileHash) throw fail('activation_unverified', 'Profile hash differs from the reserved lease');
52
108
  let profile, args;
53
109
  try {
54
110
  profile = parseCompositeProfile(platform, bytes);
55
- args = platform === 'claude' ? buildClaudeArgs({role: lease.role, profile, sessionId: lease.sessionId, policy}) : buildCodexArgs({role: lease.role, profile, worktree, resultPath, threadId: lease.sessionId, policy});
111
+ args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), resume: lease.segment > 0});
56
112
  } catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
57
113
  const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
58
114
  const expected = platform === 'claude'
59
115
  ? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
116
+ : platform === 'gemini' ? {model: requested.model, effort: 'default'}
60
117
  : {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
61
- return {platform, args, argsDigest: argsDigest(args), expected, requested};
118
+ return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {})};
62
119
  }
63
120
 
64
121
  /** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
@@ -89,19 +146,19 @@ export async function runSupervisor(options) {
89
146
  }
90
147
  }
91
148
  };
92
- const context = {cwd, userHome, env};
93
- const homes = {codex: resolveConfigHome('codex', context), claude: resolveConfigHome('claude', context)};
149
+ const context = {cwd, userHome, env, runtimePlatforms: options.runtimePlatforms};
150
+ const homes = resolveRuntimeHomes(context), runtimePlatforms = options.runtimePlatforms;
94
151
  const target = await resolveWorktree(cwd);
95
- let lease = await readLease(codexHome, dispatchId);
152
+ let lease = await readLease(codexHome, dispatchId, {runtimePlatforms});
96
153
  if (!lease || lease.route !== 'bridge') return;
97
154
  const artifactDir = segmentDirectory(target, lease.workflowId, dispatchId, lease.segment), resultFile = path.join(artifactDir, 'result.md');
98
155
  const mine = current => current && current.state === 'starting' && current.supervisor?.pid === process.pid;
99
156
  let config;
100
157
  const guarded = await locked(async () => {
101
- const current = await readLease(codexHome, dispatchId);
158
+ const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
102
159
  if (!mine(current)) return false;
103
160
  lease = current;
104
- try { config = await readActivation(homes, lease.revision); } catch { config = null; }
161
+ try { config = await readActivation(homes, lease.revision, {anchorHome: codexHome, host: lease.hostPlatform, runtimePlatforms}); } catch { config = null; }
105
162
  return true;
106
163
  });
107
164
  if (!guarded) return; // not the supervisor registered for this dispatch
@@ -119,9 +176,9 @@ export async function runSupervisor(options) {
119
176
  };
120
177
  const commit = async (state, codes, claims, extra = {}) => {
121
178
  await locked(async () => {
122
- const current = await readLease(codexHome, dispatchId);
179
+ const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
123
180
  if (!current || TERMINAL_STATES.includes(current.state)) return;
124
- await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null});
181
+ await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null}, {runtimePlatforms});
125
182
  });
126
183
  };
127
184
  const earlyFailure = async (code, spawned = null) => {
@@ -148,8 +205,10 @@ export async function runSupervisor(options) {
148
205
  try {
149
206
  if (config === null) return await earlyFailure('activation_unverified');
150
207
  const requested = config.roles[lease.role], platform = requested.platform;
208
+ const implementation = (options.supervisorImplementations ?? SUPERVISOR_IMPLEMENTATIONS).get(platform);
209
+ if (!implementation) throw Error('Invalid composite profile: unknown platform');
151
210
  let invocation;
152
- try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
211
+ try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy, supervisorImplementations: options.supervisorImplementations}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
153
212
  if (invocation.argsDigest !== lease.argsDigest) return await earlyFailure('activation_unverified');
154
213
  const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
155
214
  const cli = resolveLocalCli(platform, context);
@@ -166,7 +225,7 @@ export async function runSupervisor(options) {
166
225
  child.on('error', () => { exited = true; exitResolve({code: null, signal: null, spawnError: true}); });
167
226
  child.stdin.on('error', () => {});
168
227
  if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
169
- child.stdin.end(brief);
228
+ child.stdin.end(invocation.stdinInstructions === undefined ? brief : `${invocation.stdinInstructions}\n\n${brief}`);
170
229
  const stdoutClosed = new Promise(resolve => { child.stdout.on('close', resolve); child.stdout.on('error', resolve); });
171
230
 
172
231
  const state = {init: null, initEval: null, threadId: null, codexEval: null, terminal: false, terminalError: false, resultText: undefined, messages: [], mismatch: null, internal: null};
@@ -211,9 +270,29 @@ export async function runSupervisor(options) {
211
270
  }
212
271
  };
213
272
  const handle = raw => {
214
- const normalized = platform === 'claude' ? normalizeClaudeStreamEvent(raw) : normalizeCodexStreamEvent(raw);
273
+ const normalized = implementation.normalize(raw);
215
274
  if (!normalized) return;
216
275
  writeEvent(normalized);
276
+ if (platform === 'gemini') {
277
+ if (normalized.kind !== 'unknown') {
278
+ if (normalized.sessionId) {
279
+ if (normalized.sessionId !== lease.sessionId) state.geminiSessionMismatch = true;
280
+ state.geminiSessionId = normalized.sessionId;
281
+ }
282
+ if (normalized.model) {
283
+ if (normalized.model !== invocation.expected.model) state.geminiModelMismatch = true;
284
+ state.geminiModel = normalized.model;
285
+ }
286
+ }
287
+ if (normalized.kind === 'init') state.init = normalized;
288
+ if (normalized.kind === 'message' && normalized.role === 'assistant' && typeof normalized.text === 'string') {
289
+ state.resultText = (state.resultText ?? '') + normalized.text;
290
+ }
291
+ if (normalized.kind === 'result') {
292
+ state.terminal = true; state.terminalError ||= normalized.isError === true;
293
+ }
294
+ return;
295
+ }
217
296
  if (normalized.kind === 'init') {
218
297
  state.init = normalized; state.initEval = evaluateClaudeInit({init: normalized, expected: invocation.expected});
219
298
  if (state.initEval.reason && !state.mismatch) { state.mismatch = state.initEval.reason; terminate('mismatch'); }
@@ -235,9 +314,9 @@ export async function runSupervisor(options) {
235
314
  const startTime = child.pid ? processStartTime(child.pid) ?? 'unavailable' : null;
236
315
  if (startTime === null) throw Error('Child did not start');
237
316
  await locked(async () => {
238
- const current = await readLease(codexHome, dispatchId);
317
+ const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
239
318
  if (!mine(current)) throw Error('Lease changed before the child was recorded');
240
- await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}});
319
+ await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}}, {runtimePlatforms});
241
320
  });
242
321
  } catch { state.internal = 'execution_failed'; terminate('internal'); }
243
322
 
@@ -262,8 +341,8 @@ export async function runSupervisor(options) {
262
341
  const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
263
342
  await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow}).catch(() => {});
264
343
  await locked(async () => {
265
- const current = await readLease(codexHome, dispatchId);
266
- if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)});
344
+ const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
345
+ if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
267
346
  });
268
347
  return;
269
348
  }
@@ -274,39 +353,24 @@ export async function runSupervisor(options) {
274
353
  const codes = [];
275
354
  if (state.mismatch) codes.push(state.mismatch);
276
355
  if (state.internal) codes.push(state.internal);
277
- let claims, effortMismatch = false;
278
356
  const terminalClaim = {level: 'runtime-observed', source: 'supervisor-exit', observed: {exitCode: exit.code, signal: exit.signal}};
279
- let sessionId = lease.sessionId;
280
- if (platform === 'claude') {
281
- const evaluation = state.initEval ?? evaluateClaudeInit({init: null, expected: invocation.expected});
282
- const observed = await readClaudeTranscriptEffort({claudeHome: homes.claude, sessionId: state.init?.sessionId});
283
- const effort = observed === null ? {level: 'unverified', source: 'none', requested: requested.effort, observed: null, label: 'model_effort_unverified'}
284
- : {level: observed === requested.effort ? 'runtime-observed' : 'unverified', source: 'claude-transcript', requested: requested.effort, observed};
285
- effortMismatch = observed !== null && observed !== requested.effort;
286
- claims = {...evaluation.claims, effort, terminal: terminalClaim};
287
- sessionId = state.init?.sessionId ?? sessionId;
288
- } else {
289
- let finalContext = null;
290
- if (state.threadId) finalContext = await readContext().catch(() => null);
291
- const evaluation = finalContext ? evaluateCodexContext({context: finalContext, expected: invocation.expected, policy}) : state.codexEval ?? evaluateCodexContext({context: null, expected: invocation.expected, policy});
292
- if (evaluation.reason && !codes.includes(evaluation.reason)) codes.push(evaluation.reason);
293
- claims = {identity: state.threadId ? {level: 'runtime-observed', source: 'codex-stream-thread', observed: state.threadId} : {level: 'unverified', source: 'none'}, ...evaluation.claims, terminal: terminalClaim};
294
- sessionId = state.threadId ?? sessionId;
295
- }
357
+ const observation = await implementation.observe({state, invocation, homes, requested, terminalClaim, lease, readContext, policy});
358
+ let {claims, sessionId} = observation;
359
+ const {effortMismatch} = observation;
360
+ const cancelledBeforeIdentity = platform === 'gemini' && terminating === 'cancel' && !implementation.session(state);
361
+ if (observation.reason && !(cancelledBeforeIdentity && observation.reason === 'execution_identity_unverified') && !codes.includes(observation.reason)) codes.push(observation.reason);
362
+ if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
296
363
  if (effortMismatch) codes.push('model_effort_mismatch');
297
364
  if (violations.reason) codes.push(violations.reason);
298
365
  if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
299
366
  else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
300
367
  if (terminating === 'timeout') codes.push('timeout');
301
368
 
302
- let resultPath = null;
303
- if (platform === 'claude') {
304
- if (state.terminal && !state.terminalError && typeof state.resultText === 'string') { await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); resultPath = resultFile; }
305
- } else if (fs.existsSync(resultFile)) resultPath = resultFile;
369
+ const resultPath = await implementation.resultPath(state, resultFile);
306
370
  if (resultPath) await fsp.chmod(resultPath, 0o600);
307
371
 
308
372
  let finalState = 'failed';
309
- const observedSession = platform === 'claude' ? state.init?.sessionId : state.threadId;
373
+ const observedSession = implementation.session(state);
310
374
  if (!codes.length && terminating === 'cancel') finalState = 'cancelled';
311
375
  else if (!codes.length) {
312
376
  const failure = classifyFailure({exitCode: exit.code, signal: exit.signal, terminal: state.terminal, terminalError: state.terminalError, messages: [...state.messages, Buffer.concat(stderrParts).toString('utf8')]});
@@ -319,13 +383,14 @@ export async function runSupervisor(options) {
319
383
  claims.identity = {level: 'unverified', source: 'none'};
320
384
  }
321
385
  }
386
+ if (platform === 'gemini' && codes.includes('execution_identity_unverified') && terminating !== 'cancel') finalState = 'unknown';
322
387
  if (lease.sessionId && observedSession && observedSession !== lease.sessionId && finalState !== 'cancelled') {
323
388
  // A resumed segment must continue the recorded session; a different observed id leaves the slot occupied.
324
389
  finalState = 'unknown'; sessionId = lease.sessionId; if (!codes.includes('execution_identity_unverified')) codes.push('execution_identity_unverified');
325
390
  claims.identity = {level: 'unverified', source: 'none'};
326
391
  }
327
392
  if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
328
- await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath});
393
+ await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : {})});
329
394
  await commit(finalState, codes, claims, {sessionId, resultPath});
330
395
  } catch {
331
396
  // Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
@@ -340,8 +405,8 @@ export async function runSupervisor(options) {
340
405
  const codes = ['execution_failed', 'terminal_state_unverified'];
341
406
  await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
342
407
  await locked(async () => {
343
- const current = await readLease(codexHome, dispatchId);
344
- if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)});
408
+ const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
409
+ if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
345
410
  }).catch(() => {});
346
411
  }
347
412
  } finally {
@@ -1,3 +1,4 @@
1
+ import {isPlatformId} from './platform-registry.mjs';
1
2
  /**
2
3
  * @typedef {object} WorkflowState
3
4
  * @property {1} schemaVersion
@@ -11,7 +12,7 @@
11
12
  * @property {Array<object>} leases
12
13
  * @typedef {object} NormalizedRequest
13
14
  * @property {string} requestId
14
- * @property {'codex'|'claude'} platform
15
+ * @property {string} platform
15
16
  * @property {string} operation
16
17
  * @property {string} actorRef
17
18
  * @property {string} taskId
@@ -47,7 +48,7 @@ export function validateWorkflowState(s){
47
48
  if(!unique(s.approvals,'id')||s.approvals.some(a=>!approval(a)))fail('approval provenance');
48
49
  if(!unique(s.identities,'actorRef')||s.identities.some(i=>!ROLES.includes(i.role)||!text(i.taskId)||!text(i.observationRef)))fail('identity');
49
50
  if(!unique(s.leases,'actorRef')||s.leases.some(l=>!text(l.taskId)||!['active','suspended','retired'].includes(l.status)))fail('lease');
50
- if(s.assignments.some(a=>!object(a)||!((a.status==='pending'&&a.actorRef===null&&text(a.assignmentId)&&text(a.correlationRef)&&text(a.requestId)&&text(a.requestedBy)&&['codex','claude'].includes(a.platform))||text(a.actorRef))||!text(a.taskId)||!ROLES.includes(a.role)||!strings(a.paths)||a.paths.some(p=>!absolute(p))||!strings(a.operations)||a.operations.some(op=>!OPERATIONS.includes(op))||!text(a.approvalRef)))fail('assignment');
51
+ if(s.assignments.some(a=>!object(a)||!((a.status==='pending'&&a.actorRef===null&&text(a.assignmentId)&&text(a.correlationRef)&&text(a.requestId)&&text(a.requestedBy)&&isPlatformId(a.platform))||text(a.actorRef))||!text(a.taskId)||!ROLES.includes(a.role)||!strings(a.paths)||a.paths.some(p=>!absolute(p))||!strings(a.operations)||a.operations.some(op=>!OPERATIONS.includes(op))||!text(a.approvalRef)))fail('assignment');
51
52
  for(const a of s.assignments){
52
53
  if(a.checks!==undefined&&(!Array.isArray(a.checks)||a.checks.some(c=>!object(c)||!absolute(c.executable)||!Array.isArray(c.args)||!c.args.every(x=>typeof x==='string')||!absolute(c.cwd)||!object(c.env)||!strings(c.outputs)||c.outputs.some(p=>!absolute(p)))))fail('check descriptor');
53
54
  if(a.temporary!==undefined&&(!object(a.temporary)||!strings(a.temporary.paths)||a.temporary.paths.some(p=>!absolute(p))||!text(a.temporary.cleanupOwner)||!Number.isFinite(Date.parse(a.temporary.expiresAt))))fail('temporary assignment');
@@ -63,7 +64,7 @@ export function validateWorkflowState(s){
63
64
  return s;
64
65
  }
65
66
  export function validateRequest(r){
66
- if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!['codex','claude'].includes(r.platform)||!OPERATIONS.includes(r.operation)||!absolute(r.cwd)||!object(r.arguments)||!object(r.descriptor)||!strings(r.paths)||r.paths.some(p=>!absolute(p)))fail('request');
67
+ if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!isPlatformId(r.platform)||!OPERATIONS.includes(r.operation)||!absolute(r.cwd)||!object(r.arguments)||!object(r.descriptor)||!strings(r.paths)||r.paths.some(p=>!absolute(p)))fail('request');
67
68
  return r;
68
69
  }
69
70
  export function validateEvidence(e){
@@ -72,7 +73,7 @@ export function validateEvidence(e){
72
73
  if(e.facts!==undefined&&(!Array.isArray(e.facts)||e.facts.some(f=>!object(f)||!text(f.kind)||!text(f.workflowId)||!Number.isSafeInteger(f.revision)||!object(f.target)||!hash(f.policyHash)||!text(f.sourceRef)||!object(f.data))))fail('facts');
73
74
  for(const p of e.provenance){
74
75
  if(!['platform-event','user-message','human-confirmation'].includes(p.source))fail('provenance source');
75
- if(p.source==='platform-event'&&(!text(p.eventRef)||!text(p.actorRef)||!['codex','claude'].includes(p.platform)))fail('platform provenance');
76
+ if(p.source==='platform-event'&&(!text(p.eventRef)||!text(p.actorRef)||!isPlatformId(p.platform)))fail('platform provenance');
76
77
  if(p.source!=='platform-event'&&(!text(p.messageRef)||!hash(p.contentHash)))fail('approval provenance');
77
78
  if(!object(p.verification)||p.verification.status!=='verified'||!text(p.verification.verifierRef)||!text(p.verification.sourceRef))fail('unverified provenance');
78
79
  }