@aibyzero/cm-workflow 0.16.9 → 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 (139) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +9 -1
  4. package/VERSION +1 -1
  5. package/docs/cm-control-policy-v2.md +331 -0
  6. package/docs/execution-optimizations.md +1 -1
  7. package/docs/external-models.md +3 -3
  8. package/docs/human-correction.md +5 -5
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +101 -84
  11. package/docs/next-steps.md +11 -0
  12. package/docs/untested-branches.md +2 -3
  13. package/docs/user-guide.md +3 -3
  14. package/package.json +1 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  17. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  18. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  20. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  23. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  24. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  25. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  26. package/runtime/js/cm-ai/host-tool-bridge.mjs +3 -0
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  28. package/runtime/js/cm-ai/host.mjs +1 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +1 -24
  30. package/runtime/js/cm-ai/review-package.mjs +16 -4
  31. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  32. package/runtime/js/cm-ai/task-runner.mjs +36 -99
  33. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  34. package/runtime/js/cm-prd/review-host.mjs +1 -1
  35. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  36. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  37. package/runtime/js/notify-send.mjs +15 -14
  38. package/runtime/js/notify.mjs +27 -4
  39. package/runtime/js/policy-binding-compat.mjs +2 -1
  40. package/runtime/review.md +52 -7
  41. package/runtime/task-gates.md +107 -9
  42. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  43. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  44. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  45. package/scripts/cm-ai-batch-drive.mjs +50 -31
  46. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  47. package/scripts/cm-ai-batch-host.mjs +39 -20
  48. package/scripts/cm-ai-batch-host.test.mjs +62 -38
  49. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  50. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  51. package/scripts/cm-ai-batch-run.mjs +34 -8
  52. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  53. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  54. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  55. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  56. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  57. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  58. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  59. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  60. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  61. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  62. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  63. package/scripts/cm-ai-drive.mjs +96 -54
  64. package/scripts/cm-ai-drive.test.mjs +43 -84
  65. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  66. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  67. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  68. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  69. package/scripts/cm-ai-host-fixture.mjs +38 -10
  70. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  71. package/scripts/cm-ai-host.mjs +103 -93
  72. package/scripts/cm-ai-host.test.mjs +19 -18
  73. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  74. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  75. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  76. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  77. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  78. package/scripts/cm-ai-progress.test.mjs +10 -8
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  80. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  81. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  82. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  83. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  84. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  85. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  86. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  87. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  88. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  89. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  90. package/scripts/cm-ai-review-timeout.test.mjs +15 -128
  91. package/scripts/cm-ai-run.mjs +78 -24
  92. package/scripts/cm-ai-run.test.mjs +11 -38
  93. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  94. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  95. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  96. package/scripts/cm-ai-supersede.test.mjs +3 -10
  97. package/scripts/cm-blocked-reason.test.mjs +2 -3
  98. package/scripts/cm-capability-gate.test.mjs +33 -1
  99. package/scripts/cm-check-drive-files.mjs +1 -1
  100. package/scripts/cm-check-runtime.sh +1 -1
  101. package/scripts/cm-claude-worker.test.mjs +5 -3
  102. package/scripts/cm-controlled-correction.test.mjs +469 -0
  103. package/scripts/cm-external-batch-host.test.mjs +30 -11
  104. package/scripts/cm-external-model-host.test.mjs +1 -1
  105. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  106. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  107. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  108. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  109. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  110. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  111. package/scripts/cm-host-review-authority.test.mjs +0 -31
  112. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  113. package/scripts/cm-notify-command.test.mjs +54 -18
  114. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  115. package/scripts/cm-notify.mjs +16 -4
  116. package/scripts/cm-notify.test.mjs +91 -19
  117. package/scripts/cm-patrol.test.mjs +3 -2
  118. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  119. package/scripts/cm-task-gate.mjs +368 -34
  120. package/scripts/cm-task-gate.py +2 -0
  121. package/scripts/cm-task-gate.test.mjs +252 -4
  122. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  123. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  124. package/scripts/policy-binding-compat.test.mjs +4 -0
  125. package/skills/cm-ai/SKILL.md +8 -6
  126. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  127. package/skills/cm-ai/references/N4-review.md +11 -21
  128. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  129. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  130. package/skills/cm-ai/references/js-host-modes.md +35 -14
  131. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  132. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  133. package/skills/cm-ai/references/js-host.md +65 -28
  134. package/skills/cm-fix/SKILL.md +12 -0
  135. package/skills/cm-init/references/js-host.md +1 -1
  136. package/skills/cm-prd/references/js-host.md +1 -1
  137. package/skills/cm-refactor/SKILL.md +12 -0
  138. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  139. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -24,15 +24,14 @@ async function fixture(value,provider,fn){
24
24
  const adapter=createDeveloperRun({provider,requestedModel:'fixture',worker:async()=>{
25
25
  dispatched++;return {status:'succeeded',value};
26
26
  }});
27
- const execution={configuration:{kind:'blocked-fixture-v1'},timeoutMs:3000,excludedContexts:['host'],
28
- hostDecision:{status:'approved'},applicableAgentFiles:[],qaLogHome:path.join(root,'logs'),
27
+ const execution={configuration:{kind:'blocked-fixture-v1'},timeoutMs:3000,excludedContexts:['host'],applicableAgentFiles:[],qaLogHome:path.join(root,'logs'),
29
28
  developer:{provider,requestedModel:'fixture',contextId:'author',run:async(r,c)=>{
30
29
  request=r;terminal=await adapter(r,c);return terminal;
31
30
  }},
32
31
  check:()=>assert.fail('blocked must not run checks'),
33
32
  reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
34
33
  allowed:true,available:true,contexts:['review-1','review-2'],run:()=>assert.fail('blocked must not run review')}],
35
- reviewInvocation:{developerThreadId:'author',excludedThreadIds:['host'],authorize:()=>assert.fail('blocked must not authorize review')},
34
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['host']},
36
35
  };
