@aibyzero/cm-workflow 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +23 -0
  3. package/CHANGELOG.md +224 -0
  4. package/README.md +14 -3
  5. package/THIRD_PARTY_NOTICES.md +13 -0
  6. package/VERSION +1 -1
  7. package/compat/claude-commands/cm-challenge.md +3 -0
  8. package/docs/architecture.md +11 -0
  9. package/docs/cm-control-policy-v2.md +127 -9
  10. package/docs/installation.md +310 -4
  11. package/docs/js-workflow-control.md +150 -15
  12. package/docs/live-evidence-drivers.md +28 -4
  13. package/docs/out-of-scope/README.md +25 -0
  14. package/docs/out-of-scope/background-supervisor.md +32 -0
  15. package/docs/reviewed-integration.md +48 -0
  16. package/docs/user-guide.md +50 -21
  17. package/install-codex.sh +331 -18
  18. package/install.ps1 +28 -2
  19. package/install.sh +321 -17
  20. package/package.json +2 -1
  21. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  22. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  23. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  24. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  25. package/runtime/js/cm-ai/claude-review-stream.mjs +83 -14
  26. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  27. package/runtime/js/cm-ai/cm-ai-admission.mjs +18 -12
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  30. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  31. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  32. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  33. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  34. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  35. package/runtime/js/cm-ai/control-policy.mjs +21 -4
  36. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  37. package/runtime/js/cm-ai/drive-core.mjs +114 -11
  38. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  39. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  40. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  41. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  42. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  43. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  44. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  45. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  46. package/runtime/js/cm-ai/host-check.mjs +11 -5
  47. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  48. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  49. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  50. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  51. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  54. package/runtime/js/cm-ai/host.mjs +1 -1
  55. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  56. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  58. package/runtime/js/cm-ai/operator-guidance.mjs +9 -2
  59. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  60. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  61. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  62. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  63. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  64. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  65. package/runtime/js/cm-ai/review-package.mjs +79 -7
  66. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  68. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  69. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  70. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  71. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  72. package/runtime/js/cm-ai/task-runner.mjs +242 -39
  73. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  74. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  75. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  76. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  77. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  78. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  79. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  80. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  81. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  82. package/runtime/js/cm-fix/dossier.mjs +8 -2
  83. package/runtime/js/cm-fix/execution.mjs +578 -100
  84. package/runtime/js/cm-fix/final-review.mjs +39 -8
  85. package/runtime/js/cm-fix/finish.mjs +15 -11
  86. package/runtime/js/cm-fix/host-review.mjs +65 -10
  87. package/runtime/js/cm-fix/host.mjs +35 -12
  88. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  89. package/runtime/js/cm-fix/metrics.mjs +18 -5
  90. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  91. package/runtime/js/cm-fix/regression.mjs +16 -7
  92. package/runtime/js/cm-fix/repair.mjs +29 -8
  93. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  94. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  95. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  96. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  97. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  98. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  99. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  100. package/runtime/js/cm-fix/start.mjs +6 -3
  101. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  102. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  103. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  104. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  105. package/runtime/js/cm-prd/analysis.mjs +13 -9
  106. package/runtime/js/cm-prd/change.mjs +37 -16
  107. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  108. package/runtime/js/cm-prd/draft.mjs +31 -3
  109. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  110. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  111. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  112. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  113. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  114. package/runtime/js/cm-prd/self-check.mjs +125 -6
  115. package/runtime/js/cm-prd/session.mjs +30 -1
  116. package/runtime/js/cm-prd/summary.mjs +11 -5
  117. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  118. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  119. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  120. package/runtime/js/cm-security/scan.mjs +1 -1
  121. package/runtime/js/commander/decision.mjs +44 -0
  122. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  123. package/runtime/js/commander/ledger.mjs +265 -0
  124. package/runtime/js/commander/preflight.mjs +107 -0
  125. package/runtime/js/notify-later.mjs +13 -0
  126. package/runtime/js/notify-send.mjs +6 -2
  127. package/runtime/js/notify.mjs +570 -63
  128. package/runtime/js/review-findings.mjs +38 -0
  129. package/runtime/js/session-boundary.mjs +56 -0
  130. package/runtime/js/session-handoff.mjs +68 -0
  131. package/runtime/js/spec-task-line.mjs +27 -13
  132. package/runtime/js/specs-status.mjs +1 -1
  133. package/runtime/js/task-scope.mjs +197 -0
  134. package/runtime/logging.md +6 -1
  135. package/runtime/model-efficiency.md +69 -10
  136. package/runtime/orchestration.md +3 -1
  137. package/runtime/project-learning.md +2 -0
  138. package/runtime/review.md +3 -2
  139. package/runtime/test-contract.md +1 -0
  140. package/scripts/ci-test-weights.json +3 -0
  141. package/scripts/cm-ai-admission.mjs +11 -5
  142. package/scripts/cm-ai-admission.test.mjs +23 -2
  143. package/scripts/cm-ai-batch-drive.mjs +79 -18
  144. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  145. package/scripts/cm-ai-batch-host.mjs +38 -9
  146. package/scripts/cm-ai-batch-host.test.mjs +6 -5
  147. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  148. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  149. package/scripts/cm-ai-batch-plan.mjs +52 -0
  150. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  151. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  152. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  153. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  154. package/scripts/cm-ai-batch-run.mjs +471 -57
  155. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  156. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  157. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  158. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  159. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  160. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  161. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  162. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  163. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  164. package/scripts/cm-ai-control-policy.test.mjs +14 -0
  165. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  166. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  167. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  168. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  169. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  170. package/scripts/cm-ai-drive.mjs +73 -17
  171. package/scripts/cm-ai-drive.test.mjs +34 -2
  172. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  173. package/scripts/cm-ai-host.mjs +60 -19
  174. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  175. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  176. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  177. package/scripts/cm-ai-integration-preview.mjs +41 -0
  178. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  179. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  180. package/scripts/cm-ai-operator-guidance.test.mjs +16 -1
  181. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  182. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  183. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  184. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  185. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  186. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  187. package/scripts/cm-ai-run.mjs +88 -21
  188. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  189. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  190. package/scripts/cm-ai-supersede.test.mjs +28 -0
  191. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  192. package/scripts/cm-announce-hook.mjs +35 -8
  193. package/scripts/cm-announce-hook.test.mjs +25 -0
  194. package/scripts/cm-challenge.test.mjs +61 -0
  195. package/scripts/cm-check-drive-files.mjs +1 -1
  196. package/scripts/cm-check-runtime.sh +58 -1
  197. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  198. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  199. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  200. package/scripts/cm-claude-review-stream.test.mjs +13 -0
  201. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  202. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  203. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  204. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  205. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  206. package/scripts/cm-commander-ledger.test.mjs +260 -0
  207. package/scripts/cm-commander-p2.test.mjs +295 -0
  208. package/scripts/cm-commander-preflight.mjs +84 -0
  209. package/scripts/cm-commander.mjs +116 -0
  210. package/scripts/cm-config-lock.mjs +35 -0
  211. package/scripts/cm-controlled-correction.test.mjs +10 -1
  212. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  213. package/scripts/cm-display-task-id.test.mjs +41 -0
  214. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  215. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  216. package/scripts/cm-external-batch-host.test.mjs +4 -3
  217. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  218. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  219. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  220. package/scripts/cm-failover.mjs +48 -10
  221. package/scripts/cm-failover.test.mjs +46 -0
  222. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  223. package/scripts/cm-fix-command-correction.mjs +17 -0
  224. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  225. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  226. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  227. package/scripts/cm-fix-drive.mjs +33 -5
  228. package/scripts/cm-fix-drive.test.mjs +49 -0
  229. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  230. package/scripts/cm-fix-host-review.test.mjs +21 -9
  231. package/scripts/cm-fix-host.mjs +26 -8
  232. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  233. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  234. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  235. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  236. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  237. package/scripts/cm-fix-review-preflight.mjs +24 -0
  238. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  239. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  240. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  241. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  242. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  243. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  244. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  245. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  246. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  247. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  248. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  249. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  250. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  251. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  252. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  253. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  254. package/scripts/cm-host-replay.test.mjs +176 -0
  255. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  256. package/scripts/cm-install-manifest.sh +351 -0
  257. package/scripts/cm-live-evidence.test.mjs +59 -1
  258. package/scripts/cm-log-event.mjs +61 -10
  259. package/scripts/cm-log-event.test.mjs +121 -1
  260. package/scripts/cm-matt-skills.mjs +576 -0
  261. package/scripts/cm-matt-skills.test.mjs +550 -0
  262. package/scripts/cm-notify-command.test.mjs +42 -10
  263. package/scripts/cm-notify.mjs +14 -10
  264. package/scripts/cm-notify.test.mjs +575 -59
  265. package/scripts/cm-patrol.mjs +4 -1
  266. package/scripts/cm-patrol.test.mjs +23 -5
  267. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  268. package/scripts/cm-prd-completion.test.mjs +56 -13
  269. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  270. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  271. package/scripts/cm-prd-draft.test.mjs +1 -1
  272. package/scripts/cm-prd-drive.mjs +13 -6
  273. package/scripts/cm-prd-drive.test.mjs +45 -1
  274. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  275. package/scripts/cm-prd-host.mjs +10 -5
  276. package/scripts/cm-prd-host.test.mjs +4 -2
  277. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  278. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  279. package/scripts/cm-prd-revision.test.mjs +1 -1
  280. package/scripts/cm-prd-self-check-revision.test.mjs +1 -1
  281. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  282. package/scripts/cm-prd-self-check.test.mjs +105 -5
  283. package/scripts/cm-prd-summary.test.mjs +24 -3
  284. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  285. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  286. package/scripts/cm-refactor-drive.mjs +2 -1
  287. package/scripts/cm-refactor-drive.test.mjs +9 -0
  288. package/scripts/cm-release-smoke.sh +1 -1
  289. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  290. package/scripts/cm-skill-hints-exam.mjs +149 -0
  291. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  292. package/scripts/cm-skill-hints.exam.json +706 -0
  293. package/scripts/cm-skill-hints.json +119 -0
  294. package/scripts/cm-skill-hints.mjs +669 -0
  295. package/scripts/cm-skill-hints.test.mjs +831 -0
  296. package/scripts/cm-skill-judge.mjs +181 -0
  297. package/scripts/cm-skill-judge.test.mjs +255 -0
  298. package/scripts/cm-specs-status.test.mjs +4 -2
  299. package/scripts/cm-start-check.mjs +208 -0
  300. package/scripts/cm-start-check.test.mjs +321 -0
  301. package/scripts/cm-task-gate.mjs +150 -29
  302. package/scripts/cm-task-gate.test.mjs +73 -1
  303. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  304. package/scripts/cm-task-scope.test.mjs +308 -0
  305. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  306. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  307. package/scripts/cm-workflow-config.mjs +12 -2
  308. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  309. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  310. package/scripts/scan-public-safety.py +1 -0
  311. package/scripts/session-boundary.test.mjs +170 -0
  312. package/scripts/test-npm-install.py +14 -3
  313. package/scripts/test-shell-compat.sh +2 -0
  314. package/scripts/validate-public-repo.py +1 -0
  315. package/scripts/validate-test-cases.mjs +3 -2
  316. package/skills/cm-ai/SKILL.md +5 -2
  317. package/skills/cm-ai/references/N4-review.md +2 -1
  318. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  319. package/skills/cm-ai/references/N8-finish.md +22 -0
  320. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  321. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  322. package/skills/cm-ai/references/js-host.md +56 -16
  323. package/skills/cm-challenge/SKILL.md +65 -0
  324. package/skills/cm-challenge/evals/README.md +18 -0
  325. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  326. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  327. package/skills/cm-challenge/references/examples.md +15 -0
  328. package/skills/cm-check/SKILL.md +5 -0
  329. package/skills/cm-check/references/js-host.md +2 -0
  330. package/skills/cm-fix/SKILL.md +12 -3
  331. package/skills/cm-fix/references/command-correction.md +67 -0
  332. package/skills/cm-fix/references/isolated-review.md +54 -0
  333. package/skills/cm-fix/references/js-host.md +62 -2
  334. package/skills/cm-fix/references/test-type-correction.md +72 -0
  335. package/skills/cm-fix/references/verification-recovery.md +114 -0
  336. package/skills/cm-idea/SKILL.md +2 -0
  337. package/skills/cm-idea/references/js-host.md +2 -0
  338. package/skills/cm-notify/SKILL.md +2 -0
  339. package/skills/cm-prd/SKILL.md +12 -8
  340. package/skills/cm-prd/references/brownfield.md +8 -1
  341. package/skills/cm-prd/references/change-mode.md +6 -0
  342. package/skills/cm-prd/references/greenfield.md +4 -0
  343. package/skills/cm-prd/references/js-host.md +4 -2
  344. package/skills/cm-prd/references/spec-self-check.md +5 -1
  345. package/skills/cm-refactor/SKILL.md +8 -0
  346. package/skills/cm-refactor/references/js-host.md +2 -0
  347. package/skills/cm-test/SKILL.md +4 -0
  348. package/templates/dashboard/dashboard.html +2 -2
  349. package/templates/pixel/cm-pixel.html +1 -1
  350. package/templates/pixel/cm-pixel.sh +1 -1
  351. package/templates/pixel/dev/template.html +1 -1
  352. package/templates/statusline/cm-statusline.sh +1 -1
