@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,194 @@
1
+ #!/usr/bin/env node
2
+ // Fixed PRD single-review recovery contract. No provider dispatch or task writes.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import {createHash,randomUUID} from 'node:crypto';
7
+ import {TextDecoder} from 'node:util';
8
+ import {fileURLToPath} from 'node:url';
9
+
10
+ const fail=message=>{throw new Error(message);};
11
+ const need=(ok,message)=>{if(!ok)fail(message);};
12
+ const read=p=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(fs.readFileSync(p));
13
+ const hash=p=>createHash('sha256').update(fs.readFileSync(p)).digest('hex');
14
+ const stat=p=>{try{return fs.statSync(p);}catch(e){if(e.code==='ENOENT'||e.code==='ENOTDIR')return null;throw e;}};
15
+ const link=p=>{try{return fs.lstatSync(p).isSymbolicLink();}catch(e){if(e.code==='ENOENT')return false;throw e;}};
16
+ const keys=(v,names)=>v!==null&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join('|')===[...names].sort().join('|');
17
+ const dispositions=['applied','escalated','no_findings'];
18
+ // Python str.strip/re \s exclude BOM and include these Unicode whitespace chars.
19
+ const whitespace='[\\x09-\\x0d\\x1c-\\x20\\x85\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
20
+ const strip=value=>value.replace(new RegExp(`^${whitespace}+|${whitespace}+$`,'g'),'');
21
+ function resolve(p,depth=0){
22
+ need(depth<64,'path resolution limit');
23
+ p=p==='~'?os.homedir():p.startsWith('~/')?os.homedir()+'/'+p.slice(2):p;
24
+ try{return fs.realpathSync.native(p);}catch(e){if(!['ENOENT','ENOTDIR'].includes(e.code))throw e;}
25
+ if(link(p)){
26
+ const target=fs.readlinkSync(p);
27
+ return resolve(path.isAbsolute(target)?target:path.dirname(p)+'/'+target,depth+1);
28
+ }
29
+ const parent=path.dirname(p);need(parent!==p,'cannot resolve path');
30
+ return path.resolve(resolve(parent,depth+1),path.basename(p));
31
+ }
32
+ function within(root,p){const rel=path.relative(root,p);return rel!==''&&!path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
33
+ function counts(disposition,total,unresolved){
34
+ need(dispositions.includes(disposition),'invalid disposition');
35
+ need(Number.isSafeInteger(total)&&Number.isSafeInteger(unresolved)&&total>=0&&unresolved>=0,'finding counts must be non-negative integers');
36
+ need(unresolved<=total,'unresolved_count cannot exceed finding_count');
37
+ need(!['applied','no_findings'].includes(disposition)||unresolved===0,'completed disposition cannot retain unresolved findings');
38
+ need(disposition!=='no_findings'||total===0,'no_findings disposition requires finding_count 0');
39
+ need(disposition!=='escalated'||unresolved>0,'escalated disposition requires unresolved findings');
40
+ }
41
+ function timestamp(value){
42
+ if(typeof value==='string')value=value.replaceAll('Z','+00:00');
43
+ // Match the repository's Python 3.9 datetime.fromisoformat grammar; Date.parse
44
+ // alone accepts non-ISO prose and silently rolls invalid calendar dates over.
45
+ const m=typeof value==='string'&&/^(\d{4})-(\d{2})-(\d{2})[\s\S](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(?:\d{3}|\d{6}))?)?)?(?:Z|[+-](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}|\d{6}))?)?)$(?![\s\S])/.exec(value);
46
+ need(m,'PRD review timestamp must be ISO-8601 with a timezone');
47
+ const year=Number(m[1]),month=Number(m[2]),day=Number(m[3]);
48
+ const days=[31,year%4===0&&(year%100!==0||year%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];
49
+ need(year>=1&&month>=1&&month<=12&&day>=1&&day<=days[month-1]
50
+ &&Number(m[4])<24&&Number(m[5]??0)<60&&Number(m[6]??0)<60
51
+ &&Number(m[7]??0)*3600+Number(m[8]??0)*60+Number(m[9]??0)+Number('0.'+(m[10]??'0'))<86400,
52
+ 'PRD review timestamp is invalid');
53
+ }
54
+ function paths(args){
55
+ need(typeof args.feature==='string'&&args.feature.length>0&&!/[<>:"/\\|?*\x00-\x1f]/.test(args.feature)
56
+ &&!['.','..'].includes(args.feature)&&!/[ .]$/.test(args.feature),'feature must be a safe filename slug');
57
+ need(['design','split'].includes(args.stage),'invalid stage');
58
+ const evidence=resolve(args.evidence),receipt=resolve(args.receipt),prefix=`prd-${args.feature}-${args.stage}`;
59
+ need(path.basename(evidence)===prefix+'-r1.md',`evidence must use ${prefix}-r1.md`);
60
+ need(path.basename(receipt)===prefix+'-disposition.json'&&path.dirname(receipt)===path.dirname(evidence),
61
+ `receipt must be adjacent and use ${prefix}-disposition.json`);
62
+ need(!link(path.dirname(evidence)),'review directory must not be a symlink');
63
+ need(!stat(path.join(path.dirname(evidence),prefix+'-r2.md')),'single-attempt PRD review forbids r2 evidence');
64
+ return {evidence,receipt};
65
+ }
66
+ function evidenceHeader(file){
67
+ need(!link(file),'PRD review evidence must not be a symlink');
68
+ const lines=read(file).split(/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/);
69
+ need(strip(lines[0]??'')==='---','PRD review evidence must start with a YAML header');
70
+ const end=lines.findIndex((line,i)=>i>0&&strip(line)==='---');need(end>0,'PRD review evidence header is not closed');
71
+ const fields=new Map(),scope=[];let inScope=false;
72
+ for(const line of lines.slice(1,end)){
73
+ const field=new RegExp(`^([A-Za-z_][A-Za-z0-9_-]*):${whitespace}*(.*)$`).exec(line);
74
+ if(field){need(!fields.has(field[1]),`PRD review evidence duplicates ${field[1]}`);
75
+ fields.set(field[1],strip(field[2]));inScope=field[1]==='scope';continue;}
76
+ const item=new RegExp(`^${whitespace}+-${whitespace}+(.+)$`).exec(line);
77
+ if(inScope&&item){scope.push(strip(item[1]));continue;}
78
+ need(!strip(line),'PRD review evidence header contains invalid YAML');
79
+ }
80
+ for(const key of ['at','reviewer','independent','scope'])need(fields.has(key),`PRD review evidence is missing ${key}`);
81
+ const reviewer=fields.get('reviewer');
82
+ need(['codex-subagent','codex-cli','self-degraded'].includes(reviewer),'PRD review evidence reviewer is not a supported channel');
83
+ need(reviewer==='self-degraded'?fields.get('independent')==='false'&&Boolean(fields.get('degraded_reason'))
84
+ :fields.get('independent')==='true','PRD review independence evidence invalid');
85
+ need(!fields.get('scope')&&scope.length>0&&scope.every(Boolean),'PRD review evidence scope must be a non-empty list');
86
+ timestamp(fields.get('at'));need(strip(lines.slice(end+1).join('\n')),'PRD review evidence body must not be empty');
87
+ }
88
+ function loadReceipt(file,args,evidence){
89
+ need(!link(file),'PRD review receipt must not be a symlink');
90
+ const value=JSON.parse(read(file));
91
+ need(keys(value,['schema_version','stage','feature','status','disposition','finding_count','unresolved_count',
92
+ 'evidence','evidence_sha256','artifacts','at']),'PRD review receipt fields do not match the contract');
93
+ need(value.schema_version===1&&value.stage===args.stage&&value.feature===args.feature&&value.status==='completed'
94
+ &&value.evidence===path.basename(evidence)&&value.evidence_sha256===hash(evidence),'PRD review receipt does not match current evidence');
95
+ counts(value.disposition,value.finding_count,value.unresolved_count);timestamp(value.at);
96
+ need(Array.isArray(value.artifacts)&&value.artifacts.length>0,'PRD review receipt must contain artifact hashes');
97
+ const root=resolve(path.dirname(path.dirname(file))),seen=new Set();
98
+ for(const item of value.artifacts){
99
+ need(keys(item,['path','sha256'])&&typeof item.path==='string'&&typeof item.sha256==='string'
100
+ &&/^[0-9a-f]{64}$/.test(item.sha256),'PRD review receipt contains an invalid artifact');
101
+ need(!item.path.startsWith('/')&&!item.path.includes('\\')&&!item.path.split('/').includes('..')&&!seen.has(item.path),
102
+ 'PRD review receipt contains an unsafe artifact path');seen.add(item.path);
103
+ const raw=path.join(root,item.path);need(!link(raw),'PRD review artifact is missing or unsafe');
104
+ const artifact=resolve(raw);need(within(root,artifact),'PRD review artifact escapes the specs directory');
105
+ need(stat(artifact)?.isFile(),'PRD review artifact is missing or unsafe');
106
+ need(hash(artifact)===item.sha256,'PRD review artifact changed after disposition');
107
+ }
108
+ return value;
109
+ }
110
+ function dispatchFile(evidence){return evidence.replace(/-r1\.md$/,'-dispatch.json');}
111
+ function loadDispatch(file,args){
112
+ let info;try{info=fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}
113
+ need(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1&&info.size<=4096&&resolve(file)===file,'unsafe PRD dispatch record');
114
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);let value;
115
+ try{
116
+ const opened=fs.fstatSync(fd),bytes=Buffer.alloc(4097),count=fs.readSync(fd,bytes,0,bytes.length,0);
117
+ need(opened.isFile()&&opened.nlink===1&&count===opened.size&&count<=4096,'invalid PRD dispatch record');
118
+ value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,count)));
119
+ }finally{fs.closeSync(fd);}
120
+ need(keys(value,['schema_version','stage','feature','package_sha256','status','at'])
121
+ &&value.schema_version===1&&value.stage===args.stage&&value.feature===args.feature&&value.status==='started'
122
+ &&typeof value.package_sha256==='string'&&/^[0-9a-f]{64}$/.test(value.package_sha256),'invalid PRD dispatch record');
123
+ timestamp(value.at);return value;
124
+ }
125
+ export function claimPrdReview(args){
126
+ const {evidence,receipt}=paths(args),directory=path.dirname(evidence),file=dispatchFile(evidence);
127
+ need(path.resolve(args.evidence)===evidence&&path.resolve(args.receipt)===receipt
128
+ &&fs.lstatSync(directory).isDirectory()&&!fs.lstatSync(directory).isSymbolicLink(),'unsafe PRD dispatch directory');
129
+ need(typeof args.package_sha256==='string'&&/^[0-9a-f]{64}$/.test(args.package_sha256),'invalid package digest');
130
+ need(inspectPrdReview(args).outcome==='dispatch_once','PRD review attempt already consumed');
131
+ const value={schema_version:1,stage:args.stage,feature:args.feature,package_sha256:args.package_sha256,
132
+ status:'started',at:new Date().toISOString()};
133
+ // Exclusive creation arbitrates competing callers. Partial/uncertain records
134
+ // deliberately remain blocking; there is no delete/reset/retry operation.
135
+ const fd=fs.openSync(file,'wx',0o600);
136
+ try{fs.writeFileSync(fd,JSON.stringify(value)+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
137
+ if(process.platform!=='win32'){
138
+ const directoryFd=fs.openSync(directory,'r');try{fs.fsyncSync(directoryFd);}finally{fs.closeSync(directoryFd);}
139
+ }
140
+ paths(args);need(!stat(evidence)&&!stat(receipt),'PRD evidence appeared during claim; do not dispatch');
141
+ loadDispatch(file,args);
142
+ return {stage:args.stage,feature:args.feature,outcome:'dispatch_claimed',dispatch_record:file,
143
+ package_sha256:args.package_sha256,providerAuthorized:false,completionAuthorized:false};
144
+ }
145
+ export function inspectPrdReview(args){
146
+ const {evidence,receipt}=paths(args);
147
+ const dispatch=loadDispatch(dispatchFile(evidence),args);
148
+ const base={stage:args.stage,feature:args.feature,...(dispatch?{package_sha256:dispatch.package_sha256}:{})};
149
+ need(!stat(receipt)||stat(evidence)?.isFile(),'PRD review receipt exists without its r1 evidence');
150
+ if(!stat(evidence))return dispatch?{...base,outcome:'dispatch_unknown',package_sha256:dispatch.package_sha256}:
151
+ {...base,outcome:'dispatch_once'};
152
+ evidenceHeader(evidence);if(!stat(receipt))return {...base,outcome:'resume_disposition'};
153
+ const value=loadReceipt(receipt,args,evidence);return {...base,outcome:'completed',disposition:value.disposition};
154
+ }
155
+ export function recordPrdReview(args){
156
+ counts(args.disposition,args.finding_count,args.unresolved_count);
157
+ const {evidence,receipt}=paths(args),base={stage:args.stage,feature:args.feature};evidenceHeader(evidence);
158
+ if(stat(receipt)){loadReceipt(receipt,args,evidence);return {...base,outcome:'already_recorded'};}
159
+ const root=resolve(path.dirname(path.dirname(receipt))),seen=new Set();
160
+ need(Array.isArray(args.artifact)&&args.artifact.length>0,'artifact required');
161
+ const artifacts=args.artifact.map(raw=>{
162
+ const file=resolve(raw);need(stat(file)?.isFile()&&!link(file),'artifact must be a regular non-symlink file');
163
+ need(within(root,file),'artifact must stay inside the specs directory');
164
+ const relative=path.relative(root,file).split(path.sep).join('/');need(!seen.has(relative),'artifact must not be duplicated');
165
+ seen.add(relative);return {path:relative,sha256:hash(file)};
166
+ });
167
+ const value={schema_version:1,...base,status:'completed',disposition:args.disposition,finding_count:args.finding_count,
168
+ unresolved_count:args.unresolved_count,evidence:path.basename(evidence),evidence_sha256:hash(evidence),artifacts,
169
+ at:new Date().toISOString().replace(/\.\d{3}Z$/,'+00:00')};
170
+ const temp=path.join(path.dirname(receipt),`.${path.basename(receipt)}.${randomUUID()}`);let fd;
171
+ try{
172
+ fd=fs.openSync(temp,'wx',0o600);fs.writeFileSync(fd,JSON.stringify(value)+'\n');fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
173
+ fs.renameSync(temp,receipt);
174
+ }finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(temp);}catch(e){if(e.code!=='ENOENT')throw e;}}
175
+ return {...base,outcome:'recorded'};
176
+ }
177
+ export function main(argv=process.argv.slice(2)){
178
+ try{
179
+ const [command,...flags]=argv;need(['inspect','record','claim'].includes(command),'expected inspect, record or claim');
180
+ const args={},allowed=['stage','feature','evidence','receipt',...(command==='record'?['artifact','disposition','finding-count','unresolved-count']:command==='claim'?['package-sha256']:[])];
181
+ for(let i=0;i<flags.length;i++){
182
+ const flag=flags[i],equal=flag.indexOf('='),key=flag.slice(2,equal<0?undefined:equal);
183
+ need(flag.startsWith('--')&&allowed.includes(key),'invalid arguments');
184
+ const value=equal<0?flags[++i]:flag.slice(equal+1);need(value!==undefined,'missing argument');
185
+ if(key==='artifact')(args.artifact??=[]).push(value);else args[key.replaceAll('-','_')]=value;
186
+ }
187
+ for(const key of allowed)need(Object.hasOwn(args,key.replaceAll('-','_')),'missing required argument');
188
+ for(const key of ['finding_count','unresolved_count'])if(Object.hasOwn(args,key)){
189
+ need(/^[+-]?\d+$/.test(args[key]),'invalid finding count');args[key]=Number(args[key]);}
190
+ const result=command==='inspect'?inspectPrdReview(args):command==='claim'?claimPrdReview(args):recordPrdReview(args);
191
+ process.stdout.write(JSON.stringify(result)+'\n');return 0;
192
+ }catch(error){process.stderr.write(`cm-prd-review-gate: ${error.message}\n`);return 1;}
193
+ }
194
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python3
2
+ """Compatibility CLI; PRD review recovery rules live in cm-prd-review-gate.mjs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from pathlib import Path
8
+ import subprocess
9
+ import sys
10
+
11
+
12
+ def main() -> int:
13
+ entry = Path(__file__).resolve().with_name("cm-prd-review-gate.mjs")
14
+ try:
15
+ result = subprocess.run(
16
+ [os.environ.get("CM_NODE_BIN", "node"), str(entry), *sys.argv[1:]],
17
+ check=False,
18
+ )
19
+ except OSError as error:
20
+ print(f"cm-prd-review-gate: cannot start JavaScript runtime: {error}", file=sys.stderr)
21
+ return 1
22
+ return result.returncode if result.returncode >= 0 else 128 - result.returncode
23
+
24
+
25
+ if __name__ == "__main__":
26
+ raise SystemExit(main())
@@ -0,0 +1,30 @@
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 {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
7
+ import {runPrdHostReview} from '../runtime/js/cm-prd/review-host.mjs';
8
+ for(const mode of ['success','denied','disconnect','cancel','mode-switch'])test(`host review once: ${mode}`,async t=>{
9
+ const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-review-host-')));
10
+ t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));
11
+ const draft={draftDigest:'a'.repeat(64),features:[{directory:'1.guide',name:'guide',documents:[
12
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide'},
13
+ {path:'design.md',content:'## 方案摘要\nGuide'},{path:'tasks.md',content:'- [ ] T-001: Guide'}]}]};
14
+ const prepare=()=>preparePrdReview({specs,draft,stage:'split',feature:'1.guide'}),controller=new AbortController();
15
+ let calls=0;
16
+ const run=()=>runPrdHostReview({specs,prepared:prepare(),authorContextId:'author',writeEnabled:mode!=='denied',mode:'independent',
17
+ revalidate:prepare,signal:controller.signal,review:async payload=>{
18
+ calls++;
19
+ if(mode==='disconnect')throw Error('Disconnected');
20
+ if(mode==='cancel')controller.abort();
21
+ return {reviewer:mode==='mode-switch'?'self-degraded':'codex-subagent',contextId:'reviewer',independent:true,
22
+ at:'2026-09-08T00:00:00.000Z',result:{verdict:'approved',packageDigest:payload.package.packageDigest,
23
+ examinedPaths:payload.examinedPaths,findings:[],summary:'Synthetic review'}};
24
+ }});
25
+ if(mode==='denied'){await assert.rejects(run());assert.equal(calls,0);assert.deepEqual(fs.readdirSync(specs),[]);return;}
26
+ const result=await run();assert.equal(calls,1);
27
+ assert.equal(result.status,mode==='success'?'review_recorded':mode==='cancel'?'review_cancelled':'review_unknown');
28
+ const file=path.join(specs,'.reviews/prd-guide-split-r1.md');assert.equal(fs.existsSync(file),mode==='success');
29
+ if(['disconnect','mode-switch'].includes(mode)){assert.equal((await run()).status,'review_existing');assert.equal(calls,1);}
30
+ });
@@ -0,0 +1,69 @@
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 {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
7
+ import {recordPrdReview,claimPrdReview} from './cm-prd-review-gate.mjs';
8
+ function fixture(t){
9
+ const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-review-prep-')));
10
+ t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));
11
+ const documents=[{path:'requirements.md',content:'# Req\n## 功能需求\n1. [F-001] Guide\n## 私有附录\nNot needed in split'},
12
+ {path:'design.md',content:'# Design\n## 功能模块设计\nGuide\n## 接口契约\nNone\n## 无关附录\nNot needed in split'},
13
+ {path:'tasks.md',content:'- [ ] T-001: Guide'}];
14
+ const draft={draftDigest:'a'.repeat(64),features:[{name:'guide',directory:'1.guide',documents}]};
15
+ return {specs,draft,documents,prepare:stage=>preparePrdReview({specs,draft,stage,feature:'1.guide'})};
16
+ }
17
+ test('preparation uses original gate without writes and keeps split package scoped',t=>{
18
+ const {specs,prepare}=fixture(t);
19
+ const result=prepare('split');assert.equal(result.gate.outcome,'dispatch_once');
20
+ assert.equal(result.dispatchAuthorized,false);assert.deepEqual(fs.readdirSync(specs),[]);
21
+ assert.ok(!JSON.stringify(result.reviewPackage.content).includes('Not needed in split'));
22
+ assert.ok(prepare('design').reviewPackage.content.requirements.includes('Not needed in split'));
23
+ });
24
+ test('existing r1 and disposition resume via original gate, stale draft and r2 fail',t=>{
25
+ const {specs,draft,documents,prepare}=fixture(t);fs.mkdirSync(path.join(specs,'.reviews'));fs.mkdirSync(path.join(specs,'1.guide'));
26
+ for(const document of documents)fs.writeFileSync(path.join(specs,'1.guide',document.path),document.content);
27
+ const args=prepare('design').paths;
28
+ fs.writeFileSync(args.evidence,'---\nat: 2026-09-08T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - 1.guide/design.md\n---\nSynthetic review.');
29
+ assert.equal(prepare('design').gate.outcome,'resume_disposition');
30
+ recordPrdReview({...args,disposition:'no_findings',finding_count:0,unresolved_count:0,
31
+ artifact:[path.join(specs,'1.guide/design.md')]});
32
+ assert.equal(prepare('design').gate.outcome,'completed');
33
+ draft.features[0].documents[0].content+=' changed';assert.throws(()=>prepare('design'),/prd_review_draft_disk_mismatch/);
34
+ fs.writeFileSync(path.join(specs,'.reviews/prd-guide-design-r2.md'),'Not allowed');assert.throws(()=>prepare('design'));
35
+ });
36
+ test('historic review slug collisions cannot select another feature review',t=>{
37
+ const {specs,prepare}=fixture(t);fs.mkdirSync(path.join(specs,'2.guide'));
38
+ assert.throws(()=>prepare('split'),/prd_review_slug_collision/);
39
+ });
40
+ test('split keeps Chinese and English summary sections and rejects contracts alone',t=>{
41
+ const {draft,prepare}=fixture(t),design=draft.features[0].documents.find(item=>item.path==='design.md');
42
+ for(const heading of ['方案摘要','Summary']){
43
+ design.content=`# Design\n## ${heading}\nCritical choice\n## 接口契约\nAPI details`;
44
+ assert.ok(prepare('split').reviewPackage.content.designSummary.includes('Critical choice'));
45
+ }
46
+ design.content='# Design\n## 接口契约\nAPI details';
47
+ assert.throws(()=>prepare('split'),/prd_review_design_summary_missing/);
48
+ });
49
+ test('unknown dispatch stays bound to original package without requiring spec writes',t=>{
50
+ const {specs,draft,prepare}=fixture(t);fs.mkdirSync(path.join(specs,'.reviews'));
51
+ const ready=prepare('split');claimPrdReview({...ready.paths,package_sha256:ready.packageDigest});
52
+ assert.equal(prepare('split').gate.outcome,'dispatch_unknown');
53
+ draft.draftDigest='b'.repeat(64);
54
+ assert.throws(()=>prepare('split'),/prd_review_dispatch_package_changed/);
55
+ });
56
+ test('dispatch package binding survives r1 and completed disposition',t=>{
57
+ for(const completed of [false,true]){
58
+ const {specs,draft,documents,prepare}=fixture(t);fs.mkdirSync(path.join(specs,'.reviews'));fs.mkdirSync(path.join(specs,'1.guide'));
59
+ for(const document of documents)fs.writeFileSync(path.join(specs,'1.guide',document.path),document.content);
60
+ const ready=prepare('design');claimPrdReview({...ready.paths,package_sha256:ready.packageDigest});
61
+ fs.writeFileSync(ready.paths.evidence,'---\nat: 2026-09-08T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - 1.guide/design.md\n---\nSynthetic original package review');
62
+ if(completed)recordPrdReview({...ready.paths,disposition:'no_findings',finding_count:0,unresolved_count:0,
63
+ artifact:[path.join(specs,'1.guide/design.md')]});
64
+ assert.equal(prepare('design').gate.package_sha256,ready.packageDigest);
65
+ draft.features[0].documents[0].content+='\nNew requirement';
66
+ fs.writeFileSync(path.join(specs,'1.guide/requirements.md'),draft.features[0].documents[0].content);
67
+ assert.throws(()=>prepare('design'),/prd_review_dispatch_package_changed/);
68
+ }
69
+ });
@@ -0,0 +1,95 @@
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 {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
7
+ import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
8
+ import {inspectPrdFindings} from '../runtime/js/cm-prd/review-findings.mjs';
9
+ import {claimPrdReview,inspectPrdReview} from './cm-prd-review-gate.mjs';
10
+ function fixture(t){
11
+ const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-r1-')));
12
+ t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));fs.mkdirSync(path.join(specs,'.reviews'));
13
+ const feature='1.guide',draft={draftDigest:'a'.repeat(64),features:[{directory:feature,name:'guide',documents:[
14
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide'},
15
+ {path:'design.md',content:'## 方案摘要\nDocumentation'},
16
+ {path:'tasks.md',content:'- [ ] T-001: Guide'}]}]};
17
+ const prepared=preparePrdReview({specs,draft,stage:'split',feature});
18
+ const response={reviewer:'codex-subagent',contextId:'reviewer-context',independent:true,at:'2026-09-08T00:00:00.000Z',
19
+ result:{verdict:'approved',packageDigest:prepared.packageDigest,
20
+ examinedPaths:['1.guide/design.md','1.guide/requirements.md','1.guide/tasks.md'],findings:[],summary:'Synthetic no findings'}};
21
+ return {specs,prepared,response,claim:()=>claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest}),
22
+ publish:()=>publishPrdReview({specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author-context',response})};
23
+ }
24
+ test('claimed result publishes r1 once, readback resumes original gate and conflict preserves bytes',t=>{
25
+ const {prepared,response,claim,publish}=fixture(t);claim();
26
+ const result=publish();assert.equal(result.gate.outcome,'resume_disposition');assert.equal(result.completionAuthorized,false);
27
+ const bytes=fs.readFileSync(prepared.paths.evidence);assert.equal(fs.statSync(prepared.paths.evidence).mode&0o777,0o600);
28
+ assert.equal(publish().outcome,'r1_published');
29
+ response.result.summary='Different later review';assert.throws(publish,/review_file_conflict/);
30
+ assert.deepEqual(fs.readFileSync(prepared.paths.evidence),bytes);
31
+ assert.equal(fs.existsSync(prepared.paths.receipt),false);
32
+ });
33
+ test('unclaimed or non-independent self-report cannot publish independent r1',t=>{
34
+ const {prepared,response,claim,publish}=fixture(t);assert.throws(publish,/prd_review_unclaimed/);
35
+ claim();response.contextId='author-context';assert.throws(publish,/prd_review_independence_invalid/);
36
+ assert.equal(fs.existsSync(prepared.paths.evidence),false);
37
+ response.contextId='reviewer-context';response.result.examinedPaths=[];assert.throws(publish,/missing_material/);
38
+ assert.equal(inspectPrdReview(prepared.paths).outcome,'dispatch_unknown');
39
+ });
40
+ test('canonical native subagent identity is preserved without granting completion',t=>{
41
+ const {prepared,response,claim,publish}=fixture(t);claim();
42
+ response.contextId='/root/reviewer_1/nested_review';
43
+ const original=JSON.stringify(response),result=publish();
44
+ assert.equal(result.independent,true);assert.equal(result.completionAuthorized,false);
45
+ assert.ok(fs.readFileSync(prepared.paths.evidence,'utf8').includes(original));
46
+ assert.equal(fs.existsSync(prepared.paths.receipt),false);
47
+ });
48
+ test('invalid identities and canonical IDs from other channels cannot publish',t=>{
49
+ const {prepared,response,claim,publish}=fixture(t);claim();
50
+ for(const context of ['/root','/root/../reviewer','/root//reviewer','/root/reviewer/','/other/reviewer',
51
+ '/root/Reviewer','/root/reviewer-name','/root/reviewer\n','/root/reviewer\0',
52
+ '/root/'+ 'x'.repeat(123),'reviewer\n','/root/with space']){
53
+ response.contextId=context;assert.throws(publish,/invalid_input/);
54
+ assert.equal(fs.existsSync(prepared.paths.evidence),false);
55
+ }
56
+ response.contextId='/root/reviewer';response.independent=false;
57
+ assert.throws(publish,/prd_review_independence_invalid/);
58
+ response.independent=true;response.reviewer='codex-cli';assert.throws(publish,/invalid_input/);
59
+ assert.equal(inspectPrdReview(prepared.paths).outcome,'dispatch_unknown');
60
+ });
61
+ test('changes and explicit self-degradation stay findings, not completion or independent approval',t=>{
62
+ const {prepared,response,claim,publish}=fixture(t);claim();
63
+ response.reviewer='self-degraded';response.contextId='author-context';response.independent=false;
64
+ response.degradedReason='Independent channel unavailable';response.result.verdict='changes_requested';
65
+ response.result.findings=[{id:'R1',severity:'P2',path:'1.guide/tasks.md',message:'Missing task',evidence:'Synthetic finding'}];
66
+ const result=publish();assert.equal(result.independent,false);assert.equal(result.verdict,'changes_requested');
67
+ assert.match(fs.readFileSync(prepared.paths.evidence,'utf8'),/independent: false/);
68
+ assert.equal(result.gate.outcome,'resume_disposition');assert.equal(fs.existsSync(prepared.paths.receipt),false);
69
+ });
70
+
71
+ test('archived findings read without draft files and never repair or redispatch',t=>{
72
+ const {specs,prepared,response,claim,publish}=fixture(t);claim();
73
+ const inspect=()=>inspectPrdFindings({specs,stage:'split',feature:'1.guide'});
74
+ assert.throws(inspect,/prd_review_archive_unavailable/);
75
+ assert.equal(fs.existsSync(prepared.paths.evidence),false);
76
+ response.result.verdict='changes_requested';
77
+ response.result.findings=[{id:'R1',severity:'P2',path:'1.guide/tasks.md',message:'Missing task',evidence:'Synthetic finding'}];
78
+ publish();const before=fs.readFileSync(prepared.paths.evidence);
79
+ const result=inspect();assert.deepEqual(result.findings,response.result.findings);
80
+ assert.equal(result.next,'resolve_original_findings');assert.equal(result.completionAuthorized,false);
81
+ assert.equal(fs.existsSync(path.join(specs,'1.guide')),false);
82
+ assert.equal(fs.existsSync(prepared.paths.receipt),false);
83
+ assert.throws(()=>inspectPrdFindings({specs,stage:'split',feature:'2.guide'}),/identity_mismatch/);
84
+ fs.writeFileSync(prepared.paths.evidence,before.toString().replace('verdict: changes_requested','verdict: approved'));
85
+ assert.throws(inspect,/review_file_conflict/);
86
+ assert.equal(fs.readFileSync(prepared.paths.evidence,'utf8').includes('verdict: approved'),true);
87
+ });
88
+
89
+ test('blocked review with no findings cannot suggest no-findings disposition',t=>{
90
+ const {specs,response,claim,publish}=fixture(t);claim();
91
+ response.result.verdict='blocked';publish();
92
+ const result=inspectPrdFindings({specs,stage:'split',feature:'1.guide'});
93
+ assert.equal(result.next,'keep_blocked_and_request_human_review');
94
+ assert.equal(result.completionAuthorized,false);
95
+ });
@@ -0,0 +1,32 @@
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
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
9
+ for(const mode of ['repair','limit','scope'])test(`bounded self-check revision: ${mode}`,async t=>{
10
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-revision-')));
11
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.mkdirSync(path.join(dir,'docs'));
12
+ fs.writeFileSync(path.join(dir,'docs/input.md'),'Documentation request');let drafts=0,checks=0;
13
+ const host=createCmPrdAnalysis({input:{skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir},
14
+ runtime:'codex',record:async()=>{},analyze:async()=>({status:'analyzed',summary:'Guide',sourcePaths:['docs/input.md'],openQuestions:[]}),
15
+ generate:async payload=>{
16
+ drafts++;assert.equal(payload.revision===null,drafts===1);
17
+ return {status:'draft',summary:'Guide',features:[{name:mode==='scope'&&drafts===2?'outside':'guide',testCasesReason:'no_observable_behavior',
18
+ documents:[{path:'requirements.md',content:'- [ ] [AC-001] Document setup.'},
19
+ {path:'tasks.md',content:'- [ ] T-001: Update guide'},{path:'design.md',content:`# Design v${drafts}`}]}]};
20
+ },checkContext:async({draft})=>{
21
+ checks++;return {draftDigest:draft.draftDigest,features:draft.features.map(feature=>({directory:feature.directory,
22
+ checks:draft.mechanicalSelfCheck.pending.map((id,index)=>({id,status:index===0&&(checks===1||mode==='limit')?'failed':'passed',
23
+ evidence:['Synthetic context finding']}))}))};
24
+ }});
25
+ await host.advance('Analyze');await host.plan('Draft');assert.equal((await host.verify()).stage,'self_check_failed');
26
+ if(mode==='scope'){await assert.rejects(host.plan('Fix findings'),/prd_revision_scope_changed/);return;}
27
+ await host.plan('Fix findings');const result=await host.verify();
28
+ assert.equal(result.stage,mode==='repair'?'self_check_reported_passed':'self_check_needs_human');
29
+ assert.equal(result.selfCheckRound,2);assert.equal(result.selfCheckHistory.length,1);
30
+ await assert.rejects(host.plan('Again'));await assert.rejects(host.verify());
31
+ assert.equal(drafts,2);assert.equal(checks,2);assert.deepEqual(fs.readdirSync(dir),['docs']);
32
+ });
@@ -0,0 +1,23 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {checkPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
4
+ const contract={schemaVersion:'1.0',feature:'sample',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,
5
+ acIds:['AC-001'],taskIds:['T-001'],title:'Check behavior',preconditions:[],steps:['Do it'],expected:['Works'],cleanup:[]}]};
6
+ function draft(tasks='- [ ] T-001: Implement behavior',cases=contract){
7
+ return {draftDigest:'a'.repeat(64),features:[{directory:'1.sample',name:'sample',documents:[
8
+ {path:'requirements.md',content:'- [ ] [AC-001] Behavior works.'},{path:'tasks.md',content:tasks},
9
+ {path:'test-cases.json',content:JSON.stringify(cases)}]}]};
10
+ }
11
+ test('mechanical check reuses task parser and case validator without claiming full self-check',()=>{
12
+ const report=checkPrdDraftMechanics(draft());assert.equal(report.status,'mechanical_subset_passed');
13
+ assert.equal(report.completeSelfCheck,false);assert.equal(report.independentReview,false);
14
+ assert.ok(report.pending.includes('user_case_semantics'));
15
+ });
16
+ test('cycles, task budget, false declarations and missing AC/task references fail',()=>{
17
+ assert.ok(checkPrdDraftMechanics(draft('- [ ] T-001: A\n- [ ] T-002: B\n- T-001 依赖 T-002\n- T-002 依赖 T-001')).findings.some(x=>x.code==='dependencies_invalid'));
18
+ assert.ok(checkPrdDraftMechanics(draft(Array.from({length:16},(_,i)=>`- [ ] T-${String(i+1).padStart(3,'0')}: Task`).join('\n'))).findings.some(x=>x.code==='task_limit_exceeded'));
19
+ assert.ok(checkPrdDraftMechanics(draft('```md\n- [ ] T-001: Example only\n```')).findings.some(x=>x.code==='tasks_invalid'));
20
+ const wrong=structuredClone(contract);wrong.cases[0].acIds=['AC-002'];wrong.cases[0].taskIds=['T-999'];
21
+ const codes=checkPrdDraftMechanics(draft(undefined,wrong)).findings.map(x=>x.code);
22
+ assert.ok(codes.includes('test_reference_invalid'));assert.ok(codes.includes('acceptance_test_coverage_missing'));
23
+ });
@@ -0,0 +1,76 @@
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 {spawnSync} from 'node:child_process';
8
+ import {createHash} from 'node:crypto';
9
+
10
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
11
+ function fixture(t){
12
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-sources-')));
13
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
14
+ fs.mkdirSync(path.join(dir,'docs/nested'),{recursive:true});
15
+ const write=(file,content)=>fs.writeFileSync(path.join(dir,file),content);
16
+ const run=(inspect=true,extra=[])=>{
17
+ const result=spawnSync(process.execPath,[path.join(root,'scripts/cm-prd-entry.mjs'),
18
+ ...(inspect?['--inspect-sources']:[]),'--skill-dir',path.join(root,'skills/cm-prd'),
19
+ '--project',dir,'--specs',dir,...extra],{encoding:'utf8'});
20
+ return {code:result.status,body:JSON.parse(result.stdout||result.stderr)};
21
+ };
22
+ return {dir,write,run};
23
+ }
24
+
25
+ test('real CLI inventories nested mixed sources without writing or claiming analysis',t=>{
26
+ const {dir,write,run}=fixture(t);
27
+ const content='需求:保留用户内容。\n';
28
+ write('docs/nested/product.md',content);
29
+ assert.equal(run(false).body.requirementsSourceCount,1);
30
+ write('docs/prototype.HTML','<button>save</button>');
31
+ write('docs/document.pdf','%PDF-1.7 synthetic');
32
+ write('docs/image.png',Buffer.from([0,255,1]));
33
+ write('docs/.env','synthetic hidden input');
34
+ write('cases.md','user cases');
35
+ const before=fs.readdirSync(dir,{recursive:true});
36
+ const result=run(true,['--cases',path.join(dir,'cases.md')]);
37
+ assert.equal(result.code,0);
38
+ const report=result.body.sourceInspection;
39
+ assert.equal(report.sources.length,4);
40
+ const text=report.sources.find(source=>source.format==='text');
41
+ assert.equal(text.content,content);
42
+ assert.equal(text.sha256,createHash('sha256').update(content).digest('hex'));
43
+ assert.deepEqual(report.sources.map(source=>source.requiredAction).sort(),
44
+ ['analyze_text','extract_pdf','inspect_interactions_in_authorized_browser','resolve_unsupported_source'].sort());
45
+ assert.equal(report.completeAnalysis,false);
46
+ assert.equal(report.prototypeInteractionVerified,false);
47
+ assert.equal(report.casesInspected,true);
48
+ assert.equal(report.userCases.content,'user cases');
49
+ assert.equal(report.userCases.path,path.join(dir,'cases.md'));
50
+ assert.equal(report.userCases.origin,'user');
51
+ assert.equal(result.body.writeAuthorized,false);
52
+ assert.deepEqual(fs.readdirSync(dir,{recursive:true}),before);
53
+ assert.equal(fs.readFileSync(path.join(dir,text.path),'utf8'),content);
54
+ });
55
+
56
+ test('real CLI refuses links, invalid text and oversized sources explicitly',t=>{
57
+ const {dir,write,run}=fixture(t);
58
+ write('docs/input.md','valid');
59
+ fs.symlinkSync(path.join(dir,'docs/input.md'),path.join(dir,'docs/link.md'));
60
+ assert.equal(run().body.reason,'source_path_invalid');
61
+ fs.unlinkSync(path.join(dir,'docs/link.md'));
62
+ write('docs/input.md',Buffer.from([255]));
63
+ assert.equal(run().body.reason,'source_text_encoding_invalid');
64
+ write('docs/input.md',Buffer.alloc(1048577));
65
+ assert.equal(run().code,2);
66
+ assert.equal(fs.statSync(path.join(dir,'docs/input.md')).size,1048577);
67
+ });
68
+
69
+ test('default admission remains read-only and source mode does not replace change analysis',t=>{
70
+ const {dir,write,run}=fixture(t);
71
+ assert.equal(run(false).body.reason,'requirements_source_missing');
72
+ fs.mkdirSync(path.join(dir,'1.sample'));
73
+ for(const file of ['requirements.md','design.md','tasks.md'])write(`1.sample/${file}`,'existing');
74
+ assert.equal(run(false,['--change','1']).body.next,'change_analysis');
75
+ assert.equal(run(true,['--change','1']).body.reason,'source_inspection_new_only');
76
+ });