@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
@@ -0,0 +1,242 @@
1
+ // The batch configuration /cm-ai runs, computed from the approved tasks.md
2
+ // instead of written by the session. One feature at a time (the one admission
3
+ // selects). Tasks that can run together share a parallel group. With
4
+ // `worktree_all` (the default) every other task that could be a member gets a
5
+ // group of its own, so it is developed in its own worktree and merged back in
6
+ // task order like any member; the excluded tasks below keep the batch's serial
7
+ // order in the main checkout. The batch host validates the result again
8
+ // (cm-ai-batch-run.mjs validateGroups); this module only proposes.
9
+ //
10
+ // Grouping, greedy in tasks.md order, a group of at most `max` members:
11
+ // - every remaining task declares its files (`- 范围:`); otherwise the whole
12
+ // feature stays serial (an undeclared task cannot be proven independent);
13
+ // - members share no dependency path (transitive), no file, need no device and
14
+ // none is the feature's last task (its QA collects the members' deferred QA);
15
+ // - a member's prerequisites all come before the group's first member, because
16
+ // the whole group starts there.
17
+ // Grammar 3 marks the one task the session develops (`- 开发: 会话`): it must be the
18
+ // feature's last task, so it stays serial; batch.memberDevelopment lists those members
19
+ // ({"feature/T-xxx":"session"}) and is absent when there are none, so such a batch
20
+ // configuration has exactly the bytes it had before.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import {spawnSync} from 'node:child_process';
24
+ import {inspectCmAiAdmission,parseFeatureTaskText} from './cm-ai-admission.mjs';
25
+ import {approvedTaskGrammar} from '../spec-task-line.mjs';
26
+ import {parseTaskScopes,scopesOverlap,sessionTaskProblem,sessionTaskReason,BOOTSTRAP_FEATURE} from '../task-scope.mjs';
27
+ import {need} from './effect-contract.mjs';
28
+ import {featureHasBrowserCases} from './host-workflow-capabilities.mjs';
29
+ import {decideHostQaPolicy,qaUnassessedTaskCounts} from './host-qa-policy.mjs';
30
+ import {findConfig} from '../../../scripts/cm-workflow-config.mjs';
31
+
32
+ // One-member groups (worktree_all) and N6. A task alone in a worktree decides its QA
33
+ // like a serial task and would run a triggered QA in that worktree, where the batch
34
+ // has no QA repair path. So a task gets a one-member group only when, by the same
35
+ // rules the decision uses, it cannot trigger QA there; the planner and the batch
36
+ // host (cm-ai-batch-run.mjs validateGroups) apply these two checks alike.
37
+ //
38
+ // Feature-wide: the worktree must see the same project configuration as the main
39
+ // checkout (QA reloads it there). A worktree is checked out from HEAD, so the main
40
+ // checkout's configuration file must be byte-identical to its HEAD blob: an ignored
41
+ // or untracked file never reaches the worktree, and a skip-worktree/assume-unchanged
42
+ // local override hides from `git status` while the worktree gets the committed one;
43
+ // and no interactive (browser/simulator) case may apply, since that QA may target a
44
+ // server or app built from the main checkout. null, or {code,reason}.
45
+ export function soloWorktreeBlocker({specsDir,codeProject,feature}){
46
+ const file=findConfig(codeProject);
47
+ if(file){
48
+ const name=path.basename(file);
49
+ // cat-file reads the raw committed blob: no filters, no textconv.
50
+ const committed=spawnSync('git',['-c','core.fsmonitor=false','-C',codeProject,'cat-file','blob',`HEAD:./${name}`],
51
+ {timeout:10000,maxBuffer:4*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:'0'}});
52
+ if(committed.error||committed.status!==0)return {code:'parallel_solo_config_untracked',
53
+ reason:`项目配置 ${name} 不在当前提交里(未跟踪,例如被 .gitignore 忽略),worktree 里拿不到这份配置,QA 会按另一套策略执行;提交该配置后再生成批次,或让这些任务在主目录串行`};
54
+ if(!committed.stdout.equals(fs.readFileSync(file)))return {code:'parallel_solo_config_diverged',
55
+ reason:`主目录的项目配置 ${name} 与当前提交里的不同(可能用了 skip-worktree 或 assume-unchanged 保留本地改动),worktree 拿到的是提交里的那份,QA 会按另一套策略执行;让两者一致后再生成批次,或让这些任务在主目录串行`};
56
+ }
57
+ if(featureHasBrowserCases(specsDir,feature,codeProject))return {code:'parallel_solo_interactive_qa',
58
+ reason:`功能 ${feature} 有浏览器等交互式 QA 用例,可能连接主目录启动的服务或 App;单独开 worktree 会验收到未合并的代码`};
59
+ return null;
60
+ }
61
+ // Per task: count is the five_tasks_without_qa count its decision would see, itself
62
+ // included. The changed files are the declared scope plus the Learning targets (a
63
+ // delivery outside the scope is refused as out_of_scope). A reason, or null.
64
+ export function soloQaCheckpoint({scope,count,workflow=null}){
65
+ const changedFiles=[...new Set([...scope,'AGENTS.md',...(workflow?.applicableAgentFiles??[])])];
66
+ const decision=decideHostQaPolicy({changedFiles,criticalPaths:workflow?.qa?.criticalPaths??{},pending:1,mergeEligible:false,
67
+ unassessedTasks:count});
68
+ return decision.status==='triggered'?decision.reason:null;
69
+ }
70
+ // {count,floor} before the batch (qaUnassessedTaskCounts).
71
+ export const soloQaBase=({specsDir,codeProject,feature,repositoryId})=>qaUnassessedTaskCounts({specsDir,codeProject,feature,repositoryId});
72
+
73
+ // The five_tasks_without_qa count along the batch order, as the set of values it may
74
+ // have before the next task. A triggered QA leaves floor counted (tasks with no QA row
75
+ // at all). check() judges the next task by the largest value; then
76
+ // place() records a task in the main checkout ('main') or alone in a worktree ('solo'):
77
+ // - 'solo': check() found no checkpoint, so its QA is skipped (a blocked one reruns in
78
+ // the main checkout with the same count and files, so skipped as well);
79
+ // - 'main': triggered once its count reaches five; below that skipped, unless its scope
80
+ // hits a registered path: then either, since the decision sees the files actually
81
+ // changed. (The batch's final task may trigger feature_complete; none runs after it.)
82
+ // hostDecides: the host policy decides the task's QA (a workflow configuration with qa,
83
+ // or a control policy). Without it the session supplies the decision: either.
84
+ // placeGroup() records a group developed alongside each other: each member defers its
85
+ // QA (skipped), but a blocked member reruns in the main checkout before the group
86
+ // settles and may trigger there, after any of the other members' rows.
87
+ export function soloQaCounter({count,floor}){
88
+ let counts=new Set([count]);
89
+ const check=(scope,workflow=null)=>soloQaCheckpoint({scope,count:Math.max(...counts)+1,workflow});
90
+ const place=(placement,scope,{workflow=null,hostDecides})=>{
91
+ const hits=placement==='main'&&soloQaCheckpoint({scope,count:1,workflow})!==null;
92
+ const next=new Set();
93
+ for(const before of counts){
94
+ const own=before+1;
95
+ if(!hostDecides||hits&&own<5)next.add(floor).add(own);
96
+ else next.add(placement==='main'&&own>=5?floor:own);
97
+ }
98
+ counts=next;
99
+ };
100
+ const placeGroup=size=>{
101
+ const next=new Set([...counts].map(before=>before+size));
102
+ for(let rows=0;rows<size;rows++)next.add(floor+rows);
103
+ counts=next;
104
+ };
105
+ return Object.freeze({check,place,placeGroup});
106
+ }
107
+ // Whether the host policy decides a task's QA under this workflow configuration (a
108
+ // control policy decides it as well; see soloQaCounter).
109
+ export const workflowDecidesQa=workflow=>workflow!==null&&workflow.qa!=null;
110
+
111
+ // worktree_all: every task that could be a group member runs in a worktree, alone
112
+ // when nothing pairs with it. false keeps only real groups (two or more members).
113
+ export const PARALLEL_DEFAULTS=Object.freeze({enabled:true,max:2,worktree_all:true});
114
+ // The project's parallel settings ({enabled,max,worktree_all}); absent keys take the defaults.
115
+ export function parallelSettings(config){
116
+ const value=config?.parallel??{};
117
+ const settings={...PARALLEL_DEFAULTS,...value};
118
+ need(typeof settings.enabled==='boolean'&&Number.isInteger(settings.max)&&settings.max>=1&&settings.max<=4
119
+ &&typeof settings.worktree_all==='boolean','invalid_parallel_settings');
120
+ return Object.freeze(settings);
121
+ }
122
+
123
+ // {mode:'batch',feature,config,groups}, {mode:'serial',feature,reason} or
124
+ // {mode:'complete'} when no task is left; any other admission state refuses with
125
+ // the admission's own reason. Always the feature admission selects: the batch
126
+ // host admits each task through that same selection.
127
+ // workflow: optional single-task workflow configuration (the one the session passes the
128
+ // batch host for these tasks); its qa.criticalPaths and applicableAgentFiles keep tasks
129
+ // that would hit a registered path out of one-member groups, and every member's
130
+ // workflows entry is that configuration (null without one).
131
+ export function planCmAiBatch({specsDir,codeProject,repositoryId,batchId,settings:given=PARALLEL_DEFAULTS,workflow=null}){
132
+ const settings=parallelSettings({parallel:given});
133
+ const admission=inspectCmAiAdmission({specsDir,codeProject});
134
+ if(admission.state==='complete')return {mode:'complete'};
135
+ if(admission.state!=='ready')throw Object.assign(new Error('batch_plan_not_ready'),
136
+ {code:'batch_plan_not_ready',reason:`admission ${admission.state}: ${admission.reason}`});
137
+ const selected=admission.nextTask.feature;
138
+ if(BOOTSTRAP_FEATURE.test(selected))return {mode:'serial',feature:selected,reason:'bootstrap_feature'};
139
+ const grammar=approvedTaskGrammar(specsDir);
140
+ const text=fs.readFileSync(path.join(specsDir,selected,'tasks.md'),'utf8');
141
+ const parsed=parseFeatureTaskText(text,{allowDependencyPunctuation:true,grammar});
142
+ need(!parsed.error,'batch_plan_tasks_invalid');
143
+ const scopes=parseTaskScopes(text,{grammar});
144
+ const sessionProblem=sessionTaskProblem(parsed.tasks,scopes.sessions,parsed.dependencies);
145
+ if(sessionProblem)throw Object.assign(new Error(sessionProblem.code),{code:sessionProblem.code,reason:`${selected}/tasks.md:${sessionTaskReason(sessionProblem)}`});
146
+ const remaining=parsed.tasks.filter(task=>!task.completed&&!task.dropped);
147
+ need(remaining.length>0,'batch_plan_not_ready');
148
+ if(scopes.errors.some(item=>remaining.some(task=>task.id===item.taskId)))return {mode:'serial',feature:selected,reason:'scope_invalid'};
149
+ if(!remaining.every(task=>scopes.tasks.has(task.id)))return {mode:'serial',feature:selected,reason:'scope_undeclared'};
150
+ // The batch runs its tasks in this order and the host admits each one when it is
151
+ // reached, so every task must come after its prerequisites still to run.
152
+ const schedule=executionOrder(remaining,parsed.dependencies);
153
+ if(schedule===null)return {mode:'serial',feature:selected,reason:'dependency_order'};
154
+ // The narrow rule once more on the order the batch really runs: a session task is the
155
+ // feature's last task to run, so nothing may be scheduled after it.
156
+ const lateSession=schedule.findIndex(task=>scopes.sessions.has(task.id));
157
+ if(lateSession!==-1&&lateSession!==schedule.length-1){
158
+ const after=new Set(schedule.slice(lateSession+1).map(task=>task.id));
159
+ const problem={code:'session_task_depended_on',tasks:[schedule[lateSession].id],dependents:parsed.tasks.map(task=>task.id).filter(id=>after.has(id))};
160
+ throw Object.assign(new Error(problem.code),{code:problem.code,reason:`${selected}/tasks.md:${sessionTaskReason(problem)}`});
161
+ }
162
+ need(schedule[0].id===admission.nextTask.id,'batch_plan_order_mismatch');
163
+ // The host requires the feature's last task in every batch with a group (its QA
164
+ // collects the members' deferred QA); a completed last task leaves no such task.
165
+ const lastDone=parsed.tasks.filter(task=>!task.dropped).at(-1)?.completed===true;
166
+ const tasks=schedule.map(task=>({feature:selected,taskId:task.id,scope:[...scopes.tasks.get(task.id).scope],requirements:[]}));
167
+ // One-member groups only where the task cannot trigger QA in its worktree (above);
168
+ // real groups defer their QA to the last task in the main checkout.
169
+ let solo=null;
170
+ if(settings.worktree_all&&!soloWorktreeBlocker({specsDir,codeProject,feature:selected})){
171
+ const counter=soloQaCounter(soloQaBase({specsDir,codeProject,feature:selected,repositoryId}));
172
+ const scope=task=>scopes.tasks.get(task.id).scope;
173
+ // Every task gets the same workflow. Without one (or with qa:null) the plan cannot
174
+ // tell whether the host policy decides QA (the session may), so no certain reset.
175
+ const hostDecides=workflowDecidesQa(workflow);
176
+ solo={alone:task=>counter.check(scope(task),workflow)===null,
177
+ place:(task,placement)=>counter.place(placement,scope(task),{workflow,hostDecides}),
178
+ placeGroup:tasks=>counter.placeGroup(tasks.length)};
179
+ }
180
+ const groups=settings.enabled&&(settings.max>=2||solo)&&!lastDone
181
+ ?group(parsed,schedule,scopes,settings.max,solo):[];
182
+ const key=taskId=>`${selected}/${taskId}`;
183
+ const sessions=tasks.filter(task=>scopes.sessions.has(task.taskId));
184
+ if(groups.some(members=>members.some(id=>scopes.sessions.has(id))))
185
+ throw Object.assign(new Error('session_task_parallel'),{code:'session_task_parallel',reason:`${selected}:会话任务不能进并行组`});
186
+ const config={batch:{version:1,repositoryId,batchId,specsDir,codeProject,tasks,
187
+ ...(groups.length?{parallel:groups.map(members=>members.map(key))}:{}),
188
+ ...(sessions.length?{memberDevelopment:Object.fromEntries(sessions.map(task=>[key(task.taskId),'session']))}:{})},
189
+ workflows:Object.fromEntries(tasks.map(task=>[key(task.taskId),workflow]))};
190
+ return {mode:'batch',feature:selected,config,groups};
191
+ }
192
+
193
+ // tasks.md order, except that a task waits for its prerequisites still to run
194
+ // (stable topological order). null when no order exists (a cycle).
195
+ function executionOrder(remaining,deps){
196
+ const pending=new Set(remaining.map(task=>task.id)),placed=new Set(),order=[];
197
+ while(order.length<remaining.length){
198
+ const next=remaining.find(task=>!placed.has(task.id)&&(deps.get(task.id)??[]).every(dep=>!pending.has(dep)||placed.has(dep)));
199
+ if(!next)return null;
200
+ placed.add(next.id);order.push(next);
201
+ }
202
+ return order;
203
+ }
204
+
205
+ // solo: null (no one-member groups), or alone (whether a task may run alone in a
206
+ // worktree), place and placeGroup (told where each task runs, in the batch order).
207
+ function group(parsed,schedule,scopes,max,solo){
208
+ const deps=parsed.dependencies;
209
+ const reaches=(from,target,seen=new Set())=>{
210
+ if(seen.has(from))return false;seen.add(from);
211
+ const direct=deps.get(from)??[];
212
+ return direct.includes(target)||direct.some(dep=>reaches(dep,target,seen));
213
+ };
214
+ // Neither the feature's last task nor the last one to run can be a member: the
215
+ // task that runs last collects the members' deferred QA serially.
216
+ const last=parsed.tasks.filter(task=>!task.dropped).at(-1)?.id,lastRun=schedule.at(-1)?.id;
217
+ const order=new Map(schedule.map((task,index)=>[task.id,index]));
218
+ const candidate=task=>task.id!==last&&task.id!==lastRun&&!scopes.tasks.get(task.id).device&&!scopes.sessions.has(task.id);
219
+ // The whole group starts at its first member, so every member's prerequisites
220
+ // still to run must come before that point.
221
+ const readyBefore=(task,start)=>(deps.get(task.id)??[]).every(dep=>!order.has(dep)||order.get(dep)<start);
222
+ // A candidate nothing pairs with becomes a one-member group when it may run alone.
223
+ // Members are consecutive in the schedule, so tasks are placed in the batch order.
224
+ const groups=[];let current=[];
225
+ const close=()=>{
226
+ if(current.length>=2){groups.push(current.map(task=>task.id));solo?.placeGroup(current);}
227
+ else if(current.length===1&&solo?.alone(current[0])){groups.push([current[0].id]);solo.place(current[0],'solo');}
228
+ else current.forEach(task=>solo?.place(task,'main'));
229
+ current=[];
230
+ };
231
+ for(const task of schedule){
232
+ if(!candidate(task)){close();solo?.place(task,'main');continue;}
233
+ const fits=current.length>0&&current.length<max&&readyBefore(task,order.get(current[0].id))
234
+ &&current.every(other=>!reaches(task.id,other.id)&&!reaches(other.id,task.id)
235
+ &&!scopesOverlap(scopes.tasks.get(other.id).scope,scopes.tasks.get(task.id).scope));
236
+ if(fits){current.push(task);continue;}
237
+ close();
238
+ if(readyBefore(task,order.get(task.id)))current=[task];else solo?.place(task,'main');
239
+ }
240
+ close();
241
+ return groups;
242
+ }
@@ -0,0 +1,162 @@
1
+ // Pure storage representation only. The runner still validates every restored
2
+ // checkpoint transition, package link, receipt and completion prerequisite.
3
+ import path from 'node:path';
4
+ import {digest,json,shape,need,hex,id,validIdentity,freeze,JOURNAL_PAYLOAD_LIMIT} from './effect-contract.mjs';
5
+
6
+ const INVALID='checkpoint_package_material_invalid',STATE_LIMIT=16*1024*1024;
7
+ const MARKER_ALLOWANCE=1024,REFERENCE_ALLOWANCE=512;
8
+ const must=condition=>need(condition,INVALID);
9
+ const guarded=run=>{try{return run();}catch(error){if(error?.code===INVALID)throw error;throw Object.assign(new Error(INVALID),{code:INVALID});}};
10
+ const size=value=>Buffer.byteLength(JSON.stringify(value));
11
+ const same=(left,right)=>digest(left)===digest(right);
12
+ const sameRun=(left,right)=>same({...left,attempt:right.attempt},right);
13
+ // Representation eligibility is derived from durable execution mode only.
14
+ // It is not scope authority, a recovery grant, or a requirement to revise scope.
15
+ export function packageMaterialEligible(rawConfig,version=3){
16
+ try{const config=json(rawConfig,STATE_LIMIT),policy=config.controlPolicy;
17
+ validIdentity(config.identity);shape(policy,['version','development','bootstrap','qa','qaFix']);
18
+ must(['disabled','run'].includes(policy.qa)&&['disabled','manual','auto'].includes(policy.qaFix)
19
+ &&(policy.qaFix==='disabled'||policy.qa==='run'));
20
+ return version===3&&typeof config.root==='string'&&path.isAbsolute(config.root)
21
+ &&path.resolve(config.root)===config.root&&!config.root.includes('\0')
22
+ &&policy?.version===2&&policy.development==='conversation'&&policy.bootstrap==='disabled'
23
+ &&['bootstrap','providerDevelopment','parallelSelection','parallelMember','batchWorkflowsDigest','codeProjectPaths','codeProjects']
24
+ .every(key=>!Object.hasOwn(config,key));
25
+ }catch{return false;}
26
+ }
27
+ const referenceTypes=['effect-checkpoint','review-invocation-reconciled'];
28
+ const reconciliationKeys=['invocationId','registeredDigest','startedDigest','resultDigest','receiptDigest'];
29
+ function bindingValue(type,raw={}){
30
+ must(referenceTypes.includes(type));const binding=json(raw);
31
+ shape(binding,type==='effect-checkpoint'?[]:reconciliationKeys);
32
+ if(type==='review-invocation-reconciled'){
33
+ id(binding.invocationId);for(const key of reconciliationKeys.slice(1)){
34
+ if(key==='startedDigest'&&binding[key]===null)continue;hex(binding[key]);}
35
+ }
36
+ return binding;
37
+ }
38
+ function storageHeader(payload){
39
+ const common=['effectId','checkpoint','version','protocol','type'];
40
+ shape(payload,[...common,...(payload.type==='review-invocation-reconciled'?reconciliationKeys:[]),
41
+ ...['packageMaterial','packageRef'].filter(key=>Object.hasOwn(payload,key))]);
42
+ bindingValue(payload.type,Object.fromEntries(reconciliationKeys.filter(key=>Object.hasOwn(payload,key)).map(key=>[key,payload[key]])));
43
+ }
44
+ function packageValue(raw,identity){
45
+ const value=json(raw,STATE_LIMIT);validIdentity(identity);validIdentity(value?.identity);
46
+ must(value.version===1&&value.kind==='cm-review-package'&&sameRun(value.identity,identity));hex(value.packageDigest);
47
+ const {packageDigest,...body}=value;must(digest(body)===packageDigest);return value;
48
+ }
49
+ function history(raw,identity){
50
+ validIdentity(identity);const records=json(raw,STATE_LIMIT);must(Array.isArray(records)&&records.length<=1024);
51
+ let previous=null;
52
+ for(const [index,record] of records.entries()){
53
+ shape(record,['version','seq','id','kind','payload','previousDigest','digest']);hex(record.digest);
54
+ const {digest:hash,...body}=record;
55
+ must(record.version===1&&record.seq===index+1&&record.id===`runner.${String(index+1).padStart(6,'0')}`
56
+ &&record.previousDigest===previous&&digest(body)===hash&&size(record.payload)<=JOURNAL_PAYLOAD_LIMIT);
57
+ previous=hash;
58
+ }
59
+ if(records.length){const initial=records[0]?.payload?.config?.identity;validIdentity(initial);
60
+ must(sameRun(initial,identity));}
61
+ return records;
62
+ }
63
+ function checkpointValue(checkpoint,effectId,pkg,identity){
64
+ must(checkpoint&&typeof checkpoint==='object'&&!Array.isArray(checkpoint)&&[1,2].includes(checkpoint.attempt));
65
+ const current=checkpoint.cache?.at(-1);must(current?.effect?.id===effectId);
66
+ validIdentity(current.effect.identity);validIdentity(current.result?.identity);
67
+ must(sameRun(current.effect.identity,identity)&&sameRun(current.result.identity,identity)
68
+ &&current.result.identity.attempt===checkpoint.attempt&&current.result.packageDigest===pkg.packageDigest);
69
+ return current.effect;
70
+ }
71
+ function materialRecord(record,records,index,identity){
72
+ const p=record.payload;must(record.kind==='result'&&p.version===3&&p.protocol==='cm-task-runner'&&p.type==='effect-checkpoint'
73
+ &&p.packageMaterial===true&&!Object.hasOwn(p,'packageRef'));
74
+ const pkg=packageValue(p.checkpoint?.reviewPackage,identity),effect=checkpointValue(p.checkpoint,p.effectId,pkg,identity);
75
+ must(p.checkpoint.state==='awaiting_review'&&effect.kind==='develop'
76
+ &&same(pkg.identity,identity)&&p.checkpoint.attempt===pkg.identity.attempt
77
+ &&same(effect.identity,pkg.identity)&&same(p.checkpoint.cache.at(-1).result.identity,pkg.identity));
78
+ const intent=records.slice(0,index).findLast(row=>row.payload.type==='effect-intent'&&row.payload.effect?.id===p.effectId);
79
+ must(intent?.kind==='intent'&&same(intent.payload.effect,effect));
80
+ return pkg;
81
+ }
82
+ function referenceValue(raw){const ref=json(raw);shape(ref,['recordId','recordDigest','packageDigest']);
83
+ must(typeof ref.recordId==='string'&&/^runner\.[0-9]{6}$/.test(ref.recordId));hex(ref.recordDigest);hex(ref.packageDigest);return ref;}
84
+ function findReference(records,pkg,identity){
85
+ let found=null;
86
+ for(const [index,record] of records.entries())if(Object.hasOwn(record.payload,'packageMaterial')){
87
+ const who=record.payload.checkpoint?.reviewPackage?.identity;validIdentity(who);
88
+ must(sameRun(who,identity));
89
+ const material=materialRecord(record,records,index,who);
90
+ if(material.packageDigest===pkg.packageDigest){must(same(material,pkg));
91
+ found={recordId:record.id,recordDigest:record.digest,packageDigest:material.packageDigest};}
92
+ }
93
+ return found;
94
+ }
95
+ export function packageMaterialReference(rawRecords,rawPackage,identity){return guarded(()=>{
96
+ const records=history(rawRecords,identity),pkg=packageValue(rawPackage,identity);
97
+ return freeze(findReference(records,pkg,identity));
98
+ });}
99
+
100
+ export function resolveCheckpointPackage(rawPayload,rawRecords,identity){return guarded(()=>{
101
+ const payload=json(rawPayload,STATE_LIMIT),material=Object.hasOwn(payload,'packageMaterial'),referenced=Object.hasOwn(payload,'packageRef');
102
+ must(!(material&&referenced));
103
+ // Historic inline payloads retain their exact logical shape and old validator.
104
+ if(!material&&!referenced)return json(payload.checkpoint,STATE_LIMIT);
105
+ const records=history(rawRecords,identity);
106
+ must(payload.version===3&&payload.protocol==='cm-task-runner'&&referenceTypes.includes(payload.type)
107
+ &&size(payload)<=JOURNAL_PAYLOAD_LIMIT);storageHeader(payload);
108
+ if(material){
109
+ must(payload.type==='effect-checkpoint');
110
+ const body={version:1,seq:records.length+1,id:`runner.${String(records.length+1).padStart(6,'0')}`,kind:'result',payload,
111
+ previousDigest:records.at(-1)?.digest??null};
112
+ materialRecord({...body,digest:digest(body)},records,records.length,identity);
113
+ return json(payload.checkpoint,STATE_LIMIT);
114
+ }
115
+ const ref=referenceValue(payload.packageRef);
116
+ must(payload.checkpoint?.reviewPackage===null);
117
+ const index=records.findIndex(record=>record.id===ref.recordId);must(index>=0);
118
+ const record=records[index];must(record.digest===ref.recordDigest);
119
+ const who=record.payload.checkpoint?.reviewPackage?.identity;validIdentity(who);must(sameRun(who,identity));
120
+ const pkg=materialRecord(record,records,index,who);must(pkg.packageDigest===ref.packageDigest);
121
+ const effect=checkpointValue(payload.checkpoint,payload.effectId,pkg,identity);
122
+ if(payload.type==='review-invocation-reconciled')must(effect.kind==='review');
123
+ return json({...payload.checkpoint,reviewPackage:pkg},STATE_LIMIT);
124
+ });}
125
+
126
+ // Conservative driver preflight. Real append validation additionally measures
127
+ // the exact payload/envelope; this does not change any journal or review limit.
128
+ export function checkpointPackageBudget({inlineBytes,packageBytes,reserve,enabled,referenced=false}){return guarded(()=>{
129
+ must([inlineBytes,packageBytes,reserve].every(v=>Number.isSafeInteger(v)&&v>=0)
130
+ &&packageBytes<=inlineBytes&&reserve<JOURNAL_PAYLOAD_LIMIT&&typeof enabled==='boolean'&&typeof referenced==='boolean');
131
+ const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
132
+ if(!enabled||!referenced&&inlineBytes<=budget)return freeze({fits:inlineBytes<=budget,material:false,bytes:inlineBytes,budget});
133
+ const bytes=inlineBytes-packageBytes+REFERENCE_ALLOWANCE,material=!referenced;
134
+ return freeze({fits:bytes<=budget&&(!material||inlineBytes+MARKER_ALLOWANCE<=JOURNAL_PAYLOAD_LIMIT),material,bytes,budget});
135
+ });}
136
+ export function checkpointStoragePlan({records:rawRecords,effectId,checkpoint:rawCheckpoint,identity,enabled,reserve,type='effect-checkpoint',binding:rawBinding={}}){return guarded(()=>{
137
+ must(typeof enabled==='boolean');const checkpoint=json(rawCheckpoint,STATE_LIMIT),records=history(rawRecords,identity);
138
+ must(typeof effectId==='string'&&effectId.length>0);
139
+ const binding=bindingValue(type,rawBinding);
140
+ const payload={effectId,checkpoint,version:3,protocol:'cm-task-runner',type,...binding};
141
+ // Invalid budgets are rejected even for legacy/small packages.
142
+ checkpointPackageBudget({inlineBytes:size(payload),packageBytes:checkpoint.reviewPackage?size(checkpoint.reviewPackage):0,reserve,enabled});
143
+ if(!enabled||checkpoint.reviewPackage===null)return freeze({checkpoint,payloadFields:{}});
144
+ const pkg=packageValue(checkpoint.reviewPackage,identity),effect=checkpointValue(checkpoint,effectId,pkg,identity);
145
+ const ref=findReference(records,pkg,identity);
146
+ // Develop reserved the later checkpoints before accepting its inline package.
147
+ // Those later records enforce their actual limit, not that future reserve again;
148
+ // a review or completion cannot introduce a first material archive.
149
+ if(!ref&&type==='effect-checkpoint'&&['review','complete'].includes(effect.kind)){
150
+ must(size(payload)<=JOURNAL_PAYLOAD_LIMIT);return freeze({checkpoint,payloadFields:{}});
151
+ }
152
+ const budget=checkpointPackageBudget({inlineBytes:size(payload),packageBytes:size(pkg),reserve,enabled,referenced:ref!==null});
153
+ must(budget.fits);
154
+ if(ref){
155
+ const stored={...checkpoint,reviewPackage:null},fields={packageRef:ref};
156
+ const final={...payload,checkpoint:stored,...fields};must(size(final)<=JOURNAL_PAYLOAD_LIMIT);
157
+ resolveCheckpointPackage(final,records,identity);return freeze({checkpoint:stored,payloadFields:fields});
158
+ }
159
+ if(!budget.material)return freeze({checkpoint,payloadFields:{}});
160
+ const fields={packageMaterial:true},final={...payload,...fields};must(size(final)<=JOURNAL_PAYLOAD_LIMIT);
161
+ resolveCheckpointPackage(final,records,identity);return freeze({checkpoint,payloadFields:fields});
162
+ });}
@@ -30,7 +30,12 @@
30
30
  "blocked"
