@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,119 @@
1
+ // Minimal N3 handoff update for one runner-owned task Learning result.
2
+ import {createHash,randomUUID} from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import childProcess from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
8
+ readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
9
+ import {readCmAiProjectLearningWriteback} from './cm-ai-learning-writer.mjs';
10
+ import {arrayItems,digest,freeze,json,need,shape,text,validIdentity,validTaskLearningInput} from './effect-contract.mjs';
11
+
12
+ const LIMIT=256*1024,MiB=1024*1024;
13
+ const gate=fileURLToPath(new URL('../../../scripts/cm-task-gate.mjs',import.meta.url));
14
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
15
+ const statKey=stat=>[stat.dev,stat.ino,stat.mode,stat.nlink,stat.size,stat.mtimeNs,stat.ctimeNs].join(':');
16
+
17
+ function readHandoff(target) {
18
+ let descriptor;
19
+ try {
20
+ const before=fs.lstatSync(target,{bigint:true});
21
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n&&before.size<=BigInt(LIMIT),'handoff_unsafe');
22
+ descriptor=fs.openSync(target,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
23
+ need(statKey(before)===statKey(fs.fstatSync(descriptor,{bigint:true})),'handoff_changed');
24
+ const bytes=fs.readFileSync(descriptor);need(bytes.length===Number(before.size),'handoff_changed');
25
+ const source=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);
26
+ const after=fs.fstatSync(descriptor,{bigint:true}),last=fs.lstatSync(target,{bigint:true});
27
+ need(statKey(before)===statKey(after)&&statKey(before)===statKey(last),'handoff_changed');
28
+ return {bytes,source,sha256:sha(bytes),mode:Number(before.mode&0o7777n),stat:before};
29
+ } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
30
+ }
31
+
32
+ const sameSnapshot=(left,right)=>statKey(left.stat)===statKey(right.stat)&&left.sha256===right.sha256;
33
+
34
+ function validateHandoff(target,identity) {
35
+ const result=childProcess.spawnSync(process.execPath,[gate,'validate-handoff','--handoff',target,
36
+ '--task',identity.taskId,'--attempt',String(identity.attempt)],{encoding:'buffer',timeout:10000,maxBuffer:MiB});
37
+ need(!result.error&&result.status===0&&result.signal===null&&Buffer.isBuffer(result.stdout)
38
+ &&result.stdout.length<=MiB,'handoff_invalid');
39
+ }
40
+
41
+ export function writeCmAiTaskLearningHandoff(raw) {
42
+ const input=json(raw,512*1024);
43
+ shape(input,['handoffPath','feature','identity','learningInput','application','retrospective','writeback']);
44
+ text(input.handoffPath);text(input.feature);validIdentity(input.identity);
45
+ need(path.isAbsolute(input.handoffPath)&&path.resolve(input.handoffPath)===input.handoffPath,'unsupported_path');
46
+ validTaskLearningInput(input.learningInput,input.identity,input.feature);
47
+ readCmAiTaskLearningApplication(input.application);
48
+ const writeback=readCmAiProjectLearningWriteback(input.writeback,
49
+ {learningInput:input.learningInput,retrospective:input.retrospective});
50
+ need(writeback.outcome!=='writeback_pending','handoff_invalid');
51
+
52
+ const parent=path.dirname(input.handoffPath);
53
+ need(fs.realpathSync(parent)===parent&&fs.lstatSync(parent).isDirectory(),'unsupported_path');
54
+ const before=readHandoff(input.handoffPath);validateHandoff(input.handoffPath,input.identity);
55
+ need(sameSnapshot(before,readHandoff(input.handoffPath)),'handoff_changed');
56
+ let handoff;
57
+ try {handoff=JSON.parse(before.source);}catch{need(false,'handoff_invalid');}
58
+ const applied=attachCmAiTaskLearningApplicationEvidence({handoff,feature:input.feature,identity:input.identity,
59
+ learningInput:input.learningInput,application:input.application});
60
+ const attached=attachCmAiTaskLearningEvidence({handoff:applied,feature:input.feature,identity:input.identity,
61
+ learningInput:input.learningInput,retrospective:input.retrospective});
62
+ const changedFiles=arrayItems(attached.changed_files);for(const item of changedFiles)text(item);
63
+ const includeAgents=writeback.outcome==='written';
64
+ const next={...attached,changed_files:includeAgents&&!changedFiles.includes('AGENTS.md')
65
+ ?[...changedFiles,'AGENTS.md']:changedFiles};
66
+ const bytes=Buffer.from(`${JSON.stringify(next,null,2)}\n`);
67
+ need(bytes.length<=LIMIT,'limit_exceeded');
68
+ if(bytes.equals(before.bytes))return freeze({outcome:'unchanged',handoffSha256:before.sha256});
69
+
70
+ const temporary=path.join(parent,`.${path.basename(input.handoffPath)}.cm-learning.${process.pid}.${randomUUID()}`);
71
+ let descriptor,renamed=false;
72
+ try {
73
+ descriptor=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL
74
+ |(fs.constants.O_NOFOLLOW??0),before.mode);
75
+ fs.fchmodSync(descriptor,before.mode);fs.writeFileSync(descriptor,bytes);fs.fsyncSync(descriptor);
76
+ fs.closeSync(descriptor);descriptor=undefined;
77
+ need(sameSnapshot(before,readHandoff(input.handoffPath)),'handoff_changed');
78
+ fs.renameSync(temporary,input.handoffPath);renamed=true;
79
+ const directory=fs.openSync(parent,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
80
+ try{fs.fsyncSync(directory);}finally{fs.closeSync(directory);}
81
+ const after=readHandoff(input.handoffPath);need(after.bytes.equals(bytes),'handoff_write_failed');
82
+ validateHandoff(input.handoffPath,input.identity);
83
+ need(sameSnapshot(after,readHandoff(input.handoffPath)),'handoff_changed');
84
+ return freeze({outcome:'written',handoffSha256:after.sha256});
85
+ } finally {
86
+ if(descriptor!==undefined)try{fs.closeSync(descriptor);}catch{}
87
+ if(!renamed)try{fs.unlinkSync(temporary);}catch{}
88
+ }
89
+ }
90
+
91
+ export function verifyCmAiTaskLearningHandoff(raw) {
92
+ const input=json(raw,512*1024);
93
+ const hasApplication=Object.hasOwn(input,'application');
94
+ shape(input,['handoffPath','feature','identity','learningInput',...(hasApplication?['application']:[]),
95
+ 'retrospective','writeback']);
96
+ text(input.handoffPath);text(input.feature);validIdentity(input.identity);
97
+ need(path.isAbsolute(input.handoffPath)&&path.resolve(input.handoffPath)===input.handoffPath,'unsupported_path');
98
+ validTaskLearningInput(input.learningInput,input.identity,input.feature);
99
+ if(hasApplication)readCmAiTaskLearningApplication(input.application);
100
+ const writeback=readCmAiProjectLearningWriteback(input.writeback,
101
+ {learningInput:input.learningInput,retrospective:input.retrospective});
102
+ need(writeback.outcome!=='writeback_pending','handoff_invalid');
103
+ const parent=path.dirname(input.handoffPath);
104
+ need(fs.realpathSync(parent)===parent&&fs.lstatSync(parent).isDirectory(),'unsupported_path');
105
+ const before=readHandoff(input.handoffPath);validateHandoff(input.handoffPath,input.identity);
106
+ need(sameSnapshot(before,readHandoff(input.handoffPath)),'handoff_changed');
107
+ let handoff;
108
+ try {handoff=JSON.parse(before.source);}catch{need(false,'handoff_invalid');}
109
+ if(!hasApplication){const evidence=arrayItems(handoff.evidence);for(const item of evidence)text(item);
110
+ need(!evidence.some(item=>item.startsWith('cm-learning-application-v1:')),'handoff_invalid');}
111
+ const applied=hasApplication?attachCmAiTaskLearningApplicationEvidence({handoff,feature:input.feature,
112
+ identity:input.identity,learningInput:input.learningInput,application:input.application}):handoff;
113
+ const attached=attachCmAiTaskLearningEvidence({handoff:applied,feature:input.feature,identity:input.identity,
114
+ learningInput:input.learningInput,retrospective:input.retrospective});
115
+ need(digest(attached)===digest(handoff),'handoff_invalid');
116
+ const changedFiles=arrayItems(handoff.changed_files);for(const item of changedFiles)text(item);
117
+ if(writeback.outcome==='written')need(changedFiles.includes('AGENTS.md'),'handoff_invalid');
118
+ return freeze({outcome:'matched',handoffSha256:before.sha256});
119
+ }
@@ -0,0 +1,172 @@
1
+ // Minimal project AGENTS.md writeback for the task-level Learning loop.
2
+ import {createHash,randomUUID} from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {digest,freeze,hex,json,need,shape,text,validIdentity,validTaskLearningInput} from './effect-contract.mjs';
6
+ import {encodeCmAiTaskLearningEvidence,readLearningRetrospectiveContent} from './cm-ai-context-refresh.mjs';
7
+
8
+ const LIMIT=256*1024,PREFIX='cm-learning-retrospective-v1:';
9
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
10
+ const statKey=stat=>[stat.dev,stat.ino,stat.mode,stat.nlink,stat.size,stat.mtimeNs,stat.ctimeNs].join(':');
11
+ const inline=value=>value.replace(/([\\`*_\[\]<>])/gu,'\\$1');
12
+
13
+ function canonicalRetrospective(raw) {
14
+ const encoded=encodeCmAiTaskLearningEvidence(raw);
15
+ return json(JSON.parse(encoded.slice(PREFIX.length)),16*1024);
16
+ }
17
+
18
+ function readAgents(target) {
19
+ let descriptor;
20
+ try {
21
+ const before=fs.lstatSync(target,{bigint:true});
22
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n&&before.size<=BigInt(LIMIT),'agents_unsafe');
23
+ descriptor=fs.openSync(target,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
24
+ need(statKey(before)===statKey(fs.fstatSync(descriptor,{bigint:true})),'agents_changed');
25
+ const bytes=fs.readFileSync(descriptor);need(bytes.length===Number(before.size),'agents_changed');
26
+ new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);
27
+ const after=fs.fstatSync(descriptor,{bigint:true}),last=fs.lstatSync(target,{bigint:true});
28
+ need(statKey(before)===statKey(after)&&statKey(before)===statKey(last),'agents_changed');
29
+ return {exists:true,bytes,sha256:sha(bytes),mode:Number(before.mode&0o7777n),stat:before};
30
+ } catch(error) {
31
+ if(error?.code==='ENOENT')return {exists:false,bytes:Buffer.alloc(0),sha256:null,mode:0o644,stat:null};
32
+ throw error;
33
+ } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
34
+ }
35
+
36
+ const sameSnapshot=(left,right)=>left.exists===right.exists&&(!left.exists||
37
+ statKey(left.stat)===statKey(right.stat)&&left.sha256===right.sha256);
38
+
39
+ function renderedCandidates(retrospective) {
40
+ return retrospective.candidates.map(candidate=>{
41
+ const marker=digest({version:1,trigger:candidate.trigger,action:candidate.action});
42
+ const classification=candidate.classification==='structured'?'[已结构化]':'[仅记忆]';
43
+ const source=`${retrospective.feature}/${retrospective.identity.taskId}/a${retrospective.identity.attempt}`;
44
+ return {marker:`<!-- cm-learning-v1:${marker} -->`,line:`- **${inline(candidate.trigger)}**:${inline(candidate.action)}`+
45
+ `。来源:${inline(source)};证据:${candidate.evidence.map(inline).join('、')}。${classification} `+
46
+ `<!-- cm-learning-v1:${marker} -->`};
47
+ });
48
+ }
49
+
50
+ export function mergeLessons(source,retrospective) {
51
+ const candidates=renderedCandidates(retrospective).filter(candidate=>!source.includes(candidate.marker));
52
+ if(candidates.length===0)return source;
53
+ const newline=source.includes('\r\n')?'\r\n':'\n',block=candidates.map(candidate=>candidate.line).join(newline);
54
+ const header=/^## 项目教训[ \t]*\r?$/gmu.exec(source);
55
+ if(!header){let prefix=source;if(prefix.length&&!prefix.endsWith(newline))prefix+=newline;
56
+ if(prefix.length&&!prefix.endsWith(newline+newline))prefix+=newline;
57
+ return `${prefix}## 项目教训${newline}${newline}${block}${newline}`;}
58
+ const headings=/^## [^\r\n]+\r?$/gmu;headings.lastIndex=header.index+header[0].length;
59
+ const next=headings.exec(source),insertAt=next?.index??source.length;
60
+ let before=source.slice(0,insertAt);const after=source.slice(insertAt);
61
+ if(!before.endsWith(newline))before+=newline;
62
+ if(!before.endsWith(newline+newline))before+=newline;
63
+ return `${before}${block}${newline}${after?newline:''}${after}`;
64
+ }
65
+
66
+ function result(retrospective,outcome,changed,agentsFile,reason) {
67
+ const body={version:1,workflow:'cm-ai',phase:'task_learning_writeback',feature:retrospective.feature,
68
+ identity:retrospective.identity,learningDigest:retrospective.learningDigest,
69
+ retrospectiveDigest:retrospective.retrospectiveDigest,outcome,changed,agentsFile,reason};
70
+ return freeze({...body,writebackDigest:digest(body)});
71
+ }
72
+
73
+ export function readCmAiProjectLearningWriteback(raw,{learningInput,retrospective}) {
74
+ validTaskLearningInput(learningInput,learningInput.identity,learningInput.feature);
75
+ const canonical=canonicalRetrospective(retrospective),value=json(raw,64*1024);
76
+ shape(value,['version','workflow','phase','feature','identity','learningDigest','retrospectiveDigest',
77
+ 'outcome','changed','agentsFile','reason','writebackDigest']);
78
+ need(value.version===1&&value.workflow==='cm-ai'&&value.phase==='task_learning_writeback');
79
+ need(value.feature===learningInput.feature&&digest(value.identity)===digest(learningInput.identity)
80
+ &&value.learningDigest===learningInput.learningDigest&&value.retrospectiveDigest===canonical.retrospectiveDigest,
81
+ 'identity_mismatch');
82
+ [value.learningDigest,value.retrospectiveDigest,value.writebackDigest].forEach(hex);
83
+ if(value.agentsFile!==null){shape(value.agentsFile,['scope','path','sha256']);
84
+ need(value.agentsFile.scope==='project'&&value.agentsFile.path==='AGENTS.md');hex(value.agentsFile.sha256);}
85
+ if(value.reason!==null){text(value.reason);need(value.reason.length<=512&&!/[\0\r\n\u2028\u2029]/u.test(value.reason));}
86
+ need(['no_new_lesson','written','deduplicated','writeback_pending'].includes(value.outcome));
87
+ const expectedAgents=learningInput.learningFiles.find(file=>file.scope==='project'&&file.path==='AGENTS.md')??null;
88
+ if(value.outcome==='no_new_lesson')need(canonical.status==='no_new_lesson'&&value.changed===false&&value.reason===null
89
+ &&digest(value.agentsFile)===digest(expectedAgents));
90
+ else if(value.outcome==='written')need(canonical.status==='lesson_candidate'&&value.changed===true
91
+ &&value.agentsFile!==null&&value.reason===null);
92
+ else if(value.outcome==='deduplicated')need(canonical.status==='lesson_candidate'&&value.changed===false
93
+ &&value.agentsFile!==null&&value.reason===null);
94
+ else if(canonical.status==='writeback_pending')need(value.changed===null&&value.reason===canonical.reason
95
+ &&digest(value.agentsFile)===digest(expectedAgents));
96
+ else need(canonical.status==='lesson_candidate'&&value.changed===null
97
+ &&['agents_changed','agents_unsafe','agents_too_large','agents_write_failed'].includes(value.reason));
98
+ const {writebackDigest,...body}=value;need(digest(body)===writebackDigest,'writeback_mismatch');
99
+ return freeze(value);
100
+ }
101
+
102
+ export function writeCmAiProjectLearning(raw,bootstrapAgentsSha256=null) {
103
+ const input=json(raw,256*1024);shape(input,['codeProject','learningInput','retrospective']);
104
+ text(input.codeProject);need(path.isAbsolute(input.codeProject)&&path.resolve(input.codeProject)===input.codeProject);
105
+ validTaskLearningInput(input.learningInput,input.learningInput.identity,input.learningInput.feature);
106
+ const retrospective=canonicalRetrospective(input.retrospective);
107
+ need(retrospective.feature===input.learningInput.feature
108
+ &&digest(retrospective.identity)===digest(input.learningInput.identity)
109
+ &&retrospective.learningDigest===input.learningInput.learningDigest,'identity_mismatch');
110
+ // Only the runner supplies a hash from its validated host bootstrap result.
111
+ // The Learning identity/digest still describes the original task-start read.
112
+ if(bootstrapAgentsSha256!==null){need(input.learningInput.feature==='0.bootstrap','bootstrap_task_required');hex(bootstrapAgentsSha256);}
113
+ const expected=bootstrapAgentsSha256===null
114
+ ?input.learningInput.learningFiles.find(file=>file.scope==='project'&&file.path==='AGENTS.md')??null
115
+ :{scope:'project',path:'AGENTS.md',sha256:bootstrapAgentsSha256};
116
+ if(retrospective.status==='no_new_lesson')return result(retrospective,'no_new_lesson',false,
117
+ input.learningInput.learningFiles.find(file=>file.scope==='project'&&file.path==='AGENTS.md')??null,null);
118
+ return writeLearningContent(input.codeProject,expected,retrospective,
119
+ (outcome,changed,agentsFile,reason)=>result(retrospective,outcome,changed,agentsFile,reason));
120
+ }
121
+
122
+ // Shared file operation only. Callers retain workflow identity, authorization,
123
+ // registration, evidence binding and completion ownership.
124
+ export function writeProjectLearningContent(raw){
125
+ const input=json(raw,64*1024);shape(input,['codeProject','expected','identity','feature','content']);
126
+ text(input.codeProject);need(path.isAbsolute(input.codeProject)&&path.resolve(input.codeProject)===input.codeProject);
127
+ validIdentity(input.identity);text(input.feature);
128
+ need(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(input.feature),'invalid_feature');
129
+ if(input.expected!==null){shape(input.expected,['scope','path','sha256']);
130
+ need(input.expected.scope==='project'&&input.expected.path==='AGENTS.md');hex(input.expected.sha256);}
131
+ const content=readLearningRetrospectiveContent(input.content);
132
+ return writeLearningContent(input.codeProject,input.expected,{...content,identity:input.identity,feature:input.feature},
133
+ (outcome,changed,agentsFile,reason)=>freeze({outcome,changed,agentsFile,reason}));
134
+ }
135
+
136
+ function writeLearningContent(codeProject,expected,retrospective,makeResult){
137
+ const input={codeProject};
138
+ const result=(_retrospective,...fields)=>makeResult(...fields);
139
+ if(retrospective.status==='no_new_lesson')return result(retrospective,'no_new_lesson',false,expected,null);
140
+ if(retrospective.status==='writeback_pending')return result(retrospective,'writeback_pending',null,expected,retrospective.reason);
141
+ let root,target,before;
142
+ try {
143
+ const rootStat=fs.lstatSync(input.codeProject);root=fs.realpathSync(input.codeProject);
144
+ need(rootStat.isDirectory()&&!rootStat.isSymbolicLink()&&root===input.codeProject,'agents_unsafe');
145
+ target=path.join(root,'AGENTS.md');before=readAgents(target);
146
+ need(before.exists===Boolean(expected)&&(!expected||before.sha256===expected.sha256),'agents_changed');
147
+ } catch(error) {
148
+ return result(retrospective,'writeback_pending',null,expected,error?.code==='agents_changed'?'agents_changed':'agents_unsafe');
149
+ }
150
+ const source=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(before.bytes),next=mergeLessons(source,retrospective);
151
+ if(next===source)return result(retrospective,'deduplicated',false,
152
+ before.exists?{scope:'project',path:'AGENTS.md',sha256:before.sha256}:null,null);
153
+ const bytes=Buffer.from(next);if(bytes.length>LIMIT)return result(retrospective,'writeback_pending',null,expected,'agents_too_large');
154
+ const temporary=path.join(root,`.AGENTS.md.cm-learning.${process.pid}.${randomUUID()}`);let descriptor,renamed=false;
155
+ try {
156
+ descriptor=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL
157
+ |(fs.constants.O_NOFOLLOW??0),before.mode);
158
+ fs.fchmodSync(descriptor,before.mode);fs.writeFileSync(descriptor,bytes);fs.fsyncSync(descriptor);
159
+ fs.closeSync(descriptor);descriptor=undefined;
160
+ need(sameSnapshot(before,readAgents(target)),'agents_changed');
161
+ fs.renameSync(temporary,target);renamed=true;
162
+ const directory=fs.openSync(root,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
163
+ try{fs.fsyncSync(directory);}finally{fs.closeSync(directory);}
164
+ const after=readAgents(target);need(after.bytes.equals(bytes),'agents_write_failed');
165
+ return result(retrospective,'written',true,{scope:'project',path:'AGENTS.md',sha256:after.sha256},null);
166
+ } catch(error) {
167
+ if(descriptor!==undefined)try{fs.closeSync(descriptor);}catch{}
168
+ if(!renamed)try{fs.unlinkSync(temporary);}catch{}
169
+ const reason=error?.code==='agents_changed'?'agents_changed':'agents_write_failed';
170
+ return result(retrospective,'writeback_pending',null,null,reason);
171
+ }
172
+ }
@@ -0,0 +1,320 @@
1
+ // Fixed N6 decision adapter for the JS CM log authority through its platform lock adapter.
2
+ import childProcess from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
7
+
8
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
9
+ const MiB=1024*1024;
10
+
11
+ const sameIdentity=(left,right)=>['repositoryId','runId','taskId','attempt'].every(key=>left[key]===right[key]);
12
+
13
+ export function readDecision(raw,identity,packageDigest) {
14
+ const decision=json(raw);shape(decision,['decisionId','identity','packageDigest','status','reason','score','at']);
15
+ id(decision.decisionId);validIdentity(decision.identity);hex(decision.packageDigest);
16
+ need(sameIdentity(decision.identity,identity)&&decision.packageDigest===packageDigest,'qa_decision_mismatch');
17
+ need(['triggered','skipped','blocked'].includes(decision.status));
18
+ text(decision.reason);need(decision.reason.length<=200&&!/[\n\r\0]/.test(decision.reason));
19
+ need(typeof decision.at==='string'
20
+ &&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$/.test(decision.at)
21
+ &&Number.isFinite(Date.parse(decision.at)));
22
+ if(decision.score!==null)need(Number.isInteger(decision.score)&&decision.score>=4&&decision.score<=20);
23
+ if(decision.status==='skipped')need(Number.isInteger(decision.score)&&decision.score<=7);
24
+ if(decision.status==='triggered'&&decision.score!==null)need(decision.score>=8);
25
+ return json({...decision,at:decision.at.endsWith('Z')?`${decision.at.slice(0,-1)}+00:00`:decision.at});
26
+ }
27
+
28
+ export function scanRows(log,visit) {
29
+ let descriptor;
30
+ try {
31
+ const stat=fs.lstatSync(log);need(stat.isFile()&&!stat.isSymbolicLink(),'qa_log_failed');
32
+ descriptor=fs.openSync(log,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
33
+ const chunk=Buffer.alloc(64*1024);let pending=Buffer.alloc(0);
34
+ const consume=line=>{if(line.length){need(line.length<=MiB,'qa_log_failed');
35
+ visit(json(JSON.parse(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(line)),MiB));}};
36
+ while(true){const size=fs.readSync(descriptor,chunk,0,chunk.length,null);if(size===0)break;
37
+ pending=Buffer.concat([pending,chunk.subarray(0,size)]);let newline;
38
+ while((newline=pending.indexOf(10))!==-1){consume(pending.subarray(0,newline));pending=pending.subarray(newline+1);}
39
+ need(pending.length<=MiB,'qa_log_failed');}
40
+ consume(pending);
41
+ } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
42
+ }
43
+
44
+ function existingDecision(specsDir,feature,identity,packageDigest,decision) {
45
+ const log=path.join(path.resolve(specsDir),'运行日志.jsonl');
46
+ if(!fs.existsSync(log))return false;
47
+ try {
48
+ const matches=[];scanRows(log,row=>{if(row?.schema_version===1&&row.workflow==='cm-ai'&&row.event==='qa'&&row.node==='N6'
49
+ &&row.repository_id===identity.repositoryId&&row.run_id===identity.runId&&row.feature===feature
50
+ &&row.task===identity.taskId&&row.attempt===identity.attempt&&row.package_digest===packageDigest)matches.push(row);});
51
+ if(matches.length===0)return false;
52
+ need(matches.length===1,'qa_decision_conflict');
53
+ const row=matches[0];
54
+ need(row.decision_id===decision.decisionId&&row.status===decision.status&&row.reason===decision.reason
55
+ &&row.score===decision.score&&row.at===decision.at,'qa_decision_conflict');
56
+ return true;
57
+ } catch(error) {
58
+ if(error?.code==='qa_decision_conflict')throw error;
59
+ need(false,'qa_log_failed');
60
+ }
61
+ }
62
+
63
+ function readResult(stdout,identity,specsDir) {
64
+ try {
65
+ const result=json(JSON.parse(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(stdout)),MiB);
66
+ shape(result,['event_id','run_id','project_log','global_log','global_written','pointer_written','deduplicated','degraded']);
67
+ id(result.event_id);need(result.run_id===identity.runId);text(result.project_log);text(result.global_log);
68
+ need(path.resolve(result.project_log)===path.join(path.resolve(specsDir),'运行日志.jsonl'));
69
+ need(typeof result.global_written==='boolean'&&(typeof result.pointer_written==='boolean'||result.pointer_written===null)
70
+ &&typeof result.deduplicated==='boolean'&&typeof result.degraded==='boolean');
71
+ return result;
72
+ } catch {need(false,'qa_log_failed');}
73
+ }
74
+
75
+ export function recordCmAiQaDecision(input) {
76
+ const keys=['specsDir','codeProject','feature','identity','packageDigest','decision'];
77
+ if(input&&Object.hasOwn(input,'logHome'))keys.push('logHome');
78
+ shape(input,keys);text(input.specsDir);text(input.codeProject);text(input.feature);validIdentity(input.identity);
79
+ hex(input.packageDigest);
80
+ const decision=readDecision(input.decision,input.identity,input.packageDigest);
81
+ if(existingDecision(input.specsDir,input.feature,input.identity,input.packageDigest,decision))return;
82
+ const detail=decision.status==='triggered'?`触发:${decision.reason}`:
83
+ decision.status==='skipped'?`跳过:评分${decision.score}`:`阻塞:${decision.reason}`;
84
+ const data={node:'N6',feature:input.feature,task:input.identity.taskId,attempt:input.identity.attempt,
85
+ repository_id:input.identity.repositoryId,package_digest:input.packageDigest,decision_id:decision.decisionId,
86
+ status:decision.status,reason:decision.reason,score:decision.score};
87
+ const args=[writer,'--workflow','cm-ai','--event','qa','--runtime','codex','--project-root',input.codeProject,
88
+ '--specs-dir',input.specsDir,'--run-id',input.identity.runId,'--at',decision.at,'--detail',detail,
89
+ '--data-json',JSON.stringify(data)];
90
+ const options={timeout:10000,maxBuffer:MiB,killSignal:'SIGKILL'};
91
+ if(Object.hasOwn(input,'logHome')){text(input.logHome);options.env={...process.env,CM_WORKFLOW_LOG_HOME:input.logHome};}
92
+ if(decision.status==='skipped'&&decision.reason==='merged_to_feature_qa'){
93
+ // N6 requires an explicit merge decision as well as the per-task QA row.
94
+ // Write first: a crash may repeat this same idempotent log operation, never QA.
95
+ const mergeArgs=[...args];mergeArgs[mergeArgs.indexOf('--event')+1]='decision';
96
+ mergeArgs[mergeArgs.indexOf('--detail')+1]='合并至feature级QA';
97
+ mergeArgs.push('--phase','qa_merge');
98
+ let merged;
99
+ try{merged=childProcess.spawnSync('python3',mergeArgs,options);}catch{need(false,'qa_log_failed');}
100
+ need(!merged.error&&merged.status===0&&merged.signal===null&&Buffer.isBuffer(merged.stdout),'qa_log_failed');
101
+ readResult(merged.stdout,input.identity,input.specsDir);
102
+ }
103
+ let result;
104
+ try{result=childProcess.spawnSync('python3',args,options);}
105
+ catch{need(false,'qa_log_failed');}
106
+ need(!result.error&&result.status===0&&result.signal===null&&Buffer.isBuffer(result.stdout)
107
+ &&result.stdout.length<=MiB,'qa_log_failed');
108
+ return readResult(result.stdout,input.identity,input.specsDir);
109
+ }
110
+
111
+ function findDecisionRow(input) {
112
+ shape(input,['specsDir','feature','identity','packageDigest']);
113
+ text(input.specsDir);text(input.feature);validIdentity(input.identity);hex(input.packageDigest);
114
+ const log=path.join(path.resolve(input.specsDir),'运行日志.jsonl');
115
+ if(!fs.existsSync(log))return null;
116
+ const matches=[];
117
+ try {scanRows(log,row=>{if(row?.schema_version===1&&row.workflow==='cm-ai'&&row.event==='qa'&&row.node==='N6'
118
+ &&row.repository_id===input.identity.repositoryId&&row.run_id===input.identity.runId
119
+ &&row.feature===input.feature&&row.task===input.identity.taskId&&row.attempt===input.identity.attempt
120
+ &&row.package_digest===input.packageDigest)matches.push(row);});}
121
+ catch{need(false,'context_not_ready');}
122
+ if(matches.length===0)return null;
123
+ need(matches.length===1,'context_not_ready');
124
+ const row=matches[0];id(row.decision_id);
125
+ need(['triggered','skipped','blocked'].includes(row.status),'context_not_ready');
126
+ return row;
127
+ }
128
+
129
+ export function findCmAiQaDecision(input) {
130
+ const row=findDecisionRow(input);if(row===null)return null;
131
+ return readDecision({status:row.status,decisionId:row.decision_id,identity:input.identity,
132
+ packageDigest:input.packageDigest,reason:row.reason,score:row.score,at:row.at},input.identity,input.packageDigest);
133
+ }
134
+
135
+ export function inspectCmAiQaDecision(input) {
136
+ const row=findDecisionRow(input);need(row,'context_not_ready');
137
+ return Object.freeze({status:row.status,decisionId:row.decision_id});
138
+ }
139
+
140
+ export function reportFile(specsDir,raw) {
141
+ text(raw);need(!raw.includes('\0'),'qa_report_invalid');
142
+ try {
143
+ const specs=fs.realpathSync(specsDir),reviews=path.join(specs,'.reviews'),reviewsStat=fs.lstatSync(reviews);
144
+ need(reviewsStat.isDirectory()&&!reviewsStat.isSymbolicLink(),'qa_report_invalid');
145
+ const candidate=path.isAbsolute(raw)?path.resolve(raw):path.resolve(specs,raw);
146
+ const lexical=path.relative(reviews,candidate);
147
+ need(lexical.length>0&&!lexical.startsWith(`..${path.sep}`)&&!path.isAbsolute(lexical),'qa_report_invalid');
148
+ const resolved=fs.realpathSync(candidate),relative=path.relative(fs.realpathSync(reviews),resolved),stat=fs.lstatSync(candidate);
149
+ need(relative.length>0&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative)
150
+ &&stat.isFile()&&!stat.isSymbolicLink(),'qa_report_invalid');
151
+ return resolved;
152
+ } catch(error) {
153
+ if(error?.code==='qa_report_invalid')throw error;
154
+ need(false,'qa_report_invalid');
155
+ }
156
+ }
157
+
158
+ // Discover the latest invocation from the authoritative log, never a second
159
+ // checkpoint. A started invocation without a valid result must not be resent.
160
+ export function latestCmAiQaRun(input) {
161
+ const decision=findCmAiQaDecision(input);need(decision?.status==='triggered','qa_not_triggered');
162
+ const rows=[];
163
+ try{scanRows(path.join(input.specsDir,'运行日志.jsonl'),row=>{
164
+ if(row?.schema_version===1&&row.workflow==='cm-ai'&&row.event==='test_run'
165
+ &&row.node==='N6'&&row.repository_id===input.identity.repositoryId&&row.run_id===input.identity.runId
166
+ &&row.feature===input.feature&&row.task===input.identity.taskId&&row.package_digest===input.packageDigest
167
+ &&row.qa_decision_id===decision.decisionId)rows.push(row);
168
+ });}catch{need(false,'qa_result_invalid');}
169
+ if(rows.length===0)return null;
170
+ const starts=rows.filter(row=>row.phase==='start');need(starts.length>0,'qa_result_invalid');
171
+ const testRunId=starts.at(-1).operation_id;id(testRunId);
172
+ return {testRunId,...inspectCmAiQaResult({...input,testRunId})};
173
+ }
174
+
175
+ export function recordCmAiQaRun(input) {
176
+ const keys=['specsDir','codeProject','feature','identity','packageDigest','testRunId','mode','caseCount','phase'];
177
+ if(Object.hasOwn(input,'result'))keys.push('result');
178
+ if(Object.hasOwn(input,'logHome'))keys.push('logHome');
179
+ if(Object.hasOwn(input,'qaRound'))keys.push('qaRound');
180
+ shape(input,keys);validIdentity(input.identity);id(input.testRunId);hex(input.packageDigest);
181
+ text(input.specsDir);text(input.codeProject);text(input.feature);
182
+ need(['commands','browser','all'].includes(input.mode));
183
+ need(Number.isSafeInteger(input.caseCount)&&input.caseCount>0);
184
+ need(['start','complete'].includes(input.phase));
185
+ const qaRound=input.qaRound??1;
186
+ need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=3,'qa_round_invalid');
187
+ const binding={specsDir:input.specsDir,feature:input.feature,identity:input.identity,packageDigest:input.packageDigest};
188
+ if(input.phase==='start'){
189
+ const previous=latestCmAiQaRun(binding);
190
+ scanRows(path.join(input.specsDir,'运行日志.jsonl'),row=>{
191
+ need(!(row.event==='test_run'&&row.operation_id===input.testRunId),'qa_round_invalid');
192
+ });
193
+ if(previous===null)need(qaRound===1,'qa_round_invalid');
194
+ else{
195
+ const failure=inspectCmAiQaFailure({...binding,testRunId:previous.testRunId});
196
+ need(qaRound===failure.qaRound+1&&input.testRunId!==previous.testRunId,'qa_round_invalid');
197
+ }
198
+ }else need(readCmAiQaRunRound({...binding,testRunId:input.testRunId})===qaRound,'qa_round_invalid');
199
+ const decision=findCmAiQaDecision({specsDir:input.specsDir,feature:input.feature,identity:input.identity,
200
+ packageDigest:input.packageDigest});need(decision?.status==='triggered','qa_not_triggered');
201
+ const data={node:'N6',repository_id:input.identity.repositoryId,feature:input.feature,task:input.identity.taskId,
202
+ package_digest:input.packageDigest,qa_decision_id:decision.decisionId,operation_id:input.testRunId,
203
+ attempt:qaRound,mode:input.mode,case_count:input.caseCount};
204
+ if(input.phase==='complete'){
205
+ const result=json(input.result);shape(result,['result','passed','failed','blocked','report']);
206
+ for(const key of ['passed','failed','blocked'])need(Number.isSafeInteger(result[key])&&result[key]>=0,'qa_result_invalid');
207
+ need(result.passed+result.failed+result.blocked===input.caseCount,'qa_result_invalid');
208
+ need((result.result==='PASS'&&result.passed===input.caseCount)
209
+ ||(result.result==='FAIL'&&result.failed>0)||(result.result==='BLOCKED'&&result.blocked>0),'qa_result_invalid');
210
+ reportFile(input.specsDir,result.report);Object.assign(data,result);
211
+ }else need(!Object.hasOwn(input,'result'));
212
+ const args=[writer,'--workflow','cm-ai','--event','test_run','--phase',input.phase,'--runtime','codex',
213
+ '--project-root',input.codeProject,'--specs-dir',input.specsDir,'--run-id',input.identity.runId,
214
+ '--detail',`QA ${input.phase}`,'--data-json',JSON.stringify(data)];
215
+ const options={timeout:10000,maxBuffer:MiB,killSignal:'SIGKILL'};
216
+ if(Object.hasOwn(input,'logHome')){text(input.logHome);options.env={...process.env,CM_WORKFLOW_LOG_HOME:input.logHome};}
217
+ const result=childProcess.spawnSync('python3',args,options);
218
+ need(!result.error&&result.status===0&&result.signal===null,'qa_log_failed');
219
+ return readResult(result.stdout,input.identity,input.specsDir);
220
+ }
221
+
222
+ // Read the registered round before executing cases or publishing their result.
223
+ // Task attempt remains bound by the QA decision; it is not the QA round.
224
+ export function readCmAiQaRunRound(input){
225
+ shape(input,['specsDir','feature','identity','packageDigest','testRunId']);
226
+ const {testRunId,...binding}=input;id(testRunId);
227
+ const decision=findCmAiQaDecision(binding);need(decision?.status==='triggered','qa_not_triggered');
228
+ const rows=[];
229
+ scanRows(path.join(input.specsDir,'运行日志.jsonl'),row=>{
230
+ if(row.workflow==='cm-ai'&&row.event==='test_run'&&row.run_id===input.identity.runId
231
+ &&row.node==='N6'&&row.repository_id===input.identity.repositoryId&&row.feature===input.feature
232
+ &&row.task===input.identity.taskId&&row.package_digest===input.packageDigest
233
+ &&row.qa_decision_id===decision.decisionId)rows.push(row);
234
+ });
235
+ const starts=rows.filter(row=>row.phase==='start');
236
+ need(starts.length>0&&starts.length<=3&&starts.every((row,index)=>row.attempt===index+1)
237
+ &&new Set(starts.map(row=>row.operation_id)).size===starts.length,'qa_round_invalid');
238
+ const start=starts.at(-1);
239
+ need(start.operation_id===testRunId&&!rows.some(row=>row.operation_id===testRunId&&row.phase==='complete'),'qa_round_invalid');
240
+ return start.attempt;
241
+ }
242
+
243
+ export function inspectCmAiQaResult(input) {
244
+ return inspectQaResult(input,false);
245
+ }
246
+
247
+ // Input to the separate cm-fix lifecycle, not permission to modify or rerun QA.
248
+ // Shares the exact latest-round validator; never lets callers select an old FAIL.
249
+ export function inspectCmAiQaFailure(input) {
250
+ return inspectQaResult(input,true);
251
+ }
252
+
253
+ // Historical evidence only. Never use this to select a new repair or QA action.
254
+ export function readCmAiQaFailureHistory(input) {
255
+ return inspectQaResult(input,true,true);
256
+ }
257
+
258
+ function inspectQaResult(input,failureSource,historical=false) {
259
+ shape(input,['specsDir','feature','identity','packageDigest','testRunId']);
260
+ text(input.specsDir);text(input.feature);validIdentity(input.identity);hex(input.packageDigest);id(input.testRunId);
261
+ const log=path.join(path.resolve(input.specsDir),'运行日志.jsonl');
262
+ need(fs.existsSync(log),'qa_result_incomplete');
263
+ const decisions=[],allRuns=[];let position=0;
264
+ try {scanRows(log,row=>{
265
+ const item={row,position:position++};
266
+ if(row?.schema_version===1&&row.workflow==='cm-ai'&&row.event==='qa'&&row.node==='N6'
267
+ &&row.repository_id===input.identity.repositoryId&&row.run_id===input.identity.runId
268
+ &&row.feature===input.feature&&row.task===input.identity.taskId&&row.attempt===input.identity.attempt
269
+ &&row.package_digest===input.packageDigest)decisions.push(item);
270
+ if(row?.schema_version===1&&row.workflow==='cm-ai'&&row.event==='test_run')allRuns.push(item);
271
+ });}catch{need(false,'qa_result_invalid');}
272
+ need(decisions.length===1&&decisions[0].row.status==='triggered','qa_not_triggered');
273
+ const decisionId=decisions[0].row.decision_id;id(decisionId);
274
+ const selected=allRuns.filter(item=>item.row.operation_id===input.testRunId);
275
+ need(selected.length>0,'qa_result_incomplete');
276
+ const bound=row=>row.node==='N6'&&row.repository_id===input.identity.repositoryId
277
+ &&row.run_id===input.identity.runId&&row.feature===input.feature&&row.task===input.identity.taskId
278
+ &&row.package_digest===input.packageDigest
279
+ &&row.qa_decision_id===decisionId;
280
+ for(const {row} of selected)need(bound(row),'qa_result_mismatch');
281
+ const candidates=allRuns.filter(item=>item.position>decisions[0].position&&bound(item.row));
282
+ need(candidates.length>0,'qa_result_invalid');
283
+ for(const {row} of candidates)need(typeof row.operation_id==='string'
284
+ &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(row.operation_id)
285
+ &&Number.isSafeInteger(row.attempt)&&row.attempt>=1&&row.attempt<=3,'qa_result_invalid');
286
+ const latestStarts=candidates.filter(item=>item.row.phase==='start');
287
+ need(latestStarts.length>0,'qa_result_incomplete');
288
+ need(latestStarts.every((item,index)=>item.row.attempt===index+1),'qa_result_invalid');
289
+ const latestStart=latestStarts.at(-1);
290
+ if(!historical)need(latestStart.row.operation_id===input.testRunId,'qa_result_stale');
291
+ const runs=candidates.filter(item=>item.row.operation_id===input.testRunId);
292
+ need(runs.length>0,'qa_result_invalid');
293
+ const starts=runs.filter(item=>item.row.phase==='start'),completes=runs.filter(item=>item.row.phase==='complete');
294
+ need(starts.length===1&&completes.length===1,'qa_result_incomplete');
295
+ need(decisions[0].position<starts[0].position&&starts[0].position<completes[0].position,'qa_result_invalid');
296
+ const start=starts[0].row,complete=completes[0].row;
297
+ text(start.mode);text(complete.mode);need(start.mode===complete.mode&&start.attempt===complete.attempt,'qa_result_invalid');
298
+ for(const key of ['case_count','passed','failed','blocked'])
299
+ need(Number.isSafeInteger(complete[key])&&complete[key]>=0,'qa_result_invalid');
300
+ need(Number.isSafeInteger(start.case_count)&&start.case_count>0&&start.case_count===complete.case_count
301
+ &&complete.passed+complete.failed+complete.blocked===complete.case_count,'qa_result_invalid');
302
+ text(complete.result);const result=complete.result.toUpperCase();
303
+ let status;
304
+ if(['PASS','PASSED'].includes(result)){
305
+ need(complete.passed===complete.case_count&&complete.failed===0&&complete.blocked===0
306
+ &&!runs.some(item=>item.row.phase==='case_blocked'),'qa_result_invalid');status='passed';
307
+ }else if(['FAIL','FAILED'].includes(result)){
308
+ need(complete.failed>0,'qa_result_invalid');status='failed';
309
+ }else if(['BLOCKED','NEEDS_MANUAL'].includes(result)){
310
+ need(complete.blocked>0,'qa_result_invalid');status='blocked';
311
+ }else need(false,'qa_result_invalid');
312
+ const report=reportFile(input.specsDir,complete.report);
313
+ if(failureSource){
314
+ need(status==='failed','qa_failure_required');
315
+ return json({identity:input.identity,packageDigest:input.packageDigest,testRunId:input.testRunId,
316
+ qaDecisionId:decisionId,qaRound:start.attempt,report,
317
+ counts:{total:complete.case_count,passed:complete.passed,failed:complete.failed,blocked:complete.blocked}});
318
+ }
319
+ return Object.freeze({status});
320
+ }