@aibyzero/cm-workflow 0.16.8 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -9,14 +9,9 @@ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
9
9
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
10
  import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
11
11
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
12
- import {writeHandoff,writeReview} from '../experiments/js-orchestration/native-gate-fixture.mjs';
12
+ import {writeHandoff,writeReview} from './fixtures/native-gate-fixture.mjs';
13
13
  import {acquireExternalRunGuard} from '../runtime/js/cm-ai/external-run-guard.mjs';
14
- const grant=(request,issuedAt)=>{
15
- const value={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.invocationId,adapterId:'codex-review-adapter',
16
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',logicalContextId:request.contextId,
17
- packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'host',decisionId:'decision-'+request.invocationId,decision:'approved',issuedAt,expiresAt:issuedAt+60000};
18
- return {...value,grantDigest:digest(value)};
19
- };
14
+ import {memberSupersedeAdmitted} from './cm-ai-batch-run.mjs';
20
15
  async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=false,policyOnly=false}={}){
21
16
  const tmp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-external-recovery-'))),root=path.join(tmp,'code'),specsRoot=path.join(tmp,'specs');
22
17
  fs.mkdirSync(root);fs.mkdirSync(specsRoot);fs.mkdirSync(path.join(specsRoot,'feature'));fs.mkdirSync(path.join(specsRoot,'.reviews'));
@@ -32,7 +27,7 @@ async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=f
32
27
  }},reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,contexts:['review-1','review-2'],run:(request,control)=>{calls++;const result=review(request,control);if(result?.status==='succeeded')writeReview(path.join(specsRoot,'.reviews/feature-T-001-r'+request.identity.attempt+'.md'),path.join(specsRoot,'.reviews/feature-T-001-a'+request.identity.attempt+'-handoff.json'),request.identity.attempt,result.value.verdict);return result;}}],
33
28
  check:()=>[{id:'check',command:['controlled'],outcome:'passed',exitCode:0,evidence:'fixture'}],
34
29
  taskCompletion:{reviewsDir:path.join(specsRoot,'.reviews'),handoffs:[path.join(specsRoot,'.reviews/feature-T-001-a1-handoff.json'),path.join(specsRoot,'.reviews/feature-T-001-a2-handoff.json')]},
35
- reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host',authorize:(request,{authorizationAt})=>grant(request,authorizationAt)}};
30
+ reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host'}};
36
31
  const make=mode=>createTaskRunner({...options,persistence:{store,mode,version:3}});
37
32
  const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
38
33
  const records=()=>store.snapshot().records;
@@ -44,7 +39,7 @@ async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=f
44
39
  };
45
40
  const effect=(kind,attempt=1,id=kind+'-'+attempt)=>({version:1,id,identity:{...identity,attempt},kind});
46
41
  const guard=(override={})=>acquireExternalRunGuard({specsDir:specsRoot,codeProject:root,feature:'feature',identity:{...identity,runId:'another-run'},...override});
47
- try{await fn({make:()=>make('create'),reopen,prefix,effect,records,guard,closeStore:()=>store.close(),calls:()=>calls,developerCalls:()=>developerCalls});}finally{store.close();fs.rmSync(tmp,{recursive:true,force:true});}
42
+ try{await fn({make:()=>make('create'),reopen,prefix,effect,records,guard,specsRoot,root,closeStore:()=>store.close(),calls:()=>calls,developerCalls:()=>developerCalls});}finally{store.close();fs.rmSync(tmp,{recursive:true,force:true});}
48
43
  }
49
44
  const start=(request,onEvent)=>{onEvent({event:'thread.started',provider_thread:'actual-review-'+request.identity.attempt});onEvent({event:'turn.started',item_type:null});};
50
45
  const noTerminal=(request,{onEvent})=>{start(request,onEvent);onEvent({event:'process_closed',exit_code:143,signal:null,timed_out:true});return {status:'failed',code:'timeout'};};
