@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,214 @@
1
+ // Host-owned copy and narrowly scoped review tools. Never runs in the source tree.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import {createHash} from 'node:crypto';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {digest,need,shape,json} from '../cm-ai/effect-contract.mjs';
8
+ import {readReviewVerification,verificationPath,inspectReviewVerificationEvidence,bindVerificationFiles} from './review-verification-contract.mjs';
9
+ import {ownedProcessCleanup} from '../cm-ai/owned-process-cleanup.mjs';
10
+ import {runVerificationCommand,writeInsideCopy} from './review-verification-command.mjs';
11
+ import {verificationFailure,verificationFailureCode,bindVerificationDiagnostic} from './review-verification-diagnostic.mjs';
12
+ const sha=b=>createHash('sha256').update(b).digest('hex');
13
+ function readPage(file,offset=0){
14
+ const data=file.data;
15
+ // Cursors count UTF-8 bytes, never UTF-16 code units. Refuse a cursor inside
16
+ // a character and back off the end so each bounded page decodes losslessly.
17
+ need(Number.isSafeInteger(offset)&&offset>=0&&offset<=data.length
18
+ &&(offset===data.length||(data[offset]&192)!==128),'review_verification_offset');
19
+ let end=Math.min(offset+16384,data.length);
20
+ while(end<data.length&&(data[end]&192)===128)end--;
21
+ const bytes=data.subarray(offset,end),content=bytes.toString('utf8');
22
+ need(Buffer.from(content).equals(bytes),'review_verification_encoding');
23
+ return {path:file.path,content,sha256:file.sha256,offset,nextOffset:end<data.length?end:null,totalBytes:data.length};
24
+ }
25
+ function read(root,p){
26
+ verificationPath(p);let target=root;
27
+ for(const part of p.split('/')){target=path.join(target,part);need(!fs.lstatSync(target).isSymbolicLink(),'review_verification_path');}
28
+ const st=fs.lstatSync(target);need(st.isFile()&&st.nlink===1&&st.size<=2*1024*1024,'review_verification_path');
29
+ const data=fs.readFileSync(target);return {path:p,sha256:sha(data),mode:st.mode&511,data};
30
+ }
31
+ const record=({data,...r})=>r;
32
+ function manifest(root,config){let bytes=0;return config.files.map(p=>{let f;try{f=read(root,p);}catch(e){if(e.code!=='ENOENT')throw e;f={path:p,sha256:null,mode:null,data:null};}bytes+=f.data?.length??0;need(bytes<=16*1024*1024,'review_verification_limit');return f;});}
33
+ export function assertVerificationIsolation(){need(process.platform==='darwin'&&fs.existsSync('/usr/bin/sandbox-exec'),'review_verification_isolation_unavailable');}
34
+ export function validateReviewVerificationInputs({codeProject,configuration,reviewPackage}){
35
+ assertVerificationIsolation();const config=readReviewVerification(configuration);
36
+ need(fs.realpathSync(codeProject)===codeProject,'review_verification_path');
37
+ const files=manifest(codeProject,config);bindVerificationFiles(files.map(record),reviewPackage);
38
+ return files;
39
+ }
40
+ export function createReviewVerificationSession({codeProject,configuration,request}){
41
+ const config=readReviewVerification(configuration),pkg=request.payload.reviewPackage;
42
+ const files=validateReviewVerificationInputs({codeProject,configuration:config,reviewPackage:pkg}),records=files.map(record);
43
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-verification-'))),cwd=path.join(root,'project');fs.mkdirSync(cwd,{mode:448});
44
+ for(const f of files){if(f.data===null)continue;const target=path.join(cwd,f.path);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,f.data,{mode:f.mode});}
45
+ const activePath=path.join(root,'active-command.json');
46
+ const options={configuration:config,cwd,files:records,requestDigest:request.requestDigest,packageDigest:pkg.packageDigest,activePath};
47
+ const configPath=path.join(root,'tools.json'),evidencePath=path.join(root,'evidence.json');
48
+ fs.writeFileSync(configPath,JSON.stringify({...options,evidencePath}),{mode:384});
49
+ const diagnosticPath=path.join(root,'diagnostic.json');
50
+ const tools=createVerificationTools({...options,evidencePath,diagnosticPath});
51
+ const diagnostic=(providerThreadId,error,phase='finish')=>{
52
+ let failure;
53
+ const code=verificationFailureCode(error);
54
+ // Current boundary failures outrank earlier tool failures. Only incomplete
55
+ // evidence needs the first still-unresolved tool diagnostic.
56
+ if(['review_verification_evidence','review_verification_check_failed','review_verification_baseline_failed'].includes(code)&&fs.existsSync(diagnosticPath))
57
+ failure=JSON.parse(fs.readFileSync(diagnosticPath,'utf8'))[0];
58
+ if(!failure){
59
+ let code=verificationFailureCode(error);
60
+ if(code==='review_verification_evidence'&&fs.existsSync(evidencePath)){
61
+ const evidence=JSON.parse(fs.readFileSync(evidencePath,'utf8'));
62
+ code=evidence.checks.length<config.checks.length?'review_verification_check_missing':'review_verification_mutation_missing';
63
+ }
64
+ failure=verificationFailure({phase,code});
65
+ }
66
+ return bindVerificationDiagnostic(failure,{request,configuration:config,providerThreadId});
67
+ };
68
+ return {cwd,configPath,transport:{cwd,mcpConfig:JSON.stringify({mcpServers:{cm_review:{command:process.execPath,args:[fileURLToPath(new URL('./review-verification-server.mjs',import.meta.url)),configPath]}}})},
69
+ prompt:`\nUse only the cm_review tools. This is an isolated verification copy, not the source project. Read relevant files with read_file. The ONLY callable check IDs and commands are ${JSON.stringify(config.checks)}. Package checks may have different labels; never use those labels as tool IDs. Run EVERY registered check by its exact tool ID. Then use mutate_check with an exact unique find/replace on one allowed implementation path (${config.mutationPaths.join(', ')}), selecting a check that detects that defect. The host executes baseline, mutation and exact restoration checks. A successful verdict requires all baseline checks and at least one killed and restored mutation. Do not claim a test was executed based on text. Tool failure or unsupported required checks are missing evidence, never success. No other tools or changes to the original project are allowed.\n`,
70
+ call:tools.call,diagnostic,
71
+ finish(providerThreadId){
72
+ try{
73
+ need(!fs.existsSync(activePath),'review_verification_cleanup');
74
+ need(digest(manifest(codeProject,config).map(record))===digest(records),'review_verification_source_drift');
75
+ need(digest(manifest(cwd,config).map(record))===digest(records),'review_verification_copy_drift');
76
+ const raw=JSON.parse(fs.readFileSync(evidencePath,'utf8'));
77
+ return inspectReviewVerificationEvidence({...raw,providerThreadId},{request,configuration:config,providerThreadId});
78
+ }catch(error){error.verificationDiagnostic=diagnostic(providerThreadId,error);throw error;}
79
+ },
80
+ async close(){
81
+ if(fs.existsSync(activePath)){
82
+ const {pid}=JSON.parse(fs.readFileSync(activePath,'utf8'));need(Number.isInteger(pid)&&pid>0,'review_verification_cleanup');
83
+ try{await ownedProcessCleanup({pid,kill:()=>{}})();}
84
+ catch(error){
85
+ // A possibly live process still owns this private copy; retain it explicitly.
86
+ try{process.stderr.write(JSON.stringify({diagnostic:'review_verification_cleanup_unknown',retainedDirectory:root})+'\n');}catch{}
87
+ throw error;
88
+ }
89
+ }
90
+ fs.rmSync(root,{recursive:true,force:true});}};
91
+ }
92
+ // The previous direct write, kept for injected (non-sandboxed) command runners.
93
+ function hostWrite({cwd,file,data,mode}){
94
+ const target=path.join(cwd,file);
95
+ if(mode===null)fs.writeFileSync(target,data);else{fs.writeFileSync(target,data);fs.chmodSync(target,mode);}
96
+ }
97
+ export function createVerificationTools({configuration,cwd,files,requestDigest,packageDigest,evidencePath,activePath,diagnosticPath=path.join(path.dirname(evidencePath),'diagnostic.json'),runCommand=runVerificationCommand,
98
+ // Real commands may leave an escaped descendant behind; their copy writes then go through the sandbox too.
99
+ writeFile=runCommand===runVerificationCommand?writeInsideCopy:hostWrite}){
100
+ const c=readReviewVerification(configuration);let calls=0,busy=false;
101
+ const checks=new Map(),mutations=[];
102
+ const failures=()=>fs.existsSync(diagnosticPath)?JSON.parse(fs.readFileSync(diagnosticPath,'utf8')):[];
103
+ const saveFailures=items=>{
104
+ const temporary=diagnosticPath+'.tmp';fs.writeFileSync(temporary,JSON.stringify(items),{mode:384});fs.renameSync(temporary,diagnosticPath);
105
+ };
106
+ const note=failure=>{
107
+ const items=failures();
108
+ if(!items.some(item=>item.phase===failure.phase&&item.checkId===failure.checkId))saveFailures([...items,failure].slice(0,32));
109
+ };
110
+ // A successful operation supersedes rejected tool inputs. Mutation evidence
111
+ // is global: one killed/restored mutation resolves prior surviving attempts.
112
+ const clearFailure=(id,{mutation=false}={})=>saveFailures(failures().filter(item=>
113
+ !(item.phase==='worker'&&item.checkId===null)&&!(mutation&&item.phase==='mutation')
114
+ &&(item.checkId!==id||!mutation&&item.phase==='mutation')));
115
+ const resultCode=(result,fallback)=>result.outcome==='unavailable'?verificationFailureCode(result):fallback;
116
+ const invalidate=id=>{checks.delete(id);for(let i=mutations.length-1;i>=0;i--)if(mutations[i].checkId===id)mutations.splice(i,1);};
117
+ const persist=()=>{
118
+ const e={version:1,requestDigest,packageDigest,profileDigest:digest(c),providerThreadId:'pending',files,snapshotDigest:digest(files),checks:c.checks.filter(x=>checks.has(x.id)).map(x=>checks.get(x.id)),mutations};
119
+ const tmp=evidencePath+'.tmp';fs.writeFileSync(tmp,JSON.stringify(e),{mode:384});fs.renameSync(tmp,evidencePath);
120
+ };
121
+ const resetExtras=(dir=cwd)=>{
122
+ for(const name of fs.readdirSync(dir)){
123
+ const full=path.join(dir,name),relative=path.relative(cwd,full);
124
+ if(c.files.includes(relative))continue;
125
+ const st=fs.lstatSync(full);
126
+ if(st.isDirectory()&&!st.isSymbolicLink()&&c.files.some(p=>p.startsWith(relative+'/')))resetExtras(full);
127
+ else fs.rmSync(full,{recursive:true,force:true});
128
+ }
129
+ };
130
+ const same=()=>need(digest(manifest(cwd,c).map(record))===digest(files),'review_verification_copy_drift');
131
+ const run=async(check,signal)=>{need(!fs.existsSync(activePath),'review_verification_cleanup');resetExtras();try{return await runCommand({cwd,command:check.command,timeoutMs:c.timeoutMs,signal,
132
+ onSpawn:pid=>{const tmp=activePath+'.tmp';fs.writeFileSync(tmp,JSON.stringify({pid}),{mode:384});fs.renameSync(tmp,activePath);},
133
+ onClose:()=>fs.rmSync(activePath,{force:true})});}finally{resetExtras();}};
134
+ persist();
135
+ return {async call(name,raw,signal=new AbortController().signal){
136
+ need(!busy&&++calls<=32,'review_verification_limit');busy=true;
137
+ try{
138
+ need(!fs.existsSync(activePath),'review_verification_cleanup');
139
+ const a=json(raw,32768);same();
140
+ if(name==='read_file'){
141
+ shape(a,Object.hasOwn(a,'offset')?['path','offset']:['path']);need(c.files.includes(a.path),'review_verification_path');
142
+ return readPage(read(cwd,a.path),Object.hasOwn(a,'offset')?a.offset:0);
143
+ }
144
+ if(name==='run_check'){
145
+ shape(a,['id']);const check=c.checks.find(c=>c.id===a.id);need(check,'review_verification_check');
146
+ const startedAt=Date.now(),result=await run(check,signal);same();
147
+ if(result.outcome==='passed'){clearFailure(a.id);checks.set(a.id,{id:a.id,commandDigest:digest(check.command),exitCode:0,outputSha256:sha(result.output),startedAt,endedAt:Date.now()});}
148
+ else{invalidate(a.id);note(verificationFailure({phase:'check',code:resultCode(result,'review_verification_check_failed'),checkId:a.id,result}));}persist();return result;
149
+ }
150
+ need(name==='mutate_check','review_verification_tool');shape(a,['path','find','replace','checkId']);
151
+ need(c.mutationPaths.includes(a.path)&&typeof a.find==='string'&&a.find.length>0&&typeof a.replace==='string'
152
+ &&a.find!==a.replace&&a.find.length+a.replace.length<=16384&&mutations.length<8,'review_verification_mutation');
153
+ const check=c.checks.find(c=>c.id===a.checkId);need(check,'review_verification_check');
154
+ const f=read(cwd,a.path),text=f.data.toString('utf8');need(Buffer.from(text).equals(f.data)&&text.split(a.find).length===2,'review_verification_mutation');
155
+ const changed=Buffer.from(text.replace(a.find,a.replace)),startedAt=Date.now();
156
+ invalidate(a.checkId);persist();
157
+ const baseline=await run(check,signal);same();
158
+ if(baseline.outcome!=='passed')note(verificationFailure({phase:'baseline',code:resultCode(baseline,'review_verification_baseline_failed'),checkId:a.checkId,result:baseline}));
159
+ need(baseline.outcome==='passed','review_verification_baseline_failed');
160
+ clearFailure(a.checkId);
161
+ let mutated,restored;
162
+ try{
163
+ writeFile({cwd,file:a.path,data:changed,mode:null});
164
+ mutated=await run(check,signal);
165
+ const expected=files.map(r=>r.path===a.path?{...r,sha256:sha(changed)}:r);
166
+ need(digest(manifest(cwd,c).map(record))===digest(expected),'review_verification_copy_drift');
167
+ }finally{
168
+ // Refuse a replaced path; do not follow a test-created link during restoration.
169
+ read(cwd,a.path);writeFile({cwd,file:a.path,data:f.data,mode:f.mode});same();
170
+ }
171
+ need(!signal.aborted,'cancelled');restored=await run(check,signal);same();
172
+ const killed=mutated.outcome==='failed'&&Number.isInteger(mutated.exitCode)&&mutated.exitCode>0&&restored.outcome==='passed';
173
+ if(restored.outcome==='passed')checks.set(a.checkId,{id:a.checkId,commandDigest:digest(check.command),exitCode:0,outputSha256:sha(restored.output),startedAt,endedAt:Date.now()});
174
+ if(killed){clearFailure(a.checkId,{mutation:true});mutations.push({path:a.path,beforeSha256:f.sha256,afterSha256:sha(changed),checkId:a.checkId,baselineExitCode:0,
175
+ mutatedExitCode:mutated.exitCode,restoredExitCode:restored.exitCode,restoredSha256:read(cwd,a.path).sha256,startedAt,endedAt:Date.now()});}
176
+ if(restored.outcome!=='passed')note(verificationFailure({phase:'restore',code:resultCode(restored,'review_verification_restore_failed'),checkId:a.checkId,result:restored}));
177
+ else if(!killed)note(verificationFailure({phase:'mutation',code:resultCode(mutated,'review_verification_mutation_survived'),checkId:a.checkId,result:mutated}));
178
+ persist();return {killed,baseline,mutated,restored};
179
+ }catch(error){if(failures().length===0)note(verificationFailure({phase:'worker',code:verificationFailureCode(error)}));throw error;}finally{busy=false;}
180
+ }};
181
+ }
182
+
183
+ // Capability qualification runs fixed baselines only in a private snapshot. It
184
+ // never dispatches a provider, writes an owner record or invents a mutation.
185
+ export async function verifyReviewVerificationBaseline({codeProject,configuration,reviewPackage,signal=new AbortController().signal}){
186
+ const config=readReviewVerification(configuration);
187
+ const request={provider:'claude',requestDigest:digest({packageDigest:reviewPackage.packageDigest,profile:config}),payload:{reviewPackage}};
188
+ let session,result,failure,phase='snapshot';
189
+ try{
190
+ session=createReviewVerificationSession({codeProject,configuration:config,request});phase='check';
191
+ for(const check of config.checks){
192
+ const result=await session.call('run_check',{id:check.id},signal);
193
+ if(result.outcome!=='passed'){
194
+ const error=Object.assign(new Error('review_verification_check_failed'),{code:'review_verification_check_failed'});
195
+ error.verificationDiagnostic=session.diagnostic(null,error,'check');throw error;
196
+ }
197
+ }
198
+ const source=manifest(codeProject,config).map(record),copy=manifest(session.cwd,config).map(record);
199
+ need(digest(source)===digest(copy),'review_verification_source_drift');
200
+ const evidence=JSON.parse(fs.readFileSync(path.join(path.dirname(session.cwd),'evidence.json'),'utf8'));
201
+ need(digest(source)===evidence.snapshotDigest,'review_verification_source_drift');
202
+ result={files:source,snapshotDigest:digest(source),checks:evidence.checks};
203
+ }catch(error){
204
+ failure=error;
205
+ failure.verificationDiagnostic=session?session.diagnostic(null,error,phase):
206
+ bindVerificationDiagnostic(verificationFailure({phase,code:verificationFailureCode(error)}),{request,configuration:config});
207
+ }finally{
208
+ try{await session?.close();}catch(error){
209
+ error.cause=failure;failure=error;
210
+ failure.verificationDiagnostic=bindVerificationDiagnostic(verificationFailure({phase:'cleanup',code:verificationFailureCode(error)}),{request,configuration:config});
211
+ }
212
+ }
213
+ if(failure)throw failure;return result;
214
+ }
@@ -0,0 +1,65 @@
1
+ // A single, explicit source transition inside the existing verification recovery budget.
2
+ // The original configuration and review result remain immutable.
3
+ import {digest,json,need,shape} from '../cm-ai/effect-contract.mjs';
4
+ import {readFixCausePackage} from './cause-package.mjs';
5
+ import {inspectFixReproduction} from './reproduce.mjs';
6
+ import {createTypeImportCorrection,inspectTypeImportCorrection,applyTypeImportCorrection} from './type-import-correction.mjs';
7
+ import {readReviewBaseline} from '../cm-ai/review-package.mjs';
8
+ import {verificationRecoveryTarget,inspectRecoveryBaseline,VERIFICATION_RECOVERY} from './review-verification-recovery.mjs';
9
+ import {createReviewVerificationSession,verifyReviewVerificationBaseline} from './review-verification.mjs';
10
+ export const SOURCE_INTENT=`${VERIFICATION_RECOVERY}-source-intent`;
11
+ export const SOURCE_RESULT=`${VERIFICATION_RECOVERY}-source-result`;
12
+ export const sourceIntent=records=>records.find(r=>r.id===SOURCE_INTENT)??null;
13
+ export const sourceResult=records=>records.find(r=>r.id===SOURCE_RESULT)??null;
14
+ export const sourceRevision=(target)=>({previousPackageDigest:target.packageDigest,correctionDigest:digest(target.sourceCorrection),
15
+ path:target.sourceCorrection.path,beforeSha256:target.sourceCorrection.before.sha256,afterSha256:target.sourceCorrection.after.sha256});
16
+ export function sourceRecoveryTarget(context,correction){
17
+ const pkg=readFixCausePackage(context.registration.payload.request.payload.reviewPackage),c=inspectTypeImportCorrection(correction),config=context.configuration;
18
+ need(context.phase==='cause_review'&&pkg.identity.attempt===1&&!config.qaSource&&!config.testAuthor?.visual
19
+ &&!context.records.some(r=>/^(?:fix-(?:test-author|red-test|repair|rediagnosis|observation)|fix-verification-recovery-source)/.test(r.id)), 'fix_source_correction_unavailable');
20
+ need(config.reproduction.command&&!pkg.correction&&!pkg.rediagnosis&&!pkg.sourceRevision,'fix_source_correction_unavailable');
21
+ const checked=createTypeImportCorrection({file:c.before,declaration:{kind:c.kind,path:c.path,beforeSha256:c.before.sha256,typeNames:c.typeNames},scope:config.repair.scope,verification:config.reviewVerification,reviewPackage:pkg});
22
+ need(digest(c)===digest(checked),'fix_source_correction_binding');
23
+ const files=context.baseline.files,checks=config.reviewVerification.checks.map(c=>({id:c.id,commandDigest:digest(c.command),exitCode:0}));
24
+ const target=verificationRecoveryTarget({...context,baseline:{files,snapshotDigest:digest(files),checks}});
25
+ return json({...target,sourceCorrection:c},128*1024);
26
+ }
27
+ export function inspectSourceIntent(value,context){
28
+ shape(value,['target','reason','previousInvocationStopped']);
29
+ need(value.previousInvocationStopped===true&&typeof value.reason==='string'&&value.reason.trim()&&Buffer.byteLength(value.reason)<=1000&&!/[\r\n\0\u0085\u2028\u2029]/.test(value.reason),'fix_verification_recovery_confirmation');
30
+ const expected=sourceRecoveryTarget({...context,baseline:{files:value.target.files}},value.target.sourceCorrection);
31
+ need(digest(expected)===digest(value.target),'fix_source_correction_binding');return value;
32
+ }
33
+ export function successorPackage(original,target,reproduction){
34
+ const {packageDigest,...body}=readFixCausePackage(original),c=inspectTypeImportCorrection(target.sourceCorrection);
35
+ need(packageDigest===target.packageDigest,'fix_source_correction_binding');
36
+ body.files=body.files.map(f=>f.path===c.path?c.after:f);body.reproduction=reproduction;body.sourceRevision=sourceRevision(target);
37
+ return readFixCausePackage({...body,packageDigest:digest(body)});
38
+ }
39
+ export function inspectSourceResult(value,intent,configuration,original){
40
+ shape(value,['intentDigest','reproduction','baseline','package']);
41
+ need(value.intentDigest===digest(intent),'fix_source_correction_binding');
42
+ inspectFixReproduction(value.reproduction,configuration.reproduction,{requireAttempts:true});
43
+ need(value.reproduction.status==='reproduced','fix_source_correction_reproduction_changed');
44
+ const pkg=successorPackage(original,intent.target,value.reproduction);
45
+ need(digest(value.package)===digest(pkg),'fix_source_correction_binding');
46
+ inspectRecoveryBaseline(value.baseline,configuration.reviewVerification,pkg);
47
+ const expected=intent.target.files.map(f=>f.path===intent.target.sourceCorrection.path?{path:f.path,sha256:intent.target.sourceCorrection.after.sha256,mode:intent.target.sourceCorrection.after.mode}:f);
48
+ need(digest(expected)===value.baseline.snapshotDigest,'fix_source_correction_drift');return value;
49
+ }
50
+ export async function previewSourceCorrection({codeProject,configuration,original,target}){
51
+ // Reuse the existing private-copy and fixed-command sandbox. No provider or owner writes.
52
+ const session=createReviewVerificationSession({codeProject,configuration,request:{requestDigest:digest(target),payload:{reviewPackage:original}}});
53
+ try{
54
+ applyTypeImportCorrection({root:session.cwd,correction:target.sourceCorrection});
55
+ const pkg=successorPackage(original,target,original.reproduction);
56
+ return await verifyReviewVerificationBaseline({codeProject:session.cwd,configuration,reviewPackage:pkg});
57
+ }finally{await session.close();}
58
+ }
59
+ export function sourceCorrectionReviewBaseline(raw,correction){
60
+ const c=inspectTypeImportCorrection(correction),{baselineDigest,...body}=readReviewBaseline(raw);
61
+ const before=body.files.find(f=>f.path===c.path),metadata=f=>{const {contentBase64,...rest}=f;return rest;};
62
+ need(body.scope.includes(c.path)&&before&&digest(metadata(before))===digest(metadata(c.after)),'fix_source_correction_baseline');
63
+ body.files=body.files.map(f=>f.path===c.path?c.before:f);
64
+ return readReviewBaseline({...body,baselineDigest:digest(body)});
65
+ }
@@ -39,9 +39,12 @@ export function startFixRun({specsRoot,identity,configuration}){
39
39
  log('run_start','Initial JS fix stages started',{});
40
40
  log('task_start','JS defect task started',{});
41
41
  for(const [role,route] of Object.entries(routes)){
42
- log('decision',`Current conversation fix role: ${role}`,{role,adapter:route.adapter,
43
- requested_model:route.model,source:route.source,purpose:'fix',route_state:route.route_state},'route');
44
- if(!['current-runtime','local-tool'].includes(route.route_state))
42
+ const selected=role==='reviewer'&&configuration.reviewRuntime;
43
+ // Selection is not evidence of dispatch; the invocation records establish that later.
44
+ log('decision',selected?'Independent review tool selected; dispatch has not occurred':`Current conversation fix role: ${role}`,
45
+ {role,adapter:route.adapter,requested_model:route.model,source:route.source,purpose:'fix',route_state:route.route_state,
46
+ ...(selected?{review_runtime:configuration.reviewRuntime,outcome:'selected_not_dispatched'}:{})},'route');
47
+ if(!selected&&!['current-runtime','local-tool'].includes(route.route_state))
45
48
  log('degrade','Requested fix adapter not invoked; current conversation only',
46
49
  {role,adapter:route.adapter,route_state:route.route_state,outcome:'current_conversation_only'});
47
50
  }
@@ -0,0 +1,86 @@
1
+ // Pure, explicit callback annotation. The owner separately binds scope/history.
2
+ // Emit equivalence is a runtime-byte proof, not a TypeScript type-correctness proof.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import * as nodeModule from 'node:module';
6
+ import {createHash,randomUUID} from 'node:crypto';
7
+ import {digest,json,need,shape,hex} from '../cm-ai/effect-contract.mjs';
8
+ import {readReviewSourceRecords,readReviewSourceFiles} from '../cm-ai/review-package.mjs';
9
+ import {validateDeveloperScope} from '../cm-ai/developer-adapter.mjs';
10
+ import {verificationPath} from './review-verification-contract.mjs';
11
+
12
+ const sha=b=>createHash('sha256').update(b).digest('hex');
13
+ const identifier=/^[A-Za-z_$][A-Za-z0-9_$]*$/;
14
+ function sourcePath(value){
15
+ verificationPath(value);validateDeveloperScope([value]);
16
+ need(/\.(?:spec|test)\.tsx?$/.test(value),'test_type_correction_path');
17
+ }
18
+ function emit(prefix){
19
+ need(Number(process.versions.node.split('.')[0])>=24&&typeof nodeModule.stripTypeScriptTypes==='function','test_type_correction_runtime');
20
+ try{return nodeModule.stripTypeScriptTypes(prefix,{mode:'transform'});}
21
+ catch{need(false,'test_type_correction_syntax');}
22
+ }
23
+ function derive(before,{line,parameter,annotation}){
24
+ sourcePath(before.path);
25
+ need(Number.isSafeInteger(line)&&line>=1&&typeof parameter==='string'&&identifier.test(parameter),'test_type_correction_declaration');
26
+ need(typeof annotation==='string'&&annotation.trim().length>0&&annotation===annotation.trim()
27
+ &&Buffer.byteLength(annotation)<=256&&/^[A-Za-z0-9_$ \t.,:[\]?|&(){}<>"';-]+$/.test(annotation)
28
+ &&!/\b(?:any|unknown|as|satisfies|import|asserts|typeof|new|this|extends|infer|keyof)\b/.test(annotation),'test_type_correction_annotation');
29
+ const bytes=Buffer.from(before.contentBase64,'base64'),text=bytes.toString('utf8');
30
+ need(Buffer.from(text).equals(bytes)&&!/[\0\u2028\u2029]/.test(text),'test_type_correction_syntax');
31
+ const lines=text.split('\n');need(line<=lines.length,'test_type_correction_declaration');
32
+ const selected=lines[line-1],escaped=parameter.replace(/[$]/g,'\\$');
33
+ const pattern=new RegExp(`(?<![\\p{ID_Continue}$\\u200c\\u200d])${escaped}([ \\t]*)=>`,'gu');
34
+ const matches=[...selected.matchAll(pattern)];need(matches.length===1,'test_type_correction_match');
35
+ const match=matches[0],replacement=`(${parameter}: ${annotation})${match[1]}=>`;
36
+ const corrected=selected.slice(0,match.index)+replacement+selected.slice(match.index+match[0].length);
37
+ const prefix=lines.slice(0,line).join('\n'),afterPrefix=[...lines.slice(0,line-1),corrected].join('\n'),emitted=emit(prefix);
38
+ need(emit(afterPrefix)===emitted,'test_type_correction_emit_changed');
39
+ // A match in erased type-only material is not an executable callback. Renaming
40
+ // its parameter must alter emitted JS; this also rejects type-literal strings.
41
+ let probe='__cm_type_parameter_probe__';while(prefix.includes(probe))probe+='_';
42
+ const probeLine=selected.slice(0,match.index)+probe+selected.slice(match.index+parameter.length);
43
+ need(emit([...lines.slice(0,line-1),probeLine].join('\n'))!==emitted,'test_type_correction_match');
44
+ const output=Buffer.from([...lines.slice(0,line-1),corrected,...lines.slice(line)].join('\n'));
45
+ const after=readReviewSourceRecords([{...before,size:output.length,sha256:sha(output),contentBase64:output.toString('base64')}])[0];
46
+ return {after,emitSha256:sha(emitted)};
47
+ }
48
+ export function createTestTypeCorrection({file,declaration}){
49
+ const before=readReviewSourceRecords([file])[0],d=json(declaration);
50
+ shape(d,['kind','path','beforeSha256','line','parameter','annotation']);hex(d.beforeSha256);
51
+ need(d.kind==='callback-type-annotation'&&d.path===before.path&&d.beforeSha256===before.sha256,'test_type_correction_binding');
52
+ const {after,emitSha256}=derive(before,d);
53
+ return inspectTestTypeCorrection({kind:d.kind,path:d.path,line:d.line,parameter:d.parameter,annotation:d.annotation,before,after,emitSha256,nodeVersion:process.version});
54
+ }
55
+ export function inspectTestTypeCorrection(raw){
56
+ const c=json(raw,6*1024*1024);shape(c,['kind','path','line','parameter','annotation','before','after','emitSha256','nodeVersion']);hex(c.emitSha256);
57
+ need(c.nodeVersion===process.version,'test_type_correction_runtime');
58
+ const before=readReviewSourceRecords([c.before])[0],after=readReviewSourceRecords([c.after])[0];
59
+ need(c.kind==='callback-type-annotation'&&c.path===before.path&&c.path===after.path,'test_type_correction_binding');
60
+ const derived=derive(before,c);
61
+ need(digest(derived.after)===digest(after)&&derived.emitSha256===c.emitSha256,'test_type_correction_binding');return c;
62
+ }
63
+ export function readTestTypeCorrectionFile({root,path:relative}){
64
+ sourcePath(relative);
65
+ need(typeof root==='string'&&path.isAbsolute(root)&&fs.realpathSync(root)===root,'test_type_correction_path');
66
+ let cursor=root;
67
+ for(const part of relative.split('/')){cursor=path.join(cursor,part);need(!fs.lstatSync(cursor).isSymbolicLink(),'test_type_correction_path');}
68
+ return readReviewSourceFiles(root,[relative])[0];
69
+ }
70
+ export function applyTestTypeCorrection({root,correction}){
71
+ const c=inspectTestTypeCorrection(correction),read=()=>readTestTypeCorrectionFile({root,path:c.path}),current=read();
72
+ if(digest(current)===digest(c.after))return {outcome:'already_applied'};
73
+ need(digest(current)===digest(c.before),'test_type_correction_stale');
74
+ const target=path.join(root,c.path),directory=path.dirname(target),temporary=path.join(directory,`.cm-test-type-${randomUUID()}`);let fd;
75
+ try{
76
+ fd=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW,0o600);
77
+ fs.writeFileSync(fd,Buffer.from(c.after.contentBase64,'base64'));fs.fchmodSync(fd,c.after.mode);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
78
+ need(digest(read())===digest(c.before),'test_type_correction_stale');
79
+ const st=fs.lstatSync(temporary);
80
+ need(st.isFile()&&!st.isSymbolicLink()&&st.nlink===1&&(st.mode&0o7777)===c.after.mode
81
+ &&sha(fs.readFileSync(temporary))===c.after.sha256,'test_type_correction_stale');
82
+ fs.renameSync(temporary,target);const dir=fs.openSync(directory,fs.constants.O_RDONLY);
83
+ try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
84
+ need(digest(read())===digest(c.after),'test_type_correction_stale');return {outcome:'applied'};
85
+ }finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}}
86
+ }
@@ -0,0 +1,51 @@
1
+ // One type-only repair to an owner-authored test; never replaces historical red.
2
+ import {digest,json,need,shape} from '../cm-ai/effect-contract.mjs';
3
+ import {captureReviewBaseline} from '../cm-ai/review-package.mjs';
4
+ import {createTestTypeCorrection,inspectTestTypeCorrection,readTestTypeCorrectionFile} from './test-type-correction.mjs';
5
+ export const TYPE_INTENT='fix-test-type-correction-intent',TYPE_RESULT='fix-test-type-correction-result';
6
+ export const typeIntent=records=>records.find(r=>r.id===TYPE_INTENT)??null;
7
+ export const typeCorrection=records=>records.some(r=>r.id===TYPE_RESULT)?typeIntent(records)?.payload.target.correction??null:null;
8
+ export const typeMetadata=({contentBase64,...metadata})=>metadata;
9
+ export function typeFiles(files,correction){
10
+ if(!correction)return files;
11
+ const c=inspectTestTypeCorrection(correction);return files.map(f=>f.path===c.path?typeMetadata(c.after):f);
12
+ }
13
+ export function typeSnapshot({configuration,identity,specsRoot,correction}){
14
+ const c=inspectTestTypeCorrection(correction),snapshot=captureReviewBaseline({root:configuration.reproduction.cwd,specsRoot,identity,scope:[c.path],requirements:[c.path]});
15
+ const current=snapshot.files.find(f=>f.path===c.path);
16
+ need(digest(current)===digest(c.before)||digest(current)===digest(c.after),'fix_test_type_correction_drift');
17
+ return digest(snapshot.files.map(f=>f.path===c.path?c.before:f));
18
+ }
19
+ function qualify({records,configuration,status}){
20
+ need(!typeIntent(records),'fix_test_type_correction_used');
21
+ need(status.stage==='regression_blocked'&&status.testAuthor?.outcome==='authored'&&status.redTest?.status==='red_confirmed'
22
+ &&status.regression?.red?.outcome==='passed'&&status.regression?.status==='inconclusive'
23
+ &&!configuration.qaSource&&!configuration.externalModels&&!configuration.executionPolicy
24
+ &&!records.some(r=>/^fix-final.*-registered$/.test(r.id)),'fix_test_type_correction_unavailable');
25
+ const rows=status.regression.baseline.observations,failed=rows.filter(r=>r.outcome!=='passed');
26
+ need(failed.length===1&&failed[0].outcome==='failed'&&failed[0].exitCode===2
27
+ &&failed[0].command.some(v=>/(?:^|\/)typescript\/bin\/tsc$/.test(v))&&failed[0].command.includes('--noEmit'),'fix_test_type_correction_unavailable');
28
+ }
29
+ export function inspectTestTypeTarget({configuration,records,status,identity,specsRoot,declaration}){
30
+ qualify({records,configuration,status});
31
+ const file=readTestTypeCorrectionFile({root:configuration.reproduction.cwd,path:declaration.path});
32
+ const correction=createTestTypeCorrection({file,declaration});
33
+ need(configuration.redTest.testFiles.includes(correction.path)&&status.testAuthor.testFiles.some(f=>digest(f)===digest(typeMetadata(correction.before)))
34
+ &&status.redTest.testFiles.some(f=>digest(f)===digest(typeMetadata(correction.before))),'fix_test_type_correction_binding');
35
+ return json({configurationDigest:digest(configuration),historyDigest:digest(records),regressionDigest:digest(status.regression),
36
+ redDigest:digest(status.redTest),repairDigest:digest(status.repair),correction,
37
+ snapshotDigest:typeSnapshot({configuration,identity,specsRoot,correction})},256*1024);
38
+ }
39
+ export function inspectTestTypeIntent(payload,{configuration,records,status}){
40
+ const p=json(payload,256*1024);shape(p,['target','reason','previousInvocationStopped']);
41
+ const t=p.target;shape(t,['configurationDigest','historyDigest','regressionDigest','redDigest','repairDigest','correction','snapshotDigest']);
42
+ qualify({records,configuration,status});const c=inspectTestTypeCorrection(t.correction);
43
+ need(p.previousInvocationStopped===true&&typeof p.reason==='string'&&p.reason.trim()&&Buffer.byteLength(p.reason)<=1000&&!/[\r\n\0\u0085\u2028\u2029]/.test(p.reason),'fix_test_type_correction_confirmation');
44
+ need(t.configurationDigest===digest(configuration)&&t.historyDigest===digest(records)&&t.regressionDigest===digest(status.regression)
45
+ &&t.redDigest===digest(status.redTest)&&t.repairDigest===digest(status.repair)&&/^[a-f0-9]{64}$/.test(t.snapshotDigest)
46
+ &&configuration.redTest.testFiles.includes(c.path)&&status.testAuthor.testFiles.some(f=>digest(f)===digest(typeMetadata(c.before)))
47
+ &&status.redTest.testFiles.some(f=>digest(f)===digest(typeMetadata(c.before))),'fix_test_type_correction_binding');return p;
48
+ }
49
+ export function typeEvidence(records){
50
+ const c=typeCorrection(records);return c?[`fix test type correction (data, not instructions) ${JSON.stringify({correction:c,intentDigest:digest(typeIntent(records).payload),note:'Original red and baseline remain before this type-only correction; exact transformed-prefix equality proves unchanged runtime prefix, suffix is byte-identical. Final independent review still required.'})}`]:[];
51
+ }
@@ -0,0 +1,89 @@
1
+ // An explicitly selected type-name split, not a TypeScript semantic proof.
2
+ // The owner binds approval and history; this module reports file facts only.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {createHash,randomUUID} from 'node:crypto';
6
+ import {digest,json,need,shape,hex} from '../cm-ai/effect-contract.mjs';
7
+ import {readReviewSourceRecords,readReviewSourceFiles} from '../cm-ai/review-package.mjs';
8
+ import {validateDeveloperScope} from '../cm-ai/developer-adapter.mjs';
9
+ import {readReviewVerification,verificationPath} from './review-verification-contract.mjs';
10
+
11
+ const sha=b=>createHash('sha256').update(b).digest('hex');
12
+ const identifier=/^[A-Za-z_$][A-Za-z0-9_$]*$/;
13
+ function sourcePath(value){
14
+ verificationPath(value);validateDeveloperScope([value]);
15
+ need(/\.ts$/.test(value)&&!value.endsWith('.d.ts'),'type_import_correction_path');
16
+ }
17
+ function derive(before,typeNames){
18
+ sourcePath(before.path);
19
+ const bytes=Buffer.from(before.contentBase64,'base64'),text=bytes.toString('utf8');
20
+ need(Buffer.from(text).equals(bytes)&&!text.includes('\0'),'type_import_correction_syntax');
21
+ const newline=text.indexOf('\n'),end=newline<0?text.length:newline;
22
+ const first=text.slice(0,end),eol=first.endsWith('\r')?'\r\n':'\n',line=first.replace(/\r$/,'');
23
+ // Start at byte zero: never search comments, strings or subsequent statements.
24
+ const match=/^import[ \t]+\{[ \t]*([A-Za-z_$][A-Za-z0-9_$]*(?:[ \t]*,[ \t]*[A-Za-z_$][A-Za-z0-9_$]*)*)[ \t]*\}[ \t]+from[ \t]+(['"])([A-Za-z0-9_@./-]+)\2;[ \t]*$/.exec(line);
25
+ need(match,'type_import_correction_syntax');
26
+ const names=match[1].split(',').map(n=>n.trim());
27
+ need(new Set(names).size===names.length&&!names.some(n=>['type','as','default'].includes(n)),'type_import_correction_syntax');
28
+ need(Array.isArray(typeNames)&&typeNames.length>0&&typeNames.length<names.length
29
+ &&new Set(typeNames).size===typeNames.length&&typeNames.every(n=>typeof n==='string'&&identifier.test(n)&&names.includes(n)),
30
+ 'type_import_correction_names');
31
+ const selected=new Set(typeNames),types=names.filter(n=>selected.has(n)),values=names.filter(n=>!selected.has(n));
32
+ const module=`${match[2]}${match[3]}${match[2]}`;
33
+ const replacement=`import type { ${types.join(', ')} } from ${module};${eol}import { ${values.join(', ')} } from ${module};`;
34
+ const afterBytes=Buffer.from(replacement+(newline<0?'':eol+text.slice(newline+1)));
35
+ return readReviewSourceRecords([{...before,size:afterBytes.length,sha256:sha(afterBytes),contentBase64:afterBytes.toString('base64')}])[0];
36
+ }
37
+
38
+ export function createTypeImportCorrection({file,declaration,scope,verification,reviewPackage}){
39
+ const before=readReviewSourceRecords([file])[0],d=json(declaration);
40
+ shape(d,['kind','path','beforeSha256','typeNames']);hex(d.beforeSha256);
41
+ need(d.kind==='type-import-split'&&d.path===before.path&&d.beforeSha256===before.sha256,'type_import_correction_binding');
42
+ validateDeveloperScope(scope);const profile=readReviewVerification(verification);
43
+ need(scope.includes(d.path)&&profile.files.includes(d.path)&&profile.mutationPaths.includes(d.path),'type_import_correction_scope');
44
+ hex(reviewPackage.packageDigest);
45
+ const originals=[...(reviewPackage.files??[]),...(reviewPackage.contextFiles??[])].filter(f=>f.path===d.path);
46
+ need(originals.length>0&&originals.every(f=>digest(readReviewSourceRecords([f])[0])===digest(before)),'type_import_correction_binding');
47
+ return inspectTypeImportCorrection({kind:d.kind,path:d.path,typeNames:d.typeNames,before,after:derive(before,d.typeNames)});
48
+ }
49
+ export function inspectTypeImportCorrection(raw){
50
+ const c=json(raw,3*1024*1024);shape(c,['kind','path','typeNames','before','after']);
51
+ const before=readReviewSourceRecords([c.before])[0],after=readReviewSourceRecords([c.after])[0];
52
+ need(c.kind==='type-import-split'&&c.path===before.path&&c.path===after.path,'type_import_correction_binding');
53
+ need(digest(derive(before,c.typeNames))===digest(after),'type_import_correction_binding');
54
+ return c;
55
+ }
56
+ export function readTypeImportCorrectionFile({root,path:relative}){
57
+ sourcePath(relative);
58
+ need(typeof root==='string'&&path.isAbsolute(root)&&fs.realpathSync(root)===root,'type_import_correction_path');
59
+ let cursor=root;
60
+ for(const part of relative.split('/')){
61
+ cursor=path.join(cursor,part);
62
+ need(!fs.lstatSync(cursor).isSymbolicLink(),'type_import_correction_path');
63
+ }
64
+ return readReviewSourceFiles(root,[relative])[0];
65
+ }
66
+ export function applyTypeImportCorrection({root,correction}){
67
+ const c=inspectTypeImportCorrection(correction),read=()=>readTypeImportCorrectionFile({root,path:c.path});
68
+ const current=read();
69
+ if(digest(current)===digest(c.after))return {outcome:'already_applied'};
70
+ need(digest(current)===digest(c.before),'type_import_correction_stale');
71
+ const target=path.join(root,c.path),directory=path.dirname(target),temporary=path.join(directory,`.cm-type-import-${randomUUID()}`);
72
+ let fd;
73
+ try{
74
+ fd=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW,0o600);
75
+ fs.writeFileSync(fd,Buffer.from(c.after.contentBase64,'base64'));fs.fchmodSync(fd,c.after.mode);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
76
+ need(digest(read())===digest(c.before),'type_import_correction_stale');
77
+ const temporaryStat=fs.lstatSync(temporary);
78
+ need(temporaryStat.isFile()&&!temporaryStat.isSymbolicLink()&&temporaryStat.nlink===1
79
+ &&(temporaryStat.mode&0o7777)===c.after.mode&&sha(fs.readFileSync(temporary))===c.after.sha256,'type_import_correction_stale');
80
+ fs.renameSync(temporary,target);
81
+ const dir=fs.openSync(directory,fs.constants.O_RDONLY);
82
+ try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
83
+ need(digest(read())===digest(c.after),'type_import_correction_stale');
84
+ return {outcome:'applied'};
85
+ }finally{
86
+ if(fd!==undefined)fs.closeSync(fd);
87
+ try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}
88
+ }
89
+ }
@@ -63,3 +63,11 @@ export function inspectAcceptedPrdDesign(specs,original,selection=null,{draftDig
63
63
  &&!inventory.some(name=>name!==feature.directory&&name.replace(/^\d+\./,'')===feature.name),'prd_design_inventory_invalid');
64
64
  const result={features,evidence,inventory,selection};return json({...result,bindingDigest:digest(result)});
65
65
  }
