@yunhozz/arc 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/MANIFEST.sha256 +133 -94
  2. package/README.md +56 -21
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/commit.md +10 -8
  5. package/claude/skill/references/coordination.md +6 -4
  6. package/claude/skill/references/handoff-prep.md +12 -12
  7. package/claude/skill/references/handoff.md +2 -0
  8. package/claude/skill/references/planning.md +8 -8
  9. package/claude/skill/references/verification.md +6 -6
  10. package/codex/skill/SKILL.md +1 -1
  11. package/codex/skill/references/commit.md +10 -8
  12. package/codex/skill/references/coordination.md +6 -4
  13. package/codex/skill/references/handoff-prep.md +12 -12
  14. package/codex/skill/references/handoff.md +2 -0
  15. package/codex/skill/references/planning.md +8 -8
  16. package/codex/skill/references/verification.md +6 -6
  17. package/gemini/GEMINI.md +8 -0
  18. package/gemini/agents/arc-implementer.md +37 -0
  19. package/gemini/agents/arc-planner.md +47 -0
  20. package/gemini/agents/arc-qa.md +37 -0
  21. package/gemini/agents/arc-reviewer.md +39 -0
  22. package/gemini/agents/arc-scouter.md +38 -0
  23. package/gemini/instructions.md +4 -0
  24. package/gemini/skill/SKILL.md +78 -0
  25. package/gemini/skill/models.toml +23 -0
  26. package/gemini/skill/references/arc-visual-companion.md +28 -0
  27. package/gemini/skill/references/commit.md +55 -0
  28. package/gemini/skill/references/coordination.md +149 -0
  29. package/gemini/skill/references/git-recovery.md +34 -0
  30. package/gemini/skill/references/handoff-prep.md +110 -0
  31. package/gemini/skill/references/handoff.md +227 -0
  32. package/gemini/skill/references/limits.md +31 -0
  33. package/gemini/skill/references/planning.md +168 -0
  34. package/gemini/skill/references/verification.md +155 -0
  35. package/gemini/skill/references/worktree-creation.md +8 -0
  36. package/lib/color/palette.mjs +6 -0
  37. package/lib/installer/acquisition.mjs +7 -5
  38. package/lib/installer/install-mode.mjs +49 -26
  39. package/lib/installer/install.mjs +3 -2
  40. package/lib/installer/manifest.mjs +20 -14
  41. package/lib/installer/plan.mjs +24 -21
  42. package/lib/installer/preset.mjs +9 -8
  43. package/lib/installer/role-routing.mjs +129 -77
  44. package/lib/installer/runtime-assets.mjs +2 -0
  45. package/lib/installer/runtime-config.mjs +3 -0
  46. package/lib/installer/skill-sources.mjs +4 -3
  47. package/lib/installer/superpowers.mjs +2 -1
  48. package/lib/installer/target-errors.mjs +1 -0
  49. package/lib/installer/targets.mjs +14 -6
  50. package/lib/installer/uninstall.mjs +5 -4
  51. package/lib/installer/upgrade-state.mjs +14 -10
  52. package/lib/installer/upgrade.mjs +9 -5
  53. package/lib/management/operations.mjs +91 -47
  54. package/lib/management/status.mjs +10 -8
  55. package/lib/management/update.mjs +8 -7
  56. package/lib/models/catalog-gemini.mjs +48 -0
  57. package/lib/models/catalog.mjs +27 -12
  58. package/lib/models/config.mjs +23 -22
  59. package/lib/models/gemini-models.json +12 -0
  60. package/lib/models/profiles.mjs +7 -5
  61. package/lib/models/static-catalog.mjs +13 -14
  62. package/lib/npm/upgrade.mjs +2 -2
  63. package/lib/platforms/availability.mjs +98 -0
  64. package/lib/platforms/claude.mjs +14 -0
  65. package/lib/platforms/codex.mjs +16 -0
  66. package/lib/platforms/formats/gemini-markdown.mjs +48 -0
  67. package/lib/platforms/formats/markdown.mjs +39 -0
  68. package/lib/platforms/formats/toml.mjs +39 -0
  69. package/lib/platforms/gemini.mjs +14 -0
  70. package/lib/platforms/index.mjs +27 -0
  71. package/lib/policy/placement.mjs +4 -4
  72. package/lib/policy/render.mjs +13 -8
  73. package/lib/policy/role-policy.json +40 -21
  74. package/lib/prompts/agent-fragments.json +71 -1
  75. package/lib/prompts/render.mjs +32 -11
  76. package/lib/runtime/bootstrap.mjs +1 -1
  77. package/lib/runtime/cooperative-schema.mjs +0 -23
  78. package/lib/runtime/cooperative.mjs +13 -34
  79. package/lib/runtime/evaluate.mjs +3 -69
  80. package/lib/runtime/gemini-stream.mjs +32 -0
  81. package/lib/runtime/git-evidence.mjs +0 -98
  82. package/lib/runtime/identity.mjs +2 -1
  83. package/lib/runtime/local-cli.mjs +14 -24
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/platform-registry.mjs +130 -0
  86. package/lib/runtime/role-bridge-args.mjs +57 -2
  87. package/lib/runtime/role-bridge.mjs +86 -65
  88. package/lib/runtime/role-dispatch-policy.mjs +17 -7
  89. package/lib/runtime/role-dispatch-store.mjs +20 -14
  90. package/lib/runtime/role-observe.mjs +1 -0
  91. package/lib/runtime/role-routing-config.mjs +36 -9
  92. package/lib/runtime/role-routing.mjs +62 -29
  93. package/lib/runtime/role-supervisor.mjs +114 -49
  94. package/lib/runtime/schema.mjs +5 -4
  95. package/lib/tui/app.mjs +37 -32
  96. package/lib/tui/custom-preset.mjs +114 -68
  97. package/lib/tui/derive-install-plan.mjs +19 -0
  98. package/lib/tui/diagram.mjs +68 -0
  99. package/lib/tui/mode.mjs +77 -0
  100. package/lib/tui/render.mjs +47 -16
  101. package/lib/tui/setup.mjs +167 -100
  102. package/lib/tui/terminal.mjs +9 -6
  103. package/lib/watch/anchor-store.mjs +44 -0
  104. package/lib/watch/dispatch.mjs +3 -3
  105. package/lib/watch/index.mjs +37 -24
  106. package/lib/watch/model.mjs +1 -0
  107. package/lib/watch/normalize-claude.mjs +50 -10
  108. package/lib/watch/normalize-codex.mjs +79 -5
  109. package/lib/watch/render.mjs +30 -13
  110. package/lib/watch/scope.mjs +2 -1
  111. package/lib/watch/status-line.mjs +51 -0
  112. package/lib/watch/tail.mjs +27 -0
  113. package/lib/watch/watcher.mjs +193 -53
  114. package/package.json +2 -1
  115. package/scripts/update-manifest.mjs +2 -2
  116. package/shared/skill/runtime/bootstrap.mjs +1 -1
  117. package/shared/skill/runtime/cooperative-schema.mjs +0 -23
  118. package/shared/skill/runtime/cooperative.mjs +13 -34
  119. package/shared/skill/runtime/evaluate.mjs +3 -69
  120. package/shared/skill/runtime/gemini-stream.mjs +32 -0
  121. package/shared/skill/runtime/git-evidence.mjs +0 -98
  122. package/shared/skill/runtime/identity.mjs +2 -1
  123. package/shared/skill/runtime/local-cli.mjs +14 -24
  124. package/shared/skill/runtime/operations.mjs +2 -2
  125. package/shared/skill/runtime/platform-registry.mjs +130 -0
  126. package/shared/skill/runtime/role-bridge-args.mjs +57 -2
  127. package/shared/skill/runtime/role-bridge.mjs +86 -65
  128. package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
  129. package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
  130. package/shared/skill/runtime/role-observe.mjs +1 -0
  131. package/shared/skill/runtime/role-policy.json +40 -21
  132. package/shared/skill/runtime/role-routing-config.mjs +36 -9
  133. package/shared/skill/runtime/role-routing.mjs +62 -29
  134. package/shared/skill/runtime/role-supervisor.mjs +114 -49
  135. package/shared/skill/runtime/schema.mjs +5 -4