31
31
  ]
32
32
  },
33
- "reason": {"type": ["string", "null"]},
33
+ "reason": {
34
+ "type": [
35
+ "string",
36
+ "null"
37
+ ]
38
+ },
34
39
  "application": {
35
40
  "type": "object",
36
41
  "additionalProperties": false,
@@ -113,6 +118,55 @@
113
118
  ]
114
119
  }
115
120
  }
121
+ },
122
+ "requirements": {
123
+ "type": [
124
+ "array",
125
+ "null"
126
+ ],
127
+ "maxItems": 64,
128
+ "items": {
129
+ "type": "object",
130
+ "additionalProperties": false,
131
+ "required": [
132
+ "requirement",
133
+ "satisfied",
134
+ "evidence"
135
+ ],
136
+ "properties": {
137
+ "requirement": {
138
+ "type": "string"
139
+ },
140
+ "satisfied": {
141
+ "type": "boolean"
142
+ },
143
+ "evidence": {
144
+ "type": "string"
145
+ },
146
+ "run": {
147
+ "type": [
148
+ "string",
149
+ "null"
150
+ ],
151
+ "enum": [
152
+ "red",
153
+ "baseline",
154
+ null
155
+ ]
156
+ },
157
+ "result": {
158
+ "type": [
159
+ "string",
160
+ "null"
161
+ ],
162
+ "enum": [
163
+ "passed",
164
+ "failed",
165
+ null
166
+ ]
167
+ }
168
+ }
169
+ }
116
170
  }
