@aibyzero/cm-workflow 0.16.8 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +19 -0
- package/README.md +14 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +25 -1
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +105 -5
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +9 -0
- package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
- package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
- package/runtime/js/cm-ai/effect-contract.mjs +6 -1
- package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
- package/runtime/js/cm-ai/host-check.mjs +4 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
- package/runtime/js/cm-ai/host-documentation.mjs +53 -12
- package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
- package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
- package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
- package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
- package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
- package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
- package/runtime/js/cm-ai/review-package.mjs +10 -1
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
- package/runtime/js/cm-ai/task-commit.mjs +39 -0
- package/runtime/js/cm-ai/task-runner.mjs +636 -65
- package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
- package/runtime/js/cm-ai/worker-claude.mjs +10 -3
- package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
- package/runtime/js/cm-fix/execution.mjs +176 -48
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +13 -3
- package/runtime/js/cm-fix/protected-edits.mjs +10 -3
- package/runtime/js/cm-fix/repair.mjs +11 -3
- package/runtime/js/cm-fix/test-author.mjs +10 -3
- package/runtime/js/cm-idea/session.mjs +67 -4
- package/runtime/js/cm-prd/review-correction.mjs +10 -4
- package/runtime/js/cm-prd/session.mjs +43 -0
- package/runtime/js/cm-refactor/records.mjs +98 -8
- package/runtime/js/cm-refactor/workflow.mjs +79 -9
- package/runtime/js/cm-test/host.mjs +10 -3
- package/runtime/js/cm-test/session.mjs +45 -6
- package/runtime/js/notify-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +137 -33
- package/runtime/js/policy-binding-compat.mjs +54 -0
- package/scripts/ci-test-shards.mjs +67 -0
- package/scripts/ci-test-shards.test.mjs +64 -0
- package/scripts/ci-test-weights.json +222 -0
- package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
- package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
- package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
- package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
- package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
- package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
- package/scripts/cm-ai-batch-drive.mjs +55 -10
- package/scripts/cm-ai-batch-drive.test.mjs +65 -0
- package/scripts/cm-ai-batch-host.mjs +132 -13
- package/scripts/cm-ai-batch-host.test.mjs +255 -7
- package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
- package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
- package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
- package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
- package/scripts/cm-ai-batch-run.mjs +184 -22
- package/scripts/cm-ai-batch-run.test.mjs +21 -341
- package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
- package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
- package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
- package/scripts/cm-ai-drive.mjs +64 -22
- package/scripts/cm-ai-drive.test.mjs +29 -2
- package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
- package/scripts/cm-ai-host-fixture.mjs +268 -0
- package/scripts/cm-ai-host-protected.test.mjs +251 -0
- package/scripts/cm-ai-host.mjs +27 -15
- package/scripts/cm-ai-host.test.mjs +17 -759
- package/scripts/cm-ai-light-modules.test.mjs +57 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
- package/scripts/cm-ai-protected-scope.test.mjs +7 -3
- package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +56 -10
- package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
- package/scripts/cm-ai-review-failure.test.mjs +124 -13
- package/scripts/cm-ai-review-timeout.test.mjs +188 -10
- package/scripts/cm-ai-run.mjs +15 -6
- package/scripts/cm-ai-supersede.test.mjs +486 -41
- package/scripts/cm-check-drive-files.mjs +8 -0
- package/scripts/cm-check-drive.test.mjs +2 -5
- package/scripts/cm-check-runtime.sh +4 -2
- package/scripts/cm-claude-developer-worker.test.mjs +15 -0
- package/scripts/cm-claude-review-stream.test.mjs +21 -16
- package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
- package/scripts/cm-claude-worker.test.mjs +18 -2
- package/scripts/cm-external-model-recovery.test.mjs +29 -3
- package/scripts/cm-fix-abandon.test.mjs +163 -10
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +25 -7
- package/scripts/cm-fix-host.mjs +8 -7
- package/scripts/cm-fix-review-budget.test.mjs +13 -0
- package/scripts/cm-fix-review-recovery.test.mjs +35 -0
- package/scripts/cm-host-answer-timeout.test.mjs +65 -0
- package/scripts/cm-host-call-kinds.test.mjs +28 -0
- package/scripts/cm-host-documentation.test.mjs +49 -0
- package/scripts/cm-host-qa-executor.test.mjs +22 -10
- package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
- package/scripts/cm-idea-drive.mjs +49 -11
- package/scripts/cm-idea-drive.test.mjs +66 -0
- package/scripts/cm-idea-host.mjs +106 -16
- package/scripts/cm-init-answer-gaps.test.mjs +258 -0
- package/scripts/cm-init-drive.mjs +41 -7
- package/scripts/cm-init-host.mjs +61 -12
- package/scripts/cm-log-event.mjs +21 -10
- package/scripts/cm-notify-command.test.mjs +900 -0
- package/scripts/cm-notify-read-drift.test.mjs +205 -0
- package/scripts/cm-notify.mjs +469 -0
- package/scripts/cm-notify.test.mjs +221 -4
- package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
- package/scripts/cm-prd-drive.mjs +18 -5
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +37 -4
- package/scripts/cm-prd-review-disposition.test.mjs +6 -1
- package/scripts/cm-prd-review-gate.mjs +56 -0
- package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
- package/scripts/cm-refactor-drive.mjs +52 -8
- package/scripts/cm-refactor-drive.test.mjs +44 -0
- package/scripts/cm-refactor-host.test.mjs +10 -6
- package/scripts/cm-release-smoke.sh +2 -0
- package/scripts/cm-test-answer-gaps.test.mjs +151 -0
- package/scripts/cm-test-drive.mjs +21 -5
- package/scripts/fixtures/claude-review-process.mjs +1 -1
- package/scripts/policy-binding-compat.test.mjs +99 -0
- package/scripts/scan-public-safety.py +4 -0
- package/scripts/validate-public-repo.py +4 -0
- package/skills/cm-ai/references/js-host-qa-recovery.md +27 -1
- package/skills/cm-ai/references/js-host-recovery.md +120 -8
- package/skills/cm-ai/references/js-host.md +14 -7
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/references/js-host.md +44 -5
- package/skills/cm-idea/references/js-host.md +27 -2
- package/skills/cm-init/references/js-host.md +16 -3
- package/skills/cm-notify/SKILL.md +34 -0
- package/skills/cm-prd/references/js-change-recovery.md +35 -1
- package/skills/cm-refactor/references/js-host.md +17 -0
- 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});
|
package/runtime/js/notify.mjs
CHANGED
|
@@ -11,6 +11,7 @@ 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,
|
|
@@ -32,37 +33,64 @@ export function appendNotifyLog(home,now,{event='-',workflow='-',hash='-',result
|
|
|
32
33
|
}catch{}
|
|
33
34
|
}
|
|
34
35
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
// One line per process and kind: an unusable file turns notices off; an
|
|
37
|
+
// unusable `text` only falls back to the default text (notices stay on).
|
|
38
|
+
const warned=new Set();
|
|
39
|
+
const warnOnce=(env,kind,result)=>{
|
|
40
|
+
if(warned.has(kind))return;warned.add(kind);
|
|
41
|
+
appendNotifyLog(notifyHome(env),Date.now(),{event:'config',result});
|
|
39
42
|
};
|
|
43
|
+
const warn=(env,reason)=>warnOnce(env,'config',`off invalid_config ${reason}`);
|
|
40
44
|
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
|
|
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;}
|
|
45
|
+
// Pure check of notify.json text: {config} or {reason}. Shared by the
|
|
46
|
+
// runtime reader below and by /cm:notify, which must not write notify.log.
|
|
47
|
+
export function parseNotifyConfig(raw){
|
|
49
48
|
let value;
|
|
50
|
-
try{value=JSON.parse(raw);}catch{
|
|
51
|
-
if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1){
|
|
49
|
+
try{value=JSON.parse(raw);}catch{return {reason:'not_json'};}
|
|
50
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1)return {reason:'version'};
|
|
52
51
|
const {command}=value;
|
|
53
52
|
if(!Array.isArray(command)||command.length<1||command.length>32
|
|
54
53
|
||!command.every(item=>typeof item==='string'&&item.length>0&&item.length<=4096&&!item.includes('\0'))){
|
|
55
|
-
|
|
54
|
+
return {reason:'command'};
|
|
56
55
|
}
|
|
57
|
-
if(!path.isAbsolute(command[0])){
|
|
56
|
+
if(!path.isAbsolute(command[0]))return {reason:'command_not_absolute'};
|
|
58
57
|
const minutes=value.waitMinutes??NOTIFY_LIMITS.defaultWaitMinutes;
|
|
59
|
-
if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440){
|
|
58
|
+
if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440)return {reason:'wait_minutes'};
|
|
60
59
|
const checkMinutes=value.checkWaitMinutes??NOTIFY_LIMITS.defaultCheckWaitMinutes;
|
|
61
|
-
if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440){
|
|
60
|
+
if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440)return {reason:'check_wait_minutes'};
|
|
62
61
|
const idleMinutes=value.idleMinutes??NOTIFY_LIMITS.defaultIdleMinutes;
|
|
63
|
-
if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440){
|
|
62
|
+
if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440)return {reason:'idle_minutes'};
|
|
64
63
|
const ms=value=>Math.max(1,Math.round(value*60000));
|
|
65
|
-
|
|
64
|
+
const config={command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes)};
|
|
65
|
+
// An unusable `text` never turns notices off: the default text is used and
|
|
66
|
+
// the caller is told why (textReason), so a typo cannot silence notices.
|
|
67
|
+
if(value.text===undefined)return {config};
|
|
68
|
+
const text=normalizeNotifyText(value.text);
|
|
69
|
+
if(text.reason)return {config,textReason:text.reason};
|
|
70
|
+
return {config:{...config,text:text.text}};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The runtime reads notify.json through the same safe boundary as /cm:notify
|
|
74
|
+
// (readRegularFileSync in notify-safe-read.mjs, a side-effect-free twin of the
|
|
75
|
+
// sender's reader; a drift test keeps the two identical): never through a
|
|
76
|
+
// symlink, only a regular file of at most 64 KiB, opened without blocking (a
|
|
77
|
+
// FIFO is refused, never waited on), and the opened handle must be the checked
|
|
78
|
+
// file. Still synchronous and never throws.
|
|
79
|
+
const UNSAFE_READ={permission:'not_regular_file',too_large:'too_large'};
|
|
80
|
+
|
|
81
|
+
// null = feature off. Under `node --test` only an explicit CM_WORKFLOW_HOME
|
|
82
|
+
// enables it, so a test suite never reaches the user's real configuration.
|
|
83
|
+
// An invalid file is reported in notify.log only, never on workflow output.
|
|
84
|
+
export function readNotifyConfig(env=process.env){
|
|
85
|
+
if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return null;
|
|
86
|
+
const file=path.join(notifyHome(env),'notify.json');
|
|
87
|
+
let raw;
|
|
88
|
+
try{raw=readRegularFileSync(file,'notify.json',{bytes:true}).toString('utf8');}
|
|
89
|
+
catch(error){if(error?.state!=='missing')warn(env,`unreadable_${UNSAFE_READ[error?.reason]??'error'}`);return null;}
|
|
90
|
+
const parsed=parseNotifyConfig(raw);
|
|
91
|
+
if(parsed.reason){warn(env,parsed.reason);return null;}
|
|
92
|
+
if(parsed.textReason)warnOnce(env,'text',`default_text text_config ${parsed.textReason}`);
|
|
93
|
+
return parsed.config;
|
|
66
94
|
}
|
|
67
95
|
|
|
68
96
|
// Messages carry only these structured fields. Absolute paths (POSIX, drive
|
|
@@ -78,15 +106,85 @@ function clean(value,max){
|
|
|
78
106
|
}
|
|
79
107
|
const projectName=value=>typeof value==='string'&&value?clean(path.basename(value),40):'';
|
|
80
108
|
|
|
81
|
-
|
|
109
|
+
// Local 24-hour HH:MM in the process time zone (TZ) unless one is injected.
|
|
110
|
+
export function localClock(now,timeZone){
|
|
111
|
+
const parts=new Intl.DateTimeFormat('en-GB',{hour:'2-digit',minute:'2-digit',hourCycle:'h23',
|
|
112
|
+
...(timeZone?{timeZone}:{})}).formatToParts(new Date(now));
|
|
113
|
+
const pick=type=>parts.find(part=>part.type===type)?.value??'00';
|
|
114
|
+
return `${pick('hour')}:${pick('minute')}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Optional user text (notify.json `text`): a title prefix, one headline per
|
|
118
|
+
// event, which structured fields appear in which order, and their labels.
|
|
119
|
+
// Nothing else: no templates or expressions. Custom strings go through the same
|
|
120
|
+
// clean() as field values (paths redacted, control characters removed) and are
|
|
121
|
+
// capped; the whole title and body keep their caps.
|
|
122
|
+
export const NOTIFY_TEXT_FIELDS=Object.freeze(['project','workflow','runId','task','stage','code','nextAction','time']);
|
|
123
|
+
const TEXT_EVENTS=['done','waiting','idle','idle_waiting','dead','default'];
|
|
124
|
+
const TEXT_CAPS=Object.freeze({titlePrefix:16,headline:24,label:12});
|
|
125
|
+
const FIELD_CAPS={workflow:24,runId:64,task:40,stage:48,code:64,nextAction:200};
|
|
126
|
+
export const DEFAULT_NOTIFY_TEXT=Object.freeze({titlePrefix:'CM',
|
|
127
|
+
headlines:Object.freeze({done:'流程已结束',waiting:'等待会话应答',idle:'疑似空转',idle_waiting:'在等你',dead:'宿主已退出未收尾',default:'需要人处理'}),
|
|
128
|
+
fields:Object.freeze({default:Object.freeze(['nextAction','project','workflow','task','stage','code','time']),
|
|
129
|
+
done:Object.freeze(['project','task','time'])}),
|
|
130
|
+
labels:Object.freeze({nextAction:'下一步',project:'项目',workflow:'流程',runId:'运行',task:'任务',stage:'阶段',code:'原因',time:'时间'})});
|
|
131
|
+
// Custom strings first lose every Unicode format character (\p{Cf}: bidi
|
|
132
|
+
// controls U+202A-202E, U+2066-2069, U+200E/200F, U+061C; zero-width U+200B-200D,
|
|
133
|
+
// U+2060, U+FEFF; soft hyphen, tag characters), so they cannot reorder or hide
|
|
134
|
+
// text. Unlike field values, a path is redacted whatever precedes it: every
|
|
135
|
+
// span starting at "/", "~/", a drive letter with ":\" or ":/", or a UNC "\\" up to the next
|
|
136
|
+
// whitespace or listed punctuation becomes <路径> (so "CI/CD" becomes "CI<路径>").
|
|
137
|
+
// Then the usual clean(). Something visible (a letter, digit, punctuation or
|
|
138
|
+
// symbol) must remain. Field values and the default text are not touched.
|
|
139
|
+
const FORMAT_CHARS=/\p{Cf}+/gu,VISIBLE=/[\p{L}\p{N}\p{P}\p{S}]/u;
|
|
140
|
+
const TEXT_PATH=/(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`,。;;、))]+/g;
|
|
141
|
+
const cleanText=(raw,max)=>clean(raw.replace(FORMAT_CHARS,'').replace(/[\u0000-\u001f\u007f-\u009f]+/g,' ').replace(TEXT_PATH,'<路径>'),max);
|
|
142
|
+
const plain=value=>value&&typeof value==='object'&&!Array.isArray(value);
|
|
143
|
+
const onlyKeys=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));
|
|
144
|
+
// {text} merged over the default, or {reason}. Idempotent on its own output.
|
|
145
|
+
export function normalizeNotifyText(value){
|
|
146
|
+
if(!plain(value))return {reason:'text'};
|
|
147
|
+
if(!onlyKeys(value,['titlePrefix','headlines','fields','labels']))return {reason:'text_key'};
|
|
148
|
+
const text={titlePrefix:DEFAULT_NOTIFY_TEXT.titlePrefix,headlines:{...DEFAULT_NOTIFY_TEXT.headlines},
|
|
149
|
+
fields:{default:[...DEFAULT_NOTIFY_TEXT.fields.default],done:[...DEFAULT_NOTIFY_TEXT.fields.done]},labels:{...DEFAULT_NOTIFY_TEXT.labels}};
|
|
150
|
+
// A custom string must still show something after cleaning; only the prefix
|
|
151
|
+
// may be given as exactly "" (no prefix).
|
|
152
|
+
const word=(raw,max,empty=false)=>{
|
|
153
|
+
if(typeof raw!=='string')return null;if(empty&&raw==='')return '';
|
|
154
|
+
const cleaned=cleanText(raw,max);return VISIBLE.test(cleaned)?cleaned:null;};
|
|
155
|
+
if(value.titlePrefix!==undefined){
|
|
156
|
+
const prefix=word(value.titlePrefix,TEXT_CAPS.titlePrefix,true);if(prefix===null)return {reason:'title_prefix'};
|
|
157
|
+
text.titlePrefix=prefix;
|
|
158
|
+
}
|
|
159
|
+
for(const [name,keys,cap] of [['headlines',TEXT_EVENTS,TEXT_CAPS.headline],['labels',NOTIFY_TEXT_FIELDS,TEXT_CAPS.label]]){
|
|
160
|
+
if(value[name]===undefined)continue;
|
|
161
|
+
if(!plain(value[name])||!onlyKeys(value[name],keys))return {reason:name};
|
|
162
|
+
for(const [key,raw] of Object.entries(value[name])){const cleaned=word(raw,cap);if(cleaned===null)return {reason:name};text[name][key]=cleaned;}
|
|
163
|
+
}
|
|
164
|
+
if(value.fields!==undefined){
|
|
165
|
+
if(!plain(value.fields)||!onlyKeys(value.fields,['default','done']))return {reason:'fields'};
|
|
166
|
+
for(const [key,list] of Object.entries(value.fields)){
|
|
167
|
+
if(!Array.isArray(list)||list.length<1||new Set(list).size!==list.length
|
|
168
|
+
||!list.every(item=>NOTIFY_TEXT_FIELDS.includes(item)))return {reason:'fields'};
|
|
169
|
+
text.fields[key]=[...list];
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return {text};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The default text is a next-step-first layout; a finished run only names
|
|
176
|
+
// project, task and time. `text` is a normalized notify.json `text`; anything
|
|
177
|
+
// unusable falls back to the default.
|
|
178
|
+
export function buildNotifyMessage(fields,{now=Date.now(),timeZone,text}={}){
|
|
179
|
+
const spec=text===undefined||text===null?DEFAULT_NOTIFY_TEXT:normalizeNotifyText(text).text??DEFAULT_NOTIFY_TEXT;
|
|
82
180
|
const workflow=clean(fields.workflow,24)||'cm',project=projectName(fields.project);
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
181
|
+
const event=Object.hasOwn(spec.headlines,fields.event)&&fields.event!=='default'?fields.event:'default';
|
|
182
|
+
const head=[spec.titlePrefix,workflow,spec.headlines[event]].filter(Boolean).join(' ');
|
|
183
|
+
const title=cut(`${head}${project?` · ${project}`:''}`,NOTIFY_LIMITS.titleChars);
|
|
184
|
+
const value=name=>name==='time'?localClock(now,timeZone):name==='project'?project:name==='workflow'?workflow
|
|
185
|
+
:clean(fields[name],FIELD_CAPS[name]);
|
|
186
|
+
const rows=spec.fields[fields.event==='done'?'done':'default'].map(name=>[spec.labels[name],value(name)]);
|
|
187
|
+
const lines=rows.filter(([,value])=>value).map(([label,value])=>`${label}:${value}`);
|
|
90
188
|
return {title,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
|
|
91
189
|
}
|
|
92
190
|
|
|
@@ -162,7 +260,7 @@ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_L
|
|
|
162
260
|
if(reserved!=='duplicate')appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved}`});
|
|
163
261
|
return {sent:false,reason:reserved};
|
|
164
262
|
}
|
|
165
|
-
const message=buildNotifyMessage(fields,{now});
|
|
263
|
+
const message=buildNotifyMessage(fields,{now,text:config.text});
|
|
166
264
|
const payload={...message,event};
|
|
167
265
|
for(const name of ['project','workflow','runId','task','stage','code','nextAction']){
|
|
168
266
|
const value=name==='project'?projectName(fields.project):clean(fields[name],name==='nextAction'?200:64);
|
|
@@ -286,7 +384,11 @@ const AI_STUCK_ACTIONS=new Set(['reconcile','abandon_effect','abandon_review','r
|
|
|
286
384
|
const AI_STUCK_CODES=new Set(['decision_required','permission_denied','provider_development_authorization_required',
|
|
287
385
|
'qa_decision_required','qa_mandatory_required','qa_triggered','qa_blocked','qa_failed','qa_result_blocked',
|
|
288
386
|
'qa_execution_unknown','correction_review_required','project_qa_not_passed','documentation_sync_blocked',
|
|
289
|
-
'handoff_exists','spec_drift','qa_fix_code_unmatched'
|
|
387
|
+
'handoff_exists','spec_drift','qa_fix_code_unmatched',
|
|
388
|
+
// Q23-Q26: QA-fix and batch recovery refusals and stops (host-qa-fix-owner.mjs, cm-ai-batch-run.mjs).
|
|
389
|
+
'qa_fix_action_authorization_required','batch_member_action_authorization_required','batch_member_action_not_current',
|
|
390
|
+
'batch_member_action_unavailable','batch_parallel_member_recovery_required','batch_resources_open',
|
|
391
|
+
'batch_parallel_member_unresolved','batch_member_rescheduled']);
|
|
290
392
|
function classifyAi(r){
|
|
291
393
|
const state=text(r.state),code=text(r.code),outcome=text(r.outcome);
|
|
292
394
|
if(state==='run_done'&&['run_done','run_done_degraded'].includes(code))return 'done';
|
|
@@ -312,7 +414,7 @@ const CLASSIFY={
|
|
|
312
414
|
'change_rejected','inputs_replaced'].includes(stage))return 'stuck';
|
|
313
415
|
if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
|
|
314
416
|
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';
|
|
417
|
+
if(status&&(/_unknown$/.test(status)||['correction_recovery_required','correction_recovery_conflict','disposition_details_need_verification'].includes(status)))return 'stuck';
|
|
316
418
|
if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
|
|
317
419
|
if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
|
|
318
420
|
if(['review_unknown','review_cancelled'].includes(review.status)||review.verdict==='blocked'
|
|
@@ -324,7 +426,9 @@ const CLASSIFY={
|
|
|
324
426
|
'cm-idea'(r){
|
|
325
427
|
const stage=text(r.stage),recovery=obj(r.recovery);
|
|
326
428
|
if(stage==='saved')return 'done';
|
|
327
|
-
|
|
429
|
+
// A pending call (unknown, or recorded but not yet consumed/refused) waits on
|
|
430
|
+
// resume, abandon or discard; an interrupted save waits on reconciliation.
|
|
431
|
+
if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
|
|
328
432
|
if(stage==='draft_ready')return r.confirmationRequired===true?null:'stuck';
|
|
329
433
|
return ['awaiting_user','save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
|
|
330
434
|
},
|
|
@@ -332,7 +436,7 @@ const CLASSIFY={
|
|
|
332
436
|
'cm-init'(r){
|
|
333
437
|
const stage=text(r.stage)??(r.status==='blocked'?'blocked':null),recovery=obj(r.recovery);
|
|
334
438
|
if(['rules_written','rules_present'].includes(stage))return 'done';
|
|
335
|
-
if(recovery.writing===true||obj(recovery.call).status
|
|
439
|
+
if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
|
|
336
440
|
return ['analysis_blocked','verification_blocked','confirmation_required','confirmation_rejected','review_changes_requested',
|
|
337
441
|
'review_blocked','write_incomplete','write_unknown',...STUCK_COMMON].includes(stage)?'stuck':null;
|
|
338
442
|
},
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Durable cm-init / cm-test sessions bind the policy documents they ran under.
|
|
2
|
+
// The external answer gap fixes (batch 3) added recovery sections to two of
|
|
3
|
+
// them, which would refuse every session created before (idea_session_binding_
|
|
4
|
+
// changed / cm_test_session_binding_changed) — not even status could run.
|
|
5
|
+
// This is a controlled migration, not a relaxed check: an older binding is
|
|
6
|
+
// accepted only when it is one of the known legacy digests below, every other
|
|
7
|
+
// bound file is byte-identical to that legacy version, and the changed document
|
|
8
|
+
// is one of the known successors. Any other drift still refuses. When a bound
|
|
9
|
+
// document changes again, add its new digest to the successors (a test checks
|
|
10
|
+
// that the current documents are listed).
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import {createHash} from 'node:crypto';
|
|
14
|
+
export const sha256=text=>createHash('sha256').update(text).digest('hex');
|
|
15
|
+
// origin/main 0b3040e (before batch 3).
|
|
16
|
+
export const LEGACY_INIT_POLICIES=Object.freeze([Object.freeze({since:'0b3040e',
|
|
17
|
+
policyDigest:'d467afb7082e608c0be4b2affca9a1005edc13a39d61202abede6dfead8e0d6f',
|
|
18
|
+
changed:'skills/cm-init/references/js-host.md',
|
|
19
|
+
files:Object.freeze({
|
|
20
|
+
'skills/cm-init/SKILL.md':'4b69e2a2fa14676e3aa105729ba3dccc9f54053b2876cad0af1bf66e344bd7ec',
|
|
21
|
+
'skills/cm-init/references/js-host.md':'da04c4bc6d9c5a40b99a8dd6c2c44e9c719663b4032bbf2b0ef0ae4c53948e8a',
|
|
22
|
+
'templates/rules/backend-api.md':'4c2b8d85358c81081ab3d039b23a5fb9cb8640f069b222253d612bb48bafdc7e', // gitleaks:allow SHA-256 文件摘要,不是密钥
|
|
23
|
+
'templates/rules/coding-style.md':'74b789f8aa44f2ec9643ea85d05705c702ceb278f7cc10731ca5fe78320af796',
|
|
24
|
+
'templates/rules/database.md':'b7c69d7b29870db0f725c0bf80c1d1b989f0c315a5d8f0fb9d311008922b6926',
|
|
25
|
+
'templates/rules/finance.md':'faeac9aedc4aec79161940ae422f56c65872e63c5909642a3fe27714e5646e9c',
|
|
26
|
+
'templates/rules/frontend.md':'9247f607f050ed18cfdc2ac28ee5d0b8b2f4b54b757d860fed3be5dae0a9a976',
|
|
27
|
+
'templates/rules/git-workflow.md':'28142563f8146ffe155da0b845035bcfccf828bc6312c26c9166d655e76b31cd',
|
|
28
|
+
'templates/rules/miniprogram.md':'43193532bfa1237f2f4c085eb854b332e6589ea6e3176b8bc0adbeb56f96fc3f',
|
|
29
|
+
'templates/rules/security.md':'afa53ae25dc434a690006cb7eabeb33d2656ce7371d1f7c57d70ca6b385b7fbc',
|
|
30
|
+
'templates/rules/smart-contract.md':'eabe294e3194ddbe2eff5470736db4985c3e88c1cbbc1f21a8262dd4fa15d2b7',
|
|
31
|
+
'templates/rules/testing.md':'e992de31f24b99d0b2bc9fd105c61ea9b0d6bc298190a3cf830a8f6a506c8455'})})]);
|
|
32
|
+
export const LEGACY_TEST_POLICIES=Object.freeze([Object.freeze({since:'0b3040e',
|
|
33
|
+
policy:'0a80dde424c5aea90fc05ea2bb919a8bdb1ae4a2788d252e2b97a7de135f8bf4',changed:'skills/cm-test/references/js-host.md'})]);
|
|
34
|
+
// Known versions of the changed documents that may continue a legacy binding.
|
|
35
|
+
export const POLICY_DOC_SUCCESSORS=Object.freeze({
|
|
36
|
+
'skills/cm-init/references/js-host.md':Object.freeze(['d3d6ad0b02ee7d3863302c49a9434b1a9f423e8ab4ff332cd9ad077a0b270fb1',
|
|
37
|
+
'223dd3a4a4172591480bff818bc81216d5554ea1c7c7785619ccab33ee3fd833']),
|
|
38
|
+
'skills/cm-test/references/js-host.md':Object.freeze(['0a6023c9036693a93a17650872b634b33d68eecc2fbece188519e94e31452e8c']),
|
|
39
|
+
});
|
|
40
|
+
// cm-init: files is the current [[relativePath, content|null], ...] policy list.
|
|
41
|
+
export function legacyInitBindings({project,workflowRoot,files}){
|
|
42
|
+
const current=Object.fromEntries(files.map(([file,content])=>[file,content===null?null:sha256(content)]));
|
|
43
|
+
return LEGACY_INIT_POLICIES.filter(legacy=>{
|
|
44
|
+
const names=Object.keys(legacy.files).sort();
|
|
45
|
+
return JSON.stringify(names)===JSON.stringify(Object.keys(current).sort())
|
|
46
|
+
&&names.every(file=>file===legacy.changed?POLICY_DOC_SUCCESSORS[file].includes(current[file]):current[file]===legacy.files[file]);
|
|
47
|
+
}).map(legacy=>({project,workflowRoot,policyDigest:legacy.policyDigest}));
|
|
48
|
+
}
|
|
49
|
+
// cm-test: binding is the current binding; skillDir holds references/js-host.md.
|
|
50
|
+
export function legacyTestBindings(binding,skillDir){
|
|
51
|
+
const doc=sha256(fs.readFileSync(path.join(skillDir,'references/js-host.md'),'utf8'));
|
|
52
|
+
return LEGACY_TEST_POLICIES.filter(legacy=>POLICY_DOC_SUCCESSORS[legacy.changed].includes(doc))
|
|
53
|
+
.map(legacy=>({...binding,policy:legacy.policy}));
|
|
54
|
+
}
|