@@ -14,74 +14,11 @@ import {prepareCooperativeAssignment} from './assignment.mjs';
14
14
  * @property {object} coverage
15
15
  */
16
16
  import path from 'node:path';
17
- import crypto from 'node:crypto';
18
- import {fingerprintRequest} from './store.mjs';
19
- import {validateCooperativeState,validateCooperativeCommand,validatePlanAmendArguments} from './cooperative-schema.mjs';
17
+ import {validateCooperativeState,validateCooperativeCommand} from './cooperative-schema.mjs';
20
18
  import {validateWorkflowState, validateRequest, validateEvidence,validatePlannerStage} from './schema.mjs';
21
19
  import {ROLES, ROLE_OPERATIONS, GIT_OPERATIONS, EXTERNAL_OPERATIONS} from './operations.mjs';
22
20
  const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
23
21
  const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative));};
24
- const objectFields=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
25
- const hashBytes=value=>'sha256:'+crypto.createHash('sha256').update(value).digest('hex');
26
- const gitBlob=(value,length)=>crypto.createHash(length===64?'sha256':'sha1').update(`blob ${Buffer.byteLength(value)}\0`).update(value).digest('hex');
27
- const planCoverage={enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false,remoteVerified:false};
28
- const planDecision=(state,reason,transition=null,allow=false)=>({expectedRevision:state?.revision??0,decision:allow?'allow':'hold',ruleIds:['cooperative.plan-amend'],reason,coverage:{...planCoverage},requiredEvidence:[],nextActions:[],proposedTransition:transition});
29
- const unresolvedPlan=state=>state.intents.some(i=>i.operation==='plan-amend'&&['prepared','unknown','mismatch','failed'].includes(i.status));
30
- const remoteIdentities=remotes=>remotes.map(r=>r.name+'\0'+r.identity).sort();
31
- function remoteSnapshotValid(remotes,configured,at,protectedOids){
32
- if(!Number.isFinite(at)||!Array.isArray(configured)||!Array.isArray(remotes)||configured.some(r=>!objectFields(r,['name','identity'])||typeof r.name!=='string'||!/^sha256:[a-f0-9]{64}$/.test(r.identity??''))||new Set(configured.map(r=>r.name)).size!==configured.length||!same(remoteIdentities(remotes),remoteIdentities(configured)))return false;
33
- return remotes.every(r=>r.complete===true&&Number.isFinite(Date.parse(r.observedAt))&&at-Date.parse(r.observedAt)>=0&&at-Date.parse(r.observedAt)<=300000&&r.refs.every(ref=>ref.oid.length===protectedOids[0]?.length&&!protectedOids.includes(ref.oid)));
34
- }
35
- function planEntries(commit,length){
36
- const validOid=value=>typeof value==='string'&&new RegExp(`^[a-f0-9]{${length}}$`).test(value);
37
- return commit&&validOid(commit.oid)&&validOid(commit.parent)&&typeof commit.author==='string'&&typeof commit.authorDate==='string'&&typeof commit.message==='string'&&Array.isArray(commit.headerTemplate)&&commit.headerTemplate.every(header=>typeof header==='string')&&['tree','parent','committer'].every(name=>commit.headerTemplate.filter(header=>header===name).length===1)&&Array.isArray(commit.tree)&&new Set(commit.tree.map(row=>row.path)).size===commit.tree.length&&commit.tree.every(row=>objectFields(row,['path','mode','oid'])&&typeof row.path==='string'&&row.path.length>0&&!row.path.startsWith('/')&&!/[\\\x00\r\n:]/.test(row.path)&&!row.path.split('/').some(p=>!p||p==='.'||p==='..')&&['100644','100755','120000','160000'].includes(row.mode)&&validOid(row.oid));
38
- }
39
- function oldPlanObservation(a,g,target){
40
- const h=g?.history,commits=h?.commits,length=target.head.length,oldBlob=gitBlob(a.plan.old.content,length);
41
- if(!same(g?.target,target)||!g.index||!new RegExp(`^[a-f0-9]{${length}}$`).test(g.index.tree??'')||g.index.tree!==g.index.headTree||g.index.stagedPaths?.length!==0||g.worktree?.planClean!==true||!/^sha256:[a-f0-9]{64}$/.test(g.worktree?.nonPlanFingerprint??'')||g.plan?.path!==a.plan.path||g.plan.content!==a.plan.old.content||g.plan.hash!==a.plan.old.hash||g.plan.originalHash!==a.plan.old.hash||!h||h.base!==a.history.base||h.planCommit!==a.history.planCommit||h.head!==a.history.head||!Array.isArray(commits)||!commits.length||commits.length>256||commits.some(c=>!c)||commits[0].oid!==a.history.planCommit||commits.at(-1).oid!==a.history.head||new Set(commits.map(c=>c.oid)).size!==commits.length)return false;
42
- const originalMode=commits[0].tree?.find(row=>row.path===a.plan.gitPath)?.mode;
43
- return ['100644','100755'].includes(originalMode)&&g.plan.mode===originalMode&&commits.every((c,index)=>planEntries(c,length)&&c.parent===(index?commits[index-1].oid:a.history.base)&&c.tree.filter(row=>row.path===a.plan.gitPath).length===1&&c.tree.some(row=>row.path===a.plan.gitPath&&row.mode===originalMode&&row.oid===oldBlob));
44
- }
45
- function approvalRecord(state,a,approval){
46
- const record=state.records.findLast(r=>r.kind==='approval'&&r.messageRef===approval.ref);
47
- return record?.source==='operator-attested'&&record.actor?.role==='orchestrator'&&record.targetVersion===state.targetVersion&&record.scopeVersion===state.scopeVersion&&record.data?.kind==='plan'&&record.data.path===a.plan.path&&record.data.version===approval.version&&record.data.contentHash===approval.hash&&record.data.approvedAt===approval.approvedAt;
48
- }
49
- function planAuthorization(state,a,at){
50
- if(!Number.isFinite(at)||a.ownership!=='exclusive'||a.publication!=='unpublished'||a.history.head!==state.target.head||a.history.branch!==state.target.branch||!state.target.branch||a.recovery.oid!==state.target.head||a.plan.path!==path.join(state.target.realpath,...a.plan.gitPath.split('/'))||a.plan.old.hash!==hashBytes(a.plan.old.content)||a.plan.new.hash!==hashBytes(a.plan.new.content)||a.plan.old.hash===a.plan.new.hash)return false;
51
- const old=a.approvals.original,next=a.approvals.amendment,changed=Date.parse(a.changedAt);
52
- if(old.version!==a.plan.old.version||old.hash!==a.plan.old.hash||Date.parse(old.approvedAt)>changed||changed>at||!approvalRecord(state,a,old))return false;
53
- if(a.classification==='contract'&&!next||next&&(next.version!==a.plan.new.version||next.hash!==a.plan.new.hash||Date.parse(next.approvedAt)<changed||Date.parse(next.approvedAt)>at||!approvalRecord(state,a,next)))return false;
54
- return a.writers.every(w=>Date.parse(w.stoppedAt)<=at&&state.records.some(r=>r.kind==='note'&&r.messageRef===w.evidenceRef&&r.source==='operator-attested'&&r.actor?.role==='orchestrator'&&r.targetVersion===state.targetVersion&&r.scopeVersion===state.scopeVersion&&r.data?.type==='writer-stopped'&&r.data.assignmentId===w.assignmentId&&r.data.stoppedAt===w.stoppedAt));
55
- }
56
- export function prepareCooperativePlanAmend({state,request,evidence}={}){
57
- const a=request?.arguments,g=evidence?.git,at=evidence?.now;
58
- try{validatePlanAmendArguments(a);}catch{return planDecision(state,'Exact plan-amend evidence required');}
59
- if(request.actor?.role!=='orchestrator'||request.expectedRevision!==state.revision||state.unresolved.some(x=>!x.resolvedBy)||state.intents.some(i=>i.operation==='plan-amend'&&['prepared','unknown','mismatch','failed'].includes(i.status))||!planAuthorization(state,a,at)||!oldPlanObservation(a,g,state.target)||g.recoveryRef!==null||!remoteSnapshotValid(a.remotes,g.configuredRemotes,at,g.history.commits.map(c=>c.oid)))return planDecision(state,'Approval, stopped writers, clean index, local history and unpublished remote attestations required');
60
- return planDecision(state,'Durable intent only; the operator performs any rewrite',{intent:{requestId:request.requestId,operation:'plan-amend',status:'prepared',arguments:structuredClone(a),target:structuredClone(state.target),versions:structuredClone(state.versions),scopeVersion:state.scopeVersion,targetVersion:state.targetVersion,observation:structuredClone(g),fingerprint:fingerprintRequest(request),source:'operator-attested'}},true);
61
- }
62
- export function checkpointCooperativePlanAmend({state,request,evidence}={}){
63
- const d=request?.evidence?.data,intent=state.intents.find(i=>i.requestId===d?.intentId&&i.operation==='plan-amend'),a=intent?.arguments,g=evidence?.git;
64
- if(request?.actor?.role!=='orchestrator'||!objectFields(d,['type','intentId'])||d.type!=='plan-amend-checkpoint'||!intent||intent.status!=='prepared'||intent.checkpoint||!same(intent.target,state.target)||!same(intent.versions,state.versions)||!planAuthorization(state,a,evidence?.now)||!oldPlanObservation(a,g,state.target)||!same(g.recoveryRef,{name:a.recovery.ref,oid:a.recovery.oid})||g.worktree.nonPlanFingerprint!==intent.observation.worktree.nonPlanFingerprint||g.index.tree!==intent.observation.index.tree||!same(g.history.commits,intent.observation.history.commits)||!remoteSnapshotValid(a.remotes,g.configuredRemotes,evidence.now,g.history.commits.map(c=>c.oid)))return planDecision(state,'Current prepared intent, recovery ref and pre-rewrite observation required');
65
- return planDecision(state,'Pre-rewrite checkpoint recorded',{checkpoint:{intentId:intent.requestId,messageRef:request.evidence.messageRef,observedAt:new Date(evidence.now).toISOString(),observation:structuredClone(g)}},true);
66
- }
67
- export function reconcileCooperativePlanAmend({state,intent,result,observations,now}={}){
68
- const transition={result:{...structuredClone(result),status:result?.status==='unknown'?'unknown':result?.status==='failed'?'failed':'mismatch',data:{...structuredClone(result?.data??{}),remoteVerified:false},source:'operator-attested'},observation:observations?.git??null};
69
- const hold=reason=>planDecision(state,reason,transition);
70
- if(!intent||intent.operation!=='plan-amend'||!['prepared','unknown','mismatch'].includes(intent.status)||!intent.checkpoint||!same(intent.target,state.target)||!same(intent.versions,state.versions)||intent.scopeVersion!==state.scopeVersion||intent.targetVersion!==state.targetVersion)return hold('Matching unresolved plan-amend intent and checkpoint required');
71
- if(result?.status!=='succeeded')return hold('Rewrite did not establish a successful result');
72
- const d=result.data,a=intent.arguments,g=observations?.git,target=observations?.target,mapping=d?.mapping,old=intent.observation.history.commits,next=g?.history?.newCommits;
73
- try{validatePlanAmendArguments({...a,remotes:d?.remotes});}catch{return hold('Exact result and fresh remote attestations required');}
74
- if(!objectFields(d,['head','mapping','remotes'])||!Array.isArray(mapping)||mapping.length!==old.length||!mapping.length||mapping.some(m=>!objectFields(m,['old','new']))||new Set(mapping.map(m=>m.old)).size!==mapping.length||new Set(mapping.map(m=>m.new)).size!==mapping.length||!Array.isArray(next)||next.length!==mapping.length||!target||target.realpath!==intent.target.realpath||target.gitCommonDir!==intent.target.gitCommonDir||target.gitDir!==intent.target.gitDir||target.branch!==intent.target.branch||target.head!==d.head||mapping.at(-1).new!==target.head||!same(g?.target,target)||g.index?.tree!==g.index?.headTree||g.index?.stagedPaths?.length!==0||g.worktree?.planClean!==true||g.worktree.nonPlanFingerprint!==intent.observation.worktree.nonPlanFingerprint||!same(g.recoveryRef,{name:a.recovery.ref,oid:a.recovery.oid})||g.plan?.path!==a.plan.path||g.plan.content!==a.plan.new.content||g.plan.hash!==a.plan.new.hash||g.plan.originalHash!==a.plan.old.hash||!same(g.history.commits,old)||!same(remoteIdentities(d.remotes),remoteIdentities(a.remotes))||!remoteSnapshotValid(d.remotes,g.configuredRemotes,now,[...old.map(c=>c.oid),...mapping.map(m=>m.new)]))return hold('Observed target, preservation, mapping, document or remote evidence differs');
75
- const planOid=gitBlob(a.plan.new.content,target.head.length),originalMode=old[0].tree.find(row=>row.path===a.plan.gitPath)?.mode;if(g.plan.mode!==originalMode)return hold('Working plan mode differs');
76
- for(let i=0;i<mapping.length;i++){
77
- const before=old[i],after=next[i],m=mapping[i];
78
- if(!planEntries(after,target.head.length)||m.old!==before.oid||m.new!==after.oid||after.parent!==(i?mapping[i-1].new:a.history.base)||after.author!==before.author||after.authorDate!==before.authorDate||after.message!==before.message||!same(after.headerTemplate,before.headerTemplate))return hold('Commit mapping or metadata differs');
79
- const plan=after.tree.filter(row=>row.path===a.plan.gitPath),oldPlan=before.tree.find(row=>row.path===a.plan.gitPath);if(plan.length!==1||!oldPlan||plan[0].mode!==oldPlan.mode||plan[0].oid!==planOid)return hold('Unexpected plan bytes or mode in rewritten history');
80
- const other=rows=>rows.filter(row=>row.path!==a.plan.gitPath).sort((x,y)=>x.path<y.path?-1:x.path>y.path?1:0);
81
- if(!same(other([...before.tree]),other([...after.tree])))return hold('Non-plan tree changed');
82
- }
83
- transition.result.status='succeeded';transition.target=structuredClone(target);transition.mapping=structuredClone(mapping);return planDecision(state,'Locally observed same-intent amendment; remote claims remain operator-attested',transition,true);
84
- }
85
22
  /** Pure policy decision. Evidence is supplied by a trusted adapter/provider, never tool arguments. */
