@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
@@ -0,0 +1,103 @@
1
+ // V2 + R3 (P1-2): a current-session develop whose answer never arrived (timed
2
+ // out after writing, disconnected) cannot be redispatched until the operator
3
+ // confirms the session stopped (develop_redo + reason, journaled). The redo
4
+ // keeps the edits on disk; the package is built against the task baseline and
5
+ // reviewed, so nothing written during the lost answer skips review.
6
+ import test from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
11
+ import {gapFixture,gapExecution,gapSession,records,added} from './cm-ai-answer-gap-fixture.mjs';
12
+
13
+ const hangAfterWrite={write:'half written\n',response:new Promise(()=>{})};
14
+
15
+ test('develop_answer_missing: a develop that timed out after writing waits for develop_redo, then redoes the round',async t=>{
16
+ const f=gapFixture(t,'redo');
17
+ const [stuck]=await gapSession(f,'create',gapExecution(f,{developer:[hangAfterWrite]}),[['advance',1]]);
18
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','develop_answer_missing','develop_redo'],JSON.stringify(stuck));
19
+ assert.match(stuck.reason,/代码根已变化/);assert.equal(stuck.guidance.recoveryOperation,'develop_redo');
20
+ const before=records(f);
21
+ // The journal is what older runtimes wrote: unknown/call_timeout.
22
+ assert.deepEqual([before.at(-1).payload.checkpoint.state,before.at(-1).payload.checkpoint.code],['unknown','call_timeout']);
23
+ // advance alone never redispatches; develop_redo needs its launch flag.
24
+ const [advanced,refused]=await gapSession(f,'resume',gapExecution(f),[['advance',1],['develop_redo',1,{reason:'会话已停止'}]]);
25
+ // advance reports the block without even trying a develop effect.
26
+ assert.deepEqual([advanced.outcome,advanced.code,advanced.pendingAction],['reported','develop_answer_missing','develop_redo'],JSON.stringify(advanced));
27
+ assert.equal(records(f).length,before.length);
28
+ assert.deepEqual([refused.outcome,refused.code],['rejected','develop_redo_authorization_required']);
29
+ // Confirmed: develop-answer-redo, then advance redoes the round with a new effect id.
30
+ const [confirmed,status]=await gapSession(f,'resume',gapExecution(f),
31
+ [['develop_redo',1,{reason:'会话已停止修改代码'}],['status',1]],{allowDevelopRedo:true});
32
+ assert.equal(confirmed.outcome,'recorded',JSON.stringify(confirmed));
33
+ assert.deepEqual([status.state,status.code,status.pendingAction],['blocked','develop_answer_missing','resume']);
34
+ assert.equal(f.calls.developer,1);
35
+ const redo=records(f).at(-1).payload;
36
+ assert.deepEqual([redo.type,redo.cause,redo.reason],['develop-answer-redo','call_timeout','会话已停止修改代码']);
37
+ const middle=records(f);
38
+ const [delivered]=await gapSession(f,'resume',gapExecution(f,{developer:['final\n'],verdicts:['approved']}),[['advance',1]]);
39
+ assert.equal(f.calls.developer,2);
40
+ assert.deepEqual(added(f,middle).slice(0,2),['intent:develop-1-retry-1','effect-checkpoint']);
41
+ assert.ok(added(f,middle).includes('intent:review-1'),JSON.stringify(delivered));
42
+ const checkpoint=records(f)[middle.length+1].payload.checkpoint;
43
+ assert.equal(checkpoint.state,'awaiting_review');
44
+ // Reviewed against the task baseline, not re-captured after the lost answer.
45
+ assert.equal(Buffer.from(checkpoint.reviewPackage.changes.find(c=>c.path==='a.mjs').before.contentBase64,'base64').toString(),'old\n');
46
+ const history=readRunnerHistory(records(f),records(f)[0].payload.config,3);
47
+ assert.equal(history.answerGaps.developRedo,1);
48
+ assert.deepEqual(records(f).slice(0,before.length),before,'journal is append-only');
49
+ });
50
+
51
+ test('develop_answer_missing: a disconnected develop (unknown/unknown) takes the same confirmed redo; the cap is two per run',async t=>{
52
+ const f=gapFixture(t,'disconnect');
53
+ const disconnect=write=>({write,throw:'host_disconnected'});
54
+ const [stuck]=await gapSession(f,'create',gapExecution(f,{developer:[disconnect('one\n')]}),[['advance',1]]);
55
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','develop_answer_missing','develop_redo'],JSON.stringify(stuck));
56
+ assert.deepEqual([records(f).at(-1).payload.checkpoint.state,records(f).at(-1).payload.checkpoint.code],['unknown','unknown']);
57
+ for(const [index,write] of ['two\n','three\n'].entries()){
58
+ const [ok]=await gapSession(f,'resume',gapExecution(f,{developer:[disconnect(write)]}),
59
+ [['develop_redo',1,{reason:`确认第 ${index+1} 次`}],['advance',1]],{allowDevelopRedo:true});
60
+ assert.equal(ok.outcome,'recorded');
61
+ }
62
+ // Two redos used: the third stuck develop has no redo exit left.
63
+ const [last,third]=await gapSession(f,'resume',gapExecution(f),[['status',1],['develop_redo',1,{reason:'第三次'}]],{allowDevelopRedo:true});
64
+ assert.deepEqual([third.outcome,third.code],['rejected','develop_redo_unavailable']);
65
+ assert.deepEqual([last.state,last.code,last.pendingAction],['blocked','develop_redo_limit','none'],JSON.stringify(last));
66
+ assert.match(last.reason,/--supersede-reviewed-evidence/);
67
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'a.mjs'),'utf8'),'three\n');
68
+ assert.deepEqual(records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id),
69
+ ['develop-1','develop-1-retry-1','develop-1-retry-2']);
70
+ });
71
+
72
+ test('develop_answer_missing: a bare failed answer (blocked/failed without a result) also needs develop_redo; the driver checks the plan',async t=>{
73
+ const f=gapFixture(t,'bare');
74
+ const [stuck]=await gapSession(f,'create',gapExecution(f,{developer:[{write:'tried\n',response:{status:'failed',code:'session_error'}}]}),[['advance',1]]);
75
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','develop_answer_missing','develop_redo'],JSON.stringify(stuck));
76
+ assert.match(stuck.reason,/只回了 failed/);
77
+ const {developRedoPlanError}=await import('./cm-ai-drive.mjs');
78
+ assert.equal(developRedoPlanError('develop_redo',{mode:'resume',reason:'已停'},['--allow-develop-redo']),null);
79
+ assert.match(developRedoPlanError('develop_redo',{mode:'resume',reason:'已停'},[]),/--allow-develop-redo/);
80
+ assert.match(developRedoPlanError('develop_redo',{mode:'create',reason:'已停'},['--allow-develop-redo']),/resume/);
81
+ });
82
+
83
+ test('develop_redo passes the shared JSONL transport (serveCmAiHost) and is journaled',async t=>{
84
+ const {PassThrough}=await import('node:stream');
85
+ const {serveCmAiHost}=await import('../runtime/js/cm-ai/host-session.mjs');
86
+ const {openControlRun}=await import('./cm-ai-run.mjs');
87
+ const {definition,identity}=await import('./cm-ai-answer-gap-fixture.mjs');
88
+ const f=gapFixture(t,'transport');
89
+ await gapSession(f,'create',gapExecution(f,{developer:[{write:'one\n',throw:'host_disconnected'}]}),[['advance',1]]);
90
+ const run=await openControlRun(definition(f),'resume',gapExecution(f),{allowDevelopRedo:true});
91
+ const input=new PassThrough(),output=new PassThrough(),errors=new PassThrough();let text='';
92
+ output.on('data',chunk=>{text+=chunk;});
93
+ try{
94
+ const served=serveCmAiHost({host:run.host,input,output,errorOutput:errors});
95
+ input.write(JSON.stringify({version:1,operation:'develop_redo',requestId:'redo-1',identity:identity(1),reason:'会话已停止修改代码'})+'\n');
96
+ input.end();await served;
97
+ }finally{run.close();}
98
+ const rows=text.trim().split('\n').map(line=>JSON.parse(line));
99
+ const reply=rows.find(row=>row.requestId==='redo-1');
100
+ assert.ok(reply&&!reply.error,text);
101
+ assert.deepEqual([reply.result.outcome,reply.result.code,reply.result.pendingAction],['recorded','develop_answer_missing','resume']);
102
+ assert.equal(records(f).at(-1).payload.type,'develop-answer-redo');
103
+ });
@@ -13,6 +13,8 @@
13
13
  // status/cancel -> none: batch-run.mjs handle routes only these and advance;
