@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,669 @@
1
+ #!/usr/bin/env node
2
+ // Skill hints: a UserPromptSubmit hook for Claude Code and Codex that matches the
3
+ // user's message against a keyword table and shows the user at most two fitting
4
+ // skills. Most rules only hint; the few marked `invoke` start an author skill instead
5
+ // (see "Auto-invoke" below).
6
+ //
7
+ // The hint goes to the user directly (`systemMessage`), not to the model: real
8
+ // sessions showed a model told "mention it only if it fits" left even clear cases
9
+ // out (2026-10-24). Shown directly, it is always seen and costs no context.
10
+ //
11
+ // Decided 2026-10-23 (方案-技能提醒): keywords not AI, so nothing leaves the machine
12
+ // and no tokens are spent; the CM table ships here, the user's own table lives in
13
+ // ~/.cm-workflow/skill-hints.local.json and wins; the log keeps rule ids and times,
14
+ // never message text. Any error exits quietly so a message is never held up.
15
+ // Wiring is on by default (decided 2026-10-25): each installer runs `install --host <its
16
+ // host>`, which adds the hook once per host and otherwise only refreshes the copy the hook
17
+ // runs. It never wires against the user's choice: --no-skill-hints,
18
+ // CM_SKILL_HINTS_INSTALL=off, "enabled": false, or a hook the user removed after it was
19
+ // there (see "settled hosts" below). `enable` still adds the hook by hand.
20
+ //
21
+ // Auto-invoke, decided 2026-10-25 (方案-技能自动调用): author skills the model cannot
22
+ // start itself (`disable-model-invocation`) get a rule with `invoke`. When one fits, the
23
+ // hook tells the model to read that skill's SKILL.md and follow it (mode "direct"), or to
24
+ // ask the user first (mode "ask"), and shows the user one line saying so. Whether it fits
25
+ // is judged by Jev when a TypeSafe key exists (cm-skill-judge.mjs: first 500 characters
26
+ // only, never a message that looks like it holds a secret, 3 seconds at most), else and
27
+ // on any Jev failure by the rule's keywords. Only the pinned author version is started.
28
+ import fs from 'node:fs';
29
+ import os from 'node:os';
30
+ import path from 'node:path';
31
+ import vm from 'node:vm';
32
+ import crypto from 'node:crypto';
33
+ import {fileURLToPath} from 'node:url';
34
+
35
+ export const SCRIPT_NAME='cm-skill-hints.mjs';
36
+ export const RULES_NAME='cm-skill-hints.json';
37
+ export const LOCAL_NAME='skill-hints.local.json';
38
+ export const AUTO_NAME='skill-hints.auto.json';
39
+ // Copied together into ~/.cm-workflow/skill-hints so the hook runs without the CM tree.
40
+ // They are written before the script itself, so a failed copy leaves the old script.
41
+ const COMPANIONS=['cm-matt-skills.mjs','cm-config-lock.mjs','cm-skill-judge.mjs',RULES_NAME];
42
+ export const MAX_PROMPT=2000;
43
+ export const MAX_HINTS=2;
44
+ export const ADOPT_WINDOW=5;
45
+ export const LOG_LIMIT=1024*1024;
46
+ export const PATTERN_BUDGET_MS=200;
47
+ const MAX_READ=1024*1024;
48
+ const HOSTS=['claude','codex'];
49
+ const SKILL_NAME=/^[\w.:-]+$/;
50
+ const INVOKE_MODES=['direct','ask'];
51
+
52
+ const homeOf=env=>env.HOME||os.homedir();
53
+ export const cmHome=env=>path.resolve(env.CM_WORKFLOW_HOME||path.join(homeOf(env),'.cm-workflow'));
54
+ export const logFile=env=>path.join(path.resolve(env.CM_WORKFLOW_LOG_HOME||path.join(cmHome(env),'logs')),'skill-hints.jsonl');
55
+ export const localPath=env=>path.join(cmHome(env),LOCAL_NAME);
56
+ export const installDir=env=>path.join(cmHome(env),'skill-hints');
57
+ export const autoPath=env=>path.join(cmHome(env),AUTO_NAME);
58
+ export const claudeSettingsPath=env=>path.join(path.resolve(env.CLAUDE_HOME||path.join(homeOf(env),'.claude')),'settings.json');
59
+ export const codexHooksPath=env=>path.join(path.resolve(env.CODEX_HOME||path.join(homeOf(env),'.codex')),'hooks.json');
60
+ const here=path.dirname(fileURLToPath(import.meta.url));
61
+ export const defaultRulesPath=()=>path.join(here,RULES_NAME);
62
+
63
+ // An author skill counts only when it is the pinned author version (same contract as
64
+ // cm-matt-skills: a same-named skill with other content is not it). Checked lazily,
65
+ // only for rules that matched, and only in the current host's skills directory.
66
+ // The checker is loaded inside the hook's quiet boundary; if it cannot be loaded,
67
+ // no author skill counts as installed and CM counterparts are hinted instead.
68
+ export async function loadAuthorCheck(specifier='./cm-matt-skills.mjs'){
69
+ try{
70
+ const {SKILLS,UPSTREAM,skillState,skillRoots}=await import(new URL(specifier,import.meta.url).href);
71
+ return {skills:SKILLS,license:UPSTREAM.license.sha256,skillState,skillRoots};
72
+ }catch{return null;}
73
+ }
74
+ export function isAuthorInstalled(name,host,env,check){
75
+ const skill=check?.skills.find(item=>item.name===name);
76
+ const root=check?.skillRoots(env).find(item=>item.runtime===host)?.root;
77
+ return Boolean(skill&&root)&&check.skillState(root,skill,check.license)==='author';
78
+ }
79
+ export const mention=(skill,host)=>`${host==='codex'?'$':'/'}${skill}`;
80
+ // Loaded like the author checker: if it cannot be loaded, every invoke rule uses keywords.
81
+ export async function loadJudge(specifier='./cm-skill-judge.mjs'){
82
+ try{return await import(new URL(specifier,import.meta.url).href);}catch{return null;}
83
+ }
84
+
85
+ // Only a regular file of bounded size is read: a FIFO or device at one of these
86
+ // paths would otherwise block the hook. `allowEmpty` is only for per-session state, where
87
+ // an empty file just means nothing hinted yet. Every config (host, local, CM table, record)
88
+ // is strict: an empty one is not valid JSON and is reported, never rewritten.
89
+ export function readJson(file,{allowEmpty=false}={}){
90
+ let text;
91
+ try{
92
+ const st=fs.lstatSync(file);
93
+ if(!st.isFile())return {error:'not-file'};
94
+ if(st.size>MAX_READ)return {error:'too-large'};
95
+ text=fs.readFileSync(file,'utf8');
96
+ }catch(error){if(error.code==='ENOENT')return {missing:true};return {error:error.code||'read'};}
97
+ if(!text.trim())return allowEmpty?{value:{},text}:{error:'empty'};
98
+ try{return {value:JSON.parse(text),text};}catch{return {error:'parse'};}
99
+ }
100
+
101
+ const strings=value=>Array.isArray(value)?value.filter(item=>typeof item==='string'&&item.trim()):[];
102
+ export function normalizeRule(rule,user){
103
+ if(!rule||typeof rule!=='object'||typeof rule.skill!=='string'||!SKILL_NAME.test(rule.skill))return null;
104
+ const keywords=strings(rule.keywords).map(word=>word.toLowerCase());
105
+ const patterns=strings(rule.patterns).flatMap(source=>{try{return [new RegExp(source,'i')];}catch{return [];}});
106
+ if(!keywords.length&&!patterns.length)return null;
107
+ const fallback=rule.fallback&&typeof rule.fallback.skill==='string'&&SKILL_NAME.test(rule.fallback.skill)
108
+ ?{skill:rule.fallback.skill,reason:String(rule.fallback.reason??'')}:null;
109
+ // Starting a skill is for CM's own author rules only; a user rule never gets it.
110
+ const invoke=!user&&rule.author===true&&INVOKE_MODES.includes(rule.invoke?.mode)&&typeof rule.invoke.when==='string'&&rule.invoke.when.trim()
111
+ ?{mode:rule.invoke.mode,when:rule.invoke.when,...(typeof rule.invoke.near==='string'&&rule.invoke.near.trim()?{near:rule.invoke.near}:{})}:null;
112
+ return {id:typeof rule.id==='string'&&rule.id?rule.id:`${user?'user':'cm'}:${rule.skill}`,skill:rule.skill,
113
+ reason:String(rule.reason??''),author:rule.author===true,fallback,keywords,patterns,user,invoke};
114
+ }
115
+
116
+ // The known fields of the user's local file and their types. One check, used by the hook,
117
+ // by `status` and by the installers, so they never disagree about a file.
118
+ export function localShapeError(value){
119
+ if(!value||typeof value!=='object'||Array.isArray(value))return '应为对象';
120
+ for(const key of ['enabled','judge'])if(value[key]!==undefined&&typeof value[key]!=='boolean')return `${key} 只能是 true 或 false`;
121
+ if(value.rules!==undefined&&!Array.isArray(value.rules))return 'rules 应为列表';
122
+ if(value.disable!==undefined&&!(Array.isArray(value.disable)&&value.disable.every(item=>typeof item==='string')))return 'disable 应为字符串列表';
123
+ return null;
124
+ }
125
+ // {settings} for a usable file (or none), else {settings:{}, error}: a read code such as
126
+ // 'parse', or a shape reason.
127
+ export function readLocal(env){
128
+ // Strict JSON: an empty or blank file is a problem like broken JSON (review round 4).
129
+ const local=readJson(localPath(env));
130
+ if(local.missing)return {settings:{},error:null,missing:true};
131
+ if(local.error)return {settings:{},error:local.error};
132
+ const shape=localShapeError(local.value);
133
+ return shape?{settings:{},error:`格式异常(${shape})`,shape:true}:{settings:local.value,error:null};
134
+ }
135
+
136
+ // User rules come first so they win a tie. A user rule with a CM rule's id replaces
137
+ // it, and `disable` switches CM rules off by id. A local file with any problem (cannot be
138
+ // read, not an object, a known field of the wrong type) pauses hints as a whole, decided
139
+ // 2026-10-25: no hint, no skill started, nothing sent to Jev. Taking only its good parts
140
+ // could drop a valid "enabled": false next to a broken field. `status` reports the cause.
141
+ export function loadRules({env=process.env,rulesFile=defaultRulesPath()}={}){
142
+ const local=readLocal(env);
143
+ if(local.error)return {enabled:false,paused:true,rules:[],localError:local.error};
144
+ const settings=local.settings;
145
+ if(settings.enabled===false)return {enabled:false,rules:[]};
146
+ const defaults=readJson(rulesFile);
147
+ const user=(Array.isArray(settings.rules)?settings.rules:[]).map(rule=>normalizeRule(rule,true)).filter(Boolean);
148
+ const disabled=new Set(strings(settings.disable));
149
+ const replaced=new Set(user.map(rule=>rule.id));
150
+ const cm=(Array.isArray(defaults.value?.rules)?defaults.value.rules:[])
151
+ .map(rule=>normalizeRule(rule,false)).filter(rule=>rule&&!disabled.has(rule.id)&&!replaced.has(rule.id));
152
+ return {enabled:true,rules:[...user,...cm],judge:settings.judge!==false,localError:null,defaultsError:defaults.error??(defaults.missing?'missing':null),
153
+ userCount:user.length,disabledCount:disabled.size,cmCount:cm.length};
154
+ }
155
+
156
+ // Pasted logs and code are where stray keywords live, so fenced blocks never match.
157
+ export const stripCode=text=>text.replace(/```[\s\S]*?(?:```|$)/g,' ');
158
+
159
+ // A user regex can backtrack for minutes; it runs in a context with a hard time
160
+ // budget, and on timeout no pattern counts as matched (keywords still do).
161
+ export function patternMatches(rules,text,budget=PATTERN_BUDGET_MS){
162
+ const lists=rules.map(rule=>rule.patterns);
163
+ if(!lists.some(list=>list.length))return lists.map(()=>false);
164
+ try{
165
+ return vm.runInNewContext('lists.map(list=>list.some(pattern=>pattern.test(text)))',{lists,text},{timeout:budget});
166
+ }catch{return lists.map(()=>false);}
167
+ }
168
+
169
+ // An author skill that is not installed falls back to its CM counterpart, or is dropped.
170
+ function resolve(rule,host,env,authorCheck){
171
+ if(rule.user||!rule.author||isAuthorInstalled(rule.skill,host,env,authorCheck))return {rule:rule.id,skill:rule.skill,reason:rule.reason};
172
+ return rule.fallback?{rule:rule.id,skill:rule.fallback.skill,reason:rule.fallback.reason}:null;
173
+ }
174
+
175
+ // `/name` or `$name` as a whole token: not `/cm-fix-extra`, not the tail of a URL or
176
+ // path. It must start the message or follow whitespace or an opening/separating
177
+ // punctuation mark or a backtick; a letter of any script before it (as in `文档/cm-fix`)
178
+ // does not count.
179
+ const escape=text=>text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
180
+ const BEFORE='(?<=^|[\\s`(\\[{<"\'“‘(【「『《,。、;:!?,;!?])';
181
+ export const typed=(prompt,skill,host)=>
182
+ new RegExp(`${BEFORE}${escape(mention(skill,host))}(?![\\w.:/-])`,'i').test(prompt);
183
+
184
+ // Which rules' keywords or patterns occur in the message (fenced code left out).
185
+ export function keywordHits(rules,prompt){
186
+ const text=stripCode(prompt.toLowerCase());
187
+ const byPattern=patternMatches(rules,text);
188
+ return rules.map((rule,index)=>rule.keywords.some(word=>text.includes(word))||byPattern[index]);
189
+ }
190
+
191
+ export function pickHints({prompt,rules,host,env,hinted=[],authorCheck=null}){
192
+ const lower=prompt.toLowerCase();
193
+ const hits=keywordHits(rules,prompt);
194
+ const picked=[];
195
+ for(const [index,rule] of rules.entries()){
196
+ if(picked.length>=MAX_HINTS)break;
197
+ if(!hits[index])continue;
198
+ const hint=resolve(rule,host,env,authorCheck);
199
+ if(!hint||hinted.includes(hint.skill)||picked.some(item=>item.skill===hint.skill))continue;
200
+ // The user already typed or named it: nothing to remind.
201
+ if(lower.includes(hint.skill.toLowerCase()))continue;
202
+ picked.push(hint);
203
+ }
204
+ return picked;
205
+ }
206
+
207
+ // Per-session state: skills already hinted, and hints still waiting to be adopted.
208
+ const statePath=(env,session)=>path.join(installDir(env),'state',
209
+ `${crypto.createHash('sha256').update(String(session)).digest('hex').slice(0,16)}.json`);
210
+ function readState(file){
211
+ const read=readJson(file,{allowEmpty:true}).value;
212
+ return {hinted:strings(read?.hinted),pending:Array.isArray(read?.pending)?read.pending.filter(item=>
213
+ item&&typeof item.skill==='string'&&typeof item.rule==='string'&&Number.isInteger(item.left)):[]};
214
+ }
215
+ // Replace by rename of a freshly created file, so a link planted at the path is never written through.
216
+ function writeAtomic(file,text,{before}={}){
217
+ const temporary=`${file}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
218
+ fs.mkdirSync(path.dirname(file),{recursive:true});
219
+ try{
220
+ fs.writeFileSync(temporary,text,{flag:'wx',mode:0o600});
221
+ before?.();
222
+ fs.renameSync(temporary,file);
223
+ }finally{try{fs.unlinkSync(temporary);}catch{/* 已改名或未创建 */}}
224
+ }
225
+
226
+ // Rule id, skill, host and time only: the message itself is never written.
227
+ // A log path that is not a regular file is left alone (appending could block).
228
+ export function appendLog(env,record){
229
+ const file=logFile(env);
230
+ fs.mkdirSync(path.dirname(file),{recursive:true});
231
+ try{
232
+ const st=fs.lstatSync(file);
233
+ if(!st.isFile())return;
234
+ if(st.size>LOG_LIMIT){
235
+ const lines=fs.readFileSync(file,'utf8').split('\n').filter(Boolean);
236
+ writeAtomic(file,lines.slice(Math.ceil(lines.length/2)).join('\n')+'\n');
237
+ }
238
+ }catch(error){if(error.code!=='ENOENT')throw error;}
239
+ fs.appendFileSync(file,JSON.stringify(record)+'\n',{mode:0o600});
240
+ }
241
+
242
+ // ---- auto-invoke ----
243
+
244
+ // A message that opens with a command (`/grill-me …`, `$handoff`) already names its
245
+ // skill: the host runs it, so nothing is judged or added.
246
+ export const opensWithCommand=prompt=>/^\s*[/$][\w.:-]+(?:\s|$)/.test(prompt);
247
+ export const skillFile=(skill,host,env,check)=>
248
+ path.join(check.skillRoots(env).find(item=>item.runtime===host).root,skill,'SKILL.md');
249
+
250
+ // What the model is told. The "direct" wording is the one the 2026-10-25 gate test
251
+ // measured (5 of 5 sessions read the file first and followed it).
252
+ export function invokeContext({skill,mode,reason},file,host){
253
+ const read=host==='claude'?`先用 Read 工具读取 ${file}`:`先读取文件 ${file}`;
254
+ if(mode==='direct')return `[CM 技能提醒] 这条消息属于作者技能 ${skill} 的场景。请${read},再严格按其中的步骤执行(该技能不能用 Skill 工具调起,必须读文件照做)。`;
255
+ return `[CM 技能提醒] 这条消息可能适合用作者技能 ${skill}(${reason})。作者把它设为手动调用,因为它动静较大,所以请先用一句话问用户要不要用它,别的什么都先不做。用户同意后,${read.slice(1)},再严格按其中的步骤执行;用户不同意就照常回答。`;
256
+ }
257
+ export const invokeLine=({skill,mode},host)=>mode==='direct'
258
+ ?`🤖 技能自动调用:已让模型用 ${mention(skill,host)}`
259
+ :`🤖 技能自动调用:已让模型先问你要不要用 ${mention(skill,host)}`;
260
+
261
+ // The invoke rule to start for this message, or null. Jev decides when it answered;
262
+ // keywords decide when it could not (no key, secret, timeout, error, switched off).
263
+ export async function pickInvoke({prompt,rules,host,env,authorCheck,judgeModule,useJudge=true,judgeOptions={}}){
264
+ const candidates=rules.filter(rule=>rule.invoke&&isAuthorInstalled(rule.skill,host,env,authorCheck));
265
+ if(!candidates.length||opensWithCommand(prompt))return {rule:null,candidates};
266
+ let verdict={error:useJudge?'no-judge':'off'};
267
+ if(useJudge&&judgeModule){
268
+ verdict=await judgeModule.judge({prompt,env,...judgeOptions,
269
+ choices:candidates.map(rule=>({skill:rule.skill,when:rule.invoke.when,near:rule.invoke.near}))});
270
+ }
271
+ if(!verdict.error)return {rule:candidates.find(rule=>rule.skill===verdict.skill)??null,via:'jev',candidates};
272
+ const hits=keywordHits(candidates,prompt);
273
+ return {rule:candidates.find((rule,index)=>hits[index])??null,via:'keyword',error:verdict.error,candidates};
274
+ }
275
+
276
+ export const messageText=(hints,host)=>
277
+ hints.map(hint=>`💡 技能提醒:可以试 ${mention(hint.skill,host)}——${hint.reason}`).join('\n');
278
+
279
+ export async function hook(input,{env=process.env,host='claude',rulesFile=defaultRulesPath(),now=Date.now(),loadAuthor=loadAuthorCheck,
280
+ loadJudgeModule=loadJudge,judgeOptions={}}={}){
281
+ if(env.CM_SKILL_HINTS==='off'||!HOSTS.includes(host))return '';
282
+ const prompt=typeof input?.prompt==='string'?input.prompt:'';
283
+ if(!prompt)return '';
284
+ const loaded=loadRules({env,rulesFile});
285
+ if(!loaded.enabled)return '';
286
+ const session=typeof input.session_id==='string'&&input.session_id?input.session_id:null;
287
+ const file=session?statePath(env,session):null;
288
+ const state=file?readState(file):{hinted:[],pending:[]};
289
+ const time=new Date(now).toISOString();
290
+
291
+ // Adopted = the user typed the hinted skill within the next ADOPT_WINDOW messages.
292
+ const pending=[];
293
+ const adopted=[];
294
+ for(const item of state.pending){
295
+ if(typed(prompt,item.skill,host))adopted.push(item);
296
+ else if(item.left>1)pending.push({...item,left:item.left-1});
297
+ }
298
+ const authorCheck=loaded.rules.some(rule=>rule.author)?await loadAuthor():null;
299
+ const short=prompt.length<=MAX_PROMPT;
300
+ const invoked=short&&loaded.rules.some(rule=>rule.invoke)
301
+ ?await pickInvoke({prompt,rules:loaded.rules,host,env,authorCheck,useJudge:loaded.judge,judgeOptions,
302
+ judgeModule:loaded.judge?await loadJudgeModule():null})
303
+ :{rule:null,candidates:[]};
304
+ // An installed invoke rule is handled above only; the rest hint as before.
305
+ const handled=new Set(invoked.candidates.map(rule=>rule.id));
306
+ const hints=short?pickHints({prompt,rules:loaded.rules.filter(rule=>!handled.has(rule.id)),host,env,hinted:state.hinted,authorCheck}):[];
307
+ const start=invoked.rule?{skill:invoked.rule.skill,mode:invoked.rule.invoke.mode,reason:invoked.rule.reason}:null;
308
+ // Bookkeeping failures cost the statistics, never the hint itself.
309
+ try{
310
+ for(const item of adopted)appendLog(env,{t:time,event:'adopted',host,rule:item.rule,skill:item.skill});
311
+ // A missing key is the normal state for most users, not worth a line per message.
312
+ if(invoked.error&&!['no-key','off'].includes(invoked.error))appendLog(env,{t:time,event:'judge-error',host,error:invoked.error});
313
+ if(start)appendLog(env,{t:time,event:'invoke',host,rule:invoked.rule.id,skill:start.skill,mode:start.mode,via:invoked.via});
314
+ for(const hint of hints)appendLog(env,{t:time,event:'hint',host,rule:hint.rule,skill:hint.skill});
315
+ }catch{/* 统计丢一条 */}
316
+ // Session state is never removed (decided 2026-10-24): a session resumed months
317
+ // later must still not repeat a hint. Each file is a few hundred bytes.
318
+ if(file&&(hints.length||state.pending.length)){
319
+ try{
320
+ writeAtomic(file,JSON.stringify({hinted:[...state.hinted,...hints.map(hint=>hint.skill)],
321
+ pending:[...pending,...hints.map(hint=>({rule:hint.rule,skill:hint.skill,left:ADOPT_WINDOW}))]}));
322
+ }catch{/* 下条消息可能重复提醒一次 */}
323
+ }
324
+ if(!start&&!hints.length)return '';
325
+ const lines=[...(start?[invokeLine(start,host)]:[]),...(hints.length?[messageText(hints,host)]:[])];
326
+ const output={systemMessage:lines.join('\n')};
327
+ if(start)output.hookSpecificOutput={hookEventName:'UserPromptSubmit',
328
+ additionalContext:invokeContext(start,skillFile(start.skill,host,env,authorCheck),host)};
329
+ return JSON.stringify(output);
330
+ }
331
+
332
+ // ---- wiring: copy a stable script + table into ~/.cm-workflow/skill-hints and add the hook ----
333
+
334
+ const shellWord=word=>/^[\w@%+=:,./-]+$/.test(word)?word:`'${word.replace(/'/g,`'\\''`)}'`;
335
+ const managedTail=(env,host)=>`${shellWord(path.join(installDir(env),SCRIPT_NAME))} hook --host ${host}`;
336
+ export const hookCommand=(env,host,node=process.execPath)=>`${shellWord(node)} ${managedTail(env,host)}`;
337
+ // Ours = a command hook that is exactly "<node> <managed copy> hook --host <host>",
338
+ // where <node> is one shell word naming a node executable.
339
+ function isOurs(hook,env,host){
340
+ if(hook?.type!=='command'||typeof hook.command!=='string')return false;
341
+ const tail=' '+managedTail(env,host);
342
+ if(!hook.command.endsWith(tail))return false;
343
+ const word=hook.command.slice(0,-tail.length);
344
+ const interpreter=/^[^\s']+$/.test(word)?word:/^'[^']+'$/.test(word)?word.slice(1,-1):null;
345
+ return Boolean(interpreter)&&/^node(?:\.exe)?$/i.test(path.basename(interpreter));
346
+ }
347
+ // A UserPromptSubmit that is not a list holds no hook of ours. A config of the wrong shape
348
+ // is reported by status and refused by enable: merging into it would drop what is there.
349
+ const promptHooks=config=>config?.hooks?.UserPromptSubmit;
350
+ const plainObject=value=>Boolean(value)&&typeof value==='object'&&!Array.isArray(value);
351
+ export function shapeError(config){
352
+ if(config===undefined)return null;
353
+ if(!plainObject(config))return '顶层不是对象';
354
+ if(config.hooks!==undefined&&!plainObject(config.hooks))return 'hooks 不是对象';
355
+ const list=promptHooks(config);
356
+ return list!==undefined&&!Array.isArray(list)?'UserPromptSubmit 不是列表':null;
357
+ }
358
+ export const hasHintHook=(config,env,host)=>{
359
+ const list=promptHooks(config);
360
+ return Array.isArray(list)&&list.some(group=>Array.isArray(group?.hooks)&&group.hooks.some(hook=>isOurs(hook,env,host)));
361
+ };
362
+ export function withHintHook(config,command){
363
+ const next=structuredClone(config??{});
364
+ next.hooks??={};
365
+ const list=Array.isArray(next.hooks.UserPromptSubmit)?[...next.hooks.UserPromptSubmit]:[];
366
+ list.push({hooks:[{type:'command',command,timeout:5}]});
367
+ next.hooks.UserPromptSubmit=list;
368
+ return next;
369
+ }
370
+
371
+ const COPIED=[...COMPANIONS,SCRIPT_NAME];
372
+ const sourceOf=name=>name===SCRIPT_NAME?fileURLToPath(import.meta.url):path.join(here,name);
373
+ // 'dir' only for a real directory: a link there would take every copy somewhere else.
374
+ const copyDirKind=env=>{
375
+ try{return fs.lstatSync(installDir(env)).isDirectory()?'dir':'other';}
376
+ catch(error){return error.code==='ENOENT'?'missing':'other';}
377
+ };
378
+ // The copy reports on and refreshes from itself only: it cannot see the installed version.
379
+ const runningFromCopy=env=>{try{return fs.realpathSync(here)===fs.realpathSync(installDir(env));}catch{return false;}};
380
+ function copyInstall(env){
381
+ const dir=installDir(env);
382
+ if(copyDirKind(env)==='other')throw new Error(`${dir} 不是普通目录,未写入`);
383
+ for(const name of COPIED)writeAtomic(path.join(dir,name),fs.readFileSync(sourceOf(name),'utf8'));
384
+ }
385
+
386
+ const configFile=(host,env)=>host==='codex'?codexHooksPath(env):claudeSettingsPath(env);
387
+
388
+ // Turned on = our hook is in a host config, or the copy directory exists (enable writes
389
+ // it before the hook, and the hook keeps its state there). A link at that path does not
390
+ // count. Read-only: nothing is created to find out.
391
+ export function hintsInstalled(env){
392
+ if(copyDirKind(env)==='dir')return true;
393
+ return HOSTS.some(host=>{try{return hasHintHook(readJson(configFile(host,env)).value,env,host);}catch{return false;}});
394
+ }
395
+ // Copied files that differ from this version's. Missing, linked or special files count as
396
+ // different and are never opened (a FIFO would block status; the hook refuses a linked table).
397
+ export function staleCopies(env){
398
+ return COPIED.filter(name=>{
399
+ try{
400
+ const source=fs.readFileSync(sourceOf(name));
401
+ const st=fs.lstatSync(path.join(installDir(env),name));
402
+ return !st.isFile()||st.size!==source.length||!fs.readFileSync(path.join(installDir(env),name)).equals(source);
403
+ }catch{return true;}
404
+ });
405
+ }
406
+ const refreshCommand=()=>`node ${shellWord(fileURLToPath(import.meta.url))} refresh`;
407
+
408
+ // Run by the installers: bring an enabled user's copy to this version. Only the four
409
+ // copied files are replaced; host configs, Codex trust, session state and logs are not
410
+ // touched, and a user who never enabled hints gets nothing. Failure is a warning.
411
+ export function refresh({env=process.env,write=text=>process.stdout.write(text)}={}){
412
+ if(!hintsInstalled(env))return 0;
413
+ if(runningFromCopy(env)){write(`⚠ 这是运行副本本身(${installDir(env)}),拿不到已装版本,未刷新;请运行已装 CM 里的 cm-skill-hints.mjs refresh\n`);return 1;}
414
+ try{copyInstall(env);}
415
+ catch(error){write(`⚠ 技能提醒运行副本未刷新(${installDir(env)}):${error.message};可稍后运行 ${refreshCommand()}\n`);return 1;}
416
+ write(`技能提醒:运行副本已刷新(${installDir(env)})。\n`);
417
+ return 0;
418
+ }
419
+ const LABEL={claude:'Claude',codex:'Codex'};
420
+ class Drift extends Error{}
421
+
422
+ // Read, merge and replace happen under the lock CM's other config writers share.
423
+ // Programs outside CM do not take it, so the bytes are compared once more right
424
+ // before the rename; if they changed, nothing is written.
425
+ export async function enable({env=process.env,hosts=HOSTS,node=process.execPath,write=text=>process.stdout.write(text),beforeReplace,lockWaitMs,
426
+ notes=true,requireRecord=false,copyFiles=copyInstall}={}){
427
+ const {withConfigLock,LockBusy}=await import('./cm-config-lock.mjs');
428
+ // The record is written before the copy, so a copy this run leaves half made is never
429
+ // taken for an old enable's (see settledHosts). Only the installer insists on it.
430
+ const noted=await noteRecord(env,[],{lockWaitMs});
431
+ if(noted.warning){
432
+ write(noted.warning);
433
+ if(requireRecord)return 1;
434
+ }
435
+ try{copyFiles(env);}
436
+ catch(error){write(`✗ 复制提醒脚本到 ${installDir(env)} 失败:${error.message}\n`);return 1;}
437
+ let failed=0;
438
+ const done=[];
439
+ for(const host of hosts){
440
+ const file=configFile(host,env);
441
+ let outcome;
442
+ try{
443
+ outcome=withConfigLock(env,file,()=>{
444
+ const read=readJson(file);
445
+ // A config we cannot parse is never rewritten: that would destroy user content.
446
+ if(read.error)return `✗ ${LABEL[host]}:无法读取 ${file}(${read.error}),未改动。\n`;
447
+ const shape=shapeError(read.value);
448
+ if(shape)return `✗ ${LABEL[host]}:${file} 格式异常(${shape}),未改动。\n`;
449
+ const config=read.value??{};
450
+ if(hasHintHook(config,env,host)){done.push(host);return `${LABEL[host]}:提醒钩子已挂,未改动。\n`;}
451
+ writeAtomic(file,JSON.stringify(withHintHook(config,hookCommand(env,host,node)),null,2)+'\n',{before:()=>{
452
+ beforeReplace?.(file);
453
+ const now=readJson(file);
454
+ if(read.missing?!now.missing:now.text!==read.text)throw new Drift();
455
+ }});
456
+ done.push(host);
457
+ return `${LABEL[host]}:已挂提醒钩子(${file})。\n`;
458
+ },lockWaitMs===undefined?{}:{waitMs:lockWaitMs});
459
+ }catch(error){
460
+ outcome=error instanceof Drift?`✗ ${LABEL[host]}:${file} 刚被其他程序改动,未改写;请重跑 enable。\n`
461
+ :error instanceof LockBusy?`✗ ${LABEL[host]}:另一个 CM 程序正在改 ${file},未改写;请稍后重跑 enable。\n`
462
+ :`✗ ${LABEL[host]}:写入 ${file} 失败:${error.message}\n`;
463
+ }
464
+ if(outcome.startsWith('✗'))failed++;
465
+ write(outcome);
466
+ }
467
+ if(done.length&&!noted.warning){
468
+ const after=await noteRecord(env,done,{lockWaitMs});
469
+ if(after.warning){write(after.warning);failed++;}
470
+ }
471
+ if(!notes)return failed?1:0;
472
+ if(hosts.includes('codex'))write(CODEX_TRUST);
473
+ write(`关掉提醒:在 ${localPath(env)} 写 {"enabled": false}。\n`);
474
+ return failed?1:0;
475
+ }
476
+ const CODEX_TRUST='Codex 首次运行这条钩子时会请你确认信任;不确认它就不会运行。\n';
477
+
478
+ // ---- install-time default ----
479
+ // Settled hosts are those whose install-time default has been applied: the hook was added
480
+ // or found there. A settled host without our hook is one the user took it out of, and no
481
+ // install adds it back. --no-skill-hints and CM_SKILL_HINTS_INSTALL=off cover one run only
482
+ // and settle nothing.
483
+ // The record is ~/.cm-workflow/skill-hints.auto.json, outside the copy directory, so
484
+ // removing that directory to switch hints off is still respected. It is written before the
485
+ // copy is made, so a copy without a record can only come from an `enable` older than the
486
+ // record: that user already chose their hosts, and both count as settled.
487
+ // A record CM cannot read or whose shape is unknown is kept as is, and no install adds a
488
+ // hook while it is there.
489
+ function readRecord(env){
490
+ const read=readJson(autoPath(env));
491
+ if(read.missing)return {state:'missing',read};
492
+ const value=read.value;
493
+ if(read.error||!plainObject(value)||value.version!==1||!Array.isArray(value.hosts)||!value.hosts.every(host=>HOSTS.includes(host)))
494
+ return {state:'invalid',read,reason:read.error??'格式异常'};
495
+ return {state:'ok',read,hosts:HOSTS.filter(host=>value.hosts.includes(host))};
496
+ }
497
+ const legacyHosts=env=>copyDirKind(env)==='dir'?[...HOSTS]:[];
498
+ export function settledHosts(env){
499
+ const record=readRecord(env);
500
+ return {state:record.state,reason:record.reason,
501
+ hosts:record.state==='ok'?record.hosts:record.state==='missing'?legacyHosts(env):[...HOSTS]};
502
+ }
503
+ const recordWarning=(env,reason)=>`⚠ 技能提醒:${autoPath(env)} 异常(${reason}),已保留原样;修好或删掉它之前,安装不会自动挂钩子。\n`;
504
+ // Adds hosts to the record. Read, check, merge and replace happen under the shared config
505
+ // lock, and the bytes are compared again right before the rename. Never throws: a problem
506
+ // comes back as one warning line.
507
+ async function noteRecord(env,add,{lockWaitMs,beforeReplace,lock}={}){
508
+ const file=autoPath(env);
509
+ try{
510
+ const {withConfigLock,LockBusy}=await import('./cm-config-lock.mjs');
511
+ try{
512
+ return (lock??withConfigLock)(env,file,()=>{
513
+ const record=readRecord(env);
514
+ if(record.state==='invalid')return {warning:recordWarning(env,record.reason)};
515
+ const base=record.state==='ok'?record.hosts:legacyHosts(env);
516
+ const next=HOSTS.filter(host=>base.includes(host)||add.includes(host));
517
+ if(record.state==='ok'&&next.length===base.length)return {hosts:next};
518
+ writeAtomic(file,JSON.stringify({version:1,hosts:next})+'\n',{before:()=>{
519
+ beforeReplace?.();
520
+ const now=readJson(file);
521
+ if(record.read.missing?!now.missing:now.text!==record.read.text)throw new Drift();
522
+ }});
523
+ return {hosts:next};
524
+ },lockWaitMs===undefined?{}:{waitMs:lockWaitMs});
525
+ }catch(error){
526
+ const why=error instanceof Drift?'刚被其他程序改动':error instanceof LockBusy?'另一个 CM 程序正在改它':error.message;
527
+ return {warning:`⚠ 技能提醒:未能记下已处理的端(${file}:${why});不影响本次安装,下次安装再记。\n`};
528
+ }
529
+ }catch(error){return {warning:`⚠ 技能提醒:未能记下已处理的端(${file}:${error.message})。\n`};}
530
+ }
531
+
532
+ const OFF_NOTE=env=>`关掉提醒:在 ${localPath(env)} 写 {"enabled": false}`;
533
+ const TYPESAFE_NOTE='有 TypeSafe 密钥时,handoff、wayfinder、improve-codebase-architecture 三个作者技能会把消息前 500 字发给 TypeSafe 判断。';
534
+
535
+ // Why an install must not add the hook now, or null. `optOut` is the user skipping this
536
+ // run; `off` is "enabled": false; `pause` is a local file CM cannot use, so it does nothing.
537
+ function installGate(env,skip){
538
+ if(skip)return {optOut:'安装参数 --no-skill-hints'};
539
+ if(env.CM_SKILL_HINTS_INSTALL==='off')return {optOut:'环境变量 CM_SKILL_HINTS_INSTALL=off'};
540
+ const local=readLocal(env);
541
+ if(local.error)return {pause:`${localPath(env)} ${local.shape?local.error:`读取失败(${local.error})`}`};
542
+ if(local.settings.enabled===false)return {off:`${localPath(env)} 里 enabled 为 false`};
543
+ return null;
544
+ }
545
+
546
+ // Run by the installers for their own host. Adds the hook once, unless the user said no;
547
+ // in every other case it only refreshes an existing copy. Never throws; 1 means a warning.
548
+ export async function install({env=process.env,host,skip=false,node=process.execPath,write=text=>process.stdout.write(text),lockWaitMs,
549
+ lockRecord,beforeRecordReplace,copyFiles}={}){
550
+ try{
551
+ const label=LABEL[host];
552
+ const note=async()=>{const noted=await noteRecord(env,[host],{lockWaitMs,beforeReplace:beforeRecordReplace,lock:lockRecord});if(noted.warning)write(noted.warning);return noted.warning?1:0;};
553
+ const gate=installGate(env,skip);
554
+ if(gate?.optOut){
555
+ write(`技能提醒:按${gate.optOut},这次没给 ${label} 挂钩子(只管这一次,下次不带它安装照常挂)。`
556
+ +`已挂着的钩子不受影响,要关掉提醒在 ${localPath(env)} 写 {"enabled": false}。\n`);
557
+ return refresh({env,write});
558
+ }
559
+ if(gate){
560
+ write(gate.pause?`⚠ 技能提醒:${gate.pause},这次没给 ${label} 挂钩子;改好后重装或运行 ${enableCommand(host)}。\n`
561
+ :`技能提醒:${gate.off},没给 ${label} 挂钩子。\n`);
562
+ return refresh({env,write});
563
+ }
564
+ const file=configFile(host,env);
565
+ const read=readJson(file);
566
+ if(!read.error&&!shapeError(read.value)&&hasHintHook(read.value,env,host)){
567
+ const code=refresh({env,write});
568
+ return Math.max(code,await note());
569
+ }
570
+ const settled=settledHosts(env);
571
+ if(settled.state==='invalid'){
572
+ write(recordWarning(env,settled.reason).replace(/\n$/,`这次没给 ${label} 挂钩子。\n`));
573
+ return Math.max(refresh({env,write}),1);
574
+ }
575
+ if(settled.hosts.includes(host)){
576
+ write(settled.state==='ok'
577
+ ?`技能提醒:${label} 的钩子之前挂过后被移除,按你的选择不再自动挂回,要挂上运行 ${enableCommand(host)}。\n`
578
+ :`技能提醒:你之前开启技能提醒时没给 ${label} 挂钩子(或后来移除了),这次不自动挂;要挂上运行 ${enableCommand(host)}。\n`);
579
+ return refresh({env,write});
580
+ }
581
+ const code=await enable({env,hosts:[host],node,write,lockWaitMs,notes:false,requireRecord:true,...(copyFiles?{copyFiles}:{})});
582
+ const now=readJson(file);
583
+ if(!now.error&&hasHintHook(now.value,env,host)){
584
+ write(`技能提醒:已给 ${label} 挂上技能提醒钩子,消息里有合适的技能时会提示你。${OFF_NOTE(env)}`
585
+ +`(重装加 --no-skill-hints 只是不自动挂,不会摘掉已挂的钩子)。${TYPESAFE_NOTE}\n`);
586
+ if(host==='codex')write(CODEX_TRUST);
587
+ }
588
+ return code;
589
+ }catch(error){
590
+ write(`⚠ 技能提醒钩子未处理:${error.message}\n`);
591
+ return 1;
592
+ }
593
+ }
594
+ const enableCommand=host=>`node ${shellWord(fileURLToPath(import.meta.url))} enable --${host}`;
595
+
596
+ export function statusText({env=process.env,rulesFile=defaultRulesPath()}={}){
597
+ const lines=[];
598
+ const wired=HOSTS.map(host=>{
599
+ const read=readJson(configFile(host,env));
600
+ const shape=read.error?null:shapeError(read.value);
601
+ return `${LABEL[host]} ${read.error?`无法读取(${read.error})`:shape?`格式异常(${shape})`
602
+ :hasHintHook(read.value,env,host)?'已挂':'未挂'}`;
603
+ });
604
+ const loaded=loadRules({env,rulesFile});
605
+ const localCause=error=>`${localPath(env)} ${/^格式异常/.test(error)?error:`读取失败(${error})`}`;
606
+ lines.push(`skill hints: ${wired.join(',')};开关 ${loaded.enabled?'开'
607
+ :loaded.paused?`暂停(本地配置格式异常,提醒已暂停(${localCause(loaded.localError)}))`
608
+ :`关(${localPath(env)} 里 enabled 为 false)`}`);
609
+ // Same gate and record as `install`, so status never says "on" where an install would not wire.
610
+ const gate=installGate(env,false);
611
+ const settled=settledHosts(env);
612
+ lines.push(gate?.optOut?` 安装时自动挂:已关闭(${gate.optOut.replace('环境变量 ','')})`
613
+ :gate?.off?` 安装时自动挂:已关闭(${gate.off})`
614
+ :gate?.pause?` 安装时自动挂:暂停(${gate.pause})`
615
+ :settled.state==='invalid'?` 安装时自动挂:暂停(${autoPath(env)} 异常:${settled.reason})`
616
+ :` 安装时自动挂:开;已处理过:${settled.hosts.length?`${settled.hosts.map(host=>LABEL[host]).join('、')}(这些端不会再被自动挂上)`:'无'}`);
617
+ if(!hintsInstalled(env))lines.push(' 运行副本:未建(还没开启)');
618
+ else if(runningFromCopy(env))lines.push(' ⚠ 这是从运行副本本身查的,无法核验它与已装版本是否一致;请用已装 CM 里的 cm-skill-hints.mjs status');
619
+ else{
620
+ const kind=copyDirKind(env);
621
+ const stale=kind==='dir'?staleCopies(env):[];
622
+ lines.push(kind==='missing'?` ⚠ 运行副本缺失(${installDir(env)}),钩子跑不起来;运行 ${refreshCommand()} 补上`
623
+ :kind==='other'?` ⚠ 运行副本目录不是普通目录(${installDir(env)}),CM 不会写进去;请移走后运行 ${refreshCommand()}`
624
+ :stale.length?` ⚠ 运行副本与已装版本不一致(${stale.join('、')});运行 ${refreshCommand()} 刷新`
625
+ :' 运行副本:与已装版本一致');
626
+ }
627
+ if(loaded.enabled){
628
+ lines.push(` 对照表:CM 自带 ${loaded.defaultsError?`读取失败(${loaded.defaultsError})`:`${loaded.cmCount} 条`};用户自加 ${loaded.userCount} 条;关掉自带 ${loaded.disabledCount} 条`);
629
+ lines.push(loaded.judge?' 自动调用:有 TypeSafe 密钥(TYPESAFE_API_KEY 或钥匙串)时由 Jev 判断,否则用关键词'
630
+ :` 自动调用:已关 Jev(${localPath(env)} 里 judge 为 false),只用关键词`);
631
+ }
632
+ return lines.join('\n')+'\n';
633
+ }
634
+
635
+ const USAGE='用法: cm-skill-hints.mjs hook --host claude|codex | status | refresh | enable [--claude] [--codex] | install --host claude|codex [--no-skill-hints]\n';
636
+
637
+ export async function main(argv=process.argv.slice(2),{env=process.env,readInput=()=>fs.readFileSync(0,'utf8'),
638
+ write=text=>process.stdout.write(text),error=text=>process.stderr.write(text)}={}){
639
+ const [command,...rest]=argv;
640
+ if(command==='hook'){
641
+ // Quiet on every failure: a hint is never worth holding up the user's message.
642
+ try{
643
+ const host=rest[0]==='--host'?rest[1]:'claude';
644
+ const output=await hook(JSON.parse(readInput()),{env,host});
645
+ if(output)write(output+'\n');
646
+ }catch{/* 安静跳过 */}
647
+ return 0;
648
+ }
649
+ if(command==='status'&&!rest.length){write(statusText({env}));return 0;}
650
+ if(command==='refresh'&&!rest.length)return refresh({env,write});
651
+ if(command==='enable'){
652
+ const hosts=rest.length?rest.map(flag=>flag.replace(/^--/,'')):HOSTS;
653
+ if(hosts.some(host=>!HOSTS.includes(host))){error(USAGE);return 2;}
654
+ return enable({env,hosts});
655
+ }
656
+ if(command==='install'){
657
+ const [flag,host,...extra]=rest;
658
+ const skip=extra.length===1&&extra[0]==='--no-skill-hints';
659
+ if(flag!=='--host'||!HOSTS.includes(host)||(extra.length&&!skip)){error(USAGE);return 2;}
660
+ return install({env,host,skip,write});
661
+ }
662
+ error(USAGE);
663
+ return 2;
664
+ }
665
+
666
+ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fs.realpathSync(fileURLToPath(import.meta.url))){
667
+ // The hook exits 0 whatever happens; other commands report their own code.
668
+ process.exitCode=await main().catch(()=>process.argv[2]==='hook'?0:1);
669
+ }