@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,831 @@
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 crypto from 'node:crypto';
7
+ import {execFileSync} from 'node:child_process';
8
+ import {
9
+ hook,main,enable,refresh,statusText,loadRules,stripCode,hookCommand,hasHintHook,
10
+ localPath,logFile,installDir,claudeSettingsPath,codexHooksPath,defaultRulesPath,
11
+ MAX_PROMPT,ADOPT_WINDOW,LOG_LIMIT,SCRIPT_NAME,RULES_NAME,patternMatches,typed,readJson,loadAuthorCheck,
12
+ } from './cm-skill-hints.mjs';
13
+ import {SKILLS} from './cm-matt-skills.mjs';
14
+
15
+ const NOW=Date.parse('2026-10-24T08:00:00Z');
16
+
17
+ function fixture(t,{rules,local,authorSkills=[],authorNames=['grill-me','handoff']}={}){
18
+ const home=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-skill-hints-')));
19
+ t.after(()=>fs.rmSync(home,{recursive:true,force:true}));
20
+ const env={HOME:home,CLAUDE_HOME:path.join(home,'.claude'),CODEX_HOME:path.join(home,'.codex'),
21
+ CM_WORKFLOW_HOME:path.join(home,'.cm-workflow'),CM_WORKFLOW_LOG_HOME:path.join(home,'.cm-workflow','logs')};
22
+ const rulesFile=path.join(home,'rules.json');
23
+ fs.writeFileSync(rulesFile,JSON.stringify(rules??{version:1,rules:[
24
+ {id:'grill-plan',skill:'grill-me',author:true,keywords:['设计一个方案','Grill Me'],reason:'先问透',
25
+ fallback:{skill:'cm-challenge',reason:'先挑战'}},
26
+ {id:'long-session',skill:'handoff',author:true,keywords:['会话太长'],reason:'写交接'},
27
+ {id:'fix-bug',skill:'cm-fix',keywords:['修这个 bug'],reason:'先复现'},
28
+ {id:'test',skill:'cm-test',keywords:['补单测'],patterns:['覆盖率\\s*\\d+'],reason:'补测试'},
29
+ ]}));
30
+ if(local!==undefined){
31
+ fs.mkdirSync(env.CM_WORKFLOW_HOME,{recursive:true});
32
+ fs.writeFileSync(localPath(env),typeof local==='string'?local:JSON.stringify(local));
33
+ }
34
+ // Pinned "author versions" for the test: exact SKILL.md + LICENSE bytes, checked by hash.
35
+ const sha=text=>crypto.createHash('sha256').update(text).digest('hex');
36
+ const authorOptions={license:sha('MIT'),skills:authorNames.map(name=>({name,files:{'SKILL.md':sha(`author ${name}`)}}))};
37
+ // The real checker, fed the test's pinned list instead of the upstream one.
38
+ const loadAuthor=async()=>({...(await loadAuthorCheck()),skills:authorOptions.skills,license:authorOptions.license});
39
+ for(const [root,name,content=`author ${name}`] of authorSkills){
40
+ const dir=path.join(home,root,name);
41
+ fs.mkdirSync(dir,{recursive:true});
42
+ fs.writeFileSync(path.join(dir,'SKILL.md'),content);
43
+ fs.writeFileSync(path.join(dir,'LICENSE'),'MIT');
44
+ }
45
+ const send=async(prompt,{host='claude',session='s1',extraEnv={},now=NOW}={})=>{
46
+ const out=await hook({prompt,session_id:session},{env:{...env,...extraEnv},host,rulesFile,now,loadAuthor});
47
+ return out?JSON.parse(out).systemMessage:'';
48
+ };
49
+ const log=()=>{try{return fs.readFileSync(logFile(env),'utf8').split('\n').filter(Boolean).map(line=>JSON.parse(line));}catch{return [];}};
50
+ return {home,env,rulesFile,send,log,authorOptions};
51
+ }
52
+
53
+ test('a keyword hint names the skill in the host\'s own syntax',async t=>{
54
+ const f=fixture(t,{authorSkills:[['.claude/skills','grill-me'],['.agents/skills','grill-me']]});
55
+ assert.match(await f.send('帮我设计一个方案'),/可以试 \/grill-me——先问透/);
56
+ assert.match(await f.send('帮我设计一个方案',{host:'codex',session:'s2'}),/可以试 \$grill-me——先问透/);
57
+ });
58
+
59
+ test('matching ignores case and supports optional regex patterns',async t=>{
60
+ const f=fixture(t,{authorSkills:[['.claude/skills','grill-me']]});
61
+ assert.match(await f.send('please GRILL ME on this'),/grill-me/);
62
+ assert.match(await f.send('覆盖率 40 太低',{session:'s2'}),/cm-test/);
63
+ assert.equal(await f.send('覆盖率很低',{session:'s3'}),'');
64
+ });
65
+
66
+ test('a missing author skill falls back to its CM counterpart, or is dropped',async t=>{
67
+ const f=fixture(t);
68
+ const text=await f.send('帮我设计一个方案,会话太长了');
69
+ assert.match(text,/\/cm-challenge——先挑战/);
70
+ assert.doesNotMatch(text,/grill-me|handoff/);
71
+ });
72
+
73
+ test('an author skill installed only for the other host does not count',async t=>{
74
+ const f=fixture(t,{authorSkills:[['.agents/skills','grill-me']]});
75
+ assert.match(await f.send('设计一个方案'),/cm-challenge/);
76
+ });
77
+
78
+ test('at most two hints per message, user rules first',async t=>{
79
+ const f=fixture(t,{local:{rules:[{skill:'my-skill',keywords:['bug'],reason:'自己的'}]}});
80
+ const text=await f.send('设计一个方案,修这个 bug,再补单测');
81
+ assert.deepEqual(text.split('\n'),['💡 技能提醒:可以试 /my-skill——自己的','💡 技能提醒:可以试 /cm-challenge——先挑战']);
82
+ });
83
+
84
+ test('the same skill is hinted once per session, again in a new session',async t=>{
85
+ const f=fixture(t);
86
+ assert.match(await f.send('修这个 bug'),/cm-fix/);
87
+ assert.equal(await f.send('再修这个 bug'),'');
88
+ assert.match(await f.send('修这个 bug',{session:'other'}),/cm-fix/);
89
+ });
90
+
91
+ test('no hint when the user already typed or named the skill',async t=>{
92
+ const f=fixture(t);
93
+ assert.equal(await f.send('/cm-fix 修这个 bug'),'');
94
+ assert.equal(await f.send('用 cm-fix 修这个 bug',{session:'s2'}),'');
95
+ });
96
+
97
+ test('long messages and fenced code never trigger',async t=>{
98
+ const f=fixture(t);
99
+ assert.equal(await f.send('修这个 bug'+'x'.repeat(MAX_PROMPT)),'');
100
+ assert.equal(await f.send('看日志:\n```\n修这个 bug\n```\n怎么回事',{session:'s2'}),'');
101
+ assert.equal(stripCode('a```x```b```y'),'a b ');
102
+ });
103
+
104
+ test('CM_SKILL_HINTS=off and enabled:false both silence the hook',async t=>{
105
+ const f=fixture(t);
106
+ assert.equal(await f.send('修这个 bug',{extraEnv:{CM_SKILL_HINTS:'off'}}),'');
107
+ const g=fixture(t,{local:{enabled:false}});
108
+ assert.equal(await g.send('修这个 bug'),'');
109
+ });
110
+
111
+ test('disable switches off a CM rule by id; a broken local file pauses hints altogether',async t=>{
112
+ const f=fixture(t,{local:{disable:['fix-bug']}});
113
+ assert.equal(await f.send('修这个 bug'),'');
114
+ assert.match(await f.send('补单测'),/cm-test/);
115
+ const g=fixture(t,{local:'{oops'});
116
+ assert.equal(await g.send('修这个 bug'),'');
117
+ const loaded=loadRules({env:g.env,rulesFile:g.rulesFile});
118
+ assert.equal(loaded.enabled,false);
119
+ assert.equal(loaded.localError,'parse');
120
+ });
121
+
122
+ test('invalid user rules are skipped, not fatal',async t=>{
123
+ const f=fixture(t,{local:{rules:[{skill:'bad name',keywords:['bug']},{skill:'ok',keywords:[]},{skill:'re',patterns:['(']},
124
+ {skill:'good',keywords:['修这个']}]}});
125
+ assert.match(await f.send('修这个 bug'),/可以试 \/good——/);
126
+ });
127
+
128
+ test('the log keeps rule, skill, host and time, never the message',async t=>{
129
+ const f=fixture(t);
130
+ await f.send('修这个 bug,密码是 hunter2');
131
+ const [entry]=f.log();
132
+ assert.deepEqual(entry,{t:'2026-10-24T08:00:00.000Z',event:'hint',host:'claude',rule:'fix-bug',skill:'cm-fix'});
133
+ assert.doesNotMatch(fs.readFileSync(logFile(f.env),'utf8'),/hunter2|修这个/);
134
+ });
135
+
136
+ test('typing the hinted skill within the window is logged as adopted',async t=>{
137
+ const f=fixture(t);
138
+ await f.send('修这个 bug');
139
+ await f.send('好的');
140
+ await f.send('/cm-fix 开始');
141
+ assert.deepEqual(f.log().map(entry=>entry.event),['hint','adopted']);
142
+ });
143
+
144
+ test('typing it after the window is not adopted',async t=>{
145
+ const f=fixture(t);
146
+ await f.send('修这个 bug');
147
+ for(let i=0;i<ADOPT_WINDOW;i++)await f.send(`第 ${i} 条`);
148
+ await f.send('/cm-fix 开始');
149
+ assert.deepEqual(f.log().map(entry=>entry.event),['hint']);
150
+ });
151
+
152
+ test('the log drops its older half once over the size limit',async t=>{
153
+ const f=fixture(t);
154
+ fs.mkdirSync(path.dirname(logFile(f.env)),{recursive:true});
155
+ const line=JSON.stringify({t:'old',pad:'x'.repeat(200)})+'\n';
156
+ fs.writeFileSync(logFile(f.env),line.repeat(Math.ceil(LOG_LIMIT/line.length)+10));
157
+ const before=fs.readFileSync(logFile(f.env),'utf8').split('\n').filter(Boolean).length;
158
+ await f.send('修这个 bug');
159
+ const after=f.log();
160
+ assert.ok(after.length<=Math.floor(before/2)+1);
161
+ assert.equal(after.at(-1).rule,'fix-bug');
162
+ });
163
+
164
+ test('main hook stays quiet on bad input and exits 0',async t=>{
165
+ const f=fixture(t);
166
+ let out='';
167
+ assert.equal(await main(['hook','--host','claude'],{env:f.env,readInput:()=>'not json',write:text=>{out+=text;}}),0);
168
+ assert.equal(out,'');
169
+ assert.equal(await main(['hook','--host','claude'],{env:f.env,readInput:()=>{throw new Error('closed');},write:text=>{out+=text;}}),0);
170
+ assert.equal(out,'');
171
+ });
172
+
173
+ test('main hook prints the UserPromptSubmit JSON shape with the shipped table',async t=>{
174
+ const f=fixture(t);
175
+ let out='';
176
+ await main(['hook','--host','codex'],{env:f.env,readInput:()=>JSON.stringify({prompt:'帮我修这个 bug',session_id:'x'}),write:text=>{out+=text;}});
177
+ const parsed=JSON.parse(out);
178
+ // Shown to the user only: nothing is added to the model's context.
179
+ assert.deepEqual(Object.keys(parsed),['systemMessage']);
180
+ assert.match(parsed.systemMessage,/^💡 技能提醒:可以试 \$cm-fix——/);
181
+ });
182
+
183
+ test('the shipped table loads cleanly and every rule resolves to a CM skill or a fallback',async ()=>{
184
+ const table=JSON.parse(fs.readFileSync(defaultRulesPath(),'utf8'));
185
+ const loaded=loadRules({env:{HOME:'/nonexistent',CM_WORKFLOW_HOME:'/nonexistent/.cm'}});
186
+ assert.equal(loaded.cmCount,table.rules.length);
187
+ assert.ok(table.rules.length>=10&&table.rules.length<=20);
188
+ assert.equal(new Set(table.rules.map(rule=>rule.id)).size,table.rules.length);
189
+ const skills=new Set(fs.readdirSync(path.join(path.dirname(defaultRulesPath()),'..','skills')));
190
+ for(const rule of table.rules){
191
+ if(rule.author)continue;
192
+ assert.ok(skills.has(rule.skill),`${rule.id} 指向不存在的 CM 技能 ${rule.skill}`);
193
+ }
194
+ for(const rule of table.rules.filter(rule=>rule.fallback))assert.ok(skills.has(rule.fallback.skill));
195
+ // A message naming the skill is never hinted, so such a keyword could never fire.
196
+ // Anchored patterns scan the message once, which keeps the shared regex budget.
197
+ for(const rule of table.rules)for(const source of rule.patterns??[])assert.ok(source.startsWith('^'),`${rule.id} 有未锚定的正则`);
198
+ for(const rule of table.rules)for(const word of rule.keywords)assert.ok(!word.toLowerCase().includes(rule.skill),`${rule.id} 的关键词「${word}」含技能名,永远不会触发`);
199
+ // Installed-or-not is decided by the pinned fingerprint, so an author rule must name a pinned skill.
200
+ const pinned=new Set(SKILLS.map(skill=>skill.name));
201
+ for(const rule of table.rules.filter(rule=>rule.author))assert.ok(pinned.has(rule.skill),`${rule.id} 的 ${rule.skill} 不在固定清单里`);
202
+ });
203
+
204
+ // The shipped table against real phrasings (from the 2026-10-24 trial of the author
205
+ // skills) and everyday chatter. Every prompt gets its own session.
206
+ const SHIPPED_AUTHORS=['grill-me','grill-with-docs','handoff','wayfinder','improve-codebase-architecture','prototype'];
207
+ function shipped(t,{installed=true,authorSkills}={}){
208
+ const f=fixture(t,{rules:JSON.parse(fs.readFileSync(defaultRulesPath(),'utf8')),authorNames:SHIPPED_AUTHORS,
209
+ authorSkills:authorSkills??(installed?SHIPPED_AUTHORS.map(name=>['.claude/skills',name]):[])});
210
+ let n=0;
211
+ // Hinted or started (no TypeSafe key here, so invoke rules go by their keywords).
212
+ return {...f,hints:async prompt=>[...(await f.send(prompt,{session:`p${n++}`})).matchAll(/(?:可以试|已让模型用|要不要用) \/([\w.:-]+)/g)].map(m=>m[1])};
213
+ }
214
+ const PHRASES=[
215
+ ['我想给这个记账工具加一个预算提醒功能,但还没想清楚,你逼问我几轮把方案理清。','grill-me','cm-challenge'],
216
+ ['帮我压力测试一下这个方案:每天凌晨跑定时任务汇总消费,超预算就推送手机通知。','grill-me','cm-challenge'],
217
+ ['Grill me on this plan before I start','grill-me','cm-challenge'],
218
+ ['在这个仓库里加多币种,逼问我把技术方案理清','grill-with-docs','cm-challenge'],
219
+ ['帮我定一下技术方案,存储用 SQLite 还是 JSON','grill-with-docs','cm-challenge'],
220
+ ['help me think this through for the codebase','grill-with-docs','cm-challenge'],
221
+ // One module's interface is codebase-design (model-invocable), not the whole-codebase report.
222
+ ['src/storage 下面拆了五个小文件,接口太碎了。帮我想想怎么设计一个更深的模块接口。',null,null],
223
+ ['代码太乱了,不知道从哪重构','improve-codebase-architecture','cm-refactor'],
224
+ ['the architecture is a mess, where to start refactoring?','improve-codebase-architecture','cm-refactor'],
225
+ ['我拿不准预算状态机对不对,做个能点着玩的原型让我看看。','prototype',null],
226
+ ['预算页面该长什么样我没想法,给我做几版差别很大的界面对比看看。','prototype',null],
227
+ ['mock up a few versions of the budget page','prototype',null],
228
+ ['做个预算页面的可点击原型,数据先用 Object.create(null) 模拟。','prototype',null],
229
+ ['做几版界面对比看看,文案里要讲清楚 JavaScript 原型继承。','prototype',null],
230
+ ['不要讲原型链,给我做个预算页面原型。','prototype',null],
231
+ ['上下文快用完了,写个交接吧','handoff',null],
232
+ ['写个交接,下个会话接着做','handoff',null],
233
+ ['这个会话快满了,写个交接。','handoff',null],
234
+ ["we're running out of context, let's continue in a new session",'handoff',null],
235
+ ['这个改造一个会话做不完,拆成几个会话推进','wayfinder','cm-prd'],
236
+ ['this is too big for one session','wayfinder','cm-prd'],
237
+ ];
238
+ const CHATTER=['今天天气怎么样','把这行改成中文','帮我看看这个报错是什么意思','提交一下代码','这个函数是做什么的',
239
+ 'JS 的原型链怎么理解','用 jmeter 给登录接口做压力测试','这个方案我已经想清楚了,直接写吧','右键的上下文菜单点不开','帮我把按钮颜色改成蓝色',
240
+ '帮我写个压力测试方案','做个原型链的例子','我明天要和同事交接,帮我写一份交接文档。',
241
+ '用 JavaScript 做个原型继承的例子。','帮我写同事离职交接文档,需要补充项目上下文。','修好右键上下文菜单后,写一份给同事的交接文档。',
242
+ '帮我写同事离职交接文档,附上项目上下文快照。','交接文档里的项目上下文要怎么整理?','做一个用完就扔的原型对象,演示原型继承。','做一个原型对象,演示 Object.create 怎么继承属性。',
243
+ '用 JMeter 压力测试一下这个方案的登录接口,记录吞吐量和 P99。','这个方案上线前要压力测试一下并发','what is the weather today','rename this variable'];
244
+
245
+ test('shipped table: real phrasings hint the author skill when it is installed',async t=>{
246
+ const f=shipped(t);
247
+ for(const [prompt,skill] of PHRASES)assert.deepEqual(await f.hints(prompt),skill?[skill]:[],prompt);
248
+ });
249
+
250
+ test('shipped table: without the author skill it falls back to the CM counterpart, or stays quiet',async t=>{
251
+ const f=shipped(t,{installed:false});
252
+ for(const [prompt,,fallback] of PHRASES)assert.deepEqual(await f.hints(prompt),fallback?[fallback]:[],prompt);
253
+ });
254
+
255
+ test('shipped table: everyday chatter never triggers',async t=>{
256
+ const f=shipped(t);
257
+ for(const prompt of CHATTER)assert.deepEqual(await f.hints(prompt),[],prompt);
258
+ });
259
+
260
+ test('shipped table: a long message of repeated cue words stays within the pattern budget',async t=>{
261
+ const f=shipped(t);
262
+ const prompt='压力测试'.repeat(498)+'仓库。原型看看';
263
+ assert.ok(prompt.length<MAX_PROMPT);
264
+ assert.deepEqual(await f.hints(prompt),['prototype']);
265
+ });
266
+
267
+ test('shipped table: grill-me and grill-with-docs are never hinted together',async t=>{
268
+ const f=shipped(t);
269
+ for(const prompt of ['逼问我这个方案,顺便看看仓库里的数据模型','压力测试一下这个方案,记进决策记录','grill me on the repo layout',
270
+ 'Grill with docs: help me think this through.','grill with docs,帮我理清方案']){
271
+ assert.deepEqual(await f.hints(prompt),['grill-with-docs'],prompt);
272
+ }
273
+ });
274
+
275
+ test('shipped table: a third-party prototype skill is never hinted',async t=>{
276
+ const f=shipped(t,{authorSkills:[['.claude/skills','prototype','someone else\'s prototype']]});
277
+ assert.deepEqual(await f.hints('做个能点着玩的原型让我看看'),[]);
278
+ });
279
+
280
+ test('shipped table: "refactor it now" wording goes to cm-refactor alone, not the architecture report too',async t=>{
281
+ const f=shipped(t);
282
+ assert.deepEqual(await f.hints('代码太乱了,重构一下'),['cm-refactor']);
283
+ });
284
+
285
+ test('enable copies a stable script and merges one hook into each host config',async t=>{
286
+ const f=fixture(t);
287
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
288
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({statusLine:{command:'x'},hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:'other'}]}]}}));
289
+ let out='';
290
+ assert.equal(await enable({env:f.env,node:'/usr/bin/node',write:text=>{out+=text;}}),0);
291
+ assert.ok(fs.existsSync(path.join(installDir(f.env),SCRIPT_NAME)));
292
+ assert.ok(fs.existsSync(path.join(installDir(f.env),RULES_NAME)));
293
+ const claude=JSON.parse(fs.readFileSync(claudeSettingsPath(f.env),'utf8'));
294
+ assert.equal(claude.statusLine.command,'x');
295
+ assert.equal(claude.hooks.UserPromptSubmit.length,2);
296
+ assert.equal(claude.hooks.UserPromptSubmit[1].hooks[0].command,hookCommand(f.env,'claude','/usr/bin/node'));
297
+ const codex=JSON.parse(fs.readFileSync(codexHooksPath(f.env),'utf8'));
298
+ assert.ok(hasHintHook(codex,f.env,"codex"));
299
+ assert.match(codex.hooks.UserPromptSubmit[0].hooks[0].command,/--host codex$/);
300
+ assert.match(out,/信任/);
301
+ await enable({env:f.env,node:'/usr/bin/node',write:()=>{}});
302
+ assert.equal(JSON.parse(fs.readFileSync(claudeSettingsPath(f.env),'utf8')).hooks.UserPromptSubmit.length,2);
303
+ });
304
+
305
+ test('enable never rewrites a config it cannot parse',async t=>{
306
+ const f=fixture(t);
307
+ fs.mkdirSync(path.dirname(codexHooksPath(f.env)),{recursive:true});
308
+ fs.writeFileSync(codexHooksPath(f.env),'{broken');
309
+ let out='';
310
+ assert.equal(await enable({env:f.env,hosts:['codex'],write:text=>{out+=text;}}),1);
311
+ assert.equal(fs.readFileSync(codexHooksPath(f.env),'utf8'),'{broken');
312
+ assert.match(out,/未改动/);
313
+ });
314
+
315
+ test('the installed copy runs on its own with its own table',async t=>{
316
+ const f=fixture(t);
317
+ await enable({env:f.env,write:()=>{}});
318
+ const installed=await import(path.join(installDir(f.env),SCRIPT_NAME));
319
+ const out=await installed.hook({prompt:'修这个 bug',session_id:'z'},{env:f.env,host:'claude',now:NOW});
320
+ assert.match(JSON.parse(out).systemMessage,/cm-fix/);
321
+ });
322
+
323
+ test('hook command quotes paths with spaces',async t=>{
324
+ const env={HOME:'/Users/a b',CM_WORKFLOW_HOME:'/Users/a b/.cm-workflow'};
325
+ assert.equal(hookCommand(env,'claude','/opt/node/bin/node'),
326
+ `/opt/node/bin/node '/Users/a b/.cm-workflow/skill-hints/${SCRIPT_NAME}' hook --host claude`);
327
+ });
328
+
329
+ test('status reports wiring, switch and table counts',async t=>{
330
+ const f=fixture(t,{local:{rules:[{skill:'mine',keywords:['x']}],disable:['fix-bug']}});
331
+ let text=statusText({env:f.env,rulesFile:f.rulesFile});
332
+ assert.match(text,/Claude 未挂,Codex 未挂;开关 开/);
333
+ assert.match(text,/CM 自带 3 条;用户自加 1 条;关掉自带 1 条/);
334
+ assert.match(text,/自动调用:有 TypeSafe 密钥/);
335
+ fs.writeFileSync(localPath(f.env),JSON.stringify({enabled:false}));
336
+ text=statusText({env:f.env,rulesFile:f.rulesFile});
337
+ assert.match(text,/开关 关/);
338
+ });
339
+
340
+ test('CM-launched Claude and Codex sessions carry the off switch',async()=>{
341
+ const {claudeEnvironment}=await import('../runtime/js/cm-ai/worker-claude.mjs');
342
+ const {cleanEnvironment}=await import('../runtime/js/cm-ai/codex-config.mjs');
343
+ assert.equal(claudeEnvironment().CM_SKILL_HINTS,'off');
344
+ assert.equal(cleanEnvironment().CM_SKILL_HINTS,'off');
345
+ });
346
+
347
+ // ---- regressions from Codex review round 1 ----
348
+
349
+ test('a same-named skill that is not the pinned author version does not count as installed',async t=>{
350
+ const f=fixture(t,{authorSkills:[['.claude/skills','grill-me','someone else\'s grill-me']]});
351
+ const text=await f.send('设计一个方案');
352
+ assert.match(text,/cm-challenge/);
353
+ assert.doesNotMatch(text,/grill-me/);
354
+ });
355
+
356
+ test('a catastrophic user regex is cut off by the time budget; keywords still match',async t=>{
357
+ const f=fixture(t,{local:{rules:[{skill:'slow',patterns:['^(a+)+$']}]}});
358
+ const started=Date.now();
359
+ const text=await f.send('a'.repeat(40)+'! 修这个 bug');
360
+ assert.ok(Date.now()-started<2000,`took ${Date.now()-started}ms`);
361
+ assert.match(text,/cm-fix/);
362
+ assert.doesNotMatch(text,/slow/);
363
+ assert.deepEqual(patternMatches([{patterns:[/^(a+)+$/]}],'a'.repeat(40)+'!',50),[false]);
364
+ });
365
+
366
+ test('special files at the local rules, state or log path never block the hook',async t=>{
367
+ const f=fixture(t);
368
+ fs.mkdirSync(f.env.CM_WORKFLOW_HOME,{recursive:true});
369
+ fs.mkdirSync(path.dirname(logFile(f.env)),{recursive:true});
370
+ execFileSync('mkfifo',[logFile(f.env)]);
371
+ assert.match(await f.send('修这个 bug'),/cm-fix/);
372
+ // A special file at the local path is read as a problem, which pauses hints; still no block.
373
+ execFileSync('mkfifo',[localPath(f.env)]);
374
+ assert.equal(readJson(localPath(f.env)).error,'not-file');
375
+ assert.equal(await f.send('修这个 bug',{session:'s2'}),'');
376
+ assert.equal(loadRules({env:f.env,rulesFile:f.rulesFile}).localError,'not-file');
377
+ });
378
+
379
+ test('a user rule with a CM rule id replaces that CM rule',async t=>{
380
+ const f=fixture(t,{local:{rules:[{id:'fix-bug',skill:'my-fix',keywords:['修这个 bug'],reason:'用我的'}]}});
381
+ assert.equal(await f.send('修这个 bug'),'💡 技能提醒:可以试 /my-fix——用我的');
382
+ });
383
+
384
+ test('session state is never pruned: a session resumed much later still does not repeat a hint',async t=>{
385
+ const f=fixture(t);
386
+ await f.send('修这个 bug',{session:'old'});
387
+ const dir=path.join(installDir(f.env),'state');
388
+ const [name]=fs.readdirSync(dir);
389
+ const ancient=new Date(NOW-365*24*60*60*1000);
390
+ fs.utimesSync(path.join(dir,name),ancient,ancient);
391
+ await f.send('补单测',{session:'new'});
392
+ assert.ok(fs.existsSync(path.join(dir,name)));
393
+ assert.equal(await f.send('修这个 bug',{session:'old'}),'');
394
+ });
395
+
396
+ test('a foreign command that merely mentions the script name is not taken as ours',async t=>{
397
+ const f=fixture(t);
398
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
399
+ const tail=hookCommand(f.env,'claude','x').slice(2);
400
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({hooks:{UserPromptSubmit:[{hooks:[
401
+ {type:'command',command:`echo ${SCRIPT_NAME}`},{type:'command',command:`echo x ${tail}`}]}]}}));
402
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/Claude 未挂/);
403
+ await enable({env:f.env,hosts:['claude'],node:'/usr/bin/node',write:()=>{}});
404
+ assert.ok(hasHintHook(JSON.parse(fs.readFileSync(claudeSettingsPath(f.env),'utf8')),f.env,'claude'));
405
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/Claude 已挂/);
406
+ const codexCmd=hookCommand(f.env,'codex','/usr/bin/node');
407
+ assert.ok(!hasHintHook({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:codexCmd}]}]}},f.env,'claude'));
408
+ });
409
+
410
+ test('an existing empty or blank host config is reported and left byte-identical',async t=>{
411
+ for(const content of ['',' \n']){
412
+ const f=fixture(t);
413
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
414
+ fs.writeFileSync(claudeSettingsPath(f.env),content);
415
+ let out='';
416
+ assert.equal(await enable({env:f.env,hosts:['claude'],write:text=>{out+=text;}}),1);
417
+ assert.equal(fs.readFileSync(claudeSettingsPath(f.env),'utf8'),content);
418
+ assert.match(out,/empty/);
419
+ }
420
+ });
421
+
422
+ test('a config changed by someone else during enable is not overwritten',async t=>{
423
+ const f=fixture(t);
424
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
425
+ fs.writeFileSync(claudeSettingsPath(f.env),'{"a":1}');
426
+ let out='';
427
+ const code=await enable({env:f.env,hosts:['claude'],write:text=>{out+=text;},
428
+ beforeReplace:file=>fs.writeFileSync(file,'{"a":1,"theirs":true}')});
429
+ assert.equal(code,1);
430
+ assert.equal(fs.readFileSync(claudeSettingsPath(f.env),'utf8'),'{"a":1,"theirs":true}');
431
+ assert.match(out,/刚被其他程序改动/);
432
+ });
433
+
434
+ test('adoption needs the whole skill token, not a longer name sharing its prefix',async t=>{
435
+ assert.ok(typed('/cm-fix 开始','cm-fix','claude'));
436
+ assert.ok(typed('先 $cm-fix','cm-fix','codex'));
437
+ assert.ok(!typed('/cm-fix-extra','cm-fix','claude'));
438
+ assert.ok(!typed('/cm-fix.v2','cm-fix','claude'));
439
+ const f=fixture(t);
440
+ await f.send('修这个 bug');
441
+ await f.send('/cm-fix-extra 开始');
442
+ assert.deepEqual(f.log().map(entry=>entry.event),['hint']);
443
+ });
444
+
445
+ // ---- regressions from Codex review round 2 ----
446
+
447
+ test('only a node interpreter running the managed copy counts as our hook',async t=>{
448
+ const f=fixture(t);
449
+ const tail=hookCommand(f.env,'claude','node').slice('node '.length);
450
+ const ours=command=>hasHintHook({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command}]}]}},f.env,'claude');
451
+ assert.ok(ours(`node ${tail}`));
452
+ assert.ok(ours(`/opt/homebrew/bin/node ${tail}`));
453
+ assert.ok(ours(`'/Users/a b/node' ${tail}`));
454
+ assert.ok(!ours(`echo ${tail}`));
455
+ assert.ok(!ours(`python3 ${tail}`));
456
+ assert.ok(!ours(`'/Users/a b/echo' ${tail}`));
457
+ });
458
+
459
+ test('two CM writers never hold the config lock at once; a stale lock is taken over',async t=>{
460
+ const f=fixture(t);
461
+ const {withConfigLock,LockBusy,lockPath}=await import('./cm-config-lock.mjs');
462
+ const file=claudeSettingsPath(f.env);
463
+ assert.throws(()=>withConfigLock(f.env,file,()=>withConfigLock(f.env,file,()=>'inner',{waitMs:100})),LockBusy);
464
+ assert.equal(withConfigLock(f.env,file,()=>'free again'),'free again');
465
+ const lock=lockPath(f.env,file);
466
+ fs.writeFileSync(lock,'12345');
467
+ const old=new Date(Date.now()-60000);
468
+ fs.utimesSync(lock,old,old);
469
+ assert.equal(withConfigLock(f.env,file,()=>'taken over',{waitMs:100}),'taken over');
470
+ assert.ok(!fs.existsSync(lock));
471
+ });
472
+
473
+ test('enable leaves the config alone while another CM writer holds its lock',async t=>{
474
+ const f=fixture(t);
475
+ const {lockPath}=await import('./cm-config-lock.mjs');
476
+ const lock=lockPath(f.env,claudeSettingsPath(f.env));
477
+ fs.mkdirSync(path.dirname(lock),{recursive:true});
478
+ fs.writeFileSync(lock,'other');
479
+ let out='';
480
+ assert.equal(await enable({env:f.env,hosts:['claude'],write:text=>{out+=text;},lockWaitMs:100}),1);
481
+ assert.ok(!fs.existsSync(claudeSettingsPath(f.env)));
482
+ assert.match(out,/另一个 CM 程序正在改/);
483
+ });
484
+
485
+ test('a missing author checker falls back to CM skills instead of failing',async t=>{
486
+ assert.equal(await loadAuthorCheck('./does-not-exist.mjs'),null);
487
+ const f=fixture(t,{authorSkills:[['.claude/skills','grill-me']]});
488
+ const out=await hook({prompt:'设计一个方案',session_id:'m'},{env:f.env,host:'claude',rulesFile:f.rulesFile,now:NOW,loadAuthor:async()=>null});
489
+ assert.match(JSON.parse(out).systemMessage,/cm-challenge/);
490
+ });
491
+
492
+ test('the installed hook still exits 0 with a hint when its checker file is gone',async t=>{
493
+ const f=fixture(t);
494
+ await enable({env:f.env,hosts:['claude'],write:()=>{}});
495
+ fs.unlinkSync(path.join(installDir(f.env),'cm-matt-skills.mjs'));
496
+ const out=execFileSync(process.execPath,[path.join(installDir(f.env),SCRIPT_NAME),'hook','--host','claude'],
497
+ {env:{...process.env,...f.env},input:JSON.stringify({prompt:'帮我设计一个方案',session_id:'gone'}),encoding:'utf8'});
498
+ assert.match(JSON.parse(out).systemMessage,/cm-challenge/);
499
+ });
500
+
501
+ test('a failed companion copy leaves the previously installed script in place',async t=>{
502
+ const f=fixture(t);
503
+ const dir=installDir(f.env);
504
+ fs.mkdirSync(path.join(dir,'cm-config-lock.mjs','blocker'),{recursive:true});
505
+ fs.writeFileSync(path.join(dir,SCRIPT_NAME),'// previous working copy\n');
506
+ let out='';
507
+ assert.equal(await enable({env:f.env,hosts:['claude'],write:text=>{out+=text;}}),1);
508
+ assert.equal(fs.readFileSync(path.join(dir,SCRIPT_NAME),'utf8'),'// previous working copy\n');
509
+ assert.match(out,/复制提醒脚本/);
510
+ });
511
+
512
+ test('a URL or path ending in the skill name is not an adoption',async t=>{
513
+ assert.ok(!typed('请看 https://example.invalid/cm-fix','cm-fix','claude'));
514
+ assert.ok(!typed('文件在 docs/cm-fix','cm-fix','claude'));
515
+ assert.ok(!typed('a$cm-fix','cm-fix','codex'));
516
+ assert.ok(typed('好,/cm-fix','cm-fix','claude'));
517
+ assert.ok(typed('用(/cm-fix)','cm-fix','claude'));
518
+ });
519
+
520
+ test('a skill name after a CJK path segment is not an adoption',async t=>{
521
+ assert.ok(!typed('文档/cm-fix','cm-fix','claude'));
522
+ assert.ok(!typed('看 https://example.invalid/文档/cm-fix','cm-fix','claude'));
523
+ assert.ok(!typed('目录$cm-fix','cm-fix','codex'));
524
+ assert.ok(typed('/cm-fix','cm-fix','claude'));
525
+ assert.ok(typed('好的 /cm-fix 开始','cm-fix','claude'));
526
+ assert.ok(typed('就用「$cm-fix」','cm-fix','codex'));
527
+ assert.ok(typed('用 `/cm-fix` 开始','cm-fix','claude'));
528
+ assert.ok(typed('就用 `$cm-fix`','cm-fix','codex'));
529
+ const f=fixture(t);
530
+ await f.send('修这个 bug');
531
+ await f.send('参考 文档/cm-fix 那页');
532
+ assert.deepEqual(f.log().map(entry=>entry.event),['hint']);
533
+ });
534
+
535
+ // ---- refresh: an install or upgrade brings an enabled copy up to the installed version ----
536
+
537
+ const COPIED=[SCRIPT_NAME,RULES_NAME,'cm-matt-skills.mjs','cm-config-lock.mjs','cm-skill-judge.mjs'];
538
+ const shippedFile=name=>fs.readFileSync(path.join(path.dirname(defaultRulesPath()),name),'utf8');
539
+ const bytesOf=file=>fs.existsSync(file)?fs.readFileSync(file,'utf8'):null;
540
+
541
+ test('refresh brings an enabled copy up to date and leaves configs, trust, session state and logs alone',async t=>{
542
+ const f=fixture(t);
543
+ await enable({env:f.env,node:'/usr/bin/node',write:()=>{}});
544
+ const dir=installDir(f.env);
545
+ for(const name of COPIED)fs.writeFileSync(path.join(dir,name),'// old version\n');
546
+ const state=path.join(dir,'state','0123456789abcdef.json');
547
+ fs.mkdirSync(path.dirname(state),{recursive:true});
548
+ fs.writeFileSync(state,'{"hinted":["cm-fix"],"pending":[]}');
549
+ fs.mkdirSync(path.dirname(logFile(f.env)),{recursive:true});
550
+ fs.writeFileSync(logFile(f.env),'{"event":"hint"}\n');
551
+ const trust=path.join(f.env.CODEX_HOME,'config.toml');
552
+ fs.writeFileSync(trust,'[hooks.state]\nx = "trusted"\n');
553
+ const before=[claudeSettingsPath(f.env),codexHooksPath(f.env),trust,state,logFile(f.env)].map(bytesOf);
554
+ let out='';
555
+ assert.equal(await refresh({env:f.env,write:text=>{out+=text;}}),0);
556
+ for(const name of COPIED)assert.ok(fs.readFileSync(path.join(dir,name),'utf8')===shippedFile(name),name);
557
+ assert.deepEqual([claudeSettingsPath(f.env),codexHooksPath(f.env),trust,state,logFile(f.env)].map(bytesOf),before);
558
+ assert.match(out,/已刷新/);
559
+ });
560
+
561
+ test('refresh never creates the copy or touches any config for a user who did not enable hints',async t=>{
562
+ const f=fixture(t);
563
+ let out='';
564
+ assert.equal(await refresh({env:f.env,write:text=>{out+=text;}}),0);
565
+ assert.equal(out,'');
566
+ assert.ok(!fs.existsSync(f.env.CM_WORKFLOW_HOME));
567
+ assert.ok(!fs.existsSync(claudeSettingsPath(f.env)));
568
+ assert.ok(!fs.existsSync(codexHooksPath(f.env)));
569
+ });
570
+
571
+ test('refresh counts a wired hook as enabled even when the copy is gone',async t=>{
572
+ const f=fixture(t);
573
+ fs.mkdirSync(path.dirname(codexHooksPath(f.env)),{recursive:true});
574
+ const wired=JSON.stringify({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:hookCommand(f.env,'codex','/usr/bin/node')}]}]}});
575
+ fs.writeFileSync(codexHooksPath(f.env),wired);
576
+ assert.equal(await refresh({env:f.env,write:()=>{}}),0);
577
+ for(const name of COPIED)assert.ok(fs.readFileSync(path.join(installDir(f.env),name),'utf8')===shippedFile(name),name);
578
+ assert.equal(fs.readFileSync(codexHooksPath(f.env),'utf8'),wired);
579
+ assert.ok(!fs.existsSync(claudeSettingsPath(f.env)));
580
+ });
581
+
582
+ test('refresh does not take a link at the copy path as an enabled install',async t=>{
583
+ const f=fixture(t);
584
+ const elsewhere=path.join(f.home,'elsewhere');
585
+ fs.mkdirSync(elsewhere);
586
+ fs.mkdirSync(f.env.CM_WORKFLOW_HOME,{recursive:true});
587
+ fs.symlinkSync(elsewhere,installDir(f.env));
588
+ assert.equal(await refresh({env:f.env,write:()=>{}}),0);
589
+ assert.deepEqual(fs.readdirSync(elsewhere),[]);
590
+ });
591
+
592
+ test('a failed refresh warns, exits non-zero and keeps the previous script',async t=>{
593
+ const f=fixture(t);
594
+ const dir=installDir(f.env);
595
+ fs.mkdirSync(path.join(dir,'cm-config-lock.mjs','blocker'),{recursive:true});
596
+ fs.writeFileSync(path.join(dir,SCRIPT_NAME),'// previous working copy\n');
597
+ let out='';
598
+ assert.equal(await refresh({env:f.env,write:text=>{out+=text;}}),1);
599
+ assert.equal(fs.readFileSync(path.join(dir,SCRIPT_NAME),'utf8'),'// previous working copy\n');
600
+ assert.match(out,/⚠.*未刷新/);
601
+ });
602
+
603
+ test('status says whether the copy matches the installed version and how to refresh it',async t=>{
604
+ const f=fixture(t);
605
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/运行副本:未建/);
606
+ await enable({env:f.env,node:'/usr/bin/node',write:()=>{}});
607
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/运行副本:与已装版本一致/);
608
+ fs.writeFileSync(path.join(installDir(f.env),RULES_NAME),'{"rules":[]}');
609
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
610
+ assert.match(text,new RegExp(`运行副本与已装版本不一致(${RULES_NAME})`));
611
+ assert.match(text,/cm-skill-hints\.mjs'? refresh/);
612
+ fs.rmSync(installDir(f.env),{recursive:true});
613
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/运行副本缺失.*refresh/);
614
+ });
615
+
616
+ test('main refresh is wired and reports its own exit code',async t=>{
617
+ const f=fixture(t);
618
+ let out='';
619
+ assert.equal(await main(['refresh'],{env:f.env,write:text=>{out+=text;}}),0);
620
+ assert.ok(!fs.existsSync(installDir(f.env)));
621
+ assert.equal(await main(['refresh','extra'],{env:f.env,write:()=>{},error:()=>{}}),2);
622
+ });
623
+
624
+ test('refresh and enable never write through a linked copy directory, even with the hook wired',async t=>{
625
+ const f=fixture(t);
626
+ const elsewhere=path.join(f.home,'elsewhere');
627
+ fs.mkdirSync(elsewhere);
628
+ fs.writeFileSync(path.join(elsewhere,RULES_NAME),'keep');
629
+ fs.mkdirSync(f.env.CM_WORKFLOW_HOME,{recursive:true});
630
+ fs.symlinkSync(elsewhere,installDir(f.env));
631
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
632
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:hookCommand(f.env,'claude','/usr/bin/node')}]}]}}));
633
+ let out='';
634
+ assert.equal(await refresh({env:f.env,write:text=>{out+=text;}}),1);
635
+ assert.match(out,/⚠.*未刷新.*不是普通目录/);
636
+ assert.equal(await enable({env:f.env,hosts:['claude'],write:()=>{}}),1);
637
+ assert.deepEqual(fs.readdirSync(elsewhere),[RULES_NAME]);
638
+ assert.equal(fs.readFileSync(path.join(elsewhere,RULES_NAME),'utf8'),'keep');
639
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/⚠ 运行副本目录不是普通目录/);
640
+ });
641
+
642
+ test('status never blocks on a special file in the copy and does not take a linked file as current',
643
+ {skip:process.platform==='win32'},async t=>{
644
+ const f=fixture(t);
645
+ await enable({env:f.env,node:'/usr/bin/node',write:()=>{}});
646
+ const dir=installDir(f.env);
647
+ fs.rmSync(path.join(dir,'cm-matt-skills.mjs'));
648
+ execFileSync('mkfifo',[path.join(dir,'cm-matt-skills.mjs')]);
649
+ fs.rmSync(path.join(dir,RULES_NAME));
650
+ fs.symlinkSync(defaultRulesPath(),path.join(dir,RULES_NAME));
651
+ fs.rmSync(path.join(dir,'cm-config-lock.mjs'));
652
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
653
+ assert.match(text,/运行副本与已装版本不一致(cm-matt-skills\.mjs、cm-config-lock\.mjs、cm-skill-hints\.json)/);
654
+ });
655
+
656
+ test('run from the copy itself, status and refresh do not claim the copy is current',async t=>{
657
+ const f=fixture(t);
658
+ await enable({env:f.env,node:'/usr/bin/node',write:()=>{}});
659
+ const copy=await import(path.join(installDir(f.env),SCRIPT_NAME));
660
+ fs.writeFileSync(path.join(installDir(f.env),RULES_NAME),'{"rules":[]}');
661
+ assert.match(copy.statusText({env:f.env}),/无法核验.*已装版本/);
662
+ let out='';
663
+ assert.equal(await copy.refresh({env:f.env,write:text=>{out+=text;}}),1);
664
+ assert.match(out,/运行副本本身/);
665
+ assert.equal(fs.readFileSync(path.join(installDir(f.env),RULES_NAME),'utf8'),'{"rules":[]}');
666
+ });
667
+
668
+ test('a UserPromptSubmit that is not a list is reported by status, not thrown',async t=>{
669
+ const f=fixture(t);
670
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
671
+ fs.writeFileSync(claudeSettingsPath(f.env),'{"hooks":{"UserPromptSubmit":{}}}');
672
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/Claude 格式异常(UserPromptSubmit 不是列表)/);
673
+ assert.equal(fs.readFileSync(claudeSettingsPath(f.env),'utf8'),'{"hooks":{"UserPromptSubmit":{}}}');
674
+ });
675
+
676
+ test('enable refuses a host config whose hooks or UserPromptSubmit has the wrong shape and keeps its bytes',async t=>{
677
+ const f=fixture(t);
678
+ const shapes=['{"hooks":{"UserPromptSubmit":{"hooks":[{"type":"command","command":"echo keep-me"}]}}}',
679
+ '{"hooks":["keep-me"]}','{"hooks":"keep-me"}'];
680
+ for(const host of ['claude','codex']){
681
+ const file=host==='codex'?codexHooksPath(f.env):claudeSettingsPath(f.env);
682
+ fs.mkdirSync(path.dirname(file),{recursive:true});
683
+ for(const text of shapes){
684
+ fs.writeFileSync(file,text);
685
+ let out='';
686
+ assert.equal(await enable({env:f.env,hosts:[host],node:'/usr/bin/node',write:chunk=>{out+=chunk;}}),1,`${host} ${text}`);
687
+ assert.match(out,/格式异常.*未改动/);
688
+ assert.equal(fs.readFileSync(file,'utf8'),text);
689
+ }
690
+ }
691
+ });
692
+
693
+ // ---- auto-invoke (方案-技能自动调用 2026-10-25) ----
694
+ // Jev is always a fake here: `jev` answers with the given probabilities, or throws.
695
+
696
+ const INVOKE_RULES={version:1,rules:[
697
+ {id:'long-session',skill:'handoff',author:true,keywords:['会话太长'],reason:'写交接',invoke:{mode:'direct',when:'写交接'}},
698
+ {id:'multi-session-work',skill:'wayfinder',author:true,keywords:['好几个会话'],reason:'拆决策票',
699
+ fallback:{skill:'cm-prd',reason:'拆规格'},invoke:{mode:'ask',when:'拆决策票',near:'排个计划'}},
700
+ {id:'fix-bug',skill:'cm-fix',keywords:['修这个 bug'],reason:'先复现'},
701
+ ]};
702
+ function invoking(t,{installed=['handoff','wayfinder'],local,answer={none:1},key='fake-key'}={}){
703
+ const f=fixture(t,{rules:INVOKE_RULES,local,authorNames:['handoff','wayfinder'],
704
+ authorSkills:installed.flatMap(name=>[['.claude/skills',name],['.agents/skills',name]])});
705
+ const calls=[];
706
+ const fetchImpl=async(url,options)=>{
707
+ const sent=JSON.parse(options.body);
708
+ calls.push(sent);
709
+ if(answer instanceof Error)throw answer;
710
+ // Options the test leaves out get 0, so every option asked has a probability.
711
+ const probabilities=Object.fromEntries(Object.keys(sent.questions.skill.criteria).map(label=>[label,answer[label]??0]));
712
+ return new Response(JSON.stringify({answers:{skill:{type:'choice',probabilities}}}),{status:200});
713
+ };
714
+ const loadAuthor=async()=>({...(await loadAuthorCheck()),skills:f.authorOptions.skills,license:f.authorOptions.license});
715
+ const run=async(prompt,{host='claude',session='s1',loadJudgeModule}={})=>{
716
+ const out=await hook({prompt,session_id:session},{env:f.env,host,rulesFile:f.rulesFile,now:NOW,loadAuthor,
717
+ judgeOptions:{key,fetchImpl},...(loadJudgeModule?{loadJudgeModule}:{})});
718
+ return out?JSON.parse(out):null;
719
+ };
720
+ return {...f,calls,run};
721
+ }
722
+
723
+ test('a fitting direct skill: the model is told to read its SKILL.md and the user sees one line',async t=>{
724
+ const f=invoking(t,{answer:{handoff:0.97,wayfinder:0.01,none:0.02}});
725
+ const out=await f.run('今天先到这,明天接着做');
726
+ assert.deepEqual(Object.keys(out),['systemMessage','hookSpecificOutput']);
727
+ assert.equal(out.systemMessage,'🤖 技能自动调用:已让模型用 /handoff');
728
+ assert.equal(out.hookSpecificOutput.hookEventName,'UserPromptSubmit');
729
+ const file=path.join(f.home,'.claude/skills/handoff/SKILL.md');
730
+ assert.ok(out.hookSpecificOutput.additionalContext.includes(`先用 Read 工具读取 ${file},再严格按其中的步骤执行`));
731
+ const codex=await f.run('今天先到这,明天接着做',{host:'codex'});
732
+ assert.equal(codex.systemMessage,'🤖 技能自动调用:已让模型用 $handoff');
733
+ assert.ok(codex.hookSpecificOutput.additionalContext.includes(`先读取文件 ${path.join(f.home,'.agents/skills/handoff/SKILL.md')}`));
734
+ });
735
+
736
+ test('an ask skill: the model is told to ask the user first',async t=>{
737
+ const f=invoking(t,{answer:{wayfinder:0.9,handoff:0.05,none:0.05}});
738
+ const out=await f.run('这活很大,得慢慢来');
739
+ assert.equal(out.systemMessage,'🤖 技能自动调用:已让模型先问你要不要用 /wayfinder');
740
+ assert.match(out.hookSpecificOutput.additionalContext,/先用一句话问用户要不要用它/);
741
+ assert.match(out.hookSpecificOutput.additionalContext,/用户同意后,用 Read 工具读取 .*wayfinder\/SKILL\.md/);
742
+ // Jev sees the candidates, their look-alike and none; only the first 500 characters.
743
+ assert.deepEqual(Object.keys(f.calls[0].questions.skill.criteria),['handoff','wayfinder','wayfinder~near','none']);
744
+ });
745
+
746
+ test('Jev decides when it answers: a keyword match it calls none starts and hints nothing',async t=>{
747
+ const f=invoking(t,{answer:{handoff:0.1,none:0.9}});
748
+ assert.equal(await f.run('会话太长的时候界面会卡吗'),null);
749
+ assert.equal(f.calls.length,1);
750
+ // Other rules still hint alongside.
751
+ assert.deepEqual(Object.keys(await f.run('修这个 bug',{session:'s2'})),['systemMessage']);
752
+ });
753
+
754
+ test('when Jev fails, the invoke rule\'s keywords decide, and the failure is logged without text',async t=>{
755
+ const f=invoking(t,{answer:new TypeError('fetch failed')});
756
+ const out=await f.run('会话太长了,换个会话接着做');
757
+ assert.equal(out.systemMessage,'🤖 技能自动调用:已让模型用 /handoff');
758
+ assert.equal(f.calls.length,2);
759
+ assert.deepEqual(f.log().map(({event,via,error,skill,mode})=>({event,via,error,skill,mode})),[
760
+ {event:'judge-error',via:undefined,error:'network',skill:undefined,mode:undefined},
761
+ {event:'invoke',via:'keyword',error:undefined,skill:'handoff',mode:'direct'}]);
762
+ assert.doesNotMatch(fs.readFileSync(logFile(f.env),'utf8'),/会话太长|换个会话|fake-key/);
763
+ assert.equal(await f.run('今天先到这',{session:'s2'}),null);
764
+ });
765
+
766
+ test('a message with a credential never reaches Jev; keywords still work',async t=>{
767
+ const f=invoking(t,{answer:{handoff:1}});
768
+ const secret='sk-'+'Q1w2E3r4'.repeat(3);
769
+ assert.equal((await f.run(`会话太长了,key 是 ${secret}`)).systemMessage,'🤖 技能自动调用:已让模型用 /handoff');
770
+ assert.equal(await f.run(`换个话题,key 是 ${secret}`,{session:'s2'}),null);
771
+ assert.equal(await f.run('换个话题,密码是 hunter2',{session:'s3'}),null);
772
+ // The TypeSafe key itself, whatever its shape.
773
+ assert.equal(await f.run('帮我看看配置里的 fake-key 对不对',{session:'s4'}),null);
774
+ assert.equal(f.calls.length,0);
775
+ assert.deepEqual(f.log().filter(entry=>entry.event==='judge-error').map(entry=>entry.error),['secret','secret','secret','secret']);
776
+ assert.doesNotMatch(fs.readFileSync(logFile(f.env),'utf8'),/hunter2|Q1w2E3r4|fake-key/);
777
+ });
778
+
779
+ test('nothing is judged or added when the message opens with a command or is too long',async t=>{
780
+ const f=invoking(t,{answer:{handoff:1}});
781
+ assert.equal(await f.run('/handoff 下个会话负责导出'),null);
782
+ assert.equal(await f.run('$wayfinder 拆一下',{host:'codex'}),null);
783
+ assert.equal(await f.run('/grill-me 先问透'),null);
784
+ assert.equal(await f.run('写交接'+'x'.repeat(MAX_PROMPT)),null);
785
+ assert.equal(f.calls.length,0);
786
+ });
787
+
788
+ test('a skill that is not the installed author version is never judged or started; its fallback hints as before',async t=>{
789
+ const f=invoking(t,{installed:['handoff'],answer:{handoff:0.1,none:0.9}});
790
+ const out=await f.run('这个活要分好几个会话做');
791
+ assert.deepEqual(Object.keys(out),['systemMessage']);
792
+ assert.match(out.systemMessage,/可以试 \/cm-prd——拆规格/);
793
+ assert.deepEqual(Object.keys(f.calls[0].questions.skill.criteria),['handoff','none']);
794
+ const none=invoking(t,{installed:[],answer:{handoff:1}});
795
+ assert.equal(await none.run('今天先到这'),null);
796
+ assert.equal(none.calls.length,0);
797
+ });
798
+
799
+ test('judge:false, no key or a missing judge module all fall back to keywords without a call',async t=>{
800
+ for(const options of [{local:{judge:false}},{key:''}]){
801
+ const f=invoking(t,{...options,answer:{handoff:1}});
802
+ assert.equal(await f.run('今天先到这'),null);
803
+ assert.match((await f.run('会话太长了',{session:'s2'})).systemMessage,/已让模型用 \/handoff/);
804
+ assert.equal(f.calls.length,0);
805
+ assert.deepEqual(f.log().map(entry=>entry.event),['invoke']);
806
+ }
807
+ const f=invoking(t,{answer:{handoff:1}});
808
+ assert.match((await f.run('会话太长了',{loadJudgeModule:async()=>null})).systemMessage,/已让模型用 \/handoff/);
809
+ assert.equal(f.calls.length,0);
810
+ });
811
+
812
+ test('a user rule cannot start a skill, even naming an author skill with invoke',async t=>{
813
+ const f=invoking(t,{installed:['handoff'],local:{rules:[{id:'long-session',skill:'handoff',author:true,keywords:['收工'],
814
+ reason:'mine',invoke:{mode:'direct',when:'x'}}]},answer:{handoff:1}});
815
+ const out=await f.run('收工');
816
+ assert.deepEqual(Object.keys(out),['systemMessage']);
817
+ assert.match(out.systemMessage,/可以试 \/handoff——mine/);
818
+ assert.equal(f.calls.length,0);
819
+ });
820
+
821
+ test('a later request in the same session starts the skill again',async t=>{
822
+ const f=invoking(t,{answer:{handoff:0.95,none:0.05}});
823
+ assert.ok((await f.run('先到这,交接一下')).hookSpecificOutput);
824
+ assert.ok((await f.run('再交接一次,刚才漏了')).hookSpecificOutput);
825
+ });
826
+
827
+ test('the shipped table marks only handoff direct and the two heavy skills ask',()=>{
828
+ const {rules}=loadRules({env:{HOME:'/nonexistent',CM_WORKFLOW_HOME:'/nonexistent/.cm'}});
829
+ assert.deepEqual(Object.fromEntries(rules.filter(rule=>rule.invoke).map(rule=>[rule.skill,rule.invoke.mode])),
830
+ {handoff:'direct',wayfinder:'ask','improve-codebase-architecture':'ask'});
831
+ });