@yunhozz/arc 0.4.3 → 0.4.5

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 (87) hide show
  1. package/MANIFEST.sha256 +86 -84
  2. package/README.md +3 -2
  3. package/claude/agents/arc-implementer.md +1 -0
  4. package/claude/agents/arc-planner.md +1 -0
  5. package/claude/agents/arc-qa.md +1 -0
  6. package/claude/agents/arc-reviewer.md +1 -0
  7. package/claude/agents/arc-scouter.md +1 -0
  8. package/claude/skill/SKILL.md +7 -4
  9. package/claude/skill/references/commit.md +6 -4
  10. package/claude/skill/references/coordination.md +84 -9
  11. package/claude/skill/references/handoff-prep.md +4 -4
  12. package/claude/skill/references/handoff.md +1 -1
  13. package/claude/skill/references/planning.md +41 -4
  14. package/claude/skill/references/verification.md +4 -4
  15. package/codex/agents/arc-implementer.toml +1 -0
  16. package/codex/agents/arc-planner.toml +1 -0
  17. package/codex/agents/arc-qa.toml +1 -0
  18. package/codex/agents/arc-reviewer.toml +1 -0
  19. package/codex/agents/arc-scouter.toml +1 -0
  20. package/codex/skill/SKILL.md +7 -4
  21. package/codex/skill/references/commit.md +6 -4
  22. package/codex/skill/references/coordination.md +84 -9
  23. package/codex/skill/references/handoff-prep.md +4 -4
  24. package/codex/skill/references/handoff.md +1 -1
  25. package/codex/skill/references/planning.md +41 -4
  26. package/codex/skill/references/verification.md +4 -4
  27. package/gemini/agents/arc-implementer.md +1 -0
  28. package/gemini/agents/arc-planner.md +1 -0
  29. package/gemini/agents/arc-qa.md +1 -0
  30. package/gemini/agents/arc-reviewer.md +1 -0
  31. package/gemini/agents/arc-scouter.md +1 -0
  32. package/gemini/skill/SKILL.md +7 -4
  33. package/gemini/skill/references/commit.md +6 -4
  34. package/gemini/skill/references/coordination.md +85 -10
  35. package/gemini/skill/references/handoff-prep.md +4 -4
  36. package/gemini/skill/references/handoff.md +1 -1
  37. package/gemini/skill/references/planning.md +41 -4
  38. package/gemini/skill/references/verification.md +4 -4
  39. package/grok/agents/arc-implementer.md +1 -0
  40. package/grok/agents/arc-planner.md +1 -0
  41. package/grok/agents/arc-qa.md +1 -0
  42. package/grok/agents/arc-reviewer.md +1 -0
  43. package/grok/agents/arc-scouter.md +1 -0
  44. package/grok/skill/SKILL.md +7 -4
  45. package/grok/skill/references/commit.md +6 -4
  46. package/grok/skill/references/coordination.md +88 -13
  47. package/grok/skill/references/handoff-prep.md +4 -4
  48. package/grok/skill/references/handoff.md +1 -1
  49. package/grok/skill/references/planning.md +41 -4
  50. package/grok/skill/references/verification.md +4 -4
  51. package/lib/installer/global-config.mjs +8 -3
  52. package/lib/installer/language.mjs +54 -6
  53. package/lib/installer/plan.mjs +13 -11
  54. package/lib/installer/role-routing.mjs +2 -2
  55. package/lib/installer/runtime-assets.mjs +1 -0
  56. package/lib/installer/upgrade-state.mjs +10 -3
  57. package/lib/installer/upgrade.mjs +3 -3
  58. package/lib/management/operations.mjs +9 -6
  59. package/lib/management/status.mjs +22 -3
  60. package/lib/platforms/claude.mjs +1 -0
  61. package/lib/platforms/codex.mjs +1 -0
  62. package/lib/platforms/index.mjs +7 -0
  63. package/lib/policy/placement.mjs +2 -2
  64. package/lib/policy/render.mjs +1 -1
  65. package/lib/policy/role-policy.json +28 -2
  66. package/lib/prompts/agent-fragments.json +1 -1
  67. package/lib/prompts/render.mjs +1 -1
  68. package/lib/runtime/bootstrap.mjs +1 -1
  69. package/lib/runtime/grok-sandbox.mjs +234 -0
  70. package/lib/runtime/platform-registry.mjs +2 -2
  71. package/lib/runtime/role-bridge-args.mjs +6 -4
  72. package/lib/runtime/role-bridge.mjs +14 -6
  73. package/lib/runtime/role-dispatch-policy.mjs +30 -5
  74. package/lib/runtime/role-routing.mjs +31 -4
  75. package/lib/runtime/role-supervisor.mjs +77 -16
  76. package/lib/tui/mode.mjs +15 -3
  77. package/lib/tui/setup.mjs +51 -34
  78. package/package.json +1 -1
  79. package/shared/skill/runtime/bootstrap.mjs +1 -1
  80. package/shared/skill/runtime/grok-sandbox.mjs +234 -0
  81. package/shared/skill/runtime/platform-registry.mjs +2 -2
  82. package/shared/skill/runtime/role-bridge-args.mjs +6 -4
  83. package/shared/skill/runtime/role-bridge.mjs +14 -6
  84. package/shared/skill/runtime/role-dispatch-policy.mjs +30 -5
  85. package/shared/skill/runtime/role-policy.json +28 -2
  86. package/shared/skill/runtime/role-routing.mjs +31 -4
  87. package/shared/skill/runtime/role-supervisor.mjs +77 -16
