@yunhozz/arc 0.5.5 → 0.5.6

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 (39) hide show
  1. package/MANIFEST.sha256 +38 -38
  2. package/claude/skill/SKILL.md +1 -1
  3. package/claude/skill/references/coordination.md +1 -1
  4. package/claude/skill/references/handoff-prep.md +4 -4
  5. package/claude/skill/references/handoff.md +5 -5
  6. package/claude/skill/references/planning.md +72 -24
  7. package/codex/skill/SKILL.md +1 -1
  8. package/codex/skill/references/coordination.md +1 -1
  9. package/codex/skill/references/handoff-prep.md +4 -4
  10. package/codex/skill/references/handoff.md +5 -5
  11. package/codex/skill/references/planning.md +72 -24
  12. package/gemini/skill/SKILL.md +1 -1
  13. package/gemini/skill/references/coordination.md +1 -1
  14. package/gemini/skill/references/handoff-prep.md +4 -4
  15. package/gemini/skill/references/handoff.md +5 -5
  16. package/gemini/skill/references/planning.md +72 -24
  17. package/grok/skill/SKILL.md +1 -1
  18. package/grok/skill/references/coordination.md +1 -1
  19. package/grok/skill/references/handoff-prep.md +4 -4
  20. package/grok/skill/references/handoff.md +5 -5
  21. package/grok/skill/references/planning.md +72 -24
  22. package/lib/policy/role-policy.json +1 -1
  23. package/lib/prompts/agent-fragments.json +2 -2
  24. package/lib/runtime/assignment.mjs +3 -2
  25. package/lib/runtime/cooperative.mjs +36 -3
  26. package/lib/runtime/evaluate.mjs +21 -6
  27. package/lib/runtime/gate.mjs +2 -1
  28. package/lib/runtime/schema.mjs +16 -0
  29. package/lib/runtime/target-preparation.mjs +7 -2
  30. package/lib/runtime/verification.mjs +1 -1
  31. package/package.json +1 -1
  32. package/shared/skill/runtime/assignment.mjs +3 -2
  33. package/shared/skill/runtime/cooperative.mjs +36 -3
  34. package/shared/skill/runtime/evaluate.mjs +21 -6
  35. package/shared/skill/runtime/gate.mjs +2 -1
  36. package/shared/skill/runtime/role-policy.json +1 -1
  37. package/shared/skill/runtime/schema.mjs +16 -0
  38. package/shared/skill/runtime/target-preparation.mjs +7 -2
  39. package/shared/skill/runtime/verification.mjs +1 -1
@@ -38,7 +38,7 @@ export function validateTargetPreparationRecord(kind,data){
38
38
  if(kind==='intent'&&(!Number.isSafeInteger(data.sourceTargetVersion)||data.sourceTargetVersion<1||!['realpath','gitCommonDir','gitDir'].every(k=>typeof data.sourceTarget[k]==='string'&&path.isAbsolute(data.sourceTarget[k])&&path.normalize(data.sourceTarget[k])===data.sourceTarget[k])||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.sourceTarget.head)||!(data.sourceTarget.branch===null||text(data.sourceTarget.branch))||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.base)||new Set(data.documents.map(d=>d.path)).size!==data.documents.length))throw Error('Invalid target preparation intent identity');
39
39
  if(kind==='checkpoint'&&(!text(data.intentId)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)))throw Error('Invalid target preparation checkpoint');
40
40
  if(kind==='transition'&&(!text(data.intentId)||!text(data.checkpointRef)||!Number.isSafeInteger(data.expectedRevision)||data.expectedRevision<0))throw Error('Invalid target preparation transition');
41
- if(kind==='destination'&&(!text(data.intentId)||!text(data.transitionRef)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)||!relative(data.path)||!/^sha256:[a-f0-9]{64}$/.test(data.hash)||![0o100644,0o100755].includes(data.mode)||!text(data.reviewRef)||!text(data.approvalRef)||!Number.isSafeInteger(data.targetVersion)||data.targetVersion<1))throw Error('Invalid target preparation destination');
41
+ if(kind==='destination'&&(!text(data.intentId)||!text(data.transitionRef)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)||!relative(data.path)||!/^sha256:[a-f0-9]{64}$/.test(data.hash)||![0o100644,0o100755].includes(data.mode)||!text(data.reviewRef)||(data.approvalRef!==undefined&&!text(data.approvalRef))||!Number.isSafeInteger(data.targetVersion)||data.targetVersion<1))throw Error('Invalid target preparation destination');
42
42
  return data;
43
43
  }
44
44
 
@@ -49,6 +49,7 @@ export function evaluateTargetPreparation({state,request,evidence}={}){
49
49
  if(state.targetIntents?.some(intent=>!state.targetTransitions?.some(transition=>transition.intentId===intent.id)))return hold('Existing target preparation intent is still active');
50
50
  const approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.source==='operator-attested'&&r.actor?.role==='orchestrator'&&r.targetVersion===state.targetVersion&&r.scopeVersion===state.scopeVersion);
51
51
  const approved=approval?.data?.targetPreparation;
52
+ if(request.depth==='Bounded'&&request.documents.some(d=>d.kind==='spec'))return hold('Bounded depth has no spec stage');
52
53
  if(!['Bounded','Architectural'].includes(request.depth)||(request.depth==='Architectural'&&(!request.documents.some(d=>d.kind==='spec')||!request.documents.some(d=>d.kind==='plan'))))return hold('Approved depth requires its complete document set');
53
54
  if(!text(request.approvalRef)||!text(request.depth)||['depth','selectionRef','kind','candidate','base','workflowId','firstStageId','sourceTargetVersion'].some(k=>approved?.[k]!==request[k])||!same(approved?.sourceTarget,request.sourceTarget)||!same(approved?.documents,request.documents)||request.workflowId!==state.workflowId||request.sourceTargetVersion!==state.targetVersion||!same(request.sourceTarget,state.target)||!same(evidence?.source?.target,state.target)||!text(evidence?.source?.fingerprint)||!state.selections?.some(s=>s.messageRef===request.selectionRef&&s.targetVersion===state.targetVersion)||state.targetIntents?.some(i=>i.id===request.id)||request.base!==state.target.head)return hold('Current approval, document set, source, explicit choice and preservation snapshot required');
