@aibyzero/cm-workflow 0.17.0 → 0.18.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 (372) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +27 -0
  3. package/CHANGELOG.md +230 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +21 -3
  6. package/THIRD_PARTY_NOTICES.md +13 -0
  7. package/VERSION +1 -1
  8. package/compat/claude-commands/cm-challenge.md +3 -0
  9. package/docs/architecture.md +40 -13
  10. package/docs/cm-control-policy-v2.md +127 -9
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/installation.md +310 -4
  13. package/docs/js-workflow-control.md +153 -16
  14. package/docs/live-evidence-drivers.md +28 -4
  15. package/docs/out-of-scope/README.md +25 -0
  16. package/docs/out-of-scope/background-supervisor.md +32 -0
  17. package/docs/reviewed-integration.md +48 -0
  18. package/docs/user-guide.md +50 -21
  19. package/install-codex.sh +331 -18
  20. package/install.ps1 +28 -2
  21. package/install.sh +321 -17
  22. package/package.json +2 -1
  23. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  24. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  25. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  26. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  27. package/runtime/js/cm-ai/claude-review-stream.mjs +94 -21
  28. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  29. package/runtime/js/cm-ai/cm-ai-admission.mjs +18 -12
  30. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  31. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  32. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  33. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  34. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  35. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  36. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  37. package/runtime/js/cm-ai/control-policy.mjs +24 -6
  38. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  39. package/runtime/js/cm-ai/drive-core.mjs +236 -34
  40. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  41. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  42. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  43. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  44. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  45. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  46. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  47. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  48. package/runtime/js/cm-ai/host-check.mjs +14 -6
  49. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  52. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  53. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  54. package/runtime/js/cm-ai/host-session.mjs +42 -9
  55. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  56. package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
  57. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  58. package/runtime/js/cm-ai/host.mjs +1 -1
  59. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  60. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  61. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  62. package/runtime/js/cm-ai/operator-guidance.mjs +63 -30
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  64. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  65. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  66. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  67. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  68. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  69. package/runtime/js/cm-ai/review-package.mjs +79 -7
  70. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  71. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  72. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  73. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  74. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  75. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  76. package/runtime/js/cm-ai/task-runner.mjs +247 -41
  77. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  78. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  79. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  80. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  81. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  82. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  83. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  84. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  85. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  86. package/runtime/js/cm-fix/dossier.mjs +8 -2
  87. package/runtime/js/cm-fix/execution.mjs +578 -100
  88. package/runtime/js/cm-fix/final-review.mjs +39 -8
  89. package/runtime/js/cm-fix/finish.mjs +15 -11
  90. package/runtime/js/cm-fix/host-review.mjs +65 -10
  91. package/runtime/js/cm-fix/host.mjs +35 -12
  92. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  93. package/runtime/js/cm-fix/metrics.mjs +18 -5
  94. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  95. package/runtime/js/cm-fix/regression.mjs +16 -7
  96. package/runtime/js/cm-fix/repair.mjs +29 -8
  97. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  98. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  99. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  100. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  101. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  102. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  103. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  104. package/runtime/js/cm-fix/start.mjs +6 -3
  105. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  106. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  107. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  108. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  109. package/runtime/js/cm-prd/analysis.mjs +13 -9
  110. package/runtime/js/cm-prd/change.mjs +37 -16
  111. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  112. package/runtime/js/cm-prd/draft.mjs +31 -3
  113. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  114. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  115. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  116. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  117. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  118. package/runtime/js/cm-prd/self-check.mjs +125 -6
  119. package/runtime/js/cm-prd/session.mjs +30 -1
  120. package/runtime/js/cm-prd/summary.mjs +38 -17
  121. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  122. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  123. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  124. package/runtime/js/cm-security/scan.mjs +1 -1
  125. package/runtime/js/commander/decision.mjs +44 -0
  126. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  127. package/runtime/js/commander/ledger.mjs +265 -0
  128. package/runtime/js/commander/preflight.mjs +107 -0
  129. package/runtime/js/notify-later.mjs +13 -0
  130. package/runtime/js/notify-send.mjs +6 -2
  131. package/runtime/js/notify.mjs +570 -63
  132. package/runtime/js/review-findings.mjs +38 -0
  133. package/runtime/js/session-boundary.mjs +56 -0
  134. package/runtime/js/session-handoff.mjs +68 -0
  135. package/runtime/js/spec-task-line.mjs +27 -13
  136. package/runtime/js/specs-status.mjs +1 -1
  137. package/runtime/js/task-scope.mjs +197 -0
  138. package/runtime/logging.md +6 -1
  139. package/runtime/model-efficiency.md +69 -10
  140. package/runtime/orchestration.md +3 -1
  141. package/runtime/project-learning.md +2 -0
  142. package/runtime/review.md +12 -2
  143. package/runtime/test-contract.md +1 -0
  144. package/scripts/ci-test-weights.json +3 -0
  145. package/scripts/cm-ai-admission.mjs +11 -5
  146. package/scripts/cm-ai-admission.test.mjs +23 -2
  147. package/scripts/cm-ai-batch-drive.mjs +79 -18
  148. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  149. package/scripts/cm-ai-batch-host.mjs +38 -9
  150. package/scripts/cm-ai-batch-host.test.mjs +27 -14
  151. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  152. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  153. package/scripts/cm-ai-batch-plan.mjs +52 -0
  154. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  155. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  156. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  157. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  158. package/scripts/cm-ai-batch-run.mjs +483 -63
  159. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  160. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  161. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  162. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  163. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  164. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  165. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  166. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  167. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  168. package/scripts/cm-ai-control-policy.test.mjs +82 -0
  169. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  170. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  171. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  172. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  173. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  174. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
  175. package/scripts/cm-ai-drive.mjs +73 -17
  176. package/scripts/cm-ai-drive.test.mjs +37 -5
  177. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  178. package/scripts/cm-ai-host-fixture.mjs +9 -6
  179. package/scripts/cm-ai-host-protected.test.mjs +1 -1
  180. package/scripts/cm-ai-host.mjs +60 -19
  181. package/scripts/cm-ai-host.test.mjs +15 -0
  182. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  183. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  184. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  185. package/scripts/cm-ai-integration-preview.mjs +41 -0
  186. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  187. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  188. package/scripts/cm-ai-operator-guidance.test.mjs +71 -0
  189. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  190. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  191. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  192. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  193. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  194. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  195. package/scripts/cm-ai-review-timeout.test.mjs +20 -0
  196. package/scripts/cm-ai-run.mjs +88 -21
  197. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  198. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  199. package/scripts/cm-ai-supersede.test.mjs +28 -0
  200. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  201. package/scripts/cm-announce-hook.mjs +35 -8
  202. package/scripts/cm-announce-hook.test.mjs +25 -0
  203. package/scripts/cm-challenge.test.mjs +61 -0
  204. package/scripts/cm-check-drive-files.mjs +2 -2
  205. package/scripts/cm-check-host.test.mjs +1 -1
  206. package/scripts/cm-check-runtime.sh +58 -1
  207. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  208. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  209. package/scripts/cm-claude-probe.test.mjs +26 -0
  210. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  211. package/scripts/cm-claude-review-stream.test.mjs +49 -0
  212. package/scripts/cm-claude-worker.test.mjs +16 -0
  213. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  214. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  215. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  216. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  217. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  218. package/scripts/cm-commander-ledger.test.mjs +260 -0
  219. package/scripts/cm-commander-p2.test.mjs +295 -0
  220. package/scripts/cm-commander-preflight.mjs +84 -0
  221. package/scripts/cm-commander.mjs +116 -0
  222. package/scripts/cm-config-lock.mjs +35 -0
  223. package/scripts/cm-controlled-correction.test.mjs +10 -1
  224. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  225. package/scripts/cm-display-task-id.test.mjs +41 -0
  226. package/scripts/cm-drive-liveness.test.mjs +83 -0
  227. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  228. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  229. package/scripts/cm-external-batch-host.test.mjs +12 -9
  230. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  231. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  232. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  233. package/scripts/cm-failover.mjs +48 -10
  234. package/scripts/cm-failover.test.mjs +46 -0
  235. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  236. package/scripts/cm-fix-command-correction.mjs +17 -0
  237. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  238. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  239. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  240. package/scripts/cm-fix-drive.mjs +33 -5
  241. package/scripts/cm-fix-drive.test.mjs +49 -0
  242. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  243. package/scripts/cm-fix-host-review.test.mjs +21 -9
  244. package/scripts/cm-fix-host.mjs +26 -8
  245. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  246. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  247. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  248. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  249. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  250. package/scripts/cm-fix-review-preflight.mjs +24 -0
  251. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  252. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  253. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  254. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  255. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  256. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  257. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  258. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  259. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  260. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  261. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  262. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  263. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  264. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  265. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  266. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  267. package/scripts/cm-host-liveness.test.mjs +150 -0
  268. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  269. package/scripts/cm-host-replay.test.mjs +176 -0
  270. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  271. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  272. package/scripts/cm-install-manifest.sh +351 -0
  273. package/scripts/cm-live-evidence.test.mjs +59 -1
  274. package/scripts/cm-log-event.mjs +61 -10
  275. package/scripts/cm-log-event.test.mjs +121 -1
  276. package/scripts/cm-matt-skills.mjs +576 -0
  277. package/scripts/cm-matt-skills.test.mjs +550 -0
  278. package/scripts/cm-notify-command.test.mjs +42 -10
  279. package/scripts/cm-notify.mjs +14 -10
  280. package/scripts/cm-notify.test.mjs +625 -75
  281. package/scripts/cm-patrol.mjs +4 -1
  282. package/scripts/cm-patrol.test.mjs +23 -5
  283. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  284. package/scripts/cm-prd-completion.test.mjs +56 -13
  285. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  286. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  287. package/scripts/cm-prd-draft.test.mjs +1 -1
  288. package/scripts/cm-prd-drive.mjs +13 -6
  289. package/scripts/cm-prd-drive.test.mjs +46 -2
  290. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  291. package/scripts/cm-prd-host.mjs +10 -5
  292. package/scripts/cm-prd-host.test.mjs +4 -2
  293. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  294. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  295. package/scripts/cm-prd-revision.test.mjs +1 -1
  296. package/scripts/cm-prd-self-check-revision.test.mjs +16 -1
  297. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  298. package/scripts/cm-prd-self-check.test.mjs +105 -5
  299. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  300. package/scripts/cm-prd-summary.test.mjs +55 -3
  301. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  302. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  303. package/scripts/cm-refactor-drive.mjs +2 -1
  304. package/scripts/cm-refactor-drive.test.mjs +9 -0
  305. package/scripts/cm-release-smoke.sh +3 -15
  306. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  307. package/scripts/cm-skill-hints-exam.mjs +149 -0
  308. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  309. package/scripts/cm-skill-hints.exam.json +706 -0
  310. package/scripts/cm-skill-hints.json +119 -0
  311. package/scripts/cm-skill-hints.mjs +669 -0
  312. package/scripts/cm-skill-hints.test.mjs +831 -0
  313. package/scripts/cm-skill-judge.mjs +181 -0
  314. package/scripts/cm-skill-judge.test.mjs +255 -0
  315. package/scripts/cm-specs-status.test.mjs +4 -2
  316. package/scripts/cm-start-check.mjs +208 -0
  317. package/scripts/cm-start-check.test.mjs +321 -0
  318. package/scripts/cm-task-gate.mjs +150 -29
  319. package/scripts/cm-task-gate.test.mjs +73 -1
  320. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  321. package/scripts/cm-task-scope.test.mjs +308 -0
  322. package/scripts/cm-test-suite.mjs +109 -0
  323. package/scripts/cm-test-suite.test.mjs +162 -0
  324. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  325. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  326. package/scripts/cm-workflow-config.mjs +12 -2
  327. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  328. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  329. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  330. package/scripts/scan-public-safety.py +1 -0
  331. package/scripts/session-boundary.test.mjs +170 -0
  332. package/scripts/test-npm-install.py +14 -3
  333. package/scripts/test-shell-compat.sh +2 -0
  334. package/scripts/validate-public-repo.py +1 -0
  335. package/scripts/validate-test-cases.mjs +3 -2
  336. package/skills/cm-ai/SKILL.md +5 -2
  337. package/skills/cm-ai/references/N4-review.md +2 -1
  338. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  339. package/skills/cm-ai/references/N8-finish.md +22 -0
  340. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  341. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  342. package/skills/cm-ai/references/js-host.md +89 -17
  343. package/skills/cm-challenge/SKILL.md +65 -0
  344. package/skills/cm-challenge/evals/README.md +18 -0
  345. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  346. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  347. package/skills/cm-challenge/references/examples.md +15 -0
  348. package/skills/cm-check/SKILL.md +5 -0
  349. package/skills/cm-check/references/js-host.md +2 -0
  350. package/skills/cm-fix/SKILL.md +12 -3
  351. package/skills/cm-fix/references/command-correction.md +67 -0
  352. package/skills/cm-fix/references/isolated-review.md +54 -0
  353. package/skills/cm-fix/references/js-host.md +62 -2
  354. package/skills/cm-fix/references/test-type-correction.md +72 -0
  355. package/skills/cm-fix/references/verification-recovery.md +114 -0
  356. package/skills/cm-idea/SKILL.md +2 -0
  357. package/skills/cm-idea/references/js-host.md +2 -0
  358. package/skills/cm-notify/SKILL.md +2 -0
  359. package/skills/cm-prd/SKILL.md +12 -8
  360. package/skills/cm-prd/references/brownfield.md +8 -1
  361. package/skills/cm-prd/references/change-mode.md +6 -0
  362. package/skills/cm-prd/references/greenfield.md +4 -0
  363. package/skills/cm-prd/references/js-host.md +4 -2
  364. package/skills/cm-prd/references/spec-self-check.md +5 -1
  365. package/skills/cm-refactor/SKILL.md +8 -0
  366. package/skills/cm-refactor/references/js-host.md +2 -0
  367. package/skills/cm-test/SKILL.md +4 -0
  368. package/templates/dashboard/dashboard.html +2 -2
  369. package/templates/pixel/cm-pixel.html +1 -1
  370. package/templates/pixel/cm-pixel.sh +1 -1
  371. package/templates/pixel/dev/template.html +1 -1
  372. package/templates/statusline/cm-statusline.sh +1 -1