@@ -67,7 +62,28 @@ for(const [name,review] of [['close without provider terminal',noTerminal],['out
67
62
  assert.throws(()=>f.guard({identity:{repositoryId:'fixture',runId:'other-task-run',taskId:'T-002',attempt:1}}),{code:'external_prior_attempt_unresolved'});
68
63
  assert.throws(()=>f.guard({feature:'other-feature',identity:{repositoryId:'fixture',runId:'other-feature-run',taskId:'T-002',attempt:1}}),{code:'external_prior_attempt_unresolved'});assert.equal(f.calls(),1);
69
64
  const init=rows[0].payload;assert.equal(readRunnerHistory(rows,init.config,3).state.state,'unknown');
65
+ // Batch 4 review round 2: the batch's unresolved hint decides supersede from the same
66
+ // entry conditions as the guard above, so this strict raw-unknown run (which the
67
+ // supersede state check alone would take) is not sent to supersede.
68
+ assert.equal(memberSupersedeAdmitted(f.specsRoot,'strict-run',readRunnerHistory(rows,init.config,3)),false);
70
69
  },review,{timeoutMs:40}));
70
+ // The same probe on a non-strict run left unknown: admitted. The supersede it names is
71
+ // an ordinary single-task launch; the guard such a launch takes when a strict binding
72
+ // exists on the root (strictOnly) does not refuse it. A strict
73
+ // new run would refuse any unresolved same-task prior run, so the hint names an
74
+ // ordinary launch.
75
+ test('a non-strict unknown run is admitted to supersede by the batch hint check and the guard alike',()=>fixture(async f=>{
76
+ const runner=f.make();await runner.executeEffect(f.effect('develop'));
77
+ const reviewed=await runner.executeEffect(f.effect('review'));assert.equal(reviewed.state,'unknown',JSON.stringify(reviewed));f.closeStore();
78
+ const rows=JSON.parse(fs.readFileSync(path.join(f.specsRoot,'.reviews/.execution/strict-run/state.json'),'utf8')).records;
79
+ const history=readRunnerHistory(rows,rows[0].payload.config,3);assert.equal(history.pending,null);
80
+ assert.equal(memberSupersedeAdmitted(f.specsRoot,'strict-run',history),true);
81
+ const identity={repositoryId:'fixture',runId:'another-run',taskId:'T-001',attempt:1};
82
+ acquireExternalRunGuard({specsDir:f.specsRoot,codeProject:f.root,feature:'feature',identity},{strictOnly:true}).close();
83
+ assert.throws(()=>acquireExternalRunGuard({specsDir:f.specsRoot,codeProject:f.root,feature:'feature',identity}),{code:'external_prior_attempt_unresolved'});
84
+ // (This runner fixture carries no task-learning feature, so the supersede check itself
85
+ // is probed on a real batch member journal in cm-ai-batch-run.test.mjs.)
86
+ },(request,{onEvent})=>{onEvent({event:'thread.started',provider_thread:'review-lost'});throw Error('Synthetic lost reviewer');},{strict:false}));
71
87
  for(const type of ['review-invocation-registered','review-invocation-started','review-invocation-result'])test(type+' crash prefix preserves original attempt and rejects old abandonment paths',()=>fixture(async f=>{
72
88
  let runner=f.make();await runner.executeEffect(f.effect('develop'));await runner.executeEffect(f.effect('review'));runner=f.prefix(type);
73
89
  assert.equal(runner.status().state,'unknown');assert.equal(runner.status().pendingReviewInvocation,undefined);assert.equal(runner.status().pendingEffectKind,undefined);
@@ -76,15 +92,19 @@ for(const type of ['review-invocation-registered','review-invocation-started','r
76
92
  await runner.executeEffect(f.effect('review',1,'new-call'));assert.equal(f.calls(),1);assert.equal(JSON.stringify(f.records()),before);
77
93
  assert.throws(f.guard,{code:'external_prior_attempt_unresolved'});
78
94
  },noTerminal));
79
- test('legacy missing marker retains its once-only local timeout retry contract',()=>fixture(async f=>{
95
+ test('legacy missing marker keeps the local no-result redispatch contract (two per round)',()=>fixture(async f=>{
80
96
  const runner=f.make();await runner.executeEffect(f.effect('develop'));assert.equal((await runner.executeEffect(f.effect('review'))).state,'pending_review');
81
- assert.equal((await runner.executeEffect(f.effect('review',1,'retry'))).state,'blocked');assert.equal(f.calls(),2);
97
+ const second=await runner.executeEffect(f.effect('review',1,'retry'));
98
+ assert.equal(second.state,'blocked');assert.equal(second.reviewRedispatchStopRequired,true);assert.equal(f.calls(),2);
99
+ assert.equal(runner.abandonReview({allowed:true,reason:'reviewer stopped'}).state,'pending_review');
100
+ const spent=await runner.executeEffect(f.effect('review',1,'retry-2'));
101
+ assert.equal(spent.state,'blocked');assert.equal(spent.code,'review_redispatch_limit');assert.equal(f.calls(),3);
82
102
  },noTerminal,{strict:false}));
83
103
  test('valid changes_requested permits a fresh separately authorized second attempt and completion',()=>fixture(async f=>{
84
104
  const runner=f.make();await runner.executeEffect(f.effect('develop'));assert.equal((await runner.executeEffect(f.effect('review'))).state,'changes_requested');
85
105
  await runner.executeEffect(f.effect('develop',2));assert.equal((await runner.executeEffect(f.effect('review',2))).state,'approved');
86
106
  const done=await runner.executeEffect(f.effect('complete',2));assert.equal(done.state,'fixture_completed',JSON.stringify(done));assert.equal(f.calls(),2);
87
- const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.grant.invocationId,registered[1].payload.grant.invocationId);
107
+ const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.binding.invocationId,registered[1].payload.binding.invocationId);
88
108
  assert.throws(()=>f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}}),{code:'external_prior_writer_active'});
89
109
  f.closeStore();
90
110
  const next=f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}});next.close();assert.equal(f.calls(),2);