54
55
  return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{intent:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceFingerprint:evidence.source.fingerprint,...(evidence.source.snapshot?{sourceSnapshot:structuredClone(evidence.source.snapshot)}:{}),source:'operator-attested'}}};
@@ -70,8 +71,12 @@ export function evaluateTargetPreparation({state,request,evidence}={}){
70
71
  if(request.type==='destination'){
71
72
  const intent=state.targetIntents?.find(i=>i.id===request.intentId),document=intent?.documents?.find(d=>d.path===request.path),transition=state.targetTransitions?.find(t=>t.intentId===request.intentId&&t.messageRef===request.transitionRef&&t.targetVersion===state.targetVersion),checkpoint=state.targetCheckpoints?.find(c=>c.intentId===request.intentId&&c.messageRef===transition?.checkpointRef),stage=state.plannerLedger?.stages?.find(s=>s.id===request.stageId),chat=stage?.result?.chatDraft,observed=evidence?.destination?.document;
72
73
  const review=state.records?.find(r=>r.kind==='planner-review'&&r.messageRef===request.reviewRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested'),approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested');
74
+ if(intent&&document&&request.approvalRef===undefined&&!(intent.depth==='Architectural'&&document.kind==='spec'))return hold('Document approval required for this destination');
73
75
  if(!intent||!document||intent.firstStageId!==request.stageId||!transition||!same(transition.target,state.target)||request.targetVersion!==state.targetVersion||!checkpoint||checkpoint.stageId!==request.stageId||checkpoint.resultRef!==request.resultRef||checkpoint.selfReviewRef!==request.selfReviewRef||stage?.targetIntentId!==intent.id||stage.result?.ref!==request.resultRef||stage.result.status!=='succeeded'||chat?.intentId!==intent.id||chat.complete!==true||chat.selfReviewRef!==request.selfReviewRef||!same(evidence?.destination?.target,state.target)||observed?.verification?.status!=='verified'||observed.verification.source!=='local-bytes'||observed.path!==request.path||observed.hash!==request.hash||observed.mode!==request.mode)return hold('Current transition, source attestation and observed destination bytes required');
74
- if(stage.scopeVersion!==state.scopeVersion||review?.data?.resultRef!==request.resultRef||review.data.full!==true||review.data.complete!==true||review.data.hash!==request.hash||!Array.isArray(stage.criteria)||!Array.isArray(review.data.criteria)||review.data.criteria.length!==stage.criteria.length||new Set(review.data.criteria.map(c=>c.id)).size!==stage.criteria.length||review.data.criteria.some(c=>!stage.criteria.some(s=>s.id===c.id)||c.status!=='resolved'||!text(c.judgmentRef))||approval?.data?.kind!==document.kind||approval.data.contentHash!==request.hash||![request.path,path.join(state.target.realpath,request.path)].includes(approval.data.path))return hold('Current full review and document approval required');
76
+ const approvedPath=[request.path,path.join(state.target.realpath,request.path)];
77
+ const matchesApproval=entry=>entry?.kind===document.kind&&entry.contentHash===request.hash&&approvedPath.includes(entry.path);
78
+ const approved=request.approvalRef===undefined||(Array.isArray(approval?.data?.documents)?stage?.document?.kind===document.kind&&approval.data.documents.filter(matchesApproval).length===1:matchesApproval(approval?.data));
79
+ if(stage.scopeVersion!==state.scopeVersion||review?.data?.resultRef!==request.resultRef||review.data.full!==true||review.data.complete!==true||review.data.hash!==request.hash||!Array.isArray(stage.criteria)||!Array.isArray(review.data.criteria)||review.data.criteria.length!==stage.criteria.length||new Set(review.data.criteria.map(c=>c.id)).size!==stage.criteria.length||review.data.criteria.some(c=>!stage.criteria.some(s=>s.id===c.id)||c.status!=='resolved'||!text(c.judgmentRef))||!approved)return hold('Current full review and document approval required');
75
80
  return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{destination:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceLink:'operator-attested',verification:{status:'verified',source:'local-bytes'}}}};
76
81
  }
77
82
  if(request?.type!=='checkpoint')return hold('Unsupported target preparation request');
