@aibyzero/cm-workflow 0.16.7 → 0.16.9

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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -26,7 +26,7 @@ after(()=>{
26
26
  const diagnosis={status:'diagnosed',rootCause:'Wrong value',affectedPaths:['value.mjs'],
27
27
  affectedModules:['value'],plan:'Correct value',crossLayer:false};
28
28
 
29
- async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,lesson=false}={}){
29
+ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,lesson=false,repairContent=null}={}){
30
30
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-abandon-')));
31
31
  t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
32
32
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');
@@ -52,14 +52,20 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
52
52
  const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
53
53
  onEvent({event:'thread.started',provider_thread:`fixture-review-${reviewMode==='first_lost_same_thread'?1:reviews}`});
54
54
  if(reviewMode==='lost'||['second_lost','second_lost_retry'].includes(reviewMode)&&reviews===2
55
- ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1)throw Error('Synthetic lost review result');
55
+ ||reviewMode==='second_lost_twice'&&[2,3].includes(reviews)
56
+ ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1
57
+ ||['rediagnosis_lost','rediagnosis_twice','rediagnosis_thrice','rediagnosis_context'].includes(reviewMode)
58
+ &&(reviews===2||['rediagnosis_twice','rediagnosis_thrice'].includes(reviewMode)&&reviews===3||reviewMode==='rediagnosis_thrice'&&reviews===4))
59
+ throw Error('Synthetic lost review result');
56
60
  for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
57
61
  {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
58
- const verdict=['changes_requested','second_lost'].includes(reviewMode)||reviewMode==='second_lost_retry'&&reviews===1
59
- ?'changes_requested':'approved';
62
+ const outsidePath=reviewMode==='rediagnosis_invalid'&&reviews===2;
63
+ const verdict=['changes_requested','second_lost'].includes(reviewMode)||['second_lost_retry','second_lost_twice'].includes(reviewMode)&&reviews===1
64
+ ||reviewMode?.startsWith('rediagnosis_')&&reviews===1||outsidePath?'changes_requested':'approved';
60
65
  return {status:'succeeded',value:{verdict,packageDigest:data.reviewPackage.packageDigest,
61
66
  examinedPaths:data.examinedPaths,
62
- findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:'value.mjs',message:'Revise value',evidence:'Fixture'}]:[],
67
+ findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:outsidePath?'not-in-package.mjs':'value.mjs',message:'Revise value',evidence:'Fixture'}]
68
+ :reviewMode==='rediagnosis_context'?[{id:'C1',severity:'P3',path:'existing.mjs',message:'Prior-round file still fine',evidence:'Fixture'}]:[],
63
69
  summary:'Synthetic review'}};
64
70
  }}):null;
65
71
  if(reviewHost)configuration.causeReview=reviewHost.reviewer;
@@ -67,14 +73,16 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
67
73
  let loseObservation=true,loseRevisionRepair=true;
