@aibyzero/cm-workflow 0.16.8 → 0.17.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 (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,313 @@
1
+ #!/usr/bin/env node
2
+ // CM managed push sender for Bark (iOS) and pushplus (WeChat). /cm:notify copies
3
+ // this file to <CM_WORKFLOW_HOME>/notify/cm-notify-send.mjs and points
4
+ // notify.json at it, so it must stay self-contained (node: built-ins only).
5
+ // One channel at a time, chosen by notify-channel.conf CHANNEL=bark|pushplus.
6
+ // One process sends HTTPS itself (no curl, no child processes). Windows is not
7
+ // supported yet: every path exits 2 there (owner/ACL checks of the secret
8
+ // files are not verified on a real Windows machine). Total deadline: 12 s from
9
+ // the moment this script starts executing. A hard timer armed first at entry
10
+ // exits with 5; file reads are asynchronous so that timer can always fire, and the
11
+ // remaining budget is checked before every read, before the request and
12
+ // before every exit 0. This stays inside the plugin's 15 s kill. Secret files are parsed as data
13
+ // (never executed or exported) and their values are never printed or logged.
14
+ // No retry: a timed-out request may already have been delivered.
15
+ // Exit codes: 0 sent; 2 config or secret problem; 3 network failure;
16
+ // 4 server rejected or odd response; 5 deadline passed; 6 unexpected error.
17
+ // Kept apart so the launcher's notify.log line (exit code only) tells them apart.
18
+ // CM_NOTIFY_DRY_RUN=1: opens no secret file, no network, prints a redacted request.
19
+ // --check: only verifies that the active channel's files parse; sends nothing.
20
+ import fs from 'node:fs';
21
+ import fsp from 'node:fs/promises';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import https from 'node:https';
25
+ import {performance} from 'node:perf_hooks';
26
+ import {fileURLToPath} from 'node:url';
27
+
28
+ // Process entry, first: record the start and decide from import.meta.main
29
+ // alone (no file-system access; symlinked entries work too). The plugin needs
30
+ // Node 24.14+; no version number is checked here. Only a missing
31
+ // import.meta.main is detected, and then the process ends with 3 rather than
32
+ // doing nothing. When run directly the
33
+ // 12 s hard timer is armed next, and on Windows the very next action is the
34
+ // refusal (exit 2), before anything reads a file. The timer is not unref'd:
35
+ // the process ends with 5 at the deadline even if some work never settles.
36
+ export const WINDOWS_UNSUPPORTED='/cm:notify 暂不支持 Windows:密钥文件权限核对尚未在 Windows 实机验证';
37
+ export const NODE_UNSUPPORTED='cm-notify: 当前 Node 没有 import.meta.main,不受支持(插件要求 Node 24.14 或更高版本),没有发送';
38
+ export function entryDecision(main,platform){
39
+ if(main===undefined)return 'unsupported_node';
40
+ if(main!==true)return 'imported';
41
+ return platform==='win32'?'windows':'run';
42
+ }
43
+ const ENTRY_STARTED_AT=performance.now();
44
+ const ENTRY=entryDecision(import.meta.main,process.platform);
45
+ const armHardTimer=(deadlineMs,startedAt)=>setTimeout(()=>{
46
+ try{process.stderr.write(`cm-notify: 整次调用超过 ${Math.ceil(deadlineMs/1000)} 秒,已放弃\n`);}catch{}process.exit(5);
47
+ },Math.max(0,deadlineMs-(performance.now()-startedAt)));
48
+ if(ENTRY==='unsupported_node'){try{process.stderr.write(`${NODE_UNSUPPORTED}\n`);}catch{}process.exit(3);}
49
+ const ENTRY_HARD_TIMER=ENTRY==='run'||ENTRY==='windows'?armHardTimer(12000,ENTRY_STARTED_AT):null;
50
+ if(ENTRY==='windows'){try{process.stderr.write(`cm-notify: ${WINDOWS_UNSUPPORTED}\n`);}catch{}process.exit(2);}
51
+
52
+ export const SEND_EXIT=Object.freeze({ok:0,config:2,network:3,rejected:4,deadline:5,unexpected:6});
53
+ export const DEADLINE_MS=12000;
54
+ const MAX_FILE=64*1024,MAX_RESPONSE=64*1024,MAX_STDIN=64*1024;
55
+ // Largest file the safe read boundary accepts; /cm:notify never writes a bigger notify.json.
56
+ export const MAX_FILE_BYTES=MAX_FILE;
57
+ export const CHANNEL_FILE='notify-channel.conf';
58
+ export const CHANNELS=Object.freeze({
59
+ bark:Object.freeze({file:'bark.env',names:['BARK_KEY','BARK_SERVER'],required:'BARK_KEY'}),
60
+ pushplus:Object.freeze({file:'pushplus.env',names:['PUSHPLUS_TOKEN'],required:'PUSHPLUS_TOKEN'}),
61
+ });
62
+ export const BARK_DEFAULT_SERVER='https://api.day.app';
63
+ export const PUSHPLUS_URL='https://www.pushplus.plus/send';
64
+ const BARK_KEY=/^[A-Za-z0-9]{8,64}$/,DEVICE_TOKEN=/^[0-9a-fA-F]{64}$/,PUSHPLUS_TOKEN=/^[A-Za-z0-9]{8,128}$/;
65
+ const HTTPS_ORIGIN=/^https:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$/;
66
+
67
+ export class SendError extends Error{
68
+ constructor(exit,message,detail={}){super(message);this.exit=exit;this.detail=detail;}
69
+ }
70
+ const configError=(message,detail)=>new SendError(SEND_EXIT.config,message,detail);
71
+
72
+ export function notifyHome(env=process.env){
73
+ return path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
74
+ }
75
+
76
+ // Windows is refused until owner/ACL verification bound to the opened handle
77
+ // has been built and tested on a real machine (see docs/next-steps.md).
78
+ const windowsRefusal=()=>configError(WINDOWS_UNSUPPORTED,{state:'unsupported'});
79
+
80
+ // Safe read boundary used for every file this tool reads: lstat must show a
81
+ // regular file (never a symlink), the size is capped, the opened handle must be
82
+ // the same file object (dev+ino), and content is read from that handle only.
83
+ // `privateFile` adds: owned by this user, no group/other mode bits.
84
+ // `budget` (from runSender) returns the milliseconds left and throws once the
85
+ // total deadline has passed. `fileOps` (lstat/open) is replaceable only through
86
+ // this module API, so tests can simulate slow reads. `bytes` returns the exact
87
+ // bytes read instead of strict UTF-8 text (BOM kept).
88
+ async function readChecked(file,label,{privateFile,budget,fileOps=fsp,bytes:raw=false}){
89
+ if(budget)budget();
90
+ const notRegular=privateFile?`${label} 必须是自己的普通文件且权限 600`:`${label} 必须是普通文件(不能是符号链接)`;
91
+ let link;
92
+ try{link=await fileOps.lstat(file,{bigint:true});}
93
+ catch(error){if(error.code==='ENOENT')throw configError(`读不到 ${label}`,{state:'missing'});throw configError(`读不到 ${label}`,{state:'invalid'});}
94
+ const bad=st=>!st.isFile()||(privateFile&&((typeof process.getuid==='function'&&st.uid!==BigInt(process.getuid()))||(st.mode&0o077n)!==0n));
95
+ if(link.isSymbolicLink()||bad(link))throw configError(notRegular,{state:'invalid',reason:'permission'});
96
+ if(link.size>BigInt(MAX_FILE))throw configError(`${label} 太大`,{state:'invalid',reason:'too_large'});
97
+ let handle;
98
+ try{
99
+ // O_NONBLOCK: a file swapped for a FIFO after lstat opens at once (instead of
100
+ // waiting for a writer) and is then refused by the type check below.
101
+ // Reads of regular files are unaffected.
102
+ handle=await fileOps.open(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0));
103
+ const st=await handle.stat({bigint:true});
104
+ if(bad(st))throw configError(notRegular,{state:'invalid',reason:'permission'});
105
+ if(st.dev!==link.dev||st.ino!==link.ino)throw configError(`${label} 在核对期间被替换,为安全起见不使用它`,{state:'invalid',reason:'permission'});
106
+ if(st.size>BigInt(MAX_FILE))throw configError(`${label} 太大`,{state:'invalid',reason:'too_large'});
107
+ const size=Number(st.size),bytes=Buffer.alloc(size);let read=0;
108
+ while(read<size){const {bytesRead}=await handle.read(bytes,read,size-read,read);if(bytesRead===0)break;read+=bytesRead;}
109
+ if(raw)return bytes.subarray(0,read);
110
+ return new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,read)).replace(/^\uFEFF/,'');
111
+ }catch(error){
112
+ if(error instanceof SendError)throw error;
113
+ throw configError(`读取 ${label} 失败`,{state:'invalid'});
114
+ }finally{if(handle)await handle.close().catch(()=>{});}
115
+ }
116
+ // Secret and channel files: refused on Windows, private-file rules elsewhere.
117
+ export async function readPrivateFile(file,label,{platform=process.platform,budget,fileOps}={}){
118
+ if(platform==='win32')throw windowsRefusal();
119
+ return readChecked(file,label,{privateFile:true,budget,fileOps});
120
+ }
121
+ // A file that holds no secret (the channel file, for display on Windows):
122
+ // the same boundary without the owner/mode rule, so a link to a secret file
123
+ // is never followed. `bytes` (used for notify.json) returns the raw bytes.
124
+ export async function readRegularFile(file,label,{fileOps,bytes=false}={}){
125
+ return readChecked(file,label,{privateFile:false,fileOps,bytes});
126
+ }
127
+
128
+ // KEY=value lines only: optional `export `, optional matching quotes, blank
129
+ // lines and # comments. Unknown or repeated names reject the whole file.
130
+ // Errors name the line number, never its content.
131
+ export function parseAssignments(text,allowed,label){
132
+ const values={},lines={};
133
+ text.split(/\r\n|\n|\r/).forEach((raw,index)=>{
134
+ let line=raw.trim();
135
+ if(!line||line.startsWith('#'))return;
136
+ if(line.startsWith('export '))line=line.slice(7).trim();
137
+ const at=line.indexOf('=');
138
+ const name=at<0?'':line.slice(0,at).trim();
139
+ let value=at<0?'':line.slice(at+1).trim();
140
+ if(at<0||!allowed.includes(name)||Object.hasOwn(values,name))
141
+ throw configError(`${label} 第 ${index+1} 行无法识别或重复`,{state:'invalid',line:index+1});
142
+ if(value.length>=2&&value[0]===value.at(-1)&&(value[0]==='"'||value[0]==="'"))value=value.slice(1,-1);
143
+ values[name]=value;lines[name]=index+1;
144
+ });
145
+ return {values,lines};
146
+ }
147
+
148
+ export async function readChannel(home,fileOptions={}){
149
+ const file=path.join(home,CHANNEL_FILE);
150
+ const {values,lines}=parseAssignments(await readPrivateFile(file,CHANNEL_FILE,fileOptions),['CHANNEL'],CHANNEL_FILE);
151
+ const channel=values.CHANNEL??'';
152
+ if(!Object.hasOwn(CHANNELS,channel))
153
+ throw configError(`${CHANNEL_FILE} 的 CHANNEL 只能是 bark 或 pushplus`,{state:'invalid',line:lines.CHANNEL});
154
+ return channel;
155
+ }
156
+
157
+ // Validated secret values for one channel. Messages say which file and line to
158
+ // fix; they never contain a value.
159
+ export async function readSecret(home,channel,fileOptions={}){
160
+ const spec=CHANNELS[channel];
161
+ if(!spec)throw configError('未知渠道');
162
+ const {values,lines}=parseAssignments(await readPrivateFile(path.join(home,spec.file),spec.file,fileOptions),spec.names,spec.file);
163
+ const where=name=>lines[name]?`第 ${lines[name]} 行 `:'';
164
+ const empty=name=>configError(`${spec.file} ${where(name)}${name} 未填写`,{state:'empty',line:lines[name]??null,name});
165
+ if(channel==='bark'){
166
+ const key=values.BARK_KEY??'',server=values.BARK_SERVER??BARK_DEFAULT_SERVER;
167
+ if(!key)throw empty('BARK_KEY');
168
+ if(DEVICE_TOKEN.test(key))throw configError(`bark.env ${where('BARK_KEY')}BARK_KEY 像是 64 位 Device Token,应填示例地址里 api.day.app/ 后面那一段`,{state:'invalid',line:lines.BARK_KEY,name:'BARK_KEY'});
169
+ if(!BARK_KEY.test(key))throw configError(`bark.env ${where('BARK_KEY')}BARK_KEY 格式不对(应为 8–64 位字母或数字)`,{state:'invalid',line:lines.BARK_KEY,name:'BARK_KEY'});
170
+ if(!HTTPS_ORIGIN.test(server))throw configError(`bark.env ${where('BARK_SERVER')}BARK_SERVER 必须是不带路径的 https 地址`,{state:'invalid',line:lines.BARK_SERVER,name:'BARK_SERVER'});
171
+ return {key,server};
172
+ }
173
+ const token=values.PUSHPLUS_TOKEN??'';
174
+ if(!token)throw empty('PUSHPLUS_TOKEN');
175
+ if(!PUSHPLUS_TOKEN.test(token))throw configError(`pushplus.env ${where('PUSHPLUS_TOKEN')}PUSHPLUS_TOKEN 格式不对(应为 8–128 位字母或数字)`,{state:'invalid',line:lines.PUSHPLUS_TOKEN,name:'PUSHPLUS_TOKEN'});
176
+ return {token};
177
+ }
178
+
179
+ const chars=(text,max)=>Array.from(text).slice(0,max).join('');
180
+ export async function buildRequest(channel,{home,env=process.env,dry=false,fileOptions={}}){
181
+ const title=chars(env.CM_NOTIFY_TITLE||'CM 提醒',100),body=chars(env.CM_NOTIFY_BODY||'(无正文)',1000);
182
+ if(channel==='bark'){
183
+ const {key,server}=dry?{key:'<已隐藏>',server:BARK_DEFAULT_SERVER}:await readSecret(home,'bark',fileOptions);
184
+ return {url:`${server}/push`,payload:{device_key:key,title,body,group:'CM',level:'active'}};
185
+ }
186
+ const {token}=dry?{token:'<已隐藏>'}:await readSecret(home,'pushplus',fileOptions);
187
+ return {url:PUSHPLUS_URL,payload:{token,title,content:body,template:'txt',channel:'wechat'}};
188
+ }
189
+
190
+ // Node 24.5+ routes https.Agent through HTTPS_PROXY/NO_PROXY when given
191
+ // proxyEnv; older Node ignores the option and connects directly.
192
+ function proxyAgent(env){
193
+ const proxy=env.HTTPS_PROXY||env.https_proxy;
194
+ if(!proxy)return undefined;
195
+ const proxyEnv={HTTPS_PROXY:proxy};
196
+ const noProxy=env.NO_PROXY??env.no_proxy;if(noProxy!==undefined)proxyEnv.NO_PROXY=noProxy;
197
+ return new https.Agent({proxyEnv,keepAlive:false});
198
+ }
199
+
200
+ // One POST, no redirects (https.request never follows them), TLS verification
201
+ // forced on regardless of NODE_TLS_REJECT_UNAUTHORIZED. `request` is injectable
202
+ // only through this module API (tests use a loopback http server).
203
+ export function postJson(url,data,{request=https.request,agent,signal}={}){
204
+ return new Promise((resolve,reject)=>{
205
+ const target=new URL(url);
206
+ const options={method:'POST',hostname:target.hostname,port:target.port||443,path:`${target.pathname}${target.search}`,
207
+ headers:{'Content-Type':'application/json; charset=utf-8','Content-Length':Buffer.byteLength(data)},
208
+ rejectUnauthorized:true,signal};
209
+ if(agent)options.agent=agent;
210
+ const req=request(options,response=>{
211
+ const parts=[];let size=0;
212
+ response.on('data',chunk=>{
213
+ size+=chunk.length;
214
+ if(size>MAX_RESPONSE){response.destroy();reject(new SendError(SEND_EXIT.rejected,'响应过大'));return;}
215
+ parts.push(chunk);
216
+ });
217
+ response.on('end',()=>resolve({status:response.statusCode,raw:Buffer.concat(parts)}));
218
+ response.on('error',()=>reject(new SendError(SEND_EXIT.network,'网络请求失败')));
219
+ });
220
+ req.on('error',()=>reject(new SendError(SEND_EXIT.network,'网络请求失败')));
221
+ req.end(data);
222
+ });
223
+ }
224
+
225
+ // Only the JSON type of `code` is ever reported, never its value: a server
226
+ // that echoes the request could put the secret there.
227
+ export function responseCodeType(raw){
228
+ let value;
229
+ try{value=JSON.parse(Buffer.from(raw).toString('utf8'));}catch{return {ok:false,type:'not_json'};}
230
+ if(!value||typeof value!=='object'||Array.isArray(value)||!Object.hasOwn(value,'code'))return {ok:false,type:'missing'};
231
+ const code=value.code,type=code===null?'null':Array.isArray(code)?'array':typeof code;
232
+ return {ok:typeof code==='number'&&code===200,type};
233
+ }
234
+
235
+ // Reads one line or EOF from the plugin's stdin, then discards it.
236
+ export function drainStdinLine(stdin){
237
+ return new Promise(resolve=>{
238
+ if(!stdin||stdin.isTTY){resolve();return;}
239
+ let size=0,done=false;
240
+ const finish=()=>{
241
+ if(done)return;done=true;
242
+ stdin.off('data',data);stdin.off('end',finish);stdin.off('error',finish);stdin.off('close',finish);
243
+ try{stdin.pause();stdin.destroy?.();}catch{}
244
+ resolve();
245
+ };
246
+ const data=chunk=>{size+=chunk.length;if(size>=MAX_STDIN||chunk.includes(10))finish();};
247
+ stdin.on('data',data);stdin.on('end',finish);stdin.on('error',finish);stdin.on('close',finish);
248
+ stdin.resume?.();
249
+ });
250
+ }
251
+
252
+ // The whole call, bounded by one deadline that covers stdin, config and the
253
+ // request. Returns an exit code; writes one line to stderr on failure.
254
+ export async function runSender({argv=[],env=process.env,stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,
255
+ request,home=notifyHome(env),deadlineMs=DEADLINE_MS,startedAt,platform=process.platform,fileOps,clock=()=>performance.now()}={}){
256
+ const say=(stream,line)=>{try{stream.write(`${line}\n`);}catch{}};
257
+ const controller=new AbortController();
258
+ // The monotonic budget is checked before every read, before the request and
259
+ // before every exit 0, besides the timer below (and the CLI's hard timer).
260
+ const started=startedAt??clock(),seconds=Math.ceil(deadlineMs/1000);
261
+ const budget=()=>{
262
+ const left=deadlineMs-(clock()-started);
263
+ if(left<=0)throw new SendError(SEND_EXIT.deadline,`整次调用超过 ${seconds} 秒,已放弃(未发送)`,{deadline:true});
264
+ return left;
265
+ };
266
+ let timer;
267
+ const deadline=new Promise(resolve=>{timer=setTimeout(()=>{controller.abort();resolve('deadline');},Math.max(0,deadlineMs-(clock()-started)));timer.unref?.();});
268
+ let channel='-';
269
+ const work=(async()=>{
270
+ if(platform==='win32')throw windowsRefusal();// every path, including --check and dry-run
271
+ await drainStdinLine(stdin);
272
+ const dry=env.CM_NOTIFY_DRY_RUN==='1';
273
+ const fileOptions={budget,platform,...(fileOps?{fileOps}:{})};
274
+ channel=await readChannel(home,fileOptions);
275
+ const {url,payload}=await buildRequest(channel,{home,env,dry,fileOptions});
276
+ if(argv.includes('--check')){budget();say(stdout,`cm-notify: 渠道 ${channel} 配置可解析(未发送)`);return SEND_EXIT.ok;}
277
+ if(dry){budget();say(stdout,`POST ${url}`);say(stdout,JSON.stringify(payload));return SEND_EXIT.ok;}
278
+ const data=JSON.stringify(payload);
279
+ const agent=request?undefined:proxyAgent(env);
280
+ budget();
281
+ const {status,raw}=await postJson(url,data,{request,agent,signal:controller.signal});
282
+ const code=responseCodeType(raw);
283
+ if(status!==200||!code.ok)throw new SendError(SEND_EXIT.rejected,`推送返回 http=${Number.isSafeInteger(status)?status:'?'} code类型=${code.type}`);
284
+ // Accepted, but too late: report the deadline (it may have been delivered).
285
+ if(deadlineMs-(clock()-started)<=0)throw new SendError(SEND_EXIT.deadline,`整次调用超过 ${seconds} 秒,已放弃(可能已送达)`,{deadline:true});
286
+ return SEND_EXIT.ok;
287
+ })();
288
+ try{
289
+ const result=await Promise.race([work.then(code=>({code}),error=>({error})),deadline]);
290
+ if(result==='deadline'){work.catch(()=>{});say(stderr,`cm-notify: 整次调用超过 ${seconds} 秒,已放弃`);return SEND_EXIT.deadline;}
291
+ if(result.error){
292
+ const error=result.error;
293
+ if(error instanceof SendError){
294
+ const prefix=error.exit===SEND_EXIT.config||error.detail.deadline?'':`${channel} `;
295
+ say(stderr,`cm-notify: ${prefix}${error.message}`);return error.exit;
296
+ }
297
+ say(stderr,'cm-notify: 意外错误(详情已隐藏,避免带出密钥)');return SEND_EXIT.unexpected;
298
+ }
299
+ if(result.code===SEND_EXIT.ok&&deadlineMs-(clock()-started)<=0){say(stderr,`cm-notify: 整次调用超过 ${seconds} 秒,已放弃`);return SEND_EXIT.deadline;}
300
+ return result.code;
301
+ }finally{clearTimeout(timer);}
302
+ }
303
+
304
+ // Runs the sender as a process. `startedAt` and `hardTimer` come from the
305
+ // entry block above; tests call it with their own start and deadline.
306
+ export function runCli({argv=process.argv.slice(2),deadlineMs=DEADLINE_MS,softDeadlineMs=deadlineMs,startedAt=performance.now(),
307
+ hardTimer=armHardTimer(deadlineMs,startedAt),senderOptions={}}={}){
308
+ const hard=()=>{try{process.stderr.write('cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n');}catch{}process.exit(SEND_EXIT.unexpected);};
309
+ process.on('uncaughtException',hard);process.on('unhandledRejection',hard);
310
+ return runSender({argv,deadlineMs:softDeadlineMs,startedAt,...senderOptions})
311
+ .then(code=>{clearTimeout(hardTimer);process.exit(code);},hard);
312
+ }
313
+ if(ENTRY==='run')runCli({startedAt:ENTRY_STARTED_AT,hardTimer:ENTRY_HARD_TIMER});
@@ -11,11 +11,14 @@ import path from 'node:path';
11
11
  import {spawn} from 'node:child_process';