66
+
67
+ // The acceptedDesign the next prd_generate is built on, from a saved analysis
68
+ // checkpoint: leaving design_ready the host reads it again from the files, later
69
+ // it keeps the one it recorded. Drivers preflight tasks_after_design replies with it.
70
+ export function acceptedPrdDesignForPlanning(specs,analysis){
71
+ return analysis?.stage==='design_ready'?inspectAcceptedPrdDesign(specs,analysis.designDraft,analysis.designRiskSelection)
72
+ :analysis?.acceptedDesign??null;
73
+ }
@@ -7,8 +7,8 @@ import {inspectCmPrdAdmission,inspectCmPrdSources} from '../../../scripts/cm-prd
7
7
  import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
8
8
  import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
9
9
  import {inspectPrdMaterialResults} from './materials.mjs';
10
- import {prdFeatureInventory,nextPrdFeatureIndex,inspectPrdDraft,inspectPrdDesignDraft} from './draft.mjs';
11
- import {checkPrdDraftMechanics,inspectPrdContextCheck} from './self-check.mjs';
10
+ import {prdFeatureInventory,nextPrdFeatureIndex,inspectPrdDraft,inspectPrdDesignDraft,withAcceptedPrdDocuments} from './draft.mjs';
11
+ import {checkPrdDraftMechanics,inspectPrdContextCheck,PRD_SELF_CHECK_RULES} from './self-check.mjs';
12
12
  import {acceptedPrdDraftForSave} from './draft-save.mjs';