68
74
  const bridge={async call(kind,payload){
69
75
  if(kind==='fix_diagnose'){
76
+ // Round 1 covers existing.mjs too; the rediagnosis narrows it away.
77
+ if(reviewMode==='rediagnosis_context'&&!payload.reviewFeedback)return {...diagnosis,affectedPaths:['existing.mjs','value.mjs'],crossLayer:true};
70
78
  if(observation&&payload.observationEvidence&&loseObservation){loseObservation=false;throw Error('Lost observation answer');}
71
79
  return crossLayer?{...diagnosis,crossLayer:true}:diagnosis;
72
80
  }
73
81
  if(kind==='fix_repair'){
74
- if(['changes_requested','second_lost','second_lost_retry'].includes(reviewMode)&&payload.identity.attempt===2&&loseRevisionRepair){
82
+ if(['changes_requested','second_lost','second_lost_retry','second_lost_twice'].includes(reviewMode)&&payload.identity.attempt===2&&loseRevisionRepair){
75
83
  loseRevisionRepair=false;throw Error('Lost revision repair answer');
76
84
  }
77
- fs.writeFileSync(path.join(cwd,'value.mjs'),payload.identity.attempt===2?'export const value=2; // revised\n':'export const value=2;\n');
85
+ fs.writeFileSync(path.join(cwd,'value.mjs'),repairContent??(payload.identity.attempt===2?'export const value=2; // revised\n':'export const value=2;\n'));
78
86
  return {outcome:'repaired'};
79
87
  }
80
88
  if(kind==='fix_retrospective')return (lesson===true||lesson==='revision'&&payload.identity.attempt===2)?{status:'lesson_candidate',candidates:[{classification:'memory_only',
@@ -97,7 +105,9 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
97
105
  owner=openFixExecution({...options,create:false},dependencies);
98
106
  };
99
107
  const reopen=()=>{owner.close();owner=openFixExecution({...options,create:false},dependencies);return owner;};
100
- return {cwd,specsRoot,identity,configuration,options,statePath,records,append,reopen,owner:()=>owner,reviewHost,reviews:()=>reviews};
108
+ // After a refused append left no open owner: restore the saved bytes and reopen.
109
+ const restore=bytes=>{owner?.close();fs.writeFileSync(statePath,bytes);owner=openFixExecution({...options,create:false},dependencies);return owner;};
110
+ return {cwd,specsRoot,identity,configuration,options,statePath,records,append,reopen,restore,owner:()=>owner,reviewHost,reviews:()=>reviews};
101
111
  }
102
112
 
103
113
  test('an unknown red test needs explicit authorization and reason, then redoes with distinct records and evidence',async t=>{
@@ -429,16 +439,25 @@ test('#15 a no-result cause review is abandoned once, audited, and retried on a
429
439
  assert.equal(f.owner().status().causeReview.providerThreadId,'fixture-review-2');
430
440
  });
431
441
 
432
- test('#15 a second no-result cause review exhausts the one-time budget without changing the store',async t=>{
442
+ test('#15 a third no-result cause review exhausts the round\'s two abandonments without changing the store',async t=>{
433
443
  const f=await fixture(t,{reviewMode:'lost',crossLayer:true});
434
444
  await f.owner().advance({authorized:true});await causeDecide(f);
435
445
  assert.equal((await f.owner().reviewCause()).stage,'unknown');
436
446
  f.owner().abandonReview({authorized:true,reason:'First reviewer stopped'});
437
447
  await causeDecide(f);
448
+ // V5: the round keeps a second abandonment, redispatched under fix-cause-retry-2-*.
449
+ const second=await f.owner().reviewCause();
450
+ assert.equal(second.stage,'unknown');assert.equal(second.reviewAbandonable,'cause_review');
451
+ const abandoned=f.owner().abandonReview({authorized:true,reason:'Second reviewer stopped'});
452
+ assert.equal(abandoned.stage,'cause_review_required');assert.equal(abandoned.causeReviewAbandonment2.providerThreadId,'fixture-review-2');
453
+ assert.deepEqual(f.records().filter(row=>/^fix-cause-abandoned/.test(row.id)).map(row=>row.id),['fix-cause-abandoned','fix-cause-abandoned-2']);
454
+ await causeDecide(f);
438
455
  const again=await f.owner().reviewCause();
456
+ assert(f.records().some(row=>row.id==='fix-cause-retry-2-registered'));
439
457
  assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
440
458
  const before=fs.readFileSync(f.statePath);
441
- assert.throws(()=>f.owner().abandonReview({authorized:true,reason:'Second reviewer stopped'}),{code:'fix_review_abandon_budget_exhausted'});
459
+ assert.throws(()=>f.owner().abandonReview({authorized:true,reason:'Third reviewer stopped'}),{code:'fix_review_abandon_budget_exhausted'});
460
+ assert.equal(f.reopen().status().reviewAbandonBudgetExhausted,true);
442
461
  assert.deepEqual(fs.readFileSync(f.statePath),before);
443
462
  });
444
463
 
@@ -490,6 +509,46 @@ test('#15 a no-result second-round final review is abandoned once and retried on
490
509
  assert.equal(f.reopen().status().stage,'revision_completion_gate_required');
491
510
  });
492
511
 
512
+ // V5 (F26): the second-round final review keeps two no-result abandonments;
513
+ // the second cycle runs under fix-revision-final-retry-2-* on a third thread.
514
+ test('V5 a twice-lost second-round final review is abandoned twice and retried on fresh threads',async t=>{
515
+ const f=await fixture(t,{reviewMode:'second_lost_twice'});
516
+ await toRevision(f);await completeRevisionRepair(f);
517
+ await f.owner().runRegression({authorized:true});await f.owner().retrospect();
518
+ assert.equal(f.owner().createHandoff().stage,'revision_final_review_required');
519
+ const decide=async()=>{const pkg=f.owner().finalReviewPackage();
520
+ await f.reviewHost.finalAuthority.hostDecisionProvider.decide({identity:f.owner().status().revision.nextIdentity,
521
+ packageDigest:pkg.packageDigest},new AbortController().signal);};
522
+ let beforeSecond=null,afterSecond=null;
523
+ for(const reason of ['First stopped','Second stopped']){
524
+ await decide();
525
+ const lost=await f.owner().reviewFinal();
526
+ assert.equal(lost.stage,'unknown');assert.equal(lost.reviewAbandonable,'revision_final_review');
527
+ if(reason==='Second stopped')beforeSecond=fs.readFileSync(f.statePath);
528
+ assert.equal(f.owner().abandonReview({authorized:true,reason}).stage,'revision_final_review_required');
529
+ }
530
+ afterSecond=fs.readFileSync(f.statePath);
531
+ // Replay refuses a second abandonment bound to the first cycle, and a duplicate one.
532
+ const second=f.records().find(row=>row.id==='fix-revision-final-abandoned-2').payload;
533
+ f.restore(beforeSecond);
534
+ const firstRegistration=f.records().find(row=>row.id==='fix-revision-final-registered').payload;
535
+ assert.throws(()=>f.append('fix-revision-final-abandoned-2','result',{...second,registrationDigest:digest(firstRegistration),
536
+ invocationId:firstRegistration.request.invocationId}),{code:'fix_review_abandon_mismatch'});
537
+ f.restore(afterSecond);
538
+ assert.throws(()=>f.append('fix-revision-final-abandoned-2','result',{...second,reason:'Again'}));
539
+ assert.equal(f.records().filter(row=>row.id==='fix-revision-final-abandoned-2').length,1);
540
+ f.restore(afterSecond);
541
+ assert.equal(f.reopen().status().revisionFinalReviewAbandonment2.providerThreadId,'fixture-review-3');
542
+ await decide();
543
+ assert.equal((await f.owner().reviewFinal()).stage,'revision_final_review_evidence_required');
544
+ const records=f.records(),ids=records.map(row=>row.id).filter(id=>id.startsWith('fix-revision-final'));
545
+ assert.deepEqual(ids,['fix-revision-final-registered','fix-revision-final-started','fix-revision-final-abandoned',
546
+ 'fix-revision-final-retry-registered','fix-revision-final-retry-started','fix-revision-final-abandoned-2',
547
+ 'fix-revision-final-retry-2-registered','fix-revision-final-retry-2-started','fix-revision-final-retry-2-result']);
548
+ assert.equal(f.owner().publishReview().stage,'revision_completion_gate_required');
549
+ assert.equal(f.reopen().status().stage,'revision_completion_gate_required');
550
+ });
551
+
493
552
  test('#15 the retried cause review refuses the abandoned reviewer thread',async t=>{
494
553
  const f=await fixture(t,{reviewMode:'first_lost_same_thread',crossLayer:true});
495
554
  await f.owner().advance({authorized:true});await causeDecide(f);await f.owner().reviewCause();
@@ -499,3 +558,183 @@ test('#15 the retried cause review refuses the abandoned reviewer thread',async
499
558
  assert.equal(reused.stage,'unknown');assert.equal(reused.pending,'cause_review');
500
559
  assert(!f.records().some(row=>row.id==='fix-cause-retry-started'));
501
560
  });
561
+
562
+ // A round-2 (post-rediagnosis) cause review with no result used to stay unknown
563
+ // forever: it was excluded from abandon_review, and a finished reviewer whose
564
+ // answer broke the verdict contract left no result record at all.
565
+ async function toRediagnosisReview(f){
566
+ assert.equal((await f.owner().advance({authorized:true})).stage,'cause_review_required');
567
+ await causeDecide(f);assert.equal((await f.owner().reviewCause()).stage,'rediagnosis_required');
568
+ assert.equal((await f.owner().rediagnose({authorized:true,reason:'Address F1'})).stage,'cause_review_required');
569
+ await causeDecide(f);return f.owner().reviewCause();
570
+ }
571
+ const hostFor=(f,permissions)=>createFixHost({owner:f.owner(),config:{...f.configuration,specsRoot:f.specsRoot,identity:f.identity},permissions});
572
+ for(const reviewMode of ['rediagnosis_lost','rediagnosis_invalid'])
573
+ test(`regression: a no-result round-2 cause review (${reviewMode}) is abandoned once via the host and re-dispatched in the same round on a fresh thread`,async t=>{
574
+ const f=await fixture(t,{reviewMode,crossLayer:true});
575
+ const lost=await toRediagnosisReview(f);
576
+ assert.equal(lost.stage,'unknown');assert.equal(lost.reviewAbandonable,'cause_review');
577
+ const round2=f.records().map(row=>row.id).filter(id=>id.startsWith('fix-cause-rediagnosis'));
578
+ if(reviewMode==='rediagnosis_lost'){
579
+ assert.equal(lost.pending,'cause_review');
580
+ assert.deepEqual(round2,['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-started']);
581
+ }else{
582
+ // The finished reviewer's off-contract answer is a recorded failed observation, not a dropped result.
583
+ assert.equal(lost.pending,null);assert.equal(lost.causeReview.observationStatus,'unknown');
584
+ assert.deepEqual(round2,['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-started','fix-cause-rediagnosis-result']);
585
+ assert.deepEqual(f.records().find(row=>row.id==='fix-cause-rediagnosis-result').payload.observation.result,
586
+ {status:'failed',code:'invalid_finding_path'});
587
+ assert.equal(f.reopen().status().reviewAbandonable,'cause_review');
588
+ }
589
+ const prefix=fs.readFileSync(f.statePath),prefixRecords=f.records();
590
+ assert.match((await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'s',operation:'status'})).progress.nextAction,/abandon_review/);
591
+ await assert.rejects(hostFor(f,['--allow-reproduction','--allow-abandon']).handle({requestId:'a',operation:'abandon_review',reason:'Stopped'}),
592
+ {code:'fix_review_abandon_authorization_required'});
593
+ assert.deepEqual(fs.readFileSync(f.statePath),prefix);
594
+ const abandoned=await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'a',operation:'abandon_review',reason:'Round-2 reviewer confirmed stopped'});
595
+ assert.equal(abandoned.stage,'cause_review_required');assert.equal(abandoned.causeReviewAbandonment.providerThreadId,'fixture-review-2');
596
+ assert.equal(f.reopen().status().stage,'cause_review_required');
597
+ await causeDecide(f);
598
+ assert.equal((await f.owner().reviewCause()).stage,'red_test_required');
599
+ const records=f.records();
600
+ assert.deepEqual(records.slice(0,prefixRecords.length),prefixRecords);
601
+ assert.deepEqual(records.slice(prefixRecords.length).map(row=>row.id),['fix-cause-rediagnosis-abandoned',
602
+ 'fix-cause-rediagnosis-retry-registered','fix-cause-rediagnosis-retry-started','fix-cause-rediagnosis-retry-result']);
603
+ assert.equal(records.find(row=>row.id==='fix-cause-rediagnosis-retry-started').payload.providerThreadId,'fixture-review-3');
604
+ assert.equal(records.filter(row=>row.id==='fix-rediagnosis-intent').length,1);assert.equal(f.reviews(),3);
605
+ assert.match(fs.readFileSync(path.join(f.specsRoot,'.reviews','fix-abandon-cause-r2.md'),'utf8'),/round: 2\nverdict: approved/);
606
+ const reopened=f.reopen().status();
607
+ assert.equal(reopened.stage,'red_test_required');assert.equal(reopened.causeReview.providerThreadId,'fixture-review-3');
608
+ });
609
+
610
+ test('regression: a third no-result round-2 cause review exhausts that round\'s two abandonments without changing the store',async t=>{
611
+ const f=await fixture(t,{reviewMode:'rediagnosis_thrice',crossLayer:true});
612
+ await toRediagnosisReview(f);
613
+ const host=()=>hostFor(f,['--allow-reproduction','--allow-abandon-review']);
614
+ assert.equal((await host().handle({requestId:'a',operation:'abandon_review',reason:'First round-2 reviewer stopped'})).stage,'cause_review_required');
615
+ await causeDecide(f);
616
+ assert.equal((await f.owner().reviewCause()).reviewAbandonable,'cause_review');
617
+ assert.equal((await host().handle({requestId:'a2',operation:'abandon_review',reason:'Second round-2 reviewer stopped'})).stage,'cause_review_required');
618
+ assert(f.records().some(row=>row.id==='fix-cause-rediagnosis-abandoned-2'));
619
+ await causeDecide(f);
620
+ const again=await f.owner().reviewCause();
621
+ assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
622
+ const before=fs.readFileSync(f.statePath);
623
+ await assert.rejects(host().handle({requestId:'b',operation:'abandon_review',reason:'Second round-2 reviewer stopped'}),{code:'fix_review_abandon_budget_exhausted'});
624
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
625
+ assert.equal(f.reopen().status().reviewAbandonBudgetExhausted,true);
626
+ });
627
+
628
+ test('regression: the round-2 cause package carries the prior review\'s examined files as context, on first dispatch and on the retry, and a finding citing them is accepted',async t=>{
629
+ const f=await fixture(t,{reviewMode:'rediagnosis_context',crossLayer:true});
630
+ assert.equal((await toRediagnosisReview(f)).reviewAbandonable,'cause_review');
631
+ await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'a',operation:'abandon_review',reason:'Round-2 reviewer stopped'});
632
+ await causeDecide(f);
633
+ assert.equal((await f.owner().reviewCause()).stage,'red_test_required');
634
+ const pkgOf=id=>f.records().find(row=>row.id===id).payload.request.payload.reviewPackage;
635
+ assert.equal(pkgOf('fix-cause-registered').contextFiles,undefined);
636
+ for(const id of ['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-retry-registered']){
637
+ const pkg=pkgOf(id);
638
+ assert.deepEqual(pkg.diagnosis.affectedPaths,['value.mjs']);assert.deepEqual(pkg.files.map(file=>file.path),['value.mjs']);
639
+ assert.deepEqual(pkg.contextFiles.map(file=>file.path),['existing.mjs']);
640
+ }
641
+ const review=f.reopen().status().causeReview.review;
642
+ assert.equal(review.verdict,'approved');assert.deepEqual(review.findings.map(row=>row.path),['existing.mjs']);
643
+ assert.equal(f.owner().status().stage,'red_test_required');
644
+ });
645
+
646
+ // V2 (F14): a repair abandoned after it left residue is redone on the baseline
647
+ // its first intent pinned. The residue is reviewed, not absorbed, and an
648
+ // approved cause review does not turn it into cause_review_drift.
649
+ test('abandoned repair with residue keeps its pinned baseline and stays out of cause_review_drift',async t=>{
650
+ const f=await fixture(t,{reviewMode:'approved_pinned',crossLayer:true});
651
+ assert.equal((await f.owner().advance({authorized:true})).stage,'cause_review_required');
652
+ await causeDecide(f);await f.owner().reviewCause();
653
+ if(f.owner().status().stage==='cause_review_evidence_required')await f.owner().reviewCause();
654
+ await f.owner().runRedTest({authorized:true});
655
+ assert.equal((await f.owner().captureBaseline({authorized:true})).stage,'repair_required');
656
+ const atRepair=f.owner().status();
657
+ const baseline=captureReviewBaseline({root:f.cwd,specsRoot:f.specsRoot,identity:f.identity,
658
+ scope:f.configuration.repair.scope,requirements:f.configuration.repair.requirements});
659
+ f.append('fix-repair-intent','intent',{baseline,redDigest:digest(atRepair.redTest),testBaselineDigest:digest(atRepair.baseline)});
660
+ // The lost attempt wrote half a repair before the host lost its answer.
661
+ fs.writeFileSync(path.join(f.cwd,'value.mjs'),'export const value=7; // half\n');
662
+ const abandoned=f.owner().abandonStep({authorized:true,reason:'Repair answer lost after a partial write'});
663
+ assert.equal(abandoned.stage,'repair_required');assert.equal(abandoned.pinnedBaselines.repair,baseline.baselineDigest);
664
+ assert.equal(f.reopen().status().stage,'repair_required');
665
+ // A redo intent that re-captured the residue as its "before" image is refused on replay.
666
+ const forged=captureReviewBaseline({root:f.cwd,specsRoot:f.specsRoot,identity:f.identity,
667
+ scope:f.configuration.repair.scope,requirements:f.configuration.repair.requirements});
668
+ const saved=fs.readFileSync(f.statePath);
669
+ assert.throws(()=>f.append('fix-repair-retry-1-intent','intent',{baseline:forged,redDigest:digest(atRepair.redTest),
670
+ testBaselineDigest:digest(atRepair.baseline)}),{code:'fix_history_invalid'});
671
+ f.restore(saved);
672
+ assert.equal((await f.owner().repair({authorized:true})).stage,'regression_required');
673
+ const retry=f.records().find(row=>row.id==='fix-repair-retry-1-intent');
674
+ assert.equal(retry.payload.baseline.baselineDigest,baseline.baselineDigest,'the redo registers the pinned baseline');
675
+ assert.equal(f.records().find(row=>row.id==='fix-abandoned-1').payload.baselinePinned,true);
676
+ });
677
+
678
+ // V10 (F18): an inconclusive regression (the red test could not run) is a
679
+ // legitimate blocked verdict; with a reason it is rerun at most twice.
680
+ test('a blocked regression is rerun with a reason through the host, keeping the blocked result',async t=>{
681
+ const marker=path.join(fs.realpathSync(os.tmpdir()),`cm-fix-hang-${process.pid}-${Date.now()}`);t.after(()=>fs.rmSync(marker,{force:true}));
682
+ const f=await fixture(t,{repairContent:`import fs from 'node:fs';if(fs.existsSync(${JSON.stringify(marker)}))await new Promise(()=>{});export const value=2;\n`});
683
+ await toRepair(f);
684
+ assert.equal((await f.owner().repair({authorized:true})).stage,'regression_required');
685
+ fs.writeFileSync(marker,'');
686
+ const blocked=await f.owner().runRegression({authorized:true});
687
+ assert.equal(blocked.stage,'regression_blocked',JSON.stringify(blocked.regression?.status));
688
+ assert.deepEqual(blocked.blockedRerun,{pending:'regression',used:0,limit:2});
689
+ const host=createFixHost({owner:f.owner(),config:{...f.configuration,specsRoot:f.specsRoot,identity:f.identity},permissions:[]});
690
+ await assert.rejects(host.handle({requestId:'r',operation:'rerun_blocked_step',reason:'environment fixed'}),{code:'fix_blocked_rerun_authorization_required'});
691
+ const allowed=createFixHost({owner:f.owner(),config:{...f.configuration,specsRoot:f.specsRoot,identity:f.identity},permissions:['--allow-rerun-blocked-step']});
692
+ await assert.rejects(allowed.handle({requestId:'r',operation:'rerun_blocked_step',reason:'two\nlines'}),{code:'fix_blocked_rerun_reason_required'});
693
+ fs.rmSync(marker);
694
+ const rerun=await allowed.handle({requestId:'r',operation:'rerun_blocked_step',reason:'Stale hang marker removed'});
695
+ assert.equal(rerun.stage,'regression_required');assert.deepEqual(rerun.blockedReruns,{regression:1});
696
+ assert.equal(f.reopen().status().stage,'regression_required');
697
+ assert.equal((await f.owner().runRegression({authorized:true})).stage,'handoff_required');
698
+ const ids=f.records().map(row=>row.id);
699
+ assert(ids.includes('fix-regression-result')&&ids.includes('fix-blocked-rerun-1')&&ids.includes('fix-regression-retry-1-result'));
700
+ // A forged second rerun record at a non-blocked stage is refused on replay.
701
+ const saved=fs.readFileSync(f.statePath);
702
+ assert.throws(()=>f.append('fix-blocked-rerun-2','result',{stage:'regression_blocked',pending:'regression',reason:'x',rerunAt:1,
703
+ intentDigest:'0'.repeat(64),resultDigest:'0'.repeat(64)}),{code:'fix_history_invalid'});
704
+ f.restore(saved);
705
+ });
706
+
707
+ // V6 (F13): in protected mode a redo refuses while the scope still holds a
708
+ // partial write of the abandoned attempt; elsewhere only out-of-scope residue refuses.
709
+ test('pinned residue: out-of-scope always refuses, in-scope refuses only in protected mode',async()=>{
710
+ const {pinnedResidue}=await import('../runtime/js/cm-fix/pinned-baseline.mjs');
711
+ const file=(p,sha)=>({path:p,type:'file',mode:420,size:1,sha256:sha.repeat(64)});
712
+ const baseline={files:[file('value.mjs','a'),file('requirements.md','b')]};
713
+ const now={files:[file('value.mjs','c'),file('requirements.md','b')]};
714
+ assert.deepEqual(pinnedResidue(baseline,now,['value.mjs'],false),['value.mjs']);
715
+ assert.throws(()=>pinnedResidue(baseline,now,['value.mjs'],true),error=>error.code==='fix_protected_residue'&&error.paths[0]==='value.mjs');
716
+ assert.throws(()=>pinnedResidue(baseline,{files:[file('value.mjs','a'),file('requirements.md','d')]},['value.mjs'],false),{code:'fix_pinned_residue'});
717
+ });
718
+
719
+ // P2 (Codex round 1): a rerun record is checked against the replay parser
720
+ // before it is appended. Here the regression step already used its eight retry
721
+ // ids, so a rerun record could not replay: it is refused and nothing is written.
722
+ test('a blocked rerun that could not replay is refused before append',async t=>{
723
+ const marker=path.join(fs.realpathSync(os.tmpdir()),`cm-fix-hang-cap-${process.pid}-${Date.now()}`);t.after(()=>fs.rmSync(marker,{force:true}));
724
+ const f=await fixture(t,{repairContent:`import fs from 'node:fs';if(fs.existsSync(${JSON.stringify(marker)}))await new Promise(()=>{});export const value=2;\n`});
725
+ await toRepair(f);
726
+ assert.equal((await f.owner().repair({authorized:true})).stage,'regression_required');
727
+ for(let n=0;n<8;n++){
728
+ const at=f.owner().status();
729
+ f.append(n?`fix-regression-retry-${n}-intent`:'fix-regression-intent','intent',
730
+ {repairDigest:digest(at.repair),redDigest:digest(at.redTest),baselineDigest:digest(at.baseline)});
731
+ assert.equal(f.owner().abandonStep({authorized:true,reason:`Regression process crashed ${n+1}`}).stage,'regression_required');
732
+ }
733
+ fs.writeFileSync(marker,'');
734
+ assert.equal((await f.owner().runRegression({authorized:true})).stage,'regression_blocked');
735
+ assert(f.records().some(row=>row.id==='fix-regression-retry-8-result'));
736
+ const before=fs.readFileSync(f.statePath);
737
+ assert.throws(()=>f.owner().rerunBlockedStep({authorized:true,reason:'environment fixed'}),{code:'fix_blocked_rerun_unavailable'});
738
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
739
+ assert.equal(f.reopen().status().stage,'regression_blocked');
740
+ });
@@ -115,3 +115,36 @@ test('F56 M1 cause transition rejects hidden drift beneath a registered test-aut
115
115
  assert.equal(JSON.stringify(reviewed),reviewedBytes);
116
116
  }
117
117
  });
