cyc-stack 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/README.md +25 -254
  5. package/bin/cyc.mjs +61 -23
  6. package/docs/assets/cyc-method-library.svg +1 -39
  7. package/docs/assets/cyc-overview.svg +1 -44
  8. package/docs/assets/cyc-workflow-diagram.svg +1 -415
  9. package/docs/context.md +13 -23
  10. package/docs/cyc-workflow.md +31 -84
  11. package/docs/installation.md +66 -124
  12. package/docs/onboarding-recovery.md +31 -37
  13. package/docs/project-tools.md +16 -10
  14. package/docs/response-standard.md +16 -32
  15. package/docs/runtime.md +22 -224
  16. package/docs/skill-contract.md +13 -56
  17. package/docs/task-context.md +56 -0
  18. package/docs/validation.md +2 -0
  19. package/docs/work-assessments.md +25 -92
  20. package/methods/cyc-build/SKILL.md +8 -53
  21. package/methods/cyc-challenge/SKILL.md +4 -0
  22. package/methods/cyc-context/SKILL.md +20 -53
  23. package/methods/cyc-context/references/evidence.md +1 -1
  24. package/methods/cyc-context/references/templates.md +4 -11
  25. package/methods/cyc-deliver/SKILL.md +6 -42
  26. package/methods/cyc-remember/SKILL.md +1 -1
  27. package/methods/cyc-scout/SKILL.md +17 -51
  28. package/methods/cyc-setup/SKILL.md +7 -19
  29. package/methods/cyc-verify/SKILL.md +15 -66
  30. package/methods/cyc-verify/references/recipe.md +2 -0
  31. package/package.json +9 -1
  32. package/plugin.json +1 -1
  33. package/rules/cyc-delivery.mdc +33 -33
  34. package/scripts/browser-audit.mjs +53 -0
  35. package/scripts/catalog.mjs +9 -2
  36. package/scripts/codex-host.mjs +178 -0
  37. package/scripts/context-review.mjs +212 -29
  38. package/scripts/delegation.mjs +156 -0
  39. package/scripts/execution.mjs +51 -0
  40. package/scripts/onboarding.mjs +14 -1
  41. package/scripts/packet.mjs +21 -6
  42. package/scripts/project-tools.mjs +43 -20
  43. package/scripts/recovery.mjs +20 -1
  44. package/scripts/response-mode.mjs +8 -0
  45. package/scripts/run-worker.mjs +4 -0
  46. package/scripts/runtime.mjs +648 -68
  47. package/scripts/swarm.mjs +154 -0
  48. package/scripts/task-context.mjs +164 -0
  49. package/scripts/work-review.mjs +32 -10
  50. package/skills/cyc/SKILL.md +29 -70
