@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,481 @@
1
+ #!/usr/bin/env node
2
+ // /cm:notify ($cm-notify): pick the one active phone-notice channel (Bark or
3
+ // pushplus), show its state, send one test push, or turn notices off.
4
+ // Secret files are filled by the user; this tool only checks that they parse
5
+ // and never prints, logs or asks for their values.
6
+ // status (default) read-only; writes nothing, not even notify.log
7
+ // bark | pushplus switch after the target's secret parses; else nothing changes
8
+ // off moves notify.json aside to notify.off.json
9
+ // test one real push through the configured command
10
+ // preview read-only; prints each event's title and body from sample fields, sends nothing
11
+ // --replace-custom allow replacing a notify.json command this tool does not manage (backed up first)
12
+ // --json machine-readable status
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import {spawn} from 'node:child_process';
16
+ import {randomUUID} from 'node:crypto';
17
+ import {fileURLToPath} from 'node:url';
18
+ import {parseNotifyConfig,appendNotifyLog,buildNotifyMessage,localClock,NOTIFY_LIMITS} from '../runtime/js/notify.mjs';
19
+ import {CHANNELS,CHANNEL_FILE,SEND_EXIT,SendError,WINDOWS_UNSUPPORTED,NODE_UNSUPPORTED,MAX_FILE_BYTES,notifyHome,readChannel,readSecret,readRegularFile,parseAssignments,buildRequest} from '../runtime/js/notify-send.mjs';
20
+
21
+ export const SENDER_SOURCE=fileURLToPath(new URL('../runtime/js/notify-send.mjs',import.meta.url));
22
+ export const NOTIFY_FILE='notify.json',OFF_FILE='notify.off.json',LEGACY_SCRIPT='cm-notify.py';
23
+ export const managedSenderPath=home=>path.join(home,'notify','cm-notify-send.mjs');
24
+
25
+ export class NotifyCommandError extends Error{constructor(message,exit=2){super(message);this.exit=exit;}}
26
+ const refuse=message=>{throw new NotifyCommandError(message);};
27
+
28
+ // Empty templates with what to fill. `line` is the line the user fills in.
29
+ export const TEMPLATES=Object.freeze({
30
+ bark:{line:5,text:[
31
+ '# CM 提醒 · Bark(iOS)密钥文件。只留在这台电脑上,权限保持 600;不要提交到仓库,也不要贴到对话里。',
32
+ '# Bark App 首页的示例地址形如 https://api.day.app/AbCd1234EfGh/推送内容 。',
33
+ '# BARK_KEY 填 api.day.app/ 后面那一段(8–64 位字母或数字),不是 App 里 64 位十六进制的 Device Token。',
34
+ '# 用自建 Bark 服务时,去掉最后一行开头的 # 并改成你的 https 地址(不带路径,结尾不加 /)。',
35
+ 'BARK_KEY=',
36
+ '# BARK_SERVER=https://api.day.app',''].join('\n')},
37
+ pushplus:{line:3,text:[
38
+ '# CM 提醒 · pushplus(微信)密钥文件。只留在这台电脑上,权限保持 600;不要提交到仓库,也不要贴到对话里。',
39
+ '# 登录 pushplus 官网,在「一对一推送」页复制你的 token(8–128 位字母或数字),填在下一行等号后面。',
40
+ 'PUSHPLUS_TOKEN=',''].join('\n')},
41
+ });
42
+
43
+ function lstat(file){try{return fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}}
44
+ function safeTarget(file){
45
+ const st=lstat(file);
46
+ if(st&&(st.isSymbolicLink()||!st.isFile()))refuse(`拒绝写入:${file} 不是普通文件(可能是符号链接),cm-notify 不会改它`);
47
+ const dir=lstat(path.dirname(file));
48
+ if(dir&&(dir.isSymbolicLink()||!dir.isDirectory()))refuse(`拒绝写入:${path.dirname(file)} 不是普通目录`);
49
+ }
50
+ const readBytes=file=>{try{return fs.readFileSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}};
51
+
52
+ // One secret file's state. Never returns or prints a value.
53
+ // missing / empty / invalid / ok, plus where to fill it.
54
+ // On Windows only the file's existence is reported; its content is never read.
55
+ export async function inspectSecret(home,channel,{platform=process.platform}={}){
56
+ const spec=CHANNELS[channel],file=path.join(home,spec.file);
57
+ if(platform==='win32')return {channel,file,state:lstat(file)?'unchecked':'missing',line:null,name:spec.required,message:WINDOWS_UNSUPPORTED};
58
+ try{await readSecret(home,channel);return {channel,file,state:'ok',line:null,name:spec.required,message:'已填写,可解析'};}
59
+ catch(error){
60
+ if(!(error instanceof SendError))return {channel,file,state:'invalid',line:null,name:spec.required,message:'无法读取'};
61
+ const state=error.detail.state??'invalid',line=error.detail.line??null,name=error.detail.name??spec.required;
62
+ const message=state==='missing'?`${spec.file} 不存在`:error.message;
63
+ return {channel,file,state,line,name,message,reason:error.detail.reason??null};
64
+ }
65
+ }
66
+ // The concrete thing to do, in one sentence, naming the file and the line.
67
+ export function fillHint(info){
68
+ const line=info.state==='missing'?TEMPLATES[info.channel].line:info.line;
69
+ if(info.state==='missing')return `请在 ${info.file} 第 ${line} 行 ${info.name}= 后面填写,再重试`;
70
+ if(info.state==='empty')return line?`请在 ${info.file} 第 ${line} 行 ${info.name}= 后面填写,再重试`
71
+ :`请在 ${info.file} 里加一行 ${info.name}=(等号后填写),再重试`;
72
+ if(info.reason==='permission')return `${info.message};请执行 chmod 600 "${info.file}"(并确认文件归你所有),再重试`;
73
+ return `${info.message};请打开 ${info.file}${line?` 第 ${line} 行`:''}修正,再重试`;
74
+ }
75
+
76
+ async function inspectChannelFile(home,{platform=process.platform}={}){
77
+ const file=path.join(home,CHANNEL_FILE);
78
+ if(!lstat(file))return {file,state:'missing',value:null,message:`${CHANNEL_FILE} 不存在`};
79
+ // The channel file holds no secret; on Windows it is shown through the same
80
+ // safe read boundary minus the owner/mode rule (never through a symlink).
81
+ if(platform==='win32'){
82
+ try{
83
+ const {values}=parseAssignments(await readRegularFile(file,CHANNEL_FILE),['CHANNEL'],CHANNEL_FILE);
84
+ return Object.hasOwn(CHANNELS,values.CHANNEL??'')?{file,state:'ok',value:values.CHANNEL,message:'可解析'}
85
+ :{file,state:'invalid',value:null,message:`${CHANNEL_FILE} 的 CHANNEL 只能是 bark 或 pushplus`};
86
+ }catch(error){return {file,state:'invalid',value:null,message:error instanceof SendError?error.message:'无法读取'};}
87
+ }
88
+ try{return {file,state:'ok',value:await readChannel(home),message:'可解析'};}
89
+ catch(error){return {file,state:'invalid',value:null,message:error instanceof SendError?error.message:'无法读取'};}
90
+ }
91
+
92
+ // Shape only. Managed: exactly [<absolute node>, <home>/notify/cm-notify-send.mjs].
93
+ // Legacy: exactly [<home>/cm-notify.py]. Anything else is the user's own command.
94
+ const NODE_NAME=/^node(?:\.exe)?$/i;
95
+ export function classifyCommand(home,command){
96
+ if(!Array.isArray(command)||!command.every(item=>typeof item==='string'))return 'custom';
97
+ if(command.length===2&&path.isAbsolute(command[0])&&NODE_NAME.test(path.basename(command[0]))
98
+ &&path.isAbsolute(command[1])&&path.resolve(command[1])===managedSenderPath(home))return 'managed';
99
+ if(command.length===1&&path.isAbsolute(command[0])&&path.resolve(command[0])===path.join(home,LEGACY_SCRIPT))return 'legacy';
100
+ return 'custom';
101
+ }
102
+ // notify.json and notify.off.json are read only through the safe boundary
103
+ // (never via a symlink, regular file, size cap, same file object), as exact
104
+ // bytes so the content matches what the runtime sees. null = no such file.
105
+ const UNSAFE_REASON={permission:'not_regular_file',too_large:'too_large'};
106
+ async function readConfigBytes(file){
107
+ try{return {bytes:await readRegularFile(file,path.basename(file),{bytes:true})};}
108
+ catch(error){
109
+ if(error instanceof SendError&&error.detail.state==='missing')return {bytes:null};
110
+ return {bytes:null,reason:error instanceof SendError?UNSAFE_REASON[error.detail.reason]??'unreadable':'unreadable'};
111
+ }
112
+ }
113
+ // notify.json is read once per operation; `test` runs exactly this snapshot.
114
+ async function loadConfig(home){
115
+ const file=path.join(home,NOTIFY_FILE),off=path.join(home,OFF_FILE);
116
+ const {bytes,reason}=await readConfigBytes(file);
117
+ if(reason)return {file,state:'invalid',reason,command:null};
118
+ if(bytes===null)return {file,state:lstat(off)?'off':'missing',command:null};
119
+ const parsed=parseNotifyConfig(bytes.toString('utf8'));
120
+ if(parsed.reason)return {file,state:'invalid',reason:parsed.reason,command:null};
121
+ const {command,text}=parsed.config;
122
+ // Optional custom text: default, custom, or invalid (then the default text is used).
123
+ const textState=parsed.textReason?'invalid':text?'custom':'default';
124
+ return {file,state:classifyCommand(home,command),command,textState,...(parsed.textReason?{textReason:parsed.textReason}:{}),textSpec:text??null};
125
+ }
126
+ // Status view of a snapshot; neither the command (custom arguments may hold
127
+ // anything) nor the custom strings are included.
128
+ function describeConfig(home,{command,textSpec,...snapshot},{senderSource=SENDER_SOURCE}={}){
129
+ const result={...snapshot};
130
+ if(!command)return result;
131
+ Object.assign(result,{program:command[0],programExists:Boolean(lstat(command[0]))});
132
+ if(result.state==='managed'){
133
+ const installed=readBytes(managedSenderPath(home)),source=readBytes(senderSource);
134
+ Object.assign(result,{sender:managedSenderPath(home),senderExists:installed!==null,
135
+ senderCurrent:installed!==null&&source!==null&&installed.equals(source)});
136
+ }
137
+ return result;
138
+ }
139
+ const inspectConfig=async(home,options)=>describeConfig(home,await loadConfig(home),options);
140
+
141
+ export async function notifyStatus(home,{platform=process.platform,...options}={}){
142
+ const config=await inspectConfig(home,options),channelFile=await inspectChannelFile(home,{platform});
143
+ const channels={};for(const name of Object.keys(CHANNELS))channels[name]=await inspectSecret(home,name,{platform});
144
+ const active=platform!=='win32'&&['managed','legacy'].includes(config.state)&&channelFile.state==='ok'?channelFile.value:null;
145
+ return {home,platform,config,channelFile,channels,active};
146
+ }
147
+
148
+ const UNSAFE_WORD={not_regular_file:'notify.json 不是普通文件(可能是符号链接),cm-notify 不读取它,无法确认提醒是否生效',
149
+ too_large:'notify.json 超过 64 KiB,cm-notify 不读取它,无法确认提醒是否生效'};
150
+ const STATE_WORD={missing:'未填写(文件不存在)',empty:'未填写',invalid:'格式不对',ok:'已填写,可解析',unchecked:'文件存在(Windows 上不读取内容,无法判断是否填好)'};
151
+ export function formatStatus(status){
152
+ const {config,channelFile,channels,active}=status,lines=[`CM 提醒设置(目录 ${status.home})`];
153
+ const windows=status.platform==='win32';
154
+ if(windows)lines.push(WINDOWS_UNSUPPORTED);
155
+ const describe={
156
+ managed:'CM 托管发送器',
157
+ legacy:`旧版本机脚本 ${LEGACY_SCRIPT}(读同一组文件;下次切换渠道时自动换成托管发送器,原脚本不动)`,
158
+ custom:'自定义命令(cm-notify 不管理,切换渠道不会改它,除非加 --replace-custom)',
159
+ missing:'未开启(没有 notify.json)',
160
+ off:`已关闭(配置已移到 ${OFF_FILE},切换渠道即重新开启)`,
161
+ invalid:UNSAFE_WORD[config.reason]??`notify.json 无效(${config.reason}),提醒实际关闭`};
162
+ lines.push(`发送命令:${describe[config.state]}`);
163
+ if(['managed','legacy','custom'].includes(config.state)&&!config.programExists)
164
+ lines.push(` 警告:命令程序 ${config.program} 不存在(node 可能已移动或升级),重新执行 /cm:notify <渠道> 修复`);
165
+ if(config.state==='managed'&&!config.senderExists)lines.push(' 警告:托管发送器文件缺失,重新执行 /cm:notify <渠道> 修复');
166
+ else if(config.state==='managed'&&!config.senderCurrent)lines.push(' 提示:托管发送器与当前插件版本不同,重新执行 /cm:notify <渠道> 更新');
167
+ if(config.textState)lines.push(textLine(config));
168
+ const chosen=channelFile.state==='ok'?channelFile.value:null;
169
+ lines.push(`当前渠道:${active?`${active}(生效中)`:chosen&&windows?`${chosen}(Windows 上不会发送)`:chosen?`${chosen}(未生效:${describe[config.state]})`
170
+ :channelFile.state==='missing'?'未选择':`无法确定:${channelFile.message}`}`);
171
+ for(const [name,info] of Object.entries(channels)){
172
+ const mark=name===active?'[当前]':'';
173
+ lines.push(`渠道 ${name}${mark}:${STATE_WORD[info.state]} — ${info.file}`);
174
+ if(info.state!=='ok'&&!windows)lines.push(` ${fillHint(info)}`);
175
+ }
176
+ lines.push('密钥只由你自己编辑上面的文件填写;本工具不读出、不显示其中的值。');
177
+ return lines.join('\n');
178
+ }
179
+
180
+ const textLine=config=>config.textState==='custom'?'文案:自定义(/cm:notify preview 查看效果)'
181
+ :config.textState==='invalid'?`文案:默认(notify.json 里的 text 无效:${config.textReason},已改用默认文案,提醒照常发送)`:'文案:默认';
182
+
183
+ // Read-only preview of every event's title and body under the current
184
+ // notify.json text, built from fixed sample fields. Sends and logs nothing.
185
+ const PREVIEW_SAMPLE=Object.freeze({project:'demo-app',workflow:'cm-ai',runId:'run-sample-1',task:'T-001'});
186
+ export const PREVIEW_EVENTS=Object.freeze([
187
+ {event:'stuck',name:'卡住,需要人处理',stage:'blocked',code:'checks_not_passed',nextAction:'核对原因后恢复原运行'},
188
+ {event:'waiting',name:'等待会话应答',stage:'check',code:'waiting_session_answer',nextAction:'宿主已等待会话应答约 10 分钟,请回到会话处理'},
189
+ {event:'idle',name:'疑似空转',stage:'requirements_analysis',code:'no_next_step',nextAction:'上一步已结束约 45 分钟,会话没有发下一步,请回到会话查看'},
190
+ {event:'idle_waiting',name:'在等你',stage:'blocked',code:'waiting_for_you',nextAction:'上一步停在需要你处理的状态,约 45 分钟没有下一步,请回到会话处理'},
191
+ {event:'dead',name:'宿主已退出未收尾',stage:'1 个宿主进程已不在',code:'host_process_gone',nextAction:'请回到会话用 status 核对运行状态,需要时按恢复说明接手'},
192
+ {event:'done',name:'流程已结束',stage:'run_done',code:'run_done',nextAction:'建议在新会话里开始下一个任务,减少重复读入的上下文'}]);
193
+ export async function previewText(home,{now=Date.now(),timeZone}={}){
194
+ const {state,textState=null,textReason=null,textSpec=null}=await loadConfig(home);
195
+ const messages=PREVIEW_EVENTS.map(({name,...fields})=>({event:fields.event,name,
196
+ ...buildNotifyMessage({...PREVIEW_SAMPLE,...fields},{now,timeZone,text:textSpec})}));
197
+ return {state,textState,textReason,messages};
198
+ }
199
+ export function formatPreview(preview){
200
+ const head=preview.textState?textLine(preview).replace('(/cm:notify preview 查看效果)','')
201
+ :`文案:默认(${preview.state==='invalid'?'notify.json 无效':'没有生效的 notify.json'},按默认文案预览)`;
202
+ const lines=[`提醒文案预览,用示例字段生成,不发送。${head}`];
203
+ for(const message of preview.messages)lines.push('',`【${message.name}】${message.event}`,`标题:${message.title}`,message.body);
204
+ return lines.join('\n');
205
+ }
206
+
207
+ function backupName(file,now){
208
+ const stamp=new Date(now).toISOString().replace(/[-:]/g,'').replace(/\.\d+Z$/,'Z');
209
+ let candidate=`${file}.bak-${stamp}`;
210
+ if(lstat(candidate))candidate=`${candidate}-${randomUUID().slice(0,8)}`;
211
+ return candidate;
212
+ }
213
+ // File-system calls used for writes; tests inject faults here, nothing else does.
214
+ const FS_OPS=Object.freeze({writeFileSync:fs.writeFileSync,renameSync:fs.renameSync,unlinkSync:fs.unlinkSync,chmodSync:fs.chmodSync});
215
+ function writeAtomic(file,data,mode=0o600,ops=FS_OPS){
216
+ safeTarget(file);
217
+ fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
218
+ const temp=path.join(path.dirname(file),`.${path.basename(file)}.${randomUUID()}.tmp`);
219
+ try{ops.writeFileSync(temp,data,{flag:'wx',mode});try{ops.chmodSync(temp,mode);}catch{}ops.renameSync(temp,file);}
220
+ finally{try{fs.unlinkSync(temp);}catch{}}
221
+ }
222
+ // All-or-nothing over a few files. On a failure every file already written is
223
+ // put back from the previous bytes held in memory. No extra copies are made:
224
+ // a file that cannot be put back is reported by path, never silently kept.
225
+ class ApplyError extends Error{constructor(cause,restored,unrestored){super(cause);Object.assign(this,{restored,unrestored});}}
226
+ // An item may carry `before` already read through the safe boundary.
227
+ function applyAll(writes,{ops=FS_OPS}={}){
228
+ const done=[];let failedFile=null;
229
+ try{
230
+ for(const item of writes){failedFile=item.file;const before=Object.hasOwn(item,'before')?item.before:readBytes(item.file);writeAtomic(item.file,item.data,item.mode,ops);done.push({file:item.file,before});}
231
+ }catch(error){
232
+ const restored=[],unrestored=[];
233
+ for(const {file,before} of done.reverse()){
234
+ try{if(before===null)ops.unlinkSync(file);else writeAtomic(file,before,0o600,ops);restored.push(file);}
235
+ catch(restoreError){unrestored.push({file,code:restoreError.code??'error',created:before===null,keptAt:null});}
236
+ }
237
+ throw new ApplyError(error instanceof NotifyCommandError?error.message:`写 ${failedFile} 时失败(${error.code??'error'})`,restored,unrestored);
238
+ }
239
+ }
240
+ function rollbackMessage({message,restored,unrestored}){
241
+ if(!unrestored.length)return Object.assign(new NotifyCommandError(`切换失败:${message};已写入的文件都已恢复原样`),{restored,unrestored});
242
+ const lines=unrestored.map(entry=>entry.created?`${entry.file} 是这次新建的,没能删除(${entry.code})`
243
+ :entry.renamedFrom?`${entry.file} 没能改回原名(${entry.code}),原内容仍在 ${entry.keptAt}`
244
+ :`${entry.file} 没能恢复(${entry.code}),原内容${entry.keptAt?`仍在 ${entry.keptAt}`:'没有留在磁盘上'}`);
245
+ return Object.assign(new NotifyCommandError(`切换失败:${message};并且有文件没能恢复,需要你手动处理:${lines.join(';')}`
246
+ +`${restored.length?`。已恢复:${restored.join('、')}`:''}`),{restored,unrestored});
247
+ }
248
+
249
+ // Creates an empty 0600 template only when the file does not exist at all.
250
+ export function ensureTemplate(home,channel){
251
+ const file=path.join(home,CHANNELS[channel].file);
252
+ if(lstat(file))return false;
253
+ fs.mkdirSync(home,{recursive:true,mode:0o700});
254
+ try{fs.writeFileSync(file,TEMPLATES[channel].text,{flag:'wx',mode:0o600});}catch(error){if(error.code==='EEXIST')return false;throw error;}
255
+ try{fs.chmodSync(file,0o600);}catch{}
256
+ return true;
257
+ }
258
+
259
+ export async function switchChannel(home,channel,{platform=process.platform,replaceCustom=false,execPath=process.execPath,senderSource=SENDER_SOURCE,now=Date.now(),ops=FS_OPS}={}){
260
+ if(platform==='win32')refuse(WINDOWS_UNSUPPORTED);
261
+ if(!Object.hasOwn(CHANNELS,channel))refuse(`未知渠道 ${channel},只能是 bark 或 pushplus`);
262
+ const target=await inspectSecret(home,channel);
263
+ if(target.state!=='ok'){
264
+ const created=target.state==='missing'&&ensureTemplate(home,channel);
265
+ refuse(`没有切换到 ${channel},原有设置都没动:${STATE_WORD[target.state]}。${created?`已新建空模板 ${target.file}(权限 600)。`:''}${fillHint(target)}`);
266
+ }
267
+ if(!path.isAbsolute(execPath))refuse('当前 node 路径不是绝对路径,无法写入发送命令');
268
+ const file=path.join(home,NOTIFY_FILE),offFile=path.join(home,OFF_FILE);
269
+ for(const item of [file,offFile,path.join(home,CHANNEL_FILE),managedSenderPath(home)])safeTarget(item);
270
+ const fromOff=!lstat(file)&&Boolean(lstat(offFile));
271
+ const baseFile=fromOff?offFile:file,baseRead=await readConfigBytes(baseFile),baseRaw=baseRead.bytes;
272
+ if(baseRead.reason)refuse(`${baseFile} ${baseRead.reason==='too_large'?'超过 64 KiB':'不是普通文件(可能是符号链接)或无法安全读取'},cm-notify 不会改它`);
273
+ let base={version:1};
274
+ if(baseRaw!==null){
275
+ try{base=JSON.parse(baseRaw.toString('utf8'));}catch{refuse(`${baseFile} 不是有效 JSON,cm-notify 不会改它;请先修好或移走`);}
276
+ if(!base||typeof base!=='object'||Array.isArray(base))refuse(`${baseFile} 不是 JSON 对象,cm-notify 不会改它`);
277
+ if(base.version!==undefined&&base.version!==1)refuse(`${baseFile} 的 version 不是 1,cm-notify 不会改它`);
278
+ }
279
+ const kind=Object.hasOwn(base,'command')?classifyCommand(home,base.command):'none';
280
+ if(kind==='custom'&&!replaceCustom)
281
+ refuse(`没有切换:${baseFile} 里是你自己配置的提醒命令,cm-notify 不会静默覆盖。确认要换成 CM 托管发送器时,加 --replace-custom 重试(原文件会改名备份)`);
282
+ const source=readBytes(senderSource);
283
+ if(source===null)refuse('插件里找不到发送器 runtime/js/notify-send.mjs,请重新安装 CM Workflow');
284
+ const sender=managedSenderPath(home);
285
+ const next={...base,version:1,command:[execPath,sender]};
286
+ const checked=parseNotifyConfig(JSON.stringify(next));
287
+ if(checked.reason)refuse(`没有切换:${baseFile} 里其他字段无效(${checked.reason}),请先修好`);
288
+ // The rewritten file (re-indented, new command) must stay readable by this
289
+ // tool: checked on the exact bytes, before any backup or write.
290
+ const data=`${JSON.stringify(next,null,2)}\n`,size=Buffer.byteLength(data);
291
+ if(size>MAX_FILE_BYTES)refuse(`没有切换:改写后的 notify.json 会有 ${size} 字节,超过 ${MAX_FILE_BYTES} 字节(64 KiB)的读取上限;请先精简 ${baseFile}(如缩短 text、删掉不用的字段),原有文件都没动`);
292
+ // A replaced custom or legacy config is backed up by renaming the original
293
+ // file (its permissions/ACL travel with it), never by copying its content.
294
+ let backup=null;
295
+ if(baseRaw!==null&&(kind==='custom'||kind==='legacy')){
296
+ backup=backupName(baseFile,now);
297
+ try{ops.renameSync(baseFile,backup);}
298
+ catch(error){refuse(`没有切换:备份 ${baseFile} 失败(${error.code??'error'}),什么都没改`);}
299
+ }
300
+ try{
301
+ // notify.json's previous bytes (for rollback) come through the safe boundary too.
302
+ const current=await readConfigBytes(file);
303
+ if(current.reason)throw new ApplyError(`${file} 不是普通文件或无法安全读取,没有写入`,[],[]);
304
+ applyAll([
305
+ {file:sender,data:source,mode:0o600},
306
+ {file:path.join(home,CHANNEL_FILE),data:`# CM 提醒渠道,由 /cm:notify 维护;同一时刻只开一个:bark 或 pushplus\nCHANNEL=${channel}\n`,mode:0o600},
307
+ {file,data,mode:0o600,before:current.bytes},
308
+ ],{ops});
309
+ }catch(error){
310
+ if(!(error instanceof ApplyError))throw error;
311
+ // Put the renamed original back. If the new notify.json could not be removed
312
+ // the rename would overwrite it; either way the result is reported exactly.
313
+ if(backup){
314
+ try{ops.renameSync(backup,baseFile);error.restored.push(baseFile);}
315
+ catch(renameError){error.unrestored.push({file:baseFile,code:renameError.code??'error',created:false,renamedFrom:true,keptAt:backup});}
316
+ }
317
+ throw rollbackMessage(error);
318
+ }
319
+ if(fromOff&&!backup)try{fs.unlinkSync(offFile);}catch{}
320
+ return {channel,file,sender,node:execPath,replaced:kind,backup,fromOff,textReason:checked.textReason??null};
321
+ }
322
+
323
+ // `ops` lets tests inject file-system faults; nothing else passes it.
324
+ export function turnOff(home,{now=Date.now(),ops={renameSync:fs.renameSync}}={}){
325
+ const file=path.join(home,NOTIFY_FILE),offFile=path.join(home,OFF_FILE);
326
+ safeTarget(file);safeTarget(offFile);
327
+ if(!lstat(file))return {changed:false};
328
+ let backup=null;
329
+ if(lstat(offFile)){
330
+ backup=backupName(offFile,now);
331
+ try{ops.renameSync(offFile,backup);}
332
+ catch(error){throw new NotifyCommandError(`关闭失败(${error.code??'error'}):什么都没改,提醒仍开启`);}
333
+ }
334
+ try{ops.renameSync(file,offFile);}
335
+ catch(error){
336
+ const code=error.code??'error';
337
+ if(!backup)throw new NotifyCommandError(`关闭失败(${code}):notify.json 仍在原处,提醒仍开启;其他文件没改`);
338
+ try{ops.renameSync(backup,offFile);}
339
+ catch(restoreError){
340
+ throw new NotifyCommandError(`关闭失败(${code}):notify.json 仍在原处,提醒仍开启;原来的 ${offFile} 已移到 ${backup},`
341
+ +`放回时也失败(${restoreError.code??'error'}),请手动把它改回 ${OFF_FILE}`);
342
+ }
343
+ throw new NotifyCommandError(`关闭失败(${code}):notify.json 仍在原处,提醒仍开启;原来的 ${OFF_FILE} 已放回原处`);
344
+ }
345
+ return {changed:true,offFile,backup};
346
+ }
347
+
348
+ // Runs the configured command exactly as the runtime does (no shell, message
349
+ // in CM_NOTIFY_TITLE/CM_NOTIFY_BODY, one JSON line on stdin, killed after 15 s),
350
+ // but in the foreground so the result can be reported. A test push bypasses
351
+ // dedupe and rate limits (it is one explicit request) and is not counted.
352
+ // Runs the configured command exactly as the runtime does (no shell, message
353
+ // in CM_NOTIFY_TITLE/CM_NOTIFY_BODY, one JSON line on stdin, killed after 15 s),
354
+ // in the foreground. It runs the same notify.json snapshot that was checked.
355
+ // Its output is never read or relayed, for any command type; only the exit
356
+ // code is reported. NODE_OPTIONS is removed so no preload can run first.
357
+ // A test push bypasses dedupe and rate limits and is not counted.
358
+ // With CM_NOTIFY_DRY_RUN=1 nothing is run and the secret file is not opened or
359
+ // checked at all: the redacted request is built here from the channel file only.
360
+ export async function sendTest(home,{platform=process.platform,env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,beforeSpawn}={}){
361
+ if(platform==='win32')refuse(WINDOWS_UNSUPPORTED);// also covers dry-run
362
+ const snapshot=await loadConfig(home),config=describeConfig(home,snapshot);
363
+ if(config.state==='missing'||config.state==='off')refuse('提醒未开启:先执行 /cm:notify bark 或 /cm:notify pushplus');
364
+ if(config.state==='invalid')refuse(`notify.json 无效(${config.reason}),先修好或重新选择渠道`);
365
+ const dry=env.CM_NOTIFY_DRY_RUN==='1';
366
+ if(dry&&config.state==='custom')refuse('演练模式只适用于 bark / pushplus 渠道;自定义命令不会被运行');
367
+ let channel=null;
368
+ if(config.state!=='custom'){
369
+ const channelFile=await inspectChannelFile(home);
370
+ if(channelFile.state!=='ok')refuse(`没有发送:${channelFile.message},重新执行 /cm:notify bark 或 pushplus`);
371
+ channel=channelFile.value;
372
+ }
373
+ if(channel&&!dry){
374
+ const secret=await inspectSecret(home,channel);
375
+ if(secret.state!=='ok')refuse(`没有发送:当前渠道 ${channel} ${STATE_WORD[secret.state]}。${fillHint(secret)}`);
376
+ }
377
+ const title='CM 测试推送',body=`这是 /cm:notify test 发出的测试消息。\n时间:${localClock(now)}`;
378
+ if(dry){
379
+ const {url,payload}=await buildRequest(channel,{home,env:{CM_NOTIFY_TITLE:title,CM_NOTIFY_BODY:body},dry:true});
380
+ return {kind:config.state,channel,dry:true,preview:`POST ${url}\n${JSON.stringify(payload)}`};
381
+ }
382
+ if(!config.programExists)refuse(`没有发送:命令程序 ${config.program} 不存在,重新执行 /cm:notify ${channel??'<渠道>'} 修复`);
383
+ if(config.state==='managed'&&!config.senderExists)refuse(`没有发送:托管发送器缺失,重新执行 /cm:notify ${channel} 修复`);
384
+ const command=[...snapshot.command];
385
+ beforeSpawn?.();
386
+ const childEnv={...env,CM_NOTIFY_TITLE:title,CM_NOTIFY_BODY:body};
387
+ delete childEnv.CM_NOTIFY_PAYLOAD;delete childEnv.NODE_OPTIONS;
388
+ const result=await new Promise(resolve=>{
389
+ let child,settled=false;
390
+ const finish=value=>{if(!settled){settled=true;clearTimeout(timer);resolve(value);}};
391
+ const timer=setTimeout(()=>{try{child?.kill('SIGKILL');}catch{}finish({exit:null,reason:'timeout'});},timeoutMs);
392
+ try{child=spawn(command[0],command.slice(1),{stdio:['pipe','ignore','ignore'],shell:false,windowsHide:true,env:childEnv});}
393
+ catch(error){finish({exit:null,reason:`spawn_${String(error.code??'failed').toLowerCase()}`});return;}
394
+ child.on('error',error=>finish({exit:null,reason:`spawn_${String(error.code??'failed').toLowerCase()}`}));
395
+ child.on('close',(code,signal)=>finish({exit:code,reason:signal?`signal_${signal}`:null}));
396
+ child.stdin.on('error',()=>{});
397
+ child.stdin.end(`${JSON.stringify({title,body,event:'test',workflow:'cm-notify'})}\n`);
398
+ });
399
+ appendNotifyLog(home,now,{event:'test',workflow:'cm-notify',result:result.exit===0?'test ok':`test failed ${result.exit===null?result.reason:`exit_${result.exit}`}`});
400
+ return {kind:config.state,channel,dry:false,exit:result.exit,reason:result.reason,...(config.state==='managed'?{senderCurrent:config.senderCurrent===true}:{})};
401
+ }
402
+
403
+ // Custom and legacy commands, and a managed sender copied by an older plugin,
404
+ // keep the original words: there 3 may also be a timeout and 5/6 mean nothing.
405
+ export const COMMAND_EXIT_WORDS=Object.freeze({
406
+ [SEND_EXIT.ok]:'已被推送服务接受(不代表已送达)',
407
+ [SEND_EXIT.config]:'配置或密钥问题',
408
+ [SEND_EXIT.network]:'网络失败或超时',
409
+ [SEND_EXIT.rejected]:'服务端拒绝',
410
+ });
411
+ // Only the managed sender identical to this plugin's copy splits 3/5/6.
412
+ export const EXIT_WORDS=Object.freeze({
413
+ ...COMMAND_EXIT_WORDS,
414
+ [SEND_EXIT.network]:'网络请求失败',
415
+ [SEND_EXIT.deadline]:'超过 12 秒期限(可能已送达)',
416
+ [SEND_EXIT.unexpected]:'意外错误',
417
+ });
418
+ export function formatTest(result){
419
+ const who=result.kind==='custom'?'自定义命令':`渠道 ${result.channel}`;
420
+ if(result.dry)return `${who}:演练模式(CM_NOTIFY_DRY_RUN=1),没有运行发送命令、没有联网,也没有读取或检查密钥文件(是否填好请用 /cm:notify 查看);下面是按渠道设置生成的脱敏请求。\n${result.preview}`;
421
+ const stale=result.kind==='managed'&&result.senderCurrent!==true;
422
+ const hint=stale?`托管发送器与当前插件版本不同,退出码按旧含义解释;重新执行 /cm:notify ${result.channel} 更新。`:'';
423
+ if(result.exit===null)return `${who}:命令没有正常结束(${result.reason}),未知。${hint}`;
424
+ const words=result.kind==='managed'&&!stale?EXIT_WORDS:COMMAND_EXIT_WORDS;
425
+ return `${who}:退出码 ${result.exit},${words[result.exit]??'未知'}。${hint}`;
426
+ }
427
+
428
+ const USAGE='用法:cm-notify.mjs [status|bark|pushplus|off|test|preview] [--replace-custom] [--json]';
429
+ export async function main(argv=process.argv.slice(2),{env=process.env,stdout=process.stdout,stderr=process.stderr,platform=process.platform}={}){
430
+ const say=(stream,text)=>stream.write(`${text}\n`);
431
+ // First action: on Windows everything except status, off and preview is refused
432
+ // before any file is touched (argument parsing only).
433
+ const first=argv.find(arg=>!arg.startsWith('--'))??'status';
434
+ if(platform==='win32'&&!['status','off','preview'].includes(first)){say(stderr,`cm-notify: ${WINDOWS_UNSUPPORTED}`);return 2;}
435
+ // Under node --test only an explicit CM_WORKFLOW_HOME is allowed: the real
436
+ // home would push to the user's phone.
437
+ if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME){say(stderr,'cm-notify: 测试环境必须设置 CM_WORKFLOW_HOME');return 2;}
438
+ const flags=new Set(argv.filter(arg=>arg.startsWith('--'))),words=argv.filter(arg=>!arg.startsWith('--'));
439
+ const unknown=[...flags].filter(flag=>!['--replace-custom','--json'].includes(flag));
440
+ const sub=words[0]??'status';
441
+ if(unknown.length||words.length>1||!['status','bark','pushplus','off','test','preview'].includes(sub)){say(stderr,USAGE);return 2;}
442
+ const home=notifyHome(env);
443
+ try{
444
+ if(sub==='status'){
445
+ const status=await notifyStatus(home,{platform});
446
+ say(stdout,flags.has('--json')?JSON.stringify(status,null,2):formatStatus(status));return 0;
447
+ }
448
+ if(sub==='preview'){
449
+ const preview=await previewText(home);
450
+ say(stdout,flags.has('--json')?JSON.stringify(preview,null,2):formatPreview(preview));return 0;
451
+ }
452
+ if(sub==='off'){
453
+ const result=turnOff(home);
454
+ say(stdout,result.changed?`提醒已关闭:notify.json 已移到 ${result.offFile};渠道设置和密钥文件都保留,/cm:notify bark 或 pushplus 重新开启。${result.backup?`之前的 ${OFF_FILE} 已备份到 ${result.backup}。`:''}`
455
+ :'提醒本来就没有开启,什么都没改。');
456
+ return 0;
457
+ }
458
+ if(sub==='test'){
459
+ const result=await sendTest(home,{env,platform});
460
+ say(stdout,formatTest(result));
461
+ return result.dry?0:result.exit===null?SEND_EXIT.network:result.exit;
462
+ }
463
+ const result=await switchChannel(home,sub,{platform,replaceCustom:flags.has('--replace-custom')});
464
+ const lines=[`已切换到 ${result.channel}(同一时刻只开这一个渠道)。`,
465
+ `发送命令:${result.node} ${result.sender}`];
466
+ if(result.backup)lines.push(`原配置文件已改名备份为 ${result.backup}${result.replaced==='legacy'?`(原 ${LEGACY_SCRIPT} 未改动)`:''}`);
467
+ if(result.fromOff)lines.push(`已从 ${OFF_FILE} 恢复其他设置。`);
468
+ if(result.textReason)lines.push(`提示:notify.json 里的 text 无效(${result.textReason}),提醒使用默认文案;/cm:notify preview 可查看。`);
469
+ lines.push('node 移动或升级后,再执行一次本命令即可修复路径。发一条测试推送:/cm:notify test');
470
+ say(stdout,lines.join('\n'));return 0;
471
+ }catch(error){
472
+ if(error instanceof NotifyCommandError){say(stderr,`cm-notify: ${error.message}`);return error.exit;}
473
+ say(stderr,`cm-notify: 意外错误(${error?.code??'error'}),没有显示详情以免带出密钥`);return 3;
474
+ }
475
+ }
476
+
477
+ // Entry detection uses import.meta.main only (no file-system access, symlinked
478
+ // entries work). No version number is checked; the plugin requires Node 24.14+,
479
+ // and only a missing import.meta.main is detected here: exit 3.
480
+ if(import.meta.main===undefined){process.stderr.write(`${NODE_UNSUPPORTED}\n`);process.exitCode=3;}
481
+ else if(import.meta.main)main().then(code=>{process.exitCode=code;});