@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,272 @@
1
+ #!/usr/bin/env python3
2
+ """Summarize recent cm-prd phase timing events from the local global mirror."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sys
10
+ from dataclasses import dataclass
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
14
+
15
+
16
+ PHASE_ORDER = (
17
+ "context_load",
18
+ "requirements_analysis",
19
+ "design_generation",
20
+ "design_review",
21
+ "task_split",
22
+ "spec_validation",
23
+ "spec_review",
24
+ )
25
+
26
+
27
+ @dataclass
28
+ class RunRef:
29
+ run_id: str
30
+ project: str
31
+ status: str
32
+ updated_at: datetime
33
+ at_text: str
34
+ log_file: str
35
+
36
+
37
+ @dataclass
38
+ class RunTiming:
39
+ ref: RunRef
40
+ phases: Dict[str, float]
41
+ triggered: Set[str]
42
+ pauses: int
43
+ incomplete: int
44
+
45
+
46
+ def configure_output() -> None:
47
+ for stream in (sys.stdout, sys.stderr):
48
+ reconfigure = getattr(stream, "reconfigure", None)
49
+ if callable(reconfigure):
50
+ reconfigure(encoding="utf-8", errors="backslashreplace")
51
+
52
+
53
+ def positive_int(value: str) -> int:
54
+ parsed = int(value)
55
+ if parsed < 1:
56
+ raise argparse.ArgumentTypeError("must be at least 1")
57
+ return parsed
58
+
59
+
60
+ def parse_args() -> argparse.Namespace:
61
+ parser = argparse.ArgumentParser(
62
+ description="Show active phase time for recent cm-prd runs."
63
+ )
64
+ parser.add_argument("--last", type=positive_int, default=5)
65
+ parser.add_argument(
66
+ "--log-home",
67
+ help="Override CM_WORKFLOW_LOG_HOME for this report.",
68
+ )
69
+ return parser.parse_args()
70
+
71
+
72
+ def parse_at(value: Any) -> Optional[datetime]:
73
+ if not isinstance(value, str) or not value:
74
+ return None
75
+ normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
76
+ try:
77
+ parsed = datetime.fromisoformat(normalized)
78
+ except ValueError:
79
+ return None
80
+ if parsed.tzinfo is None:
81
+ return parsed.replace(tzinfo=timezone.utc)
82
+ return parsed
83
+
84
+
85
+ def read_jsonl(path: Path) -> Iterable[Tuple[int, Dict[str, Any]]]:
86
+ try:
87
+ lines = path.read_text(encoding="utf-8").splitlines()
88
+ except OSError as exc:
89
+ print(f"warning: cannot read {path}: {type(exc).__name__}", file=sys.stderr)
90
+ return []
91
+ rows: List[Tuple[int, Dict[str, Any]]] = []
92
+ for line_number, line in enumerate(lines, start=1):
93
+ if not line.strip():
94
+ continue
95
+ try:
96
+ value = json.loads(line)
97
+ except json.JSONDecodeError:
98
+ print(f"warning: invalid JSON at {path}:{line_number}", file=sys.stderr)
99
+ continue
100
+ if isinstance(value, dict):
101
+ rows.append((line_number, value))
102
+ return rows
103
+
104
+
105
+ def load_run_refs(log_home: Path) -> List[RunRef]:
106
+ index_path = log_home / "index.jsonl"
107
+ if not index_path.is_file():
108
+ return []
109
+ refs: Dict[str, RunRef] = {}
110
+ for _, row in read_jsonl(index_path):
111
+ if row.get("workflow") != "cm-prd":
112
+ continue
113
+ run_id = row.get("run_id")
114
+ log_file = row.get("log_file")
115
+ updated_at = parse_at(row.get("at"))
116
+ if not isinstance(run_id, str) or not isinstance(log_file, str) or updated_at is None:
117
+ continue
118
+ previous = refs.get(run_id)
119
+ status = "done" if row.get("status") == "done" else "running"
120
+ if previous is not None and previous.status == "done":
121
+ status = "done"
122
+ if previous is None or updated_at >= previous.updated_at:
123
+ refs[run_id] = RunRef(
124
+ run_id=run_id,
125
+ project=str(row.get("project") or "unknown"),
126
+ status=status,
127
+ updated_at=updated_at,
128
+ at_text=str(row.get("at")),
129
+ log_file=log_file,
130
+ )
131
+ elif status == "done":
132
+ previous.status = "done"
133
+ return sorted(refs.values(), key=lambda item: item.updated_at, reverse=True)
134
+
135
+
136
+ def safe_log_path(log_home: Path, relative: str) -> Optional[Path]:
137
+ candidate = (log_home / relative).resolve(strict=False)
138
+ try:
139
+ candidate.relative_to(log_home)
140
+ except ValueError:
141
+ print(f"warning: ignored log path outside log home: {relative}", file=sys.stderr)
142
+ return None
143
+ return candidate
144
+
145
+
146
+ def load_run_timing(log_home: Path, ref: RunRef) -> Optional[RunTiming]:
147
+ log_path = safe_log_path(log_home, ref.log_file)
148
+ if log_path is None or not log_path.is_file():
149
+ print(f"warning: missing run log for {ref.run_id}", file=sys.stderr)
150
+ return None
151
+
152
+ groups: Dict[Tuple[str, str, int], Dict[str, List[Dict[str, Any]]]] = {}
153
+ for _, row in read_jsonl(log_path):
154
+ if row.get("workflow") != "cm-prd" or row.get("event") != "progress":
155
+ continue
156
+ operation_id = row.get("operation_id")
157
+ phase_name = row.get("phase_name")
158
+ segment = row.get("segment")
159
+ phase = row.get("phase")
160
+ if (
161
+ not isinstance(operation_id, str)
162
+ or not isinstance(phase_name, str)
163
+ or not isinstance(segment, int)
164
+ or phase not in {"start", "complete"}
165
+ ):
166
+ continue
167
+ key = (operation_id, phase_name, segment)
168
+ groups.setdefault(key, {"start": [], "complete": []})[str(phase)].append(row)
169
+
170
+ phases: Dict[str, float] = {}
171
+ triggered: Set[str] = set()
172
+ pauses = 0
173
+ incomplete = 0
174
+ for (_, phase_name, _), pair in groups.items():
175
+ if pair["start"]:
176
+ triggered.add(phase_name)
177
+ if len(pair["start"]) != 1 or len(pair["complete"]) != 1:
178
+ incomplete += 1
179
+ continue
180
+ started_at = parse_at(pair["start"][0].get("at"))
181
+ completed_at = parse_at(pair["complete"][0].get("at"))
182
+ if started_at is None or completed_at is None or completed_at < started_at:
183
+ incomplete += 1
184
+ continue
185
+ phases[phase_name] = phases.get(phase_name, 0.0) + (
186
+ completed_at - started_at
187
+ ).total_seconds()
188
+ if pair["complete"][0].get("outcome") == "awaiting_input":
189
+ pauses += 1
190
+ return RunTiming(
191
+ ref=ref,
192
+ phases=phases,
193
+ triggered=triggered,
194
+ pauses=pauses,
195
+ incomplete=incomplete,
196
+ )
197
+
198
+
199
+ def format_seconds(value: float) -> str:
200
+ if value < 60:
201
+ return f"{value:.1f}s"
202
+ minutes = int(value // 60)
203
+ seconds = value - minutes * 60
204
+ return f"{minutes}m {seconds:.1f}s"
205
+
206
+
207
+ def phase_sort_key(name: str) -> Tuple[int, str]:
208
+ try:
209
+ return (PHASE_ORDER.index(name), name)
210
+ except ValueError:
211
+ return (len(PHASE_ORDER), name)
212
+
213
+
214
+ def print_report(runs: List[RunTiming], requested: int) -> None:
215
+ if not runs:
216
+ print("没有找到可读取的 cm-prd 阶段耗时日志。")
217
+ return
218
+
219
+ print(f"CM PRD 阶段耗时(最近 {min(requested, len(runs))} 次)")
220
+ slowest: Optional[Tuple[float, str, RunRef]] = None
221
+ total_pauses = 0
222
+ total_incomplete = 0
223
+ design_reviews = 0
224
+ spec_reviews = 0
225
+
226
+ for run in runs:
227
+ print(
228
+ f"\n- {run.ref.at_text} | {run.ref.project} | "
229
+ f"{run.ref.run_id} | {run.ref.status}"
230
+ )
231
+ if run.phases:
232
+ for phase_name in sorted(run.phases, key=phase_sort_key):
233
+ duration = run.phases[phase_name]
234
+ print(f" {phase_name}: {format_seconds(duration)}")
235
+ candidate = (duration, phase_name, run.ref)
236
+ if slowest is None or candidate[0] > slowest[0]:
237
+ slowest = candidate
238
+ else:
239
+ print(" 暂无完整的阶段事件配对")
240
+ total_pauses += run.pauses
241
+ total_incomplete += run.incomplete
242
+ design_reviews += int("design_review" in run.triggered)
243
+ spec_reviews += int("spec_review" in run.triggered)
244
+
245
+ print("\n汇总")
246
+ if slowest is None:
247
+ print("- 最慢阶段: 暂无完整数据")
248
+ else:
249
+ print(
250
+ f"- 最慢阶段: {slowest[1]} {format_seconds(slowest[0])} "
251
+ f"({slowest[2].project} / {slowest[2].run_id})"
252
+ )
253
+ print(f"- 人工暂停: {total_pauses}")
254
+ print(f"- 审查触发: design_review {design_reviews},spec_review {spec_reviews}")
255
+ print(f"- 未配对 segment: {total_incomplete}(未猜测耗时)")
256
+
257
+
258
+ def main() -> int:
259
+ configure_output()
260
+ args = parse_args()
261
+ configured_home = args.log_home or os.environ.get(
262
+ "CM_WORKFLOW_LOG_HOME", "~/.cm-workflow/logs"
263
+ )
264
+ log_home = Path(configured_home).expanduser().resolve(strict=False)
265
+ refs = load_run_refs(log_home)[: args.last]
266
+ timings = [timing for ref in refs if (timing := load_run_timing(log_home, ref))]
267
+ print_report(timings, args.last)
268
+ return 0
269
+
270
+
271
+ if __name__ == "__main__":
272
+ raise SystemExit(main())
@@ -0,0 +1,145 @@
1
+ // Read-only admission and route gate for the existing cm-refactor workflow.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+
6
+ const INTENTS=new Set(['defect','behavior-change','gradual-adoption','structure-only']);
7
+
8
+ function reject(code) {
9
+ const error=new Error(code);
10
+ error.code=code;
11
+ throw error;
12
+ }
13
+
14
+ function frozen(value) {
15
+ if(value&&typeof value==='object'){
16
+ for(const item of Object.values(value))frozen(item);
17
+ Object.freeze(value);
18
+ }
19
+ return value;
20
+ }
21
+
22
+ function text(value,code) {
23
+ if(typeof value!=='string'||value.trim().length===0||value.includes('\0'))reject(code);
24
+ return value;
25
+ }
26
+
27
+ function realDirectory(raw,code) {
28
+ try {
29
+ const target=fs.realpathSync(path.resolve(text(raw,code)));
30
+ const stat=fs.lstatSync(target);
31
+ if(!stat.isDirectory()||stat.isSymbolicLink())reject(code);
32
+ return target;
33
+ } catch(error) {
34
+ if(error?.code===code)throw error;
35
+ reject(code);
36
+ }
37
+ }
38
+
39
+ function ownedFile(root,relative,code) {
40
+ try {
41
+ const target=path.join(root,relative);
42
+ const stat=fs.lstatSync(target);
43
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||fs.realpathSync(target)!==target)reject(code);
44
+ return target;
45
+ } catch(error) {
46
+ if(error?.code===code)throw error;
47
+ reject(code);
48
+ }
49
+ }
50
+
51
+ function workflowRoot(skillDir) {
52
+ const skill=realDirectory(skillDir,'skill_path_invalid');
53
+ const root=realDirectory(path.resolve(skill,'../..'),'skill_path_invalid');
54
+ if(skill!==path.join(root,'skills','cm-refactor'))reject('skill_path_invalid');
55
+ let layout;
56
+ if(fs.existsSync(path.join(root,'VERSION'))){
57
+ ownedFile(root,'VERSION','skill_path_invalid');layout='plugin';
58
+ }else if(fs.existsSync(path.join(root,'templates','cm-VERSION'))){
59
+ ownedFile(root,'templates/cm-VERSION','skill_path_invalid');layout='claude-compat';
60
+ }else reject('skill_path_invalid');
61
+ if(realDirectory(path.join(root,'templates'),'skill_path_invalid')!==path.join(root,'templates'))
62
+ reject('skill_path_invalid');
63
+ for(const file of ['skills/cm-refactor/SKILL.md','templates/refactor/cm-refactor-denies.json',
64
+ 'runtime/project-context.md','runtime/orchestration.md','runtime/workflow-routing.md',
65
+ 'runtime/review.md','runtime/logging.md','runtime/project-learning.md',
66
+ 'scripts/cm-refactor-entry.mjs'])ownedFile(root,file,'skill_path_invalid');
67
+ return {root,skill,layout};
68
+ }
69
+
70
+ function normalizeInput(input) {
71
+ if(!input||typeof input!=='object'||Array.isArray(input))reject('invalid_input');
72
+ const keys=Object.keys(input),allowed=new Set(['skillDir','project','specs','targetPresent','intent']);
73
+ if(!['skillDir','project','targetPresent','intent'].every(key=>keys.includes(key))
74
+ ||keys.some(key=>!allowed.has(key))||typeof input.targetPresent!=='boolean'
75
+ ||typeof input.intent!=='string'||!INTENTS.has(input.intent))reject('invalid_input');
76
+ text(input.project,'invalid_input');
77
+ if(Object.hasOwn(input,'specs'))text(input.specs,'invalid_input');
78
+ return input;
79
+ }
80
+
81
+ export function inspectCmRefactorAdmission(raw) {
82
+ const input=normalizeInput(raw);
83
+ const {root,skill,layout}=workflowRoot(input.skillDir);
84
+ const base={
85
+ schemaVersion:1,workflow:'cm-refactor',workflowRoot:root,skillDir:skill,runtimeLayout:layout,
86
+ intent:input.intent,executionAuthorized:false,writeAuthorized:false
87
+ };
88
+ if(!input.targetPresent)return frozen({...base,status:'blocked',reason:'target_required',
89
+ next:'collect_refactor_target'});
90
+ if(input.intent==='defect')return frozen({...base,status:'redirect',
91
+ reason:'defect_flow_required',next:'cm-fix'});
92
+ if(input.intent==='behavior-change')return frozen({...base,status:'redirect',
93
+ reason:'behavior_change_flow_required',next:'cm-prd_change'});
94
+ if(input.intent==='gradual-adoption')return frozen({...base,status:'redirect',
95
+ reason:'gradual_adoption_not_refactor',next:'ordinary_change'});
96
+ const project=realDirectory(input.project,'project_path_invalid');
97
+ const specs=Object.hasOwn(input,'specs')?realDirectory(input.specs,'specs_path_invalid'):null;
98
+ return frozen({...base,project,specs,mode:specs===null?'bare':'specs',status:'ready',
99
+ reason:null,next:'g0_feasibility',
100
+ behaviorMustRemainUnchanged:true,humanApprovalRequiredBeforeChange:true,
101
+ requiredRoles:['coder','tester','reviewer'],roleResolution:'pending',logging:'pending',
102
+ learning:'pending'});
103
+ }
104
+
105
+ function parseCli(argv) {
106
+ const input={targetPresent:false},values=new Map([
107
+ ['--skill-dir','skillDir'],['--project','project'],['--specs','specs'],['--intent','intent']
108
+ ]);
109
+ for(let index=0;index<argv.length;index+=1){
110
+ const flag=argv[index];
111
+ if(flag==='--target-present'){
112
+ if(input.targetPresent)reject('invalid_arguments');
113
+ input.targetPresent=true;continue;
114
+ }
115
+ const key=values.get(flag);
116
+ if(!key||Object.hasOwn(input,key)||index+1>=argv.length
117
+ ||values.has(argv[index+1])||argv[index+1]==='--target-present')reject('invalid_arguments');
118
+ input[key]=argv[index+1];index+=1;
119
+ }
120
+ return input;
121
+ }
122
+
123
+ function isMainModule(entry) {
124
+ if(!entry)return false;
125
+ try {
126
+ return fs.realpathSync(entry)===fileURLToPath(import.meta.url);
127
+ } catch {
128
+ return path.resolve(entry)===fileURLToPath(import.meta.url);
129
+ }
130
+ }
131
+
132
+ if(isMainModule(process.argv[1])){
133
+ try {
134
+ const result=inspectCmRefactorAdmission(parseCli(process.argv.slice(2)));
135
+ if(fileURLToPath(import.meta.url)!==path.join(result.workflowRoot,'scripts','cm-refactor-entry.mjs'))
136
+ reject('entry_path_invalid');
137
+ const output=`${JSON.stringify(result)}\n`;
138
+ if(result.status==='ready')process.stdout.write(output);
139
+ else { process.stderr.write(output);process.exitCode=2; }
140
+ } catch(error) {
141
+ process.stderr.write(`${JSON.stringify({schemaVersion:1,workflow:'cm-refactor',status:'error',
142
+ reason:error?.code??'admission_failed',executionAuthorized:false,writeAuthorized:false})}\n`);
143
+ process.exitCode=2;
144
+ }
145
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
6
+ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
7
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
8
+ import {need} from '../runtime/js/cm-ai/effect-contract.mjs';
9
+ export async function main(argv=process.argv.slice(2)){
10
+ let bridge;
11
+ try{
12
+ if(argv.length===1&&argv[0]==='--help'){
13
+ process.stdout.write('cm-refactor-host.mjs serve --config ABSOLUTE_JSON\nLight/batch tracks: start/status/cancel/resume/finish over original host JSONL. Durable original review rounds; unknown effects require actual host reconciliation. Judge preparation, assembly and pre-review Learning/rules/memos share N4/N5. No provider, install or Git delivery. See skills/cm-refactor/references/js-host.md.\n');return 0;
14
+ }
15
+ need(argv.length===3&&argv[0]==='serve'&&argv[1]==='--config'&&path.isAbsolute(argv[2]),'invalid_arguments');
16
+ const stat=fs.lstatSync(argv[2]);need(stat.isFile()&&!stat.isSymbolicLink()&&stat.size<=64*1024,'refactor_config_invalid');
17
+ const config=JSON.parse(fs.readFileSync(argv[2],'utf8'));
18
+ need(path.resolve(config.skillDir,'../..','scripts/cm-refactor-host.mjs')===fileURLToPath(import.meta.url),'entry_path_invalid');
19
+ bridge=createHostToolBridge({responseLimit:2*1024*1024});const host=createCmRefactorHost(config,{call:(...args)=>bridge.call(...args)});
20
+ const raw=process.stdin.isTTY&&typeof process.stdin.setRawMode==='function';if(raw)process.stdin.setRawMode(true);
21
+ try{await serveCmAiHost({host,input:process.stdin,output:process.stdout,toolBridge:bridge,inputLimit:2*1024*1024});}finally{if(raw)process.stdin.setRawMode(false);}
22
+ return 0;
23
+ }catch(error){process.stderr.write(JSON.stringify({error:{code:error.code??'refactor_host_failed'}})+'\n');return 1;}
24
+ finally{bridge?.close();}
25
+ }
26
+ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();
@@ -0,0 +1,201 @@
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 {spawn,spawnSync} from 'node:child_process';
7
+ import {once} from 'node:events';
8
+ import {createInterface} from 'node:readline';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+ const root=fileURLToPath(new URL('..',import.meta.url));
13
+ const original='export const calc = x => x < 0 ? 0 : x + 1;\n';
14
+ const replacement='export function calc(x) { if (x < 0) return 0; return x + 1; }\n';
15
+ function fixture(t){
16
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-refactor-host-'))),project=path.join(temp,'project');
17
+ fs.mkdirSync(project);fs.writeFileSync(path.join(project,'input.mjs'),original);
18
+ fs.writeFileSync(path.join(project,'baseline.mjs'),"import assert from 'node:assert/strict'; import {calc} from './input.mjs'; assert.equal(calc(-1),0); assert.equal(calc(2),3);\n");
19
+ fs.writeFileSync(path.join(project,'judge.mjs'),"import {calc} from './input.mjs'; console.log(JSON.stringify({cases:[-2,0,2].map((x,i)=>({id:String(i),input:x,output:calc(x)}))}));\n");
20
+ t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
21
+ return {temp,project,config:{skillDir:path.join(root,'skills/cm-refactor'),project,specs:null,runtime:'codex',
22
+ target:'Synthetic structure-only refactor',slug:'extract',scope:['input.mjs'],crossModule:false,
23
+ baselineCommands:[{id:'baseline',command:[process.execPath,'baseline.mjs']}],judgeCommand:[process.execPath,'judge.mjs'],
24
+ mutations:[{path:'input.mjs',find:'x + 1',replace:'x + 2'},{path:'input.mjs',find:'x < 0',replace:'x < -5'}],logHome:path.join(temp,'logs')}};
25
+ }
26
+ function response(kind,payload,mode='normal'){
27
+ if(kind==='refactor_analyze')return {decision:'proceed',metric:{name:'Synthetic nesting',before:2,unit:'levels'},impact:[],claimedMemos:[],reason:'Synthetic simplification'};
28
+ if(kind==='refactor_confirm')return {decision:mode==='reject'?'rejected':'approved'};
29
+ if(kind==='refactor_apply')return {files:[{path:'input.mjs',beforeDigest:digest(original),content:mode==='behavior-change'?replacement.replace('x + 1','x + 9'):replacement}],
30
+ summary:'Synthetic explicit function extraction',metricAfter:1,unfixedDefects:[],conventions:[],
31
+ learningApplication:'No additional relevant project lesson in this fixture',learningRetrospective:'no_new_lesson'};
32
+ assert.equal(kind,'refactor_review');
33
+ return {markdown:`---\nat: 2026-09-08T18:00:00+00:00\nreviewer: codex-subagent\nindependent: true\ntask: ${payload.task}\nattempt: ${payload.attempt}\nround: ${payload.attempt}\nverdict: approved\nblocking_findings: 0\nhandoff: ${path.basename(payload.handoff)}\nhandoff_sha256: ${mode==='stale-review'?'0'.repeat(64):payload.handoffSha256}\nscope:\n - input.mjs\n---\n\nZero findings in synthetic review; not a live independent reviewer invocation.\n`};
34
+ }
35
+ test('light-track actual CLI: both runtimes use real baseline/mutations/differential and original gates',async t=>{
36
+ for(const runtime of ['codex','claude']){
37
+ const {config,temp,project}=fixture(t);config.runtime=runtime;
38
+ if(runtime==='codex'){config.specs=path.join(temp,'specs');fs.mkdirSync(config.specs);}
39
+ const configPath=path.join(temp,'config.json');fs.writeFileSync(configPath,JSON.stringify(config));
40
+ const child=spawn(process.execPath,[path.join(root,'scripts/cm-refactor-host.mjs'),'serve','--config',configPath],{stdio:['pipe','pipe','pipe']});
41
+ const closed=once(child,'close'),lines=createInterface({input:child.stdout});let sessionId,result,stderr='';
42
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',chunk=>{stderr+=chunk;});t.after(()=>child.kill());
43
+ for await(const line of lines){const message=JSON.parse(line);
44
+ if(message.type==='host_ready'){sessionId=message.sessionId;send({requestId:'start',operation:'start'});}
45
+ else if(message.type==='host_request')send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result:response(message.kind,message.payload)});
46
+ else if(message.requestId==='start'){
47
+ assert.equal(message.result.stage,'awaiting_finish',JSON.stringify(message));send({requestId:'finish',operation:'finish'});
48
+ }else if(message.requestId==='finish'){result=message.result;send({type:'host_close',sessionId});}
49
+ }
50
+ assert.equal((await closed)[0],0,stderr);assert.equal(result.stage,'done',JSON.stringify(result));
51
+ assert.equal(result.differentialCount,3);assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),replacement);
52
+ assert.equal(result.completionAuthorized,false);assert.ok(result.reports.some(file=>file.endsWith('-r1.md')));
53
+ if(config.specs){assert.match(fs.readFileSync(path.join(config.specs,'METRICS.md'),'utf8'),/\| refactor \|/);
54
+ const status=JSON.parse(fs.readFileSync(path.join(config.specs,'.cm-status.json'),'utf8'));
55
+ assert.equal(status.node,'REFACTOR');assert.equal(status.state,'run_done');
56
+ assert.match(fs.readFileSync(path.join(config.specs,'运行日志.jsonl'),'utf8'),/"event":"run_done"/);}
57
+ }
58
+ });
59
+ test('G0 rejection never mutates or executes the judge',async t=>{
60
+ const {config,project}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload,'reject')});
61
+ const result=await host.handle({requestId:'start',operation:'start'});
62
+ assert.equal(result.stage,'rejected');assert.equal(result.commandCount,0);assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
63
+ });
64
+ test('behavior regression restores only the controlled file and blocks review',async t=>{
65
+ const {config,project}=fixture(t);let reviewCalls=0;
66
+ const host=createCmRefactorHost(config,{call:async(kind,payload)=>{if(kind==='refactor_review')reviewCalls++;return response(kind,payload,'behavior-change');}});
67
+ const result=await host.handle({requestId:'start',operation:'start'});
68
+ assert.equal(result.stage,'blocked',JSON.stringify(result));assert.equal(reviewCalls,0);
69
+ assert.equal(result.reason,'refactor_baseline_failed');
70
+ assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
71
+ });
72
+ test('stale independent-review header cannot bypass existing N5',async t=>{
73
+ const {config}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload,'stale-review')});
74
+ const result=await host.handle({requestId:'start',operation:'start'});
75
+ assert.equal(result.stage,'blocked');assert.match(result.reason,/digest/);
76
+ });
77
+
78
+ function fullResponse(kind,payload){
79
+ if(kind==='refactor_review'){
80
+ const value=response(kind,payload);value.markdown=value.markdown.replace(' - input.mjs',payload.files.map(file=>' - '+file.path).join('\n'));return value;
81
+ }
82
+ if(kind==='refactor_prepare_tests')return {files:payload.assets.map(file=>({...file,content:file.path==='baseline.mjs'
83
+ ?"import assert from 'node:assert/strict'; import {calc} from './input.mjs'; assert.equal(calc(2),3);\n"
84
+ :"import {calc} from './input.mjs'; console.log(JSON.stringify({cases:[-2,0,2].map((x,i)=>({id:String(i),input:x,output:calc(x)}))}));\n"}))};
85
+ if(kind==='refactor_retrospective')return {learningApplication:'Apply original behavior contract',learning:{status:'lesson_candidate',reason:null,
86
+ candidates:[{classification:'structured',trigger:'Boundary-sensitive refactor',action:'Keep negative inputs in differential judge',evidence:['judge.mjs']}]},
87
+ conventions:[{path:'.claude/rules/shape.md',text:'Use named function exports.',evidence:['input.mjs']}],documentation:payload.files.filter(file=>file.path==='README.md')
88
+ .map(file=>({...file,content:(file.content??'')+'\nRefactored module structure.\n'})),resolved:(payload.needs??[]).map(item=>item.id),unfixedDefects:[],metricAfter:1};
89
+ if(kind==='refactor_batch'){
90
+ if(payload.action==='plan')return {rulebook:'Named functions; preserve values; do not fix bugs.',units:payload.files.filter(file=>!payload.assemblyFiles.includes(file.path))
91
+ .map((file,i)=>({id:`unit-${i}`,files:[file.path],dependsOn:i?[`unit-${i-1}`]:[]})),sample:['input.mjs'],perFileEstimate:300,reason:'Reduce nesting'};
92
+ if(payload.action==='bakeoff')return {channelId:payload.variant,files:payload.files.map(file=>({...file,content:replacement}))};
93
+ if(payload.action==='adjudicate')return {channelId:'third',rulebook:payload.rulebook,decisions:[]};
94
+ if(payload.action==='assemble')return {files:payload.files.map(file=>({...file,content:'export {calc} from "./input.mjs";\n'})),resolved:payload.needs.map(item=>item.id)};
95
+ if(payload.action==='generate')return {files:payload.files.map(file=>({...file,content:file.path==='old.mjs'?null:
96
+ (file.path==='input.mjs'?replacement:'export const helper = 1;\n')+'// REFACTOR STATUS: confidence=high todos=0\n'})),
97
+ needs:payload.files[0].path==='input.mjs'?[{id:'entry-wire',path:'entry.mjs',instruction:'Preserve entry export'}]:[],summary:'Structure only'};
98
+ if(payload.action==='diagnose')return {errorClass:'syntax',reason:'Same generator rule produces invalid syntax'};
99
+ }
100
+ return response(kind,payload);
101
+ }
102
+ async function finishInProcess(t,config,temp){
103
+ const configPath=path.join(temp,'resume-config.json');fs.writeFileSync(configPath,JSON.stringify(config));
104
+ const child=spawn(process.execPath,[path.join(root,'scripts/cm-refactor-host.mjs'),'serve','--config',configPath],{stdio:['pipe','pipe','pipe']});
105
+ const closed=once(child,'close'),lines=createInterface({input:child.stdout});let sessionId,result,stderr='';
106
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',chunk=>{stderr+=chunk;});t.after(()=>child.kill());
107
+ for await(const line of lines){const message=JSON.parse(line);
108
+ if(message.type==='host_ready'){sessionId=message.sessionId;send({requestId:'finish',operation:'finish'});}
109
+ else if(message.type==='host_request'){
110
+ assert.equal(message.kind,'refactor_confirm');assert.equal(message.payload.gate,'finish');
111
+ send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result:{decision:'approved'}});
112
+ }else if(message.requestId==='finish'){result=message.result;send({type:'host_close',sessionId});}
113
+ }
114
+ assert.equal((await closed)[0],0,stderr);return result;
115
+ }
116
+ test('missing judge assets, Learning, memo reconciliation and new-process finish use one reviewed path',async t=>{
117
+ const {config,project,temp}=fixture(t);config.specs=path.join(temp,'specs');fs.mkdirSync(config.specs);
118
+ fs.writeFileSync(path.join(config.specs,'LESSONS.md'),'## 待触发备忘\n- [待触发] 重构 input 分支\n');
119
+ fs.writeFileSync(path.join(project,'AGENTS.md'),'# Project\n\nKeep existing instructions.\n');fs.writeFileSync(path.join(project,'README.md'),'# Example\n');
120
+ fs.unlinkSync(path.join(project,'baseline.mjs'));fs.unlinkSync(path.join(project,'judge.mjs'));
121
+ config.testSetup={paths:['baseline.mjs','judge.mjs']};config.writebackPaths=['AGENTS.md','README.md'];let calls=0;
122
+ const call=async(kind,payload)=>{calls++;const result=fullResponse(kind,payload);
123
+ if(kind==='refactor_analyze')result.claimedMemos=['- [待触发] 重构 input 分支'];return result;};
124
+ const host=createCmRefactorHost(config,{call});const started=await host.handle({requestId:'start',operation:'start'});
125
+ assert.equal(started.stage,'awaiting_finish',JSON.stringify(started));const before=calls;
126
+ const finished=await finishInProcess(t,config,temp);assert.equal(finished.stage,'done',JSON.stringify(finished));assert.equal(calls,before);
127
+ assert.match(fs.readFileSync(path.join(project,'AGENTS.md'),'utf8'),/Keep existing instructions[\s\S]*Boundary-sensitive refactor/);
128
+ const lessons=fs.readFileSync(path.join(config.specs,'LESSONS.md'),'utf8');assert.match(lessons,/已认领/);assert.match(lessons,/仅记忆/);
129
+ assert.equal((fs.readFileSync(path.join(project,'AGENTS.md'),'utf8').match(/cm-learning-v1/g)??[]).length,1);
130
+ const reopened=createCmRefactorHost(config,{call:async()=>{throw Error('must not call');}});
131
+ assert.equal((await reopened.handle({requestId:'again',operation:'finish'})).stage,'done');
132
+ fs.appendFileSync(path.join(project,'input.mjs'),'// user changed after completion\n');
133
+ const status=await reopened.handle({requestId:'status',operation:'status'});assert.equal(status.stage,'correction_required');assert.equal(status.historicalStage,'done');
134
+ });
135
+ test('batch uses bakeoff, pilot, disk units, add/delete and owner assembly before final review',async t=>{
136
+ const {config,project}=fixture(t);fs.writeFileSync(path.join(project,'old.mjs'),'export const old = true;\n');
137
+ fs.writeFileSync(path.join(project,'entry.mjs'),'export {calc} from "./input.mjs"; // original\n');
138
+ fs.writeFileSync(path.join(project,'AGENTS.md'),'# Project\n');
139
+ for(const args of [['init','-q'],['add','.'],['-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','fixture']]){
140
+ const out=spawnSync('git',args,{cwd:project});assert.equal(out.status,0,out.stderr.toString());}
141
+ config.scope=['input.mjs','new.mjs','old.mjs','entry.mjs'];config.batch={assemblyFiles:['entry.mjs'],cheapCommands:[{id:'syntax',command:[process.execPath,'--check','{file}']}],maxPasses:6};
142
+ config.writebackPaths=['AGENTS.md'];const kinds=[];let generation=0,ruleRevisions=0;
143
+ const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
144
+ kinds.push(payload.action??kind);const result=fullResponse(kind,payload);
145
+ if(kind==='refactor_confirm'&&payload.gate==='rulebook_revision')ruleRevisions++;
146
+ if(kind==='refactor_batch'&&payload.action==='generate'&&payload.files[0].path==='input.mjs'){
147
+ generation++;if(generation>=2&&generation<=4)result.files[0].content='export const calc = ;\n// REFACTOR STATUS: confidence=low todos=0\n';}
148
+ return result;}});
149
+ const started=await host.handle({requestId:'start',operation:'start'});assert.equal(started.stage,'awaiting_finish',JSON.stringify(started));
150
+ const finished=await host.handle({requestId:'finish',operation:'finish'});assert.equal(finished.stage,'done',JSON.stringify(finished));
151
+ assert.equal(fs.existsSync(path.join(project,'old.mjs')),false);assert.ok(fs.existsSync(path.join(project,'new.mjs')));
152
+ assert.equal(kinds.filter(kind=>kind==='bakeoff').length,2);assert.equal(kinds.filter(kind=>kind==='refactor_review').length,1);
153
+ assert.equal(ruleRevisions,1);assert.equal(kinds.filter(kind=>kind==='diagnose').length,3);
154
+ assert.ok(kinds.includes('assemble'));assert.match(fs.readFileSync(path.join(project,'docs/refactors/extract/batch-log.jsonl'),'utf8'),/"diff_pass":true/);
155
+ });
156
+ test('interrupted host invocation needs reconciliation, then resumes without repeating the review',async t=>{
157
+ const {config}=fixture(t);let request=null;
158
+ const broken=createCmRefactorHost(config,{call:async(kind,payload)=>{if(kind==='refactor_review'){request=payload;throw Error('connection lost');}return response(kind,payload);}});
159
+ assert.equal((await broken.handle({requestId:'start',operation:'start'})).stage,'blocked');
160
+ let reviews=0;
161
+ const reopened=createCmRefactorHost(config,{call:async(kind,payload)=>{
162
+ if(kind==='refactor_recover')return {decision:'completed',evidence:'Synthetic recorded reviewer response from original call',
163
+ result:{value:response('refactor_review',request),durationMs:1}};
164
+ if(kind==='refactor_review')reviews++;return response(kind,payload);}});
165
+ const resumed=await reopened.handle({requestId:'resume',operation:'resume'});assert.equal(resumed.stage,'awaiting_finish',JSON.stringify(resumed));assert.equal(reviews,0);
166
+ const finished=await reopened.handle({requestId:'finish',operation:'finish'});assert.equal(finished.stage,'done',JSON.stringify(finished));
167
+ });
168
+
169
+ test('pending finish keeps its key; approved finish replays frozen budget after archival interruption',async t=>{
170
+ const {config,project}=fixture(t);let confirmations=0,reconciliations=0;
171
+ const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
172
+ if(kind==='refactor_confirm'&&payload.gate==='finish'){confirmations++;throw Error('lost finish response');}return response(kind,payload);}});
173
+ assert.equal((await host.handle({requestId:'start',operation:'start'})).stage,'awaiting_finish');
174
+ assert.equal((await host.handle({requestId:'finish',operation:'finish'})).stage,'blocked');
175
+ const recovered=createCmRefactorHost(config,{call:async(kind,payload)=>{
176
+ assert.equal(kind,'refactor_recover');assert.equal(payload.input.kind,'refactor_confirm');reconciliations++;
177
+ return {decision:'completed',result:{value:{decision:'approved'},durationMs:51},evidence:'Synthetic original confirmation receipt'};}});
178
+ const finished=await recovered.handle({requestId:'finish',operation:'finish'});assert.equal(finished.stage,'done',JSON.stringify(finished));
179
+ assert.equal(confirmations,1);assert.equal(reconciliations,1);
180
+ const file=path.join(project,'docs/refactors/extract/execution.jsonl'),rows=fs.readFileSync(file,'utf8').trimEnd().split('\n');
181
+ const index=rows.findIndex(line=>{const row=JSON.parse(line);return row.type==='result'&&row.key==='host/finish-1';});assert.ok(index>=0);
182
+ // Isolated crash-prefix fixture: approval persisted, later archive/checkpoint records did not.
183
+ fs.writeFileSync(file,rows.slice(0,index+1).join('\n')+'\n');
184
+ const retry=createCmRefactorHost(config,{call:async()=>{throw Error('approval must not be requested again');}});
185
+ const repeated=await retry.handle({requestId:'finish',operation:'finish'});assert.equal(repeated.stage,'done',JSON.stringify(repeated));
186
+ assert.doesNotMatch(fs.readFileSync(file,'utf8'),/host\/finish-2/);
187
+ });
188
+ test('interrupted resume differential reconciles original round before creating another command',async t=>{
189
+ const {config,project}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload)});
190
+ assert.equal((await host.handle({requestId:'start',operation:'start'})).stage,'awaiting_finish');
191
+ assert.equal((await host.handle({requestId:'resume',operation:'resume'})).stage,'awaiting_finish');
192
+ const file=path.join(project,'docs/refactors/extract/execution.jsonl'),lines=fs.readFileSync(file,'utf8').trimEnd().split('\n'),rows=lines.map(line=>JSON.parse(line));
193
+ const key='command/resume-check/1/differential',index=rows.findIndex(row=>row.type==='intent'&&row.key===key);
194
+ const originalResult=rows.find(row=>row.type==='result'&&row.key===key).result;assert.ok(index>=0);
195
+ fs.writeFileSync(file,lines.slice(0,index+1).join('\n')+'\n');let reconciliations=0;
196
+ const reopened=createCmRefactorHost(config,{call:async(kind,payload)=>{
197
+ assert.equal(kind,'refactor_recover');assert.equal(payload.kind,'command');reconciliations++;
198
+ return {decision:'completed',result:originalResult,cleanupConfirmed:true,evidence:'Synthetic original command result and confirmed cleanup'};}});
199
+ const resumed=await reopened.handle({requestId:'resume',operation:'resume'});assert.equal(resumed.stage,'awaiting_finish',JSON.stringify(resumed));
200
+ assert.equal(reconciliations,1);assert.doesNotMatch(fs.readFileSync(file,'utf8'),/command\/resume-check\/2\//);
201
+ });