118
+
119
+ test('regression: a round-2 context file that is a registered test admits the test-author transition, and only that',async t=>{
120
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-cause-context-')));
121
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
122
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
123
+ const source='export const value=1;',testBody="import {value} from './value.mjs';if(value!==2)throw Error('BUG');";
124
+ fs.writeFileSync(path.join(cwd,'value.mjs'),source);fs.writeFileSync(path.join(cwd,'regression.mjs'),testBody);
125
+ const hex=c=>c.repeat(64);
126
+ // Round 1 covered value.mjs and regression.mjs; the rediagnosis narrowed affectedPaths to value.mjs.
127
+ const status={stage:'cause_review_required',identity:{repositoryId:'fixture',runId:'context',taskId:'T-FIX-cause',attempt:1},
128
+ learning:null,reproduction:{status:'reproduced',next:'diagnose',observation:{id:'reproduce',command:['node','regression.mjs'],
129
+ outcome:'failed',exitCode:1,evidence:'Synthetic BUG',signatureMatched:true}},
130
+ diagnosis:{status:'diagnosed',rootCause:'Wrong value',plan:'Correct value',crossLayer:false,affectedPaths:['value.mjs'],affectedModules:['value']},
131
+ rediagnosis:{historyDigest:hex('a'),priorPackageDigest:hex('b'),priorObservationDigest:hex('c'),reason:'Address F1',
132
+ reviewFeedback:{verdict:'changes_requested',packageDigest:hex('b'),examinedPaths:['regression.mjs','value.mjs'],
133
+ findings:[{id:'F1',severity:'P2',path:'regression.mjs',message:'Test misses the boundary',evidence:'Fixture'}],summary:'Fixture'}}};
134
+ const capture=()=>createFixCausePackage({codeProject:cwd,defect:'Wrong value',status});
135
+ const reviewed=readFixCausePackage(capture());
136
+ assert.deepEqual(reviewed.contextFiles.map(file=>file.path),['regression.mjs']);
137
+ for(const hiddenDrift of [false,true]){
138
+ fs.writeFileSync(path.join(cwd,'regression.mjs'),testBody+(hiddenDrift?'\n// unregistered edit after cause review':''));
139
+ let registered;
140
+ const author=prepareFixTestAuthor({codeProject:cwd,specsRoot,identity:status.identity,testFiles:['regression.mjs'],
141
+ requirements:['value.mjs'],defect:'Wrong value',diagnosis:status.diagnosis,reproduction:status.reproduction},
142
+ {assertReviewReady(){},bridge:{async call(){fs.appendFileSync(path.join(cwd,'regression.mjs'),'\nif(!Number.isInteger(value))throw Error("boundary");');return {outcome:'authored'};}}});
143
+ const result=await author.execute({authorized:true,signal:new AbortController().signal,register(baseline){registered=baseline;}});
144
+ assert.equal(result.outcome,'authored');
145
+ const verify=()=>verifyFixCauseTransition(reviewed,capture(),registered,result);
146
+ if(hiddenDrift)assert.throws(verify,{code:'cause_review_drift'});else assert.doesNotThrow(verify);
147
+ }
148
+ // Without a registered test transition, any change to a context file is drift.
149
+ assert.throws(()=>verifyFixCauseTransition(reviewed,capture(),null,null),{code:'cause_review_drift'});
150
+ });
@@ -0,0 +1,37 @@
1
+ // F11: outside protected mode the fix driver must answer like a session: write
2
+ // the planned files inside the supplied scope and return only {outcome}. It used
3
+ // to return the protected {outcome,edits} proposal, which the host always
4
+ // refused (shape), so the step went unknown and abandon_step was spent each time.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {prepareFixTestAuthor} from '../runtime/js/cm-fix/test-author.mjs';
11
+ import {answerFor} from './cm-fix-drive.mjs';
12
+
13
+ test('fix driver answers a non-protected fix_test_author through the real test-author step',async t=>{
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-drive-unprotected-')));
15
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs'),answers=path.join(root,'answers');
17
+ for(const dir of [cwd,specsRoot,answers])fs.mkdirSync(dir);
18
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');fs.writeFileSync(path.join(cwd,'requirements.md'),'fixture');
19
+ fs.writeFileSync(path.join(answers,'red.mjs'),"import {value} from './value.mjs';if(value!==2)process.exit(1)\n");
20
+ const identity={repositoryId:'fixture',runId:'driver-unprotected',taskId:'T-FIX-demo',attempt:1};
21
+ const options={codeProject:cwd,specsRoot,identity,testFiles:['red.mjs'],requirements:['requirements.md'],defect:'Constant bug',diagnosis:{},reproduction:{}};
22
+ const driverAnswers={'test-edits':{'red.mjs':'red.mjs'}},paths={answers,round:1};
23
+ let asked=null;
24
+ const author=prepareFixTestAuthor(options,{assertReviewReady(){},bridge:{async call(kind,payload){
25
+ asked=payload;return answerFor({kind,payload},driverAnswers,paths);}}});
26
+ const result=await author.execute({authorized:true,signal:new AbortController().signal,register(){}});
27
+ assert.equal(asked.editMode,undefined,'non-protected request');
28
+ assert.deepEqual([result.outcome,result.changedFiles],['authored',['red.mjs']]);
29
+ assert.equal(fs.readFileSync(path.join(cwd,'red.mjs'),'utf8'),fs.readFileSync(path.join(answers,'red.mjs'),'utf8'));
30
+ // A planned file outside the supplied scope is a legal blocked answer, nothing written.
31
+ assert.deepEqual(answerFor({kind:'fix_repair',payload:{identity,codeProject:cwd,scope:['value.mjs']}},
32
+ {'repair-edits':{'other.mjs':'red.mjs'}},paths),{outcome:'blocked'});
33
+ assert.equal(fs.existsSync(path.join(cwd,'other.mjs')),false);
34
+ // Protected mode keeps the proposal shape.
35
+ const proposal=answerFor({kind:'fix_test_author',payload:{identity,editMode:'protected-text-v1',expected:{'red.mjs':null}}},driverAnswers,paths);
36
+ assert.deepEqual(Object.keys(proposal),['outcome','edits']);assert.equal(proposal.edits[0].path,'red.mjs');
37
+ });
@@ -22,7 +22,7 @@
22
22
  // "reviewConfig": "review.json", 可选