86
23
  export function evaluate(policy, state, request, evidence){
87
24
  const result=(decision,id,reason,requiredEvidence=[])=>({decision,ruleIds:[id],reason,requiredEvidence,expectedRevision:state?.revision??0,proposedTransition:null,coverage:{platform:request?.platform??'unknown',enforcement:'decision-only'}});
@@ -176,7 +113,6 @@ export function evaluate(policy, state, request, evidence){
176
113
  if(d.kind!=='task'||!accepted||task.status!=='accepted'||request.paths.some(p=>!task.paths.some(base=>within(base,p))))return result('hold','git.orchestrator-accept-commit','accepted task verification required',['git-evidence']);
177
114
  }
178
115
  }
179
- if(request.operation==='plan-amend')return result('hold','runtime.plan-amend','Cooperative plan-amend requires its durable intent and local observer',['plan-amend-intent']);
180
116
  if(EXTERNAL_OPERATIONS.includes(request.operation))return result('hold','external.explicit-user-authority','explicit external target approval must be verified',['external-approval']);
181
117
  if(request.operation==='transition')return result('hold','runtime.transition','result confirmation required',['observed-result']);
182
118
  return result('allow',roleRule,'assigned operation with verified provenance');
@@ -187,20 +123,18 @@ export function evaluateCooperative({policy,state,request,evidence}={}){
187
123
  const base={expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false}};