@@ -58,7 +58,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0,exter
58
58
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
59
59
  }};
60
60
  const executionFor=live=>{
61
- const execution=createConversationExecution(definition,live,bridge,review,1,workflow,true,'codex',
61
+ const execution=createConversationExecution(definition,live,bridge,review,null,workflow,true,'codex',
62
62
  live===A?{}:{originalHostContextId:A});
63
63
  execution.check=createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]});
64
64
  execution.reviewers[0].run=async(request,{onEvent})=>{
@@ -25,13 +25,6 @@ import {createClaudeReviewRun} from '../runtime/js/cm-ai/claude-review-adapter.m
25
25
 
26
26
 
27
27
  const checks=[{id:'check',command:['synthetic'],outcome:'passed',exitCode:0,evidence:'fixture'}];
28
- const grantFor=(request,authorizationAt,change=grant=>grant)=>{
29
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.invocationId}`,adapterId:`${request.provider}-review-adapter`,
30
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
31
- reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
32
- hostContextId:'actual-main',decisionId:'decision-1',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
33
- change(body);return {...body,grantDigest:digest(body)};
34
- };
35
28
  const events=(onEvent,thread='actual-review')=>{
36
29
  onEvent({event:'thread.started',provider_thread:thread});
37
30
  onEvent({event:'turn.started',item_type:null});
@@ -40,7 +33,7 @@ const events=(onEvent,thread='actual-review')=>{
40
33
  onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
41
34
  };
42
35
 
43
- async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='codex'}={}) {
36
+ async function fixture(fn,{reviewRun,times,timeoutMs=1000,provider='codex'}={}) {
44
37
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-v3-')));
45
38
  const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
46
39
  fs.mkdirSync(root);fs.mkdirSync(reviewsDir,{recursive:true});
@@ -64,8 +57,7 @@ async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='co
64
57
  dispatches++;lateEvent=control.onEvent;return (reviewRun??defaultRun)(request,control);
65
58
  }}],check:()=>checks,
66
59
  taskCompletion:{reviewsDir,handoffs:[path.join(reviewsDir,'a1.json'),path.join(reviewsDir,'a2.json')]},
67
- reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
68
- authorize:authorize??((request,{authorizationAt})=>grantFor(request,authorizationAt))}};
60
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main']}};
69
61
  const make=mode=>{
70
62
  const old=Date.now,values=times?[...times]:null;if(values)Date.now=()=>values.length>1?values.shift():values[0];
71
63
  try{return createTaskRunner({...options,persistence:{store,mode,version:3}});}finally{Date.now=old;}
@@ -127,7 +119,7 @@ for(const provider of ['codex','claude'])test(`${provider} late terminal receipt
127
119
  assert.equal(f.dispatches(),1);
128
120
  },{timeoutMs:20,provider,reviewRun:lateReceiptRun({duplicate:true})}));