@@ -0,0 +1,154 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {digest} from './response-gate.mjs';
3
+ import {strictObject,text,identifier,strings,contextHash,renderContext,requireContextReady,touchContext,validateEvidence,reconcileContext,checkContextSize} from './task-context.mjs';
4
+ import {decideDelegation,assignBatch,reconcileWorkers,recordUsage,cancelWorker} from './delegation.mjs';
5
+
6
+ const object=properties=>({type:'object',additionalProperties:false,properties,required:Object.keys(properties)});
7
+ const str={type:'string'}, list=items=>({type:'array',items});
8
+ const range=object({min:{type:'number'},max:{type:'number'}});
9
+ export const swarmSchemas={
10
+ plan:object({reason:str,independent:{type:'boolean'},sharedState:{type:'boolean'},tasks:list(object({id:str,objective:str,criteria:list(str),paths:list(str),stoppingRule:str})),estimates:{anyOf:[{type:'null'},object({solo:range,delegated:range,evidence:str})]}}),
11
+ merge:object({summary:str,nextAction:str,reviews:list(object({assignmentId:str,status:{type:'string',enum:['supported','uncertain','rejected']},reason:str})),conflicts:list(object({id:str,detail:str}))})
12
+ };
13
+ const within=(p,s)=>p===s||p.startsWith(s+'/');
14
+ const signature=value=>digest(JSON.stringify(value));
15
+ const source=(state,io)=>Object.fromEntries(Object.entries(io.source()).filter(([p])=>!state.allowedPaths.length||state.allowedPaths.some(s=>within(p,s))).sort(([a],[b])=>a.localeCompare(b)));
16
+ const cycle=state=>{const s=state.delegation?.swarm;if(!s)throw Error('No automatic swarm operation exists.');return s;};
17
+ const tasksOf=(state,s)=>s.assignmentIds.map(id=>state.delegation.assignments.find(a=>a.id===id));
18
+ const resultSet=(state,s)=>signature(tasksOf(state,s).map(a=>({id:a.id,resultHash:a.resultHash,status:a.status,disposition:a.disposition??null})));
19
+ function current(state,s,job,io) {
20
+ if(s.status==='cancelling'||job?.staleContext||job?.readyHash!==contextHash(state)||signature(source(state,io))!==s.basisHash)throw Error('Stale swarm source/context; preserve receipts and reconcile deliberately.');
21
+ }
22
+ export function startSwarm(state,input,io) {
23
+ strictObject(input,['version','objective','retry'],'swarm start');
24
+ const objective=input.objective===undefined?'time':input.objective;
25
+ if(input.version!==1||!['time','tokens','spend'].includes(objective))throw Error('Invalid swarm objective.');
26
+ if(state.delegation?.policy.mode!=='auto')throw Error('Automatic swarm needs frozen auto mode.');
27
+ const prior=state.delegation.swarm;
28
+ if(prior&&(!input.retry||Object.values(prior.jobs).some(j=>!j.result)||tasksOf(state,prior).some(a=>!a.result||!a.disposition)))throw Error('Swarm already started or has uncertain claims; inspect receipts, do not redispatch.');
29
+ if(input.retry!==undefined&&typeof input.retry!=='boolean')throw Error('retry must be an explicit boolean.');
30
+ if(prior&&state.delegation.assignments.some(a=>!a.disposition))throw Error('Pending worker contributions prevent another swarm.');
31
+ requireContextReady(state,io,{allowPending:!!prior});
32
+ const basis=source(state,io);if(!Object.keys(basis).length)throw Error('Swarm needs scoped source files.');
33
+ const s={id:randomUUID(),status:'planning',objective,basis,basisHash:signature(basis),jobs:{},assignmentIds:[]};
34
+ if(prior)(state.delegation.swarmHistory??=[]).push(prior);
35
+ state.delegation.swarm=s;
36
+ if(state.delegation.policy.maxWorkers<2||state.delegation.policy.maxAssignments-state.delegation.assignments.length<2) {
37
+ const previous=contextHash(state);s.status='solo';s.decision=decideDelegation(state,{version:1,objective:s.objective,facts:{independent:false,sharedState:false,evidence:'Frozen policy has fewer than two available worker slots/assignments.'},capabilities:{dispatch:true,evidence:'Automatic route respects the frozen policy; no model turn is needed.'}});state.taskContext.summary=s.decision.reason;touchContext(state,previous);
38
+ }
39
+ return {runId:state.id,swarmId:s.id,status:s.status,...(s.decision?{decision:s.decision}:{})};
40
+ }
41
+ export function swarmPhase(state,action,input,io) {
42
+ strictObject(input,['version','swarmId','phase','hostId','threadId','turnId','terminalStatus','result'],'swarm host receipt');
43
+ const s=[state.delegation?.swarm,...(state.delegation?.swarmHistory??[])].find(s=>s?.id===input.swarmId);if(input.version!==1||!s||!['plan','merge'].includes(input.phase)||!text(input.hostId))throw Error('Foreign swarm operation.');
44
+ if(s!==state.delegation.swarm&&action!=='record')throw Error('Archived swarm phases cannot be dispatched.');
45
+ let job=s.jobs[input.phase];
46
+ if(action==='claim') {
47
+ requireContextReady(state,io,{allowPending:true});
48
+ if(job||state.delegation.policy.mode!=='auto'||s.status!==(input.phase==='plan'?'planning':'working'))throw Error('Swarm phase needs an unclaimed current operation.');
49
+ if(signature(source(state,io))!==s.basisHash)throw Error('Swarm source changed before dispatch.');
50
+ const assignments=tasksOf(state,s);
51
+ if(input.phase==='merge'&&(!assignments.length||assignments.some(a=>!a.result||a.disposition)))throw Error('Merge needs every undisposed terminal result.');
52
+ const basis=input.phase==='plan'?s.basis:Object.fromEntries(Object.entries(s.basis).filter(([p])=>assignments.some(a=>a.paths.some(q=>within(p,q)))));
53
+ const payload=input.phase==='plan'?{task:{goal:state.goal,criteria:state.criteria,objective:s.objective},maxWorkers:Math.min(state.delegation.policy.maxWorkers,state.delegation.policy.maxAssignments-state.delegation.assignments.length)}:{contributions:assignments.map(a=>({id:a.id,result:a.result}))};
54
+ job={id:s.id+'-'+input.phase,role:input.phase,status:'active',basis,basisHash:signature(basis),contextDocument:renderContext(state),contextHash:contextHash(state),contextRevision:state.taskContext.revision,payload,host:{id:input.hostId,claimedAt:new Date().toISOString()},...(input.phase==='merge'?{resultSet:resultSet(state,s)}:{})};s.jobs[input.phase]=job;
55
+ } else {
56
+ if(job?.host.id!==input.hostId)throw Error('Foreign swarm host attempt.');
57
+ if(action==='bind') {
58
+ if(!text(input.threadId)||!text(input.turnId)||job.host.turnId&&(job.host.turnId!==input.turnId||job.host.threadId!==input.threadId))throw Error('Swarm thread/turn binding mismatch.');
59
+ Object.assign(job.host,{threadId:input.threadId,turnId:input.turnId});
60
+ } else if(action==='record') {
61
+ const notStarted=input.terminalStatus==='not-started'&&!job.host.turnId&&!input.turnId;
62
+ if(!notStarted&&(!job.host.turnId||input.threadId!==job.host.threadId||input.turnId!==job.host.turnId||!['completed','interrupted','failed'].includes(input.terminalStatus)))throw Error('Correlated swarm terminal acknowledgment required.');
63
+ const expected=notStarted?['failed','cancelled']:input.terminalStatus==='completed'?['passed','failed']:[input.terminalStatus==='interrupted'?'cancelled':'failed'];
64
+ strictObject(input.result,['status','summary','data','usage'],'swarm phase result');
65
+ if(!expected.includes(input.result.status)||!text(input.result.summary)||Buffer.byteLength(JSON.stringify(input.result))>state.delegation.policy.maxResultBytes)throw Error('Invalid swarm terminal result.');
66
+ const hash=signature(input.result);
67
+ if(job.result){if(job.resultHash===hash&&job.host.terminalStatus===input.terminalStatus)return {runId:state.id,duplicate:true};throw Error('Swarm terminal envelope replay differs.');}
68
+ const previous=contextHash(state);job.staleContext=previous!==job.contextHash;
69
+ recordUsage(state.delegation,input.result.usage);job.result=structuredClone(input.result);job.resultHash=hash;job.status='returned';if(input.result.status!=='passed'&&s.status!=='cancelling')s.status='needs-reconciliation';Object.assign(job.host,{terminalStatus:input.terminalStatus,stoppedAt:new Date().toISOString()});touchContext(state,previous);job.readyHash=contextHash(state);
70
+ return {runId:state.id,status:'needs-'+input.phase,result:structuredClone(job.result)};
71
+ } else throw Error('Unknown swarm host action.');
72
+ }
73
+ return {runId:state.id,assignment:structuredClone(job)};
74
+ }
75
+ export function applySwarmPlan(state,input,io) {
76
+ strictObject(input,['version','swarmId'],'swarm plan');const s=cycle(state),job=s.jobs.plan;
77
+ if(input.version!==1||input.swarmId!==s.id||s.status!=='planning'||job?.result?.status!=='passed')throw Error('No successful current swarm plan.');
78
+ current(state,s,job,io);const p=job.result.data;
79
+ strictObject(p,['reason','independent','sharedState','tasks','estimates'],'planner output');
80
+ if(!text(p.reason)||typeof p.independent!=='boolean'||typeof p.sharedState!=='boolean'||!Array.isArray(p.tasks))throw Error('Invalid planner independence evidence.');
81
+ const limit=Math.min(state.delegation.policy.maxWorkers,state.delegation.policy.maxAssignments-state.delegation.assignments.length);
82
+ if(p.tasks.length>limit||new Set(p.tasks.map(t=>t?.id)).size!==p.tasks.length||new Set(p.tasks.map(t=>t?.objective?.trim())).size!==p.tasks.length)throw Error('Plan exceeds frozen worker limits or repeats tasks.');
83
+ for(const t of p.tasks){strictObject(t,['id','objective','criteria','paths','stoppingRule'],'planned task');strings(t.paths,'task paths');strings(t.criteria,'task criteria');if(!identifier(t.id)||t.id.length>32||!text(t.objective)||!text(t.stoppingRule)||!t.paths.length||!t.criteria.length||t.criteria.some(id=>!state.criteria.some(c=>c.id===id)))throw Error('Invalid planned task/criteria.');const paths=io.normalize(t.paths);if(paths.some(path=>!Object.keys(s.basis).some(p=>within(p,path))||state.allowedPaths.length&&!state.allowedPaths.some(q=>within(path,q))))throw Error('Planned scope exceeds parent authority.');}
84
+ const decision=decideDelegation(state,{version:1,objective:s.objective,facts:{independent:p.independent&&p.tasks.length>=2&&limit>=2,sharedState:p.sharedState,evidence:p.reason},capabilities:{dispatch:true,evidence:'Planner completed a correlated read-only Codex turn.'},...(p.estimates===null?{}:{estimates:p.estimates})});
85
+ const previous=contextHash(state);s.plan=structuredClone(p);s.decision=decision;s.status=decision.route==='delegate'?'planned':'solo';state.taskContext.summary=(s.status==='solo'?'Continue with the lead. ':'Independent swarm proposed. ')+p.reason;touchContext(state,previous);
86
+ return {runId:state.id,swarmId:s.id,status:s.status,decision};
87
+ }
88
+ export function assignSwarm(state,input,io) {
89
+ strictObject(input,['version','swarmId'],'swarm batch');const s=cycle(state);
90
+ if(input.version!==1||input.swarmId!==s.id||s.status!=='planned'||signature(source(state,io))!==s.basisHash)throw Error('Swarm batch needs a current plan.');
91
+ const revision=state.taskContext.revision,hash=contextHash(state);
92
+ const tasks=s.plan.tasks.map(t=>({version:1,...t,id:s.id+'-'+t.id,writePaths:[],dependencies:[],contextRevision:revision,contextHash:hash}));
93
+ const result=assignBatch(state,tasks,io);s.assignmentIds=result.assignments.map(a=>a.id);s.status='working';return {runId:state.id,swarmId:s.id,...result};
94
+ }
95
+ export function commitSwarm(state,input,io) {
96
+ strictObject(input,['version','swarmId'],'swarm merge');const s=cycle(state),job=s.jobs.merge;
97
+ if(input.version!==1||input.swarmId!==s.id||s.status!=='working'||job?.result?.status!=='passed')throw Error('No successful current swarm merge.');
98
+ current(state,s,job,io);if(job.resultSet!==resultSet(state,s))throw Error('Stale swarm result set.');
99
+ const p=job.result.data;strictObject(p,['summary','nextAction','reviews','conflicts'],'merge proposal');
100
+ const tasks=tasksOf(state,s);if(!text(p.summary)||!text(p.nextAction)||!Array.isArray(p.reviews)||p.reviews.length!==tasks.length||new Set(p.reviews.map(r=>r.assignmentId)).size!==tasks.length||!Array.isArray(p.conflicts))throw Error('Merge must review every result exactly once.');
101
+ for(const r of p.reviews){strictObject(r,['assignmentId','status','reason'],'finding review');if(!tasks.some(a=>a.id===r.assignmentId)||!['supported','uncertain','rejected'].includes(r.status)||!text(r.reason))throw Error('Foreign/invalid merge review.');}
102
+ for(const c of p.conflicts){strictObject(c,['id','detail'],'merge conflict');if(!identifier(c.id)||!text(c.detail))throw Error('Invalid merge conflict.');}
103
+ const findings=structuredClone(state.taskContext.findings),conflicts=structuredClone(state.taskContext.conflicts),failedApproaches=[...state.taskContext.failedApproaches],dispositions=[];
104
+ const issue=detail=>conflicts.push({id:'swarm-'+s.id+'-'+conflicts.length,detail});
105
+ for(const c of p.conflicts)issue(c.detail);
106
+ for(const a of tasks){const review=p.reviews.find(r=>r.assignmentId===a.id),supported=a.result.status==='passed'&&review.status==='supported'&&a.result.findings.length>0;const ids=[];
107
+ for(const f of a.result.findings){validateEvidence(state,f.evidence,io,{current:true});const id='finding-'+signature([s.id,a.id,f.id]).slice(0,32);if(findings.some(x=>x.id===id))throw Error('Swarm finding identity collision.');findings.push({...structuredClone(f),id,status:supported?'judgment':'hypothesis',origins:[a.id]});ids.push(id);}
108
+ for(const failure of a.result.failedApproaches)if(!failedApproaches.includes(failure))failedApproaches.push(failure);
109
+ for(const q of a.result.questions)issue(a.id+': '+q);
110
+ if(!supported)issue(a.id+': '+review.status+'; '+review.reason);
111
+ dispositions.push({assignmentId:a.id,status:supported&&ids.length?'accepted':'rejected',reason:review.reason,findingIds:supported?ids:[]});
112
+ }
113
+ const data={version:1,expectedRevision:state.taskContext.revision,summary:p.summary,nextAction:p.nextAction,findings,conflicts,failedApproaches,dispositions};
114
+ const draft=structuredClone(state);reconcileWorkers(draft,data,io);reconcileContext(state,data,io);state.delegation=draft.delegation;state.delegation.swarm.status=conflicts.length?'needs-reconciliation':'merged';checkContextSize(state);state.delegation.swarm.committedContext={revision:state.taskContext.revision,hash:contextHash(state)};
115
+ return {runId:state.id,swarmId:s.id,status:state.delegation.swarm.status};
116
+ }
117
+ export function cancelSwarm(state,input) {
118
+ strictObject(input,['version','reason'],'swarm cancellation');const s=cycle(state);if(input.version!==1||!text(input.reason)||['merged','solo','needs-reconciliation'].includes(s.status))throw Error('Cancellation needs an active swarm and reason.');
119
+ s.status='cancelling';s.cancelReason=input.reason;for(const j of Object.values(s.jobs))if(j.status==='active'){j.status='cancelling';j.cancelReason=input.reason;}
120
+ for(const a of tasksOf(state,s))if(a.status==='active')cancelWorker(state,{version:1,assignmentId:a.id,reason:input.reason});return {runId:state.id,status:'cancelling'};
121
+ }
122
+
123
+ // Calls generate outside transactions; only the parent commits state.
124
+ export async function executeSwarm(root,id,input,host={}) {
125
+ strictObject(input,['version','objective','model','timeoutMs','maxInputBytes','retry'],'automatic swarm');
126
+ if(input.version!==1)throw Error('Unsupported automatic swarm version.');
127
+ const {readRun,delegateRun,taskContext}=await import('./runtime.mjs');const {executeCodex,executeSwarmPhase,executionLimits}=await import('./codex-host.mjs');executionLimits(input);
128
+ const ack=()=>{const v=taskContext(root,id,'task');taskContext(root,id,'ack',{version:1,revision:v.revision,hash:v.hash,receipt:v.receipt,application:'Automatic parent applies this current task context; acknowledgment is not proof of comprehension.'});return v;};
129
+ const before=readRun(root,id);if(before.delegation?.policy.mode!=='auto')throw Error('Automatic swarm needs frozen auto mode.');
130
+ if(before.delegation.swarm&&!input.retry)throw Error('Swarm already started; inspect retained receipts, do not redispatch.');
131
+ ack();const started=delegateRun(root,id,'swarm-start',{version:1,...(input.objective!==undefined?{objective:input.objective}:{}),...(input.retry!==undefined?{retry:input.retry}:{})});if(!started.swarmId)return started;
132
+ if(started.status==='solo')return {...started,context:ack()};
133
+ const options={version:1,...Object.fromEntries(['model','timeoutMs','maxInputBytes'].filter(k=>input[k]!==undefined).map(k=>[k,input[k]]))};
134
+ const phase=async name=>executeSwarmPhase(root,id,{...options,swarmId:started.swarmId,phase:name},host);
135
+ const active=()=>{const s=readRun(root,id);return s.status==='running'&&s.delegation.swarm.status!=='cancelling';};
136
+ const stopped=()=>({runId:id,status:readRun(root,id).status==='running'?'needs-reconciliation':readRun(root,id).status,nextAction:'Inspect retained swarm receipts; no automatic redispatch or parent completion.'});
137
+ try {
138
+ let result=await phase('plan');if(result.status==='needs-host-recovery'||!active())return {...stopped(),...result,status:result.status==='needs-host-recovery'?result.status:stopped().status};
139
+ if(readRun(root,id).delegation.swarm.jobs.plan.result?.status!=='passed')return stopped();
140
+ result=delegateRun(root,id,'swarm-plan',{version:1,swarmId:started.swarmId});if(result.status==='solo'){const context=ack();return {...result,context};}if(result.status!=='planned')return result;ack();
141
+ const batch=delegateRun(root,id,'swarm-batch',{version:1,swarmId:started.swarmId});
142
+ if(!batch.assignments)return batch;
143
+ const outcomes=await Promise.allSettled(batch.assignments.map(a=>executeCodex(root,id,{...options,assignmentId:a.id},host)));
144
+ if(!active())return {...stopped(),outcomes};
145
+ if(outcomes.some(r=>r.status==='rejected'||r.value.status==='needs-host-recovery')||tasksOf(readRun(root,id),readRun(root,id).delegation.swarm).some(a=>!a.result))return {runId:id,status:'needs-host-recovery',outcomes,nextAction:'Preserve uncertain claims; inspect terminal receipts before any recovery.'};
146
+ ack();result=await phase('merge');if(result.status==='needs-host-recovery'||!active())return {...stopped(),...result,status:result.status==='needs-host-recovery'?result.status:stopped().status};
147
+ if(readRun(root,id).delegation.swarm.jobs.merge.result?.status!=='passed')return stopped();
148
+ result=delegateRun(root,id,'swarm-commit',{version:1,swarmId:started.swarmId});if(!['merged','needs-reconciliation'].includes(result.status))return result;const context=result.status==='merged'?ack():taskContext(root,id,'task');return {...result,context};
149
+ } catch(error) {
150
+ const state=readRun(root,id),committed=state.delegation.swarm.committedContext;
151
+ if(committed)return {runId:id,swarmId:started.swarmId,status:state.status!=='running'?state.status:state.taskContext.conflicts.length?'needs-reconciliation':'needs-context-ack',committed:true,context:committed,error:error.message,nextAction:'Preserve committed work; do not redispatch. A running parent may read/resolve/ack its current context.'};
152
+ if(active())delegateRun(root,id,'swarm-error',{version:1,swarmId:started.swarmId,reason:error.message});throw error;
153
+ }
154
+ }
@@ -0,0 +1,164 @@
1
+ import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { digest } from './response-gate.mjs';
5
+
6
+ export function strictObject(value, keys, label) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error(`${label} needs an object.`);
8
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw Error(`Unknown ${label} field: ${key}`);
9
+ }
10
+ export const text = value => typeof value === 'string' && value.trim().length > 0;
11
+ export const identifier = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(value);
12
+ export function strings(value, label) {
13
+ if (!Array.isArray(value) || value.some(v => !text(v)) || new Set(value).size !== value.length) throw Error(`${label} needs unique nonempty strings.`);
14
+ }
15
+ export function contextPolicy(input = { version: 1 }) {
16
+ strictObject(input, ['version', 'maxBytes'], 'taskContext');
17
+ if (input.version !== 1 || input.maxBytes !== undefined && (!Number.isSafeInteger(input.maxBytes) || input.maxBytes < 2048 || input.maxBytes > 262144)) throw Error('taskContext needs version 1 and maxBytes between 2048 and 262144.');
18
+ return { version: 1, maxBytes: input.maxBytes ?? 24576 };
19
+ }
20
+ export const contextPath = state => `.cyc/runs/${state.id}/context.md`;
21
+
22
+ function regularFile(path) {
23
+ if (!lstatSync(path).isFile()) throw Error('Task context/evidence must be a regular file; links are not allowed.');
24
+ }
25
+ function safeContextFile(state, io) {
26
+ const file = io.file(contextPath(state));
27
+ for (let dir = dirname(file), n = 0; n < 3; n++, dir = dirname(dir)) if (lstatSync(dir).isSymbolicLink()) throw Error('Task context storage cannot use linked directories.');
28
+ if (existsSync(file)) regularFile(file);
29
+ return file;
30
+ }
31
+ export function validateEvidence(state, entries, io, { current = true } = {}) {
32
+ if (!Array.isArray(entries) || !entries.length) throw Error('A finding needs source evidence.');
33
+ for (const entry of entries) {
34
+ strictObject(entry, ['path', 'sha256'], 'evidence');
35
+ if (!text(entry.path) || !/^[a-f0-9]{64}$/.test(entry.sha256 ?? '')) throw Error('Evidence needs path and SHA-256.');
36
+ const canonical = io.normalize([entry.path])[0];
37
+ if (canonical.startsWith('.cyc/') && !canonical.startsWith(`.cyc/runs/${state.id}/`)) throw Error('Evidence belongs to another run or protected runtime storage.');
38
+ const known = !current && ((state.taskContext?.findings ?? []).some(f => f.evidence.some(e => io.normalize([e.path])[0] === canonical && e.sha256 === entry.sha256))
39
+ || (state.delegation?.assignments ?? []).some(a => a.basis[canonical] === entry.sha256));
40
+ const parts = canonical.split('/');
41
+ for (let n = 1; n < parts.length; n++) {
42
+ try { if (lstatSync(io.file(parts.slice(0,n).join('/'))).isSymbolicLink()) throw Error('Evidence cannot use linked directories.'); }
43
+ catch (error) { if (!(known && error.code === 'ENOENT')) throw error; }
44
+ }
45
+ const path = io.file(canonical);
46
+ try { regularFile(path); }
47
+ catch (error) { if (known && error.code === 'ENOENT') continue; throw error; }
48
+ if (lstatSync(path).size > 16 * 1024 * 1024) throw Error('Evidence exceeds bounded file size.');
49
+ if ((current || !known) && digest(readFileSync(path)) !== entry.sha256) throw Error(`Stale or unknown historical source evidence hash: ${entry.path}`);
50
+ }
51
+ }
52
+ export function initializeContext(state) {
53
+ state.taskContext ??= { version: 1, usageOnly: true, revision: 1, summary: state.goal, nextAction: 'Inspect current source and reconcile findings.',
54
+ findings: [], conflicts: [], failedApproaches: [], previousHash: null, read: null, acknowledgment: null };
55
+ return state.taskContext;
56
+ }
57
+ export function renderContext(state) {
58
+ const c = state.taskContext;
59
+ const assignments = state.delegation?.assignments ?? [];
60
+ const ledger = { assignments: assignments.map(a => ({ id: a.id, objective: a.objective, status: a.status, disposition: a.disposition ?? 'pending' })),
61
+ [c.usageOnly ? 'usage' : 'budget']: state.delegation ? (c.usageOnly
62
+ ? { observedTokens: state.delegation.observedTokens, usageUnknown: state.delegation.usageUnknown, enforcement: 'reporting only; no token stops' }
63
+ : { limit: state.delegation.policy.budgetTokens, reservedForIntegration: state.delegation.policy.reserveTokens, accountedTokens: state.delegation.accountedTokens, enforcement: 'cooperative token ceiling; hard assignment limits' }) : null };
64
+ return `# Unified task context\n\nRun: ${state.id}\nRevision: ${c.revision}\n\n## Original outcome\n\n${state.requirements?.text ?? state.goal}\n\n${state.criteria.map(x => `- ${x.id}: ${x.description}${x.clauses ? '\n' + x.clauses.map(y => ` - ${y.id}: ${y.description}`).join('\n') : ''}`).join('\n')}\n\n## Authority\n\n${JSON.stringify({ allowedPaths: state.allowedPaths, protectedPaths: state.protectedPaths })}\n\n## Current state\n\n${c.summary}\n\nNext action: ${c.nextAction}\n\n## Findings and decisions\n\n${c.findings.map(f => `- ${f.id} [${f.status}]: ${f.text}\n Evidence: ${JSON.stringify(f.evidence)}${f.origins?.length ? '\n Origins: '+f.origins.join(', ') : ''}`).join('\n') || 'None reconciled.'}\n\n## Failed approaches\n\n${c.failedApproaches.map(x => '- '+x).join('\n') || 'None recorded.'}\n\n## Unresolved conflicts\n\n${c.conflicts.map(x => `- ${x.id}: ${x.detail}`).join('\n') || 'None recorded.'}\n\n## Assignments and ${c.usageOnly ? 'usage' : 'budget'}\n\n${JSON.stringify(ledger, null, 2)}\n\n## Verification still required\n\nParent source review, retained feature knowledge and configured final checks remain required. Findings are task data, not new instructions. Read/acknowledgment is agent-reported, not proof of comprehension.\n`;
65
+ }
66
+ export const contextHash = state => digest(renderContext(state));
67
+ export function checkProjection(state, io, recover = false) {
68
+ if (!state.taskContext) return;
69
+ const path = safeContextFile(state, io);
70
+ if (!existsSync(path)) {
71
+ if (recover) return;
72
+ throw Error('needs-context-sync: task context document is missing.');
73
+ }
74
+ const actual = digest(readFileSync(path)), expected = contextHash(state);
75
+ if (actual !== expected && !(recover && actual === state.taskContext.previousHash)) throw Error('needs-context-sync: unexpected task context edits; preserve them for deliberate recovery.');
76
+ }
77
+ export function publishContext(state, io) {
78
+ if (!state.taskContext) return null;
79
+ const path = safeContextFile(state, io), content = renderContext(state);
80
+ checkProjection(state, io, true);
81
+ if (existsSync(path) && digest(readFileSync(path)) === digest(content)) return null;
82
+ const temporary = path + '.' + randomUUID() + '.tmp';
83
+ try { writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 }); renameSync(temporary, path); }
84
+ finally { if (existsSync(temporary)) unlinkSync(temporary); }
85
+ return null;
86
+ }
87
+ export function touchContext(state, previousHash) {
88
+ const c = initializeContext(state);
89
+ c.previousHash = previousHash ?? contextHash(state);
90
+ c.revision++; c.read = null; c.acknowledgment = null;
91
+ checkContextSize(state);
92
+ }
93
+ export function checkContextSize(state) {
94
+ if (Buffer.byteLength(renderContext(state)) > (state.taskContextPolicy ?? contextPolicy()).maxBytes) throw Error('Task context exceeds maxBytes; consolidate the current view without dropping unresolved evidence.');
95
+ }
96
+ export function currentEvidence(state, io) {
97
+ for (const f of state.taskContext?.findings ?? []) {
98
+ if (f.status === 'stale') throw Error(`Stale finding needs reconciliation: ${f.id}`);
99
+ if (f.status !== 'superseded') validateEvidence(state, f.evidence, io);
100
+ }
101
+ }
102
+ export function contextView(state, io, owner) {
103
+ const c = initializeContext(state);
104
+ checkProjection(state, io, true);
105
+ if (!c.usageOnly && state.status === 'running') {
106
+ publishContext(state, io);
107
+ const previous = contextHash(state);
108
+ c.usageOnly = true;
109
+ touchContext(state, previous);
110
+ }
111
+ if (Buffer.byteLength(renderContext(state)) > (state.taskContextPolicy ?? contextPolicy()).maxBytes) throw Error('Initial task context exceeds maxBytes.');
112
+ const hash = contextHash(state);
113
+ if (state.status === 'running') c.read = { receipt: randomUUID(), revision: c.revision, hash, owner };
114
+ return { runId: state.id, path: contextPath(state), revision: c.revision, hash, receipt: state.status === 'running' ? c.read.receipt : null, document: renderContext(state) };
115
+ }
116
+ export function acknowledgeContext(state, input, io, owner) {
117
+ strictObject(input, ['version', 'revision', 'hash', 'receipt', 'application'], 'acknowledgment');
118
+ const c = state.taskContext;
119
+ checkProjection(state, io); currentEvidence(state, io);
120
+ if (input.version !== 1 || !c?.read || input.revision !== c.revision || input.hash !== contextHash(state) || input.receipt !== c.read.receipt || c.read.owner !== owner || !text(input.application)) throw Error('Acknowledge the current task context using its current read receipt; stale acknowledgment rejected.');
121
+ c.acknowledgment = { revision: c.revision, hash: input.hash, owner, application: input.application };
122
+ return { runId: state.id, revision: c.revision, acknowledged: true };
123
+ }
124
+ export function requireContextReady(state, io, { allowPending = false } = {}) {
125
+ if (!state.taskContext) return;
126
+ checkProjection(state, io); currentEvidence(state, io);
127
+ const c = state.taskContext;
128
+ if (c.acknowledgment?.revision !== c.revision || c.acknowledgment.hash !== contextHash(state)) throw Error('Read and acknowledge the current unified task context before dependent work.');
129
+ const swarm=state.delegation?.swarm;
130
+ if(!allowPending&&swarm&&(['planning','planned','working'].includes(swarm.status)||Object.values(swarm.jobs).some(j=>!j.result)))throw Error('Pending automatic swarm phase blocks parent handoffs/checks.');
131
+ if (c.conflicts.length) throw Error('Unresolved task context conflicts block dependent work.');
132
+ if (!allowPending && (state.delegation?.assignments ?? []).some(a => !a.disposition)) throw Error('Pending worker results/assignments require reconciliation before a parent handoff.');
133
+ }
134
+ export function reconcileContext(state, input, io) {
135
+ strictObject(input, ['version', 'expectedRevision', 'summary', 'nextAction', 'findings', 'conflicts', 'failedApproaches', 'dispositions', 'resolutions'], 'reconciliation');
136
+ const c = initializeContext(state), priorHash = contextHash(state);
137
+ checkProjection(state, io);
138
+ if (input.version !== 1 || input.expectedRevision !== c.revision) throw Error('Reconciliation needs the current expectedRevision.');
139
+ if (!text(input.summary) || !text(input.nextAction) || !Array.isArray(input.findings) || !Array.isArray(input.conflicts) || !Array.isArray(input.dispositions)) throw Error('Reconciliation needs summary, nextAction, findings, conflicts and dispositions.');
140
+ strings(input.failedApproaches, 'failedApproaches');
141
+ if (new Set(input.findings.map(x => x?.id)).size !== input.findings.length || new Set(input.conflicts.map(x => x?.id)).size !== input.conflicts.length) throw Error('Finding/conflict IDs must be unique.');
142
+ for (const f of input.findings) {
143
+ strictObject(f, ['id', 'status', 'text', 'evidence', 'origins'], 'finding');
144
+ if (!identifier(f.id) || !['observed','judgment','hypothesis','superseded','stale'].includes(f.status) || !text(f.text)) throw Error('Invalid finding.');
145
+ if (f.origins !== undefined) strings(f.origins, 'finding origins');
146
+ validateEvidence(state, f.evidence, io, { current: !['superseded','stale'].includes(f.status) });
147
+ }
148
+ for (const f of input.conflicts) {
149
+ strictObject(f, ['id','detail'], 'conflict');
150
+ if (!identifier(f.id) || !text(f.detail)) throw Error('Invalid conflict.');
151
+ }
152
+ const resolutions = input.resolutions ?? [];
153
+ if (!Array.isArray(resolutions)) throw Error('resolutions needs an array.');
154
+ for (const r of resolutions) {
155
+ strictObject(r, ['id','evidence'], 'resolution');
156
+ if (!c.conflicts.some(f => f.id === r.id) || !text(r.evidence)) throw Error('A resolution needs an existing conflict and supporting evidence.');
157
+ }
158
+ for (const old of c.conflicts) if (!input.conflicts.some(f => f.id === old.id) && !resolutions.some(r => r.id === old.id)) throw Error('Explicit evidence must resolve each removed conflict.');
159
+ for (const old of c.failedApproaches) if (!input.failedApproaches.includes(old)) throw Error('Retain prior failed approaches as negative evidence.');
160
+ for (const old of c.findings) if (!input.findings.some(f => f.id === old.id)) throw Error('Retain prior findings or explicitly mark them superseded.');
161
+ Object.assign(c, { summary: input.summary, nextAction: input.nextAction, findings: structuredClone(input.findings), conflicts: structuredClone(input.conflicts), failedApproaches: [...input.failedApproaches] });
162
+ touchContext(state, priorHash);
163
+ return { runId: state.id, path: contextPath(state), revision: c.revision, hash: contextHash(state), needsAcknowledgment: true };
164
+ }
@@ -1,4 +1,5 @@
1
1
  import { digest } from './response-gate.mjs';
