@aibyzero/cm-workflow 0.16.3 → 0.16.5

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -1,5 +1,5 @@
1
1
  // Pure review data functions. Only task-runner owns invocation/registration.
2
- import { digest,need,shape,id,text,json,freeze } from './effect-contract.mjs';
2
+ import { digest,need,shape,id,text,json,freeze,REVIEW_TEXT_LIMIT } from './effect-contract.mjs';
3
3
  export function reviewPaths(pkg) {
4
4
  return [...new Set([...pkg.changes.map(c=>c.path),...pkg.requirements.map(f=>f.path),
5
5
  ...(pkg.unchangedScope??[]).map(file=>file.path),
@@ -34,6 +34,52 @@ export function reviewResultForPaths(raw,pkg,paths) {
34
34
  need(r.verdict!=='approved'||blocking===0,'contradictory_verdict');
35
35
  need(r.verdict!=='changes_requested'||blocking>0,'contradictory_verdict');return r;
36
36
  }
37
+ // A reviewer result is journaled many times (see developCheckpointReserve), so its
38
+ // text is bounded before any record is written. Rule, applied only when the result
39
+ // JSON without examinedPaths exceeds REVIEW_TEXT_LIMIT bytes:
40
+ // 1. every finding message and evidence and the summary are cut to one shared,
41
+ // largest-fitting byte cap and end with TRUNCATED;
42
+ // 2. if even the smallest cap does not fit, findings are omitted from the end,
43
+ // P3 first, then blocking ones while at least one blocking finding remains,
44
+ // and the summary says how many were omitted.
45
+ // Ids, severities, paths and the verdict are never changed. Malformed results are
46
+ // returned as they are for the validator to refuse. Null means nothing fits.
47
+ const TRUNCATED=' …[cm-ai: truncated to the review text limit]';
48
+ const MIN_CAP=Buffer.byteLength(TRUNCATED)+16;
49
+ const reviewTextBytes=r=>Buffer.byteLength(JSON.stringify(r))-Buffer.byteLength(JSON.stringify(r.examinedPaths));
50
+ function utf8Prefix(value,max){
51
+ const bytes=Buffer.from(value);if(bytes.length<=max)return value;
52
+ let end=max;while(end>0&&(bytes[end]&0xc0)===0x80)end--;
53
+ return bytes.subarray(0,end).toString('utf8');
54
+ }
55
+ export function boundReviewText(value){
56
+ const shaped=value!==null&&typeof value==='object'&&!Array.isArray(value)&&typeof value.summary==='string'
57
+ &&Array.isArray(value.examinedPaths)&&Array.isArray(value.findings)
58
+ &&value.findings.every(f=>f!==null&&typeof f==='object'&&typeof f.message==='string'&&typeof f.evidence==='string');
59
+ if(!shaped||reviewTextBytes(value)<=REVIEW_TEXT_LIMIT)return value;
60
+ const cut=(text,cap)=>Buffer.byteLength(text)<=cap?text:utf8Prefix(text,cap-Buffer.byteLength(TRUNCATED))+TRUNCATED;
61
+ const candidate=(findings,cap,omitted)=>{
62
+ const note=omitted?` [cm-ai: ${omitted} findings omitted to fit the review text limit]`:'';
63
+ return {...value,findings:findings.map(f=>({...f,message:cut(f.message,cap),evidence:cut(f.evidence,cap)})),
64
+ summary:cut(value.summary,Math.max(MIN_CAP,cap-Buffer.byteLength(note)))+note};
65
+ };
66
+ const widest=Math.max(MIN_CAP,...[value.summary,...value.findings.flatMap(f=>[f.message,f.evidence])].map(text=>Buffer.byteLength(text)));
67
+ const fitted=(findings,omitted)=>{
68
+ if(reviewTextBytes(candidate(findings,MIN_CAP,omitted))>REVIEW_TEXT_LIMIT)return null;
69
+ let low=MIN_CAP,high=widest;
70
+ while(low<high){const middle=Math.ceil((low+high)/2);
71
+ if(reviewTextBytes(candidate(findings,middle,omitted))<=REVIEW_TEXT_LIMIT)low=middle;else high=middle-1;}
72
+ return candidate(findings,low,omitted);
73
+ };
74
+ let findings=[...value.findings];
75
+ for(;;){
76
+ const result=fitted(findings,value.findings.length-findings.length);if(result)return result;
77
+ let index=findings.findLastIndex(f=>f.severity==='P3');
78
+ if(index===-1&&findings.filter(f=>f.severity!=='P3').length>1)index=findings.length-1;
79
+ if(index===-1)return null;
80
+ findings=findings.filter((_,position)=>position!==index);
81
+ }
82
+ }
37
83
  export function reviewReceipt({request,call,result,reviewPackage,developerProvider,fallbackReasons}) {
38
84
  const checked=reviewResult(result,reviewPackage);
39
85
  need(call.started===true && call.terminal==='succeeded' && call.requestDigest===request.requestDigest
@@ -0,0 +1,97 @@
1
+ // Read-only discovery of other task runs' completed, reviewed deliveries in the
2
+ // same specs root. A delivery counts only after its own journal replays through
3
+ // the runner grammar to a committed fixture_completed state: its review package
4
+ // (and any accepted QA-fix packages) then describe reviewed before->after file
5
+ // transitions. This grants nothing, never repairs, and never opens a writer.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
+ import {readRunnerHistory} from './durable-runner-state.mjs';
10
+ import {deliveredAfter,deliveryStep} from './fix-code-association.mjs';
11
+ import {digest,need} from './effect-contract.mjs';
12
+
13
+ const RUN_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
14
+ const cache=new Map();
15
+
16
+ function readDelivery(specsRoot,identity){
17
+ try{
18
+ const snapshot=readExecutionSnapshot({specsRoot,identity});
19
+ const init=snapshot.records[0]?.payload;
20
+ if(init?.protocol!=='cm-task-runner'||init.type!=='init'||![2,3].includes(init.version))return null;
21
+ const history=readRunnerHistory(snapshot.records,init.config,init.version);
22
+ const state=history.state;
23
+ if(history.pending!==null||state.state!=='fixture_completed'||state.taskCommit?.outcome!=='fixture_committed'
24
+ ||!state.reviewPackage)return null;
25
+ // Each package carries its own review time: the run's approving review, or
26
+ // for an accepted QA fix the fix's final review registration it cites.
27
+ return Object.freeze({runId:identity.runId,root:init.config.root,taskId:init.config.identity.taskId,
28
+ packages:Object.freeze([{pkg:state.reviewPackage,reviewedAt:approvedReviewAt(state)},
29
+ ...history.acceptedFixes.map(item=>({pkg:item.evidence.reviewPackage,reviewedAt:fixReviewedAt(specsRoot,item.evidence)}))])});
30
+ }catch{return null;}
31
+ }
32
+ // A QA fix package's durable review time: the final review registration its
33
+ // completion evidence cites, read from the fix child's own store, for exactly
34
+ // that package. Anything else has no time and never orders.
35
+ export function fixReviewedAt(specsRoot,evidence){
36
+ try{
37
+ const {repositoryId,runId}=evidence.identity;
38
+ const row=readExecutionSnapshot({specsRoot,identity:{repositoryId,runId}}).records.find(record=>
39
+ /^fix-(?:revision-)?final(?:-recovery(?:-[1-9]\d*)?|-retry)?-registered$/.test(record.id)
40
+ &&digest(record.payload)===evidence.reviewRegistrationDigest
41
+ &&record.payload.request?.payload?.reviewPackage?.packageDigest===evidence.reviewPackage.packageDigest);
42
+ return Number.isSafeInteger(row?.payload.registeredAt)?row.payload.registeredAt:null;
43
+ }catch{return null;}
44
+ }
45
+
46
+ // Durable order: when the approving review of this exact package was registered.
47
+ // Journals without a registered V3 review have no order and never qualify.
48
+ export function approvedReviewAt(state){
49
+ const registration=state?.reviewInvocation?.registration;
50
+ return registration&&registration.grant?.packageDigest===state.reviewPackage?.packageDigest
51
+ &&Number.isSafeInteger(registration.registeredAt)?registration.registeredAt:null;
52
+ }
53
+
54
+ function cachedDelivery(specsRoot,repositoryId,runId,stat){
55
+ const slot=[specsRoot,repositoryId,runId].join('\0');
56
+ const version=[stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(':');
57
+ if(cache.get(slot)?.version!==version)cache.set(slot,{version,delivery:readDelivery(specsRoot,{repositoryId,runId})});
58
+ return cache.get(slot).delivery;
59
+ }
60
+
61
+ // Resolve recorded steps to the real, completed, later reviewed packages of the
62
+ // named runs. allowAbsent is only for journal replay: a missing store cannot be
63
+ // re-proved there (returns null), and every live use refuses it.
64
+ export function resolveDeliverySteps({specsRoot,root,identity,after,steps,allowAbsent=false}){
65
+ const resolved=[];
66
+ for(const step of steps){
67
+ need(RUN_ID.test(step.runId)&&step.runId!==identity.runId,'fix_association_unverified');
68
+ let stat;
69
+ try{stat=fs.lstatSync(path.join(specsRoot,'.reviews','.execution',step.runId,'state.json'));}
70
+ catch(error){if(error.code==='ENOENT'){need(allowAbsent,'fix_association_unverified');return null;}throw error;}
71
+ const delivery=cachedDelivery(specsRoot,identity.repositoryId,step.runId,stat);
72
+ need(delivery&&delivery.root===root&&delivery.taskId!==identity.taskId,'fix_association_unverified');
73
+ const found=delivery.packages.find(item=>item.pkg.packageDigest===step.packageDigest);
74
+ need(found&&deliveredAfter(found,after)&&digest(deliveryStep(step.runId,found.pkg,step.beforeFix))===digest(step),'fix_association_unverified');
75
+ resolved.push({...step,pkg:found.pkg});
76
+ }
77
+ return resolved;
78
+ }
79
+
80
+ // Deliveries for the same code root and repository, excluding the caller's own
81
+ // run and any other run of the same task: a superseding rerun of a task is not
82
+ // a later change that its superseded run may adopt.
83
+ export function completedReviewedDeliveries({specsRoot,root,identity}){
84
+ const execution=path.join(specsRoot,'.reviews','.execution');
85
+ let entries;
86
+ try{entries=fs.readdirSync(execution,{withFileTypes:true});}catch{return [];}
87
+ const deliveries=[];
88
+ for(const entry of entries.sort((left,right)=>left.name<right.name?-1:left.name>right.name?1:0)){
89
+ if(!entry.isDirectory()||!RUN_ID.test(entry.name)||entry.name===identity.runId)continue;
90
+ let stat;
91
+ try{stat=fs.lstatSync(path.join(execution,entry.name,'state.json'));}catch{continue;}
92
+ // Replay once per journal version; a changed state.json is read again.
93
+ const delivery=cachedDelivery(specsRoot,identity.repositoryId,entry.name,stat);
94
+ if(delivery&&delivery.root===root&&delivery.taskId!==identity.taskId)deliveries.push(delivery);
95
+ }
96
+ return deliveries;
97
+ }
@@ -10,16 +10,47 @@ import {readRunnerHistory} from './durable-runner-state.mjs';
10
10
  import {supersedeWorkflowFile} from './review-evidence-file.mjs';
11
11
  import {need,digest} from './effect-contract.mjs';
12
12
  import {readEvidenceSupersession,supersedableEvidenceName} from './reviewed-evidence-supersession-record.mjs';
13
+ import {boundReviewText} from './review-runner.mjs';
13
14
  import {scanRows} from './cm-ai-qa-log.mjs';
14
- import {parseCmAiTaskLine} from './cm-ai-admission.mjs';
15
+ import {taskDeclarations,approvedTaskGrammar} from '../spec-task-line.mjs';
16
+ import {compareReviewInventoryToBaseline,readReviewBaseline} from './review-package.mjs';
15
17
 
16
18
  const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
17
19
  const unavailable=reason=>{const error=new Error('supersede_unavailable');error.code='supersede_unavailable';error.reason=reason;throw error;};
18
20
  const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
21
+ const codeDrift=reason=>{const error=new Error('supersede_code_drift');error.code='supersede_code_drift';error.reason=reason;throw error;};
22
+ const driftInstruction='这些文件与直接前驱运行开工前的基线不一致。手动还原这些文件后重建运行;或确认保留这些改动时加 --accept-superseded-code-drift 重建(这些文件会被当成已有代码,不进新运行的审查改动)。';
23
+
24
+ function verifyOldCodeBaseline(codeProject,rawBaseline){
25
+ // Legacy journals without a complete V2 inventory cannot prove code drift.
26
+ if(rawBaseline?.version!==2)return [];
27
+ const baseline=readReviewBaseline(rawBaseline);
28
+ let current;
29
+ try{
30
+ if(fs.realpathSync(codeProject)!==codeProject||!fs.lstatSync(codeProject).isDirectory())
31
+ codeDrift(`无法安全核对代码根目录。${driftInstruction}`);
32
+ current=compareReviewInventoryToBaseline(codeProject,baseline);
33
+ }catch(error){
34
+ if(error.code==='supersede_code_drift')throw error;
35
+ codeDrift(`无法安全核对代码树(${error.code??'read_failed'})。${driftInstruction}`);
36
+ }
37
+ // The shared comparison filters both sides with one ignore-decision union.
38
+ return current;
39
+ }
40
+
41
+ // The direct predecessor's last review receipt, or the context it carried itself
42
+ // when it never reached a review. Bounded like any journaled review text.
43
+ function carriedReviewFrom(runId,state,supersession){
44
+ const result=state.receipts.at(-1)?.result;
45
+ if(!result)return supersession?.carriedReview??null;
46
+ const bounded=boundReviewText({verdict:result.verdict,packageDigest:result.packageDigest,
47
+ examinedPaths:[],findings:result.findings,summary:result.summary});
48
+ return bounded?{previousRunId:runId,verdict:bounded.verdict,summary:bounded.summary,findings:bounded.findings}:null;
49
+ }
19
50
 
20
51
  function taskChecked(tasksPath,taskId){
21
- const body=fs.readFileSync(tasksPath,'utf8');
22
- const rows=body.split(/\r?\n/).map(parseCmAiTaskLine).filter(task=>task?.id===taskId);
52
+ const rows=taskDeclarations(fs.readFileSync(tasksPath,'utf8'),
53
+ {grammar:approvedTaskGrammar(path.dirname(path.dirname(tasksPath)))}).filter(task=>task.id===taskId);
23
54
  if(rows.length!==1)unavailable('tasks.md 中任务身份不唯一或不存在');
24
55
  return rows[0].completed;
25
56
  }
@@ -65,14 +96,14 @@ export function oldWriterOpen(execution,runId,{lsofPath}={}){
65
96
  unavailable(`缺少核对旧运行 ${runId} writer 占用的本地工具`);
66
97
  }
67
98
 
68
- export function prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason,tasksPath}){
99
+ export function prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason,tasksPath,acceptSupersededCodeDrift=false}){
69
100
  if(typeof reason!=='string'||!reason.trim()||Buffer.byteLength(reason,'utf8')>500||/[\r\n\0]/.test(reason))
70
101
  unavailable('必须提供单行且不超过 500 字节的 --supersede-reason');
71
102
  if(taskChecked(tasksPath,identity.taskId))unavailable('tasks.md 已将任务标为完成;若 QA BLOCKED 后确需重跑,先将该任务改回 - [ ],再以 --supersede-reviewed-evidence 和 --supersede-reason 创建新运行');
72
103
  const reviewsDir=path.join(specsDir,'.reviews');
73
- if(!fs.existsSync(reviewsDir))unavailable('没有可替换的旧任务证据');
104
+ if(!fs.existsSync(reviewsDir))unavailable('没有同 feature、task 的旧运行');
74
105
  const execution=path.join(reviewsDir,'.execution');
75
- const previousRunIds=[];
106
+ const previousRunIds=[],priorRuns=[],alreadySuperseded=new Set();
76
107
  if(fs.existsSync(execution))for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
77
108
  if(!entry.isDirectory()||entry.name===identity.runId)continue;
78
109
  const stateFile=path.join(execution,entry.name,'state.json');
@@ -89,24 +120,87 @@ export function prepareReviewedEvidenceSupersession({specsDir,codeProject,featur
89
120
  unavailable(`旧运行 ${entry.name} 的任务身份或路径不匹配`);
90
121
  if(first.version!==3)unavailable(`旧运行 ${entry.name} 的 journal 版本无法验证`);
91
122
  const history=readRunnerHistory(snapshot.records,first.config,3);
92
- if(history.pending||!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state))
123
+ if(history.pending){
124
+ const exit=history.pendingAbandonable?'abandon_effect':
125
+ history.pending.kind==='review'&&history.state.reviewInvocation?.registration
126
+ &&history.state.reviewInvocation.result===null?'abandon_review':'原运行恢复入口';
127
+ unavailable(`旧运行 ${entry.name} 的 ${history.pending.kind} effect 已中断且未结;先确认旧 host 和子进程已退出,再在原 run 上使用 ${exit},随后重新发起 supersede`);
128
+ }
129
+ if(!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state))
93
130
  unavailable(`旧运行 ${entry.name} 仍可继续或有未结操作`);
94
131
  if(oldWriterOpen(execution,entry.name))unavailable(`旧运行 ${entry.name} 的 writer 仍被进程持有`);
95
132
  const qa=qaTerminal(specsDir,entry.name,identity.taskId);
96
133
  if(history.state.state==='fixture_completed'&&!['BLOCKED','never_finished'].includes(qa))
97
- unavailable(`旧运行 ${entry.name} 已完成或 QA 已通过`);
134
+ unavailable(qa==='completed'?`旧运行 ${entry.name} 已完成(run_done)`
135
+ :['PASS','PASSED'].includes(qa)?`旧运行 ${entry.name} 的 QA 已通过`
136
+ :['FAIL','FAILED'].includes(qa)?`旧运行 ${entry.name} 的最新 QA 结果为 FAIL(未通过),失败要修复而不是重开发:在原运行上用 QA 修复(fix_advance / fix_run)处理;修复子运行的审查卡在结果未知时,确认旧进程已退出后用 abandon_review 放弃一次再重审`
137
+ :`旧运行 ${entry.name} 的最新 QA 结果为 ${qa},不是 BLOCKED,不能用重开发替换;请在原运行上按该结果的恢复入口处理`);
138
+ priorRuns.push({runId:entry.name,baseline:first.baseline,
139
+ carriedReview:carriedReviewFrom(entry.name,history.state,history.supersession)});
140
+ for(const runId of history.supersession?.previousRunIds??[])alreadySuperseded.add(runId);
98
141
  previousRunIds.push(entry.name);
99
142
  }
100
143
  if(!previousRunIds.length)unavailable('没有同 feature、task 的旧运行');
144
+ const drift=priorRuns.filter(run=>!alreadySuperseded.has(run.runId))
145
+ .flatMap(run=>verifyOldCodeBaseline(codeProject,run.baseline)
146
+ .map(file=>({predecessorRunId:run.runId,...file})))
147
+ .sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:
148
+ a.predecessorRunId<b.predecessorRunId?-1:a.predecessorRunId>b.predecessorRunId?1:0);
149
+ if(drift.length&&!acceptSupersededCodeDrift){
150
+ const paths=[...new Set(drift.map(file=>file.path))],listed=paths.slice(0,20).join('、');
151
+ codeDrift(`${listed}${paths.length>20?` 等 ${paths.length-20} 个`:''}:${driftInstruction}`);
152
+ }
153
+ // A run that stopped before any handoff or review has nothing to archive; the
154
+ // record still ends the prior runs and carries any accepted code drift.
155
+ const previous=new Set(previousRunIds);
156
+ const carriedReview=priorRuns.filter(run=>!alreadySuperseded.has(run.runId)&&run.carriedReview
157
+ &&previous.has(run.carriedReview.previousRunId))
158
+ .sort((a,b)=>a.runId<b.runId?-1:a.runId>b.runId?1:0).at(-1)?.carriedReview??null;
101
159
  const names=evidenceNames(reviewsDir,feature,identity.taskId);
102
- if(!names.length)unavailable('没有可归档的旧任务证据');
103
160
  const files=names.map(name=>{
104
161
  const p=path.join(reviewsDir,name),stat=fs.lstatSync(p);
105
162
  if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)unavailable(`证据文件不可安全归档:${name}`);
106
163
  return {name,sha256:hash(fs.readFileSync(p))};
107
164
  });
108
165
  return readEvidenceSupersession({version:1,feature,taskId:identity.taskId,newRunId:identity.runId,
109
- previousRunIds:previousRunIds.sort(),reason,files,authorizedAt:new Date().toISOString()});
166
+ previousRunIds:previousRunIds.sort(),reason,files,authorizedAt:new Date().toISOString(),
167
+ ...(drift.length?{acceptedCodeDrift:drift}:{}),...(carriedReview?{carriedReview}:{})});
168
+ }
169
+
170
+ // A plain create (no supersede) must not silently adopt a previous run's
171
+ // unreviewed edits as its baseline. Same comparison as supersede, over the runs
172
+ // of this task that no later run has superseded; the only way to keep the
173
+ // edits is the explicit supersede record with --accept-superseded-code-drift.
174
+ export function assertNoUnrecordedPriorCode({specsDir,codeProject,feature,identity,tasksPath}){
175
+ const execution=path.join(specsDir,'.reviews','.execution');
176
+ if(!fs.existsSync(execution))return;
177
+ const priorRuns=[],superseded=new Set();
178
+ for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
179
+ if(!entry.isDirectory()||entry.name===identity.runId)continue;
180
+ if(!fs.existsSync(path.join(execution,entry.name,'state.json')))continue;
181
+ let snapshot;
182
+ try{snapshot=readExecutionSnapshot({specsRoot:specsDir,
183
+ identity:{repositoryId:identity.repositoryId,runId:entry.name}});}
184
+ catch(error){if(error.code==='identity_mismatch')continue;throw error;}
185
+ const first=snapshot.records[0]?.payload;
186
+ // Other tasks, roots and pre-V3 journals are out of this comparison (the
187
+ // latter cannot prove drift, as in supersede).
188
+ if(first?.version!==3||first.config?.identity?.taskId!==identity.taskId
189
+ ||first.config?.taskLearning?.feature!==feature||first.config.root!==codeProject
190
+ ||first.config.completion?.owner?.tasksPath!==tasksPath)continue;
191
+ const record=snapshot.records[1]?.payload;
192
+ if(record?.type==='evidence-superseded')for(const runId of readEvidenceSupersession(record.record).previousRunIds)
193
+ superseded.add(runId);
194
+ priorRuns.push({runId:entry.name,baseline:first.baseline});
195
+ }
196
+ const drift=priorRuns.filter(run=>!superseded.has(run.runId))
197
+ .flatMap(run=>verifyOldCodeBaseline(codeProject,run.baseline).map(file=>({runId:run.runId,path:file.path})));
198
+ if(!drift.length)return;
199
+ const paths=[...new Set(drift.map(file=>file.path))].sort(),runs=[...new Set(drift.map(file=>file.runId))].sort();
200
+ codeDrift(`旧运行 ${runs.join('、')} 开工后这些文件被改动,且没有替代记录:${paths.slice(0,20).join('、')}`
201
+ +`${paths.length>20?` 等 ${paths.length-20} 个`:''}。新运行不会把它们当成已有代码。`
202
+ +'可选:回到旧运行继续;手动还原这些文件后再新建;或旧运行结束后用 --supersede-reviewed-evidence --supersede-reason 原因 '
203
+ +'--accept-superseded-code-drift 新建(改动记入替代记录,作为已有代码,不进新运行的审查改动)。');
110
204
  }
