@aibyzero/cm-workflow 0.16.9 → 0.17.1

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 (165) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +18 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +16 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/cm-control-policy-v2.md +331 -0
  9. package/docs/execution-optimizations.md +1 -1
  10. package/docs/external-models.md +3 -3
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/human-correction.md +5 -5
  13. package/docs/installation.md +1 -1
  14. package/docs/js-workflow-control.md +104 -85
  15. package/docs/next-steps.md +11 -0
  16. package/docs/untested-branches.md +2 -3
  17. package/docs/user-guide.md +3 -3
  18. package/package.json +1 -1
  19. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  22. package/runtime/js/cm-ai/control-policy.mjs +112 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  24. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  26. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  27. package/runtime/js/cm-ai/host-check.mjs +3 -1
  28. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  29. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  31. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  32. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  33. package/runtime/js/cm-ai/host-session.mjs +41 -8
  34. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  35. package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
  36. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  37. package/runtime/js/cm-ai/host.mjs +1 -2
  38. package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
  39. package/runtime/js/cm-ai/review-package.mjs +16 -4
  40. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  41. package/runtime/js/cm-ai/task-runner.mjs +41 -101
  42. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  43. package/runtime/js/cm-prd/review-host.mjs +1 -1
  44. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  45. package/runtime/js/cm-prd/summary.mjs +27 -12
  46. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  47. package/runtime/js/notify-send.mjs +15 -14
  48. package/runtime/js/notify.mjs +27 -4
  49. package/runtime/js/policy-binding-compat.mjs +2 -1
  50. package/runtime/review.md +61 -7
  51. package/runtime/task-gates.md +107 -9
  52. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  53. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  54. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  55. package/scripts/cm-ai-batch-drive.mjs +50 -31
  56. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  57. package/scripts/cm-ai-batch-host.mjs +39 -20
  58. package/scripts/cm-ai-batch-host.test.mjs +83 -47
  59. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  60. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  61. package/scripts/cm-ai-batch-run.mjs +46 -14
  62. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  63. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  64. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  65. package/scripts/cm-ai-control-policy.test.mjs +192 -0
  66. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  67. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  68. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  69. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  70. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  71. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  72. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
  73. package/scripts/cm-ai-drive.mjs +96 -54
  74. package/scripts/cm-ai-drive.test.mjs +46 -87
  75. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  77. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  78. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  79. package/scripts/cm-ai-host-fixture.mjs +47 -16
  80. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  81. package/scripts/cm-ai-host.mjs +103 -93
  82. package/scripts/cm-ai-host.test.mjs +34 -18
  83. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  84. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  85. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  86. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  87. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  88. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  89. package/scripts/cm-ai-progress.test.mjs +10 -8
  90. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  91. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  92. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  93. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  94. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  95. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  96. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  97. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  98. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  99. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  100. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  101. package/scripts/cm-ai-review-timeout.test.mjs +35 -128
  102. package/scripts/cm-ai-run.mjs +78 -24
  103. package/scripts/cm-ai-run.test.mjs +11 -38
  104. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  105. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  106. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  107. package/scripts/cm-ai-supersede.test.mjs +3 -10
  108. package/scripts/cm-blocked-reason.test.mjs +2 -3
  109. package/scripts/cm-capability-gate.test.mjs +33 -1
  110. package/scripts/cm-check-drive-files.mjs +1 -1
  111. package/scripts/cm-check-host.test.mjs +1 -1
  112. package/scripts/cm-check-runtime.sh +1 -1
  113. package/scripts/cm-claude-probe.test.mjs +26 -0
  114. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  115. package/scripts/cm-claude-worker.test.mjs +21 -3
  116. package/scripts/cm-controlled-correction.test.mjs +469 -0
  117. package/scripts/cm-drive-liveness.test.mjs +83 -0
  118. package/scripts/cm-external-batch-host.test.mjs +38 -17
  119. package/scripts/cm-external-model-host.test.mjs +1 -1
  120. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  121. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  122. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  123. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  124. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  125. package/scripts/cm-host-liveness.test.mjs +150 -0
  126. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  127. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  128. package/scripts/cm-host-review-authority.test.mjs +0 -31
  129. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  130. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  131. package/scripts/cm-notify-command.test.mjs +54 -18
  132. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  133. package/scripts/cm-notify.mjs +16 -4
  134. package/scripts/cm-notify.test.mjs +135 -29
  135. package/scripts/cm-patrol.test.mjs +3 -2
  136. package/scripts/cm-prd-drive.test.mjs +1 -1
  137. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  138. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  139. package/scripts/cm-prd-summary.test.mjs +31 -0
  140. package/scripts/cm-release-smoke.sh +2 -14
  141. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  142. package/scripts/cm-task-gate.mjs +368 -34
  143. package/scripts/cm-task-gate.py +2 -0
  144. package/scripts/cm-task-gate.test.mjs +252 -4
  145. package/scripts/cm-test-suite.mjs +109 -0
  146. package/scripts/cm-test-suite.test.mjs +162 -0
  147. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  148. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  149. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  150. package/scripts/policy-binding-compat.test.mjs +4 -0
  151. package/skills/cm-ai/SKILL.md +8 -6
  152. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  153. package/skills/cm-ai/references/N4-review.md +11 -21
  154. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  155. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  156. package/skills/cm-ai/references/js-host-modes.md +35 -14
  157. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  158. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  159. package/skills/cm-ai/references/js-host.md +98 -29
  160. package/skills/cm-fix/SKILL.md +12 -0
  161. package/skills/cm-init/references/js-host.md +1 -1
  162. package/skills/cm-prd/references/js-host.md +1 -1
  163. package/skills/cm-refactor/SKILL.md +12 -0
  164. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  165. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -1,3 +1,4 @@
1
+ import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
1
2
  import test from 'node:test';
2
3
  import assert from 'node:assert/strict';
3
4
  import fs from 'node:fs';
