@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
@@ -12,14 +12,17 @@ import {spawn} from 'node:child_process';
12
12
  import {fileURLToPath} from 'node:url';
13
13
  import {createHash,randomUUID} from 'node:crypto';
14
14
  import {readRegularFileSync} from './notify-safe-read.mjs';
15
+ import {readAutonomy} from './autonomy.mjs';
15
16
 
16
- export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perMinute:4,perDay:150,
17
+ export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perDay:150,
18
+ windowMs:10*60000,perWindow:3,followUpMs:2*3600*1000,attentionTtlMs:24*3600*1000,
17
19
  commandTimeoutMs:15000,titleChars:60,bodyChars:500,defaultWaitMinutes:10,defaultCheckWaitMinutes:45,
18
20
  defaultIdleMinutes:45});
19
21
  const LOCK_STALE_MS=30000,LOG_LIMIT=256*1024;
20
22
  // Lock and dedup state are tiny JSON files; perDay sends bound the state size.
21
23
  const CONTROL_FILE_LIMIT=256*1024;
22
24
  const RUNNER=fileURLToPath(new URL('./notify-run.mjs',import.meta.url));
25
+ const LATER_RUNNER=fileURLToPath(new URL('./notify-later.mjs',import.meta.url));
23
26
 
24
27
  export function notifyHome(env=process.env){
25
28
  return path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
@@ -63,9 +66,27 @@ export function parseNotifyConfig(raw){
63
66
  const idleMinutes=value.idleMinutes??NOTIFY_LIMITS.defaultIdleMinutes;
64
67
  if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440)return {reason:'idle_minutes'};
65
68
  const ms=value=>Math.max(1,Math.round(value*60000));
66
- const config={command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes)};
69
+ const config={command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes),
70
+ followUpMs:NOTIFY_LIMITS.followUpMs,windowMs:NOTIFY_LIMITS.windowMs,perWindow:NOTIFY_LIMITS.perWindow};
71
+ // Optional frequency: {followUpMinutes, windowMinutes, perWindow}. Unknown keys or out-of-range values are an error.
72
+ if(value.frequency!==undefined){
73
+ const frequency=value.frequency;
74
+ if(!frequency||typeof frequency!=='object'||Array.isArray(frequency)
75
+ ||!Object.keys(frequency).every(key=>['followUpMinutes','windowMinutes','perWindow'].includes(key)))return {reason:'frequency'};
76
+ const range=(raw,max)=>raw===undefined||(typeof raw==='number'&&Number.isFinite(raw)&&raw>=1&&raw<=max);
77
+ if(!range(frequency.followUpMinutes,1440)||!range(frequency.windowMinutes,1440)
78
+ ||!(frequency.perWindow===undefined||(Number.isInteger(frequency.perWindow)&&frequency.perWindow>=1&&frequency.perWindow<=50)))return {reason:'frequency'};
79
+ if(frequency.followUpMinutes!==undefined)config.followUpMs=ms(frequency.followUpMinutes);
80
+ if(frequency.windowMinutes!==undefined)config.windowMs=ms(frequency.windowMinutes);
81
+ if(frequency.perWindow!==undefined)config.perWindow=frequency.perWindow;
82
+ }
67
83
  // An unusable `text` never turns notices off: the default text is used and
68
84
  // the caller is told why (textReason), so a typo cannot silence notices.
85
+ // Optional layout: "full" (default) or "compact" (project, session, reason only).
86
+ if(value.layout!==undefined){
87
+ if(!['full','compact'].includes(value.layout))return {reason:'layout'};
88
+ if(value.layout==='compact')config.layout='compact';
89
+ }
69
90
  if(value.text===undefined)return {config};
70
91
  const text=normalizeNotifyText(value.text);
71
92
  if(text.reason)return {config,textReason:text.reason};
@@ -82,8 +103,16 @@ const UNSAFE_READ={permission:'not_regular_file',too_large:'too_large'};
82
103
 
83
104
  // null = feature off. Under `node --test` only an explicit CM_WORKFLOW_HOME
84
105
  // enables it, so a test suite never reaches the user's real configuration.
106
+ // CM_NOTIFY_OFF (any value but empty or "0") turns notices off for this process
107
+ // and its children before anything is read or written: acceptance runs in a test
108
+ // copy of a project keep the real CM_WORKFLOW_HOME (runtimes.yml and the rest)
109
+ // without pushing to the user's phone. Every automatic notice path starts here; the
110
+ // explicit `/cm:notify test` and running a sender by hand do not (they are asked for).
111
+ // cleanEnvironment / claudeEnvironment keep the variable for check and provider children.
85
112
  // An invalid file is reported in notify.log only, never on workflow output.
113
+ export const notifyOffByEnv=(env=process.env)=>typeof env.CM_NOTIFY_OFF==='string'&&env.CM_NOTIFY_OFF!==''&&env.CM_NOTIFY_OFF!=='0';
86
114
  export function readNotifyConfig(env=process.env){
115
+ if(notifyOffByEnv(env))return null;
87
116
  if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return null;
88
117
  const file=path.join(notifyHome(env),'notify.json');
89
118
  let raw;
@@ -106,7 +135,84 @@ function clean(value,max){
106
135
  .replace(/\s+/g,' ').trim();
107
136
  return cut(text,max);
108
137
  }
109
- const projectName=value=>typeof value==='string'&&value?clean(path.basename(value),40):'';
138
+ // The last two path segments: "app" alone does not say which project.
139
+ const projectName=value=>{
140
+ if(typeof value!=='string'||!value)return '';
141
+ const base=path.basename(value),parent=path.basename(path.dirname(value));
142
+ return clean(parent&&parent!=='.'&&parent!==base&&path.dirname(value)!==value?`${parent}/${base}`:base,48);
143
+ };
144
+ // The session the host was started for: the value of --host-context (a UUID
145
+ // is shortened to its first 8 characters). Printed by the driver so the
146
+ // notice can be matched to the session that has to act.
147
+ const SESSION_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
148
+ export function notifySessionLabel(args=[]){
149
+ const list=Array.isArray(args)?args.map(String):[];
150
+ const at=list.indexOf('--host-context'),raw=at>=0?list[at+1]:null;
151
+ if(typeof raw!=='string'||!raw||raw.startsWith('--'))return null;
152
+ return SESSION_UUID.test(raw)?raw.slice(0,8).toLowerCase():clean(raw,24)||null;
153
+ }
154
+ // The title the person sees for the Claude Code session that runs this
155
+ // process (its sidebar name): the last custom-title (else ai-title) record in
156
+ // the tail of <claude config>/projects/*/<CLAUDE_CODE_SESSION_ID>.jsonl. Only
157
+ // the last 1 MiB is read. Static links (a linked project directory or
158
+ // transcript) and replacements the re-checks below can see are refused; see
159
+ // the known limit there for concurrent swaps. Under node --test only an
160
+ // explicit CM_NOTIFY_CLAUDE_PROJECTS directory is read. null when unknown.
161
+ const TITLE_TAIL_BYTES=1024*1024;
162
+ const TITLE_DIR_LIMIT=2000;
163
+ export function sessionTitle(env=process.env){
164
+ try{
165
+ const id=env.CLAUDE_CODE_SESSION_ID;
166
+ if(typeof id!=='string'||!SESSION_UUID.test(id))return null;
167
+ const projects=env.CM_NOTIFY_CLAUDE_PROJECTS||(env.NODE_TEST_CONTEXT?null
168
+ :path.join(env.CLAUDE_CONFIG_DIR||path.join(os.homedir(),'.claude'),'projects'));
169
+ if(!projects)return null;
170
+ // The projects root may itself be a link (a moved config directory); the
171
+ // project directories below it and the transcript must not be.
172
+ const dirs=fs.readdirSync(projects,{withFileTypes:true}).filter(entry=>entry.isDirectory()).slice(0,TITLE_DIR_LIMIT);
173
+ const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino;
174
+ for(const dir of dirs){
175
+ const folder=path.join(projects,dir.name),file=path.join(folder,`${id}.jsonl`);
176
+ let before,stat;
177
+ try{before=fs.lstatSync(folder);stat=fs.lstatSync(file);}catch{continue;}
178
+ if(!before.isDirectory()||!stat.isFile())continue;
179
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0));
180
+ try{
181
+ // Node has no openat: re-check after opening. The project directory
182
+ // must still be the same real directory, and the transcript path must
183
+ // still name the opened regular file; a directory swapped for a link
184
+ // (or swapped and restored) around the open fails one of these.
185
+ // Known limit: repeated swaps between these checks are not covered.
186
+ // Whoever can swap this directory can already write the transcript
187
+ // (and so its title) directly; the checks only keep static links,
188
+ // FIFOs and simple replacements out.
189
+ const opened=fs.fstatSync(fd);
190
+ let after,again;try{after=fs.lstatSync(folder);again=fs.lstatSync(file);}catch{return null;}
191
+ if(!opened.isFile()||!same(opened,stat)||!after.isDirectory()||!same(after,before)||!same(again,opened))return null;
192
+ const length=Math.min(opened.size,TITLE_TAIL_BYTES),buffer=Buffer.alloc(length);
193
+ fs.readSync(fd,buffer,0,length,opened.size-length);
194
+ let custom=null,ai=null;
195
+ for(const line of buffer.toString('utf8').split('\n')){
196
+ if(!line.includes('-title"'))continue;
197
+ let row;try{row=JSON.parse(line);}catch{continue;}
198
+ if(row?.type==='custom-title'&&typeof row.customTitle==='string')custom=row.customTitle;
199
+ if(row?.type==='ai-title'&&typeof row.aiTitle==='string')ai=row.aiTitle;
200
+ }
201
+ return clean(custom??ai??'',40)||null;
202
+ }finally{fs.closeSync(fd);}
203
+ }
204
+ return null;
205
+ }catch{return null;}
206
+ }
207
+ // Without a returned run id, the launch arguments identify the run (the
208
+ // driver passes the same arguments to the host it starts).
209
+ export const launchRunKey=(args=[])=>`args:${keyHash((Array.isArray(args)?args:[]).map(String).join('\0'))}`;
210
+ // One attention record per project and session: stuck, waiting and idle
211
+ // notices about the same session are one thing to handle, not three.
212
+ export function attentionKeyFor({project,session,workflow,runId}){
213
+ const label=projectName(project)||'-';
214
+ return session?`attn|${label}|${session}`:`attn|${label}|${clean(workflow,24)||'cm'}|${clean(runId,64)||'-'}`;
215
+ }
110
216
 