188
124
  const hold=(id,reason)=>({...base,decision:'hold',ruleIds:[id],reason,requiredEvidence:[],nextActions:[],proposedTransition:null});
189
125
  try{validateCooperativeState(state);validateCooperativeCommand(request);}catch(error){return hold('cooperative.schema',error.message);}
126
+ if(state.intents.some(i=>i.operation==='plan-amend'&&['prepared','unknown','mismatch','failed'].includes(i.status)))return {...hold('cooperative.plan-amend-removed','Legacy plan-amend intent is no longer supported; inspect Git history and any refs/arc/recovery/* refs manually, then start a new workflow'),nextActions:['inspect-legacy-plan-amend','start-new-workflow']};
127
+ if(request.command==='prepare'&&request.input?.operation==='plan-amend')return hold('cooperative.plan-amend-removed','Plan-amend operation is no longer supported');
190
128
  if(policy!==undefined&&policy.workflowKind!=='cooperative')return hold('cooperative.contract','Explicit cooperative policy required');
191
129
  if(state.mode!=='plan'||request.command==='result')return hold('cooperative.unsupported','Operation is not supported in this CLI phase');
192
130
  if(!evidence||!same(evidence.target,state.target))return hold('cooperative.target','Observed target changed');
193
131
  if(!same(evidence.versions,state.versions))return hold('cooperative.versions','Policy or runtime changed');