@@ -22,7 +23,13 @@ process.stdin.on('end',()=>{setTimeout(()=>{fs.appendFileSync(${JSON.stringify(s
22
23
  body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');process.exit(${exit});},${sleepMs});});`);
23
24
  fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script],...config}));
24
25
  const env={...process.env,CM_WORKFLOW_HOME:dir};
25
- const rows=()=>fs.existsSync(sent)?fs.readFileSync(sent,'utf8').trim().split('\n').map(line=>JSON.parse(line)):[];
26
+ const rows=()=>{
27
+ if(!fs.existsSync(sent))return [];
28
+ const contents=fs.readFileSync(sent,'utf8'),completeEnd=contents.lastIndexOf('\n')+1;
29
+ // appendFileSync may expose an empty file or an unfinished final record.
30
+ // Only complete JSONL records are consumable; malformed complete JSON fails.
31
+ return contents.slice(0,completeEnd).split('\n').slice(0,-1).map(line=>JSON.parse(line));
32
+ };
26
33
  const log=()=>fs.existsSync(path.join(dir,'notify.log'))?fs.readFileSync(path.join(dir,'notify.log'),'utf8'):'';
27
34
  const until=async(check,ms=8000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,25));return check();};
28
35
  return {dir,env,rows,log,until};
@@ -30,6 +37,16 @@ body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');p
30
37
  const fields=(key,over={})=>({key,event:'stuck',project:'/srv/work/demo-app',workflow:'cm-fix',runId:'run-1',
31
38
  task:'T-001',stage:'blocked',code:'checks_not_passed',nextAction:'核对 reason 后恢复原运行',...over});
32
39
 
40
+ test('fixture JSONL reader waits for complete records and rejects malformed complete JSON',t=>{
41
+ const h=home(t),file=path.join(h.dir,'sent.jsonl');
42
+ assert.deepEqual(h.rows(),[]);
43
+ fs.writeFileSync(file,'');assert.deepEqual(h.rows(),[]);
44
+ fs.writeFileSync(file,'{"marker":1');assert.deepEqual(h.rows(),[]);
45
+ fs.appendFileSync(file,'}\n{"marker":');assert.deepEqual(h.rows(),[{marker:1}]);
46
+ fs.appendFileSync(file,'2}\n');assert.deepEqual(h.rows(),[{marker:1},{marker:2}]);
47
+ fs.appendFileSync(file,'{"bad":}\n');assert.throws(()=>h.rows(),SyntaxError);
48
+ });
49
+
33
50
  test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME is explicit',async t=>{
34
51
  const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-empty-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
35
52
  assert.equal(readNotifyConfig({CM_WORKFLOW_HOME:dir}),null);
@@ -329,6 +346,78 @@ test('command failure, timeout and broken state never throw; they log one line w
329
346
  for(const h of [failing,slow,missing,broken])assert(!/demo-app|T-001|核对|run-1/.test(h.log()));
330
347
  });
331
348
 