12
12
  import {fileURLToPath} from 'node:url';
13
13
  import {createHash,randomUUID} from 'node:crypto';
14
+ import {readRegularFileSync} from './notify-safe-read.mjs';
14
15
 
15
16
  export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perMinute:4,perDay:150,
16
17
  commandTimeoutMs:15000,titleChars:60,bodyChars:500,defaultWaitMinutes:10,defaultCheckWaitMinutes:45,
17
18
  defaultIdleMinutes:45});
18
19
  const LOCK_STALE_MS=30000,LOG_LIMIT=256*1024;
20
+ // Lock and dedup state are tiny JSON files; perDay sends bound the state size.
21
+ const CONTROL_FILE_LIMIT=256*1024;
19
22
  const RUNNER=fileURLToPath(new URL('./notify-run.mjs',import.meta.url));
20
23
 
21
24
  export function notifyHome(env=process.env){
@@ -32,37 +35,64 @@ export function appendNotifyLog(home,now,{event='-',workflow='-',hash='-',result
32
35
  }catch{}
33
36
  }
34
37
 
35
- let warned=false;
36
- const warn=(env,reason)=>{
37
- if(warned)return;warned=true;
38
- appendNotifyLog(notifyHome(env),Date.now(),{event:'config',result:`off invalid_config ${reason}`});
38
+ // One line per process and kind: an unusable file turns notices off; an
39
+ // unusable `text` only falls back to the default text (notices stay on).
40
+ const warned=new Set();
41
+ const warnOnce=(env,kind,result)=>{
42
+ if(warned.has(kind))return;warned.add(kind);
43
+ appendNotifyLog(notifyHome(env),Date.now(),{event:'config',result});
39
44
  };
45
+ const warn=(env,reason)=>warnOnce(env,'config',`off invalid_config ${reason}`);
40
46
 
41
- // null = feature off. Under `node --test` only an explicit CM_WORKFLOW_HOME
42
- // enables it, so a test suite never reaches the user's real configuration.
43
- // An invalid file is reported in notify.log only, never on workflow output.
44
- export function readNotifyConfig(env=process.env){
45
- if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return null;
46
- const file=path.join(notifyHome(env),'notify.json');
47
- let raw;
48
- try{raw=fs.readFileSync(file,'utf8');}catch(error){if(error.code!=='ENOENT')warn(env,`unreadable_${error.code??'error'}`);return null;}
47
+ // Pure check of notify.json text: {config} or {reason}. Shared by the
48
+ // runtime reader below and by /cm:notify, which must not write notify.log.
49
+ export function parseNotifyConfig(raw){
49
50
  let value;
50
- try{value=JSON.parse(raw);}catch{warn(env,'not_json');return null;}
51
- if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1){warn(env,'version');return null;}
51
+ try{value=JSON.parse(raw);}catch{return {reason:'not_json'};}
52
+ if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1)return {reason:'version'};
52
53
  const {command}=value;
53
54
  if(!Array.isArray(command)||command.length<1||command.length>32
54
55
  ||!command.every(item=>typeof item==='string'&&item.length>0&&item.length<=4096&&!item.includes('\0'))){
55
- warn(env,'command');return null;
56
+ return {reason:'command'};
56
57
  }
57
- if(!path.isAbsolute(command[0])){warn(env,'command_not_absolute');return null;}
58
+ if(!path.isAbsolute(command[0]))return {reason:'command_not_absolute'};
58
59
  const minutes=value.waitMinutes??NOTIFY_LIMITS.defaultWaitMinutes;
59
- if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440){warn(env,'wait_minutes');return null;}
60
+ if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440)return {reason:'wait_minutes'};
60
61
  const checkMinutes=value.checkWaitMinutes??NOTIFY_LIMITS.defaultCheckWaitMinutes;