@@ -67,7 +67,7 @@ function record({state,request,evidence}){
67
67
  export function evaluateCooperativeVerification({state,request,evidence}={}){
68
68
  const denial=legacyCooperativeRoleDenial(request);
69
69
  if(denial)return {...base(state),...denial};
70
- if(state?.mode!=='plan')return hold(state,'unsupported','Only the complete spec and plan path is supported');
70
+ if(state?.mode!=='plan')return hold(state,'unsupported','Only the plan path is supported');
71
71
  if(!request||request.expectedRevision!==state.revision)return hold(state,'revision','Stale verification request');
72
72
  if(request.actor?.role!=='orchestrator')return hold(state,'verification-actor','Orchestrator statement required');
73
73
  if(request.operation==='verification-record')return record({state,request,evidence});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.5.5",
3
+ "version": "0.5.6",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -1,5 +1,6 @@
1
1
  import {fingerprintRequest} from './store.mjs';
2
2
  import {absolute,within} from './scope.mjs';
3
+ import {hasExactPlanningKinds,expectedCooperativePlanningKinds} from './schema.mjs';
3
4
  const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
4
5
  const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
5
6
  const text=value=>typeof value==='string'&&value.length>0;
@@ -22,8 +23,8 @@ export function prepareCooperativeAssignment({policy,state,request,observations}
22
23
  if(task&&(task.invalidated||task.status==='held'||task.dependencies?.some(id=>{const predecessor=state.tasks.find(t=>t.id===id);return !predecessor||predecessor.invalidated||!['accepted','committed'].includes(predecessor.status);})))return hold(state,'task-stale','Affected task or predecessor requires renewed readiness and approval');
23
24
  const scope=state.scopes?.findLast(s=>s.scopeVersion===state.scopeVersion&&(!s.data.affectedTaskIds||s.data.affectedTaskIds.includes(request.taskId)));
24
25
  if(!task||!task.paths?.length||args.paths.some(p=>!task.paths.some(base=>within(base,p)))||scope&&args.paths.some(p=>!scope.data.paths?.some(base=>within(base,p))))return hold(state,'assignment-scope','Assignment must stay inside approved task and recorded scope');
25
- const documents=args.documents,git=observations.git;
26
- if(!Array.isArray(documents)||documents.length!==2||!setEqual(documents.map(d=>d.kind),['spec','plan'])||!git.docsCommit||!setEqual(git.docsCommit.paths,documents.map(d=>d.gitPath))||!same(git.docsCommit.documents,documents)||documents.some(d=>d.commit!==git.docsCommit.commit)||!Array.isArray(git.documents)||git.documents.length!==2||documents.some(d=>!git.documents.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.kind===d.kind&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash)))return hold(state,'documents','Exact committed spec and plan plus current bytes must match approval');
26
+ const documents=args.documents,git=observations.git,kinds=expectedCooperativePlanningKinds(state);
27
+ if(!hasExactPlanningKinds(documents,kinds)||!git.docsCommit||!setEqual(git.docsCommit.paths,documents.map(d=>d.gitPath))||!same(git.docsCommit.documents,documents)||documents.some(d=>d.commit!==git.docsCommit.commit)||!hasExactPlanningKinds(git.documents,kinds)||documents.some(d=>!git.documents.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.kind===d.kind&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash)))return hold(state,'documents','Exact committed spec and plan plus current bytes must match approval');
27
28
  const approval=state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(request.taskId))).at(-1);
28
29
  if(task.approvalRef!==args.approvalRef||task.approvalVersion!==args.approvalVersion||task.documentVersion!==args.documentVersion||task.scopeVersion!==state.scopeVersion||task.targetVersion!==state.targetVersion||!approval||approval.source!=='operator-attested'||approval.messageRef!==args.approvalRef||approval.targetVersion!==state.targetVersion||approval.scopeVersion!==state.scopeVersion||approval.data.approvalVersion!==args.approvalVersion||approval.data.documentVersion!==args.documentVersion||!same(approval.data.documents,documents)||documents.some(d=>d.approvalRef!==args.approvalRef))return hold(state,'approval','Current document and approval versions must match');
29
30
  const intent={requestId:request.requestId,taskId:request.taskId,operation:request.operation,status:'prepared',role:args.role,paths:[...args.paths],operations:[...args.operations],correlation:args.correlation,documents:structuredClone(documents),docsCommit:git.docsCommit.commit,approvalRef:args.approvalRef,approvalVersion:args.approvalVersion,documentVersion:args.documentVersion,target:structuredClone(state.target),targetVersion:state.targetVersion,scopeVersion:state.scopeVersion,revision:state.revision+1,fingerprint:fingerprintRequest(request),source:'operator-attested'};
@@ -13,6 +13,7 @@ import {fingerprintRequest,saveDurableState,applyCooperativeCommitTransition,app
13
13
  import {commandResult,cooperativeVersions} from './bootstrap.mjs';
14
14
  import {evaluateCooperative,reconcileCooperativeResult} from './evaluate.mjs';
15
15
  import {evaluateTargetPreparation,readTargetPreparationEvidence} from './target-preparation.mjs';
16
+ import {expectedCooperativePlanningKinds,hasExactPlanningKinds,preparedTargetIntent} from './schema.mjs';
16
17
  const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
17
18
  const sameCheckout=(a,b)=>['realpath','gitCommonDir','gitDir'].every(k=>a[k]===b[k]);
18
19
  /** Only trusted code may inject observation/storage. CLI JSON cannot set either. */
@@ -59,8 +60,17 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
59
60
  const changes=state.tasks.length?await readChanges({state}):undefined;
60
61
  const plannerArtifacts=plannerWork?await readPlannerArtifacts(state,command==='record'&&input.evidence.kind==='planner-evidence'?input.evidence:undefined):undefined;
61
62
  const plannerHistory=command==='record'&&input.evidence.kind==='planner-stage'?await readPlannerHistory(state,statePath,input.evidence.data.document?.path):{};
63
+ let reviewedSpec;
64
+ if(command==='record'&&input.evidence.kind==='planner-stage'&&input.evidence.data.document?.kind==='plan'){
65
+ const intent=preparedTargetIntent(state),spec=intent?.documents.find(d=>d.kind==='spec');
66
+ if(spec){
67
+ let observed;
68
+ try{observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:{realpath:state.target.realpath,path:spec.path},observe,readChanges});}catch{}
69
+ reviewedSpec={path:spec.path,hash:observed?.destination?.document?.hash};
70
+ }
71
+ }
62
72
  let destinationReview=false;
