@yunhozz/arc 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/MANIFEST.sha256 +133 -94
  2. package/README.md +56 -21
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/commit.md +10 -8
  5. package/claude/skill/references/coordination.md +6 -4
  6. package/claude/skill/references/handoff-prep.md +12 -12
  7. package/claude/skill/references/handoff.md +2 -0
  8. package/claude/skill/references/planning.md +8 -8
  9. package/claude/skill/references/verification.md +6 -6
  10. package/codex/skill/SKILL.md +1 -1
  11. package/codex/skill/references/commit.md +10 -8
  12. package/codex/skill/references/coordination.md +6 -4
  13. package/codex/skill/references/handoff-prep.md +12 -12
  14. package/codex/skill/references/handoff.md +2 -0
  15. package/codex/skill/references/planning.md +8 -8
  16. package/codex/skill/references/verification.md +6 -6
  17. package/gemini/GEMINI.md +8 -0
  18. package/gemini/agents/arc-implementer.md +37 -0
  19. package/gemini/agents/arc-planner.md +47 -0
  20. package/gemini/agents/arc-qa.md +37 -0
  21. package/gemini/agents/arc-reviewer.md +39 -0
  22. package/gemini/agents/arc-scouter.md +38 -0
  23. package/gemini/instructions.md +4 -0
  24. package/gemini/skill/SKILL.md +78 -0
  25. package/gemini/skill/models.toml +23 -0
  26. package/gemini/skill/references/arc-visual-companion.md +28 -0
  27. package/gemini/skill/references/commit.md +55 -0
  28. package/gemini/skill/references/coordination.md +149 -0
  29. package/gemini/skill/references/git-recovery.md +34 -0
  30. package/gemini/skill/references/handoff-prep.md +110 -0
  31. package/gemini/skill/references/handoff.md +227 -0
  32. package/gemini/skill/references/limits.md +31 -0
  33. package/gemini/skill/references/planning.md +168 -0
  34. package/gemini/skill/references/verification.md +155 -0
  35. package/gemini/skill/references/worktree-creation.md +8 -0
  36. package/lib/color/palette.mjs +6 -0
  37. package/lib/installer/acquisition.mjs +7 -5
  38. package/lib/installer/install-mode.mjs +49 -26
  39. package/lib/installer/install.mjs +3 -2
  40. package/lib/installer/manifest.mjs +20 -14
  41. package/lib/installer/plan.mjs +24 -21
  42. package/lib/installer/preset.mjs +9 -8
  43. package/lib/installer/role-routing.mjs +129 -77
  44. package/lib/installer/runtime-assets.mjs +2 -0
  45. package/lib/installer/runtime-config.mjs +3 -0
  46. package/lib/installer/skill-sources.mjs +4 -3
  47. package/lib/installer/superpowers.mjs +2 -1
  48. package/lib/installer/target-errors.mjs +1 -0
  49. package/lib/installer/targets.mjs +14 -6
  50. package/lib/installer/uninstall.mjs +5 -4
  51. package/lib/installer/upgrade-state.mjs +14 -10
  52. package/lib/installer/upgrade.mjs +9 -5
  53. package/lib/management/operations.mjs +91 -47
  54. package/lib/management/status.mjs +10 -8
  55. package/lib/management/update.mjs +8 -7
  56. package/lib/models/catalog-gemini.mjs +48 -0
  57. package/lib/models/catalog.mjs +27 -12
  58. package/lib/models/config.mjs +23 -22
  59. package/lib/models/gemini-models.json +12 -0
  60. package/lib/models/profiles.mjs +7 -5
  61. package/lib/models/static-catalog.mjs +13 -14
  62. package/lib/npm/upgrade.mjs +2 -2
  63. package/lib/platforms/availability.mjs +98 -0
  64. package/lib/platforms/claude.mjs +14 -0
  65. package/lib/platforms/codex.mjs +16 -0
  66. package/lib/platforms/formats/gemini-markdown.mjs +48 -0
  67. package/lib/platforms/formats/markdown.mjs +39 -0
  68. package/lib/platforms/formats/toml.mjs +39 -0
  69. package/lib/platforms/gemini.mjs +14 -0
  70. package/lib/platforms/index.mjs +27 -0
  71. package/lib/policy/placement.mjs +4 -4
  72. package/lib/policy/render.mjs +13 -8
  73. package/lib/policy/role-policy.json +40 -21
  74. package/lib/prompts/agent-fragments.json +71 -1
  75. package/lib/prompts/render.mjs +32 -11
  76. package/lib/runtime/bootstrap.mjs +1 -1
  77. package/lib/runtime/cooperative-schema.mjs +0 -23
  78. package/lib/runtime/cooperative.mjs +13 -34
  79. package/lib/runtime/evaluate.mjs +3 -69
  80. package/lib/runtime/gemini-stream.mjs +32 -0
  81. package/lib/runtime/git-evidence.mjs +0 -98
  82. package/lib/runtime/identity.mjs +2 -1
  83. package/lib/runtime/local-cli.mjs +14 -24
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/platform-registry.mjs +130 -0
  86. package/lib/runtime/role-bridge-args.mjs +57 -2
  87. package/lib/runtime/role-bridge.mjs +86 -65
  88. package/lib/runtime/role-dispatch-policy.mjs +17 -7
  89. package/lib/runtime/role-dispatch-store.mjs +20 -14
  90. package/lib/runtime/role-observe.mjs +1 -0
  91. package/lib/runtime/role-routing-config.mjs +36 -9
  92. package/lib/runtime/role-routing.mjs +62 -29
  93. package/lib/runtime/role-supervisor.mjs +114 -49
  94. package/lib/runtime/schema.mjs +5 -4
  95. package/lib/tui/app.mjs +37 -32
  96. package/lib/tui/custom-preset.mjs +114 -68
  97. package/lib/tui/derive-install-plan.mjs +19 -0
  98. package/lib/tui/diagram.mjs +68 -0
  99. package/lib/tui/mode.mjs +77 -0
  100. package/lib/tui/render.mjs +47 -16
  101. package/lib/tui/setup.mjs +167 -100
  102. package/lib/tui/terminal.mjs +9 -6
  103. package/lib/watch/anchor-store.mjs +44 -0
  104. package/lib/watch/dispatch.mjs +3 -3
  105. package/lib/watch/index.mjs +37 -24
  106. package/lib/watch/model.mjs +1 -0
  107. package/lib/watch/normalize-claude.mjs +50 -10
  108. package/lib/watch/normalize-codex.mjs +79 -5
  109. package/lib/watch/render.mjs +30 -13
  110. package/lib/watch/scope.mjs +2 -1
  111. package/lib/watch/status-line.mjs +51 -0
  112. package/lib/watch/tail.mjs +27 -0
  113. package/lib/watch/watcher.mjs +193 -53
  114. package/package.json +2 -1
  115. package/scripts/update-manifest.mjs +2 -2
  116. package/shared/skill/runtime/bootstrap.mjs +1 -1
  117. package/shared/skill/runtime/cooperative-schema.mjs +0 -23
  118. package/shared/skill/runtime/cooperative.mjs +13 -34
  119. package/shared/skill/runtime/evaluate.mjs +3 -69
  120. package/shared/skill/runtime/gemini-stream.mjs +32 -0
  121. package/shared/skill/runtime/git-evidence.mjs +0 -98
  122. package/shared/skill/runtime/identity.mjs +2 -1
  123. package/shared/skill/runtime/local-cli.mjs +14 -24
  124. package/shared/skill/runtime/operations.mjs +2 -2
  125. package/shared/skill/runtime/platform-registry.mjs +130 -0
  126. package/shared/skill/runtime/role-bridge-args.mjs +57 -2
  127. package/shared/skill/runtime/role-bridge.mjs +86 -65
  128. package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
  129. package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
  130. package/shared/skill/runtime/role-observe.mjs +1 -0
  131. package/shared/skill/runtime/role-policy.json +40 -21
  132. package/shared/skill/runtime/role-routing-config.mjs +36 -9
  133. package/shared/skill/runtime/role-routing.mjs +62 -29
  134. package/shared/skill/runtime/role-supervisor.mjs +114 -49
  135. package/shared/skill/runtime/schema.mjs +5 -4