23
23
  // "permissions": ["--allow-red-test", ...], 原样传给宿主,不另造一套词
24
24
  // "answers": "answers", 答案目录;abandon_step / abandon_review 可省略
25
- // "reason": "旧本地步骤结果丢失" abandon_step 必填并需 --allow-abandon;abandon_review 必填并需 --allow-abandon-review
25
+ // "reason": "旧本地步骤结果丢失" abandon_step 必填并需 --allow-abandon;abandon_review 必填并需 --allow-abandon-review;rerun_blocked_step 必填并需 --allow-rerun-blocked-step
26
26
  // "inputLimit": 1048576 可选;宿主输入与应答上限(65536–4194304,默认 65536)
27
27
  // }
28
28
  //
@@ -30,6 +30,7 @@
30
30
  // learning.json {status, summary} 恢复时若存档里已有记录会自动复用
31
31
  // diagnosis.json 首次诊断结论对象
32
32
  // diagnosis-rediagnosis.json 显式原运行重新诊断的新结论,不能复用首次文件
33
+ // 两份诊断都在开宿主前用宿主同一校验器检查(如 investigation.discardedAlternatives 最多 3 项)
33
34
  // retrospective.json {status, candidates, reason}
34
35
  // test-edits.json {"仓库内路径": "本目录下的内容文件"};修订轮用 test-edits-a2.json