194
132
  if(request.input&&request.input.expectedRevision!==state.revision)return hold('cooperative.revision','Stale revision');
195
- const checkpoint=request.command==='record'&&request.input.evidence.kind==='note'&&request.input.evidence.data?.type==='plan-amend-checkpoint';
196
- if(unresolvedPlan(state)&&((request.command==='prepare')||(request.command==='record'&&!checkpoint)))return hold('cooperative.plan-amend-unresolved','Resolve the same plan-amend intent before further work');
197
- if(checkpoint)return checkpointCooperativePlanAmend({state,request:request.input,evidence});
198
133
  if(request.command==='record'&&request.input.evidence.kind==='external-approval'&&request.input.actor.role!=='orchestrator')return hold('cooperative.external-approval','Orchestrator records explicit external approval');
199
134
  if(request.command==='record'&&request.input.evidence.kind.startsWith('planner-')||request.command==='prepare'&&request.input.operation==='planner-call')return evaluateCooperativePlanner({state,request,evidence});
200
135
  if(request.command==='prepare'){
201
136
  if(unresolvedExternal(state))return hold('cooperative.external-unresolved','Investigate unresolved external effects before follow-up');
202
137
  if(EXTERNAL_ACTIONS.includes(request.input.operation))return evaluateCooperativeExternal({state,request:request.input,approvalEvidence:state.records.findLast(r=>r.kind==='external-approval'&&r.messageRef===request.input.arguments?.approvalRef)});
203
- if(request.input.operation==='plan-amend')return prepareCooperativePlanAmend({state,request:request.input,evidence});
204
138
  if(request.input.operation==='accept')return evaluateCooperativeAcceptance({state,request:request.input,evidence});
205
139
  if(request.input.operation==='commit')return prepareCooperativeCommit({state,request:request.input,evidence,gitEvidence:evidence.git});
206
140
  return request.input.operation==='assign-agent'?prepareCooperativeAssignment({policy,state,request:request.input,observations:{target:evidence.target,git:evidence.git}}):evaluateCooperativeVerification({state,request:request.input,evidence});
@@ -0,0 +1,32 @@
1
+ // U-B3/U-B4: verified by L5 live evidence (Gemini 0.68.0).
2
+ // U-B7 delegation and U-B9 UUID resume remain unverified; implementation resume stays off.
3
+ export const GEMINI_CONTRACT = Object.freeze({
4
+ prompt: 'Follow the role instructions and task on stdin.',
5
+ eventKinds: Object.freeze({init: 'init', message: 'message', tool_use: 'tool_use', tool_result: 'tool_result', result: 'result'}),
6
+ isolationArgs: Object.freeze(['-e', 'none', '--allowed-mcp-server-names', '__arc_none__']),
7
+ resumeFlag: '--resume', // U-B9: UUID acceptance is unverified; implementation resume stays off.
8
+ delegation: 'undetectable', // U-B7: no verified delegation event schema.
9
+ });
10
+ const text = value => typeof value === 'string' && value !== '' ? value : undefined;
11
+ export function normalizeGeminiStreamEvent(line) {
12
+ let raw = line;
13
+ if (typeof line === 'string') {try {raw = JSON.parse(line);} catch {return {kind: 'unknown', raw};}}
14
+ const kind = raw && Object.hasOwn(GEMINI_CONTRACT.eventKinds, raw.type) ? GEMINI_CONTRACT.eventKinds[raw.type] : 'unknown';
15
+ if (kind === 'unknown') return {kind, raw};
16
+ return {kind, raw, ...(text(raw.session_id) ? {sessionId: raw.session_id} : {}), ...(text(raw.model) ? {model: raw.model} : {}),
17
+ ...(kind === 'message' ? {role: raw.role} : {}),
18
+ ...(typeof raw.content === 'string' ? {text: raw.content} : {}),
19
+ ...(kind === 'result' ? {isError: raw.status !== 'success'} : {})};
20
+ }
21
+ export function evaluateGeminiObservation({state, expected, sessionId}) {
22
+ const observedSession = state.geminiSessionId ?? state.init?.sessionId, model = state.geminiModel ?? state.init?.model;
23
+ const identityOk = Boolean(observedSession && observedSession === sessionId && !state.geminiSessionMismatch);
24
+ const modelMismatch = state.geminiModelMismatch || Boolean(model && model !== expected.model);
25
+ return {reason: !identityOk ? 'execution_identity_unverified' : modelMismatch ? 'model_effort_mismatch' : null,
26
+ claims: {
27
+ identity: identityOk ? {level: 'runtime-observed', source: 'gemini-stream-session', observed: observedSession} : {level: 'unverified', source: 'none'},
28
+ model: {level: model && !modelMismatch ? 'runtime-observed' : 'unverified', source: model ? 'gemini-stream-model' : 'none', requested: expected.model, observed: model ?? null},
29
+ effort: {level: 'unverified', source: 'none', requested: 'default', observed: null},
30
+ permissions: {level: 'runtime-observed', source: 'worktree-snapshot', details: 'git-visible worktree only'},
31
+ }};
32
+ }
@@ -3,7 +3,6 @@ import {inspectPath} from './scope.mjs';
3
3
  import crypto from 'node:crypto';
4
4
  import path from 'node:path';
5
5
  import {spawnSync} from 'node:child_process';
6
- import {constants} from 'node:fs';
7
6
 
8
7
  const oid=value=>typeof value==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
9
8
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
@@ -143,103 +142,6 @@ export async function readCooperativeCommitGitEvidence({target,commit,gitRunner=
143
142
  return {...evidence,commit:{commit,parent:metadata[1],tree:metadata[2],paths:committedPaths,head:target.head}};
144
143
  }
145
144
 
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
145
  const validGitPaths=values=>Array.isArray(values)&&values.every(gitPath)&&unique(values);
244
146
  const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||!path.isAbsolute(relative)&&relative!=='..'&&!relative.startsWith('..'+path.sep);};
245
147
  /** Provenance-neutral Git checks shared by trusted and cooperative callers.
@@ -1,3 +1,4 @@
1
+ import {isPlatformId} from './platform-registry.mjs';
1
2
  import {validateWorkflowState, text} from './schema.mjs';
2
3
  import {ROLES} from './operations.mjs';
3
4
  import fs from 'node:fs/promises';
@@ -31,7 +32,7 @@ export function registerAgentObservation(state, observation){
31
32
 
32
33
  /** A raw start is audit only; verified correlation may bind an existing assignment. */
33
34
  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
+ if(!path.isAbsolute(statePath??'')||input?.hook_event_name!=='SubagentStart'||input.session_id!==sessionRef||!text(sessionRef)||!text(input.agent_id)||!isPlatformId(platform))throw Error('Trusted observation target and complete start required');
35
36
  const parent=await fs.realpath(path.dirname(statePath));statePath=path.join(parent,path.basename(statePath));let lock;
36
37
  try{
37
38
  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');
@@ -2,44 +2,33 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
4
  import { spawn } from 'node:child_process';
5
+ import {runtimeRegistryOf} from './platform-registry.mjs';
5
6
 
6
7
  const environments = new WeakMap();
7
- export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
8
- if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
9
- if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
10
- userHome = path.resolve(userHome);
11
- if (!env || typeof env !== 'object') throw Error('env must be an environment object');
12
- const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
13
- let home;
14
- if (platform === 'codex') {
15
- const raw = env.CODEX_HOME;
16
- if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
17
- const expanded = expand(raw ?? path.join(userHome, '.codex'));
18
- if (path.isAbsolute(expanded)) home = path.resolve(expanded);
19
- 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); }
20
- } else {
21
- home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
22
- 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');
23
- }
24
- if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
25
- return home;
8
+ const authKinds = new WeakMap();
9
+ export function resolveConfigHome(platform, context = {}) {
10
+ const descriptor = runtimeRegistryOf(context).getPlatform(platform);
11
+ if (!descriptor) throw Error('Target must be codex or claude');
12
+ return descriptor.home.resolve(context);
26
13
  }
