@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
@@ -0,0 +1,251 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {spawnSync} from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {readRunDefinition,openControlRun} from './cm-ai-run.mjs';
8
+ import {cli,identity,request,fixture,runCli,installDispatchFakes,protectedResultFixture,implementedValue,lastCheckpoint,installTimeoutReviewer} from './cm-ai-host-fixture.mjs';
9
+
10
+ for(const [available,coder,reviewer,runtime] of [
11
+ ['codex','codex','codex','codex'],['codex','codex','codex','claude'],['claude','claude','claude','codex'],
12
+ ['both','codex','claude','claude'],['both','claude','codex','codex'],
13
+ ])test(`protected dispatch ${available}: ${runtime} host -> ${coder} coder -> ${reviewer} reviewer`,async()=>{
14
+ const f=fixture();
15
+ try{
16
+ installDispatchFakes(f);
17
+ fs.writeFileSync(path.join(f.codeProject,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available},
18
+ roles:{coder:{adapter:`${coder}-cli`},reviewer:{adapter:`${reviewer}-cli`}}}));
19
+ const preview=spawnSync(process.execPath,[cli,'preflight','--config',f.config,'--review-model','fixture','--runtime',reviewer],
20
+ {encoding:'utf8',env:f.env,timeout:5000});assert.equal(preview.status,0,preview.stderr);
21
+ const reviewFile=path.join(f.root,'review.json'),protectedFile=path.join(f.root,'protected.json');
22
+ fs.writeFileSync(reviewFile,preview.stdout);
23
+ fs.writeFileSync(protectedFile,JSON.stringify({model:'fixture',timeoutMs:5000,
24
+ checkCommands:[{id:'syntax',command:[process.execPath,'--check','target.mjs']}]}));
25
+ f.args.push('--runtime',runtime,'--review-config',reviewFile,'--protected-config',protectedFile);
26
+ const denied=await runCli(f,'normal');assert.equal(denied.code,1);assert.match(denied.stderr,/provider_development_authorization_required/);
27
+ assert(!fs.existsSync(path.join(f.codeProject,'target.mjs')));assert(!fs.existsSync(path.join(f.specsDir,'.reviews')));
28
+ f.args.push('--allow-provider-development-attempt','1');
29
+ const first=await runCli(f,'normal');assert.equal(first.code,0,first.stderr);
30
+ assert.equal(first.rows.find(row=>row.requestId==='advance').result.code,'decision_required');assert.deepEqual(first.calls,[]);
31
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 42;\n');
32
+ const readRoutes=()=>fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)
33
+ .filter(row=>row.phase==='route'&&row.event==='decision');
34
+ assert.equal(readRoutes().filter(row=>row.role==='coder'&&row.route_state===(coder===runtime?'current-runtime':'cli-dispatch')).length,1);
35
+ assert.equal(readRoutes().filter(row=>row.role==='reviewer').length,0);
36
+ f.args.push('--allow-review-attempt','2');
37
+ const wrong=await runCli(f,'normal','resume');assert.equal(wrong.rows.find(row=>row.requestId==='advance').result.code,'decision_required');
38
+ assert.equal(readRoutes().filter(row=>row.role==='reviewer').length,0);
39
+ f.args[f.args.length-1]='1';
40
+ const reviewed=await runCli(f,'normal','resume');assert.equal(reviewed.code,0,reviewed.stderr);
41
+ assert.equal(reviewed.rows.find(row=>row.requestId==='advance').result.state,'fixture_completed',JSON.stringify(reviewed.rows));
42
+ const route=readRoutes().find(row=>row.role==='reviewer');assert(route);
43
+ assert.equal(route.adapter,`${reviewer}-cli`);assert.equal(route.route_state,reviewer===runtime?'current-runtime':'cli-dispatch');
44
+ const receipt=fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md'),'utf8');
45
+ assert.match(receipt,new RegExp(`reviewer: ${reviewer}-cli`));assert.match(receipt,/independent: true/);
46
+ const gate=spawnSync(process.execPath,[fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url)),'check-n4',
47
+ '--handoff',path.join(f.specsDir,'.reviews','work-T-001-a1-handoff.json'),
48
+ '--reviews-dir',path.join(f.specsDir,'.reviews'),'--feature','work','--task','T-001','--project-root',f.codeProject],{encoding:'utf8'});
49
+ assert.equal(gate.status,0,gate.stderr);assert.equal(JSON.parse(gate.stdout).content_bound,true);
50
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
51
+ });
52
+
53
+ for(const available of ['unknown','codex'])test(`legacy protected ${available} run resumes with its original fingerprint and contexts`,async()=>{
54
+ const f=fixture();
55
+ try{
56
+ installDispatchFakes(f);
57
+ const projectConfig=path.join(f.codeProject,'.cm-workflow.json');
58
+ const declaration={version:1,...(available==='codex'?{runtimes:{available}}:{})};
59
+ fs.writeFileSync(projectConfig,JSON.stringify(declaration));
60
+ const preview=spawnSync(process.execPath,[cli,'preflight','--config',f.config,'--review-model','fixture'],
61
+ {encoding:'utf8',env:f.env,timeout:5000});assert.equal(preview.status,0,preview.stderr);
62
+ const reviewFile=path.join(f.root,'review.json'),protectedFile=path.join(f.root,'protected.json');
63
+ fs.writeFileSync(reviewFile,preview.stdout);
64
+ fs.writeFileSync(protectedFile,JSON.stringify({model:'fixture',timeoutMs:5000,
65
+ checkCommands:[{id:'syntax',command:[process.execPath,'--check','target.mjs']}]}));
66
+ // The original unmodified createCodexExecution constructs a genuine old run;
67
+ // no hand-written fingerprints, journals or approval receipts.
68
+ const initializer=path.join(f.root,'old-host.mjs');
69
+ fs.writeFileSync(initializer,`
70
+ import fs from 'node:fs';
71
+ import {readRunDefinition,createCodexExecution,openControlRun} from ${JSON.stringify(new URL('./cm-ai-run.mjs',import.meta.url).href)};
72
+ import {createHostReviewAuthority} from ${JSON.stringify(new URL('../runtime/js/cm-ai/host-review-authority.mjs',import.meta.url).href)};
73
+ const definition=readRunDefinition(${JSON.stringify(f.config)}),review=JSON.parse(fs.readFileSync(${JSON.stringify(reviewFile)}));
74
+ const config=JSON.parse(fs.readFileSync(${JSON.stringify(protectedFile)}));
75
+ const authority=createHostReviewAuthority({hostContextId:'native-host-fixture',reviewerId:'reviewer',adapterId:'codex-review-adapter',decide:async()=>null});
76
+ const execution=await createCodexExecution({codeProject:definition.codeProject,specsRoot:definition.specsDir,
77
+ developerModel:config.model,checkCommands:config.checkCommands,timeoutMs:config.timeoutMs,
78
+ hostContextId:'native-host-fixture',developerContextId:'cm-protected-author',reviewerModel:review.model,
79
+ reviewerPreflight:review.preflight,disabledSkills:review.disabledSkills},
80
+ {hostDecision:null,developmentAttempt:1,hostDecisionProvider:authority.hostDecisionProvider,authorizeReview:authority.authorize,
81
+ authorizeDevelopment:()=>({status:'approved'})});
82
+ const run=await openControlRun(definition,'create',execution);
83
+ try{console.log(JSON.stringify(await run.host.handle(${JSON.stringify(request('advance'))})));}finally{run.close();}
84
+ `);
85
+ const old=spawnSync(process.execPath,[initializer],{encoding:'utf8',env:f.env,timeout:10000});
86
+ assert.equal(old.status,0,old.stderr);assert.equal(JSON.parse(old.stdout).code,'decision_required');
87
+ f.args.push('--protected-config',protectedFile,'--allow-provider-development-attempt','1','--review-config',reviewFile,'--allow-review-attempt','1');
88
+ // A changed two-provider declaration cannot recover through Codex-only compatibility.
89
+ fs.writeFileSync(projectConfig,JSON.stringify({version:1,runtimes:{available:'both'},
90
+ roles:{coder:{adapter:'claude-cli'},reviewer:{adapter:'codex-cli'}}}));
91
+ const mismatch=await runCli(f,'normal','resume');assert.equal(mismatch.code,1);assert.match(mismatch.stderr,/fingerprint_mismatch/);
92
+ assert(!fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'),'utf8').includes('[x]'));
93
+ fs.writeFileSync(projectConfig,JSON.stringify(declaration));
94
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
95
+ assert.match(resumed.stderr,/resumed original Codex protected execution after exact fingerprint validation/);
96
+ assert.equal(resumed.rows.find(row=>row.requestId==='advance').result.state,'fixture_completed');
97
+ assert.deepEqual(resumed.calls,[]);
98
+ assert.match(fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md'),'utf8'),/reviewer: codex-cli/);
99
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
100
+ });
101
+
102
+
103
+ test('protected local invalid_result writes nothing and corrected CLI resume keeps run and attempt',async()=>{
104
+ const f=protectedResultFixture(),target=path.join(f.codeProject,'target.mjs');
105
+ try{
106
+ f.develop=payload=>{
107
+ assert.equal(payload.editMode,'protected-text-v1');assert.equal(payload.expected['target.mjs'],null);
108
+ return {status:'succeeded',value:{...implementedValue(),
109
+ retrospective:{status:'no_new_lesson',candidates:[],reason:'No new lesson'}},
110
+ edits:[{path:'target.mjs',beforeSha256:null,content:'export const value = 42;\n'}]};
111
+ };
112
+ for(const mode of ['create',...Array(6).fill('resume')]){
113
+ const rejected=await runCli(f,'normal',mode);assert.equal(rejected.code,0,rejected.stderr);
114
+ const result=rejected.rows.find(row=>row.requestId==='advance').result;
115
+ assert.equal(result.state,'blocked');assert.equal(result.code,'developer_result_invalid');
116
+ assert.equal(result.pendingAction,'resume');assert.deepEqual(result.identity,identity);
117
+ assert(!fs.existsSync(target));
118
+ const checkpoint=lastCheckpoint(f);assert.equal(checkpoint.calls.at(-1).terminal,'failed');
119
+ assert.deepEqual(checkpoint.calls.at(-1).failureResult,{code:'invalid_result',reason:'invalid_input',retryable:true});
120
+ }
121
+ f.develop=payload=>({status:'succeeded',value:implementedValue(),
122
+ edits:[{path:'target.mjs',beforeSha256:payload.expected['target.mjs'],content:'export const value = 42;\n'}]});
123
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
124
+ const result=resumed.rows.find(row=>row.requestId==='advance').result;
125
+ assert.equal(result.state,'awaiting_review');assert.equal(result.code,'decision_required');
126
+ assert.deepEqual(result.identity,identity);assert.equal(fs.readFileSync(target,'utf8'),'export const value = 42;\n');
127
+ assert.deepEqual(lastCheckpoint(f).calls.map(call=>call.terminal),[...Array(7).fill('failed'),'succeeded']);
128
+ const reopened=await runCli(f,'normal','resume');assert.equal(reopened.code,0,reopened.stderr);
129
+ assert.deepEqual(reopened.calls,[]);assert.equal(reopened.rows.find(row=>row.requestId==='advance').result.code,'decision_required');
130
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
131
+ });
132
+
133
+ for(const matches of [true,false])test(`protected old proposal compares exact output with expected disk hashes: matches=${matches}`,async()=>{
134
+ const f=protectedResultFixture(),target=path.join(f.codeProject,'target.mjs');
135
+ try{
136
+ // Simulate a proposal already applied before this invocation was rejected.
137
+ const content='export const value = 42;\n';
138
+ f.develop=()=>({status:'succeeded',value:{...implementedValue(),
139
+ retrospective:{status:'no_new_lesson',candidates:[],reason:'invalid'}},edits:[]});
140
+ const failed=await runCli(f,'normal');assert.equal(failed.code,0,failed.stderr);
141
+ assert.equal(failed.rows.find(row=>row.requestId==='advance').result.code,'developer_result_invalid');
142
+ fs.writeFileSync(target,matches?content:'export const value = 99;\n');
143
+ const before=fs.readFileSync(target);
144
+ f.develop=()=>({status:'succeeded',value:implementedValue(),
145
+ edits:[{path:'target.mjs',beforeSha256:null,content}]});
146
+ const run=await runCli(f,'normal','resume');assert.equal(run.code,0,run.stderr);
147
+ const result=run.rows.find(row=>row.requestId==='advance').result;
148
+ assert.equal(result.state,matches?'awaiting_review':'blocked');
149
+ assert.equal(result.code,matches?'decision_required':'protected_edit_stale');
150
+ assert.deepEqual(fs.readFileSync(target),before);
151
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
152
+ assert.deepEqual(resumed.calls,[]);
153
+ assert.equal(resumed.rows.find(row=>row.requestId==='advance').result.code,result.code);
154
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
155
+ });
156
+
157
+ for(const mode of ['blocked','disconnect'])test(`protected ${mode} cannot use the local invalid-result retry entry`,async()=>{
158
+ const f=protectedResultFixture();
159
+ try{
160
+ f.develop=()=>({status:'succeeded',value:{...implementedValue(),outcome:'blocked'},edits:[]});
161
+ const result=await runCli(f,mode==='disconnect'?'disconnect':'normal');assert.equal(result.code,0,result.stderr);
162
+ const status=result.rows.find(row=>row.requestId==='advance').result;
163
+ assert.equal(status.state,mode==='blocked'?'blocked':'unknown');
164
+ assert.equal(status.code,mode==='blocked'?'failed':'unknown');
165
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
166
+ assert.deepEqual(resumed.calls,[]);
167
+ assert.equal(resumed.rows.find(row=>row.requestId==='advance').result.state,status.state);
168
+ assert(!fs.existsSync(path.join(f.codeProject,'target.mjs')));
169
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
170
+ });
171
+
172
+ for(const variant of ['delete-absent','missing-edits','extra-field'])test(`protected malformed proposal ${variant} fails before sandbox writes`,async()=>{
173
+ const f=protectedResultFixture();
174
+ try{
175
+ f.develop=()=>({status:'succeeded',value:implementedValue(),
176
+ ...(variant==='missing-edits'?{}:{edits:[{path:'target.mjs',beforeSha256:null,
177
+ content:variant==='delete-absent'?null:'export const value = 42;\n'}]}),
178
+ ...(variant==='extra-field'?{extra:true}:{})});
179
+ const result=await runCli(f,'normal');assert.equal(result.code,0,result.stderr);
180
+ const status=result.rows.find(row=>row.requestId==='advance').result;
181
+ assert.equal(status.state,'blocked');assert.equal(status.code,'developer_result_invalid');
182
+ assert.equal(lastCheckpoint(f).calls.at(-1).terminal,'failed');
183
+ assert(!fs.existsSync(path.join(f.codeProject,'target.mjs')));
184
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
185
+ });
186
+
187
+
188
+ for(const [runtime,second] of [['codex','approved'],['claude','approved'],['codex','timeout'],['codex','result'],['claude','result']])
189
+ test(`protected conversation review timeout ${runtime} -> ${second}`,async()=>{
190
+ const f=protectedResultFixture();
191
+ try{
192
+ f.runtime=runtime;f.args.push('--runtime',runtime);
193
+ const setMode=installTimeoutReviewer(f,runtime);
194
+ const preview=spawnSync(process.execPath,[cli,'preflight','--config',f.config,'--review-model','fixture','--runtime',runtime],
195
+ {encoding:'utf8',env:f.env,timeout:5000});assert.equal(preview.status,0,preview.stderr);
196
+ const review=JSON.parse(preview.stdout);assert.equal(review.timeoutMs,900000);
197
+ delete review.timeoutMs;
198
+ const config=path.join(f.root,'review.json');fs.writeFileSync(config,JSON.stringify(review));
199
+ f.args.push('--review-config',config,'--allow-review-attempt','1');
200
+ f.develop=payload=>({status:'succeeded',value:implementedValue(),
201
+ edits:[{path:'target.mjs',beforeSha256:payload.expected['target.mjs'],content:'export const value = 42;\n'}]});
202
+ setMode(second==='result'?'result':'timeout');
203
+ const start=Date.now(),first=await runCli(f,'normal');assert.equal(first.code,0,first.stderr);
204
+ const result=first.rows.find(row=>row.requestId==='advance').result;
205
+ // A legacy review config without timeoutMs inherits the protected conversation's 5s reviewer budget.
206
+ assert(Date.now()-start>=4900);assert(Date.now()-start<14000);
207
+ assert.equal(result.state,second==='result'?'unknown':'pending_review');
208
+ assert.equal(result.code,second==='result'?'transport_timeout':'review_transport_timeout');
209
+ // A final message cut off by the timeout is never retried by itself; its
210
+ // only exit is the explicit, audited abandon_review (see cm-ai-review-failure).
211
+ assert.equal(result.pendingAction,second==='result'?'abandon_review':'resume');
212
+ const before=lastCheckpoint(f),original=before.reviewInvocation;
213
+ assert.equal(before.calls.at(-1).terminal,second==='result'?'unknown':'failed');
214
+ assert.equal(original.result.outcome,'timed_out');
215
+ assert.equal(original.result.reconciliationRequired,second==='result');
216
+ assert.equal(original.result.inspection.code,'transport_timeout');
217
+ assert.equal(original.result.observation.events.at(-1).event,'process_closed');
218
+ assert.equal(original.result.observation.events.at(-1).timed_out,true);
219
+ const snapshot=()=>JSON.parse(fs.readFileSync(path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json')));
220
+ const {readRunnerHistory}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
221
+ const history=snapshot(),configuration=history.records[0].payload.config;
222
+ assert.equal(readRunnerHistory(history.records,configuration,3).state.state,result.state);
223
+ // Prefix recovery never redispatches an invocation whose checkpoint is absent.
224
+ for(const type of ['review-invocation-registered','review-invocation-started','review-invocation-result']){
225
+ const index=history.records.findIndex(row=>row.payload.type===type);
226
+ const recovered=readRunnerHistory(history.records.slice(0,index+1),configuration,3);
227
+ assert.equal(recovered.state.state,'unknown');assert.equal(recovered.state.code,'reconciliation_required');
228
+ }
229
+ setMode(second==='result'?'approved':second);
230
+ const resumed=await runCli(f,'normal','resume');assert.equal(resumed.code,0,resumed.stderr);
231
+ const end=resumed.rows.find(row=>row.requestId==='advance').result,after=lastCheckpoint(f);
232
+ assert.deepEqual(end.identity,identity);assert.deepEqual(resumed.calls,[]);
233
+ if(second==='result'){
234
+ assert.equal(end.state,'unknown');assert.deepEqual(after,before);
235
+ }else{
236
+ assert.equal(end.state,second==='approved'?'fixture_completed':'blocked');
237
+ assert.equal(end.code,second==='approved'?'qa_decision_required':'review_transport_timeout');
238
+ assert.equal(after.cache.find(entry=>entry.effect.id==='review-1-retry-1').effect.identity.attempt,1);
239
+ assert.notEqual(after.reviewInvocation.registration.grant.invocationId,original.registration.grant.invocationId);
240
+ assert.notEqual(after.reviewInvocation.registration.grant.grantId,original.registration.grant.grantId);
241
+ assert.notEqual(after.reviewInvocation.started,original.started);
242
+ assert.deepEqual(after.calls.slice(0,before.calls.length),before.calls);
243
+ assert.deepEqual(after.cache.slice(0,before.cache.length),before.cache);
244
+ if(second==='timeout'){
245
+ const blocked=await runCli(f,'normal','resume');assert.equal(blocked.code,0,blocked.stderr);
246
+ assert.equal(blocked.rows.find(row=>row.requestId==='advance').result.state,'blocked');
247
+ assert.deepEqual(lastCheckpoint(f),after);
248
+ }else assert(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'),'utf8').includes('[x] T-001'));
249
+ }
250
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
251
+ });
@@ -12,7 +12,7 @@ import {fileURLToPath} from 'node:url';
12
12
  import {REVIEWED_HANDOFF_HINT} from '../runtime/js/cm-ai/host-handoff.mjs';
13
13
  import {readRunDefinition,openControlRun,createCodexExecution,assertCreatableScope} from './cm-ai-run.mjs';
14
14
  import {createConversationExecution as executionFor} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
15
- import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
15
+ import {createHostToolBridge,HOST_ANSWER_BACKSTOP_MS} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
16
16
  import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
17
17
  import {createQaFixOwnerHost} from '../runtime/js/cm-ai/host-qa-fix-owner.mjs';
18
18
  import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
@@ -21,7 +21,7 @@ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authori
21
21
  import {loadConfig,declaredRuntimes,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
22
22
  import {readHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
23
23
  import {digest,json,need,shape,id} from '../runtime/js/cm-ai/effect-contract.mjs';
24
- export {executionFor as createConversationExecution,reviewConfiguration as readConversationReviewConfiguration};
24
+ export {executionFor as createConversationExecution,reviewConfiguration as readConversationReviewConfiguration,reviewConfigurationValue as readConversationReviewConfigurationValue};
25
25
  export function withHandoffDiagnostic(host,error){
26
26
  return {...host,async handle(request){
27
27
  const result=await host.handle(request);
@@ -48,10 +48,10 @@ const REASONED_CODES=['supersede_unavailable','supersede_code_drift','handoff_ex
48
48
  'browser_capability_unavailable','invalid_arguments','fingerprint_mismatch','task_selection_mismatch','review_configuration_required',
49
49
  'spec_rebind_refused','spec_rebind_unavailable','protected_scope'];
50
50
  const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon',
51
- 'abandon-review','test-author','repair','cause-review','final-review']
51
+ 'abandon-review','test-author','repair','cause-review','final-review','rediagnosis','rerun-blocked-step','final-review-recovery']
52
52
  .map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
53
53
 
54
- const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--review-runtime codex|claude] [--feature N.slug] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
54
+ const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--review-runtime codex|claude] [--feature N.slug] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--allow-develop-redo] [--hold-revision] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
55
55
 
56
56
  export function formatClaudeModelHint(config,version=null){
57
57
  const marker=config?.preflight?.request_checks?.find(check=>check?.model_recognized===false);
@@ -74,7 +74,11 @@ export async function serveHostTransport(options,rawInputLimit,serve=serveCmAiHo
74
74
  function reviewConfiguration(file,pair=null){
75
75
  const info=fs.lstatSync(file);
76
76
  need(info.isFile()&&!info.isSymbolicLink()&&info.size<=64*1024,'invalid_review_config');
77
- let config=json(JSON.parse(fs.readFileSync(file,'utf8')));
77
+ return reviewConfigurationValue(JSON.parse(fs.readFileSync(file,'utf8')),pair);
78
+ }
79
+ // Same validation for bytes the caller already read (and pinned) itself.
80
+ function reviewConfigurationValue(raw,pair=null){
81
+ let config=json(raw);
78
82
  if(pair){need(!Object.hasOwn(config,'model')||config.model===pair.model,'external_model_configuration_conflict');
79
83
  need(!Object.hasOwn(config,'effort')||config.effort===pair.effort,'external_model_configuration_conflict');config={...config,...pair};}
80
84
  shape(config,['model','preflight',...(pair?['effort']:[]),...(Object.hasOwn(config,'disabledSkills')?['disabledSkills']:[]),
@@ -181,17 +185,19 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
181
185
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--auto-qa-fix optionally connects parent advance -> fix_run -> re-QA. Requires --qa-fix-template-config, --allow-qa-fix-start, original action permissions and project policies.auto_fix=auto. Explicit/never policies stop. Unknown, blocked or incomplete repair stops; status/cancel remain available and no fourth QA round is dispatched.\n');
182
186
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--qa-fix-template-config PATH is an alternative to --qa-fix-owner-config. Supply {specsRoot, feature, identity: parent identity, configuration: original fix configuration without qaSource}. Each fix request binds it to the latest completed QA failure; identity/digests are generated, commands/scope/permissions are not. Existing child configuration remains immutable.\n');
183
187
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_run continuously executes normal stages of the fixed QA child using the same binding as fix_advance. Requires --allow-qa-fix-start and every original per-action permission/configuration. Stops on unknown, blocked, observation, revision-required or unchanged state; a design-change child closes as escalated and reports qa_fix_incomplete, never qa_fix_completed. It does not auto-switch child configuration or run parent QA.\n');
184
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_action delegates to the shared original cm-fix dispatcher. Local flags: --allow-qa-fix-red-test, --allow-qa-fix-baseline, --allow-qa-fix-regression, --allow-qa-fix-learning-writeback, --allow-qa-fix-walkthrough, --allow-qa-fix-finish, --allow-qa-fix-abandon, --allow-qa-fix-abandon-review. abandon_step also requires a reason in the fix_action request and only applies to eligible local unknown steps; abandon_review requires --allow-qa-fix-abandon-review and a reason, and applies once to the child cause review and once to its second-round final review while that registered review has no review result. The parent run\'s own --allow-abandon-review does not reach the child. Adapter flags: --allow-qa-fix-test-author, --allow-qa-fix-repair, --allow-qa-fix-cause-review, --allow-qa-fix-final-review, with separate --qa-fix-review-config PATH and matching original child reviewer metadata. All require --allow-qa-fix-start and the original action configuration/gates. Parent --review-config/--allow-review-attempt do not grant child review permission.\n');
188
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('fix_action delegates to the shared original cm-fix dispatcher. Local flags: --allow-qa-fix-red-test, --allow-qa-fix-baseline, --allow-qa-fix-regression, --allow-qa-fix-learning-writeback, --allow-qa-fix-walkthrough, --allow-qa-fix-finish, --allow-qa-fix-abandon, --allow-qa-fix-abandon-review, --allow-qa-fix-rediagnosis, --allow-qa-fix-rerun-blocked-step, --allow-qa-fix-final-review-recovery [--qa-fix-final-review-recovery-invocation ID]. Recovery fixOperations rediagnose, rerun_blocked_step (reason), revision_test_check (regression flag) and recover_final_review ({invocationId, reviewPackageDigest = the child final review package digest, previousInvocationStopped:true, reason}) go to the same cm-fix dispatcher with the same conditions as cm-fix-host; a missing flag returns qa_fix_action_authorization_required naming the parent flag, a cm-fix refusal returns its own code, and the parent reopens either way. abandon_step also requires a reason in the fix_action request and only applies to eligible local unknown steps; abandon_review requires --allow-qa-fix-abandon-review and a reason, and applies once to the child cause review and once to its second-round final review while that registered review has no review result. The parent run\'s own --allow-abandon-review does not reach the child. Adapter flags: --allow-qa-fix-test-author, --allow-qa-fix-repair, --allow-qa-fix-cause-review, --allow-qa-fix-final-review, with separate --qa-fix-review-config PATH and matching original child reviewer metadata. All require --allow-qa-fix-start and the original action configuration/gates. Parent --review-config/--allow-review-attempt do not grant child review permission.\n');
185
189
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-qa-fix-start additionally permits fix_advance to create or resume the fixed QA child and run only its original Learning/reproduction/diagnosis stages. Child runtime must match this host. A new child hostContextId must be the live session or the parent durable creator; an existing child retains its fingerprint-verified configuration. Child opens and review grants use the live session. It does not authorize test authoring, repair, independent provider Review, finish, Git or re-QA. Active child status/cancel use the original child owner; repeated advance never resets an unknown or completed step.\n');
186
190
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--qa-fix-owner-config PATH enables read-only fix_status. The file contains the existing fix owner definition {specsRoot, identity, configuration}, including its exact original qaSource and immutable configuration, not provider grants. fix_status binds the parent identity/packageDigest/testRunId, serially closes the parent writer, opens only an existing child, reads its original completion evidence, closes it and resumes the same parent. It does not create/execute repairs, rerun QA or clear correction gates.\n');
187
191
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session invalid_result means local value/Learning validation failed before file writes. Fix the reply, keep the same configuration, host identity and runId, restart with --mode resume and advance: blocked/developer_result_invalid retries develop at the same attempt. no_new_lesson requires reason:null (dogfood incident: nonempty reason previously wrote files then stranded the run as unknown). Already-applied proposals must match expected disk hashes; conflicts block as protected_edit_stale. Worker exceptions/timeouts and old unknown history are not retryable.\n');
188
192
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('New cm-ai runs carry approved specification data in developer requests and review packages: task/verification, all AC lines, design (64 KiB UTF-8 maximum, truncated:true above it), task-related test cases and manifest hashes. Sources must match .cm-specs-status.specFiles or spec_drift blocks. requirements may be [] or additional code-project files; specs never become writable scope. Legacy runs/packages retain their original representation. Dogfood: separate specs/code roots previously left developers and reviewers without task/interface contracts.\n');
189
193
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Completed fixture_completed runs originally without QA may explicitly attach N6 once on --mode resume with --workflow-config (non-null qa) and --allow-qa. Original definition, scope, requirements, identity and non-workflow configuration must match. The immutable qa-attached journal record binds the full resumed config fingerprint; later resumes require that same configuration and fresh --allow-qa. qa still requests qa_assess; no automatic decision or repeated development/Review. Dogfood: missing workflow at create previously stranded mandatory feature QA.\n');
190
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated.\n');
191
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-blocked-qa requires --mode resume, the original --workflow-config and fresh --allow-qa. Only the latest completed BLOCKED invocation with zero failures and exclusively host/environment evidence gaps can be superseded: browser evidenceProblem, failed cleanup, environment mismatch, host timeout or a host-declared BLOCKED answer; logic INSUFFICIENT_EVIDENCE or blocked only by a mapped command without exit code; QA commands that produced no exit code (timeout, killed, spawn/output failure). Missing/deferred command rows ([需确认], commands-unavailable, no-applicable-cases, no browser capability) and source drift are excluded. A new testRunId reruns every case at qaRound+1 (maximum 3, the shared QA round budget); superseded and start link previous_test_run_id. The flag is consumed once, never persisted; no development/Review/task replay or new QA decision. Do not combine with --rerun-unknown-qa.\n');
194
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated. Exception: a call stopped as a whole (qa_execution_timeout) with no report and no FAIL, whose every case_blocked is a host request timeout (host_request_timeout: true; an older row without that field needs the full qa.timeoutMs elapsed since case_start plus an operator --qa-environment-failure REASON attesting no session answer, recorded verbatim as legacy_timeout_attestation, otherwise qa_environment_failure_required) and never session-declared, is superseded (reason host_request_timeout) and rerun at qaRound+1; --rerun-blocked-qa on it is refused as qa_rerun_unknown_qa_required. The same applies to a call stopped as a whole (timeout, host death or a hard-invalid answer) whose other BLOCKED rows were session-declared or host-judged evidence/environment/cleanup gaps (blocked_reason): they are listed as host_blocked_cases. The whole-round deadline scales with the frozen plan (commands x command timeout, logic cases x request window, browser cases x two windows, plus one minute; at least 30 minutes, at most 24 hours). A cleanup_failed QA command resource whose recorded process group the host proves gone is released first (released_by host_verified).\n');
195
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-blocked-qa requires --mode resume, the original --workflow-config and fresh --allow-qa. Only the latest completed BLOCKED invocation with zero failures and exclusively host/environment evidence gaps can be superseded: browser evidenceProblem, failed cleanup, environment mismatch, host timeout or a host-declared BLOCKED answer; logic INSUFFICIENT_EVIDENCE or blocked only by a mapped command without exit code; QA commands that produced no exit code (timeout, killed, spawn/output failure). Missing/deferred command rows ([需确认], commands-unavailable, no-applicable-cases, no browser capability) and source drift are excluded. A new testRunId reruns every case at qaRound+1 (three rounds, plus at most two given back for rounds superseded for host or answer problems: host_request_timeout, host_evidence_problem); superseded and start link previous_test_run_id. The flag is consumed once, never persisted; no development/Review/task replay or new QA decision. Do not combine with --rerun-unknown-qa.\n');
192
196
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('For a QA decision an older host recorded as blocked/host_request_timeout, --rerun-blocked-qa instead re-asks qa_assess once and appends a decision linked by previous_decision_id; history is kept (current hosts report a missed qa_assess window as retryable rejected/qa_decision_timeout and record nothing). --qa-environment-failure REASON (with --rerun-blocked-qa, single line, at most 500 UTF-8 bytes) declares that the non-zero QA command exits of the latest completed FAIL came from the environment: only command exits and logic cases failed solely by them qualify, never browser FAIL or CONTRADICTED; the superseded row records reason, failed_cases and blocked_cases. Every rerun reuses the three-round QA budget. Single-task host only.\n');
193
197
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-abandon-review: resume 原 run 后发送 abandon_review,request.reason 必须是单行且不超过 500 UTF-8 字节。操作员先确认旧 host 与 review 进程已退出;旗标只消费一次,不写入配置。\n');
194
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-abandon-effect: resume 原 run 后发送 abandon_effect,request.reason 必须是单行且不超过 500 UTF-8 字节。操作员须确认旧 host 和 effect 启动的检查/构建进程均已退出;仅当前会话 develop/complete 且无 task-commit-intent 时可用。\n');
198
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-abandon-effect: resume 原 run 后发送 abandon_effect,request.reason 必须是单行且不超过 500 UTF-8 字节。用于宿主在 develop/review(登记前)/complete(无 task-commit-intent)中途退出、只留下意图的运行:操作员先确认旧 host、会话写入和 effect 启动的检查/构建进程均已退出,宿主写 effect-interrupted,运行不作废,而从这一步的可重试阻断继续(develop_interrupted 后 advance 重发本轮;审查回到 awaiting_review;完成回到原状态)。provider 开发须存档记有 worker 进程身份且宿主核对进程组已退出;受保护当前会话开发须代码根仍等于本轮起点。已登记且本轮重派已用完的审查仍按旧规则作废运行(effect-abandoned),之后可 supersede。写了 task-commit-intent 的完成改发 complete 按提交计划收尾。\n');
199
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--hold-revision: 本次启动在第 1 轮审查要求修改后停在 changes_requested(revision_answer_required),不发起第 2 轮开发意图;只缩小本次启动,不写入配置,下次不带它即继续修订。\n');
200
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-develop-redo: resume 原 run 后发送 develop_redo,request.reason 必须是单行且不超过 500 UTF-8 字节。当前会话开发(非受保护)的应答没拿到,或 provider 开发结果不明且存档记有 worker 进程身份(宿主先核对进程组已退出),pendingAction=develop_redo 时可用;操作员先确认会话已停止修改代码,宿主写入 develop-answer-redo 记录,之后 advance 重发本轮开发。旗标只消费一次,不写入配置。\n');
195
201
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-bootstrap-review-recovery: resume 原 run 后发送 bootstrap_review_recover;只在 bootstrap develop 已完成且审查包构建失败时核对现有文件、handoff 与原始证据,并追加恢复记录,不重新派发开发。\n');
196
202
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--supersede-reviewed-evidence --supersede-reason REASON:仅新建同任务运行;旧运行都已终止且 tasks.md 未勾选时,先在新 journal 记授权,再归档旧审查证据。若保留直接前驱运行留下的代码漂移,可额外使用 --accept-superseded-code-drift;漂移文件会作为新运行的已有代码并记录当前 SHA-256。\n');
197
203
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rebind-spec-material --spec-rebind-reason REASON:仅 resume。规格经 cm-prd --change 重新批准后,若本任务的描述、验证要求、验收标准、设计摘录与测试用例都未变,只换绑批准哈希并写 specification-rebound 记录,已有开发与审查结论保留;内容有变则拒绝并列出变化。status 的 spec_drift 会说明是否可换绑。\n');
@@ -223,8 +229,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
223
229
  const extra=new Map();
224
230
  for(let index=8;index<argv.length;index++){
225
231
  const name=argv[index];refuse(!extra.has(name),'invalid_arguments',`参数重复:${name}`);
226
- refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--review-runtime','--feature','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
227
- if(['--execution-optimizations','--external-models','--verification-precheck','--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material','--allow-bootstrap-write','--allow-qa','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
232
+ refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--allow-develop-redo','--hold-revision','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--review-runtime','--feature','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--qa-fix-final-review-recovery-invocation','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
233
+ if(['--execution-optimizations','--external-models','--verification-precheck','--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material','--allow-bootstrap-write','--allow-qa','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--allow-develop-redo','--hold-revision','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
228
234
  else{refuse(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments',`${name} 需要一个值`);extra.set(name,argv[++index]);}
229
235
  }
230
236
  let inputLimit;
@@ -241,6 +247,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
241
247
  'spec_rebind_unavailable','--rebind-spec-material 只用于 --mode resume,并须同时提供单行 --spec-rebind-reason 原因');
242
248
  need(!extra.has('--allow-abandon-effect')||argv[4]==='resume','effect_abandon_unavailable');
243
249
  need(!extra.has('--allow-bootstrap-review-recovery')||argv[4]==='resume','bootstrap_review_recovery_unavailable');
250
+ need(!extra.has('--allow-develop-redo')||argv[4]==='resume','develop_redo_unavailable');
244
251
  const qaConfigRevision=revisionRequested?{previousWorkflow:readHostWorkflowConfiguration(extra.get('--revise-qa-config')),
245
252
  reason:extra.get('--qa-config-revision-reason')}:null;
246
253
  const originalHostContextId=extra.get('--original-host-context')??null;
@@ -254,13 +261,17 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
254
261
  workflow===null?'--allow-qa 需要同时提供 --workflow-config':'--allow-qa 需要 --workflow-config 中的 qa 不为 null;本运行没有 QA 时去掉 --allow-qa');
255
262
  need(!(extra.has('--rerun-unknown-qa')&&extra.has('--rerun-blocked-qa')),'qa_recovery_authorization_required');
256
263
  need(!(extra.has('--rerun-unknown-qa')||extra.has('--rerun-blocked-qa'))||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
257
- need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa'),'qa_recovery_authorization_required');
264
+ need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa')||extra.has('--rerun-unknown-qa'),'qa_recovery_authorization_required');
258
265
  const hasFix=extra.has('--qa-fix-owner-config')||extra.has('--qa-fix-template-config');
259
266
  need(!(extra.has('--qa-fix-owner-config')&&extra.has('--qa-fix-template-config')),'invalid_fix_config');
260
267
  need(!extra.has('--allow-qa-fix-start')||hasFix,'qa_fix_source_required');
261
268
  need(!extra.has('--qa-fix-review-config')||hasFix,'qa_fix_source_required');
262
269
  need(!extra.has('--auto-qa-fix')||(extra.has('--qa-fix-template-config')&&extra.has('--allow-qa-fix-start')),'qa_fix_auto_authorization_required');
263
270
  need(![...fixLocalPermissions.keys()].some(flag=>extra.has(flag))||extra.has('--allow-qa-fix-start'),'qa_fix_start_authorization_required');
271
+ // Same binding as cm-fix-host --final-review-recovery-invocation, for the child.
272
+ refuse(!extra.has('--qa-fix-final-review-recovery-invocation')||extra.has('--allow-qa-fix-final-review-recovery'),'invalid_arguments',
273
+ '--qa-fix-final-review-recovery-invocation 需要同时提供 --allow-qa-fix-final-review-recovery');
274
+ if(extra.has('--qa-fix-final-review-recovery-invocation'))id(extra.get('--qa-fix-final-review-recovery-invocation'));
264
275
  need(!extra.has('--allow-provider-development-attempt')||extra.has('--protected-config'),'protected_configuration_required');
265
276
  refuse(!(extra.has('--review-runtime')&&(extra.has('--protected-config')||extra.has('--external-models'))),'invalid_arguments',
266
277
  '--review-runtime 只用于普通当前会话宿主;--protected-config 与 --external-models 按 roles 自行选择审查端');
@@ -293,7 +304,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
293
304
  workflow?.qa!=null&&featureHasBrowserCases(definition.specsDir,definition.feature,definition.codeProject)
294
305
  ?[workflow.qa.environment?.carrier??'browser']:[]);
295
306
  // Tool replies travel on the same input lines, so they share the one limit.
296
- bridge=createHostToolBridge({responseLimit:inputLimit});
307
+ bridge=createHostToolBridge({responseLimit:inputLimit,answerTimeoutMs:HOST_ANSWER_BACKSTOP_MS});
297
308
  // Startup-only role failover. The project's runtimes.available declaration is
298
309
  // primary: it fixes which runtimes may be chosen and, via roles.coder, the
299
310
  // requested start runtime. The CLI probe only confirms reachability. It never
@@ -330,7 +341,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
330
341
  if(argv[4]==='resume'&&!extra.has('--original-host-context')&&extra.has('--protected-config')&&!externalModels&&!executionPolicy&&canResumeLegacyProtected(definition,runtime)){
331
342
  try{
332
343
  execution=await legacyProtectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap);
333
- run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),specRebindReason:extra.get('--spec-rebind-reason')??null});
344
+ run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),allowDevelopRedo:extra.has('--allow-develop-redo'),...(extra.has('--hold-revision')?{holdRevision:true}:{}),specRebindReason:extra.get('--spec-rebind-reason')??null});
334
345
  error.write('cm-ai-host: resumed original Codex protected execution after exact fingerprint validation.\n');
335
346
  }catch(cause){
336
347
  if(!['fingerprint_mismatch','tool_preflight_missing'].includes(cause.code))throw cause;
@@ -342,7 +353,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
342
353
  ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap,externalModels,executionPolicy)
343
354
  :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),runtime,
344
355
  {...(extra.has('--review-runtime')?{reviewRuntime:extra.get('--review-runtime')}:{}),...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),...(extra.has('--verification-precheck')?{verificationPrecheck:true}:{}),...(extra.has('--original-host-context')?{originalHostContextId:extra.get('--original-host-context')}:{}),...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
345
- run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),specRebindReason:extra.get('--spec-rebind-reason')??null});
356
+ run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),allowDevelopRedo:extra.has('--allow-develop-redo'),...(extra.has('--hold-revision')?{holdRevision:true}:{}),specRebindReason:extra.get('--spec-rebind-reason')??null});
346
357
  }
347
358
  if(run.blocked){output.write(JSON.stringify({outcome:'blocked',admission:run.blocked})+'\n');return 1;}
348
359
  if(hasFix){
@@ -370,7 +381,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
370
381
  }else if(fixReview)need(digest(fix.configuration.causeReview??null)===digest(fixReviewHost.reviewer),'qa_fix_review_configuration_mismatch');
371
382
  const host=createQaFixOwnerHost({parent:run,hostContextId:argv[6],parentHostContextId:execution.configuration.hostContextId,...(templated?{template:fix}:{fix}),reopenParent:()=>openControlRun(definition,'resume',execution),
372
383
  externalModels:fixModels,executionPolicy,fixPermissions,fixAuthorities:{authority:fixReviewHost.authority,finalAuthority:fixReviewHost.finalAuthority},
373
- allowStart:extra.has('--allow-qa-fix-start'),autoFix:extra.has('--auto-qa-fix'),fixExecution:{bridge,...fixReviewHost.execution,
384
+ allowStart:extra.has('--allow-qa-fix-start'),autoFix:extra.has('--auto-qa-fix'),
385
+ recoveryInvocationId:extra.get('--qa-fix-final-review-recovery-invocation')??null,fixExecution:{bridge,...fixReviewHost.execution,
374
386
  prepare:createFixLearningPreparation({bridge,codeProject:definition.codeProject,
375
387
  applicableAgentFiles:fix.configuration.applicableAgentFiles??[]})}});
376
388
  run={host,close:host.close};