@@ -1,30 +1,35 @@
1
+ import {runtimeRegistryOf, DEFAULT_PLATFORM_REGISTRY} from './platform-registry.mjs';
1
2
  // A caller's JSON, local hook or child process ID cannot authorize execution.
2
3
  // run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
3
4
  import fsp from 'node:fs/promises';
4
5
  import path from 'node:path';
5
- import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons} from './role-dispatch-policy.mjs';
6
- import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES} from './role-dispatch-store.mjs';
7
- import {withRoutingLock, readActivation, readRevision, authenticate} from './role-routing.mjs';
8
- import {resolveConfigHome} from './local-cli.mjs';
9
- import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
6
+ import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
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';
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}]});
12
12
 
13
13
  const ID=/^[A-Za-z0-9._-]{1,128}$/;
14
+ const v1Platforms = Object.freeze(['codex', 'claude']);
14
15
  const NATIVE_EVENTS={started:[['reserved'],'running'],completed:[['running'],'completed'],failed:[['running'],'failed'],cancelled:[['running','reserved'],'cancelled']};
15
16
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
16
- const hostOf=context=>['codex','claude'].includes(context?.hostPlatform)?context.hostPlatform:null;
17
- const environmentOf=(context,host)=>['codex-cli','claude-cli','codex-desktop','claude-desktop'].includes(context?.executionEnvironment)&&host&&context.executionEnvironment.startsWith(`${host}-`)?context.executionEnvironment:null;
17
+ const hostOf=context=>runtimeRegistryOf(context).isPlatformId(context?.hostPlatform)?context.hostPlatform:null;
18
+ const environmentOf=(context,host)=>runtimeRegistryOf(context).getPlatform(host)?.executionEnvironments.includes(context?.executionEnvironment)?context.executionEnvironment:null;
18
19
  const validContext=context=>{const host=hostOf(context);return Boolean(host&&environmentOf(context,host)&&typeof context.workflowId==='string'&&context.workflowId&&typeof context.cwd==='string');};
19
20
  const blank=(context,dispatchId,decision,code)=>({decision,routeStatus:'held',supportStatus:'unverified',dispatchId:typeof dispatchId==='string'&&ID.test(dispatchId)?dispatchId:null,route:null,profileName:null,executionEnvironment:context?.executionEnvironment??null,hostPlatform:context?.hostPlatform??null,role:null,requested:null,authentication:null,cliVersion:null,claims:null,reasons:[reason(code)]});
