@aibyzero/cm-workflow 0.16.8 → 0.17.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 (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,469 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {createHash} from 'node:crypto';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {captureBaseline,checkN4,checkN5,implementationSha256,prepareControlledCorrection,publishControlledCorrectionReview,
10
+ prepareHumanCorrection,publishHumanCorrectionReview,prepareMarkDone,verifyMarkDonePlan} from './cm-task-gate.mjs';
11
+
12
+ const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
13
+ const jsGate=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
14
+ const pyGate=fileURLToPath(new URL('./cm-task-gate.py',import.meta.url));
15
+ function fixture(t){
16
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-controlled-correction-')));
17
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
18
+ const reviewsDir=path.join(root,'specs','.reviews');fs.mkdirSync(reviewsDir,{recursive:true});
19
+ const tasks=path.join(root,'specs','tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
20
+ // Inventory baseline precedes every in-scope edit; both scope files are new after it.
21
+ captureBaseline({projectRoot:root,reviewsDir,feature:'login',task:'T-001'});
22
+ fs.mkdirSync(path.join(root,'src'));
23
+ const code=path.join(root,'src/example.ts');fs.writeFileSync(code,'original implementation');
24
+ fs.writeFileSync(path.join(root,'src/unchanged.ts'),'retained original scope');
25
+ const files=['src/example.ts','src/unchanged.ts'];
26
+ const payload=attempt=>({schema_version:1,task_id:'T-001',attempt,status:'ready_for_review',changed_files:files,
27
+ implementation_sha256:implementationSha256(root,files),
28
+ verification:[{command:'fixture',status:'passed',evidence:'synthetic fixture passed'}],
29
+ evidence:['learning: no_relevant_lesson','learning: retrospective no_new_lesson'],blockers:[],scope_deviation:[]});
30
+ const review=(file,handoff,attempt,verdict,correctionDigest=null)=>{
31
+ const body=file.endsWith('-controlled-correction.md')?JSON.stringify({
32
+ conclusion:verdict==='approved'?'Zero findings.':'Blocking findings.',
33
+ findings:verdict==='approved'?[]:[{id:'r2-P2-1',priority:'P2',evidence:'Original issue remains unresolved.'}],
34
+ resolved_findings:[],
35
+ },null,2):verdict==='approved'?'Zero findings.':'P2 original blocking finding; retain its disposition as historical rejected evidence.';
36
+ fs.writeFileSync(file,`---\nat: ${new Date().toISOString()}\nreviewer: codex-subagent\nindependent: true\ntask: T-001\nattempt: ${attempt}\nround: ${attempt}\nverdict: ${verdict}\nblocking_findings: ${verdict==='approved'?0:1}\nhandoff: ${path.basename(handoff)}\nhandoff_sha256: ${sha(handoff)}\n${correctionDigest?`correction_sha256: ${correctionDigest}\n`:''}scope:\n${files.map(item=>` - ${item}\n`).join('')}---\n${body}\n`);
37
+ };
38
+ const history=[];
39
+ for(const [attempt,verdict] of [[1,'changes_requested'],[2,'blocked']]){
40
+ const handoff=path.join(reviewsDir,`login-T-001-a${attempt}-handoff.json`),file=path.join(reviewsDir,`login-T-001-r${attempt}.md`);
41
+ fs.writeFileSync(handoff,JSON.stringify(payload(attempt)));review(file,handoff,attempt,verdict);history.push(handoff,file);
42
+ }
43
+ const original=history.map(sha);fs.writeFileSync(code,'corrected implementation');
44
+ const draft=path.join(root,'specs','draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
45
+ const selectors={handoff:draft,reviewsDir,feature:'login',task:'T-001',projectRoot:root,
46
+ decisionSource:'model',reason:'Revise the exact implementation to resolve the original P2 finding.'};
47
+ const prepare=()=>prepareControlledCorrection(selectors);
48
+ const finish=(record,verdict='approved')=>{
49
+ const selected={...selectors,...record,tasksPath:tasks};
50
+ review(record.review,record.handoff,2,verdict,record.correction_sha256);
51
+ publishControlledCorrectionReview(selected);return selected;
52
+ };
53
+ return {root,specs:path.join(root,'specs'),reviewsDir,code,tasks,draft,files,payload,history,original,selectors,review,prepare,finish};
54
+ }
55
+ function cliArgs(command,f,selected=f.selectors){
56
+ return [command,'--handoff',selected.handoff,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,
57
+ ...(selected.correction?['--correction',selected.correction]:[])];
58
+ }
59
+ function draftChange(f,change){
60
+ const payload=JSON.parse(fs.readFileSync(f.draft));change(payload);
61
+ fs.writeFileSync(f.draft,JSON.stringify(payload));
62
+ }
63
+ function reviewBody(file,body){
64
+ const text=fs.readFileSync(file,'utf8'),end=text.indexOf('\n---\n',4);
65
+ assert.notEqual(end,-1);fs.writeFileSync(file,text.slice(0,end+5)+body+'\n');
66
+ }
67
+
68
+ test('controlled model continuation is honest provenance and preserves every original rejected byte',t=>{
69
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
70
+ const value=JSON.parse(fs.readFileSync(record.correction));
71
+ assert.equal(value.version,2);assert.equal(value.protocol,'cm-controlled-correction');
72
+ assert.equal(value.decision_source,'model');assert.equal(value.source_semantics,'provenance-only');
73
+ assert.equal(value.continuation,1);assert.equal(value.attempt,2);
74
+ assert.equal(Object.hasOwn(value,'authorization'),false);
75
+ assert.equal(checkN4(selected).outcome,'ready_for_review');assert.throws(()=>checkN5(selected));
76
+ assert.equal(fs.existsSync(record.review),false);assert.equal(fs.existsSync(path.join(f.reviewsDir,'login-T-001-controlled-correction-receipt.json')),false);
77
+ assert.deepEqual(f.history.map(sha),f.original);
78
+ assert.match(fs.readFileSync(f.history[3],'utf8'),/verdict: blocked/);
79
+ assert.match(fs.readFileSync(f.history[3],'utf8'),/P2 original blocking finding/);
80
+ assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
81
+ });
82
+
83
+ test('fresh independent approval for an actual revision reaches the existing locked completion adapter',t=>{
84
+ const f=fixture(t),record=f.prepare(),done=f.finish(record);
85
+ assert.equal(checkN5(done).outcome,'approved');
86
+ const plan=prepareMarkDone(done);assert.equal(plan.evidence.length,8);
87
+ assert.equal(verifyMarkDonePlan(done,plan.planDigest).outcome,'matched');
88
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,done),'--tasks',f.tasks],{encoding:'utf8'});
89
+ assert.equal(result.status,0,result.stderr);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[x\]/);
90
+ assert.deepEqual(f.history.map(sha),f.original);
91
+ assert.throws(()=>f.prepare(),/already exists/);
92
+ });
93
+
94
+ test('operator provenance uses the same gates and never writes a human authorization field',t=>{
95
+ const f=fixture(t),record=prepareControlledCorrection({...f.selectors,decisionSource:'operator'});
96
+ const value=JSON.parse(fs.readFileSync(record.correction));assert.equal(value.decision_source,'operator');
97
+ assert.equal(JSON.stringify(value).includes('explicit-human-confirmation'),false);
98
+ assert.equal(checkN5(f.finish(record)).outcome,'approved');
99
+ });
100
+
101
+ test('JS-owned or retained execution evidence refuses preparation before any correction artifact is created',t=>{
102
+ for(const name of ['js-run','writer.sqlite-journal','unknown.json']){
103
+ const f=fixture(t),execution=path.join(f.reviewsDir,'.execution');fs.mkdirSync(execution,{mode:0o700});
104
+ if(name==='js-run')fs.mkdirSync(path.join(execution,name));else fs.writeFileSync(path.join(execution,name),'retained');
105
+ assert.throws(()=>f.prepare(),/retained journal, JS run or unknown evidence/);
106
+ assert.deepEqual(fs.readdirSync(f.reviewsDir).sort(),[...f.history.map(file=>path.basename(file)),'login-T-001-baseline.json','.execution'].sort());
107
+ assert.deepEqual(f.history.map(sha),f.original);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
108
+ }
109
+ });
110
+
111
+ test('incomplete or inconsistent compatibility writer evidence refuses preparation before any correction artifact',t=>{
112
+ const ready=digest=>JSON.stringify({version:1,protocol:'cm-writer-ready',databaseDigest:digest})+'\n';
113
+ const bytes=Buffer.from('sqlite bytes'),digest=createHash('sha256').update(bytes).digest('hex');
114
+ const cases={
115
+ 'empty database without readiness':e=>fs.writeFileSync(path.join(e,'writer.sqlite'),'',{mode:0o600}),
116
+ 'empty database with matching readiness':e=>{fs.writeFileSync(path.join(e,'writer.sqlite'),'',{mode:0o600});fs.writeFileSync(path.join(e,'writer-ready.json'),ready(createHash('sha256').update('').digest('hex')),{mode:0o600});},
117
+ 'orphan readiness without database':e=>fs.writeFileSync(path.join(e,'writer-ready.json'),ready(digest),{mode:0o600}),
118
+ 'database without readiness':e=>fs.writeFileSync(path.join(e,'writer.sqlite'),bytes,{mode:0o600}),
119
+ 'readiness digest mismatch':e=>{fs.writeFileSync(path.join(e,'writer.sqlite'),bytes,{mode:0o600});fs.writeFileSync(path.join(e,'writer-ready.json'),ready('0'.repeat(64)),{mode:0o600});},
120
+ 'readiness with extra whitespace':e=>{fs.writeFileSync(path.join(e,'writer.sqlite'),bytes,{mode:0o600});fs.writeFileSync(path.join(e,'writer-ready.json'),ready(digest)+'\n',{mode:0o600});},
121
+ };
122
+ for(const [name,arrange] of Object.entries(cases)){
123
+ const f=fixture(t),execution=path.join(f.reviewsDir,'.execution');fs.mkdirSync(execution,{mode:0o700});arrange(execution);
124
+ const before=fs.readdirSync(f.reviewsDir).sort();
125
+ assert.throws(()=>f.prepare(),/writer/,name);
126
+ assert.deepEqual(fs.readdirSync(f.reviewsDir).sort(),before,name);assert.deepEqual(f.history.map(sha),f.original);
127
+ }
128
+ const f=fixture(t),execution=path.join(f.reviewsDir,'.execution');fs.mkdirSync(execution,{mode:0o700});
129
+ fs.writeFileSync(path.join(execution,'writer.sqlite'),bytes,{mode:0o600});
130
+ fs.writeFileSync(path.join(execution,'writer-ready.json'),ready(digest),{mode:0o600});
131
+ assert.equal(f.prepare().outcome,'ready_for_correction_review');
132
+ });
133
+
134
+ test('library callers never require an editing baseline while CLI entries do',t=>{
135
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record,tasksPath:f.tasks};
136
+ fs.rmSync(path.join(f.reviewsDir,'login-T-001-baseline.json'));
137
+ assert.equal(checkN4(selected).outcome,'ready_for_review');
138
+ const cli=spawnSync(process.execPath,[jsGate,...cliArgs('check-n4',f,selected)],{encoding:'utf8'});
139
+ assert.equal(cli.status,1);assert.match(cli.stderr,/missing editing baseline/);
140
+ f.finish(record);
141
+ assert.equal(checkN5(selected).outcome,'approved');assert.equal(prepareMarkDone(selected).evidence.length,8);
142
+ for(const command of ['check-n5','prepare-mark-done']){
143
+ const refused=spawnSync(process.execPath,[jsGate,...cliArgs(command,f,selected),...(command==='prepare-mark-done'?['--tasks',f.tasks]:[])],{encoding:'utf8'});
144
+ assert.equal(refused.status,1,command);assert.match(refused.stderr,/missing editing baseline/,command);
145
+ }
146
+ assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
147
+ });
148
+
149
+ test('feature-local task owner cannot hide its specs-wide retained JS run from preparation',t=>{
150
+ const f=fixture(t),featureRoot=path.join(f.specs,'login');fs.mkdirSync(featureRoot);
151
+ const local=path.join(featureRoot,'.reviews');fs.renameSync(f.reviewsDir,local);
152
+ fs.writeFileSync(path.join(local,'.cm-task-owner.json'),JSON.stringify({version:1,tasksPath:path.join(featureRoot,'tasks.md'),specsRoot:f.specs})+'\n',{mode:0o600});
153
+ fs.mkdirSync(path.join(f.reviewsDir,'.execution','js-run'),{recursive:true});
154
+ const before=fs.readdirSync(local).sort();
155
+ assert.throws(()=>prepareControlledCorrection({...f.selectors,reviewsDir:local}),/retained journal, JS run or unknown evidence/);
156
+ assert.deepEqual(fs.readdirSync(local).sort(),before);
157
+ });
158
+
159
+ test('JS ownership appearing after preparation or publication closes every correction consumer without changing evidence',t=>{
160
+ for(const published of [false,true]){
161
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record,tasksPath:f.tasks};
162
+ if(published)f.finish(record);else f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
163
+ const files=fs.readdirSync(f.reviewsDir).sort(),bytes=files.map(name=>fs.readFileSync(path.join(f.reviewsDir,name)));
164
+ fs.mkdirSync(path.join(f.reviewsDir,'.execution','js-run'),{recursive:true});
165
+ for(const consume of [checkN4,publishControlledCorrectionReview,checkN5])
166
+ assert.throws(()=>consume(selected),/retained journal, JS run or unknown evidence/);
167
+ assert.throws(()=>prepareMarkDone(selected),published?/retained journal, JS run or unknown evidence/:/receipt/);
168
+ const done=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,selected),'--tasks',f.tasks],{encoding:'utf8'});
169
+ assert.equal(done.status,1);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
170
+ assert.deepEqual(fs.readdirSync(f.reviewsDir).filter(name=>name!=='.execution').sort(),files);
171
+ assert.deepEqual(files.map(name=>fs.readFileSync(path.join(f.reviewsDir,name))),bytes);
172
+ assert.deepEqual(f.history.map(sha),f.original);
173
+ }
174
+ });
175
+
176
+ test('copied history in a noncanonical review directory cannot bypass the original JS owner',t=>{
177
+ const f=fixture(t),alias=path.join(f.root,'fake-reviews');fs.mkdirSync(alias);
178
+ for(const file of f.history)fs.copyFileSync(file,path.join(alias,path.basename(file)));
179
+ fs.mkdirSync(path.join(f.reviewsDir,'.execution','js-run'),{recursive:true});
180
+ const before=fs.readdirSync(alias).sort();
181
+ assert.throws(()=>prepareControlledCorrection({...f.selectors,reviewsDir:alias}),/canonical.*\.reviews/);
182
+ assert.deepEqual(fs.readdirSync(alias).sort(),before);assert.deepEqual(f.history.map(sha),f.original);
183
+ });
184
+
185
+ test('feature-local preparation rejects a symlinked specs-wide review root even when it appears empty',t=>{
186
+ const f=fixture(t),featureRoot=path.join(f.specs,'login');fs.mkdirSync(featureRoot);
187
+ const local=path.join(featureRoot,'.reviews');fs.renameSync(f.reviewsDir,local);
188
+ fs.writeFileSync(path.join(local,'.cm-task-owner.json'),JSON.stringify({version:1,tasksPath:path.join(featureRoot,'tasks.md'),specsRoot:f.specs})+'\n',{mode:0o600});
189
+ const empty=path.join(f.root,'empty');fs.mkdirSync(empty);fs.symlinkSync(empty,f.reviewsDir);
190
+ const before=fs.readdirSync(local).sort();
191
+ assert.throws(()=>prepareControlledCorrection({...f.selectors,reviewsDir:local}),/canonical real non-symlink/);
192
+ assert.deepEqual(fs.readdirSync(local).sort(),before);assert.deepEqual(fs.readdirSync(empty),[]);
193
+ });
194
+
195
+ test('missing reason, invalid provenance, reduced scope and incomplete Learning cannot create a record',t=>{
196
+ const f=fixture(t);
197
+ for(const reason of [undefined,'',' '.repeat(8),'x'.repeat(2001)])
198
+ assert.throws(()=>prepareControlledCorrection({...f.selectors,reason}),/reason/);
199
+ for(const decisionSource of [undefined,'human','approved'])
200
+ assert.throws(()=>prepareControlledCorrection({...f.selectors,decisionSource}),/decision source/);
201
+ draftChange(f,p=>{p.changed_files=['src/example.ts'];p.implementation_sha256=implementationSha256(f.root,p.changed_files);});
202
+ assert.throws(()=>f.prepare(),/full original/);
203
+ fs.writeFileSync(f.draft,JSON.stringify(f.payload(2)));draftChange(f,p=>{p.evidence=['learning: no_relevant_lesson'];});
204
+ assert.throws(()=>f.prepare(),/Learning/);
205
+ assert.equal(fs.readdirSync(f.reviewsDir).length,5);
206
+ });
207
+
208
+ test('changing handoff evidence alone cannot masquerade as an implementation revision',t=>{
209
+ const f=fixture(t);fs.writeFileSync(f.code,'original implementation');
210
+ draftChange(f,p=>{p.implementation_sha256=implementationSha256(f.root,p.changed_files);p.evidence.push('claimed correction without code change');});
211
+ assert.throws(()=>f.prepare(),/actual implementation revision/);
212
+ assert.equal(fs.readdirSync(f.reviewsDir).length,5);
213
+ });
214
+
215
+ test('failed checks, remaining blockers and scope deviations keep controlled correction closed',t=>{
216
+ const f=fixture(t),valid=fs.readFileSync(f.draft);
217
+ for(const change of [p=>{p.verification[0].status='failed';},p=>{p.blockers=['unresolved P2'];},p=>{p.scope_deviation=['omitted required work'];}]){
218
+ draftChange(f,change);assert.throws(()=>f.prepare(),/verification|blockers|scope_deviation/);
219
+ fs.writeFileSync(f.draft,valid);
220
+ }
221
+ const record=f.prepare(),done=f.finish(record);
222
+ const bytes=fs.readFileSync(record.handoff);
223
+ const value=JSON.parse(bytes);value.verification[0].status='failed';fs.writeFileSync(record.handoff,JSON.stringify(value));
224
+ assert.throws(()=>checkN5(done),/verification/);
225
+ });
226
+
227
+ test('only the original independent blocked r2 can enter the continuation',t=>{
228
+ const f=fixture(t),original=fs.readFileSync(f.history[3]);
229
+ f.review(f.history[3],f.history[2],2,'approved');assert.throws(()=>f.prepare(),/blocked round 2 declaring independent/);
230
+ fs.writeFileSync(f.history[3],original.toString().replace('codex-subagent','self-degraded').replace('independent: true','independent: false').replace('scope:','degraded_reason: fixture\nscope:'));
231
+ assert.throws(()=>f.prepare(),/blocked round 2 declaring independent/);
232
+ fs.writeFileSync(f.history[3],original);
233
+ f.review(f.history[1],f.history[0],1,'blocked');assert.throws(()=>f.prepare(),/changes_requested/);
234
+ });
235
+
236
+ test('sealed blocked correction cannot become approved or acquire another continuation',t=>{
237
+ const f=fixture(t),record=f.prepare(),done=f.finish(record,'blocked');
238
+ assert.throws(()=>checkN5(done),/remains blocked/);assert.throws(()=>prepareMarkDone(done),/remains blocked/);
239
+ assert.throws(()=>publishControlledCorrectionReview(done),/already exists/);
240
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
241
+ assert.throws(()=>checkN5(done),/review or receipt changed/);
242
+ assert.throws(()=>f.prepare(),/already exists/);
243
+ assert.throws(()=>prepareHumanCorrection(f.selectors),/another continuation is forbidden/);
244
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,done),'--tasks',f.tasks],{encoding:'utf8'});
245
+ assert.notEqual(result.status,0);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
246
+ });
247
+
248
+ test('fresh review must bind correction and full handoff and declare zero blocking findings',t=>{
249
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
250
+ const write=()=>f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
251
+ f.review(record.review,record.handoff,2,'approved');assert.throws(()=>publishControlledCorrectionReview(selected),/fresh independent/);
252
+ write();fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('blocking_findings: 0','blocking_findings: 1'));
253
+ assert.throws(()=>publishControlledCorrectionReview(selected),/blocking_findings: 0/);
254
+ write();fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace(' - src/unchanged.ts\n',''));
255
+ assert.throws(()=>publishControlledCorrectionReview(selected),/scope does not cover/);
256
+ write();fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('Zero findings.','P2 remains unresolved.'));
257
+ assert.throws(()=>publishControlledCorrectionReview(selected),/zero blocking findings/);
258
+ write();fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace(/at: [^\n]+/,'at: 2020-01-01T00:00:00Z'));
259
+ assert.throws(()=>publishControlledCorrectionReview(selected),/fresh independent/);
260
+ write();fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('codex-subagent','self-degraded').replace('independent: true','independent: false').replace('scope:','degraded_reason: fixture\nscope:'));
261
+ assert.throws(()=>publishControlledCorrectionReview(selected),/fresh independent/);
262
+ });
263
+
264
+ test('mixed zero-findings prose and unresolved P2 cannot publish or complete even with a matching forged receipt',t=>{
265
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record,tasksPath:f.tasks};
266
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
267
+ reviewBody(record.review,'Zero findings.\nP2 remains unresolved and must be fixed before completion.');
268
+ assert.throws(()=>publishControlledCorrectionReview(selected),/structured findings/);
269
+ const receipt=path.join(f.reviewsDir,'login-T-001-controlled-correction-receipt.json');
270
+ assert.equal(fs.existsSync(receipt),false);
271
+ fs.writeFileSync(receipt,JSON.stringify({version:2,protocol:'cm-controlled-correction-review',
272
+ correction_sha256:record.correction_sha256,review_sha256:sha(record.review),verdict:'approved'}));
273
+ assert.throws(()=>checkN5(selected),/structured findings/);
274
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,selected),'--tasks',f.tasks],{encoding:'utf8'});
275
+ assert.equal(result.status,1,result.stderr);assert.match(result.stderr,/structured findings/);
276
+ assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
277
+ });
278
+
279
+ test('active structured P1/P2 findings override an approved header and zero conclusion',t=>{
280
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
281
+ for(const priority of ['P1','P2']){
282
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
283
+ reviewBody(record.review,JSON.stringify({conclusion:'Zero findings.',
284
+ findings:[{id:`active-${priority}`,priority,evidence:'Issue remains unresolved.'}],resolved_findings:[]}));
285
+ assert.throws(()=>publishControlledCorrectionReview(selected),/active findings|finding count/);
286
+ }
287
+ });
288
+
289
+ test('resolved historical P2 is explicit structured evidence and may pass without active findings',t=>{
290
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record,tasksPath:f.tasks};
291
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
292
+ reviewBody(record.review,JSON.stringify({conclusion:'Zero findings.',findings:[],
293
+ resolved_findings:[{id:'r2-P2-1',priority:'P2',evidence:'The revised implementation and regression resolve the historical P2 finding.'}]}));
294
+ assert.equal(publishControlledCorrectionReview(selected).outcome,'approved');
295
+ assert.equal(checkN5(selected).outcome,'approved');assert.equal(prepareMarkDone(selected).evidence.length,8);
296
+ assert.deepEqual(f.history.map(sha),f.original);
297
+ });
298
+
299
+ test('structured review rejects missing fields, extra prose, duplicate keys, invalid arrays and contradictory conclusions',t=>{
300
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
301
+ const valid={conclusion:'Zero findings.',findings:[],resolved_findings:[]};
302
+ const malformed=[
303
+ {conclusion:'Zero findings.',resolved_findings:[]},
304
+ {...valid,extra:'P2 remains unresolved.'},
305
+ {...valid,conclusion:'Zero findings. P2 remains unresolved.'},
306
+ {...valid,findings:null},
307
+ {...valid,resolved_findings:'P2 was fixed'},
308
+ {...valid,findings:[{}]},
309
+ {...valid,resolved_findings:[{id:'old-P2',priority:'P2'}]},
310
+ {...valid,resolved_findings:[{id:'old-P2',priority:'P9',evidence:'fixed'}]},
311
+ {...valid,resolved_findings:[{id:'old-P2',priority:'P2',evidence:'fixed'},{id:'old-P2',priority:'P2',evidence:'duplicate'}]},
312
+ JSON.stringify(valid)+'\nP2 remains unresolved.',
313
+ 'Zero findings.\n'+JSON.stringify(valid),
314
+ '{"conclusion":"Zero findings.","findings":[],"findings":[],"resolved_findings":[]}',
315
+ ];
316
+ for(const body of malformed){
317
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
318
+ reviewBody(record.review,typeof body==='string'?body:JSON.stringify(body));
319
+ assert.throws(()=>publishControlledCorrectionReview(selected),/controlled correction/);
320
+ }
321
+ f.review(record.review,record.handoff,2,'blocked',record.correction_sha256);
322
+ reviewBody(record.review,JSON.stringify({conclusion:'Blocking findings.',
323
+ findings:[{id:'P1-1',priority:'P1',evidence:'one'},{id:'P2-2',priority:'P2',evidence:'two'}],resolved_findings:[]}));
324
+ assert.throws(()=>publishControlledCorrectionReview(selected),/finding count/);
325
+ });
326
+
327
+ test('history, implementation, finalized handoff, record, review and receipt tampering invalidate completion',t=>{
328
+ const f=fixture(t),record=f.prepare(),done=f.finish(record),plan=prepareMarkDone(done);
329
+ const receipt=path.join(f.reviewsDir,'login-T-001-controlled-correction-receipt.json');
330
+ for(const file of [...f.history,record.correction,record.handoff,record.review,receipt,f.code]){
331
+ const bytes=fs.readFileSync(file);fs.appendFileSync(file,'\nchanged');
332
+ assert.throws(()=>checkN5(done),undefined,file);assert.throws(()=>verifyMarkDonePlan(done,plan.planDigest),undefined,file);
333
+ fs.writeFileSync(file,bytes);
334
+ }
335
+ assert.equal(checkN5(done).outcome,'approved');
336
+ });
337
+
338
+ test('fixed paths and strict versioning prevent mixing human and controlled protocols',t=>{
339
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
340
+ const bytes=fs.readFileSync(record.correction),value=JSON.parse(bytes);
341
+ value.protocol='cm-human-correction';value.version=1;fs.writeFileSync(record.correction,JSON.stringify(value));
342
+ assert.throws(()=>checkN4(selected),/provenance record/);fs.writeFileSync(record.correction,bytes);
343
+ assert.throws(()=>publishHumanCorrectionReview(selected),/fixed evidence/);
344
+ assert.throws(()=>checkN4({...selected,correction:path.join(f.root,'record.json')}),/fixed evidence/);
345
+ fs.writeFileSync(record.correction,bytes.toString().replace('"version": 2','"version": 2, "version": 2'));
346
+ assert.throws(()=>checkN4(selected),/duplicate key/);
347
+ });
348
+
349
+ test('controlled evidence rejects hardlinks and symlinks',t=>{
350
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
351
+ const alias=path.join(f.root,'alias');fs.linkSync(record.correction,alias);
352
+ assert.throws(()=>checkN4(selected),/hardlinked/);fs.unlinkSync(alias);
353
+ fs.renameSync(record.correction,alias);fs.symlinkSync(alias,record.correction);
354
+ assert.throws(()=>checkN4(selected),/non-symlink/);
355
+ });
356
+
357
+ test('strict record and receipt fields reject missing reasons and cross-protocol receipt tampering',t=>{
358
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
359
+ const recordBytes=fs.readFileSync(record.correction);
360
+ for(const change of [p=>{delete p.reason;},p=>{p.continuation=2;},p=>{p.authorization='model-approved';},p=>{p.decision_source='authenticated';}]){
361
+ const value=JSON.parse(recordBytes);change(value);fs.writeFileSync(record.correction,JSON.stringify(value));
362
+ assert.throws(()=>checkN4(selected),/controlled correction/);fs.writeFileSync(record.correction,recordBytes);
363
+ }
364
+ const done=f.finish(record),receipt=path.join(f.reviewsDir,'login-T-001-controlled-correction-receipt.json');
365
+ const receiptBytes=fs.readFileSync(receipt);
366
+ for(const change of [p=>{p.protocol='cm-human-correction-review';p.version=1;},p=>{p.correction_sha256='0'.repeat(64);},p=>{p.verdict='blocked';}]){
367
+ const value=JSON.parse(receiptBytes);change(value);fs.writeFileSync(receipt,JSON.stringify(value));
368
+ assert.throws(()=>checkN5(done),/review or receipt changed/);fs.writeFileSync(receipt,receiptBytes);
369
+ }
370
+ });
371
+
372
+ test('interleaved legacy and controlled preparation seals at most one continuation',t=>{
373
+ const f=fixture(t),humanHandoff=path.join(f.reviewsDir,'login-T-001-human-correction-handoff.json');
374
+ const originalWrite=fs.writeFileSync;let denied=false,human;
375
+ try{
376
+ fs.writeFileSync=function(file,...args){
377
+ // Contend while the human preparation owns the shared protocol lock.
378
+ if(file===humanHandoff&&!denied){
379
+ denied=true;assert.throws(()=>f.prepare(),/blocked: correction preparation lock/);
380
+ }
381
+ return originalWrite.call(this,file,...args);
382
+ };
383
+ human=prepareHumanCorrection(f.selectors);
384
+ }finally{fs.writeFileSync=originalWrite;}
385
+ assert.equal(denied,true);assert.equal(checkN4({...f.selectors,...human}).outcome,'ready_for_review');
386
+ assert.equal(fs.existsSync(path.join(f.reviewsDir,'login-T-001-controlled-correction.json')),false);
387
+ assert.throws(()=>f.prepare(),/another continuation is forbidden/);
388
+ });
389
+
390
+ for(const first of ['controlled','human'])test(`dual unsealed orphan handoffs recover safely with ${first} preparation first`,t=>{
391
+ const f=fixture(t),humanHandoff=path.join(f.reviewsDir,'login-T-001-human-correction-handoff.json');
392
+ const controlledHandoff=path.join(f.reviewsDir,'login-T-001-controlled-correction-handoff.json');
393
+ fs.copyFileSync(f.draft,humanHandoff);fs.copyFileSync(f.draft,controlledHandoff);
394
+ const originalOrphans=[sha(humanHandoff),sha(controlledHandoff)];
395
+ const record=first==='controlled'?f.prepare():prepareHumanCorrection(f.selectors);
396
+ assert.deepEqual([sha(humanHandoff),sha(controlledHandoff)],originalOrphans);
397
+ let selected;
398
+ if(first==='controlled'){
399
+ selected=f.finish(record);assert.throws(()=>prepareHumanCorrection(f.selectors),/another continuation is forbidden/);
400
+ }else{
401
+ selected={...f.selectors,...record,tasksPath:f.tasks};
402
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);publishHumanCorrectionReview(selected);
403
+ assert.throws(()=>f.prepare(),/another continuation is forbidden/);
404
+ }
405
+ assert.equal(checkN5(selected).outcome,'approved');assert.equal(prepareMarkDone(selected).evidence.length,8);
406
+ assert.equal(fs.existsSync(path.join(f.reviewsDir,'login-T-001-correction-prepare.lock')),false);
407
+ assert.deepEqual(f.history.map(sha),f.original);
408
+ });
409
+
410
+ test('retained preparation lock blocks both protocols without clearing unknown ownership or evidence',t=>{
411
+ const f=fixture(t),lock=path.join(f.reviewsDir,'login-T-001-correction-prepare.lock');
412
+ const retained=JSON.stringify({version:1,protocol:'cm-correction-prepare-lock',pid:process.pid,at:new Date().toISOString()});
413
+ fs.writeFileSync(lock,retained);
414
+ assert.throws(()=>f.prepare(),/blocked: correction preparation lock/);
415
+ assert.throws(()=>prepareHumanCorrection(f.selectors),/blocked: correction preparation lock/);
416
+ assert.equal(fs.readFileSync(lock,'utf8'),retained);assert.deepEqual(f.history.map(sha),f.original);
417
+ });
418
+
419
+ test('failed preparation releases its lock and preserves identical orphan recovery',t=>{
420
+ const f=fixture(t),lock=path.join(f.reviewsDir,'login-T-001-correction-prepare.lock');
421
+ draftChange(f,p=>{p.evidence=['learning: no_relevant_lesson'];});assert.throws(()=>f.prepare(),/Learning/);
422
+ assert.equal(fs.existsSync(lock),false);fs.writeFileSync(f.draft,JSON.stringify(f.payload(2)));
423
+ assert.equal(f.prepare().outcome,'ready_for_correction_review');assert.equal(fs.existsSync(lock),false);
424
+ });
425
+
426
+ test('legacy human record remains version 1 and model continuation cannot follow it',t=>{
427
+ const f=fixture(t),record=prepareHumanCorrection(f.selectors);
428
+ const value=JSON.parse(fs.readFileSync(record.correction));
429
+ assert.equal(value.version,1);assert.equal(value.protocol,'cm-human-correction');
430
+ assert.equal(value.authorization,'explicit-human-confirmation');assert.equal(Object.hasOwn(value,'decision_source'),false);
431
+ const selected={...f.selectors,...record,tasksPath:f.tasks};
432
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);publishHumanCorrectionReview(selected);
433
+ assert.equal(checkN5(selected).outcome,'approved');assert.equal(prepareMarkDone(selected).evidence.length,8);
434
+ assert.throws(()=>f.prepare(),/another continuation is forbidden/);assert.deepEqual(f.history.map(sha),f.original);
435
+ });
436
+
437
+ test('new CLI and Python forwarder prepare, check, publish and complete; --human-authorized is rejected',t=>{
438
+ const f=fixture(t),args=[...cliArgs('prepare-controlled-correction',f),'--decision-source','model','--reason',f.selectors.reason];
439
+ const invalid=spawnSync(process.execPath,[jsGate,...args,'--human-authorized'],{encoding:'utf8'});
440
+ assert.equal(invalid.status,1);assert.match(invalid.stderr,/invalid arguments/);
441
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...args],{encoding:'utf8'});
442
+ assert.equal(result.status,0,result.stderr);const record=JSON.parse(result.stdout),selected={...f.selectors,...record};
443
+ const ready=spawnSync(process.execPath,[jsGate,...cliArgs('check-n4',f,selected)],{encoding:'utf8'});
444
+ assert.equal(ready.status,0,ready.stderr);assert.equal(JSON.parse(ready.stdout).inventory,'verified');
445
+ // CLI entries verify the edit inventory on the controlled path too: an unlisted edit blocks N4/N5.
446
+ const stray=path.join(f.root,'src/stray.ts');fs.writeFileSync(stray,'unlisted edit');
447
+ const mismatch=spawnSync(process.execPath,[jsGate,...cliArgs('check-n4',f,selected)],{encoding:'utf8'});
448
+ assert.equal(mismatch.status,1);assert.match(mismatch.stderr,/inventory mismatch/);
449
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
450
+ const published=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('publish-controlled-correction-review',f,selected)],{encoding:'utf8'});
451
+ assert.equal(published.status,0,published.stderr);
452
+ const blocked=spawnSync(process.execPath,[jsGate,...cliArgs('check-n5',f,selected)],{encoding:'utf8'});
453
+ assert.equal(blocked.status,1);assert.match(blocked.stderr,/inventory mismatch/);
454
+ const refused=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,selected),'--tasks',f.tasks],{encoding:'utf8'});
455
+ assert.equal(refused.status,1);assert.match(refused.stderr,/inventory mismatch/);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
456
+ fs.rmSync(stray);
457
+ const approved=spawnSync(process.execPath,[jsGate,...cliArgs('check-n5',f,selected)],{encoding:'utf8'});
458
+ assert.equal(approved.status,0,approved.stderr);assert.equal(JSON.parse(approved.stdout).inventory,'verified');
459
+ const done=spawnSync(process.env.CM_PYTHON_BIN||'python3',[pyGate,...cliArgs('mark-done',f,selected),'--tasks',f.tasks],{encoding:'utf8'});
460
+ assert.equal(done.status,0,done.stderr);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[x\]/);
461
+ });
462
+
463
+ test('only an identical orphan handoff can recover before the one-time record was created',t=>{
464
+ const f=fixture(t),orphan=path.join(f.reviewsDir,'login-T-001-controlled-correction-handoff.json');
465
+ fs.copyFileSync(f.draft,orphan);fs.appendFileSync(orphan,' ');
466
+ assert.throws(()=>f.prepare(),/already exists/);
467
+ fs.copyFileSync(f.draft,orphan);assert.equal(f.prepare().outcome,'ready_for_correction_review');
468
+ assert.throws(()=>f.prepare(),/already exists/);
469
+ });
@@ -41,9 +41,22 @@ function fixture(runtime='codex'){
41
41
  ...(runtime==='claude'?['--runtime','claude']:[])]};