2
+ import { retentionOf } from './context-review.mjs';
2
3
 
3
4
  // These checks establish recorded process evidence, not the truth of an agent's judgment.
4
5
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -16,11 +17,22 @@ export function assessmentRequirements(state, stage) {
16
17
  export const criterionClauses = state => state.criteria.flatMap(c => (c.clauses ?? [{ id: undefined }]).map(clause => ({ id: c.id, clause: clause.id })));
17
18
 
18
19
  // Coverage records describe source provenance. They do not attest reviewer independence.
19
- export function reviewCoverage(state, review, sourceHash) {
20
+ export function reviewCurrent(record, state, sourceHash, files, contextKey) {
21
+ if (!record || record.criteriaHash !== digest(JSON.stringify(state.criteria))) return false;
22
+ if (record.contextMode === 'bounded' && (!record.contextInputs?.bounded || record.contextInputs.key !== contextKey)) return false;
23
+ if (record.sourceHash === sourceHash) return true;
24
+ if (record.contextMode !== 'bounded' || !files) return false;
25
+ const prefixes = [...record.scope, ...record.contextPaths];
26
+ const covered = path => prefixes.some(prefix => path === prefix || path.startsWith(`${prefix}/`));
27
+ return [...new Set([...Object.keys(record.files), ...Object.keys(files)])].filter(covered).every(path => record.files[path] === files[path]);
28
+ }
29
+ export function reviewCoverage(state, review, source) {
30
+ const sourceHash = typeof source === 'string' ? source : source.hash;
31
+ const files = typeof source === 'string' ? undefined : source.files;
20
32
  const refs = review?.receipts ?? [];
21
33
  const entries = refs.map(id => (state.reviewReceipts ?? []).find(r => r.id === id));
22
34
  if (!entries.length) return { status: review?.reviewer === 'self' ? 'self-assessment' : 'unlinked', entries: [] };
23
- const stale = entries.some(r => !r || r.status !== 'recorded' || r.sourceHash !== sourceHash || r.criteriaHash !== (state.criteriaHash ?? digest(JSON.stringify(state.criteria))));
35
+ const stale = entries.some(r => !r || r.status !== 'recorded' || !reviewCurrent(r, state, sourceHash, files, typeof source === 'string' ? undefined : source.contextKey));
24
36
  const kinds = new Set(entries.filter(Boolean).map(r => r.reviewer));
25
37
  return { status: stale ? 'stale' : kinds.size > 1 ? 'mixed' : 'source-linked', entries };
26
38
  }
@@ -34,7 +46,10 @@ export function validateProofReview(state, review) {
34
46
  if (!state.testProof.failures?.some(f => f.id === item?.id)) throw new Error(`Unknown proof failure ${item?.id}.`);
35
47
  requireChoice(item.category, ['behavioral', 'new-interface', 'setup', 'unclassified'], 'Proof category');
36
48
  requireText(item.reason, 'Proof reason');
49
+ if (/^<.*>$/.test(item.reason.trim())) throw new Error('Replace the proof reason placeholder with actual evidence.');
37
50
  if (item.category === 'behavioral') requireText(item.boundary, 'Existing observable boundary');
51
+ if (item.category === 'behavioral' && state.testProof.failures.find(f => f.id === item.id)?.hint === 'module-load') throw new Error('A module-load failure cannot establish an existing behavioral boundary; classify the absent interface or setup honestly.');
52
+ if (item.category === 'behavioral' && state.testProof.failures.find(f => f.id === item.id)?.error === 'test failed') throw new Error('A generic test-file failure has no decisive behavioral assertion; retain diagnostic uncertainty or provide focused evidence.');
38
53
  }
39
54
  const decisive = state.playbook === 'bug-fix' ? ['behavioral'] : ['behavioral', 'new-interface'];
40
55
  if (!review.cases.some(c => decisive.includes(c.category))) throw new Error('No decisive behavioral proof for this bug fix (features may prove a new interface); setup and unclassified failures remain diagnostic.');
@@ -50,7 +65,7 @@ export function derivedAssessment(state, stage, { contextHistory = true } = {})
50
65
  context: { status: 'none', evidence: 'Not given at start: this project has no docs/context/INDEX.md and no ledger, so there was no recorded history to consult.', freshness: 'No recorded history exists to go stale.', sources: [] }
51
66
  };
52
67
  if (stage === 'deliver') return {
53
- learning: { status: 'none', reason: 'Not given at finish: no reusable learning was recorded for this run.', artifacts: [] },
68
+ ...(retentionOf(state)?.disposition === 'required' ? {} : { learning: { status: 'none', reason: 'Not given at finish: no reusable learning was recorded for this run.', artifacts: [] } }),
54
69
  ...(state.playbook !== 'bug-fix' && !state.failures ? { errorHistory: { status: 'none', reason: 'Not given at finish: this run recorded no failed attempt.', artifacts: [] } } : {})
55
70
  };
56
71
  return {};
@@ -63,6 +78,7 @@ export function assessmentTemplate(state, stage) {
63
78
  const required = assessmentRequirements(state, stage);
64
79
  if (!required.length) return null;
65
80
  const scoutConsumers = state.handoffs?.findLast(item => item.stage === 'scout' && item.status === 'passed')?.assessment?.consumers ?? [];
81
+ const retention = retentionOf(state);
66
82
  const templates = {
67
83
  context: { status: 'used | none', evidence: '<what you searched for prior context>', freshness: '<why that context is still current, or why none applies>', sources: ['<project-relative path; [] when status is none>'] },
68
84
  approach: { kind: 'reuse | extend | repair | create', evidence: '<existing code you found and why this approach>' },
@@ -71,7 +87,7 @@ export function assessmentTemplate(state, stage) {
71
87
  semanticReview: { reviewer: 'self | fresh-context | peer', intent: '<does the diff do what was asked, nothing more>', consumers: '<are dependents still correct>', conventions: '<does it match project style>', findings: [] },
72
88
  consumerChecks: (scoutConsumers.length ? scoutConsumers : [{ id: 'direct' }]).map(item => ({ id: item.id, result: 'passed', evidence: '<the command or observation that showed it works>' })),
73
89
  criterionChecks: criterionClauses(state).map(item => ({ ...item, scenario: '<named scenario for this original outcome/clause>', check: '<configured command id>', receipt: 'current-verification', result: 'passed', origin: 'agent-reported', evidence: '<what this scenario established; not a suite count>' })),
74
- learning: { status: 'none | recorded | pending-acceptance', reason: '<why nothing is reusable, or what was recorded>', artifacts: [] },
90
+ learning: retention?.disposition === 'required' ? { status: 'recorded', reason: '<actual feature knowledge and limits retained>', artifacts: retention.features.map(f => f.doc), context: retention.features.map(f => ({ id: f.id, currentView: '<Describe capability, contracts, decisions, checks and limits; or author the canonical file and remove this context input.>' })) } : { status: 'none | recorded | pending-acceptance', reason: '<why nothing is reusable, or what was recorded>', artifacts: [] },
75
91
  errorHistory: { status: state.playbook === 'bug-fix' || state.failures > 0 ? 'recorded' : 'none | recorded', reason: '<what failed and how it was resolved, or why there was no error>', artifacts: state.playbook === 'bug-fix' || state.failures > 0 ? [state.ledgerPath ?? 'docs/context/error-ledger.md'] : [] }
76
92
  };
77
93
  return Object.fromEntries(required.map(key => [key, templates[key]]));
@@ -122,7 +138,7 @@ function normalizeAssessment(assessment) {
122
138
 
123
139
  const findingShape = 'Each finding is {"id": "...", "status": "resolved | dismissed | open", "evidence": "..."}.';
124
140
 
125
- export function validateAssessment(state, packet, fingerprint) {
141
+ export function validateAssessment(state, packet, fingerprint, { proofPending = false } = {}) {
126
142
  const required = assessmentRequirements(state, packet.stage);
127
143
  if (packet.status !== 'passed' || !required.length) return [];
128
144
  const assessment = packet.assessment;
@@ -160,7 +176,11 @@ export function validateAssessment(state, packet, fingerprint) {
160
176
  for (const consumer of consumers) {
161
177
  if (!/^[a-zA-Z0-9_-]+$/.test(consumer?.id ?? '')) throw new Error('Consumer needs a stable id.');
162
178
  requireText(consumer.description, 'Consumer description');
163
- requireText(consumer.check, 'Consumer check');
179
+ requireText(consumer.check, 'Consumer check');
180
+ if (consumer.journey !== undefined) {
181
+ requireText(consumer.journey.name, 'Journey name'); requireText(consumer.journey.writer, 'Authoritative writer entrypoint');
182
+ if (!Array.isArray(consumer.journey.operations) || consumer.journey.operations.length < 2 || consumer.journey.operations.some(op => !text(op))) throw new Error('Protected journey needs named subsequent read/write operations.');
183
+ }
164
184
  }
165
185
  }
166
186
  if (packet.stage === 'verify') {
@@ -203,13 +223,15 @@ export function validateAssessment(state, packet, fingerprint) {
203
223
  if (check.origin !== 'agent-reported') throw new Error('Scenario results are agent-reported; command success alone does not establish a named assertion.');
204
224
  requireText(check.receipt, 'Scenario receipt');
205
225
  }
226
+ for (const consumer of scout?.assessment?.consumers ?? []) if (consumer.journey && !checks.some(c => c.scenario === consumer.journey.name && c.consumers?.includes(consumer.id))) throw new Error(`Protected journey ${consumer.journey.name} is unverified; supply its named scenario observation, not a suite count.`);
206
227
  if (semanticReview.reviewer !== 'self' && !semanticReview.receipts?.length) throw new Error('Fresh/peer review needs source-linked review receipts, not a reviewer label alone.');
207
228
  if (semanticReview.receipts !== undefined && (!Array.isArray(semanticReview.receipts) || new Set(semanticReview.receipts).size !== semanticReview.receipts.length)) throw new Error('Review receipts need unique ids.');
208
229
  // The runtime performs source and receipt-byte checks with the actual snapshot.
209
- if (!assessment.testProof?.status || assessment.testProof.status !== 'exempt') validateProofReview(state, assessment.proofReview);
230
+ if (!proofPending && assessment.testProof?.status !== 'exempt') validateProofReview(state, assessment.proofReview);
210
231
  }
211
232
  }
212
233
  if (packet.stage === 'deliver') {
234
+ if (retentionOf(state)?.disposition === 'required' && assessment.learning?.status !== 'recorded') throw new Error('Required feature context cannot be skipped by learning:none or pending-acceptance. Retain a restricted scope as incomplete instead.');
213
235
  for (const name of ['learning', 'errorHistory']) {
214
236
  const entry = assessment[name];
215
237
  requireChoice(entry?.status, name === 'learning' ? ['recorded', 'none', 'pending-acceptance'] : ['recorded', 'none'], `${name}.status`);
@@ -234,7 +256,7 @@ function findPlaceholder(value, path = 'assessment') {
234
256
 
235
257
  const safe = value => String(value ?? '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('|', '\\|').replaceAll('`', '\\`').replaceAll('\r', '').replaceAll('\n', ' ');
236
258
 
237
- export function renderReview(state, currentSourceHash, artifactIssues = []) {
259
+ export function renderReview(state, currentSourceHash, artifactIssues = [], currentFiles, contextKey) {
238
260
  const passed = stage => state.handoffs.findLast(item => item.stage === stage && item.status === 'passed');
239
261
  const scout = state.workContractVersion === 1 ? passed('scout')?.assessment : null;
240
262
  const verification = passed('verify');
@@ -281,7 +303,7 @@ export function renderReview(state, currentSourceHash, artifactIssues = []) {
281
303
  else if (['bug-fix', 'feature', 'refactor'].includes(state.playbook) && state.base === null) lines.push('Test proof: unavailable (this older run has no Git base or run-start source capture).');
282
304
  const assessment = state.workContractVersion === 1 ? verification?.assessment : null;
283
305
  if (assessment) {
284
- const coverage = reviewCoverage(state, assessment.semanticReview, currentSourceHash);
306
+ const coverage = reviewCoverage(state, assessment.semanticReview, { hash: currentSourceHash, files: currentFiles, contextKey });
285
307
  if (coverage.entries.length && artifactIssues.length) coverage.status = 'unverified (receipt/evidence unavailable)';
286
308
  const reviewers = coverage.entries.length ? [...new Set(coverage.entries.filter(Boolean).map(r => r.reviewer))].join(' + ') : assessment.semanticReview.reviewer;
287
309
  lines.push(`Semantic review: ${coverage.status === 'self-assessment' ? (semanticCurrent ? 'current' : 'stale') : coverage.status}; reviewer: ${safe(reviewers)}; provenance: agent-reported. Final assessment: ${semanticCurrent ? 'current' : 'stale'}.`);
@@ -307,7 +329,7 @@ export function renderReview(state, currentSourceHash, artifactIssues = []) {
307
329
  const entry = state.workContractVersion === 1 ? delivery?.assessment?.[name] : null;
308
330
  lines.push(entry ? `- ${name} (${safe(entry.status)}): ${safe(entry.reason)}${entry.artifacts.length ? ` — ${entry.artifacts.map(safe).join(', ')}` : ''}` : `- ${name}: not yet recorded.`);
309
331
  }
310
- if (delivery) lines.push(`- Context docs touched: ${delivery.contextDocs?.length ? delivery.contextDocs.map(safe).join(', ') : 'none'}. Propose the component doc entry with cyc context review --run ${safe(state.id)}.`);
332
+ if (delivery) lines.push(`- Context docs touched: ${delivery.contextDocs?.length ? delivery.contextDocs.map(safe).join(', ') : 'none'}. ${retentionOf(state) ? 'Canonical retention was checked under this run’s actual contract.' : `Historical catch-up requires a new scoped update: cyc context review --run ${safe(state.id)} --write --update-run UPDATE_ID.`}`);
311
333
  lines.push('', '## Recovery, remaining risks, and decisions', '');
312
334
  for (const conflict of state.proofRecovery?.conflicts ?? []) lines.push(`- Proof conflict ${safe(conflict.path)}: ${safe(conflict.reason)}${conflict.savedUnexpected ? ` Unexpected bytes saved at ${safe(conflict.savedUnexpected)}.` : ''}${conflict.preservationError ? ` ${safe(conflict.preservationError)}` : ''}`);
313
335
  if (state.proofRecovery?.preservationError) lines.push(`- Proof recovery record: ${safe(state.proofRecovery.preservationError)}`);