20
- const bridgeTarget=lease=>lease.route==='native'?lease.hostPlatform:lease.hostPlatform==='codex'?'claude':'codex';
21
+ export function leaseTargetPlatform(lease,registry=DEFAULT_PLATFORM_REGISTRY){
22
+ if(lease.version===2)return lease.targetPlatform;
23
+ if(!v1Platforms.includes(lease.hostPlatform))throw Error('Invalid composite profile: unknown platform');
24
+ if(lease.route==='native')return lease.hostPlatform;
25
+ return v1Platforms.find(id=>id!==lease.hostPlatform);
26
+ }
21
27
  const supportOf=lease=>lease.route==='bridge'&&!String(lease.executionEnvironment).endsWith('-desktop')&&lease.state==='completed'&&lease.reasons.length===0&&['identity','model','effort','permissions','terminal'].every(key=>lease.claims?.[key]?.level==='runtime-observed')?'verified':'unverified';
22
28
  /** Result view of a lease. failed and unknown hold dependent work; every other observed state is reported as allow. */
23
- function fromLease(lease,decision=['failed','unknown'].includes(lease.state)?'hold':'allow'){
24
- const platform=bridgeTarget(lease);
25
- return {decision,routeStatus:lease.state,supportStatus:supportOf(lease),dispatchId:lease.dispatchId,route:lease.route,profileName:profileName(platform,lease.role),executionEnvironment:lease.executionEnvironment,hostPlatform:lease.hostPlatform,role:lease.role,requested:{platform,model:lease.claims?.model?.requested??null,effort:lease.claims?.effort?.requested??null},authentication:null,cliVersion:null,claims:lease.claims,reasons:lease.reasons,resultPath:lease.resultPath};
29
+ function fromLease(lease,decision=['failed','unknown'].includes(lease.state)?'hold':'allow',runtimePlatforms=DEFAULT_PLATFORM_REGISTRY){
30
+ const platform=leaseTargetPlatform(lease,runtimePlatforms);
31
+ return {decision,routeStatus:lease.state,supportStatus:supportOf(lease),dispatchId:lease.dispatchId,route:lease.route,profileName:profileName(platform,lease.role,{runtimePlatforms}),executionEnvironment:lease.executionEnvironment,hostPlatform:lease.hostPlatform,role:lease.role,requested:{platform,model:lease.claims?.model?.requested??null,effort:lease.claims?.effort?.requested??null},authentication:null,cliVersion:null,claims:lease.claims,reasons:lease.reasons,resultPath:lease.resultPath};
26
32
  }
27
- const homesOf=context=>({codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)});
28
33
  const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
29
34
  const hold=(context,dispatchId,code,error)=>{const result=blank(context,dispatchId,'hold',code);const residual=residualOf(error);if(residual)result.residualPaths=residual;return result;};
30
35
  const classifyLock=error=>{const code=error?.code==='ARC_ROUTING_LOCK_RELEASE'&&error.failure?error.failure.code:error?.code;return code==='ARC_HOST_SANDBOX'?'host_sandbox_blocked':'activation_unverified';};
@@ -34,23 +39,29 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
34
39
  if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
35
40
  const bytes=Buffer.byteLength(brief,'utf8');
36
41
  if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
37
- let homes,result,residual;
38
- try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
42
+ const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
43
+ const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
44
+ let anchorHome,result,residual;
45
+ try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
39
46
  try{
40
- await withRoutingLock(homes.codex,async()=>{
41
- const lease=await readLease(homes.codex,dispatchId);
47
+ await withRoutingLock(anchorHome,async()=>{
48
+ const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
42
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;}
43
- let config;try{config=await readActivation(homes,lease.revision);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
50
+ leaseTargetPlatform(lease,runtimePlatforms);
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
+ validateLease(lease,{runtimePlatforms,config});
53
+ const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:leaseTargetPlatform(lease,runtimePlatforms),route:lease.route,runtimePlatforms});
54
+ if(capabilities.length){result=blank(context,dispatchId,'hold',capabilities[0]);return;}
44
55
  let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
45
56
  const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
46
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;}
47
58
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
48
59
  await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
49
60
  let supervisor;
50
- try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
61
+ try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
51
62
  catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
52
- const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now});
53
- result=fromLease(next,'allow');
63
+ const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now,runtimePlatforms});
64
+ result=view(next,'allow');
54
65
  },{retryMs:policy.lockRetryMs});
55
66
  }catch(error){
56
67
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
@@ -61,30 +72,31 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
61
72
  }
62
73
 
63
74
  const TEXT=/^[^\p{Cc}]{1,256}$/u;
