@yunhozz/arc 0.5.1 → 0.5.3

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 (151) hide show
  1. package/MANIFEST.sha256 +146 -139
  2. package/README.md +12 -3
  3. package/claude/agents/arc-implementer.md +7 -7
  4. package/claude/agents/arc-planner.md +5 -5
  5. package/claude/agents/arc-reviewer.md +6 -6
  6. package/claude/agents/arc-scouter.md +5 -5
  7. package/claude/agents/{arc-qa.md → arc-tester.md} +10 -10
  8. package/claude/skill/SKILL.md +6 -6
  9. package/claude/skill/models.toml +2 -2
  10. package/claude/skill/references/arc-visual-companion.md +2 -2
  11. package/claude/skill/references/commit.md +3 -3
  12. package/claude/skill/references/coordination.md +27 -21
  13. package/claude/skill/references/git-recovery.md +3 -1
  14. package/claude/skill/references/handoff-prep.md +3 -3
  15. package/claude/skill/references/handoff.md +16 -14
  16. package/claude/skill/references/limits.md +2 -2
  17. package/claude/skill/references/planning.md +12 -10
  18. package/claude/skill/references/verification.md +67 -35
  19. package/claude/skill/references/worktree-creation.md +2 -0
  20. package/claude/skill/scripts/model_config.py +25 -9
  21. package/codex/agents/arc-implementer.toml +7 -7
  22. package/codex/agents/arc-planner.toml +6 -6
  23. package/codex/agents/arc-reviewer.toml +7 -7
  24. package/codex/agents/arc-scouter.toml +6 -6
  25. package/codex/agents/{arc-qa.toml → arc-tester.toml} +10 -10
  26. package/codex/skill/SKILL.md +7 -7
  27. package/codex/skill/models.toml +2 -2
  28. package/codex/skill/references/arc-visual-companion.md +3 -3
  29. package/codex/skill/references/commit.md +4 -4
  30. package/codex/skill/references/coordination.md +26 -20
  31. package/codex/skill/references/git-recovery.md +2 -0
  32. package/codex/skill/references/handoff-prep.md +4 -4
  33. package/codex/skill/references/handoff.md +17 -15
  34. package/codex/skill/references/limits.md +2 -2
  35. package/codex/skill/references/planning.md +13 -11
  36. package/codex/skill/references/verification.md +68 -36
  37. package/codex/skill/references/worktree-creation.md +2 -0
  38. package/codex/skill/scripts/model_config.py +28 -15
  39. package/gemini/agents/arc-implementer.md +7 -7
  40. package/gemini/agents/arc-planner.md +5 -5
  41. package/gemini/agents/arc-reviewer.md +6 -6
  42. package/gemini/agents/arc-scouter.md +5 -5
  43. package/gemini/agents/{arc-qa.md → arc-tester.md} +10 -10
  44. package/gemini/skill/SKILL.md +6 -6
  45. package/gemini/skill/models.toml +2 -2
  46. package/gemini/skill/references/arc-visual-companion.md +2 -2
  47. package/gemini/skill/references/commit.md +3 -3
  48. package/gemini/skill/references/coordination.md +27 -21
  49. package/gemini/skill/references/git-recovery.md +3 -1
  50. package/gemini/skill/references/handoff-prep.md +3 -3
  51. package/gemini/skill/references/handoff.md +16 -14
  52. package/gemini/skill/references/limits.md +2 -2
  53. package/gemini/skill/references/planning.md +12 -10
  54. package/gemini/skill/references/verification.md +67 -35
  55. package/gemini/skill/references/worktree-creation.md +2 -0
  56. package/grok/agents/arc-implementer.md +7 -7
  57. package/grok/agents/arc-planner.md +5 -5
  58. package/grok/agents/arc-reviewer.md +6 -6
  59. package/grok/agents/arc-scouter.md +5 -5
  60. package/grok/agents/{arc-qa.md → arc-tester.md} +10 -10
  61. package/grok/skill/SKILL.md +6 -6
  62. package/grok/skill/models.toml +2 -2
  63. package/grok/skill/references/arc-visual-companion.md +2 -2
  64. package/grok/skill/references/commit.md +3 -3
  65. package/grok/skill/references/coordination.md +27 -21
  66. package/grok/skill/references/git-recovery.md +3 -1
  67. package/grok/skill/references/handoff-prep.md +3 -3
  68. package/grok/skill/references/handoff.md +16 -14
  69. package/grok/skill/references/limits.md +2 -2
  70. package/grok/skill/references/planning.md +12 -10
  71. package/grok/skill/references/verification.md +67 -35
  72. package/grok/skill/references/worktree-creation.md +2 -0
  73. package/lib/installer/install-mode.mjs +4 -2
  74. package/lib/installer/install.mjs +4 -3
  75. package/lib/installer/language.mjs +1 -1
  76. package/lib/installer/legacy-profiles.mjs +51 -0
  77. package/lib/installer/manifest.mjs +1 -1
  78. package/lib/installer/plan.mjs +5 -3
  79. package/lib/installer/preset.mjs +2 -2
  80. package/lib/installer/role-routing.mjs +49 -18
  81. package/lib/installer/runtime-assets.mjs +3 -0
  82. package/lib/installer/targets.mjs +1 -1
  83. package/lib/installer/transaction.mjs +35 -4
  84. package/lib/installer/uninstall.mjs +13 -10
  85. package/lib/installer/upgrade-state.mjs +13 -1
  86. package/lib/management/operations.mjs +10 -10
  87. package/lib/management/reapply.mjs +5 -3
  88. package/lib/models/config.mjs +25 -7
  89. package/lib/models/profiles.mjs +1 -1
  90. package/lib/platforms/formats/gemini-markdown.mjs +3 -3
  91. package/lib/platforms/formats/grok-markdown.mjs +3 -3
  92. package/lib/platforms/formats/markdown.mjs +2 -2
  93. package/lib/platforms/formats/toml.mjs +2 -2
  94. package/lib/policy/placement.mjs +1 -1
  95. package/lib/policy/render.mjs +3 -3
  96. package/lib/policy/role-policy.json +28 -28
  97. package/lib/prompts/agent-fragments.json +24 -24
  98. package/lib/prompts/render.mjs +9 -9
  99. package/lib/runtime/acceptance.mjs +4 -3
  100. package/lib/runtime/bootstrap.mjs +4 -2
  101. package/lib/runtime/command.mjs +29 -3
  102. package/lib/runtime/cooperative-schema.mjs +16 -5
  103. package/lib/runtime/cooperative.mjs +6 -3
  104. package/lib/runtime/evaluate.mjs +10 -7
  105. package/lib/runtime/handoff-record.mjs +58 -0
  106. package/lib/runtime/host-service.mjs +155 -0
  107. package/lib/runtime/identity.mjs +10 -7
  108. package/lib/runtime/operations.mjs +41 -3
  109. package/lib/runtime/role-bridge-args.mjs +115 -13
  110. package/lib/runtime/role-bridge.mjs +57 -22
  111. package/lib/runtime/role-dispatch-policy.mjs +15 -5
  112. package/lib/runtime/role-dispatch-store.mjs +9 -2
  113. package/lib/runtime/role-observe.mjs +12 -7
  114. package/lib/runtime/role-routing-config.mjs +20 -6
  115. package/lib/runtime/role-routing.mjs +17 -4
  116. package/lib/runtime/role-supervisor.mjs +248 -9
  117. package/lib/runtime/schema.mjs +8 -5
  118. package/lib/runtime/scope.mjs +1 -1
  119. package/lib/runtime/store.mjs +2 -2
  120. package/lib/runtime/tool-access.mjs +560 -0
  121. package/lib/runtime/verification.mjs +15 -7
  122. package/lib/tui/setup.mjs +1 -1
  123. package/lib/watch/labels.mjs +2 -1
  124. package/lib/watch/model.mjs +2 -2
  125. package/lib/watch/render.mjs +2 -2
  126. package/lib/watch/watcher.mjs +46 -25
  127. package/package.json +1 -1
  128. package/shared/skill/runtime/acceptance.mjs +4 -3
  129. package/shared/skill/runtime/bootstrap.mjs +4 -2
  130. package/shared/skill/runtime/command.mjs +29 -3
  131. package/shared/skill/runtime/cooperative-schema.mjs +16 -5
  132. package/shared/skill/runtime/cooperative.mjs +6 -3
  133. package/shared/skill/runtime/evaluate.mjs +10 -7
  134. package/shared/skill/runtime/handoff-record.mjs +58 -0
  135. package/shared/skill/runtime/host-service.mjs +155 -0
  136. package/shared/skill/runtime/identity.mjs +10 -7
  137. package/shared/skill/runtime/operations.mjs +41 -3
  138. package/shared/skill/runtime/role-bridge-args.mjs +115 -13
  139. package/shared/skill/runtime/role-bridge.mjs +57 -22
  140. package/shared/skill/runtime/role-dispatch-policy.mjs +15 -5
  141. package/shared/skill/runtime/role-dispatch-store.mjs +9 -2
  142. package/shared/skill/runtime/role-observe.mjs +12 -7
  143. package/shared/skill/runtime/role-policy.json +28 -28
  144. package/shared/skill/runtime/role-routing-config.mjs +20 -6
  145. package/shared/skill/runtime/role-routing.mjs +17 -4
  146. package/shared/skill/runtime/role-supervisor.mjs +248 -9
  147. package/shared/skill/runtime/schema.mjs +8 -5
  148. package/shared/skill/runtime/scope.mjs +1 -1
  149. package/shared/skill/runtime/store.mjs +2 -2
  150. package/shared/skill/runtime/tool-access.mjs +560 -0
  151. package/shared/skill/runtime/verification.mjs +15 -7