349
+ // State and lock files are read bounded: a FIFO, a symlink (live or dangling)
350
+ // or an oversized file never blocks the host and never counts as valid state.
351
+ // FIFO cases run in a child with a hard deadline so a regression hangs the
352
+ // child, not the suite.
353
+ test('state and lock reads never block on a FIFO and refuse symlinks and oversized files',{skip:process.platform==='win32'},t=>{
354
+ const fifo=file=>{const made=spawnSync('mkfifo',[file]);assert.equal(made.status,0,`mkfifo ${file}`);};
355
+ const cases=[
356
+ ['state FIFO',h=>fifo(path.join(h.dir,'notify-state.json')),'state_invalid',true],
357
+ ['state symlink',h=>{fs.writeFileSync(path.join(h.dir,'real.json'),JSON.stringify({version:1,keys:{},sends:[]}));fs.symlinkSync(path.join(h.dir,'real.json'),path.join(h.dir,'notify-state.json'));},'state_invalid'],
358
+ ['state dangling symlink',h=>fs.symlinkSync(path.join(h.dir,'missing.json'),path.join(h.dir,'notify-state.json')),'state_invalid'],
359
+ ['state oversized',h=>fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:1,keys:{},sends:[],pad:'x'.repeat(300*1024)})),'state_invalid'],
360
+ ['lock FIFO',h=>fifo(path.join(h.dir,'notify-state.lock')),'state_busy',true],
361
+ ['lock symlink',h=>{fs.writeFileSync(path.join(h.dir,'real.lock'),JSON.stringify({pid:process.pid,at:Date.now()-60000,token:'old'}));fs.symlinkSync(path.join(h.dir,'real.lock'),path.join(h.dir,'notify-state.lock'));},'state_busy'],
362
+ ['lock dangling symlink',h=>fs.symlinkSync(path.join(h.dir,'missing.lock'),path.join(h.dir,'notify-state.lock')),'state_busy'],
363
+ ];
364
+ for(const [name,arrange,reason,inChild=false] of cases){
365
+ const h=home(t);arrange(h);const listing=()=>fs.readdirSync(h.dir).filter(name=>name!=='notify.log').sort(),before=listing();
366
+ let result;
367
+ if(inChild){
368
+ const child=spawnSync(process.execPath,['--input-type=module','-e',
369
+ `import {notify} from ${JSON.stringify(NOTIFY_URL)};process.stdout.write(JSON.stringify(notify(${JSON.stringify(fields('f'))},{now:${NOW}})));`],
370
+ {encoding:'utf8',timeout:5000,env:h.env});
371
+ assert.equal(child.signal,null,`${name}: bounded read must not block (child killed by ${child.signal})`);
372
+ assert.equal(child.status,0,`${name}: ${child.stderr}`);result=JSON.parse(child.stdout);
373
+ }else result=notify(fields('f'),{env:h.env,now:NOW});
374
+ assert.deepEqual(result,{sent:false,reason},name);
375
+ assert.equal(h.rows().length,0,name);
376
+ // Nothing but the log is written through or beside the refused entry.
377
+ assert.deepEqual(listing(),before,name);assert.match(h.log(),new RegExp(`skipped ${reason}`),name);
378
+ }
379
+ });
380
+
381
+ // Where O_NOFOLLOW is 0 (Windows), the open flags no longer refuse a symlink;
382
+ // only the lstat check before the open does. The child masks O_NOFOLLOW out of
383
+ // every open before the runtime loads (and proves the mask by opening a probe
384
+ // link that an unmasked open would refuse) and records every path opened, so
385
+ // the refusal is shown to happen before any open of the link: a build that
386
+ // first opens and only then notices the link goes red on every platform, not
387
+ // only in a Windows job. The link itself and its target are snapshotted so a
388
+ // same-name replacement or a rewritten target cannot hide behind a name list.
389
+ test('state and lock symlinks are refused before open when O_NOFOLLOW is masked (Windows semantics)',t=>{
390
+ const cases=[
391
+ ['state symlink','notify-state.json','real.json',JSON.stringify({version:1,keys:{},sends:[]}),'state_invalid'],
392
+ ['lock symlink','notify-state.lock','real.lock',JSON.stringify({pid:process.pid,at:Date.now()-60000,token:'old'}),'state_busy'],
393
+ ];
394
+ for(const [name,linkName,targetName,targetBody,reason] of cases){
395
+ const h=home(t),link=path.join(h.dir,linkName),target=path.join(h.dir,targetName);
396
+ try{fs.writeFileSync(target,targetBody);fs.symlinkSync(target,link);fs.writeFileSync(path.join(h.dir,'probe.txt'),'probe');fs.symlinkSync(path.join(h.dir,'probe.txt'),path.join(h.dir,'probe.link'));}
397
+ catch(error){if(process.platform==='win32'&&error.code==='EPERM'){t.skip('symlink creation needs a privilege on this Windows host');return;}throw error;}
398
+ const snapshot=()=>({names:fs.readdirSync(h.dir).filter(name=>name!=='notify.log').sort(),isLink:fs.lstatSync(link).isSymbolicLink(),points:fs.readlinkSync(link),target:fs.readFileSync(target,'utf8')});
399
+ const before=snapshot();
400
+ const child=spawnSync(process.execPath,['--input-type=module','-e',
401
+ `import fs from 'node:fs';import path from 'node:path';const open=fs.openSync,opened=[];
402
+ fs.openSync=(file,flags,...rest)=>{opened.push(path.resolve(String(file)));return open(file,typeof flags==='number'?flags&~fs.constants.O_NOFOLLOW:flags,...rest);};
403
+ const probe=fs.openSync(${JSON.stringify(path.join(h.dir,'probe.link'))},fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
404
+ const followed=fs.readFileSync(probe,'utf8');fs.closeSync(probe);
405
+ const {notify}=await import(${JSON.stringify(NOTIFY_URL)});
406
+ const result=notify(${JSON.stringify(fields('f'))},{now:${NOW}});
407
+ process.stdout.write(JSON.stringify({followed,result,opened}));`],
408
+ {encoding:'utf8',timeout:5000,env:h.env});
409
+ assert.equal(child.status,0,`${name}: ${child.stderr}`);
410
+ const {followed,result,opened}=JSON.parse(child.stdout);
411
+ assert.equal(followed,'probe',`${name}: the masked open must follow links like a Windows open`);
412
+ assert.ok(opened.includes(path.join(h.dir,'probe.link')),`${name}: the open recorder must see the probe open`);
413
+ assert.ok(!opened.includes(link),`${name}: the link must be refused before any open of it (opened: ${opened.join(', ')})`);
414
+ assert.ok(!opened.includes(target),`${name}: the link target must never be opened`);
415
+ assert.deepEqual(result,{sent:false,reason},name);
416
+ assert.equal(h.rows().length,0,name);
417
+ assert.deepEqual(snapshot(),before,name);assert.match(h.log(),new RegExp(`skipped ${reason}`),name);
418
+ }
419
+ });
420
+
332
421
  // Lock contention never waits; only a provably stale lock is reclaimed, and
333
422
  // a live lock is never removed.