64
- async function markLostIfDue(homes,lease,{now,lostMs,policy}){
75
+ async function markLostIfDue(anchorHome,lease,{now,lostMs,policy,runtimePlatforms}){
65
76
  if(!['starting','running'].includes(lease.state)||!lease.supervisor)return lease;
66
- const heartbeat=await readHeartbeat(homes.codex,lease.dispatchId);
77
+ const heartbeat=await readHeartbeat(anchorHome,lease.dispatchId);
67
78
  const lastSeen=Math.max(heartbeat?.at??0,Date.parse(lease.updatedAt)||0);
68
79
  if(now-lastSeen<=lostMs||processAlive(lease.supervisor))return lease;
69
80
  try{
70
- return await withRoutingLock(homes.codex,async()=>{
71
- const current=await readLease(homes.codex,lease.dispatchId);
81
+ return await withRoutingLock(anchorHome,async()=>{
82
+ const current=await readLease(anchorHome,lease.dispatchId,{runtimePlatforms});
72
83
  if(!current||!['starting','running'].includes(current.state))return current??lease;
73
- return writeLease(homes.codex,{...current,state:'unknown',claims:{...(current.claims??{}),terminal:{level:'unverified',source:'none'}},reasons:[reason('terminal_state_unverified')]},{now});
84
+ return writeLease(anchorHome,{...current,state:'unknown',claims:{...(current.claims??{}),terminal:{level:'unverified',source:'none'}},reasons:[reason('terminal_state_unverified')]},{now,runtimePlatforms});
74
85
  },{retryMs:policy.lockRetryMs});
75
86
  }catch{return lease;}// a busy lock only delays the transition; the next observe retries it
76
87
  }
77
- async function recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now,policy}){
88
+ async function recordNativeEvent({context,anchorHome,dispatchId,event,nativeAgentId,now,policy,runtimePlatforms}){
89
+ const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
78
90
  let result;
79
91
  try{
80
- await withRoutingLock(homes.codex,async()=>{
81
- const lease=await readLease(homes.codex,dispatchId);
92
+ await withRoutingLock(anchorHome,async()=>{
93
+ const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
82
94
  const rule=NATIVE_EVENTS[event];
83
95
  if(!lease||lease.route!=='native'||lease.workflowId!==context.workflowId||!rule[0].includes(lease.state)||(event==='started')!==(nativeAgentId!==undefined)){result=blank(context,dispatchId,'deny','invalid_request');return;}
84
96
  const attested={level:'operator-attested',source:'orchestrator'};
85
97
  const claims={...lease.claims,...(event==='started'?{identity:{...attested,observed:nativeAgentId}}:{terminal:{...attested,observed:event}})};
86
- const next=await writeLease(homes.codex,{...lease,state:rule[1],claims,nativeAgentId:nativeAgentId??lease.nativeAgentId,reasons:event==='failed'?[reason('execution_failed')]:[]},{now});
87
- result=fromLease(next);
98
+ const next=await writeLease(anchorHome,{...lease,state:rule[1],claims,nativeAgentId:nativeAgentId??lease.nativeAgentId,reasons:event==='failed'?[reason('execution_failed')]:[]},{now,runtimePlatforms});
99
+ result=view(next);
88
100
  },{retryMs:policy.lockRetryMs});
89
101
  }catch(error){return hold(context,dispatchId,classifyLock(error),error);}
90
102
  return result;
@@ -96,64 +108,70 @@ export async function recordRoleObservation({context,dispatchId,waitMs,event,nat
96
108
  if(waitMs!==undefined&&(!Number.isInteger(waitMs)||waitMs<0||waitMs>policy.observeMaxWaitMs))return blank(context,dispatchId,'deny','invalid_request');
97
109
  if(event!==undefined&&!Object.hasOwn(NATIVE_EVENTS,event))return blank(context,dispatchId,'deny','invalid_request');
98
110
  if(nativeAgentId!==undefined&&(typeof nativeAgentId!=='string'||!TEXT.test(nativeAgentId)))return blank(context,dispatchId,'deny','invalid_request');
99
- let homes,lease;
100
- try{homes=homesOf(context);lease=await readLease(homes.codex,dispatchId);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
111
+ const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
112
+ const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
113
+ let anchorHome,lease;
114
+ try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});if(lease)leaseTargetPlatform(lease,runtimePlatforms);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
101
115
  if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform)return blank(context,dispatchId,'deny','invalid_request');
102
116
  if(lease.route==='native'){
103
117
  if(waitMs!==undefined||event===undefined)return blank(context,dispatchId,'deny','invalid_request');
104
- return recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now:now??Date.now(),policy});
118
+ return recordNativeEvent({context,anchorHome,dispatchId,event,nativeAgentId,now:now??Date.now(),policy,runtimePlatforms});
105
119
  }
106
120
  if(event!==undefined||nativeAgentId!==undefined)return blank(context,dispatchId,'deny','invalid_request');
107
121
  const end=Date.now()+(waitMs??0),lost=lostMs??policy.supervisorLostMs;
108
122
  try{
109
123
  for(;;){
110
- lease=await markLostIfDue(homes,lease,{now:now??Date.now(),lostMs:lost,policy});
111
- if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return fromLease(lease);
124
+ lease=await markLostIfDue(anchorHome,lease,{now:now??Date.now(),lostMs:lost,policy,runtimePlatforms});
125
+ if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return view(lease);
112
126
  await sleep(Math.min(pollMs,Math.max(0,end-Date.now())));
113
- lease=await readLease(homes.codex,dispatchId)??lease;
127
+ lease=await readLease(anchorHome,dispatchId,{runtimePlatforms})??lease;
114
128
  }
115
129
  }catch{return blank(context,dispatchId,'hold','activation_unverified');}
116
130
  }
117
131
 
118
132
  /** Continues a completed or failed bridge dispatch in its recorded session. The input carries no session id; only the lease value is used. */
119
- export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
133
+ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor,supervisorImplementations=SUPERVISOR_IMPLEMENTATIONS}={}){
120
134
  if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
121
135
  const bytes=Buffer.byteLength(brief,'utf8');
122
136
  if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
123
- let homes,result,residual;
124
- try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
137
+ const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
138
+ const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
139
+ let anchorHome,result,residual;
140
+ try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
125
141
  try{
126
- await withRoutingLock(homes.codex,async()=>{
127
- const lease=await readLease(homes.codex,dispatchId);
142
+ await withRoutingLock(anchorHome,async()=>{
143
+ const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
128
144
  if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||!['completed','failed'].includes(lease.state)){result=blank(context,dispatchId,'deny','invalid_request');return;}
145
+ const targetPlatform=leaseTargetPlatform(lease,runtimePlatforms);
146
+ if(targetPlatform==='gemini'&&!['on','verified'].includes(supervisorImplementations.get(targetPlatform)?.resume)){result=blank(context,dispatchId,'hold','resume_unverified');return;}
129
147
  if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
130
148
  let config;
131
- try{config=await readActivation(homes,lease.revision);}
149
+ try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}
132
150
  catch{
133
- let active=null;try{active=await readRevision(homes);}catch{/* unreadable activation stays unverified */}
151
+ let active=null;try{active=await readRevision(homes,{anchorHome,runtimePlatforms});}catch{/* unreadable activation stays unverified */}
134
152
  result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
135
153
  }
136
154
  const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
137
155
  const {authentication}=await authenticate(platform,context,policy);
138
- if(authentication.status!=='Available')codes.add(authentication.status);
156
+ if(authentication.status!=='Available'&&!(runtimePlatforms.getPlatform(platform).auth.kind==='none'&&authentication.authStatus==='unknown'&&authentication.reason==='auth_unverified'))codes.add(authentication.status??'Incomplete');
139
157
  for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
140
158
  for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
141
159
  // The dispatch itself is terminal here, so only other non-terminal bridge leases occupy slots. The workflow total is not increased by a follow-up segment.
142
160
  let limits;try{limits=readHostLimits(homes[context.hostPlatform]);}catch{codes.add('activation_unverified');}
143
- if(limits&&(await listLeases(homes.codex)).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
161
+ if(limits&&(await listLeases(anchorHome,{runtimePlatforms})).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
144
162
  if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
145
163
  let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
146
164
  const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
147
- let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
165
+ 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;}
148
166
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
149
167
  await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
150
- await clearCancel(homes.codex,dispatchId);
168
+ await clearCancel(anchorHome,dispatchId);
151
169
  let supervisor;
152
- try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
170
+ try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
153
171
  catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
154
172
  const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
155
- const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now});
156
- result={...fromLease(next,'allow'),segment};
173
+ const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now,runtimePlatforms});
174
+ result={...view(next,'allow'),segment};
157
175
  },{retryMs:policy.lockRetryMs});
