@aibyzero/cm-workflow 0.16.3 → 0.16.5

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -5,7 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {parseFeatureTaskText,validDependencies} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
8
+ import {parseFeatureTaskText,validDependencies,identifyApprovedBootstrapFeature} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
9
9
  import {validateRunDefinition} from './cm-ai-run.mjs';
10
10
 
11
11
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
@@ -39,6 +39,36 @@ test('product admission reports generic continuation without approving or writin
39
39
  assert.equal(fs.readdirSync(root).length,2);
40
40
  }));
41
41
 
42
+ test('spec approval accepts only normalized explicit start phrases',()=>fixture(({specs,code})=>{
43
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',features:['1.login'],testCases:[]}));
44
+ const run=reply=>{
45
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approval-response',reply],{encoding:'utf8'});
46
+ assert.equal(result.status,0,result.stderr);return JSON.parse(result.stdout);
47
+ };
48
+ for(const reply of ['开始','开始吧','可以开始','确认开始','开始执行','现在开始',' 开始吧。 ','现在开始! ','可以开始!.~~ ']){
49
+ const result=run(reply);assert.equal(result.approvalIntent,'explicit',reply);
50
+ assert.equal(result.reason,'approval_write_required',reply);
51
+ }
52
+ for(const reply of ['继续','可以','好','好的','OK','按最优解处理','你看着办','行','开始开发','开始吧,请继续']){
53
+ const result=run(reply);assert.equal(result.approvalIntent,'not_approval',reply);
54
+ assert.equal(result.reason,'spec_approval_required',reply);
55
+ assert.match(result.message,/回复.*开始/);
56
+ }
57
+ }));
58
+ test('approve writes only after a whitelisted reply and preserves the original reply',()=>fixture(({specs,code})=>{
59
+ const status=path.join(specs,'.cm-specs-status');
60
+ fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',features:['1.login'],testCases:[]}));
61
+ const before=fs.readFileSync(status);
62
+ const invoke=reply=>spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,
63
+ '--approve','--approval-response',reply],{encoding:'utf8'});
64
+ const rejected=invoke('好的');assert.equal(rejected.status,1);
65
+ assert.equal(JSON.parse(rejected.stdout).approveRefused,'explicit_approval_required');
66
+ assert.deepEqual(fs.readFileSync(status),before);
67
+ const accepted=invoke('开始吧!');assert.equal(accepted.status,0,`stdout: ${accepted.stdout}\nstderr: ${accepted.stderr}`);
68
+ assert.equal(JSON.parse(accepted.stdout).state,'ready');
69
+ assert.equal(JSON.parse(fs.readFileSync(status,'utf8')).approval.response,'开始吧!');
70
+ }));
71
+
42
72
  test('ready admission prints a directly valid run definition without writing the project',()=>fixture(({root,specs,code})=>{
43
73
  fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],testCases:[]}));
44
74
  fs.writeFileSync(path.join(code,'package.json'),JSON.stringify({name:'login-app'}));
