@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,258 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import {inspectPath} from './scope.mjs';
3
- import crypto from 'node:crypto';
4
- import path from 'node:path';
5
- import {spawnSync} from 'node:child_process';
6
- import {constants} from 'node:fs';
7
-
8
- const oid=value=>typeof value==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
9
- const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
10
- const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
11
- const text=bytes=>new TextDecoder('utf-8',{fatal:true}).decode(bytes);
12
- const gitPath=value=>typeof value==='string'&&value.length>0&&!/[\\\x00\r\n:]/.test(value)&&!value.startsWith('/')&&!value.split('/').some(p=>!p||p==='.'||p==='..');
13
- const absolute=value=>typeof value==='string'&&path.isAbsolute(value)&&path.normalize(value)===value;
14
- const unique=values=>new Set(values).size===values.length;
15
- const samePaths=(a,b)=>Array.isArray(a)&&Array.isArray(b)&&unique(a)&&unique(b)&&equal([...a].sort(),[...b].sort());
16
- function paths(bytes){
17
- const output=text(bytes);if(!output)return [];
18
- if(!output.endsWith('\0'))throw Error('Incomplete Git path output');
19
- const result=output.slice(0,-1).split('\0');if(!result.every(gitPath)||!unique(result))throw Error('Invalid Git paths');return result;
20
- }
21
- /** The default transport is read-only, bounded and shell-free. Inherited Git
22
- * overrides and optional locks are disabled; no caller environment is accepted. */
23
- function defaultRunner({args,cwd}){
24
- const env=Object.fromEntries(Object.entries(process.env).filter(([key])=>!key.toUpperCase().startsWith('GIT_')));
25
- Object.assign(env,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_OPTIONAL_LOCKS:'0',GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0'});
26
- return spawnSync('git',['--no-pager','--literal-pathspecs','-c','core.fsmonitor=false','-c','core.untrackedCache=false',...args],{cwd,env,encoding:'buffer',maxBuffer:16*1024*1024,timeout:10000,windowsHide:true});
27
- }
28
- /** Construct Git tree object IDs in memory from the complete stage-0 index.
29
- * No write-tree/hash-object -w or other repository mutation is needed. */
30
- function indexTree(bytes,objectLength){
31
- const entries=text(bytes);if(entries&&!entries.endsWith('\0'))throw Error('Incomplete index');
32
- const root=new Map();
33
- for(const entry of entries?entries.slice(0,-1).split('\0'):[]){
34
- const match=/^(100644|100755|120000|160000) ([a-f0-9]+) ([0-3])\t([\s\S]+)$/.exec(entry);
35
- if(!match||match[3]!=='0'||!oid(match[2])||match[2].length!==objectLength||!gitPath(match[4]))throw Error('Invalid or unmerged index');
36
- const parts=match[4].split('/');let directory=root;
37
- for(const part of parts.slice(0,-1)){if(directory.has(part)&&!(directory.get(part) instanceof Map))throw Error('Index path collision');if(!directory.has(part))directory.set(part,new Map());directory=directory.get(part);}
38
- const name=parts.at(-1);if(directory.has(name))throw Error('Duplicate index path');directory.set(name,{mode:match[1],object:match[2]});
39
- }
40
- const algorithm=objectLength===64?'sha256':'sha1';
41
- const tree=directory=>{
42
- const rows=[...directory].map(([name,value])=>({name,directory:value instanceof Map,value}));
43
- rows.sort((a,b)=>Buffer.compare(Buffer.from(a.name+(a.directory?'/':'')),Buffer.from(b.name+(b.directory?'/':''))));
44
- const body=Buffer.concat(rows.map(row=>Buffer.concat([Buffer.from(`${row.directory?'40000':row.value.mode} ${row.name}\0`),Buffer.from(row.directory?tree(row.value):row.value.object,'hex')])));
45
- return crypto.createHash(algorithm).update(Buffer.from(`tree ${body.length}\0`)).update(body).digest('hex');
46
- };
47
- return tree(root);
48
- }
49
- function documentInput(documents,target){
50
- if(!Array.isArray(documents))throw Error('Documents must be an array');
51
- for(const d of documents){
52
- if(!d||!['spec','plan'].includes(d.kind)||!gitPath(d.gitPath)||!absolute(d.path)||d.path!==path.join(target.realpath,...d.gitPath.split('/'))||!/^sha256:[a-f0-9]{64}$/.test(d.contentHash)||typeof d.approvalRef!=='string'||!d.approvalRef||(d.commit!==undefined&&!oid(d.commit)))throw Error('Invalid approved document');
53
- }
54
- if(!unique(documents.map(d=>d.gitPath))||!unique(documents.map(d=>d.kind)))throw Error('Duplicate document');
55
- const commits=new Set(documents.map(d=>d.commit));if(commits.size>1)throw Error('Documents must share a single commit');
56
- }
57
- /** Read actual objects/index and compare approved documents. gitRunner is a
58
- * trusted transport injection for tests/providers, never a tool argument. */
59
- export async function readGitEvidence({target,documents=[],gitRunner=defaultRunner,env,...options}={}){
60
- if(!target||!absolute(target.realpath)||!absolute(target.gitCommonDir)||!oid(target.head)||!(target.branch===null||typeof target.branch==='string'&&target.branch)||typeof gitRunner!=='function'||env!==undefined&&(!env||Object.keys(env).length)||Object.keys(options).length)throw Error('Invalid Git evidence target or overrides');
61
- documentInput(documents,target);
62
- const run=async args=>{
63
- const result=await gitRunner({args,cwd:target.realpath});
64
- if(!result||result.status!==0||result.error||!(typeof result.stdout==='string'||Buffer.isBuffer(result.stdout)))throw Error('Git evidence query failed: '+args[0]);
65
- return Buffer.isBuffer(result.stdout)?result.stdout:Buffer.from(result.stdout);
66
- };
67
- const line=async args=>{const output=text(await run(args));if(!output.endsWith('\n')||output.slice(0,-1).includes('\n'))throw Error('Invalid Git scalar output');return output.slice(0,-1);};
68
- const observeTarget=async()=>{
69
- const realpath=await line(['rev-parse','--show-toplevel']);
70
- const gitCommonDir=await line(['rev-parse','--path-format=absolute','--git-common-dir']);
71
- const head=await line(['rev-parse','HEAD']);
72
- // Detached HEAD is deliberately represented as null, never silently rebound.
73
- let branch;
74
- if(target.branch===null){
75
- const r=await gitRunner({args:['symbolic-ref','--quiet','--short','HEAD'],cwd:target.realpath});
76
- if(r?.status!==1||r.error)throw Error('Expected detached HEAD');branch=null;
77
- }else branch=await line(['symbolic-ref','--quiet','--short','HEAD']);
78
- if(realpath!==target.realpath||gitCommonDir!==target.gitCommonDir||head!==target.head||branch!==target.branch)throw Error('Git target or HEAD drift');
79
- return {...target,realpath,gitCommonDir,head,branch};
80
- };
81
- const observedTarget=await observeTarget();
82
- const index=await run(['ls-files','--stage','-z']);
83
- const stagedPaths=paths(await run(['diff','--cached','--name-only','-z','--']));
84
- const diff=await run(['diff','--cached','--binary','--no-ext-diff','--no-textconv','--']);
85
- const workingPaths=paths(await run(['diff','--name-only','-z','--no-ext-diff','--no-textconv','--']));
86
- const untrackedPaths=paths(await run(['ls-files','--others','--exclude-standard','-z']));
87
- const observedDocuments=[];let docsCommit;
88
- if(documents.length){
89
- const commit=documents[0].commit;
90
- if(commit){
91
- const metadata=text(await run(['show','--no-patch','--format=%P%n%T',commit])).trimEnd().split('\n');
92
- if(metadata.length!==2||!oid(metadata[0])||!oid(metadata[1]))throw Error('Expected a single-parent document commit');
93
- await run(['merge-base','--is-ancestor',commit,target.head]);
94
- const committedPaths=paths(await run(['diff-tree','--no-commit-id','--name-only','-r','-z',commit,'--']));
95
- if(!samePaths(committedPaths,documents.map(d=>d.gitPath)))throw Error('Document commit must contain the exact approved document set');
96
- const rows=pathsForTree(await run(['ls-tree','-r','-z',commit,'--',...documents.map(d=>d.gitPath)]));
97
- if(!samePaths(rows.map(row=>row.path),documents.map(d=>d.gitPath))||rows.some(row=>!['100644','100755'].includes(row.mode)||row.type!=='blob'))throw Error('Documents must be regular committed files');
98
- docsCommit={commit,parent:metadata[0],tree:metadata[1],paths:committedPaths,documents:structuredClone(documents)};
99
- }
100
- const stagedModes=new Map(text(index).split('\0').filter(Boolean).map(entry=>{const m=/^(\d+) [a-f0-9]+ 0\t([\s\S]+)$/.exec(entry);return m?[m[2],m[1]]:[];}));
101
- for(const d of documents){
102
- if(!commit&&!['100644','100755'].includes(stagedModes.get(d.gitPath)))throw Error('Documents must be regular staged files');
103
- const bytes=await run(['show',`${commit??''}:${d.gitPath}`]);
104
- const observedHash=hash(bytes);if(observedHash!==d.contentHash)throw Error('Approved document hash mismatch');
105
- observedDocuments.push({...d,observedHash});
106
- }
107
- }
108
- // Reading a concurrent index twice is conservative: never publish a mixed
109
- // snapshot or infer completion after the target changed during observation.
110
- if(!(await run(['ls-files','--stage','-z'])).equals(index)||!(await run(['diff','--cached','--binary','--no-ext-diff','--no-textconv','--'])).equals(diff))throw Error('Index changed during Git observation');
111
- await observeTarget();
112
- return {target:observedTarget,indexTree:indexTree(index,target.head.length),stagedPaths,stagedFingerprint:hash(diff),workingPaths,untrackedPaths,documents:observedDocuments,...(docsCommit?{docsCommit}:{})};
113
- }
114
- function pathsForTree(bytes){
115
- const output=text(bytes);if(!output||!output.endsWith('\0'))throw Error('Invalid document tree');
116
- return output.slice(0,-1).split('\0').map(entry=>{const match=/^(\d+) (blob|tree|commit) ([a-f0-9]+)\t([\s\S]+)$/.exec(entry);if(!match||!oid(match[3])||!gitPath(match[4]))throw Error('Invalid document tree entry');return {mode:match[1],type:match[2],path:match[4]};});
117
- }
118
-
119
- /** Assignment observation additionally compares regular current files to Git objects.
120
- * No Git facts or transport override are accepted from workflow command JSON. */
121
- export async function readAssignmentGitEvidence({target,documents}){
122
- const evidence=await readGitEvidence({target,documents});
123
- for(const document of evidence.documents){
124
- await inspectPath(document.path);
125
- document.currentHash=hash(await fs.readFile(document.path));
126
- if(document.currentHash!==document.contentHash)throw Error('Current approved document hash mismatch');
127
- }
128
- return evidence;
129
- }
130
-
131
- /** Cooperative observations come only from local read-only Git queries. */
132
- export async function readCooperativeCommitGitEvidence({target,commit,gitRunner=defaultRunner}){
133
- if(commit!==undefined&&!oid(commit))throw Error('Invalid commit object ID');
134
- const evidence=await readGitEvidence({target,gitRunner});
135
- if(commit===undefined)return evidence;
136
- const run=async args=>{const r=await gitRunner({args,cwd:target.realpath});if(r?.status!==0||r.error||!(Buffer.isBuffer(r.stdout)||typeof r.stdout==='string'))throw Error('Commit evidence query failed');return Buffer.from(r.stdout);};
137
- const metadata=text(await run(['show','--no-patch','--format=%H%n%P%n%T',commit])).trimEnd().split('\n');
138
- if(metadata.length!==3||metadata[0]!==commit||!metadata.every(oid))throw Error('Expected exact single-parent commit');
139
- const committedPaths=paths(await run(['diff-tree','--no-commit-id','--name-only','-r','-z',commit,'--']));
140
- // Reobserve both HEAD and index after metadata so a concurrent mutation holds.
141
- const after=await readGitEvidence({target,gitRunner});
142
- if(!equal(evidence,after))throw Error('Git changed during commit observation');
143
- return {...evidence,commit:{commit,parent:metadata[1],tree:metadata[2],paths:committedPaths,head:target.head}};
144
- }
145
-
146
- // Capture every working-tree entry, including ignored and empty directories.
147
- // Never follow a symlink or include Git's own mutable workflow directory.
148
- async function preservationFingerprint(root,planPath){
149
- const rows=[];let total=0;
150
- async function visit(dir,relative=''){
151
- const before=await fs.lstat(dir);if(!before.isDirectory()||before.isSymbolicLink())throw Error('Unsafe worktree directory');
152
- const names=(await fs.readdir(dir,{encoding:'buffer'})).map(text).sort((a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b)));
153
- for(const name of names){
154
- if(!relative&&name==='.git')continue;
155
- const rel=relative?relative+'/'+name:name;if(!gitPath(rel))throw Error('Unsafe worktree path');if(rel===planPath)continue;
156
- const filename=path.join(dir,name),stat=await fs.lstat(filename);if(++total>50000)throw Error('Worktree snapshot too large');
157
- const mode=stat.mode&0o7777;
158
- if(stat.isDirectory()&&!stat.isSymbolicLink()){rows.push({path:rel,type:'directory',mode});await visit(filename,rel);}
159
- else if(stat.isSymbolicLink())rows.push({path:rel,type:'symlink',mode,target:await fs.readlink(filename)});
160
- else if(stat.isFile()){
161
- if(stat.size>64*1024*1024)throw Error('Worktree file too large');
162
- const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let bytes;
163
- try{const first=await handle.stat();if(!first.isFile()||first.dev!==stat.dev||first.ino!==stat.ino)throw Error('Worktree file changed');bytes=await handle.readFile();const last=await handle.stat(),named=await fs.lstat(filename);if(first.dev!==last.dev||first.ino!==last.ino||first.size!==last.size||first.mtimeMs!==last.mtimeMs||last.dev!==named.dev||last.ino!==named.ino||last.mode!==named.mode)throw Error('Worktree file changed');}finally{await handle.close();}
164
- rows.push({path:rel,type:'file',mode,hash:hash(bytes)});
165
- }else throw Error('Unsupported worktree entry');
166
- }
167
- const after=await fs.lstat(dir);if(before.dev!==after.dev||before.ino!==after.ino||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode)throw Error('Worktree directory changed');
168
- }
169
- await visit(root);return hash(Buffer.from(JSON.stringify(rows)));
170
- }
171
- async function readPlanBytes(filename){
172
- await inspectPath(filename);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);
173
- try{const before=await handle.stat();if(!before.isFile()||before.size>1024*1024)throw Error('Invalid plan file');const bytes=await handle.readFile(),after=await handle.stat(),named=await fs.lstat(filename);if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||after.dev!==named.dev||after.ino!==named.ino||after.mode!==named.mode)throw Error('Plan file changed');await inspectPath(filename);return {bytes,mode:before.mode&0o111?'100755':'100644'};}finally{await handle.close();}
174
- }
175
- // This value is used only as input to an opaque fingerprint and is never
176
- // persisted or returned. URL credentials and fragment are discarded; a query
177
- // can affect routing, so its presence requires operator investigation.
178
- function sanitizedFetchUrl(value){
179
- if(typeof value!=='string'||!value||/[\x00-\x1f\x7f]/.test(value))throw Error('Invalid remote identity');
180
- if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){
181
- let parsed;try{parsed=new URL(value);}catch{throw Error('Invalid remote identity');}
182
- if(!['http:','https:','ssh:','git:','file:'].includes(parsed.protocol)||parsed.protocol!=='file:'&&!parsed.hostname||parsed.search)throw Error('Invalid remote identity');
183
- parsed.username='';parsed.password='';parsed.hash='';return parsed.toString();
184
- }
185
- if(!/^[A-Za-z]:[\\/]/.test(value)){
186
- const scp=/^(?:[^@/:\s]+@)?(\[[0-9A-Fa-f:.]+\]|[^@/:\s]+):(.+)$/.exec(value);
187
- if(scp)return `scp:${scp[1].toLowerCase()}:${scp[2]}`;
188
- }
189
- return `path:${value}`;
190
- }
191
-
192
- /** Local, read-only plan-amend observation. Git arguments and object IDs are
193
- * checked before transport; operator snapshots never enter the Git runner. */
194
- export async function readPlanAmendGitEvidence({target,arguments:a,mapping=[],gitRunner=defaultRunner}={}){
195
- if(!target||!a?.plan||!a?.history||!a?.recovery||!gitPath(a.plan.gitPath)||a.plan.path!==path.join(target.realpath,...a.plan.gitPath.split('/'))||![a.history.base,a.history.planCommit,a.history.head].every(oid)||!/^refs\/arc\/recovery\/[A-Za-z0-9._/-]+$/.test(a.recovery.ref)||a.recovery.ref.includes('..')||a.recovery.ref.includes('//')||!Array.isArray(mapping)||mapping.length>256||mapping.some(m=>!m||!oid(m.old)||!oid(m.new)))throw Error('Invalid plan-amend observation request');
196
- const run=async args=>{const r=await gitRunner({args,cwd:target.realpath});if(!r||r.status!==0||r.error||!(Buffer.isBuffer(r.stdout)||typeof r.stdout==='string'))throw Error('Plan-amend Git query failed: '+args[0]);return Buffer.from(r.stdout);};
197
- const line=async args=>{const v=text(await run(args));if(!v.endsWith('\n')||v.slice(0,-1).includes('\n'))throw Error('Invalid Git scalar');return v.slice(0,-1);};
198
- const before=await readGitEvidence({target,gitRunner});
199
- const headTree=await line(['rev-parse','--verify',`${target.head}^{tree}`]);if(!oid(headTree))throw Error('Invalid HEAD tree');
200
- const observeRemotes=async()=>{
201
- const remoteOutput=text(await run(['remote']));if(remoteOutput&&!remoteOutput.endsWith('\n'))throw Error('Incomplete remote list');
202
- const names=remoteOutput?remoteOutput.slice(0,-1).split('\n'):[];if(!unique(names)||names.some(name=>!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)))throw Error('Invalid configured remote');
203
- const remotes=[];for(const name of names.sort()){
204
- const output=text(await run(['remote','get-url','--all',name]));if(!output||!output.endsWith('\n'))throw Error('Invalid remote identity');
205
- const urls=output.slice(0,-1).split('\n').map(sanitizedFetchUrl),identities=[...new Set(urls)].sort();if(!identities.length)throw Error('Invalid remote identity');
206
- remotes.push({name,identity:hash(Buffer.from(JSON.stringify(identities)))});
207
- }return remotes;
208
- };
209
- const observeRecoveryRef=async()=>{
210
- const result=await gitRunner({args:['show-ref','--verify','--quiet',a.recovery.ref],cwd:target.realpath});
211
- if(result?.status===0&&!result.error){const value=await line(['rev-parse','--verify',a.recovery.ref]);if(!oid(value))throw Error('Invalid recovery ref');return {name:a.recovery.ref,oid:value};}
212
- if(result?.status!==1||result.error)throw Error('Recovery ref observation failed');return null;
213
- };
214
- const configuredRemotes=await observeRemotes();
215
- const list=text(await run(['rev-list','--reverse','--topo-order',`${a.history.base}..${a.history.head}`]));
216
- if(!list.endsWith('\n'))throw Error('Empty or incomplete history');const ids=list.slice(0,-1).split('\n');if(ids.length>256||!ids.every(oid)||!unique(ids))throw Error('Invalid history range');
217
- const commit=async id=>{
218
- const raw=await run(['cat-file','commit',id]),separator=raw.indexOf(Buffer.from('\n\n'));if(separator<0)throw Error('Malformed commit');
219
- const headers=[];for(const header of text(raw.subarray(0,separator)).split('\n')){
220
- if(header.startsWith(' ')){const previous=headers.at(-1);if(!previous||['tree','parent','committer'].includes(previous.name))throw Error('Malformed commit header');previous.raw+='\n'+header;continue;}
221
- const parsed=/^([^\s]+) (.*)$/.exec(header);if(!parsed)throw Error('Malformed commit header');headers.push({name:parsed[1],raw:header,value:parsed[2]});
222
- }
223
- const fields=name=>headers.filter(header=>header.name===name),trees=fields('tree'),parents=fields('parent'),authors=fields('author'),committers=fields('committer');
224
- const match=/^author (.*) (\d+) ([+-]\d{4})$/.exec(authors[0]?.raw??'');if(trees.length!==1||!oid(trees[0].value)||parents.length!==1||!oid(parents[0].value)||authors.length!==1||committers.length!==1||!match)throw Error('Expected linear commit metadata');
225
- const headerTemplate=headers.map(header=>['tree','parent','committer'].includes(header.name)?header.name:header.raw);
226
- const bytes=await run(['ls-tree','-r','-z','--full-tree',id]);const entries=text(bytes);if(entries&&!entries.endsWith('\0'))throw Error('Incomplete tree');
227
- const treeEntries=(entries?entries.slice(0,-1).split('\0'):[]).map(row=>{const m=/^(100644|100755|120000|160000) (blob|commit) ([a-f0-9]+)\t([\s\S]+)$/.exec(row);if(!m||!oid(m[3])||!gitPath(m[4]))throw Error('Invalid tree entry');return {path:m[4],mode:m[1],oid:m[3]};});
228
- if(!unique(treeEntries.map(x=>x.path)))throw Error('Duplicate tree path');
229
- return {oid:id,parent:parents[0].value,author:match[1],authorDate:match[2]+' '+match[3],message:text(raw.subarray(separator+2)),tree:treeEntries,headerTemplate};
230
- };
231
- const commits=[];for(const id of ids)commits.push(await commit(id));
232
- const newCommits=[];for(const item of mapping)newCommits.push(await commit(item.new));
233
- const original=await run(['show',`${a.history.planCommit}:${a.plan.gitPath}`]);
234
- const current=await readPlanBytes(a.plan.path);
235
- const firstFingerprint=await preservationFingerprint(target.realpath,a.plan.gitPath);
236
- const recoveryRef=await observeRecoveryRef();
237
- const after=await readGitEvidence({target,gitRunner}),secondFingerprint=await preservationFingerprint(target.realpath,a.plan.gitPath);
238
- const latest=await readPlanBytes(a.plan.path),finalRemotes=await observeRemotes(),finalRecoveryRef=await observeRecoveryRef();
239
- if(!equal(before,after)||firstFingerprint!==secondFingerprint||!latest.bytes.equals(current.bytes)||latest.mode!==current.mode||!equal(configuredRemotes,finalRemotes)||!equal(recoveryRef,finalRecoveryRef))throw Error('Git or worktree changed during observation');
240
- return {target,index:{tree:before.indexTree,headTree,stagedPaths:before.stagedPaths},worktree:{planClean:!before.workingPaths.includes(a.plan.gitPath)&&!before.untrackedPaths.includes(a.plan.gitPath),nonPlanFingerprint:firstFingerprint},configuredRemotes,history:{base:a.history.base,planCommit:a.history.planCommit,head:a.history.head,commits,newCommits},plan:{path:a.plan.path,content:text(current.bytes),hash:hash(current.bytes),originalHash:hash(original),mode:current.mode},recoveryRef};
241
- }
242
-
243
- const validGitPaths=values=>Array.isArray(values)&&values.every(gitPath)&&unique(values);
244
- const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||!path.isAbsolute(relative)&&relative!=='..'&&!relative.startsWith('..'+path.sep);};
245
- /** Provenance-neutral Git checks shared by trusted and cooperative callers.
246
- * The caller must establish role, approval and acceptance separately. */
247
- export function validateGitPreflight({target,descriptor:d,scope,gitEvidence:g}){
248
- if(!g||!equal(g.target,target)||!oid(d?.parent)||d.parent!==target.head||!oid(d.indexTree)||!/^sha256:[a-f0-9]{64}$/.test(d.fingerprint)||!validGitPaths(d.paths)||!d.paths.length||g.indexTree!==d.indexTree||g.stagedFingerprint!==d.fingerprint||!samePaths(g.stagedPaths,d.paths)||!validGitPaths(g.workingPaths)||!validGitPaths(g.untrackedPaths))return 'Actual Git target index diff and exact paths required';
249
- if(d.paths.some(file=>!scope.some(base=>within(base,path.join(target.realpath,...file.split('/'))))))return 'Commit contains another task or unrelated changes';
250
- if([...g.workingPaths,...g.untrackedPaths].some(file=>scope.some(base=>within(base,path.join(target.realpath,...file.split('/'))))))return 'Unstaged or untracked task changes invalidate acceptance';
251
- return null;
252
- }
253
- export function validateGitCommitResult({target,expected,result,scope}){
254
- if(!result||!oid(result.commit)||result.commit===expected.parent||result.commit.length!==expected.parent.length||result.parent!==expected.parent||result.tree!==expected.tree||!samePaths(result.paths,expected.paths)||result.head!==result.commit||!equal(result.target,{...target,head:result.commit})||!validGitPaths(result.remainingPaths))return 'Commit result unavailable or differs from expected parent tree paths and HEAD';
255
- if(result.remainingPaths.some(file=>scope.some(base=>within(base,path.join(target.realpath,...file.split('/'))))))return 'Committed task still has remaining changes';
256
- if(expected.remainingPaths!==undefined&&!samePaths(result.remainingPaths,expected.remainingPaths))return 'Remaining changes differ from preflight observation';
257
- return null;
258
- }
@@ -1,88 +0,0 @@
1
- /** Shared, non-executing Git query classifier. Target/configuration overrides fail closed. */
2
- const deny = reason => ({allowed:false,reason});
3
- const isGit = word => /(?:^|[\\/])git(?:\.exe)?$/i.test(word);
4
- export function validateGitPolicy(policy) {
5
- if (!policy || policy.schemaVersion !== 1 || !Array.isArray(policy.globalValueOptions) || !Array.isArray(policy.globalFlags) || !policy.commands || typeof policy.commands !== 'object' || Array.isArray(policy.commands)) throw Error('Invalid Git policy');
6
- const strings = list => Array.isArray(list) && list.every(x=>typeof x === 'string' && x.startsWith('-'));
7
- if (!strings(policy.globalValueOptions) || !strings(policy.globalFlags) || !Object.keys(policy.commands).length) throw Error('Invalid Git policy');
8
- for (const rule of Object.values(policy.commands)) if (!rule || !strings(rule.flags) || !strings(rule.values) || !['any','none','query','list'].includes(rule.positionals)) throw Error('Invalid Git command policy');
9
- return policy;
10
- }
11
- // This deliberately supports a small shell grammar, rather than executing a shell.
12
- function tokenize(command) {
13
- const tokens=[]; let word='', started=false, quote=null;
14
- for(let i=0;i<command.length;i++) {
15
- const char=command[i];
16
- if(char==='\\' && /[\r\n]/.test(command[i+1]??'')) throw Error('Escaped line terminator');
17
- if(quote) {
18
- if(char===quote){quote=null;continue;}
19
- if(quote==='"' && /[$`]/.test(char)) throw Error('Dynamic shell syntax');
20
- // Preserve Windows paths in quoted executable names.
21
- if(char==='\\' && quote==='"' && /["\\$`]/.test(command[i+1]??'')){word+=command[++i];continue;}
22
- word+=char;continue;
23
- }
24
- if(char==='"'||char==="'"){quote=char;started=true;continue;}
25
- if(/[\r\n\x00<>`$(){}&]/.test(char) && !(char==='&'&&command[i+1]==='&')) throw Error('Unsupported shell syntax');
26
- if(char===';'||char==='|'||char==='&') {
27
- if(started){tokens.push(word);word='';started=false;}
28
- const operator=command.slice(i,i+2); if(operator==='&&'||operator==='||')i++;
29
- tokens.push({operator:operator==='&&'||operator==='||'?operator:char});continue;
30
- }
31
- if(/\s/.test(char)){if(started){tokens.push(word);word='';started=false;}continue;}
32
- if(char==='\\') {if(i+1>=command.length)throw Error('Incomplete escape'); word+=command[++i];started=true;continue;}
33
- if(char==='#')throw Error('Unsupported shell comment');
34
- word+=char;started=true;
35
- }
36
- if(quote)throw Error('Unclosed quote'); if(started)tokens.push(word);return tokens;
37
- }
38
- function classifyWords(words,policy,depth) {
39
- if(!words.length)return deny('Empty shell segment');
40
- const executable=words[0].split(/[\\/]/).at(-1).toLowerCase();
41
- if(['sh','bash','sh.exe','bash.exe'].includes(executable)) {
42
- if(depth>=4 || words.length!==3 || words[1]!=='-c')return deny('Unsupported shell wrapper');
43
- return classifyGitCommand(words[2],policy,depth+1);
44
- }
45
- if(!isGit(words[0]))return words.some(isGit)?deny('Unsupported indirect Git invocation'):{allowed:true};
46
- let i=1;
47
- while(i<words.length && words[i].startsWith('-')) {
48
- const option=words[i++],equal=option.indexOf('='),key=equal<0?option:option.slice(0,equal);
49
- if(policy.globalFlags.includes(option))continue;
50
- // A query must stay on the target already resolved by the trusted adapter.
51
- if(['-C','--git-dir','--work-tree','--namespace','--config-env','-c'].includes(key))return deny('Git target or configuration override');
52
- if(!policy.globalValueOptions.includes(key))return deny('Unknown Git global option');
53
- if(equal<0 && (i>=words.length || words[i++].startsWith('-')))return deny('Missing Git option value');
54
- if(equal>=0 && !option.slice(equal+1))return deny('Missing Git option value');
55
- }
56
- const combined=`${words[i]} ${words[i+1]}`;
57
- const name=Object.hasOwn(policy.commands,combined)?(i+=2,combined):words[i++];
58
- const rule=Object.hasOwn(policy.commands,name)?policy.commands[name]:null; if(!rule)return deny('Git mutation or unknown subcommand');
59
- let positions=0,query=false,list=false,paths=false;
60
- for(;i<words.length;i++) {
61
- const arg=words[i];
62
- if(arg==='--no-index')return deny('Query outside repository');
63
- if(arg!=='--'&&!arg.startsWith('-')&&(/^(?:[\\/]|[A-Za-z]:)/.test(arg)||arg.split(/[\\/]/).includes('..')||arg.includes(':(')))return deny('Query path escapes target');
64
- if(arg==='--' && rule.positionals==='any'){paths=true;continue;}
65
- if(!paths && arg.startsWith('-')) {
66
- if(/^-[0-9]+$/.test(arg)&&rule.flags.includes('-<count>'))continue;
67
- const equal=arg.indexOf('='),key=equal<0?arg:arg.slice(0,equal);
68
- if(rule.values.includes(key)) {if(equal<0 && (i+1>=words.length||words[++i].startsWith('-')))return deny('Missing query option value'); if(equal>=0&&!arg.slice(equal+1))return deny('Missing query option value');continue;}
69
- if(!rule.flags.includes(arg))return deny('Unknown or mutating Git option');
70
- if(['--get','--get-all','--get-regexp','--list','-l'].includes(arg))query=true;
71
- if(['--list','-l','--show-current'].includes(arg))list=true;
72
- } else positions++;
73
- }
74
- if(rule.positionals==='none'&&positions || rule.positionals==='query'&&(!query||positions>1) || rule.positionals==='list'&&positions&&!list)return deny('Git write or unsupported arguments');
75
- return {allowed:true};
76
- }
77
- export function classifyGitCommand(command,policy,depth=0) {
78
- try {
79
- validateGitPolicy(policy);
80
- if(typeof command!=='string'||!command.trim())return deny('Missing shell command');
81
- const tokens=tokenize(command); let words=[];
82
- for(const token of [...tokens,{operator:'end'}]) {
83
- if(typeof token==='string'){words.push(token);continue;}
84
- const result=classifyWords(words,policy,depth);if(!result.allowed)return result;words=[];
85
- }
86
- return {allowed:true};
87
- } catch {return deny('Invalid policy or unsupported command syntax');}
88
- }
@@ -1,49 +0,0 @@
1
- import {validateWorkflowState, text} from './schema.mjs';
2
- import {ROLES} from './operations.mjs';
3
- import fs from 'node:fs/promises';
4
- import path from 'node:path';
5
- import {fingerprintRequest,saveDurableState} from './store.mjs';
6
- const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
7
- /** Observation is supplied by the trusted platform provider, never agent/tool arguments. */
8
- export function registerAgentObservation(state, observation){
9
- validateWorkflowState(state);
10
- const result=(decision,reason)=>({decision,reason,state,proposedTransition:null});
11
- if(!observation||!text(observation.actorRef)||!text(observation.taskId)||!text(observation.observationRef)||!ROLES.includes(observation.role))return result('hold','complete observed identity required');
12
- const old=state.identities.find(i=>i.actorRef===observation.actorRef);
13
- const lease=state.leases.find(l=>l.actorRef===observation.actorRef);
14
- if(old&&(old.taskId!==observation.taskId||old.role!==observation.role))return result('deny','identity rebind');
15
- if(lease?.status==='retired')return result('deny','retired identity');
16
- const p=observation.provenance;
17
- if(!text(observation.eventRef)||!text(observation.correlationRef)||!p||p.source!=='platform-event'||p.eventRef!==observation.eventRef||p.actorRef!==observation.actorRef||p.platform!==observation.platform||p.correlationRef!==observation.correlationRef||p.verification?.status!=='verified'||!text(p.verification.verifierRef)||p.verification.sourceRef!==observation.eventRef)return result('hold','trusted platform spawn observation and correlation required');
18
- const assignment=state.assignments.find(a=>a.assignmentId===observation.assignmentId&&a.correlationRef===observation.correlationRef);
19
- if(!assignment||assignment.taskId!==observation.taskId||assignment.role!==observation.role||assignment.platform!==observation.platform||assignment.approvalRef!==observation.approvalRef||!same(assignment.paths,observation.paths)||!same(assignment.operations,observation.operations))return result('hold','observation does not match approved pending assignment');
20
- if(old){
21
- if(assignment.status==='active'&&assignment.actorRef===old.actorRef&&old.observationRef===observation.observationRef&&lease?.status==='active')return result('allow','same confirmed observation');
22
- return result('hold','existing identity cannot be assigned through another observation');
23
- }
24
- if(assignment.status!=='pending'||assignment.actorRef!==null||lease)return result('hold','new identity requires pending unbound assignment');
25
- const task=state.tasks.find(t=>t.id===assignment.taskId);if(!task||['accepted','committed'].includes(task.status))return result('hold','task no longer accepts agent observations');
26
- const next=structuredClone(state);const active=next.assignments.find(a=>a.assignmentId===assignment.assignmentId);active.actorRef=observation.actorRef;active.status='active';active.observationRef=observation.observationRef;
27
- next.identities.push({actorRef:observation.actorRef,taskId:observation.taskId,role:observation.role,observationRef:observation.observationRef});next.leases.push({actorRef:observation.actorRef,taskId:observation.taskId,status:'active'});next.tasks.find(t=>t.id===assignment.taskId).status='assigned';
28
- validateWorkflowState(next);
29
- return {decision:'allow',reason:'matching observed spawn bound to pending assignment',state:next,proposedTransition:next};
30
- }
31
-
32
- /** A raw start is audit only; verified correlation may bind an existing assignment. */
33
- export async function recordPlannerAgentObservation({statePath,expectedRevision,input,platform,sessionRef,observation}={}){
34
- if(!path.isAbsolute(statePath??'')||input?.hook_event_name!=='SubagentStart'||input.session_id!==sessionRef||!text(sessionRef)||!text(input.agent_id)||!['codex','claude'].includes(platform))throw Error('Trusted observation target and complete start required');
35
- const parent=await fs.realpath(path.dirname(statePath));statePath=path.join(parent,path.basename(statePath));let lock;
36
- try{
37
- lock=await fs.open(statePath+'.lock','wx',0o600);const stat=await fs.lstat(statePath);if(!stat.isFile()||stat.isSymbolicLink())throw Error('Observation state must be regular file');
38
- const state=validateWorkflowState(JSON.parse(await fs.readFile(statePath,'utf8'))),eventHash=fingerprintRequest({input,observation:observation??null});
39
- if(state.plannerObservations?.some(o=>o.eventHash===eventHash))return {decision:'hold',reason:'Observation replay',proposedTransition:null,replayed:true};
40
- const candidates=state.assignments.filter(a=>a.status==='pending'&&a.role==='planner');
41
- let decision={decision:'hold',reason:'Raw event lacks verified assignment correlation',proposedTransition:null};
42
- if(state.revision!==expectedRevision)decision.reason='Stale provider context cannot bind identity';
43
- else if(observation?.actorRef===input.agent_id&&observation.platform===platform)decision=registerAgentObservation(state,observation);
44
- const correlated=decision.decision==='allow'&&Boolean(decision.proposedTransition),next=correlated?decision.proposedTransition:structuredClone(state);
45
- const entry={eventHash,event:'SubagentStart',source:correlated?'verified-provider':'hook-stdin',sessionRef,agentRef:input.agent_id,classification:correlated?'correlated':candidates.length?'uncorrelated':'unmatched',identityVerified:correlated,reason:decision.reason,stageCandidates:candidates.map(a=>({assignmentId:a.assignmentId,stageId:a.plannerStageId??null,requestId:a.requestId})),coverage:{enforcement:'observation-only',nativeVerified:false,prevention:false},deduplication:'content-hash-only'};
46
- next.plannerObservations=[...(state.plannerObservations??[]),entry];next.revision=state.revision+1;next.audit.push({event:'SubagentStart',eventHash,revision:next.revision,classification:entry.classification,source:entry.source});validateWorkflowState(next);await saveDurableState({statePath,state:next});
47
- return {...decision,proposedTransition:correlated?next:null,observation:entry,persisted:true};
48
- }finally{if(lock){await lock.close();await fs.unlink(statePath+'.lock');}}
49
- }
@@ -1,6 +0,0 @@
1
- /** Canonical semantic operations, independent of platform tool aliases. */
2
- export const ROLES = Object.freeze(['orchestrator','scouter','planner','implementer','qa','reviewer']);
3
- export const GIT_OPERATIONS = Object.freeze(['stage','commit','push','merge','rebase','reset','branch-create','branch-switch','worktree-create','worktree-remove']);
4
- export const EXTERNAL_OPERATIONS = Object.freeze(['push','merge','deploy','publish','external-message']);
5
- export const OPERATIONS = Object.freeze(['read','draft','write','check','qa','review','temporary-write','operational-query','install','prepare-target','request-approval','assign-agent','accept','transition','plan-amend','scope-expansion','indirect-bypass',...new Set([...GIT_OPERATIONS,...EXTERNAL_OPERATIONS])]);
6
- export const ROLE_OPERATIONS = Object.freeze({orchestrator:['read','write','check','prepare-target','request-approval','assign-agent','accept','transition','plan-amend','install',...GIT_OPERATIONS,...EXTERNAL_OPERATIONS],scouter:['read'],planner:['read','draft'],implementer:['read','write','check'],qa:['read','check','temporary-write'],reviewer:['read','review']});
@@ -1,148 +0,0 @@
1
- // Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
2
- import crypto from 'node:crypto';
3
- import path from 'node:path';
4
- import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
5
-
6
- const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer'];
7
- const deepFreeze = value => { for (const child of Object.values(value)) if (child && typeof child === 'object') deepFreeze(child); return Object.freeze(value); };
8
- export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
9
- claude: {
10
- arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
11
- arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_qa: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
12
- },
13
- codex: {
14
- arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
15
- arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
16
- }
17
- });
18
-
19
- const bad = message => { throw Error(`Invalid composite profile: ${message}`); };
20
- const unquote = raw => {
21
- const value = raw.trim();
22
- if (/^"(?:[^"\\]|\\.)*"$/.test(value)) { try { return JSON.parse(value); } catch { bad('unsupported string escape'); } }
23
- if (/^'[^']*'$/.test(value)) return value.slice(1, -1);
24
- return value;
25
- };
26
-
27
- function parseClaude(text) {
28
- const lines = text.split('\n').map(line => line.replace(/\r$/, ''));
29
- if (lines[0] !== '---') bad('missing frontmatter');
30
- const end = lines.indexOf('---', 1);
31
- if (end < 0) bad('unterminated frontmatter');
32
- const fields = {}; let tools = null, inTools = false;
33
- for (const line of lines.slice(1, end)) {
34
- const item = /^[ \t]+-[ \t]+(\S.*?)[ \t]*$/.exec(line);
35
- if (item) { if (!inTools) bad('unexpected list item'); tools.push(unquote(item[1])); continue; }
36
- const field = /^([A-Za-z][A-Za-z0-9_-]*):[ \t]*(.*?)[ \t]*$/.exec(line);
37
- if (!field) { if (line.trim() === '') continue; bad('unrecognized frontmatter line'); }
38
- inTools = false;
39
- if (field[1] === 'tools') { if (field[2] !== '') bad('tools must be a block list'); if (tools !== null) bad('duplicate tools'); tools = []; inTools = true; continue; }
40
- if (Object.hasOwn(fields, field[1])) bad(`duplicate ${field[1]}`);
41
- fields[field[1]] = unquote(field[2]);
42
- }
43
- for (const key of ['name', 'description', 'model', 'effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
44
- if (tools !== null && tools.length === 0) bad('empty tools');
45
- const instructions = lines.slice(end + 1).join('\n');
46
- if (instructions.trim() === '') bad('empty instructions');
47
- return {name: fields.name, description: fields.description, model: fields.model, effort: fields.effort, tools, instructions};
48
- }
49
-
50
- const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
51
- // Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
52
- function readMultiline(lines, index, rest) {
53
- let out = '', buffer = rest, line = index;
54
- for (;;) {
55
- for (let i = 0; i < buffer.length; i++) {
56
- const ch = buffer[i];
57
- if (ch === '"' && buffer.startsWith('"""', i)) {
58
- if (!/^(?:"{0,2})[ \t]*(?:#.*)?$/.test(buffer.slice(i + 3))) bad('unsupported developer_instructions terminator');
59
- return {value: out + buffer.slice(i + 3).match(/^"*/)[0], next: line + 1};
60
- }
61
- if (ch !== '\\') { out += ch; continue; }
62
- const next = buffer[i + 1];
63
- if (next === undefined) { // line-ending backslash trims following whitespace and newlines
64
- let j = line + 1; while (j < lines.length && /^[ \t]*$/.test(lines[j])) j++;
65
- if (j >= lines.length) bad('unterminated developer_instructions');
66
- out += ''; buffer = lines[j].replace(/^[ \t]+/, ''); line = j; i = -1; continue;
67
- }
68
- if (Object.hasOwn(ESCAPES, next)) { out += ESCAPES[next]; i++; continue; }
69
- const width = next === 'u' ? 4 : next === 'U' ? 8 : 0, hex = buffer.slice(i + 2, i + 2 + width);
70
- if (!width || !new RegExp(`^[0-9A-Fa-f]{${width}}$`).test(hex)) bad('invalid escape in developer_instructions');
71
- try { out += String.fromCodePoint(parseInt(hex, 16)); } catch { bad('invalid code point in developer_instructions'); }
72
- i += 1 + width;
73
- }
74
- line++;
75
- if (line >= lines.length) bad('unterminated developer_instructions');
76
- out += '\n'; buffer = lines[line];
77
- }
78
- }
79
- function parseCodex(text) {
80
- const lines = text.split('\n').map(line => line.replace(/\r$/, '')), fields = {};
81
- let instructions = null;
82
- for (let i = 0; i < lines.length; i++) {
83
- const line = lines[i];
84
- if (/^[ \t]*\[/.test(line)) break;
85
- const multi = /^developer_instructions[ \t]*=[ \t]*"""(.*)$/.exec(line);
86
- if (multi) {
87
- if (instructions !== null) bad('duplicate developer_instructions');
88
- const rest = multi[1], result = readMultiline(lines, i, rest === '' ? '' : rest);
89
- // A newline directly after the opening delimiter is trimmed; readMultiline starts at an empty remainder, so skip that join.
90
- instructions = rest === '' ? result.value.replace(/^\n/, '') : result.value; i = result.next - 1; continue;
91
- }
92
- if (/^developer_instructions[ \t]*=/.test(line)) bad('developer_instructions must be a multiline string');
93
- const single = /^(name|description|model|model_reasoning_effort)[ \t]*=[ \t]*("(?:[^"\\]|\\.)*")[ \t]*(?:#.*)?$/.exec(line);
94
- if (single) { if (Object.hasOwn(fields, single[1])) bad(`duplicate ${single[1]}`); fields[single[1]] = unquote(single[2]); continue; }
95
- if (/^(name|description|model|model_reasoning_effort)[ \t]*=/.test(line)) bad(`${line.split('=')[0].trim()} must be a one-line string`);
96
- }
97
- for (const key of ['name', 'description', 'model', 'model_reasoning_effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
98
- if (instructions === null || instructions.trim() === '') bad('missing developer_instructions');
99
- return {name: fields.name, description: fields.description, model: fields.model, effort: fields.model_reasoning_effort, tools: null, instructions};
100
- }
101
-
102
- /** Narrow extractor: the installed runtime cannot import lib/models, so only the managed profile shapes are accepted. */
103
- export function parseCompositeProfile(platform, bytes) {
104
- if (platform !== 'claude' && platform !== 'codex') bad('unknown platform');
105
- const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? '');
106
- let text;
107
- try { text = new TextDecoder('utf-8', {fatal: true}).decode(buffer); } catch { bad('not valid UTF-8'); }
108
- if (text.charCodeAt(0) === 0xfeff) bad('unexpected BOM');
109
- return platform === 'claude' ? parseClaude(text) : parseCodex(text);
110
- }
111
-
112
- const permissionsFor = (platform, role) => {
113
- if (!ROLES.includes(role)) throw Error(`Unknown role: ${role}`);
114
- return ROLE_BRIDGE_PERMISSIONS[platform][role];
115
- };
116
- const requireText = (value, label) => { if (typeof value !== 'string' || value === '') throw Error(`Missing ${label}`); return value; };
117
-
118
- export function buildClaudeArgs({role, profile, sessionId = null, policy = DEFAULT_POLICY}) {
119
- const permissions = permissionsFor('claude', role);
120
- if (!Array.isArray(profile?.tools) || profile.tools.length === 0) throw Error('Claude profile tools are required');
121
- const args = ['-p', '--safe-mode', '--output-format', 'stream-json', '--verbose', '--model', requireText(profile.model, 'model'), '--effort', requireText(profile.effort, 'effort'),
122
- '--append-system-prompt', requireText(profile.instructions, 'instructions'), '--tools', profile.tools.join(','), '--permission-mode', permissions.permissionMode];
123
- if (permissions.sandbox) {
124
- const settings = effectiveClaudeSandboxSettings(policy);
125
- if (settings === null) throw Error('Claude sandbox settings are not available for this role');
126
- args.push('--settings', JSON.stringify(settings));
127
- }
128
- if (policy?.gates?.G6 === 'strict') args.push('--strict-mcp-config');
129
- if (sessionId !== null) args.push('--resume', requireText(sessionId, 'sessionId'));
130
- return args;
131
- }
132
-
133
- export function buildCodexArgs({role, profile, worktree, resultPath, threadId = null, policy = DEFAULT_POLICY}) {
134
- void policy;
135
- const permissions = permissionsFor('codex', role);
136
- if (typeof resultPath !== 'string' || !path.isAbsolute(resultPath)) throw Error('Absolute resultPath required');
137
- const settings = ['-m', requireText(profile?.model, 'model'), '-c', `model_reasoning_effort=${JSON.stringify(requireText(profile.effort, 'effort'))}`,
138
- '-c', `developer_instructions=${JSON.stringify(requireText(profile.instructions, 'instructions'))}`, '-c', `sandbox_mode=${JSON.stringify(permissions.sandboxMode)}`,
139
- '-c', 'approval_policy="never"', '-o', resultPath, '-'];
140
- if (threadId !== null) {
141
- if (typeof threadId !== 'string' || !/^[A-Za-z0-9._-]+$/.test(threadId)) throw Error('Invalid threadId');
142
- return [...(permissions.search ? ['--search'] : []), 'exec', 'resume', threadId, '--json', ...settings];
143
- }
144
- if (typeof worktree !== 'string' || !path.isAbsolute(worktree)) throw Error('Absolute worktree required');
145
- return [...(permissions.search ? ['--search'] : []), 'exec', '--json', '-C', worktree, ...settings];
146
- }
147
-
148
- export const argsDigest = args => 'sha256:' + crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');