@@ -1,6 +1,8 @@
1
1
  import {runtimeRegistryOf} from './platform-registry.mjs';
2
2
 
3
- export const ROUTING_ROLES = Object.freeze(['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer']);
3
+ export const ROUTING_ROLES = Object.freeze(['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_tester', 'arc_reviewer']);
4
+ export const LEGACY_ROUTING_ROLES = Object.freeze({arc_qa: 'arc_tester'});
5
+ export const ROUTING_CONFIG_VERSION = 3;
4
6
  const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value);
5
7
  const exact = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
6
8
  const v1Platforms = Object.freeze(['codex', 'claude']);
@@ -8,22 +10,34 @@ const isV1Platforms = platforms => platforms.length === v1Platforms.length && v1
8
10
  // Keep injected validation context out of the public config and serialized bytes.
9
11
  const configRegistries = new WeakMap();
10
12
 
13
+ export function displayRoutingRole(role) {
14
+ if (ROUTING_ROLES.includes(role)) return role;
15
+ if (typeof role === 'string' && /^arc[_-](?:routing[_-])?qa$/.test(role)) return LEGACY_ROUTING_ROLES.arc_qa;
16
+ return null;
17
+ }
18
+
11
19
  export function validRoleValues(platform, model, effort, {runtimePlatforms} = {}) {
12
20
  const registry = runtimeRegistryOf({runtimePlatforms});
13
21
  return registry.isPlatformId(platform) && registry.getPlatform(platform).routing.validatePair(model, effort);
14
22
  }