61
- if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440){warn(env,'check_wait_minutes');return null;}
62
+ if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440)return {reason:'check_wait_minutes'};
62
63
  const idleMinutes=value.idleMinutes??NOTIFY_LIMITS.defaultIdleMinutes;
63
- if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440){warn(env,'idle_minutes');return null;}
64
+ if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440)return {reason:'idle_minutes'};
64
65
  const ms=value=>Math.max(1,Math.round(value*60000));
65
- return {command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes)};
66
+ const config={command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes)};
67
+ // An unusable `text` never turns notices off: the default text is used and
68
+ // the caller is told why (textReason), so a typo cannot silence notices.
69
+ if(value.text===undefined)return {config};
70
+ const text=normalizeNotifyText(value.text);
71
+ if(text.reason)return {config,textReason:text.reason};
72
+ return {config:{...config,text:text.text}};
73
+ }
74
+
75
+ // The runtime reads notify.json through the same safe boundary as /cm:notify
76
+ // (readRegularFileSync in notify-safe-read.mjs, a side-effect-free twin of the
77
+ // sender's reader; a drift test keeps the two identical): never through a
78
+ // symlink, only a regular file of at most 64 KiB, opened without blocking (a
79
+ // FIFO is refused, never waited on), and the opened handle must be the checked
80
+ // file. Still synchronous and never throws.
81
+ const UNSAFE_READ={permission:'not_regular_file',too_large:'too_large'};
82
+
83
+ // null = feature off. Under `node --test` only an explicit CM_WORKFLOW_HOME
84
+ // enables it, so a test suite never reaches the user's real configuration.
85
+ // An invalid file is reported in notify.log only, never on workflow output.
86
+ export function readNotifyConfig(env=process.env){
87
+ if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return null;
88
+ const file=path.join(notifyHome(env),'notify.json');
89
+ let raw;
90
+ try{raw=readRegularFileSync(file,'notify.json',{bytes:true}).toString('utf8');}
91
+ catch(error){if(error?.state!=='missing')warn(env,`unreadable_${UNSAFE_READ[error?.reason]??'error'}`);return null;}
92
+ const parsed=parseNotifyConfig(raw);
93
+ if(parsed.reason){warn(env,parsed.reason);return null;}
94
+ if(parsed.textReason)warnOnce(env,'text',`default_text text_config ${parsed.textReason}`);
95
+ return parsed.config;
66
96
  }