63
- let decision=evaluateCooperative({state,request:{command,input},evidence:{target:currentTarget,versions,git,changes,requestFingerprint,plannerArtifacts,...plannerHistory}});
73
+ let decision=evaluateCooperative({state,request:{command,input},evidence:{target:currentTarget,versions,git,changes,requestFingerprint,plannerArtifacts,...plannerHistory,reviewedSpec}});
64
74
  if(command==='record'&&input.evidence.kind==='planner-review'){
65
75
  const data=input.evidence.data,stage=state.plannerLedger?.stages.find(s=>s.id===data.stageId),intent=state.targetIntents?.find(i=>i.id===stage?.targetIntentId),transition=state.targetTransitions?.find(t=>t.intentId===intent?.id&&t.targetVersion===state.targetVersion),document=intent?.documents.find(d=>d.kind===stage?.document.kind);
66
76
  if(transition&&document){
@@ -70,7 +80,11 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
70
80
  decision=valid?{decision:'allow',ruleIds:['cooperative.target-preparation']}:{decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Current destination bytes and complete source-bound review required'};
71
81
  }
72
82
  }
73
- if(command==='record'&&['document','approval'].includes(input.evidence.kind)&&state.targetIntents?.some(intent=>!state.targetTransitions?.some(t=>t.intentId===intent.id)&&intent.documents.some(doc=>doc.kind===input.evidence.data.kind&&(input.evidence.data.path===doc.path||input.evidence.data.path===path.join(intent.sourceTarget.realpath,doc.path)))))decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Prepared target transition required before document records'};
83
+ if(command==='record'&&['document','approval'].includes(input.evidence.kind)){
84
+ const {kind,data}=input.evidence;
85
+ const documents=kind==='approval'&&Array.isArray(data.documents)?data.documents:[data];
86
+ if(state.targetIntents?.some(intent=>!state.targetTransitions?.some(t=>t.intentId===intent.id)&&intent.documents.some(doc=>documents.some(d=>d?.kind===doc.kind&&[doc.path,path.join(intent.sourceTarget.realpath,doc.path)].includes(d.path)))))decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Prepared target transition required before document records'};
87
+ }
74
88
  if(command==='record'&&input.evidence.kind==='approval'){
75
89
  const data=input.evidence.data,intent=state.targetIntents?.find(i=>state.targetTransitions?.some(t=>t.intentId===i.id&&t.targetVersion===state.targetVersion)&&i.documents.some(d=>d.kind===data.kind));
76
90
  if(intent){
@@ -81,6 +95,25 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
81
95
  if(stage?.scopeVersion!==state.scopeVersion||![document.path,path.join(state.target.realpath,document.path)].includes(data.path)||!review||observed?.destination?.document?.hash!==data.contentHash||!same(currentTarget,state.target)||!same(versions,state.versions)||input.actor.role!=='orchestrator')decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Current reviewed destination bytes required for approval'};
82
96
  }
83
97
  }
98
+ if(command==='record'&&input.evidence.kind==='approval'&&Array.isArray(input.evidence.data.documents)&&decision.decision==='allow'){
99
+ const intent=preparedTargetIntent(state),documents=input.evidence.data.documents;
100
+ if(intent){
101
+ let valid=input.actor.role==='orchestrator'&&same(currentTarget,state.target)&&same(versions,state.versions)&&hasExactPlanningKinds(documents,expectedCooperativePlanningKinds(state));
102
+ for(const doc of intent.documents){
103
+ if(!valid)break;
104
+ const absolutePath=path.join(state.target.realpath,doc.path);
105
+ const entry=documents.find(d=>d.kind===doc.kind&&[doc.path,absolutePath].includes(d.path));
106
+ const firstStage=state.plannerLedger?.stages.find(s=>s.id===intent.firstStageId);
107
+ const stage=firstStage?.document.kind===doc.kind?firstStage:state.plannerLedger?.stages.find(s=>s.document.kind===doc.kind&&s.document.path===absolutePath&&s.targetVersion===state.targetVersion);
108
+ const review=entry&&state.records.findLast(r=>r.kind==='planner-review'&&r.source==='operator-attested'&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.data?.stageId===stage?.id&&r.data?.resultRef===stage?.result?.ref&&r.data?.full===true&&r.data?.complete===true&&r.data?.hash===entry.contentHash);
109
+ if(!review||stage?.scopeVersion!==state.scopeVersion){valid=false;break;}
110
+ let observed;
111
+ try{observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:{realpath:state.target.realpath,path:doc.path},observe,readChanges});}catch{}
112
+ valid=same(observed?.destination?.target,state.target)&&observed.destination.document?.hash===entry.contentHash;
113
+ }
114
+ if(!valid)decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Current reviewed bytes required for every approved document'};
115
+ }
116
+ }
84
117
  if(command==='record'&&input.evidence.kind==='target-preparation'){
85
118
  let observed;
86
119
  try{const intent=state.targetIntents?.find(i=>i.id===input.evidence.data.intentId);observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:input.evidence.data.destination,observe,readChanges});}catch{}
@@ -171,7 +204,7 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
171
204
  const task=state.tasks.find(t=>t.id===id),approval=state.records.findLast(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(id)));
172
205
  if(!task||task.invalidated||task.scopeVersion!==state.scopeVersion||!approval||approval.revision<=marker.revision||approval.scopeVersion!==state.scopeVersion||approval.targetVersion!==state.targetVersion||task.approvalRef!==approval.messageRef||task.approvalVersion!==approval.data.approvalVersion||task.documentVersion!==approval.data.documentVersion){ready=false;break;}
173
206
  const documents=approval.data.documents;
174
- if(!Array.isArray(documents)||documents.length!==2||!['spec','plan'].every(kind=>documents.some(d=>d.kind===kind))){ready=false;break;}
207
+ if(!hasExactPlanningKinds(documents,expectedCooperativePlanningKinds(state))){ready=false;break;}
175
208
  try{const observed=await readGit({target:currentTarget,documents});if(!same(observed.target,currentTarget)||!observed.docsCommit||!same(observed.docsCommit.documents,documents)||documents.some(d=>d.commit!==observed.docsCommit.commit||d.approvalRef!==approval.messageRef||!observed.documents?.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash))){ready=false;break;}}
176
209
  catch{ready=false;break;}
177
210
  const scope=state.scopes.find(s=>s.scopeVersion===state.scopeVersion);if(!scope||task.paths.some(p=>!scope.data.paths.some(base=>within(base,p)))){ready=false;break;}
@@ -15,7 +15,7 @@ import {prepareCooperativeAssignment} from './assignment.mjs';
15
15
  */
16
16
  import path from 'node:path';
17
17
  import {legacyCooperativeRoleDenial,validateCooperativeState,validateCooperativeCommand} from './cooperative-schema.mjs';
18
- import {validateWorkflowState, validateRequest, validateEvidence,validatePlannerStage} from './schema.mjs';
18
+ import {validateWorkflowState, validateRequest, validateEvidence,validatePlannerStage,hasExactPlanningKinds,planningDocumentKinds} from './schema.mjs';
19
19
  import {ROLES, ROLE_OPERATIONS, GIT_OPERATIONS, EXTERNAL_OPERATIONS, canonicalCooperativeRole} from './operations.mjs';
