@aibyzero/cm-workflow 0.10.5

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 (448) hide show
  1. package/.codex-plugin/plugin.json +30 -0
  2. package/AGENTS.md +74 -0
  3. package/CONTRIBUTING.md +62 -0
  4. package/LICENSE +21 -0
  5. package/README.md +263 -0
  6. package/SECURITY.md +49 -0
  7. package/THIRD_PARTY_NOTICES.md +29 -0
  8. package/VERSION +1 -0
  9. package/agents/cm-backend-agent.md +34 -0
  10. package/agents/cm-contract-agent.md +34 -0
  11. package/agents/cm-database-agent.md +34 -0
  12. package/agents/cm-frontend-agent.md +33 -0
  13. package/agents/cm-miniprogram-agent.md +33 -0
  14. package/agents/cm-ui-agent.md +34 -0
  15. package/assets/docs/command-picker-mobile.svg +56 -0
  16. package/assets/docs/command-picker.svg +56 -0
  17. package/assets/docs/user-guide-hero-mobile.svg +35 -0
  18. package/assets/docs/user-guide-hero.svg +36 -0
  19. package/assets/readme/delivery-flow.svg +86 -0
  20. package/assets/readme/hero.svg +77 -0
  21. package/assets/readme/recovery-record.svg +73 -0
  22. package/assets/readme/test-evidence.svg +64 -0
  23. package/compat/claude-commands/cm-ai.md +3 -0
  24. package/compat/claude-commands/cm-check.md +3 -0
  25. package/compat/claude-commands/cm-fix.md +3 -0
  26. package/compat/claude-commands/cm-idea.md +3 -0
  27. package/compat/claude-commands/cm-init.md +3 -0
  28. package/compat/claude-commands/cm-prd.md +3 -0
  29. package/compat/claude-commands/cm-refactor.md +3 -0
  30. package/compat/claude-commands/cm-test.md +3 -0
  31. package/docs/architecture.md +155 -0
  32. package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-a1-handoff.json +57 -0
  33. package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-a2-handoff.json +58 -0
  34. package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-r1.md +121 -0
  35. package/docs/fixes/.reviews/fix-cancel-throw-v2-T-FIX-cancel-throw-v2-a1-handoff.json +56 -0
  36. package/docs/fixes/.reviews/fix-cancel-throw-v2-T-FIX-cancel-throw-v2-r1.md +100 -0
  37. package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-a1-handoff.json +61 -0
  38. package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-a2-handoff.json +63 -0
  39. package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-r1.md +58 -0
  40. package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-r2.md +55 -0
  41. package/docs/fixes/.reviews/fix-f01-dual-failure-terminal-T-FIX-f01-dual-failure-terminal-a1-handoff.json +65 -0
  42. package/docs/fixes/.reviews/fix-f01-dual-failure-terminal-T-FIX-f01-dual-failure-terminal-r1.md +88 -0
  43. package/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r1.md +33 -0
  44. package/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r2.md +31 -0
  45. package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a1-handoff.json +56 -0
  46. package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a2-handoff.json +85 -0
  47. package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r1.md +53 -0
  48. package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r2.md +80 -0
  49. package/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-a1-handoff.json +35 -0
  50. package/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-r1.md +33 -0
  51. package/docs/fixes/.reviews/fix-windows-cp1252-log-output-r1.md +30 -0
  52. package/docs/fixes/.reviews/fix-windows-cp1252-log-output-r2.md +16 -0
  53. package/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-a1-handoff.json +40 -0
  54. package/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-r1.md +30 -0
  55. package/docs/fixes/20260729-windows-cp1252-log-output.md +65 -0
  56. package/docs/fixes/20260804-manifest-runtime-checkbox-drift.md +67 -0
  57. package/docs/fixes/20260806-model-call-boundary-identity.md +80 -0
  58. package/docs/fixes/20260807-prelanding-integrity.md +58 -0
  59. package/docs/fixes/20260826-openai-compatible-depth-fixture.md +39 -0
  60. package/docs/fixes/20260903-cm-js-n1n2-admission-r1.md +64 -0
  61. package/docs/fixes/20260903-cm-js-n1n2-admission-successor.md +83 -0
  62. package/docs/fixes/20260903-s4c1b-v3-cancel-throw.md +89 -0
  63. package/docs/fixes/20260904-f01-codex-dual-failure-terminal.md +89 -0
  64. package/docs/fixes/20260907-wip-triage-log.md +44 -0
  65. package/docs/installation.md +202 -0
  66. package/docs/js-workflow-control.md +1010 -0
  67. package/docs/sample-prd/prd-funding-rate-alert.md +42 -0
  68. package/docs/sample-specs/docs//351/234/200/346/261/202/347/244/272/344/276/213.md +24 -0
  69. package/docs/user-guide.md +526 -0
  70. package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/README.md +19 -0
  71. package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.excalidraw +3650 -0
  72. package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.mp4 +0 -0
  73. package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.png +0 -0
  74. package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.spec.json +223 -0
  75. package/install-codex.sh +184 -0
  76. package/install.ps1 +206 -0
  77. package/install.sh +244 -0
  78. package/package.json +58 -0
  79. package/runtime/external-expert.md +302 -0
  80. package/runtime/js/cm-ai/accepted-fix.mjs +28 -0
  81. package/runtime/js/cm-ai/claude-developer-adapter.mjs +6 -0
  82. package/runtime/js/cm-ai/claude-review-adapter.mjs +16 -0
  83. package/runtime/js/cm-ai/claude-review-stream.mjs +53 -0
  84. package/runtime/js/cm-ai/claude-tool-preview.mjs +107 -0
  85. package/runtime/js/cm-ai/cm-ai-admission.mjs +353 -0
  86. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +217 -0
  87. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +538 -0
  88. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +119 -0
  89. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +172 -0
  90. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +320 -0
  91. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +107 -0
  92. package/runtime/js/cm-ai/code-projects.mjs +85 -0
  93. package/runtime/js/cm-ai/codex-config.mjs +48 -0
  94. package/runtime/js/cm-ai/codex-developer-adapter.mjs +5 -0
  95. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +6 -0
  96. package/runtime/js/cm-ai/codex-developer-output.schema.json +37 -0
  97. package/runtime/js/cm-ai/codex-review-adapter.mjs +73 -0
  98. package/runtime/js/cm-ai/contracts.mjs +156 -0
  99. package/runtime/js/cm-ai/developer-adapter.mjs +93 -0
  100. package/runtime/js/cm-ai/durable-runner-state.mjs +504 -0
  101. package/runtime/js/cm-ai/effect-contract.mjs +102 -0
  102. package/runtime/js/cm-ai/execution-platform.mjs +7 -0
  103. package/runtime/js/cm-ai/execution-store.mjs +211 -0
  104. package/runtime/js/cm-ai/fix-code-association.mjs +40 -0
  105. package/runtime/js/cm-ai/gate-bridge.mjs +25 -0
  106. package/runtime/js/cm-ai/host-bootstrap.mjs +170 -0
  107. package/runtime/js/cm-ai/host-check.mjs +89 -0
  108. package/runtime/js/cm-ai/host-conversation-execution.mjs +125 -0
  109. package/runtime/js/cm-ai/host-documentation.mjs +40 -0
  110. package/runtime/js/cm-ai/host-handoff.mjs +71 -0
  111. package/runtime/js/cm-ai/host-project-execution.mjs +58 -0
  112. package/runtime/js/cm-ai/host-qa-executor.mjs +238 -0
  113. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +131 -0
  114. package/runtime/js/cm-ai/host-qa-fix.mjs +30 -0
  115. package/runtime/js/cm-ai/host-qa-policy.mjs +70 -0
  116. package/runtime/js/cm-ai/host-review-authority.mjs +36 -0
  117. package/runtime/js/cm-ai/host-review-file.mjs +56 -0
  118. package/runtime/js/cm-ai/host-role-routing.mjs +41 -0
  119. package/runtime/js/cm-ai/host-session.mjs +96 -0
  120. package/runtime/js/cm-ai/host-tool-bridge.mjs +53 -0
  121. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +45 -0
  122. package/runtime/js/cm-ai/host.mjs +20 -0
  123. package/runtime/js/cm-ai/index.mjs +7 -0
  124. package/runtime/js/cm-ai/provider-review-observation.mjs +86 -0
  125. package/runtime/js/cm-ai/qa-fix-definition.mjs +21 -0
  126. package/runtime/js/cm-ai/review-evidence-file.mjs +38 -0
  127. package/runtime/js/cm-ai/review-package.mjs +426 -0
  128. package/runtime/js/cm-ai/review-result.schema.json +40 -0
  129. package/runtime/js/cm-ai/review-runner.mjs +35 -0
  130. package/runtime/js/cm-ai/task-commit-codec.mjs +54 -0
  131. package/runtime/js/cm-ai/task-commit.mjs +201 -0
  132. package/runtime/js/cm-ai/task-owner.mjs +97 -0
  133. package/runtime/js/cm-ai/task-runner.mjs +766 -0
  134. package/runtime/js/cm-ai/tool-preview.mjs +205 -0
  135. package/runtime/js/cm-ai/worker-claude.mjs +104 -0
  136. package/runtime/js/cm-ai/worker-codex-developer.mjs +124 -0
  137. package/runtime/js/cm-ai/worker-codex.mjs +143 -0
  138. package/runtime/js/cm-check/host.mjs +101 -0
  139. package/runtime/js/cm-fix/baseline.mjs +70 -0
  140. package/runtime/js/cm-fix/cause-evidence.mjs +24 -0
  141. package/runtime/js/cm-fix/cause-invocation.mjs +40 -0
  142. package/runtime/js/cm-fix/cause-package.mjs +68 -0
  143. package/runtime/js/cm-fix/dossier.mjs +140 -0
  144. package/runtime/js/cm-fix/execution.mjs +1549 -0
  145. package/runtime/js/cm-fix/final-review-evidence.mjs +20 -0
  146. package/runtime/js/cm-fix/final-review.mjs +156 -0
  147. package/runtime/js/cm-fix/finish.mjs +124 -0
  148. package/runtime/js/cm-fix/handoff.mjs +64 -0
  149. package/runtime/js/cm-fix/host-review.mjs +38 -0
  150. package/runtime/js/cm-fix/host.mjs +96 -0
  151. package/runtime/js/cm-fix/investigation.mjs +25 -0
  152. package/runtime/js/cm-fix/layout.mjs +17 -0
  153. package/runtime/js/cm-fix/learning-writeback.mjs +86 -0
  154. package/runtime/js/cm-fix/learning.mjs +31 -0
  155. package/runtime/js/cm-fix/metrics.mjs +75 -0
  156. package/runtime/js/cm-fix/progress.mjs +64 -0
  157. package/runtime/js/cm-fix/protected-edits.mjs +95 -0
  158. package/runtime/js/cm-fix/qa-source.mjs +58 -0
  159. package/runtime/js/cm-fix/red-test.mjs +92 -0
  160. package/runtime/js/cm-fix/regression-evidence.mjs +64 -0
  161. package/runtime/js/cm-fix/regression.mjs +41 -0
  162. package/runtime/js/cm-fix/repair.mjs +95 -0
  163. package/runtime/js/cm-fix/reproduce.mjs +54 -0
  164. package/runtime/js/cm-fix/retrospective.mjs +41 -0
  165. package/runtime/js/cm-fix/review-baseline.mjs +47 -0
  166. package/runtime/js/cm-fix/start.mjs +49 -0
  167. package/runtime/js/cm-fix/test-author.mjs +63 -0
  168. package/runtime/js/cm-fix/visual.mjs +72 -0
  169. package/runtime/js/cm-fix/walkthrough.mjs +126 -0
  170. package/runtime/js/cm-idea/session.mjs +79 -0
  171. package/runtime/js/cm-init/draft-generation.mjs +66 -0
  172. package/runtime/js/cm-init/draft-inspection.mjs +70 -0
  173. package/runtime/js/cm-init/project-analysis.mjs +60 -0
  174. package/runtime/js/cm-init/project-scan.mjs +55 -0
  175. package/runtime/js/cm-init/review-evidence.mjs +80 -0
  176. package/runtime/js/cm-prd/accepted-design.mjs +46 -0
  177. package/runtime/js/cm-prd/analysis.mjs +260 -0
  178. package/runtime/js/cm-prd/change.mjs +268 -0
  179. package/runtime/js/cm-prd/correction-check.mjs +49 -0
  180. package/runtime/js/cm-prd/design-risk.mjs +30 -0
  181. package/runtime/js/cm-prd/disposition-plan.mjs +33 -0
  182. package/runtime/js/cm-prd/draft-save.mjs +122 -0
  183. package/runtime/js/cm-prd/draft.mjs +70 -0
  184. package/runtime/js/cm-prd/materials.mjs +48 -0
  185. package/runtime/js/cm-prd/review-correction.mjs +158 -0
  186. package/runtime/js/cm-prd/review-disposition.mjs +96 -0
  187. package/runtime/js/cm-prd/review-findings.mjs +36 -0
  188. package/runtime/js/cm-prd/review-host.mjs +48 -0
  189. package/runtime/js/cm-prd/review-preparation.mjs +49 -0
  190. package/runtime/js/cm-prd/review-publication.mjs +56 -0
  191. package/runtime/js/cm-prd/self-check.mjs +75 -0
  192. package/runtime/js/cm-prd/session.mjs +74 -0
  193. package/runtime/js/cm-prd/summary.mjs +133 -0
  194. package/runtime/js/cm-refactor/host.mjs +2 -0
  195. package/runtime/js/cm-refactor/records.mjs +86 -0
  196. package/runtime/js/cm-refactor/workflow.mjs +478 -0
  197. package/runtime/js/cm-test/declared-command.mjs +32 -0
  198. package/runtime/js/cm-test/host.mjs +319 -0
  199. package/runtime/js/cm-test/logic-results.mjs +39 -0
  200. package/runtime/js/cm-test/recovery.mjs +58 -0
  201. package/runtime/js/cm-test/session.mjs +56 -0
  202. package/runtime/js/cm-test/source-snapshot.mjs +136 -0
  203. package/runtime/logging.md +207 -0
  204. package/runtime/model-efficiency.md +201 -0
  205. package/runtime/orchestration.md +113 -0
  206. package/runtime/project-context.md +43 -0
  207. package/runtime/project-learning.md +49 -0
  208. package/runtime/review.md +140 -0
  209. package/runtime/steelman-review.md +111 -0
  210. package/runtime/task-gates.md +283 -0
  211. package/runtime/task-handoff.schema.json +103 -0
  212. package/runtime/test-contract.md +212 -0
  213. package/runtime/workflow-config.md +118 -0
  214. package/runtime/workflow-routing.md +82 -0
  215. package/scripts/cm-ai-admission.mjs +50 -0
  216. package/scripts/cm-ai-admission.test.mjs +38 -0
  217. package/scripts/cm-ai-batch-host.mjs +77 -0
  218. package/scripts/cm-ai-batch-host.test.mjs +155 -0
  219. package/scripts/cm-ai-batch-run.mjs +136 -0
  220. package/scripts/cm-ai-batch-run.test.mjs +128 -0
  221. package/scripts/cm-ai-bootstrap.test.mjs +228 -0
  222. package/scripts/cm-ai-fix-integration.test.mjs +233 -0
  223. package/scripts/cm-ai-host.mjs +175 -0
  224. package/scripts/cm-ai-host.test.mjs +368 -0
  225. package/scripts/cm-ai-multi-root.test.mjs +289 -0
  226. package/scripts/cm-ai-nested-execution.test.mjs +313 -0
  227. package/scripts/cm-ai-run.mjs +293 -0
  228. package/scripts/cm-ai-run.test.mjs +336 -0
  229. package/scripts/cm-check-entry.mjs +120 -0
  230. package/scripts/cm-check-host.mjs +29 -0
  231. package/scripts/cm-check-host.test.mjs +71 -0
  232. package/scripts/cm-check-runtime.ps1 +69 -0
  233. package/scripts/cm-check-runtime.sh +910 -0
  234. package/scripts/cm-claude-probe.test.mjs +54 -0
  235. package/scripts/cm-claude-review-stream.test.mjs +45 -0
  236. package/scripts/cm-claude-worker.test.mjs +92 -0
  237. package/scripts/cm-codex-developer-adapter.test.mjs +85 -0
  238. package/scripts/cm-codex-developer-worker.test.mjs +128 -0
  239. package/scripts/cm-codex-review-progress.test.mjs +96 -0
  240. package/scripts/cm-execution-platform.test.mjs +47 -0
  241. package/scripts/cm-fix-cause-invocation.test.mjs +72 -0
  242. package/scripts/cm-fix-cause-package.test.mjs +68 -0
  243. package/scripts/cm-fix-code-association.test.mjs +55 -0
  244. package/scripts/cm-fix-entry.mjs +132 -0
  245. package/scripts/cm-fix-execution.test.mjs +63 -0
  246. package/scripts/cm-fix-final-review.test.mjs +124 -0
  247. package/scripts/cm-fix-host-review-assembly.test.mjs +34 -0
  248. package/scripts/cm-fix-host-review.test.mjs +261 -0
  249. package/scripts/cm-fix-host-sequence.test.mjs +26 -0
  250. package/scripts/cm-fix-host.mjs +89 -0
  251. package/scripts/cm-fix-host.test.mjs +105 -0
  252. package/scripts/cm-fix-learning-writeback.test.mjs +73 -0
  253. package/scripts/cm-fix-learning.test.mjs +66 -0
  254. package/scripts/cm-fix-metrics.test.mjs +58 -0
  255. package/scripts/cm-fix-no-existing-tests.test.mjs +92 -0
  256. package/scripts/cm-fix-observation-dossier.test.mjs +452 -0
  257. package/scripts/cm-fix-progress.test.mjs +45 -0
  258. package/scripts/cm-fix-protected-edits.test.mjs +54 -0
  259. package/scripts/cm-fix-qa-source.test.mjs +206 -0
  260. package/scripts/cm-fix-red-owner.test.mjs +143 -0
  261. package/scripts/cm-fix-red-test.test.mjs +38 -0
  262. package/scripts/cm-fix-regression.test.mjs +57 -0
  263. package/scripts/cm-fix-repair-owner.test.mjs +370 -0
  264. package/scripts/cm-fix-repair.test.mjs +68 -0
  265. package/scripts/cm-fix-reproduce.test.mjs +31 -0
  266. package/scripts/cm-fix-retrospective.test.mjs +46 -0
  267. package/scripts/cm-fix-review-baseline.test.mjs +54 -0
  268. package/scripts/cm-fix-review-recovery.test.mjs +197 -0
  269. package/scripts/cm-fix-test-author.test.mjs +105 -0
  270. package/scripts/cm-fix-visual-bare.test.mjs +171 -0
  271. package/scripts/cm-fix-walkthrough.test.mjs +45 -0
  272. package/scripts/cm-host-check.test.mjs +113 -0
  273. package/scripts/cm-host-documentation.test.mjs +45 -0
  274. package/scripts/cm-host-handoff.test.mjs +58 -0
  275. package/scripts/cm-host-qa-executor.test.mjs +156 -0
  276. package/scripts/cm-host-qa-policy.test.mjs +59 -0
  277. package/scripts/cm-host-review-authority.test.mjs +60 -0
  278. package/scripts/cm-host-role-routing.test.mjs +33 -0
  279. package/scripts/cm-idea-entry.mjs +104 -0
  280. package/scripts/cm-idea-host.mjs +144 -0
  281. package/scripts/cm-idea-host.test.mjs +75 -0
  282. package/scripts/cm-idea-recovery.test.mjs +90 -0
  283. package/scripts/cm-init-analysis-host.test.mjs +50 -0
  284. package/scripts/cm-init-draft-generation.test.mjs +52 -0
  285. package/scripts/cm-init-draft-inspection.test.mjs +41 -0
  286. package/scripts/cm-init-entry.mjs +170 -0
  287. package/scripts/cm-init-host.mjs +284 -0
  288. package/scripts/cm-init-host.test.mjs +231 -0
  289. package/scripts/cm-init-project-analysis.test.mjs +47 -0
  290. package/scripts/cm-init-project-scan.test.mjs +41 -0
  291. package/scripts/cm-init-revision-host.test.mjs +61 -0
  292. package/scripts/cm-init-session.test.mjs +122 -0
  293. package/scripts/cm-log-event.mjs +538 -0
  294. package/scripts/cm-log-event.py +133 -0
  295. package/scripts/cm-log-event.test.mjs +70 -0
  296. package/scripts/cm-openai-compatible-call.py +661 -0
  297. package/scripts/cm-prd-analysis.test.mjs +67 -0
  298. package/scripts/cm-prd-completion.test.mjs +190 -0
  299. package/scripts/cm-prd-design-phase.test.mjs +296 -0
  300. package/scripts/cm-prd-draft-save.test.mjs +63 -0
  301. package/scripts/cm-prd-draft.test.mjs +39 -0
  302. package/scripts/cm-prd-entry.mjs +245 -0
  303. package/scripts/cm-prd-host.mjs +273 -0
  304. package/scripts/cm-prd-host.test.mjs +169 -0
  305. package/scripts/cm-prd-materials.test.mjs +41 -0
  306. package/scripts/cm-prd-review-claim.test.mjs +42 -0
  307. package/scripts/cm-prd-review-disposition.test.mjs +196 -0
  308. package/scripts/cm-prd-review-gate.mjs +194 -0
  309. package/scripts/cm-prd-review-gate.py +26 -0
  310. package/scripts/cm-prd-review-host.test.mjs +30 -0
  311. package/scripts/cm-prd-review-preparation.test.mjs +69 -0
  312. package/scripts/cm-prd-review-publication.test.mjs +95 -0
  313. package/scripts/cm-prd-revision.test.mjs +32 -0
  314. package/scripts/cm-prd-self-check.test.mjs +23 -0
  315. package/scripts/cm-prd-sources.test.mjs +76 -0
  316. package/scripts/cm-prd-timing.py +272 -0
  317. package/scripts/cm-refactor-entry.mjs +145 -0
  318. package/scripts/cm-refactor-host.mjs +26 -0
  319. package/scripts/cm-refactor-host.test.mjs +201 -0
  320. package/scripts/cm-review-dependency-snapshot.test.mjs +67 -0
  321. package/scripts/cm-review-inventory.test.mjs +109 -0
  322. package/scripts/cm-spec-manifest.mjs +104 -0
  323. package/scripts/cm-spec-manifest.py +26 -0
  324. package/scripts/cm-task-gate.mjs +879 -0
  325. package/scripts/cm-task-gate.py +312 -0
  326. package/scripts/cm-task-gate.test.mjs +202 -0
  327. package/scripts/cm-test-declared-command.test.mjs +18 -0
  328. package/scripts/cm-test-entry.mjs +231 -0
  329. package/scripts/cm-test-host.mjs +40 -0
  330. package/scripts/cm-test-host.test.mjs +169 -0
  331. package/scripts/cm-test-logic-results.test.mjs +26 -0
  332. package/scripts/cm-test-session.test.mjs +138 -0
  333. package/scripts/cm-usage-report.py +516 -0
  334. package/scripts/cm-workflow-config.mjs +463 -0
  335. package/scripts/cm-workflow-config.test.mjs +181 -0
  336. package/scripts/cm-workflow.mjs +36 -0
  337. package/scripts/cm-workflow.test.mjs +51 -0
  338. package/scripts/cm_workflow_config.py +52 -0
  339. package/scripts/fixtures/claude-review-process.mjs +35 -0
  340. package/scripts/fixtures/codex-review-process.mjs +22 -0
  341. package/scripts/fixtures/prd-review-gate-python-oracle.py +320 -0
  342. package/scripts/fixtures/spec-manifest-python-oracle.py +172 -0
  343. package/scripts/scan-public-safety.py +117 -0
  344. package/scripts/test-cm-log-event.py +1213 -0
  345. package/scripts/test-cm-openai-compatible-call.py +1185 -0
  346. package/scripts/test-cm-prd-review-gate.py +272 -0
  347. package/scripts/test-cm-prd-timing.py +168 -0
  348. package/scripts/test-cm-usage-report.py +584 -0
  349. package/scripts/test-npm-install.py +171 -0
  350. package/scripts/test-scan-public-safety.py +76 -0
  351. package/scripts/test-shell-compat.sh +365 -0
  352. package/scripts/test-spec-manifest.py +263 -0
  353. package/scripts/test-task-gate.py +46 -0
  354. package/scripts/test-workflow-config.py +30 -0
  355. package/scripts/validate-public-repo.py +245 -0
  356. package/scripts/validate-test-cases.mjs +71 -0
  357. package/scripts/validate-test-cases.py +27 -0
  358. package/scripts/validate-test-cases.test.mjs +36 -0
  359. package/skills/cm-ai/SKILL.md +137 -0
  360. package/skills/cm-ai/references/N1-init.md +108 -0
  361. package/skills/cm-ai/references/N2-enter-feature.md +38 -0
  362. package/skills/cm-ai/references/N3-execute-task.md +123 -0
  363. package/skills/cm-ai/references/N4-review.md +103 -0
  364. package/skills/cm-ai/references/N5-mark-done.md +117 -0
  365. package/skills/cm-ai/references/N6-qa-eval.md +102 -0
  366. package/skills/cm-ai/references/N7-context.md +23 -0
  367. package/skills/cm-ai/references/N8-finish.md +103 -0
  368. package/skills/cm-ai/references/js-host.md +126 -0
  369. package/skills/cm-backend-engineer/SKILL.md +100 -0
  370. package/skills/cm-check/SKILL.md +52 -0
  371. package/skills/cm-check/references/js-host.md +44 -0
  372. package/skills/cm-contract-engineer/SKILL.md +136 -0
  373. package/skills/cm-database-engineer/SKILL.md +89 -0
  374. package/skills/cm-devops-engineer/SKILL.md +137 -0
  375. package/skills/cm-doc-syncer/SKILL.md +150 -0
  376. package/skills/cm-finance-expert/SKILL.md +85 -0
  377. package/skills/cm-fix/SKILL.md +199 -0
  378. package/skills/cm-fix/references/cross-boundary-debugging.md +44 -0
  379. package/skills/cm-fix/references/js-host.md +135 -0
  380. package/skills/cm-frontend-engineer/SKILL.md +127 -0
  381. package/skills/cm-idea/SKILL.md +55 -0
  382. package/skills/cm-idea/references/domains/trading.md +97 -0
  383. package/skills/cm-idea/references/example-prd.md +92 -0
  384. package/skills/cm-idea/references/idea-to-prd.md +282 -0
  385. package/skills/cm-idea/references/js-host.md +63 -0
  386. package/skills/cm-init/SKILL.md +191 -0
  387. package/skills/cm-init/references/js-host.md +123 -0
  388. package/skills/cm-miniprogram-engineer/SKILL.md +141 -0
  389. package/skills/cm-miniprogram-engineer/references/platform-readiness.md +58 -0
  390. package/skills/cm-miniprogram-engineer/references/release-checklist.md +59 -0
  391. package/skills/cm-prd/SKILL.md +548 -0
  392. package/skills/cm-prd/references/brownfield.md +13 -0
  393. package/skills/cm-prd/references/change-mode.md +145 -0
  394. package/skills/cm-prd/references/context-scope.md +62 -0
  395. package/skills/cm-prd/references/greenfield.md +80 -0
  396. package/skills/cm-prd/references/js-change-recovery.md +57 -0
  397. package/skills/cm-prd/references/js-host.md +98 -0
  398. package/skills/cm-prd/references/phase-timing.md +68 -0
  399. package/skills/cm-prd/references/spec-self-check.md +22 -0
  400. package/skills/cm-product-manager/SKILL.md +83 -0
  401. package/skills/cm-qa-engineer/SKILL.md +142 -0
  402. package/skills/cm-refactor/SKILL.md +236 -0
  403. package/skills/cm-refactor/references/js-batch.md +75 -0
  404. package/skills/cm-refactor/references/js-host.md +78 -0
  405. package/skills/cm-test/SKILL.md +288 -0
  406. package/skills/cm-test/references/js-host.md +118 -0
  407. package/skills/cm-ui-engineer/SKILL.md +105 -0
  408. package/skills/codebase-context/SKILL.md +489 -0
  409. package/skills/darwin-skill/NOTICE.md +26 -0
  410. package/skills/darwin-skill/README.md +272 -0
  411. package/skills/darwin-skill/SKILL.md +492 -0
  412. package/skills/darwin-skill/references/runtime-neutrality.md +68 -0
  413. package/skills/darwin-skill/references/skilllens-evidence.md +142 -0
  414. package/skills/darwin-skill/scripts/screenshot.mjs +71 -0
  415. package/skills/darwin-skill/templates/result-card-dark.html +698 -0
  416. package/skills/darwin-skill/templates/result-card-white.html +444 -0
  417. package/skills/darwin-skill/templates/result-card.html +616 -0
  418. package/skills/external-expert/SKILL.md +250 -0
  419. package/templates/arch-reference.md +68 -0
  420. package/templates/auto-update/cm-announce.sh +19 -0
  421. package/templates/auto-update/cm-update.sh +274 -0
  422. package/templates/cm-workflow.yml +52 -0
  423. package/templates/dashboard/dashboard.html +153 -0
  424. package/templates/dashboard/serve.sh +10 -0
  425. package/templates/hooks/pre-commit-cm-task-check +67 -0
  426. package/templates/pixel/cm-pixel.html +388 -0
  427. package/templates/pixel/cm-pixel.sh +212 -0
  428. package/templates/pixel/dev/README.md +20 -0
  429. package/templates/pixel/dev/atlas-preview.png +0 -0
  430. package/templates/pixel/dev/build.py +55 -0
  431. package/templates/pixel/dev/sheets/roguelikeChar_transparent.png +0 -0
  432. package/templates/pixel/dev/sheets/roguelikeCity_tilemap.png +0 -0
  433. package/templates/pixel/dev/sheets/roguelikeIndoor_transparent.png +0 -0
  434. package/templates/pixel/dev/template.html +388 -0
  435. package/templates/pixel/serve.sh +12 -0
  436. package/templates/refactor/cm-refactor-denies.json +14 -0
  437. package/templates/rules/backend-api.md +36 -0
  438. package/templates/rules/coding-style.md +44 -0
  439. package/templates/rules/database.md +27 -0
  440. package/templates/rules/finance.md +32 -0
  441. package/templates/rules/frontend.md +32 -0
  442. package/templates/rules/git-workflow.md +25 -0
  443. package/templates/rules/miniprogram.md +31 -0
  444. package/templates/rules/security.md +31 -0
  445. package/templates/rules/smart-contract.md +28 -0
  446. package/templates/rules/testing.md +36 -0
  447. package/templates/statusline/cm-statusline.sh +73 -0
  448. package/templates/ui-lens/cm-ui-lens-extract.mjs +55 -0
