@aibyzero/cm-workflow 0.21.7 → 0.25.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 (200) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +10 -1
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +36 -10
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  23. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  24. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  25. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  26. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  27. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  28. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  29. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  30. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  31. package/runtime/js/cm-ai/host-check.mjs +4 -2
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  33. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  34. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  42. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  44. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  45. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  46. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  47. package/runtime/js/cm-ai/review-package.mjs +25 -4
  48. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  49. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  50. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  52. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  53. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  54. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  56. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  57. package/runtime/js/cm-fix/execution.mjs +47 -9
  58. package/runtime/js/cm-fix/finish.mjs +9 -1
  59. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  60. package/runtime/js/cm-idea/session.mjs +22 -3
  61. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  62. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  63. package/runtime/js/cm-prd/analysis.mjs +27 -9
  64. package/runtime/js/cm-prd/change.mjs +29 -8
  65. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  66. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  67. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  68. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  69. package/runtime/js/cm-prd/self-check.mjs +121 -9
  70. package/runtime/js/cm-prd/session.mjs +55 -13
  71. package/runtime/js/cm-prd/summary.mjs +34 -6
  72. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  73. package/runtime/js/cm-refactor/records.mjs +82 -11
  74. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  75. package/runtime/js/executor-version.mjs +81 -0
  76. package/runtime/js/python-log-writer.mjs +15 -0
  77. package/runtime/js/run-analysis.mjs +136 -11
  78. package/runtime/logging.md +6 -0
  79. package/runtime/review.md +2 -1
  80. package/scripts/ci-test-weights.json +1 -0
  81. package/scripts/cm-ai-admission.mjs +27 -1
  82. package/scripts/cm-ai-admission.test.mjs +34 -2
  83. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  84. package/scripts/cm-ai-batch-drive.mjs +54 -17
  85. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  86. package/scripts/cm-ai-batch-host.mjs +55 -9
  87. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  88. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  89. package/scripts/cm-ai-batch-merge.mjs +102 -0
  90. package/scripts/cm-ai-batch-plan.mjs +55 -2
  91. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  92. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  93. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  94. package/scripts/cm-ai-batch-run.mjs +435 -33
  95. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  96. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  97. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  98. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  99. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  100. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  101. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  102. package/scripts/cm-ai-drive.mjs +66 -14
  103. package/scripts/cm-ai-drive.test.mjs +13 -3
  104. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  105. package/scripts/cm-ai-host.mjs +16 -8
  106. package/scripts/cm-ai-host.test.mjs +12 -0
  107. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  108. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  109. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  110. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  111. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  112. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  113. package/scripts/cm-ai-run.mjs +42 -11
  114. package/scripts/cm-ai-run.test.mjs +26 -0
  115. package/scripts/cm-ai-supersede.test.mjs +10 -2
  116. package/scripts/cm-capability-gate.test.mjs +1 -1
  117. package/scripts/cm-check-runtime.sh +9 -0
  118. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  119. package/scripts/cm-developer-self-review.test.mjs +27 -0
  120. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  121. package/scripts/cm-efficiency-response.test.mjs +2 -1
  122. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  123. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  124. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  125. package/scripts/cm-executor-version-records.test.mjs +256 -0
  126. package/scripts/cm-executor-version.test.mjs +250 -0
  127. package/scripts/cm-external-model-host.test.mjs +6 -1
  128. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  129. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  130. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  131. package/scripts/cm-fix-drive.mjs +7 -2
  132. package/scripts/cm-fix-drive.test.mjs +45 -0
  133. package/scripts/cm-fix-entry.mjs +5 -2
  134. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  135. package/scripts/cm-fix-host.mjs +9 -2
  136. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  137. package/scripts/cm-host-check.test.mjs +12 -0
  138. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  139. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  140. package/scripts/cm-idea-drive.mjs +5 -2
  141. package/scripts/cm-idea-entry.mjs +5 -2
  142. package/scripts/cm-idea-host.mjs +3 -1
  143. package/scripts/cm-init-drive.mjs +8 -5
  144. package/scripts/cm-init-entry.mjs +5 -2
  145. package/scripts/cm-init-host.mjs +6 -2
  146. package/scripts/cm-log-event.mjs +10 -2
  147. package/scripts/cm-log-event.test.mjs +29 -0
  148. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  149. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  150. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  151. package/scripts/cm-prd-completion.test.mjs +67 -4
  152. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  153. package/scripts/cm-prd-drive.mjs +89 -20
  154. package/scripts/cm-prd-drive.test.mjs +109 -4
  155. package/scripts/cm-prd-entry.mjs +5 -2
  156. package/scripts/cm-prd-host.mjs +89 -20
  157. package/scripts/cm-prd-host.test.mjs +17 -8
  158. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  159. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  160. package/scripts/cm-prd-review-gate.mjs +11 -4
  161. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  162. package/scripts/cm-prd-self-check.test.mjs +1 -1
  163. package/scripts/cm-refactor-drive.mjs +10 -4
  164. package/scripts/cm-refactor-entry.mjs +5 -2
  165. package/scripts/cm-refactor-host.mjs +3 -1
  166. package/scripts/cm-run-analysis.test.mjs +373 -1
  167. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  168. package/scripts/cm-skill-hints-exam.mjs +3 -1
  169. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  170. package/scripts/cm-skill-hints.mjs +106 -10
  171. package/scripts/cm-skill-hints.test.mjs +162 -6
  172. package/scripts/cm-skill-judge.mjs +2 -1
  173. package/scripts/cm-task-gate.mjs +88 -18
  174. package/scripts/cm-task-scope.test.mjs +1 -1
  175. package/scripts/cm-test-drive.mjs +13 -8
  176. package/scripts/cm-test-entry.mjs +5 -2
  177. package/scripts/cm-test-host.mjs +3 -1
  178. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  179. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  180. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  181. package/scripts/policy-binding-compat.test.mjs +3 -2
  182. package/scripts/test-cm-prd-review-gate.py +25 -0
  183. package/skills/cm-ai/SKILL.md +1 -1
  184. package/skills/cm-ai/references/N1-init.md +1 -1
  185. package/skills/cm-ai/references/N4-review.md +2 -2
  186. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  187. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  188. package/skills/cm-ai/references/js-host.md +17 -8
  189. package/skills/cm-fix/references/js-host.md +20 -0
  190. package/skills/cm-fix/references/test-extension.md +1 -1
  191. package/skills/cm-prd/SKILL.md +8 -6
  192. package/skills/cm-prd/references/ai-draft.md +81 -0
  193. package/skills/cm-prd/references/change-mode.md +2 -0
  194. package/skills/cm-prd/references/greenfield.md +2 -0
  195. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  196. package/skills/cm-prd/references/js-host.md +9 -6
  197. package/skills/cm-prd/references/light-mode.md +19 -0
  198. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  199. package/skills/cm-prd/references/spec-self-check.md +1 -0
  200. package/skills/cm-prd/references/summary-card.md +1 -0