20
20
  const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
21
21
  const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative));};
@@ -68,7 +68,7 @@ export function evaluate(policy, state, request, evidence){
68
68
  if(d.role==='implementer'){
69
69
  if(state.mode==='plan'){
70
70
  // T3 supplies verified Git object evidence. Local assertions never satisfy this gate.
71
- 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']);
71
+ if(!hasExactPlanningKinds(state.documents,planningDocumentKinds(state.planningDepth)))return result('hold','runtime.docs-commit','approved complete planning-document set required',['approved-documents','docs-only-commit']);
72
72
  const docs=fact('docs-commit')?.data;
73
73
  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)));
74
74
  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']);
@@ -88,7 +88,12 @@ export function evaluate(policy, state, request, evidence){
88
88
  const stage=state.plannerLedger?.stages.find(s=>s.id===d.plannerCall?.stageId),proof=fact('planner-call');
89
89
  const contract=stage&&{document:stage.document,inputVersion:stage.inputVersion,criteriaVersion:stage.criteriaVersion,scopeVersion:stage.scopeVersion};
90
90
  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']);
91
- 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']);
91
+ if(state.planningDepth==='Bounded'&&stage.document.kind==='spec')return result('hold','runtime.planner-call','Bounded depth has no spec stage',['approved-spec']);
92
+ if(stage.document.kind==='plan'&&state.planningDepth!=='Bounded'){
93
+ const reviewedSpecStage=state.plannerLedger.stages.some(s=>s.workflowId===state.workflowId&&s.document.kind==='spec'&&s.ready===true&&s.review.full===true&&s.review.complete===true&&s.scopeVersion===stage.scopeVersion);
94
+ const approvedSpec=reviewedSpecStage||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)));
95
+ if(!approvedSpec)return result('hold','runtime.planner-call','Reviewed spec prerequisite required',['approved-spec']);
96
+ }
92
97
  const planner=evaluatePlannerCall({stage,request:{...d.plannerCall,requestId:request.requestId},evidence:{artifacts:proof.data.artifacts,semanticProvenance:'operator-attested'}});
93
98
  if(planner.decision!=='allow')return planner;
94
99
  next.plannerLedger.stages[next.plannerLedger.stages.findIndex(s=>s.id===stage.id)]=planner.proposedTransition;
@@ -108,7 +113,7 @@ export function evaluate(policy, state, request, evidence){
108
113
  const relative=p=>typeof p==='string'&&p.length>0&&!/[\\\x00\r\n:]/.test(p)&&!p.startsWith('/')&&!p.split('/').some(x=>!x||x==='.'||x==='..');
109
114
  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']);
110
115
  if(d.kind==='documents'){
111
- 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']);
116
+ if(state.mode!=='plan'||!hasExactPlanningKinds(state.documents,planningDocumentKinds(state.planningDepth))||!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']);
112
117
  }else{
113
118
  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'));
114
119
  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']);
@@ -222,8 +227,18 @@ export function evaluateCooperativePlanner({state,request,evidence}={}){
222
227
  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');}
223
228
  const targetIntent=state.targetIntents?.find(i=>i.id===data.targetIntentId);
224
229
  const approvedOmission=targetIntent?.depth==='Bounded'&&targetIntent.firstStageId===data.id&&targetIntent.documents.length===1&&targetIntent.documents[0].kind==='plan';
225
- 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))));
226
- if(data.document.kind==='plan'&&!approvedOmission&&!approvedSpec)return result('hold','Approved spec prerequisite is required for plan drafting');
230
+ if(data.document.kind==='plan'&&!approvedOmission){
231
+ const refs=approval.data.prerequisiteRefs;
232
+ const current=r=>r.source==='operator-attested'&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion;
233
+ if(preparedIntent){
234
+ const spec=preparedIntent.documents.find(d=>d.kind==='spec');
235
+ const reviewedSpec=state.targetDocuments?.findLast(d=>d.intentId===preparedIntent.id&&d.path===spec?.path&&d.scopeVersion===state.scopeVersion&&d.targetVersion===state.targetVersion);
236
+ const review=reviewedSpec&&state.records.find(r=>r.kind==='planner-review'&&r.messageRef===reviewedSpec.reviewRef&&current(r)&&r.data?.full===true&&r.data?.complete===true&&r.data?.hash===reviewedSpec.hash);
237
+ const approvedSpec=reviewedSpec?.approvalRef&&state.records.find(r=>r.kind==='approval'&&r.messageRef===reviewedSpec.approvalRef&&r.data.kind==='spec'&&current(r)&&[reviewedSpec.path,path.join(state.target.realpath,reviewedSpec.path)].includes(r.data.path)&&r.data.contentHash===reviewedSpec.hash);
238
+ if(!review||approval.actor?.role!=='orchestrator'||!Array.isArray(refs)||!(refs.includes(reviewedSpec.reviewRef)||approvedSpec&&refs.includes(approvedSpec.messageRef)))return result('hold','Reviewed spec prerequisite is required for plan drafting');
239
+ if(evidence.reviewedSpec?.hash!==reviewedSpec.hash)return result('hold','Reviewed spec bytes changed');
240
+ }else if(!Array.isArray(refs)||!refs.some(ref=>state.records.some(r=>r.kind==='approval'&&r.messageRef===ref&&r.data.kind==='spec'&&current(r))))return result('hold','Reviewed spec prerequisite is required for plan drafting');
241
+ }
227
242
  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);
228
243
  if(evidence.plannerHistoryError)return result('hold','Planner history could not be verified: '+evidence.plannerHistoryError);
229
244
  if(previous.length){
@@ -1,6 +1,7 @@
1
1
  import {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
2
2
  export {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
3
3
  import path from 'node:path';
4
+ import {hasExactPlanningKinds,planningDocumentKinds} from './schema.mjs';
4
5
 
5
6
  const reconciliations=new WeakMap();
6
7
  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));}