@@ -20,8 +20,8 @@ export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
20
20
  arc_scouter: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
21
21
  arc_planner: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
22
22
  arc_reviewer: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
23
- arc_implementer: {permissionMode: 'acceptEdits', sandbox: 'workspace', deny: []},
24
- arc_qa: {permissionMode: 'acceptEdits', sandbox: 'workspace', deny: []},
23
+ arc_implementer: {permissionMode: 'acceptEdits', sandbox: 'custom', deny: []},
24
+ arc_qa: {permissionMode: 'acceptEdits', sandbox: 'custom', deny: []},
25
25
  },
26
26
  codex: {
27
27
  arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
@@ -231,13 +231,15 @@ export function buildGeminiArgs({role, model, profile, sessionId, policyFile, pr
231
231
  return args;
232
232
  }
233
233
 
234
- export function buildGrokArgs({role, profile, sessionId, promptFile}) {
234
+ export function buildGrokArgs({role, profile, sessionId, promptFile, sandboxProfile}) {
235
235
  const permissions = permissionsFor('grok', role);
236
236
  if (typeof promptFile !== 'string' || !path.isAbsolute(promptFile)) throw Error('Absolute promptFile required');
237
237
  if (typeof sessionId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) throw Error('Grok sessionId must be a UUID');
238
238
  const model = requireText(profile?.model, 'model');
239
239
  if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model)) throw Error('Invalid Grok model');
240
+ const sandbox = permissions.sandbox === 'custom' ? sandboxProfile : permissions.sandbox;
241
+ if (permissions.sandbox === 'custom' && (typeof sandbox !== 'string' || !/^arc-bridge-[0-9a-f]{8}$/.test(sandbox))) throw Error('Invalid Grok sandbox profile');
240
242
  return ['--prompt-file', promptFile, '--output-format', GROK_CONTRACT.outputFormat, '-m', model, '--session-id', sessionId,
241
- '--permission-mode', permissions.permissionMode, '--sandbox', permissions.sandbox,
243
+ '--permission-mode', permissions.permissionMode, '--sandbox', sandbox,
242
244
  ...permissions.deny.flatMap(rule => ['--deny', rule]), ...GROK_CONTRACT.isolationArgs];
243
245
  }
@@ -3,9 +3,9 @@ import {runtimeRegistryOf, DEFAULT_PLATFORM_REGISTRY} from './platform-registry.
3
3
  // run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
4
4
  import fsp from 'node:fs/promises';
5
5
  import path from 'node:path';
6
- import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
6
+ import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
7
7
  import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease} from './role-dispatch-store.mjs';
8
- import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome} from './role-routing.mjs';
8
+ import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome, probeHomeWritable} from './role-routing.mjs';
9
9
  import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
10
10
 
11
11
  export const heldRoutingResult=(code,releaseCondition)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',route:null,executionEnvironment:null,hostPlatform:null,role:null,requested:null,authentication:null,reasons:[{code,releaseCondition}]});