35
36
  // repair-edits.json 同上;修订轮用 repair-edits-a2.json
@@ -37,6 +38,7 @@ import fs from 'node:fs';
37
38
  import path from 'node:path';
38
39
  import {fileURLToPath} from 'node:url';
39
40
  import {fixEvidenceNames} from '../runtime/js/cm-fix/layout.mjs';
41
+ import {inspectFixDiagnosis,describeFixDiagnosisError} from '../runtime/js/cm-fix/diagnosis.mjs';
40
42
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
41
43
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
42
44
 
@@ -58,11 +60,11 @@ const ASKS={
58
60
  const READ_ONLY=new Set(['status','final_review_package','completion_evidence','cause_review_package']);
59
61
  const KNOWN=new Set([...Object.keys(ASKS),...READ_ONLY,'cancel','handoff','publish_review','check_n5',
60
62
  'publish_dossier','learning_writeback','walkthrough','finish','final_review','cause_review',
61
- 'reconcile_review','recover_final_review','abandon_step','abandon_review','resume','revision_test_check']);
63
+ 'reconcile_review','recover_final_review','abandon_step','abandon_review','rerun_blocked_step','resume','revision_test_check']);
62
64
 
63
65
  function loadPlan(){
64
66
  const {operation,plan,base}=loadPlanFile({name:'cm-fix-drive.mjs',known:KNOWN});
65
- const abandoning=['abandon_step','abandon_review'].includes(operation);
67
+ const abandoning=['abandon_step','abandon_review','rerun_blocked_step'].includes(operation);
66
68
  requireFields(plan,['config','cwd','mode','hostContext','permissions',...(abandoning||operation==='reconcile_review'?[]:['answers'])]);
67
69
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
68
70
  if(!Array.isArray(plan.permissions))stop(2,'permissions must be an array');
@@ -74,7 +76,7 @@ function loadPlan(){
74
76
  }else if(!['--execution-optimizations','--external-models'].includes(flag)&&!/^--allow-[a-z-]+$/.test(flag))stop(2,'invalid permissions');
75
77
  }