@@ -94,6 +124,21 @@ function admission(specs,code,names,exitCode=0){
94
124
 
95
125
  const threeTasks='- [x] T-001: first\n- [ ] T-002: second\n- [ ] T-003: third\n';
96
126
 
127
+ test('approved bootstrap identity accepts numbered scaffold and rejects ambiguous candidates',()=>fixture(({specs,code})=>{
128
+ writeFeature(specs,'1.bootstrap','- [ ] T-001: 生成项目骨架 scaffold\n- [ ] T-002: 生成 AGENTS.md 和 .claude/ 规范\n');
129
+ fs.rmSync(path.join(specs,'1.login'),{recursive:true});
130
+ fs.rmSync(path.join(code,'README.md'));
131
+ assert.equal(identifyApprovedBootstrapFeature(['1.bootstrap']),'1.bootstrap');
132
+ assert.equal(identifyApprovedBootstrapFeature(['1.bootstrap-extra']),null);
133
+ assert.equal(admission(specs,code,['1.bootstrap']).nextTask.feature,'1.bootstrap');
134
+ assert.throws(()=>identifyApprovedBootstrapFeature(['0.bootstrap','1.bootstrap']),{code:'bootstrap_feature_ambiguous'});
135
+ assert.throws(()=>identifyApprovedBootstrapFeature(['1.bootstrap','2.bootstrap']),{code:'bootstrap_feature_ambiguous'});
136
+ for(const names of [['0.bootstrap','1.bootstrap'],['1.bootstrap','2.bootstrap']]){
137
+ for(const name of names)if(!fs.existsSync(path.join(specs,name)))writeFeature(specs,name,'- [ ] T-001: scaffold\n');
138
+ assert.equal(admission(specs,code,names,1).reason,'bootstrap_feature_ambiguous');
139
+ }
140
+ }));
141
+
97
142
  test('dependency parser accepts sentence punctuation per ID and preserves internal ID characters',()=>{
98
143
  for(const suffix of ['。','.','.',';',';','、',' 。 ..;;、 \t']){
99
144
  const parsed=parseFeatureTaskText(threeTasks+`- T-002 依赖 T-001${suffix}\n- T-003 依赖 T-001${suffix},T-002${suffix}\n`,
@@ -185,3 +230,22 @@ test('parallel eligibility preserves nextTask and returns only dependency-ready
185
230
  assert.equal(admission.nextTask.id,'T-001');
186
231
  assert.deepEqual(admission.eligibleTasks,[{feature:'1.login',id:'T-001'},{feature:'1.login',id:'T-002'}]);
187
232
  }));
233
+
234
+ test('explicit task prints only a dependency-ready member and binds selection in the definition',()=>fixture(({specs,code})=>{
235
+ fs.writeFileSync(path.join(specs,'1.login','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
236
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login']}));
237
+ const args=[entry,'--specs-dir',specs,'--code-project',code,'--print-run-definition','--scope','src/a.js'];
238
+ const chosen=spawnSync(process.execPath,[...args,'--task','T-002'],{encoding:'utf8'});
239
+ assert.equal(chosen.status,0,chosen.stderr);
240
+ const definition=JSON.parse(chosen.stdout);
241
+ assert.equal(definition.identity.taskId,'T-002');
242
+ assert.deepEqual(definition.taskSelection,{version:1,taskId:'T-002'});
243
+ assert.deepEqual(validateRunDefinition(definition),definition);
244
+ for(const task of ['T-003','T-999']){
245
+ const refused=spawnSync(process.execPath,[...args,'--task',task],{encoding:'utf8'});
246
+ assert.equal(refused.status,1,refused.stderr);assert.equal(JSON.parse(refused.stderr).error.code,'task_selection_mismatch');
247
+ assert.equal(refused.stdout,'');
248
+ }
249
+ const invalid=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--task','T-002'],{encoding:'utf8'});
250
+ assert.equal(invalid.status,2);assert.match(invalid.stderr,/--print-run-definition/);
251
+ }));
@@ -23,19 +23,33 @@ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
23
23
  import {validateRunDefinition} from './cm-ai-run.mjs';
24
24
  import {createCmAiBatch} from './cm-ai-batch-run.mjs';
25
25
  import {readConversationReviewConfiguration,readConversationProtection} from './cm-ai-host.mjs';
26
- import {validateCmAiAnswer} from './cm-ai-drive.mjs';
27
- import {stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
26
+ import {validateCmAiAnswer,developFilename,preflightDevelopDeliveries,baselineScope,inputLimitFrom,
27
+ applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes} from './cm-ai-drive.mjs';
28
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
29
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
30
+ import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
31
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
28
32
 
29
33
  const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
30
34
  const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
31
35
  documentation_sync:'documentation-sync.json',documentation_inspect:'documentation-inspect.json'};
32
36
  const PAIRS=new Set(['--runtime','--review-config','--browser-qa','--protected-conversation-config',
33
- '--protected-config','--allow-provider-development','--allow-review']);
37
+ '--protected-config','--allow-provider-development','--allow-review','--input-limit']);
34
38
  const FLAGS=new Set(['--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
35
39
  '--allow-bootstrap-write']);
36
40
  const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
37
41
  const nonempty=x=>typeof x==='string'&&x.trim().length>0;
38
42
  function taskKey(task){return `${task.feature}/${task.taskId}`;}
43
+ export function batchDevelopAttempts(state,key,permissions){
44
+ if(developmentRetryable(state))return [state.attempt];
45
+ if(state.state==='ready'&&state.attempt===1&&permissions.some((flag,index)=>
46
+ flag==='--allow-review'&&permissions[index+1]===`${key}:1`))return [1,2];
47
+ if(['ready','changes_requested'].includes(state.state))return [state.attempt];
48
+ if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2
49
+ &&permissions.some((flag,index)=>flag==='--allow-review'
50
+ &&permissions[index+1]===`${key}:${state.attempt}`))return [state.attempt+1];
51
+ return [];
52
+ }
39
53
  function actualCwd(bundle,key,generation=1){
40
54
  if(generation===2)return bundle.batch.codeProject;
41
55
  const group=bundle.batch.parallel?.find(group=>group.includes(key));
@@ -43,26 +57,32 @@ function actualCwd(bundle,key,generation=1){
43
57
  const id=key.slice(key.lastIndexOf('/')+1);
44
58
  return path.resolve(bundle.batch.codeProject,'..','.cm-worktrees',bundle.batch.batchId.slice(0,8),id);
45
59
  }
46
- function checkCommandShape(commands,key){
60
+ function checkCommandShape(commands,key,plan){
47
61
  if(!Array.isArray(commands)||!commands.length||commands.length>32)stop(2,`任务 ${key} 会反问 check,但 PLAN.checks.${key} 缺少真实命令列表`);
48
62
  const ids=new Set();
49
63
  for(const item of commands){
50
- if(!isObject(item)||Object.keys(item).sort().join()!=='command,id'
51
- ||!nonempty(item.id)||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
52
- ||item.command.some(arg=>typeof arg!=='string'||arg.includes('\0')))
64
+ if(!isObject(item)||Object.keys(item).some(field=>!['id','command','timeoutMs'].includes(field))
65
+ ||!nonempty(item.id)||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item.id)
66
+ ||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
67
+ ||item.command.some(arg=>typeof arg!=='string'||!arg.trim()||arg.includes('\0')))
53
68
  stop(2,`PLAN.checks.${key} 格式错误`);
69
+ try{planCheckTimeout(plan,item);}catch(error){stop(2,error.message);}
54
70
  ids.add(item.id);
55
71
  }
56
72
  }
57
73
  function preflight(){
58
74
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
59
75
  process.stdout.write('用法: cm-ai-batch-drive.mjs --plan PLAN.json <operation>\n'
60
- +'operation: advance, status, cancel。PLAN: config, mode, hostContext, permissions, answers, checks。\n');
76
+ +'operation: advance, status, cancel。PLAN: config, mode, hostContext, permissions, answers, checks, checkTimeoutMs。\n'
77
+ +'checks 每项为 {id,command,timeoutMs?};超时为 1..3600000 整数,默认 900000 ms(15 分钟)。\n'
78
+ +'develop.json.edits 与单任务驾驶员相同:内容文件、{file,mode}、{mode}、{delete:true};启动前同样拒绝超限、空交付与受保护模式下的非 UTF-8 内容(尚未开跑的后续任务不看代码树,只做答案本身就能判定的检查:单文件 1 MiB、答案写入的 scope 文件合计 2 MiB,等等;运行存档单条记录上限要看该任务开跑时的代码树,驾驶员事先算不出,超限交付写入后由宿主拦下,停在可重试的 blocked/develop_package_too_large)。\n'
79
+ +'带 --allow-review 任务:1 但还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
61
80
  process.exit(0);
62
81
  }
63
82
  const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel'])});
64
83
  const {plan,base,operation}=loaded;
65
84
  requireFields(plan,['config','mode','hostContext','permissions']);
85
+ try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
66
86
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
67
87
  if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
68
88
  if(plan.mode==='resume'&&plan.originalHostContext!==plan.hostContext)
@@ -153,7 +173,11 @@ function preflight(){
153
173
  stop(2,'缺少真实执行 runner: verification_precheck;不能从静态答案文件应答');
154
174
  if(operation==='advance'&&bundle.bootstraps&&Object.keys(bundle.bootstraps).length)
155
175
  stop(2,'缺少真实执行 runner: init_verify;不能从静态答案文件应答');
156
- const root=plan.answers?path.resolve(base,plan.answers):null,answers={};
176
+ const root=plan.answers?path.resolve(base,plan.answers):null,answers={},developAnswers=new Map(),holds=[];
177
+ const inputLimit=inputLimitFrom(permissions);
178
+ // Tasks that start from today's tree: the first task (and its parallel group) of
179
+ // a new batch. Later tasks start from trees earlier tasks have not written yet.
180
+ const firstGroup=batch.parallel?.find(group=>group.includes(keys[0]))??[keys[0]];
157
181
  if(operation==='advance')for(const task of batch.tasks){
158
182
  const key=taskKey(task),workflow=bundle.workflows[key],kinds=[];
159
183
  if(!providerAll)kinds.push('develop');
@@ -169,22 +193,69 @@ function preflight(){
169
193
  if(workflow)kinds.push('documentation_inspect');
170
194
  const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind));
171
195
  if(evidence.length)stop(2,`缺少真实执行 runner: ${evidence.join(', ')};不能从静态答案文件应答`);
172
- if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key);
196
+ if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key,plan);
173
197
  const taskRoot=root&&path.join(root,task.feature,task.taskId);
174
- answers[key]=preflightAnswers(kinds.filter(kind=>KINDS[kind]),kind=>{
198
+ const perAttempt=new Map();
199
+ if(kinds.includes('develop')){
200
+ let attempts=[1],current=1,journal=null;
201
+ if(plan.mode==='resume'){
202
+ const runIds=[...runs].filter(([,binding])=>binding.key===key).sort((a,b)=>b[1].generation-a[1].generation);
203
+ const existing=runIds.find(([runId])=>fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',runId,'state.json')));
204
+ if(existing)try{
205
+ const snapshot=readExecutionSnapshot({specsRoot:batch.specsDir,identity:{repositoryId:batch.repositoryId,runId:existing[0]}});
206
+ const history=readRunnerHistory(snapshot.records,snapshot.records[0].payload.config,3);
207
+ attempts=batchDevelopAttempts(history.state,key,permissions);current=history.state.attempt;
208
+ journal={baseline:snapshot.records[0].payload.baseline,generation:existing[1].generation,
209
+ frame:journalRestBytes(snapshot.records)};
210
+ }catch(error){stop(2,`任务 ${key} 无法只读检查恢复存档: ${error.code??error.message}`);}
211
+ }
212
+ // A task with no run yet (a new batch, or a later task on resume) starts at
213
+ // attempt 1; a first-round review grant can then reach attempt 2 as well.
214
+ if(journal===null&&permissions.some((flag,index)=>flag==='--allow-review'&&permissions[index+1]===`${key}:1`))attempts=[1,2];
215
+ const deliveries=[],definition=definitions.get(key);
216
+ for(const attempt of attempts){
217
+ const file=path.join(taskRoot??'',developFilename(taskRoot??'',attempt));
218
+ if(!taskRoot||!fs.existsSync(file)){
219
+ // A later attempt is only reached if the review this launch authorizes asks
220
+ // for changes. Without its answer the task stops right after that review.
221
+ if(attempt>current){
222
+ holds.push(key);
223
+ 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`);
224
+ continue;
225
+ }
226
+ stop(2,attempt===1?`任务 ${key} 会反问 develop,但答案文件不存在: ${file}`
227
+ :`任务 ${key} 已在第 ${attempt} 轮等待修订,但答案文件不存在: ${file};读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings 后写入再 advance`);
228
+ }
229
+ const value=readJson(file,'develop');validateCmAiAnswer('develop',value,taskRoot);
230
+ if(value.status==='succeeded')for(const target of Object.keys(value.edits))
231
+ if(!definition.scope.includes(target))stop(2,`任务 ${key} ${path.basename(file)}.edits 越过批准 scope: ${target}`);
232
+ perAttempt.set(attempt,value);deliveries.push({file,value,attempt});
233
+ }
234
+ if(deliveries.length){
235
+ const known=journal!==null||plan.mode==='create'&&firstGroup.includes(key);
236
+ const cwd=journal?actualCwd(bundle,key,journal.generation):batch.codeProject;
237
+ const codeProject=fs.existsSync(cwd)?cwd:batch.codeProject;
238
+ preflightDevelopDeliveries({deliveries,answersRoot:taskRoot,codeProject,
239
+ scope:definition.scope,requirements:definition.requirements,diskChecks:known,
240
+ baseline:journal?baselineScope(journal.baseline,definition.scope):'disk',protectedMode,inputLimit,
241
+ checks:plannedCheckResults(protectedMode?null:plan.checks?.[key]),
242
+ preview:known?developPreview({definition,codeProject,journal,
243
+ parallelSelection:batch.parallel?.find(group=>group.includes(key))
244
+ ?{version:1,group:batch.parallel.find(group=>group.includes(key)).map(member=>definitions.get(member).identity.taskId)}:null}):null});
245
+ }
246
+ }
247
+ developAnswers.set(key,perAttempt);
248
+ answers[key]=preflightAnswers(kinds.filter(kind=>KINDS[kind]&&kind!=='develop'),kind=>{
175
249
  const file=path.join(taskRoot??'',KINDS[kind]);
176
250
  if(!taskRoot||!fs.existsSync(file))stop(2,`任务 ${key} 会反问 ${kind},但答案文件不存在: ${file}`);
177
251
  const value=readJson(file,kind);
178
252
  validateCmAiAnswer(kind,value,taskRoot);
179
253
  return value;
180
254
  });
181
- const develop=answers[key].develop;
182
- if(develop?.status==='succeeded')for(const target of Object.keys(develop.edits))
183
- if(!definitions.get(key).scope.includes(target))stop(2,`任务 ${key} develop.json.edits 越过批准 scope: ${target}`);
184
255
  if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
185
256
  if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
186
257
  }
187
- return {...loaded,bundle,definitions,runs,config,permissions,answers,answerRoot:root};
258
+ return {...loaded,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds};
188
259
  }
189
260
 
190
261
  let loaded;
@@ -207,12 +278,13 @@ async function answerFor(row){
207
278
  const cwd=actualCwd(loaded.bundle,key,binding.generation);
208
279
  const task=loaded.bundle.batch.tasks.find(task=>taskKey(task)===key);
209
280
  const root=path.join(loaded.answerRoot,task.feature,task.taskId);
210
- const value=loaded.answers[key][row.kind];
281
+ const value=row.kind==='develop'?loaded.developAnswers.get(key)?.get(identity?.attempt):loaded.answers[key][row.kind];
211
282
  if(row.kind==='check'){
212
283
  if(row.payload.codeProject!==cwd)return null;
213
284
  const results=[];
214
285
  for(const command of loaded.plan.checks[key]){
215
- const run=createHostCheck({cwd,commands:[command],onOutput:({stream,chunk})=>{
286
+ const run=createHostCheck({cwd,commands:[{id:command.id,command:command.command}],
287
+ timeoutMs:planCheckTimeout(loaded.plan,command),onOutput:({stream,chunk})=>{
216
288
  process.stderr.write(`[drive check ${key} ${command.id} ${stream}] ${chunk.toString('utf8')}`);
217
289
  }});
218
290
  const [result]=await run({identity},{signal:new AbortController().signal});
@@ -221,12 +293,12 @@ async function answerFor(row){
221
293
  return results;
222
294
  }
223
295
  if(row.kind==='develop'){
296
+ if(!value)throw Error(`任务 ${key} develop attempt ${identity?.attempt} 未预检,拒绝复用旧答案`);
224
297
  if(row.payload.codeProject!==cwd)return null;
225
298
  if(value.status!=='succeeded')return {status:'failed',code:value.code};
226
299
  if(row.payload.editMode==='protected-text-v1')return {status:'succeeded',value:value.value,
227
- edits:Object.entries(value.edits).map(([target,local])=>({path:target,
228
- beforeSha256:row.payload.expected?.[target]??null,content:fs.readFileSync(path.join(root,local),'utf8')}))};
229
- safeWrite(value.edits,root,cwd,row.payload.request.payload.scope);
300
+ edits:protectedDevelopEdits(value.edits,root,cwd,row.payload.expected)};
301
+ applyDevelopEdits(value.edits,root,cwd,row.payload.request.payload.scope);
230
302
  return {status:'succeeded',value:value.value};
231
303
  }
232
304
  if(row.kind==='documentation_sync'){
@@ -245,7 +317,7 @@ function main(){
245
317
  loaded=preflight();
246
318
  const {plan,operation,bundle,config,permissions}=loaded;
247
319
  driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
248
- '--allow-development',...permissions],cwd:bundle.batch.codeProject,operation,
320
+ '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,
249
321
  answers:loaded.answers,answerFor});
250
322
  }
251
323
  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 {batchDevelopAttempts} from './cm-ai-batch-drive.mjs';
10
11
 
11
12
  const DRIVER=fileURLToPath(new URL('./cm-ai-batch-drive.mjs',import.meta.url));
12
13
  const reviewer=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
@@ -18,7 +19,7 @@ const develop={status:'succeeded',value:{outcome:'implemented',
18
19
  function fixture(t,count=1){
19
20
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-batch-drive-')));
20
21
  t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
21
- const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),bin=path.join(root,'bin');
22
+ const specsDir=path.join(root,'specs5'),codeProject=path.join(root,'app'),bin=path.join(root,'bin');
22
23
  fs.mkdirSync(path.join(specsDir,'1.work'),{recursive:true});fs.mkdirSync(codeProject);fs.mkdirSync(bin);
23
24
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,'1.work',name),'# Fixture\n');
24
25
  fs.writeFileSync(path.join(specsDir,'1.work','tasks.md'),Array.from({length:count},(_,n)=>
@@ -44,9 +45,12 @@ function fixture(t,count=1){
44
45
  const write=(name,value)=>fs.writeFileSync(path.join(answers,name),JSON.stringify(value));
45
46
  const plan=(extra={})=>{
46
47
  const file=path.join(root,`plan-${Math.random().toString(36).slice(2)}.json`);
47
- fs.writeFileSync(file,JSON.stringify({config:'batch.json',mode:'create',hostContext:'batch-host-a',
48
+ const value={config:'batch.json',mode:'create',hostContext:'batch-host-a',
48
49
  permissions:['--allow-qa'],answers:'answers',checks:Object.fromEntries(batch.tasks.map(task=>
49
- [`1.work/${task.taskId}`,[{id:'syntax',command:[process.execPath,'--check',task.taskId==='T-001'?'target.mjs':'target2.mjs']}]])),...extra}));
50
+ [`1.work/${task.taskId}`,[{id:'syntax',command:[process.execPath,'--check',task.taskId==='T-001'?'target.mjs':'target2.mjs']}]])),...extra};
51
+ // A new batch requires a bound review configuration (it grants no review).
52
+ if(!value.permissions.includes('--review-config'))value.permissions=[...value.permissions,'--review-config','review.json'];
53
+ fs.writeFileSync(file,JSON.stringify(value));
50
54
  return file;
51
55
  };
52
56
  const drive=(file,operation)=>spawnSync(process.execPath,[DRIVER,'--plan',file,operation],{encoding:'utf8',timeout:60000,
@@ -67,6 +71,13 @@ test('help names plan invocation',()=>{
67
71
  const run=spawnSync(process.execPath,[DRIVER,'--help'],{encoding:'utf8'});
68
72
  assert.equal(run.status,0);assert.match(run.stdout,/--plan PLAN\.json <operation>/);
69
73
  });
74
+ test('batch driver accepts input limit as a value before host launch',t=>{
75
+ const f=fixture(t);
76
+ const run=f.drive(f.plan({permissions:['--allow-qa','--input-limit','1048576']}),'advance');
77
+ assert.equal(run.status,2);assert.match(run.stderr,/develop\.json/);
78
+ assert.doesNotMatch(run.stderr,/permissions 无效|--input-limit 文件不存在/);
79
+ noStore(f);
80
+ });
70
81
  test('real batch host advances with authored edit and actual check, then resumes and reports status',t=>{
71
82
  const f=fixture(t);prepared(f);
72
83
  const first=f.drive(f.plan(),'advance');assert.equal(first.status,0,first.stderr);
@@ -85,6 +96,7 @@ test('real batch host advances with authored edit and actual check, then resumes
85
96
  });
86
97
  test('real batch reaches completion with an independently dispatched fixture review',t=>{
87
98
  const f=fixture(t);prepared(f);
99
+ f.write('develop-a2.json',develop);
88
100
  const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
89
101
  const first=f.drive(f.plan({permissions}),'advance');
90
102
  assert.equal(first.status,0,first.stderr);assert.match(first.stderr,/应答 check/);
@@ -95,6 +107,162 @@ test('real batch reaches completion with an independently dispatched fixture rev
95
107
  }
96
108
  assert.equal(result.state,'run_done',JSON.stringify(result));
97
109
  });
110
+ // Deliberately replaced (#30). The batch driver has no separate decision step, so
111
+ // demanding develop-a2.json before any findings existed made a first review with
112
+ // a possible revision impossible. Without the answer it now stops after the review.
113
+ function changesRequested(f){
114
+ const cli=path.join(f.root,'bin','codex');
115
+ fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8').replace("verdict:'approved'","verdict:'changes_requested'")
116
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Fixture finding'}]"));
117
+ fs.chmodSync(cli,0o700);
118
+ }
119
+ const developIntents=f=>{
120
+ const state=path.join(f.store,fs.readdirSync(f.store).find(name=>name.startsWith('task-')),'state.json');
121
+ return JSON.parse(fs.readFileSync(state,'utf8')).records.filter(row=>row.payload.type==='effect-intent'
122
+ &&row.payload.effect.kind==='develop').map(row=>row.payload.effect.id);
123
+ };
124
+ test('batch review without a second-round answer stops at changes_requested after the first review',t=>{
125
+ const f=fixture(t);prepared(f);changesRequested(f);
126
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
127
+ const run=f.drive(f.plan({permissions}),'advance');
128
+ assert.equal(run.status,0,run.stderr);
129
+ assert.match(run.stderr,/没有 develop-a2\.json/);assert.match(run.stderr,/\.reviews\/work-T-001-r1\.md/);
130
+ const result=JSON.parse(run.stdout).result;
131
+ assert.equal(result.state,'changes_requested',run.stdout);assert.equal(result.code,'revision_answer_required');
132
+ assert.equal(result.identity.attempt,2);assert.equal(result.pendingAction,'resume');
133
+ assert(fs.existsSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md')));
134
+ assert.deepEqual(developIntents(f),['develop-1'],'no second-round develop intent before its answer exists');
135
+ // The findings exist now: the revision is written and the same batch continues.
136
+ fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 43;\n');
137
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
138
+ const revised=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',
139
+ permissions:['--allow-qa','--review-config','review.json']}),'advance');
140
+ assert.equal(revised.status,0,revised.stderr);assert.match(revised.stderr,/应答 develop/);
141
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 43;\n');
142
+ assert.equal(JSON.parse(revised.stdout).result.identity.attempt,2);
143
+ assert.deepEqual(developIntents(f),['develop-1','develop-2']);
144
+ });
145
+ test('batch resume holds a later task that has no run yet when its second-round answer is missing',t=>{
146
+ const f=fixture(t,2);prepared(f);
147
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
148
+ fs.writeFileSync(path.join(later,'target2.txt'),'export const value = 42;\n');
149
+ for(const name of ['qa-assess.json','documentation-inspect.json'])
150
+ fs.copyFileSync(path.join(f.answers,name),path.join(later,name));
151
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:{'target2.mjs':'target2.txt'}}));
152
+ // T-001 stops at awaiting_review first, so T-002 has no run when the batch resumes.
153
+ const first=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json']}),'advance');
154
+ assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'awaiting_review');
155
+ // The reviewer approves T-001 and asks for changes on T-002.
156
+ const cli=path.join(f.root,'bin','codex');
157
+ fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8').replace("verdict:'approved'",
158
+ "verdict:prompt.includes('target2.mjs')?'changes_requested':'approved'")
159
+ .replace('findings:[]',"findings:prompt.includes('target2.mjs')?[{id:'F1',severity:'P2',path:'target2.mjs',message:'Revise',evidence:'Fixture finding'}]:[]"));
160
+ fs.chmodSync(cli,0o700);
161
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`,'--allow-review','1.work/T-002:1'];
162
+ let result;
163
+ for(let n=0;n<4;n++){
164
+ const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
165
+ assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;
166
+ if(result.code==='revision_answer_required')break;
167
+ }
168
+ assert.equal(result.state,'changes_requested',JSON.stringify(result));assert.equal(result.code,'revision_answer_required');
169
+ assert.equal(result.identity.taskId,'T-002');
170
+ });
171
+ test('batch hold without a second-round answer does not interfere with an approving review',t=>{
172
+ const f=fixture(t);prepared(f);
173
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
174
+ const first=f.drive(f.plan({permissions}),'advance');assert.equal(first.status,0,first.stderr);
175
+ let result=JSON.parse(first.stdout).result;
176
+ for(let n=0;n<4&&result.state!=='run_done';n++){
177
+ const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
178
+ assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;
179
+ }
180
+ assert.equal(result.state,'run_done',JSON.stringify(result));
181
+ });
182
+ test('batch driver refuses an oversized answer of a later task before launching the first',t=>{
183
+ const f=fixture(t,2);prepared(f);
184
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
185
+ fs.writeFileSync(path.join(later,'big.txt'),Buffer.alloc(1200*1024,0x61));
186
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:{'target2.mjs':'big.txt'}}));
187
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
188
+ assert.match(run.stderr,/target2\.mjs/);assert.match(run.stderr,/1048576/);noStore(f);
189
+ });
190
+ // Codex review of 910b84c: a later task's starting tree is unknown, but its answer
191
+ // files alone can already prove a limit is exceeded; those checks still apply.
192
+ function laterTask(f,scope,files){
193
+ const config=path.join(f.root,'batch.json'),bundle=JSON.parse(fs.readFileSync(config,'utf8'));
194
+ bundle.batch.tasks[1].scope=scope;fs.writeFileSync(config,JSON.stringify(bundle));
195
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
196
+ for(const name of ['qa-assess.json','documentation-inspect.json'])
197
+ fs.copyFileSync(path.join(f.answers,name),path.join(later,name));
198
+ for(const [name,size] of Object.entries(files))fs.writeFileSync(path.join(later,name.replaceAll('/','_')+'.txt'),Buffer.alloc(size,0x61));
199
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:Object.fromEntries(Object.keys(files).map(name=>[name,name.replaceAll('/','_')+'.txt']))}));
200
+ }
201
+ test('batch driver refuses a later task whose new files alone exceed the 2 MiB material limit',t=>{
202
+ const f=fixture(t,2);prepared(f);
203
+ const scope=['gen/a.bin','gen/b.bin','gen/c.bin'];laterTask(f,scope,Object.fromEntries(scope.map(file=>[file,700*1024])));
204
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
205
+ assert.match(run.stderr,/2097152/);assert.match(run.stderr,/gen\/[abc]\.bin/);noStore(f);
206
+ });
207
+ test('batch driver lets a later task\'s second-round delete bring its delivered files back under 2 MiB',t=>{
208
+ const f=fixture(t,2);prepared(f);
209
+ laterTask(f,['gen/a.bin','gen/b.bin','gen/c.bin'],{'gen/a.bin':1000*1024,'gen/b.bin':1000*1024});
210
+ const later=path.join(f.root,'answers','1.work','T-002');
211
+ fs.writeFileSync(path.join(later,'gen_c.bin.txt'),Buffer.alloc(100*1024,0x61));
212
+ fs.writeFileSync(path.join(later,'develop-a2.json'),JSON.stringify({...develop,edits:{'gen/b.bin':{delete:true},'gen/c.bin':'gen_c.bin.txt'}}));
213
+ const run=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json','--allow-review','1.work/T-002:1']}),'advance');
214
+ assert.equal(run.status,0,run.stderr);assert.doesNotMatch(run.stderr,/仅答案写入/);assert.equal(fs.existsSync(f.store),true);
215
+ });
216
+ test('batch driver refuses a no-op or non-UTF-8 protected develop answer before launch',t=>{
217
+ const f=fixture(t);prepared(f);
218
+ f.write('develop.json',{...develop,edits:{}});
219
+ const empty=f.drive(f.plan(),'advance');assert.equal(empty.status,2,empty.stderr);
220
+ assert.match(empty.stderr,/没有任何改动/);noStore(f);
221
+ fs.writeFileSync(path.join(f.root,'protection.json'),JSON.stringify({checkCommands:[{id:'noop',command:['/usr/bin/true']}],timeoutMs:60000}));
222
+ fs.writeFileSync(path.join(f.answers,'target.txt'),Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0xff]));
223
+ f.write('develop.json',develop);
224
+ const binary=f.drive(f.plan({permissions:['--allow-qa','--protected-conversation-config','protection.json'],checks:undefined}),'advance');
225
+ assert.equal(binary.status,2,binary.stderr);assert.match(binary.stderr,/UTF-8/);assert.match(binary.stderr,/target\.mjs/);noStore(f);
226
+ });
227
+ test('batch review revision applies the second-round develop content',t=>{
228
+ const f=fixture(t);prepared(f);
229
+ const cli=path.join(f.root,'bin','codex');
230
+ fs.writeFileSync(cli,fs.readFileSync(cli,'utf8').replace("verdict:'approved'","verdict:'changes_requested'")
231
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Fixture finding'}]"));
232
+ fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 43;\n');
233
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
234
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
235
+ const run=f.drive(f.plan({permissions}),'advance');assert.equal(run.status,0,run.stderr);
236
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 43;\n');
237
+ });
238
+ test('batch first-round answer aliases cannot coexist',t=>{
239
+ const f=fixture(t);prepared(f);f.write('develop-a1.json',develop);
240
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
241
+ assert.match(run.stderr,/develop\.json.*develop-a1\.json/);noStore(f);
242
+ });
243
+ test('batch retryable blocked state projects the same develop attempt',()=>{
244
+ for(const code of ['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed'])
245
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code,attempt:2},key,[]),[2]);
246
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code:'checks_not_passed',attempt:2},key,[]),[]);
247
+ });
248
+
249
+ test('D1 batch rejects invalid check timeout before opening a host',t=>{
250
+ const f=fixture(t);prepared(f);
251
+ const checks={[key]:[{id:'syntax',command:[process.execPath,'--check','target.mjs'],timeoutMs:0}]};
252
+ const run=f.drive(f.plan({checks}),'advance');
253
+ assert.equal(run.status,2);assert.match(run.stderr,/timeoutMs/);noStore(f);
254
+ });
255
+
256
+ test('D1 batch retries failed checks before review in the same attempt',t=>{
257
+ const f=fixture(t);prepared(f);
258
+ const failed={[key]:[{id:'test',command:[process.execPath,'-e','process.exit(1)']}]};
259
+ const first=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude'],checks:failed}),'advance');assert.equal(first.status,0,first.stderr);
260
+ const result=JSON.parse(first.stdout).result;
261
+ assert.equal(result.code,'develop_checks_not_passed');assert.equal(result.pendingAction,'resume');
262
+ const clean={[key]:[{id:'test',command:[process.execPath,'-e','0']}]};
263
+ const second=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions:['--allow-qa','--runtime','claude'],checks:clean}),'advance');
264
+ assert.equal(second.status,0,second.stderr);assert.match(second.stderr,/应答 develop/);
265
+ });
98
266
  test('missing answer leaves no batch store or session',t=>{
99
267
  const f=fixture(t);const run=f.drive(f.plan(),'advance');
100
268
  assert.equal(run.status,2);assert.match(run.stderr,/develop\.json/);noStore(f);