117
171
  }
118
172
  },
@@ -20,11 +20,61 @@ const API_ERROR_CLASSES = Object.freeze({authentication_failed:'reviewer_auth_fa
20
20
  billing_error:'reviewer_billing_error', rate_limit:'reviewer_rate_limited',
21
21
  server_error:'reviewer_server_error', model_not_found:'reviewer_model_not_found'});
22
22
 
23
- export function createClaudeReviewStream(onEvent, onNotice = null) {
24
- let session = null, stage = 'init', value, noticeCount = 0, thinkingCount = 0, rejectedAttempts = 0;
23
+ // Diagnostic enums also name rejected CLI 2.1.x messages. They never extend the
24
+ // accepted stream grammar. Unknown strings, bodies and identifiers stay private.
25
+ const DIAGNOSTIC_TYPES = new Set(['system','assistant','user','result','rate_limit_event',
26
+ 'auth_status','keep_alive','stream_event','tool_progress','tool_use_summary']);
27
+ const DIAGNOSTIC_SUBTYPES = new Set(['init','dev_intent','ui_invalidate','thinking_tokens',
28
+ 'api_retry','hook_started','hook_response','commands_changed','compact_boundary','status',
29
+ 'task_started','task_progress','task_notification','files_persisted','hook_progress',
30
+ 'local_command_output','success','error_during_execution','error_max_turns',
31
+ 'error_max_budget_usd','error_max_structured_output_retries']);
32
+ const DIAGNOSTIC_ERRORS = new Set([...Object.keys(API_ERROR_CLASSES),'invalid_request',
33
+ 'invalid_request_error','api_error','overloaded_error','context_window_exceeded',
34
+ 'context_length_exceeded','prompt_too_long','authentication_error','permission_error',
35
+ 'not_found_error','rate_limit_error','request_too_large','unknown']);
36
+ const diagnosticEnum = (value, allowed) => typeof value !== 'string' ? 'absent'
37
+ : allowed.has(value) ? value : 'other';
38
+ const diagnosticLength = value => typeof value === 'string' ? Math.min(value.length,1_000_001) : 0;
39
+ const httpStatus = value => Number.isInteger(value) && value >= 100 && value <= 599 ? value : null;
40
+ function apiFailureDetail(message) {
41
+ const detail={apiErrorClass:diagnosticEnum(message.error,DIAGNOSTIC_ERRORS),
42
+ apiErrorClassLength:diagnosticLength(message.error),providerErrorClass:'absent',
43
+ httpStatus:httpStatus(message.api_error_status)??httpStatus(message.error_status)??httpStatus(message.status_code),
44
+ errorFlags:[],tokenBudget:null};
45
+ // Inspect only the bounded synthetic API error envelope, extracting fixed
46
+ // classifications and numeric token limits. Never return its original text.
47
+ const content=message.message?.content;
48
+ if(!Array.isArray(content)||content.length!==1||content[0]?.type!=='text'||typeof content[0].text!=='string')return detail;
49
+ const text=content[0].text;
50
+ const prefix=/^API Error: ([1-5][0-9]{2})(?:\s|$)/.exec(text.slice(0,32));
51
+ if(prefix&&detail.httpStatus===null)detail.httpStatus=Number(prefix[1]);
52
+ if(text.length>8192)return detail;
53
+ let errorText=text;
54
+ if(prefix){
55
+ try{
56
+ const body=JSON.parse(text.slice(prefix[0].length));
57
+ detail.providerErrorClass=diagnosticEnum(body?.error?.type,DIAGNOSTIC_ERRORS);
58
+ errorText=typeof body?.error?.message==='string'?body.error.message:'';
59
+ }catch{} // Non-JSON API errors still permit fixed, body-free flags below.
60
+ }
61
+ if(/\bprompt(?: is)? too long\b|\bprompt_too_long\b/i.test(errorText))detail.errorFlags.push('prompt_too_long');
62
+ if(/\bcontext_length_exceeded\b|\bcontext_window_exceeded\b/i.test(errorText))detail.errorFlags.push('context_length_exceeded');
63
+ const budget=/^prompt(?: is)? too long:\s*([0-9]{1,9}) tokens? > ([0-9]{1,9}) maximum\b/i.exec(errorText);
64
+ if(budget)detail.tokenBudget={inputTokens:Number(budget[1]),maximumTokens:Number(budget[2])};
65
+ return detail;
66
+ }
67
+
68
+ export function createClaudeReviewStream(onEvent, onNotice = null, allowedTools = []) {
69
+ const permitted=new Set(allowedTools);
70
+ let session = null, stage = 'init', value, noticeCount = 0, thinkingCount = 0, progressCount = 0, rejectedAttempts = 0, current = null;
25
71
  const pendingTools = new Map(), toolIds = new Set();
26
- const reject = (code, detail = null) => {
27
- stage = 'failed'; throw Object.assign(new Error(code), {code, ...(detail ? {detail} : {})});
72
+ const reject = (code, detail = null, check = code) => {
73
+ const failureDetail={version:1,check,stage,
74
+ eventType:diagnosticEnum(current?.type,DIAGNOSTIC_TYPES),eventTypeLength:diagnosticLength(current?.type),
75
+ eventSubtype:diagnosticEnum(current?.subtype,DIAGNOSTIC_SUBTYPES),eventSubtypeLength:diagnosticLength(current?.subtype),
76
+ noticeCount,thinkingCount,progressCount,...(check==='api_error'?apiFailureDetail(current):{})};
77
+ stage = 'failed'; throw Object.assign(new Error(code), {code, failureDetail, ...(detail ? {detail} : {})});
28
78
  };
29
79
  // Body-free summary of the message that broke the review boundary: which
30
80
  // check (k), message type (m), block type (b), tool name (t), is_error (e).
@@ -34,15 +84,16 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
34
84
  t: typeof tool === 'string' && /^[A-Za-z0-9_.:-]{1,64}$/.test(tool) ? tool : null,
35
85
  e: typeof isError === 'boolean' ? isError : null});
36
86
  const startupNotice = subtype => {
37
- if (noticeCount >= 32) reject('unexpected_event');
87
+ if (noticeCount >= 32) reject('unexpected_event',null,'notice_limit');
38
88
  noticeCount++;
39
89
  if (subtype === 'dev_intent') reportClaudeDevIntentNotice(onNotice);
40
90
  else try { if (typeof onNotice === 'function') onNotice({kind:'claude_system_notice', subtype:'ui_invalidate'}); } catch {}
41
91
  };
42
92
  return Object.freeze({
43
93
  accept(message) {
94
+ current=message;
44
95
  if (!message || typeof message !== 'object' || Array.isArray(message)) reject('invalid_event');
45
- if (stage === 'done' || stage === 'failed') reject('unexpected_event');
96
+ if (stage === 'done' || stage === 'failed') reject('unexpected_event',null,'terminal_stage');
46
97
  if (typeof message.session_id !== 'string' || !message.session_id.trim()
47
98
  || message.session_id.length > 256) reject('invalid_session');
48
99
  if (session !== null && session !== message.session_id) reject('session_mismatch');
@@ -62,7 +113,7 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
62
113
  return;
63
114
  }
64
115
  if (message.type === 'rate_limit_event') {
65
- if (noticeCount >= 32) reject('unexpected_event');
116
+ if (noticeCount >= 32) reject('unexpected_event',null,'notice_limit');
66
117
  noticeCount++;
67
118
  reportClaudeRateLimitNotice(message.rate_limit_info, onNotice);
68
119
  return;
@@ -74,12 +125,13 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
74
125
  }
75
126
  if (message.subtype === 'thinking_tokens') {
76
127
  // Long reviews emit usage heartbeats; worker-claude also caps total output at 1 MB.
77
- if (thinkingCount >= 4096) reject('unexpected_event');
128
+ if (thinkingCount >= 4096) reject('unexpected_event',null,'thinking_limit');
78
129
  thinkingCount++;
79
130
  return;
80
131
  }
81
- if (!['api_retry','hook_started','hook_response','commands_changed'].includes(message.subtype)
82
- || noticeCount >= 32) reject('unexpected_event');
132
+ if (!['api_retry','hook_started','hook_response','commands_changed'].includes(message.subtype))
133
+ reject('unexpected_event',null,'unknown_system_subtype');
134
+ if (noticeCount >= 32) reject('unexpected_event',null,'notice_limit');
83
135
  noticeCount++;
84
136
  // CLI notifications carry no verdict; never forward hook output or command bodies.
85
137
  const notice = {kind:'claude_system_notice', subtype:message.subtype};
@@ -90,13 +142,29 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
90
142
  try { if (typeof onNotice === 'function') onNotice(notice); } catch {}
91
143
  return;
92
144
  }
145
+ if (message.type === 'tool_progress') {
146
+ // A heartbeat belongs only to an already registered, permitted tool in
147
+ // this top-level review turn. Its result must still arrive separately.
148
+ if(stage!=='result')reject('unexpected_event',null,'tool_progress_stage');
149
+ if(message.parent_tool_use_id!==null)reject('unexpected_event',null,'tool_progress_parent');
150
+ if(typeof message.tool_use_id!=='string'||!pendingTools.has(message.tool_use_id))
151
+ reject('unexpected_event',null,'tool_progress_identity');
152
+ const name=pendingTools.get(message.tool_use_id);
153
+ if(message.tool_name!==name||(name!=='StructuredOutput'&&!permitted.has(name)))
154
+ reject('unexpected_event',null,'tool_progress_tool');
155
+ if(!Number.isSafeInteger(message.elapsed_time_seconds)||message.elapsed_time_seconds<0)
156
+ reject('unexpected_event',null,'tool_progress_elapsed');
157
+ if(progressCount>=4096)reject('unexpected_event',null,'tool_progress_limit');
158
+ progressCount++;
159
+ return;
160
+ }
93
161
  if (message.type === 'assistant') {
94
162
  // CLI 2.1.x reports an API failure as a synthetic assistant message with
95
163
  // a string error class, then an is_error result. Before any tool call it
96
164
  // carries no verdict: stop with the class so the user knows what to fix.
97
165
  if (typeof message.error === 'string' && message.parent_tool_use_id === null
98
166
  && message.message?.role === 'assistant' && toolIds.size === 0) {
99
- reject(Object.hasOwn(API_ERROR_CLASSES, message.error) ? API_ERROR_CLASSES[message.error] : 'reviewer_api_error');
167
+ reject(Object.hasOwn(API_ERROR_CLASSES, message.error) ? API_ERROR_CLASSES[message.error] : 'reviewer_api_error',null,'api_error');
100
168
  }
101
169
  if (message.parent_tool_use_id !== null || message.error != null
102
170
  || message.message?.role !== 'assistant') reject('unexpected_assistant');
@@ -140,7 +208,7 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
140
208
  || pendingTools.size !== 0) {
141
209
  reject('unexpected_tool_or_content', summary('user_content', 'user', content?.[0]));
142
210
  }
143
- if (noticeCount >= 32) reject('unexpected_event');
211
+ if (noticeCount >= 32) reject('unexpected_event',null,'notice_limit');
144
212
  noticeCount++;
145
213
  try { if (typeof onNotice === 'function') onNotice({kind:'claude_system_notice', subtype:'synthetic_user'}); } catch {}
146
214
  return;
@@ -152,7 +220,7 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
152
220
  if (block?.type !== 'tool_result') reject('unexpected_tool_or_content', summary('user_content', 'user', block));
153
221
  if (!pendingTools.has(block.tool_use_id)) reject('unexpected_tool_or_content', summary('unknown_tool_result', 'user', block));
154
222
  const name = pendingTools.get(block.tool_use_id);
155
- if (name !== 'StructuredOutput' && block.is_error !== true) {
223
+ if (name !== 'StructuredOutput' && !permitted.has(name) && block.is_error !== true) {
156
224
  // A successful non-StructuredOutput tool is a real boundary break.
157
225
  reject('unexpected_tool_or_content', summary('tool_result_not_error', 'user', block, name, block.is_error));
158
226
  }
@@ -174,9 +242,10 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
174
242
  onEvent({event:'turn.completed', item_type:null});
175
243
  return;
176
244
  }
177
- reject('unexpected_event');
245
+ reject('unexpected_event',null,'unknown_message_type');
178
246
  },
179
247
  finish() {
248
+ current=null;
180
249
  if (stage !== 'done') reject('incomplete_result');
181
250
  return {status:'succeeded', value};
182
251
  },