@yunhozz/arc 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,233 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import {constants} from 'node:fs';
3
- import path from 'node:path';
4
- import crypto from 'node:crypto';
5
- import {COOPERATIVE_RUNTIME_MODULES, cooperativeVersions} from './bootstrap.mjs';
6
- import {inspectPath} from './scope.mjs';
7
- import {resolveConfigHome, resolveLocalCli, probePlatformAuth, probeCodexAuthStatus, probeCliVersion} from './local-cli.mjs';
8
- import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
9
- import {DEFAULT_POLICY, reason, profileName, revisionTag, bridgeGateReasons, environmentReasons, initialClaims} from './role-dispatch-policy.mjs';
10
- import {NON_TERMINAL_STATES, createLease, listLeases, pruneTerminalLeases, readHostLimits} from './role-dispatch-store.mjs';
11
-
12
- const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
13
- const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
14
- const equalStat=(a,b)=>['dev','ino','mode','size','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
15
- const validHash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
16
-
17
- async function readStable(filename,snapshot){
18
- await inspectPath(filename);
19
- const before=await fs.lstat(filename,{bigint:true});
20
- if(!before.isFile()||before.isSymbolicLink()||before.size>10485760n)throw Error('Unsafe file');
21
- const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW);
22
- try{
23
- const opened=await handle.stat({bigint:true});if(!equalStat(before,opened))throw Error('File changed');
24
- const bytes=await handle.readFile();const after=await handle.stat({bigint:true});const named=await fs.lstat(filename,{bigint:true});
25
- if(!equalStat(opened,after)||!equalStat(after,named))throw Error('File changed');
26
- snapshot.push({filename,stat:named});return bytes;
27
- }finally{await handle.close();}
28
- }
29
- async function checkSnapshot(snapshot){
30
- for(const entry of snapshot){await inspectPath(entry.filename);if(!equalStat(entry.stat,await fs.lstat(entry.filename,{bigint:true})))throw Error('File changed');}
31
- }
32
- export async function acquireRoleRoutingLock(home){
33
- await inspectPath(home,{directory:true});
34
- const filename=path.join(home,'arc-role-platform-routing.lock'),operationId=crypto.randomUUID();
35
- const handle=await fs.open(filename,'wx',0o600);let identity,closed=false;
36
- try{
37
- identity=await handle.stat({bigint:true});
38
- if(!identity.isFile())throw Error('Created lock is not a regular file');
39
- await handle.writeFile(JSON.stringify({version:1,operationId,pid:process.pid,createdAt:new Date().toISOString()})+'\n');
40
- await handle.sync();
41
- await handle.close();closed=true;
42
- }catch(cause){
43
- let residual=true;
44
- try{
45
- if(!identity?.isFile())throw Error('Created lock identity is unavailable');
46
- const opened=await handle.stat({bigint:true}),named=await fs.lstat(filename,{bigint:true});
47
- if(!opened.isFile()||!named.isFile()||named.isSymbolicLink()||opened.dev!==identity.dev||opened.ino!==identity.ino||named.dev!==identity.dev||named.ino!==identity.ino)throw Error('Created lock identity changed');
48
- await fs.unlink(filename);residual=false;
49
- }catch{}
50
- if(!closed)try{await handle.close();}catch{}
51
- const error=new Error(residual?'Composite lock initialization failed; inspect the residual path':'Composite lock initialization failed',{cause});
52
- error.code='ARC_ROUTING_LOCK_INITIALIZATION';if(residual)error.residualPaths=[filename];throw error;
53
- }
54
- return async()=>{
55
- try{
56
- const stat=await fs.lstat(filename,{bigint:true});
57
- if(!stat.isFile()||stat.isSymbolicLink()||stat.dev!==identity.dev||stat.ino!==identity.ino)return false;
58
- const data=JSON.parse(await fs.readFile(filename,'utf8'));
59
- if(!exact(data,['version','operationId','pid','createdAt'])||data.version!==1||data.operationId!==operationId||data.pid!==process.pid)return false;
60
- const current=await fs.lstat(filename,{bigint:true});if(current.dev!==identity.dev||current.ino!==identity.ino)return false;
61
- await fs.unlink(filename);return true;
62
- }catch{return false;}
63
- };
64
- }
65
- export async function readActivation(homes,expectedRevision){
66
- const snapshot=[],activePath=path.join(homes.codex,'arc-role-platform-routing.json');
67
- const configBytes=await readStable(activePath,snapshot),config=parseRoleRoutingConfig(configBytes.toString('utf8'));
68
- if(config.revision!==expectedRevision)throw Error('Revision mismatch');
69
- const versions=await cooperativeVersions();
70
- for(const platform of ['codex','claude']){
71
- const home=homes[platform],marker=JSON.parse((await readStable(path.join(home,'arc-role-platform-routing.prepared.json'),snapshot)).toString('utf8'));
72
- if(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||marker.revision!==config.revision||marker.platform!==platform||marker.targetHome!==home||marker.activeConfigPath!==activePath||marker.configHash!==hash(configBytes))throw Error('Invalid marker');
73
- if(!exact(marker.runtime,['version','hash','policyHash'])||marker.runtime.version!==versions.runtime||!validHash(marker.runtime.hash)||!validHash(marker.runtime.policyHash))throw Error('Invalid runtime marker');
74
- const runtimeDir=path.join(home,'skills','arc','runtime');
75
- const runtime=[];for(const module of COOPERATIVE_RUNTIME_MODULES)runtime.push(await readStable(path.join(runtimeDir,module),snapshot));
76
- const policy=await readStable(path.join(runtimeDir,'role-policy.json'),snapshot);
77
- if(hash(Buffer.concat(runtime))!==marker.runtime.hash||hash(policy)!==marker.runtime.policyHash||marker.runtime.hash!==versions.runtimeHash||marker.runtime.policyHash!==versions.policyHash)throw Error('Runtime mismatch');
78
- const roles=ROUTING_ROLES.filter(role=>config.roles[role].platform===platform);
79
- if(!exact(marker.profiles,roles))throw Error('Invalid profiles');
80
- for(const role of roles){
81
- const suffix=role.slice('arc_'.length),relative=`agents/arc-routing-${suffix}.${platform==='codex'?'toml':'md'}`,entry=marker.profiles[role];
82
- if(!exact(entry,['path','hash'])||entry.path!==relative||!validHash(entry.hash)||hash(await readStable(path.join(home,relative),snapshot))!==entry.hash)throw Error('Profile mismatch');
83
- }
84
- }
85
- await checkSnapshot(snapshot);return config;
86
- }
87
-
88
-
89
- const HOST_ERRORS=['EACCES','EPERM','EROFS'];
90
- const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
91
- const lockFile=codexHome=>path.join(codexHome,'arc-role-platform-routing.lock');
92
- /** Runs fn under the shared routing lock. Only EEXIST is retried; the lock file is never removed except by its owner. */
93
- export async function withRoutingLock(codexHome,fn,{retryMs=DEFAULT_POLICY.lockRetryMs}={}){
94
- const deadline=Date.now()+retryMs;let release;
95
- for(;;){
96
- try{release=await acquireRoleRoutingLock(codexHome);break;}
97
- catch(error){
98
- if(error?.code==='EEXIST'){
99
- if(Date.now()>=deadline){const busy=new Error('Routing lock is busy; inspect the residual path',{cause:error});busy.code='ARC_ROUTING_LOCK_BUSY';busy.residualPaths=[lockFile(codexHome)];throw busy;}
100
- await sleep(50);continue;
101
- }
102
- if(HOST_ERRORS.includes(error?.code)){const denied=new Error('The host denied access to the routing lock',{cause:error});denied.code='ARC_HOST_SANDBOX';throw denied;}
103
- throw error;
104
- }
105
- }
106
- let value,failure,failed=false;
107
- try{value=await fn();}catch(error){failed=true;failure=error;}
108
- let released=false;try{released=await release();}catch{}
109
- if(!released){
110
- const error=new Error('Routing lock ownership could not be verified; inspect the residual path');
111
- error.code='ARC_ROUTING_LOCK_RELEASE';error.residualPaths=[lockFile(codexHome)];if(failed)error.failure=failure;else error.value=value;throw error;
112
- }
113
- if(failed)throw failure;return value;
114
- }
115
-
116
- const textValue=value=>typeof value==='string'&&/^[^\p{Cc}]{1,256}$/u.test(value);
117
- const validRelativePath=value=>typeof value==='string'&&value.length>0&&value.length<=1024&&!value.includes('\0')&&!value.startsWith('/')&&!/^[A-Za-z]:/.test(value)&&value.replace(/\/$/,'').split('/').every(part=>part&&part!=='..');
118
- const hostOf=context=>['codex','claude'].includes(context?.hostPlatform)?context.hostPlatform:null;
119
- const environmentOf=(context,host)=>['codex-cli','claude-cli','codex-desktop','claude-desktop'].includes(context?.executionEnvironment)&&host&&context.executionEnvironment.startsWith(`${host}-`)?context.executionEnvironment:null;
120
- function validateAssignment(assignment,expectedRevision,context){
121
- const role=assignment?.role;
122
- if(!ROUTING_ROLES.includes(role)||!textValue(assignment.requestId)||!textValue(assignment.taskId)||!textValue(expectedRevision)||!textValue(context?.workflowId))return false;
123
- const paths=assignment.allowedPaths;
124
- if(role==='arc_implementer')return Array.isArray(paths)&&paths.length>0&&paths.every(validRelativePath);
125
- if(paths===undefined)return true;
126
- return role==='arc_qa'&&Array.isArray(paths)&&paths.every(validRelativePath);
127
- }
128
- 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:[]});
129
- const classify=error=>{
130
- const code=error?.code==='ARC_ROUTING_LOCK_RELEASE'&&error.failure?error.failure.code:error?.code;
131
- return code==='ARC_HOST_SANDBOX'||HOST_ERRORS.includes(code)?'host_sandbox_blocked':'activation_unverified';
132
- };
133
- export async function authenticate(platform,context,policy){
134
- const cli=resolveLocalCli(platform,context);
135
- if(cli.reason)return {cli:null,authentication:{status:cli.reason==='cli_not_found'?'Not Available':'Incomplete',reason:cli.reason}};
136
- const auth=await (platform==='codex'?probeCodexAuthStatus:probePlatformAuth)(cli,{timeoutMs:policy.probeTimeoutMs});
137
- return {cli,authentication:{status:auth.authStatus==='authenticated'?'Available':auth.authStatus==='unauthorized'?'Unauthorized':'Incomplete',...(auth.reason?{reason:auth.reason}:{})}};
138
- }
139
- export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs,policy}):{version:null,supported:false,reason:'cli_not_found'};
140
- export async function readRevision(homes){
141
- const bytes=await readStable(path.join(homes.codex,'arc-role-platform-routing.json'),[]);
142
- return parseRoleRoutingConfig(bytes.toString('utf8')).revision;
143
- }
144
- export async function readProfileHash(home,role){
145
- const marker=JSON.parse(await fs.readFile(path.join(home,'arc-role-platform-routing.prepared.json'),'utf8'));
146
- const hashValue=marker?.profiles?.[role]?.hash;if(!validHash(hashValue))throw Error('Invalid profile hash');return hashValue;
147
- }
148
- const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
149
-
150
- /** Reports the active revision, per-role routes, profile names, authentication and CLI versions. Never reserves a lease. */
151
- export async function routingStatus({context,now=Date.now(),policy=DEFAULT_POLICY}={}){
152
- const host=hostOf(context),environment=environmentOf(context,host);
153
- const result={decision:'hold',revision:null,hostPlatform:host,executionEnvironment:environment,roles:null,platforms:null,pruned:{removed:0,errors:0},reasons:[]};
154
- if(!host||!environment){result.decision='deny';result.reasons=[reason('invalid_request')];return result;}
155
- let homes;
156
- try{homes={codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)};}
157
- catch{result.reasons=[reason('activation_unverified')];return result;}
158
- try{
159
- await withRoutingLock(homes.codex,async()=>{
160
- result.pruned=await pruneTerminalLeases(homes.codex,{now,retentionMs:policy.leaseRetentionMs});
161
- let config;try{config=await readActivation(homes,await readRevision(homes));}catch{result.reasons=[reason('activation_unverified')];return;}
162
- result.revision=config.revision;result.roles={};
163
- for(const role of ROUTING_ROLES){const requested=config.roles[role];result.roles[role]={route:requested.platform===host?'native':'bridge',platform:requested.platform,model:requested.model,effort:requested.effort,profileName:profileName(requested.platform,role),revisionTag:revisionTag(config.revision)};}
164
- result.platforms={};
165
- for(const platform of ['codex','claude'].filter(name=>name===host||ROUTING_ROLES.some(role=>config.roles[role].platform===name))){
166
- const {cli,authentication}=await authenticate(platform,context,policy);
167
- result.platforms[platform]={authentication,cliVersion:await versionOf(cli,policy)};
168
- }
169
- result.decision='allow';
170
- },{retryMs:policy.lockRetryMs});
171
- }catch(error){
172
- result.decision='hold';result.revision=null;result.roles=null;result.platforms=null;result.reasons=[reason(classify(error))];
173
- const residual=residualOf(error);if(residual)result.residualPaths=residual;
174
- }
175
- return result;
176
- }
177
-
178
- /** Applies the pre-start decision table and reserves a lease only when no reason remains. */
179
- export async function prepareRoleDispatch({context,assignment,expectedRevision,now=Date.now(),policy=DEFAULT_POLICY}={}){
180
- const host=hostOf(context),environment=environmentOf(context,host),role=ROUTING_ROLES.includes(assignment?.role)?assignment.role:null;
181
- const result=blankResult(host,environment,role);
182
- if(!host||!environment||!validateAssignment(assignment,expectedRevision,context)){result.decision='deny';result.reasons=[reason('invalid_request')];return result;}
183
- const codes=new Set();let duplicate=false,homes;
184
- try{homes={codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)};}
185
- catch{result.reasons=[reason('activation_unverified')];return result;}
186
- try{
187
- await withRoutingLock(homes.codex,async()=>{
188
- await pruneTerminalLeases(homes.codex,{now,retentionMs:policy.leaseRetentionMs});
189
- let config;try{config=await readActivation(homes,expectedRevision);}catch{result.reasons=[reason('activation_unverified')];return;}
190
- const requested=config.roles[role],route=requested.platform===host?'native':'bridge';
191
- result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role);
192
- const {cli,authentication}=await authenticate(requested.platform,context,policy);
193
- result.authentication=authentication;
194
- if(authentication.status!=='Available')codes.add(authentication.status);
195
- if(route==='bridge'){
196
- result.cliVersion=await versionOf(cli,policy);
197
- if(cli&&!result.cliVersion.supported)codes.add('permission_scope_unverified');
198
- }
199
- for(const code of environmentReasons(environment,policy))codes.add(code);
200
- const leases=await listLeases(homes.codex);
201
- const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
202
- if(leases.some(lease=>lease.requestId===assignment.requestId)||live.some(lease=>lease.workflowId===context.workflowId&&lease.taskId===assignment.taskId&&lease.role===role)){duplicate=true;codes.add('duplicate_dispatch');}
203
- if(route==='bridge'){
204
- let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
205
- if(limits){
206
- const bridges=leases.filter(lease=>lease.route==='bridge');
207
- if(bridges.filter(lease=>NON_TERMINAL_STATES.includes(lease.state)).length>=limits.maxConcurrent||bridges.filter(lease=>lease.workflowId===context.workflowId).length>=limits.maxTotal)codes.add('capacity_exhausted');
208
- }
209
- for(const code of bridgeGateReasons({platform:requested.platform,role,hostPlatform:host,policy}))codes.add(code);
210
- }
211
- result.reasons=[...codes].map(reason);
212
- if(codes.size){result.decision=duplicate?'deny':'hold';return;}
213
- const claims=initialClaims(route,policy,requested),iso=new Date(now).toISOString(),dispatchId=crypto.randomUUID();
214
- const lease=await createLease(homes.codex,{version:1,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:null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso});
215
- Object.assign(result,{decision:'allow',routeStatus:'reserved',dispatchId:lease.dispatchId,claims});
216
- },{retryMs:policy.lockRetryMs});
217
- }catch(error){
218
- if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result.decision==='allow'){
219
- // The lease was written but lock ownership could not be verified: report it as held and keep the id for inspection.
220
- {const base=reason('activation_unverified');Object.assign(result,{decision:'hold',routeStatus:'held',claims:null,reasons:[result.dispatchId?{...base,releaseCondition:`${base.releaseCondition} Reserved dispatch ${result.dispatchId} remains reserved and must be cleaned up with cancel (native or bridge route).`}:base]});}
221
- }else{
222
- Object.assign(result,{decision:'hold',routeStatus:'held',dispatchId:null,claims:null,reasons:[reason(classify(error))]});
223
- }
224
- const residual=residualOf(error);if(residual)result.residualPaths=residual;
225
- }
226
- return result;
227
- }
228
-
229
- /** Denial for requests whose keys do not match the documented set. */
230
- export function invalidRoutingRequest(context){
231
- const host=hostOf(context);
232
- return {...blankResult(host,environmentOf(context,host),null),decision:'deny',reasons:[reason('invalid_request')]};
233
- }
@@ -1,356 +0,0 @@
1
- // Detached supervisor for bridge dispatches: the only code that starts a bridge child CLI.
2
- // It records state transitions under the routing lock, observes the child stream, enforces timeout/cancel, and writes the terminal state only after the child's exit is observed.
3
- import fs from 'node:fs';
4
- import fsp from 'node:fs/promises';
5
- import path from 'node:path';
6
- import crypto from 'node:crypto';
7
- import {spawn, spawnSync} from 'node:child_process';
8
- import {fileURLToPath} from 'node:url';
9
- import {DEFAULT_POLICY, reason} from './role-dispatch-policy.mjs';
10
- import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
11
- import {withRoutingLock, readActivation} from './role-routing.mjs';
12
- import {observeCooperativeTarget} from './scope.mjs';
13
- import {resolveConfigHome, resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
14
- import {parseCompositeProfile, buildClaudeArgs, buildCodexArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
15
- import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} from './role-observe.mjs';
16
-
17
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
18
- const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
19
- const STDERR_LIMIT = 65536;
20
-
21
- /** `ps -o lstart=` start time; used with the pid to tell a live process from a reused pid. Null when ps is unavailable or the pid is gone. */
22
- export function processStartTime(pid) {
23
- if (!Number.isInteger(pid) || pid <= 0) return null;
24
- const result = spawnSync('ps', ['-o', 'lstart=', '-p', String(pid)], {encoding: 'utf8', env: {PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C'}, timeout: 5000});
25
- if (result.error || result.status !== 0) return null;
26
- return result.stdout.trim().replace(/\s+/g, ' ') || null;
27
- }
28
- export function processAlive({pid, startTime} = {}) {
29
- const current = processStartTime(pid);
30
- return current !== null && current === startTime;
31
- }
32
-
33
- /** Worktree root and git common dir for a cwd that may be a subdirectory of the worktree. */
34
- export async function resolveWorktree(cwd) {
35
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
36
- const result = spawnSync('git', ['--no-pager', 'rev-parse', '--show-toplevel'], {cwd, env: {...env, GIT_CONFIG_NOSYSTEM: '1', GIT_OPTIONAL_LOCKS: '0'}, encoding: 'utf8', timeout: 10000});
37
- if (result.error || result.status !== 0 || !result.stdout.endsWith('\n')) throw Error('Worktree root unavailable');
38
- return observeCooperativeTarget(result.stdout.slice(0, -1));
39
- }
40
- export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
41
- /** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
42
- export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
43
-
44
- /** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
45
- export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY}) {
46
- const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
47
- const requested = config.roles[lease.role], platform = requested.platform;
48
- const file = path.join(homes[platform], 'agents', `arc-routing-${lease.role.slice('arc_'.length)}.${platform === 'codex' ? 'toml' : 'md'}`);
49
- let bytes;
50
- try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
51
- if (sha256(bytes) !== lease.profileHash) throw fail('activation_unverified', 'Profile hash differs from the reserved lease');
52
- let profile, args;
53
- try {
54
- profile = parseCompositeProfile(platform, bytes);
55
- args = platform === 'claude' ? buildClaudeArgs({role: lease.role, profile, sessionId: lease.sessionId, policy}) : buildCodexArgs({role: lease.role, profile, worktree, resultPath, threadId: lease.sessionId, policy});
56
- } catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
57
- const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
58
- const expected = platform === 'claude'
59
- ? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
60
- : {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
61
- return {platform, args, argsDigest: argsDigest(args), expected, requested};
62
- }
63
-
64
- /** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
65
- export async function startSupervisor({codexHome, dispatchId, cwd, userHome, env = process.env}) {
66
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), codexHome, dispatchId, cwd, userHome], {detached: true, stdio: 'ignore', env, cwd});
67
- await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
68
- child.unref();
69
- const startTime = processStartTime(child.pid);
70
- if (startTime === null) { try { process.kill(child.pid, 'SIGKILL'); } catch { /* already gone */ } throw Error('Supervisor start time unavailable'); }
71
- return {pid: child.pid, startTime};
72
- }
73
-
74
- export async function runSupervisor(options) {
75
- const {codexHome, dispatchId, cwd, userHome, env = process.env, policy = DEFAULT_POLICY} = options;
76
- const heartbeatMs = options.heartbeatMs ?? policy.heartbeatMs, graceMs = options.graceMs ?? policy.cancelGraceMs;
77
- const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
78
- const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
79
- const startedAt = new Date().toISOString();
80
-
81
- // Lease writes retry a busy lock; the supervisor never gives up a terminal write because of a short contention.
82
- const locked = async fn => {
83
- const deadline = Date.now() + lockDeadlineMs;
84
- for (;;) {
85
- try { return await withRoutingLock(codexHome, fn, {retryMs: lockRetryMs}); } catch (error) {
86
- if (error?.code === 'ARC_ROUTING_LOCK_RELEASE' && !error.failure) return error.value;
87
- if (error?.code === 'ARC_ROUTING_LOCK_BUSY' && Date.now() < deadline) continue;
88
- throw error;
89
- }
90
- }
91
- };
92
- const context = {cwd, userHome, env};
93
- const homes = {codex: resolveConfigHome('codex', context), claude: resolveConfigHome('claude', context)};
94
- const target = await resolveWorktree(cwd);
95
- let lease = await readLease(codexHome, dispatchId);
96
- if (!lease || lease.route !== 'bridge') return;
97
- const artifactDir = segmentDirectory(target, lease.workflowId, dispatchId, lease.segment), resultFile = path.join(artifactDir, 'result.md');
98
- const mine = current => current && current.state === 'starting' && current.supervisor?.pid === process.pid;
99
- let config;
100
- const guarded = await locked(async () => {
101
- const current = await readLease(codexHome, dispatchId);
102
- if (!mine(current)) return false;
103
- lease = current;
104
- try { config = await readActivation(homes, lease.revision); } catch { config = null; }
105
- return true;
106
- });
107
- if (!guarded) return; // not the supervisor registered for this dispatch
108
-
109
- const timers = new Set();
110
- let hbBusy = false;
111
- const beat = async () => { if (hbBusy) return; hbBusy = true; try { await writeHeartbeat(codexHome, dispatchId, {at: Date.now(), pid: process.pid}); } catch { /* heartbeat loss is detected by observe */ } finally { hbBusy = false; } };
112
- await beat();
113
- timers.add(setInterval(beat, heartbeatMs));
114
-
115
- const writeRecord = async body => {
116
- const file = path.join(artifactDir, 'record.json');
117
- await fsp.writeFile(file, JSON.stringify({version: 1, dispatchId, role: lease.role, startedAt, endedAt: new Date().toISOString(), ...body}, null, 2) + '\n', {mode: 0o600});
118
- await fsp.chmod(file, 0o600);
119
- };
120
- const commit = async (state, codes, claims, extra = {}) => {
121
- await locked(async () => {
122
- const current = await readLease(codexHome, dispatchId);
123
- if (!current || TERMINAL_STATES.includes(current.state)) return;
124
- await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null});
125
- });
126
- };
127
- const earlyFailure = async (code, spawned = null) => {
128
- const claims = {...(lease.claims ?? {}), terminal: {level: 'runtime-observed', source: 'supervisor'}};
129
- await writeRecord({state: 'failed', reasons: [code], spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {})}).catch(() => {});
130
- await commit('failed', [code], claims);
131
- };
132
-
133
- let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
134
- const killGroup = signal => { if (child?.pid) { try { (options.signalGroup ?? process.kill)(-child.pid, signal); } catch { /* group already gone */ } } };
135
- const groupAlive = () => { try { process.kill(-child.pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
136
- // Terminal states are recorded only after the whole process group is observed gone: SIGKILL goes to the group after the grace period even when the leader already exited.
137
- const reapGroup = async () => {
138
- if (!child?.pid || !termAt) return true;
139
- const killAt = termAt + graceMs, giveUp = killAt + Math.max(graceMs, 500);
140
- for (;;) {
141
- if (!groupAlive()) return true;
142
- const now = Date.now();
143
- if (now >= killAt) killGroup('SIGKILL');
144
- if (now >= giveUp) return false;
145
- await sleep(25);
146
- }
147
- };
148
- try {
149
- if (config === null) return await earlyFailure('activation_unverified');
150
- const requested = config.roles[lease.role], platform = requested.platform;
151
- let invocation;
152
- try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
153
- if (invocation.argsDigest !== lease.argsDigest) return await earlyFailure('activation_unverified');
154
- const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
155
- const cli = resolveLocalCli(platform, context);
156
- if (cli.reason) return await earlyFailure(cli.reason === 'cli_not_found' ? 'Not Available' : 'execution_failed');
157
- let before;
158
- try { before = await snapshotWorktree(target.realpath); } catch { return await earlyFailure('execution_failed'); }
159
-
160
- eventsFd = fs.openSync(path.join(artifactDir, 'events.jsonl'), 'a', 0o600);
161
- // The child is a process-group leader so one signal reaches its descendants. brief goes to stdin only.
162
- child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...localCliEnvironment(cli), ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
163
- let exitResolve, exited = false;
164
- const exitPromise = new Promise(resolve => { exitResolve = resolve; });
165
- child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
166
- child.on('error', () => { exited = true; exitResolve({code: null, signal: null, spawnError: true}); });
167
- child.stdin.on('error', () => {});
168
- if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
169
- child.stdin.end(brief);
170
- const stdoutClosed = new Promise(resolve => { child.stdout.on('close', resolve); child.stdout.on('error', resolve); });
171
-
172
- const state = {init: null, initEval: null, threadId: null, codexEval: null, terminal: false, terminalError: false, resultText: undefined, messages: [], mismatch: null, internal: null};
173
- let eventsBytes = 0, eventsTruncated = false, stderrLength = 0, contextTask = null;
174
- const stderrParts = [];
175
- const terminate = why => {
176
- if (terminating) return;
177
- terminating = why; termAt = Date.now(); killGroup('SIGTERM');
178
- killTimers.push(setTimeout(() => {
179
- killGroup('SIGKILL');
180
- killTimers.push(setTimeout(() => exitResolve({code: null, signal: null, unobserved: true}), graceMs));
181
- }, graceMs));
182
- };
183
- const deadline = options.timeoutMs ?? lease.timeoutMinutes * 60000;
184
- timers.add(setTimeout(() => terminate('timeout'), deadline));
185
- let cancelBusy = false;
186
- timers.add(setInterval(async () => {
187
- if (cancelBusy || terminating || exited) return;
188
- cancelBusy = true;
189
- try { if (await cancelRequested(codexHome, dispatchId)) terminate('cancel'); } catch { /* retried on the next tick */ } finally { cancelBusy = false; }
190
- }, Math.min(heartbeatMs, 200)));
191
-
192
- const writeEvent = normalized => {
193
- if (eventsTruncated) return;
194
- const line = JSON.stringify(eventRecord(normalized)) + '\n', size = Buffer.byteLength(line);
195
- if (eventsBytes + size > eventsMax) { eventsTruncated = true; return; }
196
- fs.writeSync(eventsFd, line); eventsBytes += size;
197
- };
198
- const readContext = async () => readCodexTurnContext({codexHome: homes.codex, threadId: state.threadId, delegationNames: policy.codexDelegationCallNames});
199
- const watchContext = async () => {
200
- const limit = Date.now() + codexWaitMs;
201
- for (;;) {
202
- const context_ = await readContext();
203
- if (context_) {
204
- const evaluation = evaluateCodexContext({context: context_, expected: invocation.expected, policy});
205
- state.codexEval = evaluation;
206
- if (evaluation.reason && !state.mismatch) { state.mismatch = evaluation.reason; terminate('mismatch'); }
207
- return;
208
- }
209
- if (exited || Date.now() >= limit) return;
210
- await sleep(100);
211
- }
212
- };
213
- const handle = raw => {
214
- const normalized = platform === 'claude' ? normalizeClaudeStreamEvent(raw) : normalizeCodexStreamEvent(raw);
215
- if (!normalized) return;
216
- writeEvent(normalized);
217
- if (normalized.kind === 'init') {
218
- state.init = normalized; state.initEval = evaluateClaudeInit({init: normalized, expected: invocation.expected});
219
- if (state.initEval.reason && !state.mismatch) { state.mismatch = state.initEval.reason; terminate('mismatch'); }
220
- } else if (normalized.kind === 'result') {
221
- state.terminal = true; state.terminalError = normalized.isError === true; state.resultText = normalized.resultText;
222
- if (state.terminalError && typeof normalized.resultText === 'string') state.messages.push(normalized.resultText);
223
- } else if (normalized.kind === 'thread') {
224
- if (normalized.threadId && !state.threadId) { state.threadId = normalized.threadId; contextTask = watchContext().catch(() => {}); }
225
- } else if (normalized.kind === 'turn_completed') state.terminal = true;
226
- else if (normalized.kind === 'turn_failed') { state.terminal = true; state.terminalError = true; if (normalized.message) state.messages.push(normalized.message); }
227
- else if (normalized.kind === 'warning' && normalized.message) state.messages.push(normalized.message);
228
- };
229
- const parser = createLineParser(raw => { try { handle(raw); } catch { /* an unexpected event shape never stops observation */ } });
230
- child.stdout.on('data', chunk => { try { parser.push(chunk); } catch { /* keep the supervisor alive */ } });
231
- child.stderr.on('data', chunk => { if (stderrLength < STDERR_LIMIT) { stderrParts.push(chunk); stderrLength += chunk.length; } });
232
-
233
- // Output listeners must be attached before any await: Node drains and discards unread stdio once the child exits.
234
- try {
235
- const startTime = child.pid ? processStartTime(child.pid) ?? 'unavailable' : null;
236
- if (startTime === null) throw Error('Child did not start');
237
- await locked(async () => {
238
- const current = await readLease(codexHome, dispatchId);
239
- if (!mine(current)) throw Error('Lease changed before the child was recorded');
240
- await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}});
241
- });
242
- } catch { state.internal = 'execution_failed'; terminate('internal'); }
243
-
244
-
245
- let exit = await exitPromise;
246
- // A cancel request whose own SIGTERM stopped the child before the marker poll ran still counts as a cancel, and the group is reaped the same way.
247
- if (!terminating && !exit.unobserved && (exit.signal || !state.terminal) && await cancelRequested(codexHome, dispatchId)) { terminating = 'cancel'; termAt = Date.now(); }
248
- // A leader that exited on its own may leave descendants in the process group: they are stopped (SIGTERM, grace, SIGKILL) before the post-run snapshot is taken.
249
- let orphanGroupReaped = false;
250
- if (!termAt && !exit.unobserved && child?.pid && groupAlive()) { orphanGroupReaped = true; termAt = Date.now(); killGroup('SIGTERM'); }
251
- if (termAt && !exit.unobserved && !await reapGroup()) exit = {code: null, signal: null, unobserved: true};
252
- await Promise.race([stdoutClosed, sleep(1000)]);
253
- parser.end();
254
- if (contextTask) await contextTask;
255
- for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
256
- for (const timer of killTimers) clearTimeout(timer);
257
- timers.clear(); killTimers = [];
258
- fs.closeSync(eventsFd); eventsFd = null;
259
-
260
- if (exit.unobserved) {
261
- // The child was signalled but its exit was never observed: the slot stays occupied.
262
- const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
263
- await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow}).catch(() => {});
264
- await locked(async () => {
265
- const current = await readLease(codexHome, dispatchId);
266
- if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)});
267
- });
268
- return;
269
- }
270
-
271
- let after = null;
272
- try { after = await snapshotWorktree(target.realpath); } catch { after = null; }
273
- const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false};
274
- const codes = [];
275
- if (state.mismatch) codes.push(state.mismatch);
276
- if (state.internal) codes.push(state.internal);
277
- let claims, effortMismatch = false;
278
- const terminalClaim = {level: 'runtime-observed', source: 'supervisor-exit', observed: {exitCode: exit.code, signal: exit.signal}};
279
- let sessionId = lease.sessionId;
280
- if (platform === 'claude') {
281
- const evaluation = state.initEval ?? evaluateClaudeInit({init: null, expected: invocation.expected});
282
- const observed = await readClaudeTranscriptEffort({claudeHome: homes.claude, sessionId: state.init?.sessionId});
283
- const effort = observed === null ? {level: 'unverified', source: 'none', requested: requested.effort, observed: null, label: 'model_effort_unverified'}
284
- : {level: observed === requested.effort ? 'runtime-observed' : 'unverified', source: 'claude-transcript', requested: requested.effort, observed};
285
- effortMismatch = observed !== null && observed !== requested.effort;
286
- claims = {...evaluation.claims, effort, terminal: terminalClaim};
287
- sessionId = state.init?.sessionId ?? sessionId;
288
- } else {
289
- let finalContext = null;
290
- if (state.threadId) finalContext = await readContext().catch(() => null);
291
- const evaluation = finalContext ? evaluateCodexContext({context: finalContext, expected: invocation.expected, policy}) : state.codexEval ?? evaluateCodexContext({context: null, expected: invocation.expected, policy});
292
- if (evaluation.reason && !codes.includes(evaluation.reason)) codes.push(evaluation.reason);
293
- claims = {identity: state.threadId ? {level: 'runtime-observed', source: 'codex-stream-thread', observed: state.threadId} : {level: 'unverified', source: 'none'}, ...evaluation.claims, terminal: terminalClaim};
294
- sessionId = state.threadId ?? sessionId;
295
- }
296
- if (effortMismatch) codes.push('model_effort_mismatch');
297
- if (violations.reason) codes.push(violations.reason);
298
- if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
299
- else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
300
- if (terminating === 'timeout') codes.push('timeout');
301
-
302
- let resultPath = null;
303
- if (platform === 'claude') {
304
- if (state.terminal && !state.terminalError && typeof state.resultText === 'string') { await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); resultPath = resultFile; }
305
- } else if (fs.existsSync(resultFile)) resultPath = resultFile;
306
- if (resultPath) await fsp.chmod(resultPath, 0o600);
307
-
308
- let finalState = 'failed';
309
- const observedSession = platform === 'claude' ? state.init?.sessionId : state.threadId;
310
- if (!codes.length && terminating === 'cancel') finalState = 'cancelled';
311
- else if (!codes.length) {
312
- const failure = classifyFailure({exitCode: exit.code, signal: exit.signal, terminal: state.terminal, terminalError: state.terminalError, messages: [...state.messages, Buffer.concat(stderrParts).toString('utf8')]});
313
- if (failure) codes.push(failure);
314
- else if (!resultPath) codes.push('invalid_output');
315
- finalState = codes.length ? 'failed' : 'completed';
316
- if (finalState === 'completed' && !observedSession) {
317
- // Without a session id the execution identity cannot be tied to this dispatch: the slot stays occupied.
318
- finalState = 'unknown'; codes.push('execution_identity_unverified');
319
- claims.identity = {level: 'unverified', source: 'none'};
320
- }
321
- }
322
- if (lease.sessionId && observedSession && observedSession !== lease.sessionId && finalState !== 'cancelled') {
323
- // A resumed segment must continue the recorded session; a different observed id leaves the slot occupied.
324
- finalState = 'unknown'; sessionId = lease.sessionId; if (!codes.includes('execution_identity_unverified')) codes.push('execution_identity_unverified');
325
- claims.identity = {level: 'unverified', source: 'none'};
326
- }
327
- if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
328
- await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath});
329
- await commit(finalState, codes, claims, {sessionId, resultPath});
330
- } catch {
331
- // Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
332
- const spawnedPid = child?.pid ?? null;
333
- let stopped = true;
334
- if (spawnedPid) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
335
- for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
336
- for (const timer of killTimers) clearTimeout(timer);
337
- if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
338
- if (stopped) await earlyFailure('execution_failed', spawnedPid).catch(() => {});
339
- else {
340
- const codes = ['execution_failed', 'terminal_state_unverified'];
341
- await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
342
- await locked(async () => {
343
- const current = await readLease(codexHome, dispatchId);
344
- if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)});
345
- }).catch(() => {});
346
- }
347
- } finally {
348
- for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
349
- }
350
- }
351
-
352
- const isMain = () => { try { return Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; } };
353
- if (isMain()) {
354
- const [, , codexHome, dispatchId, cwd, userHome] = process.argv;
355
- runSupervisor({codexHome, dispatchId, cwd, userHome, env: process.env}).then(() => process.exit(0), () => process.exit(1));
356
- }