@@ -164,6 +164,7 @@
164
164
  "cm-notify-command.test.mjs": 10,
165
165
  "cm-notify.test.mjs": 28,
166
166
  "cm-patrol.test.mjs": 2,
167
+ "cm-prd-ai-draft.test.mjs": 3,
167
168
  "cm-prd-analysis.test.mjs": 1,
168
169
  "cm-prd-answer-gaps.test.mjs": 12,
169
170
  "cm-prd-completion.test.mjs": 25,
@@ -6,6 +6,8 @@ import path from 'node:path';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {inspectCmAiAdmission,approveCmAiSpecs,matchesCmAiTaskSelection,explainCmAiTaskSelection} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
8
8
  import {validateRunDefinition} from './cm-ai-run.mjs';
9
+ import {spawnPythonLogWriter} from '../runtime/js/python-log-writer.mjs';
10
+ import {scanRows} from '../runtime/js/cm-ai/log-rows.mjs';
9
11
 
10
12
  const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve (--approval-response TEXT | --standing-authorization) (no --yes) [--expect-revision-digest HEX] [--no-spec-amend]] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
11
13
 
@@ -89,11 +91,35 @@ function buildRunDefinition(admission,input){
89
91
  return validateRunDefinition(definition);
90
92
  }
91
93
 