76
78
  if(operation==='reconcile_review'&&(plan.mode!=='resume'||typeof plan.invocationId!=='string'||!plan.invocationId))stop(2,'reconcile_review requires resume and original invocationId');
77
- const abandonFlag=operation==='abandon_review'?'--allow-abandon-review':'--allow-abandon';
79
+ const abandonFlag=operation==='abandon_review'?'--allow-abandon-review':operation==='rerun_blocked_step'?'--allow-rerun-blocked-step':'--allow-abandon';
78
80
  if(abandoning&&(!plan.permissions.includes(abandonFlag)||typeof plan.reason!=='string'
79
81
  ||!plan.reason.trim().length||Buffer.byteLength(plan.reason,'utf8')>1000||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))
80
82
  stop(2,`${operation} 需要 PLAN.reason(单行,最多 1000 字节)和 ${abandonFlag}`);
@@ -138,7 +140,13 @@ export function preflight({operation,plan,paths}){
138
140
  if(recorded){stderr(`恢复:复用存档里已记的学习记录(${recorded.status})`);return recorded;}
139
141
  return need('学习记录','learning.json');
140
142
  }
141
- if(kind==='diagnosis')return need('诊断',operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json');
143
+ if(kind==='diagnosis'){
144
+ // 用宿主同一个校验器:不合格的答案在开宿主前就拦下,免得登记了却交不出结论。
145
+ const file=operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json';
146
+ const value=need('诊断',file);
147
+ try{inspectFixDiagnosis(value);}catch(error){stop(2,`${path.join(paths.answers,file)}:${describeFixDiagnosisError(error)};改好再来,宿主未启动`);}
148
+ return value;
149
+ }
142
150
  if(kind==='retrospective')return need('复盘','retrospective.json');
143
151
  const file=roundAnswerName(paths.answers,kind,round);
144
152
  const map=need(kind==='test-edits'?'测试内容':'修复内容',file);
@@ -180,7 +188,7 @@ function hostArgs({plan,paths}){
180
188
  ...plan.permissions];
181
189
  }