@@ -47,16 +47,20 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
47
47
  await withRoutingLock(anchorHome,async()=>{
48
48
  const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
49
49
  if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
50
- leaseTargetPlatform(lease,runtimePlatforms);
50
+ const platform=leaseTargetPlatform(lease,runtimePlatforms);
51
51
  let config;try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
52
52
  validateLease(lease,{runtimePlatforms,config});
53
- const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:leaseTargetPlatform(lease,runtimePlatforms),route:lease.route,runtimePlatforms});
53
+ const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:platform,route:lease.route,runtimePlatforms});
54
54
  if(capabilities.length){result=blank(context,dispatchId,'hold',capabilities[0]);return;}
55
55
  let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
56
56
  const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
57
57
  let invocation;try{invocation=await buildBridgeInvocation({lease,config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
58
58
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
59
59
  await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
60
+ if(Object.hasOwn(HOST_SANDBOX_GATES,lease.hostPlatform)){
61
+ const probe=await probeHomeWritable(homes[platform]);
62
+ if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
63
+ }
60
64
  let supervisor;
61
65
  try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
62
66
  catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
@@ -67,7 +71,7 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
67
71
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
68
72
  else return hold(context,dispatchId,classifyLock(error),error);
69
73
  }
70
- if(residual)result.residualPaths=residual;
74
+ if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
71
75
  return result;
72
76
  }
73
77
 
@@ -165,6 +169,10 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
165
169
  let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy,supervisorImplementations});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
166
170
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
167
171
  await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
172
+ if(Object.hasOwn(HOST_SANDBOX_GATES,lease.hostPlatform)){
173
+ const probe=await probeHomeWritable(homes[platform]);
174
+ if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
175
+ }
168
176
  await clearCancel(anchorHome,dispatchId);
169
177
  let supervisor;
170
178
  try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
@@ -177,7 +185,7 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
177
185
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
178
186
  else return hold(context,dispatchId,classifyLock(error),error);
179
187
  }
180
- if(residual)result.residualPaths=residual;
188
+ if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
181
189
  return result;
182
190
  }
183
191
 
@@ -1,8 +1,28 @@
1
1
  import {runtimeRegistryOf} from './platform-registry.mjs';
2
2
  // Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
3
- export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail', GK1: 'fail', GK2: 'fail'});
4
- // No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
5
- const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
3
+ // GK2/GG2 'approval' means a Grok/Gemini host keeps its platform-default sandbox (off), runs in ask mode, and obtains user approval for each runtime command; it is not a verified pass.
4
+ // GK2 evidence: Grok 1.0.89, 2026-11-19, ask mode with the sandbox off.
5
+ // GK1 evidence: Grok 1.0.89, 2026-11-19, writing roles only, with mandatory ProfileApplied verification.
6
+ export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'pass', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail', GK1: 'pass', GK2: 'approval'});
7
+ export const HOST_SANDBOX_GATES = Object.freeze({grok: 'GK2', gemini: 'GG2'});
8
+ export const HOST_GATE_ALLOWED = Object.freeze(['pass', 'approval']);
9
+
10
+ function deepFreeze(value) {
11
+ for (const nested of Object.values(value)) {
12
+ if (nested !== null && typeof nested === 'object') deepFreeze(nested);
13
+ }
14
+ return Object.freeze(value);
15
+ }
16
+
17
+ // Claude 2.1.328, 2026-11-19, macOS Seatbelt: /private/tmp/claude-<uid> is writable, Bash exits 71 per command if sandboxing is unavailable, and M-C4 found no widening in trusted or untrusted workspaces.
18
+ const RECORDED_CLAUDE_SANDBOX_SETTINGS = deepFreeze({
19
+ sandbox: {
20
+ enabled: true,
21
+ autoAllowBashIfSandboxed: true,
22
+ allowUnsandboxedCommands: false,
23
+ failIfUnavailable: true,
24
+ },
25
+ });
6
26
  const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
7
27
  export const CLAUDE_SANDBOX_SETTINGS = BRIDGE_GATE_RESULTS.G1 === 'pass' && isRecordedObject(RECORDED_CLAUDE_SANDBOX_SETTINGS) ? RECORDED_CLAUDE_SANDBOX_SETTINGS : null;
8
28
  /** G1 counts as passed only with an explicitly recorded settings object; otherwise the settings are null. */