42
42
  }
43
43
 
44
- function execute(f,approvals,{cancel=false}={}){
44
+ // Use an actual first-round review finding for a launch-only revision pause.
45
+ // The synthetic native process still emits its normal bound review observation.
46
+ function requestFirstRevision(f,taskIds){
47
+ const fake=path.join(f.root,'bin',f.runtime);
48
+ const first=`${JSON.stringify(taskIds)}.includes(data.reviewPackage.identity.taskId)&&data.reviewPackage.identity.attempt===1`;
49
+ const source=fs.readFileSync(fake,'utf8');
50
+ assert(source.includes("verdict:'approved'")&&source.includes('findings:[]'),'native review fixture must retain its known response fields');
51
+ fs.writeFileSync(fake,source
52
+ .replace("verdict:'approved'",`verdict:(${first})?'changes_requested':'approved'`)
53
+ .replace('findings:[]',`findings:(${first})?[{id:'F1',severity:'P2',path:'task'+Number(data.reviewPackage.identity.taskId.slice(-1))+'.mjs',message:'Recheck the export in a revision',evidence:'Synthetic first-round review finding'}]:[]`));
54
+ return taskIds.flatMap(taskId=>['--hold-revision',`1.work/${taskId}`]);
55
+ }
56
+
57
+ function execute(f,{cancel=false,args=[]}={}){
45
58
  return new Promise((resolve,reject)=>{
46
- const child=spawn(process.execPath,[cli,...f.args,...approvals.flatMap(value=>['--allow-review',value])],
59
+ const child=spawn(process.execPath,[cli,...f.args,...args],
47
60
  {env:f.env,stdio:['pipe','pipe','pipe']});
48
61
  let buffer='',stderr='',sessionId;const calls=[],rows=[];
49
62
  const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('batch host timeout'));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
@@ -69,7 +82,7 @@ function execute(f,approvals,{cancel=false}={}){
69
82
  assert.deepEqual(payload.request.payload.scope,f.batch.tasks[n-1].scope);
70
83
  assert.equal(payload.request.payload.specification.task.id,identity.taskId);
71
84
  assert.deepEqual(payload.request.payload.specification.sources,buildManifest(f.specsDir));
72
- const content=`export const value = ${40+n};\n`;
85
+ const content=`export const value = ${40+n};\n${identity.attempt===2?"// Revised after the independent review finding.\n":""}`;
73
86
  if(!f.protected)fs.writeFileSync(path.join(cwd,`task${n}.mjs`),content);
74
87
  respond(row,{status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
75
88
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}},...(f.protected?{edits:
@@ -81,8 +94,7 @@ function execute(f,approvals,{cancel=false}={}){
81
94
  const result=spawnSync(command[0],command.slice(1));assert.equal(result.status,0);
82
95
  return {id:'syntax',command,outcome:'passed',exitCode:0,evidence:'Actual Node syntax check exited 0'};
83
96
  });respond(row,checks);
84
- }else if(row.kind==='qa_assess')respond(row,{scores:{scope:2,risk:2,accumulation:2,boundary:2},
85
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
97
+ }else if(row.kind==='qa_assess')respond(row,{confirmed:true});
86
98
  else if(row.kind==='documentation_sync'){
87
99
  assert.equal(identity.taskId,'T-002');assert.deepEqual(payload.paths,['README.md']);
88
100
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');respond(row,{status:'completed'});
@@ -112,13 +124,16 @@ for(const runtime of ['codex','claude'])test(`${runtime} real batch host freezes
112
124
  const sent=path.join(f.root,'sent.jsonl'),fake=path.join(f.root,'bin',runtime);
113
125
  fs.writeFileSync(fake,fs.readFileSync(fake,'utf8').replace("import {randomUUID}",`import fs from 'node:fs';fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify(process.argv.slice(2))+'\\n');\nimport {randomUUID}`));
114
126
  const review=JSON.parse(fs.readFileSync(f.review));review.effort=pair.effort;review.preflight.config_fingerprint=(runtime==='claude'?claudeReviewFingerprint:configFingerprint)({cwd:f.codeProject,...pair});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
115
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
127
+ const held=requestFirstRevision(f,['T-001']);
128
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
129
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
130
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
116
131
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
117
132
  assert(!fs.existsSync(statePath(2)));assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.externalModels,models);
118
133
  fs.writeFileSync(settings,'invalid new user defaults');
119
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
134
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
120
135
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.externalModels,models);
121
- const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,2);
136
+ const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,3);
122
137
  for(const args of calls){if(runtime==='codex'){assert(args.includes('model_reasoning_effort="low"'));assert(args.includes('--ephemeral'));}else{assert(!args.includes('--effort'));assert(args.includes('--no-session-persistence'));}}
123
138
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));assert(!tracked.stdout.includes('.cm-model-config.lock'));
124
139
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -136,7 +151,7 @@ test('new parallel batch merges reviewed members without committing private bind
136
151
  const review=JSON.parse(fs.readFileSync(f.review));review.effort='low';review.preflight.config_fingerprint=configFingerprint({cwd:f.codeProject,model:'fixture',effort:'low'});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
137
152
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');
138
153
  for(const args of [['add','README.md'],['commit','-m','fixture documentation']])assert.equal(spawnSync('git',['-C',f.codeProject,...args]).status,0);
139
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1','1.work/T-003:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
154
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
140
155
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'}).stdout;assert(!tracked.includes('.cm-external-models-v1.json'));assert(!tracked.includes('.cm-model-config.lock'));
141
156
  for(const n of [1,2])assert(!fs.existsSync(path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),'T-00'+n)));
142
157
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -145,12 +160,16 @@ test('new parallel batch merges reviewed members without committing private bind
145
160
  test('optimization-only serial batch freezes policy for later members after removing launch flag',async()=>{
146
161
  const f=fixture();f.args.push('--execution-optimizations');f.env.CM_WORKFLOW_HOME=path.join(f.root,'home');f.env.CM_WORKFLOW_LOG_HOME=path.join(f.root,'logs');
147
162
  try{
148
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
163
+ const held=requestFirstRevision(f,['T-001']);
164
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
165
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
166
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
149
167
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');
150
168
  const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
169
+ assert(!fs.existsSync(statePath(2)));
151
170
  assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
152
171
  f.args=f.args.filter(arg=>arg!=='--execution-optimizations');
153
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
172
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
154
173
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
155
174
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));
156
175
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -62,7 +62,7 @@ else for(const event of [{type:'thread.started',thread_id:dev?'fake-author':'fak
62
62
  const routes=resolveProtectedRuntimes(loadConfig({projectRoot:codeProject}),'codex');
63
63
  const execution=(selected=models,{legacy=false}={})=>createConversationExecution(definition,'fixture-host',bridge,
64
64
  legacy?((({effort,...rest})=>({...rest,model:'fixture-codex',preflight:{...rest.preflight,config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture-codex'})}}))(review)):review,
65
- 1,null,false,'codex',{
65
+ null,null,false,'codex',{
66
66
  ...(efficiency?{executionPolicy:EXECUTION_POLICY_V1}:{}),
67
67
  ...(!legacy?{externalModels:selected}:{}),
68
68
  ...(!session?{protection,providerDevelopment:{model:legacy?'fixture-codex':selected.providers.codex.model,