@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.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +37 -0
- package/README.md +39 -3
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +61 -4
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +204 -0
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +26 -4
- 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/execution-store.mjs +4 -2
- 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 +86 -17
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +47 -7
- package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- 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-deliveries.mjs +29 -6
- 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/cause-package.mjs +37 -8
- package/runtime/js/cm-fix/diagnosis.mjs +43 -0
- package/runtime/js/cm-fix/execution.mjs +356 -187
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +15 -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-run.mjs +26 -0
- package/runtime/js/notify-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +492 -0
- package/runtime/js/policy-binding-compat.mjs +54 -0
- package/runtime/model-efficiency.md +17 -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 +189 -22
- package/scripts/cm-ai-batch-run.test.mjs +22 -334
- 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 +68 -23
- package/scripts/cm-ai-drive.test.mjs +37 -2
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- 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 +28 -16
- 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-project-qa-gate.test.mjs +71 -4
- 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 +127 -8
- 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 +249 -10
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +34 -8
- package/scripts/cm-fix-host.mjs +8 -7
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- 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 +143 -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 +49 -12
- 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 +685 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- 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/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- 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/SKILL.md +7 -3
- package/skills/cm-ai/references/N6-qa-eval.md +2 -2
- package/skills/cm-ai/references/js-host-modes.md +90 -0
- package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
- package/skills/cm-ai/references/js-host-recovery.md +311 -0
- package/skills/cm-ai/references/js-host.md +76 -331
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +56 -10
- 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/SKILL.md +2 -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,492 @@
|
|
|
1
|
+
// Optional "a person is needed" notices, shared by every workflow.
|
|
2
|
+
// Provider-neutral: hands one user-configured local command (no shell) a short
|
|
3
|
+
// message built only from structured fields. It never answers, continues or
|
|
4
|
+
// authorizes anything. Nothing here waits: the command runs under a detached,
|
|
5
|
+
// unref'd launcher (notify-run.mjs) that owns its own 15 s timeout, so a
|
|
6
|
+
// workflow's exit time, exit code, output and state never depend on it.
|
|
7
|
+
// Problems only append one line to notify.log.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import {spawn} from 'node:child_process';
|
|
12
|
+
import {fileURLToPath} from 'node:url';
|
|
13
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
14
|
+
import {readRegularFileSync} from './notify-safe-read.mjs';
|
|
15
|
+
|
|
16
|
+
export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perMinute:4,perDay:150,
|
|
17
|
+
commandTimeoutMs:15000,titleChars:60,bodyChars:500,defaultWaitMinutes:10,defaultCheckWaitMinutes:45,
|
|
18
|
+
defaultIdleMinutes:45});
|
|
19
|
+
const LOCK_STALE_MS=30000,LOG_LIMIT=256*1024;
|
|
20
|
+
const RUNNER=fileURLToPath(new URL('./notify-run.mjs',import.meta.url));
|
|
21
|
+
|
|
22
|
+
export function notifyHome(env=process.env){
|
|
23
|
+
return path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// One line per problem; never the message, the command's output or any env.
|
|
27
|
+
export function appendNotifyLog(home,now,{event='-',workflow='-',hash='-',result}){
|
|
28
|
+
try{
|
|
29
|
+
const file=path.join(home,'notify.log');
|
|
30
|
+
try{if(fs.statSync(file).size>LOG_LIMIT)fs.renameSync(file,`${file}.1`);}catch{}
|
|
31
|
+
const word=(value,max)=>String(value??'-').replace(/[^A-Za-z0-9_.:-]+/g,'_').slice(0,max)||'-';
|
|
32
|
+
fs.appendFileSync(file,`${new Date(now).toISOString()} ${word(event,12)} ${word(workflow,24)} key=${word(hash,16)} ${String(result).replace(/[^A-Za-z0-9_ .:-]+/g,'_').slice(0,80)}\n`,{mode:0o600});
|
|
33
|
+
}catch{}
|
|
34
|
+
}
|
|
35
|
+
|
|
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});
|
|
42
|
+
};
|
|
43
|
+
const warn=(env,reason)=>warnOnce(env,'config',`off invalid_config ${reason}`);
|
|
44
|
+
|
|
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){
|
|
48
|
+
let value;
|
|
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'};
|
|
51
|
+
const {command}=value;
|
|
52
|
+
if(!Array.isArray(command)||command.length<1||command.length>32
|
|
53
|
+
||!command.every(item=>typeof item==='string'&&item.length>0&&item.length<=4096&&!item.includes('\0'))){
|
|
54
|
+
return {reason:'command'};
|
|
55
|
+
}
|
|
56
|
+
if(!path.isAbsolute(command[0]))return {reason:'command_not_absolute'};
|
|
57
|
+
const minutes=value.waitMinutes??NOTIFY_LIMITS.defaultWaitMinutes;
|
|
58
|
+
if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440)return {reason:'wait_minutes'};
|
|
59
|
+
const checkMinutes=value.checkWaitMinutes??NOTIFY_LIMITS.defaultCheckWaitMinutes;
|
|
60
|
+
if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440)return {reason:'check_wait_minutes'};
|
|
61
|
+
const idleMinutes=value.idleMinutes??NOTIFY_LIMITS.defaultIdleMinutes;
|
|
62
|
+
if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440)return {reason:'idle_minutes'};
|
|
63
|
+
const ms=value=>Math.max(1,Math.round(value*60000));
|
|
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;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Messages carry only these structured fields. Absolute paths (POSIX, drive
|
|
97
|
+
// letter, UNC; also when glued to CJK text) are redacted and control
|
|
98
|
+
// characters removed; every field and the whole message are bounded.
|
|
99
|
+
const cut=(text,max)=>{const chars=Array.from(text);return chars.length<=max?text:chars.slice(0,max-1).join('')+'…';};
|
|
100
|
+
function clean(value,max){
|
|
101
|
+
if(typeof value!=='string'&&!(typeof value==='number'&&Number.isFinite(value)))return '';
|
|
102
|
+
const text=String(value).replace(/[\u0000-\u001f\u007f-\u009f]+/g,' ')
|
|
103
|
+
.replace(/(?<![A-Za-z0-9_.~-])(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`,。;;、))]+/g,'<路径>')
|
|
104
|
+
.replace(/\s+/g,' ').trim();
|
|
105
|
+
return cut(text,max);
|
|
106
|
+
}
|
|
107
|
+
const projectName=value=>typeof value==='string'&&value?clean(path.basename(value),40):'';
|
|
108
|
+
|
|
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;
|
|
180
|
+
const workflow=clean(fields.workflow,24)||'cm',project=projectName(fields.project);
|
|
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}`);
|
|
188
|
+
return {title,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const keyHash=key=>createHash('sha256').update(key).digest('hex').slice(0,16);
|
|
192
|
+
|
|
193
|
+
// Cross-process lock without any waiting. The lock file is published complete
|
|
194
|
+
// (written to a temp file, then hard-linked into place, which fails if a lock
|
|
195
|
+
// exists). A busy lock skips the notice at once. A stale lock (owner gone or
|
|
196
|
+
// older than 30 s; the critical section takes milliseconds) is reclaimed only
|
|
197
|
+
// by renaming it to a unique name and confirming it is byte-identical to the
|
|
198
|
+
// stale lock that was judged; anything else is put back and the notice skipped.
|
|
199
|
+
function readLock(file){try{return fs.readFileSync(file,'utf8');}catch{return null;}}
|
|
200
|
+
function stale(raw){
|
|
201
|
+
let value;try{value=JSON.parse(raw);}catch{return false;}
|
|
202
|
+
if(!Number.isSafeInteger(value?.pid)||!Number.isFinite(value?.at))return false;
|
|
203
|
+
if(Date.now()-value.at>LOCK_STALE_MS)return true;
|
|
204
|
+
if(value.pid===process.pid)return false;
|
|
205
|
+
try{process.kill(value.pid,0);return false;}catch(error){return error.code==='ESRCH';}
|
|
206
|
+
}
|
|
207
|
+
function publishLock(file,body){
|
|
208
|
+
const temp=`${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
209
|
+
try{fs.writeFileSync(temp,body,{mode:0o600});fs.linkSync(temp,file);return true;}
|
|
210
|
+
catch{return false;}
|
|
211
|
+
finally{try{fs.unlinkSync(temp);}catch{}}
|
|
212
|
+
}
|
|
213
|
+
function takeLock(file){
|
|
214
|
+
const token=randomUUID(),body=JSON.stringify({pid:process.pid,at:Date.now(),token});
|
|
215
|
+
if(publishLock(file,body))return body;
|
|
216
|
+
const seen=readLock(file);
|
|
217
|
+
if(seen===null||!stale(seen))return null;
|
|
218
|
+
const grave=`${file}.stale-${randomUUID()}`;
|
|
219
|
+
try{fs.renameSync(file,grave);}catch{return null;}
|
|
220
|
+
if(readLock(grave)!==seen){try{fs.linkSync(grave,file);}catch{}try{fs.unlinkSync(grave);}catch{}return null;}
|
|
221
|
+
try{fs.unlinkSync(grave);}catch{}
|
|
222
|
+
return publishLock(file,body)?body:null;
|
|
223
|
+
}
|
|
224
|
+
function releaseLock(file,body){if(readLock(file)===body){try{fs.unlinkSync(file);}catch{}}}
|
|
225
|
+
|
|
226
|
+
// Dedup and throttle across processes. Any lock or parse trouble skips the
|
|
227
|
+
// notice instead of waiting on it.
|
|
228
|
+
function reserve(home,hash,now){
|
|
229
|
+
const lockFile=path.join(home,'notify-state.lock'),stateFile=path.join(home,'notify-state.json');
|
|
230
|
+
const lock=takeLock(lockFile);if(lock===null)return 'state_busy';
|
|
231
|
+
try{
|
|
232
|
+
let state={version:1,keys:{},sends:[]};
|
|
233
|
+
try{state=JSON.parse(fs.readFileSync(stateFile,'utf8'));}
|
|
234
|
+
catch(error){if(error.code!=='ENOENT')return 'state_invalid';}
|
|
235
|
+
if(!state||state.version!==1||!state.keys||typeof state.keys!=='object'||Array.isArray(state.keys)
|
|
236
|
+
||!Array.isArray(state.sends)||!state.sends.every(Number.isFinite)
|
|
237
|
+
||!Object.values(state.keys).every(Number.isFinite))return 'state_invalid';
|
|
238
|
+
const keys=Object.fromEntries(Object.entries(state.keys).filter(([,at])=>now-at<NOTIFY_LIMITS.sameKeyMs&&at<=now));
|
|
239
|
+
const sends=state.sends.filter(at=>now-at<24*3600*1000&&at<=now);
|
|
240
|
+
if(Object.hasOwn(keys,hash))return 'duplicate';
|
|
241
|
+
if(sends.filter(at=>now-at<60000).length>=NOTIFY_LIMITS.perMinute)return 'rate_minute';
|
|
242
|
+
if(sends.length>=NOTIFY_LIMITS.perDay)return 'rate_day';
|
|
243
|
+
keys[hash]=now;sends.push(now);
|
|
244
|
+
const temp=`${stateFile}.${process.pid}.${randomUUID()}.tmp`;
|
|
245
|
+
try{fs.writeFileSync(temp,JSON.stringify({version:1,keys,sends}),{mode:0o600});fs.renameSync(temp,stateFile);}
|
|
246
|
+
catch{try{fs.unlinkSync(temp);}catch{}return 'state_write_failed';}
|
|
247
|
+
return 'ok';
|
|
248
|
+
}finally{releaseLock(lockFile,lock);}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Never throws and never waits. Returns {sent, reason}; sent means the command
|
|
252
|
+
// was handed to the detached launcher, whose own failures go to notify.log.
|
|
253
|
+
export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs}={}){
|
|
254
|
+
try{
|
|
255
|
+
const config=readNotifyConfig(env);if(!config)return {sent:false,reason:'off'};
|
|
256
|
+
if(typeof fields?.key!=='string'||!fields.key)return {sent:false,reason:'invalid_key'};
|
|
257
|
+
const home=notifyHome(env),hash=keyHash(fields.key),event=fields.event??'stuck',workflow=clean(fields.workflow,24)||'cm';
|
|
258
|
+
const reserved=reserve(home,hash,now);
|
|
259
|
+
if(reserved!=='ok'){
|
|
260
|
+
if(reserved!=='duplicate')appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved}`});
|
|
261
|
+
return {sent:false,reason:reserved};
|
|
262
|
+
}
|
|
263
|
+
const message=buildNotifyMessage(fields,{now,text:config.text});
|
|
264
|
+
const payload={...message,event};
|
|
265
|
+
for(const name of ['project','workflow','runId','task','stage','code','nextAction']){
|
|
266
|
+
const value=name==='project'?projectName(fields.project):clean(fields[name],name==='nextAction'?200:64);
|
|
267
|
+
if(value)payload[name]=value;
|
|
268
|
+
}
|
|
269
|
+
const child=spawn(process.execPath,[RUNNER,home,hash,event,workflow,String(timeoutMs),'--',...config.command],
|
|
270
|
+
{detached:true,stdio:'ignore',windowsHide:true,
|
|
271
|
+
env:{...env,CM_NOTIFY_TITLE:message.title,CM_NOTIFY_BODY:message.body,CM_NOTIFY_PAYLOAD:JSON.stringify(payload)}});
|
|
272
|
+
child.on('error',()=>appendNotifyLog(home,Date.now(),{event,workflow,hash,result:'failed launcher'}));
|
|
273
|
+
child.unref();
|
|
274
|
+
return {sent:true,reason:'launched'};
|
|
275
|
+
}catch{return {sent:false,reason:'error'};}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Host registry: one small private file per live host session under
|
|
279
|
+
// <home>/hosts, so the read-only patrol (scripts/cm-patrol.mjs) can tell a host
|
|
280
|
+
// that died from one that is merely idle. Written only when notices are
|
|
281
|
+
// configured, updated on events the host already has (start, each reply),
|
|
282
|
+
// removed at session end. Best-effort: never throws, never changes the host.
|
|
283
|
+
export const HOST_REGISTRY_MAX_AGE_MS=48*3600*1000;
|
|
284
|
+
const SESSION_KEY=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
285
|
+
export function hostRegistryDir(env=process.env){return path.join(notifyHome(env),'hosts');}
|
|
286
|
+
export function writeHostRegistry({sessionKey,workflow,project,startedAt,row=null,operation=null},{env=process.env,now=Date.now()}={}){
|
|
287
|
+
try{
|
|
288
|
+
if(!readNotifyConfig(env)||!SESSION_KEY.test(sessionKey))return false;
|
|
289
|
+
const dir=hostRegistryDir(env);fs.mkdirSync(dir,{recursive:true,mode:0o700});
|
|
290
|
+
const result=obj(row?.result);
|
|
291
|
+
const entry={version:1,pid:process.pid,sessionKey,workflow:clean(workflow,24)||'cm',
|
|
292
|
+
project:typeof project==='string'?project:'',startedAt:new Date(startedAt).toISOString(),at:new Date(now).toISOString(),
|
|
293
|
+
operation:clean(operation,32)||null,
|
|
294
|
+
runId:text(result.identity?.runId)??text(result.runId)??text(result.batchId)??null,
|
|
295
|
+
task:text(result.identity?.taskId)??text(result.taskId)??null,
|
|
296
|
+
stage:text(result.stage)??text(result.state)??text(result.status)??null};
|
|
297
|
+
const file=path.join(dir,`${sessionKey}.json`),temp=`${file}.${process.pid}.tmp`;
|
|
298
|
+
fs.writeFileSync(temp,JSON.stringify(entry),{mode:0o600});fs.renameSync(temp,file);return true;
|
|
299
|
+
}catch{return false;}
|
|
300
|
+
}
|
|
301
|
+
// Same test guard as readNotifyConfig: a test suite without an explicit
|
|
302
|
+
// CM_WORKFLOW_HOME never touches the user's real directory, not even to unlink.
|
|
303
|
+
export function removeHostRegistry(sessionKey,{env=process.env}={}){
|
|
304
|
+
if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return;
|
|
305
|
+
try{if(SESSION_KEY.test(sessionKey))fs.unlinkSync(path.join(hostRegistryDir(env),`${sessionKey}.json`));}catch{}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Host side: one notice when a host_request has waited waitMinutes for the
|
|
309
|
+
// session's answer. The timer never keeps the process alive.
|
|
310
|
+
const CHECK_KINDS=new Set(['check','verification_precheck','init_verify']);
|
|
311
|
+
export function scheduleWaitNotice({kind,callId,workflow,project,env=process.env}){
|
|
312
|
+
try{
|
|
313
|
+
const config=readNotifyConfig(env);if(!config)return null;
|
|
314
|
+
// A check request is answered only after the session has run the project's
|
|
315
|
+
// check commands (xcodebuild, test suites), which normally take tens of
|
|
316
|
+
// minutes; waiting that long is not idleness, so it uses its own threshold.
|
|
317
|
+
const waitMs=CHECK_KINDS.has(kind)?config.checkWaitMs:config.waitMs;
|
|
318
|
+
const minutes=Math.max(1,Math.round(waitMs/60000));
|
|
319
|
+
const timer=setTimeout(()=>{notify({key:`wait|${workflow}|${callId}`,event:'waiting',workflow,project,stage:kind,
|
|
320
|
+
code:'waiting_session_answer',nextAction:`宿主已等待会话应答约 ${minutes} 分钟,请回到会话处理`},{env});},waitMs);
|
|
321
|
+
timer.unref?.();
|
|
322
|
+
return ()=>clearTimeout(timer);
|
|
323
|
+
}catch{return null;}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// Host side: one notice when an operation has replied, nothing is in flight
|
|
327
|
+
// and the session has not sent the next operation for idleMinutes (polls excluded). A last
|
|
328
|
+
// result that already waits on a person (or ended the run) says so instead of
|
|
329
|
+
// "idle". Built only from that result's structured fields; the timer never
|
|
330
|
+
// keeps the process alive.
|
|
331
|
+
export function scheduleIdleNotice({workflow,project,sessionKey,seq,row,since=Date.now(),env=process.env}){
|
|
332
|
+
try{
|
|
333
|
+
const config=readNotifyConfig(env);if(!config)return null;
|
|
334
|
+
// `since` is the last real reply: re-arming after a poll keeps that deadline.
|
|
335
|
+
const delay=Math.max(1,Math.min(config.idleMs,config.idleMs-(Date.now()-since)));
|
|
336
|
+
const minutes=Math.max(1,Math.round(config.idleMs/60000));
|
|
337
|
+
const kind=classifyDriveResult(workflow,row),result=obj(row?.result);
|
|
338
|
+
const runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
|
|
339
|
+
const task=text(result.identity?.taskId)??text(result.taskId);
|
|
340
|
+
const stage=text(result.stage)??text(result.state)??text(result.status);
|
|
341
|
+
const nextAction=kind==='done'?`流程已结束,宿主仍开着约 ${minutes} 分钟没有下一步,请回到会话收尾或开始下一项`
|
|
342
|
+
:kind==='stuck'?`上一步停在需要你处理的状态,约 ${minutes} 分钟没有下一步,请回到会话处理`
|
|
343
|
+
:`上一步已结束约 ${minutes} 分钟,会话没有发下一步,请回到会话查看`;
|
|
344
|
+
const timer=setTimeout(()=>{notify({key:`idle|${workflow}|${sessionKey}|${seq}`,event:kind?'idle_waiting':'idle',
|
|
345
|
+
workflow,project,runId,task,stage,code:kind?'waiting_for_you':'no_next_step',nextAction},{env});},delay);
|
|
346
|
+
timer.unref?.();
|
|
347
|
+
return ()=>clearTimeout(timer);
|
|
348
|
+
}catch{return null;}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Driver side: decide from the final host response (or the driver's own stop)
|
|
352
|
+
// whether a person is needed. Each workflow is classified by its own result
|
|
353
|
+
// contract (see the host named in each entry); normal progress returns null.
|
|
354
|
+
// 'stuck' = stopped until a person acts; 'done' = the run has ended.
|
|
355
|
+
const text=value=>typeof value==='string'&&value?value:null;
|
|
356
|
+
const obj=value=>value&&typeof value==='object'&&!Array.isArray(value)?value:{};
|
|
357
|
+
const STUCK_COMMON=new Set(['blocked','cancelled','failed','interrupted']);
|
|
358
|
+
const verdict=(value,{done,stuck})=>stuck.has(value)?'stuck':done.has(value)?'done':null;
|
|
359
|
+
// cm-fix owner projection (runtime/js/cm-fix/execution.mjs, progress.mjs): stages
|
|
360
|
+
// on the normal path continue; everything else falls through to "a person
|
|
361
|
+
// decides", exactly like fixProgress's requiresUser fallback.
|
|
362
|
+
const FIX_FLOW=new Set(['reproduce','diagnose','cause_review_required','test_author_required','red_test_required',
|
|
363
|
+
'design_change_required','baseline_required','repair_required','regression_required','handoff_required',
|
|
364
|
+
'learning_writeback_required','handoff_ready','final_review_required','final_review_evidence_required',
|
|
365
|
+
'completion_gate_required','post_review_regression_required','closeout_required','escalation_required',
|
|
366
|
+
'observation_resume_prepared','observation_diagnose_required','revision_prepared','revision_test_author_required',
|
|
367
|
+
'revision_test_check_required']);
|
|
368
|
+
function classifyFix(r){
|
|
369
|
+
const stage=text(r.stage);if(!stage)return null;
|
|
370
|
+
if(stage==='completed')return 'done';
|
|
371
|
+
if(r.progress&&typeof r.progress==='object'){if(r.progress.finished===true)return 'done';if(r.progress.requiresUser===true)return 'stuck';}
|
|
372
|
+
// A refused review authorization keeps the stage (execution.mjs) but waits on a person.
|
|
373
|
+
if(text(r.reason)==='permission_denied')return 'stuck';
|
|
374
|
+
return FIX_FLOW.has(stage)||FIX_FLOW.has(stage.replace(/^revision_/,''))?null:'stuck';
|
|
375
|
+
}
|
|
376
|
+
// cm-ai conversation entry (runtime/js/cm-ai/cm-ai-conversation-entry.mjs, operator-guidance.mjs,
|
|
377
|
+
// task-runner.mjs) and the QA-fix owner (host-qa-fix-owner.mjs). The only run end is
|
|
378
|
+
// run_done; start_next_task hands over to the next task and is progress.
|
|
379
|
+
const AI_PROGRESS_CODES=new Set(['context_refreshed','context_complete','qa_skipped','qa_passed','documentation_synced',
|
|
380
|
+
'documentation_sync_required','revision_answer_required']);
|
|
381
|
+
const AI_STUCK_STATES=new Set(['blocked','unknown','pending_review','cancelled','awaiting_spec_approval']);
|
|
382
|
+
const AI_STUCK_ACTIONS=new Set(['reconcile','abandon_effect','abandon_review','reconcile_review','bootstrap_review_recover',
|
|
383
|
+
'review_evidence','spec_rebind','fix_authorization','fix_dispatch','qa_execution']);
|
|
384
|
+
const AI_STUCK_CODES=new Set(['decision_required','permission_denied','provider_development_authorization_required',
|
|
385
|
+
'qa_decision_required','qa_mandatory_required','qa_triggered','qa_blocked','qa_failed','qa_result_blocked',
|
|
386
|
+
'qa_execution_unknown','correction_review_required','project_qa_not_passed','documentation_sync_blocked',
|
|
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']);
|
|
392
|
+
function classifyAi(r){
|
|
393
|
+
const state=text(r.state),code=text(r.code),outcome=text(r.outcome);
|
|
394
|
+
if(state==='run_done'&&['run_done','run_done_degraded'].includes(code))return 'done';
|
|
395
|
+
if(code==='qa_fix_incomplete')return classifyFix({stage:r.fixStage});
|
|
396
|
+
if(['qa_fix_completed','qa_fix_active','qa_fix_owner_busy'].includes(code)||outcome==='abandoned')return null;
|
|
397
|
+
if(r.pendingAction==='start_next_task'||AI_PROGRESS_CODES.has(code))return null;
|
|
398
|
+
if(['rejected','denied','cancelled','blocked','awaiting'].includes(outcome)||AI_STUCK_STATES.has(state)
|
|
399
|
+
||AI_STUCK_ACTIONS.has(r.pendingAction)||AI_STUCK_CODES.has(code))return 'stuck';
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
const CLASSIFY={
|
|
403
|
+
'cm-ai':classifyAi,
|
|
404
|
+
// scripts/cm-ai-batch-run.mjs: member results pass through; batch-level stops
|
|
405
|
+
// carry outcome blocked/cancelled; the last member's run_done ends the batch.
|
|
406
|
+
'cm-ai-batch':classifyAi,
|
|
407
|
+
'cm-fix':classifyFix,
|
|
408
|
+
// runtime/js/cm-prd/analysis.mjs, change.mjs, summary.mjs, draft-save.mjs, review-*.mjs; scripts/cm-prd-host.mjs.
|
|
409
|
+
'cm-prd'(r){
|
|
410
|
+
const stage=text(r.stage),status=text(r.status),review=obj(r.reviewState);
|
|
411
|
+
if(stage==='awaiting_review'||status==='awaiting_review')return 'done';
|
|
412
|
+
if(STUCK_COMMON.has(stage)||STUCK_COMMON.has(status))return 'stuck';
|
|
413
|
+
if(['awaiting_user','awaiting_planning_user','awaiting_design_user','self_check_needs_human','change_confirmation',
|
|
414
|
+
'change_rejected','inputs_replaced'].includes(stage))return 'stuck';
|
|
415
|
+
if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
|
|
416
|
+
if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'stuck';
|
|
417
|
+
if(status&&(/_unknown$/.test(status)||['correction_recovery_required','correction_recovery_conflict','disposition_details_need_verification'].includes(status)))return 'stuck';
|
|
418
|
+
if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
|
|
419
|
+
if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
|
|
420
|
+
if(['review_unknown','review_cancelled'].includes(review.status)||review.verdict==='blocked'
|
|
421
|
+
||obj(review.gate).outcome==='dispatch_unknown')return 'stuck';
|
|
422
|
+
if(Array.isArray(obj(r.recovery).calls)&&r.recovery.calls.some(call=>obj(call).status==='unknown'))return 'stuck';
|
|
423
|
+
return null;
|
|
424
|
+
},
|
|
425
|
+
// scripts/cm-idea-host.mjs.
|
|
426
|
+
'cm-idea'(r){
|
|
427
|
+
const stage=text(r.stage),recovery=obj(r.recovery);
|
|
428
|
+
if(stage==='saved')return 'done';
|
|
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';
|
|
432
|
+
if(stage==='draft_ready')return r.confirmationRequired===true?null:'stuck';
|
|
433
|
+
return ['awaiting_user','save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
|
|
434
|
+
},
|
|
435
|
+
// scripts/cm-init-host.mjs, runtime/js/cm-init/draft-generation.mjs (generation returns status, no stage).
|
|
436
|
+
'cm-init'(r){
|
|
437
|
+
const stage=text(r.stage)??(r.status==='blocked'?'blocked':null),recovery=obj(r.recovery);
|
|
438
|
+
if(['rules_written','rules_present'].includes(stage))return 'done';
|
|
439
|
+
if(recovery.writing===true||['unknown','recorded'].includes(obj(recovery.call).status))return 'stuck';
|
|
440
|
+
return ['analysis_blocked','verification_blocked','confirmation_required','confirmation_rejected','review_changes_requested',
|
|
441
|
+
'review_blocked','write_incomplete','write_unknown',...STUCK_COMMON].includes(stage)?'stuck':null;
|
|
442
|
+
},
|
|
443
|
+
// runtime/js/cm-refactor/workflow.mjs.
|
|
444
|
+
'cm-refactor'(r){
|
|
445
|
+
const stage=text(r.stage);
|
|
446
|
+
if(['done','not_needed','rejected'].includes(stage))return 'done';
|
|
447
|
+
return ['awaiting_finish','rulebook_rejected','correction_required',...STUCK_COMMON].includes(stage)?'stuck':null;
|
|
448
|
+
},
|
|
449
|
+
// runtime/js/cm-test/host.mjs: verdict in result.overall when stage is reported.
|
|
450
|
+
'cm-test'(r){
|
|
451
|
+
if(r.historical===true)return null;
|
|
452
|
+
const stage=text(r.stage);
|
|
453
|
+
if(stage==='reported')return verdict(r.overall,{stuck:new Set(['FAIL','BLOCKED','FINDING']),
|
|
454
|
+
done:new Set(['PASS','GENERATED','NO_CHANGES','ANALYZED','PARTIAL','REVIEWED','NO_FINDING'])})??'stuck';
|
|
455
|
+
return STUCK_COMMON.has(stage)?'stuck':null;
|
|
456
|
+
},
|
|
457
|
+
// runtime/js/cm-check/host.mjs: verdict nested in result.result.overall.
|
|
458
|
+
'cm-check'(r){
|
|
459
|
+
const stage=text(r.stage);
|
|
460
|
+
if(stage==='reported')return verdict(obj(r.result).overall,{stuck:new Set(['FAILED','BLOCKED']),
|
|
461
|
+
done:new Set(['PASSED','MECHANICAL_ONLY'])})??'stuck';
|
|
462
|
+
return STUCK_COMMON.has(stage)?'stuck':null;
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
// Inspection operations never notify (per host help and driver READ_ONLY sets).
|
|
466
|
+
const READ_ONLY=new Set(['status','fix_status','cancel','qa_result','context_refresh','read_batch','inspect_correction',
|
|
467
|
+
'final_review_package','review_findings','completion_evidence','cause_review_package']);
|
|
468
|
+
export const NOTIFY_WORKFLOWS=Object.freeze(Object.keys(CLASSIFY));
|
|
469
|
+
export function classifyDriveResult(workflow,row){
|
|
470
|
+
if(row?.error)return 'stuck';
|
|
471
|
+
const classify=CLASSIFY[workflow];
|
|
472
|
+
return classify?classify(obj(row?.result)):null;
|
|
473
|
+
}
|
|
474
|
+
export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
|
|
475
|
+
if(READ_ONLY.has(operation))return null;
|
|
476
|
+
const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
|
|
477
|
+
const kind=failure?'stuck':classifyDriveResult(workflow,row);
|
|
478
|
+
if(!kind)return null;
|
|
479
|
+
const done=kind==='done',result=obj(row?.result),progress=obj(result.progress),nested=obj(result.result);
|
|
480
|
+
const code=text(failure)??text(row?.error?.code)??text(result.code)??text(result.reason)??text(result.blocker)
|
|
481
|
+
??text(progress.blocker)??text(result.overall)??text(nested.overall)??text(result.state)??text(result.status)??text(result.stage)??null;
|
|
482
|
+
const runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
|
|
483
|
+
const task=text(result.identity?.taskId)??text(result.taskId);
|
|
484
|
+
const attempt=Number.isSafeInteger(result.identity?.attempt)?result.identity.attempt:null;
|
|
485
|
+
const stage=text(result.stage)??text(result.state)??text(result.status)??operation??null;
|
|
486
|
+
const run=runId??`args:${keyHash(args.map(String).join('\0'))}`;
|
|
487
|
+
return {key:[workflow,run,task??'',attempt??'',stage??'',done?'done':code??''].join('|'),
|
|
488
|
+
event:kind,workflow,project:cwd?path.basename(path.resolve(cwd)):null,runId,task,stage,
|
|
489
|
+
code:done?(text(result.code)??text(result.overall)??text(nested.overall)??'done'):code,
|
|
490
|
+
// A finished unit is the natural point to start a fresh session (runtime/model-efficiency.md).
|
|
491
|
+
nextAction:done?'建议在新会话里开始下一个任务,减少重复读入的上下文':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction)};
|
|
492
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -33,6 +33,23 @@ shared contract, or review finding shows that the packet is insufficient.
|
|
|
33
33
|
Record the reason and newly added scope; do not reread or resend unchanged full
|
|
34
34
|
context. `cm-prd` additionally follows its progressive context-scope contract.
|
|
35
35
|
|
|
36
|
+
## Session boundary
|
|
37
|
+
|
|
38
|
+
Conversation length can outweigh packet size. In one real project sample
|
|
39
|
+
(2026-09-27 to 10-09, 8,417 calls, measured with a local token report), a single
|
|
40
|
+
long session carried 89% of weighted usage: each call re-read about 480k tokens
|
|
41
|
+
of prior history while producing a few hundred output tokens. This is one
|
|
42
|
+
sample, not a general measurement; it motivates suggesting fresh sessions, not a
|
|
43
|
+
claim about every project.
|
|
44
|
+
|
|
45
|
+
Workflows therefore suggest, at the end of a unit of work (a single-task cm-ai
|
|
46
|
+
run at `run_done`, a cm-prd human-review stop, a cm-fix run), starting the next
|
|
47
|
+
unit in a fresh session, which becomes the next run's host context. Batches are
|
|
48
|
+
excluded: a batch hands over to its next task inside the same `advance` and
|
|
49
|
+
keeps its original host context; the suggestion comes only after the whole batch
|
|
50
|
+
ends. Mid-run handover uses the workflow's documented cross-session resume. Changing sessions never rewrites records, skips review, or resets
|
|
51
|
+
authorization.
|
|
52
|
+
|
|
36
53
|
## Stable prefix
|
|
37
54
|
|
|
38
55
|
When an integration owns the prompt assembly, keep reusable instructions in
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CI 分片:把测试文件按实测耗时分到 N 份,每个文件恰好落在一份里。
|
|
3
|
+
// 以前按排序后的序号轮流分,最慢的几个文件挤进同一份,那一份比别的慢近一倍。
|
|
4
|
+
// 现在用 ci-test-weights.json 里记的秒数做贪心分配(最重的先放进当前最轻的一份),
|
|
5
|
+
// 表里没有的新文件按表中位数计,所以新增测试不用先改表也会被分到某一份。
|
|
6
|
+
// 只决定哪份跑哪些文件,不跳过、不过滤任何文件。
|
|
7
|
+
// 用法:node scripts/ci-test-shards.mjs --shards 4 --index 0 scripts/a.test.mjs scripts/b.test.mjs ...
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import {fileURLToPath} from 'node:url';
|
|
11
|
+
|
|
12
|
+
const weightsFile=fileURLToPath(new URL('./ci-test-weights.json',import.meta.url));
|
|
13
|
+
|
|
14
|
+
export function readWeights(file=weightsFile){
|
|
15
|
+
const raw=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
16
|
+
const weights=new Map();
|
|
17
|
+
for(const [name,seconds] of Object.entries(raw.seconds??{})){
|
|
18
|
+
if(!Number.isFinite(seconds)||seconds<0)throw new Error(`invalid weight for ${name}`);
|
|
19
|
+
weights.set(name,seconds);
|
|
20
|
+
}
|
|
21
|
+
return weights;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function median(values){
|
|
25
|
+
const sorted=[...values].sort((a,b)=>a-b);
|
|
26
|
+
if(sorted.length===0)return 1;
|
|
27
|
+
const mid=Math.floor(sorted.length/2);
|
|
28
|
+
return sorted.length%2?sorted[mid]:(sorted[mid-1]+sorted[mid])/2;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Deterministic longest-processing-time assignment: heaviest file first, ties by
|
|
32
|
+
// name; each goes to the currently lightest shard, ties by lowest shard index.
|
|
33
|
+
export function assignShards(files,shards,weights){
|
|
34
|
+
if(!Number.isInteger(shards)||shards<1)throw new Error('shards must be a positive integer');
|
|
35
|
+
const unique=[...new Set(files)];
|
|
36
|
+
if(unique.length!==files.length)throw new Error('duplicate test file');
|
|
37
|
+
const fallback=median(weights.values());
|
|
38
|
+
const weightOf=file=>weights.get(path.basename(file))??fallback;
|
|
39
|
+
const order=[...files].sort((a,b)=>weightOf(b)-weightOf(a)||(a<b?-1:a>b?1:0));
|
|
40
|
+
const result=Array.from({length:shards},()=>({files:[],seconds:0}));
|
|
41
|
+
for(const file of order){
|
|
42
|
+
let target=0;
|
|
43
|
+
for(let i=1;i<shards;i++)if(result[i].seconds<result[target].seconds)target=i;
|
|
44
|
+
result[target].files.push(file);result[target].seconds+=weightOf(file);
|
|
45
|
+
}
|
|
46
|
+
for(const shard of result)shard.files.sort();
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function main(argv){
|
|
51
|
+
let shards=null,index=null;const files=[];
|
|
52
|
+
for(let i=0;i<argv.length;i++){
|
|
53
|
+
if(argv[i]==='--shards')shards=Number(argv[++i]);
|
|
54
|
+
else if(argv[i]==='--index')index=Number(argv[++i]);
|
|
55
|
+
else if(argv[i]==='--summary')index='summary';
|
|
56
|
+
else files.push(argv[i]);
|
|
57
|
+
}
|
|
58
|
+
const result=assignShards(files,shards,readWeights());
|
|
59
|
+
if(index==='summary'){
|
|
60
|
+
result.forEach((shard,i)=>process.stdout.write(`shard ${i}: ${shard.files.length} files, ~${Math.round(shard.seconds)}s\n`));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if(!Number.isInteger(index)||index<0||index>=shards)throw new Error('index must be in [0, shards)');
|
|
64
|
+
for(const file of result[index].files)process.stdout.write(file+'\n');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main(process.argv.slice(2));
|