@aibyzero/cm-workflow 0.17.1 → 0.19.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 (357) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +23 -0
  3. package/CHANGELOG.md +242 -0
  4. package/README.md +20 -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/autonomy.mjs +152 -0
  22. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  23. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  24. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  25. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  26. package/runtime/js/cm-ai/claude-review-stream.mjs +83 -14
  27. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  28. package/runtime/js/cm-ai/cm-ai-admission.mjs +56 -17
  29. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  30. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  31. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  32. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  33. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  34. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  35. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  36. package/runtime/js/cm-ai/control-policy.mjs +21 -4
  37. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  38. package/runtime/js/cm-ai/drive-core.mjs +115 -11
  39. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  40. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  41. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  42. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  43. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  44. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  45. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  46. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  47. package/runtime/js/cm-ai/host-check.mjs +11 -5
  48. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  49. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  50. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  51. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  52. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  53. package/runtime/js/cm-ai/host-session.mjs +1 -1
  54. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  55. package/runtime/js/cm-ai/host.mjs +1 -1
  56. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  57. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  58. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  59. package/runtime/js/cm-ai/operator-guidance.mjs +9 -2
  60. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  61. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  62. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  63. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  64. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  65. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  66. package/runtime/js/cm-ai/review-package.mjs +79 -7
  67. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  68. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  69. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  70. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  71. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  72. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  73. package/runtime/js/cm-ai/task-runner.mjs +242 -39
  74. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  75. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  76. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  77. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  78. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  79. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  80. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  81. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  82. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  83. package/runtime/js/cm-fix/dossier.mjs +8 -2
  84. package/runtime/js/cm-fix/execution.mjs +578 -100
  85. package/runtime/js/cm-fix/final-review.mjs +39 -8
  86. package/runtime/js/cm-fix/finish.mjs +15 -11
  87. package/runtime/js/cm-fix/host-review.mjs +65 -10
  88. package/runtime/js/cm-fix/host.mjs +35 -12
  89. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  90. package/runtime/js/cm-fix/metrics.mjs +18 -5
  91. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  92. package/runtime/js/cm-fix/regression.mjs +16 -7
  93. package/runtime/js/cm-fix/repair.mjs +29 -8
  94. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  95. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  96. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  97. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  98. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  99. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  100. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  101. package/runtime/js/cm-fix/start.mjs +6 -3
  102. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  103. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  104. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  105. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  106. package/runtime/js/cm-prd/analysis.mjs +13 -9
  107. package/runtime/js/cm-prd/change.mjs +37 -16
  108. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  109. package/runtime/js/cm-prd/draft.mjs +31 -3
  110. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  111. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  112. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  113. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  114. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  115. package/runtime/js/cm-prd/self-check.mjs +125 -6
  116. package/runtime/js/cm-prd/session.mjs +30 -1
  117. package/runtime/js/cm-prd/summary.mjs +11 -5
  118. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  119. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  120. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  121. package/runtime/js/cm-security/scan.mjs +1 -1
  122. package/runtime/js/commander/decision.mjs +44 -0
  123. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  124. package/runtime/js/commander/ledger.mjs +265 -0
  125. package/runtime/js/commander/preflight.mjs +107 -0
  126. package/runtime/js/notify-later.mjs +13 -0
  127. package/runtime/js/notify-send.mjs +6 -2
  128. package/runtime/js/notify.mjs +581 -65
  129. package/runtime/js/review-findings.mjs +38 -0
  130. package/runtime/js/session-boundary.mjs +56 -0
  131. package/runtime/js/session-handoff.mjs +68 -0
  132. package/runtime/js/spec-task-line.mjs +27 -13
  133. package/runtime/js/specs-status.mjs +5 -4
  134. package/runtime/js/task-scope.mjs +197 -0
  135. package/runtime/logging.md +6 -1
  136. package/runtime/model-efficiency.md +69 -10
  137. package/runtime/orchestration.md +3 -1
  138. package/runtime/project-learning.md +2 -0
  139. package/runtime/review.md +3 -2
  140. package/runtime/test-contract.md +1 -0
  141. package/scripts/ci-test-weights.json +3 -0
  142. package/scripts/cm-ai-admission.mjs +21 -7
  143. package/scripts/cm-ai-admission.test.mjs +171 -3
  144. package/scripts/cm-ai-batch-drive.mjs +79 -18
  145. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  146. package/scripts/cm-ai-batch-host.mjs +38 -9
  147. package/scripts/cm-ai-batch-host.test.mjs +6 -5
  148. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  149. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  150. package/scripts/cm-ai-batch-plan.mjs +52 -0
  151. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  152. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  153. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  154. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  155. package/scripts/cm-ai-batch-run.mjs +471 -57
  156. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  157. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  158. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  159. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  160. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  161. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  162. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  163. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  164. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  165. package/scripts/cm-ai-control-policy.test.mjs +14 -0
  166. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  167. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  168. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  169. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  170. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  171. package/scripts/cm-ai-drive.mjs +73 -17
  172. package/scripts/cm-ai-drive.test.mjs +34 -2
  173. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  174. package/scripts/cm-ai-host.mjs +60 -19
  175. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  176. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  177. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  178. package/scripts/cm-ai-integration-preview.mjs +41 -0
  179. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  180. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  181. package/scripts/cm-ai-operator-guidance.test.mjs +16 -1
  182. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  183. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  184. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  185. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  186. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  187. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  188. package/scripts/cm-ai-run.mjs +88 -21
  189. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  190. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  191. package/scripts/cm-ai-supersede.test.mjs +28 -0
  192. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  193. package/scripts/cm-announce-hook.mjs +35 -8
  194. package/scripts/cm-announce-hook.test.mjs +25 -0
  195. package/scripts/cm-autonomy.mjs +94 -0
  196. package/scripts/cm-autonomy.test.mjs +162 -0
  197. package/scripts/cm-challenge.test.mjs +61 -0
  198. package/scripts/cm-check-drive-files.mjs +1 -1
  199. package/scripts/cm-check-runtime.sh +60 -1
  200. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  201. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  202. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  203. package/scripts/cm-claude-review-stream.test.mjs +13 -0
  204. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  205. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  206. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  207. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  208. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  209. package/scripts/cm-commander-ledger.test.mjs +260 -0
  210. package/scripts/cm-commander-p2.test.mjs +295 -0
  211. package/scripts/cm-commander-preflight.mjs +84 -0
  212. package/scripts/cm-commander.mjs +116 -0
  213. package/scripts/cm-config-lock.mjs +35 -0
  214. package/scripts/cm-controlled-correction.test.mjs +10 -1
  215. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  216. package/scripts/cm-display-task-id.test.mjs +41 -0
  217. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  218. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  219. package/scripts/cm-external-batch-host.test.mjs +4 -3
  220. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  221. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  222. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  223. package/scripts/cm-failover.mjs +48 -10
  224. package/scripts/cm-failover.test.mjs +46 -0
  225. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  226. package/scripts/cm-fix-command-correction.mjs +17 -0
  227. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  228. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  229. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  230. package/scripts/cm-fix-drive.mjs +33 -5
  231. package/scripts/cm-fix-drive.test.mjs +49 -0
  232. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  233. package/scripts/cm-fix-host-review.test.mjs +21 -9
  234. package/scripts/cm-fix-host.mjs +26 -8
  235. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  236. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  237. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  238. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  239. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  240. package/scripts/cm-fix-review-preflight.mjs +24 -0
  241. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  242. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  243. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  244. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  245. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  246. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  247. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  248. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  249. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  250. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  251. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  252. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  253. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  254. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  255. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  256. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  257. package/scripts/cm-host-replay.test.mjs +176 -0
  258. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  259. package/scripts/cm-install-manifest.sh +351 -0
  260. package/scripts/cm-live-evidence.test.mjs +59 -1
  261. package/scripts/cm-log-event.mjs +61 -10
  262. package/scripts/cm-log-event.test.mjs +121 -1
  263. package/scripts/cm-matt-skills.mjs +576 -0
  264. package/scripts/cm-matt-skills.test.mjs +550 -0
  265. package/scripts/cm-notify-command.test.mjs +42 -10
  266. package/scripts/cm-notify.mjs +14 -10
  267. package/scripts/cm-notify.test.mjs +581 -59
  268. package/scripts/cm-patrol.mjs +4 -1
  269. package/scripts/cm-patrol.test.mjs +23 -5
  270. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  271. package/scripts/cm-prd-completion.test.mjs +56 -13
  272. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  273. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  274. package/scripts/cm-prd-draft.test.mjs +1 -1
  275. package/scripts/cm-prd-drive.mjs +13 -6
  276. package/scripts/cm-prd-drive.test.mjs +45 -1
  277. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  278. package/scripts/cm-prd-host.mjs +10 -5
  279. package/scripts/cm-prd-host.test.mjs +4 -2
  280. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  281. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  282. package/scripts/cm-prd-revision.test.mjs +1 -1
  283. package/scripts/cm-prd-self-check-revision.test.mjs +1 -1
  284. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  285. package/scripts/cm-prd-self-check.test.mjs +105 -5
  286. package/scripts/cm-prd-summary.test.mjs +24 -3
  287. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  288. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  289. package/scripts/cm-refactor-drive.mjs +2 -1
  290. package/scripts/cm-refactor-drive.test.mjs +9 -0
  291. package/scripts/cm-release-smoke.sh +1 -1
  292. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  293. package/scripts/cm-skill-hints-exam.mjs +149 -0
  294. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  295. package/scripts/cm-skill-hints.exam.json +706 -0
  296. package/scripts/cm-skill-hints.json +119 -0
  297. package/scripts/cm-skill-hints.mjs +669 -0
  298. package/scripts/cm-skill-hints.test.mjs +831 -0
  299. package/scripts/cm-skill-judge.mjs +181 -0
  300. package/scripts/cm-skill-judge.test.mjs +255 -0
  301. package/scripts/cm-specs-status.test.mjs +4 -2
  302. package/scripts/cm-start-check.mjs +323 -0
  303. package/scripts/cm-start-check.test.mjs +406 -0
  304. package/scripts/cm-task-gate.mjs +150 -29
  305. package/scripts/cm-task-gate.test.mjs +73 -1
  306. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  307. package/scripts/cm-task-scope.test.mjs +308 -0
  308. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  309. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  310. package/scripts/cm-workflow-config.mjs +12 -2
  311. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  312. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  313. package/scripts/scan-public-safety.py +1 -0
  314. package/scripts/session-boundary.test.mjs +170 -0
  315. package/scripts/test-npm-install.py +14 -3
  316. package/scripts/test-shell-compat.sh +2 -0
  317. package/scripts/validate-public-repo.py +4 -0
  318. package/scripts/validate-test-cases.mjs +3 -2
  319. package/skills/cm-ai/SKILL.md +5 -2
  320. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  321. package/skills/cm-ai/references/N4-review.md +2 -1
  322. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  323. package/skills/cm-ai/references/N8-finish.md +22 -0
  324. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  325. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  326. package/skills/cm-ai/references/js-host.md +82 -16
  327. package/skills/cm-challenge/SKILL.md +65 -0
  328. package/skills/cm-challenge/evals/README.md +18 -0
  329. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  330. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  331. package/skills/cm-challenge/references/examples.md +15 -0
  332. package/skills/cm-check/SKILL.md +5 -0
  333. package/skills/cm-check/references/js-host.md +2 -0
  334. package/skills/cm-fix/SKILL.md +12 -3
  335. package/skills/cm-fix/references/command-correction.md +67 -0
  336. package/skills/cm-fix/references/isolated-review.md +54 -0
  337. package/skills/cm-fix/references/js-host.md +62 -2
  338. package/skills/cm-fix/references/test-type-correction.md +72 -0
  339. package/skills/cm-fix/references/verification-recovery.md +114 -0
  340. package/skills/cm-idea/SKILL.md +2 -0
  341. package/skills/cm-idea/references/js-host.md +2 -0
  342. package/skills/cm-notify/SKILL.md +2 -0
  343. package/skills/cm-prd/SKILL.md +14 -9
  344. package/skills/cm-prd/references/brownfield.md +8 -1
  345. package/skills/cm-prd/references/change-mode.md +8 -1
  346. package/skills/cm-prd/references/greenfield.md +4 -0
  347. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  348. package/skills/cm-prd/references/js-host.md +4 -2
  349. package/skills/cm-prd/references/spec-self-check.md +5 -1
  350. package/skills/cm-refactor/SKILL.md +8 -0
  351. package/skills/cm-refactor/references/js-host.md +2 -0
  352. package/skills/cm-test/SKILL.md +4 -0
  353. package/templates/dashboard/dashboard.html +2 -2
  354. package/templates/pixel/cm-pixel.html +1 -1
  355. package/templates/pixel/cm-pixel.sh +1 -1
  356. package/templates/pixel/dev/template.html +1 -1
  357. package/templates/statusline/cm-statusline.sh +1 -1