@@ -83,13 +103,18 @@ export function capabilityReasons({hostPlatform, targetPlatform, route, runtimeP
83
103
  && (route !== 'bridge' || target?.capabilities.bridge.state === 'verified') ? [] : ['capability_not_verified'];
84
104
  }
85
105
 
106
+ export function hostGateReasons({hostPlatform, policy = DEFAULT_POLICY}) {
107
+ if (!Object.hasOwn(HOST_SANDBOX_GATES, hostPlatform)) return [];
108
+ const gates = policy.gates ?? BRIDGE_GATE_RESULTS;
109
+ return HOST_GATE_ALLOWED.includes(gates[HOST_SANDBOX_GATES[hostPlatform]]) ? [] : ['host_sandbox_blocked'];
110
+ }
111
+
86
112
  export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
87
113
  const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
88
114
  if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
89
115
  if (platform === 'gemini' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GG1 !== 'pass') codes.push('permission_scope_unverified');
90
116
  if (platform === 'grok' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GK1 !== 'pass') codes.push('permission_scope_unverified');
91
- if (hostPlatform === 'grok' && gates.GK2 !== 'pass') codes.push('host_sandbox_blocked');
92
- if (hostPlatform === 'gemini' && gates.GG2 !== 'pass') codes.push('host_sandbox_blocked');
117
+ codes.push(...hostGateReasons({hostPlatform, policy}));
93
118
  if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
94
119
  if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
95
120
  return [...new Set(codes)];
@@ -108,7 +108,7 @@
108
108
  "task-progress-classification-reason-time"
109
109
  ],
110
110
  "authority": "orchestrator",
111
- "text": "Only Orchestrator accepts work and performs Git mutations. One approved top-level plan task becomes one focused implementation commit after criteria, required checks and findings are satisfied. Orchestrator accepts, then includes that task's own progress records made after task completion (checkboxes, notes, results, evidence and status) with its implementation work in that commit, without a separate docs/fixup commit or planning-commit amendment for those records. Exclude other tasks; pending approved spec/plan revisions follow planning.plan-revision and preserve the no-change path without empty commits. Orchestrator commits without separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.",
111
+ "text": "Only Orchestrator accepts work and performs Git mutations. One approved top-level plan task becomes one focused implementation commit after criteria, required checks and findings are satisfied. Orchestrator accepts, then includes that task's own progress records made after task completion (checkboxes, notes, results, evidence and status) with its implementation work in that commit, without a separate docs/fixup commit or planning-commit amendment for those records. Exclude other tasks; pending approved spec/plan revisions follow planning.plan-revision and preserve the no-change path without empty commits. Plan-level progress records (final verification results, final Reviewer verdicts and finding dispositions, overall completion status) are the sole exception: include them in the plan's next task acceptance or final Reviewer follow-up commit; when no implementation work remains and no standalone closing commit for pending revisions is made, keep them only in the canonical handoff record without changing the plan document or creating a commit. Orchestrator commits without separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.",
112
112
  "controls": {
113
113
  "codex": "prompt",
114
114
  "claude": "prompt",
@@ -146,6 +146,32 @@
146
146
  "grok": "prompt"
147
147
  }
148
148
  },
