@aibyzero/cm-workflow 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +27 -0
  3. package/CHANGELOG.md +230 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +21 -3
  6. package/THIRD_PARTY_NOTICES.md +13 -0
  7. package/VERSION +1 -1
  8. package/compat/claude-commands/cm-challenge.md +3 -0
  9. package/docs/architecture.md +40 -13
  10. package/docs/cm-control-policy-v2.md +127 -9
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/installation.md +310 -4
  13. package/docs/js-workflow-control.md +153 -16
  14. package/docs/live-evidence-drivers.md +28 -4
  15. package/docs/out-of-scope/README.md +25 -0
  16. package/docs/out-of-scope/background-supervisor.md +32 -0
  17. package/docs/reviewed-integration.md +48 -0
  18. package/docs/user-guide.md +50 -21
  19. package/install-codex.sh +331 -18
  20. package/install.ps1 +28 -2
  21. package/install.sh +321 -17
  22. package/package.json +2 -1
  23. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  24. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  25. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  26. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  27. package/runtime/js/cm-ai/claude-review-stream.mjs +94 -21
  28. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  29. package/runtime/js/cm-ai/cm-ai-admission.mjs +18 -12
  30. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  31. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  32. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  33. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  34. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  35. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  36. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  37. package/runtime/js/cm-ai/control-policy.mjs +24 -6
  38. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  39. package/runtime/js/cm-ai/drive-core.mjs +236 -34
  40. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  41. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  42. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  43. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  44. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  45. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  46. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  47. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  48. package/runtime/js/cm-ai/host-check.mjs +14 -6
  49. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  52. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  53. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  54. package/runtime/js/cm-ai/host-session.mjs +42 -9
  55. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  56. package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
  57. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  58. package/runtime/js/cm-ai/host.mjs +1 -1
  59. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  60. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  61. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  62. package/runtime/js/cm-ai/operator-guidance.mjs +63 -30
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  64. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  65. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  66. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  67. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  68. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  69. package/runtime/js/cm-ai/review-package.mjs +79 -7
  70. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  71. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  72. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  73. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  74. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  75. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  76. package/runtime/js/cm-ai/task-runner.mjs +247 -41
  77. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  78. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  79. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  80. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  81. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  82. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  83. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  84. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  85. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  86. package/runtime/js/cm-fix/dossier.mjs +8 -2
  87. package/runtime/js/cm-fix/execution.mjs +578 -100
  88. package/runtime/js/cm-fix/final-review.mjs +39 -8
  89. package/runtime/js/cm-fix/finish.mjs +15 -11
  90. package/runtime/js/cm-fix/host-review.mjs +65 -10
  91. package/runtime/js/cm-fix/host.mjs +35 -12
  92. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  93. package/runtime/js/cm-fix/metrics.mjs +18 -5
  94. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  95. package/runtime/js/cm-fix/regression.mjs +16 -7
  96. package/runtime/js/cm-fix/repair.mjs +29 -8
  97. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  98. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  99. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  100. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  101. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  102. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  103. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  104. package/runtime/js/cm-fix/start.mjs +6 -3
  105. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  106. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  107. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  108. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  109. package/runtime/js/cm-prd/analysis.mjs +13 -9
  110. package/runtime/js/cm-prd/change.mjs +37 -16
  111. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  112. package/runtime/js/cm-prd/draft.mjs +31 -3
  113. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  114. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  115. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  116. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  117. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  118. package/runtime/js/cm-prd/self-check.mjs +125 -6
  119. package/runtime/js/cm-prd/session.mjs +30 -1
  120. package/runtime/js/cm-prd/summary.mjs +38 -17
  121. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  122. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  123. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  124. package/runtime/js/cm-security/scan.mjs +1 -1
  125. package/runtime/js/commander/decision.mjs +44 -0
  126. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  127. package/runtime/js/commander/ledger.mjs +265 -0
  128. package/runtime/js/commander/preflight.mjs +107 -0
  129. package/runtime/js/notify-later.mjs +13 -0
  130. package/runtime/js/notify-send.mjs +6 -2
  131. package/runtime/js/notify.mjs +570 -63
  132. package/runtime/js/review-findings.mjs +38 -0
  133. package/runtime/js/session-boundary.mjs +56 -0
  134. package/runtime/js/session-handoff.mjs +68 -0
  135. package/runtime/js/spec-task-line.mjs +27 -13
  136. package/runtime/js/specs-status.mjs +1 -1
  137. package/runtime/js/task-scope.mjs +197 -0
  138. package/runtime/logging.md +6 -1
  139. package/runtime/model-efficiency.md +69 -10
  140. package/runtime/orchestration.md +3 -1
  141. package/runtime/project-learning.md +2 -0
  142. package/runtime/review.md +12 -2
  143. package/runtime/test-contract.md +1 -0
  144. package/scripts/ci-test-weights.json +3 -0
  145. package/scripts/cm-ai-admission.mjs +11 -5
  146. package/scripts/cm-ai-admission.test.mjs +23 -2
  147. package/scripts/cm-ai-batch-drive.mjs +79 -18
  148. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  149. package/scripts/cm-ai-batch-host.mjs +38 -9
  150. package/scripts/cm-ai-batch-host.test.mjs +27 -14
  151. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  152. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  153. package/scripts/cm-ai-batch-plan.mjs +52 -0
  154. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  155. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  156. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  157. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  158. package/scripts/cm-ai-batch-run.mjs +483 -63
  159. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  160. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  161. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  162. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  163. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  164. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  165. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  166. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  167. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  168. package/scripts/cm-ai-control-policy.test.mjs +82 -0
  169. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  170. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  171. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  172. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  173. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  174. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
  175. package/scripts/cm-ai-drive.mjs +73 -17
  176. package/scripts/cm-ai-drive.test.mjs +37 -5
  177. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  178. package/scripts/cm-ai-host-fixture.mjs +9 -6
  179. package/scripts/cm-ai-host-protected.test.mjs +1 -1
  180. package/scripts/cm-ai-host.mjs +60 -19
  181. package/scripts/cm-ai-host.test.mjs +15 -0
  182. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  183. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  184. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  185. package/scripts/cm-ai-integration-preview.mjs +41 -0
  186. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  187. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  188. package/scripts/cm-ai-operator-guidance.test.mjs +71 -0
  189. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  190. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  191. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  192. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  193. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  194. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  195. package/scripts/cm-ai-review-timeout.test.mjs +20 -0
  196. package/scripts/cm-ai-run.mjs +88 -21
  197. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  198. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  199. package/scripts/cm-ai-supersede.test.mjs +28 -0
  200. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  201. package/scripts/cm-announce-hook.mjs +35 -8
  202. package/scripts/cm-announce-hook.test.mjs +25 -0
  203. package/scripts/cm-challenge.test.mjs +61 -0
  204. package/scripts/cm-check-drive-files.mjs +2 -2
  205. package/scripts/cm-check-host.test.mjs +1 -1
  206. package/scripts/cm-check-runtime.sh +58 -1
  207. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  208. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  209. package/scripts/cm-claude-probe.test.mjs +26 -0
  210. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  211. package/scripts/cm-claude-review-stream.test.mjs +49 -0
  212. package/scripts/cm-claude-worker.test.mjs +16 -0
  213. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  214. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  215. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  216. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  217. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  218. package/scripts/cm-commander-ledger.test.mjs +260 -0
  219. package/scripts/cm-commander-p2.test.mjs +295 -0
  220. package/scripts/cm-commander-preflight.mjs +84 -0
  221. package/scripts/cm-commander.mjs +116 -0
  222. package/scripts/cm-config-lock.mjs +35 -0
  223. package/scripts/cm-controlled-correction.test.mjs +10 -1
  224. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  225. package/scripts/cm-display-task-id.test.mjs +41 -0
  226. package/scripts/cm-drive-liveness.test.mjs +83 -0
  227. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  228. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  229. package/scripts/cm-external-batch-host.test.mjs +12 -9
  230. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  231. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  232. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  233. package/scripts/cm-failover.mjs +48 -10
  234. package/scripts/cm-failover.test.mjs +46 -0
  235. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  236. package/scripts/cm-fix-command-correction.mjs +17 -0
  237. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  238. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  239. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  240. package/scripts/cm-fix-drive.mjs +33 -5
  241. package/scripts/cm-fix-drive.test.mjs +49 -0
  242. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  243. package/scripts/cm-fix-host-review.test.mjs +21 -9
  244. package/scripts/cm-fix-host.mjs +26 -8
  245. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  246. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  247. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  248. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  249. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  250. package/scripts/cm-fix-review-preflight.mjs +24 -0
  251. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  252. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  253. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  254. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  255. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  256. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  257. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  258. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  259. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  260. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  261. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  262. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  263. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  264. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  265. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  266. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  267. package/scripts/cm-host-liveness.test.mjs +150 -0
  268. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  269. package/scripts/cm-host-replay.test.mjs +176 -0
  270. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  271. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  272. package/scripts/cm-install-manifest.sh +351 -0
  273. package/scripts/cm-live-evidence.test.mjs +59 -1
  274. package/scripts/cm-log-event.mjs +61 -10
  275. package/scripts/cm-log-event.test.mjs +121 -1
  276. package/scripts/cm-matt-skills.mjs +576 -0
  277. package/scripts/cm-matt-skills.test.mjs +550 -0
  278. package/scripts/cm-notify-command.test.mjs +42 -10
  279. package/scripts/cm-notify.mjs +14 -10
  280. package/scripts/cm-notify.test.mjs +625 -75
  281. package/scripts/cm-patrol.mjs +4 -1
  282. package/scripts/cm-patrol.test.mjs +23 -5
  283. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  284. package/scripts/cm-prd-completion.test.mjs +56 -13
  285. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  286. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  287. package/scripts/cm-prd-draft.test.mjs +1 -1
  288. package/scripts/cm-prd-drive.mjs +13 -6
  289. package/scripts/cm-prd-drive.test.mjs +46 -2
  290. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  291. package/scripts/cm-prd-host.mjs +10 -5
  292. package/scripts/cm-prd-host.test.mjs +4 -2
  293. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  294. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  295. package/scripts/cm-prd-revision.test.mjs +1 -1
  296. package/scripts/cm-prd-self-check-revision.test.mjs +16 -1
  297. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  298. package/scripts/cm-prd-self-check.test.mjs +105 -5
  299. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  300. package/scripts/cm-prd-summary.test.mjs +55 -3
  301. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  302. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  303. package/scripts/cm-refactor-drive.mjs +2 -1
  304. package/scripts/cm-refactor-drive.test.mjs +9 -0
  305. package/scripts/cm-release-smoke.sh +3 -15
  306. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  307. package/scripts/cm-skill-hints-exam.mjs +149 -0
  308. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  309. package/scripts/cm-skill-hints.exam.json +706 -0
  310. package/scripts/cm-skill-hints.json +119 -0
  311. package/scripts/cm-skill-hints.mjs +669 -0
  312. package/scripts/cm-skill-hints.test.mjs +831 -0
  313. package/scripts/cm-skill-judge.mjs +181 -0
  314. package/scripts/cm-skill-judge.test.mjs +255 -0
  315. package/scripts/cm-specs-status.test.mjs +4 -2
  316. package/scripts/cm-start-check.mjs +208 -0
  317. package/scripts/cm-start-check.test.mjs +321 -0
  318. package/scripts/cm-task-gate.mjs +150 -29
  319. package/scripts/cm-task-gate.test.mjs +73 -1
  320. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  321. package/scripts/cm-task-scope.test.mjs +308 -0
  322. package/scripts/cm-test-suite.mjs +109 -0
  323. package/scripts/cm-test-suite.test.mjs +162 -0
  324. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  325. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  326. package/scripts/cm-workflow-config.mjs +12 -2
  327. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  328. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  329. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  330. package/scripts/scan-public-safety.py +1 -0
  331. package/scripts/session-boundary.test.mjs +170 -0
  332. package/scripts/test-npm-install.py +14 -3
  333. package/scripts/test-shell-compat.sh +2 -0
  334. package/scripts/validate-public-repo.py +1 -0
  335. package/scripts/validate-test-cases.mjs +3 -2
  336. package/skills/cm-ai/SKILL.md +5 -2
  337. package/skills/cm-ai/references/N4-review.md +2 -1
  338. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  339. package/skills/cm-ai/references/N8-finish.md +22 -0
  340. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  341. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  342. package/skills/cm-ai/references/js-host.md +89 -17
  343. package/skills/cm-challenge/SKILL.md +65 -0
  344. package/skills/cm-challenge/evals/README.md +18 -0
  345. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  346. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  347. package/skills/cm-challenge/references/examples.md +15 -0
  348. package/skills/cm-check/SKILL.md +5 -0
  349. package/skills/cm-check/references/js-host.md +2 -0
  350. package/skills/cm-fix/SKILL.md +12 -3
  351. package/skills/cm-fix/references/command-correction.md +67 -0
  352. package/skills/cm-fix/references/isolated-review.md +54 -0
  353. package/skills/cm-fix/references/js-host.md +62 -2
  354. package/skills/cm-fix/references/test-type-correction.md +72 -0
  355. package/skills/cm-fix/references/verification-recovery.md +114 -0
  356. package/skills/cm-idea/SKILL.md +2 -0
  357. package/skills/cm-idea/references/js-host.md +2 -0
  358. package/skills/cm-notify/SKILL.md +2 -0
  359. package/skills/cm-prd/SKILL.md +12 -8
  360. package/skills/cm-prd/references/brownfield.md +8 -1
  361. package/skills/cm-prd/references/change-mode.md +6 -0
  362. package/skills/cm-prd/references/greenfield.md +4 -0
  363. package/skills/cm-prd/references/js-host.md +4 -2
  364. package/skills/cm-prd/references/spec-self-check.md +5 -1
  365. package/skills/cm-refactor/SKILL.md +8 -0
  366. package/skills/cm-refactor/references/js-host.md +2 -0
  367. package/skills/cm-test/SKILL.md +4 -0
  368. package/templates/dashboard/dashboard.html +2 -2
  369. package/templates/pixel/cm-pixel.html +1 -1
  370. package/templates/pixel/cm-pixel.sh +1 -1
  371. package/templates/pixel/dev/template.html +1 -1
  372. package/templates/statusline/cm-statusline.sh +1 -1