15
23
  export function validateRoleRoutingConfig(config, opts = {}) {
16
24
  const keys = ['version', 'revision', 'platforms', 'roles'];
17
- if (!(exact(config, keys) || (config?.version === 1 && exact(config, ['version', 'revision', 'roles']))) || ![1, 2].includes(config.version) || !validText(config.revision) || !exact(config.roles, ROUTING_ROLES)) throw Error('Invalid role routing configuration');
25
+ if (!(exact(config, keys) || (config?.version === 1 && exact(config, ['version', 'revision', 'roles']))) || ![1, 2, ROUTING_CONFIG_VERSION].includes(config.version) || !validText(config.revision)) throw Error('Invalid role routing configuration');
26
+ let roles = config.roles;
27
+ if (roles && typeof roles === 'object' && !Array.isArray(roles) && Object.hasOwn(roles, 'arc_qa')) {
28
+ if (config.version === ROUTING_CONFIG_VERSION || Object.hasOwn(roles, 'arc_tester')) throw Error('Invalid role routing configuration');
29
+ roles = Object.fromEntries(Object.entries(roles).map(([role, fields]) => [Object.hasOwn(LEGACY_ROUTING_ROLES, role) ? LEGACY_ROUTING_ROLES[role] : role, fields]));
30
+ }
31
+ if (!exact(roles, ROUTING_ROLES)) throw Error('Invalid role routing configuration');
18
32
  const registry = runtimeRegistryOf(opts);
19
33
  const platforms = config.version === 1 && !Object.hasOwn(config, 'platforms') ? [...v1Platforms] : config.platforms;
20
34
  if (!Array.isArray(platforms) || platforms.length < 2 || new Set(platforms).size !== platforms.length || platforms.some(id => !registry.isPlatformId(id))) throw Error('Invalid role routing platforms');
21
35
  if (platforms.some((id, index) => index > 0 && registry.getPlatform(platforms[index - 1]).anchorOrder >= registry.getPlatform(id).anchorOrder) || (config.version === 1 && !isV1Platforms(platforms))) throw Error('Invalid role routing platforms');
22
36
  for (const role of ROUTING_ROLES) {
23
- const fields = config.roles[role];
37
+ const fields = roles[role];
24
38
  if (!exact(fields, ['platform', 'model', 'effort']) || !validRoleValues(fields.platform, fields.model, fields.effort, opts) || !platforms.includes(fields.platform)) throw Error(`Invalid role routing values for ${role}`);
25
39
  }
26
- const result = structuredClone({version: config.version, revision: config.revision, platforms, roles: config.roles});
40
+ const result = structuredClone({version: config.version, revision: config.revision, platforms, roles});
27
41
  configRegistries.set(result, registry);
28
42
  return result;
29
43
  }
@@ -33,7 +47,7 @@ export function parseRoleRoutingConfig(text, opts) {
33
47
  }
34
48
  export function serializeRoleRoutingConfig(config) {
35
49
  const {revision, platforms, roles} = validateRoleRoutingConfig(config, {runtimePlatforms: configRegistries.get(config)});
36
- const value = {version: 2, revision, platforms, roles};
50
+ const value = {version: ROUTING_CONFIG_VERSION, revision, platforms, roles};
37
51
  return JSON.stringify(value, null, 2) + '\n';
38
52
  }