67
97
 
68
98
  // Messages carry only these structured fields. Absolute paths (POSIX, drive
@@ -78,15 +108,85 @@ function clean(value,max){
78
108
  }
79
109
  const projectName=value=>typeof value==='string'&&value?clean(path.basename(value),40):'';
80
110
 
81
- export function buildNotifyMessage(fields,{now=Date.now()}={}){
111
+ // Local 24-hour HH:MM in the process time zone (TZ) unless one is injected.
112
+ export function localClock(now,timeZone){
113
+ const parts=new Intl.DateTimeFormat('en-GB',{hour:'2-digit',minute:'2-digit',hourCycle:'h23',
114
+ ...(timeZone?{timeZone}:{})}).formatToParts(new Date(now));
115
+ const pick=type=>parts.find(part=>part.type===type)?.value??'00';
116
+ return `${pick('hour')}:${pick('minute')}`;
117
+ }
118
+
119
+ // Optional user text (notify.json `text`): a title prefix, one headline per
120
+ // event, which structured fields appear in which order, and their labels.
121
+ // Nothing else: no templates or expressions. Custom strings go through the same
122
+ // clean() as field values (paths redacted, control characters removed) and are
123
+ // capped; the whole title and body keep their caps.
124
+ export const NOTIFY_TEXT_FIELDS=Object.freeze(['project','workflow','runId','task','stage','code','nextAction','time']);
125
+ const TEXT_EVENTS=['done','waiting','idle','idle_waiting','dead','default'];
126
+ const TEXT_CAPS=Object.freeze({titlePrefix:16,headline:24,label:12});
127
+ const FIELD_CAPS={workflow:24,runId:64,task:40,stage:48,code:64,nextAction:200};
128
+ export const DEFAULT_NOTIFY_TEXT=Object.freeze({titlePrefix:'CM',
129
+ headlines:Object.freeze({done:'流程已结束',waiting:'等待会话应答',idle:'疑似空转',idle_waiting:'在等你',dead:'宿主已退出未收尾',default:'需要人处理'}),
130
+ fields:Object.freeze({default:Object.freeze(['nextAction','project','workflow','task','stage','code','time']),
131
+ done:Object.freeze(['project','task','time'])}),
132
+ labels:Object.freeze({nextAction:'下一步',project:'项目',workflow:'流程',runId:'运行',task:'任务',stage:'阶段',code:'原因',time:'时间'})});
133
+ // Custom strings first lose every Unicode format character (\p{Cf}: bidi
134
+ // controls U+202A-202E, U+2066-2069, U+200E/200F, U+061C; zero-width U+200B-200D,
135
+ // U+2060, U+FEFF; soft hyphen, tag characters), so they cannot reorder or hide
136
+ // text. Unlike field values, a path is redacted whatever precedes it: every
137
+ // span starting at "/", "~/", a drive letter with ":\" or ":/", or a UNC "\\" up to the next
138
+ // whitespace or listed punctuation becomes <路径> (so "CI/CD" becomes "CI<路径>").
139
+ // Then the usual clean(). Something visible (a letter, digit, punctuation or
140
+ // symbol) must remain. Field values and the default text are not touched.
141
+ const FORMAT_CHARS=/\p{Cf}+/gu,VISIBLE=/[\p{L}\p{N}\p{P}\p{S}]/u;
142
+ const TEXT_PATH=/(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`,。;;、))]+/g;
143
+ const cleanText=(raw,max)=>clean(raw.replace(FORMAT_CHARS,'').replace(/[\u0000-\u001f\u007f-\u009f]+/g,' ').replace(TEXT_PATH,'<路径>'),max);
144
+ const plain=value=>value&&typeof value==='object'&&!Array.isArray(value);
145
+ const onlyKeys=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));
146
+ // {text} merged over the default, or {reason}. Idempotent on its own output.
147
+ export function normalizeNotifyText(value){
148
+ if(!plain(value))return {reason:'text'};
149
+ if(!onlyKeys(value,['titlePrefix','headlines','fields','labels']))return {reason:'text_key'};
150
+ const text={titlePrefix:DEFAULT_NOTIFY_TEXT.titlePrefix,headlines:{...DEFAULT_NOTIFY_TEXT.headlines},
151
+ fields:{default:[...DEFAULT_NOTIFY_TEXT.fields.default],done:[...DEFAULT_NOTIFY_TEXT.fields.done]},labels:{...DEFAULT_NOTIFY_TEXT.labels}};
152
+ // A custom string must still show something after cleaning; only the prefix
153
+ // may be given as exactly "" (no prefix).
154
+ const word=(raw,max,empty=false)=>{
155
+ if(typeof raw!=='string')return null;if(empty&&raw==='')return '';
156
+ const cleaned=cleanText(raw,max);return VISIBLE.test(cleaned)?cleaned:null;};
157
+ if(value.titlePrefix!==undefined){
158
+ const prefix=word(value.titlePrefix,TEXT_CAPS.titlePrefix,true);if(prefix===null)return {reason:'title_prefix'};
159
+ text.titlePrefix=prefix;
160
+ }
161
+ for(const [name,keys,cap] of [['headlines',TEXT_EVENTS,TEXT_CAPS.headline],['labels',NOTIFY_TEXT_FIELDS,TEXT_CAPS.label]]){
162
+ if(value[name]===undefined)continue;
163
+ if(!plain(value[name])||!onlyKeys(value[name],keys))return {reason:name};
164
+ for(const [key,raw] of Object.entries(value[name])){const cleaned=word(raw,cap);if(cleaned===null)return {reason:name};text[name][key]=cleaned;}
165
+ }
166
+ if(value.fields!==undefined){
167
+ if(!plain(value.fields)||!onlyKeys(value.fields,['default','done']))return {reason:'fields'};
168
+ for(const [key,list] of Object.entries(value.fields)){
169
+ if(!Array.isArray(list)||list.length<1||new Set(list).size!==list.length
170
+ ||!list.every(item=>NOTIFY_TEXT_FIELDS.includes(item)))return {reason:'fields'};
171
+ text.fields[key]=[...list];
172
+ }
173
+ }
174
+ return {text};
175
+ }
176
+
177
+ // The default text is a next-step-first layout; a finished run only names
178
+ // project, task and time. `text` is a normalized notify.json `text`; anything
179
+ // unusable falls back to the default.
180
+ export function buildNotifyMessage(fields,{now=Date.now(),timeZone,text}={}){
181
+ const spec=text===undefined||text===null?DEFAULT_NOTIFY_TEXT:normalizeNotifyText(text).text??DEFAULT_NOTIFY_TEXT;
82
182
  const workflow=clean(fields.workflow,24)||'cm',project=projectName(fields.project);
83
- const headline={done:'流程已结束',waiting:'等待会话应答',idle:'疑似空转',idle_waiting:'在等你',dead:'宿主已退出未收尾'}[fields.event]??'需要人处理';
84
- const title=cut(`CM ${workflow} ${headline}${project?` · ${project}`:''}`,NOTIFY_LIMITS.titleChars);
85
- const lines=[['项目',project],['流程',workflow],['运行',clean(fields.runId,64)],['任务',clean(fields.task,40)],
86
- ['阶段',clean(fields.stage,48)],['原因',clean(fields.code,64)],['下一步',clean(fields.nextAction,200)]]
87
- .filter(([,value])=>value).map(([label,value])=>`${label}:${value}`);
88
- lines.push(`时间:${new Date(now).toISOString()}`);
89
- if(fields.event!=='done')lines.push('CM 不会自动继续,请回到会话处理。');
183
+ const event=Object.hasOwn(spec.headlines,fields.event)&&fields.event!=='default'?fields.event:'default';
184
+ const head=[spec.titlePrefix,workflow,spec.headlines[event]].filter(Boolean).join(' ');
185
+ const title=cut(`${head}${project?` · ${project}`:''}`,NOTIFY_LIMITS.titleChars);
186
+ const value=name=>name==='time'?localClock(now,timeZone):name==='project'?project:name==='workflow'?workflow
187
+ :clean(fields[name],FIELD_CAPS[name]);
188
+ const rows=spec.fields[fields.event==='done'?'done':'default'].map(name=>[spec.labels[name],value(name)]);
189
+ const lines=rows.filter(([,value])=>value).map(([label,value])=>`${label}:${value}`);
90
190
  return {title,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
91
191
  }
92
192
 
@@ -98,7 +198,28 @@ const keyHash=key=>createHash('sha256').update(key).digest('hex').slice(0,16);
98
198
  // older than 30 s; the critical section takes milliseconds) is reclaimed only
99
199
  // by renaming it to a unique name and confirming it is byte-identical to the
100
200
  // stale lock that was judged; anything else is put back and the notice skipped.
101
- function readLock(file){try{return fs.readFileSync(file,'utf8');}catch{return null;}}
201
+ // Bounded read of a control file we may not own. lstat first: a symlink (even a
202
+ // dangling one, and even where O_NOFOLLOW is 0 as on Windows), a non-regular
203
+ // file or an oversized file never counts as readable. The descriptor is opened
204
+ // without following links and without blocking (a FIFO cannot stall the host),
205
+ // and must be the same inode lstat saw. Returns {missing:true} only for ENOENT;
206
+ // every other trouble returns null, which skips the notice.
207
+ function readBounded(file,limit){
208
+ let before;
209
+ try{before=fs.lstatSync(file);}catch(error){return error.code==='ENOENT'?{missing:true}:null;}
210
+ if(before.isSymbolicLink()||!before.isFile()||before.size>limit)return null;
211
+ let descriptor=null;
212
+ try{
213
+ descriptor=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
214
+ const info=fs.fstatSync(descriptor);
215
+ if(!info.isFile()||info.size>limit||info.dev!==before.dev||info.ino!==before.ino)return null;
216
+ const buffer=Buffer.alloc(info.size);
217
+ let offset=0;while(offset<info.size){const n=fs.readSync(descriptor,buffer,offset,info.size-offset,offset);if(n===0)break;offset+=n;}
218
+ return {text:buffer.subarray(0,offset).toString('utf8')};
219
+ }catch{return null;}
220
+ finally{if(descriptor!==null)try{fs.closeSync(descriptor);}catch{}}
221
+ }
222
+ function readLock(file){const read=readBounded(file,CONTROL_FILE_LIMIT);return read===null||read.missing?null:read.text;}
102
223
  function stale(raw){
103
224
  let value;try{value=JSON.parse(raw);}catch{return false;}
104
225
  if(!Number.isSafeInteger(value?.pid)||!Number.isFinite(value?.at))return false;
@@ -132,8 +253,8 @@ function reserve(home,hash,now){
132
253
  const lock=takeLock(lockFile);if(lock===null)return 'state_busy';
133
254
  try{
134
255
  let state={version:1,keys:{},sends:[]};
135
- try{state=JSON.parse(fs.readFileSync(stateFile,'utf8'));}
136
- catch(error){if(error.code!=='ENOENT')return 'state_invalid';}
256
+ const read=readBounded(stateFile,CONTROL_FILE_LIMIT);if(read===null)return 'state_invalid';
257
+ if(!read.missing){try{state=JSON.parse(read.text);}catch{return 'state_invalid';}}
137
258
  if(!state||state.version!==1||!state.keys||typeof state.keys!=='object'||Array.isArray(state.keys)
138
259
  ||!Array.isArray(state.sends)||!state.sends.every(Number.isFinite)
139
260
  ||!Object.values(state.keys).every(Number.isFinite))return 'state_invalid';
@@ -162,7 +283,7 @@ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_L
162
283
  if(reserved!=='duplicate')appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved}`});