111
217
  // Local 24-hour HH:MM in the process time zone (TZ) unless one is injected.
112
218
  export function localClock(now,timeZone){
@@ -121,15 +227,46 @@ export function localClock(now,timeZone){
121
227
  // Nothing else: no templates or expressions. Custom strings go through the same
122
228
  // clean() as field values (paths redacted, control characters removed) and are
123
229
  // capped; the whole title and body keep their caps.
124
- export const NOTIFY_TEXT_FIELDS=Object.freeze(['project','workflow','runId','task','stage','code','nextAction','time']);
230
+ export const NOTIFY_TEXT_FIELDS=Object.freeze(['project','workflow','runId','feature','task','stage','code','nextAction','time']);
125
231
  const TEXT_EVENTS=['done','waiting','idle','idle_waiting','dead','default'];
126
232
  const TEXT_CAPS=Object.freeze({titlePrefix:16,headline:24,label:12});
127
- const FIELD_CAPS={workflow:24,runId:64,task:40,stage:48,code:64,nextAction:200};
233
+ const FIELD_CAPS={workflow:24,runId:64,feature:48,task:40,stage:48,code:96,nextAction:200};
128
234
  export const DEFAULT_NOTIFY_TEXT=Object.freeze({titlePrefix:'CM',
129
235
  headlines:Object.freeze({done:'流程已结束',waiting:'等待会话应答',idle:'疑似空转',idle_waiting:'在等你',dead:'宿主已退出未收尾',default:'需要人处理'}),
130
- fields:Object.freeze({default:Object.freeze(['nextAction','project','workflow','task','stage','code','time']),
131
- done:Object.freeze(['project','task','time'])}),
132
- labels:Object.freeze({nextAction:'下一步',project:'项目',workflow:'流程',runId:'运行',task:'任务',stage:'阶段',code:'原因',time:'时间'})});
236
+ // Project is in the title; workflow, feature, task and session in the subtitle.
237
+ fields:Object.freeze({default:Object.freeze(['nextAction','code','time']),
238
+ done:Object.freeze(['nextAction','time'])}),
239
+ labels:Object.freeze({nextAction:'下一步',project:'项目',workflow:'流程',runId:'运行',feature:'功能',task:'任务',stage:'阶段',code:'卡在',time:'时间'})});
240
+ // Common stop codes in plain words; the code itself stays in brackets so it can be searched.
241
+ const CODE_WORDS=Object.freeze({qa_decision_required:'在等 QA 判定',qa_mandatory_required:'在等必需 QA 判定',
242
+ qa_triggered:'QA 已触发,缺执行器',waiting_session_answer:'在等会话应答',waiting_for_you:'在等你处理',no_next_step:'会话没有发下一步',
243
+ fingerprint_mismatch:'启动参数与创建时不一致',review_blocked:'审查判定无法通过',review_limit:'审查轮次用完',
244
+ host_exited:'宿主中途退出',host_request_unanswered:'宿主请求没人应答',host_response_rejected:'宿主应答被拒绝',
245
+ permission_denied:'权限被拒绝',spec_drift:'规格有改动,需重新批准',awaiting_spec_approval:'在等规格批准',
246
+ blocked:'被阻断',cancelled:'已取消',failed:'失败',interrupted:'被中断',
247
+ checks_not_passed:'检查没通过',develop_checks_not_passed:'开发检查没通过',qa_failed:'QA 没通过',qa_blocked:'QA 被阻断',
248
+ qa_result_blocked:'QA 结果被阻断',qa_execution_unknown:'QA 执行结果不明',project_qa_not_passed:'项目 QA 没通过',
249
+ correction_review_required:'需要重新审查改动',documentation_sync_blocked:'文档同步被阻断',handoff_exists:'交接记录已存在',
250
+ provider_development_authorization_required:'需要你授权外部开发',host_process_gone:'宿主进程已退出',run_done:'跑完了',
251
+ notify_pending_unsafe:'延后提醒不可用'});
252
+ // Codes without an entry: "subject + outcome" from the words in the code, so
253
+ // the reason is still in Chinese; null when the code says neither.
254
+ const CODE_SUBJECTS=[['qa_fix','QA 修复'],['qa','QA'],['review','审查'],['develop','开发'],['checks','检查'],['check','检查'],
255
+ ['spec','规格'],['documentation','文档'],['batch','批次'],['fix','修复'],['host','宿主'],['bootstrap','初始化'],
256
+ ['permission','权限'],['verification','验证'],['completion','完成'],['scope','范围'],['provider','外部模型']];
257
+ const CODE_OUTCOMES=[['not_passed','没通过'],['failed','失败'],['blocked','被阻断'],['authorization_required','要你授权'],
258
+ ['approval_required','要你批准'],['required','要你处理'],['timeout','超时'],['unknown','结果不明'],['interrupted','被中断'],
259
+ ['drift','有改动'],['exhausted','次数用完'],['unavailable','不可用'],['invalid','无效'],['denied','被拒绝'],['cancelled','已取消']];
260
+ function codeChinese(code){
261
+ if(!code)return null;
262
+ if(Object.hasOwn(CODE_WORDS,code))return CODE_WORDS[code];
263
+ const outcome=CODE_OUTCOMES.find(([word])=>code===word||code.endsWith(`_${word}`));
264
+ if(!outcome)return null;
265
+ const subject=CODE_SUBJECTS.find(([word])=>code===word||code.startsWith(`${word}_`)||code.includes(`_${word}_`));
266
+ return `${subject?subject[1]:''}${outcome[1]}`;
267
+ }
268
+ const codeWords=code=>{const value=clean(code,64);if(!value)return '';
269
+ const words=codeChinese(value);return words?`${words}(${value})`:value;};
133
270
  // Custom strings first lose every Unicode format character (\p{Cf}: bidi
134
271
  // controls U+202A-202E, U+2066-2069, U+200E/200F, U+061C; zero-width U+200B-200D,
135
272
  // U+2060, U+FEFF; soft hyphen, tag characters), so they cannot reorder or hide
@@ -174,20 +311,113 @@ export function normalizeNotifyText(value){
174
311
  return {text};
175
312
  }
176
313
 
