@yunhozz/arc 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/MANIFEST.sha256 +105 -147
  2. package/README.md +3 -3
  3. package/claude/agents/arc-implementer.md +4 -4
  4. package/claude/agents/arc-planner.md +5 -5
  5. package/claude/agents/arc-qa.md +4 -4
  6. package/claude/agents/arc-reviewer.md +4 -4
  7. package/claude/agents/arc-scouter.md +5 -5
  8. package/claude/skill/SKILL.md +13 -8
  9. package/claude/skill/references/arc-visual-companion.md +5 -5
  10. package/claude/skill/references/commit.md +8 -8
  11. package/claude/skill/references/coordination.md +23 -21
  12. package/claude/skill/references/git-recovery.md +9 -4
  13. package/claude/skill/references/handoff-prep.md +13 -15
  14. package/claude/skill/references/handoff.md +22 -22
  15. package/claude/skill/references/limits.md +2 -2
  16. package/claude/skill/references/planning.md +20 -15
  17. package/claude/skill/references/verification.md +9 -9
  18. package/claude/skill/references/worktree-creation.md +14 -0
  19. package/codex/agents/arc-implementer.toml +4 -4
  20. package/codex/agents/arc-planner.toml +4 -4
  21. package/codex/agents/arc-qa.toml +4 -4
  22. package/codex/agents/arc-reviewer.toml +4 -4
  23. package/codex/agents/arc-scouter.toml +4 -4
  24. package/codex/skill/SKILL.md +12 -8
  25. package/codex/skill/references/arc-visual-companion.md +2 -2
  26. package/codex/skill/references/commit.md +8 -8
  27. package/codex/skill/references/coordination.md +22 -20
  28. package/codex/skill/references/git-recovery.md +5 -9
  29. package/codex/skill/references/handoff-prep.md +9 -9
  30. package/codex/skill/references/handoff.md +20 -20
  31. package/codex/skill/references/limits.md +2 -2
  32. package/codex/skill/references/planning.md +15 -15
  33. package/codex/skill/references/verification.md +10 -10
  34. package/codex/skill/references/worktree-creation.md +20 -0
  35. package/lib/installer/global-config.mjs +2 -2
  36. package/lib/installer/manifest.mjs +10 -9
  37. package/lib/installer/package-references.mjs +2 -2
  38. package/lib/installer/plan.mjs +3 -1
  39. package/lib/installer/skill-sources.mjs +23 -0
  40. package/lib/installer/superpowers.mjs +5 -5
  41. package/lib/policy/role-policy.json +10 -10
  42. package/lib/prompts/agent-fragments.json +16 -16
  43. package/lib/runtime/bootstrap.mjs +1 -1
  44. package/lib/runtime/local-cli.mjs +10 -20
  45. package/lib/runtime/role-bridge.mjs +2 -4
  46. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  47. package/lib/runtime/role-routing.mjs +1 -2
  48. package/lib/watch/dispatch.mjs +10 -2
  49. package/lib/watch/git.mjs +4 -2
  50. package/lib/watch/index.mjs +16 -8
  51. package/lib/watch/model.mjs +8 -4
  52. package/lib/watch/normalize-claude.mjs +89 -7
  53. package/lib/watch/normalize-codex.mjs +15 -11
  54. package/lib/watch/render.mjs +73 -19
  55. package/lib/watch/scope.mjs +5 -5
  56. package/lib/watch/watcher.mjs +110 -10
  57. package/package.json +2 -1
  58. package/scripts/check-installer-parity.mjs +3 -1
  59. package/scripts/update-manifest.mjs +1 -1
  60. package/scripts/update-runtime-assets.mjs +1 -1
  61. package/{codex → shared}/skill/references/handoff-worktree.md +21 -20
  62. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  63. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  64. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  65. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  66. package/{claude → shared}/skill/runtime/role-policy.json +10 -10
  67. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  68. package/claude/skill/runtime/bootstrap.mjs +0 -38
  69. package/claude/skill/runtime/local-cli.mjs +0 -248
  70. package/claude/skill/runtime/role-bridge.mjs +0 -227
  71. package/codex/skill/references/brainstorming.md +0 -316
  72. package/codex/skill/references/builder-check-prompt.md +0 -23
  73. package/codex/skill/references/scripts/frame-template.html +0 -213
  74. package/codex/skill/references/scripts/helper.js +0 -167
  75. package/codex/skill/references/scripts/server.cjs +0 -723
  76. package/codex/skill/references/scripts/start-server.sh +0 -216
  77. package/codex/skill/references/scripts/stop-server.sh +0 -120
  78. package/codex/skill/references/superpowers-LICENSE +0 -21
  79. package/codex/skill/references/superpowers-provenance.json +0 -26
  80. package/codex/skill/references/test-driven-development.md +0 -330
  81. package/codex/skill/references/visual-companion.md +0 -299
  82. package/codex/skill/references/writing-good-tests.md +0 -198
  83. package/codex/skill/references/writing-plans.md +0 -204
  84. package/codex/skill/runtime/acceptance.mjs +0 -68
  85. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  86. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  87. package/codex/skill/runtime/assignment.mjs +0 -42
  88. package/codex/skill/runtime/capabilities.mjs +0 -44
  89. package/codex/skill/runtime/cli.mjs +0 -8
  90. package/codex/skill/runtime/command.mjs +0 -38
  91. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  92. package/codex/skill/runtime/cooperative.mjs +0 -239
  93. package/codex/skill/runtime/evaluate.mjs +0 -331
  94. package/codex/skill/runtime/external.mjs +0 -51
  95. package/codex/skill/runtime/gate.mjs +0 -71
  96. package/codex/skill/runtime/git-evidence.mjs +0 -258
  97. package/codex/skill/runtime/git-query.mjs +0 -88
  98. package/codex/skill/runtime/identity.mjs +0 -49
  99. package/codex/skill/runtime/operations.mjs +0 -6
  100. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  101. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  102. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  103. package/codex/skill/runtime/role-observe.mjs +0 -299
  104. package/codex/skill/runtime/role-policy.json +0 -654
  105. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  106. package/codex/skill/runtime/role-routing.mjs +0 -233
  107. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  108. package/codex/skill/runtime/schema.mjs +0 -98
  109. package/codex/skill/runtime/scope.mjs +0 -36
  110. package/codex/skill/runtime/store.mjs +0 -94
  111. package/codex/skill/runtime/target-preparation.mjs +0 -110
  112. package/codex/skill/runtime/verification.mjs +0 -125
  113. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  114. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  115. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  116. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  117. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  118. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  119. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  120. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  121. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  122. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  123. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  124. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  125. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  126. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  127. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  128. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  129. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  130. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  131. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  132. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  133. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  134. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  135. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  136. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  137. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  138. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  139. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  140. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  141. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  142. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  143. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  144. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  145. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  146. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  147. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  148. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  149. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  150. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  151. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,38 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import crypto from 'node:crypto';
