@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,49 @@
1
+ // Read-only preparation around the original single-attempt PRD review gate.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
6
+ import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
7
+ import {need,json,digest} from '../cm-ai/effect-contract.mjs';
8
+ const sha=text=>createHash('sha256').update(text).digest('hex');
9
+ function sections(text,pattern){
10
+ const parts=text.split(/(?=^##\s+)/m);
11
+ return parts.filter(part=>pattern.test(part.split('\n')[0])).join('\n').trim();
12
+ }
13
+ export function preparePrdReview({specs,draft,stage,feature}){
14
+ need(['design','split'].includes(stage),'prd_review_stage_invalid');
15
+ need(fs.realpathSync(specs)===specs,'prd_review_root_invalid');
16
+ const target=draft.features.find(item=>item.directory===feature);
17
+ need(target&&draft.features.filter(item=>item.name===target.name).length===1,'prd_review_feature_invalid');
18
+ // A second directory with the same slug would share the historic r1 filename.
19
+ need(!fs.readdirSync(specs).some(name=>/^\d+\./.test(name)&&name!==feature
20
+ &&name.replace(/^\d+\./,'')===target.name),'prd_review_slug_collision');
21
+ const reviews=path.join(specs,'.reviews');
22
+ try{need(fs.lstatSync(reviews).isDirectory()&&!fs.lstatSync(reviews).isSymbolicLink()
23
+ &&fs.realpathSync(reviews)===reviews,'prd_review_path_invalid');}catch(error){if(error.code!=='ENOENT')throw error;}
24
+ const prefix=`prd-${target.name}-${stage}`;
25
+ const args={stage,feature:target.name,evidence:path.join(reviews,`${prefix}-r1.md`),
26
+ receipt:path.join(reviews,`${prefix}-disposition.json`)};
27
+ // Reject unsafe local files before letting the compatibility inspector read them.
28
+ for(const suffix of ['-r1.md','-r2.md','-disposition.json'])readCmInitSource(specs,`.reviews/${prefix}${suffix}`);
29
+ const gate=inspectPrdReview(args);
30
+ if(['resume_disposition','completed'].includes(gate.outcome))for(const document of target.documents){
31
+ const current=readCmInitSource(specs,`${feature}/${document.path}`);
32
+ need(current!==null&&current.equals(Buffer.from(document.content)),'prd_review_draft_disk_mismatch');
33
+ }
34
+ const files=new Map(target.documents.map(document=>[document.path,document.content]));
35
+ const requirements=files.get('requirements.md'),design=files.get('design.md');
36
+ if(stage==='split')need(sections(design,/^##\s+(方案摘要|概述|功能模块设计|架构.*|summary|design summary|overview|architecture.*)\s*$/i),
37
+ 'prd_review_design_summary_missing');
38
+ const content=stage==='design'?{requirements,design}:{
39
+ requirementsFunctions:sections(requirements,/^##\s+(功能需求|Functional requirements)\s*$/i),
40
+ tasks:files.get('tasks.md'),designSummary:sections(design,/^##\s+.*(方案摘要|概述|架构|功能模块|技术|接口|数据|波及|安全|summary|overview|architecture|decision|contract|data|impact|security)/i)};
41
+ need(Object.values(content).every(value=>typeof value==='string'&&value.trim()),'prd_review_sections_missing');
42
+ const reviewPackage=json({workflow:'cm-prd',stage,feature,draftDigest:draft.draftDigest,content,
43
+ artifacts:target.documents.map(document=>({path:`${feature}/${document.path}`,sha256:sha(document.content)})),
44
+ instructions:stage==='design'?'Apply original Step 9.5 only when its risk triggers were established. Read relevant project rules and changed-module context plus steelman-review. No second attempt.':
45
+ 'Apply original Step 10.6 to the functional requirements, complete task list and selected design sections. Respect prior design review and do not repeat it. No second attempt.'});
46
+ if(gate.package_sha256!==undefined)need(gate.package_sha256===digest(reviewPackage),'prd_review_dispatch_package_changed');
47
+ return json({gate,paths:args,reviewPackage,packageDigest:digest(reviewPackage),
48
+ stageSelection:'caller_must_apply_original_risk_rules',dispatchAuthorized:false,writeAuthorized:false,completionAuthorized:false});
49
+ }
@@ -0,0 +1,56 @@
1
+ // Publish an unchanged host-attested r1. Not a provider receipt or completion issuer.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
5
+ import {writeReviewEvidence} from '../cm-ai/review-evidence-file.mjs';
6
+ import {reviewResultForPaths} from '../cm-ai/review-runner.mjs';
7
+ import {need,shape,json,digest,id} from '../cm-ai/effect-contract.mjs';
8
+
9
+ export function publishPrdReview({specs,reviewPackage,packageDigest,authorContextId,response,inspectOnly=false}){
10
+ reviewPackage=json(reviewPackage,256*1024);response=json(response,64*1024);id(authorContextId);
11
+ need(digest(reviewPackage)===packageDigest&&reviewPackage.workflow==='cm-prd'
12
+ &&['design','split'].includes(reviewPackage.stage),'prd_review_package_invalid');
13
+ const match=typeof reviewPackage.feature==='string'&&reviewPackage.feature.match(/^([1-9]\d*)\.([a-z0-9]+(?:-[a-z0-9]+)*)$/);
14
+ need(match,'prd_review_feature_invalid');
15
+ need(path.isAbsolute(specs)&&fs.realpathSync(specs)===specs,'prd_review_root_invalid');
16
+ const reviews=path.join(specs,'.reviews');
17
+ need(fs.realpathSync(reviews)===reviews&&fs.lstatSync(reviews).isDirectory(),'prd_review_path_invalid');
18
+ const stage=reviewPackage.stage,feature=match[2],prefix=`prd-${feature}-${stage}`;
19
+ const args={stage,feature,evidence:path.join(reviews,`${prefix}-r1.md`),receipt:path.join(reviews,`${prefix}-disposition.json`)};
20
+ const gate=inspectPrdReview(args);
21
+ need(gate.package_sha256===packageDigest&&['dispatch_unknown','resume_disposition','completed'].includes(gate.outcome),
22
+ 'prd_review_unclaimed');
23
+ const degraded=response.reviewer==='self-degraded';
24
+ shape(response,['reviewer','contextId','independent','at','result',...(degraded?['degradedReason']:[])]);
25
+ // Native subagents return canonical context identities, not filesystem paths.
26
+ // Preserve their exact spelling; shared effect/path IDs keep their existing grammar.
27
+ const context=response.contextId;
28
+ need(typeof context==='string'&&context.length<=128&&!/\s/.test(context));
29
+ if(response.reviewer==='codex-subagent'&&context.startsWith('/')){
30
+ need(/^\/root(?:\/[a-z0-9_]+)+$/.test(context));
31
+ }else id(context);
32
+ need(degraded?response.independent===false&&response.contextId===authorContextId
33
+ &&typeof response.degradedReason==='string'&&response.degradedReason.trim().length>0
34
+ &&!/[\r\n\v\f\x1c-\x1e\x85\u2028\u2029\0]/.test(response.degradedReason):
35
+ ['codex-subagent','codex-cli'].includes(response.reviewer)&&response.independent===true&&response.contextId!==authorContextId,
36
+ 'prd_review_independence_invalid');
37
+ need(typeof response.at==='string'&&Number.isFinite(Date.parse(response.at))
38
+ &&new Date(response.at).toISOString()===response.at,'prd_review_timestamp_invalid');
39
+ const files=stage==='design'?['requirements.md','design.md']:['requirements.md','design.md','tasks.md'];
40
+ const examinedPaths=files.map(file=>`${reviewPackage.feature}/${file}`).sort();
41
+ const result=reviewResultForPaths(response.result,{packageDigest},examinedPaths);
42
+ const bytes=Buffer.from(['---',`at: ${response.at}`,`reviewer: ${response.reviewer}`,`independent: ${response.independent}`,
43
+ ...(degraded?[`degraded_reason: ${JSON.stringify(response.degradedReason)}`]:[]),`package_sha256: ${packageDigest}`,
44
+ `verdict: ${result.verdict}`,'scope:',...examinedPaths.map(file=>` - ${file}`),'---','',
45
+ 'Current-host-attested review result; context identity and tool execution require host verification.',
46
+ 'Not a V3 invocation receipt, disposition, specification approval or task completion.',
47
+ 'Private review material; do not publish or transmit without separate authorization.',
48
+ '```json',JSON.stringify({version:1,authorContextId,reviewPackage,response}),'```',''].join('\n'));
49
+ const validate=file=>need((fs.lstatSync(file).mode&0o777)===0o600,'prd_review_permissions');
50
+ const published=writeReviewEvidence({reviewsDir:reviews,name:path.basename(args.evidence),bytes,validate,inspectOnly});
51
+ writeReviewEvidence({reviewsDir:reviews,name:path.basename(args.evidence),bytes,validate,inspectOnly:true});
52
+ const after=inspectPrdReview(args);
53
+ need(after.package_sha256===packageDigest&&['resume_disposition','completed'].includes(after.outcome),'prd_review_publication_unknown');
54
+ return json({outcome:'r1_published',path:published.path,packageDigest,verdict:result.verdict,gate:after,
55
+ source:'current_host_review_attestation',independent:response.independent,completionAuthorized:false});
56
+ }
@@ -0,0 +1,75 @@
1
+ // Mechanical subset of the existing Step 10.5 checklist. No semantic approval.
2
+ import {parseFeatureTaskText,validDependencies,declaredAcceptanceIds} from '../cm-ai/cm-ai-admission.mjs';
3
+ import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
4
+ import {json,shape,need} from '../cm-ai/effect-contract.mjs';
5
+
6
+ export function inspectPrdContextCheck(raw,draft){
7
+ const report=json(raw,64*1024);shape(report,['draftDigest','features']);
8
+ need(report.draftDigest===draft.draftDigest&&Array.isArray(report.features)
9
+ &&report.features.length===draft.features.length,'prd_context_check_binding');
10
+ const seen=new Set();let failed=false;
11
+ for(const feature of report.features){
12
+ shape(feature,['directory','checks']);
13
+ need(draft.features.some(item=>item.directory===feature.directory)&&!seen.has(feature.directory)
14
+ &&Array.isArray(feature.checks),'prd_context_check_binding');seen.add(feature.directory);
15
+ const expected=draft.mechanicalSelfCheck.pending,ids=new Set();
16
+ need(feature.checks.length===expected.length,'prd_context_check_coverage');
17
+ for(const check of feature.checks){
18
+ shape(check,['id','status','evidence']);
19
+ need(expected.includes(check.id)&&!ids.has(check.id)&&['passed','failed','not_applicable'].includes(check.status)
20
+ &&Array.isArray(check.evidence)&&check.evidence.length>0
21
+ &&check.evidence.every(item=>typeof item==='string'&&item.trim()),'prd_context_check_invalid');
22
+ need(check.status!=='not_applicable'||check.id==='brownfield_references_and_B2_B3_B5_if_applicable','prd_context_check_invalid');
23
+ ids.add(check.id);failed ||= check.status==='failed';
24
+ }
25
+ }
26
+ return json({...report,status:failed?'failed':'host_reported_passed',independentReview:false,completionAuthorized:false});
27
+ }
28
+
29
+ // Examples are not declarations. Leave the original N1 parser behavior unchanged.
30
+ function outsideFences(source){
31
+ let fence=null;return source.split(/\r?\n/).map(line=>{
32
+ const match=line.match(/^\s*(`{3,}|~{3,})/);
33
+ if(match){
34
+ if(fence===null)fence=match[1];
35
+ else if(match[1][0]===fence[0]&&match[1].length>=fence.length)fence=null;
36
+ return '';
37
+ }
38
+ return fence===null?line:'';
39
+ }).join('\n');
40
+ }
41
+ export function checkPrdDraftMechanics(draft,{change=false}={}){
42
+ const findings=[],features=[];
43
+ for(const feature of draft.features){
44
+ const files=new Map(feature.documents.map(document=>[document.path,document.content]));
45
+ const add=code=>findings.push({feature:feature.directory,code});
46
+ const parsed=parseFeatureTaskText(outsideFences(files.get('tasks.md')));
47
+ const acIds=declaredAcceptanceIds(outsideFences(files.get('requirements.md')));
48
+ if(acIds.size===0)add('acceptance_missing');
49
+ let taskIds=new Set();
50
+ if(parsed.error)add(parsed.error);
51
+ else{
52
+ taskIds=new Set(parsed.tasks.map(task=>task.id));
53
+ if(parsed.tasks.length>15)add('task_limit_exceeded');
54
+ if(!change&&parsed.tasks.some(task=>task.completed||task.dropped))add('new_task_not_pending');
55
+ if(!validDependencies(parsed.tasks,parsed.dependencies))add('dependencies_invalid');
56
+ }
57
+ if(files.has('test-cases.json')){
58
+ let cases;try{cases=JSON.parse(files.get('test-cases.json'));}catch{add('test_cases_invalid');}
59
+ if(cases){
60
+ if(validateTestCases(cases).length||cases.feature!==feature.name)add('test_cases_invalid');
61
+ else{
62
+ if(cases.cases.some(item=>item.taskIds.length===0||item.taskIds.some(id=>!taskIds.has(id))
63
+ ||item.acIds.some(id=>!acIds.has(id))))add('test_reference_invalid');
64
+ const covered=new Set(cases.cases.flatMap(item=>item.acIds));
65
+ if([...acIds].some(id=>!covered.has(id)))add('acceptance_test_coverage_missing');
66
+ }
67
+ }
68
+ }
69
+ features.push({directory:feature.directory,tasks:taskIds.size,acceptanceCriteria:acIds.size});
70
+ }
71
+ return json({draftDigest:draft.draftDigest,status:findings.length?'failed':'mechanical_subset_passed',features,findings,
72
+ pending:['task_boundary_and_existing_asset_overlap','acceptance_verifiability','user_case_semantics',
73
+ 'test_contract_applicability','brownfield_references_and_B2_B3_B5_if_applicable'],
74
+ completeSelfCheck:false,independentReview:false,completionAuthorized:false});
75
+ }
@@ -0,0 +1,74 @@
1
+ // PRD-local checkpoint and call journal. It never owns review/task approval.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {need,json,digest} from '../cm-ai/effect-contract.mjs';
6
+ import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
7
+
8
+ function readState(root,relative){
9
+ if(relative!=='state.json')return readCmInitSource(root,relative)?.toString('utf8')??null;
10
+ const file=path.join(root,relative);let stat;try{stat=fs.lstatSync(file);}catch(e){if(e.code==='ENOENT')return null;throw e;}
11
+ need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=16*1024*1024&&(stat.mode&0o777)===0o600,'prd_session_file_invalid');
12
+ return new TextDecoder('utf8',{fatal:true}).decode(fs.readFileSync(file));
13
+ }
14
+
15
+ export function replaceSessionFile(root,relative,before,after){
16
+ need(readState(root,relative)===before,'prd_write_conflict');
17
+ need(typeof after==='string'&&Buffer.byteLength(after)<=16*1024*1024&&Buffer.from(after).toString('utf8')===after,'prd_write_limit');
18
+ const target=path.join(root,relative),dir=path.dirname(target);
19
+ need(fs.realpathSync(dir)===dir,'prd_write_path_invalid');
20
+ const tmp=path.join(dir,`.prd-${randomUUID()}`);let fd;
21
+ try{
22
+ fd=fs.openSync(tmp,'wx',0o600);fs.writeFileSync(fd,after);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
23
+ need(readState(root,relative)===before,'prd_write_conflict');
24
+ if(before===null)fs.linkSync(tmp,target);else fs.renameSync(tmp,target);
25
+ const d=fs.openSync(dir,'r');try{fs.fsyncSync(d);}finally{fs.closeSync(d);}
26
+ }finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(tmp);}catch(e){if(e.code!=='ENOENT')throw e;}}
27
+ }
28
+ export function openPrdSession({specs,sessionId,identity}){
29
+ need(/^prd-[a-zA-Z0-9-]{1,80}$/.test(sessionId),'prd_session_id_invalid');
30
+ for(const relative of ['.reviews','.reviews/prd-sessions',`.reviews/prd-sessions/${sessionId}`]){
31
+ const dir=path.join(specs,relative);try{fs.mkdirSync(dir,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}
32
+ need(fs.realpathSync(dir)===dir&&fs.lstatSync(dir).isDirectory(),'prd_session_path_invalid');
33
+ }
34
+ const directory=path.join(specs,'.reviews/prd-sessions',sessionId),lock=path.join(directory,'writer.json');
35
+ const read=()=>readState(directory,'state.json');
36
+ if(fs.existsSync(lock)){
37
+ const bytes=readCmInitSource(directory,'writer.json'),old=JSON.parse(bytes);
38
+ need(Number.isSafeInteger(old.pid)&&old.pid>0,'prd_session_lock_invalid');
39
+ try{process.kill(old.pid,0);need(false,'prd_session_busy');}catch(e){if(e.code!=='ESRCH')throw e;}
40
+ need(readCmInitSource(directory,'writer.json')?.equals(bytes),'prd_session_lock_changed');fs.unlinkSync(lock);
41
+ }
42
+ const lockBytes=JSON.stringify({pid:process.pid,nonce:randomUUID()});
43
+ const fd=fs.openSync(lock,'wx',0o600);try{fs.writeFileSync(fd,lockBytes);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
44
+ let bytes=read(),state=bytes===null?{version:1,identity,checkpoint:null,active:null,segments:{}}:JSON.parse(bytes);
45
+ try{need(state.version===1&&digest(state.identity)===digest(identity),'prd_session_identity_changed');}
46
+ catch(e){fs.unlinkSync(lock);throw e;}
47
+ let cursor=0;
48
+ const save=()=>{const next=JSON.stringify(state);replaceSessionFile(directory,'state.json',bytes,next);bytes=next;};
49
+ return {
50
+ get state(){return json(state,12*1024*1024);},
51
+ begin(request,before){need(state.active===null,'prd_operation_recovery_required');state.active={request,before,calls:[]};cursor=0;save();},
52
+ replay(){need(state.active!==null,'prd_nothing_to_resume');cursor=0;return json(state.active,12*1024*1024);},
53
+ commit(checkpoint){state.checkpoint=checkpoint;state.active=null;save();},
54
+ checkpoint(checkpoint){state.checkpoint=checkpoint;save();},
55
+ async call(kind,payload,signal,perform){
56
+ need(state.active!==null,'prd_operation_required');const index=cursor++,input=json({kind,payload},12*1024*1024);
57
+ const previous=state.active.calls[index];
58
+ if(previous){need(previous.requestDigest===digest(input),'prd_replay_inputs_changed');
59
+ need(Object.hasOwn(previous,'result'),'prd_host_result_unknown');return previous.result;}
60
+ need(!state.active.calls.some(call=>!Object.hasOwn(call,'result')),'prd_host_result_unknown');
61
+ const call={callId:randomUUID(),requestDigest:digest(input),...input};state.active.calls.push(call);save();
62
+ const result=json(await perform({...payload,recovery:{sessionId,callId:call.callId,requestDigest:call.requestDigest}},signal),1024*1024);
63
+ call.result=result;save();return result;
64
+ },
65
+ resolve({callId,requestDigest,result,evidence}){
66
+ need(typeof evidence==='string'&&evidence.trim(),'prd_recovery_evidence_required');
67
+ const call=state.active?.calls.find(item=>item.callId===callId);
68
+ need(call&&call.requestDigest===requestDigest&&!Object.hasOwn(call,'result'),'prd_recovery_binding');
69
+ call.result=json(result,1024*1024);call.recoveryEvidence=evidence;save();
70
+ },
71
+ segment(phase){const segment=(state.segments[phase]??0)+1;state.segments[phase]=segment;save();return segment;},
72
+ close(){need(readCmInitSource(directory,'writer.json')?.toString('utf8')===lockBytes,'prd_session_lock_changed');fs.unlinkSync(lock);},
73
+ };
74
+ }
@@ -0,0 +1,133 @@
1
+ // Evidence-backed human handoff. No specification approval or development.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash,randomUUID} from 'node:crypto';
5
+ import {TextDecoder} from 'node:util';
6
+ import {buildManifest} from '../../../scripts/cm-spec-manifest.mjs';
7
+ import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
8
+ import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
9
+ import {inspectPrdFindings} from './review-findings.mjs';
10
+ import {checkPrdDraftMechanics} from './self-check.mjs';
11
+ import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
12
+ import {prdDesignRiskSignals} from './design-risk.mjs';
13
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
14
+
15
+ export function inspectPrdSummaryEvidence(specs){
16
+ need(path.isAbsolute(specs)&&fs.realpathSync(specs)===specs,'prd_summary_root_invalid');
17
+ const specFiles=buildManifest(specs),names=[...new Set(specFiles.map(item=>item.path.split('/')[0]))];
18
+ const slugs=new Set(),features=[],documents=[],evidenceFiles=[];
19
+ const statusBytes=readCmInitSource(specs,'.cm-specs-status');
20
+ if(statusBytes!==null)evidenceFiles.push({path:'.cm-specs-status',sha256:sha(statusBytes)});
21
+ for(const directory of names){
22
+ need(/^[1-9]\d*\.[a-z0-9]+(?:-[a-z0-9]+)*$/.test(directory),'prd_summary_feature_invalid');
23
+ const slug=directory.replace(/^\d+\./,'');need(!slugs.has(slug),'prd_summary_slug_collision');slugs.add(slug);
24
+ const files=specFiles.filter(item=>item.path.startsWith(directory+'/')).map(item=>{
25
+ const bytes=readCmInitSource(specs,item.path);need(bytes!==null,'prd_summary_file_missing');
26
+ evidenceFiles.push({path:item.path,sha256:sha(bytes)});
27
+ return {path:item.path.slice(directory.length+1),content:new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes)};
28
+ });
29
+ documents.push({directory,name:slug,documents:files});
30
+ const reviews={};
31
+ for(const stage of ['design','split']){
32
+ const prefix=`.reviews/prd-${slug}-${stage}`;
33
+ for(const suffix of ['-r1.md','-r2.md','-disposition.json','-dispatch.json']){
34
+ const file=prefix+suffix,bytes=readCmInitSource(specs,file);
35
+ if(bytes!==null)evidenceFiles.push({path:file,sha256:sha(bytes)});
36
+ }
37
+ const args={stage,feature:slug,evidence:path.join(specs,prefix+'-r1.md'),receipt:path.join(specs,prefix+'-disposition.json')};
38
+ const gate=inspectPrdReview(args);
39
+ let findings=null;
40
+ if(['resume_disposition','completed'].includes(gate.outcome))findings=inspectPrdFindings({specs,stage,feature:directory});
41
+ if(gate.outcome==='completed'){
42
+ const receipt=JSON.parse(readCmInitSource(specs,prefix+'-disposition.json').toString('utf8'));
43
+ const expected=stage==='design'?[`${directory}/design.md`]:files.map(item=>`${directory}/${item.path}`).sort();
44
+ need(digest(receipt.artifacts.map(item=>item.path).sort())===digest(expected),'prd_summary_receipt_coverage');
45
+ }
46
+ reviews[stage]={gate,independent:findings?.independent??null,verdict:findings?.verdict??null,
47
+ findings:findings?.findings??[],source:findings?.source??null};
48
+ }
49
+ let cases={total:0,user:0,generated:0};
50
+ const contract=files.find(item=>item.path==='test-cases.json');
51
+ if(contract){const data=JSON.parse(contract.content);need(Array.isArray(data.cases),'prd_summary_cases_invalid');
52
+ cases={total:data.cases.length,user:data.cases.filter(item=>item.origin==='user').length,
53
+ generated:data.cases.filter(item=>item.origin==='generated').length};}
54
+ features.push({directory,reviews,cases});
55
+ }
56
+ const mechanical=checkPrdDraftMechanics({draftDigest:digest(evidenceFiles),features:documents});
57
+ return json({specs,specFiles,features,documents,mechanical,evidenceFiles},1024*1024);
58
+ }
59
+
60
+ export function publishPrdAwaitingReview({specs,summary,writeEnabled,recover=false}){
61
+ need(writeEnabled===true,'prd_summary_write_not_enabled');
62
+ need(summary.status==='human_summary_prepared'&&summary.readyForAwaitingReview===true
63
+ &&summary.blockers.length===0,'prd_summary_not_ready');
64
+ const before=inspectPrdSummaryEvidence(specs);
65
+ const existing=readCmInitSource(specs,'.cm-specs-status');
66
+ if(recover&&existing!==null){
67
+ const value=JSON.parse(existing);
68
+ if(value.summaryDigest===summary.summaryDigest){
69
+ need(value.status==='awaiting_review'&&digest(value.specFiles)===digest(before.specFiles)
70
+ &&summary.publicationInput.every(item=>item.path==='.cm-specs-status'||before.evidenceFiles.some(next=>next.path===item.path&&next.sha256===item.sha256))
71
+ &&before.evidenceFiles.filter(item=>item.path!=='.cm-specs-status').length===summary.publicationInput.filter(item=>item.path!=='.cm-specs-status').length,
72
+ 'prd_summary_inputs_changed');
73
+ return json({status:'awaiting_review',path:path.join(specs,'.cm-specs-status'),features:value.features,
74
+ completionAuthorized:false,next:'human_review_then_explicit_cm_ai'});
75
+ }
76
+ }
77
+ need(digest(before)===summary.evidenceDigest,'prd_summary_inputs_changed');
78
+ const status={status:'awaiting_review',summaryDigest:summary.summaryDigest,at:new Date().toISOString(),features:before.features.map(item=>item.directory),
79
+ specFiles:before.specFiles,testCases:before.specFiles.filter(item=>item.path.endsWith('/test-cases.json'))};
80
+ const bytes=Buffer.from(JSON.stringify(status)+'\n'),target=path.join(specs,'.cm-specs-status');
81
+ const temporary=path.join(specs,`.cm-prd-status-${randomUUID()}`);let fd;
82
+ try{
83
+ fd=fs.openSync(temporary,'wx',0o600);fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
84
+ need(digest(inspectPrdSummaryEvidence(specs))===summary.evidenceDigest,'prd_summary_inputs_changed');
85
+ fs.renameSync(temporary,target);
86
+ const dir=fs.openSync(specs,'r');try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
87
+ need(readCmInitSource(specs,'.cm-specs-status')?.equals(bytes),'prd_summary_status_unknown');
88
+ need(digest(buildManifest(specs))===digest(before.specFiles),'prd_summary_inputs_changed');
89
+ return json({status:'awaiting_review',path:target,features:status.features,completionAuthorized:false,
90
+ next:'human_review_then_explicit_cm_ai'});
91
+ }catch{return json({status:'awaiting_review_write_unknown',next:'inspect_status_and_specs_without_automatic_retry',completionAuthorized:false});}
92
+ finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}}
93
+ }
94
+
95
+ const requiredSignals=prdDesignRiskSignals;
96
+ export function createPrdSummaryOwner({summarize}){
97
+ need(typeof summarize==='function','prd_summary_host_required');
98
+ return async(specs,signal)=>{
99
+ need(!signal.aborted,'cancelled');const evidence=inspectPrdSummaryEvidence(specs),evidenceDigest=digest(evidence);
100
+ const details=json(await summarize({evidence,evidenceDigest,
101
+ instructions:'Prepare original cm-prd Step 11 human summary. Read actual source/context as needed. Return {evidenceDigest,deliveryForm,estimatedTime,openQuestions,risks,contextScope,platformReadiness,uiBaseline,designRisk:[{feature,signals:{greenfieldAdr,architectureOrDataFlow,newRuntimeDependencyOrToolchain,publicContractDataOrSecurity,fiveOrMoreFunctions},evidence:[specific references]}]}. Signals are booleans and must cover original Step 9.5 criteria; unknown facts must remain explicit in openQuestions/risks, never infer approval. All descriptive fields are non-empty strings. Do not claim review or tests beyond supplied evidence, write files, dispatch reviewers/providers, approve specs or start development.'},signal),64*1024);
102
+ need(!signal.aborted,'cancelled');
103
+ shape(details,['evidenceDigest','deliveryForm','estimatedTime','openQuestions','risks','contextScope','platformReadiness','uiBaseline','designRisk']);
104
+ need(details.evidenceDigest===evidenceDigest,'prd_summary_binding');
105
+ for(const field of ['deliveryForm','estimatedTime','openQuestions','risks','contextScope','platformReadiness','uiBaseline'])
106
+ need(typeof details[field]==='string'&&details[field].trim(),'prd_summary_details_invalid');
107
+ need(Array.isArray(details.designRisk)&&details.designRisk.length===evidence.features.length,'prd_summary_risk_coverage');
108
+ const seen=new Set(),blockers=[];
109
+ for(const risk of details.designRisk){
110
+ shape(risk,['feature','signals','evidence']);shape(risk.signals,requiredSignals);
111
+ const feature=evidence.features.find(item=>item.directory===risk.feature);
112
+ need(feature&&!seen.has(risk.feature)&&requiredSignals.every(key=>typeof risk.signals[key]==='boolean')
113
+ &&Array.isArray(risk.evidence)&&risk.evidence.length&&risk.evidence.every(item=>typeof item==='string'&&item.trim()),'prd_summary_risk_invalid');seen.add(risk.feature);
114
+ const {design,split}=feature.reviews;
115
+ if(split.gate.outcome!=='completed'||split.verdict==='blocked')blockers.push(`${risk.feature}: split_review_disposition_required`);
116
+ if(Object.values(risk.signals).some(Boolean)){
117
+ if(design.gate.outcome!=='completed'||design.verdict==='blocked')blockers.push(`${risk.feature}: design_review_disposition_required`);
118
+ }else if(!['dispatch_once','completed'].includes(design.gate.outcome)||design.verdict==='blocked')
119
+ blockers.push(`${risk.feature}: existing_design_attempt_unresolved`);
120
+ }
121
+ if(evidence.mechanical.status==='failed')blockers.push('mechanical_self_check_failed');
122
+ need(digest(inspectPrdSummaryEvidence(specs))===evidenceDigest,'prd_summary_inputs_changed');
123
+ const checklist=['跨feature产物不重复','依赖完整且无环','AC可验证','功能粒度合规且每feature≤15任务',
124
+ '开放问题和敏感决策已经人工确认','交付形态符合需求','存在原型时功能与交互覆盖完整'];
125
+ const totals=evidence.mechanical.features.reduce((sum,item)=>({tasks:sum.tasks+item.tasks,
126
+ acceptanceCriteria:sum.acceptanceCriteria+item.acceptanceCriteria}),{tasks:0,acceptanceCriteria:0});
127
+ const summary=json({status:'human_summary_prepared',evidenceDigest,details,features:evidence.features,totals,
128
+ mechanicalSelfCheck:evidence.mechanical,blockers,checklist:checklist.map(text=>({text,checked:false})),
129
+ specFiles:evidence.specFiles,publicationInput:evidence.evidenceFiles,readyForAwaitingReview:blockers.length===0,
130
+ next:'human_review_then_explicit_cm_ai',completionAuthorized:false},1024*1024);
131
+ return json({...summary,summaryDigest:digest(summary)},1024*1024);
132
+ };
133
+ }
@@ -0,0 +1,2 @@
1
+ // Stable import surface; both tracks use the same persisted workflow and N4/N5.
2
+ export {createCmRefactorHost} from './workflow.mjs';
@@ -0,0 +1,86 @@
1
+ // Refactor-local replay of recorded effects. Task/review authority stays in N4/N5.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {randomUUID,createHash} from 'node:crypto';
5
+ import {need,digest,json} from '../cm-ai/effect-contract.mjs';
6
+ import {canonicalFuture} from '../cm-test/source-snapshot.mjs';
7
+ export const sha=value=>createHash('sha256').update(value).digest('hex');
8
+ export function readText(target){
9
+ need(canonicalFuture(target)===target,'refactor_path_changed');
10
+ let stat;try{stat=fs.lstatSync(target);}catch(error){if(error.code==='ENOENT')return null;throw error;}
11
+ need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=1024*1024,'refactor_file_invalid');
12
+ const bytes=fs.readFileSync(target);return new TextDecoder('utf8',{fatal:true,ignoreBOM:true}).decode(bytes);
13
+ }
14
+ export function replaceText(target,before,after,mode=0o644){
15
+ need(readText(target)===before,'refactor_write_conflict');
16
+ if(after===before)return;
17
+ if(after===null){fs.unlinkSync(target);return;}
18
+ need(typeof after==='string'&&Buffer.byteLength(after)<=1024*1024,'refactor_file_limit');
19
+ const dir=path.dirname(target);need(canonicalFuture(dir)===dir,'refactor_path_changed');fs.mkdirSync(dir,{recursive:true});
20
+ const tmp=path.join(dir,`.cm-refactor-${randomUUID()}`);let fd;
21
+ try{
22
+ fd=fs.openSync(tmp,'wx',mode);fs.fchmodSync(fd,mode);fs.writeFileSync(fd,after);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
23
+ need(readText(target)===before,'refactor_write_conflict');
24
+ if(before===null){fs.linkSync(tmp,target);fs.unlinkSync(tmp);}else fs.renameSync(tmp,target);
25
+ const d=fs.openSync(dir,'r');try{fs.fsyncSync(d);}finally{fs.closeSync(d);}
26
+ }finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(tmp);}catch(error){if(error.code!=='ENOENT')throw error;}}
27
+ }
28
+ export function openRefactorRecords(directory){
29
+ need(canonicalFuture(directory)===directory,'refactor_archive_changed');
30
+ const target=path.join(directory,'execution.jsonl'),lock=path.join(directory,'.writer.json');
31
+ let events=[],last=null,locked=false;const effects=new Map();
32
+ if(fs.existsSync(target)){
33
+ const stat=fs.lstatSync(target);need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=32*1024*1024,'refactor_journal_invalid');
34
+ const source=fs.readFileSync(target,'utf8');need(source.endsWith('\n'),'refactor_journal_incomplete');
35
+ events=source.trimEnd().split('\n').map(line=>JSON.parse(line));
36
+ for(const row of events){const {hash,...body}=row;need(hash===digest(body)&&body.previous===last,'refactor_journal_invalid');last=hash;
37
+ if(row.type==='intent'){need(!effects.has(row.key),'refactor_journal_invalid');effects.set(row.key,{input:row.input,kind:row.kind});}
38
+ if(row.type==='result'){const entry=effects.get(row.key);need(entry&&!Object.hasOwn(entry,'result'),'refactor_journal_invalid');entry.result=row.result;}
39
+ }
40
+ }
41
+ function append(body){
42
+ need(locked,'refactor_lock_required');const row={...json(body,4*1024*1024),previous:last},hash=digest(row);
43
+ const fd=fs.openSync(target,fs.constants.O_WRONLY|fs.constants.O_APPEND|fs.constants.O_CREAT|fs.constants.O_NOFOLLOW,0o600);
44
+ try{need(fs.fstatSync(fd).nlink===1,'refactor_journal_invalid');fs.writeFileSync(fd,JSON.stringify({...row,hash})+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
45
+ events.push({...row,hash});last=hash;
46
+ }
47
+ return {
48
+ get context(){return events.find(row=>row.type==='context')?.value??null;},
49
+ get progress(){return events.findLast(row=>row.type==='progress')?.value??null;},
50
+ effects,
51
+ acquire(){
52
+ need(!locked,'refactor_busy');fs.mkdirSync(directory,{recursive:true,mode:0o700});
53
+ if(fs.existsSync(lock)){
54
+ const old=JSON.parse(readText(lock));need(Number.isSafeInteger(old.pid)&&old.pid>0,'refactor_lock_invalid');
55
+ try{process.kill(old.pid,0);need(false,'refactor_busy');}catch(error){if(error.code!=='ESRCH')throw error;}
56
+ need(readText(lock)===JSON.stringify(old),'refactor_lock_changed');fs.unlinkSync(lock);
57
+ }
58
+ const fd=fs.openSync(lock,'wx',0o600);try{fs.writeFileSync(fd,JSON.stringify({pid:process.pid}));}finally{fs.closeSync(fd);}locked=true;
59
+ // Another process may have advanced the journal between construction and lock.
60
+ if(fs.existsSync(target)){const lines=fs.readFileSync(target,'utf8').trimEnd().split('\n');
61
+ need(lines.length===events.length&&JSON.parse(lines.at(-1)).hash===last,'refactor_reopen_required');}
62
+ },
63
+ release(){if(locked){fs.unlinkSync(lock);locked=false;}},
64
+ initialize(value){need(!this.context,'refactor_already_started');append({type:'context',value});},
65
+ progressWrite(value){append({type:'progress',value});},
66
+ async effect(key,kind,input,perform,recover){
67
+ input=json(input,4*1024*1024);
68
+ const old=effects.get(key);
69
+ if(old){need(old.kind===kind&&digest(old.input)===digest(input),'refactor_replay_mismatch');
70
+ if(Object.hasOwn(old,'result'))return json(old.result,4*1024*1024);
71
+ need(typeof recover==='function','refactor_unknown_effect');
72
+ const result=json(await recover(old,perform),4*1024*1024);append({type:'result',key,result});old.result=result;return json(result,4*1024*1024);
73
+ }
74
+ if(['host','command'].includes(kind))need(![...effects.values()].some(entry=>['host','command'].includes(entry.kind)
75
+ &&!Object.hasOwn(entry,'result')),'refactor_unknown_effect');
76
+ append({type:'intent',key,kind,input});const entry={kind,input};effects.set(key,entry);
77
+ const result=json(await perform(),4*1024*1024);append({type:'result',key,result});entry.result=result;return json(result,4*1024*1024);
78
+ },
79
+ async write(key,target,before,after,mode){
80
+ const input={target,before,after,mode};
81
+ const perform=()=>{const current=readText(target);need(current===before||current===after,'refactor_write_conflict');
82
+ if(current!==after)replaceText(target,before,after,mode);return {written:true};};
83
+ return this.effect(key,'write',input,perform,perform);
84
+ }
85
+ };
86
+ }