@aibyzero/cm-workflow 0.17.1 → 0.19.0

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 (357) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +23 -0
  3. package/CHANGELOG.md +242 -0
  4. package/README.md +20 -3
  5. package/THIRD_PARTY_NOTICES.md +13 -0
  6. package/VERSION +1 -1
  7. package/compat/claude-commands/cm-challenge.md +3 -0
  8. package/docs/architecture.md +11 -0
  9. package/docs/cm-control-policy-v2.md +127 -9
  10. package/docs/installation.md +310 -4
  11. package/docs/js-workflow-control.md +150 -15
  12. package/docs/live-evidence-drivers.md +28 -4
  13. package/docs/out-of-scope/README.md +25 -0
  14. package/docs/out-of-scope/background-supervisor.md +32 -0
  15. package/docs/reviewed-integration.md +48 -0
  16. package/docs/user-guide.md +50 -21
  17. package/install-codex.sh +331 -18
  18. package/install.ps1 +28 -2
  19. package/install.sh +321 -17
  20. package/package.json +2 -1
  21. package/runtime/js/autonomy.mjs +152 -0
  22. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  23. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  24. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  25. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  26. package/runtime/js/cm-ai/claude-review-stream.mjs +83 -14
  27. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  28. package/runtime/js/cm-ai/cm-ai-admission.mjs +56 -17
  29. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  30. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  31. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  32. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  33. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  34. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  35. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  36. package/runtime/js/cm-ai/control-policy.mjs +21 -4
  37. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  38. package/runtime/js/cm-ai/drive-core.mjs +115 -11
  39. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  40. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  41. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  42. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  43. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  44. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  45. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  46. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  47. package/runtime/js/cm-ai/host-check.mjs +11 -5
  48. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  49. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  50. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  51. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  52. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  53. package/runtime/js/cm-ai/host-session.mjs +1 -1
  54. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  55. package/runtime/js/cm-ai/host.mjs +1 -1
  56. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  57. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  58. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  59. package/runtime/js/cm-ai/operator-guidance.mjs +9 -2
  60. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  61. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  62. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  63. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  64. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  65. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  66. package/runtime/js/cm-ai/review-package.mjs +79 -7
  67. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  68. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  69. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  70. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  71. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  72. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  73. package/runtime/js/cm-ai/task-runner.mjs +242 -39
  74. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  75. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  76. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  77. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  78. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  79. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  80. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  81. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  82. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  83. package/runtime/js/cm-fix/dossier.mjs +8 -2
  84. package/runtime/js/cm-fix/execution.mjs +578 -100
  85. package/runtime/js/cm-fix/final-review.mjs +39 -8
  86. package/runtime/js/cm-fix/finish.mjs +15 -11
  87. package/runtime/js/cm-fix/host-review.mjs +65 -10
  88. package/runtime/js/cm-fix/host.mjs +35 -12
  89. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  90. package/runtime/js/cm-fix/metrics.mjs +18 -5
  91. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  92. package/runtime/js/cm-fix/regression.mjs +16 -7
  93. package/runtime/js/cm-fix/repair.mjs +29 -8
  94. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  95. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  96. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  97. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  98. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  99. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  100. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  101. package/runtime/js/cm-fix/start.mjs +6 -3
  102. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  103. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  104. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  105. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  106. package/runtime/js/cm-prd/analysis.mjs +13 -9
  107. package/runtime/js/cm-prd/change.mjs +37 -16
  108. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  109. package/runtime/js/cm-prd/draft.mjs +31 -3
  110. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  111. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  112. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  113. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  114. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  115. package/runtime/js/cm-prd/self-check.mjs +125 -6
  116. package/runtime/js/cm-prd/session.mjs +30 -1
  117. package/runtime/js/cm-prd/summary.mjs +11 -5
  118. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  119. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  120. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  121. package/runtime/js/cm-security/scan.mjs +1 -1
  122. package/runtime/js/commander/decision.mjs +44 -0
  123. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  124. package/runtime/js/commander/ledger.mjs +265 -0
  125. package/runtime/js/commander/preflight.mjs +107 -0
  126. package/runtime/js/notify-later.mjs +13 -0
  127. package/runtime/js/notify-send.mjs +6 -2
  128. package/runtime/js/notify.mjs +581 -65
  129. package/runtime/js/review-findings.mjs +38 -0
  130. package/runtime/js/session-boundary.mjs +56 -0
  131. package/runtime/js/session-handoff.mjs +68 -0
  132. package/runtime/js/spec-task-line.mjs +27 -13
  133. package/runtime/js/specs-status.mjs +5 -4
  134. package/runtime/js/task-scope.mjs +197 -0
  135. package/runtime/logging.md +6 -1
  136. package/runtime/model-efficiency.md +69 -10
  137. package/runtime/orchestration.md +3 -1
  138. package/runtime/project-learning.md +2 -0
  139. package/runtime/review.md +3 -2
  140. package/runtime/test-contract.md +1 -0
  141. package/scripts/ci-test-weights.json +3 -0
  142. package/scripts/cm-ai-admission.mjs +21 -7
  143. package/scripts/cm-ai-admission.test.mjs +171 -3
  144. package/scripts/cm-ai-batch-drive.mjs +79 -18
  145. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  146. package/scripts/cm-ai-batch-host.mjs +38 -9
  147. package/scripts/cm-ai-batch-host.test.mjs +6 -5
  148. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  149. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  150. package/scripts/cm-ai-batch-plan.mjs +52 -0
  151. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  152. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  153. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  154. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  155. package/scripts/cm-ai-batch-run.mjs +471 -57
  156. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  157. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  158. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  159. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  160. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  161. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  162. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  163. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  164. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  165. package/scripts/cm-ai-control-policy.test.mjs +14 -0
  166. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  167. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  168. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  169. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  170. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  171. package/scripts/cm-ai-drive.mjs +73 -17
  172. package/scripts/cm-ai-drive.test.mjs +34 -2
  173. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  174. package/scripts/cm-ai-host.mjs +60 -19
  175. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  176. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  177. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  178. package/scripts/cm-ai-integration-preview.mjs +41 -0
  179. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  180. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  181. package/scripts/cm-ai-operator-guidance.test.mjs +16 -1
  182. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  183. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  184. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  185. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  186. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  187. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  188. package/scripts/cm-ai-run.mjs +88 -21
  189. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  190. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  191. package/scripts/cm-ai-supersede.test.mjs +28 -0
  192. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  193. package/scripts/cm-announce-hook.mjs +35 -8
  194. package/scripts/cm-announce-hook.test.mjs +25 -0
  195. package/scripts/cm-autonomy.mjs +94 -0
  196. package/scripts/cm-autonomy.test.mjs +162 -0
  197. package/scripts/cm-challenge.test.mjs +61 -0
  198. package/scripts/cm-check-drive-files.mjs +1 -1
  199. package/scripts/cm-check-runtime.sh +60 -1
  200. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  201. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  202. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  203. package/scripts/cm-claude-review-stream.test.mjs +13 -0
  204. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  205. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  206. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  207. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  208. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  209. package/scripts/cm-commander-ledger.test.mjs +260 -0
  210. package/scripts/cm-commander-p2.test.mjs +295 -0
  211. package/scripts/cm-commander-preflight.mjs +84 -0
  212. package/scripts/cm-commander.mjs +116 -0
  213. package/scripts/cm-config-lock.mjs +35 -0
  214. package/scripts/cm-controlled-correction.test.mjs +10 -1
  215. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  216. package/scripts/cm-display-task-id.test.mjs +41 -0
  217. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  218. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  219. package/scripts/cm-external-batch-host.test.mjs +4 -3
  220. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  221. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  222. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  223. package/scripts/cm-failover.mjs +48 -10
  224. package/scripts/cm-failover.test.mjs +46 -0
  225. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  226. package/scripts/cm-fix-command-correction.mjs +17 -0
  227. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  228. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  229. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  230. package/scripts/cm-fix-drive.mjs +33 -5
  231. package/scripts/cm-fix-drive.test.mjs +49 -0
  232. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  233. package/scripts/cm-fix-host-review.test.mjs +21 -9
  234. package/scripts/cm-fix-host.mjs +26 -8
  235. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  236. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  237. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  238. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  239. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  240. package/scripts/cm-fix-review-preflight.mjs +24 -0
  241. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  242. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  243. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  244. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  245. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  246. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  247. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  248. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  249. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  250. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  251. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  252. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  253. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  254. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  255. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  256. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  257. package/scripts/cm-host-replay.test.mjs +176 -0
  258. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  259. package/scripts/cm-install-manifest.sh +351 -0
  260. package/scripts/cm-live-evidence.test.mjs +59 -1
  261. package/scripts/cm-log-event.mjs +61 -10
  262. package/scripts/cm-log-event.test.mjs +121 -1
  263. package/scripts/cm-matt-skills.mjs +576 -0
  264. package/scripts/cm-matt-skills.test.mjs +550 -0
  265. package/scripts/cm-notify-command.test.mjs +42 -10
  266. package/scripts/cm-notify.mjs +14 -10
  267. package/scripts/cm-notify.test.mjs +581 -59
  268. package/scripts/cm-patrol.mjs +4 -1
  269. package/scripts/cm-patrol.test.mjs +23 -5
  270. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  271. package/scripts/cm-prd-completion.test.mjs +56 -13
  272. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  273. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  274. package/scripts/cm-prd-draft.test.mjs +1 -1
  275. package/scripts/cm-prd-drive.mjs +13 -6
  276. package/scripts/cm-prd-drive.test.mjs +45 -1
  277. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  278. package/scripts/cm-prd-host.mjs +10 -5
  279. package/scripts/cm-prd-host.test.mjs +4 -2
  280. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  281. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  282. package/scripts/cm-prd-revision.test.mjs +1 -1
  283. package/scripts/cm-prd-self-check-revision.test.mjs +1 -1
  284. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  285. package/scripts/cm-prd-self-check.test.mjs +105 -5
  286. package/scripts/cm-prd-summary.test.mjs +24 -3
  287. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  288. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  289. package/scripts/cm-refactor-drive.mjs +2 -1
  290. package/scripts/cm-refactor-drive.test.mjs +9 -0
  291. package/scripts/cm-release-smoke.sh +1 -1
  292. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  293. package/scripts/cm-skill-hints-exam.mjs +149 -0
  294. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  295. package/scripts/cm-skill-hints.exam.json +706 -0
  296. package/scripts/cm-skill-hints.json +119 -0
  297. package/scripts/cm-skill-hints.mjs +669 -0
  298. package/scripts/cm-skill-hints.test.mjs +831 -0
  299. package/scripts/cm-skill-judge.mjs +181 -0
  300. package/scripts/cm-skill-judge.test.mjs +255 -0
  301. package/scripts/cm-specs-status.test.mjs +4 -2
  302. package/scripts/cm-start-check.mjs +323 -0
  303. package/scripts/cm-start-check.test.mjs +406 -0
  304. package/scripts/cm-task-gate.mjs +150 -29
  305. package/scripts/cm-task-gate.test.mjs +73 -1
  306. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  307. package/scripts/cm-task-scope.test.mjs +308 -0
  308. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  309. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  310. package/scripts/cm-workflow-config.mjs +12 -2
  311. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  312. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  313. package/scripts/scan-public-safety.py +1 -0
  314. package/scripts/session-boundary.test.mjs +170 -0
  315. package/scripts/test-npm-install.py +14 -3
  316. package/scripts/test-shell-compat.sh +2 -0
  317. package/scripts/validate-public-repo.py +4 -0
  318. package/scripts/validate-test-cases.mjs +3 -2
  319. package/skills/cm-ai/SKILL.md +5 -2
  320. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  321. package/skills/cm-ai/references/N4-review.md +2 -1
  322. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  323. package/skills/cm-ai/references/N8-finish.md +22 -0
  324. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  325. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  326. package/skills/cm-ai/references/js-host.md +82 -16
  327. package/skills/cm-challenge/SKILL.md +65 -0
  328. package/skills/cm-challenge/evals/README.md +18 -0
  329. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  330. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  331. package/skills/cm-challenge/references/examples.md +15 -0
  332. package/skills/cm-check/SKILL.md +5 -0
  333. package/skills/cm-check/references/js-host.md +2 -0
  334. package/skills/cm-fix/SKILL.md +12 -3
  335. package/skills/cm-fix/references/command-correction.md +67 -0
  336. package/skills/cm-fix/references/isolated-review.md +54 -0
  337. package/skills/cm-fix/references/js-host.md +62 -2
  338. package/skills/cm-fix/references/test-type-correction.md +72 -0
  339. package/skills/cm-fix/references/verification-recovery.md +114 -0
  340. package/skills/cm-idea/SKILL.md +2 -0
  341. package/skills/cm-idea/references/js-host.md +2 -0
  342. package/skills/cm-notify/SKILL.md +2 -0
  343. package/skills/cm-prd/SKILL.md +14 -9
  344. package/skills/cm-prd/references/brownfield.md +8 -1
  345. package/skills/cm-prd/references/change-mode.md +8 -1
  346. package/skills/cm-prd/references/greenfield.md +4 -0
  347. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  348. package/skills/cm-prd/references/js-host.md +4 -2
  349. package/skills/cm-prd/references/spec-self-check.md +5 -1
  350. package/skills/cm-refactor/SKILL.md +8 -0
  351. package/skills/cm-refactor/references/js-host.md +2 -0
  352. package/skills/cm-test/SKILL.md +4 -0
  353. package/templates/dashboard/dashboard.html +2 -2
  354. package/templates/pixel/cm-pixel.html +1 -1
  355. package/templates/pixel/cm-pixel.sh +1 -1
  356. package/templates/pixel/dev/template.html +1 -1
  357. package/templates/statusline/cm-statusline.sh +1 -1