27
- export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
28
- if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
14
+ export function resolveLocalCli(platform, { cwd, userHome, env = process.env, runtimePlatforms } = {}) {
15
+ const descriptor = runtimeRegistryOf({runtimePlatforms}).getPlatform(platform);
16
+ if (!descriptor) return { platform, reason: 'unsupported_platform' };
29
17
  let home;
30
18
  try {
31
19
  if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
32
- home = resolveConfigHome(platform, { cwd, userHome, env });
20
+ home = resolveConfigHome(platform, { cwd, userHome, env, runtimePlatforms });
33
21
  } catch { return { platform, reason: 'invalid_context' }; }
34
22
  const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
35
23
  let executable;
36
24
  for (const dir of dirs) {
37
- const candidate = path.resolve(cwd, dir || '.', platform);
25
+ const candidate = path.resolve(cwd, dir || '.', descriptor.cli.command);
38
26
  try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
39
27
  }
40
28
  if (!executable) return { platform, reason: 'cli_not_found' };
41
29
  const context = Object.freeze({ platform, executable, cwd, configHome: home });
42
- environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
30
+ environments.set(context, Object.freeze({ ...env, [descriptor.home.env]: home }));
31
+ authKinds.set(context, descriptor.auth.kind);
43
32
  return context;
44
33
  }
45
34
  export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
@@ -188,6 +177,7 @@ export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000
188
177
  return value;
189
178
  }
190
179
  export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
180
+ if (authKinds.get(context) === 'none') return {authStatus: 'unknown', reason: 'auth_unverified'};
191
181
  const platform = context?.platform;
192
182
  const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
193
183
  if (platform !== 'claude') return result('unknown', 'invalid_context');
@@ -2,5 +2,5 @@
2
2
  export const ROLES = Object.freeze(['orchestrator','scouter','planner','implementer','qa','reviewer']);
3
3
  export const GIT_OPERATIONS = Object.freeze(['stage','commit','push','merge','rebase','reset','branch-create','branch-switch','worktree-create','worktree-remove']);