37
36
  const statePath=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
38
37
  const read=()=>JSON.parse(fs.readFileSync(statePath,'utf8'));
@@ -10,6 +10,7 @@ import {spawnSync} from 'node:child_process';
10
10
  import {fileURLToPath} from 'node:url';
11
11
  import {buildManifest} from './cm-spec-manifest.mjs';
12
12
  import {loadConfig} from './cm-workflow-config.mjs';
13
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
13
14
 
14
15
  const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-capability-home-'));
15
16
  process.env.CM_WORKFLOW_HOME=path.join(isolatedHome,'user');
@@ -42,7 +43,8 @@ function fixture(browserCase,{blocking=true,tests=['logic','commands','browser']
42
43
  qa:{commands:[{id:'unit',command:[process.execPath,'--version'],caseIds:browserCase?[]:['TC-001']}],
43
44
  environment:{kind:'web',carrier:'browser',target:'https://example.invalid/fixture',scope:'local'}}}));
44
45
  // create requires a bound review configuration; this one grants no review attempt.
45
- const review=path.join(root,'placeholder-review.json');fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{}}));
46
+ const review=path.join(root,'placeholder-review.json');fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
47
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}}));
46
48
  return {root,specsDir,codeProject,config,workflow,
47
49
  args:['serve','--config',config,'--mode','create','--host-context','gate-fixture','--allow-development',
48
50
  '--workflow-config',workflow,'--allow-qa','--review-config',review]};
@@ -196,3 +198,33 @@ test('declaring browser tests requires the role that serves them',()=>{
196
198
  assert.deepEqual(loadConfig({projectRoot:root}).policies.tests,['logic']);
197
199
  }finally{fs.rmSync(root,{recursive:true,force:true});}
198
200
  });