149
+ {
150
+ "id": "approval.run-mode",
151
+ "roles": [
152
+ "orchestrator",
153
+ "scouter",
154
+ "planner",
155
+ "implementer",
156
+ "qa",
157
+ "reviewer"
158
+ ],
159
+ "effect": "require",
160
+ "operations": [
161
+ "gate-decision"
162
+ ],
163
+ "evidence": [
164
+ "user-choice-or-recorded-full-auto-decision"
165
+ ],
166
+ "authority": "user",
167
+ "text": "The installed ARC Run mode is Supervised unless the installed skill states Full Auto. In Full Auto, an Orchestrator decision recorded as `auto-decided (Full Auto)` with gate, choice, reason and evidence counts as the explicit choice or approval for that listed gate only; briefs cite it as `full-auto:<doc>@<version>` or the recorded decision. It never authorizes new product decisions outside the original request, external actions, resolution of failures, holds, unknown state or ownership conflicts, preservation-rule Git actions, permission or sandbox changes, or unknown slots and exhausted capacity, and it changes no plan-depth, commit, QA, Reviewer or acceptance rule. A user request to stop or use Supervised applies from the next gate.",
168
+ "controls": {
169
+ "codex": "prompt",
170
+ "claude": "prompt",
171
+ "gemini": "prompt",
172
+ "grok": "prompt"
173
+ }
174
+ },
149
175
  {
150
176
  "id": "role.orchestrator-boundary",
151
177
  "roles": [
@@ -378,7 +404,7 @@
378
404
  "plan-revision-trailers"
379
405
  ],
380
406
  "authority": "orchestrator",
381
- "text": "Task progress records (checkboxes, notes, results, evidence and status) preserving the approved contract need no new user approval; Orchestrator includes the completed task's own records in its accepted implementation commit and records classification, reason and actual time as applicable. All other spec/plan content changes, contract or mechanical, require applicable approval and preparation; changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval, preparation and holds on affected work before it continues, with a fresh Implementer for remaining work. After approval Orchestrator edits the same document, appends a revision-history row and leaves it uncommitted as an Orchestrator-owned pending revision, recording version, content hash, approval reference, actual time, classification, reason, affected tasks and the full approved content in the canonical handoff record. Orchestrator includes all pending revisions with Plan-Revision, Plan-Approved-At and Plan-Reason trailers in the accepted commit of the first top-level task executed or reconfirmed against the revised version, otherwise in a current task or final Reviewer follow-up commit; only when no implementation work remains before overall completion MAY it make one standalone docs(plan) closing commit without implementation files. Exclude revision hunks from commits of independent tasks accepted on a prior version, or hold that commit when separation is unsafe. NEVER amend or rewrite planning or implementation commits, create any other docs/fixup commit or authorize past work retroactively. After commit verify the committed document content matches the latest approved content apart from classified progress records of that commit's task or committed for other tasks after approval, and that no pending revision remains. Follow planning, handoff-prep, commit and verification for the full contract.",
407
+ "text": "Task progress records (checkboxes, notes, results, evidence and status) preserving the approved contract need no new user approval; Orchestrator includes the completed task's own records in its accepted implementation commit and records classification, reason and actual time as applicable. Plan-level progress records preserving the approved contract also need no new user approval and alone never trigger the standalone docs(plan) closing commit. All other spec/plan content changes, contract or mechanical, require applicable approval and preparation; changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval, preparation and holds on affected work before it continues, with a fresh Implementer for remaining work. After approval Orchestrator edits the same document, appends a revision-history row and leaves it uncommitted as an Orchestrator-owned pending revision, recording version, content hash, approval reference, actual time, classification, reason, affected tasks and the full approved content in the canonical handoff record. Orchestrator includes all pending revisions with Plan-Revision, Plan-Approved-At and Plan-Reason trailers in the accepted commit of the first top-level task executed or reconfirmed against the revised version, otherwise in a current task or final Reviewer follow-up commit; only when no implementation work remains before overall completion MAY it make one standalone docs(plan) closing commit without implementation files. Exclude revision hunks from commits of independent tasks accepted on a prior version, or hold that commit when separation is unsafe. NEVER amend or rewrite planning or implementation commits, create any other docs/fixup commit or authorize past work retroactively. After commit verify the committed document content matches the latest approved content apart from classified progress records of that commit's task or committed for other tasks after approval, or plan-level progress records carried by that commit, and that no pending revision remains. Follow planning, handoff-prep, commit and verification for the full contract.",
382
408
  "controls": {
383
409
  "codex": "prompt",
384
410
  "claude": "prompt",
@@ -7,7 +7,7 @@ import {COOPERATIVE_RUNTIME_MODULES, cooperativeVersions} from './bootstrap.mjs'
7
7
  import {inspectPath} from './scope.mjs';
8
8
  import {resolveConfigHome, resolveLocalCli, probePlatformAuth, probeCodexAuthStatus, probeCliVersion} from './local-cli.mjs';
9
9
  import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
10
- import {DEFAULT_POLICY, reason, profileName, revisionTag, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
10
+ import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, revisionTag, hostGateReasons, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
11
11
  import {NON_TERMINAL_STATES, createLease, listLeases, pruneTerminalLeases, readHostLimits} from './role-dispatch-store.mjs';
12
12
 
13
13
  const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
@@ -114,6 +114,27 @@ export async function readActivation(homes,expectedRevision,{anchorHome=homes.co
114
114
 
115
115
 
116
116
  const HOST_ERRORS=['EACCES','EPERM','EROFS'];
117
+ export async function probeHomeWritable(home, {unlink = fs.unlink} = {}) {
118
+ const file = path.join(home, '.arc-host-probe-' + crypto.randomUUID());
119
+ let handle;
120
+ try {
121
+ handle = await fs.open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
122
+ } catch (error) {
123
+ return {ok: false, code: HOST_ERRORS.includes(error?.code) ? 'host_sandbox_blocked' : 'activation_unverified'};
124
+ }
125
+ let closed = false;
126
+ try {
127
+ await handle.close();
128
+ closed = true;
129
+ } catch { /* Attempt to remove the file even if close fails. */ }
130
+ try {
131
+ await unlink(file);
132
+ } catch {
133
+ return {ok: false, code: 'host_sandbox_blocked', residualPaths: [file]};
134
+ }
135
+ return closed ? {ok: true} : {ok: false, code: 'activation_unverified'};
136
+ }
137
+
117
138
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
118
139
  const lockFile=codexHome=>path.join(codexHome,'arc-role-platform-routing.lock');
119
140
  /** Runs fn under the shared routing lock. Only EEXIST is retried; the lock file is never removed except by its owner. */
@@ -231,14 +252,20 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
231
252
  const leases=await listLeases(anchorHome,{runtimePlatforms});
232
253
  const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
233
254
  if(leases.some(lease=>lease.requestId===assignment.requestId)||live.some(lease=>lease.workflowId===context.workflowId&&lease.taskId===assignment.taskId&&lease.role===role)){duplicate=true;codes.add('duplicate_dispatch');}
234
- if(host==='grok'&&(policy.gates?.GK2??DEFAULT_POLICY.gates.GK2)!=='pass')codes.add('host_sandbox_blocked');
235
- if(host==='gemini'&&(policy.gates?.GG2??DEFAULT_POLICY.gates.GG2)!=='pass')codes.add('host_sandbox_blocked');
255
+ for(const code of hostGateReasons({hostPlatform:host,policy}))codes.add(code);
236
256
  if(route==='bridge'){
237
257
  let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
238
258
  if(limits){
239
259
  const bridges=leases.filter(lease=>lease.route==='bridge');
240
260
  if(bridges.filter(lease=>NON_TERMINAL_STATES.includes(lease.state)).length>=limits.maxConcurrent||bridges.filter(lease=>lease.workflowId===context.workflowId).length>=limits.maxTotal)codes.add('capacity_exhausted');
241
261
  }
262
+ if(Object.hasOwn(HOST_SANDBOX_GATES,host)){
263
+ const probe=await probeHomeWritable(homes[requested.platform]);
264
+ if(!probe.ok){
265
+ codes.add(probe.code);
266
+ if(probe.residualPaths)result.residualPaths=probe.residualPaths;
267
+ }
268
+ }
242
269
  for(const code of bridgeGateReasons({platform:requested.platform,role,hostPlatform:host,policy}))codes.add(code);
243
270
  }
244
271
  result.reasons=[...codes].map(reason);
@@ -254,7 +281,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
254
281
  }else{
255
282
  Object.assign(result,{decision:'hold',routeStatus:'held',dispatchId:null,claims:null,reasons:[reason(classify(error))]});
256
283
  }
257
- const residual=residualOf(error);if(residual)result.residualPaths=residual;
284
+ const residual=residualOf(error);if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
258
285
  }
259
286
  return result;
260
287
  }
@@ -7,6 +7,7 @@ import crypto from 'node:crypto';
7
7
  import {spawn, spawnSync} from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
10
+ import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied} from './grok-sandbox.mjs';
10
11
  import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
11
12
  import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
12
13
  import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
@@ -117,6 +118,14 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
117
118
  }