14
14
  // host-session.mjs operationNames admits all three. Other operationNames belong
15
15
  // to child/single-task hosts and are not batch operations.
16
+ // develop_redo/abandon_effect/abandon_review/bootstrap_review_recover -> none:
17
+ // batch-run.mjs memberAction forwards one to the stopped member's cm-ai entry (Q24).
16
18
  import {readBatchExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
17
19
  import {readBatchExternalModels,batchModelsFile} from '../runtime/js/cm-ai/external-group-models.mjs';
18
20
  import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
@@ -20,16 +22,17 @@ import fs from 'node:fs';
20
22
  import path from 'node:path';
21
23
  import {fileURLToPath} from 'node:url';
22
24
  import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
23
- import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
25
+ import {readQaAssessment} from '../runtime/js/cm-ai/host-qa-policy.mjs';
24
26
  import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
25
27
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
26
28
  import {validateRunDefinition} from './cm-ai-run.mjs';
27
29
  import {createCmAiBatch} from './cm-ai-batch-run.mjs';
28
30
  import {readConversationReviewConfiguration,readConversationProtection} from './cm-ai-host.mjs';
29
31
  import {validateCmAiAnswer,developFilename,preflightDevelopDeliveries,baselineScope,inputLimitFrom,
30
- applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes} from './cm-ai-drive.mjs';
32
+ applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes,
33
+ readDriverControl,controlDevelopAttempts} from './cm-ai-drive.mjs';
31
34
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
32
- import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
35
+ import {readRunnerHistory,projectedRunnerStatus,RECHECK_CODES,DOCUMENTATION_SYNC_CODES} from '../runtime/js/cm-ai/durable-runner-state.mjs';
33
36
  import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
34
37
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
35
38
 
@@ -39,21 +42,40 @@ import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
39
42
  const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
40
43
  const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
41
44
  documentation_sync:'documentation-sync.json',documentation_inspect:'documentation-inspect.json'};
45
+ // Q24: per-member recovery grants (cm-ai-batch-host.mjs) and their batch operation.
46
+ const MEMBER_ACTION_FLAGS={develop_redo:'--allow-develop-redo',abandon_effect:'--allow-abandon-effect',
47
+ abandon_review:'--allow-abandon-review',bootstrap_review_recover:'--allow-bootstrap-review-recovery'};
42
48
  const PAIRS=new Set(['--external-models-config','--runtime','--review-config','--browser-qa','--protected-conversation-config',
43
- '--protected-config','--allow-provider-development','--allow-review','--input-limit']);
49
+ '--protected-config','--allow-provider-development','--input-limit','--qa-environment-failure',...Object.values(MEMBER_ACTION_FLAGS)]);
44
50
  const FLAGS=new Set(['--execution-optimizations','--external-models','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
45
51
  '--allow-bootstrap-write']);
46
52
  const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
47
53
  const nonempty=x=>typeof x==='string'&&x.trim().length>0;
48
54
  function taskKey(task){return `${task.feature}/${task.taskId}`;}