4
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']});
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','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','install',...GIT_OPERATIONS,...EXTERNAL_OPERATIONS],scouter:['read'],planner:['read','draft'],implementer:['read','write','check'],qa:['read','check','temporary-write'],reviewer:['read','review']});
@@ -0,0 +1,130 @@
1
+ import path from 'node:path';
2
+
3
+ export const CAPABILITY_KEYS = Object.freeze([
4
+ 'install', 'standalone', 'compositeRole', 'compositeHost', 'bridge',
5
+ 'nativeProfile', 'authProbe', 'catalog', 'watch',
6
+ ]);
7
+
8
+ export const CAPABILITY_PREREQUISITES = Object.freeze({
9
+ install: Object.freeze([]), nativeProfile: Object.freeze(['install']),
10
+ catalog: Object.freeze(['install']), standalone: Object.freeze(['install', 'nativeProfile', 'catalog']),
11
+ bridge: Object.freeze(['install', 'catalog']), compositeRole: Object.freeze(['bridge']),
12
+ compositeHost: Object.freeze(['install', 'nativeProfile']), authProbe: Object.freeze([]), watch: Object.freeze([]),
13
+ });
14
+
15
+ function frozenCopy(value) {
16
+ if (Array.isArray(value)) return Object.freeze(value.map(frozenCopy));
17
+ if (value && typeof value === 'object') return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, frozenCopy(entry)])));
18
+ return value;
19
+ }
20
+
21
+ export function createPlatformRegistry(descriptors) {
22
+ const ids = new Set(), anchors = new Set(), displays = new Set();
23
+ const platforms = Object.freeze(descriptors.map(descriptor => {
24
+ const {id, anchorOrder, displayOrder} = descriptor;
25
+ if (ids.has(id)) throw Error(`Duplicate platform id: ${id}`);
26
+ if (anchors.has(anchorOrder)) throw Error(`Duplicate platform anchorOrder: ${anchorOrder}`);
27
+ if (displays.has(displayOrder)) throw Error(`Duplicate platform displayOrder: ${displayOrder}`);
28
+ ids.add(id); anchors.add(anchorOrder); displays.add(displayOrder);
29
+ const capabilities = Object.fromEntries(CAPABILITY_KEYS.map(key => [key, descriptor.capabilities?.[key] ?? {state: 'off'}]));
30
+ for (const [key, prerequisites] of Object.entries(CAPABILITY_PREREQUISITES)) {
31
+ if (capabilities[key].state !== 'verified') continue;
32
+ for (const prerequisite of prerequisites) if (capabilities[prerequisite].state !== 'verified') throw Error(`${id} capability ${key} requires ${prerequisite}`);
33
+ }
34
+ return frozenCopy({...descriptor, capabilities});
35
+ }).sort((a, b) => a.anchorOrder - b.anchorOrder));
36
+ const byId = new Map(platforms.map(platform => [platform.id, platform]));
37
+ const platformIds = Object.freeze(platforms.map(platform => platform.id));
38
+ const displayOrder = Object.freeze([...platforms].sort((a, b) => a.displayOrder - b.displayOrder));
39
+ return Object.freeze({
40
+ platforms,
41
+ platformIds: () => platformIds,
42
+ getPlatform: id => byId.get(id) ?? null,
43
+ byDisplayOrder: () => displayOrder,
44
+ byAnchorOrder: () => platforms,
45
+ isPlatformId: value => byId.has(value),
46
+ });
47
+ }
48
+
49
+ function resolveHome(platform, {userHome, env = {}, cwd} = {}) {
50
+ if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
51
+ userHome = path.resolve(userHome);
52
+ if (!env || typeof env !== 'object') throw Error('env must be an environment object');
53
+ const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
54
+ let home;
55
+ if (platform === 'codex') {
56
+ const raw = env.CODEX_HOME;
57
+ if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
58
+ const expanded = expand(raw ?? path.join(userHome, '.codex'));
59
+ if (path.isAbsolute(expanded)) home = path.resolve(expanded);
60
+ 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); }
61
+ } else if (platform === 'gemini') {
62
+ if (env.GEMINI_CLI_HOME !== undefined) throw Error('GEMINI_CLI_HOME is not verified');
63
+ home = path.join(userHome, '.gemini');
64
+ } else {
65
+ home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
66
+ 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');
67
+ }
68
+ if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
69
+ return home;
70
+ }
71
+
72
+ const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value);
73
+ const verifiedCapabilities = Object.fromEntries(CAPABILITY_KEYS.map(key => [key, {state: 'verified'}]));
74
+
75
+ export const DEFAULT_PLATFORM_REGISTRY = createPlatformRegistry([
76
+ {
77
+ id: 'codex', label: 'Codex', displayOrder: 1, anchorOrder: 1,
78
+ home: {env: 'CODEX_HOME', resolve: context => resolveHome('codex', context)},
79
+ cli: {command: 'codex', supportedVersions: null},
80
+ auth: {kind: 'codex-refresh'},
81
+ models: {effortField: 'model_reasoning_effort'},
82
+ profile: {
83
+ ext: 'toml',
84
+ standaloneName: role => role,
85
+ routingName: role => `arc_routing_${role.slice(4)}`,
86
+ },
87
+ executionEnvironments: ['codex-cli', 'codex-desktop'],
88
+ routing: {validatePair: (model, effort) => validText(model) && validText(effort)},
89
+ capabilities: verifiedCapabilities,
90
+ },
91
+ {
92
+ id: 'claude', label: 'Claude', displayOrder: 0, anchorOrder: 0,
93
+ home: {env: 'CLAUDE_CONFIG_DIR', resolve: context => resolveHome('claude', context)},
94
+ cli: {command: 'claude', supportedVersions: null},
95
+ auth: {kind: 'cli-status-json'},
96
+ models: {effortField: 'effort'},
97
+ profile: {
98
+ ext: 'md',
99
+ standaloneName: role => `arc-${role.slice(4)}`,
100
+ routingName: role => `arc-routing-${role.slice(4)}`,
101
+ },
102
+ executionEnvironments: ['claude-cli', 'claude-desktop'],
103
+ routing: {validatePair: (model, effort) => validText(model) && validText(effort) && /^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && ['low', 'medium', 'high', 'xhigh', 'max'].includes(effort)},
104
+ capabilities: verifiedCapabilities,
105
+ },
106
+ {
107
+ id: 'gemini', label: 'Gemini', displayOrder: 2, anchorOrder: 2,
108
+ home: {env: 'GEMINI_CLI_HOME', resolve: context => resolveHome('gemini', context)},
109
+ cli: {command: 'gemini', supportedVersions: '>=0.68.0 <0.69.0'},
110
+ auth: {kind: 'none'},
111
+ models: {effortField: 'effort'},
112
+ profile: {
113
+ ext: 'md',
114
+ standaloneName: role => `arc-${role.slice(4)}`,
115
+ routingName: role => `arc-routing-${role.slice(4)}`,
116
+ },
117
+ executionEnvironments: ['gemini-cli'],
118
+ routing: {validatePair: (model, effort) => validText(model) && /^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && effort === 'default'},
119
+ capabilities: {install: {state: 'verified'}, nativeProfile: {state: 'verified'}, catalog: {state: 'verified'}, standalone: {state: 'verified'}, bridge: {state: 'verified'}, compositeRole: {state: 'verified'}, ...Object.fromEntries(Object.entries({
120
+ compositeHost: 'composite host not verified',
121
+ authProbe: 'no official auth status command', watch: 'watch support out of scope',
122
+ }).map(([key, reason]) => [key, {state: 'off', reason}]))},
123
+ },
124
+ ]);
125
+
126
+ export const RUNTIME_PLATFORMS = DEFAULT_PLATFORM_REGISTRY.platforms;
127
+ export const {platformIds, getPlatform, byDisplayOrder, byAnchorOrder, isPlatformId} = DEFAULT_PLATFORM_REGISTRY;
128
+ export const runtimeRegistryOf = context => context?.runtimePlatforms ?? DEFAULT_PLATFORM_REGISTRY;
129
+ export const standaloneProfileFile = (descriptor, role) => `arc-${role.slice(4)}.${descriptor.profile.ext}`;
130
+ export const routingProfileFile = (descriptor, role) => `arc-routing-${role.slice(4)}.${descriptor.profile.ext}`;
@@ -1,6 +1,7 @@
1
1
  // Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
2
2
  import crypto from 'node:crypto';
3
3
  import path from 'node:path';