129
121
 
130
- test('reconciled provider failure spends the original one-retry budget and requires a fresh grant',()=>fixture(async f=>{
122
+ test('reconciled provider failure spends the original one-retry budget and requires a fresh request binding',()=>fixture(async f=>{
131
123
  const runner=f.make();await runner.executeEffect(f.effect('develop'));
132
124
  const first=await runner.executeEffect(f.effect('review'));
133
125
  const after=runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
@@ -135,7 +127,7 @@ test('reconciled provider failure spends the original one-retry budget and requi
135
127
  const second=await runner.executeEffect(retryEffect(f));assert.equal(second.state,'unknown');
136
128
  const final=runner.reconcileReview({invocationId:second.reviewReconciliation.invocationId});
137
129
  assert.equal(final.state,'blocked');assert.equal(final.code,'review_provider_failed');assert.equal(f.dispatches(),2);
138
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,second.reviewInvocation.registration.grant.grantDigest);
130
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,second.reviewInvocation.registration.binding.requestDigest);
139
131
  assert.equal((await runner.executeEffect({...retryEffect(f),id:'third-review'})).code,'stage_mismatch');
140
132
  assert.equal(f.dispatches(),2);assert.deepEqual(f.reopen().status(),final);
141
133
  },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true})}));
@@ -147,7 +139,7 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
147
139
  const original=f.getStore().snapshot().records;
148
140
  for(const [type,key,value] of [
149
141
  ['review-invocation-receipt','invocationId','other-call'],['review-invocation-receipt','effectId','review-2'],
150
- ['review-invocation-receipt','registeredDigest',digest('other-grant')],
142
+ ['review-invocation-receipt','registeredDigest',digest('other-registration')],
151
143
  ['review-invocation-receipt','startedDigest',digest('other-thread')],
152
144
  ['review-invocation-receipt','resultDigest',digest('other-result')],
153
145
  ['review-invocation-reconciled','receiptDigest',digest('other-receipt')],
@@ -160,16 +152,6 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
160
152
  assert.deepEqual(f.getStore().snapshot().records,original);assert.equal(f.dispatches(),1);
161
153
  },{timeoutMs:20,reviewRun:lateReceiptRun()}));
162
154
 
163
- test('reconciliation is not dispatch approval and the original grant cannot authorize another invocation',()=>{
164
- let originalGrant;
165
- return fixture(async f=>{
166
- const runner=f.make();await runner.executeEffect(f.effect('develop'));
167
- const first=await runner.executeEffect(f.effect('review'));
168
- runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
169
- assert.equal((await runner.executeEffect(retryEffect(f))).code,'authorization_invalid');
170
- assert.equal(f.dispatches(),1);
171
- },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true}),authorize:(request,{authorizationAt})=>originalGrant??=grantFor(request,authorizationAt)});
172
- });
173
155
 
174
156
  for(const [name,change] of [
175
157
  ['only local exit',r=>{r.events=r.events.filter(e=>!['item.completed','turn.completed'].includes(e.event));r.result={status:'failed',code:'incomplete_result'};}],
@@ -241,7 +223,7 @@ setInterval(()=>{},1000);
241
223
  const retry=await resumed.executeEffect(retryEffect(f));assert.equal(retry.state,'unknown');
242
224
  const exhausted=resumed.reconcileReview({invocationId:retry.reviewReconciliation.invocationId});
243
225
  assert.equal(exhausted.state,'blocked');assert.equal(spawns,2);
244
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,retry.reviewInvocation.registration.grant.grantDigest);
226
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,retry.reviewInvocation.registration.binding.requestDigest);
245
227
  }
246
228
  },{provider,timeoutMs:2000}));
247
229
 
@@ -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,13 +52,15 @@ 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
+ ||reviewMode==='second_lost_twice'&&[2,3].includes(reviews)
55
56
  ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1
56
- ||['rediagnosis_lost','rediagnosis_twice','rediagnosis_context'].includes(reviewMode)&&(reviews===2||reviewMode==='rediagnosis_twice'&&reviews===3))
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))
57
59
  throw Error('Synthetic lost review result');
58
60
  for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