@@ -0,0 +1,318 @@
1
+ import test,{after} from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn,spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {openControlRun,controlLaunchTarget,inspectRunHistory} from './cm-ai-run.mjs';
9
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
11
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
12
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
13
+ import {oldWriterOpen,prepareReviewedEvidenceSupersession} from '../runtime/js/cm-ai/reviewed-evidence-supersede.mjs';
14
+
15
+ // Never write the real ~/.cm-workflow home or its global log mirror from this suite;
16
+ // spawned CLIs inherit these variables as well.
17
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-v2-supersede-home-'));
18
+ const savedHome={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
19
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedHome,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedHome,'logs');
20
+ after(()=>{
21
+ for(const [key,value] of Object.entries(savedHome)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
22
+ fs.rmSync(isolatedHome,{recursive:true,force:true});
23
+ });
24
+
25
+ // V2 restart of a stopped task: the operator previews the predecessor's launch
26
+ // target read-only, and create compares it before any archive or new journal.
27
+ const policy={version:2,development:'conversation',bootstrap:'disabled',qa:'disabled',qaFix:'disabled'};
28
+ const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
29
+ const drive=fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url));
30
+
31
+ function fixture(t){
32
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-v2-supersede-')));
33
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
34
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
35
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
36
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=1;\n');
37
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture');
38
+ for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,file),'# fixture\n');
39
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement a\n');
40
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),
41
+ JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
42
+ const definitionFor=runId=>({version:1,specsDir,codeProject,feature,
43
+ identity:{repositoryId:'supersede-fixture',runId,taskId:'T-001',attempt:1},scope:['a.mjs'],requirements:['requirements.md']});
44
+ const execution=({legacy=false}={})=>({configuration:{kind:'synthetic-supersede-v1',hostContextId:'main',
45
+ ...(legacy?{}:{controlPolicy:policy})},
46
+ timeoutMs:1000,excludedContexts:['main'],developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',
47
+ run:()=>{throw new Error('must not execute');}},
48
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
49
+ contexts:['review-1','review-2'],run:()=>{throw new Error('must not review');}}],
50
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['main']},
51
+ check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]})});
52
+ const snapshotOf=runId=>readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:'supersede-fixture',runId}});
53
+ const store=runId=>path.join(specsDir,'.reviews','.execution',runId);
54
+ return {root,codeProject,specsDir,feature,definitionFor,execution,snapshotOf,store};
55
+ }
56
+
57
+ // The predecessor stops through its own host so its journal ends in a terminal state.
58
+ async function stoppedPredecessor(f,runId='old-run-0001'){
59
+ const definition=f.definitionFor(runId);
60
+ let run=await openControlRun(definition,'create',f.execution());run.close();
61
+ run=await openControlRun(definition,'resume',f.execution());
62
+ try{
63
+ const result=await run.host.handle({version:1,operation:'cancel',requestId:'stop',identity:definition.identity});
64
+ assert.equal(result.state,'cancelled');
65
+ }finally{run.close();}
66
+ return {definition,target:controlLaunchTarget(f.snapshotOf(runId))};
67
+ }
68
+
69
+ const reason='旧运行开发额度用完,按批准重开新一轮';
70
+
71
+ test('v2 create keeps refusing supersede without the previewed predecessor target',async t=>{
72
+ const f=fixture(t);await stoppedPredecessor(f);
73
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason}),
74
+ {code:'invalid_input'});
75
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
76
+ });
77
+
78
+ test('v2 create refuses a target whose predecessor moved after the preview',async t=>{
79
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
80
+ for(const drift of [{revision:'0'.repeat(64)},{state:'blocked'},{code:'develop_retry_limit'}]){
81
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),
82
+ {supersedeReason:reason,supersedeTarget:{...target,...drift}}),{code:'snapshot_changed'});
83
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
84
+ }
85
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),
86
+ {supersedeReason:reason,supersedeTarget:{...target,identity:{...target.identity,runId:'other-run-0001'}}}),
87
+ {code:'snapshot_changed'});
88
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
89
+ });
90
+
91
+ test('v2 create with the exact predecessor target records the supersession and starts attempt 1',async t=>{
92
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
93
+ const before=fs.readFileSync(path.join(f.store('old-run-0001'),'state.json'));
94
+ const run=await openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:target});
95
+ run.close();
96
+ const records=f.snapshotOf('new-run-0001').records.map(row=>row.payload.type);
97
+ assert.deepEqual(records.slice(0,2),['init','evidence-superseded']);
98
+ const supersession=f.snapshotOf('new-run-0001').records[1].payload.record;
99
+ assert.deepEqual(supersession.previousRunIds,['old-run-0001']);
100
+ assert.equal(supersession.reason,reason);
101
+ // The predecessor's journal is evidence, never rewritten by the restart.
102
+ assert.deepEqual(fs.readFileSync(path.join(f.store('old-run-0001'),'state.json')),before);
103
+ });
104
+
105
+ test('a second v2 restart must name the newest live predecessor, not an already superseded one',async t=>{
106
+ const f=fixture(t);const first=await stoppedPredecessor(f);
107
+ let run=await openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:first.target});
108
+ run.close();
109
+ run=await openControlRun(f.definitionFor('new-run-0001'),'resume',f.execution());
110
+ try{await run.host.handle({version:1,operation:'cancel',requestId:'stop',identity:f.definitionFor('new-run-0001').identity});}
111
+ finally{run.close();}
112
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0002'),'create',f.execution(),
113
+ {supersedeReason:reason,supersedeTarget:first.target}),{code:'snapshot_changed'});
114
+ const second=controlLaunchTarget(f.snapshotOf('new-run-0001'));
115
+ run=await openControlRun(f.definitionFor('new-run-0002'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:second});
116
+ run.close();
117
+ assert.deepEqual(f.snapshotOf('new-run-0002').records[1].payload.record.previousRunIds,['new-run-0001','old-run-0001']);
118
+ });
119
+
120
+ test('the read-only history exposes the same target and legacy launches refuse it',async t=>{
121
+ const f=fixture(t);const {definition,target}=await stoppedPredecessor(f);
122
+ assert.deepEqual(inspectRunHistory(definition).supersedeTarget,target);
123
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution({legacy:true}),
124
+ {supersedeReason:reason,supersedeTarget:target}),{code:'invalid_arguments'});
125
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
126
+ });
127
+
128
+ test('host CLI requires --supersede-target for v2 restart and rejects it everywhere else',t=>{
129
+ const f=fixture(t);
130
+ const config=path.join(f.root,'run.json'),control=path.join(f.root,'control.json'),target=path.join(f.root,'target.json');
131
+ fs.writeFileSync(config,JSON.stringify(f.definitionFor('new-run-0001')));fs.writeFileSync(control,JSON.stringify(policy));
132
+ fs.writeFileSync(target,'{}');
133
+ const run=extra=>spawnSync(process.execPath,[cli,'serve','--config',config,'--mode','create','--host-context','main',
134
+ '--control-config',control,...extra],{encoding:'utf8'});
135
+ const flags=['--supersede-reviewed-evidence','--supersede-reason','fixture'];
136
+ let result=run(flags);assert.equal(result.status,1);assert.match(result.stderr,/supersede_unavailable/);
137
+ result=run(['--supersede-target',target]);assert.equal(result.status,1);assert.match(result.stderr,/invalid_input/);
138
+ const legacy=spawnSync(process.execPath,[cli,'serve','--config',config,'--mode','create','--host-context','main',
139
+ '--allow-development',...flags,'--supersede-target',target],{encoding:'utf8'});
140
+ assert.equal(legacy.status,1);assert.match(legacy.stderr,/invalid_arguments/);
141
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
142
+ });
143
+
144
+ test('driver demands a v2 supersede target file and forbids it on legacy plans',t=>{
145
+ const f=fixture(t);
146
+ const config=path.join(f.root,'run.json'),control=path.join(f.root,'control.json'),target=path.join(f.root,'target.json');
147
+ fs.writeFileSync(config,JSON.stringify(f.definitionFor('new-run-0001')));fs.writeFileSync(control,JSON.stringify(policy));
148
+ fs.writeFileSync(target,'{}');
149
+ const plan=(extra,permissions)=>{const file=path.join(f.root,'plan.json');
150
+ fs.writeFileSync(file,JSON.stringify({config:'run.json',mode:'create',hostContext:'main',permissions,...extra}));return file;};
151
+ const flags=['--supersede-reviewed-evidence','--supersede-reason','fixture'];
152
+ let result=spawnSync(process.execPath,[drive,'--plan',plan({controlConfig:'control.json'},flags),'advance'],{encoding:'utf8'});
153
+ assert.equal(result.status,2,result.stderr);assert.match(result.stderr,/supersede-target/);
154
+ result=spawnSync(process.execPath,[drive,'--plan',plan({},[...flags,'--supersede-target','target.json']),'advance'],{encoding:'utf8'});
155
+ assert.equal(result.status,2,result.stderr);assert.match(result.stderr,/supersede-target/);
156
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
157
+ });
158
+
159
+ test('a predecessor whose writer is held elsewhere cannot be restarted, and the refusal leaves nothing behind',async t=>{
160
+ const f=fixture(t);const {definition,target}=await stoppedPredecessor(f);
161
+ // A concurrent resume of the old run owns its writer while the approval is checked.
162
+ const resumed=await openControlRun(definition,'resume',f.execution());
163
+ try{
164
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),
165
+ {supersedeReason:reason,supersedeTarget:target}),{code:'supersede_unavailable'});
166
+ assert.equal(fs.existsSync(f.store('new-run-0001')),false);
167
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.superseded')),false);
168
+ }finally{resumed.close();}
169
+ // Once the other owner is gone the same approval still works: nothing was consumed.
170
+ const run=await openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:target});
171
+ run.close();
172
+ assert.equal(f.snapshotOf('new-run-0001').records[1].payload.type,'evidence-superseded');
173
+ });
174
+
175
+ test('the predecessor writer lock is released after both a refused and a successful restart',async t=>{
176
+ const f=fixture(t);const {definition,target}=await stoppedPredecessor(f);
177
+ await assert.rejects(openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),
178
+ {supersedeReason:reason,supersedeTarget:{...target,revision:'0'.repeat(64)}}),{code:'snapshot_changed'});
179
+ // A leaked hold would make this resume fail with store_busy.
180
+ let run=await openControlRun(definition,'resume',f.execution());run.close();
181
+ run=await openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:target});
182
+ run.close();
183
+ run=await openControlRun(definition,'resume',f.execution());run.close();
184
+ });
185
+
186
+ test('after the target is verified the predecessor writer stays locked until the caller releases it',async t=>{
187
+ const f=fixture(t);const {definition,target}=await stoppedPredecessor(f);
188
+ const holds=[];
189
+ const record=prepareReviewedEvidenceSupersession({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
190
+ identity:f.definitionFor('new-run-0001').identity,reason,tasksPath:path.join(f.specsDir,f.feature,'tasks.md'),
191
+ expectedPredecessor:target,predecessorTarget:controlLaunchTarget,holds});
192
+ assert.deepEqual(record.previousRunIds,['old-run-0001']);
193
+ assert.equal(holds.length,1);
194
+ // Between verification and journaling no other process may resume the old run.
195
+ await assert.rejects(openControlRun(definition,'resume',f.execution()),{code:'store_busy'});
196
+ for(const held of holds)held.close();
197
+ const run=await openControlRun(definition,'resume',f.execution());run.close();
198
+ // The helper never verifies a v2 target without somewhere to hand the lock back.
199
+ assert.throws(()=>prepareReviewedEvidenceSupersession({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
200
+ identity:f.definitionFor('new-run-0001').identity,reason,tasksPath:path.join(f.specsDir,f.feature,'tasks.md'),
201
+ expectedPredecessor:target,predecessorTarget:controlLaunchTarget}),{code:'supersede_unavailable'});
202
+ });
203
+
204
+ // Cross-process race: restart B scans the single predecessor, then stops on a file
205
+ // barrier before taking its lock. Restart A completes in that gap. B must not proceed.
206
+ const raceChild=fileURLToPath(new URL('./cm-ai-control-v2-supersede-race.mjs',import.meta.url));
207
+ async function raceSecondRestart(f,target,{between}){
208
+ const barrier=path.join(f.root,'barrier');fs.mkdirSync(barrier);
209
+ const child=spawn(process.execPath,[raceChild,JSON.stringify({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
210
+ repositoryId:'supersede-fixture',runId:'new-run-0002',taskId:'T-001',reason,target,barrier})]);
211
+ let out='';child.stdout.on('data',chunk=>{out+=chunk;});child.stderr.on('data',()=>{});
212
+ const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
213
+ // Bounded wait whose timer is always cleared, so it never keeps the test process alive.
214
+ const within=async(promise,ms,message)=>{
215
+ let timer;
216
+ try{return await Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),ms);})]);}
217
+ finally{clearTimeout(timer);}
218
+ };
219
+ try{
220
+ for(let i=0;i<200&&!fs.existsSync(path.join(barrier,'scanned'));i++)await new Promise(resolve=>setTimeout(resolve,50));
221
+ assert.equal(fs.existsSync(path.join(barrier,'scanned')),true,'child never reached the barrier');
222
+ // Whatever happens while B is paused after its scan (the callback owns and releases its own handles), then B is released.
223
+ await between();
224
+ fs.writeFileSync(path.join(barrier,'go'),'');
225
+ await within(exited,30000,'child did not exit');
226
+ return JSON.parse(out.trim().split('\n').at(-1));
227
+ }finally{
228
+ child.kill();
229
+ try{await within(exited,5000,'child did not stop');}catch{}
230
+ }
231
+ }
232
+
233
+ test('a second restart that scanned the same predecessor before the first finished is refused under the lock',async t=>{
234
+ for(const cancelFirst of [false,true]){
235
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
236
+ const outcome=await raceSecondRestart(f,target,{between:async()=>{
237
+ // Restart A runs to completion (and optionally stops) while B is paused after its scan.
238
+ const first=await openControlRun(f.definitionFor('new-run-0001'),'create',f.execution(),{supersedeReason:reason,supersedeTarget:target});
239
+ // The first restart is over (its writer released) before B is let go, even when a step below fails.
240
+ try{
241
+ if(cancelFirst){
242
+ const result=await first.host.handle({version:1,operation:'cancel',requestId:'stop-a',identity:f.definitionFor('new-run-0001').identity});
243
+ assert.equal(result.state,'cancelled');
244
+ }
245
+ }finally{first.close();}
246
+ return null;
247
+ }});
248
+ assert.equal(outcome.ok,false,JSON.stringify(outcome));
249
+ // The first restart left a live or stopped successor: either way B must not become a second one.
250
+ assert.equal(outcome.code,cancelFirst?'snapshot_changed':'supersede_unavailable',JSON.stringify(outcome));
251
+ assert.equal(fs.existsSync(f.store('new-run-0002')),false);
252
+ }
253
+ });
254
+
255
+ test('a restart that failed before its first journal record leaves a directory the paused restart must not ignore',async t=>{
256
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
257
+ const outcome=await raceSecondRestart(f,target,{between:async()=>{
258
+ // Restart A takes the predecessor, creates its (still empty) journal, then fails before 'init'.
259
+ const store=openExecutionStore({specsRoot:f.specsDir,identity:{repositoryId:'supersede-fixture',runId:'new-run-0001'},
260
+ fingerprints:f.snapshotOf('old-run-0001').fingerprints,create:true});
261
+ store.close();
262
+ assert.equal(fs.existsSync(path.join(f.store('new-run-0001'),'state.json')),true);
263
+ return null;
264
+ }});
265
+ assert.equal(outcome.ok,false,JSON.stringify(outcome));
266
+ assert.equal(outcome.code,'snapshot_changed',JSON.stringify(outcome));
267
+ assert.equal(fs.existsSync(f.store('new-run-0002')),false);
268
+ });
269
+
270
+ test('a paused restart that is never released fails instead of continuing out of order',async t=>{
271
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
272
+ const barrier=path.join(f.root,'barrier-timeout');fs.mkdirSync(barrier);
273
+ // No release signal is ever written: the child reports the timeout itself.
274
+ const child=spawn(process.execPath,[raceChild,JSON.stringify({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
275
+ repositoryId:'supersede-fixture',runId:'new-run-0002',taskId:'T-001',reason,target,barrier})]);
276
+ let out='';child.stdout.on('data',chunk=>{out+=chunk;});child.stderr.on('data',()=>{});
277
+ await new Promise(resolve=>child.on('close',resolve));
278
+ assert.equal(JSON.parse(out.trim().split('\n').at(-1)).code,'barrier_timeout');
279
+ assert.equal(fs.existsSync(f.store('new-run-0002')),false);
280
+ });
281
+
282
+ // The prior-writer guard (execution optimizations) and the supersede checks both ask
283
+ // "is this writer open?". The lock this call took itself must not read as foreign.
284
+ test('the open-writer check exempts only a lock this process registered for its own restart',async t=>{
285
+ const f=fixture(t);const {target}=await stoppedPredecessor(f);
286
+ const execution=path.join(f.specsDir,'.reviews','.execution');
287
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),false);
288
+ // A plain lock taken by this same process without registering it still counts as open.
289
+ const fingerprints=f.snapshotOf('old-run-0001').fingerprints;
290
+ const plain=openExecutionStore({specsRoot:f.specsDir,identity:{repositoryId:'supersede-fixture',runId:'old-run-0001'},fingerprints,create:false});
291
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),true);
292
+ plain.close();
293
+ // A lock taken through the restart path is exempt while held, and only while held.
294
+ const holds=[];
295
+ prepareReviewedEvidenceSupersession({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
296
+ identity:f.definitionFor('new-run-0001').identity,reason,tasksPath:path.join(f.specsDir,f.feature,'tasks.md'),
297
+ expectedPredecessor:target,predecessorTarget:controlLaunchTarget,holds});
298
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),false);
299
+ // ...but not when another process also has the same writer file open.
300
+ const writerFile=path.join(execution,'old-run-0001','writer.sqlite');
301
+ const reader=spawn(process.execPath,['-e',`const fs=require('fs');fs.openSync(${JSON.stringify(writerFile)},'r');process.stdout.write('open\\n');setTimeout(()=>{},15000);`]);
302
+ t.after(()=>reader.kill());
303
+ await new Promise((resolve,reject)=>{reader.stdout.once('data',resolve);reader.on('error',reject);reader.stderr.on('data',()=>{});});
304
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),true);
305
+ reader.kill();await new Promise(resolve=>reader.on('close',resolve));
306
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),false);
307
+ for(const held of holds)held.close();
308
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),false);
309
+ // Another process holding the writer is never exempt.
310
+ const holder=spawn(process.execPath,['--input-type=module','-e',`
311
+ import {openExecutionStore} from ${JSON.stringify(new URL('../runtime/js/cm-ai/execution-store.mjs',import.meta.url).href)};
312
+ const s=openExecutionStore({specsRoot:${JSON.stringify(f.specsDir)},identity:{repositoryId:'supersede-fixture',runId:'old-run-0001'},
313
+ fingerprints:${JSON.stringify(fingerprints)},create:false});
314
+ process.stdout.write('held\\n');setTimeout(()=>{s.close();},15000);`]);
315
+ t.after(()=>holder.kill());
316
+ await new Promise((resolve,reject)=>{holder.stdout.once('data',resolve);holder.on('error',reject);holder.stderr.on('data',()=>{});});
317
+ assert.equal(oldWriterOpen(execution,'old-run-0001'),true);
318
+ });
@@ -123,6 +123,169 @@ test('single live verification precheck executes after checks and blocks before
123
123
  assert.equal(result(out).pendingAction,'resume');
124
124
  });