111
205
 
112
206
  export function archiveReviewedEvidence(reviewsDir,raw){
@@ -1,9 +1,32 @@
1
1
  // Strict V3 payload grammar, shared by live authorization and journal replay.
2
- import {need,shape,id,hex,json} from './effect-contract.mjs';
2
+ import {need,shape,id,hex,text,json,REVIEW_TEXT_LIMIT} from './effect-contract.mjs';
3
+
4
+ // Read-only context carried from the most recent superseded run's last review
5
+ // receipt. It is never a verdict: runners only show it to the attempt-1
6
+ // developer and reviewer, and stage, attempt and budget rules never read it.
7
+ export function readCarriedReview(value,previousRunIds=null){
8
+ const fail=()=>need(false,'supersede_record_invalid');
9
+ try{
10
+ shape(value,['previousRunId','verdict','summary','findings']);id(value.previousRunId);
11
+ need(['approved','changes_requested','blocked'].includes(value.verdict));text(value.summary);
12
+ need(Array.isArray(value.findings)&&value.findings.length<=100);
13
+ const ids=new Set();
14
+ for(const f of value.findings){
15
+ shape(f,['id','severity','path','message','evidence']);id(f.id);need(!ids.has(f.id));ids.add(f.id);
16
+ need(['P0','P1','P2','P3'].includes(f.severity));text(f.path);text(f.message);text(f.evidence);
17
+ }
18
+ const {previousRunId,...body}=value;
19
+ need(Buffer.byteLength(JSON.stringify(body),'utf8')<=REVIEW_TEXT_LIMIT);
20
+ }catch{fail();}
21
+ if(previousRunIds)need(previousRunIds.has(value.previousRunId),'supersede_record_invalid');
22
+ return value;
23
+ }
3
24
 
4
25
  export function readEvidenceSupersession(raw,expected=null){
5
26
  const record=json(raw,1024*1024);
6
- shape(record,['version','feature','taskId','newRunId','previousRunIds','reason','files','authorizedAt']);
27
+ shape(record,['version','feature','taskId','newRunId','previousRunIds','reason','files','authorizedAt',
28
+ ...(Object.hasOwn(record,'acceptedCodeDrift')?['acceptedCodeDrift']:[]),
29
+ ...(Object.hasOwn(record,'carriedReview')?['carriedReview']:[])]);
7
30
  need(record.version===1,'supersede_record_invalid');
8
31
  need(typeof record.authorizedAt==='string'
9
32
  &&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(record.authorizedAt)
@@ -11,9 +34,25 @@ export function readEvidenceSupersession(raw,expected=null){
11
34
  for(const key of ['feature','taskId','newRunId'])id(record[key]);
12
35
  need(Array.isArray(record.previousRunIds)&&record.previousRunIds.length>0&&record.previousRunIds.length<=128,'supersede_record_invalid');
13
36
  const runs=new Set();for(const runId of record.previousRunIds){id(runId);need(!runs.has(runId)&&runId!==record.newRunId,'supersede_record_invalid');runs.add(runId);}
37
+ if(Object.hasOwn(record,'acceptedCodeDrift')){
38
+ need(Array.isArray(record.acceptedCodeDrift)&&record.acceptedCodeDrift.length>0
39
+ &&record.acceptedCodeDrift.length<=8192,'supersede_record_invalid');
40
+ const seen=new Set();
41
+ for(const file of record.acceptedCodeDrift){
42
+ shape(file,['predecessorRunId','path','sha256']);
43
+ need(runs.has(file.predecessorRunId)&&typeof file.path==='string'&&file.path.length>0
44
+ &&file.path.normalize('NFC')===file.path&&!/[\\:\x00-\x1f\x7f-\x9f]/.test(file.path)
45
+ &&file.path.split('/').every(part=>part&&part!=='.'&&part!=='..'),'supersede_record_invalid');
46
+ if(file.sha256!==null)hex(file.sha256);
47
+ const key=`${file.predecessorRunId}\0${file.path}`;
48
+ need(!seen.has(key),'supersede_record_invalid');seen.add(key);
49
+ }
50
+ }
51
+ if(Object.hasOwn(record,'carriedReview'))readCarriedReview(record.carriedReview,runs);
14
52
  need(typeof record.reason==='string'&&record.reason.trim()&&Buffer.byteLength(record.reason,'utf8')<=500
15
53
  &&!/[\r\n\0]/.test(record.reason),'supersede_reason_required');
16
- need(Array.isArray(record.files)&&record.files.length>0&&record.files.length<=256,'supersede_record_invalid');
54
+ // Zero files: the prior runs stopped before any handoff or review existed.
55
+ need(Array.isArray(record.files)&&record.files.length<=256,'supersede_record_invalid');
17
56
  const names=new Set();for(const file of record.files){
18
57
  shape(file,['name','sha256']);
19
58
  need(typeof file.name==='string'&&/^[A-Za-z0-9._-]+\.(md|json)$/.test(file.name)
@@ -2,10 +2,12 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {createHash} from 'node:crypto';
5
- import {buildManifest,verifyManifest,normalizeRuntimeMarks} from '../../../scripts/cm-spec-manifest.mjs';
6
- import {parseFeatureTaskText,declaredAcceptanceIds} from './cm-ai-admission.mjs';
5
+ import {verifyApprovedManifest,normalizeRuntimeMarks,normalizeRuntimeMarkBytes} from '../../../scripts/cm-spec-manifest.mjs';
6
+ import {parseFeatureTaskText,declaredAcceptanceIds,DEPENDENCY} from './cm-ai-admission.mjs';
7
+ import {taskLines,TASK_GRAMMAR,LEGACY_TASK_GRAMMAR} from '../spec-task-line.mjs';
7
8
  import {readReviewSourceFiles,readReviewSourceExcerpt} from './review-package.mjs';
8
- import {json,need,shape,hex,freeze,digest} from './effect-contract.mjs';
9
+ import {json,need,shape,hex,id,freeze,digest} from './effect-contract.mjs';
10
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
11
 
10
12
  const DESIGN_LIMIT=64*1024;
11
13
  const filenames=['requirements.md','design.md','tasks.md','test-cases.json'];
@@ -15,7 +17,8 @@ const featureName=value=>need(typeof value==='string'&&/^\d+\.[^/\\\x00-\x1f]+$/
15
17
  export function readSpecificationMaterial(raw,taskId){
16
18
  const v=json(raw,2*1024*1024);
17
19
  shape(v,['feature','task','acceptanceCriteria','designExcerpt','testCases','sources',
18
- ...(Object.hasOwn(v,'truncated')?['truncated']:[])]);
20
+ ...['truncated','taskScopeDigest'].filter(key=>Object.hasOwn(v,key))]);
21
+ if(Object.hasOwn(v,'taskScopeDigest'))hex(v.taskScopeDigest);
19
22
  featureName(v.feature);
20
23
  shape(v.task,['id','description',...(Object.hasOwn(v.task,'verification')?['verification']:[])]);
21
24
  need(v.task.id===taskId&&/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(taskId));
@@ -38,6 +41,41 @@ export function readSpecificationMaterial(raw,taskId){
38
41
  return freeze(v);
39
42
  }
40
43
 
44
+ // Everything in tasks.md and test-cases.json that can belong to this task:
45
+ // every line that names it wherever it sits (another task's sub-item, a
46
+ // dependency line, a note), its whole list item (continuation lines and
47
+ // sub-bullets included), and shared text naming no task. Left out are only
48
+ // lines naming other tasks alone: other tasks' items and their sub-lines,
49
+ // their dependency lines, and their test cases that do not name this task.
50
+ // Recorded for new runs so an explicit rebind can prove the re-approved change
51
+ // did not touch this task.
52
+ const TASK_ID_TOKEN=/(?<![A-Za-z0-9])T-[A-Za-z0-9][A-Za-z0-9._-]*/g;
53
+ const indentOf=line=>/^[ \t]*/.exec(line)[0].length;
54
+ const MENTIONS_TASK=/(?<![A-Za-z0-9])T-[A-Za-z0-9]/;
55
+ const namesTask=(text,taskId)=>(text.match(TASK_ID_TOKEN)??[]).some(id=>id.replace(/[._-]+$/,'')===taskId);
56
+ export function taskScopeText(tasks,taskId,grammar=TASK_GRAMMAR){
57
+ const kept=[];let owner=null,ownerIndent=0;
58
+ for(const {body,fenced,declaration} of taskLines(tasks,{grammar})){
59
+ if(!body.trim())continue;
60
+ if(declaration){owner=declaration.id;ownerIndent=indentOf(body);}
61
+ // Only lines indented under an item belong to it; a fence or heading at
62
+ // its level ends it, leaving the rest to the shared/named rules below.
63
+ else if(owner!==null&&!(indentOf(body)>ownerIndent&&!/^\s*#/.test(body)))owner=null;
64
+ const dependency=fenced||declaration?null:body.match(DEPENDENCY);
65
+ const belongs=declaration?declaration.id:owner??dependency?.[1]??null;
66
+ if(namesTask(body,taskId)||belongs===taskId||belongs===null&&!MENTIONS_TASK.test(body))kept.push(body);
67
+ }
68
+ return kept.join('\n');
69
+ }
70
+ function taskScopeDigest(texts,taskId,grammar){
71
+ let cases=null;
72
+ if(texts['test-cases.json']!==undefined){
73
+ const {cases:all,...contract}=JSON.parse(texts['test-cases.json']);
74
+ cases={...contract,cases:all.filter(item=>item.taskIds.includes(taskId)||namesTask(JSON.stringify(item),taskId))};
75
+ }
76
+ return digest({tasks:taskScopeText(texts['tasks.md'],taskId,grammar),testCases:cases});
77
+ }
78
+
41
79
  function verificationFor(source,taskId){
42
80
  let level=null;const lines=[];
43
81
  for(const line of source.split(/\r?\n/)){
@@ -60,7 +98,10 @@ export function captureSpecificationMaterial({specsRoot,feature,taskId}){
60
98
  const statusRecord=readReviewSourceFiles(specsRoot,['.cm-specs-status'])[0];
61
99
  const status=JSON.parse(Buffer.from(statusRecord.contentBase64,'base64').toString('utf8'));
62
100
  need(status.status==='approved'&&Array.isArray(status.features)&&status.features.includes(feature));
63
- const manifest=buildManifest(specsRoot);verifyManifest(manifest,statusPath);
101
+ // Sources are the approved rows themselves. A legacy approval therefore keeps
102
+ // its recorded digests, and material captured before the shared task grammar
103
+ // compares equal to material captured after it.
104
+ const manifest=verifyApprovedManifest(specsRoot,statusPath);
64
105
  need(JSON.stringify([...status.features].sort())===JSON.stringify([...new Set(manifest.map(row=>row.path.split('/')[0]))].sort()));
65
106
  const sources=manifest.filter(row=>row.path.startsWith(feature+'/'));
66
107
  const designPath=feature+'/design.md';
@@ -69,14 +110,17 @@ export function captureSpecificationMaterial({specsRoot,feature,taskId}){
69
110
  need(design.sha256===sources.find(row=>row.path===designPath)?.sha256);
70
111
  for(const record of records){
71
112
  const name=path.basename(record.path),bytes=Buffer.from(record.contentBase64,'base64');
72
- // Hash the very bytes that supply the material, using the existing runtime-mark contract.
73
- const normalized=Buffer.from(normalizeRuntimeMarks(bytes.toString('latin1'),name),'latin1');
74
- need(hash(normalized)===sources.find(row=>row.path===record.path)?.sha256);
113
+ // Hash the very bytes that supply the material, using the runtime-mark contract
114
+ // that approved them (current grammar, or the legacy rule for old approvals).
115
+ const approved=sources.find(row=>row.path===record.path)?.sha256;
116
+ need([false,true].some(legacy=>hash(normalizeRuntimeMarkBytes(bytes,name,{legacy}))===approved));
75
117
  texts[name]=normalizeRuntimeMarks(bytes.toString('utf8'),name);
76
118
  }
77
119
  need(readReviewSourceFiles(specsRoot,['.cm-specs-status'])[0].sha256===statusRecord.sha256);
78
- verifyManifest(buildManifest(specsRoot),statusPath);
79
- const parsed=parseFeatureTaskText(texts['tasks.md'],{allowDependencyPunctuation:true});
120
+ verifyApprovedManifest(specsRoot,statusPath);
121
+ // The approval binds the grammar its bytes were approved with (spec-task-line.mjs).
122
+ const grammar=status.taskGrammar===TASK_GRAMMAR?TASK_GRAMMAR:LEGACY_TASK_GRAMMAR;
123
+ const parsed=parseFeatureTaskText(texts['tasks.md'],{allowDependencyPunctuation:true,grammar});
80
124
  need(!parsed.error);
81
125
  const selected=parsed.tasks.find(task=>task.id===taskId&&!task.dropped);need(selected);
82
126
  const verification=verificationFor(texts['tasks.md'],taskId);
@@ -86,13 +130,111 @@ export function captureSpecificationMaterial({specsRoot,feature,taskId}){
86
130
  const cases=texts['test-cases.json']===undefined?[]:JSON.parse(texts['test-cases.json']).cases;
87
131
  need(Array.isArray(cases)&&cases.every(item=>item&&Array.isArray(item.taskIds)));
88
132
  return readSpecificationMaterial({feature,task,acceptanceCriteria,designExcerpt:design.excerpt,
89
- ...(design.truncated?{truncated:true}:{}),testCases:cases.filter(item=>item.taskIds.includes(taskId)),sources},taskId);
133
+ ...(design.truncated?{truncated:true}:{}),testCases:cases.filter(item=>item.taskIds.includes(taskId)),sources,
134
+ taskScopeDigest:taskScopeDigest(texts,taskId,grammar)},taskId);
90
135
  }catch{throw Object.assign(new Error('spec_drift'),{code:'spec_drift'});}
91
136
  }
92
137
 
138
+ // Material captured by older versions has no taskScopeDigest; compare a fresh
139
+ // capture in the bound representation so their runs keep verifying.
140
+ const asBound=(bound,current)=>{
141
+ if(Object.hasOwn(bound,'taskScopeDigest'))return current;
142
+ const {taskScopeDigest:unused,...legacy}=current;return legacy;
143
+ };
144
+ // Rebind eligibility, deliberately conservative: requirements.md and design.md
145
+ // must be unchanged as whole files (acceptance items may span lines, and prose
146
+ // can state requirements); in tasks.md and test-cases.json only other tasks'
147
+ // items, dependency lines and cases may differ (taskScopeDigest). A run bound
148
+ // before taskScopeDigest existed cannot prove that and is never rebindable.
149
+ const CONTENT_FIELDS=['feature','task','acceptanceCriteria','designExcerpt','truncated','testCases','taskScopeDigest'];
150
+ const FIELD_NAMES={feature:'feature',task:'本任务描述/验证要求',acceptanceCriteria:'验收标准',
151
+ designExcerpt:'设计摘录',truncated:'设计摘录',testCases:'本任务测试用例',
152
+ taskScopeDigest:'tasks.md/test-cases.json 中本任务的条目、续行、依赖、用例或共用说明'};
153
+ const WHOLE_FILES={'requirements.md':'requirements.md(整份核对,含验收标准续行与说明)','design.md':'design.md(整份核对)'};
154
+
155
+ // Explicit, journaled rebind (task-runner rebindSpecification). It can only ever
156
+ // replace `sources`: the accepted material is the bound material with the
157
+ // approved hashes of the re-approved files, never different content.
158
+ export function readSpecificationRebind(raw,expected=null){
159
+ const record=json(raw,64*1024);
160
+ shape(record,['version','taskId','boundDigest','sources','files','reason','reboundAt']);
161
+ need(record.version===1,'spec_rebind_invalid');id(record.taskId);hex(record.boundDigest);
162
+ need(Array.isArray(record.sources)&&[3,4].includes(record.sources.length),'spec_rebind_invalid');
163
+ for(const row of record.sources){shape(row,['path','sha256']);need(typeof row.path==='string','spec_rebind_invalid');hex(row.sha256);}
164
+ need(Array.isArray(record.files)&&record.files.length>0&&record.files.length<=filenames.length
165
+ &&new Set(record.files).size===record.files.length
166
+ &&record.files.every(file=>typeof file==='string'&&filenames.includes(file.split('/').at(-1))),'spec_rebind_invalid');
167
+ need(typeof record.reason==='string'&&record.reason.trim().length>0&&Buffer.byteLength(record.reason,'utf8')<=500
168
+ &&!/[\r\n\0]/.test(record.reason),'spec_rebind_reason_required');
169
+ need(typeof record.reboundAt==='string'&&Number.isFinite(Date.parse(record.reboundAt))
170
+ &&new Date(record.reboundAt).toISOString()===record.reboundAt,'spec_rebind_invalid');
171
+ if(expected)need(record.taskId===expected.taskId&&record.boundDigest===expected.boundDigest,'spec_rebind_invalid');
172
+ return freeze(record);
173
+ }
174
+
175
+ // The run's own journal is the only authority for a rebind; any read or
176
+ // validation problem means no rebind, so verification fails closed.
177
+ function acceptedRebindMaterial(baseline){
178
+ try{
179
+ const snapshot=readExecutionSnapshot({specsRoot:baseline.specificationRoot,
180
+ identity:{repositoryId:baseline.identity.repositoryId,runId:baseline.identity.runId}});
181
+ const row=snapshot.records.findLast(item=>item.payload?.version===3&&item.payload.type==='specification-rebound');
182
+ if(!row)return null;
183
+ const record=readSpecificationRebind(row.payload.record,{taskId:baseline.identity.taskId,
184
+ boundDigest:digest(baseline.specification)});
185
+ return readSpecificationMaterial({...baseline.specification,sources:record.sources},baseline.identity.taskId);
186
+ }catch{return null;}
187
+ }
188
+ const accepted=(baseline,captured)=>{
189
+ const current=asBound(baseline.specification,captured);
190
+ if(digest(current)===digest(baseline.specification))return true;
191
+ const rebound=acceptedRebindMaterial(baseline);
192
+ return rebound!==null&&digest(current)===digest(rebound);
193
+ };
194
+
93
195
  export function verifySpecificationMaterial(baseline){
94
196
  const current=captureSpecificationMaterial({specsRoot:baseline.specificationRoot,
95
197
  feature:baseline.specification.feature,taskId:baseline.identity.taskId});
96
- need(digest(current)===digest(baseline.specification),'spec_drift');
198
+ need(accepted(baseline,current),'spec_drift');
199
+ return baseline.specification;
200
+ }
201
+
202
+ // A freshly captured material equal to the bound (or explicitly rebound) one is
203
+ // represented by the bound material, so reviewed baselines and packages keep
204
+ // their digests. Anything else is spec_drift.
205
+ export function boundSpecificationMaterial(baseline,captured){
206
+ need(accepted(baseline,captured),'spec_drift');
97
207
  return baseline.specification;
98
208
  }
209
+
210
+ // Diagnostic for status and rebind: null when the bound material (or an
211
+ // explicit rebind) still verifies; otherwise what changed and whether an
212
+ // explicit rebind is allowed. Never grants anything itself.
213
+ export function inspectSpecificationDrift(baseline){
214
+ let current;
215
+ try{current=captureSpecificationMaterial({specsRoot:baseline.specificationRoot,
216
+ feature:baseline.specification.feature,taskId:baseline.identity.taskId});}
217
+ catch{return freeze({approved:false,files:[],fields:[],rebindable:false});}
218
+ if(accepted(baseline,current))return null;
219
+ const bound=baseline.specification,before=new Map(bound.sources.map(row=>[row.path,row.sha256]));
220
+ const after=new Map(current.sources.map(row=>[row.path,row.sha256]));
221
+ const files=[...new Set([...before.keys(),...after.keys()])].filter(file=>before.get(file)!==after.get(file)).sort();
222
+ const fields=[...new Set([
223
+ ...files.map(file=>WHOLE_FILES[file.split('/').at(-1)]).filter(Boolean),
224
+ ...(before.size!==after.size?['test-cases.json 的有无']:[]),
225
+ ...(Object.hasOwn(bound,'taskScopeDigest')?[]:['本运行由旧版本创建,未记录本任务段落摘要,无法证明其未变']),
226
+ ...CONTENT_FIELDS.filter(field=>Object.hasOwn(bound,'taskScopeDigest')||field!=='taskScopeDigest')
227
+ .filter(field=>digest(current[field]??null)!==digest(bound[field]??null)).map(field=>FIELD_NAMES[field])])];
228
+ return freeze({approved:true,files,fields,rebindable:fields.length===0,sources:current.sources});
229
+ }
230
+
231
+ export function describeSpecificationDrift(drift){
232
+ if(!drift.approved)return '规格当前未处于已批准且与批准清单一致的状态(cm-prd 变更尚未重新批准,或规格文件被直接修改);'
233
+ +'先完成 cm-prd --change 并重新批准,之后按 status 提示继续。';
234
+ const files=drift.files.join('、');
235
+ if(drift.rebindable)return `规格已重新批准,变更文件:${files};只有其他任务的条目、依赖或用例变了,requirements.md、design.md 与本任务相关内容均未变。`
236
+ +'用 --mode resume --rebind-spec-material --spec-rebind-reason 原因 重开本运行即可显式换绑,已有开发与审查结论保留。';
237
+ return `规格已变更:${files};以下与本任务相关的内容已变或无法证明未变:${drift.fields.join('、')},不能换绑。`
238
+ +'出口:还原这些规格改动并重新批准后本运行可继续;或 cancel 本运行,还原本运行改动的代码后用 '
239
+ +'--supersede-reviewed-evidence --supersede-reason 原因 新建运行重做。';
240
+ }
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { createHash,randomUUID } from 'node:crypto';
5
5
  import { types } from 'node:util';
6
6
  import {createRequire} from 'node:module';
7
- import { verifyReviewPackage,reviewSpecsPath } from './review-package.mjs';
7
+ import { verifyCompletionReviewPackage,reviewSpecsPath } from './review-package.mjs';
8
8
  import { checkCompletion } from './gate-bridge.mjs';
9
9
  import { need,shape,json,digest,validIdentity } from './effect-contract.mjs';
10
10
  import {planBytes,readCommitIntent,readCommitResult} from './task-commit-codec.mjs';
@@ -64,7 +64,7 @@ function readFile(p) {
64
64
  function nativeRevision(p,f) {return digest({path:p,stat:statFields(f.stat),sha256:sha(f.bytes)});}
65
65
  function completionSelectors(selectors,identity,projectRoot){return {...selectors,task:identity.taskId,projectRoot};}
66
66
  function verifyProof(v) {
67
- verifyReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,reviewPackage:v.reviewPackage,expectedDigest:v.reviewPackage.packageDigest,
67
+ verifyCompletionReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,reviewPackage:v.reviewPackage,expectedDigest:v.reviewPackage.packageDigest,
68
68
  ...(Object.hasOwn(v.reviewPackage,'handoff')?{handoffPath:v.selectors.handoff}:{})});
69
69
  checkCompletion({receipt:v.receipt,registered:v.registered,execution:v.execution,reviewPackage:v.reviewPackage,identity:v.identity});
70
70
  }