118
119
  if ((platform === 'gemini' || platform === 'grok') && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', platform === 'grok' ? 'Grok resume is not verified' : 'Gemini resume is not verified');
119
120
  if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
121
+ const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
122
+ let grokSandbox;
123
+ if (platform === 'grok' && permissions.sandbox === 'custom') {
124
+ const name = grokSandboxProfileName(lease.dispatchId);
125
+ if (!name || grokProfileCovered(lease.allowedPaths)) throw fail('permission_scope_unverified', 'Grok sandbox profile scope is unavailable');
126
+ inspectGrokProfileSlot(worktree);
127
+ grokSandbox = {name, path: path.join(worktree, GROK_SANDBOX_RELATIVE), bytes: renderGrokSandboxProfile(name)};
128
+ }
120
129
  const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
121
130
  let bytes;
122
131
  try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
@@ -124,14 +133,13 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
124
133
  let profile, args;
125
134
  try {
126
135
  profile = parseCompositeProfile(platform, bytes);
127
- args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath)} : {}), resume: lease.segment > 0});
136
+ args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath), sandboxProfile: grokSandbox?.name} : {}), resume: lease.segment > 0});
128
137
  } catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
129
- const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
130
138
  const expected = platform === 'claude'
131
139
  ? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
132
140
  : platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
