@aibyzero/cm-workflow 0.16.7 → 0.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +18 -0
  3. package/README.md +26 -1
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/docs/installation.md +1 -1
  8. package/docs/js-workflow-control.md +36 -3
  9. package/docs/user-guide.md +104 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +27 -6
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +82 -8
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  15. package/runtime/js/cm-ai/drive-core.mjs +17 -4
  16. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  17. package/runtime/js/cm-ai/host-qa-executor.mjs +37 -13
  18. package/runtime/js/cm-ai/host-session.mjs +46 -6
  19. package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
  20. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  21. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  22. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  23. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  24. package/runtime/js/cm-fix/execution.mjs +189 -148
  25. package/runtime/js/cm-fix/investigation.mjs +25 -9
  26. package/runtime/js/cm-fix/progress.mjs +3 -1
  27. package/runtime/js/notify-run.mjs +26 -0
  28. package/runtime/js/notify.mjs +388 -0
  29. package/runtime/model-efficiency.md +17 -0
  30. package/scripts/cm-ai-batch-run.mjs +5 -0
  31. package/scripts/cm-ai-batch-run.test.mjs +9 -1
  32. package/scripts/cm-ai-drive.mjs +4 -1
  33. package/scripts/cm-ai-drive.test.mjs +8 -0
  34. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  35. package/scripts/cm-ai-host.mjs +2 -2
  36. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  37. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
  38. package/scripts/cm-fix-abandon.test.mjs +89 -3
  39. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  40. package/scripts/cm-fix-drive.mjs +9 -1
  41. package/scripts/cm-fix-host.mjs +1 -1
  42. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  43. package/scripts/cm-host-qa-executor.test.mjs +121 -0
  44. package/scripts/cm-log-event.mjs +31 -5
  45. package/scripts/cm-notify.test.mjs +468 -0
  46. package/scripts/cm-patrol.mjs +83 -0
  47. package/scripts/cm-patrol.test.mjs +161 -0
  48. package/scripts/cm-token-report.mjs +497 -0
  49. package/scripts/cm-token-report.test.mjs +346 -0
  50. package/skills/cm-ai/SKILL.md +7 -3
  51. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  52. package/skills/cm-ai/references/js-host-modes.md +90 -0
  53. package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
  54. package/skills/cm-ai/references/js-host-recovery.md +199 -0
  55. package/skills/cm-ai/references/js-host.md +67 -329
  56. package/skills/cm-fix/SKILL.md +2 -0
  57. package/skills/cm-fix/references/js-host.md +16 -9
  58. package/skills/cm-prd/SKILL.md +2 -0