4
- import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
5
- import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath} from './scope.mjs';
6
- import {saveDurableState} from './store.mjs';
7
- export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
- 'cli.mjs','command.mjs','bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
9
- 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs','target-preparation.mjs',
10
- 'local-cli.mjs','role-routing-config.mjs','role-routing.mjs','role-bridge.mjs',
11
- 'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs'
12
- ]);
13
- export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
14
- export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
15
- return {decision,ruleIds:[ruleId],workflowId,taskId:input?.taskId??null,requestId:input?.requestId??null,revision:state?.revision??0,coverage:cooperativeCoverage(),requiredEvidence:[],nextActions:[],persisted,...extra};
16
- }
17
- export async function cooperativeVersions(){
18
- const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
19
- let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
20
- const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
21
- return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
22
- }
23
- export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
24
- validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
25
- if(input.mode!=='plan')return commandResult({workflowId,input,decision:'hold',ruleId:'cooperative.unsupported'});
26
- const target=await validateObservedTarget(cwd,await observe(cwd));const statePath=await workflowStatePath(target,workflowId);
27
- const parent=path.dirname(statePath);await fs.mkdir(parent,{recursive:true,mode:0o700});await inspectPath(parent,{directory:true});
28
- const lockPath=statePath+'.lock';let lock;
29
- try{
30
- lock=await fs.open(lockPath,'wx',0o600);await inspectPath(statePath,{missing:true});
31
- const state={schemaVersion:1,workflowKind:'cooperative',contractVersion:1,workflowId,revision:0,mode:'plan',coverage:cooperativeCoverage(),versions:await cooperativeVersions(),target,targetVersion:1,scopeVersion:0};
32
- for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])state[key]=[];
33
- state.plannerLedger={version:1,stages:[]};
34
- state.actors.push({actor:input.actor,source:'operator-attested'});state.selections.push({...input.selection,actor:input.actor,source:'operator-attested',targetVersion:1});
35
- state.audit.push({command:'init',revision:0,source:'operator-attested',actor:input.actor});validateCooperativeState(state);
36
- await saveDurableState({statePath,state,create:true,storage});return commandResult({workflowId,state,input,persisted:true,ruleId:'cooperative.initialized'});
37
- }finally{if(lock){await lock.close();await fs.unlink(lockPath);}}
38
- }
@@ -1,248 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs';
3
- import { StringDecoder } from 'node:string_decoder';
4
- import { spawn } from 'node:child_process';
5
- import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
-
7
- const environments = new WeakMap();
8
- export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
9
- if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
10
- if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
11
- userHome = path.resolve(userHome);
12
- if (!env || typeof env !== 'object') throw Error('env must be an environment object');
13
- const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
14
- let home;
15
- if (platform === 'codex') {
16
- const raw = env.CODEX_HOME;
17
- if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
18
- const expanded = expand(raw ?? path.join(userHome, '.codex'));
19
- if (path.isAbsolute(expanded)) home = path.resolve(expanded);
20
- else { const base = cwd ?? process.cwd(); if (typeof base !== 'string' || !path.isAbsolute(base)) throw Error('cwd must be absolute for relative CODEX_HOME'); home = path.resolve(base, expanded); }
21
- } else {
22
- home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
23
- if (raw !== undefined && (typeof raw !== 'string' || !raw.trim() || !path.isAbsolute(expand(raw)) || path.resolve(expand(raw)) !== home)) throw Error('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');
24
- }
25
- if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
26
- return home;
27
- }
28
- export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
29
- if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
30
- let home;
31
- try {
32
- if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
33
- home = resolveConfigHome(platform, { cwd, userHome, env });
34
- } catch { return { platform, reason: 'invalid_context' }; }
35
- const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
36
- let executable;
37
- for (const dir of dirs) {
38
- const candidate = path.resolve(cwd, dir || '.', platform);
39
- try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
40
- }
41
- if (!executable) return { platform, reason: 'cli_not_found' };
42
- const context = Object.freeze({ platform, executable, cwd, configHome: home });
43
- environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
44
- return context;
45
- }
46
- export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
47
- /** Checks Codex authentication with refresh; only a token-presence boolean survives parsing. */
48
- export async function probeCodexAuthStatus(context, { signal, timeoutMs = 10000 } = {}) {
49
- const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
50
- if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
51
- if (signal?.aborted) return result('unknown', 'aborted');
52
- let child;
53
- try { child = spawn(context.executable, ['app-server'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['pipe', 'pipe', 'pipe'], shell: false }); }
54
- catch { return result('unknown', 'cli_execution_error'); }
55
- let closed = false, failure, pending, nextId = 0, buffer = '', outputBytes = 0;
56
- const decoder = new StringDecoder('utf8');
57
- let resolveClosed;
58
- const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
59
- const fail = reason => { failure ??= reason; if (pending) { const {reject} = pending; pending = null; reject(); } };
60
- const onClose = () => { closed = true; resolveClosed(); fail('cli_execution_error'); };
61
- const onError = () => fail('cli_execution_error');
62
- const onAbort = () => fail('aborted');
63
- const countOutput = chunk => { outputBytes += chunk.length; if (outputBytes > 1048576) { fail('invalid_response'); return false; } return !failure; };
64
- const classify = value => {
65
- if (!value || typeof value !== 'object' || Array.isArray(value) || !(value.requiresOpenaiAuth === null || typeof value.requiresOpenaiAuth === 'boolean') ||
66
- !(value.authMethod === null || typeof value.authMethod === 'string') ||
67
- !(value.authToken === null || typeof value.authToken === 'string')) return result('unknown', 'invalid_response');
68
- const hasToken = typeof value.authToken === 'string' && value.authToken.length > 0;
69
- if (value.requiresOpenaiAuth === false || typeof value.authMethod === 'string' && hasToken) return result('authenticated');
70
- if (value.authMethod === null) return result('unauthorized', 'not_logged_in');
71
- if (value.authToken !== null) return result('unknown', 'invalid_response');
72
- if (value.authMethod === 'chatgpt') return result('unauthorized', 'token_rejected');
73
- if (['headers', 'agentIdentity', 'personalAccessToken'].includes(value.authMethod)) return result('authenticated');
74
- return result('unknown', 'auth_unverified');
75
- };
76
- const onData = chunk => {
77
- if (!countOutput(chunk)) { buffer = ''; return; }
78
- buffer += decoder.write(chunk);
79
- let newline;
80
- while (!failure && (newline = buffer.indexOf('\n')) !== -1) {
81
- let line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
82
- if (!line.trim()) continue;
83
- let message;
84
- try { message = JSON.parse(line); } catch { line = ''; buffer = ''; fail('invalid_response'); return; }
85
- line = '';
86
- if (message && typeof message === 'object' && !Array.isArray(message) &&
87
- (Object.hasOwn(message, 'method') || !Object.hasOwn(message, 'id'))) { message = null; continue; }
88
- if (!message || !pending || message.id !== pending.id) { message = null; fail('invalid_response'); return; }
89
- if (Object.hasOwn(message, 'error')) { message = null; fail('status_command_failed'); return; }
90
- if (!Object.hasOwn(message, 'result')) { message = null; fail('invalid_response'); return; }
91
- const value = pending.method === 'initialize'
92
- ? (message.result && typeof message.result === 'object' && !Array.isArray(message.result) && typeof message.result.userAgent === 'string' && message.result.userAgent.length > 0 ? true : false)
93
- : classify(message.result);
94
- message = null;
95
- const {resolve} = pending; pending = null; resolve(value);
96
- }
97
- };
98
- const onStderr = chunk => { countOutput(chunk); };
99
- child.on('close', onClose); child.on('error', onError);
100
- child.stdout.on('data', onData); child.stderr.on('data', onStderr);
101
- for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', onError);
102
- signal?.addEventListener('abort', onAbort, { once: true });
103
- if (signal?.aborted) onAbort();
104
- const timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
105
- const send = message => { if (failure || closed) throw new Error('Codex authentication unavailable'); child.stdin.write(JSON.stringify(message) + '\n'); };
106
- const request = (method, params) => new Promise((resolve, reject) => {
107
- if (failure || closed) { reject(); return; }
108
- const id = ++nextId; pending = {id, method, resolve, reject};
109
- try { send({id, method, params}); } catch { fail('cli_execution_error'); }
110
- });
111
- let authentication;
112
- try {
113
- if (!await request('initialize', {clientInfo: {name: 'arc', title: 'ARC', version: '1.0.0'}})) fail('invalid_response');
114
- send({method: 'initialized', params: {}});
115
- authentication = await request('getAuthStatus', {includeToken: true, refreshToken: true});
116
- if (failure) authentication = result('unknown', failure);
117
- } catch { authentication = result('unknown', failure ?? 'cli_execution_error'); }
118
- finally {
119
- clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
120
- buffer = ''; pending = null;
121
- try { child.stdin.end(); } catch { /* cleanup only */ }
122
- if (!closed) { try { child.kill('SIGTERM'); } catch { /* still wait for close */ } }
123
- const wait = async ms => {
124
- if (closed) return true;
125
- let timerId;
126
- const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
127
- clearTimeout(timerId); return done;
128
- };
129
- if (!await wait(1000)) {
130
- try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
131
- if (!await wait(1000)) authentication = result('unknown', 'cli_execution_error');
132
- }
133
- child.stdout.removeListener('data', onData); child.stderr.removeListener('data', onStderr);
134
- child.removeListener('close', onClose);
135
- // Keep error guards on streams until destruction, including late pipe errors.
136
- for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
137
- }
138
- return authentication;
139
- }
140
- /** Checks local Codex login state without starting app-server or refreshing credentials. */
141
- export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000 } = {}) {
142
- const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
143
- if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
144
- if (signal?.aborted) return result('unknown', 'aborted');
145
- let child;
146
- try { child = spawn(context.executable, ['login', 'status'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
147
- catch { return result('unknown', 'status_command_failed'); }
148
- let closed = false, stderr = '', outputBytes = 0, timer, resolveClosed;
149
- const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
150
- let finish;
151
- const authentication = new Promise(resolve => { finish = resolve; });
152
- const fail = reason => finish(result('unknown', reason));
153
- const onError = () => fail('status_command_failed');
154
- const onAbort = () => fail('aborted');
155
- const countOutput = chunk => {
156
- outputBytes += chunk.length;
157
- if (outputBytes > 65536) { stderr = ''; fail('status_command_failed'); return false; }
158
- return true;
159
- };
160
- const onStdout = chunk => { countOutput(chunk); };
161
- const onStderr = chunk => { if (countOutput(chunk)) stderr += chunk.toString(); };
162
- const onClose = (code, exitSignal) => {
163
- closed = true; resolveClosed();
164
- finish(exitSignal ? result('unknown', 'status_command_failed') : code === 0 ? result('authenticated') :
165
- code === 1 && stderr.trim() === 'Not logged in' ? result('unauthorized', 'not_logged_in') : result('unknown', 'status_command_failed'));
166
- };
167
- child.on('error', onError); child.on('close', onClose);
168
- child.stdout.on('data', onStdout); child.stderr.on('data', onStderr);
169
- for (const stream of [child.stdout, child.stderr]) stream.on('error', onError);
170
- signal?.addEventListener('abort', onAbort, { once: true });
171
- timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
172
- if (signal?.aborted) onAbort();
173
- const value = await authentication;
174
- clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
175
- if (!closed) { try { child.kill('SIGTERM'); } catch { /* bounded cleanup */ } }
176
- const wait = async ms => {
177
- if (closed) return true;
178
- let timerId;
179
- const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
180
- clearTimeout(timerId); return done;
181
- };
182
- if (!await wait(1000)) {
183
- try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
184
- await wait(1000);
185
- }
186
- child.stdout.removeListener('data', onStdout); child.stderr.removeListener('data', onStderr);
187
- child.removeListener('close', onClose);
188
- child.stdout.destroy(); child.stderr.destroy();
189
- return value;
190
- }
191
- export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
192
- const platform = context?.platform;
193
- const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
194
- if (platform !== 'claude') return result('unknown', 'invalid_context');
195
- if (!environments.has(context)) return result('unknown', context?.reason ?? 'invalid_context');
196
- if (signal?.aborted) return result('unknown', 'aborted');
197
- return new Promise(resolve => {
198
- let child, output = '', stderr = '', overflow = false, done = false, reason;
199
- const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
200
- const abort = () => { reason = 'aborted'; child?.kill(); finish(result('unknown', reason)); };
201
- const timer = setTimeout(() => { reason = 'timeout'; child?.kill(); finish(result('unknown', reason)); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
202
- signal?.addEventListener('abort', abort, { once: true });
203
- try { child = spawn(context.executable, ['auth', 'status', '--json'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
204
- catch { finish(result('unknown', 'cli_execution_error')); return; }
205
- child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
206
- child.stderr.on('data', chunk => { if (stderr.length + chunk.length > 65536) overflow = true; else if (!overflow) stderr += chunk.toString(); });
207
- child.on('error', () => finish(result('unknown', 'cli_execution_error')));
208
- child.on('close', (code, exitSignal) => {
209
- if (exitSignal || overflow) return finish(result('unknown', overflow ? 'invalid_response' : 'cli_execution_error'));
210
- let parsed; try { parsed = JSON.parse(output); } catch { return finish(result('unknown', 'invalid_response')); }
211
- if (parsed?.loggedIn === true && code === 0) return finish(result('authenticated'));
212
- if (parsed?.loggedIn === false && code === 1) return finish(result('unauthorized', 'not_logged_in'));
213
- finish(result('unknown', 'status_mismatch'));
214
- });
215
- if (signal?.aborted) abort();
216
- });
217
- }
218
- export function compareVersions(a, b) {
219
- const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
- return 0;
222
- }
223
- /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
- export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
- const platform = context?.platform;
226
- const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
- if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
228
- return new Promise(resolve => {
229
- let child, output = '', overflow = false, done = false;
230
- const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
- const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
- const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
- signal?.addEventListener('abort', abort, { once: true });
234
- try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
- catch { finish(result(null, false, 'cli_execution_error')); return; }
236
- child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
- child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
- child.on('error', () => finish(result(null, false, 'cli_execution_error')));
239
- child.on('close', (code, exitSignal) => {
240
- if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
241
- const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
- if (!version) return finish(result(null, false, 'version_unparsed'));
243
- const range = policy?.supportedVersions?.[platform];
244
- const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
- finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
246
- });
247
- });
248
- }
@@ -1,227 +0,0 @@
1
- // A caller's JSON, local hook or child process ID cannot authorize execution.
2
- // run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
3
- import fsp from 'node:fs/promises';
4
- 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, versionOf} from './role-routing.mjs';
8
- import {resolveConfigHome} from './local-cli.mjs';
9
- import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
10
-
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
-
13
- const ID=/^[A-Za-z0-9._-]{1,128}$/;
14
- const NATIVE_EVENTS={started:[['reserved'],'running'],completed:[['running'],'completed'],failed:[['running'],'failed'],cancelled:[['running','reserved'],'cancelled']};
15
- 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;
18
- const validContext=context=>{const host=hostOf(context);return Boolean(host&&environmentOf(context,host)&&typeof context.workflowId==='string'&&context.workflowId&&typeof context.cwd==='string');};
19
- 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
- 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
- /** 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};
26
- }
27
- const homesOf=context=>({codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)});
28
- const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
29
- 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
- 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';};
31
-
32
- /** Starts the detached supervisor for a reserved bridge lease; the supervisor, not this function, spawns the child. */
33
- export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
34
- if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
35
- const bytes=Buffer.byteLength(brief,'utf8');
36
- 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');}
39
- try{
40
- await withRoutingLock(homes.codex,async()=>{
41
- const lease=await readLease(homes.codex,dispatchId);
42
- 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;}
44
- let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
45
- const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
46
- 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
- await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
48
- await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
49
- let supervisor;
50
- try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
51
- 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');
54
- },{retryMs:policy.lockRetryMs});
55
- }catch(error){
56
- if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
57
- else return hold(context,dispatchId,classifyLock(error),error);
58
- }
59
- if(residual)result.residualPaths=residual;
60
- return result;
61
- }
62
-
63
- const TEXT=/^[^\p{Cc}]{1,256}$/u;
64
- async function markLostIfDue(homes,lease,{now,lostMs,policy}){
65
- if(!['starting','running'].includes(lease.state)||!lease.supervisor)return lease;
66
- const heartbeat=await readHeartbeat(homes.codex,lease.dispatchId);
67
- const lastSeen=Math.max(heartbeat?.at??0,Date.parse(lease.updatedAt)||0);
68
- if(now-lastSeen<=lostMs||processAlive(lease.supervisor))return lease;
69
- try{
70
- return await withRoutingLock(homes.codex,async()=>{
71
- const current=await readLease(homes.codex,lease.dispatchId);
72
- 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});
74
- },{retryMs:policy.lockRetryMs});
75
- }catch{return lease;}// a busy lock only delays the transition; the next observe retries it
76
- }
77
- async function recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now,policy}){
78
- let result;
79
- try{
80
- await withRoutingLock(homes.codex,async()=>{
81
- const lease=await readLease(homes.codex,dispatchId);
82
- const rule=NATIVE_EVENTS[event];
83
- 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
- const attested={level:'operator-attested',source:'orchestrator'};
85
- 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);
88
- },{retryMs:policy.lockRetryMs});
89
- }catch(error){return hold(context,dispatchId,classifyLock(error),error);}
90
- return result;
91
- }
92
-
93
- /** bridge: waits up to waitMs for a terminal or unknown state and marks a lost supervisor unknown. native: records operator events. */
94
- export async function recordRoleObservation({context,dispatchId,waitMs,event,nativeAgentId,now,lostMs,pollMs=500,policy=DEFAULT_POLICY}={}){
95
- if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
96
- if(waitMs!==undefined&&(!Number.isInteger(waitMs)||waitMs<0||waitMs>policy.observeMaxWaitMs))return blank(context,dispatchId,'deny','invalid_request');
97
- if(event!==undefined&&!Object.hasOwn(NATIVE_EVENTS,event))return blank(context,dispatchId,'deny','invalid_request');
98
- 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');}
101
- if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform)return blank(context,dispatchId,'deny','invalid_request');
102
- if(lease.route==='native'){
103
- 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});
105
- }
106
- if(event!==undefined||nativeAgentId!==undefined)return blank(context,dispatchId,'deny','invalid_request');
107
- const end=Date.now()+(waitMs??0),lost=lostMs??policy.supervisorLostMs;
108
- try{
109
- 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);
112
- await sleep(Math.min(pollMs,Math.max(0,end-Date.now())));
113
- lease=await readLease(homes.codex,dispatchId)??lease;
114
- }
115
- }catch{return blank(context,dispatchId,'hold','activation_unverified');}
116
- }
117
-
118
- /** 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}={}){
120
- if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
121
- const bytes=Buffer.byteLength(brief,'utf8');
122
- 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');}
125
- try{
126
- await withRoutingLock(homes.codex,async()=>{
127
- const lease=await readLease(homes.codex,dispatchId);
128
- 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;}
129
- if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
130
- let config;
131
- try{config=await readActivation(homes,lease.revision);}
132
- catch{
133
- let active=null;try{active=await readRevision(homes);}catch{/* unreadable activation stays unverified */}
134
- result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
135
- }
136
- const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
137
- const {cli,authentication}=await authenticate(platform,context,policy);
138
- if(authentication.status!=='Available')codes.add(authentication.status);
139
- const version=await versionOf(cli,policy);
140
- if(cli&&!version.supported)codes.add('permission_scope_unverified');
141
- for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
142
- for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
143
- // 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.
144
- let limits;try{limits=readHostLimits(homes[context.hostPlatform]);}catch{codes.add('activation_unverified');}
145
- 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');
146
- if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
147
- let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
148
- const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
149
- 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;}
150
- await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
151
- await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
152
- await clearCancel(homes.codex,dispatchId);
153
- let supervisor;
154
- try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
155
- catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
156
- const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
157
- const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now});
158
- result={...fromLease(next,'allow'),segment};
159
- },{retryMs:policy.lockRetryMs});
160
- }catch(error){
161
- if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
162
- else return hold(context,dispatchId,classifyLock(error),error);
163
- }
164
- if(residual)result.residualPaths=residual;
165
- return result;
166
- }
167
-
168
- const groupExists=pid=>{try{process.kill(-pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
169
- const pidExists=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
170
- const signalGroup=(pid,signal)=>{try{process.kill(-pid,signal);}catch{/* group already gone */}};
171
- /** 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. */
172
- export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),policy=DEFAULT_POLICY}={}){
173
- if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
174
- let homes,result,direct=null,residual;
175
- try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
176
- const graceMs=policy.cancelGraceMs;
177
- try{
178
- await withRoutingLock(homes.codex,async()=>{
179
- const lease=await readLease(homes.codex,dispatchId);
180
- if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform){result=blank(context,dispatchId,'deny','invalid_request');return;}
181
- if(lease.route==='native'){
182
- // A native lease has no child: only a reserved one is cancelled here (under the lock); started native dispatches are closed with observe events.
183
- if(lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
184
- const claims={...lease.claims,terminal:{level:'operator-attested',source:'orchestrator',observed:'cancelled'}};
185
- result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',claims,reasons:[]},{now}),'allow');return;
186
- }
187
- if(TERMINAL_STATES.includes(lease.state)){result=fromLease(lease,'allow');return;}
188
- if(lease.state==='reserved'){result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',reasons:[]},{now}),'allow');return;}
189
- const supervised=['starting','running'].includes(lease.state)&&lease.supervisor&&processAlive(lease.supervisor);
190
- if(supervised){
191
- await requestCancel(homes.codex,dispatchId);
192
- if(lease.child&&processAlive(lease.child))signalGroup(lease.child.pid,'SIGTERM');
193
- result={...fromLease(lease,'allow'),routeStatus:'cancelling'};return;
194
- }
195
- if(lease.child&&processAlive(lease.child)){signalGroup(lease.child.pid,'SIGTERM');direct={lease,identified:true};}
196
- else if(lease.child&&!groupExists(lease.child.pid)&&!pidExists(lease.child.pid))direct={lease,identified:false};
197
- else result=fromLease(lease,'hold');
198
- },{retryMs:policy.lockRetryMs});
199
- }catch(error){
200
- if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&(result||direct)){residual=residualOf(error);}
201
- else return hold(context,dispatchId,classifyLock(error),error);
202
- }
203
- if(direct){
204
- const pid=direct.lease.child.pid,begin=Date.now();let killed=false,gone=!groupExists(pid);
205
- while(!gone&&Date.now()<begin+2*graceMs){
206
- if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
207
- await sleep(25);gone=!groupExists(pid);
208
- }
209
- if(!gone)result=fromLease(direct.lease,'hold');
210
- else{
211
- try{
212
- await withRoutingLock(homes.codex,async()=>{
213
- const current=await readLease(homes.codex,dispatchId);
214
- if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?fromLease(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
215
- const claims={...(current.claims??{}),terminal:{level:'runtime-observed',source:'cancel-group-gone',observed:{pid}}};
216
- // The recorded reasons (for example terminal_state_unverified) stay on the cancelled lease.
217
- result=fromLease(await writeLease(homes.codex,{...current,state:'cancelled',claims},{now:Date.now()}),'allow');
218
- },{retryMs:policy.lockRetryMs});
219
- }catch(error){
220
- if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
221
- else return hold(context,dispatchId,classifyLock(error),error);
222
- }
223
- }
224
- }
225
- if(residual)result.residualPaths=residual;
226
- return result;
227
- }