@@ -33,7 +34,7 @@ export async function runGate({phase,state,request,gitEvidence,expectedCommit,re
33
34
  return path.relative(state.target.realpath,file).split(path.sep).join('/');
34
35
  }),d.paths))return hold('Request paths differ from commit paths');
35
36
  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
+ if(state.mode!=='plan'||!hasExactPlanningKinds(state.documents,planningDocumentKinds(state.planningDepth))||!samePaths(d.paths,state.documents.map(x=>x.gitPath)))return hold('Complete exact approved planning-document set required','runtime.docs-commit');
37
38
  for(const document of state.documents){
38
39
  const approvals=state.approvals?.filter(a=>a.id===document.approvalRef);
39
40
  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');
@@ -428,7 +428,7 @@
428
428
  "preceding-approval"
429
429
  ],
430
430
  "authority": "orchestrator",
431
- "text": "Follow planning.md's Planner drafting preparation and review procedure, including preflight, ledger, evidence classification, target preparation, preceding approvals, provenance and reference gates. Before Planner dispatch, evaluate F1–F8 direct-path eligibility and Bounded plan-omission eligibility independently. Enter each path only when all of that path's existing conditions are proven; if neither path qualifies, use normal full evaluation. Send one complete stage-specific initial brief. Reuse the same Planner instance only within the design/brainstorming stage while its role, context and source remain valid; after design approval, use a fresh Planner instance for each spec and plan stage, whose initial brief contains every required field, saved document paths and approved versions. Follow-up briefs send changed fields and cite an accessible prior brief for unchanged fields. Reuse evidence only for the same source set, absolute locator, resolved path, content fingerprint, purpose and approval scope in an accessible matching context. When source, target or scope changed, reconfirm affected inputs. Planner returns a complete proportional first draft and self-review. Orchestrator reviews and directly revises the same spec or plan when needed. A missing or failed first draft does not transfer initial authorship to Orchestrator. New product decisions outside approved scope require user input before Orchestrator revises the document. For design and brainstorming, allow the initial draft and one consolidated correction. Orchestrator reviews once with the fixed checklist and sends one consolidated correction using changed fields only. Further calls require user-approved material scope/evidence changes or concrete unmet checklist items after correction, plus meaningful new input or criterion-state progress. State changed input, target criterion, expected artifact and expected progress. Repeated unmet criteria without new input, evidence or progress hold the stage; report the criterion, observed evidence and exact unblock input/decision. DO NOT split omissions, repeat resolved items or count rewording/agent replacement as progress. DO NOT invoke Planner only for reformatting, re-expression, save errors or patch-application errors; Orchestrator handles these. Evaluate separate substantive work under the normal Planner gate. Preserve separate sequential design/spec/plan approvals. Add no fixed call cap or profile call-count conditions, and NEVER accept an incomplete draft. Keep user progress brief and based on Planner status without relaying draft content. At approval, present the integrated, saved and reviewed Markdown without repeating its body in chat.",
431
+ "text": "Follow planning.md's Planner drafting preparation and review procedure, including preflight, ledger, evidence classification, target preparation, preceding approvals, provenance and reference gates. Before Planner dispatch, evaluate F1–F8 direct-path eligibility and Bounded plan-omission eligibility independently. Enter each path only when all of that path's existing conditions are proven; if neither path qualifies, use normal full evaluation. Send one complete stage-specific initial brief. Reuse the same Planner instance only within the design/brainstorming stage while its role, context and source remain valid, except that on the Architectural path that Planner continues as the spec Planner after start confirmation through a spec-stage delta brief; use a fresh Planner instance for each plan stage, and for an Architectural spec stage when that Planner is unavailable or its role, context or source is no longer valid, whose initial brief contains every required field, saved document paths and approved versions (for the Architectural plan stage, the reviewed spec path, version and SHA-256). Follow-up briefs send changed fields and cite an accessible prior brief for unchanged fields. Reuse evidence only for the same source set, absolute locator, resolved path, content fingerprint, purpose and approval scope in an accessible matching context. When source, target or scope changed, reconfirm affected inputs. Planner returns a complete proportional first draft and self-review. Orchestrator reviews and directly revises the same spec or plan when needed. A missing or failed first draft does not transfer initial authorship to Orchestrator. New product decisions outside approved scope require user input before Orchestrator revises the document. For design and brainstorming, follow planning.md's design conversation: each Planner response is exactly one of one question, 2–3 approaches with a recommendation and a selection question, one design section with a confirmation question, or the final design (Architectural: the start summary). Ask one question at a time only when the answer changes the outcome and is not already answered; otherwise state the judgment and its reason. Ask an open question about the user's reason before offering options. A clear request may receive a short design for approval at once; when the user says to proceed, stop asking and list the remaining author judgments in the final design or start summary. Relay user answers verbatim and mark added interpretation separately. Every call needs a new user answer or new evidence; without progress, report the blocked criterion, observed facts and needed decision, and hold. Conversation responses use no correction opportunity. Orchestrator reviews the final design once with the fixed checklist, including decision-inventory completeness and no ambiguous scope wording, and sends one consolidated correction using changed fields only. On the Architectural path the start summary receives no consolidated correction; Orchestrator checks its decision inventory and scope notation before presenting it, and the spec draft takes Orchestrator's review and direct revision. Further calls require user-approved material scope/evidence changes or concrete unmet checklist items after correction, plus meaningful new input or criterion-state progress. State changed input, target criterion, expected artifact and expected progress. Repeated unmet criteria without new input, evidence or progress hold the stage; report the criterion, observed evidence and exact unblock input/decision. DO NOT split omissions, repeat resolved items or count rewording/agent replacement as progress. DO NOT invoke Planner only for reformatting, re-expression, save errors or patch-application errors; Orchestrator handles these. Evaluate separate substantive work under the normal Planner gate. For Bounded work, obtain design approval before plan drafting. For Architectural work, obtain one start confirmation (scope and explicit target; no design document or design approval) before spec drafting, let the design Planner continue as the spec Planner (a fresh spec Planner when it is unavailable or invalid), then draft the plan with a fresh Planner, assigning the plan Planner only after the spec is saved and reviewed and its path, version and SHA-256 are fixed; NEVER draft them concurrently; then obtain one combined spec+plan approval. Bounded work has no spec stage; required plans keep their own approval. Add no fixed call cap or profile call-count conditions, and NEVER accept an incomplete draft. Keep user progress brief and based on Planner status without relaying draft content. At approval, present the integrated, saved and reviewed Markdown without repeating its body in chat.",
432
432
  "controls": {
433
433
  "codex": "prompt",
434
434
  "claude": "prompt",
@@ -43,6 +43,7 @@ export function validateWorkflowState(s,{allowLegacyOperations=true,preserveStor
43
43
  if(['policyHash','runtimeHash','adapterHash'].some(k=>!hash(s.versions[k])))fail('hash algorithm');
44
44
  if(!object(s.target)||!absolute(s.target.realpath)||['repository','worktree','baseHead','head'].some(k=>!text(s.target[k]))||!(s.target.branch===null||text(s.target.branch)))fail('target');
45
45
  if(!['plan','small-task','no-plan'].includes(s.mode))fail('mode');
46
+ if(s.planningDepth!==undefined&&!['Architectural','Bounded'].includes(s.planningDepth))fail('planning depth');
46
47
  for(const k of ['documents','approvals','tasks','assignments','identities','leases','checks','findings','acceptances','commits','audit','capabilities','requests'])if(!Array.isArray(s[k]))fail(k);
47
48
  const stored=s,normalized=normalizeStoredOperations(s);
48
49
  if(!allowLegacyOperations&&normalized!==s&&(!legacyOperationsFrom||hasNewStoredOperationAliases(s,legacyOperationsFrom)))fail('legacy operation in new state');
@@ -66,6 +67,21 @@ export function validateWorkflowState(s,{allowLegacyOperations=true,preserveStor
66
67
  if(s.plannerLedger!==undefined){validatePlannerLedger(s.plannerLedger);if(s.plannerLedger.stages.some(stage=>stage.workflowId!==s.workflowId))fail('Planner workflow binding');}
67
68
  return preserveStoredOperations?stored:s;
68
69
  }
70
+ export function planningDocumentKinds(depth){
71
+ return depth==='Bounded'?['plan']:['plan','spec'];
72
+ }
73
+ export function hasExactPlanningKinds(documents,kinds){
74
+ if(!Array.isArray(documents)||documents.length!==kinds.length)return false;
75
+ const actual=documents.map(d=>d?.kind).sort();
76
+ return kinds.every((kind,index)=>kind===actual[index]);
77
+ }
78
+ export function preparedTargetIntent(state){
79
+ return state.targetIntents?.find(i=>state.targetTransitions?.some(t=>t.intentId===i.id&&t.targetVersion===state.targetVersion));
80
+ }
81
+ export function expectedCooperativePlanningKinds(state){
82
+ const intent=preparedTargetIntent(state);
83
+ return intent?[...new Set(intent.documents.map(d=>d.kind))].sort():planningDocumentKinds();
84
+ }
69
85
  export function validateRequest(r){
70
86
  if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!isPlatformId(r.platform)||!OPERATIONS.includes(r.operation)||!absolute(r.cwd)||!object(r.arguments)||!object(r.descriptor)||!strings(r.paths)||r.paths.some(p=>!absolute(p)))fail('request');
71
87
  return r;
@@ -38,7 +38,7 @@ export function validateTargetPreparationRecord(kind,data){
38
38
  if(kind==='intent'&&(!Number.isSafeInteger(data.sourceTargetVersion)||data.sourceTargetVersion<1||!['realpath','gitCommonDir','gitDir'].every(k=>typeof data.sourceTarget[k]==='string'&&path.isAbsolute(data.sourceTarget[k])&&path.normalize(data.sourceTarget[k])===data.sourceTarget[k])||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.sourceTarget.head)||!(data.sourceTarget.branch===null||text(data.sourceTarget.branch))||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.base)||new Set(data.documents.map(d=>d.path)).size!==data.documents.length))throw Error('Invalid target preparation intent identity');
39
39
  if(kind==='checkpoint'&&(!text(data.intentId)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)))throw Error('Invalid target preparation checkpoint');
40
40
  if(kind==='transition'&&(!text(data.intentId)||!text(data.checkpointRef)||!Number.isSafeInteger(data.expectedRevision)||data.expectedRevision<0))throw Error('Invalid target preparation transition');
41
- if(kind==='destination'&&(!text(data.intentId)||!text(data.transitionRef)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)||!relative(data.path)||!/^sha256:[a-f0-9]{64}$/.test(data.hash)||![0o100644,0o100755].includes(data.mode)||!text(data.reviewRef)||!text(data.approvalRef)||!Number.isSafeInteger(data.targetVersion)||data.targetVersion<1))throw Error('Invalid target preparation destination');
41
+ if(kind==='destination'&&(!text(data.intentId)||!text(data.transitionRef)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)||!relative(data.path)||!/^sha256:[a-f0-9]{64}$/.test(data.hash)||![0o100644,0o100755].includes(data.mode)||!text(data.reviewRef)||(data.approvalRef!==undefined&&!text(data.approvalRef))||!Number.isSafeInteger(data.targetVersion)||data.targetVersion<1))throw Error('Invalid target preparation destination');
42
42
  return data;