125
125
 
126
+ // A satisfied gate's per-requirement answers are the only place a task's process
127
+ // evidence (baseline counts, RED failures, location lists) can reach the reviewer.
128
+ const handoffOf=f=>JSON.parse(fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-a1-handoff.json'),'utf8'));
129
+ const requirementEntries=handoff=>handoff.evidence.filter(item=>item.startsWith('cm-requirement-evidence-v1: '));
130
+ function precheckFixture(t){
131
+ const f=fixture(t);f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});
132
+ fs.writeFileSync(path.join(f.specsDir,'1.work/tasks.md'),'- [ ] T-001: fixture\n - 验证: 记录实现前基线;value is 42\n');
133
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
134
+ return f;
135
+ }
136
+ const satisfiedItems=[{requirement:'记录实现前基线',satisfied:true,evidence:'改前 npm test:tests 49 / pass 49 / fail 0'},
137
+ {requirement:'value is 42',satisfied:true,evidence:'target.mjs 第 1 行导出 42'}];
138
+ test('a satisfied precheck writes its requirement evidence into the reviewed handoff',async t=>{
139
+ const f=precheckFixture(t);
140
+ const plan=f.plan({verificationPrecheck:true,liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
141
+ const out=await runLiveDriver(DRIVER,plan,'advance',()=>({items:satisfiedItems}),{env:f.env});
142
+ assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
143
+ assert.notEqual(result(out).code,'verification_precheck_failed');
144
+ const handoff=handoffOf(f),entries=requirementEntries(handoff);
145
+ assert.equal(entries.length,1);
146
+ const record=JSON.parse(entries[0].slice('cm-requirement-evidence-v1: '.length));
147
+ assert.deepEqual(record.identity,f.identity);
148
+ assert.deepEqual(record.items,satisfiedItems.map(({requirement,evidence})=>({requirement,evidence})));
149
+ // The handoff the reviewer read is the one carrying the record.
150
+ const receipt=fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-r1.md'),'utf8');
151
+ assert.match(receipt,new RegExp(`handoff_sha256: ${crypto.createHash('sha256').update(fs.readFileSync(path.join(f.specsDir,'.reviews','work-T-001-a1-handoff.json'))).digest('hex')}`));
152
+ });
153
+ test('without the gate the handoff carries no requirement evidence entry',t=>{
154
+ const f=precheckFixture(t);
155
+ const out=f.drive(f.plan(),'advance');
156
+ assert.equal(out.status,0,out.stderr);
157
+ assert.deepEqual(requirementEntries(handoffOf(f)),[]);
158
+ });
159
+ function v2Policy(f,extra={}){
160
+ fs.writeFileSync(path.join(f.root,'POLICY.json'),JSON.stringify({version:2,development:'conversation',
161
+ bootstrap:'disabled',qa:'disabled',qaFix:'disabled',...extra}));
162
+ f.write('qa-assess.json',{confirmed:true});
163
+ }
164
+ test('a v2 policy with verification precheck enables the gate without the launch flag',async t=>{
165
+ const f=precheckFixture(t);v2Policy(f,{verification:'precheck'});
166
+ // Without a live runner the driver refuses before launch, exactly as for the flag.
167
+ const refused=f.drive(f.plan({controlConfig:'POLICY.json'}),'advance');
168
+ assert.equal(refused.status,2);assert.match(refused.stderr,/verification_precheck/);
169
+ noRun(f);
170
+ const plan=f.plan({controlConfig:'POLICY.json',liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
171
+ const out=await runLiveDriver(DRIVER,plan,'advance',()=>({items:satisfiedItems}),{env:f.env});
172
+ assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
173
+ assert.equal(requirementEntries(handoffOf(f)).length,1);
174
+ });
175
+ test('a v2 policy without the verification field keeps the gate off',t=>{
176
+ const f=precheckFixture(t);v2Policy(f);
177
+ const out=f.drive(f.plan({controlConfig:'POLICY.json'}),'advance');
178
+ assert.equal(out.status,0,out.stderr);
179
+ assert.deepEqual(requirementEntries(handoffOf(f)),[]);
180
+ });
181
+
182
+ // The requirement entry can push a handoff that fit before the Learning append
183
+ // over the 256 KiB limit only after it. The behaviour test below reaches that
184
+ // window through a direct live host; this one pins the structure: every append
185
+ // goes through the guarded helper, which maps a size failure to the retryable
186
+ // package block.
187
+ test('every Learning append to the host handoff takes the retryable package boundary',()=>{
188
+ const source=fs.readFileSync(new URL('../runtime/js/cm-ai/task-runner.mjs',import.meta.url),'utf8');
189
+ const calls=[...source.matchAll(/writeCmAiTaskLearningHandoff\(/g)].length;
190
+ assert.equal(calls,1,'Learning must be appended only inside appendLearningHandoff');
191
+ const helper=/function appendLearningHandoff\(v,\{application,retrospective,writeback\}\)\{([\s\S]*?)\n \}/.exec(source);
192
+ assert.notEqual(helper,null,'appendLearningHandoff not found');
193
+ assert.match(helper[1],/try\{writeCmAiTaskLearningHandoff\(/);
194
+ assert.match(helper[1],/catch\(error\)\{emptyDelivery\(error\);return false;\}/);
195
+ // Both delivery paths (fresh develop and check-only recheck) use it.
196
+ assert.equal([...source.matchAll(/if\(!appendLearningHandoff\(v,/g)].length,2);
197
+ // emptyDelivery is where limit_exceeded becomes develop_package_too_large.
198
+ assert.match(source,/if\(error\?\.code==='limit_exceeded'&&metadata\.bootstrap\?\.mode!=='instructions'\)\{\n\s*halt\('blocked','develop_package_too_large'/);
199
+ });
200
+ // The behaviour behind that structure, through a direct live host (no driver):
201
+ // its check answer is not bounded by the driver's 32 KiB command list, so the
202
+ // check commands and the precheck answer together bring the published handoff
203
+ // right under 256 KiB, and only the Learning append pushes it over.
204
+ const QUOTE_ITEMS=16,QUOTE_TEXT=1990;
205
+ function paddedLiveSession(f,{mode,commandPad,items}){
206
+ const wrapper=path.join(f.root,`padded-${mode}-${Math.random().toString(36).slice(2)}.mjs`);
207
+ fs.writeFileSync(wrapper,`import fs from 'node:fs';
208
+ import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
209
+ import {createHostCheck} from ${JSON.stringify(HOST_CHECK)};
210
+ const cwd=${JSON.stringify(f.codeProject)};
211
+ driveHost({host:${JSON.stringify(HOST)},args:['serve','--config',${JSON.stringify(f.config)},'--mode',${JSON.stringify(mode)},
212
+ '--host-context','drive-host-a','--allow-development','--verification-precheck','--review-config',${JSON.stringify(path.join(f.root,'review.json'))}],
213
+ cwd,operation:'start',answers:{},request:{version:1,identity:${JSON.stringify(f.identity)}},
214
+ answerFor:async row=>{
215
+ if(row.kind==='develop'){for(const file of ${JSON.stringify(f.scope)}){fs.mkdirSync(cwd+'/'+file.replace(/[^/]*$/,''),{recursive:true});
216
+ fs.writeFileSync(cwd+'/'+file,'export const value = 42;\\n');}
217
+ return {status:'succeeded',value:${JSON.stringify(developValue)}};}
218
+ if(row.kind==='check'){
219
+ const checks=await createHostCheck({cwd,commands:[{id:'noop',command:[process.execPath,'-e','0']}]})
220
+ ({identity:row.payload.identity},{signal:new AbortController().signal});
221
+ return checks.map(check=>({...check,command:[...check.command,'"'.repeat(${commandPad})]}));
222
+ }
223
+ if(row.kind==='verification_precheck')return {items:${JSON.stringify(items)}};
224
+ return null;
225
+ }});
226
+ `);
227
+ return spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:60000,env:f.env});
228
+ }
229
+ const quoteItems=count=>Array.from({length:count},(_,index)=>({requirement:`记录实现前基线 ${index}`,satisfied:true,
230
+ evidence:'"'.repeat(QUOTE_TEXT)}));
231
+ const LEARNING_PREFIX='cm-learning-';
232
+ // Long changed paths add the last few KiB the two bounded answers cannot reach.
233
+ const paddedScope=['target.mjs',...Array.from({length:40},(_,index)=>`pad/${'p'.repeat(200)}-${index}.mjs`)];
234
+ function paddedFixture(t){
235
+ const f=fixture(t,{scope:paddedScope});f.scope=paddedScope;
236
+ fs.writeFileSync(path.join(f.specsDir,'1.work/tasks.md'),'- [ ] T-001: fixture\n - 验证: 记录实现前基线;value is 42\n');
237
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
238
+ return f;
239
+ }
240
+ test('a Learning append that overflows the published handoff blocks retryably and the same attempt resumes',t=>{
241
+ const handoffFile=f=>path.join(f.specsDir,'.reviews','work-T-001-a1-handoff.json');
242
+ // Probe: the same delivery with a small command pad. Every extra quote in the
243
+ // command costs exactly four handoff bytes (escaped once by the command's own
244
+ // JSON, once by the handoff), so the size at any pad follows from this one.
245
+ const probe=paddedFixture(t),probePad=1000;
246
+ const fit=paddedLiveSession(probe,{mode:'create',commandPad:probePad,items:quoteItems(QUOTE_ITEMS)});
247
+ assert.equal(fit.status,0,fit.stderr);assert.equal(result(fit).state,'awaiting_review',fit.stdout);
248
+ const fitted=fs.readFileSync(handoffFile(probe));
249
+ const learning=JSON.parse(fitted).evidence.filter(item=>item.includes(LEARNING_PREFIX));
250
+ assert(learning.length>0,'the probe handoff carries Learning evidence');
251
+ const limit=256*1024,pad=probePad+Math.ceil((limit+1-fitted.length)/4);
252
+ assert(pad>probePad,`probe ${fitted.length} bytes leaves room to pad`)
253
+
254
+ const f=paddedFixture(t);
255
+ const blocked=paddedLiveSession(f,{mode:'create',commandPad:pad,items:quoteItems(QUOTE_ITEMS)});
256
+ assert.equal(blocked.status,0,blocked.stderr);
257
+ assert.equal(result(blocked).state,'blocked',blocked.stdout);
258
+ assert.equal(result(blocked).code,'develop_package_too_large');
259
+ assert.equal(result(blocked).pendingAction,'resume');
260
+ // The initial handoff was published within the limit; only the append failed.
261
+ const published=fs.readFileSync(handoffFile(f));
262
+ assert(published.length<=limit,`published ${published.length}`);
263
+ const evidence=JSON.parse(published).evidence;
264
+ assert.equal(evidence.filter(item=>item.includes(LEARNING_PREFIX)).length,0,'Learning was not appended');
265
+ assert.equal(requirementEntries({evidence}).length,1);
266
+ const kinds=()=>records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.kind);
267
+ assert(!kinds().includes('review'),'no review was dispatched');
268
+
269
+ // Smaller evidence on resume: the same attempt redoes its delivery and reaches review.
270
+ const resumed=paddedLiveSession(f,{mode:'resume',commandPad:probePad,items:quoteItems(QUOTE_ITEMS)});
271
+ assert.equal(resumed.status,0,resumed.stderr);
272
+ assert.equal(result(resumed).state,'awaiting_review',resumed.stdout);
273
+ assert.equal(result(resumed).identity.attempt,1);
274
+ assert.deepEqual(records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id),
275
+ ['develop-1','develop-1-retry-1']);
276
+ assert(JSON.parse(fs.readFileSync(handoffFile(f))).evidence.some(item=>item.includes(LEARNING_PREFIX)));
277
+ });
278
+ test('complete under a precheck policy needs no verification runner',async t=>{
279
+ const f=precheckFixture(t);v2Policy(f,{verification:'precheck'});
280
+ const live=f.plan({controlConfig:'POLICY.json',liveEvidence:{directory:'exchange',kinds:['verification_precheck'],timeoutMs:1000}});
281
+ const first=await runLiveDriver(DRIVER,live,'advance',()=>({items:satisfiedItems}),{env:f.env});
282
+ assert.equal(first.status,0,first.stderr);
283
+ const packageDigest=result(first).packageDigest??JSON.stringify(records(f)).match(/"packageDigest":"([a-f0-9]{64})"/)[1];
284
+ // The same run, a PLAN without the verification channel: complete never asks it.
285
+ const out=f.drive(f.plan({controlConfig:'POLICY.json',mode:'resume',packageDigest}),'complete');
286
+ assert.doesNotMatch(out.stderr,/缺少真实执行 runner: verification_precheck/);
287
+ });
288
+
126
289
  // ---- #24 run ID length -------------------------------------------------------------------------
127
290
  test('#24 a run ID shorter than 8 characters is refused before the driver launches a host',t=>{
128
291
  const f=fixture(t,{runId:'short'});f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});