@@ -1,10 +1,11 @@
1
+ import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
1
2
  import test from 'node:test';
2
3
  import assert from 'node:assert/strict';
3
4
  import fs from 'node:fs';
4
5
  import os from 'node:os';
5
6
  import path from 'node:path';
6
7
  import {spawn,spawnSync} from 'node:child_process';
7
- import {notify,readNotifyConfig,parseNotifyConfig,buildNotifyMessage,normalizeNotifyText,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS,DEFAULT_NOTIFY_TEXT} from '../runtime/js/notify.mjs';
8
+ import {notify,notifyLater,cancelPendingNotice,clearAttention,sessionTitle,scheduleWaitNotice,driveProgressKey,readNotifyConfig,writeHostRegistry,scheduleIdleNotice,parseNotifyConfig,buildNotifyMessage,normalizeNotifyText,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS,DEFAULT_NOTIFY_TEXT} from '../runtime/js/notify.mjs';
8
9
 
9
10
  const NOW=Date.parse('2026-10-08T08:00:00.000Z');
10
11
  const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
@@ -21,15 +22,35 @@ function home(t,{exit=0,sleepMs=0,config={}}={}){
21
22
  process.stdin.on('end',()=>{setTimeout(()=>{fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify({title:process.env.CM_NOTIFY_TITLE,
22
23
  body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');process.exit(${exit});},${sleepMs});});`);
23
24
  fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script],...config}));
24
- const env={...process.env,CM_WORKFLOW_HOME:dir};
25
- const rows=()=>fs.existsSync(sent)?fs.readFileSync(sent,'utf8').trim().split('\n').map(line=>JSON.parse(line)):[];
25
+ // Never read the real Claude Code session of whoever runs the tests.
26
+ const env={...process.env,CM_WORKFLOW_HOME:dir};delete env.CLAUDE_CODE_SESSION_ID;
27
+ const rows=()=>{
28
+ if(!fs.existsSync(sent))return [];
29
+ const contents=fs.readFileSync(sent,'utf8'),completeEnd=contents.lastIndexOf('\n')+1;
30
+ // appendFileSync may expose an empty file or an unfinished final record.
31
+ // Only complete JSONL records are consumable; malformed complete JSON fails.
32
+ return contents.slice(0,completeEnd).split('\n').slice(0,-1).map(line=>JSON.parse(line));
33
+ };
26
34
  const log=()=>fs.existsSync(path.join(dir,'notify.log'))?fs.readFileSync(path.join(dir,'notify.log'),'utf8'):'';
27
35
  const until=async(check,ms=8000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,25));return check();};
28
36
  return {dir,env,rows,log,until};
29
37
  }
38
+ // The project shown in notices: the last two path segments, one when they are the same name
39
+ // (CI checks the repository out as .../cm-workflow/cm-workflow).
40
+ const label=dir=>{const base=path.basename(dir),parent=path.basename(path.dirname(dir));return parent&&parent!==base?`${parent}/${base}`:base;};
30
41
  const fields=(key,over={})=>({key,event:'stuck',project:'/srv/work/demo-app',workflow:'cm-fix',runId:'run-1',
31
42
  task:'T-001',stage:'blocked',code:'checks_not_passed',nextAction:'核对 reason 后恢复原运行',...over});
32
43
 
44
+ test('fixture JSONL reader waits for complete records and rejects malformed complete JSON',t=>{
45
+ const h=home(t),file=path.join(h.dir,'sent.jsonl');
46
+ assert.deepEqual(h.rows(),[]);
47
+ fs.writeFileSync(file,'');assert.deepEqual(h.rows(),[]);
48
+ fs.writeFileSync(file,'{"marker":1');assert.deepEqual(h.rows(),[]);
49
+ fs.appendFileSync(file,'}\n{"marker":');assert.deepEqual(h.rows(),[{marker:1}]);
50
+ fs.appendFileSync(file,'2}\n');assert.deepEqual(h.rows(),[{marker:1},{marker:2}]);
51
+ fs.appendFileSync(file,'{"bad":}\n');assert.throws(()=>h.rows(),SyntaxError);
52
+ });
53
+
33
54
  test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME is explicit',async t=>{
34
55
  const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-empty-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
35
56
  assert.equal(readNotifyConfig({CM_WORKFLOW_HOME:dir}),null);
@@ -38,6 +59,55 @@ test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME
38
59
  assert.equal(readNotifyConfig({NODE_TEST_CONTEXT:'child-v8'}),null);
39
60
  });
40
61
 