158
176
  }catch(error){
159
177
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
@@ -169,30 +187,33 @@ const signalGroup=(pid,signal)=>{try{process.kill(-pid,signal);}catch{/* group a
169
187
  /** Reserved leases have no child and are cleaned up at once. A live supervisor receives a cancel marker and records cancelled itself after observing the exit. An unknown lease (or one whose supervisor is gone) is stopped here only for a process identified by pid and start time, and cancelled only after the group is observed gone. */
170
188
  export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),policy=DEFAULT_POLICY}={}){
171
189
  if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
172
- let homes,result,direct=null,residual;
173
- try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
190
+ const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
191
+ const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
192
+ let anchorHome,result,direct=null,residual;
193
+ try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
174
194
  const graceMs=policy.cancelGraceMs;
175
195
  try{
176
- await withRoutingLock(homes.codex,async()=>{
177
- const lease=await readLease(homes.codex,dispatchId);
196
+ await withRoutingLock(anchorHome,async()=>{
197
+ const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
178
198
  if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform){result=blank(context,dispatchId,'deny','invalid_request');return;}
199
+ leaseTargetPlatform(lease,runtimePlatforms);
179
200
  if(lease.route==='native'){
180
201
  // A native lease has no child: only a reserved one is cancelled here (under the lock); started native dispatches are closed with observe events.
181
202
  if(lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
182
203
  const claims={...lease.claims,terminal:{level:'operator-attested',source:'orchestrator',observed:'cancelled'}};
183
- result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',claims,reasons:[]},{now}),'allow');return;
204
+ result=view(await writeLease(anchorHome,{...lease,state:'cancelled',claims,reasons:[]},{now,runtimePlatforms}),'allow');return;
184
205
  }
185
- if(TERMINAL_STATES.includes(lease.state)){result=fromLease(lease,'allow');return;}
186
- if(lease.state==='reserved'){result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',reasons:[]},{now}),'allow');return;}
206
+ if(TERMINAL_STATES.includes(lease.state)){result=view(lease,'allow');return;}
207
+ if(lease.state==='reserved'){result=view(await writeLease(anchorHome,{...lease,state:'cancelled',reasons:[]},{now,runtimePlatforms}),'allow');return;}
187
208
  const supervised=['starting','running'].includes(lease.state)&&lease.supervisor&&processAlive(lease.supervisor);
188
209
  if(supervised){
189
- await requestCancel(homes.codex,dispatchId);
210
+ await requestCancel(anchorHome,dispatchId);
190
211
  if(lease.child&&processAlive(lease.child))signalGroup(lease.child.pid,'SIGTERM');
191
- result={...fromLease(lease,'allow'),routeStatus:'cancelling'};return;
212
+ result={...view(lease,'allow'),routeStatus:'cancelling'};return;
192
213
  }
193
214
  if(lease.child&&processAlive(lease.child)){signalGroup(lease.child.pid,'SIGTERM');direct={lease,identified:true};}
194
215
  else if(lease.child&&!groupExists(lease.child.pid)&&!pidExists(lease.child.pid))direct={lease,identified:false};
195
- else result=fromLease(lease,'hold');
216
+ else result=view(lease,'hold');
196
217
  },{retryMs:policy.lockRetryMs});
197
218
  }catch(error){
198
219
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&(result||direct)){residual=residualOf(error);}
@@ -204,15 +225,15 @@ export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),poli
204
225
  if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
205
226
  await sleep(25);gone=!groupExists(pid);
206
227
  }
207
- if(!gone)result=fromLease(direct.lease,'hold');
228
+ if(!gone)result=view(direct.lease,'hold');
208
229
  else{
209
230
  try{
210
- await withRoutingLock(homes.codex,async()=>{
211
- const current=await readLease(homes.codex,dispatchId);
212
- if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?fromLease(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
231
+ await withRoutingLock(anchorHome,async()=>{
232
+ const current=await readLease(anchorHome,dispatchId,{runtimePlatforms});
233
+ if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?view(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
213
234
  const claims={...(current.claims??{}),terminal:{level:'runtime-observed',source:'cancel-group-gone',observed:{pid}}};
214
235
  // The recorded reasons (for example terminal_state_unverified) stay on the cancelled lease.
215
- result=fromLease(await writeLease(homes.codex,{...current,state:'cancelled',claims},{now:Date.now()}),'allow');
236
+ result=view(await writeLease(anchorHome,{...current,state:'cancelled',claims},{now:Date.now(),runtimePlatforms}),'allow');
216
237
  },{retryMs:policy.lockRetryMs});
217
238
  }catch(error){
218
239
  if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
@@ -1,5 +1,6 @@
1
+ import {runtimeRegistryOf} from './platform-registry.mjs';
1
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.
2
- export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: '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'});
3
4
  // No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
4
5
  const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
5
6
  const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
@@ -39,12 +40,14 @@ export const DEFAULT_POLICY = Object.freeze({
39
40
  });
40
41
 
41
42
  export const RELEASE_CONDITIONS = Object.freeze({
42
- activation_unverified: 'Verify the active configuration, both prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <CODEX_HOME>/arc-role-dispatch for unreadable or corrupted files.',
43
+ activation_unverified: 'Verify the active configuration, all prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <anchor home>/arc-role-dispatch for unreadable or corrupted files.',
44
+ resume_unverified: 'Update ARC after verifying Gemini session resume against the recorded session UUID.',
45
+ capability_not_verified: 'Update ARC to a release that verifies this platform capability.',
43
46
  'Not Available': 'Install the target platform CLI so that it is found on PATH.',
44
47
  Unauthorized: 'Authenticate the target platform CLI.',
45
48
  Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
46
49
  environment_unverified: 'Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare codex-cli or claude-cli instead; otherwise use a CLI host or a later ARC update that changes the support status.',
47
- host_sandbox_blocked: 'Allow the host to write the Codex home and keep a detached supervisor alive, with explicit user approval.',
50
+ host_sandbox_blocked: 'Allow the host to write the anchor home and keep a detached supervisor alive, with explicit user approval.',
48
51
  capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
49
52
  permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
50
53
  native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
@@ -69,15 +72,22 @@ export const reason = code => {
69
72
  if (!Object.hasOwn(RELEASE_CONDITIONS, code)) throw Error(`Unknown reason code: ${code}`);
70
73
  return {code, releaseCondition: RELEASE_CONDITIONS[code]};
71
74
  };
72
- export const profileName = (platform, role) => {
73
- const suffix = role.slice('arc_'.length);
74
- return platform === 'claude' ? `arc-routing-${suffix}` : `arc_routing_${suffix}`;
75
- };
75
+ export const profileName = (platform, role, options) => runtimeRegistryOf(options).getPlatform(platform).profile.routingName(role);
76
76
  export const revisionTag = revision => `[arc-routing rev ${revision}]`;
77
77
 
78
+ export function capabilityReasons({hostPlatform, targetPlatform, route, runtimePlatforms}) {
79
+ const registry = runtimeRegistryOf({runtimePlatforms});
80
+ const host = registry.getPlatform(hostPlatform), target = registry.getPlatform(targetPlatform);
81
+ return host?.capabilities.compositeHost.state === 'verified'
82
+ && target?.capabilities.compositeRole.state === 'verified'
83
+ && (route !== 'bridge' || target?.capabilities.bridge.state === 'verified') ? [] : ['capability_not_verified'];
84
+ }
85
+
78
86
  export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
79
87
  const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
80
88
  if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
89
+ if (platform === 'gemini' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GG1 !== 'pass') codes.push('permission_scope_unverified');
90
+ if (hostPlatform === 'gemini' && gates.GG2 !== 'pass') codes.push('host_sandbox_blocked');
81
91
  if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
82
92
  if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
83
93
  return [...new Set(codes)];
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import fsp from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import crypto from 'node:crypto';
6
+ import {runtimeRegistryOf} from './platform-registry.mjs';
6
7
 
7
8
  export const NON_TERMINAL_STATES = Object.freeze(['reserved', 'starting', 'running', 'unknown']);
8
9
  export const TERMINAL_STATES = Object.freeze(['completed', 'failed', 'cancelled']);
@@ -18,11 +19,16 @@ const leasePath = (codexHome, dispatchId) => {
18
19
  if (typeof dispatchId !== 'string' || !ID.test(dispatchId) || dispatchId.startsWith('.')) throw Error('Invalid dispatch id');
19
20
  return path.join(dispatchDirectory(codexHome), `${dispatchId}.json`);
20
21
  };
21
- export function validateLease(value) {
22
- if (!isObject(value) || Object.keys(value).length !== KEYS.length || KEYS.some(key => !Object.hasOwn(value, key))) throw Error('Invalid lease keys');
23
- const ok = value.version === 1 && typeof value.dispatchId === 'string' && ID.test(value.dispatchId) && !value.dispatchId.startsWith('.')
22
+ export function validateLease(value, options) {
23
+ const keys = value?.version === 2 ? [...KEYS, 'targetPlatform'] : KEYS;
24
+ if (!isObject(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))) throw Error('Invalid lease keys');
25
+ const registry = options?.registry ?? runtimeRegistryOf(options);
26
+ const ok = [1, 2].includes(value.version) && typeof value.dispatchId === 'string' && ID.test(value.dispatchId) && !value.dispatchId.startsWith('.')
24
27
  && ['workflowId', 'taskId', 'requestId', 'role', 'executionEnvironment', 'revision', 'createdAt', 'updatedAt'].every(key => text(value[key]))
25
- && ['native', 'bridge'].includes(value.route) && ['codex', 'claude'].includes(value.hostPlatform)
28
+ && ['native', 'bridge'].includes(value.route) && registry.isPlatformId(value.hostPlatform)
29
+ && (value.version === 1 || registry.isPlatformId(value.targetPlatform)
30
+ && (value.route === 'native' ? value.targetPlatform === value.hostPlatform : value.targetPlatform !== value.hostPlatform)
31
+ && (!options?.config || Object.values(options.config.roles).some(role => role.platform === value.targetPlatform)))
26
32
  && nullableText(value.profileHash) && nullableText(value.argsDigest) && nullableText(value.sessionId) && nullableText(value.resultPath) && nullableText(value.nativeAgentId)
27
33
  && [...NON_TERMINAL_STATES, ...TERMINAL_STATES].includes(value.state) && process_(value.supervisor) && process_(value.child)
28
34
  && Number.isInteger(value.timeoutMinutes) && value.timeoutMinutes > 0 && Number.isInteger(value.segment) && value.segment >= 0
@@ -40,21 +46,21 @@ export async function ensureDispatchDirectory(codexHome, {uid = process.getuid?.
40
46
  if ((stat.mode & 0o077) !== 0) await fsp.chmod(directory, stat.mode & 0o700); // only tightens: owner bits are never widened, so a sandbox-restricted directory still fails on write
41
47
  return directory;
42
48
  }
43
- export async function createLease(codexHome, lease) {
44
- const value = validateLease(lease);
49
+ export async function createLease(codexHome, lease, options) {
50
+ const value = validateLease(lease, options);
45
51
  await ensureDispatchDirectory(codexHome);
46
52
  const handle = await fsp.open(leasePath(codexHome, value.dispatchId), 'wx', 0o600);
47
53
  try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); } finally { await handle.close(); }
48
54
  return value;
49
55
  }
50
- export async function readLease(codexHome, dispatchId) {
56
+ export async function readLease(codexHome, dispatchId, options) {
51
57
  let bytes;
52
58
  try { bytes = await fsp.readFile(leasePath(codexHome, dispatchId), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
53
- return validateLease(JSON.parse(bytes));
59
+ return validateLease(JSON.parse(bytes), options);
54
60
  }
55
- export async function writeLease(codexHome, lease, {now = Date.now()} = {}) {
61
+ export async function writeLease(codexHome, lease, {now = Date.now(), runtimePlatforms} = {}) {
56
62
  await ensureDispatchDirectory(codexHome);
57
- const value = validateLease({...lease, updatedAt: new Date(now).toISOString()}), target = leasePath(codexHome, value.dispatchId);
63
+ const value = validateLease({...lease, updatedAt: new Date(now).toISOString()}, {runtimePlatforms}), target = leasePath(codexHome, value.dispatchId);
58
64
  const temp = path.join(dispatchDirectory(codexHome), `.${value.dispatchId}.${crypto.randomUUID()}.tmp`);
59
65
  try {
60
66
  const handle = await fsp.open(temp, 'wx', 0o600);
@@ -68,19 +74,19 @@ const leaseFiles = async codexHome => {
68
74
  try { return (await fsp.readdir(dispatchDirectory(codexHome))).filter(name => name.endsWith('.json') && !name.endsWith(HEARTBEAT_SUFFIX) && !name.startsWith('.')).sort(); }
69
75
  catch (error) { if (error.code === 'ENOENT') return []; throw error; }
70
76
  };
71
- export async function listLeases(codexHome) {
77
+ export async function listLeases(codexHome, options) {
72
78
  const leases = [];
73
- for (const name of await leaseFiles(codexHome)) leases.push(validateLease(JSON.parse(await fsp.readFile(path.join(dispatchDirectory(codexHome), name), 'utf8'))));
79
+ for (const name of await leaseFiles(codexHome)) leases.push(validateLease(JSON.parse(await fsp.readFile(path.join(dispatchDirectory(codexHome), name), 'utf8')), options));
74
80
  return leases;
75
81
  }
76
82
  /** Removes only terminal leases whose updatedAt is older than retentionMs. Failures are counted, never thrown. */
77
- export async function pruneTerminalLeases(codexHome, {now = Date.now(), retentionMs}) {
83
+ export async function pruneTerminalLeases(codexHome, {now = Date.now(), retentionMs, runtimePlatforms}) {
78
84
  let removed = 0, errors = 0, names;
79
85
  try { names = await leaseFiles(codexHome); } catch { return {removed, errors: 1}; }
80
86
  for (const name of names) {
81
87
  const file = path.join(dispatchDirectory(codexHome), name);
82
88
  try {
83
- const lease = validateLease(JSON.parse(await fsp.readFile(file, 'utf8')));
89
+ const lease = validateLease(JSON.parse(await fsp.readFile(file, 'utf8')), {runtimePlatforms});
84
90
  const updated = Date.parse(lease.updatedAt);
85
91
  if (!TERMINAL_STATES.includes(lease.state) || !Number.isFinite(updated) || now - updated <= retentionMs) continue;
86
92
  await fsp.unlink(file); removed += 1;
@@ -1,5 +1,6 @@
1
1
  // Pure observation helpers: stream/transcript/rollout normalization, model, permission and failure judgement, and worktree snapshot comparison.
2
2
  // The only process started here is read-only `git` for snapshots; no CLI is ever run.
3
+ export {normalizeGeminiStreamEvent} from './gemini-stream.mjs';
3
4
  import crypto from 'node:crypto';
4
5
  import fs from 'node:fs';
5
6
  import fsp from 'node:fs/promises';
@@ -1,19 +1,46 @@
1
+ import {runtimeRegistryOf} from './platform-registry.mjs';
2
+
1
3
  export const ROUTING_ROLES = Object.freeze(['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer']);
2
4
  const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value);
3
5
  const exact = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
4
- export function validRoleValues(platform, model, effort) {
5
- return ['codex', 'claude'].includes(platform) && validText(model) && validText(effort) && (platform !== 'claude' || (/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && ['low', 'medium', 'high', 'xhigh', 'max'].includes(effort)));
6
+ const v1Platforms = Object.freeze(['codex', 'claude']);
7
+ const isV1Platforms = platforms => platforms.length === v1Platforms.length && v1Platforms.every((id, index) => platforms[index] === id);
8
+ // Keep injected validation context out of the public config and serialized bytes.
9
+ const configRegistries = new WeakMap();
10
+
11
+ export function validRoleValues(platform, model, effort, {runtimePlatforms} = {}) {
12
+ const registry = runtimeRegistryOf({runtimePlatforms});
13
+ return registry.isPlatformId(platform) && registry.getPlatform(platform).routing.validatePair(model, effort);
6
14
  }
7
- export function validateRoleRoutingConfig(config) {
8
- if (!exact(config, ['version', 'revision', 'roles']) || config.version !== 1 || !validText(config.revision) || !exact(config.roles, ROUTING_ROLES)) throw Error('Invalid role routing configuration');
15
+ export function validateRoleRoutingConfig(config, opts = {}) {
16
+ 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');
18
+ const registry = runtimeRegistryOf(opts);
19
+ const platforms = config.version === 1 && !Object.hasOwn(config, 'platforms') ? [...v1Platforms] : config.platforms;
20
+ 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
+ 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');
9
22
  for (const role of ROUTING_ROLES) {
10
23
  const fields = config.roles[role];
11
- if (!exact(fields, ['platform', 'model', 'effort']) || !validRoleValues(fields.platform, fields.model, fields.effort)) throw Error(`Invalid role routing values for ${role}`);
24
+ 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}`);
12
25
  }
13
- return structuredClone(config);
26
+ const result = structuredClone({version: config.version, revision: config.revision, platforms, roles: config.roles});
27
+ configRegistries.set(result, registry);
28
+ return result;
14
29
  }
15
- export function parseRoleRoutingConfig(text) {
30
+ export function parseRoleRoutingConfig(text, opts) {
16
31
  let value; try { value = JSON.parse(text); } catch { throw Error('Invalid role routing configuration'); }
17
- return validateRoleRoutingConfig(value);
32
+ return validateRoleRoutingConfig(value, opts);
33
+ }
34
+ export function serializeRoleRoutingConfig(config) {
35
+ const {revision, platforms, roles} = validateRoleRoutingConfig(config, {runtimePlatforms: configRegistries.get(config)});
36
+ const value = {version: 2, revision, platforms, roles};
37
+ return JSON.stringify(value, null, 2) + '\n';
38
+ }
39
+ export function buildRoleRoutingConfig({revision, platforms = [], roles}, opts = {}) {
40
+ const registry = runtimeRegistryOf(opts);
41
+ if (!Array.isArray(platforms)) throw Error('Invalid role routing platforms');
42
+ const participating = [...new Set([...platforms, ...Object.values(roles).map(fields => fields.platform)])];
43
+ if (participating.some(id => !registry.isPlatformId(id))) throw Error('Invalid role routing platforms');
44
+ participating.sort((a, b) => registry.getPlatform(a).anchorOrder - registry.getPlatform(b).anchorOrder);
45
+ return validateRoleRoutingConfig({version: 2, revision, platforms: participating, roles}, opts);
18
46
  }
19
- export function serializeRoleRoutingConfig(config) { return JSON.stringify(validateRoleRoutingConfig(config), null, 2) + '\n'; }