59
61
  {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
60
62
  const outsidePath=reviewMode==='rediagnosis_invalid'&&reviews===2;
61
- const verdict=['changes_requested','second_lost'].includes(reviewMode)||reviewMode==='second_lost_retry'&&reviews===1
63
+ const verdict=['changes_requested','second_lost'].includes(reviewMode)||['second_lost_retry','second_lost_twice'].includes(reviewMode)&&reviews===1
62
64
  ||reviewMode?.startsWith('rediagnosis_')&&reviews===1||outsidePath?'changes_requested':'approved';
63
65
  return {status:'succeeded',value:{verdict,packageDigest:data.reviewPackage.packageDigest,
64
66
  examinedPaths:data.examinedPaths,
@@ -77,10 +79,10 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
77
79
  return crossLayer?{...diagnosis,crossLayer:true}:diagnosis;
78
80
  }
79
81
  if(kind==='fix_repair'){
80
- 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){
81
83
  loseRevisionRepair=false;throw Error('Lost revision repair answer');
82
84
  }
83
- 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'));
84
86
  return {outcome:'repaired'};
85
87
  }
86
88
  if(kind==='fix_retrospective')return (lesson===true||lesson==='revision'&&payload.identity.attempt===2)?{status:'lesson_candidate',candidates:[{classification:'memory_only',
@@ -103,7 +105,9 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
103
105
  owner=openFixExecution({...options,create:false},dependencies);
104
106
  };
105
107
  const reopen=()=>{owner.close();owner=openFixExecution({...options,create:false},dependencies);return owner;};
106
- 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};
107
111
  }
108
112
 
109
113
  test('an unknown red test needs explicit authorization and reason, then redoes with distinct records and evidence',async t=>{
@@ -435,16 +439,25 @@ test('#15 a no-result cause review is abandoned once, audited, and retried on a
435
439
  assert.equal(f.owner().status().causeReview.providerThreadId,'fixture-review-2');
436
440
  });
437
441
 
438
- 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=>{
439
443
  const f=await fixture(t,{reviewMode:'lost',crossLayer:true});
440
444
  await f.owner().advance({authorized:true});await causeDecide(f);
441
445
  assert.equal((await f.owner().reviewCause()).stage,'unknown');
442
446
  f.owner().abandonReview({authorized:true,reason:'First reviewer stopped'});
443
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);
444
455
  const again=await f.owner().reviewCause();
456
+ assert(f.records().some(row=>row.id==='fix-cause-retry-2-registered'));
445
457
  assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
446
458
  const before=fs.readFileSync(f.statePath);
447
- 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);
448
461
  assert.deepEqual(fs.readFileSync(f.statePath),before);
449
462
  });
450
463
 
@@ -496,6 +509,46 @@ test('#15 a no-result second-round final review is abandoned once and retried on
496
509
  assert.equal(f.reopen().status().stage,'revision_completion_gate_required');
497
510
  });