163
284
  return {sent:false,reason:reserved};
164
285
  }
165
- const message=buildNotifyMessage(fields,{now});
286
+ const message=buildNotifyMessage(fields,{now,text:config.text});
166
287
  const payload={...message,event};
167
288
  for(const name of ['project','workflow','runId','task','stage','code','nextAction']){
168
289
  const value=name==='project'?projectName(fields.project):clean(fields[name],name==='nextAction'?200:64);
@@ -283,10 +404,14 @@ const AI_PROGRESS_CODES=new Set(['context_refreshed','context_complete','qa_skip
283
404
  const AI_STUCK_STATES=new Set(['blocked','unknown','pending_review','cancelled','awaiting_spec_approval']);
284
405
  const AI_STUCK_ACTIONS=new Set(['reconcile','abandon_effect','abandon_review','reconcile_review','bootstrap_review_recover',
285
406
  'review_evidence','spec_rebind','fix_authorization','fix_dispatch','qa_execution']);
286
- const AI_STUCK_CODES=new Set(['decision_required','permission_denied','provider_development_authorization_required',
407
+ const AI_STUCK_CODES=new Set(['permission_denied','provider_development_authorization_required',
287
408
  'qa_decision_required','qa_mandatory_required','qa_triggered','qa_blocked','qa_failed','qa_result_blocked',
288
409
  'qa_execution_unknown','correction_review_required','project_qa_not_passed','documentation_sync_blocked',
289
- 'handoff_exists','spec_drift','qa_fix_code_unmatched']);
410
+ 'handoff_exists','spec_drift','qa_fix_code_unmatched',
411
+ // Q23-Q26: QA-fix and batch recovery refusals and stops (host-qa-fix-owner.mjs, cm-ai-batch-run.mjs).
412
+ 'qa_fix_action_authorization_required','batch_member_action_authorization_required','batch_member_action_not_current',
413
+ 'batch_member_action_unavailable','batch_parallel_member_recovery_required','batch_resources_open',
414
+ 'batch_parallel_member_unresolved','batch_member_rescheduled']);
290
415
  function classifyAi(r){
291
416
  const state=text(r.state),code=text(r.code),outcome=text(r.outcome);
292
417
  if(state==='run_done'&&['run_done','run_done_degraded'].includes(code))return 'done';
@@ -312,7 +437,7 @@ const CLASSIFY={
312
437
  'change_rejected','inputs_replaced'].includes(stage))return 'stuck';
313
438
  if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
314
439
  if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'stuck';
315
- if(status&&(/_unknown$/.test(status)||['correction_recovery_required','disposition_details_need_verification'].includes(status)))return 'stuck';
440
+ if(status&&(/_unknown$/.test(status)||['correction_recovery_required','correction_recovery_conflict','disposition_details_need_verification'].includes(status)))return 'stuck';
316
441
  if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
317
442
  if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
318
443
  if(['review_unknown','review_cancelled'].includes(review.status)||review.verdict==='blocked'
@@ -324,7 +449,9 @@ const CLASSIFY={
324
449
  'cm-idea'(r){
325
450
  const stage=text(r.stage),recovery=obj(r.recovery);
326
451
  if(stage==='saved')return 'done';
327
- if(recovery.writing===true||obj(recovery.call).status==='unknown')return 'stuck';
452
+ // A pending call (unknown, or recorded but not yet consumed/refused) waits on
453
+ // resume, abandon or discard; an interrupted save waits on reconciliation.
454
+ if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
328
455
  if(stage==='draft_ready')return r.confirmationRequired===true?null:'stuck';
329
456
  return ['awaiting_user','save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
330
457
  },
@@ -332,7 +459,7 @@ const CLASSIFY={
332
459
  'cm-init'(r){
333
460
  const stage=text(r.stage)??(r.status==='blocked'?'blocked':null),recovery=obj(r.recovery);
334
461
  if(['rules_written','rules_present'].includes(stage))return 'done';
335
- if(recovery.writing===true||obj(recovery.call).status==='unknown')return 'stuck';
462
+ if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
336
463
  return ['analysis_blocked','verification_blocked','confirmation_required','confirmation_rejected','review_changes_requested',
337
464
  'review_blocked','write_incomplete','write_unknown',...STUCK_COMMON].includes(stage)?'stuck':null;
338
465
  },