49
- export function batchDevelopAttempts(state,key,permissions){
50
- if(developmentRetryable(state))return [state.attempt];
51
- if(state.state==='ready'&&state.attempt===1&&permissions.some((flag,index)=>
52
- flag==='--allow-review'&&permissions[index+1]===`${key}:1`))return [1,2];
55
+ export function batchMemberActionPlanError(operation,plan,permissions,keys){
56
+ const flag=MEMBER_ACTION_FLAGS[operation];if(!flag)return null;
57
+ if(plan.mode!=='resume')return `${operation} 只用于 mode resume`;
58
+ if(!keys.includes(plan.taskKey))return `${operation} 需要 PLAN.taskKey 为本批次当前停住的成员 FEATURE/TASK`;
59
+ if(!(typeof plan.reason==='string'&&plan.reason.trim().length>0&&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)))
60
+ return `${operation} 需要单行 PLAN.reason(最多 500 UTF-8 字节)`;
61
+ if(!permissions.some((name,index)=>name===flag&&permissions[index+1]===plan.taskKey))return `${operation} 需要 permissions 中的 ${flag} ${plan.taskKey}`;
62
+ return null;
63
+ }
64
+ export function batchDevelopAttempts(state,key,permissions,controlPolicy=null){
65
+ if(controlPolicy)return controlPolicy.development==='provider'?[]:controlDevelopAttempts(state,'advance').attempts;
66
+ // The configured round-1 review may lead into round 2 within the
67
+ // same advance (Codex round 1 on Q28): list it too; a missing a2 answer then
68
+ // holds the task after that review (revision_answer_required) instead of
69
+ // sending an unanswerable develop request.
70
+ const reviewNext=state.attempt===1;
71
+ // A re-check (check_answer_*) re-runs only the checks: no developer answer for this round.
72
+ if(state.state==='blocked'&&RECHECK_CODES.includes(state.code))return reviewNext?[2]:[];
73
+ // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
74
+ if(state.state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(state.code))return reviewNext?[2]:[];
75
+ if(developmentRetryable(state))return reviewNext?[1,2]:[state.attempt];
76
+ if(state.state==='ready'&&state.attempt===1)return [1,2];
53
77
  if(['ready','changes_requested'].includes(state.state))return [state.attempt];
54
- if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2
55
- &&permissions.some((flag,index)=>flag==='--allow-review'
56
- &&permissions[index+1]===`${key}:${state.attempt}`))return [state.attempt+1];
78
+ if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2)return [state.attempt+1];
57
79
  return [];
58
80
  }