94
+ // Diagnostic only: record how long the published specs waited for this approval.
95
+ // It is appended to the cm-prd run whose awaiting_review row matches this very
96
+ // publication time (same second), as a diagnostic row that never re-points or
97
+ // opens a run. Without that match, or on any failure, nothing is recorded.
98
+ export function logApprovalTiming(specsDir,codeProject,timing){
99
+ try{
100
+ const published=Date.parse(timing.publishedAt??''),approved=Date.parse(timing.approvedAt);
101
+ if(!Number.isFinite(published)||!Number.isFinite(approved)||approved<published)return true;
102
+ const second=Math.floor(published/1000);let runId=null;
103
+ scanRows(path.join(specsDir,'运行日志.jsonl'),row=>{
104
+ if(row?.workflow==='cm-prd'&&row.event==='spec_lifecycle'&&row.phase==='awaiting_review'&&typeof row.run_id==='string'
105
+ &&Math.floor(Date.parse(row.at)/1000)===second)runId=row.run_id;});
106
+ if(runId===null)return true; // no matching publication row: nothing to record
107
+ const data={diagnostic:true,feature_count:timing.featureCount,approval_kind:timing.kind,wait_ms:approved-published};
108
+ const result=spawnPythonLogWriter([fileURLToPath(new URL('./cm-log-event.py',import.meta.url)),'--workflow','cm-prd',
109
+ '--event','spec_approval','--phase','written','--runtime','unknown','--project-root',codeProject,'--specs-dir',specsDir,
110
+ '--run-id',runId,'--at',timing.approvedAt,'--detail','规格审批已写入','--data-json',JSON.stringify(data)],
111
+ {timeout:10000,maxBuffer:64*1024});
112
+ return !result.error&&result.status===0;
113
+ }catch{return false;}
114
+ }
115
+
92
116
  export function main(argv=process.argv.slice(2)){
93
117
  let input;
94
118
  try{input=parse(argv);}catch(error){process.stderr.write(`${usage}\nERROR: ${error.message}\n`);return 2;}
95
119
  if(input.help){process.stdout.write(`${usage}\n`);return 0;}
96
120
  const approval=input.approve?approveCmAiSpecs(input):null;
121
+ if(approval?.approvalTiming&&!logApprovalTiming(approval.projectResults?.[0]?.specsDir??input.specsDir,input.codeProjects[0],approval.approvalTiming))
122
+ try{process.stderr.write('{"diagnostic":"approval_timing_log_skipped"}\n');}catch{}
97
123
  const projectResults=approval?.projectResults??input.codeProjects.map(codeProject=>inspectCmAiAdmission({...input,codeProject}));
98
124
  const firstBlocked=projectResults.find(item=>item.state==='blocked');
99
125
  const reference=firstBlocked??projectResults[0];
@@ -106,7 +132,7 @@ export function main(argv=process.argv.slice(2)){
106
132
  codeProjects:projectResults.map(item=>item.codeProject),
107
133
  projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
108
134
  if(result.state==='awaiting_spec_approval'&&(result.approvalIntent!=='explicit'||input.assumeYes))
109
- result.message='确认规格摘要后,用 --approval-response 传入用户原话,并明确回复“开始”。';
135
+ result.message='确认规格摘要后,用 --approval-response 传入用户原话,并明确回复“开始”(也认“开工”“批准开工”“同意开始”等整句)。';
110
136
  // An explicit feature with nothing left never prints a definition, whether the
111
137
  // project still has other work (ready) or none (complete).
112
138
  if(input.printRunDefinition&&!result.approveRefused&&input.feature!==undefined&&result.requestedFeatureComplete===input.feature){
@@ -52,11 +52,12 @@ test('spec approval accepts only normalized explicit start phrases',()=>fixture(
52
52
  const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approval-response',reply],{encoding:'utf8'});
53
53
  assert.equal(result.status,0,result.stderr);return JSON.parse(result.stdout);
54
54
  };
55
- for(const reply of ['开始','开始吧','可以开始','确认开始','开始执行','现在开始',' 开始吧。 ','现在开始! ','可以开始!.~~ ']){
55
+ for(const reply of ['开始','开始吧','可以开始','确认开始','开始执行','现在开始',' 开始吧。 ','现在开始! ','可以开始!.~~ ',
56
+ '开工','开工吧','批准开工','批准开工。','同意开工','批准开始','同意开始']){
56
57
  const result=run(reply);assert.equal(result.approvalIntent,'explicit',reply);
57
58
  assert.equal(result.reason,'approval_write_required',reply);
58
59
  }
59
- for(const reply of ['继续','可以','好','好的','OK','按最优解处理','你看着办','行','开始开发','开始吧,请继续']){
60
+ for(const reply of ['继续','可以','好','好的','OK','按最优解处理','你看着办','行','开始开发','开始吧,请继续','批准','同意','批准开工,但先别动数据库']){
60
61
  const result=run(reply);assert.equal(result.approvalIntent,'not_approval',reply);
61
62
  assert.equal(result.reason,'spec_approval_required',reply);
62
63
  assert.match(result.message,/回复.*开始/);
@@ -76,6 +77,37 @@ test('approve writes only after a whitelisted reply and preserves the original r
76
77
  assert.equal(JSON.parse(fs.readFileSync(status,'utf8')).approval.response,'开始吧!');
77
78
  }));
78
79
 
80
+ // Approval wait is logged on the cm-prd run that published the specs, as data
81
+ // (wait_ms), so the time a person took to approve can be counted later.
82
+ test('approve logs how long the published specs waited, on the publishing cm-prd run',()=>fixture(({root,specs,code})=>{
83
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',at:'2026-11-01T00:00:00.000Z',features:['1.login'],testCases:[]}));
84
+ const log=path.join(specs,'运行日志.jsonl');
85
+ fs.writeFileSync(log,JSON.stringify({schema_version:1,run_id:'prd-publish-1',at:'2026-11-01T00:00:00+00:00',workflow:'cm-prd',
86
+ event:'spec_lifecycle',phase:'awaiting_review',runtime:'claude',project:'code',detail:'published'})+'\n');
87
+ const env={...process.env,CM_WORKFLOW_LOG_HOME:path.join(root,'log-home')};
88
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approve','--approval-response','开始'],{encoding:'utf8',env});
89
+ assert.equal(result.status,0,result.stderr);
90
+ const approvedAt=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8')).approval.at;
91
+ const rows=fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse).filter(row=>row.event==='spec_approval');
92
+ assert.equal(rows.length,1);
93
+ assert.equal(rows[0].run_id,'prd-publish-1');assert.equal(rows[0].approval_kind,'response');
94
+ assert.equal(rows[0].wait_ms,Date.parse(approvedAt)-Date.parse('2026-11-01T00:00:00.000Z'));
95
+ assert.equal(rows[0].diagnostic,true);assert.equal(Object.hasOwn(rows[0],'published_at'),false);
96
+ // A diagnostic row never re-points the default run.
97
+ assert.equal(fs.existsSync(path.join(specs,'.cm-run.json')),false);
98
+ }));
99
+
100
+ test('approve records no wait when no awaiting_review row matches the publication time',()=>fixture(({root,specs,code})=>{
101
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',at:'2026-11-01T00:00:05.000Z',features:['1.login'],testCases:[]}));
102
+ const log=path.join(specs,'运行日志.jsonl');
103
+ fs.writeFileSync(log,JSON.stringify({schema_version:1,run_id:'prd-older',at:'2026-11-01T00:00:00+00:00',workflow:'cm-prd',
104
+ event:'spec_lifecycle',phase:'awaiting_review',runtime:'claude',project:'code',detail:'older publication'})+'\n');
105
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approve','--approval-response','开始'],
106
+ {encoding:'utf8',env:{...process.env,CM_WORKFLOW_LOG_HOME:path.join(root,'log-home')}});
107
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stderr,'');
108
+ assert.equal(fs.readFileSync(log,'utf8').includes('spec_approval'),false,'an older publication never takes the approval');
109
+ }));
110
+
79
111
  test('approve bound to a change proposal writes only for that saved proposal and its unchanged bytes',()=>fixture(({specs,code})=>{
80
112
  const status=path.join(specs,'.cm-specs-status'),digest='a'.repeat(64),other='b'.repeat(64);
81
113
  const saved=()=>fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',revisionDigest:digest,
@@ -8,8 +8,9 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import {readRunnerHistory,projectedRunnerStatus} from '../runtime/js/cm-ai/durable-runner-state.mjs';
10
10
  import {gapFixture,gapExecution,gapSession,records,added} from './cm-ai-answer-gap-fixture.mjs';
11
+ import {withFreshCompletionChecks} from './fixtures/fresh-completion-checks.mjs';
11
12
 
12
- test('check_answer_missing: a timed-out check after a delivered develop re-runs only the checks, then complete_recheck_failed re-runs only completion',async t=>{
13
+ test('check_answer_missing: a timed-out check after a delivered develop re-runs only the checks, then complete_recheck_failed re-runs only completion',t=>withFreshCompletionChecks(()=>(async t=>{
13
14
  const f=gapFixture(t,'recheck');
14
15
  // Round 1 delivers; its check never answers (the runner limit stops it).
15
16
  const [stuck]=await gapSession(f,'create',gapExecution(f,{developer:['round-1\n'],checks:['hang']}),[['advance',1]]);
@@ -45,7 +46,7 @@ test('check_answer_missing: a timed-out check after a delivered develop re-runs
45
46
  assert.equal(final.state.state,'fixture_completed');
46
47
  assert.deepEqual([final.answerGaps.developRecheck,final.answerGaps.completeRecheck],[1,1]);
47
48
  assert.equal(final.state.receipts.length,1,'one review round');
48
- });
49
+ })(t)));
49
50
 
50
51
  test('check_answer_invalid: a malformed check answer is re-checked at most twice per run, then shows check_answer_retry_limit',async t=>{
51
52
  const f=gapFixture(t,'invalid');
@@ -41,7 +41,9 @@ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHo
41
41
  import {rateLimitRetryEligible} from '../runtime/js/cm-ai/drive-rate-limit.mjs';
42
42
 
43
43
  import {driverLiveEvidence,qaAnswerWindowShortfall} from '../runtime/js/cm-ai/live-evidence.mjs';
44
+ import {EXECUTOR_REASON_CODES} from '../runtime/js/executor-version.mjs';
44
45
  import {HOST_ANSWER_TIMEOUT_DEFAULT_MS,hostAnswerTimeoutMs} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
46
+ import {cmAiNextStep} from '../runtime/js/cm-ai/drive-next-step.mjs';
45
47
 
46
48
  // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
47
49
  const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
@@ -50,7 +52,7 @@ const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
50
52
  // Q24: per-member recovery grants (cm-ai-batch-host.mjs) and their batch operation.
51
53
  const MEMBER_ACTION_FLAGS={develop_redo:'--allow-develop-redo',abandon_effect:'--allow-abandon-effect',
52
54
  abandon_review:'--allow-abandon-review',bootstrap_review_recover:'--allow-bootstrap-review-recovery'};
53
- const PAIRS=new Set(['--external-models-config','--runtime','--review-config','--browser-qa','--protected-conversation-config',
55
+ const PAIRS=new Set(['--external-models-config','--runtime','--review-runtime','--review-config','--browser-qa','--protected-conversation-config',
54
56
  '--protected-config','--allow-provider-development','--input-limit','--qa-environment-failure',...Object.values(MEMBER_ACTION_FLAGS)]);
55
57
  const FLAGS=new Set(['--execution-optimizations','--external-models','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
56
58
  '--allow-bootstrap-write']);
@@ -117,22 +119,45 @@ function actualCwd(bundle,key,generation=1){
117
119
  return batchMemberWorktree({codeProject:bundle.batch.codeProject,taskId:id,
118
120
  segments:batchSegments({specsDir:bundle.batch.specsDir,batchId:bundle.batch.batchId})});
119
121
  }
122
+ // The first thing wrong with one PLAN.checks item, said plainly (2026-12-01 probe: a bare
123
+ // "格式错误" did not say which item or field). null when the item has the right shape.
124
+ export function checkItemProblem(item,ids,executionPolicy){
125
+ if(!isObject(item))return '必须是对象';
126
+ const known=['id','command','timeoutMs',...(executionPolicy?['sameExecutionAs']:[])];
127
+ const unknown=Object.keys(item).filter(field=>!known.includes(field));
128
+ // Field names and ids are echoed bounded and without control or bidi characters.
129
+ const plain=value=>value.replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g,'?').slice(0,64);
130
+ if(unknown.length)return `不认识的字段 ${unknown.slice(0,8).map(field=>JSON.stringify(plain(field))).join(', ')}(只允许 ${known.join(', ')})`;
131
+ if(!nonempty(item.id)||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item.id))
132
+ // Echo only a string id (bounded); another type is named, never serialized.
133
+ return `id ${typeof item.id==='string'?JSON.stringify(plain(item.id)):`不是字符串(${item.id===null?'null':Array.isArray(item.id)?'array':typeof item.id})`} 无效:须是以字母或数字开头、只含字母、数字、点、下划线、连字符的字符串,最长 128 个字符`;
134
+ if(ids.has(item.id))return `id ${JSON.stringify(plain(item.id))} 重复,同一任务的检查 id 不能相同`;
135
+ if(!Array.isArray(item.command)||!item.command.length)
136
+ return `command 必须是非空的参数数组(每个参数一项,不经 shell),现在是 ${Array.isArray(item.command)?'空数组':typeof item.command}`;
137
+ const bad=item.command.findIndex(arg=>typeof arg!=='string'||!arg.trim()||arg.includes('\0'));
138
+ if(bad!==-1)return `command[${bad}] 必须是非空字符串(不能只有空白或含 NUL)`;
139
+ return null;
140
+ }
120
141
  function checkCommandShape(commands,key,plan,executionPolicy){
121
142
  if(!Array.isArray(commands)||!commands.length||commands.length>32)stop(2,`任务 ${key} 会反问 check,但 PLAN.checks.${key} 缺少真实命令列表`);
122
- const ids=new Set();
123
- for(const item of commands){
124
- if(!isObject(item)||Object.keys(item).some(field=>!['id','command','timeoutMs',...(executionPolicy?['sameExecutionAs']:[])].includes(field))
125
- ||!nonempty(item.id)||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item.id)
126
- ||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
127
- ||item.command.some(arg=>typeof arg!=='string'||!arg.trim()||arg.includes('\0')))
128
- stop(2,`PLAN.checks.${key} 格式错误`);
129
- try{planCheckTimeout(plan,item);}catch(error){stop(2,error.message);}
143
+ const ids=new Set(),where=index=>`PLAN.checks.${key}[${index}] 格式错误:`;
144
+ for(const [index,item] of commands.entries()){
145
+ const problem=checkItemProblem(item,ids,executionPolicy);
146
+ if(problem)stop(2,`${where(index)}${problem};每项写成 {"id":"syntax","command":["node","--check","a.mjs"],"timeoutMs":900000}`);
147
+ try{planCheckTimeout(plan,item);}catch{stop(2,`${where(index)}timeoutMs 需要 1..3600000 的整数(毫秒)`);}
148
+ // sameExecutionAs reuses the item right before it: same id link, command and timeout.
149
+ if(Object.hasOwn(item,'sameExecutionAs')){
150
+ const previous=commands[index-1];
151
+ const alias=index===0?'sameExecutionAs 不能写在第 1 项,它复用紧挨着的上一项'
152
+ :item.sameExecutionAs!==previous.id?`sameExecutionAs 须等于紧挨着的上一项 id ${previous.id}`
153
+ :JSON.stringify(item.command)!==JSON.stringify(previous.command)?'command 须与上一项完全相同才能用 sameExecutionAs 复用'
154
+ :planCheckTimeout(plan,item)!==planCheckTimeout(plan,previous)?'timeoutMs 须与上一项相同才能用 sameExecutionAs 复用':null;
155
+ if(alias)stop(2,where(index)+alias);
156
+ }
130
157
  ids.add(item.id);
131
158
  }
132
- try{
133
- for(const [index,item] of commands.entries())if(Object.hasOwn(item,'sameExecutionAs')&&(index===0||planCheckTimeout(plan,item)!==planCheckTimeout(plan,commands[index-1])))throw Error('alias timeout mismatch');
134
- createHostCheck({cwd:process.cwd(),commands:commands.map(({timeoutMs,...item})=>item),reuseDeclared:executionPolicy!==null});
135
- }catch(error){stop(2,`PLAN.checks.${key} 格式错误: ${error.code??error.message}`);}
159
+ try{createHostCheck({cwd:process.cwd(),commands:commands.map(({timeoutMs,...item})=>item),reuseDeclared:executionPolicy!==null});}
160
+ catch(error){stop(2,`PLAN.checks.${key} 格式错误: ${error.code??error.message}`);}
136
161
  }
137
162
  function preflight(){
138
163
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
@@ -173,6 +198,7 @@ function preflight(){
173
198
  if(!isObject(bundle)||!isObject(bundle.batch)||!isObject(bundle.workflows)
174
199
  ||!Array.isArray(bundle.batch.tasks)||!bundle.batch.tasks.length)stop(2,`批次定义格式错误: ${config}`);
175
200
  const batch=bundle.batch,keys=batch.tasks.map(taskKey);
201
+ if(Object.hasOwn(batch,'reviewRuntime'))stop(2,'批次配置文件不能写 reviewRuntime;审查端只用 PLAN.permissions 的 --review-runtime 选择');
176
202
  if(new Set(keys).size!==keys.length||keys.length!==Object.keys(bundle.workflows).length
177
203
  ||keys.some(key=>!Object.hasOwn(bundle.workflows,key)))stop(2,'批次定义 workflows 与 tasks 不匹配');
178
204
  const sessionMembers=batchSessionMembers(batch,control?.policy);
@@ -195,7 +221,10 @@ function preflight(){
195
221
  // Use the batch owner's selection/parallel-group validator without opening a run.
196
222
  createCmAiBatch({configuration:batch,executionFor:async()=>({}),bootstrapKeys:Object.keys(bundle.bootstraps??{}),workflows:bundle.workflows,
197
223
  logHome:path.join(batch.specsDir,'.reviews','host-log-mirror')});
198
- }catch(error){stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}${error.code==='protected_scope'&&typeof error.reason==='string'?`;${error.reason}`:''}`);}
224
+ }catch(error){
225
+ // A release refusal is not an invalid definition: show its own exit (upgrade or reinstall).
226
+ if(EXECUTOR_REASON_CODES.has(error?.code))stop(2,`${error.code}: ${error.reason}`);
227
+ stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}${error.code==='protected_scope'&&typeof error.reason==='string'?`;${error.reason}`:''}`);}
199
228
  const log=path.join(batch.specsDir,'运行日志.jsonl');
200
229
  // Members the batch already rescheduled into a serial second generation
201
230
  // (batch_member_blocked). Their gen-2 run starts fresh at attempt 1.
@@ -230,7 +259,7 @@ function preflight(){
230
259
  const argumentValue=name=>permissions.includes(name)?permissions[permissions.indexOf(name)+1]:undefined;
231
260
  if(argumentValue('--external-models-config'))permissions[permissions.indexOf('--external-models-config')+1]=path.resolve(base,argumentValue('--external-models-config'));
232
261
  const chosenRuntime=argumentValue('--runtime')??'codex';
233
- const routes=permissions.includes('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),chosenRuntime):{reviewerRuntime:chosenRuntime};
262
+ const routes=permissions.includes('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),chosenRuntime):{reviewerRuntime:argumentValue('--review-runtime')??chosenRuntime};
234
263
  let executionPolicy;
235
264
  try{executionPolicy=readBatchExecutionPolicy({batch,started:hasStore,enabled:permissions.includes('--execution-optimizations')});}catch(error){stop(2,error.code??'execution_policy_invalid');}
236
265
  let externalModels;
@@ -269,6 +298,10 @@ function preflight(){
269
298
  const argument=(name)=>permissions[permissions.indexOf(name)+1];
270
299
  if(permissions.includes('--runtime')&&!['codex','claude'].includes(argument('--runtime')))
271
300
  stop(2,'--runtime 只能是 codex 或 claude');
301
+ if(permissions.includes('--review-runtime')&&!['codex','claude'].includes(argument('--review-runtime')))
302
+ stop(2,'--review-runtime 只能是 codex 或 claude');
303
+ if(permissions.includes('--review-runtime')&&argument('--review-runtime')===(permissions.includes('--runtime')?argument('--runtime'):'codex'))
304
+ stop(2,'--review-runtime 只用于让另一工具审查,不能与写代码方(--runtime,缺省 codex)相同');
272
305
  if(permissions.includes('--browser-qa')&&!['available','unavailable'].includes(argument('--browser-qa')))
273
306
  stop(2,'--browser-qa 只能是 available 或 unavailable');
274
307
  if(permissions.includes('--allow-provider-development')&&!permissions.includes('--protected-config'))
@@ -357,6 +390,8 @@ function preflight(){
357
390
  :`任务 ${key} 已在第 ${attempt} 轮等待修订,但答案文件不存在: ${file};读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings 后写入再 advance`);
358
391
  }
359
392
  const value=readJson(file,'develop');validateCmAiAnswer('develop',value,taskRoot);
393
+ if(value.status==='succeeded'&&value.edits==='disk')
394
+ stop(2,`任务 ${key} ${path.basename(file)}: 批次驱动暂不支持 edits:"disk",请使用 answers 文件`);
360
395
  if(value.status==='succeeded')for(const target of Object.keys(value.edits))
361
396
  if(!definition.scope.includes(target))stop(2,`任务 ${key} ${path.basename(file)}.edits 越过批准 scope: ${target}`);
362
397
  perAttempt.set(attempt,value);deliveries.push({file,value,attempt});
@@ -426,7 +461,8 @@ async function answerFor(row,answers,paths,control){
426
461
  let currentId=group.commands[0].id;
427
462
  const run=createHostCheck({cwd,commands:group.commands,reuseDeclared:loaded.executionPolicy!==null,
428
463
  timeoutMs:group.timeoutMs,onProgress:event=>{if(event.phase==='start')currentId=event.id;reportHostCheckProgress(event);},
429
- onOutput:({stream,chunk})=>process.stderr.write(`[drive check ${key} ${currentId} ${stream}] ${chunk.toString('utf8')}`)});
464
+ // Returns nothing: host-check ignores sync return values but refuses a Promise.
465
+ onOutput:({stream,chunk})=>{process.stderr.write(`[drive check ${key} ${currentId} ${stream}] ${chunk.toString('utf8')}`);}});
430
466
  const rows=await run({identity},control);results.push(...rows);if(rows.some(row=>row.outcome!=='passed'))break;
431
467
  }
432
468
  return results;
@@ -476,6 +512,7 @@ function main(){
476
512
  :buildCmAiBatchDriveRequest(operation,plan);
477
513
  driveHost({host:HOST,args:buildCmAiBatchDriveHostArgs(plan,permissions,config,loaded.control?.file,loaded.holds),
478
514
  cwd:bundle.batch.codeProject,operation,request,
479
- answers:loaded.answers,answerFor,rateLimitRetry:rateLimitRetryEligible(operation,plan)?'batch':false});
515
+ answers:loaded.answers,answerFor,rateLimitRetry:rateLimitRetryEligible(operation,plan)?'batch':false,
516
+ nextStep:(row,{operation:sent,exitCode})=>cmAiNextStep(row,{surface:'batch',exitCode,operation:sent})});
480
517
  }
481
518
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();
@@ -12,6 +12,7 @@ import {batchDevelopAttempts,batchSessionMembers,batchLiveDevelopError,liveDevel
12
12
  import {createLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
13
13
  import {HOST_ANSWER_TIMEOUT_DEFAULT_MS} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
14
14
  import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
15
+ import {executorRelease} from '../runtime/js/executor-version.mjs';
15
16
 
16
17
  const DRIVER=fileURLToPath(new URL('./cm-ai-batch-drive.mjs',import.meta.url));
17
18
  const reviewer=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
@@ -122,6 +123,9 @@ test('real batch host advances with authored edit and actual check, then resumes
122
123
  const before=fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'));
123
124
  const state=path.join(f.store,fs.readdirSync(f.store).find(name=>name.startsWith('task-')),'state.json');
124
125
  const stateBefore=fs.readFileSync(state);
126
+ // A new batch records the feature-v1 QA count, and its member runs freeze it.
127
+ assert.equal(JSON.parse(stateBefore).records[0].payload.config.qaCadence,'feature-v1');
128
+ assert.equal(before.toString().trim().split('\n').map(line=>JSON.parse(line)).find(row=>row.phase==='batch_start').qa_cadence,'feature-v1');
125
129
  const resumed=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a'}),'status');
126
130
  assert.equal(resumed.status,0,resumed.stderr);
127
131
  assert.equal(JSON.parse(resumed.stdout).result.batchId,'batch-drive-run');
@@ -130,6 +134,39 @@ test('real batch host advances with authored edit and actual check, then resumes
130
134
  const again=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a'}),'advance');
131
135
  assert.equal(again.status,0,again.stderr);
132
136
  });
137
+ // Dogfood 2026-12-01: a check that prints (npm test always does) failed every batch
138
+ // with output_capture_failed, because the driver's output callback returned a value.
139
+ test('a batch check that prints output passes and its output reaches the driver stderr',t=>{
140
+ const f=fixture(t);prepared(f);
141
+ const loud=[process.execPath,'-e',"console.log('loud check stdout');console.error('loud check stderr')"];
142
+ const run=f.drive(f.plan({checks:{'1.work/T-001':[{id:'loud',command:loud}]}}),'advance');
143
+ assert.equal(run.status,0,run.stderr);
144
+ assert.doesNotMatch(run.stdout,/develop_checks_not_passed|output_capture_failed/,run.stdout);
145
+ assert.notEqual(JSON.parse(run.stdout).result.state,'blocked',run.stdout);
146
+ assert.match(run.stderr,/\[check\] 检查结束 loud: passed \(exit 0\)/,'the loud check itself passed');
147
+ assert.match(run.stderr,/\[drive check 1\.work\/T-001 loud stdout\] loud check stdout/);
148
+ assert.match(run.stderr,/\[drive check 1\.work\/T-001 loud stderr\] loud check stderr/);
149
+ });
150
+ // Executor release (0.22.0): a batch's first row names the release that started it;
151
+ // a batch started by a newer release is refused before anything is written.
152
+ test('batch_start records the starting executor release and a newer one is refused on resume',t=>{
153
+ const f=fixture(t);prepared(f);
154
+ const first=f.drive(f.plan(),'advance');assert.equal(first.status,0,first.stderr);
155
+ const logFile=path.join(f.specsDir,'运行日志.jsonl'),rows=fs.readFileSync(logFile,'utf8').split('\n').filter(Boolean);
156
+ const startAt=rows.findIndex(line=>JSON.parse(line).phase==='batch_start');
157
+ assert.deepEqual(JSON.parse(rows[startAt]).created_by,{version:1,release:executorRelease()});
158
+ rows[startAt]=JSON.stringify({...JSON.parse(rows[startAt]),created_by:{version:1,release:'99.0.0'}});
159
+ fs.writeFileSync(logFile,rows.join('\n')+'\n');
160
+ const before=fs.readFileSync(logFile),tasks=fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'));
161
+ const again=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a'}),'advance');
162
+ // Refused while the batch is being set up, before any lock, member or log write.
163
+ assert.equal(again.status,2,again.stdout);
164
+ assert.match(again.stderr,/run_created_by_newer_executor: 此运行由 CM 99\.0\.0 创建/);
165
+ assert.doesNotMatch(again.stderr,/批次定义、scope 或 workflow 无效/);
166
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution','batch.lock')),false);
167
+ assert.deepEqual(fs.readFileSync(logFile),before,'the batch log is unchanged');
168
+ assert.deepEqual(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md')),tasks);
169
+ });
133
170
  // The project log is shared by every run in the specs root. Rows of other runs,
134
171
  // including another batch, must not make a new batch look already started.
135
172
  test('a new batch starts in a specs root whose shared project log has only other runs',t=>{
@@ -390,8 +427,8 @@ test('optimized real batch driver shares only a declared same-plan check and rej
390
427
  const denied=f.drive(f.plan({checks}), 'advance');assert.equal(denied.status,2);noStore(f);assert(!fs.existsSync(counter));
391
428
  const out=f.drive(f.plan({permissions:['--allow-qa','--execution-optimizations'],checks}), 'advance');
392
429
  assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'run_done',out.stdout+out.stderr);
393
- // One physical command per phase: development and the required completion recheck.
394
- assert.equal(fs.readFileSync(counter,'utf8'),'xx');
430
+ // One physical command for development; a new run completes on the reviewed checks.
431
+ assert.equal(fs.readFileSync(counter,'utf8'),'x');
395
432
  });
396
433
 
397
434
  // Q24 driver: develop_redo goes through the batch host to the stopped member; the
@@ -519,6 +556,8 @@ await import(${JSON.stringify(reviewer)});
519
556
  }
520
557
  const batchLog=f=>{const file=path.join(f.specsDir,'运行日志.jsonl');return fs.existsSync(file)?fs.readFileSync(file,'utf8')
521
558
  .split('\n').filter(Boolean).map(JSON.parse).filter(row=>typeof row.phase==='string'&&row.phase.startsWith('batch_')):[];};
559
+ // Raw log bytes: "nothing written" must also catch a reformatted row or an appended non-batch row.
560
+ const logBytes=f=>{const file=path.join(f.specsDir,'运行日志.jsonl');return fs.existsSync(file)?fs.readFileSync(file):Buffer.alloc(0);};
522
561
  const until=async(check,ms=20000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,50));return check();};
523
562
  function driveAsync(f,file,operation,env){
524
563
  const child=spawn(process.execPath,[DRIVER,'--plan',file,operation],{env:{...process.env,PATH:path.join(f.root,'bin')+path.delimiter+process.env.PATH,
@@ -529,7 +568,7 @@ function driveAsync(f,file,operation,env){
529
568
  test('batch driver waits out a member review rate limit and redispatches only that review with retry_review',async t=>{
530
569
  const f=fixture(t);prepared(f);f.write('develop-a2.json',develop);
531
570
  const reviews=rateLimitedReviewer(f,1),permissions=['--allow-qa','--review-config','review.json'];
532
- const tasks=path.join(f.specsDir,'1.work','tasks.md'),before=fs.readFileSync(tasks,'utf8');
571
+ const tasks=path.join(f.specsDir,'1.work','tasks.md'),before=fs.readFileSync(tasks);
533
572
  const run=await driveAsync(f,f.plan({permissions}),'advance',{CM_DRIVE_RATE_LIMIT_DELAYS_MS:'300,300,300'}).done;
534
573
  assert.equal(run.status,0,run.stderr);
535
574
  assert.match(run.stderr,/审查被限流(reviewer_rate_limited),1 秒后在原运行自动重派审查(第 1\/3 次)/);
@@ -538,7 +577,7 @@ test('batch driver waits out a member review rate limit and redispatches only th
538
577
  assert.equal(result.state,'approved',run.stdout);assert.equal(result.taskKey,key);assert.equal(result.operation,'decision');
539
578
  // The batch's next step, not the member's complete: send advance from the batch entry.
540
579
  assert.equal(result.pendingAction,'advance');assert.match(result.guidance.nextStep,/从批次入口发送 advance/);
541
- assert.equal(reviews(),2);assert.equal(fs.readFileSync(tasks,'utf8'),before);
580
+ assert.equal(reviews(),2);assert.deepEqual(fs.readFileSync(tasks),before);
542
581
  assert.deepEqual(batchLog(f).map(row=>row.phase),['batch_start']);
543
582
  // The next advance continues the batch as usual.
544
583
  const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
@@ -552,12 +591,12 @@ test('batch rate-limit retry is stale once another driver moved the batch on: no
552
591
  // Meanwhile the session advances the batch itself.
553
592
  const other=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
554
593
  assert.equal(other.status,0,other.stderr);assert.equal(reviews(),2);
555
- const tasks=path.join(f.specsDir,'1.work','tasks.md'),afterOther={tasks:fs.readFileSync(tasks,'utf8'),log:batchLog(f)};
594
+ const tasks=path.join(f.specsDir,'1.work','tasks.md'),afterOther={tasks:fs.readFileSync(tasks),log:logBytes(f)};
556
595
  const first=await waiting.done,result=JSON.parse(first.stdout).result;
557
596
  assert.equal(result.staleRetry,true,first.stdout);assert.equal(result.outcome,'rejected');
558
597
  assert.match(first.stderr,/状态已变,未自动重试/);
559
598
  assert.equal(reviews(),2,'no third review');
560
- assert.deepEqual({tasks:fs.readFileSync(tasks,'utf8'),log:batchLog(f)},afterOther,'tasks.md and the batch log unchanged');
599
+ assert.deepEqual({tasks:fs.readFileSync(tasks),log:logBytes(f)},afterOther,'tasks.md and the run log unchanged byte for byte');
561
600
  });
562
601
  test('batch rate-limit retry stops at the round\'s second failure and does not retry again',async t=>{
563
602
  const f=fixture(t);prepared(f);f.write('develop-a2.json',develop);
@@ -637,3 +676,81 @@ test('a new batch whose QA answer window is shorter than the live wait stops bef
637
676
  assert.match(r.stderr,/1\.work\/T-001: workflow 的 qa\.timeoutMs 未填(默认 60000) 毫秒,短于 PLAN\.liveEvidence 对 qa_logic、qa_browser 的等待 900000 毫秒/);
638
677
  noStore(f);
639
678
  });
679
+
680
+ // 2026-12-01 探针实跑:PLAN.checks 写错只报「格式错误」,看不出哪一项、错在哪。
681
+ test('a malformed PLAN.checks entry names the item and what is wrong',t=>{
682
+ const f=fixture(t);prepared(f);const key='1.work/T-001';
683
+ const cases=[
684
+ [[{id:'syntax',command:'node --check target.mjs'}],/PLAN\.checks\.1\.work\/T-001\[0\].*command 必须是非空的参数数组/],
685
+ [[{id:'-bad id',command:[process.execPath,'--check','target.mjs']}],/\[0\].*id .*字母或数字开头/],
686
+ [[{id:'syntax',command:[process.execPath,'--check','target.mjs']},{id:'syntax',command:[process.execPath,'-v']}],/\[1\].*id "syntax" 重复/],
687
+ [[{id:'syntax',command:[process.execPath,'--check','target.mjs'],cwd:'.'}],/\[0\].*不认识的字段 "cwd"/],
688
+ [[{id:'syntax',command:[process.execPath,'']}],/\[0\].*command\[1\] 必须是非空字符串/],
689
+ [[{id:'syntax',command:[process.execPath,'--check','target.mjs']},{id:'again',command:[process.execPath,'-v'],timeoutMs:0}],/\[1\].*timeoutMs 需要 1\.\.3600000/],
690
+ // An id of the wrong type is named, never serialized (it might hold a value that should not be echoed).
691
+ [[{id:{token:'fixture-private-value'},command:[process.execPath,'-v']}],/\[0\].*id 不是字符串(object)/],
692
+ [[{id:'syntax',command:[process.execPath,'-v'],'bad\u001b[2Jfield':1}],/\[0\].*不认识的字段 "bad\?\[2Jfield"/],
693
+ // Codex 第三轮:U+061C/U+200E/U+200F 也会改显示顺序;重复 id 同样截到 64 字符。
694
+ [[{id:'syntax',command:[process.execPath,'-v'],'a\u061cb\u200ec\u200fd':1}],/\[0\].*不认识的字段 "a\?b\?c\?d"/],
695
+ [[{id:'x'.repeat(100)+'TAIL',command:[process.execPath,'-v']},{id:'x'.repeat(100)+'TAIL',command:[process.execPath,'-v']}],/\[1\].*id "x{64}" 重复/],
696
+ ];
697
+ for(const [checks,pattern] of cases){
698
+ const run=f.drive(f.plan({checks:{[key]:checks}}),'advance');
699
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,pattern);assert.doesNotMatch(run.stderr,/fixture-private-value|TAIL|[\u061c\u200e\u200f]/);noStore(f);
700
+ }
701
+ });
702
+
703
+ test('a sameExecutionAs that does not reuse the item right before it names that item and why',t=>{
704
+ const f=fixture(t);prepared(f);const plan=checks=>f.plan({permissions:['--allow-qa','--execution-optimizations'],checks:{[key]:checks}});
705
+ const command=[process.execPath,'-v'];
706
+ for(const [checks,pattern] of [
707
+ [[{id:'first',command},{id:'same',command,sameExecutionAs:'other'}],/\[1\].*sameExecutionAs 须等于紧挨着的上一项 id first/],
708
+ [[{id:'first',command},{id:'same',command:[process.execPath,'--version'],sameExecutionAs:'first'}],/\[1\].*command 须与上一项完全相同/],
709
+ [[{id:'first',command},{id:'same',command,timeoutMs:5000,sameExecutionAs:'first'}],/\[1\].*timeoutMs 须与上一项相同/],
710
+ ]){const run=f.drive(plan(checks),'advance');assert.equal(run.status,2,run.stderr);assert.match(run.stderr,pattern);noStore(f);}
711
+ });
712
+
713
+ // 2026-12-01 探针实跑:review.json 是另一端的预检时批次停在 tool_preflight_missing,reason 与 guidance 都是 null。
714
+ test('a review preflight made for the other runtime names the batch reviewer and how to regenerate it',t=>{
715
+ const f=fixture(t);prepared(f);
716
+ const run=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude']}),'advance');
717
+ const output=run.stdout+run.stderr;
718
+ assert.match(output,/tool_preflight_missing/,output);
719
+ assert.match(output,/审查端是 claude/,output);
720
+ assert.match(output,/批次.*审查端.*宿主 --runtime/,output);
721
+ // #302 起批次也有 --review-runtime:说明要写明它是新批次换审查端的入口。
722
+ assert.match(output,/没传 --review-runtime.*新批次启动时加 --review-runtime/,output);
723
+ assert.match(output,/preflight --config .*--runtime claude/,output);
724
+ });
725
+
726
+ // Found by the 2026-12-01 probe: a Claude session ran a batch in a project whose roles
727
+ // say Claude codes and Codex reviews. The batch had no --review-runtime, so its reviewer
728
+ // was the host (Claude) and a Codex preflight was refused with tool_preflight_missing.
729
+ test('a Claude-session batch is reviewed by Codex with --review-runtime codex, and resumes only with it',t=>{
730
+ const f=fixture(t);prepared(f);
731
+ fs.writeFileSync(path.join(f.codeProject,'.cm-workflow.yml'),
732
+ 'version: 1\nruntimes: {available: both}\nroles:\n coder: {adapter: claude-cli, source: subscription}\n reviewer: {adapter: codex-cli, source: subscription}\n');
733
+ for(const args of [['add','-A'],['commit','-m','roles']])assert.equal(spawnSync('git',['-C',f.codeProject,...args]).status,0);
734
+ // Without it the reviewer is the host, and the Codex preflight belongs to another tool.
735
+ const host=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude']}),'advance');
736
+ assert.equal(host.status,0,host.stderr);assert.equal(JSON.parse(host.stdout).result.code,'tool_preflight_missing');
737
+ fs.rmSync(f.store,{recursive:true,force:true});fs.rmSync(path.join(f.specsDir,'运行日志.jsonl'),{force:true});
738
+ const bad=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude','--review-runtime','other']}),'advance');
739
+ assert.equal(bad.status,2);assert.match(bad.stderr,/--review-runtime 只能是 codex 或 claude/);
740
+ const same=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude','--review-runtime','claude']}),'advance');
741
+ assert.equal(same.status,2);assert.match(same.stderr,/不能与写代码方/);
742
+ // Review R2: without --runtime the coder is codex, whatever permission comes first.
743
+ const defaulted=f.drive(f.plan({permissions:['--allow-qa','--review-runtime','codex']}),'advance');
744
+ assert.equal(defaulted.status,2);assert.match(defaulted.stderr,/不能与写代码方/);
745
+ const run=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude','--review-runtime','codex']}),'advance');
746
+ assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,'run_done');
747
+ // The member run binds the choice and was reviewed by the Codex adapter, not the host.
748
+ const {config}=JSON.parse(fs.readFileSync(path.join(f.store,JSON.parse(run.stdout).result.identity.runId,'state.json'),'utf8')).records[0].payload;
749
+ assert.equal(config.developer.provider,'claude');
750
+ assert.deepEqual(config.reviewers.map(item=>[item.provider,item.adapterId]),[['codex','codex-review-adapter']]);
751
+ const status=permissions=>{const out=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'status');
752
+ assert.equal(out.status,0,out.stderr);return JSON.parse(out.stdout).result;};
753
+ assert.notEqual(status(['--allow-qa','--runtime','claude','--review-runtime','codex']).outcome,'blocked');
754
+ // Dropping it later is refused by the batch plan digest instead of switching reviewers.
755
+ assert.equal(status(['--allow-qa','--runtime','claude']).code,'batch_plan_mismatch');
756
+ });