@@ -0,0 +1,123 @@
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 {createHash} from 'node:crypto';
7
+ import {stripTypeScriptTypes} from 'node:module';
8
+ const api=()=>import('../runtime/js/cm-fix/test-type-correction.mjs');
9
+ const sha=b=>createHash('sha256').update(b).digest('hex');
10
+ const source="type Layer = { props: { style?: object } };\nconst rows: Layer[] = [];\nconst styles = rows.map(c => c.props.style);\n// 保留后续 JSX 与断言字节\nconst suffix = <Button />;\n";
11
+ const record=(body=source,p='src/press-feedback.spec.tsx',mode=0o640)=>({path:p,type:'file',mode,size:Buffer.byteLength(body),sha256:sha(body),contentBase64:Buffer.from(body).toString('base64')});
12
+ const options=(file=record(),extra={})=>({file,declaration:{kind:'callback-type-annotation',path:file.path,beforeSha256:file.sha256,line:3,parameter:'c',annotation:'Layer',...extra}});
13
+ function fixture(t,file=record()){
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-test-type-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
15
+ fs.mkdirSync(path.dirname(path.join(root,file.path)),{recursive:true});fs.writeFileSync(path.join(root,file.path),Buffer.from(file.contentBase64,'base64'));
16
+ fs.chmodSync(path.join(root,file.path),file.mode);return root;
17
+ }
18
+ test('annotation preserves execution emit and all unrelated bytes, including whitespace, CRLF and Unicode',async()=>{
19
+ const {createTestTypeCorrection,inspectTestTypeCorrection}=await api();
20
+ for(const eol of ['\n','\r\n']){
21
+ const file=record(source.replaceAll('\n',eol)),c=createTestTypeCorrection(options(file));
22
+ const expected=source.replace('c =>','(c: Layer) =>').replaceAll('\n',eol);
23
+ assert.deepEqual(c.before,file);assert.equal(Buffer.from(c.after.contentBase64,'base64').toString(),expected);assert.equal(c.after.mode,file.mode);
24
+ assert.equal(c.nodeVersion,process.version);
25
+ assert.equal(c.emitSha256,sha(stripTypeScriptTypes(source.split('\n').slice(0,3).join('\n'),{mode:'transform'})));
26
+ assert.deepEqual(inspectTestTypeCorrection(c),c);
27
+ }
28
+ });
29
+ test('actual Wue-like complete typed helper prefix supports a structural callback annotation without React',async()=>{
30
+ const {createTestTypeCorrection}=await api();
31
+ const prefix="type Node = { props: { style?: object } };\nconst layers: Node[] = [];\nconst styles = layers.map(c => c.props.style);\n";
32
+ const c=createTestTypeCorrection(options(record(prefix),{annotation:'{ props: { style?: object } }'}));
33
+ const before=stripTypeScriptTypes(prefix,{mode:'transform'}),after=stripTypeScriptTypes(Buffer.from(c.after.contentBase64,'base64').toString(),{mode:'transform'});
34
+ assert.equal(before,after);assert.equal(c.emitSha256,sha(before));
35
+ });
36
+ test('an explicit line allows other callbacks elsewhere and escapes dollar identifiers exactly',async()=>{
37
+ const {createTestTypeCorrection}=await api();
38
+ const text='const first = [1].map($c => $c);\nconst second = [2].map($c\t=> $c);\n';
39
+ const c=createTestTypeCorrection(options(record(text),{line:2,parameter:'$c',annotation:'number'}));
40
+ assert.equal(Buffer.from(c.after.contentBase64,'base64').toString(),text.replace('$c\t=>','($c: number)\t=>'));
41
+ });
42
+ test('declaration rejects parameter, annotation, line, kind, binding and arbitrary fields',async()=>{
43
+ const {createTestTypeCorrection}=await api();
44
+ for(const extra of [{parameter:'c.x'},{parameter:'c)'},{annotation:''},{annotation:'any'},{annotation:'unknown'},
45
+ {annotation:'Layer as Other'},{annotation:'Layer /* @ts-ignore */'},{annotation:'Layer\n'},{annotation:'a'.repeat(257)},
46
+ {annotation:'import("types").Layer'},{annotation:'typeof rows'},{annotation:'asserts c is Layer'},
47
+ {annotation:'Layer) => { throw Error(); }; const injected = ('},{annotation:'Layer!'},
48
+ {line:0},{line:1.5},{line:99},{kind:'other'},{beforeSha256:'f'.repeat(64)},{path:'other.spec.tsx'},{extra:true}])
49
+ assert.throws(()=>createTestTypeCorrection(options(record(),extra)),undefined,JSON.stringify(extra));
50
+ });
51
+ test('incomplete statements, JSX prefixes, strings, comments, regex literals and duplicate parameters cannot be rewritten',async()=>{
52
+ const {createTestTypeCorrection}=await api();
53
+ for(const [body,line]of [
54
+ ['function outer() {\n const a = rows.map(c => c);\n}',2],
55
+ ['const a = <Button />;\nconst b = rows.map(c => c);',2],
56
+ ['const text="c => literal";',1],['// c => comment',1],['/* c => comment */',1],
57
+ ['const text=`c => template`;',1],['const re=/c => literal/;',1],
58
+ ['const x = rows.map(c => c).map(c => c);',1],['const x=rows.map((c) => c);',1],
59
+ ['const x=rows.map((c: Layer) => c);',1],['const x=rows.map(notc => notc);',1],
60
+ ['const x=rows.map(λc => λc);',1],['/*\nc => comment\n*/',2],['const x=`\nc => template\n`;',2],
61
+ ["type Label = 'c => string';",1]
62
+ ])assert.throws(()=>createTestTypeCorrection(options(record(body),{line})),undefined,body);
63
+ });
64
+ test('only safe test suffixes are accepted; full records and exact derived output bind inspection',async()=>{
65
+ const {createTestTypeCorrection,inspectTestTypeCorrection}=await api();
66
+ for(const p of ['src/value.ts','src/value.tsx','../value.spec.ts','/value.test.ts','.claude/value.test.ts','node_modules/value.test.ts','AGENTS.md','src/value.spec.ts/other.ts'])
67
+ assert.throws(()=>createTestTypeCorrection(options(record(source,p))),undefined,p);
68
+ for(const p of ['a.spec.ts','a.spec.tsx','a.test.ts','a.test.tsx'])assert.equal(createTestTypeCorrection(options(record(source,p))).path,p);
69
+ const c=createTestTypeCorrection(options());
70
+ for(const mutate of [x=>x.after=record(Buffer.from(x.after.contentBase64,'base64').toString().replace('c.props.style','null')),
71
+ x=>x.after.mode=0o600,x=>x.emitSha256='f'.repeat(64),x=>x.nodeVersion='v24.0.0',x=>x.line=2,x=>x.annotation='number',x=>x.extra=true]){
72
+ const copy=structuredClone(c);mutate(copy);assert.throws(()=>inspectTestTypeCorrection(copy));
73
+ }
74
+ const malformed=record();malformed.size++;assert.throws(()=>createTestTypeCorrection(options(malformed)));
75
+ });
76
+ test('atomic apply preserves file mode, verifies exact before and supports already_applied replay',async t=>{
77
+ const {createTestTypeCorrection,applyTestTypeCorrection,readTestTypeCorrectionFile}=await api();
78
+ const c=createTestTypeCorrection(options()),root=fixture(t);
79
+ assert.deepEqual(readTestTypeCorrectionFile({root,path:c.path}),c.before);
80
+ assert.equal(applyTestTypeCorrection({root,correction:c}).outcome,'applied');
81
+ assert.deepEqual(readTestTypeCorrectionFile({root,path:c.path}),c.after);
82
+ assert.equal(applyTestTypeCorrection({root,correction:c}).outcome,'already_applied');
83
+ fs.chmodSync(path.join(root,c.path),0o600);assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
84
+ fs.writeFileSync(path.join(root,c.path),'changed');assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
85
+ });
86
+ test('read and apply reject root/parent/file symlinks and hardlinked files',async t=>{
87
+ const {createTestTypeCorrection,applyTestTypeCorrection,readTestTypeCorrectionFile}=await api();
88
+ const c=createTestTypeCorrection(options()),root=fixture(t),parent=path.join(root,'src'),target=path.join(root,c.path);
89
+ fs.symlinkSync(root,root+'-link');t.after(()=>fs.unlinkSync(root+'-link'));
90
+ assert.throws(()=>readTestTypeCorrectionFile({root:root+'-link',path:c.path}));
91
+ fs.renameSync(parent,parent+'-real');fs.symlinkSync('src-real',parent);assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
92
+ fs.unlinkSync(parent);fs.renameSync(parent+'-real',parent);fs.renameSync(target,target+'.original');fs.symlinkSync('press-feedback.spec.tsx.original',target);
93
+ assert.throws(()=>applyTestTypeCorrection({root,correction:c}));fs.unlinkSync(target);fs.renameSync(target+'.original',target);
94
+ fs.linkSync(target,target+'.link');assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
95
+ });
96
+ test('rename failure and post-fsync source drift cannot lose source or leave a temporary file',async t=>{
97
+ const {createTestTypeCorrection,applyTestTypeCorrection}=await api(),c=createTestTypeCorrection(options());
98
+ for(const change of ['rename','drift']){
99
+ const root=fixture(t),directory=path.join(root,'src'),target=path.join(root,c.path),rename=fs.renameSync,sync=fs.fsyncSync;let touched=false;
100
+ try{
101
+ if(change==='rename')fs.renameSync=()=>{throw Object.assign(new Error('fixture'),{code:'EIO'});};
102
+ else fs.fsyncSync=fd=>{sync(fd);if(!touched){touched=true;fs.writeFileSync(target,'concurrent bytes');}};
103
+ assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
104
+ }finally{fs.renameSync=rename;fs.fsyncSync=sync;}
105
+ assert.equal(fs.readFileSync(target,'utf8'),change==='rename'?source:'concurrent bytes');assert.deepEqual(fs.readdirSync(directory),['press-feedback.spec.tsx']);
106
+ }
107
+ });
108
+ test('temporary content or mode replacement is rejected before renaming over the source',async t=>{
109
+ const {createTestTypeCorrection,applyTestTypeCorrection}=await api(),c=createTestTypeCorrection(options());
110
+ for(const change of ['bytes','mode','link']){
111
+ const root=fixture(t),directory=path.join(root,'src'),sync=fs.fsyncSync;let touched=false;
112
+ try{
113
+ fs.fsyncSync=fd=>{sync(fd);if(touched)return;touched=true;
114
+ const temporary=path.join(directory,fs.readdirSync(directory).find(n=>n.startsWith('.cm-test-type-')));
115
+ if(change==='bytes')fs.appendFileSync(temporary,'injected');
116
+ else if(change==='mode')fs.chmodSync(temporary,0o600);
117
+ else{fs.unlinkSync(temporary);fs.symlinkSync('press-feedback.spec.tsx',temporary);}
118
+ };
119
+ assert.throws(()=>applyTestTypeCorrection({root,correction:c}));
120
+ }finally{fs.fsyncSync=sync;}
121
+ assert.equal(fs.readFileSync(path.join(root,c.path),'utf8'),source);assert.deepEqual(fs.readdirSync(directory),['press-feedback.spec.tsx']);
122
+ }
123
+ });
@@ -0,0 +1,208 @@
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 {createHash} from 'node:crypto';
7
+ import {pathToFileURL,fileURLToPath} from 'node:url';
8
+ import {spawnSync} from 'node:child_process';
9
+ import * as execution from '../runtime/js/cm-fix/execution.mjs';
10
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
12
+ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
13
+ import {fixFinalReviewConfiguration} from '../runtime/js/cm-fix/final-review.mjs';
14
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
15
+ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
16
+ import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
17
+
18
+ const sha=value=>createHash('sha256').update(value).digest('hex');
19
+ const annotation='{ props: { pointerEvents?: string; accessible?: boolean } }';
20
+ const DRIVER=fileURLToPath(new URL('./cm-fix-drive.mjs',import.meta.url));
21
+ const INSPECT=fileURLToPath(new URL('./cm-fix-test-type-correction.mjs',import.meta.url));
22
+ async function fixture(t,{commandCorrection=false}={}){
23
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-test-type-owner-'))),cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');
24
+ fs.mkdirSync(path.join(cwd,'app/node_modules/typescript/bin'),{recursive:true});fs.mkdirSync(specsRoot);
25
+ fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:'both'},roles:{coder:{adapter:'codex-cli'},reviewer:{adapter:'claude-cli'}},policies:{delivery:'diff'}}));
26
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;\n');
27
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1);\n");
28
+ fs.writeFileSync(path.join(cwd,'reproduce.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('TARGET BUG');process.exit(1);}\n");
29
+ const testPath='app/button.spec.ts',source=[
30
+ "import assert from 'node:assert/strict';",
31
+ `import {value} from ${JSON.stringify(pathToFileURL(path.join(cwd,'value.mjs')).href)};`,
32
+ "const layers = (button: { findAll: Function }) => button.findAll(n => n.props.pointerEvents === 'none' && n.props.accessible === false);",
33
+ "assert.equal(value,2,'TARGET BUG');",''].join('\n');
34
+ fs.writeFileSync(path.join(cwd,'app/foreign.spec.ts'),source);
35
+ // Synthetic local checker: this fixture scans the exact annotation; it is NOT a TypeScript compiler.
36
+ fs.writeFileSync(path.join(cwd,'app/node_modules/typescript/bin/tsc'),`const fs=require('node:fs');if(!fs.readFileSync('app/button.spec.ts','utf8').includes(${JSON.stringify(`(n: ${annotation}) =>`)})){console.error("app/button.spec.ts(3,62): error TS7006: Parameter 'n' implicitly has an 'any' type.");process.exit(2);}`);
37
+ const identity={repositoryId:'fixture',runId:'test-type-owner',taskId:'T-FIX-typing',attempt:1};
38
+ // Synthetic preflight and review worker are fixture wiring only, never real provider readiness.
39
+ const reviewConfig={model:'synthetic',disabledSkills:[],preflight:{passed:true,provider:'claude',prompt_transport:'stdin',config_fingerprint:claudeReviewFingerprint({cwd,model:'synthetic'})}};
40
+ const reviewer=createFixReviewHost({codeProject:cwd,hostContextId:'fixture-author',runtime:'codex',reviewRuntime:'claude',review:reviewConfig}).reviewer;
41
+ const configuration={hostContextId:'fixture-author',reviewRuntime:'claude',defect:'Wrong constant and an authored test has missing callback type',
42
+ causeReview:reviewer,
43
+ reproduction:{cwd,command:[process.execPath,'reproduce.mjs'],expectedFailure:{exitCode:1,outputIncludes:'TARGET BUG'},timeoutMs:3000},
44
+ testAuthor:{requirements:['value.mjs']},
45
+ redTest:{cwd,testFiles:[testPath],command:[process.execPath,testPath],expectedFailure:{exitCode:1,outputIncludes:'TARGET BUG'},timeoutMs:3000},
46
+ baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']},{id:'types',command:[process.execPath,'app/node_modules/typescript/bin/tsc','--noEmit','--project','app/tsconfig.json']}],timeoutMs:3000},
47
+ repair:{scope:['value.mjs'],requirements:['value.mjs']},
48
+ walkthrough:{timeoutMs:3000,flows:[{id:'constant',modules:['constant'],kind:'commands',steps:['Execute the authored assertion'],expected:['value equals 2'],command:[process.execPath,testPath]}]}};
49
+ fs.writeFileSync(path.join(cwd,'app/tsconfig.json'),'{}');
50
+ if(commandCorrection){
51
+ fs.mkdirSync(path.join(cwd,'app/node_modules/jest/bin'),{recursive:true});
52
+ fs.writeFileSync(path.join(cwd,'app/package.json'),JSON.stringify({jest:{}}));
53
+ const launcher='app/node_modules/jest/bin/jest.js';
54
+ // Configuration-discovery fixture only, not an actual Jest installation.
55
+ fs.writeFileSync(path.join(cwd,launcher),String.raw`if(!process.argv.includes('--config')){console.error('Error: Could not find a config file based on provided values:\ncwd: "'+process.cwd()+'"');process.exit(1)}import(require('node:url').pathToFileURL(process.cwd()+'/app/button.spec.ts').href);`);
56
+ const command=[process.execPath,launcher,'--rootDir','app','--runTestsByPath',testPath];
57
+ configuration.redTest.command=command;configuration.walkthrough.flows[0].command=command;
58
+ }
59
+
60
+ const learning={contextDigest:digest([]),files:[],application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'Fixture'}};
61
+ const capabilities={prepare:async()=>learning,assertReviewReady(){},bridge:{async call(kind){
62
+ if(kind==='fix_diagnose')return {status:'diagnosed',rootCause:'Wrong constant',affectedPaths:['value.mjs'],affectedModules:['constant'],plan:'Set value to 2',crossLayer:false,investigation:{discardedAlternatives:[],boundaryAnalysis:null}};
63
+ if(kind==='fix_test_author'){fs.writeFileSync(path.join(cwd,testPath),source);return {outcome:'authored'};}
64
+ if(kind==='fix_repair'){fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=2;\n');return {outcome:'repaired'};}
65
+ assert.equal(kind,'fix_retrospective');return {status:'no_new_lesson',candidates:[],reason:null};
66
+ }}};
67
+ const options={specsRoot,identity,configuration};let owner=execution.openFixExecution({...options,create:true},capabilities);
68
+ t.after(()=>{owner.close();fs.rmSync(root,{recursive:true,force:true});});
69
+ startFixRun(options);assert.equal((await owner.advance({authorized:true})).stage,'test_author_required');
70
+ assert.equal((await owner.authorTests({authorized:true})).stage,'red_test_required');
71
+ let commandAudit=null;
72
+ if(commandCorrection){
73
+ assert.equal((await owner.runRedTest({authorized:true})).stage,'red_test_not_confirmed');
74
+ const before=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews/.execution',identity.runId,'state.json'))),red=owner.status().redTest;
75
+ commandAudit={before,output:red.output,bytes:fs.readFileSync(path.join(specsRoot,red.output.path))};
76
+ const declaration={kind:'jest-config-path',path:'app/package.json'},expected=owner.inspectCommandCorrection({declaration});
77
+ assert.equal(owner.prepareCommandCorrection({authorized:true,expected,declaration,previousInvocationStopped:true,reason:'Add only existing Jest configuration path'}).stage,'red_test_required');
78
+ }
79
+ assert.equal((await owner.runRedTest({authorized:true})).stage,'baseline_required');
80
+ assert.equal((await owner.captureBaseline({authorized:true})).stage,'repair_required');
81
+ assert.equal((await owner.repair({authorized:true})).stage,'regression_required');
82
+ assert.equal((await owner.runRegression({authorized:true})).stage,'regression_blocked');
83
+ assert.equal(owner.status().regression.status,'inconclusive');assert.equal(owner.status().baseline.observations[1].exitCode,2);
84
+ const statePath=path.join(specsRoot,'.reviews/.execution',identity.runId,'state.json');
85
+ return {root,cwd,specsRoot,identity,configuration,reviewConfig,options,source,testPath,commandAudit,statePath,state:()=>JSON.parse(fs.readFileSync(statePath)),
86
+ declaration:{kind:'callback-type-annotation',path:testPath,beforeSha256:sha(source),line:3,parameter:'n',annotation},
87
+ get owner(){return owner;},reopen(extra={}){owner.close();owner=execution.openFixExecution({...options,create:false},{...capabilities,...extra});return owner;}};
88
+ }
89
+ const input=(f,expected)=>({authorized:true,expected,declaration:f.declaration,previousInvocationStopped:true,reason:'Add only the authored callback parameter type'});
90
+
91
+ for(const commandCorrection of [false,true])test(`${commandCorrection?'combined command and type corrections: ':''}owner typing correction retains original red/repair and reaches reviewed complete after real local command reruns`,async t=>{
92
+ const f=await fixture(t,{commandCorrection}),before=f.state(),red=f.owner.status().redTest,rawRed=fs.readFileSync(path.join(f.specsRoot,red.output.path));
93
+ const expected=f.owner.inspectTestTypeCorrection({declaration:f.declaration});assert.deepEqual(f.state(),before);
94
+ assert.equal((await f.owner.prepareTestTypeCorrection(input(f,expected))).stage,'regression_blocked');
95
+ const corrected=fs.readFileSync(path.join(f.cwd,f.testPath),'utf8');
96
+ assert.equal(corrected,f.source.replace('findAll(n =>',`findAll((n: ${annotation}) =>`));
97
+ assert.deepEqual(f.state().records.slice(0,before.records.length),before.records);assert.deepEqual(f.state().fingerprints,before.fingerprints);
98
+ assert.deepEqual(fs.readFileSync(path.join(f.specsRoot,red.output.path)),rawRed);
99
+ assert.equal(f.reopen().status().stage,'regression_blocked');
100
+ assert.equal(f.owner.rerunBlockedStep({authorized:true,reason:'Recheck the original commands after bound type-only correction'}).stage,'regression_required');
101
+ assert.equal((await f.owner.runRegression({authorized:true})).stage,'handoff_required');
102
+ assert.equal(f.owner.status().regression.baseline.observations[1].outcome,'passed');
103
+ assert.equal(f.owner.status().regression.comparison.comparisons[1].status,'now_passed');
104
+ assert.equal((await f.owner.retrospect()).stage,'handoff_ready');assert.equal(f.owner.createHandoff().stage,'final_review_required');
105
+ const pkg=f.owner.finalReviewPackage(),changed=pkg.changes.find(c=>c.path===f.testPath);
106
+ assert.ok(changed);assert.equal(Buffer.from(changed.after.contentBase64,'base64').toString(),corrected);
107
+ const handoff=JSON.parse(Buffer.from(pkg.handoff.contentBase64,'base64').toString());assert.ok(handoff.evidence.some(e=>/type.*correction|typing.*correction/i.test(e)));
108
+ const cfg=fixFinalReviewConfiguration(f.configuration),authority=createHostReviewAuthority({hostContextId:cfg.hostContextId,reviewerId:cfg.reviewer.reviewerId,adapterId:cfg.reviewer.adapterId,decide:async()=>({status:'approved'})});
109
+ await authority.hostDecisionProvider.decide({identity:pkg.identity,packageDigest:pkg.packageDigest},new AbortController().signal);
110
+ let calls=0;f.reopen({finalReview:{authorize:authority.authorize,async run(request,{onEvent}){
111
+ calls++;assert.equal(request.provider,'claude');for(const e of [{event:'thread.started',provider_thread:'synthetic-type-review'},{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])assert.equal(onEvent(e),true);
112
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic fixture only; no actual Claude call'}};
113
+ }}});
114
+ assert.equal((await f.owner.reviewFinal()).stage,'final_review_evidence_required');assert.equal(f.owner.publishReview().stage,'completion_gate_required');
115
+ assert.equal(f.owner.checkCompletionGate().stage,'post_review_regression_required');
116
+ assert.equal((await f.owner.runRegression({authorized:true,postReview:true})).stage,'closeout_required');
117
+ assert.equal((await f.reopen().runWalkthrough({authorized:true})).stage,'closeout_required');assert.equal(f.owner.status().walkthrough.status,'passed');
118
+ const pending=f.owner.finish({authorized:true,cooperative:true});assert.ok(pending instanceof Promise);
119
+ assert.throws(()=>f.owner.finish({authorized:true}),{code:'fix_busy'});
120
+ assert.throws(()=>f.owner.checkCompletionGate(),{code:'fix_busy'});
121
+ const done=await pending;assert.equal(done.stage,'completed');assert.equal(done.completionEligible,true);assert.equal(calls,1);
122
+ assert.equal((await f.owner.finish({authorized:true,cooperative:true})).stage,'completed');
123
+ assert.equal(f.reopen().completionEvidence().identity.runId,f.identity.runId);assert.deepEqual(fs.readFileSync(path.join(f.specsRoot,red.output.path)),rawRed);
124
+ if(f.commandAudit){
125
+ assert.deepEqual(f.state().records.slice(0,f.commandAudit.before.records.length),f.commandAudit.before.records);
126
+ assert.deepEqual(f.state().fingerprints,f.commandAudit.before.fingerprints);
127
+ assert.deepEqual(fs.readFileSync(path.join(f.specsRoot,f.commandAudit.output.path)),f.commandAudit.bytes);
128
+ assert.equal(f.state().records.filter(r=>r.id==='fix-command-correction').length,1);
129
+ assert.equal(f.state().records.filter(r=>r.id==='fix-test-type-correction-result').length,1);
130
+ assert.match(f.owner.status().redTest.output.path,/-retry-1\.md$/);
131
+ }
132
+
133
+ });
134
+
135
+ test('read-only typing preview exists and unauthorized/stale/foreign declarations cannot write or advance',async t=>{
136
+ const f=await fixture(t),before=f.state();assert.equal(typeof execution.inspectFixTestTypeCorrection,'function');
137
+ const expected=f.owner.inspectTestTypeCorrection({declaration:f.declaration});
138
+ assert.deepEqual(execution.inspectFixTestTypeCorrection({specsRoot:f.specsRoot,identity:{repositoryId:f.identity.repositoryId,runId:f.identity.runId},declaration:f.declaration}),expected);
139
+ assert.deepEqual(f.state(),before);
140
+ for(const override of [{authorized:false},{previousInvocationStopped:false},{reason:''},{expected:{...expected,historyDigest:digest('stale')}}]){
141
+ await assert.rejects(Promise.resolve().then(()=>f.owner.prepareTestTypeCorrection({...input(f,expected),...override})));
142
+ assert.deepEqual(f.state(),before);assert.equal(fs.readFileSync(path.join(f.cwd,f.testPath),'utf8'),f.source);
143
+ }
144
+ for(const declaration of [{...f.declaration,path:'existing.mjs'},{...f.declaration,path:'app/foreign.spec.ts'},{...f.declaration,annotation:'any'},{...f.declaration,annotation:'unknown'},{...f.declaration,line:4},{...f.declaration,parameter:'other'}]){
145
+ await assert.rejects(Promise.resolve().then(()=>f.owner.inspectTestTypeCorrection({declaration})));assert.deepEqual(f.state(),before);
146
+ }
147
+ await f.owner.prepareTestTypeCorrection(input(f,expected));const after=f.state();
148
+ await assert.rejects(Promise.resolve().then(()=>f.owner.inspectTestTypeCorrection({declaration:f.declaration})));
149
+ assert.deepEqual(f.state(),after);
150
+ });
151
+
152
+ test('real typing inspector and driver preserve frozen config and require separate preparation authority',async t=>{
153
+ const f=await fixture(t),before=f.state();f.owner.close();
154
+ const config=path.join(f.root,'config.json'),declarationFile=path.join(f.root,'declaration.json'),review=path.join(f.root,'review.json'),plan=path.join(f.root,'plan.json');
155
+ const {hostContextId,causeReview,reviewRuntime,...configuration}=f.configuration;
156
+ fs.writeFileSync(config,JSON.stringify({...configuration,specsRoot:f.specsRoot,identity:f.identity}));
157
+ fs.writeFileSync(declarationFile,JSON.stringify(f.declaration));fs.writeFileSync(review,JSON.stringify(f.reviewConfig));
158
+ const configBytes=fs.readFileSync(config),cli=args=>spawnSync(process.execPath,args,{encoding:'utf8',timeout:30000,env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
159
+ const preview=cli([INSPECT,'--config',config,'--declaration',declarationFile]);assert.equal(preview.status,0,preview.stdout+preview.stderr);
160
+ const expected=JSON.parse(preview.stdout).expected;assert.deepEqual(f.state(),before);assert.equal(fs.readFileSync(path.join(f.cwd,f.testPath),'utf8'),f.source);
161
+ const base={config,cwd:f.cwd,mode:'resume',hostContext:hostContextId,runtime:'codex',reviewRuntime,reviewConfig:review,testTypeCorrection:f.declaration,previousInvocationStopped:true,expected,reason:'Explicit parameter-only type correction'};
162
+ const drive=(permissions,extra={})=>{fs.writeFileSync(plan,JSON.stringify({...base,permissions,...extra}));return cli([DRIVER,'--plan',plan,'prepare_test_type_correction']);};
163
+ for(const [permissions,extra]of [[[],{}],[['--allow-test-type-correction'],{previousInvocationStopped:false}],[['--allow-test-type-correction'],{mode:'create'}]]){
164
+ const rejected=drive(permissions,extra);assert.notEqual(rejected.status,0);assert.deepEqual(f.state(),before);assert.equal(fs.readFileSync(path.join(f.cwd,f.testPath),'utf8'),f.source);
165
+ }
166
+ const prepared=drive(['--allow-test-type-correction']);assert.equal(prepared.status,0,prepared.stdout+prepared.stderr);assert.match(prepared.stdout,/regression_blocked/);
167
+ const after=f.state();assert.deepEqual(after.records.slice(0,before.records.length),before.records);assert.deepEqual(after.fingerprints,before.fingerprints);assert.deepEqual(fs.readFileSync(config),configBytes);
168
+ const used=cli([INSPECT,'--config',config,'--declaration',declarationFile]);assert.notEqual(used.status,0);assert.deepEqual(f.state(),after);
169
+ f.reopen();assert.equal(f.owner.rerunBlockedStep({authorized:true,reason:'Original command rerun after official typing preparation'}).stage,'regression_required');
170
+ assert.equal((await f.owner.runRegression({authorized:true})).stage,'handoff_required');
171
+ });
172
+
173
+ test('typing qualification refuses changed assertions or unrelated repaired-source drift',async t=>{
174
+ const f=await fixture(t),before=f.state(),expected=f.owner.inspectTestTypeCorrection({declaration:f.declaration});
175
+ const target=path.join(f.cwd,f.testPath);fs.writeFileSync(target,f.source.replace('assert.equal(value,2','assert.equal(value,1'));
176
+ await assert.rejects(Promise.resolve().then(()=>f.owner.prepareTestTypeCorrection(input(f,expected))));assert.deepEqual(f.state(),before);
177
+ fs.writeFileSync(target,f.source);const product=path.join(f.cwd,'value.mjs'),good=fs.readFileSync(product);fs.appendFileSync(product,'// unexpected drift\n');
178
+ await assert.rejects(Promise.resolve().then(()=>f.owner.prepareTestTypeCorrection(input(f,expected))));assert.deepEqual(f.state(),before);
179
+ fs.writeFileSync(product,good);assert.equal(f.owner.status().stage,'regression_blocked');
180
+ });
181
+
182
+ for(const when of ['before','after'])test(`typing intent resumes exact ${when} image after interrupted atomic write`,async t=>{
183
+ const f=await fixture(t),before=f.state(),expected=f.owner.inspectTestTypeCorrection({declaration:f.declaration}),target=path.join(f.cwd,f.testPath);
184
+ const rename=fs.renameSync;let interrupted=false;
185
+ fs.renameSync=(from,to)=>{
186
+ if(to===target&&!interrupted){interrupted=true;if(when==='before')throw Object.assign(new Error('fixture interruption before source rename'),{code:'fixture_interruption'});rename(from,to);throw Object.assign(new Error('fixture interruption after source rename'),{code:'fixture_interruption'});}
187
+ return rename(from,to);
188
+ };
189
+ try{try{await f.owner.prepareTestTypeCorrection(input(f,expected));}catch{/* Expected interruption; inspect the durable intent below. */}}
190
+ finally{fs.renameSync=rename;}
191
+ assert.equal(interrupted,true);const pending=f.state();assert.deepEqual(pending.records.slice(0,before.records.length),before.records);
192
+ assert.equal(pending.records.filter(r=>r.id==='fix-test-type-correction-intent').length,1);
193
+ assert.equal(pending.records.some(r=>r.id==='fix-test-type-correction-result'),false);
194
+ const image=fs.readFileSync(target,'utf8');assert.equal(image,when==='before'?f.source:f.source.replace('findAll(n =>',`findAll((n: ${annotation}) =>`));
195
+ assert.equal(f.reopen().status().stage,'unknown');
196
+ for(const override of [{previousInvocationStopped:false},{reason:'different reason'},{declaration:{...f.declaration,annotation:'number'}},{expected:{...expected,historyDigest:digest('stale')}}]){
197
+ await assert.rejects(Promise.resolve().then(()=>f.owner.prepareTestTypeCorrection({...input(f,expected),...override})));assert.deepEqual(f.state(),pending);assert.equal(fs.readFileSync(target,'utf8'),image);
198
+ }
199
+ fs.appendFileSync(target,'// third image is never a recovery authority\n');
200
+ await assert.rejects(Promise.resolve().then(()=>f.owner.prepareTestTypeCorrection(input(f,expected))));assert.deepEqual(f.state(),pending);
201
+ fs.writeFileSync(target,image);
202
+ assert.equal((await f.owner.prepareTestTypeCorrection(input(f,expected))).stage,'regression_blocked');
203
+ assert.equal(f.state().records.filter(r=>r.id==='fix-test-type-correction-intent').length,1);
204
+ assert.equal(f.state().records.filter(r=>r.id==='fix-test-type-correction-result').length,1);
205
+ assert.deepEqual(f.state().fingerprints,before.fingerprints);
206
+ assert.equal(f.owner.rerunBlockedStep({authorized:true,reason:'Recheck unchanged runtime assertions'}).stage,'regression_required');
207
+ assert.equal((await f.owner.runRegression({authorized:true})).stage,'handoff_required');
208
+ });
@@ -0,0 +1,66 @@
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 nodeModule,{syncBuiltinESMExports} from 'node:module';
7
+ import {captureReviewBaseline,readReviewSourceFiles} from '../runtime/js/cm-ai/review-package.mjs';
8
+ import {verifyFixRepair} from '../runtime/js/cm-fix/repair.mjs';
9
+ import {createTestTypeCorrection} from '../runtime/js/cm-fix/test-type-correction.mjs';
10
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
11
+
12
+ function fixture(t,count){
13
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'type-proof-cost-'))),codeProject=path.join(root,'code'),specsRoot=path.join(root,'specs');
14
+ fs.mkdirSync(codeProject);fs.mkdirSync(specsRoot);t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
15
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
16
+ const file='layers.spec.ts',source='const rows: { props: { style?: object } }[] = [];\nconst layers = rows.map(n => n.props.style);\n';
17
+ fs.writeFileSync(path.join(codeProject,file),source);
18
+ for(let i=0;i<count;i++)fs.writeFileSync(path.join(codeProject,`outside-${i}.txt`),`unchanged ${i}`);
19
+ const identity={repositoryId:'fixture',runId:'proof-cost',taskId:'T-FIX-cost',attempt:1};
20
+ const capture=()=>captureReviewBaseline({root:codeProject,specsRoot,identity,scope:['value.mjs'],requirements:['value.mjs']});
21
+ const baseline=capture(),[before]=readReviewSourceFiles(codeProject,[file]);
22
+ const correction=createTestTypeCorrection({file:before,declaration:{kind:'callback-type-annotation',path:file,beforeSha256:before.sha256,line:2,parameter:'n',annotation:'{ props: { style?: object } }'}});
23
+ fs.writeFileSync(path.join(codeProject,file),Buffer.from(correction.after.contentBase64,'base64'));
24
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=2;');
25
+ const files=capture().files.filter(f=>f.path==='value.mjs').map(({contentBase64,...metadata})=>metadata);
26
+ return {codeProject,specsRoot,baseline,result:{outcome:'repaired',baselineDigest:baseline.baselineDigest,changedFiles:['value.mjs'],files,completionEligible:false},testTypeCorrection:correction};
27
+ }
28
+ function countStrips(run){
29
+ const original=nodeModule.stripTypeScriptTypes;let calls=0;
30
+ nodeModule.stripTypeScriptTypes=(...args)=>{calls++;return original(...args);};syncBuiltinESMExports();
31
+ try{run();return calls;}finally{nodeModule.stripTypeScriptTypes=original;syncBuiltinESMExports();}
32
+ }
33
+
34
+ test('repair proof validates once per verification irrespective of unrelated inventory size',t=>{
35
+ const small=fixture(t,0),large=fixture(t,160);
36
+ assert.ok(large.baseline.files.length-small.baseline.files.length>=160);
37
+ const counts=[small,large].map(options=>countStrips(()=>verifyFixRepair(options)));
38
+ assert.deepEqual(counts,[3,3],'one proof has three exact Node stripping checks; unrelated files must not multiply proof validation');
39
+ assert.equal(countStrips(()=>verifyFixRepair(large)),3,'a new verification revalidates the proof; no cross-call cache');
40
+ });
41
+
42
+ test('bounded proof cost keeps current disk drift and altered-proof rejection',t=>{
43
+ const options=fixture(t,64);
44
+ assert.equal(countStrips(()=>verifyFixRepair(options)),3);
45
+ const target=path.join(options.codeProject,'outside-0.txt');fs.writeFileSync(target,'unexpected unrelated change');
46
+ assert.throws(()=>verifyFixRepair(options),{code:'out_of_scope'});
47
+ fs.writeFileSync(target,'unchanged 0');
48
+ const c=structuredClone(options.testTypeCorrection);c.emitSha256='f'.repeat(64);
49
+ assert.throws(()=>verifyFixRepair({...options,testTypeCorrection:c}));
50
+ fs.appendFileSync(path.join(options.codeProject,options.testTypeCorrection.path),'// unapproved test drift');
51
+ assert.throws(()=>verifyFixRepair(options),{code:'out_of_scope'});
52
+ });
53
+
54
+ test('final review handler reads one stage snapshot and yields before granting, retaining later owner verification',async()=>{
55
+ let statuses=0,packages=0,decisions=0,reviews=0,immediateRan=false;
56
+ const pkg={identity:{repositoryId:'fixture',runId:'host-cost',taskId:'T-FIX-cost',attempt:1},packageDigest:'a'.repeat(64)};
57
+ const owner={status(){statuses++;return {stage:'final_review_required'};},finalReviewPackage(){packages++;return pkg;},reviewFinal(options){reviews++;assert.deepEqual(options,{verificationRecoveryAuthorization:null});return {stage:'final_review_evidence_required'};}};
58
+ const authority={hostDecisionProvider:{async decide(binding){decisions++;assert.deepEqual(binding,{identity:pkg.identity,packageDigest:pkg.packageDigest});assert.equal(immediateRan,true,'event-loop work queued before the handler must run before a grant');}}};
59
+ const host=createFixHost({owner,config:{},finalAuthority:authority});
60
+ setImmediate(()=>{immediateRan=true;});
61
+ const pending=host.handle({requestId:'final',operation:'final_review'});
62
+ const decisionsBeforeYield=decisions;
63
+ assert.equal((await pending).stage,'final_review_evidence_required');
64
+ assert.equal(decisionsBeforeYield,0,'no grant is issued in the initial synchronous projection interval');
65
+ assert.equal(statuses,1);assert.equal(packages,1);assert.equal(decisions,1);assert.equal(reviews,1);
66
+ });
@@ -0,0 +1,95 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {createHash} from 'node:crypto';
7
+ import {spawnSync} from 'node:child_process';
8
+ const api=()=>import('../runtime/js/cm-fix/type-import-correction.mjs');
9
+ const sha=b=>createHash('sha256').update(b).digest('hex');
10
+ const source="import { Marker, value } from './types.ts';\nconst result: Marker = value;\nif(result!==7)throw new Error('value changed');\n";
11
+ const record=(body=source,p='main.ts',mode=0o640)=>({path:p,type:'file',mode,size:Buffer.byteLength(body),sha256:sha(body),contentBase64:Buffer.from(body).toString('base64')});
12
+ const options=(file=record())=>({file,declaration:{kind:'type-import-split',path:file.path,beforeSha256:file.sha256,typeNames:['Marker']},scope:[file.path],
13
+ verification:{files:[file.path],checks:[{id:'unit',command:['node','main.ts']}],mutationPaths:[file.path],timeoutMs:1000},
14
+ reviewPackage:{packageDigest:'a'.repeat(64),files:[file]}});
15
+ function fixture(t,file=record()){
16
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-type-import-')));
17
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
18
+ fs.mkdirSync(path.dirname(path.join(root,file.path)),{recursive:true});
19
+ fs.writeFileSync(path.join(root,file.path),Buffer.from(file.contentBase64,'base64'));fs.chmodSync(path.join(root,file.path),file.mode);
20
+ return root;
21
+ }
22
+ test('split retains module, names, mode and all non-import bytes',async()=>{
23
+ const {createTypeImportCorrection,inspectTypeImportCorrection}=await api();
24
+ for(const eol of ['\n','\r\n']){
25
+ const input=record(source.replaceAll('\n',eol)),c=createTypeImportCorrection(options(input));
26
+ assert.deepEqual(c.before,input);assert.equal(c.after.mode,input.mode);
27
+ assert.equal(Buffer.from(c.after.contentBase64,'base64').toString(),`import type { Marker } from './types.ts';${eol}import { value } from './types.ts';${eol}`+source.split('\n').slice(1).join(eol));
28
+ assert.deepEqual(inspectTypeImportCorrection(c),c);
29
+ }
30
+ });
31
+ test('complex, ambiguous and non-code import shapes are refused',async()=>{
32
+ const {createTypeImportCorrection}=await api();
33
+ for(const line of ["import { Marker as M, value } from './types.ts';", "import { Marker, /* note */ value } from './types.ts';", "import { Marker,\nvalue } from './types.ts';", "import defaultValue, { Marker, value } from './types.ts';", "import * as values from './types.ts';", "import type { Marker, value } from './types.ts';", "import { type Marker, value } from './types.ts';", "import { Marker, value } from './types.ts'", "import { Marker, value } from './types.ts' with { type: 'json' };", "/*\nimport { Marker, value } from './types.ts';\n*/", "const text=`\nimport { Marker, value } from './types.ts';\n`;", "import { Marker, Marker, value } from './types.ts';"])
34
+ assert.throws(()=>createTypeImportCorrection(options(record(line+'\n'))),undefined,line);
35
+ });
36
+ test('type names must be an explicit unique nonempty proper subset',async()=>{
37
+ const {createTypeImportCorrection}=await api();
38
+ for(const names of [[],['Marker','Marker'],['unknown'],['Marker','value'],['Marker as M'],['类型']]){
39
+ const o=options();o.declaration.typeNames=names;assert.throws(()=>createTypeImportCorrection(o));
40
+ }
41
+ });
42
+ test('scope, verification lists, package snapshot and declaration bind the file',async()=>{
43
+ const {createTypeImportCorrection}=await api();
44
+ for(const change of [o=>o.scope=['other.ts'],o=>o.verification.files=['other.ts'],o=>o.verification.mutationPaths=['other.ts'],o=>o.reviewPackage.files=[],o=>o.reviewPackage.files=[record('different')],o=>o.declaration.beforeSha256='f'.repeat(64),o=>o.declaration.path='other.ts']){
45
+ const o=options();change(o);assert.throws(()=>createTypeImportCorrection(o));
46
+ }
47
+ assert.throws(()=>createTypeImportCorrection(options(record(source,'types.d.ts'))));
48
+ });
49
+ test('inspection rederives after and refuses body, mode or metadata tampering',async()=>{
50
+ const {createTypeImportCorrection,inspectTypeImportCorrection}=await api();
51
+ const c=createTypeImportCorrection(options());
52
+ for(const change of [x=>x.after=record(Buffer.from(x.after.contentBase64,'base64').toString().replace('!==7','!==8')),x=>x.after.mode=0o600,x=>x.path='other.ts',x=>x.typeNames=['value'],x=>x.extra=true]){
53
+ const x=structuredClone(c);change(x);assert.throws(()=>inspectTypeImportCorrection(x));
54
+ }
55
+ });
56
+ test('atomic apply preserves mode and reports only file-level idempotence',async t=>{
57
+ const {createTypeImportCorrection,applyTypeImportCorrection}=await api();
58
+ const c=createTypeImportCorrection(options()),root=fixture(t);
59
+ assert.equal(applyTypeImportCorrection({root,correction:c}).outcome,'applied');
60
+ assert.equal(fs.readFileSync(path.join(root,c.path),'base64'),c.after.contentBase64);
61
+ assert.equal(fs.statSync(path.join(root,c.path)).mode&0o7777,c.after.mode);
62
+ assert.equal(applyTypeImportCorrection({root,correction:c}).outcome,'already_applied');
63
+ fs.chmodSync(path.join(root,c.path),0o600);assert.throws(()=>applyTypeImportCorrection({root,correction:c}));
64
+ });
65
+ test('apply rejects parent/file symlinks and multiply linked source files',async t=>{
66
+ const {createTypeImportCorrection,applyTypeImportCorrection}=await api();
67
+ const c=createTypeImportCorrection(options(record(source,'src/main.ts'))),root=fixture(t,c.before);
68
+ const original=path.join(root,'src');fs.renameSync(original,path.join(root,'real'));fs.symlinkSync('real',original);
69
+ assert.throws(()=>applyTypeImportCorrection({root,correction:c}));fs.unlinkSync(original);fs.renameSync(path.join(root,'real'),original);
70
+ const file=path.join(original,'main.ts');fs.renameSync(file,file+'.original');fs.symlinkSync('main.ts.original',file);
71
+ assert.throws(()=>applyTypeImportCorrection({root,correction:c}));fs.unlinkSync(file);fs.renameSync(file+'.original',file);
72
+ fs.linkSync(file,file+'.link');assert.throws(()=>applyTypeImportCorrection({root,correction:c}));
73
+ });
74
+ test('failure before rename preserves source and removes the temporary file',async t=>{
75
+ const {createTypeImportCorrection,applyTypeImportCorrection}=await api();
76
+ const c=createTypeImportCorrection(options()),root=fixture(t),rename=fs.renameSync;
77
+ try{fs.renameSync=()=>{throw Object.assign(new Error('synthetic interruption'),{code:'EIO'});};assert.throws(()=>applyTypeImportCorrection({root,correction:c}));}
78
+ finally{fs.renameSync=rename;}
79
+ assert.equal(fs.readFileSync(path.join(root,c.path),'base64'),c.before.contentBase64);assert.deepEqual(fs.readdirSync(root),['main.ts']);
80
+ });
81
+ test('source drift after temporary fsync is rejected before rename',async t=>{
82
+ const {createTypeImportCorrection,applyTypeImportCorrection}=await api();
83
+ const c=createTypeImportCorrection(options()),root=fixture(t),sync=fs.fsyncSync;let touched=false;
84
+ try{fs.fsyncSync=fd=>{sync(fd);if(!touched){touched=true;fs.writeFileSync(path.join(root,c.path),'concurrent user bytes');}};assert.throws(()=>applyTypeImportCorrection({root,correction:c}));}
85
+ finally{fs.fsyncSync=sync;}
86
+ assert.equal(fs.readFileSync(path.join(root,c.path),'utf8'),'concurrent user bytes');assert.deepEqual(fs.readdirSync(root),['main.ts']);
87
+ });
88
+ test('native type-strip fixture fails before split and runs the same value check afterward',{skip:Number(process.versions.node.split('.')[0])<24},async t=>{
89
+ const {createTypeImportCorrection,applyTypeImportCorrection}=await api();
90
+ const c=createTypeImportCorrection(options()),root=fixture(t);
91
+ fs.writeFileSync(path.join(root,'types.ts'),'export type Marker = number; export const value = 7;\n');
92
+ const run=()=>spawnSync(process.execPath,['--experimental-strip-types','main.ts'],{cwd:root,encoding:'utf8',timeout:5000});
93
+ const before=run();assert.equal(before.status,1);assert.match(before.stderr,/does not provide an export named 'Marker'/);
94
+ applyTypeImportCorrection({root,correction:c});const after=run();assert.equal(after.status,0,after.stderr);
95
+ });