201
+
202
+ for(const batch of [false,true])test(`v2 ${batch?'batch':'single'} inactive QA does not require browser capability`,()=>{
203
+ for(const qa of ['disabled','run'])for(const declaration of [null,'unavailable']){
204
+ const f=batch?batchFixture({}):fixture(true);
205
+ try{
206
+ const control=path.join(f.root,'control.json');
207
+ fs.writeFileSync(control,JSON.stringify({version:2,development:'conversation',bootstrap:'disabled',qa,qaFix:'disabled'}));
208
+ const review=path.join(f.root,'placeholder-review.json');
209
+ fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',
210
+ prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
211
+ if(batch)for(const args of [['init','-b','main'],['config','user.name','Fixture'],['config','user.email','fixture@example.invalid'],['add','-A'],['commit','-m','baseline']]){
212
+ const result=spawnSync('git',['-C',f.codeProject,...args],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);
213
+ }
214
+ const args=['serve','--config',f.config,...(batch?[]:['--mode','create']),'--host-context','gate-v2',
215
+ '--control-config',control,'--review-config',review,...(batch?[]:['--workflow-config',f.workflow]),
216
+ ...(declaration?['--browser-qa',declaration]:[])];
217
+ const request={version:2,operation:'status',requestId:'v2-status',...(batch?{}:{identity})};
218
+ const result=spawnSync(process.execPath,[batch?batchCli:cli,...args],{encoding:'utf8',timeout:20000,
219
+ input:JSON.stringify(request)+'\n',env:{...process.env,NODE_NO_WARNINGS:'1'}});
220
+ if(qa==='run')rejected(result,declaration?'browser_capability_unavailable':'browser_capability_required');
221
+ else if(declaration)rejected(result,'invalid_arguments');
222
+ else{
223
+ assert.equal(result.error,undefined);assert.equal(result.status,0,result.stderr);
224
+ const rows=result.stdout.trim().split('\n').map(JSON.parse);assert.equal(rows[0].type,'host_ready');
225
+ const response=rows.find(row=>row.requestId==='v2-status');assert.ok(response,result.stdout);
226
+ assert.notEqual(response.result.outcome,'rejected',result.stdout);assert.ok(response.result.state,result.stdout);
227
+ }
228
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
229
+ }
230
+ });
@@ -3,6 +3,6 @@
3
3
  export const CHECK_DRIVE_COPIED_FILES=Object.freeze([
4
4
  'scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-check-drive.mjs',
5
5
  'scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs','runtime/js/cm-ai/drive-core.mjs',
6
- 'runtime/js/cm-ai/operator-guidance.mjs','runtime/js/cm-ai/review-dispatch-limits.mjs',
6
+ 'runtime/js/cm-ai/operator-guidance.mjs',
7
7
  'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/diagnostic-reason.mjs','runtime/js/cm-ai/effect-contract.mjs',
8
8
  'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']);
@@ -284,7 +284,7 @@ for module in \
284
284
  durable-runner-state.mjs effect-contract.mjs execution-store.mjs gate-bridge.mjs \
285
285
  host.mjs host-session.mjs diagnostic-reason.mjs index.mjs provider-review-observation.mjs review-package.mjs \
286
286
  review-result.schema.json review-runner.mjs task-commit-codec.mjs task-commit.mjs \
287
- task-owner.mjs task-runner.mjs worker-codex.mjs operator-guidance.mjs review-dispatch-limits.mjs; do
287
+ task-owner.mjs task-runner.mjs worker-codex.mjs operator-guidance.mjs; do
288
288
  require_file "runtime/js/cm-ai/$module"
289
289
  done
290
290
  require_file "scripts/cm-check-runtime.ps1"
@@ -169,7 +169,9 @@ test('timeout kills inherited-pipe descendants, including TERM-ignoring children
169
169
  let descendant,leader;
170
170
  // Both guards watch this test process, never the leader, so a missed group kill still shows.
171
171
  const hung=ownerGuardSource()+"process.on('SIGTERM',()=>{});setInterval(()=>{},1000)";
172
- const worker=claudeWorker({...config,preflight:receipt,timeoutMs:300,
172
+ // 1.5 s leaves a loaded CI runner time to start the leader and report the
173
+ // descendant pid before the timeout fires; the assertions below scale with it.
174
+ const worker=claudeWorker({...config,preflight:receipt,timeoutMs:1500,
173
175
  spawnProcess:(_cli,_args,options)=>{
174
176
  const child=spawn(process.execPath,['-e',
175
177
  `${ownerGuardSource()}const {spawn}=require('node:child_process');const c=spawn(process.execPath,['-e',
@@ -181,8 +183,8 @@ test('timeout kills inherited-pipe descendants, including TERM-ignoring children
181
183
  try {
182
184
  const started=Date.now();
183
185
  const result=await worker({prompt:'synthetic'}, {signal:new AbortController().signal,onEvent:()=>{}});
184
- assert.equal(result.code,'timeout');assert.ok(Date.now()-started<4000);
185
- assert.ok(Date.now()-started>=1200,'leader close must not cancel group escalation');
186
+ assert.equal(result.code,'timeout');assert.ok(Date.now()-started<8000);
187
+ assert.ok(Date.now()-started>=2400,'leader close must not cancel group escalation');
186
188
  assert.ok(Number.isInteger(descendant));
187
189
  const gone=()=>{try{process.kill(descendant,0);return false;}catch(error){return error.code==='ESRCH';}};
188
190
  for(const deadline=Date.now()+3000;!gone()&&Date.now()<deadline;)await new Promise(resolve=>setTimeout(resolve,25));
@@ -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
+ });