39
53
  export function buildRoleRoutingConfig({revision, platforms = [], roles}, opts = {}) {
@@ -42,5 +56,5 @@ export function buildRoleRoutingConfig({revision, platforms = [], roles}, opts =
42
56
  const participating = [...new Set([...platforms, ...Object.values(roles).map(fields => fields.platform)])];
43
57
  if (participating.some(id => !registry.isPlatformId(id))) throw Error('Invalid role routing platforms');
44
58
  participating.sort((a, b) => registry.getPlatform(a).anchorOrder - registry.getPlatform(b).anchorOrder);
45
- return validateRoleRoutingConfig({version: 2, revision, platforms: participating, roles}, opts);
59
+ return validateRoleRoutingConfig({version: ROUTING_CONFIG_VERSION, revision, platforms: participating, roles}, opts);
46
60
  }
@@ -6,10 +6,11 @@ import crypto from 'node:crypto';
6
6
  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
- import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
9
+ import {LEGACY_ROUTING_ROLES, ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
10
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
  import {allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
13
+ import {effectiveGrants, toolAccessPreflight, toolAccessReasons, validateToolAccess} from './tool-access.mjs';
13
14
 
14
15
  const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
15
16
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
@@ -169,10 +170,11 @@ const environmentOf=(context,host)=>runtimeRegistryOf(context).getPlatform(host)
169
170
  function validateAssignment(assignment,expectedRevision,context){
170
171
  const role=assignment?.role;
171
172
  if(!ROUTING_ROLES.includes(role)||!textValue(assignment.requestId)||!textValue(assignment.taskId)||!textValue(expectedRevision)||!textValue(context?.workflowId))return false;
173
+ if(assignment.toolAccess!==undefined&&validateToolAccess(role,assignment.toolAccess)===null)return false;
172
174
  const paths=assignment.allowedPaths;
173
175
  if(role==='arc_implementer')return Array.isArray(paths)&&paths.length>0&&paths.every(validRelativePath);
174
176
  if(paths===undefined)return true;
175
- return role==='arc_qa'&&Array.isArray(paths)&&paths.every(validRelativePath);
177
+ return role==='arc_tester'&&Array.isArray(paths)&&paths.every(validRelativePath);
176
178
  }
177
179
  const blankResult=(host,environment,role)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',dispatchId:null,route:null,profileName:null,executionEnvironment:environment,hostPlatform:host,role,requested:null,authentication:null,cliVersion:null,claims:null,reasons:[]});
178
180
  const classify=error=>{
@@ -230,6 +232,7 @@ export async function routingStatus({context,now=Date.now(),policy=DEFAULT_POLIC
230
232
  export async function prepareRoleDispatch({context,assignment,expectedRevision,now=Date.now(),policy=DEFAULT_POLICY}={}){
231
233
  const host=hostOf(context),environment=environmentOf(context,host),role=ROUTING_ROLES.includes(assignment?.role)?assignment.role:null;
232
234
  const result=blankResult(host,environment,role);
235
+ if(typeof assignment?.role==='string'&&Object.hasOwn(LEGACY_ROUTING_ROLES,assignment.role)){result.decision='deny';result.reasons=[reason('legacy_role_arc_qa')];return result;}
233
236
  if(!host||!environment||!validateAssignment(assignment,expectedRevision,context)){result.decision='deny';result.reasons=[reason('invalid_request')];return result;}
234
237
  const codes=new Set();let duplicate=false,anchorHome;
235
238
  const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
@@ -241,7 +244,17 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
241
244
  const requested=config.roles[role],route=requested.platform===host?'native':'bridge';
242
245
  result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role,{runtimePlatforms});
243
246
  if(route==='bridge'&&allowedPathsCoverControl(assignment.allowedPaths??[])){result.reasons=[reason('permission_scope_unverified')];return;}
244
- if(route==='bridge'&&requested.platform==='claude'&&(role==='arc_implementer'||role==='arc_qa')){
247
+ const toolAccess=assignment.toolAccess===undefined?undefined:validateToolAccess(role,assignment.toolAccess);
248
+ if(toolAccess!==undefined){
249
+ const platform=requested.platform;
250
+ const {reasons,conditions}=toolAccessReasons({platform,role,route,toolAccess,policy});
251
+ if(reasons.length){result.reasons=reasons.map(reason);return;}
252
+ const grants=effectiveGrants(platform,role,toolAccess);
253
+ const preflightReasons=await toolAccessPreflight({platform,role,grants,worktree:context.cwd,userHome:context.userHome,homes,env:context.env,io:fs});
254
+ if(preflightReasons.length){result.reasons=preflightReasons.map(reason);return;}
255
+ result.toolAccess={conditions};
256
+ }
257
+ if(route==='bridge'&&requested.platform==='claude'&&(role==='arc_implementer'||role==='arc_tester')){
245
258
  const target=typeof context.cwd==='string'?await resolveWorktree(context.cwd).catch(()=>null):null;
246
259
  if(!target||await claudeProjectSettingsWidenScope(target.realpath)){result.reasons=[reason('permission_scope_unverified')];return;}
247
260
  }
@@ -277,7 +290,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
277
290
  result.reasons=[...codes].map(reason);
278
291
  if(codes.size){result.decision=duplicate?'deny':'hold';return;}
279
292
  const claims=initialClaims(route,policy,requested),iso=new Date(now).toISOString(),dispatchId=crypto.randomUUID();
280
- const lease=await createLease(anchorHome,{version:2,targetPlatform:route==='native'?host:requested.platform,dispatchId,workflowId:context.workflowId,taskId:assignment.taskId,requestId:assignment.requestId,role,route,hostPlatform:host,executionEnvironment:environment,revision:config.revision,profileHash:await readProfileHash(homes[requested.platform],role),argsDigest:null,state:'reserved',supervisor:null,child:null,sessionId:route==='bridge'&&(requested.platform==='gemini'||requested.platform==='grok')?crypto.randomUUID():null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso},{runtimePlatforms,config});
293
+ const lease=await createLease(anchorHome,{version:toolAccess===undefined?2:3,targetPlatform:route==='native'?host:requested.platform,dispatchId,workflowId:context.workflowId,taskId:assignment.taskId,requestId:assignment.requestId,role,route,hostPlatform:host,executionEnvironment:environment,revision:config.revision,profileHash:await readProfileHash(homes[requested.platform],role),argsDigest:null,state:'reserved',supervisor:null,child:null,sessionId:route==='bridge'&&(requested.platform==='gemini'||requested.platform==='grok')?crypto.randomUUID():null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso,...(toolAccess===undefined?{}:{toolAccess})},{runtimePlatforms,config});
281
294
  Object.assign(result,{decision:'allow',routeStatus:'reserved',dispatchId:lease.dispatchId,claims});
282
295
  },{retryMs:policy.lockRetryMs});
283
296
  }catch(error){
@@ -10,13 +10,15 @@ import {promisify} from 'node:util';
10
10
  import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
11
11
  import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
12
12
  import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
13
- import {DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
14
- import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
13
+ import {CODEX_PROFILE_SANDBOX_TYPE, DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
14
+ import {readLease, writeLease, writeHeartbeat, cancelRequested, dispatchDirectory, TERMINAL_STATES} from './role-dispatch-store.mjs';
15
15
  import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
16
16
  import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
17
17
  import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
18
18
  import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, observeHeadAdvance, detectViolations, toleratedRecord, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
19
19
  import {getPlatform, routingProfileFile} from './platform-registry.mjs';
20
+ import {buildToolContext, collectEvidence, createScratch, hasRetainedCleanup, removeScratch, toolAccessPreflight, toolAccessReasons, TOOL_ACCESS_ADAPTERS} from './tool-access.mjs';
21
+ import {hostDirFor, startHostService, writeServicesFile} from './host-service.mjs';
20
22
 
21
23
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
22
24
  const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
@@ -267,6 +269,150 @@ export async function reapRecordedDescendants(artifactDir, lease, options) {
267
269
  finally { await file?.close().catch(() => {}); }
268
270
  }
269
271
 
272
+ const HOST_SERVICES_FILE = 'host-services.json';
273
+ const HOST_SERVICES_MAX_BYTES = 16384;
274
+ const dirIdentity = ({dev, ino}) => ({dev, ino});
275
+ const hasKeys = (value, keys) => value && typeof value === 'object' && !Array.isArray(value)
276
+ && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
277
+ const validDirIdentity = value => hasKeys(value, ['dev', 'ino']) && Number.isSafeInteger(value.dev)
278
+ && Number.isSafeInteger(value.ino) && value.ino > 0;
279
+
280
+ function writeHostServicesSnapshot(artifactDir, snapshot) {
281
+ const filename = path.join(artifactDir, HOST_SERVICES_FILE);
282
+ const temporary = `${filename}.${crypto.randomUUID()}.tmp`;
283
+ try {
284
+ fs.writeFileSync(temporary, JSON.stringify(snapshot) + '\n', {mode: 0o600, flag: 'wx'});
285
+ fs.renameSync(temporary, filename);
286
+ } finally {
287
+ try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
288
+ }
289
+ }
290
+
291
+ function hostServiceGroupStatus(pgid) {
292
+ try { process.kill(-pgid, 0); return 'present'; }
293
+ catch (error) {
294
+ if (error.code === 'ESRCH') return 'gone';
295
+ if (error.code === 'EPERM') return 'denied';
296
+ throw error;
297
+ }
298
+ }
299
+
300
+ async function waitForHostServiceGroupExit(pgid) {
301
+ const deadline = performance.now() + 500;
302
+ while (hostServiceGroupStatus(pgid) !== 'gone') {
303
+ const remaining = deadline - performance.now();
304
+ if (remaining <= 0) return false;
305
+ await sleep(Math.min(25, remaining));
306
+ }
307
+ return true;
308
+ }
309
+
310
+ async function recoveryProcessTable(supervisor) {
311
+ const table = await sampleProcessTable();
312
+ const rows = new Map(table?.map(row => [row.pid, row]));
313
+ if (!rows.has(process.pid)) throw Error('Process table unavailable');
314
+ if (supervisor && sameStart(rows.get(supervisor.pid), supervisor)) throw Error('Supervisor still present');
315
+ return rows;
316
+ }
317
+
318
+ async function reapHostServiceGroup(entry, graceMs, supervisor) {
319
+ const {pid, pgid, startTime} = entry;
320
+ const groupMembers = table => [...table.values()].filter(row => row.pgid === pgid);
321
+ const safeMembers = table => {
322
+ const lineage = supervisorLineage(table, process.pid);
323
+ const members = groupMembers(table);
324
+ if (members.some(row => row.uid !== process.geteuid() || lineage.has(row.pid))) throw Error('Unverified service group');
325
+ return members;
326
+ };
327
+ const signal = name => {
328
+ try { process.kill(-pgid, name); }
329
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
330
+ };
331
+ const before = await recoveryProcessTable(supervisor);
332
+ const leader = before.get(pid);
333
+ if (!leader) {
334
+ const status = hostServiceGroupStatus(pgid);
335
+ if (status !== 'denied') return status === 'gone';
336
+ const fresh = await recoveryProcessTable(supervisor);
337
+ return groupMembers(fresh).length === 0 && await waitForHostServiceGroupExit(pgid);
338
+ }
339
+ if (leader.pgid !== pgid || leader.startTime !== startTime) return false;
340
+ const members = safeMembers(before);
341
+ signal('SIGTERM');
342
+ if (graceMs > 0) await sleep(graceMs);
343
+ const status = hostServiceGroupStatus(pgid);
344
+ if (status === 'gone') return true;
345
+
346
+ // A leader can exit on TERM while its descendants keep the group alive.
347
+ const after = await recoveryProcessTable(supervisor);
348
+ const currentLeader = after.get(pid);
349
+ if (currentLeader && (currentLeader.pgid !== pgid || currentLeader.startTime !== startTime)) return false;
350
+ const remaining = safeMembers(after);
351
+ // macOS can report a zombie-only group as EPERM until it is reaped.
352
+ if (status === 'denied') return remaining.length === 0 && await waitForHostServiceGroupExit(pgid);
353
+ if (!members.some(member => after.get(member.pid)?.pgid === pgid && sameStart(after.get(member.pid), member))) {
354
+ return remaining.length === 0 && await waitForHostServiceGroupExit(pgid);
355
+ }
356
+ signal('SIGKILL');
357
+ return await waitForHostServiceGroupExit(pgid);
358
+ }
359
+
360
+ const quarantineOptions = (artifactDir, anchorHome, lease) => ({
361
+ artifactDir, fallbackDir: dispatchDirectory(anchorHome), quarantineKey: `${lease.dispatchId}-${lease.segment ?? 0}`,
362
+ });
363
+
364
+ export async function reapRecordedHostServices(artifactDir, lease, {anchorHome, graceMs = DEFAULT_POLICY.cancelGraceMs} = {}) {
365
+ let file;
366
+ try {
367
+ const requested = lease.toolAccess.services;
368
+ const adapter = TOOL_ACCESS_ADAPTERS[lease.targetPlatform];
369
+ const uid = process.geteuid(), id8 = lease.dispatchId.replaceAll('-', '').slice(0, 8);
370
+ const scratch = adapter?.scratchRoot?.({id8, uid});
371
+ if (!scratch) return 'warning';
372
+ const hostDir = hostDirFor(lease.dispatchId);
373
+ file = await fsp.open(path.join(artifactDir, HOST_SERVICES_FILE), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
374
+ const stat = await file.stat();
375
+ if (!stat.isFile() || stat.uid !== uid || stat.size > HOST_SERVICES_MAX_BYTES) return 'warning';
376
+ const bytes = Buffer.alloc(HOST_SERVICES_MAX_BYTES + 1);
377
+ const {bytesRead} = await file.read(bytes, 0, bytes.length, 0);
378
+ if (bytesRead !== stat.size) return 'warning';
379
+ const snapshot = JSON.parse(bytes.toString('utf8', 0, bytesRead));
380
+ if (!hasKeys(snapshot, ['version', 'dispatchId', 'segment', 'hostDir', 'scratch', 'services', 'pending'])
381
+ || snapshot.version !== 1 || snapshot.dispatchId !== lease.dispatchId || snapshot.segment !== (lease.segment ?? 0)
382
+ || !validDirIdentity(snapshot.hostDir) || !validDirIdentity(snapshot.scratch)
383
+ || (snapshot.pending !== null && !requested.includes(snapshot.pending))
384
+ || !Array.isArray(snapshot.services) || snapshot.services.length > requested.length
385
+ || (!snapshot.services.length && snapshot.pending === null)) return 'warning';
386
+ const ids = new Set(), pids = new Set();
387
+ for (const entry of snapshot.services) {
388
+ if (!hasKeys(entry, ['id', 'pid', 'pgid', 'startTime']) || !requested.includes(entry.id) || ids.has(entry.id) || entry.id === snapshot.pending
389
+ || !validPid(entry.pid) || entry.pid <= 1 || entry.pgid !== entry.pid || pids.has(entry.pid)
390
+ || typeof entry.startTime !== 'string' || !DESCENDANT_START.test(entry.startTime)) return 'warning';
391
+ ids.add(entry.id);
392
+ pids.add(entry.pid);
393
+ }
394
+ for (const entry of snapshot.services.reverse()) {
395
+ if (!await reapHostServiceGroup(entry, graceMs, lease.supervisor)) return 'warning';
396
+ }
397
+ if (snapshot.pending !== null || snapshot.services.length !== requested.length) return 'warning';
398
+ if (lease.child && hostServiceGroupStatus(lease.child.pid) !== 'gone') return 'warning';
399
+ const parent = adapter.scratchParent?.({uid});
400
+ if (parent) {
401
+ const parentStat = await fsp.lstat(parent);
402
+ if (!parentStat.isDirectory() || parentStat.uid !== uid) return 'warning';
403
+ }
404
+ const cleanup = {...quarantineOptions(artifactDir, anchorHome, lease), missingOk: true};
405
+ if (await hasRetainedCleanup(scratch, cleanup) || await hasRetainedCleanup(hostDir, cleanup)) return 'warning';
406
+ await collectEvidence({scratch, artifactDir, identity: snapshot.scratch, recovery: true});
407
+ await recoveryProcessTable(lease.supervisor);
408
+ if (lease.child && hostServiceGroupStatus(lease.child.pid) !== 'gone') return 'warning';
409
+ const scratchRemoved = await removeScratch(scratch, {...cleanup, identity: snapshot.scratch});
410
+ const hostRemoved = await removeScratch(hostDir, {...cleanup, identity: snapshot.hostDir});
411
+ return hostRemoved && scratchRemoved ? 'ok' : 'warning';
412
+ } catch { return 'warning'; }
413
+ finally { await file?.close().catch(() => {}); }
414
+ }
415
+
270
416
  export {resolveWorktree};
271
417
  export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
272
418
  /** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
@@ -278,9 +424,9 @@ export const geminiPolicyFile = (homes, role) => path.join(homes.gemini ?? '', '
278
424
  export const grokPromptFile = resultPath => path.join(path.dirname(resultPath), 'prompt.md');
279
425
 
280
426
  /** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
281
- export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS}) {
427
+ export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, userHome, env = process.env, target = {}, runtimePlatforms, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS, observeToolContext}) {
282
428
  const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
283
- const requested = config.roles[lease.role], platform = lease.version === 2 ? lease.targetPlatform : requested.platform;
429
+ const requested = config.roles[lease.role], platform = lease.version >= 2 ? lease.targetPlatform : requested.platform;
284
430
  if (platform !== requested.platform) throw fail('activation_unverified', 'Lease target differs from the active role target');
285
431
  const implementation = supervisorImplementations.get(platform);
286
432
  if (platform === 'gemini' || platform === 'grok' || lease.hostPlatform === 'gemini' || lease.hostPlatform === 'grok') {
@@ -306,16 +452,32 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
306
452
  let bytes;
307
453
  try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
308
454
  if (sha256(bytes) !== lease.profileHash) throw fail('activation_unverified', 'Profile hash differs from the reserved lease');
455
+ const {reasons} = toolAccessReasons({platform, role: lease.role, route: lease.route, toolAccess: lease.toolAccess, policy});
456
+ if (reasons.length) throw fail(reasons[0], 'Tool access is not available for this dispatch');
457
+ const cli = resolveLocalCli(platform, {cwd: worktree, userHome, env, runtimePlatforms});
458
+ if (lease.toolAccess !== undefined && cli.reason) throw fail('permission_scope_unverified', 'Tool access requires a local CLI');
459
+ const cliEnv = cli.reason ? env : localCliEnvironment(cli);
460
+ const toolContext = buildToolContext({
461
+ platform, role: lease.role, dispatchId: lease.dispatchId, toolAccess: lease.toolAccess, uid: process.getuid(),
462
+ userHome, homes, env: cliEnv, envNames: Object.keys(cliEnv), worktree, gitDir: target.gitDir, gitCommonDir: target.gitCommonDir, policy,
463
+ });
464
+ if (toolContext) {
465
+ const preflightReasons = await toolAccessPreflight({platform, role: lease.role, grants: toolContext.grants, worktree, userHome, homes, env: cliEnv, io: fsp});
466
+ if (preflightReasons.length) throw fail(preflightReasons[0], 'Tool access preflight failed');
467
+ }
309
468
  let profile, args;
310
469
  try {
311
470
  profile = parseCompositeProfile(platform, bytes);
312
- 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});
471
+ 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, toolContext});
313
472
  } catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
314
473
  const expected = platform === 'claude'
315
474
  ? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
316
475
  : platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
317
- : {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
318
- 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} : {})};
476
+ : {model: requested.model, effort: requested.effort,
477
+ sandboxMode: toolContext?.grants.mechanisms.includes('codexProfile') ? CODEX_PROFILE_SANDBOX_TYPE : permissions.sandboxMode,
478
+ approvalPolicy: 'never'};
479
+ observeToolContext?.(structuredClone(toolContext));
480
+ return {platform, args, argsDigest: argsDigest(args), expected, requested, toolContext, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {}), ...(grokSandbox ? {grokSandbox} : {})};
319
481
  }
320
482
 
321
483
  /** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
@@ -338,6 +500,9 @@ export async function runSupervisor(options) {
338
500
  const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
339
501
  const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
340
502
  const startedAt = new Date().toISOString();
503
+ const scratchIo = {create: createScratch, collect: collectEvidence, remove: removeScratch, ...options.scratchIo};
504
+ const hostServiceIo = options.hostServiceIo;
505
+ const startService = hostServiceIo?.start ?? startHostService;
341
506
 
342
507
  // Lease writes retry a busy lock; the supervisor never gives up a terminal write because of a short contention.
343
508
  const locked = async fn => {
@@ -366,6 +531,7 @@ export async function runSupervisor(options) {
366
531
  return true;
367
532
  });
368
533
  if (!guarded) return; // not the supervisor registered for this dispatch
534
+ const quarantine = quarantineOptions(artifactDir, codexHome, lease);
369
535
 
370
536
  const timers = new Set();
371
537
  let hbBusy = false;
@@ -373,9 +539,40 @@ export async function runSupervisor(options) {
373
539
  await beat();
374
540
  timers.add(setInterval(beat, heartbeatMs));
375
541
 
542
+ let createdScratch, scratchIdentity, createdHostDir, hostDirIdentity, toolAccessResult;
543
+ let hostServiceRecoveryWarning = false;
544
+ const hostServices = [];
545
+ const recordHostServiceRecovery = record => {
546
+ if (hostServiceRecoveryWarning) return;
547
+ try { record(); } catch { hostServiceRecoveryWarning = true; }
548
+ };
549
+ const finishToolAccess = async () => {
550
+ if (!createdScratch) return {};
551
+ return toolAccessResult ??= (async () => {
552
+ const {scratch, conditions} = createdScratch;
553
+ for (const service of [...hostServices].reverse()) {
554
+ if (!service.started) continue;
555
+ try { service.cleanup = await service.stop(); } catch { service.cleanup = 'warning'; }
556
+ }
557
+ let evidence = {copied: 0, skipped: [], truncated: false}, collected = false, removed = false;
558
+ try { evidence = await scratchIo.collect({scratch, artifactDir, identity: scratchIdentity}); collected = true; } catch { /* preserve terminal result */ }
559
+ try { removed = await scratchIo.remove(scratch, {...quarantine, identity: scratchIdentity}); } catch { /* reported below */ }
560
+ if (createdHostDir) {
561
+ if (!await removeScratch(createdHostDir, {...quarantine, identity: hostDirIdentity})) {
562
+ for (const service of hostServices) service.cleanup = 'warning';
563
+ }
564
+ }
565
+ const servicesRecord = createdScratch.hostDir ? {
566
+ hostServices: hostServices.map(({id, started, endpoint, cleanup}) => ({id, started, endpoint, cleanup})),
567
+ ...(hostServiceRecoveryWarning ? {hostServiceRecovery: 'warning'} : {}),
568
+ } : {};
569
+ return {toolAccess: {conditions, scratch: {path: scratch, removed: collected && removed}, evidence, ...servicesRecord}};
570
+ })();
571
+ };
376
572
  const writeRecord = async body => {
573
+ const toolAccessRecord = await finishToolAccess();
377
574
  const file = path.join(artifactDir, 'record.json');
378
- await fsp.writeFile(file, JSON.stringify({version: 1, dispatchId, role: lease.role, startedAt, endedAt: new Date().toISOString(), ...body}, null, 2) + '\n', {mode: 0o600});
575
+ await fsp.writeFile(file, JSON.stringify({version: 1, dispatchId, role: lease.role, startedAt, endedAt: new Date().toISOString(), ...body, ...toolAccessRecord}, null, 2) + '\n', {mode: 0o600});
379
576
  await fsp.chmod(file, 0o600);
380
577
  };
381
578
  const commit = async (state, codes, claims, extra = {}) => {
@@ -475,7 +672,7 @@ export async function runSupervisor(options) {
475
672
  const implementation = (options.supervisorImplementations ?? SUPERVISOR_IMPLEMENTATIONS).get(platform);
476
673
  if (!implementation) throw Error('Invalid composite profile: unknown platform');
477
674
  let invocation;
478
- 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'); }
675
+ try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, userHome, env, target, runtimePlatforms, policy, supervisorImplementations: options.supervisorImplementations, observeToolContext: options.observeToolContext}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
479
676
  if (invocation.argsDigest !== lease.argsDigest) return await earlyFailure('activation_unverified');
480
677
  const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
481
678
  const cli = resolveLocalCli(platform, context);
@@ -495,6 +692,48 @@ export async function runSupervisor(options) {
495
692
  const {path, sha256, dirCreated} = createdGrokProfile;
496
693
  grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
497
694
  }
695
+ if (invocation.toolContext) {
696
+ const {scratch, parent, hostDir, grants} = invocation.toolContext;
697
+ try { scratchIdentity = await scratchIo.create({scratch, parent, uid: process.getuid(), ...quarantine}); }
698
+ catch (error) { return await earlyFailure(error.reasonCode ?? 'execution_failed'); }
699
+ createdScratch = invocation.toolContext;
700
+ if (hostDir) {
701
+ try {
702
+ await fsp.mkdir(hostDir, {mode: 0o700});
703
+ const stat = fs.lstatSync(hostDir);
704
+ if (!stat.isDirectory() || stat.uid !== process.geteuid()) throw Error('Host directory changed during creation');
705
+ hostDirIdentity = dirIdentity(stat);
706
+ createdHostDir = hostDir;
707
+ const recovery = {version: 1, dispatchId, segment: lease.segment ?? 0,
708
+ hostDir: hostDirIdentity, scratch: scratchIdentity, services: [], pending: null};
709
+ for (const id of grants.services) {
710
+ try {
711
+ // A crash during spawn leaves an explicit unverified entry until the identity is published.
712
+ recordHostServiceRecovery(() => {
713
+ recovery.pending = id;
714
+ writeHostServicesSnapshot(artifactDir, recovery);
715
+ });
716
+ hostServices.push(await startService({
717
+ id, dispatchId, scratch, userHome, timeoutMs: policy.probeTimeoutMs, io: hostServiceIo,
718
+ onSpawn(pid) {
719
+ recordHostServiceRecovery(() => {
720
+ const startTime = processStartTime(pid);
721
+ if (typeof startTime !== 'string' || !DESCENDANT_START.test(startTime)) throw Error('Host service start time unavailable');
722
+ recovery.services.push({id, pid, pgid: pid, startTime});
723
+ recovery.pending = null;
724
+ writeHostServicesSnapshot(artifactDir, recovery);
725
+ });
726
+ },
727
+ }));
728
+ } catch (error) {
729
+ hostServices.push({id, started: false, endpoint: null, cleanup: error.cleanup ?? 'ok'});
730
+ throw error;
731
+ }
732
+ }
733
+ await writeServicesFile(scratch, hostServices);
734
+ } catch { return await earlyFailure('execution_failed'); }
735
+ }
736
+ }
498
737
  const extra = invocation.grokSandbox ? [
499
738
  {label: 'grok-home:config.toml', path: path.join(homes.grok, 'config.toml'), project: grokConfigSecurityProjection},
500
739
  {label: 'grok-home:sandbox.toml', path: path.join(homes.grok, 'sandbox.toml')},
@@ -26,7 +26,7 @@ import {isPlatformId} from './platform-registry.mjs';
26
26
  * @property {Array<object>} [facts] Provider-confirmed facts tied to state and source references.
27
27
  */
28
28
  import path from 'node:path';
29
- import {ROLES, OPERATIONS} from './operations.mjs';
29
+ import {ROLES, OPERATIONS, canonicalCooperativeRole, hasNewStoredOperationAliases, normalizeStoredOperations} from './operations.mjs';
30
30
  const fail = message => {throw new Error(`Runtime schema: ${message}`);};
31
31
  export const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
32
32
  export const text = value => typeof value === 'string' && value.length > 0;
@@ -36,7 +36,7 @@ const absolute = value => text(value) && path.isAbsolute(value) && path.normaliz
36
36
  const unique = (items,key) => items.every(x=>object(x)&&text(x[key])) && new Set(items.map(x=>x[key])).size===items.length;
37
37
  function approval(a){return object(a)&&text(a.id)&&['user-message','human-confirmation'].includes(a.source)&&text(a.messageRef)&&hash(a.contentHash)&&object(a.scope)&&text(a.scope.taskId)&&absolute(a.scope.target)&&strings(a.scope.operations)&&a.scope.operations.every(op=>OPERATIONS.includes(op))&&strings(a.scope.paths)&&a.scope.paths.every(absolute);}
38
38
  /** Validate stored workflow data. Observed provenance must still be checked by evaluate. */
39
- export function validateWorkflowState(s){
39
+ export function validateWorkflowState(s,{allowLegacyOperations=true,preserveStoredOperations=false,legacyOperationsFrom}={}){
40
40
  if(object(s)&&s.workflowKind!==undefined)fail('provider state cannot use cooperative contract');
41
41
  if(!object(s)||s.schemaVersion!==1||!text(s.workflowId)||!Number.isSafeInteger(s.revision)||s.revision<0)fail('version or identity');
42
42
  if(!object(s.versions)||['policy','runtime','adapter','policyHash','runtimeHash','adapterHash'].some(k=>!text(s.versions[k])))fail('versions');
@@ -44,11 +44,14 @@ export function validateWorkflowState(s){
44
44
  if(!object(s.target)||!absolute(s.target.realpath)||['repository','worktree','baseHead','head'].some(k=>!text(s.target[k]))||!(s.target.branch===null||text(s.target.branch)))fail('target');
45
45
  if(!['plan','small-task','no-plan'].includes(s.mode))fail('mode');
46
46
  for(const k of ['documents','approvals','tasks','assignments','identities','leases','checks','findings','acceptances','commits','audit','capabilities','requests'])if(!Array.isArray(s[k]))fail(k);
47
+ const stored=s,normalized=normalizeStoredOperations(s);
48
+ if(!allowLegacyOperations&&normalized!==s&&(!legacyOperationsFrom||hasNewStoredOperationAliases(s,legacyOperationsFrom)))fail('legacy operation in new state');
49
+ s=normalized;
47
50
  if(!unique(s.tasks,'id')||s.tasks.some(t=>!['pending','assigned','rework','verification','accepted','committed'].includes(t.status)||!strings(t.paths)||t.paths.some(p=>!absolute(p))||!strings(t.dependencies)||!text(t.baseCommit)||!strings(t.criteria)||!strings(t.requiredChecks)))fail('tasks');
48
51
  if(!unique(s.approvals,'id')||s.approvals.some(a=>!approval(a)))fail('approval provenance');
49
- if(!unique(s.identities,'actorRef')||s.identities.some(i=>!ROLES.includes(i.role)||!text(i.taskId)||!text(i.observationRef)))fail('identity');
52
+ if(!unique(s.identities,'actorRef')||s.identities.some(i=>!ROLES.includes(canonicalCooperativeRole(i.role))||!text(i.taskId)||!text(i.observationRef)))fail('identity');
50
53
  if(!unique(s.leases,'actorRef')||s.leases.some(l=>!text(l.taskId)||!['active','suspended','retired'].includes(l.status)))fail('lease');
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');
54
+ 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(canonicalCooperativeRole(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');
52
55
  for(const a of s.assignments){
53
56
  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');
54
57
  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');
@@ -61,7 +64,7 @@ export function validateWorkflowState(s){
61
64
  if(s.commits.some(c=>!object(c)||!text(c.purpose)||!text(c.taskId)||!text(c.expectedParent)||!text(c.expectedTree)))fail('commits');
62
65
  if(s.requests.some(r=>!object(r)||!text(r.requestId)||!hash(r.requestFingerprint)||!object(r.decision))||new Set(s.requests.map(r=>r.requestId)).size!==s.requests.length)fail('request replay');
63
66
  if(s.plannerLedger!==undefined){validatePlannerLedger(s.plannerLedger);if(s.plannerLedger.stages.some(stage=>stage.workflowId!==s.workflowId))fail('Planner workflow binding');}
64
- return s;
67
+ return preserveStoredOperations?stored:s;
65
68
  }
66
69
  export function validateRequest(r){
67
70
  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');
@@ -11,7 +11,7 @@ export async function inspectPath(filename,{missing=false,directory=false}={}){
11
11
  for(let i=0;i<parts.length;i++){
12
12
  cursor=path.join(cursor,parts[i]);let stat;
13
13
  try{stat=await fs.lstat(cursor);}catch(error){if(missing&&error.code==='ENOENT')return;throw error;}
14
- if(stat.isSymbolicLink())throw Error('Unsafe symlink path');
14
+ if(stat.isSymbolicLink())throw Object.assign(Error('Unsafe symlink path'),{symlinkPath:cursor});
15
15
  if(i<parts.length-1||directory){if(!stat.isDirectory())throw Error('Unsafe directory type');}
16
16
  else if(!stat.isFile())throw Error('State must be a regular file');
17
17
  }
@@ -27,7 +27,7 @@ export async function transactWorkflow({statePath,expectedRevision,requestId,req
27
27
  try{
28
28
  lock=await fs.open(lockPath,'wx',0o600);
29
29
  const stat=await fs.lstat(statePath);if(!stat.isFile()||stat.isSymbolicLink())throw Error('State must be regular file');
30
- const state=validateWorkflowState(JSON.parse(await fs.readFile(statePath,'utf8')));
30
+ const state=validateWorkflowState(JSON.parse(await fs.readFile(statePath,'utf8')),{preserveStoredOperations:true});
31
31
  const prior=state.requests.find(r=>r.requestId===requestId);
32
32
  let decision;
33
33
  if(prior){
@@ -52,7 +52,7 @@ export async function transactWorkflow({statePath,expectedRevision,requestId,req
52
52
  for(const old of state.leases){const current=next.leases.find(l=>l.actorRef===old.actorRef);if(old.status==='retired'&&(!current||current.status!=='retired'||current.taskId!==old.taskId))throw Error('Retired lease revival forbidden');}
53
53
  next.revision=state.revision+1;next.requests=prior?state.requests.map(r=>r.requestId===requestId?{requestId,requestFingerprint,decision}:r):[...state.requests,{requestId,requestFingerprint,decision}];
54
54
  next.audit=[...state.audit,{requestId,revision:next.revision,decision:decision.decision,ruleIds:decision.ruleIds??[],result:'pending'}];
55
- validateWorkflowState(next);
55
+ validateWorkflowState(next,{allowLegacyOperations:false,legacyOperationsFrom:state});
56
56
  await saveDurableState({statePath,state:next});
57
57
  return {state:next,decision,replayed:false};
58
58
  }finally{