43
43
  }
44
44
 
@@ -49,6 +49,7 @@ export function evaluateTargetPreparation({state,request,evidence}={}){
49
49
  if(state.targetIntents?.some(intent=>!state.targetTransitions?.some(transition=>transition.intentId===intent.id)))return hold('Existing target preparation intent is still active');
50
50
  const approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.source==='operator-attested'&&r.actor?.role==='orchestrator'&&r.targetVersion===state.targetVersion&&r.scopeVersion===state.scopeVersion);
51
51
  const approved=approval?.data?.targetPreparation;
52
+ if(request.depth==='Bounded'&&request.documents.some(d=>d.kind==='spec'))return hold('Bounded depth has no spec stage');
52
53
  if(!['Bounded','Architectural'].includes(request.depth)||(request.depth==='Architectural'&&(!request.documents.some(d=>d.kind==='spec')||!request.documents.some(d=>d.kind==='plan'))))return hold('Approved depth requires its complete document set');
53
54
  if(!text(request.approvalRef)||!text(request.depth)||['depth','selectionRef','kind','candidate','base','workflowId','firstStageId','sourceTargetVersion'].some(k=>approved?.[k]!==request[k])||!same(approved?.sourceTarget,request.sourceTarget)||!same(approved?.documents,request.documents)||request.workflowId!==state.workflowId||request.sourceTargetVersion!==state.targetVersion||!same(request.sourceTarget,state.target)||!same(evidence?.source?.target,state.target)||!text(evidence?.source?.fingerprint)||!state.selections?.some(s=>s.messageRef===request.selectionRef&&s.targetVersion===state.targetVersion)||state.targetIntents?.some(i=>i.id===request.id)||request.base!==state.target.head)return hold('Current approval, document set, source, explicit choice and preservation snapshot required');
