@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -13,29 +13,49 @@
13
13
  // status/cancel -> none: batch-run.mjs handle routes only these and advance;
14
14
  // host-session.mjs operationNames admits all three. Other operationNames belong
15
15
  // to child/single-task hosts and are not batch operations.
16
+ import {readBatchExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
17
+ import {readBatchExternalModels,batchModelsFile} from '../runtime/js/cm-ai/external-group-models.mjs';
18
+ import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
16
19
  import fs from 'node:fs';
17
20
  import path from 'node:path';
18
21
  import {fileURLToPath} from 'node:url';
19
- import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
22
+ import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
20
23
  import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
21
24
  import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
22
25
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
23
26
  import {validateRunDefinition} from './cm-ai-run.mjs';
24
27
  import {createCmAiBatch} from './cm-ai-batch-run.mjs';
25
28
  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';
29
+ import {validateCmAiAnswer,developFilename,preflightDevelopDeliveries,baselineScope,inputLimitFrom,
30
+ applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes} from './cm-ai-drive.mjs';
31
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
32
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
33
+ import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
34
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
28
35
 
36
+ import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
37
+
38
+ // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
29
39
  const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
30
40
  const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
31
41
  documentation_sync:'documentation-sync.json',documentation_inspect:'documentation-inspect.json'};