59
81
  function actualCwd(bundle,key,generation=1){
@@ -82,16 +104,21 @@ function checkCommandShape(commands,key,plan,executionPolicy){
82
104
  }
83
105
  function preflight(){
84
106
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
107
+ process.stdout.write('新版 PLAN.controlConfig 为相对 PLAN 的 v2 控制配置路径;permissions 禁止所有 --allow-*,批次 qaFix 只能为 disabled。普通 advance 自动独立审查;缺少 develop-a2.json 时保持 revision_answer_required。显式成员恢复需要 resume、taskKey 与此前 status 返回的 PLAN.expectedControl,驾驶员不会读取新目标覆盖它。\n');
85
108
  process.stdout.write('用法: cm-ai-batch-drive.mjs --plan PLAN.json <operation>\n'
86
- +'operation: advance, status, cancel。PLAN: config, mode, hostContext, permissions, answers, checks, checkTimeoutMs。\n'
109
+ +'operation: advance, status, cancel, reconcile_review(taskKey、invocationId), develop_redo / abandon_effect / abandon_review / bootstrap_review_recover(resume、PLAN.taskKey、单行 PLAN.reason,permissions 带对应 --allow-… 任务)。PLAN: config, mode, hostContext, permissions, answers, checks, checkTimeoutMs。\n'
87
110
  +'checks 每项为 {id,command,timeoutMs?};超时为 1..3600000 整数,默认 900000 ms(15 分钟)。\n'
88
111
  +'develop.json.edits 与单任务驾驶员相同:内容文件、{file,mode}、{mode}、{delete:true};启动前同样拒绝超限、空交付与受保护模式下的非 UTF-8 内容(尚未开跑的后续任务不看代码树,只做答案本身就能判定的检查:单文件 1 MiB、答案写入的 scope 文件合计 2 MiB,等等;运行存档单条记录上限要看该任务开跑时的代码树,驾驶员事先算不出,超限交付写入后由宿主拦下,停在可重试的 blocked/develop_package_too_large)。\n'
89
- +'带 --allow-review 任务:1 但还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
112
+ +'按已有配置自动审查,还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
90
113
  process.exit(0);
91
114
  }
92
- const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel','reconcile_review'])});
115
+ const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel','reconcile_review',...Object.keys(MEMBER_ACTION_FLAGS)])});
93
116
  const {plan,base,operation}=loaded;
94
117
  requireFields(plan,['config','mode','hostContext','permissions']);
118
+ let control;
119
+ try{control=readDriverControl(plan,base,operation,operation==='reconcile_review'||Object.hasOwn(MEMBER_ACTION_FLAGS,operation));}
120
+ catch(error){stop(2,error.message);}
121
+ if(control&&control.policy.qaFix!=='disabled')stop(2,'invalid_arguments: batch qaFix 必须为 disabled');
95
122
  try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
96
123
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
97
124
  if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
@@ -135,6 +162,18 @@ function preflight(){
135
162
  logHome:path.join(batch.specsDir,'.reviews','host-log-mirror')});
136
163
  }catch(error){stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}${error.code==='protected_scope'&&typeof error.reason==='string'?`;${error.reason}`:''}`);}
137
164
  const log=path.join(batch.specsDir,'运行日志.jsonl');
165
+ // Members the batch already rescheduled into a serial second generation
166
+ // (batch_member_blocked). Their gen-2 run starts fresh at attempt 1.
167
+ const rescheduled=new Set(),handedOff=new Set();
168
+ if(fs.existsSync(log))for(const line of fs.readFileSync(log,'utf8').split('\n')){
169
+ if(!line.trim())continue;let row;try{row=JSON.parse(line);}catch{continue;}
170
+ if(row?.workflow==='cm-ai'&&row.event==='decision'&&row.phase==='batch_member_blocked'&&row.run_id===batch.batchId
171
+ &&row.generation===2&&typeof row.from_key==='string')rescheduled.add(row.from_key);
172
+ // A handed-off task never develops again; a merged parallel member's worktree is gone,
173
+ // so its journal cannot be replayed here (the batch host verifies it on its own).
174
+ if(row?.workflow==='cm-ai'&&row.event==='decision'&&row.phase==='batch_handoff'&&row.run_id===batch.batchId
175
+ &&typeof row.from_key==='string')handedOff.add(row.from_key);
176
+ }
138
177
  const stores=Array.from(definitions.values(),d=>path.join(batch.specsDir,'.reviews','.execution',d.identity.runId,'state.json'));
139
178
  const hasLog=fs.existsSync(log),hasStore=stores.some(file=>fs.existsSync(file));
140
179
  if(plan.mode==='resume'&&!hasLog&&!hasStore)
@@ -151,6 +190,11 @@ function preflight(){
151
190
  let externalModels;
152
191
  try{externalModels=readBatchExternalModels({batch,started:hasStore,enabled:permissions.includes('--external-models'),inputFile:argumentValue('--external-models-config'),providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});}catch(error){stop(2,error.code??'external_model_configuration_invalid');}
153
192
  if(operation==='reconcile_review'&&(plan.mode!=='resume'||!keys.includes(plan.taskKey)||!nonempty(plan.invocationId)))stop(2,'reconcile_review requires resume, taskKey and original invocationId');
193
+ if(control&&Object.hasOwn(MEMBER_ACTION_FLAGS,operation)){
194
+ if(!keys.includes(plan.taskKey)||!nonempty(plan.reason)||Buffer.byteLength(plan.reason,'utf8')>500||/[\r\n\0]/.test(plan.reason))
195
+ stop(2,`${operation} 需要本批次 taskKey、expectedControl 与单行 reason(最多 500 UTF-8 字节)`);
196
+ }
197
+ const memberError=control?null:batchMemberActionPlanError(operation,plan,permissions,keys);if(memberError)stop(2,memberError);
154
198
  for(let i=0;i<permissions.length;i++)if(PAIRS.has(permissions[i])){
155
199
  const name=permissions[i],value=permissions[++i];
156
200
  if(['--review-config','--protected-conversation-config','--protected-config'].includes(name)){
@@ -168,7 +212,9 @@ function preflight(){
168
212
  }
169
213
  }catch(error){stop(2,`${name} 配置无效: ${file}: ${error.code??error.message}`);}
170
214
  permissions[i]=file;
171
- }else if(['--allow-review','--allow-provider-development'].includes(name)){
215
+ }else if(Object.values(MEMBER_ACTION_FLAGS).includes(name)){
216
+ if(!keys.includes(value))stop(2,`${name} 需要本批次的 FEATURE/TASK: ${value}`);
217
+ }else if(name==='--allow-provider-development'){
172
218
  const cut=value.lastIndexOf(':');
173
219
  if(!keys.includes(value.slice(0,cut))||!['1','2'].includes(value.slice(cut+1)))
174
220
  stop(2,`${name} 任务授权无效: ${value}`);
@@ -179,14 +225,12 @@ function preflight(){
179
225
  stop(2,'--runtime 只能是 codex 或 claude');
180
226
  if(permissions.includes('--browser-qa')&&!['available','unavailable'].includes(argument('--browser-qa')))
181
227
  stop(2,'--browser-qa 只能是 available 或 unavailable');
182
- if(permissions.includes('--allow-review')&&!permissions.includes('--review-config'))
183
- stop(2,'--allow-review 需要 --review-config');
184
228
  if(permissions.includes('--allow-provider-development')&&!permissions.includes('--protected-config'))
185
229
  stop(2,'--allow-provider-development 需要 --protected-config');
186
- if(Object.values(bundle.workflows).some(workflow=>workflow?.qa)&&!permissions.includes('--allow-qa'))
230
+ if(!control&&Object.values(bundle.workflows).some(workflow=>workflow?.qa)&&!permissions.includes('--allow-qa'))
187
231
  stop(2,'有 QA 工作流时缺少 --allow-qa');
188
232
  const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
189
- const providerAll=permissions.includes('--protected-config')&&keys.every(key=>
233
+ const providerAll=control?control.policy.development==='provider':permissions.includes('--protected-config')&&keys.every(key=>
190
234
  permissions.includes(`${key}:1`)&&permissions[permissions.indexOf(`${key}:1`)-1]==='--allow-provider-development');
191
235
  let live;
192
236
  try{live=driverLiveEvidence(plan,{base,protectedRoots:[batch.codeProject,batch.specsDir,path.resolve(batch.codeProject,'..','.cm-worktrees'),...(batch.codeProjects??[])],
@@ -208,10 +252,13 @@ function preflight(){
208
252
  kinds.push('check');
209
253
  if(workflow?.documentationPaths?.length)kinds.push('documentation_sync');
210
254
  }
211
- if(workflow?.qa){
212
- if(!batch.parallel?.some(group=>group.includes(key)))kinds.push('qa_assess');
213
- const cases=readJson(path.join(batch.specsDir,task.feature,'test-cases.json'),'test-cases');
214
- for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
255
+ if(workflow&&(control||workflow.qa)){
256
+ // A rescheduled second generation runs serially and asks qa_assess like a serial task.
257
+ if(!batch.parallel?.some(group=>group.includes(key))||rescheduled.has(key))kinds.push('qa_assess');
258
+ if(workflow.qa&&(!control||control.policy.qa==='run')){
259
+ const cases=readJson(path.join(batch.specsDir,task.feature,'test-cases.json'),'test-cases');
260
+ for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
261
+ }
215
262
  }
216
263
  if(workflow)kinds.push('documentation_inspect');
217
264
  const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind)&&!live.has(kind));
@@ -221,29 +268,34 @@ function preflight(){
221
268
  const perAttempt=new Map();
222
269
  if(kinds.includes('develop')){
223
270
  let attempts=[1],current=1,journal=null;
224
- if(plan.mode==='resume'){
271
+ if(plan.mode==='resume'&&handedOff.has(key)){attempts=[];journal={handedOff:true};}
272
+ else if(plan.mode==='resume'){
225
273
  const runIds=[...runs].filter(([,binding])=>binding.key===key).sort((a,b)=>b[1].generation-a[1].generation);
226
- const existing=runIds.find(([runId])=>fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',runId,'state.json')));
274
+ // A rescheduled member whose gen-2 run does not exist yet is a new run: preflight
275
+ // its attempt-1 answer instead of the finished first generation.
276
+ const existing=runIds.find(([runId,binding])=>(binding.generation===2||!rescheduled.has(key))
277
+ &&fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',runId,'state.json')));
227
278
  if(existing)try{
228
279
  const snapshot=readExecutionSnapshot({specsRoot:batch.specsDir,identity:{repositoryId:batch.repositoryId,runId:existing[0]}});
229
280
  const history=readRunnerHistory(snapshot.records,snapshot.records[0].payload.config,3);
230
- attempts=batchDevelopAttempts(history.state,key,permissions);current=history.state.attempt;
281
+ // Q28: decide from what the host will show (projected answer-gap blocks), not the raw replay state.
282
+ attempts=batchDevelopAttempts(projectedRunnerStatus(history,snapshot.records[0].payload.config),key,permissions,control?.policy??null);current=history.state.attempt;
231
283
  journal={baseline:snapshot.records[0].payload.baseline,generation:existing[1].generation,
232
284
  frame:journalRestBytes(snapshot.records)};
233
285
  }catch(error){stop(2,`任务 ${key} 无法只读检查恢复存档: ${error.code??error.message}`);}
234
286
  }
235
287
  // A task with no run yet (a new batch, or a later task on resume) starts at
236
- // attempt 1; a first-round review grant can then reach attempt 2 as well.
237
- if(journal===null&&permissions.some((flag,index)=>flag==='--allow-review'&&permissions[index+1]===`${key}:1`))attempts=[1,2];
288
+ // attempt 1; the configured first-round review can reach attempt 2 as well.
289
+ if(journal===null)attempts=[1,2];
238
290
  const deliveries=[],definition=definitions.get(key);
239
291
  for(const attempt of attempts){
240
292
  const file=path.join(taskRoot??'',developFilename(taskRoot??'',attempt));
241
293
  if(!taskRoot||!fs.existsSync(file)){
242
- // A later attempt is only reached if the review this launch authorizes asks
294
+ // A later attempt is only reached if the configured review asks
243
295
  // for changes. Without its answer the task stops right after that review.
244
296
  if(attempt>current){
245
297
  holds.push(key);
246
- stderr(`任务 ${key} 没有 ${path.basename(file)}:本次授权的审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 ${attempt} 轮开发;读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings,写 ${file} 后再 advance`);
298
+ stderr(`任务 ${key} 没有 ${path.basename(file)}:本次审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 ${attempt} 轮开发;读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings,写 ${file} 后再 advance`);
247
299
  continue;
248
300
  }
249
301
  stop(2,attempt===1?`任务 ${key} 会反问 develop,但答案文件不存在: ${file}`
@@ -278,7 +330,7 @@ function preflight(){
278
330
  if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
279
331
  if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
280
332
  }
281
- return {...loaded,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
333
+ return {...loaded,control,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
282
334
  }
283
335
 
284
336
  let loaded;
@@ -338,15 +390,27 @@ async function answerFor(row,answers,paths,control){
338
390
  contextDigest:row.payload.contextDigest,
339
391
  at:value.at??new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
340
392
  if(row.kind==='qa_assess'){
341
- decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});return value;
393
+ readQaAssessment(value);return value;
342
394
  }
343
395
  return null;
344
396
  }
397
+ export function buildCmAiBatchDriveHostArgs(plan,permissions,config,controlConfig=null,holds=[]){
398
+ return ['serve','--config',config,...(Object.hasOwn(plan,'controlConfig')?['--mode',plan.mode]:[]),
399
+ '--host-context',plan.hostContext,
400
+ ...(Object.hasOwn(plan,'controlConfig')?['--control-config',controlConfig??plan.controlConfig]:['--allow-development']),
401
+ ...permissions,...holds.flatMap(key=>['--hold-revision',key])];
402
+ }
403
+ export function buildCmAiBatchDriveRequest(operation,plan){
404
+ const recovery=operation==='reconcile_review'||Object.hasOwn(MEMBER_ACTION_FLAGS,operation);
405
+ return {...(Object.hasOwn(plan,'controlConfig')?{version:2,...(recovery?{expectedControl:plan.expectedControl}:{})}:{}),
406
+ ...(operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}
407
+ :Object.hasOwn(MEMBER_ACTION_FLAGS,operation)?{taskKey:plan.taskKey,reason:plan.reason}:{})};
408
+ }
345
409
  function main(){
346
410
  loaded=preflight();
347
411
  const {plan,operation,bundle,config,permissions}=loaded;
348
- driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
349
- '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,request:operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}:{},
412
+ driveHost({host:HOST,args:buildCmAiBatchDriveHostArgs(plan,permissions,config,loaded.control?.file,loaded.holds),
413
+ cwd:bundle.batch.codeProject,operation,request:buildCmAiBatchDriveRequest(operation,plan),
350
414
  answers:loaded.answers,answerFor});
351
415
  }
352
416
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();
@@ -7,6 +7,7 @@ import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {buildManifest} from './cm-spec-manifest.mjs';
9
9
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
10
11
  import {batchDevelopAttempts} from './cm-ai-batch-drive.mjs';
11
12
  import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
12
13
 
@@ -41,6 +42,8 @@ function fixture(t,count=1){
41
42
  fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,
42
43
  cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}}));
43
44
  fs.copyFileSync(reviewer,path.join(bin,'codex'));fs.chmodSync(path.join(bin,'codex'),0o700);
45
+ const claudeReviewer=fileURLToPath(new URL('./fixtures/claude-review-process.mjs',import.meta.url));
46
+ fs.copyFileSync(claudeReviewer,path.join(bin,'claude'));fs.chmodSync(path.join(bin,'claude'),0o700);
44
47
  const answers=path.join(root,'answers','1.work','T-001');fs.mkdirSync(answers,{recursive:true});
45
48
  fs.writeFileSync(path.join(answers,'target.txt'),'export const value = 42;\n');
46
49
  const write=(name,value)=>fs.writeFileSync(path.join(answers,name),JSON.stringify(value));
@@ -49,7 +52,7 @@ function fixture(t,count=1){
49
52
  const value={config:'batch.json',mode:'create',hostContext:'batch-host-a',
50
53
  permissions:['--allow-qa'],answers:'answers',checks:Object.fromEntries(batch.tasks.map(task=>
51
54
  [`1.work/${task.taskId}`,[{id:'syntax',command:[process.execPath,'--check',task.taskId==='T-001'?'target.mjs':'target2.mjs']}]])),...extra};
52
- // A new batch requires a bound review configuration (it grants no review).
55
+ // A new batch requires bound review configuration for automatic review execution.
53
56
  if(!value.permissions.includes('--review-config'))value.permissions=[...value.permissions,'--review-config','review.json'];
54
57
  fs.writeFileSync(file,JSON.stringify(value));
55
58
  return file;
@@ -62,8 +65,7 @@ function fixture(t,count=1){
62
65
  }
63
66
  function prepared(f){
64
67
  f.write('develop.json',develop);
65
- f.write('qa-assess.json',{scores:{scope:2,risk:2,accumulation:2,boundary:2},
66
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
68
+ f.write('qa-assess.json',{confirmed:true});
67
69
  f.write('documentation-inspect.json',{status:'completed',reason:'README and task artifacts inspected'});
68
70
  }
69
71
  function noStore(f){assert.equal(fs.existsSync(f.store),false);assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);}
@@ -73,7 +75,7 @@ test('batch reaches live logic and browser QA through the real member host',asyn
73
75
  acIds:[],taskIds:['T-001'],title:'Fixture observation',preconditions:[],steps:['Observe fixture'],expected:['value is 42'],cleanup:[]}));
74
76
  fs.writeFileSync(path.join(f.specsDir,'1.work/test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases}));
75
77
  fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
76
- const plan=f.plan({permissions:['--allow-qa','--allow-review',`${key}:1`,'--browser-qa','available'],
78
+ const plan=f.plan({permissions:['--allow-qa','--browser-qa','available'],
77
79
  liveEvidence:{directory:'exchange',kinds:['qa_logic','qa_browser'],timeoutMs:1000}});
78
80
  const out=await runLiveDriver(DRIVER,plan,'advance',row=>row.kind==='qa_logic'
79
81
  ?{verdict:'SUPPORTED',evidence:['Fixture target.mjs exports 42']}
@@ -93,7 +95,7 @@ test('batch live verification request can reject a written requirement without r
93
95
  assert.equal(row.kind,'verification_precheck');
94
96
  assert.match(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),/42/);
95
97
  return {items:[{requirement:'value is 43',satisfied:false,evidence:'Fixture source exports 42'}]};
96
- },{timeoutMs:60000,env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
98
+ },{timeoutMs:60000,env:{...process.env,PATH:path.join(f.root,'bin')+path.delimiter+process.env.PATH,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
97
99
  assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
98
100
  assert.match(out.stdout,/verification_precheck_failed/);
99
101
  });
@@ -125,10 +127,10 @@ test('real batch host advances with authored edit and actual check, then resumes
125
127
  const again=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a'}),'advance');
126
128
  assert.equal(again.status,0,again.stderr);
127
129
  });
128
- test('real batch reaches completion with an independently dispatched fixture review',t=>{
130
+ test('real batch reaches completion with automatic configured fixture review',t=>{
129
131
  const f=fixture(t);prepared(f);
130
132
  f.write('develop-a2.json',develop);
131
- const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
133
+ const permissions=['--allow-qa','--review-config','review.json'];
132
134
  const first=f.drive(f.plan({permissions}),'advance');
133
135
  assert.equal(first.status,0,first.stderr);assert.match(first.stderr,/应答 check/);
134
136
  let result=JSON.parse(first.stdout).result,stderr=first.stderr;
@@ -156,7 +158,7 @@ const developIntents=f=>{
156
158
  };
157
159
  test('batch review without a second-round answer stops at changes_requested after the first review',t=>{
158
160
  const f=fixture(t);prepared(f);changesRequested(f);
159
- const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
161
+ const permissions=['--allow-qa','--review-config','review.json'];
160
162
  const run=f.drive(f.plan({permissions}),'advance');
161
163
  assert.equal(run.status,0,run.stderr);
162
164
  assert.match(run.stderr,/没有 develop-a2\.json/);assert.match(run.stderr,/\.reviews\/work-T-001-r1\.md/);
@@ -182,16 +184,19 @@ test('batch resume holds a later task that has no run yet when its second-round
182
184
  for(const name of ['qa-assess.json','documentation-inspect.json'])
183
185
  fs.copyFileSync(path.join(f.answers,name),path.join(later,name));
184
186
  fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:{'target2.mjs':'target2.txt'}}));
185
- // T-001 stops at awaiting_review first, so T-002 has no run when the batch resumes.
187
+ // T-001 holds after declared changes, so T-002 has no run when the batch resumes.
188
+ changesRequested(f);
186
189
  const first=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json']}),'advance');
187
- assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'awaiting_review');
190
+ assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'changes_requested');
191
+ fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 42; // revised\n');
192
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
188
193
  // The reviewer approves T-001 and asks for changes on T-002.
189
194
  const cli=path.join(f.root,'bin','codex');
190
195
  fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8').replace("verdict:'approved'",
191
196
  "verdict:prompt.includes('target2.mjs')?'changes_requested':'approved'")
192
197
  .replace('findings:[]',"findings:prompt.includes('target2.mjs')?[{id:'F1',severity:'P2',path:'target2.mjs',message:'Revise',evidence:'Fixture finding'}]:[]"));
193
198
  fs.chmodSync(cli,0o700);
194
- const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`,'--allow-review','1.work/T-002:1'];
199
+ const permissions=['--allow-qa','--review-config','review.json'];
195
200
  let result;