334
423
  test('lock: a live lock skips at once and is kept; a stale lock is reclaimed safely',async t=>{
@@ -558,80 +647,97 @@ test('checkWaitMinutes is validated like waitMinutes',t=>{
558
647
  // session sends no next operation for idleMinutes, one notice says so. A last
559
648
  // result that waits on a person says "在等你" instead. Any next operation or
560
649
  // session end clears it; status polls are not progress.
561
- function idleHost(h){
650
+ function idleHost(h,{startupDelayMs=0}={}){
562
651
  const script=path.join(h.dir,'cm-prd-host.mjs');
563
652
  fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
564
653
  const host={handle:async request=>{
565
654
  if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
566
655
  if(['status','fix_status'].includes(request.operation))return {stage:'status_only',doneAt:Date.now()};
567
656
  return request.answer;}};
657
+ if(${startupDelayMs})await new Promise(resolve=>setTimeout(resolve,${startupDelayMs}));
568
658
  await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
569
659
  const env={...h.env};delete env.NODE_TEST_CONTEXT;
570
660
  // steps: [delayMs, request object | raw line string | null to end stdin];
571
661
  // delay 'reply:<id>' waits until that requestId has been answered instead.
572
- return async steps=>{
662
+ const history=[];
663
+ const run=async steps=>{
573
664
  const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
574
- let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
665
+ const trace=hostDiagnostic(child);
666
+ let stdout='',buffer='';child.stdout.on('data',chunk=>{
667
+ stdout+=chunk;buffer+=chunk;let end;
668
+ while((end=buffer.indexOf('\n'))!==-1){
669
+ const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
670
+ try{trace.receive(JSON.parse(line));}catch{/* Raw lines are never retained in diagnostics. */}
671
+ }
672
+ });
575
673
  const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
576
674
  const replied=id=>stdout.includes(`"requestId":"${id}"`);
577
675
  for(const [delay,request] of steps){
578
676
  if(typeof delay==='string'){
579
677
  const id=delay.slice(6),deadline=Date.now()+15000;
580
- while(!replied(id)){if(Date.now()>deadline){child.kill();throw new Error(`no reply for ${id}`);}await new Promise(resolve=>setTimeout(resolve,10));}
678
+ while(!replied(id)){if(Date.now()>deadline){child.kill();throw trace.attach(new Error('host fixture reply timeout'));}await new Promise(resolve=>setTimeout(resolve,10));}
581
679
  }
582
680
  else await new Promise(resolve=>setTimeout(resolve,delay));
583
- if(request===null){child.stdin.end();break;}
681
+ if(request===null){trace.send({operation:'eof'});child.stdin.end();break;}
682
+ if(request!==undefined)trace.send(typeof request==='string'?{}:request);
584
683
  if(request!==undefined)child.stdin.write((typeof request==='string'?request:JSON.stringify(request))+'\n');
585
684
  }
586
685
  const started=Date.now(),code=await exited;
587
- return {code,stdout,exitMs:Date.now()-started};
686
+ const diagnostic=trace.snapshot();history.push(diagnostic);if(history.length>8)history.shift();
687
+ return {code,stdout,exitMs:Date.now()-started,diagnostic};
588
688
  };
689
+ run.diagnostics=()=>history;return run;
589
690
  }
590
691
  const op=(n,answer,extra={})=>({requestId:`r${n}`,operation:'advance',answer,...extra});
591
692
 
592
693
  test('host session idle after a finished step notifies once: 疑似空转 for progress, 在等你 for a person',async t=>{
593
- const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
594
- const progress=await run([[0,op(1,{stage:'requirements_analysis',runId:'prd-1'})],[900,null]]);
694
+ const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h);
695
+ const progress=await run([[0,op(1,{stage:'requirements_analysis',runId:'prd-1'})],[2700,null]]);
595
696
  assert.equal(progress.code,0);
596
697
  assert(await h.until(()=>h.rows().length===1));
597
698
  const [idle]=h.rows();
598
699
  assert.equal(idle.title,'CM cm-prd 疑似空转 · '+path.basename(process.cwd()));
599
700
  assert.equal(idle.stdin.event,'idle');assert.equal(idle.stdin.code,'no_next_step');
600
701
  assert.equal(idle.stdin.runId,'prd-1');assert.equal(idle.stdin.stage,'requirements_analysis');
601
- const waiting=home(t,{config:{idleMinutes:0.003}});
602
- const review=await idleHost(waiting)([[0,op(1,{stage:'awaiting_user',runId:'prd-2'})],[900,null]]);
702
+ const waiting=home(t,{config:{idleMinutes:0.009}});
703
+ const review=await idleHost(waiting)([[0,op(1,{stage:'awaiting_user',runId:'prd-2'})],[2700,null]]);
603
704
  assert.equal(review.code,0);
604
705
  assert(await waiting.until(()=>waiting.rows().length===1));
605
706
  assert.equal(waiting.rows()[0].title,'CM cm-prd 在等你 · '+path.basename(process.cwd()));
606
707
  assert.equal(waiting.rows()[0].stdin.event,'idle_waiting');assert.equal(waiting.rows()[0].stdin.code,'waiting_for_you');
607
- await new Promise(resolve=>setTimeout(resolve,300));
708
+ await new Promise(resolve=>setTimeout(resolve,900));
608
709
  assert.equal(h.rows().length,1);assert.equal(waiting.rows().length,1);
609
710
  });
610
711
 
611
- test('host session idle: next step, in-flight step and session end clear it; status polls do not',async t=>{
612
- const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
712
+ for(const startupDelayMs of [0,750])test(`host session idle: next step, in-flight step and session end clear it; status polls do not (startup ${startupDelayMs}ms)`,async t=>{
713
+ const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h,{startupDelayMs});
714
+ // Sending is not completion: a slow startup can otherwise batch the next
715
+ // line before the first reply, exercising host_busy instead of idle clearing.
613
716
  // Steady progress: each next operation arrives before the threshold.
614
- const steady=[];for(let n=1;n<=6;n++)steady.push([n===1?0:60,op(n,{stage:'requirements_analysis'})]);
615
- assert.equal((await run([...steady,[60,null]])).code,0);
717
+ const steady=[];for(let n=1;n<=6;n++){
718
+ if(n>1)steady.push([`reply:r${n-1}`,undefined]);
719
+ steady.push([n===1?0:180,op(n,{stage:'requirements_analysis'})]);
720
+ }
721
+ assert.equal((await run([...steady,['reply:r6',undefined],[180,null]])).code,0);
616
722
  // A long in-flight operation is not idleness; ending right after its reply clears the timer.
617
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
723
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
618
724
  // A slow next operation: its arrival clears the timer armed by the previous reply.
619
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,op(2,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
725
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,op(2,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
620
726
  // A cancel reply while another operation is still in flight does not arm it.
621
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[60,{requestId:'c1',operation:'cancel'}],[900,null]])).code,0);
727
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[180,{requestId:'c1',operation:'cancel'}],[2700,null]])).code,0);
622
728
  // Driver shape: EOF right after the reply arrived.
623
729
  assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',null]])).code,0);
624
730
  // A line the host rejects (not JSON, unknown operation) is still the session's next step.
625
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,'not json'],[900,null]])).code,0);
626
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'x',operation:'no_such_op'}],[900,null]])).code,0);
627
- await new Promise(resolve=>setTimeout(resolve,500));
628
- assert.equal(h.rows().length,0,h.log());
731
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,'not json'],[2700,null]])).code,0);
732
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,{requestId:'x',operation:'no_such_op'}],[2700,null]])).code,0);
733
+ await new Promise(resolve=>setTimeout(resolve,1500));
734
+ assert.equal(h.rows().length,0,JSON.stringify(run.diagnostics()));
629
735
  // Polls (status via the control path, fix_status via the normal path) neither