54
55
  return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{intent:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceFingerprint:evidence.source.fingerprint,...(evidence.source.snapshot?{sourceSnapshot:structuredClone(evidence.source.snapshot)}:{}),source:'operator-attested'}}};
@@ -70,8 +71,12 @@ export function evaluateTargetPreparation({state,request,evidence}={}){
70
71
  if(request.type==='destination'){
71
72
  const intent=state.targetIntents?.find(i=>i.id===request.intentId),document=intent?.documents?.find(d=>d.path===request.path),transition=state.targetTransitions?.find(t=>t.intentId===request.intentId&&t.messageRef===request.transitionRef&&t.targetVersion===state.targetVersion),checkpoint=state.targetCheckpoints?.find(c=>c.intentId===request.intentId&&c.messageRef===transition?.checkpointRef),stage=state.plannerLedger?.stages?.find(s=>s.id===request.stageId),chat=stage?.result?.chatDraft,observed=evidence?.destination?.document;
72
73
  const review=state.records?.find(r=>r.kind==='planner-review'&&r.messageRef===request.reviewRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested'),approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested');
74
+ if(intent&&document&&request.approvalRef===undefined&&!(intent.depth==='Architectural'&&document.kind==='spec'))return hold('Document approval required for this destination');
73
75
  if(!intent||!document||intent.firstStageId!==request.stageId||!transition||!same(transition.target,state.target)||request.targetVersion!==state.targetVersion||!checkpoint||checkpoint.stageId!==request.stageId||checkpoint.resultRef!==request.resultRef||checkpoint.selfReviewRef!==request.selfReviewRef||stage?.targetIntentId!==intent.id||stage.result?.ref!==request.resultRef||stage.result.status!=='succeeded'||chat?.intentId!==intent.id||chat.complete!==true||chat.selfReviewRef!==request.selfReviewRef||!same(evidence?.destination?.target,state.target)||observed?.verification?.status!=='verified'||observed.verification.source!=='local-bytes'||observed.path!==request.path||observed.hash!==request.hash||observed.mode!==request.mode)return hold('Current transition, source attestation and observed destination bytes required');
74
- if(stage.scopeVersion!==state.scopeVersion||review?.data?.resultRef!==request.resultRef||review.data.full!==true||review.data.complete!==true||review.data.hash!==request.hash||!Array.isArray(stage.criteria)||!Array.isArray(review.data.criteria)||review.data.criteria.length!==stage.criteria.length||new Set(review.data.criteria.map(c=>c.id)).size!==stage.criteria.length||review.data.criteria.some(c=>!stage.criteria.some(s=>s.id===c.id)||c.status!=='resolved'||!text(c.judgmentRef))||approval?.data?.kind!==document.kind||approval.data.contentHash!==request.hash||![request.path,path.join(state.target.realpath,request.path)].includes(approval.data.path))return hold('Current full review and document approval required');
76
+ const approvedPath=[request.path,path.join(state.target.realpath,request.path)];
77
+ const matchesApproval=entry=>entry?.kind===document.kind&&entry.contentHash===request.hash&&approvedPath.includes(entry.path);
78
+ const approved=request.approvalRef===undefined||(Array.isArray(approval?.data?.documents)?stage?.document?.kind===document.kind&&approval.data.documents.filter(matchesApproval).length===1:matchesApproval(approval?.data));
79
+ if(stage.scopeVersion!==state.scopeVersion||review?.data?.resultRef!==request.resultRef||review.data.full!==true||review.data.complete!==true||review.data.hash!==request.hash||!Array.isArray(stage.criteria)||!Array.isArray(review.data.criteria)||review.data.criteria.length!==stage.criteria.length||new Set(review.data.criteria.map(c=>c.id)).size!==stage.criteria.length||review.data.criteria.some(c=>!stage.criteria.some(s=>s.id===c.id)||c.status!=='resolved'||!text(c.judgmentRef))||!approved)return hold('Current full review and document approval required');
75
80
  return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{destination:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceLink:'operator-attested',verification:{status:'verified',source:'local-bytes'}}}};
76
81
  }
77
82
  if(request?.type!=='checkpoint')return hold('Unsupported target preparation request');
@@ -67,7 +67,7 @@ function record({state,request,evidence}){
67
67
  export function evaluateCooperativeVerification({state,request,evidence}={}){
68
68
  const denial=legacyCooperativeRoleDenial(request);
69
69
  if(denial)return {...base(state),...denial};
70
- if(state?.mode!=='plan')return hold(state,'unsupported','Only the complete spec and plan path is supported');
70
+ if(state?.mode!=='plan')return hold(state,'unsupported','Only the plan path is supported');
71
71
  if(!request||request.expectedRevision!==state.revision)return hold(state,'revision','Stale verification request');
72
72
  if(request.actor?.role!=='orchestrator')return hold(state,'verification-actor','Orchestrator statement required');
73
73
  if(request.operation==='verification-record')return record({state,request,evidence});