196
201
  for(let n=0;n<4;n++){
197
202
  const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
@@ -203,7 +208,7 @@ test('batch resume holds a later task that has no run yet when its second-round
203
208
  });
204
209
  test('batch hold without a second-round answer does not interfere with an approving review',t=>{
205
210
  const f=fixture(t);prepared(f);
206
- const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
211
+ const permissions=['--allow-qa','--review-config','review.json'];
207
212
  const first=f.drive(f.plan({permissions}),'advance');assert.equal(first.status,0,first.stderr);
208
213
  let result=JSON.parse(first.stdout).result;
209
214
  for(let n=0;n<4&&result.state!=='run_done';n++){
@@ -243,7 +248,7 @@ test('batch driver lets a later task\'s second-round delete bring its delivered
243
248
  const later=path.join(f.root,'answers','1.work','T-002');
244
249
  fs.writeFileSync(path.join(later,'gen_c.bin.txt'),Buffer.alloc(100*1024,0x61));
245
250
  fs.writeFileSync(path.join(later,'develop-a2.json'),JSON.stringify({...develop,edits:{'gen/b.bin':{delete:true},'gen/c.bin':'gen_c.bin.txt'}}));
246
- const run=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json','--allow-review','1.work/T-002:1']}),'advance');
251
+ const run=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json']}),'advance');
247
252
  assert.equal(run.status,0,run.stderr);assert.doesNotMatch(run.stderr,/仅答案写入/);assert.equal(fs.existsSync(f.store),true);
248
253
  });
249
254
  test('batch driver refuses a no-op or non-UTF-8 protected develop answer before launch',t=>{
@@ -264,7 +269,7 @@ test('batch review revision applies the second-round develop content',t=>{
264
269
  .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Fixture finding'}]"));
265
270
  fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 43;\n');
266
271
  f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
267
- const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
272
+ const permissions=['--allow-qa','--review-config','review.json'];
268
273
  const run=f.drive(f.plan({permissions}),'advance');assert.equal(run.status,0,run.stderr);
269
274
  assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 43;\n');
270
275
  });
@@ -288,6 +293,8 @@ test('D1 batch rejects invalid check timeout before opening a host',t=>{
288
293
 
289
294
  test('D1 batch retries failed checks before review in the same attempt',t=>{
290
295
  const f=fixture(t);prepared(f);
296
+ fs.writeFileSync(path.join(f.root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,provider:'claude',
297
+ prompt_transport:'stdin',config_fingerprint:claudeReviewFingerprint({cwd:f.codeProject,model:'fixture'})}}));
291
298
  const failed={[key]:[{id:'test',command:[process.execPath,'-e','process.exit(1)']}]};
292
299
  const first=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude'],checks:failed}),'advance');assert.equal(first.status,0,first.stderr);
293
300
  const result=JSON.parse(first.stdout).result;
@@ -360,6 +367,107 @@ test('optimized real batch driver shares only a declared same-plan check and rej
360
367
  const checks={[key]:[{id:'first',command},{id:'same',command,sameExecutionAs:'first'}]};
361
368
  const denied=f.drive(f.plan({checks}), 'advance');assert.equal(denied.status,2);noStore(f);assert(!fs.existsSync(counter));
362
369
  const out=f.drive(f.plan({permissions:['--allow-qa','--execution-optimizations'],checks}), 'advance');
363
- assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'awaiting_review',out.stdout+out.stderr);
364
- assert.equal(fs.readFileSync(counter,'utf8'),'x');
370
+ assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'run_done',out.stdout+out.stderr);
371
+ // One physical command per phase: development and the required completion recheck.
372
+ assert.equal(fs.readFileSync(counter,'utf8'),'xx');
373
+ });
374
+
375
+ // Q24 driver: develop_redo goes through the batch host to the stopped member; the
376
+ // next advance still preflights the develop answer from the projected state (Q28).
377
+ test('Q24 batch driver forwards develop_redo to the stopped member, then advance redoes the round',t=>{
378
+ const f=fixture(t);prepared(f);
379
+ f.write('develop.json',{status:'failed',code:'session_error'});
380
+ const stuck=f.drive(f.plan(),'advance');assert.equal(stuck.status,0,stuck.stderr);
381
+ const first=JSON.parse(stuck.stdout).result;
382
+ assert.deepEqual([first.state,first.code,first.pendingAction],['blocked','develop_answer_missing','develop_redo'],stuck.stdout);
383
+ const resume={mode:'resume',originalHostContext:'batch-host-a'};
384
+ const missing=f.drive(f.plan({...resume,taskKey:key,reason:'会话已停止修改代码'}),'develop_redo');
385
+ assert.equal(missing.status,2);assert.match(missing.stderr,/--allow-develop-redo 1\.work\/T-001/);
386
+ const noReason=f.drive(f.plan({...resume,taskKey:key,permissions:['--allow-qa','--allow-develop-redo',key]}),'develop_redo');
387
+ assert.equal(noReason.status,2);assert.match(noReason.stderr,/reason/);
388
+ const unknownTask=f.drive(f.plan({...resume,taskKey:key,reason:'已停',permissions:['--allow-qa','--allow-develop-redo','1.work/T-009']}),'develop_redo');
389
+ assert.equal(unknownTask.status,2);assert.match(unknownTask.stderr,/--allow-develop-redo/);
390
+ const redo=f.drive(f.plan({...resume,taskKey:key,reason:'会话已停止修改代码',permissions:['--allow-qa','--allow-develop-redo',key]}),'develop_redo');
391
+ assert.equal(redo.status,0,redo.stderr);
392
+ const recorded=JSON.parse(redo.stdout).result;
393
+ assert.deepEqual([recorded.outcome,recorded.pendingAction,recorded.taskKey],['recorded','resume',key],redo.stdout);
394
+ prepared(f);
395
+ const again=f.drive(f.plan(resume),'advance');assert.equal(again.status,0,again.stderr);
396
+ assert.match(again.stderr,/应答 develop/);
397
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 42;\n');
398
+ });
399
+
400
+ // Review round 1 (major): in a strict batch (and, batch 4, an ordinary one) a terminal parallel member is rescheduled
401
+ // into a serial second generation. The host stops at batch_member_rescheduled; the next
402
+ // resume advance preflights the gen-2 attempt-1 answer (the finished gen-1 run would
403
+ // have yielded none) and the batch continues without a host_close mid-run.
404
+ for(const [label,strict] of [['strict',true],['ordinary',false]])
405
+ test(`${label} batch driver preflights a rescheduled second generation before it is developed`,t=>{
406
+ const f=fixture(t,3);
407
+ const bundlePath=path.join(f.root,'batch.json'),bundle=JSON.parse(fs.readFileSync(bundlePath,'utf8'));
408
+ bundle.batch.parallel=[['1.work/T-001','1.work/T-002']];
409
+ fs.writeFileSync(bundlePath,JSON.stringify(bundle));
410
+ const dir=id=>{const d=path.join(f.root,'answers','1.work',id);fs.mkdirSync(d,{recursive:true});return d;};
411
+ const answer=(id,file,content,outcome='implemented')=>{
412
+ fs.writeFileSync(path.join(dir(id),`${file}.txt`),content);
413
+ fs.writeFileSync(path.join(dir(id),'develop.json'),JSON.stringify({...develop,
414
+ value:outcome==='implemented'?develop.value:{outcome:'blocked',reason:'Synthetic dependency is missing'},edits:{[`${file}.mjs`]:`${file}.txt`}}));
415
+ for(const [name,value] of [['qa-assess.json',{confirmed:true}],
416
+ ['documentation-inspect.json',{status:'completed',reason:'README and task artifacts inspected'}]])
417
+ fs.writeFileSync(path.join(dir(id),name),JSON.stringify(value));
418
+ };
419
+ answer('T-001','target','export const value = 42;\n');
420
+ answer('T-002','target2','export const value = 2;\n','blocked');
421
+ answer('T-003','target3','export const value = 3;\n');
422
+ const checks=Object.fromEntries(['T-001','T-002','T-003'].map((id,n)=>[`1.work/${id}`,
423
+ [{id:'syntax',command:[process.execPath,'--check',n===0?'target.mjs':`target${n+1}.mjs`]}]]));
424
+ const permissions=['--allow-qa',...(strict?['--execution-optimizations']:[])];
425
+ const first=f.drive(f.plan({permissions,checks}),'advance');assert.equal(first.status,0,first.stderr);
426
+ const stopped=JSON.parse(first.stdout).result;
427
+ assert.equal(stopped.code,'batch_member_rescheduled',first.stdout+first.stderr);assert.deepEqual(stopped.rescheduled,['1.work/T-002']);
428
+ // The gen-2 answer replaces the blocked one; the resume preflight must load it.
429
+ answer('T-002','target2','export const value = 2;\n');
430
+ const resumed=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',
431
+ permissions:permissions.filter(flag=>flag!=='--execution-optimizations'),checks}),'advance');
432
+ assert.equal(resumed.status,0,resumed.stderr);
433
+ assert.doesNotMatch(resumed.stderr,/未预检/);
434
+ const done=JSON.parse(resumed.stdout).result;
435
+ assert.equal(done.state,'run_done',resumed.stdout+resumed.stderr);
436
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target2.mjs'),'utf8'),'export const value = 2;\n');
437
+ });
438
+
439
+
440
+ test('batch ordinary advance preflights reachable revision answers without review grants',()=>{
441
+ assert.deepEqual(batchDevelopAttempts({state:'ready',attempt:1},key,[]),[1,2]);
442
+ assert.deepEqual(batchDevelopAttempts({state:'awaiting_review',attempt:1},key,[]),[2]);
443
+ assert.deepEqual(batchDevelopAttempts({state:'pending_review',attempt:1},key,[]),[2]);
444
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code:'develop_checks_not_passed',attempt:1},key,[]),[1,2]);
445
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code:'check_answer_missing',attempt:1},key,[]),[2]);
446
+ assert.deepEqual(batchDevelopAttempts({state:'changes_requested',attempt:2},key,[]),[2]);
447
+ });
448
+ test('batch driver rejects removed review grant before starting a batch',t=>{
449
+ const f=fixture(t);prepared(f);
450
+ const out=f.drive(f.plan({permissions:['--allow-qa','--allow-review',key+':1']}),'advance');
451
+ assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/permissions 无效.*--allow-review/);noStore(f);
452
+ });
453
+
454
+ test('batch configured review reaches both rounds and completes without a review grant',t=>{
455
+ const f=fixture(t);prepared(f);
456
+ fs.writeFileSync(path.join(f.answers,'revised.txt'),'export const value = 42; // revised after findings\n');
457
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'revised.txt'}});
458
+ const cli=path.join(f.root,'bin','codex');
459
+ fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8')
460
+ .replace("verdict:'approved'","verdict:data.reviewPackage.identity.attempt===1?'changes_requested':'approved'")
461
+ .replace('findings:[]',"findings:data.reviewPackage.identity.attempt===1?[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise',evidence:'Fixture finding'}]:[]"));
462
+ fs.chmodSync(cli,0o700);
463
+ let out=f.drive(f.plan(),'advance');assert.equal(out.status,0,out.stderr);
464
+ let result=JSON.parse(out.stdout).result;
465
+ for(let n=0;n<4&&result.state!=='run_done';n++){
466
+ out=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a'}),'advance');
467
+ assert.equal(out.status,0,out.stderr);result=JSON.parse(out.stdout).result;
468
+ }
469
+ assert.equal(result.state,'run_done',JSON.stringify(result));
470
+ assert.deepEqual(developIntents(f),['develop-1','develop-2']);
471
+ assert.match(fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md'),'utf8'),/verdict: changes_requested/);
472
+ assert.match(fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-r2.md'),'utf8'),/verdict: approved/);
365
473
  });