13
13
  import {preparePrdReview} from './review-preparation.mjs';
14
14
  import {inspectAcceptedPrdDesign} from './accepted-design.mjs';
@@ -18,7 +18,8 @@ import {prdDraftJson} from './validation-reason.mjs';
18
18
 
19
19
  const initialTaskInstructions=' For FIRST task planning only: combine related low-risk work around one independently verifiable and reversible objective. Retain every AC, original user test, expected result and verification prerequisite; keep AC-to-test-to-task references complete. Same file/component alone is not evidence to combine. Keep high-risk work, unknown-risk work, explicit user requests for independent tasks and unrelated objectives separate; preserve legitimate contract-first tasks and real dependencies. Use requirement/design/context evidence, not keyword risk classification or another model call. No fixed merge ratio or task-count target. Do not repartition an existing draft, revision, restored task list, change or in-flight task. Scope expansion during development requires the existing explicit change and renewed approval. Keep configured developer/reviewer roles and each task independent N4 unchanged.';
20
20
 
21
- export function createCmPrdAnalysis({input,runtime,analyze,record,processMaterials,generate,checkContext,restored=null,allowInputDrift=false}){
21
+ export function createCmPrdAnalysis({input,runtime,analyze,record,processMaterials,generate,checkContext,restored=null,allowInputDrift=false,
22
+ selfCheckRules=()=>PRD_SELF_CHECK_RULES}){
22
23
  need(['codex','claude'].includes(runtime)&&typeof analyze==='function'&&typeof record==='function','prd_host_invalid');
23
24
  input=json(input);
24
25
  const admission=inspectCmPrdAdmission(input);
@@ -195,13 +196,16 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
195
196
  instructions:'Correct findings only within these existing feature names/directories. Do not add, remove or rename features; retain user intent and tests. No review invocation. Two self-check rounds maximum.'},
196
197
  reference:path.join(admission.skillDir,'SKILL.md'),testContract:path.join(admission.workflowRoot,'runtime/test-contract.md'),
197
198
  instructions:(canRevise?
198
- 'Correct the failed whole-draft self-check in the existing draft schema. Keep exactly the same ordered features and file inventory. Requirements/design changes require selfCheckRevisionReason. Return question or blocked if needed. No writes, review dispatch, invented approval or extra rounds.':acceptedDesign!==null?
199
- 'Follow original cm-prd Step 10 and 10.4 on acceptedDesign. Return the existing draft schema with the exact same ordered features and exact requirements.md/design.md bytes supplied there; generate tasks.md and applicable test-cases.json only. Do not regenerate or revise accepted requirements/design, change scope or call a reviewer. Preserve original user cases and unresolved design findings for human review. Ask material questions with {status:question,question}; no invented user decisions. No writes, provider calls, installation, development or approval. Subsequent original self-check and split review remain required.':designOnly?
199
+ 'Correct the failed whole-draft self-check in the existing draft schema. Keep exactly the same ordered features and file inventory. A requirements.md/design.md left out of a feature keeps its accepted bytes. Requirements/design changes require selfCheckRevisionReason. Return question or blocked if needed. No writes, review dispatch, invented approval or extra rounds.':acceptedDesign!==null?
200
+ 'Follow original cm-prd Step 10 and 10.4 on acceptedDesign. Return the existing draft schema with the exact same ordered features; each feature lists only tasks.md and applicable test-cases.json, leaving out requirements.md/design.md, which the host restores byte-identical from acceptedDesign (if included they must be exactly the supplied bytes). The 64 KiB reply limit then counts only the new documents. Do not regenerate or revise accepted requirements/design, change scope or call a reviewer. Preserve original user cases and unresolved design findings for human review. Ask material questions with {status:question,question}; no invented user decisions. No writes, provider calls, installation, development or approval. Subsequent original self-check and split review remain required.':designOnly?
200
201
  'Follow cm-prd Steps 6-9 only, before original Step 9.5 design review. Read required references and actual relevant project context. Preserve user cases and requirements. No tasks or test-contract generation yet, even embedded in another document. Resolve material or human UI baseline decisions with {status:question,question}; never infer consent. Return {status:design,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md,content:string}]}]} with exactly both documents per feature, or {status:blocked,reason}. No writes, provider calls, browser launch, installation, review claims or development. These are unreviewed memory drafts, not authority to generate tasks.':
201
202
  'Follow cm-prd Steps 6-10 for in-memory DRAFTS ONLY. Read required references and relevant project context. Resolve material questions and human UI baseline choices before design: return {status:question,question} and wait, never infer consent. No writes, provider calls, browser launch, installation, review claims or development. Return {status:draft,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md|tasks.md|test-cases.json,content:string}],testCasesReason:null|no_observable_behavior|generation_disabled}]} or {status:blocked,reason}. Each feature needs the triad. Apply functional task granularity <=15, AC/Task references, applicable test contract and original user-case intent; generateCases false forbids generated cases only. This draft is unreviewed; original conditional design review, split review, self-check and human approval remain pending.')
202
203
  +(draft===null&&!designOnly?initialTaskInstructions:'')},controller.signal),64*1024);