@@ -0,0 +1,63 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
7
+ import {savePrdDraft} from '../runtime/js/cm-prd/draft-save.mjs';
8
+ function fixture(t){
9
+ const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-save-')));
10
+ t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));
11
+ const draft={summary:'Synthetic draft',features:[{name:'guide',directory:'1.guide',documents:[
12
+ {path:'requirements.md',content:'# Requirements'}, {path:'design.md',content:'# Design'},
13
+ {path:'tasks.md',content:'- [ ] T-001: Document'}, {path:'test-cases.json',content:'{"synthetic":true}'}]}]};
14
+ draft.draftDigest=digest(draft);
15
+ return {specs,draft,args:{specs,writeEnabled:true,getDraft:()=>draft}};
16
+ }
17
+ test('save exact Markdown and JSON, explicit identical resume, no approval',t=>{
18
+ const {specs,draft,args}=fixture(t);const result=savePrdDraft(args);
19
+ assert.equal(result.status,'draft_saved');assert.equal(result.artifacts.length,4);
20
+ for(const document of draft.features[0].documents){
21
+ const file=path.join(specs,'1.guide',document.path);
22
+ assert.equal(fs.readFileSync(file,'utf8'),document.content);assert.equal(fs.statSync(file).mode&0o777,0o600);
23
+ }
24
+ assert.equal(savePrdDraft(args).status,'draft_saved');
25
+ assert.equal(fs.existsSync(path.join(specs,'.cm-specs-status')),false);
26
+ assert.equal(result.completionAuthorized,false);
27
+ });
28
+ test('disabled and conflict preflight produce zero new spec writes',t=>{
29
+ const {specs,args}=fixture(t);assert.throws(()=>savePrdDraft({...args,writeEnabled:false}),/not_enabled/);
30
+ assert.deepEqual(fs.readdirSync(specs),[]);fs.mkdirSync(path.join(specs,'1.guide'));
31
+ fs.writeFileSync(path.join(specs,'1.guide/tasks.md'),'User content');
32
+ assert.throws(()=>savePrdDraft(args),/save_conflict/);
33
+ assert.deepEqual(fs.readdirSync(path.join(specs,'1.guide')),['tasks.md']);
34
+ });
35
+ test('partial save preserves evidence and only an explicit unchanged resume fills missing files',t=>{
36
+ const {specs,args,draft}=fixture(t);let calls=0;
37
+ const result=savePrdDraft({...args,getDraft:()=>{if(++calls===3)throw Error('interrupted');return draft;}});
38
+ assert.equal(result.status,'draft_save_unknown');
39
+ assert.deepEqual(fs.readdirSync(path.join(specs,'1.guide')),['requirements.md']);
40
+ assert.equal(savePrdDraft(args).status,'draft_saved');
41
+ });
42
+ test('linked feature directory is rejected without following it',t=>{
43
+ const {specs,args}=fixture(t);fs.mkdirSync(path.join(specs,'elsewhere'));
44
+ fs.symlinkSync('elsewhere',path.join(specs,'1.guide'));
45
+ assert.throws(()=>savePrdDraft(args),/init_draft_link/);
46
+ assert.deepEqual(fs.readdirSync(path.join(specs,'elsewhere')),[]);
47
+ });
48
+
49
+ test('lossy surrogate encoding cannot change the draft during save',t=>{
50
+ const {specs,args,draft}=fixture(t);draft.features[0].documents[0].content='Invalid \ud800';
51
+ draft.draftDigest=digest({summary:draft.summary,features:draft.features});
52
+ assert.throws(()=>savePrdDraft(args),/encoding_invalid/);
53
+ assert.deepEqual(fs.readdirSync(specs),[]);
54
+ });
55
+
56
+ test('identical public-readable file is rejected without chmod or partial new writes',t=>{
57
+ const {specs,args,draft}=fixture(t);fs.mkdirSync(path.join(specs,'1.guide'));
58
+ const file=path.join(specs,'1.guide/tasks.md'),content=draft.features[0].documents[2].content;
59
+ fs.writeFileSync(file,content);fs.chmodSync(file,0o644);
60
+ assert.throws(()=>savePrdDraft(args),/save_permissions/);
61
+ assert.deepEqual(fs.readdirSync(path.join(specs,'1.guide')),['tasks.md']);
62
+ assert.equal(fs.readFileSync(file,'utf8'),content);assert.equal(fs.statSync(file).mode&0o777,0o644);
63
+ });
@@ -0,0 +1,39 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
8
+ import {inspectPrdDraft} from '../runtime/js/cm-prd/draft.mjs';
9
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
10
+ const draft=()=>({status:'draft',summary:'Documentation draft',features:[{name:'guide',
11
+ documents:['requirements.md','design.md','tasks.md'].map(file=>({path:file,
12
+ content:file==='requirements.md'?'- [ ] [AC-001] The guide describes setup.':file==='tasks.md'?'- [ ] T-001: Update guide':'# Synthetic design'})),
13
+ testCasesReason:'no_observable_behavior'}]});
14
+ test('draft structure refuses missing triad, unsafe path and dropped user cases',()=>{
15
+ const options={nextIndex:3,generateCases:true,userCasesProvided:false};
16
+ assert.equal(inspectPrdDraft(draft(),options).features[0].directory,'3.guide');
17
+ const missing=draft();missing.features[0].documents.pop();assert.throws(()=>inspectPrdDraft(missing,options));
18
+ const unsafe=draft();unsafe.features[0].documents[0].path='../AGENTS.md';assert.throws(()=>inspectPrdDraft(unsafe,options));
19
+ assert.throws(()=>inspectPrdDraft(draft(),{...options,userCasesProvided:true}));
20
+ });
21
+ test('analysis -> planner clarification -> draft preserves scope and does not write',async t=>{
22
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-draft-')));
23
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
24
+ fs.mkdirSync(path.join(dir,'docs'));fs.mkdirSync(path.join(dir,'2.existing'));
25
+ fs.writeFileSync(path.join(dir,'docs/input.md'),'Documentation need');
26
+ const events=[];let plans=0;
27
+ const host=createCmPrdAnalysis({input:{skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir},
28
+ runtime:'codex',record:async event=>events.push(event),analyze:async()=>({status:'analyzed',summary:'Documentation',
29
+ sourcePaths:['docs/input.md'],openQuestions:[]}),generate:async payload=>{
30
+ plans++;assert.equal(payload.nextIndex,3);assert.equal(payload.analysis.summary,'Documentation');
31
+ assert.equal(payload.role.role,'planner');
32
+ return plans===1?{status:'question',question:'Should the guide include examples?'}:draft();
33
+ }});
34
+ await host.advance('Analyze');assert.equal((await host.plan('Prepare draft')).stage,'awaiting_planning_user');
35
+ const result=await host.plan('Yes');assert.equal(result.stage,'draft_ready');
36
+ assert.equal(result.draft.features[0].directory,'3.guide');assert.equal(result.draft.checks,'structure_only');
37
+ assert.deepEqual(events.map(event=>event.data.role),['analyst','planner','planner']);
38
+ assert.deepEqual(fs.readdirSync(dir).sort(),['2.existing','docs']);
39
+ });
@@ -0,0 +1,245 @@
1
+ // Read-only admission for the existing cm-prd workflow.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {createHash} from 'node:crypto';
6
+ import {readCmInitSource} from '../runtime/js/cm-init/draft-inspection.mjs';
7
+
8
+ const FEATURE_SELECTOR=/^([1-9]\d*)(?:\.([^/\\]+))?$/;
9
+
10
+ function reject(code) {
11
+ const error=new Error(code);
12
+ error.code=code;
13
+ throw error;
14
+ }
15
+
16
+ function frozen(value) {
17
+ if(value&&typeof value==='object'){
18
+ for(const item of Object.values(value))frozen(item);
19
+ Object.freeze(value);
20
+ }
21
+ return value;
22
+ }
23
+
24
+ function text(value,code) {
25
+ if(typeof value!=='string'||value.trim().length===0||value.includes('\0'))reject(code);
26
+ return value;
27
+ }
28
+
29
+ function realDirectory(raw,code) {
30
+ try {
31
+ const target=fs.realpathSync(path.resolve(text(raw,code)));
32
+ const stat=fs.lstatSync(target);
33
+ if(!stat.isDirectory()||stat.isSymbolicLink())reject(code);
34
+ return target;
35
+ } catch(error) {
36
+ if(error?.code===code)throw error;
37
+ reject(code);
38
+ }
39
+ }
40
+
41
+ function realFile(raw,code) {
42
+ try {
43
+ const target=fs.realpathSync(path.resolve(text(raw,code)));
44
+ const stat=fs.lstatSync(target);
45
+ if(!stat.isFile()||stat.isSymbolicLink())reject(code);
46
+ return target;
47
+ } catch(error) {
48
+ if(error?.code===code)throw error;
49
+ reject(code);
50
+ }
51
+ }
52
+
53
+ function ownedFile(root,relative,code) {
54
+ try {
55
+ const target=path.join(root,relative);
56
+ const stat=fs.lstatSync(target);
57
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||fs.realpathSync(target)!==target)reject(code);
58
+ return target;
59
+ } catch(error) {
60
+ if(error?.code===code)throw error;
61
+ reject(code);
62
+ }
63
+ }
64
+
65
+ function workflowRoot(skillDir,changeMode) {
66
+ const skill=realDirectory(skillDir,'skill_path_invalid');
67
+ const root=realDirectory(path.resolve(skill,'../..'),'skill_path_invalid');
68
+ if(skill!==path.join(root,'skills','cm-prd'))reject('skill_path_invalid');
69
+ let layout;
70
+ if(fs.existsSync(path.join(root,'VERSION'))){
71
+ ownedFile(root,'VERSION','skill_path_invalid');layout='plugin';
72
+ }else if(fs.existsSync(path.join(root,'templates','cm-VERSION'))){
73
+ ownedFile(root,'templates/cm-VERSION','skill_path_invalid');layout='claude-compat';
74
+ }else reject('skill_path_invalid');
75
+ if(realDirectory(path.join(root,'templates'),'skill_path_invalid')!==path.join(root,'templates'))
76
+ reject('skill_path_invalid');
77
+ for(const file of ['skills/cm-prd/SKILL.md','runtime/project-context.md','runtime/review.md',
78
+ 'runtime/logging.md','scripts/cm-prd-entry.mjs'])ownedFile(root,file,'skill_path_invalid');
79
+ if(changeMode)ownedFile(root,'skills/cm-prd/references/change-mode.md','skill_path_invalid');
80
+ return {root,skill,layout};
81
+ }
82
+
83
+ function normalizeInput(input) {
84
+ if(!input||typeof input!=='object'||Array.isArray(input))reject('invalid_input');
85
+ const keys=Object.keys(input),allowed=new Set(['skillDir','project','specs','change','cases']);
86
+ if(!['skillDir','project','specs'].every(key=>keys.includes(key))||keys.some(key=>!allowed.has(key)))
87
+ reject('invalid_input');
88
+ return input;
89
+ }
90
+
91
+ function sourceInventory(specs) {
92
+ const files=[];let entries=0;
93
+ const visit=relative=>{
94
+ const directory=path.join(specs,relative);
95
+ if(fs.lstatSync(directory).isSymbolicLink()||realDirectory(directory,'source_path_invalid')!==directory)
96
+ reject('source_path_invalid');
97
+ for(const item of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){
98
+ if(++entries>1000)reject('source_inventory_limit');
99
+ if(item.name.startsWith('.'))continue;
100
+ const file=`${relative}/${item.name}`;
101
+ if(item.isSymbolicLink())reject('source_path_invalid');
102
+ if(item.isDirectory())visit(file);
103
+ else if(item.isFile())files.push(file);
104
+ else reject('source_path_invalid');
105
+ }
106
+ };
107
+ visit('docs');return files;
108
+ }
109
+
110
+ function requirementSources(specs) {
111
+ try {
112
+ const expected=path.join(specs,'docs');
113
+ const docs=realDirectory(expected,'requirements_source_missing');
114
+ if(docs!==expected)return {docs:null,count:0};
115
+ const count=sourceInventory(specs).length;
116
+ return {docs,count};
117
+ } catch(error) {
118
+ if(['source_path_invalid','source_inventory_limit'].includes(error.code))throw error;
119
+ return {docs:null,count:0};
120
+ }
121
+ }
122
+
123
+ function featureCandidates(specs,number) {
124
+ const prefix=`${number}.`;
125
+ return fs.readdirSync(specs,{withFileTypes:true})
126
+ .filter(item=>item.isDirectory()&&item.name.startsWith(prefix))
127
+ .map(item=>item.name).sort((left,right)=>left.localeCompare(right));
128
+ }
129
+
130
+ function validFeatureContract(specs,feature) {
131
+ try {
132
+ const featureRoot=path.join(specs,feature);
133
+ if(realDirectory(featureRoot,'feature_contract_missing')!==featureRoot)return false;
134
+ for(const file of ['requirements.md','design.md','tasks.md'])
135
+ ownedFile(featureRoot,file,'feature_contract_missing');
136
+ return true;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+
142
+ function resultBase(root,skill,layout,project,specs,cases,mode) {
143
+ return {schemaVersion:1,workflow:'cm-prd',mode,workflowRoot:root,skillDir:skill,
144
+ runtimeLayout:layout,project,specs,cases,requiredRoles:['analyst','planner'],
145
+ roleResolution:'pending',logging:'pending',executionAuthorized:false,writeAuthorized:false};
146
+ }
147
+
148
+ export function inspectCmPrdAdmission(raw) {
149
+ const input=normalizeInput(raw),changeMode=Object.hasOwn(input,'change');
150
+ const {root,skill,layout}=workflowRoot(input.skillDir,changeMode);
151
+ const project=realDirectory(input.project,'project_path_invalid');
152
+ const specs=realDirectory(input.specs,'specs_path_invalid');
153
+ const cases=Object.hasOwn(input,'cases')?realFile(input.cases,'cases_path_invalid'):null;
154
+ const mode=changeMode?'change':'new',base=resultBase(root,skill,layout,project,specs,cases,mode);
155
+ if(!changeMode){
156
+ const {docs,count}=requirementSources(specs);
157
+ if(count===0)return frozen({...base,status:'blocked',reason:'requirements_source_missing',
158
+ next:'add_requirements_docs',docs,requirementsSourceCount:0,feature:null,features:[]});
159
+ return frozen({...base,status:'ready',reason:null,next:'requirements_analysis',docs,
160
+ requirementsSourceCount:count,feature:null,features:[]});
161
+ }
162
+ const selector=text(input.change,'change_selector_invalid').trim();
163
+ const match=selector.match(FEATURE_SELECTOR);
164
+ if(!match)reject('change_selector_invalid');
165
+ const candidates=featureCandidates(specs,match[1]);
166
+ let feature=null;
167
+ if(match[2]){
168
+ if(candidates.includes(selector))feature=selector;
169
+ }else if(candidates.length===1)feature=candidates[0];
170
+ else if(candidates.length>1)return frozen({...base,status:'selection_required',
171
+ reason:'feature_required',next:'select_feature',feature:null,features:candidates});
172
+ if(feature===null)return frozen({...base,status:'blocked',reason:'feature_missing',
173
+ next:'select_existing_feature',feature:null,features:candidates});
174
+ if(!validFeatureContract(specs,feature))return frozen({...base,status:'blocked',
175
+ reason:'feature_contract_missing',next:'repair_feature_contract',feature,features:[feature]});
176
+ return frozen({...base,status:'ready',reason:null,next:'change_analysis',feature,features:[feature],
177
+ requirementsSourceCount:null});
178
+ }
179
+
180
+ // Source bytes are data, never instructions or proof of prototype interaction.
181
+ export function inspectCmPrdSources(input){
182
+ const admission=inspectCmPrdAdmission(input);
183
+ if(admission.status!=='ready')return admission;
184
+ if(admission.mode!=='new')reject('source_inspection_new_only');
185
+ const sources=[];let totalBytes=0;
186
+ const readSource=(root,file,displayPath=file)=>{
187
+ const bytes=readCmInitSource(root,file);
188
+ if(bytes===null)reject('source_changed');
189
+ totalBytes+=bytes.length;if(totalBytes>4*1024*1024)reject('source_content_limit');
190
+ const extension=path.extname(file).toLowerCase();
191
+ const format=['.md','.txt'].includes(extension)?'text':['.html','.htm'].includes(extension)?'html':extension==='.pdf'?'pdf':'unsupported';
192
+ const source={path:displayPath,format,bytes:bytes.length,sha256:createHash('sha256').update(bytes).digest('hex'),
193
+ requiredAction:format==='text'?'analyze_text':format==='html'?'inspect_interactions_in_authorized_browser':format==='pdf'?'extract_pdf':'resolve_unsupported_source'};
194
+ if(['text','html'].includes(format)){
195
+ source.content=bytes.toString('utf8');
196
+ if(!Buffer.from(source.content).equals(bytes))reject('source_text_encoding_invalid');
197
+ }
198
+ return source;
199
+ };
200
+ for(const file of sourceInventory(admission.specs))sources.push(readSource(admission.specs,file));
201
+ const userCases=admission.cases===null?null:{...readSource(path.dirname(admission.cases),
202
+ path.basename(admission.cases),admission.cases),origin:'user'};
203
+ if(sources.length===0)reject('source_changed');
204
+ return frozen({...admission,requirementsSourceCount:sources.length,sourceInspection:{sources,userCases,totalBytes,casesInspected:userCases!==null,completeAnalysis:false,
205
+ prototypeInteractionVerified:false,writeAuthorized:false}});
206
+ }
207
+
208
+ function parseCli(argv) {
209
+ const input={},values=new Map([
210
+ ['--skill-dir','skillDir'],['--project','project'],['--specs','specs'],
211
+ ['--change','change'],['--cases','cases']
212
+ ]);
213
+ for(let index=0;index<argv.length;index+=1){
214
+ const key=values.get(argv[index]);
215
+ if(!key||Object.hasOwn(input,key)||index+1>=argv.length||values.has(argv[index+1]))
216
+ reject('invalid_arguments');
217
+ input[key]=argv[index+1];index+=1;
218
+ }
219
+ return input;
220
+ }
221
+
222
+ function isMainModule(entry) {
223
+ if(!entry)return false;
224
+ try {
225
+ return fs.realpathSync(entry)===fileURLToPath(import.meta.url);
226
+ } catch {
227
+ return path.resolve(entry)===fileURLToPath(import.meta.url);
228
+ }
229
+ }
230
+
231
+ if(isMainModule(process.argv[1])){
232
+ try {
233
+ const argv=process.argv.slice(2),sources=argv[0]==='--inspect-sources';
234
+ const result=(sources?inspectCmPrdSources:inspectCmPrdAdmission)(parseCli(sources?argv.slice(1):argv));
235
+ if(fileURLToPath(import.meta.url)!==path.join(result.workflowRoot,'scripts','cm-prd-entry.mjs'))
236
+ reject('entry_path_invalid');
237
+ const output=`${JSON.stringify(result)}\n`;
238
+ if(result.status==='ready')process.stdout.write(output);
239
+ else { process.stderr.write(output);process.exitCode=2; }
240
+ } catch(error) {
241
+ process.stderr.write(`${JSON.stringify({schemaVersion:1,workflow:'cm-prd',status:'error',
242
+ reason:error?.code??'admission_failed',executionAuthorized:false,writeAuthorized:false})}\n`);
243
+ process.exitCode=2;
244
+ }
245
+ }
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ // Current conversation transport; original platform adapter owns log locking.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {inspectCmPrdAdmission} from './cm-prd-entry.mjs';
9
+ import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
10
+ import {runPrdHostReview,validatePrdReviewMode} from '../runtime/js/cm-prd/review-host.mjs';
11
+ import {inspectPrdFindings} from '../runtime/js/cm-prd/review-findings.mjs';
12
+ import {createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
13
+ import {savePrdDraft,savePrdDesign,savePrdPromotedDraft} from '../runtime/js/cm-prd/draft-save.mjs';
14
+ import {createPrdCorrectionOwner,inspectPrdCorrectionRecovery,resumePrdCorrection} from '../runtime/js/cm-prd/review-correction.mjs';
15
+ import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
16
+ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
17
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
18
+ import {need,shape,json,id,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
19
+ import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
20
+ import {createPrdChange,assertPrdReviewsSettled} from '../runtime/js/cm-prd/change.mjs';
21
+ import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
22
+
23
+ export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
24
+ let bridge,analysis,session,change=null,started=false,closed=false,record;
25
+ try{
26
+ if(argv.length===1&&argv[0]==='--help'){
27
+ output.write('New and --change SELECTOR share this host. --session prd-ID resumes a durable local conversation; obtain runId from status. resume {requestId,operation,resolution:null|{callId,requestDigest,result,evidence}} consumes only the original host result, never re-dispatches an unknown call. decision {requestId,operation,proposalDigest,approved,allowUserCaseChanges} confirms an exact change proposal; save_draft archives and writes awaiting_review. prepare_revision {requestId,operation,reason} revises the saved current batch with original review history retained; no review counters reset.\n');
28
+ output.write('promote_design {requestId,operation,draftDigest,reason} moves an unreviewed full draft to design while preserving draft and self-check rounds. Saved drafts require complete exact original bytes with private permissions; partial/conflicting saves, prior review and exhausted rounds are rejected. Saved task revisions archive both versions before replacement; no approval is implied.\n');
29
+ output.write('select_design_reviews {requestId,operation,draftDigest,risks:[{feature,signals,evidence}]} at design_ready freezes host-reported Step 9.5 risks for every feature. Only high-risk features may request design review; low-risk exact saved designs continue without it. Not approval; existing attempts cannot be downgraded.\n');
30
+ output.write('plan_design {requestId,operation,text} generates requirements/design only. design_ready permits save_design with --allow-spec-write and original design review. After original design disposition, advance generates tasks from the exact current design, then original self-check/save_draft. No approval is implied.\n');
31
+ output.write('Optional --allow-spec-write enables save_draft and publish_summary. prepare_summary is read-only; publish_summary {requestId,operation,summaryDigest} requires the exact current prepared summary and writes awaiting_review only, then stops execution. --allow-disposition-write enables original disposition receipts. correct_findings requires both spec and review writes. None grants provider access or specification approval.\n');
32
+ output.write('Optional --allow-review-write --host-context ACTUAL_AUTHOR_ID enables final_review {requestId,operation,stage,feature,mode:independent|self-degraded}. This permits original claim/r1 writes only; the trusted host must have actual review-channel authority. No provider authorization is implied. Interrupted attempts remain unknown and are not retried.\n');
33
+ output.write('cm-prd-host.mjs serve --skill-dir PATH --project PATH --specs PATH --runtime codex|claude --allow-log-write [--cases PATH] [--change SELECTOR] [--session prd-ID]\nJSONL start/advance {requestId,operation,text}; status/cancel/resume. Conversations and pending requests persist privately under specs/.reviews/prd-sessions, never in global log bodies. No provider calls, approval or development.\n');return 0;
34
+ }
35
+ need(argv[0]==='serve'&&argv.filter(x=>x==='--allow-log-write').length===1,'invalid_arguments');
36
+ const reviewEnabled=argv.includes('--allow-review-write');
37
+ const dispositionEnabled=argv.includes('--allow-disposition-write');
38
+ const specWriteEnabled=argv.includes('--allow-spec-write');
39
+ need(argv.filter(x=>x==='--allow-spec-write').length<=1,'invalid_arguments');
40
+ need(argv.filter(x=>x==='--allow-disposition-write').length<=1,'invalid_arguments');
41
+ need(argv.filter(x=>x==='--allow-review-write').length<=1,'invalid_arguments');
42
+ const args=argv.slice(1).filter(x=>!['--allow-log-write','--allow-review-write','--allow-disposition-write','--allow-spec-write'].includes(x)),options={};
43
+ for(let i=0;i<args.length;i+=2){
44
+ need(['--skill-dir','--project','--specs','--runtime','--cases','--host-context','--change','--session'].includes(args[i])
45
+ &&!Object.hasOwn(options,args[i])&&typeof args[i+1]==='string','invalid_arguments');
46
+ options[args[i]]=args[i+1];
47
+ }
48
+ const runtime=options['--runtime'];need(['codex','claude'].includes(runtime),'invalid_runtime');
49
+ const authorContextId=options['--host-context']??null;
50
+ if(authorContextId!==null)id(authorContextId);if(reviewEnabled)need(authorContextId!==null,'prd_review_host_context_required');
51
+ const entry={skillDir:options['--skill-dir'],project:options['--project'],specs:options['--specs'],
52
+ ...(options['--change']?{change:options['--change']} : {}),
53
+ ...(options['--cases']?{cases:options['--cases']}:{})};
54
+ const admission=inspectCmPrdAdmission(entry);
55
+ need(admission.status==='ready'||options['--session']&&admission.mode==='change'&&admission.reason==='feature_missing','prd_admission_blocked');
56
+ need(fileURLToPath(import.meta.url)===path.join(admission.workflowRoot,'scripts/cm-prd-host.mjs'),'entry_path_invalid');
57
+ const runId=options['--session']??`prd-${randomUUID()}`;let routeTurn=0;
58
+ session=openPrdSession({specs:admission.specs,sessionId:runId,identity:{entry,runtime}});
59
+ if(admission.status!=='ready')need(session.state.checkpoint?.change?.stage==='awaiting_review'
60
+ ||session.state.active?.request.operation==='save_draft','prd_admission_blocked');
61
+ record=({event,phase='analysis',data={},at=null})=>{
62
+ if(event==='decision')data={...data,analysis_turn:++routeTurn};
63
+ const result=spawnSync('python3',[path.join(admission.workflowRoot,'scripts/cm-log-event.py'),
64
+ '--workflow','cm-prd','--event',event,'--phase',phase,'--runtime',runtime,
65
+ '--project-root',admission.project,'--specs-dir',admission.specs,'--run-id',runId,
66
+ '--detail','Current conversation PRD workflow','--data-json',JSON.stringify(data),...(at?['--at',at]:[])],
67
+ {env:process.env,encoding:'utf8',timeout:10000,maxBuffer:1024*1024});
68
+ need(!result.error&&result.status===0&&result.signal===null,'prd_log_failed');
69
+ const receipt=JSON.parse(result.stdout);
70
+ need(receipt.run_id===runId&&receipt.project_log===path.join(admission.specs,'运行日志.jsonl'),'prd_log_failed');
71
+ };
72
+ bridge=createHostToolBridge({responseLimit:1024*1024});
73
+ const call=(kind,payload,signal)=>session.call(kind,payload,signal,(body,sig)=>bridge.call(kind,body,sig));
74
+ const restoreAnalysis=restored=>admission.mode==='new'?createCmPrdAnalysis({input:entry,runtime,record,restored,
75
+ checkContext:(payload,signal)=>call('prd_self_check',payload,signal),
76
+ generate:(payload,signal)=>call('prd_generate',payload,signal),
77
+ processMaterials:(payload,signal)=>call('prd_materials',payload,signal),
78
+ analyze:(payload,signal)=>call('prd_analyze',payload,signal)}):null;
79
+ const restoreChange=(restored=null,selected,reason)=>createPrdChange({admission,runtime,call,restored,...(selected?{selected,reason}:{})});
80
+ let reviewState=null;const reviewController=new AbortController();
81
+ let summaryState=null,publishedSummary=false;
82
+ const summarize=createPrdSummaryOwner({summarize:(payload,signal)=>call('prd_summary',{
83
+ ...payload,project:admission.project,analysis:analysis.status(),
84
+ reference:path.join(admission.workflowRoot,'skills/cm-prd/SKILL.md')},signal)});
85
+ const makeCorrect=()=>createPrdCorrectionOwner({correct:(payload,signal)=>call('prd_correct',{
86
+ ...payload,project:admission.project,specs:admission.specs,
87
+ reference:path.join(admission.workflowRoot,'skills/cm-prd/SKILL.md')},signal)});
88
+ let correct=makeCorrect(),replaying=false;
89
+ const dispose=createPrdDispositionOwner({canRecoverRecorded:()=>replaying&&session.state.active.calls.some(call=>call.kind==='prd_self_check'&&Object.hasOwn(call,'result')),
90
+ checkContext:(payload,signal)=>call('prd_self_check',{
91
+ ...payload,project:admission.project,specs:admission.specs,
92
+ reference:path.join(admission.workflowRoot,'skills/cm-prd/references/spec-self-check.md')},signal)});
93
+ const restore=value=>{
94
+ correct=makeCorrect();
95
+ analysis=restoreAnalysis(value?.analysis??null);
96
+ change=value?.change?restoreChange(value.change):admission.mode==='change'?restoreChange():null;
97
+ started=value?.started??false;routeTurn=value?.routeTurn??0;reviewState=value?.reviewState??null;
98
+ summaryState=value?.summaryState??null;publishedSummary=value?.publishedSummary??false;
99
+ };
100
+ const contextStartedAt=new Date().toISOString();
101
+ const stored=session.state,cancelled=stored.checkpoint?.analysis?.stage==='cancelled'||stored.checkpoint?.change?.stage==='cancelled';
102
+ restore(cancelled?stored.checkpoint:stored.active?.before??stored.checkpoint);
103
+ const contextCompletedAt=new Date().toISOString();let contextLogged=false;
104
+ const checkpoint=()=>({analysis:analysis?.checkpoint()??null,change:change?.checkpoint()??null,started,routeTurn,reviewState,summaryState,publishedSummary});
105
+ const status=()=>({...change?.status()??analysis.status(),runId,logWriteEnabled:true,reviewState,summaryState,publishedSummary,
106
+ recovery:session.state.active?{request:session.state.active.request,calls:session.state.active.calls.map(({callId,requestDigest,kind,result})=>
107
+ ({callId,requestDigest,kind,status:result===undefined?'unknown':'recorded'}))}:null});
108
+ const handle=async raw=>{
109
+ const request=json(raw);
110
+ need(['start','advance','plan_design','promote_design','select_design_reviews','status','cancel','final_review_package','final_review','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','prepare_revision','decision'].includes(request.operation),'host_operation_invalid');
111
+ shape(request,['requestId','operation',...(['start','advance','plan_design'].includes(request.operation)?['text']:
112
+ ['final_review_package','review_findings','correct_findings','inspect_correction','resume_correction'].includes(request.operation)?['stage','feature']:
113
+ request.operation==='review_disposition'?['stage','feature','packageDigest','decisions','artifacts']:
114
+ request.operation==='publish_summary'?['summaryDigest']:request.operation==='select_design_reviews'?['draftDigest','risks']:
115
+ request.operation==='promote_design'?['draftDigest','reason']:request.operation==='prepare_revision'?['reason']:
116
+ request.operation==='decision'?['proposalDigest','approved','allowUserCaseChanges']:
117
+ request.operation==='final_review'?['stage','feature','mode']:[])]);
118
+ if(request.operation==='status')return status();
119
+ if(request.operation==='cancel'){analysis?.cancel();change?.cancel();reviewController.abort();return status();}
120
+ if(request.operation==='inspect_correction')return inspectPrdCorrectionRecovery({specs:admission.specs,stage:request.stage,feature:request.feature});
121
+ if(request.operation==='prepare_revision'){
122
+ need(change===null&&analysis!==null&&typeof request.reason==='string'&&request.reason.trim(),'prd_revision_not_ready');
123
+ const selected=analysis.status().draft?.features.map(feature=>feature.directory);need(selected?.length,'prd_revision_no_saved_draft');
124
+ assertPrdReviewsSettled(admission.specs,selected,{requireSplit:true});change=restoreChange(null,selected,request.reason);
125
+ publishedSummary=false;summaryState=null;return status();
126
+ }
127
+ if(change!==null){
128
+ if(request.operation==='decision')return change.confirm(request);
129
+ if(request.operation==='save_draft'){
130
+ const result=change.save(specWriteEnabled);for(const phase of ['changed','awaiting_review'])record({event:'spec_lifecycle',phase,data:{feature_count:result.features.length}});
131
+ publishedSummary=true;return result;
132
+ }
133
+ need(['start','advance'].includes(request.operation)&&!publishedSummary,'prd_change_operation_invalid');
134
+ need(request.operation==='start'?!started:started,'prd_turn_not_ready');
135
+ if(!started){record({event:'run_start'});started=true;}return change.advance(request.text,reviewController.signal);
136
+ }
137
+ need(!publishedSummary,'prd_human_review_required');
138
+ if(request.operation==='promote_design')return analysis.promoteDesign({draftDigest:request.draftDigest,reason:request.reason});
139
+ if(request.operation==='select_design_reviews')return analysis.selectDesignReviews({draftDigest:request.draftDigest,risks:request.risks});
140
+ if(request.operation==='resume_correction')return resumePrdCorrection({specs:admission.specs,stage:request.stage,
141
+ feature:request.feature,writeEnabled:specWriteEnabled&&reviewEnabled},reviewController.signal);
142
+ if(request.operation==='prepare_summary'){
143
+ need(started,'prd_turn_not_ready');summaryState=await summarize(admission.specs,reviewController.signal);return summaryState;
144
+ }
145
+ if(request.operation==='publish_summary'){
146
+ need(summaryState!==null&&summaryState.summaryDigest===request.summaryDigest,'prd_summary_not_ready');
147
+ need(!reviewController.signal.aborted,'cancelled');
148
+ const result=publishPrdAwaitingReview({specs:admission.specs,summary:summaryState,writeEnabled:specWriteEnabled,recover:replaying});
149
+ // Even an uncertain status write must not be silently retried.
150
+ publishedSummary=true;
151
+ if(result.status==='awaiting_review')for(const phase of ['generated','awaiting_review'])
152
+ record({event:'spec_lifecycle',phase,data:{feature_count:result.features.length,task_count:summaryState.totals.tasks}});
153
+ return result;
154
+ }
155
+ if(request.operation==='save_draft')return (analysis.status().designPromotion?.saved===true?savePrdPromotedDraft:savePrdDraft)({specs:admission.specs,
156
+ writeEnabled:specWriteEnabled,getDraft:()=>analysis.currentDraftForSave(),getOriginal:()=>analysis.originalPromotedDraft()});
157
+ if(request.operation==='save_design')return savePrdDesign({specs:admission.specs,
158
+ writeEnabled:specWriteEnabled,getDraft:()=>analysis.currentDesignForSave()});
159
+ if(request.operation==='correct_findings'){
160
+ if(replaying&&fs.existsSync(path.join(admission.specs,`.reviews/prd-${request.feature.replace(/^\d+\./,'')}-${request.stage}-correction.md`)))
161
+ return resumePrdCorrection({specs:admission.specs,stage:request.stage,feature:request.feature,writeEnabled:specWriteEnabled&&reviewEnabled},reviewController.signal);
162
+ return correct({specs:admission.specs,stage:request.stage,feature:request.feature,writeEnabled:specWriteEnabled&&reviewEnabled},reviewController.signal);
163
+ }
164
+ if(request.operation==='review_findings')return inspectPrdFindings({specs:admission.specs,stage:request.stage,feature:request.feature});
165
+ if(request.operation==='review_disposition')return dispose({specs:admission.specs,
166
+ stage:request.stage,feature:request.feature,packageDigest:request.packageDigest,
167
+ decisions:request.decisions,artifacts:request.artifacts,writeEnabled:dispositionEnabled},reviewController.signal);
168
+ if(request.operation==='final_review_package')return analysis.prepareReview(request.stage,request.feature);
169
+ if(request.operation==='final_review'){
170
+ need(reviewEnabled,'prd_review_not_enabled');
171
+ const prepared=analysis.prepareReview(request.stage,request.feature);
172
+ reviewState={status:'reviewing',feature:request.feature,stage:request.stage};
173
+ reviewState=await runPrdHostReview({specs:admission.specs,prepared,authorContextId,writeEnabled:reviewEnabled,
174
+ mode:request.mode,signal:reviewController.signal,revalidate:()=>analysis.prepareReview(request.stage,request.feature),
175
+ review:(payload,signal)=>call('prd_review',{...payload,project:admission.project,specs:admission.specs,
176
+ reference:path.join(admission.workflowRoot,'runtime/steelman-review.md')},signal)});
177
+ return status();
178
+ }
179
+ need(request.operation==='start'?!started:started,'prd_turn_not_ready');
180
+ need(typeof request.text==='string'&&request.text.trim().length>0,'prd_input_invalid');
181
+ if(!started){record({event:'run_start'});started=true;}
182
+ if(request.operation==='plan_design'||analysis.status().stage==='awaiting_design_user'){
183
+ const planned=await analysis.plan(request.text,{designOnly:true});return {...status(),planningReply:planned.planningReply};
184
+ }
185
+ if(analysis.status().stage==='draft_ready')return {...await analysis.verify(),runId,logWriteEnabled:true};
186
+ if(['analysis_ready','design_ready','awaiting_planning_user','draft_self_check_failed','self_check_failed'].includes(analysis.status().stage)){
187
+ const planned=await analysis.plan(request.text);return {...status(),planningReply:planned.planningReply};
188
+ }
189
+ await analysis.advance(request.text);return status();
190
+ };
191
+ const phaseFor=request=>{
192
+ const stage=change?.status().stage??analysis?.status().stage;
193
+ if(request.operation==='final_review')return request.stage==='design'?['prd-design-review','design_review']:['prd-spec-review','spec_review'];
194
+ if(['review_disposition','correct_findings'].includes(request.operation))return request.stage==='design'?['prd-design-review','design_review']:['prd-spec-review','spec_review'];
195
+ if(['save_draft','decision'].includes(request.operation)&&change)return ['prd-spec-validation','spec_validation'];
196
+ if(!['start','advance','plan_design'].includes(request.operation))return null;
197
+ if(['ready','awaiting_user'].includes(stage))return ['prd-requirements','requirements_analysis'];
198
+ if(stage==='change_requirements')return ['prd-requirements','requirements_analysis'];
199
+ if(stage==='change_design'||request.operation==='plan_design'||stage==='awaiting_design_user')return ['prd-design','design_generation'];
200
+ if(['draft_ready','change_check'].includes(stage))return ['prd-spec-validation','spec_validation'];
201
+ return ['prd-task-split','task_split'];
202
+ };
203
+ const host={handle:async request=>{
204
+ if(request.operation==='status')return status();
205
+ if(request.operation==='cancel'){const value=await handle(request);session.checkpoint(checkpoint());return value;}
206
+ if(request.operation==='inspect_correction')return handle(request);
207
+ let operation=request;
208
+ if(request.operation==='resume'){
209
+ shape(request,['requestId','operation','resolution']);
210
+ need(!reviewController.signal.aborted&&session.state.checkpoint?.analysis?.stage!=='cancelled'
211
+ &&session.state.checkpoint?.change?.stage!=='cancelled','cancelled');
212
+ if(request.resolution!==null)session.resolve(request.resolution);
213
+ const active=session.replay();
214
+ need(active.calls.every(call=>Object.hasOwn(call,'result')),'prd_host_result_unknown');
215
+ restore(active.before);operation=active.request;replaying=true;
216
+ // Claim-first review recovery publishes the recorded ORIGINAL result through
217
+ // the existing owner. It must not try to claim or dispatch a second review.
218
+ if(operation.operation==='final_review'&&active.calls.length){
219
+ need(reviewEnabled,'prd_review_not_enabled');const original=active.calls.find(call=>call.kind==='prd_review');
220
+ const prepared=analysis.prepareReview(operation.stage,operation.feature);
221
+ need(prepared.packageDigest===original.payload.package.packageDigest,'prd_review_inputs_changed');
222
+ validatePrdReviewMode(operation.mode,original.result);
223
+ reviewState={status:'review_recorded',...publishPrdReview({specs:admission.specs,reviewPackage:prepared.reviewPackage,
224
+ packageDigest:prepared.packageDigest,authorContextId:original.payload.authorContextId,response:original.result})};
225
+ session.commit(checkpoint());return status();
226
+ }
227
+ }else{replaying=false;session.begin(request,checkpoint());}
228
+ if(!contextLogged){
229
+ const segment=session.segment('context_load');
230
+ record({event:'progress',phase:'start',at:contextStartedAt,data:{operation_id:'prd-context',phase_name:'context_load',segment}});
231
+ record({event:'progress',phase:'complete',at:contextCompletedAt,data:{operation_id:'prd-context',phase_name:'context_load',segment,outcome:'completed'}});
232
+ contextLogged=true;
233
+ }
234
+ const phase=phaseFor(operation),phases=phase?[phase]:[];
235
+ // The accepted full-draft host contract coalesces three outputs in one call.
236
+ // Preserve that efficient contract; report overlapping spans explicitly,
237
+ // never invent per-section clocks or sum them as exclusive elapsed time.
238
+ if(!change&&['advance'].includes(operation.operation)&&['analysis_ready','awaiting_planning_user','draft_self_check_failed','self_check_failed'].includes(analysis.status().stage))
239
+ phases.push(['prd-requirements','requirements_analysis'],['prd-design','design_generation']);
240
+ const segments=phases.map(([operation_id,phase_name])=>({operation_id,phase_name,segment:session.segment(phase_name),
241
+ ...(phases.length>1?{timing_scope:'combined_host_call'}:{})}));
242
+ for(const data of segments)record({event:'progress',phase:'start',data});
243
+ try{
244
+ const result=await handle(operation);
245
+ const pending=session.state.active.calls.some(call=>!Object.hasOwn(call,'result'))
246
+ ||result.status?.includes('unknown')===true||result.reviewState?.status?.includes('unknown')===true
247
+ ||result.reviewState?.gate?.outcome==='dispatch_unknown';
248
+ if(!pending)session.commit(checkpoint());
249
+ for(const data of segments)record({event:'progress',phase:'complete',data:{...data,
250
+ outcome:pending?'blocked':/awaiting|question|confirmation/.test(change?.status().stage??analysis?.status().stage)?'awaiting_input':'completed'}});
251
+ return result;
252
+ }catch(cause){
253
+ for(const data of segments)record({event:'progress',phase:'complete',data:{...data,outcome:'blocked'}});
254
+ if(reviewController.signal.aborted)return status();
255
+ if(!session.state.active.calls.some(call=>!Object.hasOwn(call,'result'))&&session.state.active.calls.length===0)
256
+ session.commit(checkpoint());
257
+ throw cause;
258
+ }
259
+ }};
260
+ const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
261
+ try{await serveCmAiHost({host,input,output,toolBridge:bridge,inputLimit:1024*1024});}finally{if(rawMode)input.setRawMode(false);}
262
+ if(started){
263
+ const stage=change?.status().stage??analysis.status().stage;
264
+ closed=true; // An uncertain terminal log write must not be automatically repeated.
265
+ record({event:'run_done',data:{outcome:stage==='cancelled'?'cancelled':stage==='blocked'?'blocked':'incomplete'}});
266
+ }
267
+ return 0;
268
+ }catch(cause){
269
+ if(started&&!closed&&record)try{closed=true;record({event:'run_done',data:{outcome:'incomplete'}});}catch{}
270
+ error.write(JSON.stringify({error:{code:cause?.code??'prd_host_failed'}})+'\n');return 1;
271
+ }finally{bridge?.close();session?.close();}
272
+ }
273
+ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();