@yunhozz/arc 0.3.3 → 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 (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,331 +0,0 @@
1
- import {evaluateCooperativeExternal,reconcileCooperativeExternal,EXTERNAL_ACTIONS,unresolvedExternal} from './external.mjs';
2
- export {evaluateCooperativeExternal,reconcileCooperativeExternal};
3
- import {evaluateCooperativeAcceptance,prepareCooperativeCommit} from './acceptance.mjs';
4
- import {evaluateCooperativeVerification} from './verification.mjs';
5
- import {prepareCooperativeAssignment} from './assignment.mjs';
6
- /**
7
- * @typedef {object} GateDecision
8
- * @property {'allow'|'deny'|'hold'} decision
9
- * @property {string[]} ruleIds
10
- * @property {string} reason
11
- * @property {string[]} requiredEvidence
12
- * @property {number} expectedRevision
13
- * @property {object|null} proposedTransition
14
- * @property {object} coverage
15
- */
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';
20
- import {validateWorkflowState, validateRequest, validateEvidence,validatePlannerStage} from './schema.mjs';
21
- import {ROLES, ROLE_OPERATIONS, GIT_OPERATIONS, EXTERNAL_OPERATIONS} from './operations.mjs';
22
- const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
23
- 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
- /** Pure policy decision. Evidence is supplied by a trusted adapter/provider, never tool arguments. */
86
- export function evaluate(policy, state, request, evidence){
87
- 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'}});
88
- try{validateWorkflowState(state);validateRequest(request);validateEvidence(evidence);}catch(error){return result('hold','runtime.schema',error.message,['valid-state-request-evidence']);}
89
- if(policy?.runtime?.schemaVersion!==1||!same(policy.runtime.roles,ROLES)||!Array.isArray(policy.runtime.ruleIds)||!Array.isArray(policy.runtime.requiredEvidence)||policy.runtime.status!=='decision-only')return result('hold','runtime.policy','runtime policy unavailable',['runtime-policy']);
90
- const actor=state.identities.find(i=>i.actorRef===request.actorRef);
91
- if(!actor)return result('hold','runtime.identity','platform identity unresolved',['platform-identity']);
92
- const role=actor.role;
93
- const roleRule={orchestrator:'role.orchestrator-boundary',scouter:'role.scouter-read-only',planner:'role.planner-draft-only',implementer:'role.implementer-implementation',qa:'role.qa-verification',reviewer:'role.reviewer-independent'}[role];
94
- if(!ROLE_OPERATIONS[role]?.includes(request.operation))return result('deny',GIT_OPERATIONS.includes(request.operation)?'git.specialists-deny':roleRule,'operation forbidden for assigned role');
95
- const lease=state.leases.find(l=>l.actorRef===actor.actorRef);
96
- if(lease?.status==='retired')return result('deny','runtime.identity','retired identity');
97
- if(!lease||lease.status!=='active'||lease.taskId!==request.taskId||actor.taskId!==request.taskId)return result('hold','runtime.identity','active task lease missing',['active-lease']);
98
- const observation=evidence.provenance.find(p=>p.id===actor.observationRef&&p.source==='platform-event'&&p.actorRef===actor.actorRef&&p.platform===request.platform&&p.verification.sourceRef===p.eventRef);
99
- if(!observation)return result('hold','runtime.identity','platform observation unavailable',['platform-observation']);
100
- if(!same(evidence.target,state.target)||evidence.revision!==state.revision||!same(evidence.versions,state.versions))return result('hold','runtime.target','target revision or versions mismatch',['current-target-versions']);
101
- if(!within(state.target.realpath,request.cwd))return result('deny','scope.non-escalation','cwd outside workspace');
102
- const assignment=state.assignments.find(a=>a.actorRef===actor.actorRef&&a.taskId===request.taskId&&a.role===role);
103
- if(!assignment||!assignment.operations.includes(request.operation))return result('hold','runtime.assignment','approved operation assignment missing',['assignment']);
104
- const approval=state.approvals.find(a=>a.id===assignment.approvalRef);
105
- const proof=evidence.provenance.find(p=>p.id===approval?.id&&p.source===approval?.source&&p.messageRef===approval?.messageRef&&p.contentHash===approval?.contentHash&&p.verification.sourceRef===p.messageRef);
106
- if(!approval||!proof||approval.scope.taskId!==request.taskId||approval.scope.target!==state.target.realpath||!approval.scope.operations.includes(request.operation))return result('hold','runtime.approval','user approval provenance unavailable',['user-approval']);
107
- for(const filename of [request.cwd,...request.paths]){
108
- const resolved=evidence.resolvedPaths?.find(p=>p.path===filename)?.realpath;
109
- if(!resolved||!path.isAbsolute(resolved))return result('hold','runtime.paths','resolved path evidence missing',['resolved-paths']);
110
- if(!within(state.target.realpath,resolved))return result('deny','scope.non-escalation','resolved path escapes workspace');
111
- if(filename!==request.cwd&&(!assignment.paths.some(p=>within(p,resolved))||!approval.scope.paths.some(p=>within(p,resolved))))return result('deny','scope.non-escalation','path outside assigned approval');
112
- }
113
- const fact=kind=>evidence.facts?.find(f=>f.kind===kind&&f.workflowId===state.workflowId&&f.revision===state.revision&&same(f.target,state.target)&&f.policyHash===state.versions.policyHash&&evidence.provenance.some(p=>p.id===f.sourceRef));
114
- const task=state.tasks.find(t=>t.id===request.taskId);
115
- if(!task)return result('hold','runtime.assignment','task unavailable',['task']);
116
- if(role==='implementer'&&['accepted','committed'].includes(task.status))return result('deny','runtime.identity','task execution ended');
117
- if(request.operation==='temporary-write'){
118
- const temporary=assignment.temporary;
119
- if(!temporary||temporary.cleanupOwner!==request.actorRef||!Number.isFinite(Date.parse(temporary.expiresAt))||!Number.isFinite(Date.parse(evidence.observedAt))||Date.parse(temporary.expiresAt)<=Date.parse(evidence.observedAt)||!request.paths.every(p=>temporary.paths?.some(base=>within(base,p))))return result('hold','role.qa-verification','temporary scope lifetime and cleanup ownership required',['temporary-assignment']);
120
- }
121
- if(request.operation==='check'){
122
- if(!assignment.checks?.some(c=>same(c,request.descriptor)))return result('hold',roleRule,'exact assigned check descriptor required',['check-descriptor']);
123
- }
124
- if(role==='orchestrator'&&request.operation==='write'&&request.descriptor.kind!=='document')return result('hold','role.orchestrator-boundary','direct implementation requires reviewed small-task exception',['small-task-exception']);
125
- if(request.operation==='assign-agent'){
126
- const d=request.descriptor;
127
- if(!ROLES.includes(d.role)||d.taskId!==request.taskId)return result('deny','runtime.identity','invalid assignment');
128
- const previous=state.identities.find(i=>i.actorRef===d.actorRef);
129
- if(previous&&(previous.taskId!==d.taskId||state.leases.some(l=>l.actorRef===d.actorRef&&l.status==='retired')))return result('deny','runtime.identity','identity cannot cross tasks or revive');
130
- if(d.role==='implementer'){
131
- if(state.mode==='plan'){
132
- // T3 supplies verified Git object evidence. Local assertions never satisfy this gate.
133
- if(!state.documents.some(d=>d.kind==='spec')||!state.documents.some(d=>d.kind==='plan'))return result('hold','runtime.docs-commit','approved complete spec and plan required',['approved-documents','docs-only-commit']);
134
- const docs=fact('docs-commit')?.data;
135
- const approved=state.documents.every(d=>state.approvals.some(a=>a.id===d.approvalRef&&a.contentHash===d.contentHash&&evidence.provenance.some(p=>p.id===a.id&&p.source===a.source&&p.verification.sourceRef===p.messageRef&&p.messageRef===a.messageRef&&p.contentHash===d.contentHash)));
136
- if(!approved||!docs||!docs.commit||!docs.parent||!docs.tree||!same(docs.documents,state.documents)||!same([...docs.paths??[]].sort(),state.documents.map(d=>d.gitPath).sort())||state.documents.some(d=>d.commit!==docs.commit))return result('hold','runtime.docs-commit','Git object and approval verification required',['verified-docs-only-commit']);
137
- }
138
- else return result('hold','runtime.mode','mode name does not establish exception eligibility',['verified-mode-exception']);
139
- }
140
- const correlation=fact('assignment-correlation');
141
- const expected={requestId:request.requestId,platform:request.platform,...d};
142
- const correlationProof=evidence.provenance.find(p=>p.id===correlation?.sourceRef&&p.source==='platform-event'&&p.verification.sourceRef===p.eventRef&&p.platform===request.platform&&p.actorRef===request.actorRef&&p.correlationRef===d.correlationRef&&p.requestId===request.requestId);
143
- if(d.actorRef!==undefined||!d.correlationRef||!correlationProof||!same(correlation?.data,expected))return result('hold','runtime.identity','trusted platform request correlation required',['assignment-correlation']);
144
- if(!Array.isArray(d.paths)||!d.paths.length||!same([...d.paths].sort(),[...request.paths].sort())||!Array.isArray(d.operations)||!d.operations.length||d.approvalRef!==approval.id||!approval.scope.roles?.some(role=>role===d.role)||d.paths.some(p=>!task.paths.some(base=>within(base,p)))||d.operations.some(op=>!ROLE_OPERATIONS[d.role].includes(op)||!approval.scope.operations.includes(op)))return result('hold','runtime.assignment','delegated role paths operations and approval must match',['delegated-scope']);
145
- if(d.checks&&(!Array.isArray(approval.scope.checks)||d.checks.some(c=>!approval.scope.checks.some(approved=>same(approved,c)))))return result('hold','runtime.assignment','delegated checks not approved',['delegated-checks']);
146
- if(d.temporary&&!same(d.temporary,approval.scope.temporary))return result('hold','runtime.assignment','delegated temporary scope not approved',['delegated-temporary-scope']);
147
- if(state.assignments.some(a=>a.assignmentId===request.requestId||a.correlationRef===d.correlationRef))return result('hold','runtime.identity','assignment correlation already registered',['new-assignment-correlation']);
148
- const next=structuredClone(state);
149
- if(d.role==='planner'){
150
- const stage=state.plannerLedger?.stages.find(s=>s.id===d.plannerCall?.stageId),proof=fact('planner-call');
151
- const contract=stage&&{document:stage.document,inputVersion:stage.inputVersion,criteriaVersion:stage.criteriaVersion,scopeVersion:stage.scopeVersion};
152
- if(!stage||stage.workflowId!==state.workflowId||stage.approvalRef!==approval.id||!same(approval.scope.plannerStage,contract)||!d.paths.includes(stage.document.path)||proof?.sourceRef!==correlation.sourceRef||!same({stageId:proof?.data.stageId,inputVersion:proof?.data.inputVersion,criteriaVersion:proof?.data.criteriaVersion,scopeVersion:proof?.data.scopeVersion},{stageId:stage.id,inputVersion:stage.inputVersion,criteriaVersion:stage.criteriaVersion,scopeVersion:stage.scopeVersion}))return result('hold','runtime.planner-call','Current approved Planner stage and provider evidence required',['planner-stage-ledger','planner-call-evidence']);
153
- if(stage.document.kind==='plan'&&!state.documents.some(doc=>doc.kind==='spec'&&state.approvals.some(a=>a.id===doc.approvalRef&&a.contentHash===doc.contentHash&&evidence.provenance.some(p=>p.id===a.id&&p.messageRef===a.messageRef&&p.contentHash===doc.contentHash&&p.verification.sourceRef===a.messageRef))))return result('hold','runtime.planner-call','Approved spec prerequisite required',['approved-spec']);
154
- const planner=evaluatePlannerCall({stage,request:{...d.plannerCall,requestId:request.requestId},evidence:{artifacts:proof.data.artifacts,semanticProvenance:'operator-attested'}});
155
- if(planner.decision!=='allow')return planner;
156
- next.plannerLedger.stages[next.plannerLedger.stages.findIndex(s=>s.id===stage.id)]=planner.proposedTransition;
157
- }
158
- next.assignments.push({assignmentId:request.requestId,requestId:request.requestId,requestedBy:request.actorRef,status:'pending',actorRef:null,platform:request.platform,correlationRef:d.correlationRef,role:d.role,taskId:d.taskId,paths:[...d.paths],operations:[...d.operations],approvalRef:d.approvalRef,...(d.role==='planner'?{plannerStageId:d.plannerCall.stageId}:{}),...(d.checks?{checks:structuredClone(d.checks)}:{}),...(d.temporary?{temporary:structuredClone(d.temporary)}:{})});
159
- try{validateWorkflowState(next);}catch{return result('hold','runtime.assignment','invalid pending assignment scope',['valid-assignment']);}
160
- return {...result('allow','runtime.assignment','pending assignment authorized; observed spawn result still required'),proposedTransition:next};
161
- }
162
- if(request.operation==='accept'){
163
- const d=request.descriptor;const observed=fact('acceptance')?.data;
164
- const checks=Array.isArray(d.checkIds)&&task.requiredChecks?.every(id=>d.checkIds?.includes(id)&&state.checks.some(c=>c.id===id&&c.taskId===task.id&&c.status==='passed'&&c.fingerprint===d.fingerprint&&c.resultRef&&c.actorRef!==actor.actorRef&&state.identities.some(i=>i.actorRef===c.actorRef&&i.taskId===task.id&&i.role==='qa')));
165
- const findings=state.findings.filter(f=>f.taskId===task.id);
166
- if(!observed||!same(observed,d)||!d.fingerprint||!task.criteria?.length||!same(task.criteria,d.criteria)||!checks||findings.some(f=>!Array.isArray(d.findingIds)||!d.findingIds.includes(f.id)||!f.resolutionRef))return result('hold','git.orchestrator-accept-commit','criteria checks findings and fingerprint verification required',['acceptance-evidence']);
167
- }
168
- if(GIT_OPERATIONS.includes(request.operation)){
169
- const d=request.descriptor;const observed=fact('git-index')?.data;
170
- const relative=p=>typeof p==='string'&&p.length>0&&!/[\\\x00\r\n:]/.test(p)&&!p.startsWith('/')&&!p.split('/').some(x=>!x||x==='.'||x==='..');
171
- if(!observed||!same(observed,d)||d.parent!==state.target.head||!d.indexTree||!Array.isArray(d.paths)||!d.paths.length||!d.paths.every(relative)||new Set(d.paths).size!==d.paths.length||!same([...d.paths.map(p=>path.join(state.target.realpath,...p.split('/')))].sort(),[...request.paths].sort()))return result('hold','git.orchestrator-accept-commit','actual Git objects and relative path verification required',['git-evidence']);
172
- if(d.kind==='documents'){
173
- if(state.mode!=='plan'||state.documents.length!==2||!same(state.documents.map(x=>x.kind).sort(),['plan','spec'])||!same([...d.paths].sort(),state.documents.map(x=>x.gitPath).sort())||state.documents.some(doc=>doc.path!==path.join(state.target.realpath,...doc.gitPath.split('/'))||!state.approvals.some(a=>a.id===doc.approvalRef&&a.contentHash===doc.contentHash&&evidence.provenance.some(p=>p.id===a.id&&p.source===a.source&&p.messageRef===a.messageRef&&p.contentHash===doc.contentHash&&p.verification.sourceRef===a.messageRef))))return result('hold','runtime.docs-commit','exact approved documents required',['approved-documents']);
174
- }else{
175
- const accepted=state.acceptances.find(a=>a.taskId===task.id&&a.fingerprint===d.fingerprint&&state.identities.some(i=>i.actorRef===a.actorRef&&i.role==='orchestrator'));
176
- 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
- }
178
- }
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
- if(EXTERNAL_OPERATIONS.includes(request.operation))return result('hold','external.explicit-user-authority','explicit external target approval must be verified',['external-approval']);
181
- if(request.operation==='transition')return result('hold','runtime.transition','result confirmation required',['observed-result']);
182
- return result('allow',roleRule,'assigned operation with verified provenance');
183
- }
184
-
185
- /** Cooperative statements never enter provider validation or identity resolution. */
186
- export function evaluateCooperative({policy,state,request,evidence}={}){
187
- const base={expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false}};
188
- const hold=(id,reason)=>({...base,decision:'hold',ruleIds:[id],reason,requiredEvidence:[],nextActions:[],proposedTransition:null});
189
- try{validateCooperativeState(state);validateCooperativeCommand(request);}catch(error){return hold('cooperative.schema',error.message);}
190
- if(policy!==undefined&&policy.workflowKind!=='cooperative')return hold('cooperative.contract','Explicit cooperative policy required');
191
- if(state.mode!=='plan'||request.command==='result')return hold('cooperative.unsupported','Operation is not supported in this CLI phase');
192
- if(!evidence||!same(evidence.target,state.target))return hold('cooperative.target','Observed target changed');
193
- if(!same(evidence.versions,state.versions))return hold('cooperative.versions','Policy or runtime changed');
194
- 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
- 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
- if(request.command==='record'&&request.input.evidence.kind.startsWith('planner-')||request.command==='prepare'&&request.input.operation==='planner-call')return evaluateCooperativePlanner({state,request,evidence});
200
- if(request.command==='prepare'){
201
- if(unresolvedExternal(state))return hold('cooperative.external-unresolved','Investigate unresolved external effects before follow-up');
202
- 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
- if(request.input.operation==='accept')return evaluateCooperativeAcceptance({state,request:request.input,evidence});
205
- if(request.input.operation==='commit')return prepareCooperativeCommit({state,request:request.input,evidence,gitEvidence:evidence.git});
206
- 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});
207
- }
208
- if(request.command==='record'&&(['check','review','finding'].includes(request.input.evidence.kind)||request.input.evidence.kind==='acceptance-evidence'&&request.input.evidence.data.kind==='task'))return evaluateCooperativeVerification({state,request:{...request.input,operation:'verification-record'},evidence});
209
- if(request.command==='status'&&(state.tasks.some(t=>t.invalidated||t.status==='committed'&&!state.commits.some(c=>c.taskId===t.id&&c.postCommitFingerprint===evidence.changes?.tasks?.[t.id]))||state.findings.some(f=>f.status!=='closed')||state.checks.some((c,index)=>!(c.scope==='task'&&state.tasks.some(t=>t.id===c.taskId&&t.status==='committed'))&&!state.checks.slice(index+1).some(next=>next.scope===c.scope&&next.taskId===c.taskId&&same(next.descriptor,c.descriptor))&&(c.stale||c.status!=='passed'||c.changeFingerprint!==(c.scope==='final'?evidence.changes?.final:evidence.changes?.tasks?.[c.taskId])))))return hold('cooperative.verification-stale','Verification or findings require current evidence');
210
- return {...base,decision:'allow',ruleIds:['cooperative.recorded'],requiredEvidence:[],nextActions:[],proposedTransition:null};
211
- }
212
-
213
- /** Result statements preserve uncertainty. They do not authenticate native events. */
214
- export function reconcileCooperativeResult({state,intent,result,observations}={}){
215
- const base={expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},requiredEvidence:[],nextActions:[],proposedTransition:null};
216
- try{validateCooperativeState(state);}catch(error){return {...base,decision:'hold',ruleIds:['cooperative.schema'],reason:error.message};}
217
- return {...base,decision:'hold',ruleIds:[!intent?'cooperative.intent':result?.status==='unknown'?'cooperative.unknown':'cooperative.reconciliation'],requiredEvidence:[],nextActions:[],proposedTransition:null,reason:!intent?'No matching durable intent':'Recorded operator statement requires reconciliation; no execution authorized'};
218
- }
219
-
220
- /** Pure Planner decision. Artifact verification belongs to the trusted reader;
221
- * semantic judgments retain their recorded source and never become native proof. */
222
- export function evaluatePlannerCall({stage,request,evidence}={}){
223
- const base={expectedRevision:stage?.revision??0,proposedTransition:null,coverage:{enforcement:'decision-only',semanticProvenance:evidence?.semanticProvenance==='operator-attested'?'operator-attested':'unverified',nativeVerified:false}};
224
- const result=(decision,reason,requiredEvidence=[])=>({...base,decision,ruleIds:['runtime.planner-call'],reason,requiredEvidence});
225
- if(['format-only','re-expression-only','save-error-only','patch-error-only'].includes(request?.intent))return result('deny','Orchestrator handles non-progress delivery and formatting work');
226
- try{validatePlannerStage(stage);}catch(error){return result('hold',error.message,['planner-stage-ledger']);}
227
- if(!request||!['initial','correction','further'].includes(request.kind)||request.intent!=='substantive'||typeof request.requestId!=='string'||!request.requestId||request.stageId!==stage.id||!Array.isArray(request.criterionIds)||new Set(request.criterionIds).size!==request.criterionIds.length||!Array.isArray(request.evidenceRefs)||new Set(request.evidenceRefs).size!==request.evidenceRefs.length)return result('hold','Valid stage-bound Planner request required',['planner-request']);
228
- if(stage.pending)return result('hold','Reconcile the pending Planner call before another request',['confirmed-planner-result']);
229
- if(stage.calls.some(c=>c.requestId===request.requestId))return result('hold','Planner request already recorded',['new-request-id']);
230
- const initial=stage.calls.find(c=>c.kind==='initial'),correction=stage.calls.find(c=>c.kind==='correction');
231
- if(request.kind==='initial'&&stage.calls.length)return result('deny','Initial draft opportunity already used');
232
- if(request.kind!=='initial'){
233
- if(!initial||!['succeeded','failed'].includes(initial.status)||!stage.result||!['succeeded','failed'].includes(stage.result.status)||stage.result.requestId!==stage.calls.at(-1).requestId||!['succeeded','failed'].includes(stage.calls.at(-1).status))return result('hold','A confirmed prior result is required',['confirmed-planner-result']);
234
- if(!stage.review?.full||stage.review.resultRef!==stage.result.ref||stage.review.criteriaVersion!==stage.criteriaVersion||request.reviewRef!==stage.review.ref||stage.review.source!=='operator-attested')return result('hold','A complete review of the recorded result is required',['consolidated-review']);
235
- if(request.kind==='correction'&&correction)return result('deny','Consolidated correction opportunity already used');
236
- if(request.kind==='further'&&!correction)return result('hold','Use the consolidated correction before further calls',['consolidated-correction']);
237
- }
238
- const used=new Set(stage.calls.flatMap(c=>c.evidenceHashes)),artifacts=request.evidenceRefs.map(ref=>evidence?.artifacts?.find(a=>a.ref===ref));
239
- if(request.kind==='further'){
240
- if(!request.criterionIds.length||request.criterionIds.some(id=>!stage.criteria.some(c=>c.id===id&&c.status==='open')))return result('deny','Concrete open criteria are required');
241
- if(!request.evidenceRefs.length)return result('hold','Unresolved criteria alone are not new progress',['new-criterion-evidence']);
242
- }
243
- if(artifacts.some(a=>a&&a.stageId!==stage.id))return result('deny','Evidence belongs to another stage');
244
- if(artifacts.some(a=>!a||!['input','progress','finding'].includes(a.purpose)||a.verification?.status!=='verified'||a.verification.source!=='local-bytes'||!/^sha256:[a-f0-9]{64}$/.test(a.hash??'')))return result('hold','Accessible locally verified input or progress bytes are required',['verified-artifact-bytes']);
245
- if(request.kind==='further'){
246
- if(artifacts.some(a=>used.has(a.hash)))return result('deny','Identical evidence bytes cannot authorize another call');
247
- if(request.criterionIds.some(id=>!artifacts.some(a=>a.criterionIds?.includes(id))))return result('hold','Evidence must address every requested criterion',['criterion-evidence-link']);
248
- if(artifacts.some(a=>!a.semantic||a.semantic.meaningful!==true||a.semantic.source!=='operator-attested'||!a.semantic.judgmentRef||a.semantic.targetHash!==a.hash))return result('hold','A hash-bound semantic judgment is required',['semantic-attestation']);
249
- }
250
- const next=structuredClone(stage),call={requestId:request.requestId,kind:request.kind,intent:request.intent,criterionIds:[...request.criterionIds],evidenceHashes:artifacts.map(a=>a.hash),evidenceRefs:[...request.evidenceRefs],reviewRef:request.reviewRef??null,status:'reserved',ordinal:stage.calls.length+1};
251
- next.calls.push(call);next.pending=request.requestId;next.ready=false;
252
- return {...result('allow','Planner call reserved; dispatch and result remain unverified'),proposedTransition:next};
253
- }
254
-
255
- /** Cooperative Planner records are attestations with separately observed bytes. */
256
- export function evaluateCooperativePlanner({state,request,evidence}={}){
257
- const base={expectedRevision:state.revision,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},proposedTransition:null,requiredEvidence:[]};
258
- const result=(decision,reason)=>({...base,decision,ruleIds:['cooperative.planner'],reason});
259
- if(request.input.actor.role!=='orchestrator')return result('hold','Orchestrator records and prepares Planner work');
260
- if(!state.plannerLedger)return result('hold','Existing workflow Planner history has no ledger; reconciliation required');
261
- const ledger=structuredClone(state.plannerLedger),input=request.input,data=input.evidence?.data;
262
- const stage=ledger.stages.find(s=>s.id===(data?.stageId??input.arguments?.stageId));
263
- const observed=evidence.plannerArtifacts??[];
264
- const artifact=ref=>observed.find(a=>a.ref===ref&&a.stageId===stage?.id&&a.verification?.status==='verified');
265
- const transition=(s,reason,decision='allow',uncertainty=false)=>({...result(decision,reason),proposedTransition:{plannerLedger:ledger,...(s?{stageId:s.id}:{}),...(uncertainty?{recordUncertainty:true}:{})}});
266
- if(request.command==='prepare'){
267
- if(!stage)return result('hold','Planner stage ledger unavailable');
268
- if(stage.workflowId!==state.workflowId||stage.scopeVersion!==state.scopeVersion||stage.targetVersion!==state.targetVersion)return result('hold','Planner stage contract version changed');
269
- const d=evaluatePlannerCall({stage,request:{...input.arguments,requestId:input.requestId},evidence:{artifacts:observed,semanticProvenance:'operator-attested'}});
270
- if(d.decision!=='allow')return {...d,coverage:base.coverage,expectedRevision:state.revision};
271
- ledger.stages[ledger.stages.indexOf(stage)]=d.proposedTransition;
272
- return {...transition(stage,d.reason),proposedTransition:{plannerLedger:ledger,intent:{requestId:input.requestId,operation:'planner-call',stageId:stage.id,taskId:input.taskId??null,status:'prepared',fingerprint:evidence.requestFingerprint,source:'operator-attested',identityVerified:false,target:structuredClone(state.target),kind:input.arguments.kind}}};
273
- }
274
- const kind=input.evidence.kind,ref=input.evidence.messageRef;
275
- if(kind==='planner-stage'){
276
- if(ledger.stages.some(s=>s.id===data.id))return result('deny','Planner stage ID already exists');
277
- const contract={document:data.document,inputVersion:data.inputVersion,criteriaVersion:data.criteriaVersion,scopeVersion:data.scopeVersion,...(data.targetIntentId?{targetIntentId:data.targetIntentId}:{})};
278
- const approval=state.records.find(r=>r.kind==='approval'&&r.messageRef===data.approvalRef&&r.source==='operator-attested'&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion);
279
- const approved=approval?.data?.plannerStage;
280
- if(!approved||!same(contract.document,approved.document)||['inputVersion','criteriaVersion','scopeVersion','targetIntentId'].some(k=>contract[k]!==approved[k])||contract.scopeVersion!==state.scopeVersion||!within(state.target.realpath,data.document?.path))return result('hold','Approved stage contract and current scope are required');
281
- const activeIntent=state.targetIntents?.find(i=>!state.targetTransitions?.some(t=>t.intentId===i.id));
282
- if(activeIntent&&data.targetIntentId!==activeIntent.id)return result('hold','First stage must bind the active target intent');
283
- const preparedIntent=state.targetIntents?.find(i=>state.targetTransitions?.some(t=>t.intentId===i.id&&t.targetVersion===state.targetVersion));
284
- if(preparedIntent&&data.document.kind==='plan'&&!preparedIntent.documents.some(d=>d.kind==='plan'&&path.join(state.target.realpath,d.path)===data.document.path))return result('hold','Plan path must match the prepared target intent');
285
- if(data.targetIntentId){const intent=state.targetIntents?.find(i=>i.id===data.targetIntentId);if(!intent||intent.firstStageId!==data.id||intent.sourceTargetVersion!==state.targetVersion||intent.documents.some(d=>d.kind==='spec')&&data.document.kind!=='spec'||!intent.documents.some(d=>d.kind===data.document.kind&&path.join(state.target.realpath,d.path)===data.document.path))return result('hold','Current target intent and matching first document required');}
286
- const targetIntent=state.targetIntents?.find(i=>i.id===data.targetIntentId);
287
- const approvedOmission=targetIntent?.depth==='Bounded'&&targetIntent.firstStageId===data.id&&targetIntent.documents.length===1&&targetIntent.documents[0].kind==='plan';
288
- const approvedSpec=approval.data.prerequisiteRefs?.some(ref=>state.records.some(r=>r.kind==='approval'&&r.messageRef===ref&&r.data.kind==='spec'&&r.source==='operator-attested'&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&(!preparedIntent||state.targetDocuments?.some(d=>d.intentId===preparedIntent.id&&preparedIntent.documents.some(doc=>doc.kind==='spec'&&doc.path===d.path)&&d.approvalRef===ref&&d.scopeVersion===state.scopeVersion&&d.targetVersion===state.targetVersion&&[d.path,path.join(state.target.realpath,d.path)].includes(r.data.path)&&d.hash===r.data.contentHash))));
289
- if(data.document.kind==='plan'&&!approvedOmission&&!approvedSpec)return result('hold','Approved spec prerequisite is required for plan drafting');
290
- const previous=[...ledger.stages,...(evidence.plannerHistory??[]).map(h=>h.stage)].filter(s=>s.document.path===data.document.path&&s.document.kind===data.document.kind&&s.document.phase===data.document.phase);
291
- if(evidence.plannerHistoryError)return result('hold','Planner history could not be verified: '+evidence.plannerHistoryError);
292
- if(previous.length){
293
- const prior=previous.find(s=>data.previousStageRef?.workflowId===s.workflowId&&data.previousStageRef?.stageId===s.id);
294
- if(!prior||approved.newScope!==true||!same(approved.previousStageRef,data.previousStageRef)||data.inputVersion<=prior.inputVersion||data.approvalRef===prior.approvalRef)return result('hold','Existing stage history requires an approved scope transition and predecessor link');
295
- }
296
- const created={...structuredClone(data),workflowId:state.workflowId,targetVersion:state.targetVersion,targetIdentity:{realpath:state.target.realpath,gitCommonDir:state.target.gitCommonDir,gitDir:state.target.gitDir},calls:[],pending:null,result:null,review:null,artifacts:[],ready:false};
297
- try{validatePlannerStage(created);}catch(error){return result('hold',error.message);}
298
- ledger.stages.push(created);return transition(created,'Planner stage registered without resetting prior history');
299
- }
300
- if(!stage)return result('hold','Planner stage ledger unavailable');
301
- if(stage.scopeVersion!==state.scopeVersion||stage.targetVersion!==state.targetVersion)return result('hold','Planner stage contract version changed');
302
- if(kind==='planner-evidence'){
303
- if(stage.artifacts.some(a=>a.ref===ref))return result('deny','Planner evidence reference already recorded');
304
- const item=observed.find(a=>a.ref===ref&&a.stageId===stage.id);
305
- if(!item||item.verification?.status!=='verified'||!['draft','self-review','input','progress','finding'].includes(data.purpose)||!Array.isArray(data.criterionIds)||data.criterionIds.some(id=>!stage.criteria.some(c=>c.id===id)))return result('hold','Accessible stage-bound artifact bytes and purpose required');
306
- if(data.semantic&&(data.semantic.source!==undefined&&data.semantic.source!=='operator-attested'||typeof data.semantic.meaningful!=='boolean'||!data.semantic.judgmentRef||data.semantic.targetHash!==item.hash))return result('hold','Semantic attestation must bind the observed artifact hash');
307
- stage.artifacts.push({...item,purpose:data.purpose,criterionIds:[...data.criterionIds],...(data.semantic?{semantic:{...data.semantic,source:'operator-attested'}}:{})});return transition(stage,'Artifact bytes recorded separately from semantic attestation');
308
- }
309
- if(kind==='planner-result'){
310
- const call=stage.calls.find(c=>c.requestId===data.callRequestId);
311
- if(!call||stage.pending!==call.requestId||!['reserved','unknown'].includes(call.status)||!['succeeded','failed','unknown'].includes(data.status))return result('hold','A pending Planner call and confirmed result identity are required');
312
- const chat=data.chatDraft,intent=state.targetIntents?.find(i=>i.id===stage.targetIntentId);
313
- if(chat&&call.status!=='reserved')return result('hold','Unknown Planner call must be reconciled before checkpoint');
314
- const chatComplete=!!(intent&&chat?.intentId===intent.id&&typeof chat.draftRef==='string'&&chat.draftRef&&typeof chat.selfReviewRef==='string'&&chat.selfReviewRef&&chat.complete===true);
315
- if(data.status==='succeeded'&&!chatComplete&&(!artifact(data.artifactRef)||artifact(data.artifactRef).purpose!=='draft'||!artifact(data.selfReviewRef)||artifact(data.selfReviewRef).purpose!=='self-review'))return result('hold','Verified full draft and self-review artifacts are required');
316
- call.status=data.status;call.resultRef=ref;stage.result={ref,requestId:call.requestId,status:data.status,artifactRef:data.artifactRef??null,selfReviewRef:data.selfReviewRef??null,...(chatComplete?{chatDraft:structuredClone(chat)}:{}),source:'operator-attested'};stage.ready=false;
317
- if(data.status!=='unknown')stage.pending=null;
318
- return transition(stage,data.status==='unknown'?'Planner execution remains unknown':'Planner result statement recorded',data.status==='unknown'?'hold':'allow',data.status==='unknown');
319
- }
320
- if(kind==='planner-review'){
321
- if(stage.pending||!stage.result||!['succeeded','failed'].includes(stage.result.status)||data.resultRef!==stage.result.ref||data.full!==true||typeof data.complete!=='boolean'||!Array.isArray(data.criteria)||data.criteria.length!==stage.criteria.length||new Set(data.criteria.map(c=>c.id)).size!==stage.criteria.length||data.criteria.some(c=>!stage.criteria.some(old=>old.id===c.id)||!['open','resolved'].includes(c.status)||!c.judgmentRef))return result('hold','Full review must bind the confirmed result and all criteria');
322
- for(const old of stage.criteria)if(old.status==='resolved'&&data.criteria.find(c=>c.id===old.id).status==='open'){
323
- const reassessment=data.reassessments?.find(r=>r.criterionId===old.id&&r.previousJudgmentRef===old.judgmentRef&&r.reasonRef),proof=artifact(reassessment?.newEvidenceRef);
324
- if(!reassessment||!proof||!proof.criterionIds.includes(old.id)||!proof.semantic?.meaningful||stage.calls.some(c=>c.evidenceHashes.includes(proof.hash)))return result('hold','Resolved criteria require a new evidence-bound reassessment');
325
- }
326
- if(data.complete&&(data.criteria.some(c=>c.status!=='resolved')||!artifact(stage.result.artifactRef)||!artifact(stage.result.selfReviewRef)))return result('hold','Incomplete draft cannot become ready or accepted');
327
- stage.criteria=structuredClone(data.criteria);stage.review={ref,resultRef:data.resultRef,criteriaVersion:stage.criteriaVersion,full:true,complete:data.complete,source:'operator-attested'};stage.ready=data.complete;
328
- return transition(stage,'Semantic completeness and criterion judgments remain operator-attested');
329
- }
330
- return result('hold','Unsupported Planner record');
331
- }
@@ -1,51 +0,0 @@
1
- import {fingerprintRequest} from './store.mjs';
2
- import {absolute,within} from './scope.mjs';
3
- export const EXTERNAL_ACTIONS=Object.freeze(['push','merge','deploy','publish']);
4
- const keys={push:['repository','destination','refspec','sourceOid','expectedRemoteOid'],merge:['repository','changeRef','targetRef','expectedTargetOid'],deploy:['service','project','environment','artifactId','destination'],publish:['service','namespace','name','version','artifactHash','destination']};
5
- const text=v=>typeof v==='string'&&v.length>0;
6
- const same=(a,b)=>a===undefined||b===undefined?a===b:fingerprintRequest(a)===fingerprintRequest(b);
7
- const fields=(v,allowed)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===allowed.length&&allowed.every(k=>Object.hasOwn(v,k));
8
- /** Reject credentials before audit persistence; errors never contain input values. */
9
- export function assertSecretFree(value){
10
- if(typeof value==='string'){
11
- if(/(?:[a-z][a-z0-9+.-]*:\/\/|^)[^\s/]+:[^\s/]+@|[?&#](?:access[_-]?token|token|key|password|secret|signature|credential|auth)=|\b(?:Bearer|Basic)\s+\S+/i.test(value))throw Error('Secret-free identifiers required');
12
- }else if(value&&typeof value==='object')for(const [key,item] of Object.entries(value)){
13
- if(/^(?:password|passwd|token|accessToken|access_token|secret|credentials?|authorization|apiKey|api_key|privateKey)$/i.test(key))throw Error('Secret-free identifiers required');assertSecretFree(item);
14
- }
15
- }
16
- function descriptorValid(operation,d){
17
- if(!keys[operation]||!fields(d,keys[operation])||!Object.values(d).every(v=>text(v)&&!/[\r\n\x00]/.test(v)))return false;
18
- if(d.destination&&/[?#]/.test(d.destination))return false;
19
- const oid=v=>/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
20
- if(operation==='push'&&(!oid(d.sourceOid)||!oid(d.expectedRemoteOid)))return false;
21
- if(operation==='merge'&&!oid(d.expectedTargetOid))return false;
22
- return operation!=='publish'||/^sha256:[a-f0-9]{64}$/.test(d.artifactHash);
23
- }
24
- const coverage={enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false,remoteVerified:false};
25
- const decision=(state,reason,transition=null,allow=false)=>({expectedRevision:state?.revision??0,decision:allow?'allow':'hold',ruleIds:['cooperative.external'],reason,coverage:{...coverage},requiredEvidence:[],nextActions:[],proposedTransition:transition});
26
- export const unresolvedExternal=state=>state.intents.some(i=>EXTERNAL_ACTIONS.includes(i.operation)&&['prepared','unknown','mismatch'].includes(i.status));
27
- export function evaluateCooperativeExternal({state,request,approvalEvidence}={}){
28
- const a=request?.arguments;
29
- try{assertSecretFree(request);assertSecretFree(approvalEvidence);}catch{return decision(state,'Secret-free identifiers required');}
30
- if(state?.mode!=='plan'||request?.expectedRevision!==state.revision||request.actor?.role!=='orchestrator'||!fields(a,['approvalRef','scope','descriptor'])||!descriptorValid(request.operation,a.descriptor)||!Array.isArray(a.scope)||!a.scope.length||new Set(a.scope).size!==a.scope.length||a.scope.some(p=>!absolute(p)||!within(state.target.realpath,p)))return decision(state,'Exact external action, scope and secret-free target required');
31
- const approval=state.records.findLast(r=>r.kind==='external-approval'&&r.messageRef===a.approvalRef);
32
- if(!approval||approval.source!=='operator-attested'||approval.scopeVersion!==state.scopeVersion||approval.targetVersion!==state.targetVersion||!same(approval,approvalEvidence)||!same(approval.data,{operation:request.operation,scope:a.scope,descriptor:a.descriptor}))return decision(state,'Exact explicit external approval required; local approval is insufficient');
33
- if(unresolvedExternal(state)||state.unresolved.some(u=>!u.resolvedBy)||state.intents.some(i=>i.requestId===request.requestId||EXTERNAL_ACTIONS.includes(i.operation)&&i.approvalRef===a.approvalRef))return decision(state,'Unresolved effects or consumed approval require investigation; never retry');
34
- return decision(state,'External intent only; operator execution is separate',{intent:{requestId:request.requestId,operation:request.operation,status:'prepared',scope:structuredClone(a.scope),descriptor:structuredClone(a.descriptor),approvalRef:a.approvalRef,approvalFingerprint:fingerprintRequest(approval),scopeVersion:state.scopeVersion,targetVersion:state.targetVersion,target:structuredClone(state.target),versions:structuredClone(state.versions),fingerprint:fingerprintRequest(request),source:'operator-attested'}},true);
35
- }
36
- export function reconcileCooperativeExternal({state,intent,result,observations}={}){
37
- if(!intent||!EXTERNAL_ACTIONS.includes(intent.operation)||!['prepared','unknown','mismatch'].includes(intent.status))return decision(state,'Matching unresolved external intent required; replay cannot authorize another effect');
38
- try{assertSecretFree(result);}catch{return decision(state,'Secret-free result required');}
39
- const transition={result:{...structuredClone(result),status:'mismatch',messageRef:result?.messageRef??'invalid-result',data:{...structuredClone(result?.data??{}),remoteVerified:false},source:'operator-attested'}};
40
- const reject=reason=>decision(state,reason,transition);
41
- if(!result||!text(result.messageRef)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(result.status))return reject('Exact external result statement required');
42
- if(!fields(result.data,['operation','scope','descriptor'])||result.data.operation!==intent.operation||!same(result.data.scope,intent.scope)||!same(result.data.descriptor,intent.descriptor))return reject('External result action, scope or target mismatch');
43
- transition.result={...structuredClone(result),data:{...structuredClone(result.data),remoteVerified:false},source:'operator-attested'};
44
- const approval=state.records.findLast(r=>r.kind==='external-approval'&&r.messageRef===intent.approvalRef);
45
- if(!same(observations?.target,intent.target)||!approval||fingerprintRequest(approval)!==intent.approvalFingerprint||state.mode!=='plan'||!same(intent.target,state.target)||!same(intent.versions,state.versions)||intent.scopeVersion!==state.scopeVersion||intent.targetVersion!==state.targetVersion){transition.result.status='mismatch';return reject('Stale external approval, target or versions');}
46
- if(result.status==='succeeded')return decision(state,'Operator result recorded; no independent remote verification',transition,true);
47
- if(result.status==='failed')return decision(state,'Operator confirms failure; approval remains consumed and no retry authorized',transition,true);
48
- if(result.status==='cancelled'&&text(result.notExecutedEvidence?.messageRef))return decision(state,'Operator attests no execution; approval remains consumed',transition,true);
49
- return reject('External effect unresolved or unsuccessful; investigate without retry');
50
- }
51
- export function cooperativeSupport(){return {phases:[{phase:1,status:'supported',areas:['durable-state','documents','assignment']},{phase:2,status:'supported',areas:['scope','verification','acceptance-commit']},{phase:3,status:'supported',areas:['external-approval','external-result','audit-recovery']}],modes:{plan:'supported','no-plan':'unsupported',omission:'unsupported'},limits:['operator-attested identity and approval','direct calls outside CLI are not blocked','no network, native or provider execution','audit is local mutable evidence','unknown effects require investigation, not retry'],remoteVerified:false};}
@@ -1,71 +0,0 @@
1
- import {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
2
- export {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
3
- import path from 'node:path';
4
-
5
- const reconciliations=new WeakMap();
6
- export function verifiedReconciliation(decision,state,next,expectedCommit){const proof=reconciliations.get(decision);return !!proof&&proof.before===JSON.stringify(state)&&proof.after===JSON.stringify(next)&&(expectedCommit===undefined||proof.expected===JSON.stringify(expectedCommit));}
7
- const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
8
- const oid=value=>typeof value==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
9
- const hash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
10
- const gitPath=value=>typeof value==='string'&&value.length>0&&!/[\\\x00\r\n:]/.test(value)&&!value.startsWith('/')&&!value.split('/').some(p=>!p||p==='.'||p==='..');
11
- const validPaths=values=>Array.isArray(values)&&values.every(gitPath)&&new Set(values).size===values.length;
12
- const samePaths=(a,b)=>validPaths(a)&&validPaths(b)&&same([...a].sort(),[...b].sort());
13
- const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||!path.isAbsolute(relative)&&relative!=='..'&&!relative.startsWith('..'+path.sep);};
14
- const targetValid=t=>t&&path.isAbsolute(t.realpath)&&path.normalize(t.realpath)===t.realpath&&path.isAbsolute(t.gitCommonDir)&&oid(t.head)&&(t.branch===null||typeof t.branch==='string'&&t.branch);
15
-
16
- /** Git-specific validation ONLY. Trusted adapters must separately satisfy T2
17
- * evaluate() role/identity/approval policy and transactWorkflow() persistence.
18
- * Inputs here are provider observations, never facts accepted from tool input.
19
- * Preflight permission does not mean execution or completed commit. */
20
- export async function runGate({phase,state,request,gitEvidence,expectedCommit,result}={}){
21
- const hold=(reason,id='runtime.git-evidence')=>({decision:'hold',ruleIds:[id],reason,requiredEvidence:['observed-git-state'],expectedRevision:state?.revision??0,proposedTransition:null,coverage:{enforcement:'git-validation-only'}});
22
- const allow=(reason,extra={})=>({...hold(reason),decision:'allow',requiredEvidence:[],...extra});
23
- try{
24
- if(!state||!targetValid(state.target)||!Number.isSafeInteger(state.revision)||state.revision<0||!request||request.operation!=='commit'||typeof request.requestId!=='string'||!request.requestId||request.cwd!==state.target.realpath)return hold('Invalid Git gate input');
25
- const actors=state.identities?.filter(i=>i.actorRef===request.actorRef);
26
- const leases=state.leases?.filter(l=>l.actorRef===request.actorRef&&l.taskId===request.taskId&&l.status==='active');
27
- if(actors?.length!==1||actors[0].role!=='orchestrator'||actors[0].taskId!==request.taskId||leases?.length!==1)return hold('Only the observed active Orchestrator may request commit','git.specialists-deny');
28
- const task=state.tasks?.find(t=>t.id===request.taskId);
29
- const d=request.descriptor;
30
- if(!task||!d||!['documents','task'].includes(d.kind)||!oid(d.parent)||!oid(d.indexTree)||!hash(d.fingerprint)||!validPaths(d.paths)||!d.paths.length||d.parent!==state.target.head||d.parent.length!==d.indexTree.length)return hold('Incomplete or stale commit descriptor');
31
- if(!Array.isArray(request.paths)||!samePaths(request.paths.map(file=>{
32
- if(typeof file!=='string'||!path.isAbsolute(file)||!within(state.target.realpath,file)||path.normalize(file)!==file)throw Error('Requested path escapes target');
33
- return path.relative(state.target.realpath,file).split(path.sep).join('/');
34
- }),d.paths))return hold('Request paths differ from commit paths');
35
- if(d.kind==='documents'){
36
- if(state.mode!=='plan'||state.documents?.length!==2||!samePaths(state.documents.map(x=>x.kind),['spec','plan'])||!samePaths(d.paths,state.documents.map(x=>x.gitPath)))return hold('Complete exact approved spec and plan set required','runtime.docs-commit');
37
- for(const document of state.documents){
38
- const approvals=state.approvals?.filter(a=>a.id===document.approvalRef);
39
- if(!hash(document.contentHash)||document.path!==path.join(state.target.realpath,...document.gitPath.split('/'))||approvals?.length!==1||!['user-message','human-confirmation'].includes(approvals[0].source)||!approvals[0].messageRef||approvals[0].contentHash!==document.contentHash)return hold('Approved document hash unavailable','runtime.docs-commit');
40
- }
41
- }else{
42
- const accepted=state.acceptances?.filter(a=>a.taskId===task.id&&a.fingerprint===d.fingerprint&&state.identities.some(i=>i.actorRef===a.actorRef&&i.role==='orchestrator'));
43
- if(task.status!=='accepted'||accepted?.length!==1||!task.criteria?.length||!same(accepted[0].criteria,task.criteria)||!Array.isArray(accepted[0].checkIds)||!task.requiredChecks?.every(id=>accepted[0].checkIds.includes(id))||!Array.isArray(accepted[0].findingIds)||state.commits?.some(c=>c.kind==='task'&&c.taskId===task.id))return hold('Exact accepted task diff required','git.orchestrator-accept-commit');
44
- const allowed=task.paths;
45
- if(!Array.isArray(allowed)||request.paths.some(file=>!allowed.some(base=>path.isAbsolute(base)&&within(base,file))))return hold('Commit contains another task or unrelated changes','git.orchestrator-accept-commit');
46
- }
47
- if(phase==='preflight'){
48
- const g=gitEvidence;
49
- const dirty=[...g?.workingPaths??[],...g?.untrackedPaths??[]];
50
- const scope=d.kind==='documents'?state.documents.map(x=>x.path):task.paths;
51
- const invalid=validateGitPreflight({target:state.target,descriptor:d,scope,gitEvidence:g});
52
- if(invalid)return hold(invalid);
53
- if(d.kind==='documents'){
54
- if(!Array.isArray(g.documents)||!samePaths(g.documents.map(x=>x.gitPath),d.paths)||state.documents.some(document=>!g.documents.some(observed=>observed.gitPath===document.gitPath&&observed.path===document.path&&observed.contentHash===document.contentHash&&observed.observedHash===document.contentHash)))return hold('Observed document bytes differ from approved hashes','runtime.docs-commit');
55
- }
56
- return allow('Git preflight passed; observed commit result still required',{expectedCommit:{requestId:request.requestId,taskId:task.id,kind:d.kind,parent:d.parent,tree:d.indexTree,paths:[...d.paths],fingerprint:d.fingerprint,target:structuredClone(state.target),remainingPaths:[...new Set(dirty)].sort()}});
57
- }
58
- if(phase!=='reconcile')return hold('Unknown Git gate phase');
59
- const expected=expectedCommit;
60
- if(!expected||expected.requestId!==request.requestId||expected.taskId!==task.id||expected.parent!==d.parent||expected.tree!==d.indexTree||expected.fingerprint!==d.fingerprint||!samePaths(expected.paths,d.paths)||expected.kind!==undefined&&expected.kind!==d.kind||expected.target!==undefined&&!same(expected.target,state.target))return hold('Preflight correlation unavailable');
61
- const invalid=validateGitCommitResult({target:state.target,expected,result,scope:d.kind==='documents'?state.documents.map(x=>x.path):task.paths});
62
- if(invalid)return hold(invalid);
63
- const next=structuredClone(state);next.target.head=result.commit;
64
- next.commits=[...state.commits??[],{requestId:request.requestId,taskId:task.id,kind:d.kind,purpose:d.kind,expectedParent:expected.parent,expectedTree:expected.tree,commit:result.commit,parent:result.parent,tree:result.tree,paths:[...result.paths],fingerprint:d.fingerprint,actorRef:request.actorRef}];
65
- if(d.kind==='task')next.tasks.find(t=>t.id===task.id).status='committed';
66
- else for(const document of next.documents)document.commit=result.commit;
67
- const decision=allow('Observed commit matches preflight',{proposedTransition:next});
68
- reconciliations.set(decision,{before:JSON.stringify(state),after:JSON.stringify(next),expected:JSON.stringify(expected)});
69
- return decision;
70
- }catch(error){return hold('Git validation failed: '+error.message);}
71
- }