4
+ import {GEMINI_CONTRACT} from './gemini-stream.mjs';
4
5
  import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
5
6
 
6
7
  const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer'];
@@ -10,12 +11,23 @@ export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
10
11
  arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
11
12
  arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_qa: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
12
13
  },
14
+ gemini: {
15
+ arc_scouter: {approvalMode: 'plan', sandbox: false}, arc_planner: {approvalMode: 'plan', sandbox: false},
16
+ arc_implementer: {approvalMode: 'auto_edit', sandbox: true}, arc_qa: {approvalMode: 'auto_edit', sandbox: true}, arc_reviewer: {approvalMode: 'plan', sandbox: false}
17
+ },
13
18
  codex: {
14
19
  arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
15
20
  arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
16
21
  }
17
22
  });
18
23
 
24
+ const BRIDGE_IMPLEMENTATIONS = new Map([
25
+ ['claude', {parse: parseClaude, buildArgs: buildClaudeArgs}],
26
+ ['codex', {parse: parseCodex, buildArgs: buildCodexArgs}],
27
+ ['gemini', {parse: parseGemini, buildArgs: buildGeminiArgs}],
28
+ ]);
29
+ export const BRIDGE_PLATFORM_IDS = Object.freeze([...BRIDGE_IMPLEMENTATIONS.keys()]);
30
+
19
31
  const bad = message => { throw Error(`Invalid composite profile: ${message}`); };
20
32
  const unquote = raw => {
21
33
  const value = raw.trim();
@@ -47,6 +59,26 @@ function parseClaude(text) {
47
59
  return {name: fields.name, description: fields.description, model: fields.model, effort: fields.effort, tools, instructions};
48
60
  }
49
61
 
62
+ // Managed Gemini profiles use scalar-only frontmatter. Keep this independent of installer imports.
63
+ function parseGemini(text) {
64
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]+)$/.exec(text);
65
+ if (!match || !match[2].trim()) bad('missing Gemini frontmatter or instructions');
66
+ const fields = {};
67
+ const nonStringScalar = /^(?:~|null|true|false|yes|no|on|off|[-+]?(?:\.inf|\.nan|0[xob][0-9a-f_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:e[-+]?\d+)?)|\d{4}-\d{2}-\d{2}(?:[Tt ].*)?)$/i;
68
+ for (const line of match[1].split(/\r?\n/)) {
69
+ const entry = /^([a-z][a-zA-Z0-9_-]*): (.+)$/.exec(line);
70
+ if (!entry || Object.hasOwn(fields, entry[1])) bad('malformed or duplicate Gemini field');
71
+ const value = entry[2];
72
+ if (value !== value.trim() || /[\p{Cc}\u2028\u2029{}#&*!|>"']/u.test(value)
73
+ || /^(?:[-?:](?:\s|$)|[\[\],%@`])/.test(value) || value.includes(': ') || nonStringScalar.test(value)) bad('unsupported Gemini scalar');
74
+ fields[entry[1]] = value;
75
+ }
76
+ for (const key of ['name', 'description', 'model']) if (!fields[key]) bad(`missing ${key}`);
77
+ if (Object.hasOwn(fields, 'effort')) bad('Gemini effort must be omitted');
78
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(fields.model)) bad('invalid Gemini model');
79
+ return {name: fields.name, description: fields.description, model: fields.model, effort: 'default', tools: null, instructions: match[2].replaceAll('\r\n', '\n')};
80
+ }
81
+
50
82
  const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
51
83
  // Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
52
84
  function readMultiline(lines, index, rest) {
@@ -101,12 +133,19 @@ function parseCodex(text) {
101
133
 
102
134
  /** Narrow extractor: the installed runtime cannot import lib/models, so only the managed profile shapes are accepted. */
103
135
  export function parseCompositeProfile(platform, bytes) {
104
- if (platform !== 'claude' && platform !== 'codex') bad('unknown platform');
136
+ const implementation = BRIDGE_IMPLEMENTATIONS.get(platform);
137
+ if (!implementation) bad('unknown platform');
105
138
  const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? '');
106
139
  let text;
107
140
  try { text = new TextDecoder('utf-8', {fatal: true}).decode(buffer); } catch { bad('not valid UTF-8'); }
108
141
  if (text.charCodeAt(0) === 0xfeff) bad('unexpected BOM');
109
- return platform === 'claude' ? parseClaude(text) : parseCodex(text);
142
+ return implementation.parse(text);
143
+ }
144
+
145
+ export function buildBridgeArgs(platform, options) {
146
+ const implementation = BRIDGE_IMPLEMENTATIONS.get(platform);
147
+ if (!implementation) bad('unknown platform');
148
+ return implementation.buildArgs(options);
110
149
  }
111
150
 
112
151
  const permissionsFor = (platform, role) => {
@@ -146,3 +185,19 @@ export function buildCodexArgs({role, profile, worktree, resultPath, threadId =
146
185
  }
147
186
 
148
187
  export const argsDigest = args => 'sha256:' + crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');
188
+
189
+ /** L5 verifies run/observe/cancel and isolation; UUID resume remains unverified. */
190
+ export function buildGeminiArgs({role, model, profile, sessionId, policyFile, promptFlag = GEMINI_CONTRACT.prompt, resume = false}) {
191
+ const permissions = permissionsFor('gemini', role);
192
+ if (typeof sessionId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) throw Error('Gemini sessionId must be a UUID');
193
+ if (typeof policyFile !== 'string' || !path.isAbsolute(policyFile)) throw Error('Absolute policyFile required');
194
+ if (promptFlag !== GEMINI_CONTRACT.prompt) throw Error('Unsupported Gemini prompt');
195
+ const selectedModel = requireText(model ?? profile?.model, 'model');
196
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(selectedModel) || selectedModel === 'yolo') throw Error('Invalid Gemini model');
197
+ const args = ['-p', promptFlag, '-m', selectedModel, '-o', 'stream-json', '--session-id', sessionId,
198
+ '--approval-mode', permissions.approvalMode, '--policy', policyFile];
199
+ if (permissions.sandbox) args.push('--sandbox');
200
+ args.push(...GEMINI_CONTRACT.isolationArgs);
201
+ if (resume) args.push(GEMINI_CONTRACT.resumeFlag, sessionId);
202
+ return args;
203
+ }