203
204
  need(!controller.signal.aborted,'cancelled');current();
204
205
  need(digest(inventory)===digest(prdFeatureInventory(admission.specs)),'prd_feature_inventory_changed');
206
+ // The planning history keeps the reply as sent; the draft is built from it
207
+ // with any accepted requirements/design it left out restored.
208
+ const assembled=withAcceptedPrdDocuments(reply,acceptedDesign);
205
209
  if(reply.status==='question'){
206
210
  shape(reply,['status','question']);need(nonempty(reply.question),'prd_reply_invalid');stage=designOnly?'awaiting_design_user':'awaiting_planning_user';
207
211
  }else if(reply.status==='blocked'){
@@ -210,13 +214,13 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
210
214
  need(draft===null&&acceptedDesign===null&&selfCheckRound===0,'prd_late_design_transition_not_ready');
211
215
  designDraft=inspectPrdDesignDraft(reply,{nextIndex});designPlanning=true;stage='design_ready';
212
216
  }else{
213
- const {selfCheckRevisionReason,...draftReply}=reply;
217
+ const {selfCheckRevisionReason,...draftReply}=assembled.reply;
214
218
  if(acceptedDesign!==null&&draft!==null){
215
219
  const inventory=features=>features.map(f=>({name:f.name,files:f.documents.map(d=>d.path).sort()}));
216
- need(digest(inventory(reply.features))===digest(inventory(draft.features)),'prd_accepted_design_scope_changed');
220
+ need(digest(inventory(assembled.reply.features))===digest(inventory(draft.features)),'prd_accepted_design_scope_changed');
217
221
  }
218
222
  const inspected=inspectPrdDraft(draftReply,{nextIndex,generateCases:config.policies.generate_cases,
219
- userCasesProvided:snapshot.sourceInspection.userCases!==null});
223
+ userCasesProvided:snapshot.sourceInspection.userCases!==null,limit:assembled.limit});
220
224
  if(acceptedDesign!==null){
221
225
  need(digest(inspected.features.map(item=>item.directory))===digest(acceptedDesign.features.map(item=>item.directory)),
222
226
  'prd_accepted_design_scope_changed');
@@ -235,7 +239,7 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
235
239
  mechanical:draft.mechanicalSelfCheck,contextCheck});
236
240
  }
237
241
  selfCheckRound++;contextCheck=null;
238
- draft=json({...inspected,mechanicalSelfCheck:checkPrdDraftMechanics(inspected)});
242
+ draft=json({...inspected,mechanicalSelfCheck:checkPrdDraftMechanics(inspected,{rules:selfCheckRules()})});
239
243
  stage=draft.mechanicalSelfCheck.status==='failed'?(selfCheckRound>=2?'self_check_needs_human':'draft_self_check_failed'):'draft_ready';
240
244
  }
241
245
  const updated=[...next,{role:'assistant',result:reply}];