182
190
 
183
- function answerFor(row,answers,paths){
191
+ export function answerFor(row,answers,paths){
184
192
  const {kind,payload}=row;
185
193
  if(kind==='fix_learning')return {contextDigest:payload.contextDigest,status:answers.learning.status,summary:answers.learning.summary};
186
194
  if(kind==='fix_diagnose')return answers.diagnosis;
@@ -190,6 +198,24 @@ function answerFor(row,answers,paths){
190
198
  if(requestAttempt!==undefined&&requestAttempt!==paths.round)
191
199
  throw Error(`修订轮次 ${requestAttempt} 与已预检答案轮次 ${paths.round} 不一致`);
192
200
  const map=answers[kind==='fix_repair'?'repair-edits':'test-edits'],expected=payload.expected??{};
201
+ const done=kind==='fix_repair'?'repaired':'authored';
202
+ // F11: outside protected mode the session itself writes inside the supplied
203
+ // scope and answers only {outcome} (test-author.mjs / repair.mjs); a
204
+ // {outcome,edits} proposal there always failed its shape check. The driver,
205
+ // standing in for the session, writes the planned files the same way.
206
+ if(payload.editMode!=='protected-text-v1'){
207
+ const scope=Array.isArray(payload.scope)?payload.scope:[];
208
+ if(typeof payload.codeProject!=='string'||!path.isAbsolute(payload.codeProject))throw Error('宿主没有给出代码根,无法写入');
209
+ const outside=Object.keys(map).filter(target=>!scope.includes(target));
210
+ if(outside.length){stderr(`${outside.join(', ')} 不在宿主本次允许的范围内,回 blocked`);return {outcome:'blocked'};}
211
+ for(const [target,local] of Object.entries(map)){
212
+ const file=path.join(payload.codeProject,target);
213
+ if(path.relative(payload.codeProject,file).startsWith('..'))throw Error(`${target} 越出代码根`);
214
+ fs.mkdirSync(path.dirname(file),{recursive:true});
215
+ fs.writeFileSync(file,fs.readFileSync(path.join(paths.answers,local),'utf8'));
216
+ }
217
+ return {outcome:done};
218
+ }
193
219
  const edits=[];
194
220
  for(const [target,local] of Object.entries(map)){
195
221
  // 路径不在宿主给的范围里:不能硬塞,也不能断线(断线会把运行做死)。
@@ -197,7 +223,7 @@ function answerFor(row,answers,paths){
197
223
  if(!Object.hasOwn(expected,target)){stderr(`${target} 不在宿主本次允许的范围内,回 blocked`);return {outcome:'blocked',edits:[]};}
198
224
  edits.push({path:target,beforeSha256:expected[target],content:fs.readFileSync(path.join(paths.answers,local),'utf8')});
199
225
  }
200
- return {outcome:kind==='fix_repair'?'repaired':'authored',edits};
226
+ return {outcome:done,edits};
201
227
  }
202
228
  return null;
203
229
  }
@@ -207,7 +233,7 @@ function main(){
207
233
  const {answers,round}=preflight(loaded);
208
234
  const {operation,plan,paths}=loaded;
209
235
  driveHost({host:HOST,args:hostArgs(loaded).slice(1),cwd:path.resolve(plan.cwd),operation,
210
- request:{...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),...(['abandon_step','abandon_review','rediagnose'].includes(operation)?{reason:plan.reason}:{}),
236
+ request:{...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),...(['abandon_step','abandon_review','rediagnose','rerun_blocked_step'].includes(operation)?{reason:plan.reason}:{}),
211
237
  ...(operation==='prepare_revision'&&Object.hasOwn(plan,'revisionTests')?{tests:plan.revisionTests}:{})},
212
238
  answers,paths:{...paths,round},answerFor});
213
239
  }
@@ -7,7 +7,7 @@ import {fileURLToPath} from 'node:url';
7
7
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
8
8
  import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
9
9
  import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
10
- import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
10
+ import {createHostToolBridge,HOST_ANSWER_BACKSTOP_MS} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
11
11
  import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
12
12
  import {id,json,need,shape,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
13
13
  import {readConversationReviewConfiguration} from './cm-ai-host.mjs';
@@ -21,10 +21,11 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
21
21
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Omit specsRoot or use null for a bare project: the same owner stores archives in docs/fixes and reviews in docs/fixes/.reviews, uses the original no-specs log mode, and skips METRICS. No specs skeleton is created. Visual-only reproduction/redTest may use kind:visual with cwd, timeoutMs, before:{path,sha256,kind:screenshot|video,description}, reason explaining why automated red cannot be written, environment, steps and expected; redTest also has testFiles:[]. No testAuthor or fake red/green command. Repair/regression/review/finish permissions remain mandatory. qa_browser returns actual after carrier metadata; missing evidence blocks.\n');
22
22
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional startup configuration protectSpecs:true uses the existing Codex native sandbox for reproduction, red/baseline/regression/walkthrough commands and fixed text edits, without a model call. Requires the local sandbox executable; it does not change the current Codex/Claude host or reviewer identity. Original action permissions remain required. fix_test_author/fix_repair with editMode=protected-text-v1 require {outcome,edits:[{path,beforeSha256,content}]} using the supplied scope/expected hashes; never write directly. Content is full UTF-8 text or null for deletion, blocked requires edits:[]. Default 64KiB response limit applies; --input-limit may explicitly raise transport to 4MiB, while protected text proposal limits remain 1MiB. Drift or failed writes retain the original unknown boundary; no automatic retry/rollback or protection-mode switching on resume.\n');
23
23
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('completion_evidence is read-only and available only after the original finish has completed and current evidence still validates. It returns the selected attempt, original reviewed package, handoff/review digests, completion event IDs and optional qaSource from the original owner. It does not complete or resume a parent task; JSON evidence alone is not authority.\n');
24
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. No automatic retry, cancelled/complete-verdict recovery, missing-thread recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
25
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('rediagnose requires --allow-rediagnosis, the original resumed run at rediagnosis_required and a nonempty single-line reason up to 1000 UTF-8 bytes. It appends one history-bound diagnosis without repeating reproduction or overwriting cause-r1. A fresh cause review must publish cause-r2 even for a revised single-layer cause. Second rejection reaches rediagnosis_review_limit_reached. Interrupted rediagnosis or its review is not automatically retried or abandoned. Standalone only.\n');
26
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_step requires --allow-abandon, stage unknown, an eligible local pending kind, and a nonempty single-line reason up to 1000 UTF-8 bytes. It records the abandoned intent and returns to the required stage; a later separate action redoes the step. At most eight abandonments per run. Review, Learning writeback and handoff remain unavailable.\n');
27
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_review requires its own --allow-abandon-review flag (not --allow-abandon) and the same reason rules. Each run may abandon the cause review once and the second-round final review once, only while that registered review has no review result (interrupted, timed out, disconnected or cancelled); confirm the old reviewer stopped first. It records the abandoned invocation and returns to the review stage; the retry needs the original review flag, a fresh grant and a new reviewer thread. Reviews wait for the review configuration timeoutMs (default 900000), not the reproduction timeout.\n');
24
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. A first final review whose worker never opened a thread may be recovered at most twice in total. No automatic retry, cancelled/complete-verdict recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
25
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('rediagnose requires --allow-rediagnosis, the original resumed run at rediagnosis_required and a nonempty single-line reason up to 1000 UTF-8 bytes. It appends one history-bound diagnosis without repeating reproduction or overwriting cause-r1. A fresh cause review must publish cause-r2 even for a revised single-layer cause. Second rejection reaches rediagnosis_review_limit_reached. Interrupted rediagnosis or its review is not automatically retried or abandoned. A QA-fix child reaches the same operation through the parent cm-ai-host fix_action with --allow-qa-fix-rediagnosis.\n');
26
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_step requires --allow-abandon, stage unknown, an eligible local pending kind, and a nonempty single-line reason up to 1000 UTF-8 bytes. It records the abandoned intent and returns to the required stage; a later separate action redoes the step. At most eight abandonments per run. Review, Learning writeback and handoff remain unavailable. A redone test author or repair keeps the baseline its first intent captured (baselinePinned), so the residue of the abandoned attempt is reviewed; in protected mode the scope must first be restored to that baseline (fix_protected_residue lists the paths).\n');
27
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('rerun_blocked_step requires --allow-rerun-blocked-step and a nonempty single-line reason up to 1000 UTF-8 bytes. Only for a legitimate blocked verdict of test_author, repair, regression (including visual BLOCKED/inconclusive), post-review regression or walkthrough (and their revision_ forms): it records fix-blocked-rerun-N, keeps the blocked result as history and returns to the required stage; at most two reruns per step kind.\n');
28
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_review requires its own --allow-abandon-review flag (not --allow-abandon) and the same reason rules. Each run may abandon each cause review round twice (the first round and the post-rediagnosis round 2 separately) and the second-round final review twice, only while that registered review has no review result (interrupted, timed out, disconnected or cancelled); confirm the old reviewer stopped first. It records the abandoned invocation and returns to the review stage; the retry needs the original review flag, a fresh grant and a new reviewer thread. Reviews wait for the review configuration timeoutMs (default 900000), not the reproduction timeout.\n');
28
29
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('N6 child configuration may include qaSource {feature, identity, packageDigest, testRunId, handoffDigest}; derive the separate fixed child identity with qaFixIdentity. It requires --allow-qa-fix in addition to existing action flags. Close the parent host first: the original specs-wide owner lock is shared. Creation/resume rechecks the current failed round, project, report and policy; the source is bound to the original fix configuration. This does not resume the parent or automatically rerun QA, and does not authorize provider calls, installation or Git.\n');
29
30
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Second-round retrospective uses the cumulative original baseline, including previously authored tests and Learning scope. It persists the current round reflection and reaches revision_handoff_ready or revision_learning_writeback_required; neither state completes the task or publishes a new handoff. From revision_handoff_ready, handoff publishes a separate a2 handoff containing cumulative changes, current reflection, original red evidence and prior review/Learning history; final_review_package then reads that bound package. Pending Learning blocks publication. final_review requires --allow-final-review, uses fresh-thread exclusions and carries prior findings; publish_review writes the original r2 evidence and review log, and check_n5 runs the original Learning-aware gate. Approval reaches revision_post_review_regression_required, not completion.\n');
30
31
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
@@ -36,7 +37,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
36
37
  need(['create','resume'].includes(argv[4]),'invalid_arguments');id(argv[6]);
37
38
  const extra=new Map();
38
39
  for(let index=8;index<argv.length;index++){
39
- const flag=argv[index];need(!extra.has(flag)&&['--execution-optimizations','--external-models','--external-models-config','--runtime','--input-limit','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-rediagnosis','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-abandon','--allow-abandon-review','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
40
+ const flag=argv[index];need(!extra.has(flag)&&['--execution-optimizations','--external-models','--external-models-config','--runtime','--input-limit','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-rediagnosis','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-abandon','--allow-abandon-review','--allow-rerun-blocked-step','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
40
41
  if(flag.startsWith('--allow-')||flag==='--external-models'||flag==='--execution-optimizations')extra.set(flag,true);
41
42
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(flag,argv[++index]);}
42
43
  }
@@ -76,7 +77,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
76
77
  const {reviewer,authority,finalAuthority,execution:reviewExecution}=createFixReviewHost({
77
78
  codeProject:config.reproduction.cwd,hostContextId:argv[6],runtime,review,
78
79
  permissions:[...extra.keys()],workerFactory:reviewWorkerFactory,externalModels,executionPolicy,specsDir:config.specsRoot??null});
79
- bridge=createHostToolBridge({responseLimit:inputLimit});
80
+ bridge=createHostToolBridge({responseLimit:inputLimit,answerTimeoutMs:HOST_ANSWER_BACKSTOP_MS});
80
81
  owner=openFixExecution({specsRoot:config.specsRoot??null,identity:config.identity,create:argv[4]==='create',
81
82
  hostContextId:argv[6],
82
83
  configuration:{...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),hostContextId:originalHostContext??argv[6],defect:config.defect,reproduction:config.reproduction,