@@ -0,0 +1,62 @@
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 {buildManifest} from './cm-spec-manifest.mjs';
7
+ import {openControlRun} from './cm-ai-run.mjs';
8
+ import {createDeveloperRun} from '../runtime/js/cm-ai/developer-adapter.mjs';
9
+ import {terminalFor,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
10
+
11
+ // A developer call that ends without a result keeps the worker's own code in the
12
+ // run archive (timeout, missing_init...); before, only "unknown" survived.
13
+ async function fixture(response,fn){
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-failure-code-')));
15
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.work';
16
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
17
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
18
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
19
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
20
+ fs.writeFileSync(path.join(codeProject,'a.js'),'base\n');
21
+ const identity={repositoryId:'failure-code-fixture',runId:'failure-code-run',taskId:'T-001',attempt:1};
22
+ const definition={version:1,specsDir,codeProject,feature,identity,scope:['a.js'],requirements:[]};
23
+ const adapter=createDeveloperRun({provider:'claude',requestedModel:'fixture',worker:async()=>response()});
24
+ const execution={configuration:{kind:'failure-code-fixture-v1'},timeoutMs:3000,excludedContexts:['host'],applicableAgentFiles:[],qaLogHome:path.join(root,'logs'),
25
+ developer:{provider:'claude',requestedModel:'fixture',contextId:'author',run:(r,c)=>adapter(r,c)},
26
+ check:()=>assert.fail('no checks after a failed develop'),
27
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
28
+ allowed:true,available:true,contexts:['review-1','review-2'],run:()=>assert.fail('no review')}],
29
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['host']}};
30
+ const statePath=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
31
+ let run;
32
+ try{
33
+ run=await openControlRun(definition,'create',execution);
34
+ const status=await run.host.handle({version:1,operation:'start',requestId:'start',identity});
35
+ await fn({status,call:JSON.parse(fs.readFileSync(statePath,'utf8')).records.at(-1).payload.checkpoint.calls.at(-1)});
36
+ }finally{run?.close();fs.rmSync(root,{recursive:true,force:true});}
37
+ }
38
+
39
+ test('an unknown or failed developer call keeps the worker code in the archive',async()=>{
40
+ for(const [response,terminal] of [[{status:'unknown',code:'missing_init'},'unknown'],[{status:'failed',code:'provider_failed'},'failed']]){
41
+ await fixture(()=>response,async({call})=>{
42
+ assert.equal(call.terminal,terminal);assert.equal(call.failureCode,response.code);
43
+ });
44
+ }
45
+ // A thrown worker error keeps its code too; a code that is not a plain identifier is dropped, never stored.
46
+ await fixture(()=>{throw Object.assign(new Error('x'),{code:'timeout'});},async({call})=>{
47
+ assert.equal(call.terminal,'unknown');assert.equal(call.failureCode,'timeout');});
48
+ await fixture(()=>({status:'unknown',code:'Bad Code!'}),async({call})=>{
49
+ assert.equal(call.terminal,'unknown');assert.equal(Object.hasOwn(call,'failureCode'),false);});
50
+ });
51
+
52
+ test('failureCode is only valid on a developer failed/unknown terminal without a result',()=>{
53
+ const request=role=>requestFor({invocationId:'s.1',identity:{repositoryId:'r',runId:'u',taskId:'T-001',attempt:1},
54
+ role,provider:'claude',requestedModel:'fixture',contextId:'author',payload:{}});
55
+ const base={version:1,invocationId:'s.1',contextId:'author',provider:'claude',effectiveModel:'unknown',accepted:true,result:null};
56
+ assert.equal(terminalFor({...base,status:'unknown',failureCode:'missing_init'},request('developer')).failureCode,'missing_init');
57
+ for(const [value,role] of [[{...base,status:'unknown',failureCode:'missing_init'},'reviewer'],
58
+ [{...base,status:'succeeded',result:{outcome:'implemented'},failureCode:'x'},'developer'],
59
+ [{...base,status:'failed',blockedReason:'why',failureCode:'x'},'developer'],
60
+ [{...base,status:'unknown',failureCode:'Bad'},'developer']])
61
+ assert.throws(()=>terminalFor(value,request(role)));
62
+ });
@@ -0,0 +1,41 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {readFileSync} from 'node:fs';
4
+ import {execFileSync} from 'node:child_process';
5
+ import {matchTaskDeclaration} from '../runtime/js/spec-task-line.mjs';
6
+
7
+ const root=new URL('../',import.meta.url);
8
+ const read=path=>readFileSync(new URL(path,root),'utf8');
9
+ const md=['- [x] T-001: done','- [ ] T-004a: suffix','- [ ] T-FIX-api:named','- [ ] T-002/a: malformed','- [ ] T-005 plain'].join('\n')+'\n';
10
+ const expected=['T-001','T-004a','T-FIX-api','T-005'];
11
+
12
+ test('display regexes accept the same task IDs as the core parser', ()=>{
13
+ const core=md.split('\n').map(line=>matchTaskDeclaration(line)?.id).filter(Boolean);
14
+ assert.deepEqual(core,expected);
15
+ });
16
+
17
+ for(const path of ['templates/pixel/cm-pixel.html','templates/pixel/dev/template.html']){
18
+ test(`${path} counts suffixed and named task IDs`, ()=>{
19
+ const source=read(path).match(/md\.match\(\/(.+?)\/gm\)/)[1];
20
+ assert.equal(md.match(new RegExp(source,'gm')).length,expected.length);
21
+ });
22
+ }
23
+
24
+ test('dashboard parseTasks keeps full task IDs', ()=>{
25
+ const source=read('templates/dashboard/dashboard.html').match(/md\.matchAll\(\/(.+?)\/gm\)/)[1];
26
+ assert.deepEqual([...md.matchAll(new RegExp(source,'gm'))].map(m=>m[2]),expected);
27
+ });
28
+
29
+ for(const path of ['templates/statusline/cm-statusline.sh','templates/pixel/cm-pixel.sh']){
30
+ test(`${path} counts suffixed and named task IDs`, ()=>{
31
+ const pattern=read(path).match(/re\.findall\(r"(.+?)", md, re\.M\)/)[1];
32
+ const out=execFileSync('python3',['-c','import re,sys,json;print(json.dumps([t for _,t in re.findall(sys.argv[1],sys.argv[2],re.M)]))',pattern,md]).toString();
33
+ assert.deepEqual(JSON.parse(out),expected);
34
+ });
35
+ }
36
+
37
+ test('dashboard metrics table keeps full task IDs', ()=>{
38
+ const source=read('templates/dashboard/dashboard.html').match(/met\.matchAll\(\/(.+?)\/gm\)/)[1];
39
+ const met=['| T-001 | a |','| T-004a | b |','| T-FIX-api | c |','| T-002/a | d |'].join('\n')+'\n';
40
+ assert.deepEqual([...met.matchAll(new RegExp(source,'gm'))].map(m=>m[1]),['T-001','T-004a','T-FIX-api']);
41
+ });
@@ -0,0 +1,218 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {createHash} from 'node:crypto';
4
+ import {compactReviewData,expandReviewData} from '../runtime/js/cm-ai/review-presentation.mjs';
5
+ import {compactReviewDataV2,expandReviewDataV2} from '../runtime/js/cm-ai/review-presentation-delta.mjs';
6
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
7
+ import {buildReviewPrompt} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
8
+ import {EXECUTION_POLICY_V1,EXECUTION_POLICY_V2,readExecutionPolicy,readLaunchExecutionPolicy,readFixExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
9
+
10
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
11
+ const byteSize=value=>Buffer.byteLength(JSON.stringify(value));
12
+ const clone=value=>structuredClone(value);
13
+ const file=(path,bytes)=>({path,type:'file',mode:420,size:bytes.length,sha256:sha(bytes),contentBase64:bytes.toString('base64')});
14
+ const change=(path,before,after)=>({path,before:before===null?null:file(path,before),after:after===null?null:file(path,after)});
15
+ const lines=count=>Array.from({length:count},(_,i)=>'line '+String(i).padStart(5,'0')+' carries complete unchanged review evidence.\n');
16
+ function pair(){
17
+ const before=lines(240),after=[...before];
18
+ after[7]='First explicit change with 中文 and 😀.\n';
19
+ after[85]='Second separated change preserves all other code.\n';
20
+ after[179]='Third separated change is complete evidence.\n';
21
+ return [Buffer.from(before.join('')),Buffer.from(after.join(''))];
22
+ }
23
+ const dataFor=changes=>({reviewPackage:{packageDigest:'a'.repeat(64),changes,
24
+ specification:{acceptanceCriteria:['AC-001'],interfaceContracts:['GET /fixture'],systemContext:'Complete context'},
25
+ checks:[{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'Synthetic evidence'}]},
26
+ priorReview:{verdict:'changes_requested',findings:[{path:'source.mjs',message:'Original finding'}]},examinedPaths:changes.map(item=>item.path)});
27
+ function reviewRequest(provider='claude',{binary=false}={}){
28
+ let [before,after]=pair();
29
+ if(binary){before=Buffer.from(Array.from({length:16384},(_,i)=>i%256));after=Buffer.from(before);after[8192]=255;}
30
+ const changes=[change('source.mjs',before,after)];
31
+ const requirements=[file('requirements.md',Buffer.from('AC-001: preserve exact evidence.\n'))];
32
+ const checks=[{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'Synthetic evidence'}];
33
+ const identity={repositoryId:'fixture',runId:'presentation-delta',taskId:'T-001',attempt:1};
34
+ const pkg={version:1,kind:'cm-review-package',identity,rootDigest:'b'.repeat(64),baseIdentity:'c'.repeat(64),
35
+ scope:['source.mjs'],changes,requirements,checks,artifactDigest:digest(changes),
36
+ requirementsDigest:digest(requirements),checksDigest:digest(checks)};
37
+ pkg.packageDigest=digest(pkg);
38
+ const request={version:1,invocationId:'review-delta',identity,role:'reviewer',provider,
39
+ requestedModel:'fixture-model',contextId:'fresh-review',payload:{reviewPackage:pkg,priorReview:null}};
40
+ request.requestDigest=digest(request);return request;
41
+ }
42
+ const deltaEntry=presented=>Object.values(presented.contents).find(item=>item.encoding==='delta-v2');
43
+ const bad=value=>assert.throws(()=>expandReviewDataV2(value),error=>['invalid_input','limit_exceeded','review_presentation_delta_invalid'].includes(error.code));
44
+ const mutate=(presented,edit)=>{const copy=clone(presented);edit(copy);bad(copy);};
45
+ const splitPrompt=prompt=>JSON.parse(prompt.split('\n<cm-review-data-json>\n')[1]);
46
+
47
+ test('V2 reconstructs exact Unicode, CRLF, BOM, binary, empty and partial-byte boundary evidence',()=>{
48
+ const prefix=Buffer.from('complete unchanged evidence\r\n'.repeat(80));
49
+ const cases=[
50
+ [Buffer.concat([prefix,Buffer.from('😀尾')]),Buffer.concat([prefix,Buffer.from('😁尾')])],
51
+ [Buffer.concat([Buffer.from([0xef,0xbb,0xbf]),prefix,Buffer.from('old')]),Buffer.concat([Buffer.from([0xef,0xbb,0xbf]),prefix,Buffer.from('new')])],
52
+ [Buffer.concat([prefix,Buffer.from([255,128,0,17])]),Buffer.concat([prefix,Buffer.from([255,129,0,17])])],
53
+ [Buffer.from('old'),Buffer.alloc(0)],[Buffer.alloc(0),Buffer.from('new')],
54
+ [prefix,Buffer.concat([prefix,Buffer.from('tail without LF')])],
55
+ [prefix,Buffer.concat([Buffer.from('head without LF'),prefix])]
56
+ ];
57
+ const original=dataFor(cases.map(([before,after],i)=>change('file-'+i,before,after)));
58
+ original.reviewPackage.handoff=file('handoff.json',Buffer.from('{"complete":"所有材料"}\n'));
59
+ const bytes=JSON.stringify(original),presented=compactReviewDataV2(original);
60
+ assert.deepEqual(expandReviewDataV2(presented),original);assert.equal(JSON.stringify(original),bytes);
61
+ assert.equal(presented.presentation.logicalDigest,digest(original));
62
+ assert.equal(presented.presentation.logicalBytes,Buffer.byteLength(bytes));
63
+ assert.deepEqual(compactReviewDataV2(original),presented);
64
+ assert(Object.values(presented.contents).some(item=>item.encoding==='base64'));
65
+ assert(Object.values(presented.contents).some(item=>item.parts?.some(part=>part.insert?.encoding==='base64')));
66
+ });
67
+
68
+ test('multiple separated edits retain the whole source and materially shrink the inline representation',()=>{
69
+ const [before,after]=pair(),original=dataFor([change('source.mjs',before,after)]);
70
+ const v1=compactReviewData(original),v2=compactReviewDataV2(original),entry=deltaEntry(v2);
71
+ assert(entry.parts.length>3);assert(byteSize(v2)<byteSize(v1)*0.65);
72
+ assert.deepEqual(expandReviewDataV2(v2),original);
73
+ assert.deepEqual(expandReviewData(v1),original);
74
+ assert.deepEqual(v2.contents[entry.baseRef],v1.contents[entry.baseRef]);
75
+ assert.equal(entry.sha256,sha(after));assert.equal(entry.size,after.length);
76
+ });
77
+
78
+ test('only a prior full before entry for the same path can be a base and delta chains are never emitted',()=>{
79
+ const [before,after]=pair(),next=Buffer.concat([after,Buffer.from('third revision\n')]);
80
+ const original=dataFor([change('a',before,after),change('b',after,next),
81
+ change('deleted',before,null),change('new',null,Buffer.concat([before,Buffer.from('added\n')]))]);
82
+ const presented=compactReviewDataV2(original);
83
+ assert.equal(Object.values(presented.contents).filter(item=>item.encoding==='delta-v2').length,1);
84
+ for(const entry of Object.values(presented.contents))if(entry.encoding==='delta-v2')assert.notEqual(presented.contents[entry.baseRef].encoding,'delta-v2');
85
+ assert.deepEqual(expandReviewDataV2(presented),original);
86
+ const reversed=dataFor([{path:'reverse',after:file('reverse',after),before:file('reverse',before)}]);
87
+ assert.equal(Object.values(compactReviewDataV2(reversed).contents).some(item=>item.encoding==='delta-v2'),false);
88
+ });
89
+
90
+ test('V2 rejects changed metadata, malformed full content, dangling references and hidden unused evidence',()=>{
91
+ const presented=compactReviewDataV2(dataFor([change('source.mjs',...pair())]));
92
+ for(const edit of [
93
+ v=>v.presentation.version=1,v=>v.presentation.kind='other',v=>v.presentation.packageDigest='b'.repeat(64),
94
+ v=>v.presentation.logicalDigest='b'.repeat(64),v=>v.presentation.logicalBytes++,
95
+ v=>v.presentation.extra=true,v=>v.contents['content-1']=null,
96
+ v=>v.contents['content-1'].content+='changed',v=>v.contents['content-1'].encoding='unknown',
97
+ v=>v.contents['content-1'].content='\ud800',v=>v.contents['content-1'].size++,
98
+ v=>v.contents['content-1'].sha256='b'.repeat(64),
99
+ v=>v.reviewPackage.changes[0].before.contentRef='missing',
100
+ v=>v.reviewPackage.changes[0].before.contentBase64='',
101
+ v=>v.reviewPackage.changes[0].before.size++,
102
+ v=>v.reviewPackage.changes[0].after.sha256='b'.repeat(64),
103
+ v=>v.contents['content-3']=clone(v.contents['content-1'])
104
+ ])mutate(presented,edit);
105
+ mutate(presented,v=>{const entry=v.contents['content-1'];entry.content=Buffer.from(entry.content).toString('base64')+'!';entry.encoding='base64';});
106
+ });
107
+
108
+ test('V2 rejects forward, self, chained and cross-path base references even with a valid logical digest',()=>{
109
+ const [before,after]=pair(),original=dataFor([change('source.mjs',before,after),change('other',after,Buffer.concat([after,Buffer.from('next\n')]))]);
110
+ const presented=compactReviewDataV2(original);
111
+ for(const baseRef of ['missing','content-2','content-3','__proto__'])mutate(presented,v=>deltaEntry(v).baseRef=baseRef);
112
+ mutate(presented,v=>v.reviewPackage.changes[0].before.path='different-path');
113
+ mutate(presented,v=>{const entry=v.contents['content-3'];v.contents['content-3']={sha256:entry.sha256,size:entry.size,
114
+ encoding:'delta-v2',baseRef:'content-2',parts:[{copy:{offset:0,size:after.length}},{insert:{encoding:'utf8',content:'next\n'}}]};});
115
+ });
116
+
117
+ test('V2 rejects nonintegral, overlapping, out-of-range and corrupted recipes without accepting partial bytes',()=>{
118
+ const presented=compactReviewDataV2(dataFor([change('source.mjs',...pair())]));
119
+ for(const edit of [
120
+ e=>e.parts=[],e=>e.parts=[null],e=>e.parts[0].copy.offset=-1,e=>e.parts[0].copy.offset=0.5,
121
+ e=>e.parts[0].copy.offset=Number.MAX_SAFE_INTEGER+1,e=>e.parts[0].copy.size=0,
122
+ e=>e.parts[0].copy.size=NaN,e=>e.parts[0].copy.size=1e9,e=>e.parts[0].extra=true,
123
+ e=>e.parts.find(p=>p.insert).insert.content+='corrupt',
124
+ e=>e.parts.find(p=>p.insert).insert={encoding:'utf8',content:''},
125
+ e=>e.parts.find(p=>p.insert).insert={encoding:'base64',content:'YQ=='},
126
+ e=>e.parts.filter(p=>p.copy)[1].copy.offset=0,
127
+ e=>e.sha256='b'.repeat(64),e=>e.size++,e=>e.parts[0].copy.offset++
128
+ ])mutate(presented,v=>edit(deltaEntry(v)));
129
+ });
130
+
131
+ test('V2 enforces entry and total part budgets and fragmented generation falls back to complete evidence',()=>{
132
+ const presented=compactReviewDataV2(dataFor([change('source.mjs',...pair())]));
133
+ mutate(presented,v=>deltaEntry(v).parts=Array.from({length:1025},(_,i)=>({copy:{offset:i,size:1}})));
134
+ const changes=Array.from({length:5},(_,i)=>{
135
+ const before=Buffer.from('x'.repeat(1100)+i),after=Buffer.from('x'.repeat(1023)+i);
136
+ return change('budget-'+i,before,after);
137
+ });
138
+ const many=compactReviewDataV2(dataFor(changes));
139
+ for(const item of many.reviewPackage.changes){
140
+ const entry=many.contents[item.after.contentRef];
141
+ entry.encoding='delta-v2';entry.baseRef=item.before.contentRef;delete entry.content;
142
+ entry.parts=[...Array.from({length:1023},(_,i)=>({copy:{offset:i,size:1}})),{insert:{encoding:'utf8',content:item.path.at(-1)}}];
143
+ }
144
+ bad(many);
145
+ const before=lines(1500),after=before.map((line,i)=>i%2?line:'changed '+line);
146
+ after[0]='changed-first\n';after[after.length-1]='changed-last\n';
147
+ const original=dataFor([change('fragmented',Buffer.from(before.join('')),Buffer.from(after.join('')))]);
148
+ const generated=compactReviewDataV2(original);
149
+ assert.equal(Object.values(generated.contents).some(item=>item.encoding==='delta-v2'),false);
150
+ assert.deepEqual(expandReviewDataV2(generated),original);
151
+ });
152
+
153
+ test('V2 bounds source, physical input, reconstructed data and repeated-reference amplification',()=>{
154
+ const original=dataFor([change('source',null,Buffer.from('x'.repeat(1024*1024)))]);
155
+ const presented=compactReviewDataV2(original);
156
+ const oversized=clone(presented);oversized.padding='x'.repeat(11*1024*1024);bad(oversized);
157
+ mutate(presented,v=>v.presentation.logicalBytes=10*1024*1024+1);
158
+ mutate(presented,v=>v.contents['content-1'].size=10*1024*1024+1);
159
+ mutate(presented,v=>{v.amplification=Array.from({length:9},()=>({contentRef:'content-1'}));v.presentation.logicalBytes=10*1024*1024;});
160
+ assert.throws(()=>compactReviewDataV2({...original,padding:'x'.repeat(10*1024*1024)}),{code:'limit_exceeded'});
161
+ const cyclic={...original};cyclic.cycle=cyclic;
162
+ assert.throws(()=>compactReviewDataV2(cyclic),{code:'invalid_input'});
163
+ const cycle=clone(presented);cycle.cycle=cycle;bad(cycle);
164
+ const withGetter={...original};Object.defineProperty(withGetter,'getter',{enumerable:true,get(){throw new Error('must not run');}});
165
+ assert.throws(()=>compactReviewDataV2(withGetter),{code:'invalid_input'});
166
+ });
167
+
168
+ test('the line budget keeps complete fallback and duplicate lines do not create ambiguous recipes',()=>{
169
+ for(const [before,after] of [
170
+ [Buffer.from('repeat\n'.repeat(65537)),Buffer.from('repeat\n'.repeat(65537)+'tail')],
171
+ [Buffer.from('same unchanged long repeated line evidence\n'.repeat(1000)),Buffer.from('head\n'+'same unchanged long repeated line evidence\n'.repeat(1000))]
172
+ ]){
173
+ const original=dataFor([change('lines',before,after)]),presented=compactReviewDataV2(original);
174
+ assert.deepEqual(expandReviewDataV2(presented),original);
175
+ for(const entry of Object.values(presented.contents))if(entry.parts)assert(entry.parts.length<=1024);
176
+ }
177
+ });
178
+
179
+ test('V2 is an explicit policy while create defaults and existing V1 values remain unchanged',()=>{
180
+ assert.deepEqual(readExecutionPolicy(EXECUTION_POLICY_V1),EXECUTION_POLICY_V1);
181
+ assert.deepEqual(readExecutionPolicy(EXECUTION_POLICY_V2),EXECUTION_POLICY_V2);
182
+ assert.equal(readLaunchExecutionPolicy({mode:'create',definition:{}}),null);
183
+ assert.deepEqual(readLaunchExecutionPolicy({mode:'create',definition:{},enabled:true}),EXECUTION_POLICY_V1);
184
+ assert.equal(readFixExecutionPolicy({mode:'create',config:{}}),null);
185
+ assert.deepEqual(readFixExecutionPolicy({mode:'create',config:{},enabled:true}),EXECUTION_POLICY_V1);
186
+ for(const value of [{...EXECUTION_POLICY_V1,version:2},{...EXECUTION_POLICY_V2,version:1},
187
+ {...EXECUTION_POLICY_V2,usage:'other'},{...EXECUTION_POLICY_V2,extra:true}])assert.throws(()=>readExecutionPolicy(value),{code:'execution_policy_invalid'});
188
+ });
189
+
190
+ test('default and V1 prompts match the frozen pre-V2 bytes for both existing adapter variants',()=>{
191
+ // The source and transport candidate had different pre-existing unchangedScope
192
+ // wording. These exact hashes came from each adapter before this change; they were
193
+ // re-pinned deliberately when the reviewer instructions gained the
194
+ // requirement-evidence rule (cm-requirement-evidence-v1), and again when they
195
+ // gained the host-replay rule (cm-host-replay-v1).
196
+ const expected={full:new Set(['8cf6ae73bc414bd408b4756423a4748d708b9c559a6692aea585c903beaa35e7']),
197
+ v1:new Set(['b59c4ca5c36fe14d3056dd252fdc31d3e9724bca12855fe88d2bd3a110bd8338'])};
198
+ for(const provider of ['claude','codex']){
199
+ const request=reviewRequest(provider),full=buildReviewPrompt(request,provider);
200
+ assert.equal(full,buildReviewPrompt(request,provider,null));
201
+ assert(expected.full.has(sha(full)));
202
+ const v1=buildReviewPrompt(request,provider,EXECUTION_POLICY_V1);
203
+ assert(expected.v1.has(sha(v1)));assert.equal(splitPrompt(v1).presentation.version,1);
204
+ }
205
+ });
206
+
207
+ test('explicit V2 prompts contain complete reversible data and preserve request and package digests',()=>{
208
+ for(const provider of ['claude','codex'])for(const binary of [false,true]){
209
+ const request=reviewRequest(provider,{binary}),before=JSON.stringify(request),v1=buildReviewPrompt(request,provider,EXECUTION_POLICY_V1);
210
+ const prompt=buildReviewPrompt(request,provider,EXECUTION_POLICY_V2),presented=splitPrompt(prompt);
211
+ assert.equal(presented.presentation.version,2);assert(Buffer.byteLength(prompt)<Buffer.byteLength(v1));
212
+ assert.deepEqual(expandReviewDataV2(presented),{reviewPackage:request.payload.reviewPackage,priorReview:null,examinedPaths:['requirements.md','source.mjs']});
213
+ if(binary)assert.equal(v1,buildReviewPrompt(request,provider));
214
+ assert.equal(JSON.stringify(request),before);assert.equal(presented.presentation.packageDigest,request.payload.reviewPackage.packageDigest);
215
+ assert(prompt.includes('Byte offsets are not character offsets'));
216
+ assert.equal(prompt.split('No tools or follow-up fetches.').length,2);
217
+ }
218
+ });
@@ -0,0 +1,115 @@
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 {pathToFileURL} from 'node:url';
7
+ import {createHash} from 'node:crypto';
8
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
9
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
11
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
12
+ import {captureReviewBaseline,createReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
13
+ import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
14
+ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
15
+ import {createFixFinalReview} from '../runtime/js/cm-fix/final-review.mjs';
16
+
17
+ const MARKER='CM_SNAPSHOT_REUSE',runtimeRoot=path.resolve(import.meta.dirname,'..');
18
+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
19
+ const clockKey=Symbol.for('CM_SNAPSHOT_REUSE_OWNED_VALIDATOR_COST');
20
+ function fixture(t,open=openExecutionStore){
21
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-snapshot-reuse-'))),cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
22
+ const identity={repositoryId:'fixture',runId:'snapshot-reuse',taskId:'T-FIX-snapshot',attempt:1};fs.writeFileSync(path.join(cwd,'repro.mjs'),"console.error('owned fixture');process.exit(1);\n");
23
+ const config={hostContextId:'owned-snapshot-host',defect:'Snapshot reuse fixture only',reproduction:{cwd,command:[process.execPath,'repro.mjs'],expectedFailure:{exitCode:1,outputIncludes:'owned fixture'},timeoutMs:2000}};
24
+ const owner=openFixExecution({specsRoot,identity,configuration:config,create:true},{});owner.close();
25
+ const short={repositoryId:identity.repositoryId,runId:identity.runId},fingerprints=readExecutionSnapshot({specsRoot,identity:short}).fingerprints,options={specsRoot,identity:short,fingerprints,create:false};let store=open(options);
26
+ const dir=path.join(specsRoot,'.reviews','.execution',identity.runId),state=path.join(dir,'state.json');
27
+ t.after(()=>{store?.close();fs.rmSync(root,{recursive:true,force:true});});
28
+ return {root,cwd,specsRoot,identity,dir,state,store:()=>store,close(){store.close();},reopen(){store.close();store=open(options);return store;},append(id,payload){const before=store.snapshot();return store.append({id,kind:'intent',payload,expectedRevision:before.revision});}};
29
+ }
30
+ function material(f){
31
+ fs.writeFileSync(path.join(f.cwd,'sample.mjs'),'export const value=1;\n//'+'x'.repeat(360*1024));
32
+ const baseline=captureReviewBaseline({root:f.cwd,identity:f.identity,scope:['sample.mjs'],requirements:['sample.mjs']});
33
+ fs.writeFileSync(path.join(f.cwd,'sample.mjs'),'export const value=2;\n//'+'x'.repeat(360*1024));
34
+ const checks=[{id:'owned-fixture',command:['synthetic-not-executed'],outcome:'passed',exitCode:0,evidence:'Canonical storage fixture only; no command or provider result'}],handoffPath=path.join(f.root,'fix-snapshot-T-FIX-snapshot-a1-handoff.json');
35
+ createHostHandoff({root:f.cwd,baseline,checks,handoffPath,evidence:['learning: no_relevant_lesson','learning: retrospective no_new_lesson']});
36
+ const pkg=createReviewPackage({root:f.cwd,baseline,checks,handoffPath});assert(Buffer.byteLength(JSON.stringify(pkg))>1024*1024,MARKER+': fixture must exercise the actual large-review codec');return pkg;
37
+ }
38
+ async function instrumentedStore(t){
39
+ // Only the owned copied validator is instrumented. It still executes the real
40
+ // decoder/validator/encoder. No cache branch, return or export is replaced.
41
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-snapshot-clock-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
42
+ const originalStore=path.join(runtimeRoot,'runtime/js/cm-ai/execution-store.mjs'),file=path.join(root,'execution-store.mjs'),before=fs.readFileSync(originalStore,'utf8'),needle='function validateState(raw,options) {';
43
+ assert.equal(before.split(needle).length,2,MARKER+': exact private validator instrumentation point');
44
+ fs.writeFileSync(file,before.replace(needle,needle+'\n globalThis[Symbol.for("CM_SNAPSHOT_REUSE_OWNED_VALIDATOR_COST")]?.();').replace(/from '([.][^']+)'/g,(_match,specifier)=>"from '"+pathToFileURL(path.resolve(path.dirname(originalStore),specifier)).href+"'"));
45
+ const module=await import(pathToFileURL(file));return {open:module.openExecutionStore,sourceSha256:hash(before)};
46
+ }
47
+ function poisonedAfter(f,mutate,accept){
48
+ const original=fs.readFileSync(f.state);f.store().snapshot();mutate();
49
+ assert.throws(()=>f.store().snapshot(),accept,MARKER+': cached data must not hide a current failure');
50
+ fs.writeFileSync(f.state,original,{mode:0o600});assert.throws(()=>f.store().snapshot(),{code:'store_poisoned'},MARKER+': failure must poison even after exact bytes return');
51
+ }
52
+
53
+ test('CM_SNAPSHOT_REUSE: identical validated snapshots preserve a real final-review grant under controlled validation cost',async t=>{
54
+ const instrumented=await instrumentedStore(t),f=fixture(t,instrumented.open),pkg=material(f);f.append('fix-retrospective-intent',pkg);f.store().snapshot();
55
+ const physicalBefore=fs.readFileSync(f.state);assert(JSON.parse(physicalBefore).storageEncoding,MARKER+': large review must really be encoded');
56
+ let now=1700000000000,costEnabled=false,passes=0,calls=0,registered=null,registrationCost=0,result,error;const originalNow=Date.now;
57
+ globalThis[clockKey]=()=>{if(costEnabled){passes++;now+=2000;}};Date.now=()=>now;
58
+ try{
59
+ const configuration={hostContextId:'owned-snapshot-host',reviewer:{reviewerId:'final-reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',contextId:'owned-final-review',excludedThreadIds:[]}};
60
+ const authority=createHostReviewAuthority({hostContextId:configuration.hostContextId,reviewerId:configuration.reviewer.reviewerId,adapterId:configuration.reviewer.adapterId,decide:async()=>({status:'approved'})});
61
+ const signal=new AbortController().signal;await authority.hostDecisionProvider.decide({identity:f.identity,packageDigest:pkg.packageDigest},signal);
62
+ const review=createFixFinalReview({reviewPackage:pkg,configuration,timeoutMs:2000},{authorize:authority.authorize,run:async()=>{calls++;return {status:'failed',code:'owned_no_provider'};}});
63
+ try{result=await review({signal,register(value){
64
+ registered=value;assert.equal(value.grant.expiresAt-value.grant.issuedAt,60000);
65
+ costEnabled=true;const start=now;
66
+ try{for(let index=0;index<40;index++){const current=f.store().snapshot();assert.equal(current.records.at(-1).payload.packageDigest,pkg.packageDigest);}
67
+ assert.deepEqual(fs.readFileSync(f.state),physicalBefore,MARKER+': read-only projection must not write');
68
+ f.append('fix-final-registered',value);for(let index=0;index<4;index++)assert.equal(f.store().snapshot().records.at(-1).payload.request.requestDigest,value.request.requestDigest);
69
+ }finally{registrationCost=now-start;costEnabled=false;}
70
+ },onStarted(){assert.fail(MARKER+': no provider or real review thread may start');}});}catch(caught){error=caught;}
71
+ assert.equal(error?.code,undefined,MARKER+': repeated validated snapshot cost expired the real grant ('+(error?.code??'none')+'), passes='+passes+', simulatedMs='+registrationCost);
72
+ assert.equal(calls,1,MARKER+': the still-valid original grant must reach only the failed hard stub');assert(registered);assert.equal(result.completionEligible,false);assert.equal(result.value?.observation?.result?.status,'failed');assert(!['approved','changes_requested'].includes(result.inspection?.verdict));
73
+ assert(registrationCost<60000,MARKER+': registration must retain the original authority lifetime');
74
+ assert.equal(f.store().snapshot().records.at(-1).payload.request.requestDigest,registered.request.requestDigest);
75
+ console.log(JSON.stringify({marker:MARKER,kind:'controlled-real-grant',sourceSha256:instrumented.sourceSha256,repeatedSnapshots:44,fullValidationPasses:passes,simulatedValidationMs:registrationCost,grantMs:60000,failedStubCalls:calls,providerCalls:0}));
76
+ }finally{Date.now=originalNow;delete globalThis[clockKey];}
77
+ });
78
+
79
+ test('CM_SNAPSHOT_REUSE: append invalidates old logical contents and an idempotent append preserves physical old rows',t=>{
80
+ const f=fixture(t),before=f.store().snapshot(),initialBytes=fs.readFileSync(f.state);for(let i=0;i<3;i++)assert.deepEqual(f.store().snapshot(),before);
81
+ const first=f.append('owned-first',{note:'one'}),firstBytes=fs.readFileSync(f.state);assert.notDeepEqual(firstBytes,initialBytes);assert.notEqual(first.revision,before.revision);assert.equal(f.store().snapshot().records.at(-1).payload.note,'one');
82
+ const after=f.append('owned-second',{note:'two'}),physical=JSON.parse(fs.readFileSync(f.state));assert.equal(after.records.length,first.records.length+1);assert.deepEqual(physical.records.slice(0,-1),JSON.parse(firstBytes).records);
83
+ const saved=fs.readFileSync(f.state);const same=f.store().append({id:'owned-second',kind:'intent',payload:{note:'two'},expectedRevision:after.revision});assert.deepEqual(same,after);assert.deepEqual(fs.readFileSync(f.state),saved);
84
+ });
85
+
86
+ test('CM_SNAPSHOT_REUSE: different physical bytes and bad digest are never repaired by the cache and remain poisoned',t=>{
87
+ for(const mode of ['digest','noncanonical']){const f=fixture(t);f.append('owned-payload',{note:'one'});poisonedAfter(f,()=>{const raw=JSON.parse(fs.readFileSync(f.state));if(mode==='digest')raw.revision='0'.repeat(64);fs.writeFileSync(f.state,JSON.stringify(raw)+'\n'+(mode==='noncanonical'?' ':''));},{code:'store_corrupt'});}
88
+ });
89
+
90
+ test('CM_SNAPSHOT_REUSE: cache hits still enforce permissions, unknown files, symlink, readiness and writer ownership',t=>{
91
+ for(const mode of ['state-mode','unknown-file','state-symlink','readiness-mode','writer-inode','directory-mode']){
92
+ const f=fixture(t);f.store().snapshot();let expected;
93
+ if(mode==='state-mode'){fs.chmodSync(f.state,0o644);expected='store_permissions';}
94
+ if(mode==='unknown-file'){fs.writeFileSync(path.join(f.dir,'unknown'),'owned');expected='store_unknown_file';}
95
+ if(mode==='state-symlink'){const external=path.join(f.root,'saved-state');fs.renameSync(f.state,external);fs.symlinkSync(external,f.state);expected='unsupported_file';}
96
+ if(mode==='readiness-mode'){fs.chmodSync(path.join(f.dir,'writer-ready.json'),0o644);expected='store_permissions';}
97
+ if(mode==='writer-inode'){const writer=path.join(f.dir,'writer.sqlite'),old=path.join(f.root,'saved-writer');fs.renameSync(writer,old);fs.copyFileSync(old,writer);fs.chmodSync(writer,0o600);expected='store_ownership';}
98
+ if(mode==='directory-mode'){fs.chmodSync(f.dir,0o755);expected='store_permissions';}
99
+ assert.throws(()=>f.store().snapshot(),{code:expected},MARKER+': '+mode);assert.throws(()=>f.store().snapshot(),{code:'store_poisoned'},MARKER+': poison '+mode);
100
+ }
101
+ });
102
+
103
+ test('CM_SNAPSHOT_REUSE: every cache hit really reads fresh bytes and rejects an inode swap during the read',t=>{
104
+ const f=fixture(t);f.append('owned-payload',{note:'one'});const bytes=fs.readFileSync(f.state),replacement=path.join(f.root,'replacement');fs.writeFileSync(replacement,bytes,{mode:0o600});f.store().snapshot();
105
+ const inode=fs.statSync(f.state),original=fs.readFileSync;let triggered=0;
106
+ fs.readFileSync=function(file,...args){const match=typeof file==='number'&&fs.fstatSync(file).ino===inode.ino&&fs.fstatSync(file).dev===inode.dev,value=original.call(this,file,...args);if(match&&!triggered++){fs.renameSync(replacement,f.state);}return value;};
107
+ try{assert.throws(()=>f.store().snapshot(),{code:'snapshot_changed'},MARKER+': current read must bind the same inode before and after');assert.equal(triggered,1);assert.throws(()=>f.store().snapshot(),{code:'store_poisoned'});}finally{fs.readFileSync=original;}
108
+ });
109
+
110
+ test('CM_SNAPSHOT_REUSE: returned snapshots cannot be changed by callers and close/reopen revalidates preserved state',t=>{
111
+ const f=fixture(t);f.append('owned-data',{nested:{value:'retained'}});const a=f.store().snapshot(),bytes=fs.readFileSync(f.state),revision=a.revision;
112
+ assert.throws(()=>{a.records.at(-1).payload.nested.value='changed';},TypeError);assert.throws(()=>a.records.push({}),TypeError);assert.throws(()=>{a.revision='0'.repeat(64);},TypeError);
113
+ for(let i=0;i<3;i++){const b=f.store().snapshot();assert.equal(b.records.at(-1).payload.nested.value,'retained');assert.equal(b.revision,revision);}assert.deepEqual(fs.readFileSync(f.state),bytes);
114
+ f.close();assert.throws(()=>f.store().snapshot(),{code:'store_closed'});f.reopen();assert.deepEqual(f.store().snapshot(),a);assert.deepEqual(fs.readFileSync(f.state),bytes);
115
+ });
@@ -1,5 +1,6 @@
1
1
  import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
2
2
  import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
3
+ import {batchSegment} from '../runtime/js/cm-ai/batch-location.mjs';
3
4
  import test from 'node:test';
4
5
  import assert from 'node:assert/strict';
5
6
  import fs from 'node:fs';
@@ -75,7 +76,7 @@ function execute(f,{cancel=false,args=[]}={}){
75
76
  if(row.type==='host_request'){
76
77
  const payload=row.payload,identity=payload.identity??payload.request.identity;
77
78
  const cwd=f.parallel&&identity.taskId!=='T-003'
78
- ?path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),identity.taskId):f.codeProject;
79
+ ?path.join(f.root,'.cm-worktrees',batchSegment(f.batch.batchId),identity.taskId):f.codeProject;
79
80
  calls.push(`${identity.taskId}:${row.kind}`);
80
81
  if(cancel){send({operation:'status',requestId:'status'});send({operation:'cancel',requestId:'cancel'});continue;}
81
82
  if(row.kind==='develop'){
@@ -145,7 +146,7 @@ test('new parallel batch merges reviewed members without committing private bind
145
146
  const f=fixture();f.parallel=true;
146
147
  try{
147
148
  f.batch.tasks=[1,2,3].map(n=>({feature:'1.work',taskId:`T-00${n}`,scope:[`task${n}.mjs`],requirements:['requirements.md']}));f.batch.parallel=[['1.work/T-001','1.work/T-002']];
148
- fs.writeFileSync(path.join(f.specsDir,'1.work','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
149
+ fs.writeFileSync(path.join(f.specsDir,'1.work','tasks.md'),'- [ ] T-001: first\n - 范围: `task1.mjs`\n- [ ] T-002: second\n - 范围: `task2.mjs`\n- [ ] T-003: final\n - 范围: `task3.mjs`\n\n- T-003 依赖 T-001, T-002\n');
149
150
  fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
150
151
  const original=JSON.parse(fs.readFileSync(f.config)).workflows['1.work/T-001'];fs.writeFileSync(f.config,JSON.stringify({batch:f.batch,workflows:Object.fromEntries(f.batch.tasks.map(task=>[`1.work/${task.taskId}`,original]))}));
151
152
  const home=path.join(f.root,'home');fs.mkdirSync(home);f.env.CM_WORKFLOW_HOME=home;f.env.CM_WORKFLOW_LOG_HOME=path.join(f.root,'logs');
@@ -155,7 +156,7 @@ test('new parallel batch merges reviewed members without committing private bind
155
156
  for(const args of [['add','README.md'],['commit','-m','fixture documentation']])assert.equal(spawnSync('git',['-C',f.codeProject,...args]).status,0);
156
157
  const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
157
158
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'}).stdout;assert(!tracked.includes('.cm-external-models-v1.json'));assert(!tracked.includes('.cm-model-config.lock'));
158
- for(const n of [1,2])assert(!fs.existsSync(path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),'T-00'+n)));
159
+ for(const n of [1,2])assert(!fs.existsSync(path.join(f.root,'.cm-worktrees',batchSegment(f.batch.batchId),'T-00'+n)));
159
160
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
160
161
  });
161
162
 
@@ -8,6 +8,7 @@ import {EventEmitter} from 'node:events';
8
8
  import {PassThrough} from 'node:stream';
9
9
  import {codexWorker} from '../runtime/js/cm-ai/worker-codex.mjs';
10
10
  import {claudeWorker,claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
11
+ import {ownedProcessCleanup} from '../runtime/js/cm-ai/owned-process-cleanup.mjs';
11
12
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
12
13
  import {readModelJson,writeModelJson} from '../runtime/js/cm-ai/model-configuration-file.mjs';
13
14
  const fixture=t=>{const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-security-fix-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));return root;};
@@ -69,3 +70,130 @@ test('Windows old reviewer keeps successful dispatch; termination uncertainty ca
69
70
  assert.equal(kills,2);
70
71
  }finally{Object.defineProperty(process,'platform',original);}
71
72
  });
73
+
74
+ // Signal delivery is asynchronous. The last member can be exiting until the
75
+ // next event-loop turn; a probe must not run in the SIGKILL delivery turn.
76
+ test('owned cleanup waits for asynchronous exit before its first group probe',{skip:process.platform==='win32'},async()=>{
77
+ const calls=[];let reaped=false;
78
+ const cleanup=ownedProcessCleanup({pid:12345},{graceMs:0,killProcess:(pid,signal)=>{
79
+ assert.equal(pid,-12345);calls.push(signal);
80
+ if(signal==='SIGKILL'){setTimeout(()=>{reaped=true;},0);return;}
81
+ if(signal===0){
82
+ if(!reaped)throw Object.assign(new Error('synthetic exit still pending'),{code:'EPERM'});
83
+ throw Object.assign(new Error('synthetic group gone'),{code:'ESRCH'});
84
+ }
85
+ }});
86
+ await cleanup();assert.equal(reaped,true);assert.deepEqual(calls,['SIGTERM','SIGKILL',0]);
87
+ });
88
+
89
+ for(const failureAt of ['SIGTERM','SIGKILL',0])test(`owned cleanup stops at permission refusal during ${failureAt}`,{skip:process.platform==='win32'},async()=>{
90
+ const calls=[];
91
+ const cleanup=ownedProcessCleanup({pid:12345},{graceMs:0,killProcess:(pid,signal)=>{
92
+ assert.equal(pid,-12345);calls.push(signal);
93
+ if(signal===failureAt)throw Object.assign(new Error('synthetic permission denied'),{code:'EPERM'});
94
+ }});
95
+ await assert.rejects(cleanup(),{code:'process_cleanup_unknown'});
96
+ assert.deepEqual(calls,['SIGTERM','SIGKILL',0].slice(0,['SIGTERM','SIGKILL',0].indexOf(failureAt)+1));
97
+ await assert.rejects(cleanup(),{code:'process_cleanup_unknown'});
98
+ assert.equal(calls.length,['SIGTERM','SIGKILL',0].indexOf(failureAt)+1);
99
+ });
100
+
101
+ test('owned cleanup keeps a live group unknown at its original deadline',{skip:process.platform==='win32'},async()=>{
102
+ const calls=[];
103
+ const cleanup=ownedProcessCleanup({pid:12345},{graceMs:0,killWaitMs:0,killProcess:(pid,signal)=>{
104
+ assert.equal(pid,-12345);calls.push(signal);
105
+ }});
106
+ await assert.rejects(cleanup(),{code:'process_cleanup_unknown'});
107
+ assert.deepEqual(calls,['SIGTERM','SIGKILL',0]);
108
+ });
109
+
110
+ // 2026-10-27 (macOS 26 measured): a process group whose only member is our own child
111
+ // that already exited but is not reaped yet (a zombie) answers kill(-pgid, 0|SIGTERM)
112
+ // with EPERM; after the reap it is ESRCH. A provider CLI that exits right after its
113
+ // error used to end process_cleanup_unknown. A stop is proven only once our direct
114
+ // child's exit is observed and a re-probe answers ESRCH (no process table is read).
115
+ const exitedChild=(pid=12345)=>Object.assign(new EventEmitter(),{pid,exitCode:1,signalCode:null});
116
+ const denied=()=>{throw Object.assign(new Error('synthetic permission denied'),{code:'EPERM'});};
117
+ test('owned cleanup: a real child that exited at once (unreaped zombie group) is proven stopped',{skip:process.platform==='win32'},async()=>{
118
+ const child=spawn(process.execPath,['-e','process.exit(1)'],{detached:true,stdio:'ignore'});
119
+ const started=Date.now();while(Date.now()-started<400){} // the child exits; this loop keeps it unreaped
120
+ await ownedProcessCleanup(child,{graceMs:0})();
121
+ assert.notEqual(child.exitCode,null);
122
+ });
123
+ // EPERM is resolved only through our own child: after its exit is observed, a re-probe
124
+ // within the same budget must answer ESRCH (stopped) or deliver (a live member).
125
+ const waitingChild=(pid=12345)=>Object.assign(new EventEmitter(),{pid,exitCode:null,signalCode:null});
126
+ test('owned cleanup: EPERM until our child is reaped, then ESRCH, is a stop; the wait never blocks the event loop',{skip:process.platform==='win32'},async()=>{
127
+ const child=waitingChild(),calls=[];let reaped=false,ticked=false;
128
+ setTimeout(()=>{ticked=true;},10);
129
+ setTimeout(()=>{reaped=true;child.exitCode=1;child.emit('exit',1,null);},40);
130
+ await ownedProcessCleanup(child,{graceMs:0,killProcess:(pid,signal)=>{
131
+ assert.equal(pid,-12345);calls.push(signal);
132
+ throw Object.assign(new Error('synthetic'),{code:reaped?'ESRCH':'EPERM'});
133
+ }})();
134
+ assert.equal(ticked,true,'a 10 ms timer ran while waiting for the exit');
135
+ assert.deepEqual(calls,['SIGTERM','SIGTERM']);
136
+ });
137
+ test('owned cleanup: an EPERM that persists after our child exited stays unknown',{skip:process.platform==='win32'},async()=>{
138
+ const started=Date.now();
139
+ await assert.rejects(ownedProcessCleanup(exitedChild(),{graceMs:0,exitBudgetMs:200,killProcess:denied})(),{code:'process_cleanup_unknown'});
140
+ assert(Date.now()-started<1000,'bounded by the budget');
141
+ });
142
+ // Review 2026-10-27 round 2: every signal used to get the full exit budget again, so a
143
+ // probe that met EPERM at the kill deadline still waited the whole budget past it.
144
+ test('owned cleanup: an EPERM probe at the kill deadline does not wait past it',{skip:process.platform==='win32'},async()=>{
145
+ const started=Date.now();
146
+ await assert.rejects(ownedProcessCleanup(exitedChild(),{graceMs:0,killWaitMs:0,exitBudgetMs:200,killProcess:(pid,signal)=>{
147
+ if(signal===0)denied();
148
+ }})(),{code:'process_cleanup_unknown'});
149
+ assert(Date.now()-started<150,`ended at the kill deadline, not ${Date.now()-started} ms later`);
150
+ });
151
+ // Review 2026-10-27 round 3: SIGTERM and SIGKILL each met EPERM before delivering, then
152
+ // the group stayed alive; the poll after SIGKILL got a fresh killWaitMs (≈560 ms of 400).
153
+ test('owned cleanup: EPERM before SIGTERM and SIGKILL still ends at the overall deadline',{skip:process.platform==='win32'},async()=>{
154
+ const started=Date.now(),at=()=>Date.now()-started;
155
+ await assert.rejects(ownedProcessCleanup(exitedChild(),{graceMs:0,killWaitMs:200,exitBudgetMs:200,killProcess:(pid,signal)=>{
156
+ if(signal==='SIGTERM'&&at()<150)denied();
157
+ if(signal==='SIGKILL'&&at()<350)denied();
158
+ }})(),{code:'process_cleanup_unknown'});
159
+ assert(at()<480,`ended near the 400 ms overall deadline, not ${at()} ms`);
160
+ });
161
+ test('owned cleanup: a member that answers once our child exited is live, not stopped',{skip:process.platform==='win32'},async()=>{
162
+ const calls=[];let first=true;
163
+ await assert.rejects(ownedProcessCleanup(exitedChild(),{graceMs:0,killWaitMs:0,killProcess:(pid,signal)=>{
164
+ calls.push(signal);if(first){first=false;denied();}
165
+ }})(),{code:'process_cleanup_unknown'});
166
+ // It was treated as alive: escalated to SIGKILL and still probed alive at the deadline.
167
+ assert.deepEqual(calls,['SIGTERM','SIGTERM','SIGKILL',0]);
168
+ });
169
+ test('owned cleanup: EPERM without an observed exit of our child stays unknown, even if a later probe says ESRCH',{skip:process.platform==='win32'},async()=>{
170
+ await assert.rejects(ownedProcessCleanup(waitingChild(),{graceMs:0,exitBudgetMs:30,killProcess:denied})(),{code:'process_cleanup_unknown'});
171
+ let first=true;
172
+ await assert.rejects(ownedProcessCleanup(waitingChild(),{graceMs:0,exitBudgetMs:30,killProcess:()=>{
173
+ if(first){first=false;denied();}throw Object.assign(new Error('synthetic'),{code:'ESRCH'});
174
+ }})(),{code:'process_cleanup_unknown'});
175
+ });
176
+ test('owned cleanup: a zombie leader with a live descendant is killed, not taken for stopped',{skip:process.platform==='win32'},async t=>{
177
+ const root=fixture(t),pidFile=path.join(root,'grandchild.pid');
178
+ const child=spawn(process.execPath,['-e',`const c=require('child_process').spawn(process.execPath,['-e','process.on("SIGTERM",()=>{});setInterval(()=>{},1000)'],{stdio:'ignore'});
179
+ require('fs').writeFileSync(${JSON.stringify(pidFile)},String(c.pid));c.unref();process.exit(0);`],{detached:true,stdio:'ignore'});
180
+ t.after(()=>{try{process.kill(-child.pid,'SIGKILL');}catch{}});
181
+ while(!fs.existsSync(pidFile))await new Promise(resolve=>setTimeout(resolve,10));
182
+ const grandchild=Number(fs.readFileSync(pidFile,'utf8'));
183
+ await ownedProcessCleanup(child,{graceMs:50})();
184
+ assert.equal(alive(grandchild),false,'the TERM-ignoring descendant was killed');
185
+ });
186
+ test('Codex reviewer that exits right after its 429 ends reviewer_rate_limited, not process_cleanup_unknown',{skip:process.platform==='win32'},async t=>{
187
+ const root=fixture(t),script=path.join(root,'codex-429.mjs');
188
+ fs.writeFileSync(script,`let input='';for await(const part of process.stdin)input+=part;
189
+ const message='exceeded retry limit, last status: 429 Too Many Requests';
190
+ for(const value of [{type:'thread.started',thread_id:'t-429'},{type:'turn.started'},{type:'error',message},{type:'turn.failed',error:{message}}])
191
+ process.stdout.write(JSON.stringify(value)+'\\n');
192
+ process.exit(1);`);
193
+ for(let attempt=0;attempt<3;attempt++){
194
+ const result=await worker(root,{promptTransport:'stdin',timeoutMs:5000,spawnProcess:(_cli,_args,opts)=>spawn(process.execPath,[script],opts),
195
+ preflight:{passed:true,cli_model:'synthetic-reviewer',prompt_transport:'stdin',
196
+ config_fingerprint:configFingerprint({...options(root),promptTransport:'stdin'})}})({prompt:'p'},{signal:new AbortController().signal,onEvent:()=>{}});
197
+ assert.deepEqual(result,{status:'failed',code:'reviewer_rate_limited'},`attempt ${attempt}`);
198
+ }
199
+ });