@@ -5,6 +5,7 @@
5
5
  // The tests were split across files so they run in separate processes; batchFixture
6
6
  // patches Date.now and fs.existsSync for some modes, so tests of one file stay serial.
7
7
  import {buildManifest} from './cm-spec-manifest.mjs';
8
+ import {batchSegment} from '../runtime/js/cm-ai/batch-location.mjs';
8
9
  import assert from 'node:assert/strict';
9
10
  import fs from 'node:fs';
10
11
  import os from 'node:os';
@@ -20,34 +21,70 @@ import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
20
21
  import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
21
22
 
22
23
  export async function batchFixture(mode,options={}){
23
- const parallel=mode.startsWith('parallel');
24
+ // worktree-each: a chain T-001 -> T-002 -> T-003 that cannot pair; each task before
25
+ // the last still runs alone in its own worktree (one-member groups).
26
+ // worktree-each-qa: the same chain with T-001's file registered as an authentication
27
+ // path, so its own QA is triggered and must run in its worktree before the merge.
28
+ const each=mode.startsWith('worktree-each'),parallel=mode.startsWith('parallel')||each;
24
29
  const recovery=mode==='parallel-recovery',blockedIds=options.blockedIds??['T-002'];
25
30
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-batch-')));
26
31
  try{
27
32
  const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.work';
28
33
  fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
29
34
  for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
30
- fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n'+(parallel?'- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n':''));
31
- fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
35
+ // Each task declares the same file the batch config gives it (file<index>.js).
36
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n - 范围: `file0.js`\n- [ ] T-002: second\n - 范围: `file1.js`\n'
37
+ +(parallel?'- [ ] T-003: final\n - 范围: `file2.js`\n\n'+(each?'- T-002 依赖 T-001\n- T-003 依赖 T-002\n':'- T-003 依赖 T-001, T-002\n'):''));
38
+ // next-feature: a second approved feature waits after this batch's one.
39
+ if(mode==='next-feature'){
40
+ fs.mkdirSync(path.join(specsDir,'2.next'));
41
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,'2.next',name),'# Next\n');
42
+ fs.writeFileSync(path.join(specsDir,'2.next','tasks.md'),'- [ ] T-001: next feature\n - 范围: `next.js`\n');
43
+ }
44
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',
45
+ features:[feature,...(mode==='next-feature'?['2.next']:[])],specFiles:buildManifest(specsDir)}));
32
46
  fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
33
47
  const git=(cwd,args)=>{const result=spawnSync('git',['-C',cwd,...args],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);return result.stdout.trim();};
34
48
  {git(codeProject,['init','-b','main']);git(codeProject,['config','user.name','Fixture']);git(codeProject,['config','user.email','fixture@example.invalid']);
35
- fs.writeFileSync(path.join(codeProject,parallel?'base.js':'file0.js'),'base\n');git(codeProject,['add','-A']);git(codeProject,['commit','-m','fixture baseline']);}
49
+ fs.writeFileSync(path.join(codeProject,parallel?'base.js':'file0.js'),'base\n');
50
+ // configDivergence (review r4): the main checkout's file equals its HEAD blob, yet a
51
+ // worktree checked out from HEAD loads another configuration.
52
+ if(options.configDivergence==='smudge'){
53
+ // A checkout filter rewrites the policy in every new checkout; clean maps it back.
54
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.yml'),'version: 1\npolicies:\n tests: [commands]\n');
55
+ fs.writeFileSync(path.join(codeProject,'.gitattributes'),'.cm-workflow.yml filter=swap\n');
56
+ git(codeProject,['config','filter.swap.smudge','sed s/commands/logic/']);git(codeProject,['config','filter.swap.clean','sed s/logic/commands/']);
57
+ }
58
+ if(options.configDivergence==='two-files')for(const name of ['.cm-workflow.yml','.cm-workflow.yaml'])
59
+ fs.writeFileSync(path.join(codeProject,name),'version: 1\n');
60
+ git(codeProject,['add','-A']);git(codeProject,['commit','-m','fixture baseline']);
61
+ // detachedMain (map ticket 04): the main checkout sits on a detached HEAD, as a
62
+ // session that checked out a commit leaves it; the batch must still run.
63
+ if(options.detachedMain)git(codeProject,['checkout','-q','--detach']);
64
+ if(options.configDivergence==='two-files'){
65
+ // HEAD has both files; the main checkout hides one, so it sees a single config.
66
+ git(codeProject,['update-index','--skip-worktree','.cm-workflow.yaml']);fs.unlinkSync(path.join(codeProject,'.cm-workflow.yaml'));
67
+ }
68
+ if(options.configDivergence)assert.equal(git(codeProject,['status','--porcelain']),'');}
36
69
  const config={version:1,repositoryId:'batch-fixture',batchId:'batch-fixture',specsDir,codeProject,
37
70
  ...(options.executionPolicy?{executionPolicy:EXECUTION_POLICY_V1}:{}),
38
- ...(parallel?{parallel:[[`${feature}/T-001`,`${feature}/T-002`]]}:{}),
71
+ ...(parallel?{parallel:each?[[`${feature}/T-001`],[`${feature}/T-002`]]:[[`${feature}/T-001`,`${feature}/T-002`]]}:{}),
39
72
  tasks:(parallel?['T-001','T-002','T-003']:['T-001','T-002']).map((taskId,index)=>({feature,taskId,scope:[`file${index}.js`],requirements:['requirements.md']}))};