133
141
  : {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
134
- return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {})};
142
+ return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {}), ...(grokSandbox ? {grokSandbox} : {})};
135
143
  }
136
144
 
137
145
  /** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
@@ -197,10 +205,31 @@ export async function runSupervisor(options) {
197
205
  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});
198
206
  });
199
207
  };
200
- const earlyFailure = async (code, spawned = null) => {
208
+ let createdGrokProfile, grokSandboxProfile, spawnAtMs, profileViolation = false;
209
+ const grokProfileRecord = () => grokSandboxProfile ? {grokSandboxProfile, ...(spawnAtMs === undefined ? {} : {spawnAtMs})} : {};
210
+ const cleanGrokProfile = () => {
211
+ if (!grokSandboxProfile || grokSandboxProfile.removed !== null) return;
212
+ const {removed, dirRemoved, violation} = removeGrokSandboxProfile(createdGrokProfile);
213
+ Object.assign(grokSandboxProfile, {removed, dirRemoved});
214
+ profileViolation = violation;
215
+ };
216
+ const retainGrokProfile = () => {
217
+ if (grokSandboxProfile?.removed === null) Object.assign(grokSandboxProfile, {removed: false, reason: 'child_unobserved'});
218
+ return grokProfileRecord();
219
+ };
220
+ const earlyFailure = async (code, spawned = null, extra = {}) => {
201
221
  const claims = {...(lease.claims ?? {}), terminal: {level: 'runtime-observed', source: 'supervisor'}};
202
- await writeRecord({state: 'failed', reasons: [code], spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {})}).catch(() => {});
203
- await commit('failed', [code], claims);
222
+ const codes = [code];
223
+ if (profileViolation) {
224
+ codes.push('permission_violation_observed');
225
+ claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
226
+ }
227
+ await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
228
+ await commit('failed', codes, claims);
229
+ };
230
+ const failWithProfileCleanup = (code, spawned = null) => {
231
+ cleanGrokProfile();
232
+ return earlyFailure(code, spawned, grokProfileRecord());
204
233
  };
205
234
 
206
235
  let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
@@ -229,8 +258,23 @@ export async function runSupervisor(options) {
229
258
  const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
230
259
  const cli = resolveLocalCli(platform, context);
231
260
  if (cli.reason) return await earlyFailure(cli.reason === 'cli_not_found' ? 'Not Available' : 'execution_failed');
261
+ const childEnv = {...localCliEnvironment(cli), ...invocation.childEnv};
262
+ if (invocation.grokSandbox) {
263
+ if (Object.hasOwn(invocation.childEnv, 'GROK_HOME') || !checkGrokHome({grokHome: homes.grok, userHome, childEnv})) return await earlyFailure('permission_scope_unverified');
264
+ try { createdGrokProfile = createGrokSandboxProfile({worktree: target.realpath, bytes: invocation.grokSandbox.bytes}); }
265
+ catch (error) {
266
+ const cleanup = error.cleanup;
267
+ if (cleanup?.violation) {
268
+ profileViolation = true;
269
+ grokSandboxProfile = {name: invocation.grokSandbox.name, path: cleanup.path, created: true, removed: !cleanup.retained, dirRemoved: cleanup.dirRemoved, reason: 'profile_creation_cleanup_failed'};
270
+ }
271
+ return await earlyFailure(error.reasonCode ?? 'permission_scope_unverified', null, grokProfileRecord());
272
+ }
273
+ const {path, sha256, dirCreated} = createdGrokProfile;
274
+ grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
275
+ }
232
276
  let before;
233
- try { before = await snapshotWorktree(target.realpath); } catch { return await earlyFailure('execution_failed'); }
277
+ try { before = await snapshotWorktree(target.realpath); } catch { return await failWithProfileCleanup('execution_failed'); }
234
278
 
235
279
  if (invocation.promptFile) {
236
280
  let promptFd;
@@ -238,12 +282,21 @@ export async function runSupervisor(options) {
238
282
  promptFd = fs.openSync(invocation.promptFile.path, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
239
283
  fs.writeFileSync(promptFd, `${invocation.promptFile.instructions}\n\n${brief}`);
240
284
  fs.fchmodSync(promptFd, 0o600);
241
- } catch { return await earlyFailure('execution_failed'); }
285
+ } catch { return await failWithProfileCleanup('execution_failed'); }
242
286
  finally { if (promptFd !== undefined) fs.closeSync(promptFd); }
243
287
  }
244
288
  eventsFd = fs.openSync(path.join(artifactDir, 'events.jsonl'), 'a', 0o600);
289
+ if (grokSandboxProfile) {
290
+ try { grokSandboxProfile.eventsBaseline = grokEventsBaseline(homes.grok); }
291
+ catch { return await failWithProfileCleanup('permission_scope_unverified'); }
292
+ if (!verifyGrokSandboxProfile(createdGrokProfile)) {
293
+ Object.assign(grokSandboxProfile, {removed: false, reason: 'profile_changed_before_spawn'});
294
+ return await earlyFailure('permission_scope_unverified', null, grokProfileRecord());
295
+ }
296
+ spawnAtMs = Date.now();
297
+ }
245
298
  // The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
246
- child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...localCliEnvironment(cli), ...invocation.childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
299
+ child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
247
300
  let exitResolve, exited = false;
248
301
  const exitPromise = new Promise(resolve => { exitResolve = resolve; });
249
302
  child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
@@ -382,7 +435,7 @@ export async function runSupervisor(options) {
382
435
  if (exit.unobserved) {
383
436
  // The child was signalled but its exit was never observed: the slot stays occupied.
384
437
  const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
385
- await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow}).catch(() => {});
438
+ await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile()}).catch(() => {});
386
439
  await locked(async () => {
387
440
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
388
441
  if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
@@ -405,9 +458,16 @@ export async function runSupervisor(options) {
405
458
  if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
406
459
  if (platform === 'grok' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError || !state.terminal)) codes.push('execution_failed');
407
460
  if (effortMismatch) codes.push('model_effort_mismatch');
408
- if (violations.reason) codes.push(violations.reason);
461
+ if (grokSandboxProfile) {
462
+ const {eventsBaseline: baseline, name} = grokSandboxProfile;
463
+ const {ok, reason, applied} = readGrokProfileApplied({grokHome: homes.grok, baseline, spawnAtMs, name, worktreeRealpath: target.realpath});
464
+ if (ok) grokSandboxProfile.applied = applied;
465
+ else if (!(terminating === 'cancel' && reason === 'no_candidate')) codes.push('permission_scope_mismatch');
466
+ }
467
+ cleanGrokProfile();
468
+ if (violations.reason || profileViolation) codes.push(violations.reason ?? 'permission_violation_observed');
409
469
  if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
410
- else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
470
+ if (violations.reason || profileViolation) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
411
471
  if (terminating === 'timeout') codes.push('timeout');
412
472
 
413
473
  const resultPath = platform === 'grok' && (exit.code !== 0 || exit.signal) ? null : await implementation.resultPath(state, resultFile);
@@ -434,7 +494,8 @@ export async function runSupervisor(options) {
434
494
  claims.identity = {level: 'unverified', source: 'none'};
435
495
  }
436
496
  if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
437
- 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}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
497
+ if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
498
+ 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, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
438
499
  await commit(finalState, codes, claims, {sessionId, resultPath});
439
500
  } catch {
440
501
  // Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
@@ -443,11 +504,10 @@ export async function runSupervisor(options) {
443
504
  if (spawnedPid) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
444
505
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
445
506
  for (const timer of killTimers) clearTimeout(timer);
446
- if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
447
- if (stopped) await earlyFailure('execution_failed', spawnedPid).catch(() => {});
507
+ if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
448
508
  else {
449
509
  const codes = ['execution_failed', 'terminal_state_unverified'];
450
- await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
510
+ await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile()}).catch(() => {});
451
511
  await locked(async () => {
452
512
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
453
513
  if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
@@ -455,6 +515,7 @@ export async function runSupervisor(options) {
455
515
  }
456
516
  } finally {
457
517
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
518
+ if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
458
519
  }
459
520
  }
460
521