314
+ // What the person does next, in plain words, by stop code (2026-10-26: a notice
315
+ // that only says why it stopped leaves the person guessing). It always names the
316
+ // session to go back to; an unmapped code asks that session to say what it needs.
317
+ // An explicit fields.action (a driver that knows more, e.g. retries already spent)
318
+ // wins. Never built from free text other than that action, the session title and id.
319
+ const USER_STAGES=new Set(['awaiting_user','awaiting_planning_user','awaiting_design_user','change_confirmation',
320
+ 'confirmation_required','self_check_needs_human']);
321
+ // pendingAction exits the runner opens only with an explicit --allow-* (or
322
+ // rebind) permission: the person confirms and authorizes them.
323
+ const AUTHORIZED_RECOVERY=Object.freeze({
324
+ abandon_review:go=>`需要你确认旧审查进程已停后,${go}授权放弃这次审查再重派`,
325
+ abandon_effect:go=>`需要你确认上一步的进程已停后,${go}授权放弃这一步再重做`,
326
+ develop_redo:go=>`需要你确认会话已停止改代码后,${go}授权重做开发`,
327
+ bootstrap_review_recover:go=>`${go},授权它恢复初始化规则的审查`,
328
+ spec_rebind:go=>`规格被改过:${go}确认改动后,授权它换绑规格`});
329
+ const DEVELOPER_WAIT=Object.freeze({developer_rate_limited:'开发进程被限流(429):过一刻钟后',
330
+ developer_server_error:'开发服务过载或出错:稍后',developer_auth_failed:'开发 CLI 要重新登录:登录后',
331
+ developer_billing_error:'开发账号额度用完:恢复额度后'});
332
+ const REVIEW_REDISPATCH=new Set(['review_provider_failed','review_transport_timeout','review_verdict_invalid','review_abandoned']);
333
+ const REVIEWER_WAIT=Object.freeze({reviewer_rate_limited:'审查被限流:过一刻钟后',reviewer_billing_error:'审查账号额度用完:恢复额度后',
334
+ reviewer_auth_failed:'审查 CLI 要重新登录:登录后',reviewer_server_error:'审查服务暂时出错:稍后'});
335
+ export function noticeAction(fields={}){
336
+ const explicit=clean(fields.action,200);if(explicit)return explicit;
337
+ const name=clean(fields.sessionTitle,40)||clean(fields.session,24),go=name?`回到会话「${name}」`:'回到对应会话';
338
+ const code=clean(fields.code,96),stage=clean(fields.stage,48);
339
+ const pendingAction=clean(fields.pendingAction,32);
340
+ // The driver's own automatic review retries (drive-core.mjs) for a rate limit.
341
+ // "继续即可" only when the real exit is still the original run's redispatch.
342
+ if(fields.reviewFailure==='reviewer_rate_limited'&&code==='review_provider_failed'&&pendingAction==='resume'){
343
+ const retries=fields.rateLimitRetries;
344
+ if(Number.isSafeInteger(retries)&&retries>0)return `审查被限流,已自动重试 ${retries} 次仍失败;过半小时后${go}说「继续」即可`;
345
+ if(fields.rateLimitWaiting===true)return `审查被限流,自动重试没有接上;${go}说「继续」即可`;
346
+ }
347
+ // A provider develop that ended on an API failure: its redo needs the person's
348
+ // develop_redo authorization (the host then proves the old worker gone itself).
349
+ if(pendingAction==='develop_redo'&&Object.hasOwn(DEVELOPER_WAIT,fields.developFailure))
350
+ return `${DEVELOPER_WAIT[fields.developFailure]}${go},授权它重做这一轮开发(宿主会先核对旧开发进程已退出)`;
351
+ // Exits that need the person's explicit authorization (an --allow-* recovery).
352
+ if(Object.hasOwn(AUTHORIZED_RECOVERY,pendingAction))return AUTHORIZED_RECOVERY[pendingAction](go);
353
+ if(['awaiting_spec_approval','spec_approval_required'].includes(code)||stage==='awaiting_spec_approval')
354
+ return `打开规格确认内容,再${go}说「批准」`;
355
+ if(code==='spec_drift')return `规格被改过:${go},确认这些改动要不要保留`;
356
+ if(code==='permission_denied'||/(^|_)authorization_required$/.test(code))return `${go},看它要你授权什么;同意就说「授权」`;
357
+ if(code==='review_limit')return `两轮审查都没通过:${go},决定改规格还是重开这项任务`;
358
+ if(code==='review_blocked')return `审查认为在批准范围内改不好:${go}看原因,决定改规格还是放弃`;
359
+ if(['review_redispatch_limit','review_abandon_budget_exhausted'].includes(code))
360
+ return `审查多次没给结论:${go},让它查清登录或额度后新建运行重做`;
361
+ if(/_(retry|redo|recheck)_limit$/.test(code))return `自动重试次数已用完:${go},决定要不要重开这项任务`;
362
+ // The classifier saw a question or decision only the person can answer.
363
+ if(fields.ask===true||code==='confirm_reask_decision_required'||USER_STAGES.has(stage))return `${go},回答它的问题或做决定`;
364
+ if(REVIEW_REDISPATCH.has(code))return `${REVIEWER_WAIT[fields.reviewFailure]??''}${go}说「继续」,让它重派审查`;
365
+ if(code==='qa_triggered')return `${go}说「继续」,让它执行 QA`;
366
+ if(['qa_decision_required','qa_mandatory_required'].includes(code))return `${go}说「继续」,让它做 QA 判定`;
367
+ if(['qa_failed','qa_blocked','qa_result_blocked','project_qa_not_passed'].includes(code))return `QA 没通过:${go},让它说明失败项和修法`;
368
+ if(code.startsWith('host_'))return `宿主中途停了:${go}说「继续」,让它查状态后恢复`;
369
+ if(code==='waiting_session_answer')return `${go}看看它是否卡住,需要时说「继续」`;
370
+ if(['waiting_for_you','no_next_step'].includes(code))return `${go}说「继续」,让它做下一步`;
371
+ if(code==='checks_not_passed'||code.startsWith('develop_'))return `${go}说「继续」,让它修好后重新提交`;
372
+ if(code==='cancelled')return `已取消:要继续就${go}说明`;
373
+ return `${go},让它说明停在哪、需要你做什么`;
374
+ }
375
+ // A nextAction written for the session (flags, codes, file names, long recovery
376
+ // recipes) is not something a person can act on from a phone. Only a driver's
377
+ // stop is rewritten; host waiting/idle and patrol texts are already written for people.
378
+ const technicalAction=raw=>{
379
+ const value=clean(raw,1000);
380
+ return !value||Array.from(value).length>80||/--|`|[{}]|[A-Za-z0-9]_[A-Za-z0-9]|\.(?:mjs|js|json|md|sh)\b/.test(value)
381
+ ||(value.match(/[A-Za-z]{3,}/g)??[]).length>=3;
382
+ };
383
+ // The default label "下一步" reads as the workflow's step; the compact line says "你要做".
384
+ const actionLabel=spec=>spec.labels.nextAction===DEFAULT_NOTIFY_TEXT.labels.nextAction?'你要做':spec.labels.nextAction;
385
+
177
386
  // The default text is a next-step-first layout; a finished run only names
178
387
  // project, task and time. `text` is a normalized notify.json `text`; anything
179
388
  // unusable falls back to the default.
180
- export function buildNotifyMessage(fields,{now=Date.now(),timeZone,text}={}){
389
+ export function buildNotifyMessage(fields,{now=Date.now(),timeZone,text,followUp=false,suppressed=0,layout='full'}={}){
181
390
  const spec=text===undefined||text===null?DEFAULT_NOTIFY_TEXT:normalizeNotifyText(text).text??DEFAULT_NOTIFY_TEXT;
182
391
  const workflow=clean(fields.workflow,24)||'cm',project=projectName(fields.project);
183
392
  const event=Object.hasOwn(spec.headlines,fields.event)&&fields.event!=='default'?fields.event:'default';
184
- const head=[spec.titlePrefix,workflow,spec.headlines[event]].filter(Boolean).join(' ');
393
+ if(layout==='compact'){
394
+ // Only which project, which session and why it stopped. A code without a
395
+ // plain-words entry falls back to the event headline; the code itself stays
396
+ // in the stdin JSON for anyone who needs it.
397
+ const session=clean(fields.sessionTitle,40)||clean(fields.session,24),code=clean(fields.code,64);
398
+ const reason=(event!=='done'&&codeChinese(code))||spec.headlines[event];
399
+ const lines=[`${followUp?'第 2 次:':''}${reason}`];
400
+ if(event!=='done')lines.push(`${actionLabel(spec)}:${noticeAction(fields)}`);
401
+ if(Number.isSafeInteger(suppressed)&&suppressed>0)lines.push(`另有 ${suppressed} 条提醒已合并`);
402
+ return {title:cut(project||workflow,NOTIFY_LIMITS.titleChars),subtitle:session?`会话:${session}`:workflow,
403
+ body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
404
+ }
405
+ const head=[spec.titlePrefix,spec.headlines[event]].filter(Boolean).join(' ');
185
406
  const title=cut(`${head}${project?` · ${project}`:''}`,NOTIFY_LIMITS.titleChars);
407
+ const feature=clean(fields.feature,FIELD_CAPS.feature),task=clean(fields.task,FIELD_CAPS.task);
408
+ const session=clean(fields.sessionTitle,40)||clean(fields.session,24);
409
+ // The session is what says where to act: it is kept whole and the rest is shortened first.
410
+ const sessionPart=session?` · 会话 ${session}`:'',rest=[workflow,[feature,task].filter(Boolean).join(' ')].filter(Boolean).join(' · ');
411
+ const subtitle=cut(rest,Math.max(1,NOTIFY_LIMITS.titleChars-Array.from(sessionPart).length))+sessionPart;
186
412
  const value=name=>name==='time'?localClock(now,timeZone):name==='project'?project:name==='workflow'?workflow
413
+ :name==='code'?codeWords(fields.code)
414
+ :name==='nextAction'&&(fields.event===undefined||fields.event==='stuck')&&technicalAction(fields.nextAction)?noticeAction(fields)
187
415
  :clean(fields[name],FIELD_CAPS[name]);
188
416
  const rows=spec.fields[fields.event==='done'?'done':'default'].map(name=>[spec.labels[name],value(name)]);
189
417
  const lines=rows.filter(([,value])=>value).map(([label,value])=>`${label}:${value}`);
190
- return {title,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
418
+ if(followUp)lines.unshift('第 2 次提醒:上次提醒后仍未处理');
419
+ if(Number.isSafeInteger(suppressed)&&suppressed>0)lines.push(`另有 ${suppressed} 条提醒为避免刷屏已合并,请一并查看各会话`);
420
+ return {title,subtitle,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
191
421
  }
192
422
 
193
423
  const keyHash=key=>createHash('sha256').update(key).digest('hex').slice(0,16);
@@ -248,50 +478,255 @@ function releaseLock(file,body){if(readLock(file)===body){try{fs.unlinkSync(file
248
478
 
249
479
  // Dedup and throttle across processes. Any lock or parse trouble skips the
250
480
  // notice instead of waiting on it.
251
- function reserve(home,hash,now){
252
- const lockFile=path.join(home,'notify-state.lock'),stateFile=path.join(home,'notify-state.json');
253
- const lock=takeLock(lockFile);if(lock===null)return 'state_busy';
481
+ // Attention levels: idle < waiting/stuck. A higher level, or a stuck notice
482
+ // with a different code, is a new state and is sent at once; the same state
483
+ // is sent once more after followUpMs and then not again until it changes or
484
+ // the record expires (attentionTtlMs). A notice over the window limit is not
485
+ // sent but counted, and the next sent notice says how many were merged.
486
+ const ATTENTION_LEVEL=Object.freeze({idle:1,waiting:2,idle_waiting:2,stuck:2});
487
+ function readState(home){
488
+ const read=readBounded(path.join(home,'notify-state.json'),CONTROL_FILE_LIMIT);if(read===null)return null;
489
+ if(read.missing)return {version:2,keys:{},attention:{},sends:[],suppressed:0};
490
+ let state;try{state=JSON.parse(read.text);}catch{return null;}
491
+ if(!state||![1,2].includes(state.version)||!state.keys||typeof state.keys!=='object'||Array.isArray(state.keys)
492
+ ||!Array.isArray(state.sends)||!state.sends.every(Number.isFinite)
493
+ ||!Object.values(state.keys).every(Number.isFinite))return null;
494
+ if(state.version===1)return {version:2,keys:state.keys,attention:{},sends:state.sends,suppressed:0};
495
+ const record=item=>item&&typeof item==='object'&&Number.isInteger(item.level)&&Number.isInteger(item.count)
496
+ &&Number.isFinite(item.lastAt)&&(item.code===null||typeof item.code==='string');
497
+ if(!state.attention||typeof state.attention!=='object'||Array.isArray(state.attention)
498
+ ||!Object.values(state.attention).every(record)||!Number.isSafeInteger(state.suppressed)||state.suppressed<0)return null;
499
+ return state;
500
+ }
501
+ function writeState(home,state){
502
+ const stateFile=path.join(home,'notify-state.json'),temp=`${stateFile}.${process.pid}.${randomUUID()}.tmp`;
503
+ try{fs.writeFileSync(temp,JSON.stringify(state),{mode:0o600});fs.renameSync(temp,stateFile);return true;}
504
+ catch{try{fs.unlinkSync(temp);}catch{}return false;}
505
+ }
506
+ function withState(home,update){
507
+ const lockFile=path.join(home,'notify-state.lock');
508
+ const lock=takeLock(lockFile);if(lock===null)return {status:'state_busy'};
254
509
  try{
255
- let state={version:1,keys:{},sends:[]};
256
- const read=readBounded(stateFile,CONTROL_FILE_LIMIT);if(read===null)return 'state_invalid';
257
- if(!read.missing){try{state=JSON.parse(read.text);}catch{return 'state_invalid';}}
258
- if(!state||state.version!==1||!state.keys||typeof state.keys!=='object'||Array.isArray(state.keys)
259
- ||!Array.isArray(state.sends)||!state.sends.every(Number.isFinite)
260
- ||!Object.values(state.keys).every(Number.isFinite))return 'state_invalid';
261
- const keys=Object.fromEntries(Object.entries(state.keys).filter(([,at])=>now-at<NOTIFY_LIMITS.sameKeyMs&&at<=now));
262
- const sends=state.sends.filter(at=>now-at<24*3600*1000&&at<=now);
263
- if(Object.hasOwn(keys,hash))return 'duplicate';
264
- if(sends.filter(at=>now-at<60000).length>=NOTIFY_LIMITS.perMinute)return 'rate_minute';
265
- if(sends.length>=NOTIFY_LIMITS.perDay)return 'rate_day';
266
- keys[hash]=now;sends.push(now);
267
- const temp=`${stateFile}.${process.pid}.${randomUUID()}.tmp`;
268
- try{fs.writeFileSync(temp,JSON.stringify({version:1,keys,sends}),{mode:0o600});fs.renameSync(temp,stateFile);}
269
- catch{try{fs.unlinkSync(temp);}catch{}return 'state_write_failed';}
270
- return 'ok';
510
+ const state=readState(home);if(state===null)return {status:'state_invalid'};
511
+ return update(state);
271
512
  }finally{releaseLock(lockFile,lock);}
272
513
  }
514
+ // A deferred stop (notifyLater) is one pending file per attention record, read
515
+ // and changed only under the state lock. Its waiter sends only while its token
516
+ // is still the pending one; progress, a new step, a newer stop of the same
517
+ // session or an immediate notice about it removes or replaces the file.
518
+ const PENDING_DIR='notify-pending';
519
+ const CONFIG_NOTICE_MS=24*3600*1000;
520
+ // One fixed configuration-fault notice (at most once a day) replaces every
521
+ // deferred stop while the pending directory is unsafe: those stops are not
522
+ // sent one by one at once (that would bring back the noise deferral removes).
523
+ export const PENDING_UNSAFE_ACTION='延后提醒不可用:.cm-workflow 目录下的 notify-pending 权限或类型不安全(要求本人所有、权限 700 的普通目录,不能是链接),修好前普通停顿不会提醒';
524
+ // The directory itself must be a real 0700 directory of this user inside the
525
+ // notify home: never a symbolic link (a link could point the writes, renames
526
+ // and deletes below anywhere). Anything else: nothing is read, written or
527
+ // removed there. {missing:true} | {dir} | null (unsafe).
528
+ function pendingDir(home,create=false){
529
+ const dir=path.join(home,PENDING_DIR);
530
+ let info;
531
+ try{info=fs.lstatSync(dir);}
532
+ catch(error){
533
+ if(error?.code!=='ENOENT')return null;
534
+ if(!create)return {missing:true};
535
+ try{fs.mkdirSync(dir,{mode:0o700});fs.chmodSync(dir,0o700);info=fs.lstatSync(dir);}catch{return null;}
536
+ }
537
+ if(info.isSymbolicLink()||!info.isDirectory())return null;
538
+ if(process.platform!=='win32'&&((info.mode&0o777)!==0o700||typeof process.getuid==='function'&&info.uid!==process.getuid()))return null;
539
+ try{if(fs.realpathSync(dir)!==path.join(fs.realpathSync(home),PENDING_DIR))return null;}catch{return null;}
540
+ return {dir};
541
+ }
542
+ const pendingFile=(dir,hash)=>path.join(dir,`${hash}.json`);
543
+ // {missing:true} | null (unreadable or unsafe: treated as cancelled) | {token,at}
544
+ function readPending(home,hash){
545
+ const place=pendingDir(home);if(place===null||place.missing)return place;
546
+ const read=readBounded(pendingFile(place.dir,hash),4096);if(read===null||read.missing)return read;
547
+ try{const value=JSON.parse(read.text);return typeof value?.token==='string'&&Number.isFinite(value.at)?value:null;}catch{return null;}
548
+ }
549
+ function removePending(home,hash){
550
+ const place=pendingDir(home);if(place===null||place.missing)return false;
551
+ try{fs.unlinkSync(pendingFile(place.dir,hash));return true;}catch{return false;}
552
+ }
553
+ function writePending(home,hash,value){
554
+ const place=pendingDir(home,true);if(place===null||place.missing)return false;
555
+ const file=pendingFile(place.dir,hash),temp=`${file}.${process.pid}.${randomUUID()}.tmp`;
556
+ try{fs.writeFileSync(temp,JSON.stringify(value),{mode:0o600,flag:'wx'});fs.renameSync(temp,file);return true;}
557
+ catch{try{fs.unlinkSync(temp);}catch{}return false;}
558
+ }
559
+ // Removes a pending stop recorded at or before `before` (an unreadable one too),
560
+ // only inside a safe pending directory.
561
+ function dropPending(home,hash,before){
562
+ const place=pendingDir(home);if(place===null||place.missing)return false;
563
+ const pending=readPending(home,hash);
564
+ if(pending?.missing||pending&&pending.at>before)return false;
565
+ return removePending(home,hash);
566
+ }
567
+ function reserve(home,{hash,attention=null,event,code=null,pendingToken,urgent=false},now,limits){
568
+ return withState(home,state=>{
569
+ // A deferred waiter fires only for its own still-pending stop; any other
570
+ // notice about the same session supersedes a pending one.
571
+ if(attention!==null&&pendingToken!==undefined){
572
+ const pending=readPending(home,attention);
573
+ if(!pending||pending.missing||pending.token!==pendingToken)return {status:'cancelled'};
574
+ removePending(home,attention);
575
+ }else if(attention!==null)dropPending(home,attention,Infinity);
576
+ // Configuration-fault notices repeat at most once a day; other keys once per sameKeyMs.
577
+ const keys=Object.fromEntries(Object.entries(state.keys).filter(([,at])=>now-at<CONFIG_NOTICE_MS&&at<=now));
578
+ const sameKeyMs=event==='config'?CONFIG_NOTICE_MS:NOTIFY_LIMITS.sameKeyMs;
579
+ const sends=state.sends.filter(at=>now-at<24*3600*1000&&at<=now);
580
+ const records=Object.fromEntries(Object.entries(state.attention).filter(([,item])=>now-item.lastAt<NOTIFY_LIMITS.attentionTtlMs&&item.lastAt<=now));
581
+ let followUp=false,next=null;
582
+ if(attention===null){if(Object.hasOwn(keys,hash)&&now-keys[hash]<sameKeyMs)return {status:'duplicate'};}
583
+ else{
584
+ const level=ATTENTION_LEVEL[event]??2,record=records[attention];
585
+ const changed=!record||level>record.level||(event==='stuck'&&code&&code!==record.code);
586
+ if(changed)next={level,code:event==='stuck'?code:(record?.code??null),count:1,lastAt:now};
587
+ else if(record.count===1&&now-record.lastAt>=limits.followUpMs){followUp=true;next={...record,count:2,lastAt:now};}
588
+ else return {status:'duplicate'};
589
+ }
590
+ const persist=extra=>writeState(home,{version:2,keys,attention:records,sends,suppressed:state.suppressed,...extra});
591
+ // A fatal stop (urgent) is never rate limited. A deferred stop already waited and its
592
+ // pending record is gone, so neither limit may lose it for good: each one is a real
593
+ // stop the session did not move past within waitMinutes, which already bounds them.
594
+ if(!urgent&&pendingToken===undefined&&(sends.filter(at=>now-at<limits.windowMs).length>=limits.perWindow||sends.length>=NOTIFY_LIMITS.perDay)){
595
+ const status=sends.length>=NOTIFY_LIMITS.perDay?'rate_day':'rate_window';
596
+ return persist({suppressed:state.suppressed+1})?{status}:{status:'state_write_failed'};
597
+ }
598
+ if(attention===null)keys[hash]=now;else records[attention]=next;
599
+ sends.push(now);
600
+ return persist({suppressed:0})?{status:'ok',followUp,suppressed:state.suppressed}:{status:'state_write_failed'};
601
+ });
602
+ }
603
+
604
+ // A real step forward ends the attention record, so the next stop is sent at
605
+ // once. Only a record from before the step (lastAt <= before) is removed: a
606
+ // newer stop recorded meanwhile stays. A busy lock is retried a few times;
607
+ // a clear that still fails is logged, never silently dropped.
608
+ export async function clearAttention(attentionKey,{env=process.env,before=Date.now(),attempts=10,delayMs=100}={}){
609
+ try{
610
+ if(typeof attentionKey!=='string'||!attentionKey||!readNotifyConfig(env))return false;
611
+ const home=notifyHome(env),hash=keyHash(attentionKey);
612
+ for(let attempt=1;;attempt++){
613
+ const result=withState(home,state=>{
614
+ // A stop still waiting to be sent (notifyLater) from before the step is dropped too.
615
+ const dropped=dropPending(home,hash,before);
616
+ const record=state.attention[hash];
617
+ if(!record||record.lastAt>before)return {status:dropped?'ok':'unchanged'};
618
+ const attention={...state.attention};delete attention[hash];
619
+ return writeState(home,{...state,version:2,attention})?{status:'ok'}:{status:'state_write_failed'};
620
+ });
621
+ if(result.status==='ok')return true;
622
+ if(result.status==='unchanged')return false;
623
+ if(result.status!=='state_busy'||attempt>=attempts){
624
+ appendNotifyLog(home,Date.now(),{event:'clear',hash,result:`failed ${result.status}`});return false;
625
+ }
626
+ await new Promise(resolve=>setTimeout(resolve,delayMs));
627
+ }
628
+ }catch{return false;}
629
+ }
630
+
631
+ // A new step of the session (the driver's host accepted it) means someone is
632
+ // handling it: a stop from before that still waits to be sent is dropped.
633
+ export async function cancelPendingNotice(attentionKey,{env=process.env,before=Date.now(),attempts=10,delayMs=100}={}){
634
+ try{
635
+ if(typeof attentionKey!=='string'||!attentionKey||!readNotifyConfig(env))return false;
636
+ const home=notifyHome(env),hash=keyHash(attentionKey),lockFile=path.join(home,'notify-state.lock');
637
+ for(let attempt=1;;attempt++){
638
+ const lock=takeLock(lockFile);
639
+ if(lock!==null){try{return dropPending(home,hash,before);}finally{releaseLock(lockFile,lock);}}
640
+ if(attempt>=attempts){appendNotifyLog(home,Date.now(),{event:'cancel',hash,result:'failed state_busy'});return false;}
641
+ await new Promise(resolve=>setTimeout(resolve,delayMs));
642
+ }
643
+ }catch{return false;}
644
+ }
645
+
646
+ // Driver side: a stop that is not a person's own decision is sent only if
647
+ // nothing moved for waitMinutes (2026-10-26: notices arrived while the session
648
+ // was still working). A detached waiter (notify-later.mjs) sleeps, then calls
649
+ // notify() with its token; notify() sends only while that token is still the
650
+ // session's pending stop, through the usual lock, dedup and frequency rules.
651
+ // No config: nothing is written or started. Without an attention record there
652
+ // is nothing that could cancel it, so it is sent at once as before.
653
+ export const NOTIFY_LATER_MAX_MS=24*3600*1000;
654
+ export async function notifyLater(fields,{env=process.env,delayMs=null,extraDelayMs=0,now=Date.now(),attempts=10,retryMs=100}={}){
655
+ try{
656
+ const config=readNotifyConfig(env);if(!config)return {scheduled:false,reason:'off'};
657
+ if(typeof fields?.key!=='string'||!fields.key)return {scheduled:false,reason:'invalid_key'};
658
+ if(typeof fields.attentionKey!=='string'||!fields.attentionKey)return {scheduled:false,reason:'sent_now',...notify(fields,{env,now})};
659
+ const delay=Math.max(1,Math.min(NOTIFY_LATER_MAX_MS,(Number.isSafeInteger(delayMs)&&delayMs>0?delayMs:config.waitMs)
660
+ +(Number.isSafeInteger(extraDelayMs)&&extraDelayMs>0?extraDelayMs:0)));
661
+ const home=notifyHome(env),hash=keyHash(fields.attentionKey),token=randomUUID(),lockFile=path.join(home,'notify-state.lock');
662
+ let written=false;
663
+ for(let attempt=1;attempt<=attempts&&!written;attempt++){
664
+ const lock=takeLock(lockFile);
665
+ if(lock!==null){try{written=writePending(home,hash,{version:1,token,at:now,dueAt:now+delay});}finally{releaseLock(lockFile,lock);}
666
+ if(!written)break;}
667
+ else if(attempt<attempts)await new Promise(resolve=>setTimeout(resolve,retryMs));
668
+ }
669
+ const workflow=clean(fields.workflow,24)||'cm';
670
+ if(!written){
671
+ const reason=pendingDir(home)===null?'pending_dir_unsafe':'pending_write';
672
+ appendNotifyLog(home,now,{event:'later',workflow,hash,result:`failed ${reason}`});
673
+ if(reason==='pending_dir_unsafe'){
674
+ const fault=notify({key:'config|notify-pending-unsafe',event:'config',workflow,project:fields.project,session:fields.session,
675
+ sessionTitle:fields.sessionTitle,code:'notify_pending_unsafe',action:PENDING_UNSAFE_ACTION,nextAction:PENDING_UNSAFE_ACTION},{env,now});
676
+ return {scheduled:false,reason,faultNotice:fault.sent};
677
+ }
678
+ return {scheduled:false,reason};
679
+ }
680
+ const job={fields:{...fields,delivery:undefined,sessionTitle:fields.sessionTitle===undefined?sessionTitle(env):fields.sessionTitle},token,delayMs:delay};
681
+ const child=spawn(process.execPath,[LATER_RUNNER],{detached:true,stdio:'ignore',windowsHide:true,
682
+ env:{...env,CM_NOTIFY_LATER:JSON.stringify(job)}});
683
+ child.on('error',()=>{
684
+ appendNotifyLog(home,Date.now(),{event:'later',workflow,hash,result:'failed waiter'});
685
+ const lock=takeLock(lockFile);if(lock!==null){try{if(readPending(home,hash)?.token===token)removePending(home,hash);}finally{releaseLock(lockFile,lock);}}
686
+ });
687
+ child.unref();
688
+ return {scheduled:true,reason:'armed'};
689
+ }catch{return {scheduled:false,reason:'error'};}
690
+ }
691
+ // The waiter's send: retried briefly while the state lock is busy.
692
+ export async function sendPendingNotice(fields,token,{env=process.env,attempts=20,retryMs=100}={}){
693
+ for(let attempt=1;;attempt++){
694
+ const result=notify(fields,{env,pendingToken:token});
695
+ if(result.reason!=='state_busy'||attempt>=attempts)return result;
696
+ await new Promise(resolve=>setTimeout(resolve,retryMs));
697
+ }
698
+ }
273
699
 
700
+ const LEVEL_OF=Object.freeze({done:'passive',idle:'active'});
274
701
  // Never throws and never waits. Returns {sent, reason}; sent means the command
275
702
  // was handed to the detached launcher, whose own failures go to notify.log.
276
- export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs}={}){
703
+ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,pendingToken,urgent=false}={}){
277
704
  try{
278
705
  const config=readNotifyConfig(env);if(!config)return {sent:false,reason:'off'};
279
706
  if(typeof fields?.key!=='string'||!fields.key)return {sent:false,reason:'invalid_key'};
280
707
  const home=notifyHome(env),hash=keyHash(fields.key),event=fields.event??'stuck',workflow=clean(fields.workflow,24)||'cm';
281
- const reserved=reserve(home,hash,now);
282
- if(reserved!=='ok'){
283
- if(reserved!=='duplicate')appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved}`});
284
- return {sent:false,reason:reserved};
708
+ const attention=typeof fields.attentionKey==='string'&&fields.attentionKey&&Object.hasOwn(ATTENTION_LEVEL,event)
709
+ ?keyHash(fields.attentionKey):null;
710
+ if(pendingToken!==undefined&&attention===null)return {sent:false,reason:'cancelled'};
711
+ const reserved=reserve(home,{hash,attention,event,code:clean(fields.code,64)||null,pendingToken,urgent:urgent===true},now,config);
712
+ if(reserved.status!=='ok'){
713
+ if(!['duplicate','cancelled'].includes(reserved.status))appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved.status}`});
714
+ return {sent:false,reason:reserved.status};
285
715
  }
286
- const message=buildNotifyMessage(fields,{now,text:config.text});
716
+ if(fields.sessionTitle===undefined)fields={...fields,sessionTitle:sessionTitle(env)};
717
+ const message=buildNotifyMessage(fields,{now,text:config.text,layout:config.layout,followUp:reserved.followUp,suppressed:reserved.suppressed});
287
718
  const payload={...message,event};
288
- for(const name of ['project','workflow','runId','task','stage','code','nextAction']){
719
+ for(const name of ['project','workflow','runId','feature','task','stage','code','nextAction','session','sessionTitle']){
289
720
  const value=name==='project'?projectName(fields.project):clean(fields[name],name==='nextAction'?200:64);
290
721
  if(value)payload[name]=value;
291
722
  }
723
+ // What the person does next, in plain words (the same line the message shows).
724
+ if(event!=='done')payload.action=noticeAction(fields);
725
+ const group=projectName(fields.project)||'CM',level=LEVEL_OF[event]??'timeSensitive';
292
726
  const child=spawn(process.execPath,[RUNNER,home,hash,event,workflow,String(timeoutMs),'--',...config.command],
293
727
  {detached:true,stdio:'ignore',windowsHide:true,
294
- env:{...env,CM_NOTIFY_TITLE:message.title,CM_NOTIFY_BODY:message.body,CM_NOTIFY_PAYLOAD:JSON.stringify(payload)}});
728
+ env:{...env,CM_NOTIFY_LATER:undefined,CM_NOTIFY_TITLE:message.title,CM_NOTIFY_SUBTITLE:message.subtitle,CM_NOTIFY_BODY:message.body,
729
+ CM_NOTIFY_GROUP:group,CM_NOTIFY_LEVEL:level,CM_NOTIFY_PAYLOAD:JSON.stringify(payload)}});
295
730
  child.on('error',()=>appendNotifyLog(home,Date.now(),{event,workflow,hash,result:'failed launcher'}));
296
731
  child.unref();
297
732
  return {sent:true,reason:'launched'};
@@ -316,7 +751,9 @@ export function writeHostRegistry({sessionKey,workflow,project,startedAt,row=nul
316
751
  operation:clean(operation,32)||null,
317
752
  runId:text(result.identity?.runId)??text(result.runId)??text(result.batchId)??null,
318
753
  task:text(result.identity?.taskId)??text(result.taskId)??null,
319
- stage:text(result.stage)??text(result.state)??text(result.status)??null};
754
+ stage:text(result.stage)??text(result.state)??text(result.status)??null,
755
+ // The session that started this host, so a later patrol can name it.
756
+ sessionTitle:sessionTitle(env)};
320
757
  const file=path.join(dir,`${sessionKey}.json`),temp=`${file}.${process.pid}.tmp`;
321
758
  fs.writeFileSync(temp,JSON.stringify(entry),{mode:0o600});fs.renameSync(temp,file);return true;
322
759
  }catch{return false;}
@@ -331,7 +768,16 @@ export function removeHostRegistry(sessionKey,{env=process.env}={}){
331
768
  // Host side: one notice when a host_request has waited waitMinutes for the
332
769
  // session's answer. The timer never keeps the process alive.
333
770
  const CHECK_KINDS=new Set(['check','verification_precheck','init_verify']);
334
- export function scheduleWaitNotice({kind,callId,workflow,project,env=process.env}){
771
+ // A host that is still waiting re-sends once followUpMs after its first notice
772
+ // (reserve() decides whether it is due); answering or ending the session
773
+ // cancels it. A driver that already exited has no process left to do this.
774
+ function armed(delay,fire,config){
775
+ let follow=null;
776
+ const timer=setTimeout(()=>{fire();follow=setTimeout(fire,config.followUpMs);follow.unref?.();},delay);
777
+ timer.unref?.();
778
+ return ()=>{clearTimeout(timer);if(follow)clearTimeout(follow);};
779
+ }
780
+ export function scheduleWaitNotice({kind,callId,workflow,project,args=process.argv.slice(2),session=notifySessionLabel(args),env=process.env}){
335
781
  try{
336
782
  const config=readNotifyConfig(env);if(!config)return null;
337
783
  // A check request is answered only after the session has run the project's
@@ -339,10 +785,9 @@ export function scheduleWaitNotice({kind,callId,workflow,project,env=process.env
339
785
  // minutes; waiting that long is not idleness, so it uses its own threshold.
340
786
  const waitMs=CHECK_KINDS.has(kind)?config.checkWaitMs:config.waitMs;
341
787
  const minutes=Math.max(1,Math.round(waitMs/60000));
342
- const timer=setTimeout(()=>{notify({key:`wait|${workflow}|${callId}`,event:'waiting',workflow,project,stage:kind,
343
- code:'waiting_session_answer',nextAction:`宿主已等待会话应答约 ${minutes} 分钟,请回到会话处理`},{env});},waitMs);
344
- timer.unref?.();
345
- return ()=>clearTimeout(timer);
788
+ return armed(waitMs,()=>notify({key:`wait|${workflow}|${callId}`,event:'waiting',workflow,project,stage:kind,session,
789
+ attentionKey:attentionKeyFor({project,session,workflow,runId:launchRunKey(args)}),
790
+ code:'waiting_session_answer',nextAction:`宿主已等待会话应答约 ${minutes} 分钟,请回到会话处理`},{env}),config);
346
791
  }catch{return null;}
347
792
  }
348
793
 
@@ -351,7 +796,7 @@ export function scheduleWaitNotice({kind,callId,workflow,project,env=process.env
351
796
  // result that already waits on a person (or ended the run) says so instead of
352
797
  // "idle". Built only from that result's structured fields; the timer never
353
798
  // keeps the process alive.
354
- export function scheduleIdleNotice({workflow,project,sessionKey,seq,row,since=Date.now(),env=process.env}){
799
+ export function scheduleIdleNotice({workflow,project,sessionKey,seq,row,since=Date.now(),args=process.argv.slice(2),session=notifySessionLabel(args),env=process.env}){
355
800
  try{
356
801
  const config=readNotifyConfig(env);if(!config)return null;
357
802
  // `since` is the last real reply: re-arming after a poll keeps that deadline.
@@ -359,18 +804,31 @@ export function scheduleIdleNotice({workflow,project,sessionKey,seq,row,since=Da
359
804
  const minutes=Math.max(1,Math.round(config.idleMs/60000));
360
805
  const kind=classifyDriveResult(workflow,row),result=obj(row?.result);
361
806
  const runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
362
- const task=text(result.identity?.taskId)??text(result.taskId);
807
+ const task=text(result.identity?.taskId)??text(result.taskId),feature=text(result.feature);
363
808
  const stage=text(result.stage)??text(result.state)??text(result.status);
364
809
  const nextAction=kind==='done'?`流程已结束,宿主仍开着约 ${minutes} 分钟没有下一步,请回到会话收尾或开始下一项`
365
810
  :kind==='stuck'?`上一步停在需要你处理的状态,约 ${minutes} 分钟没有下一步,请回到会话处理`
366
811
  :`上一步已结束约 ${minutes} 分钟,会话没有发下一步,请回到会话查看`;
367
- const timer=setTimeout(()=>{notify({key:`idle|${workflow}|${sessionKey}|${seq}`,event:kind?'idle_waiting':'idle',
368
- workflow,project,runId,task,stage,code:kind?'waiting_for_you':'no_next_step',nextAction},{env});},delay);
369
- timer.unref?.();
370
- return ()=>clearTimeout(timer);
812
+ return armed(delay,()=>notify({key:`idle|${workflow}|${sessionKey}|${seq}`,event:kind?'idle_waiting':'idle',
813
+ workflow,project,runId,feature,task,stage,session,attentionKey:attentionKeyFor({project,session,workflow,runId:runId??launchRunKey(args)}),
814
+ code:kind?'waiting_for_you':'no_next_step',nextAction},{env}),config);
371
815
  }catch{return null;}
372
816
  }
373
817
 
818
+ // Stops sent at once: only the person's own decision or authorization helps
819
+ // (spec approval, an authorization, a spent round or retry budget, a verdict
820
+ // that cannot pass, a re-asked confirmation, a question to the person). Any
821
+ // other stop is deferred (notifyLater): the session may well move on by itself.
822
+ const IMMEDIATE_CODES=new Set(['permission_denied','awaiting_spec_approval','spec_approval_required','spec_drift',
823
+ 'review_limit','review_blocked','review_redispatch_limit','review_abandon_budget_exhausted','confirm_reask_decision_required']);
824
+ // `ask` is the classifier's own finding that the person must answer or decide
825
+ // (the same facts it used to call the stop stuck), so the two cannot drift.
826
+ export function immediateStop({codes=[],state=null,pendingAction=null,ask=false}={}){
827
+ if(ask===true||state==='awaiting_spec_approval'||pendingAction==='spec_approval'||Object.hasOwn(AUTHORIZED_RECOVERY,pendingAction))return true;
828
+ return codes.some(code=>typeof code==='string'&&(IMMEDIATE_CODES.has(code)||/(^|_)(authorization|approval)_required$/.test(code)
829
+ ||/_(retry|redo|recheck)_limit$/.test(code)));
830
+ }
831
+
374
832
  // Driver side: decide from the final host response (or the driver's own stop)
375
833
  // whether a person is needed. Each workflow is classified by its own result
376
834
  // contract (see the host named in each entry); normal progress returns null.
@@ -391,9 +849,10 @@ const FIX_FLOW=new Set(['reproduce','diagnose','cause_review_required','test_aut
391
849
  function classifyFix(r){
392
850
  const stage=text(r.stage);if(!stage)return null;
393
851
  if(stage==='completed')return 'done';
394
- if(r.progress&&typeof r.progress==='object'){if(r.progress.finished===true)return 'done';if(r.progress.requiresUser===true)return 'stuck';}
852
+ // requiresUser: the owner hands the decision to the person (progress.mjs, host.mjs).
853
+ if(r.progress&&typeof r.progress==='object'){if(r.progress.finished===true)return 'done';if(r.progress.requiresUser===true)return 'ask';}
395
854
  // A refused review authorization keeps the stage (execution.mjs) but waits on a person.
396
- if(text(r.reason)==='permission_denied')return 'stuck';
855
+ if(text(r.reason)==='permission_denied')return 'ask';
397
856
  return FIX_FLOW.has(stage)||FIX_FLOW.has(stage.replace(/^revision_/,''))?null:'stuck';
398
857
  }
399
858
  // cm-ai conversation entry (runtime/js/cm-ai/cm-ai-conversation-entry.mjs, operator-guidance.mjs,
@@ -418,6 +877,9 @@ function classifyAi(r){
418
877
  if(code==='qa_fix_incomplete')return classifyFix({stage:r.fixStage});
419
878
  if(['qa_fix_completed','qa_fix_active','qa_fix_owner_busy'].includes(code)||outcome==='abandoned')return null;
420
879
  if(r.pendingAction==='start_next_task'||AI_PROGRESS_CODES.has(code))return null;
880
+ // Spec approval and authorizations: only the person can give them.
881
+ if(state==='awaiting_spec_approval'||r.pendingAction==='spec_approval'||code==='permission_denied'
882
+ ||/(^|_)authorization_required$/.test(code??''))return 'ask';
421
883
  if(['rejected','denied','cancelled','blocked','awaiting'].includes(outcome)||AI_STUCK_STATES.has(state)
422
884
  ||AI_STUCK_ACTIONS.has(r.pendingAction)||AI_STUCK_CODES.has(code))return 'stuck';
423
885
  return null;
@@ -433,10 +895,11 @@ const CLASSIFY={
433
895
  const stage=text(r.stage),status=text(r.status),review=obj(r.reviewState);
434
896
  if(stage==='awaiting_review'||status==='awaiting_review')return 'done';
435
897
  if(STUCK_COMMON.has(stage)||STUCK_COMMON.has(status))return 'stuck';
436
- if(['awaiting_user','awaiting_planning_user','awaiting_design_user','self_check_needs_human','change_confirmation',
437
- 'change_rejected','inputs_replaced'].includes(stage))return 'stuck';
898
+ // A question or confirmation put to the person.
899
+ if(['awaiting_user','awaiting_planning_user','awaiting_design_user','self_check_needs_human','change_confirmation'].includes(stage))return 'ask';
900
+ if(['change_rejected','inputs_replaced'].includes(stage))return 'stuck';
438
901
  if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
439
- if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'stuck';
902
+ if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'ask';
440
903
  if(status&&(/_unknown$/.test(status)||['correction_recovery_required','correction_recovery_conflict','disposition_details_need_verification'].includes(status)))return 'stuck';
441
904
  if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
442
905
  if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
@@ -453,21 +916,27 @@ const CLASSIFY={
453
916
  // resume, abandon or discard; an interrupted save waits on reconciliation.
454
917
  if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
455
918
  if(stage==='draft_ready')return r.confirmationRequired===true?null:'stuck';
456
- return ['awaiting_user','save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
919
+ // awaiting_user: the interview asked the person a question (cm-idea-host.mjs).
920
+ if(stage==='awaiting_user')return 'ask';
921
+ return ['save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
457
922
  },
458
923
  // scripts/cm-init-host.mjs, runtime/js/cm-init/draft-generation.mjs (generation returns status, no stage).
459
924
  'cm-init'(r){
460
925
  const stage=text(r.stage)??(r.status==='blocked'?'blocked':null),recovery=obj(r.recovery);
461
926
  if(['rules_written','rules_present'].includes(stage))return 'done';
462
927
  if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
463
- return ['analysis_blocked','verification_blocked','confirmation_required','confirmation_rejected','review_changes_requested',
928
+ // confirmation_required: the rules wait for the person's init_confirm (cm-init-host.mjs).
929
+ if(stage==='confirmation_required')return 'ask';
930
+ return ['analysis_blocked','verification_blocked','confirmation_rejected','review_changes_requested',
464
931
  'review_blocked','write_incomplete','write_unknown',...STUCK_COMMON].includes(stage)?'stuck':null;
465
932
  },
466
933
  // runtime/js/cm-refactor/workflow.mjs.
467
934
  'cm-refactor'(r){
468
935
  const stage=text(r.stage);
469
936
  if(['done','not_needed','rejected'].includes(stage))return 'done';
470
- return ['awaiting_finish','rulebook_rejected','correction_required',...STUCK_COMMON].includes(stage)?'stuck':null;
937
+ // awaiting_finish: the finish confirmation was not given (workflow.mjs confirm 'finish').
938
+ if(stage==='awaiting_finish')return 'ask';
939
+ return ['rulebook_rejected','correction_required',...STUCK_COMMON].includes(stage)?'stuck':null;
471
940
  },
472
941
  // runtime/js/cm-test/host.mjs: verdict in result.overall when stage is reported.
473
942
  'cm-test'(r){
@@ -489,16 +958,25 @@ const CLASSIFY={
489
958
  const READ_ONLY=new Set(['status','fix_status','cancel','qa_result','context_refresh','read_batch','inspect_correction',
490
959
  'final_review_package','review_findings','completion_evidence','cause_review_package']);
491
960
  export const NOTIFY_WORKFLOWS=Object.freeze(Object.keys(CLASSIFY));
492
- export function classifyDriveResult(workflow,row){
961
+ // 'ask' (the person must answer or decide) is a stuck stop; only its delivery differs.
962
+ function classifyRaw(workflow,row){
493
963
  if(row?.error)return 'stuck';
494
964
  const classify=CLASSIFY[workflow];
495
965
  return classify?classify(obj(row?.result)):null;
496
966
  }
497
- export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
967
+ export function classifyDriveResult(workflow,row){
968
+ const kind=classifyRaw(workflow,row);
969
+ return kind==='ask'?'stuck':kind;
970
+ }
971
+ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null,env=process.env}){
498
972
  if(READ_ONLY.has(operation))return null;
973
+ // Under the standing authorization the session decides: a finished unit is not news,
974
+ // and any stop waits waitMinutes (dropped once the session moves on). Fatal stops
975
+ // page at once from the session itself (cm-autonomy.mjs notify).
976
+ const autonomous=readAutonomy(env).on;
499
977
  const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
500
- const kind=failure?'stuck':classifyDriveResult(workflow,row);
501
- if(!kind)return null;
978
+ const raw=failure?'stuck':classifyRaw(workflow,row),kind=raw==='ask'?'stuck':raw,ask=raw==='ask';
979
+ if(!kind||autonomous&&kind==='done')return null;
502
980
  const done=kind==='done',result=obj(row?.result),progress=obj(result.progress),nested=obj(result.result);
503
981
  const code=text(failure)??text(row?.error?.code)??text(result.code)??text(result.reason)??text(result.blocker)
504
982
  ??text(progress.blocker)??text(result.overall)??text(nested.overall)??text(result.state)??text(result.status)??text(result.stage)??null;
@@ -506,10 +984,48 @@ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
506
984
  const task=text(result.identity?.taskId)??text(result.taskId);
507
985
  const attempt=Number.isSafeInteger(result.identity?.attempt)?result.identity.attempt:null;
508
986
  const stage=text(result.stage)??text(result.state)??text(result.status)??operation??null;
509
- const run=runId??`args:${keyHash(args.map(String).join('\0'))}`;
987
+ const run=runId??launchRunKey(args);
988
+ const project=cwd?path.resolve(cwd):null,session=notifySessionLabel(args),feature=text(result.feature)??text(result.identity?.feature);
989
+ const reviewFailure=typeof result.reviewFailure==='string'&&/^reviewer_[a-z_]{1,48}$/.test(result.reviewFailure)?result.reviewFailure:null;
990
+ const developFailure=typeof result.developFailure==='string'&&/^developer_[a-z_]{1,48}$/.test(result.developFailure)?result.developFailure:null;
991
+ const pendingAction=typeof result.pendingAction==='string'&&/^[a-z_]{1,32}$/.test(result.pendingAction)?result.pendingAction:null;
992
+ const delivery=done||!autonomous&&immediateStop({codes:[failure,row?.error?.code,result.code,result.reason,result.blocker,progress.blocker],
993
+ state:text(result.state),pendingAction,ask})?'now':'later';
510
994
  return {key:[workflow,run,task??'',attempt??'',stage??'',done?'done':code??''].join('|'),
511
- event:kind,workflow,project:cwd?path.basename(path.resolve(cwd)):null,runId,task,stage,
995
+ ...(done?{}:{attentionKey:attentionKeyFor({project,session,workflow,runId:run})}),
996
+ event:kind,workflow,project,runId,feature,task,stage,session,
512
997
  code:done?(text(result.code)??text(result.overall)??text(nested.overall)??'done'):code,
513
998
  // A finished unit is the natural point to start a fresh session (runtime/model-efficiency.md).
514
- nextAction:done?'建议在新会话里开始下一个任务,减少重复读入的上下文':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction)};
999
+ nextAction:done?'会话边界:换新会话,下一项在新会话里运行':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction),
1000
+ ...(reviewFailure?{reviewFailure}:{}),...(developFailure?{developFailure}:{}),...(pendingAction&&!done?{pendingAction}:{}),...(ask?{ask:true}:{}),delivery,
1001
+ ...(autonomous?{autonomous:true}:{})};
1002
+ }
1003
+
1004
+ // The attention record a successful, non-read-only step clears (see clearAttention).
1005
+ export function driveProgressKey({host,cwd,args=[],operation,row=null,failure=null}){
1006
+ if(READ_ONLY.has(operation)||failure||row?.error)return null;
1007
+ const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
1008
+ if(classifyDriveResult(workflow,row))return null;
1009
+ const result=obj(row?.result),runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
1010
+ // Same fallback as driveNotice: without a returned run, the launch arguments identify it.
1011
+ const run=runId??launchRunKey(args);
1012
+ return attentionKeyFor({project:cwd?path.resolve(cwd):null,session:notifySessionLabel(args),workflow,runId:run});
1013
+ }
1014
+
1015
+ // The attention record a new, non-read-only step of this session would clear;
1016
+ // its start cancels a deferred stop (cancelPendingNotice). With a session (every
1017
+ // driver passes --host-context) the record does not depend on the run.
1018
+ export function driveAttentionKey({host,cwd,args=[],operation}){
1019
+ if(READ_ONLY.has(operation))return null;
1020
+ const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
1021
+ return attentionKeyFor({project:cwd?path.resolve(cwd):null,session:notifySessionLabel(args),workflow,runId:launchRunKey(args)});
1022
+ }
1023
+
1024
+ // One stderr line telling which project and session this driver's notices name.
1025
+ export function notifyIdentityLine({cwd,args=[]},{env=process.env}={}){
1026
+ try{
1027
+ if(!readNotifyConfig(env))return null;
1028
+ const project=projectName(cwd?path.resolve(cwd):''),session=sessionTitle(env)??notifySessionLabel(args);
1029
+ return `提醒里的标识:项目 ${project||'-'}${session?` · 会话 ${session}`:''}`;
1030
+ }catch{return null;}
515
1031
  }