@@ -0,0 +1,468 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn,spawnSync} from 'node:child_process';
7
+ import {notify,readNotifyConfig,buildNotifyMessage,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS} from '../runtime/js/notify.mjs';
8
+
9
+ const NOW=Date.parse('2026-10-08T08:00:00.000Z');
10
+ const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
11
+ const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
12
+ const HOST_SESSION=new URL('../runtime/js/cm-ai/host-session.mjs',import.meta.url).href;
13
+
14
+ // A temp CM_WORKFLOW_HOME with notify.json pointing at a fake command that
15
+ // appends its environment message and stdin payload to sent.jsonl.
16
+ function home(t,{exit=0,sleepMs=0,config={}}={}){
17
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-')));
18
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
19
+ const sent=path.join(dir,'sent.jsonl'),script=path.join(dir,'fake-notify.mjs');
20
+ fs.writeFileSync(script,`import fs from 'node:fs';let input='';process.stdin.on('data',c=>input+=c);
21
+ process.stdin.on('end',()=>{setTimeout(()=>{fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify({title:process.env.CM_NOTIFY_TITLE,
22
+ body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');process.exit(${exit});},${sleepMs});});`);
23
+ fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script],...config}));
24
+ const env={...process.env,CM_WORKFLOW_HOME:dir};
25
+ const rows=()=>fs.existsSync(sent)?fs.readFileSync(sent,'utf8').trim().split('\n').map(line=>JSON.parse(line)):[];
26
+ const log=()=>fs.existsSync(path.join(dir,'notify.log'))?fs.readFileSync(path.join(dir,'notify.log'),'utf8'):'';
27
+ const until=async(check,ms=8000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,25));return check();};
28
+ return {dir,env,rows,log,until};
29
+ }
30
+ const fields=(key,over={})=>({key,event:'stuck',project:'/srv/work/demo-app',workflow:'cm-fix',runId:'run-1',
31
+ task:'T-001',stage:'blocked',code:'checks_not_passed',nextAction:'核对 reason 后恢复原运行',...over});
32
+
33
+ test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME is explicit',async t=>{
34
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-empty-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
35
+ assert.equal(readNotifyConfig({CM_WORKFLOW_HOME:dir}),null);
36
+ assert.deepEqual(notify(fields('a'),{env:{CM_WORKFLOW_HOME:dir},now:NOW}),{sent:false,reason:'off'});
37
+ assert.deepEqual(fs.readdirSync(dir),[]);
38
+ assert.equal(readNotifyConfig({NODE_TEST_CONTEXT:'child-v8'}),null);
39
+ });
40
+
41
+ test('invalid config turns the feature off: relative command, bad version, bad waitMinutes',t=>{
42
+ const h=home(t);const file=path.join(h.dir,'notify.json');
43
+ for(const value of [{version:1,command:['notify.sh']},{version:2,command:['/bin/true']},{version:1,command:[]},
44
+ {version:1,command:['/bin/true'],waitMinutes:0},'not json']){
45
+ fs.writeFileSync(file,typeof value==='string'?value:JSON.stringify(value));
46
+ assert.equal(readNotifyConfig(h.env),null,JSON.stringify(value));
47
+ }
48
+ assert.match(h.log(),/config - key=- off invalid_config command_not_absolute/);
49
+ fs.writeFileSync(file,JSON.stringify({version:1,command:['/bin/true'],waitMinutes:0.5}));
50
+ assert.deepEqual(readNotifyConfig(h.env),{command:['/bin/true'],waitMs:30000,checkWaitMs:2700000,idleMs:2700000});
51
+ });
52
+
53
+ test('message is bounded and built only from the structured fields',()=>{
54
+ const long='x'.repeat(2000);
55
+ const message=buildNotifyMessage({...fields('k'),workflow:long,project:'/very/secret/path/'+long,runId:long,task:long,
56
+ stage:long,code:long,nextAction:`读 /srv/private/push.env 和 ~/secret/file 后\n${long}`,
57
+ diff:'DIFF-CONTENT',log:'LOG-CONTENT',env:{TOKEN:'SECRET'}},{now:NOW});
58
+ assert(Array.from(message.title).length<=NOTIFY_LIMITS.titleChars);
59
+ assert(Array.from(message.body).length<=NOTIFY_LIMITS.bodyChars);
60
+ for(const forbidden of ['DIFF-CONTENT','LOG-CONTENT','SECRET','push.env','/srv/','/very/secret','~/secret','\0'])
61
+ assert(!message.body.includes(forbidden)&&!message.title.includes(forbidden),forbidden);
62
+ assert.match(message.body,/<路径>/);
63
+ const short=buildNotifyMessage(fields('k'),{now:NOW});
64
+ assert.equal(short.title,'CM cm-fix 需要人处理 · demo-app');
65
+ assert.match(short.body,/^项目:demo-app\n流程:cm-fix\n运行:run-1\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n下一步:/);
66
+ assert.match(short.body,/CM 不会自动继续/);
67
+ });
68
+
69
+ test('sends through env and stdin once per key; the same key within 6 hours is skipped',async t=>{
70
+ const h=home(t);
71
+ assert.deepEqual(notify(fields('same'),{env:h.env,now:NOW}),{sent:true,reason:'launched'});
72
+ assert.deepEqual(notify(fields('same'),{env:h.env,now:NOW+5*3600*1000}),{sent:false,reason:'duplicate'});
73
+ assert(await h.until(()=>h.rows().length===1));
74
+ const [row]=h.rows();
75
+ assert.equal(row.title,'CM cm-fix 需要人处理 · demo-app');assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);
76
+ assert.equal(row.stdin.project,'demo-app');assert.equal(row.stdin.code,'checks_not_passed');assert.equal(row.stdin.key,undefined);
77
+ assert.equal(notify(fields('same'),{env:h.env,now:NOW+6*3600*1000+1}).sent,true);
78
+ assert(await h.until(()=>h.rows().length===2));
79
+ assert.equal(h.rows()[0].stdin.CM_NOTIFY_PAYLOAD,undefined);
80
+ const state=JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8'));
81
+ assert.equal(JSON.stringify(state).includes('same'),false);
82
+ assert(!fs.existsSync(path.join(h.dir,'notify-state.lock')));
83
+ });
84
+
85
+ test('at most 4 per rolling minute and 150 per day across keys',async t=>{
86
+ const h=home(t);
87
+ for(let i=0;i<4;i++)assert.equal(notify(fields(`m${i}`),{env:h.env,now:NOW+i}).sent,true);
88
+ assert.deepEqual(notify(fields('m4'),{env:h.env,now:NOW+10}),{sent:false,reason:'rate_minute'});
89
+ assert.equal(notify(fields('m4'),{env:h.env,now:NOW+60010}).sent,true);
90
+ assert.match(h.log(),/skipped rate_minute/);
91
+ const sends=Array.from({length:150},(_,i)=>NOW+120000+i*60000);
92
+ fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:1,keys:{},sends}));
93
+ assert.deepEqual(notify(fields('day'),{env:h.env,now:NOW+200*60000}),{sent:false,reason:'rate_day'});
94
+ assert.equal(notify(fields('day'),{env:h.env,now:NOW+120000+24*3600*1000}).sent,true);
95
+ assert(await h.until(()=>h.rows().length===6));
96
+ });
97
+
98
+ test('command failure, timeout and broken state never throw; they log one line without content',async t=>{
99
+ const failing=home(t,{exit:3});
100
+ assert.deepEqual(notify(fields('f'),{env:failing.env,now:NOW}),{sent:true,reason:'launched'});
101
+ assert(await failing.until(()=>failing.log()!==''));
102
+ assert.match(failing.log(),/^\S+ stuck cm-fix key=[0-9a-f]{16} failed exit_3\n$/);
103
+ const slow=home(t,{sleepMs:5000});
104
+ assert.equal(notify(fields('s'),{env:slow.env,now:NOW,timeoutMs:200}).sent,true);
105
+ assert(await slow.until(()=>/failed timeout/.test(slow.log())));
106
+ const missing=home(t);fs.writeFileSync(path.join(missing.dir,'notify.json'),JSON.stringify({version:1,command:['/nonexistent/notify-cmd']}));
107
+ assert.equal(notify(fields('n'),{env:missing.env,now:NOW}).sent,true);assert(await missing.until(()=>/failed spawn_enoent/.test(missing.log())));
108
+ const broken=home(t);fs.writeFileSync(path.join(broken.dir,'notify-state.json'),'{');
109
+ assert.deepEqual(notify(fields('b'),{env:broken.env,now:NOW}),{sent:false,reason:'state_invalid'});
110
+ await new Promise(r=>setTimeout(r,300));
111
+ for(const h of [slow,missing,broken])assert.equal(h.rows().length,0);
112
+ for(const h of [failing,slow,missing,broken])assert(!/demo-app|T-001|核对|run-1/.test(h.log()));
113
+ });
114
+
115
+ // Lock contention never waits; only a provably stale lock is reclaimed, and
116
+ // a live lock is never removed.
117
+ test('lock: a live lock skips at once and is kept; a stale lock is reclaimed safely',async t=>{
118
+ const live=home(t),lockFile=path.join(live.dir,'notify-state.lock');
119
+ const liveBody=JSON.stringify({pid:process.pid,at:Date.now(),token:'other'});fs.writeFileSync(lockFile,liveBody);
120
+ const started=performance.now();
121
+ assert.deepEqual(notify(fields('l'),{env:live.env,now:NOW}),{sent:false,reason:'state_busy'});
122
+ assert(performance.now()-started<50,'no synchronous waiting on contention');
123
+ assert.equal(fs.readFileSync(lockFile,'utf8'),liveBody);assert.match(live.log(),/skipped state_busy/);
124
+ const partial=home(t);fs.writeFileSync(path.join(partial.dir,'notify-state.lock'),'');
125
+ assert.equal(notify(fields('p'),{env:partial.env,now:NOW}).reason,'state_busy');
126
+ const dead=spawnSync(process.execPath,['-e','console.log(process.pid)'],{encoding:'utf8'}).stdout.trim();
127
+ for(const body of [{pid:Number(dead),at:Date.now(),token:'gone'},{pid:process.pid,at:Date.now()-60000,token:'old'}]){
128
+ const old=home(t),file=path.join(old.dir,'notify-state.lock');fs.writeFileSync(file,JSON.stringify(body));
129
+ assert.equal(notify(fields('o'),{env:old.env,now:NOW}).sent,true,JSON.stringify(body));
130
+ assert(!fs.existsSync(file));assert.deepEqual(fs.readdirSync(old.dir).filter(name=>name.includes('.lock.')),[]);
131
+ assert(await old.until(()=>old.rows().length===1));
132
+ }
133
+ });
134
+
135
+ test('respects CM_WORKFLOW_HOME: config, state and log stay in that directory',async t=>{
136
+ const a=home(t),b=home(t);fs.rmSync(path.join(b.dir,'notify.json'));
137
+ assert.equal(notify(fields('h'),{env:b.env,now:NOW}).reason,'off');
138
+ assert.equal(notify(fields('h'),{env:a.env,now:NOW}).sent,true);
139
+ assert(await a.until(()=>a.rows().length===1));
140
+ assert(fs.existsSync(path.join(a.dir,'notify-state.json')));assert(!fs.existsSync(path.join(b.dir,'notify-state.json')));
141
+ });
142
+
143
+ // Table-driven: each workflow's real result contract (host named per row)
144
+ // maps to stuck (a person must act), done (run ended) or null (progress).
145
+ const id={runId:'run-1',taskId:'T-001',attempt:1};
146
+ const ai=(over)=>({version:1,workflow:'cm-ai',operation:'advance',identity:id,packageDigest:'d',...over});
147
+ const CASES=[
148
+ // cm-ai: cm-ai-conversation-entry.mjs / operator-guidance.mjs / task-runner.mjs / host-qa-fix-owner.mjs
149
+ ['cm-ai','advance',ai({outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'}),'done'],
150
+ ['cm-ai','advance',ai({outcome:'finalized',state:'run_done',code:'run_done_degraded',pendingAction:'none'}),'done'],
151
+ ['cm-ai','advance',ai({outcome:'refreshed',state:'fixture_completed',code:'context_refreshed',pendingAction:'start_next_task'}),null],
152
+ ['cm-ai','start',ai({outcome:'advanced',state:'awaiting_review',code:null,pendingAction:'decision'}),null],
153
+ ['cm-ai','advance',ai({outcome:'advanced',state:'changes_requested',code:null,pendingAction:'resume'}),null],
154
+ ['cm-ai','complete',ai({outcome:'advanced',state:'fixture_completed',code:null,pendingAction:'qa'}),null],
155
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'fixture_completed',code:'documentation_sync_required',pendingAction:'documentation_sync'}),null],
156
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'changes_requested',code:'revision_answer_required',pendingAction:'resume'}),null],
157
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'awaiting_review',code:'decision_required',pendingAction:'decision'}),'stuck'],
158
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'fixture_completed',code:'qa_decision_required',pendingAction:'qa'}),'stuck'],
159
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'awaiting_spec_approval',code:'specs_not_approved',pendingAction:'none'}),'stuck'],
160
+ ['cm-ai','advance',ai({outcome:'recorded',state:'fixture_completed',code:'qa_triggered',pendingAction:'qa_execution'}),'stuck'],
161
+ ['cm-ai','advance',ai({outcome:'verified',state:'fixture_completed',code:'qa_failed',pendingAction:'fix_authorization'}),'stuck'],
162
+ ['cm-ai','advance',ai({outcome:'advanced',state:'blocked',code:'review_limit',pendingAction:'none'}),'stuck'],
163
+ ['cm-ai','advance',ai({outcome:'advanced',state:'pending_review',code:'review_transport_timeout',pendingAction:'resume'}),'stuck'],
164
+ ['cm-ai','advance',ai({outcome:'advanced',state:'unknown',code:'execution_error',pendingAction:'reconcile'}),'stuck'],
165
+ ['cm-ai','decision',ai({outcome:'rejected',state:null,code:'stale_decision',pendingAction:'none'}),'stuck'],
166
+ ['cm-ai','fix_advance',{outcome:'blocked',code:'qa_fix_incomplete',fixStage:'cause_review_required'},null],
167
+ ['cm-ai','fix_advance',{outcome:'blocked',code:'qa_fix_incomplete',fixStage:'repair_blocked'},'stuck'],
168
+ ['cm-ai','fix_run',{outcome:'verified',code:'qa_fix_completed'},null],
169
+ ['cm-ai','status',ai({outcome:'reported',state:'blocked',code:'review_limit',pendingAction:'none'}),null],
170
+ // cm-ai-batch: cm-ai-batch-run.mjs
171
+ ['cm-ai-batch','advance',{...ai({outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'}),batchId:'b1',task_commit:'abc'},'done'],
172
+ ['cm-ai-batch','advance',{outcome:'blocked',code:'merge_conflict',batchId:'b1',files:['a.js']},'stuck'],
173
+ ['cm-ai-batch','advance',{outcome:'blocked',code:'batch_task_scope_required'},'stuck'],
174
+ ['cm-ai-batch','advance',{outcome:'cancelled',code:'cancelled',batchId:'b1'},'stuck'],
175
+ ['cm-ai-batch','advance',{...ai({outcome:'advanced',state:'awaiting_review',code:null,pendingAction:'decision'}),batchId:'b1'},null],
176
+ // cm-fix: execution.mjs / progress.mjs
177
+ ['cm-fix','finish',{identity:id,stage:'completed',completionEligible:true},'done'],
178
+ ['cm-fix','advance',{identity:id,stage:'cause_review_required'},null],
179
+ ['cm-fix','cause_review',{identity:id,stage:'cause_review_required',reason:'permission_denied'},'stuck'],
180
+ ['cm-fix','final_review',{identity:id,stage:'final_review_required',reason:'permission_denied'},'stuck'],
181
+ ['cm-fix','final_review',{identity:id,stage:'revision_final_review_required',reason:'permission_denied'},'stuck'],
182
+ ['cm-fix','repair',{identity:id,stage:'revision_regression_required'},null],
183
+ ['cm-fix','repair',{identity:id,stage:'unknown',pending:'repair'},'stuck'],
184
+ ['cm-fix','cause_review',{identity:id,stage:'rediagnosis_review_limit_reached'},'stuck'],
185
+ ['cm-fix','regression',{identity:id,stage:'regression_blocked'},'stuck'],
186
+ ['cm-fix','finish',{identity:id,stage:'escalated',escalationRunEnded:true},'stuck'],
187
+ ['cm-fix','completion_evidence',{identity:id,stage:'unknown'},null],
188
+ // cm-prd: analysis.mjs / change.mjs / summary.mjs / draft-save.mjs / review-*.mjs
189
+ ['cm-prd','start',{stage:'awaiting_user',result:{status:'question',question:'q'},runId:'prd-1'},'stuck'],
190
+ ['cm-prd','advance',{stage:'analysis_ready',runId:'prd-1'},null],
191
+ ['cm-prd','plan',{stage:'self_check_needs_human',runId:'prd-1'},'stuck'],
192
+ ['cm-prd','plan',{stage:'draft_self_check_failed',runId:'prd-1'},null],
193
+ ['cm-prd','advance',{mode:'change',stage:'change_design',question:'which?',round:1},'stuck'],
194
+ ['cm-prd','advance',{mode:'change',stage:'change_check_failed',round:1},null],
195
+ ['cm-prd','advance',{mode:'change',stage:'change_check_failed',round:2},'stuck'],
196
+ ['cm-prd','advance',{mode:'change',stage:'change_confirmation'},'stuck'],
197
+ ['cm-prd','save_draft',{status:'draft_save_unknown'},'stuck'],
198
+ ['cm-prd','prepare_summary',{status:'human_summary_prepared',readyForAwaitingReview:false},'stuck'],
199
+ ['cm-prd','final_review',{stage:'draft_ready',reviewState:{status:'review_recorded',verdict:'blocked'}},'stuck'],
200
+ ['cm-prd','final_review',{stage:'draft_ready',reviewState:{status:'review_recorded',verdict:'approved'}},null],
201
+ ['cm-prd','publish_summary',{status:'awaiting_review',next:'human_review_then_explicit_cm_ai'},'done'],
202
+ ['cm-prd','save_draft',{status:'blocked',reason:'prd_host_result_unknown'},'stuck'],
203
+ // cm-idea: cm-idea-host.mjs
204
+ ['cm-idea','start',{stage:'awaiting_user',reply:{status:'question',question:'q',productType:null}},'stuck'],
205
+ ['cm-idea','advance',{stage:'draft_ready',reply:{status:'draft'}},'stuck'],
206
+ ['cm-idea','prepare_save',{stage:'draft_ready',confirmationRequired:true},null],
207
+ ['cm-idea','finish',{stage:'saved',saved:{maturity:'L1'}},'done'],
208
+ // cm-init: cm-init-host.mjs / draft-generation.mjs
209
+ ['cm-init','start',{stage:'analysis_ready'},null],
210
+ ['cm-init','start',{stage:'analysis_blocked'},'stuck'],
211
+ ['cm-init','advance',{workflow:'cm-init',status:'draft_generated'},null],
212
+ ['cm-init','advance',{workflow:'cm-init',status:'blocked',reason:'host_generation_blocked'},'stuck'],
213
+ ['cm-init','advance',{stage:'verification_blocked'},'stuck'],
214
+ ['cm-init','advance',{stage:'confirmation_required'},'stuck'],
215
+ ['cm-init','advance',{stage:'review_required'},null],
216
+ ['cm-init','advance',{stage:'rules_written'},'done'],
217
+ // cm-refactor: workflow.mjs
218
+ ['cm-refactor','resume',{stage:'awaiting_finish',runId:'refactor-1'},'stuck'],
219
+ ['cm-refactor','resume',{stage:'blocked',reason:'refactor_review_exhausted',runId:'refactor-1'},'stuck'],
220
+ ['cm-refactor','prepare_judge_revision',{stage:'judge_revision_prepared',runId:'refactor-1'},null],
221
+ ['cm-refactor','finish',{stage:'done',runId:'refactor-1'},'done'],
222
+ ['cm-refactor','start',{stage:'not_needed',runId:'refactor-1'},'done'],
223
+ // cm-test: cm-test/host.mjs
224
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'FAIL'},'stuck'],
225
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'BLOCKED'},'stuck'],
226
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'PASS'},'done'],
227
+ ['cm-test','start',{stage:'interrupted',runId:'test-1',pending:{key:'1'}},'stuck'],
228
+ ['cm-test','resume',{stage:'reported',runId:'test-1',overall:'FAIL',historical:true},null],
229
+ // cm-check: cm-check/host.mjs
230
+ ['cm-check','start',{stage:'reported',result:{overall:'FAILED'}},'stuck'],
231
+ ['cm-check','start',{stage:'reported',result:{overall:'BLOCKED'}},'stuck'],
232
+ ['cm-check','start',{stage:'reported',result:{overall:'PASSED'}},'done'],
233
+ ['cm-check','start',{stage:'reported',result:{overall:'MECHANICAL_ONLY'}},'done'],
234
+ ['cm-check','start',{stage:'blocked',result:{overall:'BLOCKED',reason:'check_source_changed'}},'stuck'],
235
+ ];
236
+ test('driver classification follows each workflow contract (table)',()=>{
237
+ assert.deepEqual([...new Set(CASES.map(([workflow])=>workflow))].sort(),[...NOTIFY_WORKFLOWS].sort());
238
+ for(const [workflow,operation,result,expected] of CASES){
239
+ const notice=driveNotice({host:`/x/scripts/${workflow}-host.mjs`,cwd:'/work/demo-app',args:['serve'],operation,
240
+ row:{requestId:'drive',result}});
241
+ assert.equal(notice?.event??null,expected,`${workflow} ${operation} ${JSON.stringify(result)}`);
242
+ if(expected==='done')assert.match(notice.nextAction,/新会话/,`${workflow} done suggests a fresh session`);
243
+ }
244
+ for(const workflow of NOTIFY_WORKFLOWS){
245
+ assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',row:{requestId:'drive',error:{code:'host_request_failed'}}}).event,'stuck');
246
+ assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',failure:'host_exited'}).code,'host_exited');
247
+ }
248
+ const blocked=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/work/demo-app',args:['serve'],operation:'advance',
249
+ row:{requestId:'drive',result:ai({outcome:'advanced',state:'blocked',code:'develop_checks_not_passed',pendingAction:'resume',
250
+ guidance:{nextStep:'修复后 advance'}})}});
251
+ assert.deepEqual({...blocked},{key:'cm-ai|run-1|T-001|1|blocked|develop_checks_not_passed',event:'stuck',workflow:'cm-ai',
252
+ project:'demo-app',runId:'run-1',task:'T-001',stage:'blocked',code:'develop_checks_not_passed',nextAction:'修复后 advance'});
253
+ const batch=driveNotice({host:'cm-ai-batch-host.mjs',cwd:'/w/p',args:['a'],operation:'advance',
254
+ row:{requestId:'drive',result:{outcome:'blocked',code:'merge_conflict',batchId:'b1'}}});
255
+ assert.equal(batch.runId,'b1');assert.equal(batch.code,'merge_conflict');
256
+ assert.match(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',operation:'advance',failure:'host_exited'}).key,/^cm-ai\|args:[0-9a-f]{16}\|/);
257
+ });
258
+
259
+ // Shared driver core (scripts/*-drive.mjs all use driveHost) with a host that
260
+ // stops on blocked: one notice; repeating the identical run sends nothing new.
261
+ // The notify command takes 3 s, yet the driver exits without waiting for it.
262
+ test('driver ending in blocked notifies exactly once, never waits for the command, and an identical run does not resend',async t=>{
263
+ const h=home(t,{sleepMs:3000});
264
+ const host=path.join(h.dir,'cm-ai-host.mjs'),wrapper=path.join(h.dir,'cm-ai-drive.mjs'),project=path.join(h.dir,'demo-app');
265
+ fs.mkdirSync(project);
266
+ fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
267
+ process.stdin.on('data',chunk=>{for(const line of String(chunk).split('\\n').filter(Boolean)){const row=JSON.parse(line);
268
+ if(row.requestId==='drive')process.stdout.write(JSON.stringify({requestId:'drive',result:{workflow:'cm-ai',outcome:'advanced',state:'blocked',
269
+ code:'checks_not_passed',pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1}}})+'\\n');}});
270
+ process.stdin.on('end',()=>process.exit(0));`);
271
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
272
+ driveHost({host:${JSON.stringify(host)},args:['serve'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
273
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
274
+ for(let i=0;i<2;i++){
275
+ const started=performance.now(),run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env,timeout:20000});
276
+ assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,'blocked');
277
+ assert(performance.now()-started<2000,`driver exit waited on the notify command: ${performance.now()-started} ms`);
278
+ assert.equal(h.rows().length,0,`run ${i}: the command is still running in the background`);
279
+ }
280
+ assert(await h.until(()=>h.rows().length===1));
281
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,1);
282
+ const [row]=h.rows();
283
+ assert.equal(row.title,'CM cm-ai 需要人处理 · demo-app');assert.equal(row.stdin.runId,'run-7');assert.equal(row.stdin.code,'checks_not_passed');
284
+ });
285
+
286
+ // Host bridge: a host_request outstanding past waitMinutes notifies once;
287
+ // an answer before then clears it; neither the timer nor a fired, slow
288
+ // notify command keeps the host alive.
289
+ test('host wait timer notifies once per call, is cleared on answer and does not keep the process alive',async t=>{
290
+ const h=home(t,{config:{waitMinutes:0.003}});
291
+ const script=path.join(h.dir,'cm-demo-host.mjs');
292
+ fs.writeFileSync(script,`import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
293
+ const mode=process.argv[2],bridge=createHostToolBridge();const sent=[];bridge.attach(row=>{sent.push(row);});
294
+ const answer=()=>{const r=sent.find(row=>row.type==='host_request');bridge.accept({type:'host_result',sessionId:r.sessionId,callId:r.callId,requestDigest:r.requestDigest,result:{ok:true}});};
295
+ const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
296
+ if(mode==='late'){const p=bridge.call('qa_browser',{},new AbortController().signal);await wait(1000);answer();await p;}
297
+ if(mode==='early'){const p=bridge.call('qa_logic',{},new AbortController().signal);await wait(20);answer();await p;await wait(1200);}
298
+ if(mode==='hang')bridge.call('develop',{},new AbortController().signal).catch(()=>{});`);
299
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
300
+ const late=spawnSync(process.execPath,[script,'late'],{encoding:'utf8',env,timeout:20000});
301
+ assert.equal(late.status,0,late.stderr);
302
+ assert(await h.until(()=>h.rows().length===1));
303
+ assert.equal(h.rows()[0].title,'CM cm-demo 等待会话应答 · '+path.basename(process.cwd()));
304
+ assert.equal(h.rows()[0].stdin.stage,'qa_browser');assert.equal(h.rows()[0].stdin.code,'waiting_session_answer');
305
+ const early=spawnSync(process.execPath,[script,'early'],{encoding:'utf8',env,timeout:20000});
306
+ assert.equal(early.status,0,early.stderr);await new Promise(resolve=>setTimeout(resolve,300));assert.equal(h.rows().length,1);
307
+ const slow=home(t,{sleepMs:3000,config:{waitMinutes:0.003}});
308
+ const fired=spawnSync(process.execPath,[script,'late'],{encoding:'utf8',env:{...env,CM_WORKFLOW_HOME:slow.dir},timeout:20000});
309
+ assert.equal(fired.status,0,fired.stderr);assert.equal(slow.rows().length,0,'host exited before the slow command finished');
310
+ assert(await slow.until(()=>slow.rows().length===1));
311
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({version:1,command:['/bin/true'],waitMinutes:10}));
312
+ const started=Date.now(),hang=spawnSync(process.execPath,[script,'hang'],{encoding:'utf8',env,timeout:20000});
313
+ assert.equal(hang.status,0,hang.stderr);assert(Date.now()-started<5000);
314
+ });
315
+
316
+ // A check request waits for the session to run the project's check commands,
317
+ // which normally takes tens of minutes: it uses checkWaitMinutes, not waitMinutes.
318
+ test('check requests use checkWaitMinutes so normal long checks are not reported as waiting',async t=>{
319
+ const h=home(t,{config:{waitMinutes:0.003}});
320
+ const script=path.join(h.dir,'cm-demo-host.mjs');
321
+ fs.writeFileSync(script,`import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
322
+ const kind=process.argv[2],bridge=createHostToolBridge();const sent=[];bridge.attach(row=>{sent.push(row);});
323
+ const p=bridge.call(kind,{},new AbortController().signal);await new Promise(resolve=>setTimeout(resolve,1000));
324
+ const r=sent.find(row=>row.type==='host_request');bridge.accept({type:'host_result',sessionId:r.sessionId,callId:r.callId,requestDigest:r.requestDigest,result:{ok:true}});await p;`);
325
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
326
+ for(const kind of ['check','verification_precheck','init_verify']){
327
+ const run=spawnSync(process.execPath,[script,kind],{encoding:'utf8',env,timeout:20000});assert.equal(run.status,0,run.stderr);
328
+ }
329
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,0,'default 45-minute check threshold');
330
+ const cfg=JSON.parse(fs.readFileSync(path.join(h.dir,'notify.json'),'utf8'));
331
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({...cfg,waitMinutes:10,checkWaitMinutes:0.003}));
332
+ const run=spawnSync(process.execPath,[script,'check'],{encoding:'utf8',env,timeout:20000});assert.equal(run.status,0,run.stderr);
333
+ assert(await h.until(()=>h.rows().length===1));assert.equal(h.rows()[0].stdin.stage,'check');
334
+ });
335
+ test('checkWaitMinutes is validated like waitMinutes',t=>{
336
+ const h=home(t,{config:{checkWaitMinutes:0}});
337
+ assert.equal(readNotifyConfig(h.env),null);
338
+ });
339
+
340
+ // Host session: after an operation replies, nothing is in flight and the
341
+ // session sends no next operation for idleMinutes, one notice says so. A last
342
+ // result that waits on a person says "在等你" instead. Any next operation or
343
+ // session end clears it; status polls are not progress.
344
+ function idleHost(h){
345
+ const script=path.join(h.dir,'cm-prd-host.mjs');
346
+ fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
347
+ const host={handle:async request=>{
348
+ if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
349
+ if(['status','fix_status'].includes(request.operation))return {stage:'status_only',doneAt:Date.now()};
350
+ return request.answer;}};
351
+ await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
352
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
353
+ // steps: [delayMs, request object | raw line string | null to end stdin];
354
+ // delay 'reply:<id>' waits until that requestId has been answered instead.
355
+ return async steps=>{
356
+ const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
357
+ let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
358
+ const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
359
+ const replied=id=>stdout.includes(`"requestId":"${id}"`);
360
+ for(const [delay,request] of steps){
361
+ if(typeof delay==='string'){
362
+ const id=delay.slice(6),deadline=Date.now()+15000;
363
+ while(!replied(id)){if(Date.now()>deadline){child.kill();throw new Error(`no reply for ${id}`);}await new Promise(resolve=>setTimeout(resolve,10));}
364
+ }
365
+ else await new Promise(resolve=>setTimeout(resolve,delay));
366
+ if(request===null){child.stdin.end();break;}
367
+ if(request!==undefined)child.stdin.write((typeof request==='string'?request:JSON.stringify(request))+'\n');
368
+ }
369
+ const started=Date.now(),code=await exited;
370
+ return {code,stdout,exitMs:Date.now()-started};
371
+ };
372
+ }
373
+ const op=(n,answer,extra={})=>({requestId:`r${n}`,operation:'advance',answer,...extra});
374
+
375
+ test('host session idle after a finished step notifies once: 疑似空转 for progress, 在等你 for a person',async t=>{
376
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
377
+ const progress=await run([[0,op(1,{stage:'requirements_analysis',runId:'prd-1'})],[900,null]]);
378
+ assert.equal(progress.code,0);
379
+ assert(await h.until(()=>h.rows().length===1));
380
+ const [idle]=h.rows();
381
+ assert.equal(idle.title,'CM cm-prd 疑似空转 · '+path.basename(process.cwd()));
382
+ assert.equal(idle.stdin.event,'idle');assert.equal(idle.stdin.code,'no_next_step');
383
+ assert.equal(idle.stdin.runId,'prd-1');assert.equal(idle.stdin.stage,'requirements_analysis');
384
+ const waiting=home(t,{config:{idleMinutes:0.003}});
385
+ const review=await idleHost(waiting)([[0,op(1,{stage:'awaiting_user',runId:'prd-2'})],[900,null]]);
386
+ assert.equal(review.code,0);
387
+ assert(await waiting.until(()=>waiting.rows().length===1));
388
+ assert.equal(waiting.rows()[0].title,'CM cm-prd 在等你 · '+path.basename(process.cwd()));
389
+ assert.equal(waiting.rows()[0].stdin.event,'idle_waiting');assert.equal(waiting.rows()[0].stdin.code,'waiting_for_you');
390
+ await new Promise(resolve=>setTimeout(resolve,300));
391
+ assert.equal(h.rows().length,1);assert.equal(waiting.rows().length,1);
392
+ });
393
+
394
+ test('host session idle: next step, in-flight step and session end clear it; status polls do not',async t=>{
395
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
396
+ // Steady progress: each next operation arrives before the threshold.
397
+ const steady=[];for(let n=1;n<=6;n++)steady.push([n===1?0:60,op(n,{stage:'requirements_analysis'})]);
398
+ assert.equal((await run([...steady,[60,null]])).code,0);
399
+ // A long in-flight operation is not idleness; ending right after its reply clears the timer.
400
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
401
+ // A slow next operation: its arrival clears the timer armed by the previous reply.
402
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,op(2,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
403
+ // A cancel reply while another operation is still in flight does not arm it.
404
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[60,{requestId:'c1',operation:'cancel'}],[900,null]])).code,0);
405
+ // Driver shape: EOF right after the reply arrived.
406
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',null]])).code,0);
407
+ // A line the host rejects (not JSON, unknown operation) is still the session's next step.
408
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,'not json'],[900,null]])).code,0);
409
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'x',operation:'no_such_op'}],[900,null]])).code,0);
410
+ await new Promise(resolve=>setTimeout(resolve,500));
411
+ assert.equal(h.rows().length,0,h.log());
412
+ // Polls (status via the control path, fix_status via the normal path) neither
413
+ // hold the timer off nor replace the last real step's result.
414
+ for(const poll of ['status','fix_status']){
415
+ const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})]];
416
+ for(let n=0;n<12;n++)polls.push([60,{requestId:`s${n}`,operation:poll}]);
417
+ assert.equal((await run([...polls,[60,null]])).code,0);
418
+ assert(await h.until(()=>h.rows().some(row=>row.stdin.runId===`run-${poll}`)));
419
+ const row=h.rows().find(row=>row.stdin.runId===`run-${poll}`);
420
+ assert.equal(row.stdin.event,'idle');assert.equal(row.stdin.stage,'requirements_analysis');
421
+ }
422
+ assert.equal(h.rows().length,2);
423
+ });
424
+
425
+ // A poll that is still running when the deadline passes holds the notice; it
426
+ // goes out right after the poll replies, not during it.
427
+ test('host session idle: a slow status in flight holds the notice until it replies',async t=>{
428
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
429
+ const result=await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'s1',operation:'status',slowMs:700}],['reply:s1',undefined],[400,null]]);
430
+ assert.equal(result.code,0);
431
+ const doneAt=JSON.parse(result.stdout.split('\n').find(line=>line.includes('"requestId":"s1"'))).result.doneAt;
432
+ assert(await h.until(()=>h.rows().length===1));
433
+ assert(h.rows()[0].at>=doneAt,`notice at ${h.rows()[0].at} before status finished at ${doneAt}`);
434
+ assert.equal(h.rows()[0].stdin.stage,'requirements_analysis');
435
+ });
436
+
437
+ // Tool-bridge sessions end with host_close from the driver: exit 0, no notice.
438
+ test('host session idle: host_close ends the session cleanly without a notice',async t=>{
439
+ const h=home(t,{config:{idleMinutes:0.003}});
440
+ const script=path.join(h.dir,'cm-demo-host.mjs');
441
+ fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
442
+ import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
443
+ const bridge=createHostToolBridge();
444
+ const host={handle:async()=>({stage:'awaiting_review',asked:await bridge.call('develop',{},new AbortController().signal)})};
445
+ await serveCmAiHost({host,input:process.stdin,output:process.stdout,toolBridge:bridge});`);
446
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
447
+ const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
448
+ let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
449
+ const exited=new Promise(resolve=>child.on('close',resolve));
450
+ const lines=()=>stdout.split('\n').filter(Boolean).map(line=>JSON.parse(line));
451
+ child.stdin.write(JSON.stringify({requestId:'r1',operation:'advance'})+'\n');
452
+ await h.until(()=>lines().some(row=>row.type==='host_request'));
453
+ const ask=lines().find(row=>row.type==='host_request');
454
+ child.stdin.write(JSON.stringify({type:'host_result',sessionId:ask.sessionId,callId:ask.callId,requestDigest:ask.requestDigest,result:{ok:true}})+'\n');
455
+ await h.until(()=>lines().some(row=>row.requestId==='r1'));
456
+ child.stdin.write(JSON.stringify({type:'host_close',sessionId:ask.sessionId})+'\n');
457
+ assert.equal(await exited,0);
458
+ assert.deepEqual(lines().map(row=>row.type??row.requestId),['host_ready','host_request','host_response','r1','host_response']);
459
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,0);
460
+ });
461
+
462
+ test('host session idle timer never delays exit and idleMinutes is validated',async t=>{
463
+ const h=home(t,{config:{idleMinutes:600}}),run=idleHost(h);
464
+ const result=await run([[0,op(1,{stage:'requirements_analysis'})],[100,null]]);
465
+ assert.equal(result.code,0);assert(result.exitMs<3000);assert.match(result.stdout,/"requestId":"r1"/);
466
+ assert.equal(h.rows().length,0);
467
+ for(const idleMinutes of [0,-1,1441,'45'])assert.equal(readNotifyConfig(home(t,{config:{idleMinutes}}).env),null);
468
+ });
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ // 只读巡检:找出「登记过、进程却已不在」的 CM 宿主,合并成一条卡住提醒。
3
+ // 宿主活着但没人推进由宿主自己的空转计时负责(runtime/js/cm-ai/host-session.mjs);
4
+ // 这里只抓宿主已死(被杀、崩溃、机器重启)而没来得及收尾的情况。
5
+ // 只读 <home>/hosts 下的登记文件和进程是否存在(process.kill(pid,0)),不读日志、
6
+ // 不读项目文件、不写任何流程状态。会写的只有两样:提醒模块自己的去重/限流状态
7
+ // (notify-state.json、notify.log,和其他提醒一样),以及删除已报告的登记文件。
8
+ // 用法:node cm-patrol.mjs 巡检并提醒
9
+ // node cm-patrol.mjs --report 只把结果以 JSON 打到标准输出,不提醒、不删文件
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import {fileURLToPath} from 'node:url';
13
+ import {HOST_REGISTRY_MAX_AGE_MS,hostRegistryDir,notify,readNotifyConfig} from '../runtime/js/notify.mjs';
14
+
15
+ const NAME=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$/;
16
+ // nextAction is capped at 200 chars by the notice; list what fits, count the rest.
17
+ const LIST_BUDGET=150;
18
+ const text=value=>typeof value==='string'&&value?value:null;
19
+
20
+ // A pid the current user cannot signal (EPERM) still exists; only ESRCH is gone.
21
+ export function processAlive(pid){
22
+ if(pid===process.pid)return true;
23
+ try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}
24
+ }
25
+
26
+ function readEntry(file){
27
+ try{
28
+ const value=JSON.parse(fs.readFileSync(file,'utf8'));
29
+ if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1)return null;
30
+ if(!Number.isSafeInteger(value.pid)||value.pid<=0)return null;
31
+ const at=Date.parse(value.at);if(!Number.isFinite(at))return null;
32
+ return {file,pid:value.pid,at,sessionKey:text(value.sessionKey),workflow:text(value.workflow)??'cm',project:text(value.project),
33
+ runId:text(value.runId),task:text(value.task),stage:text(value.stage),operation:text(value.operation)};
34
+ }catch{return null;}
35
+ }
36
+
37
+ // {live, dead, stale, invalid}: dead = registered within 48 hours, process gone.
38
+ export function inspectHosts({env=process.env,now=Date.now()}={}){
39
+ const result={live:[],dead:[],stale:[],invalid:0};
40
+ let names;
41
+ try{names=fs.readdirSync(hostRegistryDir(env)).filter(name=>NAME.test(name));}catch{return result;}
42
+ for(const name of names){
43
+ const entry=readEntry(path.join(hostRegistryDir(env),name));
44
+ if(!entry){result.invalid++;continue;}
45
+ if(now-entry.at>HOST_REGISTRY_MAX_AGE_MS||entry.at>now)result.stale.push(entry);
46
+ else if(processAlive(entry.pid))result.live.push(entry);
47
+ else result.dead.push(entry);
48
+ }
49
+ return result;
50
+ }
51
+
52
+ const stamp=at=>new Date(at).toISOString().slice(11,16)+'Z';
53
+ const line=entry=>[entry.workflow,entry.runId,entry.task,entry.stage??entry.operation,`最后动静 ${stamp(entry.at)}`].filter(Boolean).join(' ');
54
+
55
+ // One notice for every dead host found in this pass. The key names the set, so
56
+ // the same set is not resent within the notice window; reported entries are
57
+ // removed so the next pass only sees new ones.
58
+ export function patrol({env=process.env,now=Date.now(),report=false}={}){
59
+ const hosts=inspectHosts({env,now});
60
+ const summary={at:new Date(now).toISOString(),live:hosts.live.length,dead:hosts.dead.length,stale:hosts.stale.length,invalid:hosts.invalid,
61
+ deadHosts:hosts.dead.map(entry=>({workflow:entry.workflow,pid:entry.pid,runId:entry.runId,task:entry.task,stage:entry.stage,at:new Date(entry.at).toISOString()}))};
62
+ if(report)return {...summary,notice:'report_only'};
63
+ if(!readNotifyConfig(env))return {...summary,notice:'off'};
64
+ if(hosts.dead.length===0)return {...summary,notice:'none'};
65
+ const dead=[...hosts.dead].sort((a,b)=>a.at-b.at);
66
+ const workflows=new Set(dead.map(entry=>entry.workflow)),projects=new Set(dead.map(entry=>entry.project).filter(Boolean));
67
+ const listed=[];let used=0;
68
+ for(const entry of dead){const item=line(entry);if(used+item.length>LIST_BUDGET)break;listed.push(item);used+=item.length+1;}
69
+ if(listed.length<dead.length)listed.push(`另有 ${dead.length-listed.length} 个`);
70
+ const sent=notify({key:`dead|${dead.map(entry=>entry.sessionKey??entry.file).sort().join(',')}`,event:'dead',
71
+ workflow:workflows.size===1?[...workflows][0]:'cm',project:projects.size===1?[...projects][0]:null,
72
+ runId:dead.length===1?dead[0].runId:null,task:dead.length===1?dead[0].task:null,
73
+ stage:`${dead.length} 个宿主进程已不在`,code:'host_process_gone',
74
+ nextAction:`${listed.join(';')}。请回到会话用 status 核对运行状态,需要时按恢复说明接手`},{env,now});
75
+ if(sent.sent||sent.reason==='duplicate')for(const entry of dead){try{fs.unlinkSync(entry.file);}catch{}}
76
+ return {...summary,notice:sent.sent?'sent':sent.reason};
77
+ }
78
+
79
+ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){
80
+ const report=process.argv.includes('--report');
81
+ const result=patrol({report});
82
+ if(report)process.stdout.write(JSON.stringify(result,null,2)+'\n');
83
+ }