@aibyzero/cm-workflow 0.16.7 → 0.16.9

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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,312 @@
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 3; 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 or
16
+ // timeout (also any unexpected error); 4 server rejected or odd response.
17
+ // CM_NOTIFY_DRY_RUN=1: opens no secret file, no network, prints a redacted request.
18
+ // --check: only verifies that the active channel's files parse; sends nothing.
19
+ import fs from 'node:fs';
20
+ import fsp from 'node:fs/promises';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import https from 'node:https';
24
+ import {performance} from 'node:perf_hooks';
25
+ import {fileURLToPath} from 'node:url';
26
+
27
+ // Process entry, first: record the start and decide from import.meta.main
28
+ // alone (no file-system access; symlinked entries work too). The plugin needs
29
+ // Node 24.14+; no version number is checked here. Only a missing
30
+ // import.meta.main is detected, and then the process ends with 3 rather than
31
+ // doing nothing. When run directly the
32
+ // 12 s hard timer is armed next, and on Windows the very next action is the
33
+ // refusal (exit 2), before anything reads a file. The timer is not unref'd:
34
+ // the process ends with 3 at the deadline even if some work never settles.
35
+ export const WINDOWS_UNSUPPORTED='/cm:notify 暂不支持 Windows:密钥文件权限核对尚未在 Windows 实机验证';
36
+ export const NODE_UNSUPPORTED='cm-notify: 当前 Node 没有 import.meta.main,不受支持(插件要求 Node 24.14 或更高版本),没有发送';
37
+ export function entryDecision(main,platform){
38
+ if(main===undefined)return 'unsupported_node';
39
+ if(main!==true)return 'imported';
40
+ return platform==='win32'?'windows':'run';
41
+ }
42
+ const ENTRY_STARTED_AT=performance.now();
43
+ const ENTRY=entryDecision(import.meta.main,process.platform);
44
+ const armHardTimer=(deadlineMs,startedAt)=>setTimeout(()=>{
45
+ try{process.stderr.write(`cm-notify: 整次调用超过 ${Math.ceil(deadlineMs/1000)} 秒,已放弃\n`);}catch{}process.exit(3);
46
+ },Math.max(0,deadlineMs-(performance.now()-startedAt)));
47
+ if(ENTRY==='unsupported_node'){try{process.stderr.write(`${NODE_UNSUPPORTED}\n`);}catch{}process.exit(3);}
48
+ const ENTRY_HARD_TIMER=ENTRY==='run'||ENTRY==='windows'?armHardTimer(12000,ENTRY_STARTED_AT):null;
49
+ if(ENTRY==='windows'){try{process.stderr.write(`cm-notify: ${WINDOWS_UNSUPPORTED}\n`);}catch{}process.exit(2);}
50
+
51
+ export const SEND_EXIT=Object.freeze({ok:0,config:2,network:3,rejected:4});
52
+ export const DEADLINE_MS=12000;
53
+ const MAX_FILE=64*1024,MAX_RESPONSE=64*1024,MAX_STDIN=64*1024;
54
+ // Largest file the safe read boundary accepts; /cm:notify never writes a bigger notify.json.
55
+ export const MAX_FILE_BYTES=MAX_FILE;
56
+ export const CHANNEL_FILE='notify-channel.conf';
57
+ export const CHANNELS=Object.freeze({
58
+ bark:Object.freeze({file:'bark.env',names:['BARK_KEY','BARK_SERVER'],required:'BARK_KEY'}),
59
+ pushplus:Object.freeze({file:'pushplus.env',names:['PUSHPLUS_TOKEN'],required:'PUSHPLUS_TOKEN'}),
60
+ });
61
+ export const BARK_DEFAULT_SERVER='https://api.day.app';
62
+ export const PUSHPLUS_URL='https://www.pushplus.plus/send';
63
+ const BARK_KEY=/^[A-Za-z0-9]{8,64}$/,DEVICE_TOKEN=/^[0-9a-fA-F]{64}$/,PUSHPLUS_TOKEN=/^[A-Za-z0-9]{8,128}$/;
64
+ const HTTPS_ORIGIN=/^https:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$/;
65
+
66
+ export class SendError extends Error{
67
+ constructor(exit,message,detail={}){super(message);this.exit=exit;this.detail=detail;}
68
+ }
69
+ const configError=(message,detail)=>new SendError(SEND_EXIT.config,message,detail);
70
+
71
+ export function notifyHome(env=process.env){
72
+ return path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
73
+ }
74
+
75
+ // Windows is refused until owner/ACL verification bound to the opened handle
76
+ // has been built and tested on a real machine (see docs/next-steps.md).
77
+ const windowsRefusal=()=>configError(WINDOWS_UNSUPPORTED,{state:'unsupported'});
78
+
79
+ // Safe read boundary used for every file this tool reads: lstat must show a
80
+ // regular file (never a symlink), the size is capped, the opened handle must be
81
+ // the same file object (dev+ino), and content is read from that handle only.
82
+ // `privateFile` adds: owned by this user, no group/other mode bits.
83
+ // `budget` (from runSender) returns the milliseconds left and throws once the
84
+ // total deadline has passed. `fileOps` (lstat/open) is replaceable only through
85
+ // this module API, so tests can simulate slow reads. `bytes` returns the exact
86
+ // bytes read instead of strict UTF-8 text (BOM kept).
87
+ async function readChecked(file,label,{privateFile,budget,fileOps=fsp,bytes:raw=false}){
88
+ if(budget)budget();
89
+ const notRegular=privateFile?`${label} 必须是自己的普通文件且权限 600`:`${label} 必须是普通文件(不能是符号链接)`;
90
+ let link;
91
+ try{link=await fileOps.lstat(file,{bigint:true});}
92
+ catch(error){if(error.code==='ENOENT')throw configError(`读不到 ${label}`,{state:'missing'});throw configError(`读不到 ${label}`,{state:'invalid'});}
93
+ const bad=st=>!st.isFile()||(privateFile&&((typeof process.getuid==='function'&&st.uid!==BigInt(process.getuid()))||(st.mode&0o077n)!==0n));
94
+ if(link.isSymbolicLink()||bad(link))throw configError(notRegular,{state:'invalid',reason:'permission'});
95
+ if(link.size>BigInt(MAX_FILE))throw configError(`${label} 太大`,{state:'invalid',reason:'too_large'});
96
+ let handle;
97
+ try{
98
+ // O_NONBLOCK: a file swapped for a FIFO after lstat opens at once (instead of
99
+ // waiting for a writer) and is then refused by the type check below.
100
+ // Reads of regular files are unaffected.
101
+ handle=await fileOps.open(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0));
102
+ const st=await handle.stat({bigint:true});
103
+ if(bad(st))throw configError(notRegular,{state:'invalid',reason:'permission'});
104
+ if(st.dev!==link.dev||st.ino!==link.ino)throw configError(`${label} 在核对期间被替换,为安全起见不使用它`,{state:'invalid',reason:'permission'});
105
+ if(st.size>BigInt(MAX_FILE))throw configError(`${label} 太大`,{state:'invalid',reason:'too_large'});
106
+ const size=Number(st.size),bytes=Buffer.alloc(size);let read=0;
107
+ while(read<size){const {bytesRead}=await handle.read(bytes,read,size-read,read);if(bytesRead===0)break;read+=bytesRead;}
108
+ if(raw)return bytes.subarray(0,read);
109
+ return new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,read)).replace(/^\uFEFF/,'');
110
+ }catch(error){
111
+ if(error instanceof SendError)throw error;
112
+ throw configError(`读取 ${label} 失败`,{state:'invalid'});
113
+ }finally{if(handle)await handle.close().catch(()=>{});}
114
+ }
115
+ // Secret and channel files: refused on Windows, private-file rules elsewhere.
116
+ export async function readPrivateFile(file,label,{platform=process.platform,budget,fileOps}={}){
117
+ if(platform==='win32')throw windowsRefusal();
118
+ return readChecked(file,label,{privateFile:true,budget,fileOps});
119
+ }
120
+ // A file that holds no secret (the channel file, for display on Windows):
121
+ // the same boundary without the owner/mode rule, so a link to a secret file
122
+ // is never followed. `bytes` (used for notify.json) returns the raw bytes.
123
+ export async function readRegularFile(file,label,{fileOps,bytes=false}={}){
124
+ return readChecked(file,label,{privateFile:false,fileOps,bytes});
125
+ }
126
+
127
+ // KEY=value lines only: optional `export `, optional matching quotes, blank
128
+ // lines and # comments. Unknown or repeated names reject the whole file.
129
+ // Errors name the line number, never its content.
130
+ export function parseAssignments(text,allowed,label){
131
+ const values={},lines={};
132
+ text.split(/\r\n|\n|\r/).forEach((raw,index)=>{
133
+ let line=raw.trim();
134
+ if(!line||line.startsWith('#'))return;
135
+ if(line.startsWith('export '))line=line.slice(7).trim();
136
+ const at=line.indexOf('=');
137
+ const name=at<0?'':line.slice(0,at).trim();
138
+ let value=at<0?'':line.slice(at+1).trim();
139
+ if(at<0||!allowed.includes(name)||Object.hasOwn(values,name))
140
+ throw configError(`${label} 第 ${index+1} 行无法识别或重复`,{state:'invalid',line:index+1});
141
+ if(value.length>=2&&value[0]===value.at(-1)&&(value[0]==='"'||value[0]==="'"))value=value.slice(1,-1);
142
+ values[name]=value;lines[name]=index+1;
143
+ });
144
+ return {values,lines};
145
+ }
146
+
147
+ export async function readChannel(home,fileOptions={}){
148
+ const file=path.join(home,CHANNEL_FILE);
149
+ const {values,lines}=parseAssignments(await readPrivateFile(file,CHANNEL_FILE,fileOptions),['CHANNEL'],CHANNEL_FILE);
150
+ const channel=values.CHANNEL??'';
151
+ if(!Object.hasOwn(CHANNELS,channel))
152
+ throw configError(`${CHANNEL_FILE} 的 CHANNEL 只能是 bark 或 pushplus`,{state:'invalid',line:lines.CHANNEL});
153
+ return channel;
154
+ }
155
+
156
+ // Validated secret values for one channel. Messages say which file and line to
157
+ // fix; they never contain a value.
158
+ export async function readSecret(home,channel,fileOptions={}){
159
+ const spec=CHANNELS[channel];
160
+ if(!spec)throw configError('未知渠道');
161
+ const {values,lines}=parseAssignments(await readPrivateFile(path.join(home,spec.file),spec.file,fileOptions),spec.names,spec.file);
162
+ const where=name=>lines[name]?`第 ${lines[name]} 行 `:'';
163
+ const empty=name=>configError(`${spec.file} ${where(name)}${name} 未填写`,{state:'empty',line:lines[name]??null,name});
164
+ if(channel==='bark'){
165
+ const key=values.BARK_KEY??'',server=values.BARK_SERVER??BARK_DEFAULT_SERVER;
166
+ if(!key)throw empty('BARK_KEY');
167
+ 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'});
168
+ 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'});
169
+ if(!HTTPS_ORIGIN.test(server))throw configError(`bark.env ${where('BARK_SERVER')}BARK_SERVER 必须是不带路径的 https 地址`,{state:'invalid',line:lines.BARK_SERVER,name:'BARK_SERVER'});
170
+ return {key,server};
171
+ }
172
+ const token=values.PUSHPLUS_TOKEN??'';
173
+ if(!token)throw empty('PUSHPLUS_TOKEN');
174
+ 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'});
175
+ return {token};
176
+ }
177
+
178
+ const chars=(text,max)=>Array.from(text).slice(0,max).join('');
179
+ export async function buildRequest(channel,{home,env=process.env,dry=false,fileOptions={}}){
180
+ const title=chars(env.CM_NOTIFY_TITLE||'CM 提醒',100),body=chars(env.CM_NOTIFY_BODY||'(无正文)',1000);
181
+ if(channel==='bark'){
182
+ const {key,server}=dry?{key:'<已隐藏>',server:BARK_DEFAULT_SERVER}:await readSecret(home,'bark',fileOptions);
183
+ return {url:`${server}/push`,payload:{device_key:key,title,body,group:'CM',level:'active'}};
184
+ }
185
+ const {token}=dry?{token:'<已隐藏>'}:await readSecret(home,'pushplus',fileOptions);
186
+ return {url:PUSHPLUS_URL,payload:{token,title,content:body,template:'txt',channel:'wechat'}};
187
+ }
188
+
189
+ // Node 24.5+ routes https.Agent through HTTPS_PROXY/NO_PROXY when given
190
+ // proxyEnv; older Node ignores the option and connects directly.
191
+ function proxyAgent(env){
192
+ const proxy=env.HTTPS_PROXY||env.https_proxy;
193
+ if(!proxy)return undefined;
194
+ const proxyEnv={HTTPS_PROXY:proxy};
195
+ const noProxy=env.NO_PROXY??env.no_proxy;if(noProxy!==undefined)proxyEnv.NO_PROXY=noProxy;
196
+ return new https.Agent({proxyEnv,keepAlive:false});
197
+ }
198
+
199
+ // One POST, no redirects (https.request never follows them), TLS verification
200
+ // forced on regardless of NODE_TLS_REJECT_UNAUTHORIZED. `request` is injectable
201
+ // only through this module API (tests use a loopback http server).
202
+ export function postJson(url,data,{request=https.request,agent,signal}={}){
203
+ return new Promise((resolve,reject)=>{
204
+ const target=new URL(url);
205
+ const options={method:'POST',hostname:target.hostname,port:target.port||443,path:`${target.pathname}${target.search}`,
206
+ headers:{'Content-Type':'application/json; charset=utf-8','Content-Length':Buffer.byteLength(data)},
207
+ rejectUnauthorized:true,signal};
208
+ if(agent)options.agent=agent;
209
+ const req=request(options,response=>{
210
+ const parts=[];let size=0;
211
+ response.on('data',chunk=>{
212
+ size+=chunk.length;
213
+ if(size>MAX_RESPONSE){response.destroy();reject(new SendError(SEND_EXIT.rejected,'响应过大'));return;}
214
+ parts.push(chunk);
215
+ });
216
+ response.on('end',()=>resolve({status:response.statusCode,raw:Buffer.concat(parts)}));
217
+ response.on('error',()=>reject(new SendError(SEND_EXIT.network,'请求失败或超时')));
218
+ });
219
+ req.on('error',()=>reject(new SendError(SEND_EXIT.network,'请求失败或超时')));
220
+ req.end(data);
221
+ });
222
+ }
223
+
224
+ // Only the JSON type of `code` is ever reported, never its value: a server
225
+ // that echoes the request could put the secret there.
226
+ export function responseCodeType(raw){
227
+ let value;
228
+ try{value=JSON.parse(Buffer.from(raw).toString('utf8'));}catch{return {ok:false,type:'not_json'};}
229
+ if(!value||typeof value!=='object'||Array.isArray(value)||!Object.hasOwn(value,'code'))return {ok:false,type:'missing'};
230
+ const code=value.code,type=code===null?'null':Array.isArray(code)?'array':typeof code;
231
+ return {ok:typeof code==='number'&&code===200,type};
232
+ }
233
+
234
+ // Reads one line or EOF from the plugin's stdin, then discards it.
235
+ export function drainStdinLine(stdin){
236
+ return new Promise(resolve=>{
237
+ if(!stdin||stdin.isTTY){resolve();return;}
238
+ let size=0,done=false;
239
+ const finish=()=>{
240
+ if(done)return;done=true;
241
+ stdin.off('data',data);stdin.off('end',finish);stdin.off('error',finish);stdin.off('close',finish);
242
+ try{stdin.pause();stdin.destroy?.();}catch{}
243
+ resolve();
244
+ };
245
+ const data=chunk=>{size+=chunk.length;if(size>=MAX_STDIN||chunk.includes(10))finish();};
246
+ stdin.on('data',data);stdin.on('end',finish);stdin.on('error',finish);stdin.on('close',finish);
247
+ stdin.resume?.();
248
+ });
249
+ }
250
+
251
+ // The whole call, bounded by one deadline that covers stdin, config and the
252
+ // request. Returns an exit code; writes one line to stderr on failure.
253
+ export async function runSender({argv=[],env=process.env,stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,
254
+ request,home=notifyHome(env),deadlineMs=DEADLINE_MS,startedAt,platform=process.platform,fileOps,clock=()=>performance.now()}={}){
255
+ const say=(stream,line)=>{try{stream.write(`${line}\n`);}catch{}};
256
+ const controller=new AbortController();
257
+ // The monotonic budget is checked before every read, before the request and
258
+ // before every exit 0, besides the timer below (and the CLI's hard timer).
259
+ const started=startedAt??clock(),seconds=Math.ceil(deadlineMs/1000);
260
+ const budget=()=>{
261
+ const left=deadlineMs-(clock()-started);
262
+ if(left<=0)throw new SendError(SEND_EXIT.network,`整次调用超过 ${seconds} 秒,已放弃(未发送)`,{deadline:true});
263
+ return left;
264
+ };
265
+ let timer;
266
+ const deadline=new Promise(resolve=>{timer=setTimeout(()=>{controller.abort();resolve('deadline');},Math.max(0,deadlineMs-(clock()-started)));timer.unref?.();});
267
+ let channel='-';
268
+ const work=(async()=>{
269
+ if(platform==='win32')throw windowsRefusal();// every path, including --check and dry-run
270
+ await drainStdinLine(stdin);
271
+ const dry=env.CM_NOTIFY_DRY_RUN==='1';
272
+ const fileOptions={budget,platform,...(fileOps?{fileOps}:{})};
273
+ channel=await readChannel(home,fileOptions);
274
+ const {url,payload}=await buildRequest(channel,{home,env,dry,fileOptions});
275
+ if(argv.includes('--check')){budget();say(stdout,`cm-notify: 渠道 ${channel} 配置可解析(未发送)`);return SEND_EXIT.ok;}
276
+ if(dry){budget();say(stdout,`POST ${url}`);say(stdout,JSON.stringify(payload));return SEND_EXIT.ok;}
277
+ const data=JSON.stringify(payload);
278
+ const agent=request?undefined:proxyAgent(env);
279
+ budget();
280
+ const {status,raw}=await postJson(url,data,{request,agent,signal:controller.signal});
281
+ const code=responseCodeType(raw);
282
+ if(status!==200||!code.ok)throw new SendError(SEND_EXIT.rejected,`推送返回 http=${Number.isSafeInteger(status)?status:'?'} code类型=${code.type}`);
283
+ // Accepted, but too late: report the deadline (it may have been delivered).
284
+ if(deadlineMs-(clock()-started)<=0)throw new SendError(SEND_EXIT.network,`整次调用超过 ${seconds} 秒,已放弃(可能已送达)`,{deadline:true});
285
+ return SEND_EXIT.ok;
286
+ })();
287
+ try{
288
+ const result=await Promise.race([work.then(code=>({code}),error=>({error})),deadline]);
289
+ if(result==='deadline'){work.catch(()=>{});say(stderr,`cm-notify: 整次调用超过 ${seconds} 秒,已放弃`);return SEND_EXIT.network;}
290
+ if(result.error){
291
+ const error=result.error;
292
+ if(error instanceof SendError){
293
+ const prefix=error.exit===SEND_EXIT.config||error.detail.deadline?'':`${channel} `;
294
+ say(stderr,`cm-notify: ${prefix}${error.message}`);return error.exit;
295
+ }
296
+ say(stderr,'cm-notify: 意外错误(详情已隐藏,避免带出密钥)');return SEND_EXIT.network;
297
+ }
298
+ if(result.code===SEND_EXIT.ok&&deadlineMs-(clock()-started)<=0){say(stderr,`cm-notify: 整次调用超过 ${seconds} 秒,已放弃`);return SEND_EXIT.network;}
299
+ return result.code;
300
+ }finally{clearTimeout(timer);}
301
+ }
302
+
303
+ // Runs the sender as a process. `startedAt` and `hardTimer` come from the
304
+ // entry block above; tests call it with their own start and deadline.
305
+ export function runCli({argv=process.argv.slice(2),deadlineMs=DEADLINE_MS,softDeadlineMs=deadlineMs,startedAt=performance.now(),
306
+ hardTimer=armHardTimer(deadlineMs,startedAt),senderOptions={}}={}){
307
+ const hard=()=>{try{process.stderr.write('cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n');}catch{}process.exit(SEND_EXIT.network);};
308
+ process.on('uncaughtException',hard);process.on('unhandledRejection',hard);
309
+ return runSender({argv,deadlineMs:softDeadlineMs,startedAt,...senderOptions})
310
+ .then(code=>{clearTimeout(hardTimer);process.exit(code);},hard);
311
+ }
312
+ if(ENTRY==='run')runCli({startedAt:ENTRY_STARTED_AT,hardTimer:ENTRY_HARD_TIMER});