62
+ // 2026-10-27: acceptance runs in a test copy of a project (not under node --test)
63
+ // read the user's real notify.json and pushed to their phone. CM_NOTIFY_OFF turns
64
+ // notices off for that process tree only, before any file is read or written, and
65
+ // unlike a temporary CM_WORKFLOW_HOME keeps the user's other settings (runtimes.yml).
66
+ test('CM_NOTIFY_OFF turns every notice path off with a valid config, touching no file',async t=>{
67
+ const h=home(t),before=fs.readdirSync(h.dir).sort();
68
+ for(const value of ['1','true','yes']){
69
+ const env={...h.env,CM_NOTIFY_OFF:value};
70
+ assert.equal(readNotifyConfig(env),null,value);
71
+ assert.deepEqual(notify(fields(`off-${value}`),{env,now:NOW}),{sent:false,reason:'off'});
72
+ assert.deepEqual(await notifyLater(fields(`later-${value}`,{attentionKey:'attn|off|s'}),{env,delayMs:50}),{scheduled:false,reason:'off'});
73
+ assert.equal(scheduleWaitNotice({kind:'develop',callId:'c1',workflow:'cm-ai',project:h.dir,env}),null);
74
+ assert.equal(scheduleIdleNotice({workflow:'cm-ai',project:h.dir,sessionKey:'s',seq:1,row:null,env}),null);
75
+ assert.equal(writeHostRegistry({sessionKey:'00000000-0000-4000-8000-000000000000',workflow:'cm-ai',project:h.dir,startedAt:NOW},{env,now:NOW}),false);
76
+ }
77
+ await new Promise(resolve=>setTimeout(resolve,200));
78
+ assert.deepEqual(h.rows(),[]);
79
+ assert.deepEqual(fs.readdirSync(h.dir).sort(),before,'no notify.log, state, notify-pending or hosts entry');
80
+ // Unset, empty or "0" leaves notices on.
81
+ for(const value of [undefined,'','0'])assert.notEqual(readNotifyConfig({...h.env,CM_NOTIFY_OFF:value}),null,String(value));
82
+ });
83
+ // Review 2026-10-27 round 1: cleanEnvironment (checks, Codex workers) and
84
+ // claudeEnvironment (Claude workers) rebuild the child environment from an
85
+ // allowlist; without CM_NOTIFY_OFF in it, a child that reaches the notice module
86
+ // read the user's HOME notify.json and pushed although the run was silenced.
87
+ test('CM_NOTIFY_OFF survives the check and provider child environments',async t=>{
88
+ const h=home(t),userHome=path.join(h.dir,'user');
89
+ fs.mkdirSync(path.join(userHome,'.cm-workflow'),{recursive:true});
90
+ fs.copyFileSync(path.join(h.dir,'notify.json'),path.join(userHome,'.cm-workflow','notify.json'));
91
+ const {cleanEnvironment}=await import('../runtime/js/cm-ai/codex-config.mjs');
92
+ const {claudeEnvironment}=await import('../runtime/js/cm-ai/worker-claude.mjs');
93
+ const saved={HOME:process.env.HOME,CM_NOTIFY_OFF:process.env.CM_NOTIFY_OFF};
94
+ t.after(()=>{for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}});
95
+ const NOTIFY=new URL('../runtime/js/notify.mjs',import.meta.url).href;
96
+ const child=(env,key)=>JSON.parse(spawnSync(process.execPath,['--input-type=module','-e',
97
+ `import {notify} from ${JSON.stringify(NOTIFY)};console.log(JSON.stringify(notify({key:${JSON.stringify(key)},event:'stuck',workflow:'cm-ai'})));`],
98
+ {env,encoding:'utf8',timeout:15000}).stdout);
99
+ process.env.HOME=userHome;
100
+ for(const [name,build] of [['clean',cleanEnvironment],['claude',claudeEnvironment]]){
101
+ process.env.CM_NOTIFY_OFF='1';
102
+ assert.equal(build().CM_NOTIFY_OFF,'1',name);
103
+ assert.deepEqual(child(build(),`silenced-${name}`),{sent:false,reason:'off'},name);
104
+ // Control: the same child without the switch does reach the user's config.
105
+ delete process.env.CM_NOTIFY_OFF;
106
+ assert.equal('CM_NOTIFY_OFF' in build(),false,name);
107
+ assert.deepEqual(child(build(),`control-${name}`),{sent:true,reason:'launched'},name);
108
+ }
109
+ assert(await h.until(()=>h.rows().length===2),'only the two control children pushed');
110
+ });
41
111
  test('invalid config turns the feature off: relative command, bad version, bad waitMinutes',t=>{
42
112
  const h=home(t);const file=path.join(h.dir,'notify.json');
43
113
  for(const value of [{version:1,command:['notify.sh']},{version:2,command:['/bin/true']},{version:1,command:[]},
@@ -47,7 +117,7 @@ test('invalid config turns the feature off: relative command, bad version, bad w
47
117
  }
48
118
  assert.match(h.log(),/config - key=- off invalid_config command_not_absolute/);
49
119
  fs.writeFileSync(file,JSON.stringify({version:1,command:['/bin/true'],waitMinutes:0.5}));
50
- assert.deepEqual(readNotifyConfig(h.env),{command:['/bin/true'],waitMs:30000,checkWaitMs:2700000,idleMs:2700000});
120
+ assert.deepEqual(readNotifyConfig(h.env),{command:['/bin/true'],waitMs:30000,checkWaitMs:2700000,idleMs:2700000,followUpMs:7200000,windowMs:600000,perWindow:3});
51
121
  });
52
122
 
53
123
  // The runtime reads notify.json through the same safe boundary as /cm:notify:
@@ -56,7 +126,7 @@ test('invalid config turns the feature off: relative command, bad version, bad w
56
126
  // Each probe runs in its own process: the log line is once per process, and a
57
127
  // build that blocks on a FIFO fails by timeout instead of hanging the suite.
58
128
  const posix=process.platform!=='win32';
59
- const CONFIG={version:1,command:['/bin/true']},PARSED={command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000};
129
+ const CONFIG={version:1,command:['/bin/true']},PARSED={command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000,followUpMs:7200000,windowMs:600000,perWindow:3};
60
130
  const NOTIFY_URL=new URL('../runtime/js/notify.mjs',import.meta.url).href;
61
131
  function probe(h){
62
132
  const child=spawnSync(process.execPath,['--input-type=module','-e',
@@ -111,8 +181,9 @@ test('runtime read: a missing file stays silent, a directory is a logged off, a
111
181
 
112
182
  test('message is bounded and built only from the structured fields',()=>{
113
183
  const long='x'.repeat(2000);
184
+ // A nextAction over 80 characters is replaced by the plain action; a short one keeps its redacted paths.
114
185
  const message=buildNotifyMessage({...fields('k'),workflow:long,project:'/very/secret/path/'+long,runId:long,task:long,
115
- stage:long,code:long,nextAction:`读 /srv/private/push.env 和 ~/secret/file 后\n${long}`,
186
+ stage:long,code:long,nextAction:`读 /srv/private/push.env 和 ~/secret/file 后`,
116
187
  diff:'DIFF-CONTENT',log:'LOG-CONTENT',env:{TOKEN:'SECRET'}},{now:NOW});
117
188
  assert(Array.from(message.title).length<=NOTIFY_LIMITS.titleChars);
118
189
  assert(Array.from(message.body).length<=NOTIFY_LIMITS.bodyChars);
@@ -120,19 +191,28 @@ test('message is bounded and built only from the structured fields',()=>{
120
191
  assert(!message.body.includes(forbidden)&&!message.title.includes(forbidden),forbidden);
121
192
  assert.match(message.body,/<路径>/);
122
193
  const short=buildNotifyMessage(fields('k'),{now:NOW,timeZone:'Asia/Shanghai'});
123
- assert.equal(short.title,'CM cm-fix 需要人处理 · demo-app');
124
- assert.equal(short.body,'下一步:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
194
+ assert.equal(short.title,'CM 需要人处理 · work/demo-app');
195
+ assert.equal(short.subtitle,'cm-fix · T-001');
196
+ assert.equal(buildNotifyMessage(fields('k',{project:'/srv/work/cm-workflow/cm-workflow'}),{now:NOW,timeZone:'Asia/Shanghai'}).title,'CM 需要人处理 · cm-workflow');
197
+ assert.equal(short.body,'下一步:核对 reason 后恢复原运行\n卡在:检查没通过(checks_not_passed)\n时间:16:00');
198
+ const named=buildNotifyMessage(fields('k',{feature:'12.app-version-footer',session:'4f9fa27f',code:'qa_decision_required'}),{now:NOW,timeZone:'Asia/Shanghai'});
199
+ assert.equal(named.subtitle,'cm-fix · 12.app-version-footer T-001 · 会话 4f9fa27f');
200
+ assert.equal(named.body,'下一步:核对 reason 后恢复原运行\n卡在:在等 QA 判定(qa_decision_required)\n时间:16:00');
201
+ assert.equal(buildNotifyMessage(fields('k'),{now:NOW,timeZone:'Asia/Shanghai',followUp:true,suppressed:2}).body,
202
+ '第 2 次提醒:上次提醒后仍未处理\n下一步:核对 reason 后恢复原运行\n卡在:检查没通过(checks_not_passed)\n时间:16:00\n另有 2 条提醒为避免刷屏已合并,请一并查看各会话');
125
203
  assert.doesNotMatch(short.body,/运行:|run-1|CM 不会自动继续/);
126
204
  });
127
205
 
128
- test('done shows only project, task and local time; empty fields are left out',()=>{
206
+ test('done shows the next step and local time; project in the title, task in the subtitle; empty fields are left out',()=>{
129
207
  const done=buildNotifyMessage(fields('k',{event:'done',stage:'run_done',code:'run_done',nextAction:'建议在新会话里开始下一个任务'}),
130
208
  {now:NOW,timeZone:'Asia/Shanghai'});
131
- assert.equal(done.title,'CM cm-fix 流程已结束 · demo-app');
132
- assert.equal(done.body,'项目:demo-app\n任务:T-001\n时间:16:00');
133
- assert.equal(buildNotifyMessage(fields('k',{event:'done',task:null}),{now:NOW,timeZone:'UTC'}).body,'项目:demo-app\n时间:08:00');
134
- assert.equal(buildNotifyMessage({workflow:'cm-ai',event:'waiting'},{now:NOW,timeZone:'America/New_York'}).body,'流程:cm-ai\n时间:04:00');
135
- assert.equal(buildNotifyMessage({workflow:'cm-ai'},{now:Date.parse('2026-10-08T16:05:00.000Z'),timeZone:'Asia/Shanghai'}).body,'流程:cm-ai\n时间:00:05');
209
+ assert.equal(done.title,'CM 流程已结束 · work/demo-app');assert.equal(done.subtitle,'cm-fix · T-001');
210
+ assert.equal(done.body,'下一步:建议在新会话里开始下一个任务\n时间:16:00');
211
+ const bare=buildNotifyMessage(fields('k',{event:'done',task:null,nextAction:null}),{now:NOW,timeZone:'UTC'});
212
+ assert.equal(bare.body,'时间:08:00');assert.equal(bare.subtitle,'cm-fix');
213
+ // Host waiting/idle texts are not rewritten; a driver stop without nextAction gets the plain action line.
214
+ assert.equal(buildNotifyMessage({workflow:'cm-ai',event:'waiting'},{now:NOW,timeZone:'America/New_York'}).body,'时间:04:00');
215
+ assert.equal(buildNotifyMessage({workflow:'cm-ai'},{now:Date.parse('2026-10-08T16:05:00.000Z'),timeZone:'Asia/Shanghai'}).body.split('\n').at(-1),'时间:00:05');
136
216
  });
137
217
 
138
218
  test('without an injected time zone the clock follows the process TZ',()=>{
@@ -140,7 +220,7 @@ test('without an injected time zone the clock follows the process TZ',()=>{
140
220
  process.stdout.write(buildNotifyMessage({workflow:'cm-ai',event:'done',project:'/p/demo'},{now:${NOW}}).body);`;
141
221
  for(const [tz,clock] of [['Asia/Shanghai','16:00'],['UTC','08:00'],['America/Los_Angeles','01:00']]){
142
222
  const run=spawnSync(process.execPath,['--input-type=module','-e',script],{encoding:'utf8',env:{...process.env,TZ:tz}});
143
- assert.equal(run.status,0,run.stderr);assert.equal(run.stdout,`项目:demo\n时间:${clock}`);
223
+ assert.equal(run.status,0,run.stderr);assert.equal(run.stdout,`时间:${clock}`);
144
224
  }
145
225
  });
146
226
 
@@ -152,14 +232,15 @@ test('custom text: without `text` (or with an empty one) every event is byte-ide
152
232
  const at={now:NOW,timeZone:'Asia/Shanghai'};
153
233
  for(const [event,headline] of EVENTS){
154
234
  const base=buildNotifyMessage(fields('k',{event}),at);
155
- assert.equal(base.title,`CM cm-fix ${headline} · demo-app`,String(event));
156
- assert.equal(base.body,event==='done'?'项目:demo-app\n任务:T-001\n时间:16:00'
157
- :'下一步:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
235
+ assert.equal(base.title,`CM ${headline} · work/demo-app`,String(event));
236
+ assert.equal(base.body,event==='done'?'下一步:核对 reason 后恢复原运行\n时间:16:00'
237
+ :'下一步:核对 reason 后恢复原运行\n卡在:检查没通过(checks_not_passed)\n时间:16:00');
158
238
  for(const text of [{},DEFAULT_NOTIFY_TEXT,null,normalizeNotifyText({}).text])
159
239
  assert.deepEqual(buildNotifyMessage(fields('k',{event}),{...at,text}),base,`${event} ${JSON.stringify(text)}`);
160
240
  }
161
241
  const plainConfig=parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true']}));
162
- assert.deepEqual(plainConfig,{config:{command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000}});
242
+ assert.deepEqual(plainConfig,{config:{command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000,
243
+ followUpMs:7200000,windowMs:600000,perWindow:3}});
163
244
  assert.equal(Object.hasOwn(plainConfig.config,'text'),false);
164
245
  });
165
246
 
@@ -173,15 +254,15 @@ test('custom text: prefix, headlines, field order (runId included) and labels',(
173
254
  const want={done:'完工',waiting:'等你回话',idle:'没动静',idle_waiting:'该你了',dead:'宿主没了',stuck:'卡住了'};
174
255
  for(const [event,headline] of Object.entries(want)){
175
256
  const message=buildNotifyMessage(fields('k',{event}),{...at,text:custom});
176
- assert.equal(message.title,`【工作流】 cm-fix ${headline} · demo-app`);
177
- assert.equal(message.body,event==='done'?'时刻:16:00\n工单:T-001':'代码:checks_not_passed\n编号:run-1\n时刻:16:00');
257
+ assert.equal(message.title,`【工作流】 ${headline} · work/demo-app`);
258
+ assert.equal(message.body,event==='done'?'时刻:16:00\n工单:T-001':'代码:检查没通过(checks_not_passed)\n编号:run-1\n时刻:16:00');
178
259
  }
179
260
  // Partial text: only what is given changes; an empty prefix drops it from the title.
180
261
  const partial=buildNotifyMessage(fields('k'),{...at,text:{titlePrefix:'',labels:{nextAction:'先做'}}});
181
- assert.equal(partial.title,'cm-fix 需要人处理 · demo-app');
182
- assert.equal(partial.body,'先做:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
183
- assert.equal(buildNotifyMessage(fields('k',{event:'waiting'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM cm-fix 等 · demo-app');
184
- assert.equal(buildNotifyMessage(fields('k',{event:'idle'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM cm-fix 疑似空转 · demo-app');
262
+ assert.equal(partial.title,'需要人处理 · work/demo-app');
263
+ assert.equal(partial.body,'先做:核对 reason 后恢复原运行\n卡在:检查没通过(checks_not_passed)\n时间:16:00');
264
+ assert.equal(buildNotifyMessage(fields('k',{event:'waiting'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM 等 · work/demo-app');
265
+ assert.equal(buildNotifyMessage(fields('k',{event:'idle'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM 疑似空转 · work/demo-app');
185
266
  // Empty field values are still left out under a custom order.
186
267
  assert.equal(buildNotifyMessage({workflow:'cm-ai'},{...at,text:{fields:{default:['runId','workflow','time']}}}).body,'流程:cm-ai\n时间:16:00');
187
268
  });
@@ -193,10 +274,10 @@ test('custom text strings are cleaned like field values: paths redacted, control
193
274
  const message=buildNotifyMessage(fields('k'),{...at,text});
194
275
  for(const forbidden of ['/Users','example\\','secret','/srv/','push.env','~/proj','\\\\srv','\u0007','\u001b','\u0000','\n见'])
195
276
  assert(!message.title.includes(forbidden)&&!message.body.split('\n').map(line=>line.split(':')[0]).join('|').includes(forbidden),JSON.stringify(forbidden));
196
- assert.equal(message.title,'CM <路径> cm-fix 卡住 见<路径> [31m · demo-app');
277
+ assert.equal(message.title,'CM <路径> 卡住 见<路径> [31m · work/demo-app');
197
278
  assert.equal(message.body.split('\n')[0],'<路径> 下一步:核对 reason 后恢复原运行');
198
- assert.match(message.body,/\n<路径>:demo-app\n/);
199
- assert.match(message.body,/\n<路径>:checks_not_passed\n/);
279
+ assert.equal(text.labels.project,'<路径>');
280
+ assert.match(message.body,/\n<路径>:检查没通过(checks_not_passed)\n/);
200
281
  // Caps: prefix 16, headline 24, label 12 characters (… included); title 60, body 500.
201
282
  const long=normalizeNotifyText({titlePrefix:'前'.repeat(40),headlines:{default:'标'.repeat(40)},labels:{nextAction:'签'.repeat(40)}}).text;
202
283
  assert.equal(long.titlePrefix,'前'.repeat(15)+'…');assert.equal(long.headlines.default,'标'.repeat(23)+'…');
@@ -206,7 +287,8 @@ test('custom text strings are cleaned like field values: paths redacted, control
206
287
  {...at,text:{...long,fields:{default:['nextAction','runId','project','workflow','task','stage','code','time']}}});
207
288
  assert.equal(Array.from(big.title).length,NOTIFY_LIMITS.titleChars);
208
289
  assert(Array.from(big.body).length<=NOTIFY_LIMITS.bodyChars);
209
- assert.match(big.body,/^签{11}…:x{199}…\n/);
290
+ // A long nextAction is replaced by the plain action (see noticeAction); the label keeps its cap.
291
+ assert.match(big.body,/^签{11}…:回到对应会话,让它说明停在哪、需要你做什么\n/);
210
292
  assert.match(big.body,/\n运行:x{63}…\n/);
211
293
  });
212
294
 
@@ -218,8 +300,8 @@ test('custom text loses bidi and zero-width characters; a string left with nothi
218
300
  labels:{code:'‮原因',task:'​工‍单'}}).text;
219
301
  const message=buildNotifyMessage(fields('k'),{...at,text});
220
302
  for(const char of hidden)assert(!message.title.includes(char)&&!message.body.includes(char),`U+${char.codePointAt(0).toString(16)}`);
221
- assert.equal(message.title,'CM cm-fix 卡住了 · demo-app');
222
- assert.match(message.body,/\n工单:T-001\n/);assert.match(message.body,/\n原因:checks_not_passed\n/);
303
+ assert.equal(message.title,'CM 卡住了 · work/demo-app');
304
+ assert.equal(text.labels.task,'工单');assert.match(message.body,/\n原因:检查没通过(checks_not_passed)\n/);
223
305
  // Nothing visible left: the whole text is invalid and the default text is used.
224
306
  for(const [value,reason] of [[{headlines:{default:'​⁦⁩'}},'headlines'],[{labels:{code:'‮ ‏'}},'labels'],
225
307
  [{titlePrefix:'​'},'title_prefix'],[{titlePrefix:' '},'title_prefix'],[{headlines:{done:'̀'}},'headlines']]){
@@ -228,7 +310,7 @@ test('custom text loses bidi and zero-width characters; a string left with nothi
228
310
  assert.deepEqual(buildNotifyMessage(fields('k'),{...at,text:value}),buildNotifyMessage(fields('k'),at));
229
311
  }
230
312
  // Field values are not part of the text layer: the default path is unchanged.
231
- assert.equal(buildNotifyMessage(fields('k',{task:'T​-1'}),at).body.split('\n')[3],'任务:T​-1');
313
+ assert.equal(buildNotifyMessage(fields('k',{task:'T​-1'}),at).subtitle,'cm-fix · T​-1');
232
314
  });
233
315
 
234
316
  test('custom text redacts absolute paths even when letters touch them; field values keep the shared rule',()=>{
@@ -240,12 +322,12 @@ test('custom text redacts absolute paths even when letters touch them; field val
240
322
  const text=normalizeNotifyText({headlines:{default:raw},labels:{code:raw}}).text;
241
323
  assert.equal(text.headlines.default,want,raw);assert.equal(text.labels.code,want.slice(0,12),raw);
242
324
  const message=buildNotifyMessage(fields('k'),{...at,text});
243
- assert.equal(message.title,`CM cm-fix ${want} · demo-app`,raw);
325
+ assert.equal(message.title,`CM ${want} · work/demo-app`,raw);
244
326
  for(const leak of ['/Users','Users\\','\\\\srv','/srv','~/proj','/etc','/tmp'])assert(!message.title.includes(leak)&&!message.body.includes(leak),`${raw} ${leak}`);
245
327
  }
246
328
  // The shared rule for field values (and so the default text) is unchanged.
247
- assert.equal(buildNotifyMessage(fields('k',{task:'see/Users/example/key'}),at).body.split('\n')[3],'任务:see/Users/example/key');
248
- assert.equal(buildNotifyMessage(fields('k',{task:'见 /Users/example/key'}),at).body.split('\n')[3],'任务:见 <路径>');
329
+ assert.equal(buildNotifyMessage(fields('k',{task:'see/Users/example/key'}),at).subtitle,'cm-fix · see/Users/example/key');
330
+ assert.equal(buildNotifyMessage(fields('k',{task:'见 /Users/example/key'}),at).subtitle,'cm-fix · 见 <路径>');
249
331
  });
250
332
 
251
333
  test('invalid text falls back to the default text with one text_config log line; notices stay on',async t=>{
@@ -266,8 +348,8 @@ test('invalid text falls back to the default text with one text_config log line;
266
348
  assert.equal(readNotifyConfig(h.env).text,undefined);
267
349
  assert.deepEqual(notify(fields('typo'),{env:h.env,now:NOW}),{sent:true,reason:'launched'});
268
350
  assert(await h.until(()=>h.rows().length===1));
269
- assert.equal(h.rows()[0].title,'CM cm-fix 需要人处理 · demo-app');
270
- assert.match(h.rows()[0].body,/^下一步:核对 reason 后恢复原运行\n项目:demo-app\n/);
351
+ assert.equal(h.rows()[0].title,'CM 需要人处理 · work/demo-app');
352
+ assert.match(h.rows()[0].body,/^下一步:核对 reason 后恢复原运行\n卡在:检查没通过(checks_not_passed)\n/);
271
353
  readNotifyConfig(h.env);
272
354
  const lines=h.log().split('\n').filter(line=>line.includes('text_config'));
273
355
  assert.equal(lines.length,1,h.log());assert.match(lines[0],/ config - key=- default_text text_config fields$/);
@@ -279,7 +361,7 @@ test('custom text reaches the command in CM_NOTIFY_TITLE/BODY and the stdin JSON
279
361
  assert.equal(notify(fields('custom'),{env:h.env,now:NOW}).sent,true);
280
362
  assert(await h.until(()=>h.rows().length===1));
281
363
  const [row]=h.rows();
282
- assert.equal(row.title,'提醒 cm-fix 卡住了 · demo-app');assert.equal(row.body,'工单:T-001\n原因:checks_not_passed');
364
+ assert.equal(row.title,'提醒 卡住了 · work/demo-app');assert.equal(row.body,'工单:T-001\n卡在:检查没通过(checks_not_passed)');
283
365
  assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);assert.equal(row.stdin.runId,'run-1');
284
366
  });
285
367
 
@@ -289,8 +371,8 @@ test('sends through env and stdin once per key; the same key within 6 hours is s
289
371
  assert.deepEqual(notify(fields('same'),{env:h.env,now:NOW+5*3600*1000}),{sent:false,reason:'duplicate'});
290
372
  assert(await h.until(()=>h.rows().length===1));
291
373
  const [row]=h.rows();
292
- assert.equal(row.title,'CM cm-fix 需要人处理 · demo-app');assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);
293
- assert.equal(row.stdin.project,'demo-app');assert.equal(row.stdin.code,'checks_not_passed');assert.equal(row.stdin.key,undefined);
374
+ assert.equal(row.title,'CM 需要人处理 · work/demo-app');assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);
375
+ assert.equal(row.stdin.subtitle,'cm-fix · T-001');assert.equal(row.stdin.project,'work/demo-app');assert.equal(row.stdin.code,'checks_not_passed');assert.equal(row.stdin.key,undefined);
294
376
  assert.equal(notify(fields('same'),{env:h.env,now:NOW+6*3600*1000+1}).sent,true);
295
377
  assert(await h.until(()=>h.rows().length===2));
296
378
  assert.equal(h.rows()[0].stdin.CM_NOTIFY_PAYLOAD,undefined);
@@ -299,17 +381,192 @@ test('sends through env and stdin once per key; the same key within 6 hours is s
299
381
  assert(!fs.existsSync(path.join(h.dir,'notify-state.lock')));
300
382
  });
301
383
 
302
- test('at most 4 per rolling minute and 150 per day across keys',async t=>{
384
+ test('a busy state lock delays the progress clear instead of dropping it; a clear that never gets the lock is logged',async t=>{
385
+ const h=home(t),key='attn|work/demo-app|4f9fa27f',lock=path.join(h.dir,'notify-state.lock');
386
+ assert.equal(notify(fields('b1',{attentionKey:key}),{env:h.env,now:NOW}).sent,true);
387
+ // A lock held by another live process (the parent) is not stale.
388
+ const hold=()=>fs.writeFileSync(lock,JSON.stringify({pid:process.ppid,at:Date.now(),token:'held'}));
389
+ hold();setTimeout(()=>fs.unlinkSync(lock),60);
390
+ assert.equal(await clearAttention(key,{env:h.env,before:NOW+1,attempts:20,delayMs:20}),true);
391
+ assert.equal(notify(fields('b2',{attentionKey:key}),{env:h.env,now:NOW+60000}).sent,true,'the next stop is sent at once');
392
+ hold();
393
+ assert.equal(await clearAttention(key,{env:h.env,before:NOW+60001,attempts:3,delayMs:5}),false);
394
+ assert.match(h.log(),/ clear - key=[0-9a-f]{16} failed state_busy\n/);
395
+ fs.unlinkSync(lock);
396
+ });
397
+
398
+ test('the session is kept whole in the subtitle; a long feature name is shortened instead',()=>{
399
+ const message=buildNotifyMessage(fields('k',{feature:'12.'+'f'.repeat(45),session:'4f9fa27f'}),{now:NOW,timeZone:'UTC'});
400
+ assert(Array.from(message.subtitle).length<=NOTIFY_LIMITS.titleChars,message.subtitle);
401
+ // ' · 会话 4f9fa27f' takes 14 of 60 characters; the rest is cut to 46 (45 + …).
402
+ assert.equal(message.subtitle,'cm-fix · 12.'+'f'.repeat(33)+'… · 会话 4f9fa27f');
403
+ });
404
+
405
+ test('a host still waiting sends one follow-up after followUpMinutes; answering first cancels it',async t=>{
406
+ const h=home(t,{config:{waitMinutes:0.001,frequency:{followUpMinutes:1}}});
407
+ t.mock.timers.enable({apis:['setTimeout','Date'],now:NOW});
408
+ const wait=()=>scheduleWaitNotice({kind:'qa_browser',callId:'c1',workflow:'cm-demo',project:'/work/demo-app',session:'4f9fa27f',env:h.env});
409
+ let cancel=wait();
410
+ t.mock.timers.tick(100);
411
+ t.mock.timers.tick(60000);
412
+ cancel();
413
+ t.mock.timers.reset();
414
+ assert(await h.until(()=>h.rows().length===2));
415
+ assert.equal(h.rows().filter(row=>/^第 2 次提醒:/.test(row.body)).length,1);
416
+ // Answered before the follow-up: the second timer is cancelled with the first.
417
+ const other=home(t,{config:{waitMinutes:0.001,frequency:{followUpMinutes:1}}});
418
+ t.mock.timers.enable({apis:['setTimeout','Date'],now:NOW});
419
+ cancel=scheduleWaitNotice({kind:'qa_browser',callId:'c2',workflow:'cm-demo',project:'/work/demo-app',session:'aaaa0000',env:other.env});
420
+ t.mock.timers.tick(100);cancel();t.mock.timers.tick(120000);
421
+ t.mock.timers.reset();
422
+ assert(await other.until(()=>other.rows().length===1));
423
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(other.rows().length,1);
424
+ });
425
+
426
+ test('two hosts without a session id waiting in one project are two notices: the launch arguments keep them apart',async t=>{
427
+ const h=home(t,{config:{waitMinutes:0.001}});
428
+ t.mock.timers.enable({apis:['setTimeout','Date'],now:NOW});
429
+ for(const name of ['prd-a','prd-b'])
430
+ scheduleWaitNotice({kind:'answer',callId:'c1',workflow:'cm-prd',project:'/work/demo-app',args:['serve','--session',name],env:h.env});
431
+ t.mock.timers.tick(100);t.mock.timers.reset();
432
+ assert(await h.until(()=>h.rows().length===2));
433
+ assert.equal(Object.keys(JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8')).attention).length,2);
434
+ });
435
+
436
+ test('compact layout: title is the project, subtitle the session title, body only why it stopped',()=>{
437
+ const at={now:NOW,timeZone:'UTC',layout:'compact'};
438
+ const stuck=fields('k',{code:'qa_decision_required',session:'4f9fa27f',sessionTitle:'分析 skills 库'});
439
+ assert.deepEqual(buildNotifyMessage(stuck,at),{title:'work/demo-app',subtitle:'会话:分析 skills 库',
440
+ body:'在等 QA 判定\n你要做:回到会话「分析 skills 库」说「继续」,让它做 QA 判定'});
441
+ // No plain-words entry: the event headline, never the English code. No title: the short session id; neither: the workflow.
442
+ assert.deepEqual(buildNotifyMessage(fields('k',{session:'4f9fa27f',code:'batch_resources_open'}),{...at,text:{headlines:{default:'要你出手'}}}),
443
+ {title:'work/demo-app',subtitle:'会话:4f9fa27f',body:'要你出手\n你要做:回到会话「4f9fa27f」,让它说明停在哪、需要你做什么'});
444
+ assert.equal(buildNotifyMessage(fields('k'),at).subtitle,'cm-fix');
445
+ assert.equal(buildNotifyMessage(fields('k',{event:'done',code:'qa_decision_required'}),at).body,'流程已结束');
446
+ // Codes without an entry still read as Chinese from their words; only a code saying nothing falls back to the headline.
447
+ for(const [code,want] of [['checks_not_passed','检查没通过'],['qa_failed','QA 没通过'],['develop_checks_not_passed','开发检查没通过'],
448
+ ['review_verification_failed','审查失败'],['qa_fix_action_authorization_required','QA 修复要你授权'],['batch_resources_open','需要人处理'],
449
+ ['spec_drift','规格有改动,需重新批准'],['call_timeout','超时']])
450
+ assert.equal(buildNotifyMessage(fields('k',{code}),at).body.split('\n')[0],want,code);
451
+ assert.equal(buildNotifyMessage(fields('k',{code:'review_verification_failed'}),{now:NOW,timeZone:'UTC'}).body.split('\n')[1],'卡在:审查失败(review_verification_failed)');
452
+ assert.equal(buildNotifyMessage(stuck,{...at,followUp:true,suppressed:2}).body,
453
+ '第 2 次:在等 QA 判定\n你要做:回到会话「分析 skills 库」说「继续」,让它做 QA 判定\n另有 2 条提醒已合并');
454
+ assert.deepEqual(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],layout:'compact'})).config.layout,'compact');
455
+ assert.equal(Object.hasOwn(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],layout:'full'})).config,'layout'),false);
456
+ assert.equal(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],layout:'tiny'})).reason,'layout');
457
+ });
458
+
459
+ test('session title: last custom-title (else ai-title) from the tail of the session transcript; nothing read without a session or under tests',t=>{
460
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-title-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
461
+ const id='2e015f08-c743-427a-95fa-0e471a851593',dir=path.join(root,'-Users-x-proj');fs.mkdirSync(dir);
462
+ const file=path.join(dir,`${id}.jsonl`),line=value=>JSON.stringify(value)+'\n';
463
+ const env={CLAUDE_CODE_SESSION_ID:id,CM_NOTIFY_CLAUDE_PROJECTS:root,NODE_TEST_CONTEXT:'child-v8'};
464
+ fs.writeFileSync(file,line({type:'ai-title',aiTitle:'自动标题'})+line({type:'user',message:'x'}));
465
+ assert.equal(sessionTitle(env),'自动标题');
466
+ fs.appendFileSync(file,line({type:'custom-title',customTitle:'分析 skills 库'})+line({type:'ai-title',aiTitle:'更晚的自动标题'}));
467
+ assert.equal(sessionTitle(env),'分析 skills 库','a title the person set wins');
468
+ fs.appendFileSync(file,line({type:'custom-title',customTitle:'改名后 /srv/x/secret'}));
469
+ assert.equal(sessionTitle(env),'改名后 <路径>');
470
+ // Only the last 1 MiB is read: a title further back is not found.
471
+ fs.writeFileSync(file,line({type:'custom-title',customTitle:'很早的标题'})+'x'.repeat(1024*1024+10)+'\n');
472
+ assert.equal(sessionTitle(env),null);
473
+ // A symlinked transcript is never followed.
474
+ fs.writeFileSync(path.join(root,'real.jsonl'),line({type:'custom-title',customTitle:'别读我'}));
475
+ fs.rmSync(file);fs.symlinkSync(path.join(root,'real.jsonl'),file);
476
+ assert.equal(sessionTitle(env),null);
477
+ // A project directory that is a symlink is not followed, even to a valid transcript.
478
+ fs.rmSync(file);const outside=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-outside-')));
479
+ t.after(()=>fs.rmSync(outside,{recursive:true,force:true}));
480
+ fs.writeFileSync(path.join(outside,`${id}.jsonl`),line({type:'custom-title',customTitle:'链接外的标题'}));
481
+ fs.rmSync(dir,{recursive:true});fs.symlinkSync(outside,dir);
482
+ assert.equal(sessionTitle(env),null);
483
+ for(const bad of [{...env,CLAUDE_CODE_SESSION_ID:undefined},{...env,CLAUDE_CODE_SESSION_ID:'../x'},{...env,CM_NOTIFY_CLAUDE_PROJECTS:undefined}])
484
+ assert.equal(sessionTitle(bad),null,JSON.stringify(bad));
485
+ });
486
+
487
+ test('session title: a project directory swapped for a link while the transcript is opened is not read',t=>{
488
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-race-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
489
+ const outside=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-race-out-')));t.after(()=>fs.rmSync(outside,{recursive:true,force:true}));
490
+ const id='2e015f08-c743-427a-95fa-0e471a851593',dir=path.join(root,'p'),moved=path.join(root,'.moved');
491
+ const env={CLAUDE_CODE_SESSION_ID:id,CM_NOTIFY_CLAUDE_PROJECTS:root,NODE_TEST_CONTEXT:'child-v8'};
492
+ const title=value=>JSON.stringify({type:'custom-title',customTitle:value})+'\n';
493
+ fs.writeFileSync(path.join(outside,`${id}.jsonl`),title('外部目录标题'));
494
+ const lstat=fs.lstatSync,open=fs.openSync;t.after(()=>{fs.lstatSync=lstat;fs.openSync=open;});
495
+ const target=path.join(dir,`${id}.jsonl`);
496
+ for(const restore of [false,true]){
497
+ fs.rmSync(dir,{recursive:true,force:true});fs.rmSync(moved,{recursive:true,force:true});
498
+ fs.mkdirSync(dir);fs.writeFileSync(target,title('本会话标题'));
499
+ assert.equal(sessionTitle(env),'本会话标题');
500
+ // The directory checks out, then is swapped for a link to the outside just
501
+ // before the transcript is looked at, so the file check and the open both
502
+ // see the outside file; optionally it is put back right after the open.
503
+ let swapped=false;
504
+ fs.lstatSync=(file,...rest)=>{
505
+ if(!swapped&&String(file)===target){swapped=true;fs.renameSync(dir,moved);fs.symlinkSync(outside,dir);}
506
+ return lstat(file,...rest);
507
+ };
508
+ fs.openSync=(file,...rest)=>{
509
+ const fd=open(file,...rest);
510
+ if(restore&&String(file)===target&&swapped&&fs.existsSync(moved)){fs.unlinkSync(dir);fs.renameSync(moved,dir);}
511
+ return fd;
512
+ };
513
+ assert.equal(sessionTitle(env),null,restore?'swapped and restored':'left as a link');
514
+ fs.lstatSync=lstat;fs.openSync=open;
515
+ }
516
+ });
517
+
518
+ test('at most 3 per 10 minutes and 150 per day across keys; skipped notices are counted into the next one',async t=>{
303
519
  const h=home(t);
304
- for(let i=0;i<4;i++)assert.equal(notify(fields(`m${i}`),{env:h.env,now:NOW+i}).sent,true);
305
- assert.deepEqual(notify(fields('m4'),{env:h.env,now:NOW+10}),{sent:false,reason:'rate_minute'});
306
- assert.equal(notify(fields('m4'),{env:h.env,now:NOW+60010}).sent,true);
307
- assert.match(h.log(),/skipped rate_minute/);
520
+ for(let i=0;i<3;i++)assert.equal(notify(fields(`m${i}`),{env:h.env,now:NOW+i}).sent,true);
521
+ assert.deepEqual(notify(fields('m3'),{env:h.env,now:NOW+10}),{sent:false,reason:'rate_window'});
522
+ assert.deepEqual(notify(fields('m4'),{env:h.env,now:NOW+9*60000}),{sent:false,reason:'rate_window'});
523
+ assert.match(h.log(),/skipped rate_window/);
524
+ assert.equal(notify(fields('m5'),{env:h.env,now:NOW+10*60000+1}).sent,true);
525
+ assert(await h.until(()=>h.rows().length===4));
526
+ // Rows arrive in completion order of the background senders: look them up by content, not position.
527
+ const merged=h.rows().filter(row=>/另有/.test(row.body));
528
+ assert.equal(merged.length,1);assert.match(merged[0].body,/\n另有 2 条提醒为避免刷屏已合并,请一并查看各会话$/);
529
+ // A version 1 state file is still read; the per-day cap is unchanged.
308
530
  const sends=Array.from({length:150},(_,i)=>NOW+120000+i*60000);
309
531
  fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:1,keys:{},sends}));
310
532
  assert.deepEqual(notify(fields('day'),{env:h.env,now:NOW+200*60000}),{sent:false,reason:'rate_day'});
311
533
  assert.equal(notify(fields('day'),{env:h.env,now:NOW+120000+24*3600*1000}).sent,true);
312
- assert(await h.until(()=>h.rows().length===6));
534
+ assert(await h.until(()=>h.rows().length===5));
535
+ assert.equal(h.rows().filter(row=>/\n另有 1 条提醒/.test(row.body)).length,1);
536
+ // The window and the follow-up delay come from notify.json `frequency`.
537
+ assert.deepEqual(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],frequency:{followUpMinutes:30,windowMinutes:5,perWindow:2}})).config,
538
+ {command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000,followUpMs:1800000,windowMs:300000,perWindow:2});
539
+ for(const frequency of [{perWindow:0},{perWindow:1.5},{windowMinutes:0},{windowMinutes:0.5},{followUpMinutes:0.1},{followUpMinutes:2000},{other:1},[]])
540
+ assert.equal(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],frequency})).reason,'frequency',JSON.stringify(frequency));
541
+ });
542
+
543
+ test('one session needs one notice: stuck, waiting and idle share it; a new state or one follow-up after 2 hours resends',async t=>{
544
+ const h=home(t),attentionKey='attn|work/demo-app|4f9fa27f',at=over=>fields(over.key,{attentionKey,session:'4f9fa27f',...over});
545
+ assert.equal(notify(at({key:'s1'}),{env:h.env,now:NOW}).sent,true);
546
+ // Same session, same stuck reason, or a lower/equal level: not sent again.
547
+ assert.deepEqual(notify(at({key:'s2'}),{env:h.env,now:NOW+60000}),{sent:false,reason:'duplicate'});
548
+ assert.deepEqual(notify(at({key:'w1',event:'waiting',code:'waiting_session_answer'}),{env:h.env,now:NOW+120000}),{sent:false,reason:'duplicate'});
549
+ assert.deepEqual(notify(at({key:'i1',event:'idle_waiting',code:'waiting_for_you'}),{env:h.env,now:NOW+180000}),{sent:false,reason:'duplicate'});
550
+ // A different stuck reason is a new state.
551
+ assert.equal(notify(at({key:'s3',code:'qa_decision_required'}),{env:h.env,now:NOW+240000}).sent,true);
552
+ // Still unhandled 2 hours later: one follow-up, then nothing more.
553
+ assert.deepEqual(notify(at({key:'s4',code:'qa_decision_required'}),{env:h.env,now:NOW+240000+7199000}),{sent:false,reason:'duplicate'});
554
+ assert.equal(notify(at({key:'s5',code:'qa_decision_required'}),{env:h.env,now:NOW+240000+7200000}).sent,true);
555
+ assert.deepEqual(notify(at({key:'s6',code:'qa_decision_required'}),{env:h.env,now:NOW+240000+3*7200000}),{sent:false,reason:'duplicate'});
556
+ assert(await h.until(()=>h.rows().length===3));
557
+ assert.equal(h.rows().filter(row=>/^第 2 次提醒:上次提醒后仍未处理\n/.test(row.body)).length,1);
558
+ // An idle notice first, then waiting for the session: the higher level is sent.
559
+ const other='attn|work/demo-app|aaaa0000';
560
+ assert.equal(notify(fields('o1',{attentionKey:other,event:'idle',code:'no_next_step'}),{env:h.env,now:NOW+5*3600000}).sent,true);
561
+ assert.equal(notify(fields('o2',{attentionKey:other,event:'waiting',code:'waiting_session_answer'}),{env:h.env,now:NOW+5*3600000+1}).sent,true);
562
+ // Progress clears the record: the same stop is sent at once again. A record newer than the step stays.
563
+ assert.equal(await clearAttention(attentionKey,{env:h.env,before:NOW+240000+7200000-1}),false,'newer record kept');
564
+ assert.equal(await clearAttention(attentionKey,{env:h.env,before:NOW+240000+7200000}),true);
565
+ assert.equal(notify(at({key:'s7',code:'qa_decision_required'}),{env:h.env,now:NOW+8*3600000}).sent,true);
566
+ assert.equal(await clearAttention('attn|unknown',{env:h.env}),false);
567
+ // done keeps its own once-per-key rule and never takes the attention path.
568
+ assert.equal(notify(at({key:'d1',event:'done'}),{env:h.env,now:NOW+9*3600000}).sent,true);
569
+ assert.deepEqual(notify(at({key:'d1',event:'done'}),{env:h.env,now:NOW+9*3600000+1}),{sent:false,reason:'duplicate'});
313
570
  });
314
571
 
315
572
  test('command failure, timeout and broken state never throw; they log one line without content',async t=>{
@@ -534,42 +791,318 @@ test('driver classification follows each workflow contract (table)',()=>{
534
791
  assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',row:{requestId:'drive',error:{code:'host_request_failed'}}}).event,'stuck');
535
792
  assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',failure:'host_exited'}).code,'host_exited');
536
793
  }
537
- const blocked=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/work/demo-app',args:['serve'],operation:'advance',
538
- row:{requestId:'drive',result:ai({outcome:'advanced',state:'blocked',code:'develop_checks_not_passed',pendingAction:'resume',
794
+ const blocked=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/work/demo-app',args:['serve','--host-context','4F9FA27F-6196-4f1f-9bb7-fe5bcd5614fa'],operation:'advance',
795
+ row:{requestId:'drive',result:ai({outcome:'advanced',state:'blocked',code:'develop_checks_not_passed',pendingAction:'resume',feature:'1.login',
539
796
  guidance:{nextStep:'修复后 advance'}})}});
540
- assert.deepEqual({...blocked},{key:'cm-ai|run-1|T-001|1|blocked|develop_checks_not_passed',event:'stuck',workflow:'cm-ai',
541
- project:'demo-app',runId:'run-1',task:'T-001',stage:'blocked',code:'develop_checks_not_passed',nextAction:'修复后 advance'});
797
+ assert.deepEqual({...blocked},{key:'cm-ai|run-1|T-001|1|blocked|develop_checks_not_passed',attentionKey:'attn|work/demo-app|4f9fa27f',event:'stuck',workflow:'cm-ai',
798
+ project:'/work/demo-app',runId:'run-1',feature:'1.login',task:'T-001',stage:'blocked',session:'4f9fa27f',code:'develop_checks_not_passed',nextAction:'修复后 advance',
799
+ pendingAction:'resume',delivery:'later'});
800
+ // Without --host-context the attention record is per project, workflow and run; a non-UUID context is kept as given.
801
+ assert.equal(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',args:['serve'],operation:'advance',row:{requestId:'drive',result:ai({state:'blocked',code:'x'})}}).attentionKey,'attn|w/p|cm-ai|run-1');
802
+ assert.equal(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',args:['--host-context','claude-session-e2e'],operation:'advance',failure:'host_exited'}).session,'claude-session-e2e');
803
+ // No session and no returned run: the launch arguments keep two runs apart, and progress clears the same key.
804
+ const exited=args=>driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',args,operation:'advance',failure:'host_exited'}).attentionKey;
805
+ assert.notEqual(exited(['--config','/tmp/run-a.json']),exited(['--config','/tmp/run-b.json']));
806
+ assert.equal(driveProgressKey({host:'cm-ai-host.mjs',cwd:'/w/p',args:['--config','/tmp/run-a.json'],operation:'advance',
807
+ row:{requestId:'drive',result:{workflow:'cm-ai',state:'ready'}}}),exited(['--config','/tmp/run-a.json']));
808
+ // done keeps only its own key, not an attention record.
809
+ assert.equal(Object.hasOwn(driveNotice({host:'cm-test-host.mjs',cwd:'/w/p',operation:'start',row:{requestId:'drive',result:{stage:'reported',runId:'t',overall:'PASS'}}}),'attentionKey'),false);
542
810
  const batch=driveNotice({host:'cm-ai-batch-host.mjs',cwd:'/w/p',args:['a'],operation:'advance',
543
811
  row:{requestId:'drive',result:{outcome:'blocked',code:'merge_conflict',batchId:'b1'}}});
544
812
  assert.equal(batch.runId,'b1');assert.equal(batch.code,'merge_conflict');
545
813
  assert.match(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',operation:'advance',failure:'host_exited'}).key,/^cm-ai\|args:[0-9a-f]{16}\|/);
546
814
  });
547
815
 
816
+ // 2026-10-26 user report: a notice must say what to do. The compact layout adds
817
+ // one "你要做" line from a code→action table, naming the session to go back to.
818
+ test('compact layout adds a 你要做 line: mapped actions, rate limit, fallback, custom label, explicit action',()=>{
819
+ const at={now:NOW,timeZone:'UTC',layout:'compact'},s={session:'4f9fa27f',sessionTitle:'分析 skills 库'};
820
+ const line=over=>buildNotifyMessage(fields('k',{...s,...over}),at).body.split('\n')[1];
821
+ assert.equal(line({code:'review_provider_failed'}),'你要做:回到会话「分析 skills 库」说「继续」,让它重派审查');
822
+ assert.equal(line({code:'review_provider_failed',reviewFailure:'reviewer_rate_limited'}),
823
+ '你要做:审查被限流:过一刻钟后回到会话「分析 skills 库」说「继续」,让它重派审查');
824
+ // "继续即可" only while the real exit is still the original run's redispatch.
825
+ assert.equal(line({code:'review_provider_failed',reviewFailure:'reviewer_rate_limited',pendingAction:'resume',rateLimitRetries:2}),
826
+ '你要做:审查被限流,已自动重试 2 次仍失败;过半小时后回到会话「分析 skills 库」说「继续」即可');
827
+ assert.equal(line({code:'review_provider_failed',reviewFailure:'reviewer_rate_limited',pendingAction:'abandon_review',rateLimitRetries:1}),
828
+ '你要做:需要你确认旧审查进程已停后,回到会话「分析 skills 库」授权放弃这次审查再重派');
829
+ assert.equal(line({code:'review_redispatch_limit',reviewFailure:'reviewer_rate_limited',pendingAction:'none',rateLimitRetries:1}),
830
+ '你要做:审查多次没给结论:回到会话「分析 skills 库」,让它查清登录或额度后新建运行重做');
831
+ assert.equal(line({code:'qa_triggered'}),'你要做:回到会话「分析 skills 库」说「继续」,让它执行 QA');
832
+ assert.equal(line({code:'awaiting_spec_approval'}),'你要做:打开规格确认内容,再回到会话「分析 skills 库」说「批准」');
833
+ assert.equal(line({code:'provider_development_authorization_required'}),'你要做:回到会话「分析 skills 库」,看它要你授权什么;同意就说「授权」');
834
+ assert.equal(line({code:'review_limit'}),'你要做:两轮审查都没通过:回到会话「分析 skills 库」,决定改规格还是重开这项任务');
835
+ assert.equal(line({code:'host_exited'}),'你要做:宿主中途停了:回到会话「分析 skills 库」说「继续」,让它查状态后恢复');
836
+ assert.equal(line({code:'batch_resources_open'}),'你要做:回到会话「分析 skills 库」,让它说明停在哪、需要你做什么');
837
+ assert.equal(buildNotifyMessage(fields('k',{session:'4f9fa27f',code:'batch_resources_open'}),at).body.split('\n')[1],
838
+ '你要做:回到会话「4f9fa27f」,让它说明停在哪、需要你做什么');
839
+ assert.equal(buildNotifyMessage(fields('k',{code:'batch_resources_open'}),at).body.split('\n')[1],
840
+ '你要做:回到对应会话,让它说明停在哪、需要你做什么');
841
+ // The label is the user's own nextAction label when text sets one.
842
+ assert.equal(buildNotifyMessage(fields('k',{...s,code:'qa_triggered'}),{...at,text:{labels:{nextAction:'动作'}}}).body.split('\n')[1],
843
+ '动作:回到会话「分析 skills 库」说「继续」,让它执行 QA');
844
+ // An explicit plain action (the driver's rate-limit result) wins; it is cleaned like any field.
845
+ assert.equal(line({code:'review_provider_failed',action:'审查被限流,已自动重试 1 次仍失败;过半小时后回到会话说「继续」即可 /srv/x'}),
846
+ '你要做:审查被限流,已自动重试 1 次仍失败;过半小时后回到会话说「继续」即可 <路径>');
847
+ // done stays as before; the whole body keeps its cap.
848
+ assert.equal(buildNotifyMessage(fields('k',{...s,event:'done'}),at).body,'流程已结束');
849
+ assert(Array.from(buildNotifyMessage(fields('k',{...s,sessionTitle:'长'.repeat(200),code:'x'.repeat(300)}),at).body).length<=NOTIFY_LIMITS.bodyChars);
850
+ });
851
+
852
+ // A provider develop that hit the API rate limit stops at develop_redo, which needs
853
+ // the person's authorization: sent at once, and the action says to authorize the redo.
854
+ test('provider develop rate limit: sent at once with the redo authorization as the action',()=>{
855
+ const notice=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/w/p',args:['--host-context','s1'],operation:'advance',
856
+ row:{requestId:'drive',result:ai({state:'blocked',code:'develop_answer_missing',pendingAction:'develop_redo',developRedoRequired:true,
857
+ failureCode:'developer_rate_limited',developFailure:'developer_rate_limited'})}});
858
+ assert.equal(notice.delivery,'now');assert.equal(notice.developFailure,'developer_rate_limited');
859
+ assert.equal(buildNotifyMessage(notice,{now:NOW,layout:'compact'}).body.split('\n')[1],
860
+ '你要做:开发进程被限流(429):过一刻钟后回到会话「s1」,授权它重做这一轮开发(宿主会先核对旧开发进程已退出)');
861
+ const overloaded=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/w/p',args:['--host-context','s1'],operation:'advance',
862
+ row:{requestId:'drive',result:ai({state:'blocked',code:'develop_answer_missing',pendingAction:'develop_redo',developFailure:'developer_server_error'})}});
863
+ assert.match(buildNotifyMessage(overloaded,{now:NOW,layout:'compact'}).body,/开发服务过载或出错:稍后回到会话「s1」,授权它重做这一轮开发/);
864
+ // Without a class it stays the generic redo authorization.
865
+ assert.match(buildNotifyMessage(fields('k',{session:'s1',code:'develop_answer_missing',pendingAction:'develop_redo'}),{now:NOW,layout:'compact'}).body,
866
+ /需要你确认会话已停止改代码后,回到会话「s1」授权重做开发/);
867
+ });
868
+
869
+ test('full layout keeps a plain nextAction and replaces an empty, long or technical one with the action table',()=>{
870
+ const at={now:NOW,timeZone:'UTC'},s={session:'4f9fa27f'};
871
+ const first=over=>buildNotifyMessage(fields('k',{...s,...over}),at).body.split('\n')[0];
872
+ assert.equal(first({nextAction:'核对 reason 后恢复原运行'}),'下一步:核对 reason 后恢复原运行');
873
+ for(const nextAction of [null,'','恢复原运行并发送 advance;reason 以 reviewer_rate_limited 开头',
874
+ '显式 --allow-abandon-review,并提供单行 reason','长'.repeat(81)])
875
+ assert.equal(first({code:'review_provider_failed',nextAction}),'下一步:回到会话「4f9fa27f」说「继续」,让它重派审查',String(nextAction));
876
+ assert.equal(first({code:'review_provider_failed',nextAction:'x',action:'过半小时后回到会话说「继续」'}),'下一步:x');
877
+ assert.equal(buildNotifyMessage(fields('k',{event:'done',nextAction:null}),at).body,'时间:08:00');
878
+ });
879
+
880
+ // Only stops that need the person's own decision or authorization are sent at
881
+ // once; every other stop waits waitMinutes in case the session moves on.
882
+ test('driver notices: only a person\'s decision or authorization is sent at once; other stops are deferred',()=>{
883
+ const notice=(result,extra={})=>driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/w/p',args:['--host-context','s1'],operation:'advance',
884
+ row:{requestId:'drive',result:ai(result)},...extra});
885
+ for(const [result,delivery] of [
886
+ [{state:'pending_review',code:'review_provider_failed',pendingAction:'resume',reviewFailure:'reviewer_rate_limited'},'later'],
887
+ [{state:'blocked',code:'develop_checks_not_passed',pendingAction:'resume'},'later'],
888
+ [{state:'fixture_completed',code:'qa_triggered',pendingAction:'qa_execution'},'later'],
889
+ [{state:'unknown',code:'call_timeout',pendingAction:'reconcile'},'later'],
890
+ // Exits that need an explicit --allow-* authorization are the person's to give.
891
+ [{state:'unknown',code:'call_timeout',pendingAction:'abandon_effect'},'now'],
892
+ [{state:'blocked',code:'review_provider_failed',pendingAction:'abandon_review',reviewFailure:'reviewer_rate_limited',reviewRedispatchStopRequired:true},'now'],
893
+ [{state:'blocked',code:'develop_redo_required',pendingAction:'develop_redo'},'now'],
894
+ [{state:'awaiting_spec_approval',code:null,pendingAction:'spec_approval'},'now'],
895
+ [{state:'blocked',code:'provider_development_authorization_required',pendingAction:'none'},'now'],
896
+ [{outcome:'denied',state:'blocked',code:'permission_denied',pendingAction:'none'},'now'],
897
+ [{state:'blocked',code:'spec_drift',pendingAction:'spec_rebind'},'now'],
898
+ [{state:'blocked',code:'review_limit',pendingAction:'none'},'now'],
899
+ [{state:'blocked',code:'review_blocked',pendingAction:'none'},'now'],
900
+ [{state:'blocked',code:'review_redispatch_limit',pendingAction:'none'},'now'],
901
+ [{state:'blocked',code:'develop_redo_limit',pendingAction:'none'},'now'],
902
+ [{outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'},'now'],
903
+ ])assert.equal(notice(result).delivery,delivery,JSON.stringify(result));
904
+ assert.equal(notice({state:'pending_review',code:'review_provider_failed',pendingAction:'resume',reviewFailure:'reviewer_rate_limited'}).reviewFailure,'reviewer_rate_limited');
905
+ assert.equal(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',operation:'advance',failure:'host_exited'}).delivery,'later');
906
+ assert.equal(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',operation:'advance',failure:'confirm_reask_decision_required'}).delivery,'now');
907
+ // Every stop the classifier calls a question or decision for the person is sent at once (same facts, one table).
908
+ const other=(workflow,result)=>driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',args:['--host-context','s1'],operation:'advance',row:{requestId:'drive',result}});
909
+ for(const [workflow,result] of [['cm-prd',{stage:'awaiting_user'}],['cm-prd',{stage:'awaiting_design_user'}],['cm-prd',{stage:'change_confirmation'}],
910
+ ...['change_requirements','change_design','change_tasks','change_check'].map(stage=>['cm-prd',{stage,question:'是否保留旧功能?'}]),
911
+ ['cm-idea',{stage:'awaiting_user'}],['cm-init',{stage:'confirmation_required'}],['cm-refactor',{stage:'awaiting_finish'}],
912
+ ['cm-fix',{stage:'blocked',progress:{requiresUser:true}}]]){
913
+ const notice=other(workflow,result);
914
+ assert.equal(notice.event,'stuck',`${workflow} ${JSON.stringify(result)}`);
915
+ assert.equal(notice.delivery,'now',`${workflow} ${JSON.stringify(result)}`);
916
+ assert.equal(notice.ask,true);
917
+ assert.match(buildNotifyMessage(notice,{now:NOW,layout:'compact'}).body.split('\n')[1],/^你要做:回到会话「s1」,回答它的问题或做决定$/);
918
+ }
919
+ for(const [workflow,result] of [['cm-prd',{stage:'change_check_failed',round:2}],['cm-prd',{stage:'change_rejected'}],['cm-idea',{stage:'save_blocked'}]])
920
+ assert.equal(other(workflow,result).delivery,'later',`${workflow} ${JSON.stringify(result)}`);
921
+ assert.equal(driveNotice({host:'cm-fix-host.mjs',cwd:'/w/p',operation:'advance',row:{requestId:'drive',result:{stage:'blocked',reason:'repair_authorization_required'}}}).delivery,'now');
922
+ });
923
+
924
+ test('deferred notice: off without config; sent after the delay when nothing moved; one per session; cleared by progress, a new step or an immediate notice',async t=>{
925
+ const empty=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-later-off-'));t.after(()=>fs.rmSync(empty,{recursive:true,force:true}));
926
+ assert.deepEqual(await notifyLater(fields('off',{attentionKey:'attn|a|s'}),{env:{...process.env,CM_WORKFLOW_HOME:empty},delayMs:50}),{scheduled:false,reason:'off'});
927
+ assert.deepEqual(fs.readdirSync(empty),[]);
928
+ assert.deepEqual(await notifyLater(fields('off'),{env:{...process.env,CM_WORKFLOW_HOME:undefined,NODE_TEST_CONTEXT:'child-v8'},delayMs:50}),{scheduled:false,reason:'off'});
929
+ // The per-window cap is lifted so a stray send could not hide behind it.
930
+ const h=home(t,{config:{frequency:{perWindow:50}}}),attn=name=>`attn|work/demo-app|${name}`,pending=()=>fs.existsSync(path.join(h.dir,'notify-pending'))
931
+ ?fs.readdirSync(path.join(h.dir,'notify-pending')).filter(name=>name.endsWith('.json')):[];
932
+ const later=(key,name,delayMs=300,over={})=>notifyLater(fields(key,{attentionKey:attn(name),session:name,...over}),{env:h.env,delayMs});
933
+ // Nothing moved: sent once after the delay, and the pending record is gone.
934
+ assert.equal((await later('a1','s-a')).scheduled,true);assert.equal(pending().length,1);
935
+ assert.equal(h.rows().length,0);
936
+ assert(await h.until(()=>h.rows().length===1));assert.equal(h.rows()[0].stdin.code,'checks_not_passed');
937
+ assert(await h.until(()=>pending().length===0));
938
+ // A later stop of the same session replaces the earlier one: one notice, the newer one.
939
+ await later('b1','s-b',300,{code:'qa_triggered'});await later('b2','s-b');
940
+ // Progress cleared one session, a new step started in another, an immediate notice superseded a third.
941
+ await later('c1','s-c');assert.equal(await clearAttention(attn('s-c'),{env:h.env}),true);
942
+ await later('d1','s-d');assert.equal(await cancelPendingNotice(attn('s-d'),{env:h.env}),true);
943
+ await later('e1','s-e');assert.equal(notify(fields('e2',{attentionKey:attn('s-e'),code:'provider_development_authorization_required'}),{env:h.env}).sent,true);
944
+ assert(await h.until(()=>h.rows().length===3));
945
+ await new Promise(resolve=>setTimeout(resolve,900));
946
+ assert.deepEqual(h.rows().map(row=>row.stdin.code).slice(1).sort(),['checks_not_passed','provider_development_authorization_required']);
947
+ assert.equal(h.rows().length,3,'b2 and e2 only, never b1, c1, d1 or e1');
948
+ assert.equal(h.rows().filter(row=>row.stdin.code==='checks_not_passed').length,2,'b2 only, never b1, c1 or d1');
949
+ assert.deepEqual(pending(),[]);
950
+ // A clear only removes a pending stop from before the step; a newer one stays.
951
+ await later('f1','s-f',600);assert.equal(await cancelPendingNotice(attn('s-f'),{env:h.env,before:Date.now()-60000}),false);
952
+ assert.equal(pending().length,1);
953
+ });
954
+
955
+ // The pending directory is used only when it is a real 0700 directory inside the
956
+ // notify home: a link or a widened directory is never read, written or emptied.
957
+ test('deferred notice refuses a linked or widened notify-pending directory and reports it unscheduled',{skip:process.platform==='win32'},async t=>{
958
+ const h=home(t),outside=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-outside-')));
959
+ t.after(()=>fs.rmSync(outside,{recursive:true,force:true}));
960
+ const dir=path.join(h.dir,'notify-pending'),key=`attn|work/demo-app|s-link`;
961
+ fs.symlinkSync(outside,dir);
962
+ fs.writeFileSync(path.join(outside,'keep.json'),'{"token":"x","at":0}');
963
+ assert.deepEqual(await notifyLater(fields('l1',{attentionKey:key}),{env:h.env,delayMs:50}),{scheduled:false,reason:'pending_dir_unsafe',faultNotice:true});
964
+ assert.equal(await cancelPendingNotice(key,{env:h.env}),false);
965
+ assert.equal(await clearAttention(key,{env:h.env}),false);
966
+ assert.deepEqual(fs.readdirSync(outside),['keep.json'],'nothing written, renamed or removed through the link');
967
+ fs.unlinkSync(dir);fs.mkdirSync(dir,{mode:0o755});fs.chmodSync(dir,0o755);
968
+ assert.deepEqual(await notifyLater(fields('l2',{attentionKey:key}),{env:h.env,delayMs:50}),{scheduled:false,reason:'pending_dir_unsafe',faultNotice:false});
969
+ assert.deepEqual(fs.readdirSync(dir),[]);
970
+ fs.chmodSync(dir,0o700);
971
+ assert.equal((await notifyLater(fields('l3',{attentionKey:key}),{env:h.env,delayMs:50})).scheduled,true);
972
+ assert(await h.until(()=>h.rows().length===2));
973
+ assert.deepEqual(h.rows().map(row=>row.stdin.code),['notify_pending_unsafe','checks_not_passed']);
974
+ });
975
+
976
+ // While notify-pending is unsafe, ordinary stops are not sent one by one at
977
+ // once: one fixed configuration-fault notice a day says deferred notices are off;
978
+ // a stop that needs the person is still sent at once.
979
+ test('unsafe notify-pending: many ordinary stops give one fault notice a day; a person\'s stop is still sent',{skip:process.platform==='win32'},async t=>{
980
+ const h=home(t,{config:{frequency:{perWindow:50}}}),dir=path.join(h.dir,'notify-pending');
981
+ fs.mkdirSync(dir,{mode:0o777});fs.chmodSync(dir,0o777);
982
+ for(const [index,code] of ['checks_not_passed','qa_triggered','develop_checks_not_passed','host_exited'].entries()){
983
+ const result=await notifyLater(fields(`u${index}`,{attentionKey:`attn|work/demo-app|s${index}`,code}),{env:h.env,delayMs:50});
984
+ assert.equal(result.reason,'pending_dir_unsafe');assert.equal(result.faultNotice,index===0);
985
+ }
986
+ assert(await h.until(()=>h.rows().length===1));
987
+ assert.equal(notify(fields('a1',{attentionKey:'attn|work/demo-app|s9',code:'provider_development_authorization_required'}),{env:h.env}).sent,true);
988
+ assert(await h.until(()=>h.rows().length===2));
989
+ await new Promise(resolve=>setTimeout(resolve,400));
990
+ const rows=h.rows();assert.equal(rows.length,2);
991
+ assert.equal(rows[0].stdin.code,'notify_pending_unsafe');
992
+ assert.match(rows[0].body,/延后提醒不可用:\.cm-workflow 目录下的 notify-pending 权限或类型不安全/);
993
+ assert.equal(rows[1].stdin.code,'provider_development_authorization_required');
994
+ // Still unsafe a day later: one more fault notice.
995
+ const later=await notifyLater(fields('u9',{attentionKey:'attn|work/demo-app|s1'}),{env:h.env,delayMs:50,now:Date.now()+24*3600*1000+1000});
996
+ assert.equal(later.faultNotice,true);
997
+ });
998
+
999
+ test('driver with an unsafe notify-pending sends only the fault notice, never the ordinary stops at once',{skip:process.platform==='win32'},async t=>{
1000
+ const h=home(t,{config:{frequency:{perWindow:50}}}),dir=path.join(h.dir,'notify-pending');
1001
+ fs.mkdirSync(dir,{mode:0o755});fs.chmodSync(dir,0o755);
1002
+ const host=path.join(h.dir,'cm-ai-host.mjs'),wrapper=path.join(h.dir,'cm-ai-drive.mjs'),project=path.join(h.dir,'demo-app');
1003
+ fs.mkdirSync(project);
1004
+ fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
1005
+ process.stdin.on('data',chunk=>{for(const line of String(chunk).split('\\n').filter(Boolean)){const row=JSON.parse(line);
1006
+ if(row.requestId==='drive')process.stdout.write(JSON.stringify({requestId:'drive',result:{workflow:'cm-ai',outcome:'advanced',
1007
+ state:'blocked',code:process.env.FIXTURE_CODE,pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1}}})+'\\n');}});
1008
+ process.stdin.on('end',()=>process.exit(0));`);
1009
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
1010
+ driveHost({host:${JSON.stringify(host)},args:['serve','--host-context','4f9fa27f-6196-4f1f-9bb7-fe5bcd5614fa'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
1011
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
1012
+ for(const code of ['develop_checks_not_passed','qa_triggered','checks_not_passed']){
1013
+ const run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env:{...env,FIXTURE_CODE:code},timeout:20000});
1014
+ assert.equal(run.status,0,run.stderr);
1015
+ }
1016
+ assert(await h.until(()=>h.rows().length===1));
1017
+ await new Promise(resolve=>setTimeout(resolve,800));
1018
+ assert.deepEqual(h.rows().map(row=>row.stdin.code),['notify_pending_unsafe']);
1019
+ });
1020
+
548
1021
  // Shared driver core (scripts/*-drive.mjs all use driveHost) with a host that
549
- // stops on blocked: one notice; repeating the identical run sends nothing new.
1022
+ // stops on blocked: one notice after waitMinutes (a stop that is not a person's
1023
+ // decision is deferred); repeating the identical run sends nothing new.
550
1024
  // The notify command takes 3 s, yet the driver exits without waiting for it.
551
- test('driver ending in blocked notifies exactly once, never waits for the command, and an identical run does not resend',async t=>{
552
- const h=home(t,{sleepMs:3000});
1025
+ test('driver ending in blocked notifies exactly once after waitMinutes, never waits for the command, and an identical run does not resend',async t=>{
1026
+ const h=home(t,{sleepMs:3000,config:{waitMinutes:0.005}});
553
1027
  const host=path.join(h.dir,'cm-ai-host.mjs'),wrapper=path.join(h.dir,'cm-ai-drive.mjs'),project=path.join(h.dir,'demo-app');
554
1028
  fs.mkdirSync(project);
555
1029
  fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
556
1030
  process.stdin.on('data',chunk=>{for(const line of String(chunk).split('\\n').filter(Boolean)){const row=JSON.parse(line);
557
1031
  if(row.requestId==='drive')process.stdout.write(JSON.stringify({requestId:'drive',result:{workflow:'cm-ai',outcome:'advanced',state:'blocked',
558
- code:'checks_not_passed',pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1}}})+'\\n');}});
559
- process.stdin.on('end',()=>process.exit(0));`);
1032
+ code:process.env.FIXTURE_STATE==='progress'?null:'checks_not_passed',pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1},
1033
+ ...(process.env.FIXTURE_STATE==='progress'?{state:'ready'}:{})}})+'\\n');}});
1034
+ process.stdin.on('end',()=>setTimeout(()=>process.exit(0),Number(process.env.FIXTURE_CLOSE_DELAY??0)));`);
560
1035
  fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
561
- driveHost({host:${JSON.stringify(host)},args:['serve'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
1036
+ driveHost({host:${JSON.stringify(host)},args:['serve','--host-context','4f9fa27f-6196-4f1f-9bb7-fe5bcd5614fa'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
562
1037
  const env={...h.env};delete env.NODE_TEST_CONTEXT;
563
1038
  for(let i=0;i<2;i++){
564
1039
  const started=performance.now(),run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env,timeout:20000});
565
1040
  assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,'blocked');
566
1041
  assert(performance.now()-started<2000,`driver exit waited on the notify command: ${performance.now()-started} ms`);
567
1042
  assert.equal(h.rows().length,0,`run ${i}: the command is still running in the background`);
1043
+ assert.match(run.stderr,new RegExp(`\\[drive\\] 提醒里的标识:项目 ${label(project)} · 会话 4f9fa27f\\n`));
568
1044
  }
569
1045
  assert(await h.until(()=>h.rows().length===1));
570
1046
  await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,1);
571
1047
  const [row]=h.rows();
572
- assert.equal(row.title,'CM cm-ai 需要人处理 · demo-app');assert.equal(row.stdin.runId,'run-7');assert.equal(row.stdin.code,'checks_not_passed');
1048
+ assert.equal(row.title,`CM 需要人处理 · ${label(project)}`);assert.equal(row.stdin.runId,'run-7');assert.equal(row.stdin.code,'checks_not_passed');
1049
+ assert.equal(row.stdin.session,'4f9fa27f');assert.equal(row.stdin.subtitle,'cm-ai · T-001 · 会话 4f9fa27f');
1050
+ // A step that moves on clears the session's record: the same stop is sent at once, not after the 2-hour follow-up.
1051
+ const progress=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env:{...env,FIXTURE_STATE:'progress'},timeout:20000});
1052
+ assert.equal(progress.status,0,progress.stderr);assert.equal(JSON.parse(progress.stdout).result.state,'ready');
1053
+ const cleared=()=>Object.keys(JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8')).attention).length===0;
1054
+ assert(await h.until(cleared),'progress cleared the attention record');
1055
+ // Keep the per-window cap out of the way: only the attention rule is under test here.
1056
+ const state=JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8'));state.sends=[];
1057
+ fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify(state));
1058
+ const again=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env,timeout:20000});
1059
+ assert.equal(again.status,0,again.stderr);
1060
+ assert(await h.until(()=>h.rows().length===2),'the stop after progress is sent again');
1061
+ // The clear is bounded by when the final result arrived, not by when the host closed:
1062
+ // a stop recorded while the old host is still closing stays.
1063
+ const late=spawn(process.execPath,[wrapper],{env:{...env,FIXTURE_STATE:'progress',FIXTURE_CLOSE_DELAY:'1500'}});
1064
+ let out='';late.stdout.on('data',chunk=>out+=chunk);
1065
+ const exited=new Promise(resolve=>late.on('close',resolve));
1066
+ assert(await h.until(()=>/"state": ?"ready"/.test(out)),'final result printed before the host closed');
1067
+ await new Promise(resolve=>setTimeout(resolve,100));
1068
+ const fresh=`attn|${label(project)}|4f9fa27f`;
1069
+ assert.equal(notify(fields('late-stop',{project,attentionKey:fresh,code:'review_blocked'}),{env:h.env}).sent,true);
1070
+ assert.equal(await exited,0);
1071
+ await new Promise(resolve=>setTimeout(resolve,300));
1072
+ assert.equal(Object.keys(JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8')).attention).length,1,'the newer stop is kept');
1073
+ });
1074
+
1075
+ // 2026-10-26: a stop the session handles by itself must not reach the phone.
1076
+ // The driver defers it; the next step of the same session cancels it as soon as
1077
+ // its host accepts the step, before any result; an immediate stop is not deferred.
1078
+ test('driver stop is deferred, the next step of the session cancels it at once, and an authorization stop is sent at once',async t=>{
1079
+ const h=home(t,{config:{waitMinutes:1}});
1080
+ const host=path.join(h.dir,'cm-ai-host.mjs'),wrapper=path.join(h.dir,'cm-ai-drive.mjs'),project=path.join(h.dir,'demo-app');
1081
+ fs.mkdirSync(project);
1082
+ fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
1083
+ process.stdin.on('data',chunk=>{for(const line of String(chunk).split('\\n').filter(Boolean)){const row=JSON.parse(line);
1084
+ if(row.requestId==='drive')setTimeout(()=>process.stdout.write(JSON.stringify({requestId:'drive',result:{workflow:'cm-ai',outcome:'advanced',
1085
+ state:'blocked',code:process.env.FIXTURE_CODE,pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1}}})+'\\n'),Number(process.env.FIXTURE_REPLY_DELAY??0));}});
1086
+ process.stdin.on('end',()=>process.exit(0));`);
1087
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
1088
+ driveHost({host:${JSON.stringify(host)},args:['serve','--host-context','4f9fa27f-6196-4f1f-9bb7-fe5bcd5614fa'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
1089
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
1090
+ const pending=()=>fs.existsSync(path.join(h.dir,'notify-pending'))?fs.readdirSync(path.join(h.dir,'notify-pending')).filter(name=>name.endsWith('.json')):[];
1091
+ const first=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env:{...env,FIXTURE_CODE:'develop_checks_not_passed'},timeout:20000});
1092
+ assert.equal(first.status,0,first.stderr);
1093
+ assert(await h.until(()=>pending().length===1),'the stop waits as a pending notice');
1094
+ const slow=spawn(process.execPath,[wrapper],{env:{...env,FIXTURE_CODE:'develop_checks_not_passed',FIXTURE_REPLY_DELAY:'1500'}});
1095
+ const exited=new Promise(resolve=>slow.on('close',resolve));
1096
+ assert(await h.until(()=>pending().length===0,1200),'accepting the next step cancelled the earlier stop');
1097
+ assert.equal(await exited,0);
1098
+ assert(await h.until(()=>pending().length===1),'the new stop waits again');
1099
+ assert.deepEqual(h.rows(),[]);
1100
+ const urgent=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env:{...env,FIXTURE_CODE:'provider_development_authorization_required'},timeout:20000});
1101
+ assert.equal(urgent.status,0,urgent.stderr);
1102
+ assert(await h.until(()=>h.rows().length===1));
1103
+ assert.equal(h.rows()[0].stdin.code,'provider_development_authorization_required');
1104
+ assert.match(h.rows()[0].stdin.action,/看它要你授权什么/);
1105
+ assert(await h.until(()=>pending().length===0),'an immediate notice about the session supersedes the pending stop');
573
1106
  });
574
1107
 
575
1108
  // Host bridge: a host_request outstanding past waitMinutes notifies once;
@@ -589,7 +1122,7 @@ if(mode==='hang')bridge.call('develop',{},new AbortController().signal).catch(()
589
1122
  const late=spawnSync(process.execPath,[script,'late'],{encoding:'utf8',env,timeout:20000});
590
1123
  assert.equal(late.status,0,late.stderr);
591
1124
  assert(await h.until(()=>h.rows().length===1));
592
- assert.equal(h.rows()[0].title,'CM cm-demo 等待会话应答 · '+path.basename(process.cwd()));
1125
+ assert.equal(h.rows()[0].title,'CM 等待会话应答 · '+label(process.cwd()));assert.equal(h.rows()[0].stdin.subtitle,'cm-demo');
593
1126
  assert.equal(h.rows()[0].stdin.stage,'qa_browser');assert.equal(h.rows()[0].stdin.code,'waiting_session_answer');
594
1127
  const early=spawnSync(process.execPath,[script,'early'],{encoding:'utf8',env,timeout:20000});
595
1128
  assert.equal(early.status,0,early.stderr);await new Promise(resolve=>setTimeout(resolve,300));assert.equal(h.rows().length,1);
@@ -630,34 +1163,46 @@ test('checkWaitMinutes is validated like waitMinutes',t=>{
630
1163
  // session sends no next operation for idleMinutes, one notice says so. A last
631
1164
  // result that waits on a person says "在等你" instead. Any next operation or
632
1165
  // session end clears it; status polls are not progress.
633
- function idleHost(h){
1166
+ function idleHost(h,{startupDelayMs=0}={}){
634
1167
  const script=path.join(h.dir,'cm-prd-host.mjs');
635
1168
  fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
636
1169
  const host={handle:async request=>{
637
1170
  if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
638
1171
  if(['status','fix_status'].includes(request.operation))return {stage:'status_only',doneAt:Date.now()};
639
1172
  return request.answer;}};
1173
+ if(${startupDelayMs})await new Promise(resolve=>setTimeout(resolve,${startupDelayMs}));
640
1174
  await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
641
1175
  const env={...h.env};delete env.NODE_TEST_CONTEXT;
642
1176
  // steps: [delayMs, request object | raw line string | null to end stdin];
643
1177
  // delay 'reply:<id>' waits until that requestId has been answered instead.
644
- return async steps=>{
1178
+ const history=[];
1179
+ const run=async steps=>{
645
1180
  const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
646
- let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
1181
+ const trace=hostDiagnostic(child);
1182
+ let stdout='',buffer='';child.stdout.on('data',chunk=>{
1183
+ stdout+=chunk;buffer+=chunk;let end;
1184
+ while((end=buffer.indexOf('\n'))!==-1){
1185
+ const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
1186
+ try{trace.receive(JSON.parse(line));}catch{/* Raw lines are never retained in diagnostics. */}
1187
+ }
1188
+ });
647
1189
  const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
648
1190
  const replied=id=>stdout.includes(`"requestId":"${id}"`);
649
1191
  for(const [delay,request] of steps){
650
1192
  if(typeof delay==='string'){
651
1193
  const id=delay.slice(6),deadline=Date.now()+15000;
652
- while(!replied(id)){if(Date.now()>deadline){child.kill();throw new Error(`no reply for ${id}`);}await new Promise(resolve=>setTimeout(resolve,10));}
1194
+ while(!replied(id)){if(Date.now()>deadline){child.kill();throw trace.attach(new Error('host fixture reply timeout'));}await new Promise(resolve=>setTimeout(resolve,10));}
653
1195
  }
654
1196
  else await new Promise(resolve=>setTimeout(resolve,delay));
655
- if(request===null){child.stdin.end();break;}
1197
+ if(request===null){trace.send({operation:'eof'});child.stdin.end();break;}
1198
+ if(request!==undefined)trace.send(typeof request==='string'?{}:request);
656
1199
  if(request!==undefined)child.stdin.write((typeof request==='string'?request:JSON.stringify(request))+'\n');
657
1200
  }
658
1201
  const started=Date.now(),code=await exited;
659
- return {code,stdout,exitMs:Date.now()-started};
1202
+ const diagnostic=trace.snapshot();history.push(diagnostic);if(history.length>8)history.shift();
1203
+ return {code,stdout,exitMs:Date.now()-started,diagnostic};
660
1204
  };
1205
+ run.diagnostics=()=>history;return run;
661
1206
  }
662
1207
  const op=(n,answer,extra={})=>({requestId:`r${n}`,operation:'advance',answer,...extra});
663
1208
 
@@ -667,41 +1212,46 @@ test('host session idle after a finished step notifies once: 疑似空转 for pr
667
1212
  assert.equal(progress.code,0);
668
1213
  assert(await h.until(()=>h.rows().length===1));
669
1214
  const [idle]=h.rows();
670
- assert.equal(idle.title,'CM cm-prd 疑似空转 · '+path.basename(process.cwd()));
1215
+ assert.equal(idle.title,'CM 疑似空转 · '+label(process.cwd()));assert.equal(idle.stdin.subtitle,'cm-prd');
671
1216
  assert.equal(idle.stdin.event,'idle');assert.equal(idle.stdin.code,'no_next_step');
672
1217
  assert.equal(idle.stdin.runId,'prd-1');assert.equal(idle.stdin.stage,'requirements_analysis');
673
1218
  const waiting=home(t,{config:{idleMinutes:0.009}});
674
1219
  const review=await idleHost(waiting)([[0,op(1,{stage:'awaiting_user',runId:'prd-2'})],[2700,null]]);
675
1220
  assert.equal(review.code,0);
676
1221
  assert(await waiting.until(()=>waiting.rows().length===1));
677
- assert.equal(waiting.rows()[0].title,'CM cm-prd 在等你 · '+path.basename(process.cwd()));
1222
+ assert.equal(waiting.rows()[0].title,'CM 在等你 · '+label(process.cwd()));
678
1223
  assert.equal(waiting.rows()[0].stdin.event,'idle_waiting');assert.equal(waiting.rows()[0].stdin.code,'waiting_for_you');
679
1224
  await new Promise(resolve=>setTimeout(resolve,900));
680
1225
  assert.equal(h.rows().length,1);assert.equal(waiting.rows().length,1);
681
1226
  });
682
1227
 
683
- test('host session idle: next step, in-flight step and session end clear it; status polls do not',async t=>{
684
- const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h);
1228
+ for(const startupDelayMs of [0,750])test(`host session idle: next step, in-flight step and session end clear it; status polls do not (startup ${startupDelayMs}ms)`,async t=>{
1229
+ const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h,{startupDelayMs});
1230
+ // Sending is not completion: a slow startup can otherwise batch the next
1231
+ // line before the first reply, exercising host_busy instead of idle clearing.
685
1232
  // Steady progress: each next operation arrives before the threshold.
686
- const steady=[];for(let n=1;n<=6;n++)steady.push([n===1?0:180,op(n,{stage:'requirements_analysis'})]);
687
- assert.equal((await run([...steady,[180,null]])).code,0);
1233
+ const steady=[];for(let n=1;n<=6;n++){
1234
+ if(n>1)steady.push([`reply:r${n-1}`,undefined]);
1235
+ steady.push([n===1?0:180,op(n,{stage:'requirements_analysis'})]);
1236
+ }
1237
+ assert.equal((await run([...steady,['reply:r6',undefined],[180,null]])).code,0);
688
1238
  // A long in-flight operation is not idleness; ending right after its reply clears the timer.
689
1239
  assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
690
1240
  // A slow next operation: its arrival clears the timer armed by the previous reply.
691
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,op(2,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
1241
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,op(2,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
692
1242
  // A cancel reply while another operation is still in flight does not arm it.
693
1243
  assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[180,{requestId:'c1',operation:'cancel'}],[2700,null]])).code,0);
694
1244
  // Driver shape: EOF right after the reply arrived.
695
1245
  assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',null]])).code,0);
696
1246
  // A line the host rejects (not JSON, unknown operation) is still the session's next step.
697
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,'not json'],[2700,null]])).code,0);
698
- assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,{requestId:'x',operation:'no_such_op'}],[2700,null]])).code,0);
1247
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,'not json'],[2700,null]])).code,0);
1248
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,{requestId:'x',operation:'no_such_op'}],[2700,null]])).code,0);
699
1249
  await new Promise(resolve=>setTimeout(resolve,1500));
700
- assert.equal(h.rows().length,0,h.log());
1250
+ assert.equal(h.rows().length,0,JSON.stringify(run.diagnostics()));
701
1251
  // Polls (status via the control path, fix_status via the normal path) neither
702
1252
  // hold the timer off nor replace the last real step's result.
703
1253
  for(const poll of ['status','fix_status']){
704
- const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})]];
1254
+ const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})],['reply:r1',undefined]];
705
1255
  for(let n=0;n<12;n++)polls.push([180,{requestId:`s${n}`,operation:poll}]);
706
1256
  assert.equal((await run([...polls,[180,null]])).code,0);
707
1257
  assert(await h.until(()=>h.rows().some(row=>row.stdin.runId===`run-${poll}`)));