630
736
  // hold the timer off nor replace the last real step's result.
631
737
  for(const poll of ['status','fix_status']){
632
- const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})]];
633
- for(let n=0;n<12;n++)polls.push([60,{requestId:`s${n}`,operation:poll}]);
634
- assert.equal((await run([...polls,[60,null]])).code,0);
738
+ const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})],['reply:r1',undefined]];
739
+ for(let n=0;n<12;n++)polls.push([180,{requestId:`s${n}`,operation:poll}]);
740
+ assert.equal((await run([...polls,[180,null]])).code,0);
635
741
  assert(await h.until(()=>h.rows().some(row=>row.stdin.runId===`run-${poll}`)));
636
742
  const row=h.rows().find(row=>row.stdin.runId===`run-${poll}`);
637
743
  assert.equal(row.stdin.event,'idle');assert.equal(row.stdin.stage,'requirements_analysis');
@@ -642,8 +748,8 @@ test('host session idle: next step, in-flight step and session end clear it; sta
642
748
  // A poll that is still running when the deadline passes holds the notice; it
643
749
  // goes out right after the poll replies, not during it.
644
750
  test('host session idle: a slow status in flight holds the notice until it replies',async t=>{
645
- const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
646
- const result=await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'s1',operation:'status',slowMs:700}],['reply:s1',undefined],[400,null]]);
751
+ const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h);
752
+ const result=await run([[0,op(1,{stage:'requirements_analysis'})],[180,{requestId:'s1',operation:'status',slowMs:2100}],['reply:s1',undefined],[1200,null]]);
647
753
  assert.equal(result.code,0);
648
754
  const doneAt=JSON.parse(result.stdout.split('\n').find(line=>line.includes('"requestId":"s1"'))).result.doneAt;
649
755
  assert(await h.until(()=>h.rows().length===1));
@@ -653,7 +759,7 @@ test('host session idle: a slow status in flight holds the notice until it repli
653
759
 
654
760
  // Tool-bridge sessions end with host_close from the driver: exit 0, no notice.
655
761
  test('host session idle: host_close ends the session cleanly without a notice',async t=>{
656
- const h=home(t,{config:{idleMinutes:0.003}});
762
+ const h=home(t,{config:{idleMinutes:0.009}});
657
763
  const script=path.join(h.dir,'cm-demo-host.mjs');
658
764
  fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
659
765
  import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
@@ -125,8 +125,9 @@ test('patrol: a single dead host names its run and workflow; rate-limited or off
125
125
  });
126
126
 
127
127
  test('--report prints the summary and neither notifies nor removes anything',t=>{
128
- const h=home(t),gone=gonePid();
129
- h.write(KEYS[1],{pid:gone});
128
+ const h=home(t),gone=gonePid(),now=Date.now();
129
+ // The CLI uses the real clock; this fixture must remain inside the unchanged TTL.
130
+ h.write(KEYS[1],{pid:gone,startedAt:new Date(now-3600000).toISOString(),at:new Date(now-600000).toISOString()});
130
131
  const run=spawnSync(process.execPath,[PATROL,'--report'],{encoding:'utf8',env:{...h.env,NODE_TEST_CONTEXT:undefined}});
131
132
  assert.equal(run.status,0,run.stderr);
132
133
  const summary=JSON.parse(run.stdout);
@@ -166,7 +166,7 @@ test('real host unknown call resumes with its original callId and requestDigest'
166
166
  if(row.type==='host_ready'){
167
167
  hostSession=row.sessionId;host.stdin.write(JSON.stringify({requestId:'one',operation:'start',text:'Analyze'})+'\n');
168
168
  }else if(row.type==='host_request'){
169
- pending=row;host.stdin.write(JSON.stringify({type:'host_close',sessionId:hostSession})+'\n');break;
169
+ pending=row;host.stdin.write(JSON.stringify({type:'host_close',sessionId:hostSession,force:true})+'\n');break;
170
170
  }
171
171
  }
172
172
  assert.ok(pending,diagnostics);host.stdin.end();await closed;
@@ -300,3 +300,18 @@ test('saving after an unchanged feature split preserves pending revised features
300
300
  const f=await regenerate(await fixture(t));f.save();f.dispose(await f.review('split','2.second'));
301
301
  assert.equal(f.save().status,'draft_saved');await finish(f);assert.doesNotThrow(()=>f.host.validateCurrent());
302
302
  });
303
+
304
+ // 2026-10-12 交叉审查 P2:历史 feature 带自检修订记录时,摘要还会经 inspectPrdSplitDesign 再查同一旧拆分回执。
305
+ test('historical feature with a self-check revision is registered after a later approved change; current stays strict',async t=>{
306
+ const f=await regenerate(await fixture(t));await finish(f);
307
+ assert.doesNotThrow(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}));
308
+ fs.appendFileSync(path.join(f.specs,'1.guide/requirements.md'),'\nLater approved change');
309
+ const evidence=inspectPrdSummaryEvidence(f.specs,{currentFeatures:['2.second']});
310
+ const guide=evidence.features.find(item=>item.directory==='1.guide');
311
+ assert.equal(guide.historical,true);assert.equal(guide.reviews.split.archive,'unavailable');
312
+ assert.match(guide.reviews.split.reason,/^prd_review_artifact_changed; self_check_revision:\S+$/);
313
+ assert.ok(evidence.evidenceFiles.some(item=>item.path==='.reviews/prd-guide-self-check-revision.json'));
314
+ assert.equal(evidence.features.find(item=>item.directory==='2.second').reviews.split.gate.outcome,'completed');
315
+ assert.throws(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}),{code:'prd_review_artifact_changed'});
316
+ assert.throws(()=>inspectPrdSummaryEvidence(f.specs),{code:'prd_review_artifact_changed'});
317
+ });
@@ -49,7 +49,7 @@ async function client(t,f){
49
49
  const ready=await wait(m=>m.type==='host_ready');
50
50
  return {wait,send,requests,request:(operation,fields={})=>{const requestId=`request-${++seq}`;
51
51
  const reply=wait(m=>m.requestId===requestId);send({requestId,operation,...fields});return reply;},
52
- close:async()=>{send({type:'host_close',sessionId:ready.sessionId});assert.equal((await closed)[0],0,stderr);},
52
+ close:async({force=false}={})=>{send({type:'host_close',sessionId:ready.sessionId,...(force?{force:true}:{})});assert.equal((await closed)[0],0,stderr);},
53
53
  result:(call,result)=>send({type:'host_result',sessionId:ready.sessionId,callId:call.callId,requestDigest:call.requestDigest,result})};
54
54
  }