32
- const PAIRS=new Set(['--runtime','--review-config','--browser-qa','--protected-conversation-config',
42
+ const PAIRS=new Set(['--external-models-config','--runtime','--review-config','--browser-qa','--protected-conversation-config',
33
43
  '--protected-config','--allow-provider-development','--allow-review','--input-limit']);
34
- const FLAGS=new Set(['--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
44
+ const FLAGS=new Set(['--execution-optimizations','--external-models','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
35
45
  '--allow-bootstrap-write']);
36
46
  const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
37
47
  const nonempty=x=>typeof x==='string'&&x.trim().length>0;
38
48
  function taskKey(task){return `${task.feature}/${task.taskId}`;}
49
+ export function batchDevelopAttempts(state,key,permissions){
50
+ if(developmentRetryable(state))return [state.attempt];
51
+ if(state.state==='ready'&&state.attempt===1&&permissions.some((flag,index)=>
52
+ flag==='--allow-review'&&permissions[index+1]===`${key}:1`))return [1,2];
53
+ if(['ready','changes_requested'].includes(state.state))return [state.attempt];
54
+ if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2
55
+ &&permissions.some((flag,index)=>flag==='--allow-review'
56
+ &&permissions[index+1]===`${key}:${state.attempt}`))return [state.attempt+1];
57
+ return [];
58
+ }
39
59
  function actualCwd(bundle,key,generation=1){
40
60
  if(generation===2)return bundle.batch.codeProject;
41
61
  const group=bundle.batch.parallel?.find(group=>group.includes(key));
@@ -43,26 +63,36 @@ function actualCwd(bundle,key,generation=1){
43
63
  const id=key.slice(key.lastIndexOf('/')+1);
44
64
  return path.resolve(bundle.batch.codeProject,'..','.cm-worktrees',bundle.batch.batchId.slice(0,8),id);
45
65
  }
46
- function checkCommandShape(commands,key){
66
+ function checkCommandShape(commands,key,plan,executionPolicy){
47
67
  if(!Array.isArray(commands)||!commands.length||commands.length>32)stop(2,`任务 ${key} 会反问 check,但 PLAN.checks.${key} 缺少真实命令列表`);
48
68
  const ids=new Set();
49
69
  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')))
70
+ if(!isObject(item)||Object.keys(item).some(field=>!['id','command','timeoutMs',...(executionPolicy?['sameExecutionAs']:[])].includes(field))
71
+ ||!nonempty(item.id)||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item.id)
72
+ ||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
73
+ ||item.command.some(arg=>typeof arg!=='string'||!arg.trim()||arg.includes('\0')))
53
74
  stop(2,`PLAN.checks.${key} 格式错误`);
75
+ try{planCheckTimeout(plan,item);}catch(error){stop(2,error.message);}
54
76
  ids.add(item.id);
55
77
  }
78
+ try{
79
+ 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');
80
+ createHostCheck({cwd:process.cwd(),commands:commands.map(({timeoutMs,...item})=>item),reuseDeclared:executionPolicy!==null});
81
+ }catch(error){stop(2,`PLAN.checks.${key} 格式错误: ${error.code??error.message}`);}
56
82
  }
57
83
  function preflight(){
58
84
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
59
85
  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');
86
+ +'operation: advance, status, cancel。PLAN: config, mode, hostContext, permissions, answers, checks, checkTimeoutMs。\n'
87
+ +'checks 每项为 {id,command,timeoutMs?};超时为 1..3600000 整数,默认 900000 ms(15 分钟)。\n'
88
+ +'develop.json.edits 与单任务驾驶员相同:内容文件、{file,mode}、{mode}、{delete:true};启动前同样拒绝超限、空交付与受保护模式下的非 UTF-8 内容(尚未开跑的后续任务不看代码树,只做答案本身就能判定的检查:单文件 1 MiB、答案写入的 scope 文件合计 2 MiB,等等;运行存档单条记录上限要看该任务开跑时的代码树,驾驶员事先算不出,超限交付写入后由宿主拦下,停在可重试的 blocked/develop_package_too_large)。\n'
89
+ +'带 --allow-review 任务:1 但还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
61
90
  process.exit(0);
62
91
  }
63
- const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel'])});
92
+ const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel','reconcile_review'])});
64
93
  const {plan,base,operation}=loaded;
65
94
  requireFields(plan,['config','mode','hostContext','permissions']);
95
+ try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
66
96
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
67
97
  if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
68
98
  if(plan.mode==='resume'&&plan.originalHostContext!==plan.hostContext)
@@ -112,17 +142,26 @@ function preflight(){
112
142
  if(plan.mode==='create'&&operation==='advance'&&(hasLog||hasStore))
113
143
  stop(2,`批次已有存档,请用 resume: ${log}`);
114
144
  if(operation==='status'&&!hasStore)stop(2,`只读 status 需要已有任务存档: ${stores.join(', ')}`);
145
+ const argumentValue=name=>permissions.includes(name)?permissions[permissions.indexOf(name)+1]:undefined;
146
+ if(argumentValue('--external-models-config'))permissions[permissions.indexOf('--external-models-config')+1]=path.resolve(base,argumentValue('--external-models-config'));
147
+ const chosenRuntime=argumentValue('--runtime')??'codex';
148
+ const routes=permissions.includes('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:batch.codeProject}),chosenRuntime):{reviewerRuntime:chosenRuntime};
149
+ let executionPolicy;
150
+ try{executionPolicy=readBatchExecutionPolicy({batch,started:hasStore,enabled:permissions.includes('--execution-optimizations')});}catch(error){stop(2,error.code??'execution_policy_invalid');}
151
+ let externalModels;
152
+ try{externalModels=readBatchExternalModels({batch,started:hasStore,enabled:permissions.includes('--external-models'),inputFile:argumentValue('--external-models-config'),providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});}catch(error){stop(2,error.code??'external_model_configuration_invalid');}
153
+ if(operation==='reconcile_review'&&(plan.mode!=='resume'||!keys.includes(plan.taskKey)||!nonempty(plan.invocationId)))stop(2,'reconcile_review requires resume, taskKey and original invocationId');
115
154
  for(let i=0;i<permissions.length;i++)if(PAIRS.has(permissions[i])){
116
155
  const name=permissions[i],value=permissions[++i];
117
156
  if(['--review-config','--protected-conversation-config','--protected-config'].includes(name)){
118
157
  const file=path.resolve(base,value),data=readJson(file,name);
119
158
  if(data===undefined)stop(2,`${name} 文件不存在: ${file}`);
120
159
  try{
121
- if(name==='--review-config')readConversationReviewConfiguration(file);
160
+ if(name==='--review-config')readConversationReviewConfiguration(file,externalModels?.providers[routes.reviewerRuntime]??null);
122
161
  else if(name==='--protected-conversation-config')readConversationProtection(file);
123
162
  else {
124
- if(!isObject(data)||Object.keys(data).sort().join()!=='checkCommands,model,timeoutMs'
125
- ||!nonempty(data.model)||!/^[A-Za-z0-9._-]+$/.test(data.model)
163
+ if(!isObject(data)||Object.keys(data).some(key=>!['checkCommands','model','effort','timeoutMs'].includes(key))
164
+ ||!externalModels&&(!nonempty(data.model)||!/^[A-Za-z0-9._-]+$/.test(data.model))
126
165
  ||!Number.isSafeInteger(data.timeoutMs)||data.timeoutMs<=0||data.timeoutMs>3600000)
127
166
  throw Error('invalid_protected_config');
128
167
  createHostCheck({cwd:batch.codeProject,commands:data.checkCommands,timeoutMs:data.timeoutMs});
@@ -149,11 +188,19 @@ function preflight(){
149
188
  const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
150
189
  const providerAll=permissions.includes('--protected-config')&&keys.every(key=>
151
190
  permissions.includes(`${key}:1`)&&permissions[permissions.indexOf(`${key}:1`)-1]==='--allow-provider-development');
152
- if(operation==='advance'&&permissions.includes('--verification-precheck'))
191
+ let live;
192
+ try{live=driverLiveEvidence(plan,{base,protectedRoots:[batch.codeProject,batch.specsDir,path.resolve(batch.codeProject,'..','.cm-worktrees'),...(batch.codeProjects??[])],
193
+ allowedKinds:['qa_logic','qa_browser','verification_precheck'],maxBytes:inputLimitFrom(permissions)});}
194
+ catch(error){stop(2,error.message);}
195
+ if(operation==='advance'&&permissions.includes('--verification-precheck')&&!live.has('verification_precheck'))
153
196
  stop(2,'缺少真实执行 runner: verification_precheck;不能从静态答案文件应答');
154
197
  if(operation==='advance'&&bundle.bootstraps&&Object.keys(bundle.bootstraps).length)
155
198
  stop(2,'缺少真实执行 runner: init_verify;不能从静态答案文件应答');
156
- const root=plan.answers?path.resolve(base,plan.answers):null,answers={};
199
+ const root=plan.answers?path.resolve(base,plan.answers):null,answers={},developAnswers=new Map(),holds=[];
200
+ const inputLimit=inputLimitFrom(permissions);
201
+ // Tasks that start from today's tree: the first task (and its parallel group) of
202
+ // a new batch. Later tasks start from trees earlier tasks have not written yet.
203
+ const firstGroup=batch.parallel?.find(group=>group.includes(keys[0]))??[keys[0]];
157
204
  if(operation==='advance')for(const task of batch.tasks){
158
205
  const key=taskKey(task),workflow=bundle.workflows[key],kinds=[];
159
206
  if(!providerAll)kinds.push('develop');
@@ -167,24 +214,71 @@ function preflight(){
167
214
  for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
168
215
  }
169
216
  if(workflow)kinds.push('documentation_inspect');
170
- const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind));
217
+ const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind)&&!live.has(kind));
171
218
  if(evidence.length)stop(2,`缺少真实执行 runner: ${evidence.join(', ')};不能从静态答案文件应答`);
172
- if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key);
219
+ if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key,plan,executionPolicy);
173
220
  const taskRoot=root&&path.join(root,task.feature,task.taskId);
174
- answers[key]=preflightAnswers(kinds.filter(kind=>KINDS[kind]),kind=>{
221
+ const perAttempt=new Map();
222
+ if(kinds.includes('develop')){
223
+ let attempts=[1],current=1,journal=null;
224
+ if(plan.mode==='resume'){
225
+ const runIds=[...runs].filter(([,binding])=>binding.key===key).sort((a,b)=>b[1].generation-a[1].generation);
226
+ const existing=runIds.find(([runId])=>fs.existsSync(path.join(batch.specsDir,'.reviews','.execution',runId,'state.json')));
227
+ if(existing)try{
228
+ const snapshot=readExecutionSnapshot({specsRoot:batch.specsDir,identity:{repositoryId:batch.repositoryId,runId:existing[0]}});
229
+ const history=readRunnerHistory(snapshot.records,snapshot.records[0].payload.config,3);
230
+ attempts=batchDevelopAttempts(history.state,key,permissions);current=history.state.attempt;
231
+ journal={baseline:snapshot.records[0].payload.baseline,generation:existing[1].generation,
232
+ frame:journalRestBytes(snapshot.records)};
233
+ }catch(error){stop(2,`任务 ${key} 无法只读检查恢复存档: ${error.code??error.message}`);}
234
+ }
235
+ // A task with no run yet (a new batch, or a later task on resume) starts at
236
+ // attempt 1; a first-round review grant can then reach attempt 2 as well.
237
+ if(journal===null&&permissions.some((flag,index)=>flag==='--allow-review'&&permissions[index+1]===`${key}:1`))attempts=[1,2];
238
+ const deliveries=[],definition=definitions.get(key);
239
+ for(const attempt of attempts){
240
+ const file=path.join(taskRoot??'',developFilename(taskRoot??'',attempt));
241
+ if(!taskRoot||!fs.existsSync(file)){
242
+ // A later attempt is only reached if the review this launch authorizes asks
243
+ // for changes. Without its answer the task stops right after that review.
244
+ if(attempt>current){
245
+ holds.push(key);
246
+ stderr(`任务 ${key} 没有 ${path.basename(file)}:本次授权的审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 ${attempt} 轮开发;读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings,写 ${file} 后再 advance`);
247
+ continue;
248
+ }
249
+ stop(2,attempt===1?`任务 ${key} 会反问 develop,但答案文件不存在: ${file}`
250
+ :`任务 ${key} 已在第 ${attempt} 轮等待修订,但答案文件不存在: ${file};读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings 后写入再 advance`);
251
+ }
252
+ const value=readJson(file,'develop');validateCmAiAnswer('develop',value,taskRoot);
253
+ if(value.status==='succeeded')for(const target of Object.keys(value.edits))
254
+ if(!definition.scope.includes(target))stop(2,`任务 ${key} ${path.basename(file)}.edits 越过批准 scope: ${target}`);
255
+ perAttempt.set(attempt,value);deliveries.push({file,value,attempt});
256
+ }
257
+ if(deliveries.length){
258
+ const known=journal!==null||plan.mode==='create'&&firstGroup.includes(key);
259
+ const cwd=journal?actualCwd(bundle,key,journal.generation):batch.codeProject;
260
+ const codeProject=fs.existsSync(cwd)?cwd:batch.codeProject;
261
+ preflightDevelopDeliveries({deliveries,answersRoot:taskRoot,codeProject,
262
+ scope:definition.scope,requirements:definition.requirements,diskChecks:known,
263
+ baseline:journal?baselineScope(journal.baseline,definition.scope):'disk',protectedMode,inputLimit,
264
+ checks:plannedCheckResults(protectedMode?null:plan.checks?.[key]),
265
+ preview:known?developPreview({definition,codeProject,journal,
266
+ parallelSelection:batch.parallel?.find(group=>group.includes(key))
267
+ ?{version:1,group:batch.parallel.find(group=>group.includes(key)).map(member=>definitions.get(member).identity.taskId)}:null}):null});
268
+ }
269
+ }
270
+ developAnswers.set(key,perAttempt);
271
+ answers[key]=preflightAnswers(kinds.filter(kind=>KINDS[kind]&&kind!=='develop'),kind=>{
175
272
  const file=path.join(taskRoot??'',KINDS[kind]);
176
273
  if(!taskRoot||!fs.existsSync(file))stop(2,`任务 ${key} 会反问 ${kind},但答案文件不存在: ${file}`);
177
274
  const value=readJson(file,kind);
178
275
  validateCmAiAnswer(kind,value,taskRoot);
179
276
  return value;
180
277
  });
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
278
  if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
185
279
  if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
186
280
  }
187
- return {...loaded,bundle,definitions,runs,config,permissions,answers,answerRoot:root};
281
+ return {...loaded,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
188
282
  }
189
283
 
190
284
  let loaded;
@@ -200,33 +294,40 @@ function safeWrite(map,root,cwd,allowed){
200
294
  fs.writeFileSync(file,fs.readFileSync(path.join(root,local)));
201
295
  }
202
296
  }
203
- async function answerFor(row){
297
+ async function answerFor(row,answers,paths,control){
298
+ if(loaded.live.has(row.kind))return loaded.live.answer(row,control);
204
299
  const identity=row.payload.identity??row.payload.request?.identity;
205
300
  const binding=loaded.runs.get(identity?.runId),key=binding?.key;
206
301
  if(!Object.hasOwn(loaded.answers,key))return null;
207
302
  const cwd=actualCwd(loaded.bundle,key,binding.generation);
208
303
  const task=loaded.bundle.batch.tasks.find(task=>taskKey(task)===key);
209
304
  const root=path.join(loaded.answerRoot,task.feature,task.taskId);
210
- const value=loaded.answers[key][row.kind];
305
+ const value=row.kind==='develop'?loaded.developAnswers.get(key)?.get(identity?.attempt):loaded.answers[key][row.kind];
211
306
  if(row.kind==='check'){
212
307
  if(row.payload.codeProject!==cwd)return null;
213
308
  const results=[];
309
+ const groups=[];
214
310
  for(const command of loaded.plan.checks[key]){
215
- const run=createHostCheck({cwd,commands:[command],onOutput:({stream,chunk})=>{
216
- process.stderr.write(`[drive check ${key} ${command.id} ${stream}] ${chunk.toString('utf8')}`);
217
- }});
218
- const [result]=await run({identity},{signal:new AbortController().signal});
219
- results.push(result);if(result.outcome!=='passed')break;
311
+ const timeoutMs=planCheckTimeout(loaded.plan,command);
312
+ if(groups.at(-1)?.timeoutMs!==timeoutMs)groups.push({timeoutMs,commands:[]});
313
+ const {timeoutMs:ignored,...item}=command;groups.at(-1).commands.push(item);
314
+ }
315
+ for(const group of groups){
316
+ let currentId=group.commands[0].id;
317
+ const run=createHostCheck({cwd,commands:group.commands,reuseDeclared:loaded.executionPolicy!==null,
318
+ timeoutMs:group.timeoutMs,onProgress:event=>{if(event.phase==='start')currentId=event.id;reportHostCheckProgress(event);},
319
+ onOutput:({stream,chunk})=>process.stderr.write(`[drive check ${key} ${currentId} ${stream}] ${chunk.toString('utf8')}`)});
320
+ const rows=await run({identity},control);results.push(...rows);if(rows.some(row=>row.outcome!=='passed'))break;
220
321
  }
221
322
  return results;
222
323
  }
223
324
  if(row.kind==='develop'){
325
+ if(!value)throw Error(`任务 ${key} develop attempt ${identity?.attempt} 未预检,拒绝复用旧答案`);
224
326
  if(row.payload.codeProject!==cwd)return null;
225
327
  if(value.status!=='succeeded')return {status:'failed',code:value.code};
226
328
  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);
329
+ edits:protectedDevelopEdits(value.edits,root,cwd,row.payload.expected)};
330
+ applyDevelopEdits(value.edits,root,cwd,row.payload.request.payload.scope);
230
331
  return {status:'succeeded',value:value.value};
231
332
  }
232
333
  if(row.kind==='documentation_sync'){
@@ -245,7 +346,7 @@ function main(){
245
346
  loaded=preflight();
246
347
  const {plan,operation,bundle,config,permissions}=loaded;
247
348
  driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
248
- '--allow-development',...permissions],cwd:bundle.batch.codeProject,operation,
349
+ '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,request:operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}:{},
249
350
  answers:loaded.answers,answerFor});
250
351
  }
251
352
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();
@@ -7,6 +7,8 @@ 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';
11
+ import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
10
12
 
11
13
  const DRIVER=fileURLToPath(new URL('./cm-ai-batch-drive.mjs',import.meta.url));
12
14
  const reviewer=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
@@ -18,7 +20,7 @@ const develop={status:'succeeded',value:{outcome:'implemented',
18
20
  function fixture(t,count=1){
19
21
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-batch-drive-')));
20
22
  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');
23
+ const specsDir=path.join(root,'specs5'),codeProject=path.join(root,'app'),bin=path.join(root,'bin');
22
24
  fs.mkdirSync(path.join(specsDir,'1.work'),{recursive:true});fs.mkdirSync(codeProject);fs.mkdirSync(bin);
23
25
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,'1.work',name),'# Fixture\n');
24
26
  fs.writeFileSync(path.join(specsDir,'1.work','tasks.md'),Array.from({length:count},(_,n)=>
@@ -44,9 +46,12 @@ function fixture(t,count=1){
44
46
  const write=(name,value)=>fs.writeFileSync(path.join(answers,name),JSON.stringify(value));
45
47
  const plan=(extra={})=>{
46
48
  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',
49
+ const value={config:'batch.json',mode:'create',hostContext:'batch-host-a',
48
50
  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}));
51
+ [`1.work/${task.taskId}`,[{id:'syntax',command:[process.execPath,'--check',task.taskId==='T-001'?'target.mjs':'target2.mjs']}]])),...extra};
52
+ // A new batch requires a bound review configuration (it grants no review).
53
+ if(!value.permissions.includes('--review-config'))value.permissions=[...value.permissions,'--review-config','review.json'];
54
+ fs.writeFileSync(file,JSON.stringify(value));
50
55
  return file;
51
56
  };
52
57
  const drive=(file,operation)=>spawnSync(process.execPath,[DRIVER,'--plan',file,operation],{encoding:'utf8',timeout:60000,
@@ -62,6 +67,36 @@ function prepared(f){
62
67
  f.write('documentation-inspect.json',{status:'completed',reason:'README and task artifacts inspected'});
63
68
  }
64
69
  function noStore(f){assert.equal(fs.existsSync(f.store),false);assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);}
70
+ test('batch reaches live logic and browser QA through the real member host',async t=>{
71
+ const f=fixture(t);prepared(f);
72
+ const cases=['logic','browser'].map((kind,index)=>({id:`TC-00${index+1}`,origin:'user',kind,blocking:true,
73
+ acIds:[],taskIds:['T-001'],title:'Fixture observation',preconditions:[],steps:['Observe fixture'],expected:['value is 42'],cleanup:[]}));
74
+ fs.writeFileSync(path.join(f.specsDir,'1.work/test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases}));
75
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
76
+ const plan=f.plan({permissions:['--allow-qa','--allow-review',`${key}:1`,'--browser-qa','available'],
77
+ liveEvidence:{directory:'exchange',kinds:['qa_logic','qa_browser'],timeoutMs:1000}});
78
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>row.kind==='qa_logic'
79
+ ?{verdict:'SUPPORTED',evidence:['Fixture target.mjs exports 42']}
80
+ :{verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'},
81
+ {timeoutMs:60000,env:{...process.env,PATH:path.join(f.root,'bin')+path.delimiter+process.env.PATH,
82
+ CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
83
+ assert.equal(out.status,0,out.stderr);assert.deepEqual(out.requests.map(r=>r.kind),['qa_logic','qa_browser']);
84
+ assert.equal(JSON.parse(out.stdout).result.code,'qa_result_blocked');
85
+ });
86
+ test('batch live verification request can reject a written requirement without review',async t=>{
87
+ const f=fixture(t);prepared(f);
88
+ fs.writeFileSync(path.join(f.specsDir,'1.work/tasks.md'),'- [ ] T-001: implement target\n - 验证: value is 43\n');
89
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
90
+ const plan=f.plan({permissions:['--allow-qa','--verification-precheck'],
91
+ liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
92
+ const out=await runLiveDriver(DRIVER,plan,'advance',row=>{
93
+ assert.equal(row.kind,'verification_precheck');
94
+ assert.match(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),/42/);
95
+ return {items:[{requirement:'value is 43',satisfied:false,evidence:'Fixture source exports 42'}]};
96
+ },{timeoutMs:60000,env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
97
+ assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
98
+ assert.match(out.stdout,/verification_precheck_failed/);
99
+ });
65
100
 
66
101
  test('help names plan invocation',()=>{
67
102
  const run=spawnSync(process.execPath,[DRIVER,'--help'],{encoding:'utf8'});
@@ -92,9 +127,84 @@ test('real batch host advances with authored edit and actual check, then resumes
92
127
  });
93
128
  test('real batch reaches completion with an independently dispatched fixture review',t=>{
94
129
  const f=fixture(t);prepared(f);
130
+ f.write('develop-a2.json',develop);
95
131
  const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
96
132
  const first=f.drive(f.plan({permissions}),'advance');
97
133
  assert.equal(first.status,0,first.stderr);assert.match(first.stderr,/应答 check/);
134
+ let result=JSON.parse(first.stdout).result,stderr=first.stderr;
135
+ for(let n=0;n<4&&result.state!=='run_done';n++){
136
+ const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
137
+ assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;stderr+=next.stderr;
138
+ }
139
+ assert.equal(result.state,'run_done',JSON.stringify(result));
140
+ assert.match(stderr,/开始检查.*value/,'quiet QA command start reaches the batch caller');
141
+ assert.match(stderr,/检查结束.*value.*passed/,'quiet QA command result reaches the batch caller');
142
+ });
143
+ // Deliberately replaced (#30). The batch driver has no separate decision step, so
144
+ // demanding develop-a2.json before any findings existed made a first review with
145
+ // a possible revision impossible. Without the answer it now stops after the review.
146
+ function changesRequested(f){
147
+ const cli=path.join(f.root,'bin','codex');
148
+ fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8').replace("verdict:'approved'","verdict:'changes_requested'")
149
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Fixture finding'}]"));
150
+ fs.chmodSync(cli,0o700);
151
+ }
152
+ const developIntents=f=>{
153
+ const state=path.join(f.store,fs.readdirSync(f.store).find(name=>name.startsWith('task-')),'state.json');
154
+ return JSON.parse(fs.readFileSync(state,'utf8')).records.filter(row=>row.payload.type==='effect-intent'
155
+ &&row.payload.effect.kind==='develop').map(row=>row.payload.effect.id);
156
+ };
157
+ test('batch review without a second-round answer stops at changes_requested after the first review',t=>{
158
+ const f=fixture(t);prepared(f);changesRequested(f);
159
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
160
+ const run=f.drive(f.plan({permissions}),'advance');
161
+ assert.equal(run.status,0,run.stderr);
162
+ assert.match(run.stderr,/没有 develop-a2\.json/);assert.match(run.stderr,/\.reviews\/work-T-001-r1\.md/);
163
+ const result=JSON.parse(run.stdout).result;
164
+ assert.equal(result.state,'changes_requested',run.stdout);assert.equal(result.code,'revision_answer_required');
165
+ assert.equal(result.identity.attempt,2);assert.equal(result.pendingAction,'resume');
166
+ assert(fs.existsSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md')));
167
+ assert.deepEqual(developIntents(f),['develop-1'],'no second-round develop intent before its answer exists');
168
+ // The findings exist now: the revision is written and the same batch continues.
169
+ fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 43;\n');
170
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
171
+ const revised=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',
172
+ permissions:['--allow-qa','--review-config','review.json']}),'advance');
173
+ assert.equal(revised.status,0,revised.stderr);assert.match(revised.stderr,/应答 develop/);
174
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 43;\n');
175
+ assert.equal(JSON.parse(revised.stdout).result.identity.attempt,2);
176
+ assert.deepEqual(developIntents(f),['develop-1','develop-2']);
177
+ });
178
+ test('batch resume holds a later task that has no run yet when its second-round answer is missing',t=>{
179
+ const f=fixture(t,2);prepared(f);
180
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
181
+ fs.writeFileSync(path.join(later,'target2.txt'),'export const value = 42;\n');
182
+ for(const name of ['qa-assess.json','documentation-inspect.json'])
183
+ fs.copyFileSync(path.join(f.answers,name),path.join(later,name));
184
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:{'target2.mjs':'target2.txt'}}));
185
+ // T-001 stops at awaiting_review first, so T-002 has no run when the batch resumes.
186
+ const first=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json']}),'advance');
187
+ assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'awaiting_review');
188
+ // The reviewer approves T-001 and asks for changes on T-002.
189
+ const cli=path.join(f.root,'bin','codex');
190
+ fs.writeFileSync(cli,fs.readFileSync(reviewer,'utf8').replace("verdict:'approved'",
191
+ "verdict:prompt.includes('target2.mjs')?'changes_requested':'approved'")
192
+ .replace('findings:[]',"findings:prompt.includes('target2.mjs')?[{id:'F1',severity:'P2',path:'target2.mjs',message:'Revise',evidence:'Fixture finding'}]:[]"));
193
+ fs.chmodSync(cli,0o700);
194
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`,'--allow-review','1.work/T-002:1'];
195
+ let result;
196
+ for(let n=0;n<4;n++){
197
+ const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
198
+ assert.equal(next.status,0,next.stderr);result=JSON.parse(next.stdout).result;
199
+ if(result.code==='revision_answer_required')break;
200
+ }
201
+ assert.equal(result.state,'changes_requested',JSON.stringify(result));assert.equal(result.code,'revision_answer_required');
202
+ assert.equal(result.identity.taskId,'T-002');
203
+ });
204
+ test('batch hold without a second-round answer does not interfere with an approving review',t=>{
205
+ const f=fixture(t);prepared(f);
206
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
207
+ const first=f.drive(f.plan({permissions}),'advance');assert.equal(first.status,0,first.stderr);
98
208
  let result=JSON.parse(first.stdout).result;
99
209
  for(let n=0;n<4&&result.state!=='run_done';n++){
100
210
  const next=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions}),'advance');
@@ -102,6 +212,92 @@ test('real batch reaches completion with an independently dispatched fixture rev
102
212
  }
103
213
  assert.equal(result.state,'run_done',JSON.stringify(result));
104
214
  });
215
+ test('batch driver refuses an oversized answer of a later task before launching the first',t=>{
216
+ const f=fixture(t,2);prepared(f);
217
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
218
+ fs.writeFileSync(path.join(later,'big.txt'),Buffer.alloc(1200*1024,0x61));
219
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:{'target2.mjs':'big.txt'}}));
220
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
221
+ assert.match(run.stderr,/target2\.mjs/);assert.match(run.stderr,/1048576/);noStore(f);
222
+ });
223
+ // Codex review of 910b84c: a later task's starting tree is unknown, but its answer
224
+ // files alone can already prove a limit is exceeded; those checks still apply.
225
+ function laterTask(f,scope,files){
226
+ const config=path.join(f.root,'batch.json'),bundle=JSON.parse(fs.readFileSync(config,'utf8'));
227
+ bundle.batch.tasks[1].scope=scope;fs.writeFileSync(config,JSON.stringify(bundle));
228
+ const later=path.join(f.root,'answers','1.work','T-002');fs.mkdirSync(later,{recursive:true});
229
+ for(const name of ['qa-assess.json','documentation-inspect.json'])
230
+ fs.copyFileSync(path.join(f.answers,name),path.join(later,name));
231
+ for(const [name,size] of Object.entries(files))fs.writeFileSync(path.join(later,name.replaceAll('/','_')+'.txt'),Buffer.alloc(size,0x61));
232
+ fs.writeFileSync(path.join(later,'develop.json'),JSON.stringify({...develop,edits:Object.fromEntries(Object.keys(files).map(name=>[name,name.replaceAll('/','_')+'.txt']))}));
233
+ }
234
+ test('batch driver refuses a later task whose new files alone exceed the 2 MiB material limit',t=>{
235
+ const f=fixture(t,2);prepared(f);
236
+ const scope=['gen/a.bin','gen/b.bin','gen/c.bin'];laterTask(f,scope,Object.fromEntries(scope.map(file=>[file,700*1024])));
237
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
238
+ assert.match(run.stderr,/2097152/);assert.match(run.stderr,/gen\/[abc]\.bin/);noStore(f);
239
+ });
240
+ test('batch driver lets a later task\'s second-round delete bring its delivered files back under 2 MiB',t=>{
241
+ const f=fixture(t,2);prepared(f);
242
+ laterTask(f,['gen/a.bin','gen/b.bin','gen/c.bin'],{'gen/a.bin':1000*1024,'gen/b.bin':1000*1024});
243
+ const later=path.join(f.root,'answers','1.work','T-002');
244
+ fs.writeFileSync(path.join(later,'gen_c.bin.txt'),Buffer.alloc(100*1024,0x61));
245
+ fs.writeFileSync(path.join(later,'develop-a2.json'),JSON.stringify({...develop,edits:{'gen/b.bin':{delete:true},'gen/c.bin':'gen_c.bin.txt'}}));
246
+ const run=f.drive(f.plan({permissions:['--allow-qa','--review-config','review.json','--allow-review','1.work/T-002:1']}),'advance');
247
+ assert.equal(run.status,0,run.stderr);assert.doesNotMatch(run.stderr,/仅答案写入/);assert.equal(fs.existsSync(f.store),true);
248
+ });
249
+ test('batch driver refuses a no-op or non-UTF-8 protected develop answer before launch',t=>{
250
+ const f=fixture(t);prepared(f);
251
+ f.write('develop.json',{...develop,edits:{}});
252
+ const empty=f.drive(f.plan(),'advance');assert.equal(empty.status,2,empty.stderr);
253
+ assert.match(empty.stderr,/没有任何改动/);noStore(f);
254
+ fs.writeFileSync(path.join(f.root,'protection.json'),JSON.stringify({checkCommands:[{id:'noop',command:['/usr/bin/true']}],timeoutMs:60000}));
255
+ fs.writeFileSync(path.join(f.answers,'target.txt'),Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0xff]));
256
+ f.write('develop.json',develop);
257
+ const binary=f.drive(f.plan({permissions:['--allow-qa','--protected-conversation-config','protection.json'],checks:undefined}),'advance');
258
+ assert.equal(binary.status,2,binary.stderr);assert.match(binary.stderr,/UTF-8/);assert.match(binary.stderr,/target\.mjs/);noStore(f);
259
+ });
260
+ test('batch review revision applies the second-round develop content',t=>{
261
+ const f=fixture(t);prepared(f);
262
+ const cli=path.join(f.root,'bin','codex');
263
+ fs.writeFileSync(cli,fs.readFileSync(cli,'utf8').replace("verdict:'approved'","verdict:'changes_requested'")
264
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Fixture finding'}]"));
265
+ fs.writeFileSync(path.join(f.answers,'target-a2.txt'),'export const value = 43;\n');
266
+ f.write('develop-a2.json',{...develop,edits:{'target.mjs':'target-a2.txt'}});
267
+ const permissions=['--allow-qa','--review-config','review.json','--allow-review',`${key}:1`];
268
+ const run=f.drive(f.plan({permissions}),'advance');assert.equal(run.status,0,run.stderr);
269
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 43;\n');
270
+ });
271
+ test('batch first-round answer aliases cannot coexist',t=>{
272
+ const f=fixture(t);prepared(f);f.write('develop-a1.json',develop);
273
+ const run=f.drive(f.plan(),'advance');assert.equal(run.status,2,run.stderr);
274
+ assert.match(run.stderr,/develop\.json.*develop-a1\.json/);noStore(f);
275
+ });
276
+ test('batch retryable blocked state projects the same develop attempt',()=>{
277
+ for(const code of ['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed'])
278
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code,attempt:2},key,[]),[2]);
279
+ assert.deepEqual(batchDevelopAttempts({state:'blocked',code:'checks_not_passed',attempt:2},key,[]),[]);
280
+ });
281
+
282
+ test('D1 batch rejects invalid check timeout before opening a host',t=>{
283
+ const f=fixture(t);prepared(f);
284
+ const checks={[key]:[{id:'syntax',command:[process.execPath,'--check','target.mjs'],timeoutMs:0}]};
285
+ const run=f.drive(f.plan({checks}),'advance');
286
+ assert.equal(run.status,2);assert.match(run.stderr,/timeoutMs/);noStore(f);
287
+ });
288
+
289
+ test('D1 batch retries failed checks before review in the same attempt',t=>{
290
+ const f=fixture(t);prepared(f);
291
+ const failed={[key]:[{id:'test',command:[process.execPath,'-e','process.exit(1)']}]};
292
+ const first=f.drive(f.plan({permissions:['--allow-qa','--runtime','claude'],checks:failed}),'advance');assert.equal(first.status,0,first.stderr);
293
+ const result=JSON.parse(first.stdout).result;
294
+ assert.equal(result.code,'develop_checks_not_passed');assert.equal(result.pendingAction,'resume');
295
+ assert.equal(result.guidance.recoveryOperation,'advance');assert.equal(result.guidance.authorizationGranted,false);
296
+ assert.match(first.stderr,/原批次入口/);assert.doesNotMatch(result.guidance.prerequisites.join(' '),/--mode/);
297
+ const clean={[key]:[{id:'test',command:[process.execPath,'-e','0']}]};
298
+ const second=f.drive(f.plan({mode:'resume',originalHostContext:'batch-host-a',permissions:['--allow-qa','--runtime','claude'],checks:clean}),'advance');
299
+ assert.equal(second.status,0,second.stderr);assert.match(second.stderr,/应答 develop/);
300
+ });
105
301
  test('missing answer leaves no batch store or session',t=>{
106
302
  const f=fixture(t);const run=f.drive(f.plan(),'advance');
107
303
  assert.equal(run.status,2);assert.match(run.stderr,/develop\.json/);noStore(f);
@@ -157,3 +353,13 @@ test('resume binding is required before launch',t=>{
157
353
  const run=f.drive(f.plan({mode:'resume'}),'advance');assert.equal(run.status,2);
158
354
  assert.match(run.stderr,/originalHostContext/);noStore(f);
159
355
  });
356
+
357
+ test('optimized real batch driver shares only a declared same-plan check and rejects legacy aliases before launch',t=>{
358
+ const f=fixture(t);prepared(f);const counter=path.join(f.root,'physical-check-count');
359
+ const command=[process.execPath,'-e',`require('node:fs').appendFileSync(${JSON.stringify(counter)},'x')`];
360
+ const checks={[key]:[{id:'first',command},{id:'same',command,sameExecutionAs:'first'}]};
361
+ const denied=f.drive(f.plan({checks}), 'advance');assert.equal(denied.status,2);noStore(f);assert(!fs.existsSync(counter));
362
+ const out=f.drive(f.plan({permissions:['--allow-qa','--execution-optimizations'],checks}), 'advance');
363
+ assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'awaiting_review',out.stdout+out.stderr);
364
+ assert.equal(fs.readFileSync(counter,'utf8'),'x');
365
+ });