40
73
  const calls=[],qaCalls=[],assessments=[],blockedEvidence=[],checkCalls=new Map();let qaReady=mode!=='qa-resume',started;
41
74
  const began=new Promise(resolve=>{started=resolve;});
42
- let conflictHead=null,interrupted=false,reviewFailed=false,redoThrown=false;
75
+ let conflictHead=null,interrupted=false,reviewFailed=0,redoThrown=false,reviewHeld=null;const rateLimitedSeen={};const eachSeen=[];let activeBatchId=config.batchId;
43
76
  const developerModel=mode==='parallel-redo'?'current-session':'fixture';
44
- const executionFor=async(definition,{parallelMember=false}={})=>({configuration:{kind:'batch-fixture-v1',...(parallelMember?{parallelMember:true}:{})},timeoutMs:3000,
77
+ const qaSeen=[];
78
+ // openGate: holds executionFor (the member run's opening) until released, so a
79
+ // cancel can arrive between the retry's checks and its dispatch.
80
+ let openGate=null;
81
+ const executionFor=async(definition,{parallelMember=false,soloMember=false}={})=>(openGate&&await openGate.hold(),{configuration:{kind:'batch-fixture-v1',...(parallelMember?{parallelMember:true}:{}),...(soloMember?{soloMember:true}:{})},timeoutMs:3000,
45
82
  excludedContexts:['host'],applicableAgentFiles:[],
46
83
  developer:{provider:'codex',requestedModel:developerModel,contextId:'author',run:createCodexDeveloperRun({requestedModel:developerModel,
47
84
  worker:async({prompt},{signal})=>{
48
85
  const data=JSON.parse(prompt.split('<cm-developer-data-json>\n')[1]),material=data.specification;
49
86
  assert.equal(material.task.id,definition.identity.taskId);
50
- assert.deepEqual(material.sources,buildManifest(specsDir));
87
+ assert.deepEqual(material.sources,buildManifest(specsDir).filter(source=>source.path.startsWith(`${feature}/`)));
51
88
  if(recovery&&!parallelMember&&blockedIds.includes(definition.identity.taskId)){
52
89
  const key=`${feature}/${definition.identity.taskId}`;
53
90
  assert.equal(definition.codeProject,codeProject);
@@ -67,12 +104,27 @@ export async function batchFixture(mode,options={}){
67
104
  assert.equal(fs.readFileSync(path.join(codeProject,config.tasks.find(task=>task.taskId===id).scope[0]),'utf8'),'implemented\n');
68
105
  }
69
106
  }
107
+ // slowFirst: T-001 starts only after T-002 is ready, so completion order is the reverse of task order.
108
+ if(options.slowFirst&&parallelMember&&definition.identity.taskId==='T-001'){
109
+ const logfile=path.join(specsDir,'运行日志.jsonl');
110
+ for(let wait=0;wait<400&&!(fs.existsSync(logfile)&&fs.readFileSync(logfile,'utf8').includes('"phase":"batch_member_ready"'));wait++)
111
+ await new Promise(resolve=>setTimeout(resolve,50));
112
+ }
113
+ if(each){
114
+ const id=definition.identity.taskId,worktree=path.join(root,'.cm-worktrees',batchSegment(activeBatchId),id);
115
+ assert.equal(definition.codeProject,id==='T-003'?codeProject:worktree,`${id} code root`);
116
+ assert.equal(parallelMember,id!=='T-003');
117
+ // Each worktree starts from the main checkout after the earlier members merged.
118
+ if(id==='T-002')assert.equal(fs.readFileSync(path.join(worktree,'file0.js'),'utf8'),'implemented\n');
119
+ if(id==='T-003')for(const file of ['file0.js','file1.js'])assert.equal(fs.readFileSync(path.join(codeProject,file),'utf8'),'implemented\n');
120
+ eachSeen.push(id);
121
+ }
70
122
  // A second attempt must change the rejected bytes (develop_unchanged_after_review).
71
123
  calls.push(definition.identity.taskId);fs.writeFileSync(path.join(definition.codeProject,definition.scope[0]),
72
124
  data.identity.attempt===1?'implemented\n':'implemented again\n');
73
125
  // The session wrote, then the conversation dropped: no answer (develop_answer_missing).
74
126
  if(mode==='parallel-redo'&&parallelMember&&definition.identity.taskId==='T-002'&&!redoThrown){
75
- redoThrown=true;throw Object.assign(new Error('host_disconnected'),{code:'host_disconnected'});}
127
+ redoThrown=true;const code=options.redoCode??'host_disconnected';throw Object.assign(new Error(code),{code});}
76
128
  if(recovery&&blockedIds.includes(definition.identity.taskId)&&(parallelMember||options.terminalAgain))
77
129
  return {status:'succeeded',value:{outcome:'blocked',...(options.withReason?{reason:'Expected stub throws; waiting for peer'}:{})}};
78
130
  if(parallel&&definition.identity.taskId==='T-002')await new Promise(resolve=>setTimeout(resolve,50));
@@ -101,16 +153,25 @@ export async function batchFixture(mode,options={}){
101
153
  evidence:failed?'Synthetic transient failure':'Synthetic task check'}];
102
154
  },
103
155
  reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
104
- contexts:['review-1','review-2'],run:(request,{onEvent})=>{
156
+ contexts:['review-1','review-2'],run:async(request,{onEvent,signal})=>{
157
+ // cancelAt review: the bound retry's review waits until the batch cancel reaches it.
158
+ if(options.cancelAt==='review'&&mode.endsWith('bound-review-provider-retry')&&reviewFailed>=1&&request.identity.taskId==='T-001'){
159
+ onEvent({event:'thread.started',provider_thread:'review-held'});reviewHeld?.();
160
+ await new Promise(resolve=>signal.aborted?resolve():signal.addEventListener('abort',resolve,{once:true}));
161
+ onEvent({event:'process_closed',exit_code:null,signal:'SIGTERM',timed_out:false});
162
+ return {status:'cancelled',code:'cancelled'};
163
+ }
105
164
  assert.equal(request.payload.reviewPackage.specification.task.id,definition.identity.taskId);
106
- assert.deepEqual(request.payload.reviewPackage.specification.sources,buildManifest(specsDir));
165
+ assert.deepEqual(request.payload.reviewPackage.specification.sources,buildManifest(specsDir).filter(source=>source.path.startsWith(`${feature}/`)));
107
166
  if(mode==='learning'&&request.identity.taskId==='T-001')
108
167
  assert(request.payload.reviewPackage.changes.some(change=>change.path==='AGENTS.md'));
109
168
  // The reviewer started, then its process vanished without any terminal event: unknown.
110
169
  if(mode==='parallel-unknown'&&request.identity.taskId==='T-002'){
111
170
  onEvent({event:'thread.started',provider_thread:'review-lost'});throw Error('Synthetic lost reviewer');}
112
- if(mode.endsWith('review-provider-retry')&&request.identity.taskId==='T-001'&&!reviewFailed){
113
- reviewFailed=true;
171
+ if(mode.endsWith('review-provider-retry')&&(options.rateLimitedTasks??['T-001']).includes(request.identity.taskId)
172
+ &&(rateLimitedSeen[request.identity.taskId]??0)<(options.reviewFailures??1)){
173
+ rateLimitedSeen[request.identity.taskId]=(rateLimitedSeen[request.identity.taskId]??0)+1;
174
+ if(request.identity.taskId==='T-001')reviewFailed++;
114
175
  // Claude CLI rate limit: no tool call, no verdict, process exited.
115
176
  for(const event of [{event:'thread.started',provider_thread:'review-rate-limited'},{event:'turn.started',item_type:null},
116
177
  {event:'process_closed',exit_code:1,signal:null,timed_out:false}])onEvent(event);
@@ -124,7 +185,11 @@ export async function batchFixture(mode,options={}){
124
185
  examinedPaths:reviewPaths(request.payload.reviewPackage),findings:retry?[{id:'F1',severity:'P2',path:'file0.js',message:'Synthetic repair',evidence:'First implementation'}]:[],summary:'Synthetic independent review'}};
125
186
  }}],
126
187
  reviewInvocation:{developerThreadId:'author',excludedThreadIds:['host']},
127
- qaDecisionProvider:parallelMember?createParallelMemberQaDecisionProvider():mode==='policy'?createHostQaDecisionProvider({timeoutMs:1000,criticalPaths:{api:['file0.js']},assess:async binding=>{
188
+ // Only a member developed alongside others defers its QA (host-conversation-execution.mjs).
189
+ qaDecisionProvider:parallelMember&&!soloMember?createParallelMemberQaDecisionProvider()
190
+ :each?createHostQaDecisionProvider({timeoutMs:1000,criticalPaths:mode==='worktree-each-qa'?{authentication:['file0.js']}:{},
191
+ assess:async binding=>{assessments.push(binding.identity.taskId);return {confirmed:true};}})
192
+ :mode==='policy'?createHostQaDecisionProvider({timeoutMs:1000,criticalPaths:{api:['file0.js']},assess:async binding=>{
128
193
  assessments.push(binding.identity.taskId);
129
194
  return {confirmed:true};
130
195
  }}):{timeoutMs:1000,decide:async binding=>{
@@ -142,6 +207,12 @@ export async function batchFixture(mode,options={}){
142
207
  return {...executor,run:(binding,signal)=>{qaCalls.push(binding.identity.taskId);return executor.run(binding,signal);}};
143
208
  })():{mode:'commands',caseCount:1,timeoutMs:1000,run:async binding=>{
144
209
  qaCalls.push(binding.identity.taskId);
210
+ // Where the QA ran and whether the member was merged yet.
211
+ if(each)qaSeen.push({task:binding.identity.taskId,codeProject:binding.codeProject,merged:fs.existsSync(path.join(codeProject,'file0.js'))});
212
+ if(mode==='worktree-each-qa'&&options.qaFail&&binding.identity.taskId==='T-001'){
213
+ const report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);fs.writeFileSync(report,'# Synthetic QA failure\n');
214
+ return {result:'FAIL',passed:0,failed:1,blocked:0,report};
215
+ }
145
216
  const report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);fs.writeFileSync(report,'# Synthetic QA\n');
146
217
  const fail=mode==='failed-qa';return {result:fail?'FAIL':'PASS',passed:fail?0:1,failed:fail?1:0,blocked:0,report};
147
218
  }},
@@ -149,12 +220,100 @@ export async function batchFixture(mode,options={}){
149
220
  packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,status:'completed',reason:'Synthetic docs',at:'2026-09-08T01:00:00Z'})},
150
221
  });
151
222
  const open=(extra={})=>createCmAiBatch({configuration:config,executionFor,logHome:path.join(root,'logs'),...extra});
223
+ // retry_review (a driver's timed rate-limit retry) redispatches exactly the frozen
224
+ // review: a different invocation, batch log or member is refused as staleRetry
225
+ // with nothing dispatched or written; the exact one dispatches that review only.
226
+ const reviewCount=()=>{
227
+ const dir=path.join(specsDir,'.reviews','.execution');let count=0;
228
+ for(const name of fs.existsSync(dir)?fs.readdirSync(dir):[]){const file=path.join(dir,name,'state.json');
229
+ if(fs.existsSync(file))count+=JSON.parse(fs.readFileSync(file,'utf8')).records.filter(row=>row.payload.type==='effect-intent').length;}
230
+ return count;
231
+ };
232
+ const batchTaskRunIdFor=taskId=>`task-${digest({batchId:config.batchId,task:`${feature}/${taskId}`}).slice(0,48)}`;
233
+ const reviewIntents=runId=>JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','.execution',runId,'state.json'),'utf8')).records
234
+ .filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='review').map(row=>row.payload.effect.id);
235
+ const logText=()=>{const file=path.join(specsDir,'运行日志.jsonl');return fs.existsSync(file)?fs.readFileSync(file,'utf8'):'';};
236
+ const tasksText=()=>fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8');
237
+ async function boundReviewRetry(stop){
238
+ // Both group members hit the rate limit; the batch names the first one it stopped on.
239
+ const both=(options.rateLimitedTasks??[]).includes('T-002');
240
+ if(both){assert.equal(rateLimitedSeen['T-002'],1,'T-002 was rate limited too');assert.equal(stop.reviewRetryTarget.taskKey,`${feature}/T-001`);}
241
+ const bound=(over={})=>open().handle({operation:'retry_review',requestId:`bound-${Math.random().toString(36).slice(2)}`,
242
+ taskKey:stop.reviewRetryTarget.taskKey,identity:stop.identity,packageDigest:stop.packageDigest,
243
+ expectedReviewStop:{invocationId:stop.reviewInvocationId},batchDigest:stop.reviewRetryTarget.batchDigest,...over});
244
+ const unchanged=async(over,why)=>{
245
+ const before={log:logText(),tasks:tasksText(),effects:reviewCount(),reviews:reviewFailed};
246
+ const refused=await bound(over);
247
+ assert.equal(refused.staleRetry,true,`${why}: ${JSON.stringify(refused)}`);assert.equal(refused.outcome,'rejected',why);
248
+ assert.match(refused.reason,/^状态已变,未自动重试/,why);
249
+ assert.deepEqual({log:logText(),tasks:tasksText(),effects:reviewCount(),reviews:reviewFailed},before,`${why}: nothing dispatched or written`);
250
+ };
251
+ await unchanged({expectedReviewStop:{invocationId:'another-invocation'}},'another member invocation');
252
+ await unchanged({batchDigest:'0'.repeat(64)},'another batch log');
253
+ await unchanged({taskKey:`${feature}/T-003`},'a member the batch is not stopped on');
254
+ await unchanged({identity:{...stop.identity,attempt:2}},'another round');
255
+ if(options.staleByAdvance){
256
+ // Another driver moves the batch on meanwhile: the old timer's target is stale.
257
+ const moved=await open().handle({operation:'advance',requestId:'other-driver'});
258
+ assert.notEqual(moved.state,'pending_review',JSON.stringify(moved));
259
+ await unchanged({},'the batch moved on');
260
+ return moved;
261
+ }
262
+ if(options.cancelAt){
263
+ // A cancel on the same host while the retry opens the member run, or while its
264
+ // review runs: no review is dispatched (or it is cancelled), batch_cancel is
265
+ // logged and the retry returns cancelled.
266
+ const effects=reviewCount(),batch=open();let reached;const atOpen=new Promise(resolve=>{reached=resolve;});
267
+ let release;
268
+ if(options.cancelAt==='open')openGate={hold:()=>{reached();return new Promise(resolve=>{release=resolve;});}};
269
+ else reviewHeld=reached;
270
+ const pending=batch.handle({operation:'retry_review',requestId:'bound-cancel',taskKey:stop.reviewRetryTarget.taskKey,identity:stop.identity,
271
+ packageDigest:stop.packageDigest,expectedReviewStop:{invocationId:stop.reviewInvocationId},batchDigest:stop.reviewRetryTarget.batchDigest});
272
+ await atOpen;
273
+ const cancel=await batch.handle({operation:'cancel',requestId:'cancel-during-retry'});
274
+ assert.equal(cancel.outcome,'cancelled',JSON.stringify(cancel));
275
+ if(release){openGate=null;release();}
276
+ const ended=await pending;
277
+ assert.equal(ended.outcome,'cancelled',JSON.stringify(ended));
278
+ if(options.cancelAt==='open')assert.equal(reviewCount(),effects,'no review dispatched after the cancel');
279
+ else assert.equal(reviewCount(),effects+1,'the running review was the one cancelled');
280
+ assert.equal(reviewFailed,options.cancelAt==='open'?1:1);
281
+ const rows=logText().split('\n').filter(Boolean).map(JSON.parse);
282
+ assert.equal(rows.filter(row=>row.phase==='batch_cancel').length,1,'batch_cancel logged once');
283
+ assert.equal((await open().handle({operation:'advance',requestId:'after-cancel'})).code,'cancelled');
284
+ return null;
285
+ }
286
+ const effects=reviewCount(),log=logText(),tasks=tasksText();
287
+ const retried=await bound();
288
+ assert.equal(retried.taskKey,`${feature}/T-001`);assert.equal(reviewCount(),effects+1,'exactly one review effect');
289
+ // Only that review: no completion, merge or handoff, no tasks.md change.
290
+ assert.equal(logText(),log);assert.equal(tasksText(),tasks);
291
+ if((options.reviewFailures??1)>1){
292
+ // The round's second rate limit: the runner's blocked stop, never retried again.
293
+ assert.equal(retried.state,'blocked',JSON.stringify(retried));assert.equal(retried.code,'review_provider_failed');
294
+ assert.equal(retried.pendingAction,'abandon_review');assert.equal(retried.reviewRetryTarget,undefined);
295
+ await unchanged({},'the same target after the second failure');
296
+ return null;
297
+ }
298
+ assert.equal(retried.state,'approved',JSON.stringify(retried));assert.equal(retried.outcome,'advanced');
299
+ // The member's own state stays; the next step is the batch's advance, with guidance.
300
+ assert.equal(retried.code,null);assert.equal(retried.identity.taskId,'T-001');assert.equal(retried.pendingAction,'advance');
301
+ assert.match(retried.guidance.summary,/审查限流已自动重试/);assert.match(retried.guidance.nextStep,/从批次入口发送 advance/);
302
+ assert.deepEqual(Object.keys(retried.guidance).sort(),['authorizationGranted','nextStep','prerequisites','recoveryOperation','summary']);
303
+ const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
304
+ assert.equal(classifyDriveResult('cm-ai-batch',{result:retried}),null,'not a stop that needs a person');
305
+ await unchanged({},'the same target after it was redispatched');
306
+ if(both)assert.equal(rateLimitedSeen['T-002'],1,'retry_review did not touch the other member');
307
+ const next=await open().handle({operation:'advance',requestId:'after-bound-retry'});
308
+ // The next advance redispatched T-002's review as usual (its one automatic redispatch).
309
+ if(both){const runId=batchTaskRunIdFor('T-002');assert(reviewIntents(runId).includes('review-1-retry-1'),JSON.stringify(reviewIntents(runId)));}
310
+ return next;
311
+ }
152
312
  if(mode==='parallel-existing'){
153
- // T-002's scope file is committed on HEAD, so it is an edit, not a new file.
154
- fs.writeFileSync(path.join(codeProject,'file1.js'),'existing\n');git(codeProject,['add','file1.js']);git(codeProject,['commit','-m','existing file']);
155
- await assert.rejects(open().handle({operation:'advance',requestId:'existing'}),error=>error.code==='parallel_scope_existing_file');
156
- assert.deepEqual(calls,[]);assert(!fs.existsSync(path.join(root,'.cm-worktrees')));
157
- assert.equal(git(codeProject,['status','--porcelain']),'');return;
313
+ // Both members' scope files are committed on HEAD, so each member edits an
314
+ // existing file. The batch must run, merge both edits and finish as usual.
315
+ for(const file of ['file0.js','file1.js'])fs.writeFileSync(path.join(codeProject,file),'existing\n');
316
+ git(codeProject,['add','file0.js','file1.js']);git(codeProject,['commit','-m','existing files']);
158
317
  }
159
318
  if(mode==='parallel-dirty'){
160
319
  fs.writeFileSync(path.join(codeProject,'dirty.txt'),'user-owned\n');
@@ -182,6 +341,22 @@ export async function batchFixture(mode,options={}){
182
341
  }
183
342
  }return originalExists.call(fs,file,...args);
184
343
  };
344
+ // parallel-old-merge: stop once both members are ready and before any merge starts.
345
+ if(mode==='parallel-old-merge')fs.existsSync=function(file,...args){
346
+ if(!interrupted&&String(file).endsWith('state.json')){
347
+ const logfile=path.join(specsDir,'运行日志.jsonl');
348
+ const rows=originalExists(logfile)?originalRead(logfile,'utf8').split('\n').filter(Boolean).map(JSON.parse):[];
349
+ if(rows.filter(row=>row.phase==='batch_member_ready').length===2&&!rows.some(row=>row.phase==='batch_merge_started')){
350
+ interrupted=true;throw Object.assign(new Error('simulated interrupt'),{code:'simulated_interrupt'});
351
+ }
352
+ }return originalExists.call(fs,file,...args);
353
+ };
354
+ if(each){
355
+ // The planner proposes exactly these one-member groups for this chain.
356
+ const {planCmAiBatch}=await import('../runtime/js/cm-ai/batch-plan.mjs');
357
+ const planned=planCmAiBatch({specsDir,codeProject,repositoryId:config.repositoryId,batchId:config.batchId});
358
+ assert.deepEqual(planned.config.batch.parallel,config.parallel);
359
+ }
185
360
  const batch=open(),pending=batch.handle({operation:'advance',requestId:'advance-1'});
186
361
  if(mode==='cancel'){
187
362
  await began;await batch.handle({operation:'cancel',requestId:'cancel'});
@@ -190,7 +365,112 @@ export async function batchFixture(mode,options={}){
190
365
  assert.deepEqual(calls,['T-001']);return;
191
366
  }
192
367
  let result;
193
- try{result=await pending;}catch(error){if(!(mode==='parallel-resume'||mode==='final-commit'||recovery&&options.crashAt)||error.code!=='simulated_interrupt')throw error;}finally{fs.existsSync=originalExists;}
368
+ try{result=await pending;}catch(error){if(!(mode==='parallel-resume'||mode==='parallel-old-merge'||mode==='final-commit'||recovery&&options.crashAt)||error.code!=='simulated_interrupt')throw error;}finally{fs.existsSync=originalExists;}
369
+ if(options.configDivergence){
370
+ // Compared where it counts: after the worktree is created and before any develop
371
+ // dispatch, both checkouts' effective configurations as loaded. A difference (or a
372
+ // member that cannot load one) stops the batch. Review r6: the batch never deletes
373
+ // the worktree or its branch (hidden index flags can hide work from `git status`);
374
+ // the guidance gives the manual, non-forced cleanup commands.
375
+ const segment=batchSegment(config.batchId),worktree=path.join(root,'.cm-worktrees',segment,'T-001');
376
+ const branch=`cm/${segment}/work/T-001`,runDir=path.join(specsDir,'.reviews','.execution',`task-${digest({batchId:config.batchId,task:`${feature}/T-001`}).slice(0,48)}`);
377
+ const unsetFilter=()=>{git(codeProject,['config','--unset','filter.swap.smudge']);git(codeProject,['config','--unset','filter.swap.clean']);};
378
+ const stopped=(value,kept=[])=>{
379
+ assert.equal(value.code,'batch_member_config_diverged',JSON.stringify(value));
380
+ assert.equal(value.currentTask,`${feature}/T-001`);
381
+ assert.match(value.reason,options.configDivergence==='two-files'?/multiple CM workflow configs/:/有效配置不同/);
382
+ assert.doesNotMatch(value.reason,/已移除/);
383
+ for(const text of [value.guidance.nextStep,value.reason]){
384
+ assert(text.includes(`git -C ${codeProject} worktree remove ${worktree}`),text);assert(text.includes(`git -C ${codeProject} branch -d ${branch}`),text);
385
+ assert.doesNotMatch(text,/remove --force|branch -D/);assert.match(text,/worktree_all: false/);
386
+ }
387
+ // Nothing deleted, nothing developed.
388
+ assert(fs.existsSync(worktree));assert.equal(git(codeProject,['for-each-ref','--format=%(refname:short)','refs/heads/cm']),branch);
389
+ assert.deepEqual(calls,[]);assert(!fs.existsSync(runDir));
390
+ for(const [file,content] of kept)assert.equal(fs.readFileSync(path.join(worktree,file),'utf8'),content,file);
391
+ };
392
+ for(const requestId of ['diverged-1','diverged-2']){stopped(result);result=await open().handle({operation:'advance',requestId});}
393
+ stopped(result);
394
+ if(options.cleanup==='user-edits'){
395
+ // Operator work in the kept worktree survives further advances.
396
+ fs.writeFileSync(path.join(worktree,'notes.txt'),'operator work\n');fs.writeFileSync(path.join(worktree,'base.js'),'edited\n');
397
+ for(const requestId of ['user-edits-1','user-edits-2'])
398
+ stopped(await open().handle({operation:'advance',requestId}),[['notes.txt','operator work\n'],['base.js','edited\n']]);
399
+ return;
400
+ }
401
+ if(options.cleanup==='hidden'){
402
+ // Review r6: a change hidden by assume-unchanged does not show in `git status`; it is
403
+ // kept all the same, since nothing is deleted.
404
+ git(worktree,['update-index','--assume-unchanged','base.js']);fs.writeFileSync(path.join(worktree,'base.js'),'hidden edit\n');
405
+ assert.equal(git(worktree,['status','--porcelain','--untracked-files=all']),'');
406
+ for(const requestId of ['hidden-1','hidden-2'])stopped(await open().handle({operation:'advance',requestId}),[['base.js','hidden edit\n']]);
407
+ return;
408
+ }
409
+ if(options.cleanup==='interrupted'){
410
+ // The operator's cleanup stopped between its two commands: a branch is left with
411
+ // nothing beyond the main checkout's HEAD. It is deleted with `branch -d` and the
412
+ // worktree rebuilt, so the same batch goes on once the configuration agrees.
413
+ git(codeProject,['worktree','remove',worktree]);unsetFilter();
414
+ result=await open().handle({operation:'advance',requestId:'after-interrupted-cleanup'});
415
+ assert.equal(result.code,'run_done',JSON.stringify(result));assert.deepEqual(calls,['T-001','T-002','T-003']);
416
+ return;
417
+ }
418
+ if(options.cleanup==='unique-commit'){
419
+ // A leftover branch with its own commit is somebody's work: never deleted.
420
+ fs.writeFileSync(path.join(worktree,'kept.txt'),'kept\n');git(worktree,['add','kept.txt']);git(worktree,['commit','-qm','kept work']);
421
+ git(codeProject,['worktree','remove',worktree]);
422
+ const tip=git(codeProject,['rev-parse',branch]);unsetFilter();
423
+ for(const requestId of ['unique-1','unique-2']){
424
+ result=await open().handle({operation:'advance',requestId});
425
+ assert.equal(result.code,'batch_member_branch_exists',JSON.stringify(result));assert.match(result.reason,new RegExp(branch));
426
+ assert.equal(git(codeProject,['rev-parse',branch]),tip);assert(!fs.existsSync(worktree));assert.deepEqual(calls,[]);
427
+ }
428
+ return;
429
+ }
430
+ if(options.configDivergence==='smudge'){
431
+ // The exit as the guidance gives it: clean up by hand (no --force, no -D), make
432
+ // both checkouts load the same configuration, then advance the same batch.
433
+ git(codeProject,['worktree','remove',worktree]);git(codeProject,['branch','-d',branch]);unsetFilter();
434
+ result=await open().handle({operation:'advance',requestId:'after-config-fix'});
435
+ assert.equal(result.code,'run_done',JSON.stringify(result));assert.deepEqual(calls,['T-001','T-002','T-003']);
436
+ }
437
+ return;
438
+ }
439
+ if(mode==='worktree-each-qa'&&options.qaFail){
440
+ // The safety net: the member's own QA failed in its worktree. It is not merged; the
441
+ // batch stops with the reviewed delivery committed on the member branch and names
442
+ // the exit, which this test then follows through to the end of the feature.
443
+ const segment=batchSegment(config.batchId),worktree=path.join(root,'.cm-worktrees',segment,'T-001'),branch=`cm/${segment}/work/T-001`;
444
+ const rows=()=>fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
445
+ for(const requestId of ['qa-failed-1','qa-failed-2','qa-failed-3']){
446
+ assert.equal(result.code,'batch_solo_qa_failed',JSON.stringify(result));
447
+ assert.equal(result.currentTask,`${feature}/T-001`);assert.equal(result.guidance.authorizationGranted,false);
448
+ assert.match(result.guidance.nextStep,new RegExp(`git merge --no-ff ${branch}.*cm-fix.*cm-ai-batch-plan\\.mjs`));
449
+ assert.deepEqual(calls,['T-001']);assert.deepEqual(qaCalls,['T-001']);
450
+ assert.deepEqual(qaSeen,[{task:'T-001',codeProject:worktree,merged:false}]);
451
+ assert.equal(rows().filter(row=>['batch_member_ready','batch_merge_started','batch_handoff'].includes(row.phase)).length,0);
452
+ assert.equal(rows().filter(row=>row.phase==='batch_member_qa_failed').length,1);
453
+ assert(!fs.existsSync(path.join(codeProject,'file0.js')));
454
+ assert.equal(git(codeProject,['show',`${branch}:file0.js`]),'implemented');
455
+ assert.equal(git(codeProject,['show','-s','--format=%s',branch]),'T-001: first');
456
+ result=await open().handle({operation:requestId==='qa-failed-2'?'status':'advance',requestId});
457
+ }
458
+ // Follow the exit: merge the branch, (fix with /cm-fix: outside this fixture), remove
459
+ // the worktree and branch, and continue the remaining tasks as a new batch.
460
+ git(codeProject,['merge','--no-ff','--no-edit',branch]);
461
+ git(codeProject,['worktree','remove',worktree]);git(codeProject,['branch','-d',branch]);
462
+ const {planCmAiBatch}=await import('../runtime/js/cm-ai/batch-plan.mjs');
463
+ activeBatchId='batch-fixture-next';
464
+ const next=planCmAiBatch({specsDir,codeProject,repositoryId:config.repositoryId,batchId:activeBatchId});
465
+ assert.deepEqual(next.config.batch.tasks.map(task=>task.taskId),['T-002','T-003']);
466
+ const after=await createCmAiBatch({configuration:next.config.batch,executionFor,logHome:path.join(root,'logs')})
467
+ .handle({operation:'advance',requestId:'next-batch'});
468
+ assert.equal(after.code,'run_done',JSON.stringify(after));
469
+ assert.deepEqual(calls,['T-001','T-002','T-003']);assert.deepEqual(qaCalls,['T-001','T-003']);
470
+ for(const file of ['file0.js','file1.js','file2.js'])assert.equal(fs.readFileSync(path.join(codeProject,file),'utf8'),'implemented\n',file);
471
+ assert.equal(git(codeProject,['status','--porcelain']),'');
472
+ return;
473
+ }
194
474
  if(mode==='final-commit'){
195
475
  assert(interrupted);
196
476
  const logfile=path.join(specsDir,'运行日志.jsonl');
@@ -220,7 +500,7 @@ export async function batchFixture(mode,options={}){
220
500
  }
221
501
  // Kept in its original run: no second generation, no WIP removal, no redispatch.
222
502
  assert.equal(rows().filter(row=>row.phase==='batch_member_blocked').length,0);
223
- assert(fs.existsSync(path.join(root,'.cm-worktrees',config.batchId.slice(0,8),'T-002')));
503
+ assert(fs.existsSync(path.join(root,'.cm-worktrees',batchSegment(config.batchId),'T-002')));
224
504
  assert(!fs.existsSync(path.join(specsDir,'.reviews','.execution',`task-${digest({batchId:config.batchId,task:`${feature}/T-002`,generation:2}).slice(0,48)}`)));
225
505
  assert(fs.existsSync(statePath));
226
506
  const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
@@ -233,7 +513,7 @@ export async function batchFixture(mode,options={}){
233
513
  // Probe the exits the hint names (or withholds) through the real entry checks.
234
514
  const {prepareReviewedEvidenceSupersession}=await import('../runtime/js/cm-ai/reviewed-evidence-supersede.mjs');
235
515
  const {acquireExternalRunGuard,externalRunGuardExists}=await import('../runtime/js/cm-ai/external-run-guard.mjs');
236
- const worktree=path.join(root,'.cm-worktrees',config.batchId.slice(0,8),'T-002');
516
+ const worktree=path.join(root,'.cm-worktrees',batchSegment(config.batchId),'T-002');
237
517
  const identity={repositoryId:config.repositoryId,runId:'task-supersede-probe',taskId:'T-002',attempt:1};
238
518
  prepareReviewedEvidenceSupersession({specsDir,codeProject:worktree,feature,identity,reason:'probe',
239
519
  tasksPath:path.join(specsDir,feature,'tasks.md'),acceptSupersededCodeDrift:true});
@@ -247,10 +527,18 @@ export async function batchFixture(mode,options={}){
247
527
  const logfile=path.join(specsDir,'运行日志.jsonl'),rows=()=>fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
248
528
  assert.equal(result.code,'batch_parallel_member_recovery_required',JSON.stringify(result));
249
529
  assert.deepEqual([result.currentTask,result.pendingAction,result.memberCode],[`${feature}/T-002`,'develop_redo','develop_answer_missing']);
530
+ // The member's bounded develop class survives the batch's rebuilt stop, and the notice names it.
531
+ if(options.redoCode==='developer_rate_limited'){
532
+ assert.equal(result.developFailure,'developer_rate_limited',JSON.stringify(result));
533
+ const {driveNotice,buildNotifyMessage}=await import('../runtime/js/notify.mjs');
534
+ const notice=driveNotice({host:'/x/scripts/cm-ai-batch-host.mjs',cwd:codeProject,args:['--host-context','s1'],operation:'advance',row:{requestId:'drive',result}});
535
+ assert.equal(notice.delivery,'now');
536
+ assert.match(buildNotifyMessage(notice,{now:Date.now(),layout:'compact'}).body,/开发进程被限流(429):过一刻钟后回到会话「s1」,授权它重做这一轮开发/);
537
+ }else assert.equal(Object.hasOwn(result,'developFailure'),false);
250
538
  assert.match(result.reason,/--allow-develop-redo 1\.work\/T-002/);assert.equal(result.guidance.authorizationGranted,false);
251
539
  // Kept in place: no serial reschedule, its worktree and edits stay for the redo.
252
540
  assert.equal(rows().filter(row=>row.phase==='batch_member_blocked').length,0);
253
- const worktree=path.join(root,'.cm-worktrees',config.batchId.slice(0,8),'T-002');
541
+ const worktree=path.join(root,'.cm-worktrees',batchSegment(config.batchId),'T-002');
254
542
  assert.equal(fs.readFileSync(path.join(worktree,'file1.js'),'utf8'),'implemented\n');
255
543
  const redo={operation:'develop_redo',requestId:'redo',taskKey:`${feature}/T-002`,reason:'会话已停止修改代码'};
256
544
  const refused=await open().handle(redo);
@@ -280,7 +568,7 @@ export async function batchFixture(mode,options={}){
280
568
  const logfile=path.join(specsDir,'运行日志.jsonl');
281
569
  let rows=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
282
570
  assert.equal(rows.filter(row=>row.phase==='batch_member_blocked').length,0);
283
- assert(fs.existsSync(path.join(root,'.cm-worktrees',config.batchId.slice(0,8),'T-002')));
571
+ assert(fs.existsSync(path.join(root,'.cm-worktrees',batchSegment(config.batchId),'T-002')));
284
572
  result=await open().handle({operation:'advance',requestId:'retry-completion'});
285
573
  assert.equal(result.code,'run_done',JSON.stringify(result));
286
574
  rows=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
@@ -347,32 +635,109 @@ export async function batchFixture(mode,options={}){
347
635
  }
348
636
  return;
349
637
  }
638
+ if(mode==='parallel-old-merge'){
639
+ // An earlier version merged in completion order: it logged T-002's merge intent,
640
+ // Git committed the merge, and the process died before the handoff. The new
641
+ // version must finish that merge before merging T-001 in task order.
642
+ assert(interrupted);
643
+ const logfile=path.join(specsDir,'运行日志.jsonl'),rows=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse);
644
+ const ready=rows.find(row=>row.phase==='batch_member_ready'&&row.from_key===`${feature}/T-002`);
645
+ git(ready.worktree,['add','-A']);if(git(ready.worktree,['status','--porcelain']))git(ready.worktree,['commit','-qm','T-002: second']);
646
+ const intent={from_key:ready.from_key,expected_old:git(codeProject,['rev-parse','HEAD']),member_commit:git(ready.worktree,['rev-parse','HEAD'])};
647
+ const writer=new URL('./cm-log-event.py',import.meta.url).pathname;
648
+ const logged=spawnSync('python3',[writer,'--workflow','cm-ai','--event','decision','--phase','batch_merge_started','--runtime',ready.runtime,
649
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',config.batchId,'--detail','batch_merge_started',
650
+ '--data-json',JSON.stringify({repository_id:config.repositoryId,plan_digest:ready.plan_digest,...intent})],
651
+ {encoding:'utf8',env:{...process.env,CM_WORKFLOW_LOG_HOME:path.join(root,'logs')}});
652
+ assert.equal(logged.status,0,logged.stderr);
653
+ git(codeProject,['merge','-q','--no-ff','--no-edit',intent.member_commit]);
654
+ result=await open().handle({operation:'advance',requestId:'resume-old-merge'});
655
+ const order=fs.readFileSync(logfile,'utf8').trim().split('\n').map(JSON.parse).filter(row=>row.phase==='batch_handoff').map(row=>row.from_key);
656
+ assert.deepEqual(order.slice(0,2),[`${feature}/T-002`,`${feature}/T-001`],JSON.stringify(result));
657
+ assert.equal(result.code,'run_done',JSON.stringify(result));
658
+ assert.equal(fs.readFileSync(path.join(codeProject,'file0.js'),'utf8'),'implemented\n');
659
+ assert.equal(fs.readFileSync(path.join(codeProject,'file1.js'),'utf8'),'implemented\n');
660
+ return;
661
+ }
350
662
  if(mode==='parallel-resume'){assert(interrupted);const before=[...calls];result=await open().handle({operation:'advance',requestId:'resume-parallel'});assert.deepEqual(calls.slice(0,before.length),before);}
351
663
  if(mode==='parallel-conflict'){
352
664
  assert.equal(result.code,'merge_conflict',JSON.stringify(result));assert.equal(git(codeProject,['rev-parse','HEAD']),conflictHead);
353
- for(const task of ['T-001','T-002'])assert(fs.existsSync(path.join(root,'.cm-worktrees',config.batchId.slice(0,8),task)));
665
+ for(const task of ['T-001','T-002'])assert(fs.existsSync(path.join(root,'.cm-worktrees',batchSegment(config.batchId),task)));
354
666
  // Kept member branches are namespaced per batch, so a later batch of the same
355
667
  // tasks does not collide with the WIP branches this one leaves behind.
356
- const segment=config.batchId.slice(0,8).replace(/\./g,'-');
668
+ const segment=batchSegment(config.batchId);
357
669
  const heads=git(codeProject,['for-each-ref','--format=%(refname:short)','refs/heads/cm']).split('\n').filter(Boolean);
358
670
  assert.deepEqual(heads.sort(),[`cm/${segment}/work/T-001`,`cm/${segment}/work/T-002`]);
671
+ // T-002's reviewed delivery is committed on its branch when the stop is given.
672
+ const t2=`cm/${segment}/work/T-002`,t2tree=path.join(root,'.cm-worktrees',segment,'T-002');
673
+ assert.equal(git(codeProject,['show',`${t2}:file1.js`]),'implemented');
674
+ // A stop an older version logged left it uncommitted: the replay commits it.
675
+ git(t2tree,['reset','-q','--soft','HEAD~1']);assert.throws(()=>git(codeProject,['show',`${t2}:file1.js`]));
676
+ // status stays read-only: it reports the stop and commits nothing.
677
+ const read=await open().handle({operation:'status',requestId:'status-after-conflict'});
678
+ assert.equal(read.code,'merge_conflict');assert.deepEqual(read.files,result.files);assert.match(read.guidance.nextStep,/T-002/);
679
+ // ...but names the member not proven committed, and asks for advance before any merge.
680
+ assert.deepEqual(read.unsealed,['T-001','T-002'].map(id=>({taskKey:`${feature}/${id}`,code:'batch_seal_unverified'})));
681
+ assert.match(read.guidance.prerequisites[0],/尚未确认提交到分支.*1\.work\/T-002.*advance 一次/);
682
+ assert.throws(()=>git(codeProject,['show',`${t2}:file1.js`]));
683
+ // A member that cannot be checked is named, and the conflict is still returned.
684
+ fs.renameSync(t2tree,t2tree+'.away');
685
+ assert.deepEqual((await open().handle({operation:'status',requestId:'status-missing'})).unsealed.map(item=>item.code),['batch_seal_unverified','batch_seal_unverified']);
686
+ const unchecked=await open().handle({operation:'advance',requestId:'unsealed-after-conflict'});
687
+ fs.renameSync(t2tree+'.away',t2tree);
688
+ assert.equal(unchecked.code,'merge_conflict');assert.deepEqual(unchecked.files,result.files);
689
+ assert.deepEqual(unchecked.unsealed.map(item=>item.taskKey),[`${feature}/T-002`]);
690
+ assert.match(unchecked.guidance.prerequisites[0],/尚未确认提交到分支.*1\.work\/T-002(batch_member_action_unavailable)/);
691
+ // The stop names the conflicted member's branch and worktree and the way on, then and on every later advance.
692
+ for(const stop of [result,await open().handle({operation:'advance',requestId:'after-conflict'})]){
693
+ assert.equal(stop.code,'merge_conflict');assert.deepEqual(stop.files,result.files);assert.equal(stop.unsealed,undefined);
694
+ assert.equal(stop.guidance.recoveryOperation,null);assert.equal(stop.guidance.authorizationGranted,false);
695
+ // T-001 conflicts; T-002 is ready, marked done in tasks.md and not merged: both are listed, in task order.
696
+ assert.match(stop.guidance.nextStep,new RegExp(`T-001:git merge --no-ff cm/${segment}/work/T-001(工作树 [^)]+);1\\.work/T-002:git merge --no-ff cm/${segment}/work/T-002`));
697
+ assert.match(stop.guidance.nextStep,/cm-ai-batch-plan\.mjs/);assert.match(stop.guidance.summary,/主目录未改动/);
698
+ }
359
699
  for(const name of heads)git(codeProject,['check-ref-format','--branch',name]);
360
700
  for(const task of ['T-001','T-002'])assert.throws(()=>git(codeProject,['rev-parse','--verify',`refs/heads/cm/work/${task}`]));
701
+ // Follow the guidance: merge each listed branch in order, resolving the conflict.
702
+ // Both reviewed deliveries reach the main checkout, T-002's included.
703
+ const branches=[...result.guidance.nextStep.matchAll(/git merge --no-ff (\S+)(工作树/g)].map(match=>match[1]);
704
+ assert.deepEqual(branches,[`cm/${segment}/work/T-001`,`cm/${segment}/work/T-002`]);
705
+ for(const branch of branches){
706
+ const merged=spawnSync('git',['-C',codeProject,'merge','--no-ff','--no-edit',branch],{encoding:'utf8'});
707
+ if(merged.status!==0){git(codeProject,['checkout','--theirs','file0.js']);git(codeProject,['add','file0.js']);git(codeProject,['commit','--no-edit']);}
708
+ }
709
+ for(const file of ['file0.js','file1.js'])assert.equal(fs.readFileSync(path.join(codeProject,file),'utf8'),'implemented\n',file);
361
710
  return;
362
711
  }
363
712
  if(mode.endsWith('review-provider-retry')){
364
713
  assert.equal(result.state,'pending_review',JSON.stringify(result));assert.equal(result.code,'review_provider_failed');
365
- assert.match(result.reason,/^reviewer_rate_limited: /);assert.deepEqual(calls,parallel?['T-001','T-002']:['T-001']);
366
- result=await open().handle({operation:'advance',requestId:'retry-review'});
714
+ // One-member worktree groups (worktree-each) run one at a time; a two-member group develops both.
715
+ assert.match(result.reason,/^reviewer_rate_limited: /);assert.deepEqual(calls,parallel&&!each?['T-001','T-002']:['T-001']);
716
+ // The batch passes the member's structured class through (drivers retry on it).
717
+ assert.equal(result.reviewFailure,'reviewer_rate_limited');
718
+ // The frozen target a driver's timed retry_review must find unchanged.
719
+ assert.equal(result.taskKey,`${feature}/T-001`);assert.equal(result.reviewRetryTarget.taskKey,`${feature}/T-001`);
720
+ assert.match(result.reviewRetryTarget.batchDigest,/^[a-f0-9]{64}$/);assert.equal(typeof result.reviewInvocationId,'string');
721
+ if(mode.endsWith('bound-review-provider-retry'))result=await boundReviewRetry(result);
722
+ else result=await open().handle({operation:'advance',requestId:'retry-review'});
723
+ if(result===null)return;
367
724
  }
368
725
  if(mode==='qa-resume'){
369
726
  assert.equal(result.code,'qa_decision_required');assert.deepEqual(calls,['T-001']);
370
727
  assert(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8').includes('[x] T-001'));
728
+ // A changed plan is refused; a scope that departs from tasks.md is refused before the plan digest is compared.
371
729
  const changed=structuredClone(config);changed.tasks[1].scope=['other.js'];
372
- await assert.rejects(createCmAiBatch({configuration:changed,executionFor,logHome:path.join(root,'logs')})
373
- .handle({operation:'advance',requestId:'changed-plan'}),{code:'batch_plan_mismatch'});
730
+ assert.throws(()=>createCmAiBatch({configuration:changed,executionFor,logHome:path.join(root,'logs')}),{code:'task_scope_mismatch'});
374
731
  qaReady=true;result=await open().handle({operation:'advance',requestId:'advance-2'});
375
732
  }
733
+ if(mode==='next-feature'){
734
+ // The batch's feature is done and hands off to the next feature: complete, not batch_task_scope_required.
735
+ assert.equal(result.batchComplete,true,JSON.stringify(result));assert.equal(result.nextFeature,'2.next');
736
+ assert.match(result.task_commit,/^[a-f0-9]{40}$/);assert.match(result.guidance.nextStep,/cm-ai-batch-plan\.mjs/);
737
+ const again=await open().handle({operation:'advance',requestId:'after-feature'});
738
+ assert.equal(again.batchComplete,true);assert.equal(again.task_commit,result.task_commit);
739
+ return;
740
+ }
376
741
  assert.equal(result.code,mode==='failed-qa'?'qa_failed':'run_done',JSON.stringify(result));
377
742
  if(mode==='resources-open'){
378
743
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');
@@ -395,16 +760,62 @@ export async function batchFixture(mode,options={}){
395
760
  assert.equal(classifyDriveResult('cm-ai-batch',{result:blocked}),'stuck');
396
761
  return;
397
762
  }
398
- assert.deepEqual(calls,parallel?(mode==='parallel-retry'?['T-001','T-002','T-001','T-003']:['T-001','T-002','T-003']):mode==='failed-qa'?['T-001']:['T-001','T-002']);
763
+ assert.deepEqual(calls,parallel?(mode==='parallel-retry'?['T-001','T-002','T-001','T-003']
764
+ :options.slowFirst?['T-002','T-001','T-003']:['T-001','T-002','T-003']):mode==='failed-qa'?['T-001']:['T-001','T-002']);
399
765
  if(parallel){
400
766
  const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
401
767
  const ready=rows.filter(row=>row.phase==='batch_member_ready'),handoffs=rows.filter(row=>row.phase==='batch_handoff');
402
- assert.equal(ready.length,2);assert.equal(handoffs.length,2);assert.deepEqual(handoffs.map(row=>row.from_key),ready.map(row=>row.from_key));
768
+ assert.equal(ready.length,2);assert.equal(handoffs.length,2);assert.deepEqual(handoffs.map(row=>row.from_key),[`${feature}/T-001`,`${feature}/T-002`],'merged in task order');
403
769
  assert(handoffs.every(row=>/^[a-f0-9]{40}$/.test(row.merge_commit)&&row.post_merge_check==='skipped'));
404
- assert.equal(rows.filter(row=>row.event==='qa'&&row.reason==='parallel_member_deferred'&&row.status==='skipped').length,2);
405
- assert.deepEqual(qaCalls,['T-003']);
770
+ // Only members developed alongside others defer their QA; a one-member group decides
771
+ // with the fixed checkpoints and runs a triggered QA in its own worktree before merging.
772
+ assert.equal(rows.filter(row=>row.event==='qa'&&row.reason==='parallel_member_deferred'&&row.status==='skipped').length,each?0:2);
773
+ assert.deepEqual(qaCalls,mode==='worktree-each-qa'?['T-001','T-003']:['T-003']);
774
+ if(each){
775
+ const decision=task=>rows.find(row=>row.event==='qa'&&row.node==='N6'&&row.task===task&&['skipped','triggered'].includes(row.status));
776
+ assert.deepEqual(assessments,['T-001','T-002','T-003']);
777
+ if(mode==='worktree-each-qa'){
778
+ assert.deepEqual([decision('T-001').status,decision('T-001').reason],['triggered','authentication']);
779
+ assert.deepEqual(qaSeen[0],{task:'T-001',codeProject:path.join(root,'.cm-worktrees',batchSegment(config.batchId),'T-001'),merged:false});
780
+ }else assert.deepEqual([decision('T-001').status,decision('T-001').reason],['skipped','no_fixed_trigger']);
781
+ assert.deepEqual([decision('T-002').status,decision('T-002').reason],['skipped','no_fixed_trigger']);
782
+ assert.deepEqual([decision('T-003').status,decision('T-003').reason],['triggered','feature_complete']);
783
+ assert.equal(qaSeen.at(-1).codeProject,codeProject);
784
+ }
406
785
  assert(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8').includes('[x] T-003'));
407
- assert.equal(git(codeProject,['branch','--show-current']),'main');
786
+ if(options.detachedMain){
787
+ // Still detached: the batch never switches or creates a branch in the main checkout,
788
+ // main is untouched and the merges sit on the detached HEAD, as serial commits did.
789
+ assert.equal(git(codeProject,['branch','--show-current']),'');
790
+ assert.equal(git(codeProject,['log','-1','--format=%s','refs/heads/main']),'fixture baseline');
791
+ // The finished result names the commit holding the merges and how to keep it.
792
+ assert.equal(result.detachedHead,git(codeProject,['rev-parse','HEAD']));
793
+ assert.match(`${result.guidance.nextStep} ${result.guidance.prerequisites.join(';')}`,new RegExp(`detached HEAD(提交 ${result.detachedHead.slice(0,12)}).*git switch -c`));
794
+ }else{assert.equal(git(codeProject,['branch','--show-current']),'main');assert.equal('detachedHead' in result,false);}
795
+ if(options.slowFirst){
796
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
797
+ const order=phase=>rows.filter(row=>row.phase===phase).map(row=>row.from_key);
798
+ assert.deepEqual(order('batch_member_ready'),[`${feature}/T-002`,`${feature}/T-001`],'T-002 finished first');
799
+ }
800
+ if(each){
801
+ // Both worker assertions ran (they would otherwise surface as unknown terminals).
802
+ assert.deepEqual(eachSeen,['T-001','T-002','T-003']);
803
+ // Every member worktree and branch is gone after its merge; the main checkout is clean.
804
+ const segment=batchSegment(config.batchId);
805
+ for(const id of ['T-001','T-002'])assert(!fs.existsSync(path.join(root,'.cm-worktrees',segment,id)),id);
806
+ assert.equal(git(codeProject,['for-each-ref','--format=%(refname:short)','refs/heads/cm']),'');
807
+ assert.equal(git(codeProject,['worktree','list','--porcelain']).split('\n').filter(line=>line.startsWith('worktree ')).length,1);
808
+ assert.equal(git(codeProject,['status','--porcelain']),'');
809
+ // One merge commit per member, in task order, then the final task's own commit.
810
+ const subjects=git(codeProject,['log','--format=%s','-5']).split('\n');
811
+ assert.deepEqual([subjects[0],subjects[2],subjects[4]],['T-003: final','T-002: second','T-001: first']);
812
+ // Git names a detached target in its default message ("… into HEAD").
813
+ for(const merge of [subjects[1],subjects[3]])assert.match(merge,options.detachedMain?/^Merge commit '[a-f0-9]{40}' into HEAD$/:/^Merge commit '[a-f0-9]{40}'$/);
814
+ }
815
+ if(mode==='parallel-existing')for(const file of ['file0.js','file1.js']){
816
+ assert.equal(fs.readFileSync(path.join(codeProject,file),'utf8'),'implemented\n');
817
+ assert.equal(git(codeProject,['show',`HEAD~3:${file}`]),'existing');
818
+ }
408
819
  }
409
820
  if(mode==='learning'){
410
821
  const handoff=JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','work-T-002-a1-handoff.json'),'utf8'));