498
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
+
499
552
  test('#15 the retried cause review refuses the abandoned reviewer thread',async t=>{
500
553
  const f=await fixture(t,{reviewMode:'first_lost_same_thread',crossLayer:true});
501
554
  await f.owner().advance({authorized:true});await causeDecide(f);await f.owner().reviewCause();
@@ -554,12 +607,16 @@ test(`regression: a no-result round-2 cause review (${reviewMode}) is abandoned
554
607
  assert.equal(reopened.stage,'red_test_required');assert.equal(reopened.causeReview.providerThreadId,'fixture-review-3');
555
608
  });
556
609
 
557
- test('regression: a second no-result round-2 cause review exhausts that round\'s one-time abandonment without changing the store',async t=>{
558
- const f=await fixture(t,{reviewMode:'rediagnosis_twice',crossLayer:true});
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});
559
612
  await toRediagnosisReview(f);
560
613
  const host=()=>hostFor(f,['--allow-reproduction','--allow-abandon-review']);
561
614
  assert.equal((await host().handle({requestId:'a',operation:'abandon_review',reason:'First round-2 reviewer stopped'})).stage,'cause_review_required');
562
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);
563
620
  const again=await f.owner().reviewCause();
564
621
  assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
565
622
  const before=fs.readFileSync(f.statePath);
@@ -585,3 +642,99 @@ test('regression: the round-2 cause package carries the prior review\'s examined
585
642
  assert.equal(review.verdict,'approved');assert.deepEqual(review.findings.map(row=>row.path),['existing.mjs']);
586
643
  assert.equal(f.owner().status().stage,'red_test_required');
587
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
+ });
@@ -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
  //
@@ -60,11 +60,11 @@ const ASKS={
60
60
  const READ_ONLY=new Set(['status','final_review_package','completion_evidence','cause_review_package']);
61
61
  const KNOWN=new Set([...Object.keys(ASKS),...READ_ONLY,'cancel','handoff','publish_review','check_n5',
62
62
  'publish_dossier','learning_writeback','walkthrough','finish','final_review','cause_review',
63
- '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']);
64
64
 
65
65
  function loadPlan(){
66
66
  const {operation,plan,base}=loadPlanFile({name:'cm-fix-drive.mjs',known:KNOWN});
67
- const abandoning=['abandon_step','abandon_review'].includes(operation);
67
+ const abandoning=['abandon_step','abandon_review','rerun_blocked_step'].includes(operation);
68
68
  requireFields(plan,['config','cwd','mode','hostContext','permissions',...(abandoning||operation==='reconcile_review'?[]:['answers'])]);
69
69
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
70
70
  if(!Array.isArray(plan.permissions))stop(2,'permissions must be an array');
@@ -76,7 +76,7 @@ function loadPlan(){
76
76
  }else if(!['--execution-optimizations','--external-models'].includes(flag)&&!/^--allow-[a-z-]+$/.test(flag))stop(2,'invalid permissions');
77
77
  }
78
78
  if(operation==='reconcile_review'&&(plan.mode!=='resume'||typeof plan.invocationId!=='string'||!plan.invocationId))stop(2,'reconcile_review requires resume and original invocationId');
79
- 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';
80
80
  if(abandoning&&(!plan.permissions.includes(abandonFlag)||typeof plan.reason!=='string'
81
81
  ||!plan.reason.trim().length||Buffer.byteLength(plan.reason,'utf8')>1000||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))
82
82
  stop(2,`${operation} 需要 PLAN.reason(单行,最多 1000 字节)和 ${abandonFlag}`);
@@ -188,7 +188,7 @@ function hostArgs({plan,paths}){
188
188
  ...plan.permissions];
189
189
  }
190
190
 
191
- function answerFor(row,answers,paths){
191
+ export function answerFor(row,answers,paths){
192
192
  const {kind,payload}=row;
193
193
  if(kind==='fix_learning')return {contextDigest:payload.contextDigest,status:answers.learning.status,summary:answers.learning.summary};
194
194
  if(kind==='fix_diagnose')return answers.diagnosis;
@@ -198,6 +198,24 @@ function answerFor(row,answers,paths){
198
198
  if(requestAttempt!==undefined&&requestAttempt!==paths.round)
199
199
  throw Error(`修订轮次 ${requestAttempt} 与已预检答案轮次 ${paths.round} 不一致`);
200
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
+ }
201
219
  const edits=[];
202
220
  for(const [target,local] of Object.entries(map)){
203
221
  // 路径不在宿主给的范围里:不能硬塞,也不能断线(断线会把运行做死)。
@@ -205,7 +223,7 @@ function answerFor(row,answers,paths){
205
223
  if(!Object.hasOwn(expected,target)){stderr(`${target} 不在宿主本次允许的范围内,回 blocked`);return {outcome:'blocked',edits:[]};}
206
224
  edits.push({path:target,beforeSha256:expected[target],content:fs.readFileSync(path.join(paths.answers,local),'utf8')});
207
225
  }
208
- return {outcome:kind==='fix_repair'?'repaired':'authored',edits};
226
+ return {outcome:done,edits};
209
227
  }
210
228
  return null;
211
229
  }
@@ -215,7 +233,7 @@ function main(){
215
233
  const {answers,round}=preflight(loaded);
216
234
  const {operation,plan,paths}=loaded;
217
235
  driveHost({host:HOST,args:hostArgs(loaded).slice(1),cwd:path.resolve(plan.cwd),operation,
218
- 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}:{}),
219
237
  ...(operation==='prepare_revision'&&Object.hasOwn(plan,'revisionTests')?{tests:plan.revisionTests}:{})},
220
238
  answers,paths:{...paths,round},answerFor});
221
239
  }