55
55
  function blocked(reply,reason){
@@ -59,7 +59,8 @@ function blocked(reply,reason){
59
59
  async function unknownSummary(t,f){
60
60
  const c=await client(t,f),pending=c.request('prepare_summary');
61
61
  const call=await c.wait(m=>m.type==='host_request');assert.equal(call.kind,'prd_summary');
62
- await c.close();assert.equal((await pending).error.code,'host_request_failed');return call;
62
+ // This fixture intentionally interrupts the unanswered summary; ordinary closes remain protected.
63
+ await c.close({force:true});assert.equal((await pending).error.code,'host_request_failed');return call;
63
64
  }
64
65
  const abandon=call=>({callId:call.payload.recovery.callId,requestDigest:call.payload.recovery.requestDigest,
65
66
  abandon:true,evidence:'Synthetic original call unavailable; explicit discard reference'});
@@ -94,7 +95,8 @@ test('unknown summary exposes session reasons, abandon restores before and permi
94
95
  const retry=c.request('prepare_summary'),fresh=await c.wait(m=>m.type==='host_request');
95
96
  assert.equal(fresh.kind,'prd_summary');assert.notEqual(fresh.payload.recovery.callId,resolution.callId);
96
97
  assert.deepEqual(fresh.payload.evidence.currentFeatures,['1.guide']);
97
- await c.close();await retry;
98
+ // The fresh dispatch is deliberately left unanswered to exercise its interrupted history.
99
+ await c.close({force:true});await retry;
98
100
  });
99
101
 
100
102
  for(const mode of ['summary','analysis','change'])test(`cancel clears pending ${mode} and stays terminal across restart`,{timeout:FIXTURE_TIMEOUT_MS},async t=>{
@@ -229,3 +229,34 @@ for(const extra of ['none','same-feature','other-feature'])test(`failed-check me
229
229
  }
230
230
  evidenceFiles.forEach((file,i)=>assert.deepEqual(fs.readFileSync(file),before[i]));
231
231
  });
232
+
233
+ // 2026-10-12 AI潮 dogfood:历史 feature 的拆分回执之后,需求经 --change 正常修改过;新建 feature 的
234
+ // prepare_summary 在历史回执闸门处直接抛出 prd_review_artifact_changed,整批无法发布。
235
+ test('historical receipt artifact changed by a later revision is a note; current and unscoped drift stay strict',async t=>{
236
+ const {specs}=fixture(t);
237
+ fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\n- [ ] [AC-002] Later approved change');
238
+ const evidence=inspectPrdSummaryEvidence(specs,currentScope);
239
+ const split=evidence.features[0].reviews.split;
240
+ assert.equal(evidence.features[0].historical,true);
241
+ assert.equal(split.gate.outcome,'unavailable');assert.equal(split.archive,'unavailable');
242
+ assert.match(split.reason,/^prd_review_artifact_changed$/);
243
+ assert.equal(evidence.features[1].reviews.split.gate.outcome,'completed');
244
+ const summary=await summaryOwner()(specs,currentScope);
245
+ assert.equal(summary.readyForAwaitingReview,true);assert.deepEqual(summary.blockers,[]);
246
+ assert.match(summary.notes.join('\n'),/历史 feature 1\.guide:split 审查归档不可用,已登记未重审(prd_review_artifact_changed)/);
247
+ assert.doesNotMatch(summary.notes.join('\n'),/无处置回执|prd_summary_receipt_missing/);
248
+ assert.equal(publishPrdAwaitingReview({specs,summary,writeEnabled:true}).status,'awaiting_review');
249
+ const status=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8'));
250
+ assert.deepEqual(status.features,['1.guide','2.appendix']);assert.deepEqual(status.specFiles,evidence.specFiles);
251
+ assert.throws(()=>inspectPrdSummaryEvidence(specs),{code:'prd_review_artifact_changed'});
252
+ assert.throws(()=>inspectPrdSummaryEvidence(specs,{currentFeatures:['1.guide']}),{code:'prd_review_artifact_changed'});
253
+ fs.appendFileSync(path.join(specs,'2.appendix/design.md'),'\nUnreviewed current edit');
254
+ assert.throws(()=>inspectPrdSummaryEvidence(specs,currentScope),{code:'prd_review_artifact_changed'});
255
+ });
256
+ test('historical gate failure still rejects publication when history changes after preparation',async t=>{
257
+ const {specs}=fixture(t);
258
+ fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nLater approved change');
259
+ const summary=await summaryOwner()(specs,currentScope);assert.equal(summary.readyForAwaitingReview,true);
260
+ fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nAnother edit after preparation');
261
+ assert.throws(()=>publishPrdAwaitingReview({specs,summary,writeEnabled:true}),/prd_summary_inputs_changed/);
262
+ });
@@ -47,21 +47,9 @@ for candidate in python3 python; do
47
47
  done
48
48
  [ -n "$PYTHON_BIN" ] || blocked "Python 3.9+ not found"
49
49
 
50
- # CI 覆盖不到的那一批:它们要启动 Codex 沙箱,而在 GitHub 托管机器上 bubblewrap
51
- # 建不了网络隔离(bwrap: loopback: Failed RTM_NEWADDR),装上 codex 也没用。
52
- # 这个脚本上面已经要求本机装了 codex,所以这里是它们唯一稳定的落点——发版必过。
53
- # 名单要和 .github/workflows/ci.yml 的 js-tests 排除名单保持一致。
50
+ # Shared with the CI partition; contributors can run this group without BYZ or installation.
54
51
  printf '%s\n' '==> Running the Codex-sandbox tests that CI cannot host'
55
- ( cd "$ROOT" && node --test \
56
- scripts/cm-ai-batch-host.test.mjs \
57
- scripts/cm-ai-bootstrap.test.mjs \
58
- scripts/cm-ai-host.test.mjs \
59
- scripts/cm-ai-host-cli-workflow.test.mjs \
60
- scripts/cm-ai-host-protected.test.mjs \
61
- scripts/cm-ai-multi-root.test.mjs \
62
- scripts/cm-ai-nested-execution.test.mjs \
63
- scripts/cm-fix-protected-edits.test.mjs \
64
- scripts/cm-host-check.test.mjs )
52
+ node "$ROOT/scripts/cm-test-suite.mjs" run native
65
53
 
66
54
  printf '%s\n' '==> Validating the public Pi/BYZ package manifest'
67
55
  "$PYTHON_BIN" "$ROOT/scripts/validate-public-repo.py"
@@ -6,16 +6,17 @@ import path from 'node:path';
6
6
  import {createHash} from 'node:crypto';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {spawnSync} from 'node:child_process';
9
- import {checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
9
+ import {captureBaseline,checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
10
10
  prepareMarkDone,verifyMarkDonePlan} from './cm-task-gate.mjs';
11
11
 
12
12
  const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
13
13
  function fixture(t){
14
14
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-human-correction-')));
15
15
  t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
- const reviewsDir=path.join(root,'.reviews');fs.mkdirSync(reviewsDir);
16
+ const reviewsDir=path.join(root,'specs','.reviews');fs.mkdirSync(reviewsDir,{recursive:true});
17
17
  fs.mkdirSync(path.join(root,'src'));const code=path.join(root,'src/example.ts');fs.writeFileSync(code,'old');
18
- const tasks=path.join(root,'tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
18
+ const tasks=path.join(root,'specs','tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
19
+ captureBaseline({projectRoot:root,reviewsDir,feature:'login',task:'T-001'});
19
20
  const payload=attempt=>({schema_version:1,task_id:'T-001',attempt,status:'ready_for_review',changed_files:['src/example.ts'],
20
21
  implementation_sha256:implementationSha256(root,['src/example.ts']),
21
22
  verification:[{command:'fixture',status:'passed',evidence:'synthetic fixture'}],
@@ -27,9 +28,9 @@ function fixture(t){
27
28
  fs.writeFileSync(handoff,JSON.stringify(payload(attempt)));review(file,handoff,attempt,verdict);history.push(handoff,file);
28
29
  }
29
30
  const original=history.map(sha);fs.writeFileSync(code,'fixed');
30
- const draft=path.join(root,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
+ const draft=path.join(reviewsDir,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
32
  const selectors={handoff:draft,reviewsDir,feature:'login',task:'T-001',projectRoot:root,
32
- humanAuthorized:true,reason:'Human approved exact selector correction after original blocked round 2.'};
33
+ reason:'Correct exact selector after original blocked round 2.'};
33
34
  const prepare=()=>prepareHumanCorrection(selectors);
34
35
  const finish=(record,verdict='approved')=>{
35
36
  const selected={...selectors,...record,tasksPath:tasks};
@@ -39,6 +40,36 @@ function fixture(t){
39
40
  return {root,reviewsDir,code,tasks,draft,history,original,selectors,review,prepare,finish};
40
41
  }
41
42
 
43
+ test('library default human correction preserves results without an editing baseline',t=>{
44
+ const f=fixture(t);fs.unlinkSync(path.join(f.reviewsDir,'login-T-001-baseline.json'));
45
+ const record=f.prepare(),selected={...f.selectors,...record};
46
+ assert.equal(JSON.stringify(checkN4(selected)),JSON.stringify({gate:'n4',task:'T-001',attempt:2,
47
+ outcome:'ready_for_review',content_bound:true,handoff_sha256:sha(record.handoff),correction_sha256:record.correction_sha256}));
48
+ const done=f.finish(record);
49
+ assert.equal(JSON.stringify(checkN5(done)),JSON.stringify({gate:'n5',task:'T-001',attempt:2,
50
+ outcome:'approved',review:record.review,content_bound:true,correction_sha256:record.correction_sha256}));
51
+ const plan=prepareMarkDone(done);assert.equal(plan.evidence.length,8);
52
+ assert.deepEqual(verifyMarkDonePlan(done,plan.planDigest),{outcome:'matched',planDigest:plan.planDigest});
53
+ assert.deepEqual(f.history.map(sha),f.original);
54
+ });
55
+
56
+ test('human correction CLI and internal opt-in still require an editing baseline',t=>{
57
+ const f=fixture(t);fs.unlinkSync(path.join(f.reviewsDir,'login-T-001-baseline.json'));
58
+ const record=f.prepare(),selected={...f.selectors,...record};
59
+ assert.throws(()=>checkN4({...selected,inventory:'required'}),/missing editing baseline/);
60
+ const script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
61
+ const cli=command=>spawnSync(process.execPath,[script,command,'--handoff',record.handoff,
62
+ '--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,
63
+ '--correction',record.correction,...(command==='prepare-mark-done'?['--tasks',f.tasks]:[])],{encoding:'utf8'});
64
+ const n4=cli('check-n4');assert.equal(n4.status,1);assert.match(n4.stderr,/missing editing baseline/);
65
+ const done=f.finish(record);
66
+ assert.throws(()=>checkN5({...done,inventory:'required'}),/missing editing baseline/);
67
+ for(const command of ['check-n5','prepare-mark-done']){
68
+ const result=cli(command);assert.equal(result.status,1);assert.match(result.stderr,/missing editing baseline/);
69
+ }
70
+ assert.deepEqual(f.history.map(sha),f.original);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
71
+ });
72
+
42
73
  test('one-shot human correction retains blocked history and completes through the existing locked adapter',t=>{
43
74
  const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
44
75
  assert.equal(checkN4(selected).outcome,'ready_for_review');
@@ -54,20 +85,19 @@ test('one-shot human correction retains blocked history and completes through th
54
85
  assert.throws(()=>checkN5({...done,handoff:f.history[2],correction:null}),/implementation content changed/);
55
86
  });
56
87
 
57
- test('correction authorization, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
88
+ test('correction reason, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
58
89
  const f=fixture(t);
59
- assert.throws(()=>prepareHumanCorrection({...f.selectors,humanAuthorized:false}),/authorization/);
60
90
  assert.throws(()=>prepareHumanCorrection({...f.selectors,reason:''}),/reason/);
61
91
  const draft=JSON.parse(fs.readFileSync(f.draft));draft.evidence=['unbound application'];fs.writeFileSync(f.draft,JSON.stringify(draft));
62
92
  assert.throws(()=>prepareHumanCorrection({...f.selectors,allowLegacyUnbound:true}),/Learning/);
63
- assert.equal(fs.readdirSync(f.reviewsDir).length,4);
93
+ assert.equal(fs.readdirSync(f.reviewsDir).length,6);
64
94
  draft.evidence=['learning: no_relevant_lesson','learning: retrospective no_new_lesson'];draft.changed_files=['src/new.ts'];
65
95
  fs.writeFileSync(path.join(f.root,'src/new.ts'),'new');draft.implementation_sha256=implementationSha256(f.root,draft.changed_files);
66
96
  fs.writeFileSync(f.draft,JSON.stringify(draft));assert.throws(()=>f.prepare(),/full original/);
67
97
  f.review(f.history[3],f.history[2],2,'approved');assert.throws(()=>f.prepare(),/blocked round 2/);
68
98
  });
69
99
 
70
- test('original evidence, correction handoff, implementation and authorization record drift invalidate approval',t=>{
100
+ test('original evidence, correction handoff, implementation and source record drift invalidate approval',t=>{
71
101
  const f=fixture(t),record=f.prepare(),done=f.finish(record),plan=prepareMarkDone(done);
72
102
  for(const file of [...f.history,record.correction,record.handoff,record.review,done.receipt??path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json'),f.code]){
73
103
  const bytes=fs.readFileSync(file);fs.appendFileSync(file,'\nchanged');
@@ -87,13 +117,13 @@ test('blocked correction review is sealed once and cannot be replaced by a new a
87
117
  assert.throws(()=>f.prepare(),/already exists/);
88
118
  });
89
119
 
90
- test('old review or self-degraded review cannot authorize a correction',t=>{
120
+ test('old review or self-degraded review does not meet correction declaration and binding requirements',t=>{
91
121
  const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
92
122
  f.review(record.review,record.handoff,2,'approved');
93
- assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
123
+ assert.throws(()=>publishHumanCorrectionReview(selected),/independent: true.*bound/);
94
124
  f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
95
125
  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:'));
96
- assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
126
+ assert.throws(()=>publishHumanCorrectionReview(selected),/independent: true.*bound/);
97
127
  });
98
128
 
99
129
  test('correction file identities reject symlinks, hardlinks, sibling selection and duplicate record fields',t=>{
@@ -108,10 +138,33 @@ test('correction file identities reject symlinks, hardlinks, sibling selection a
108
138
  assert.throws(()=>checkN4(selected),/non-symlink/);
109
139
  });
110
140
 
111
- test('CLI human correction refuses missing human authorization and exposes the fixed review record',t=>{
141
+ test('CLI correction works without an authorization flag and rejects the removed flag',t=>{
112
142
  const f=fixture(t),script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
113
- const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Explicit human correction'];
114
- const denied=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});assert.equal(denied.status,1);assert.match(denied.stderr,/authorization/);
115
- const result=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
143
+ const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Correct exact selector'];
144
+ const removed=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
145
+ assert.equal(removed.status,1);assert.match(removed.stderr,/invalid arguments/);
146
+ const result=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});
116
147
  assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).attempt,2);
117
148
  });
149
+
150
+
151
+ test('correction review declarations and candidate package bindings remain mandatory',t=>{
152
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
153
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
154
+ const original=fs.readFileSync(record.review,'utf8');
155
+ for(const [before,after] of [
156
+ ['independent: true','independent: yes'],
157
+ ['reviewer: codex-subagent','reviewer: arbitrary'],
158
+ ['handoff_sha256: '+sha(record.handoff),'handoff_sha256: '+'0'.repeat(64)],
159
+ ['correction_sha256: '+record.correction_sha256,'correction_sha256: '+'0'.repeat(64)],
160
+ ['verdict: approved','verdict: blocked'],
161
+ ]){
162
+ fs.writeFileSync(record.review,original.replace(before,after));
163
+ assert.throws(()=>publishHumanCorrectionReview(selected),undefined,before);
164
+ assert.equal(fs.existsSync(path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json')),false);
165
+ }
166
+ fs.writeFileSync(record.review,original);
167
+ publishHumanCorrectionReview(selected);
168
+ assert.equal(checkN5(selected).outcome,'approved');
169
+ assert.deepEqual(f.history.map(sha),f.original);
170
+ });