@aibyzero/cm-workflow 0.16.6 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +29 -0
- package/README.md +32 -1
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +84 -9
- package/docs/user-guide.md +104 -0
- package/package.json +1 -1
- package/runtime/js/cm-ai/cm-ai-admission.mjs +37 -11
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +56 -17
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +172 -33
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
- package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
- package/runtime/js/cm-ai/drive-core.mjs +17 -4
- package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
- package/runtime/js/cm-ai/execution-store.mjs +4 -2
- package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
- package/runtime/js/cm-ai/host-documentation.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +89 -19
- package/runtime/js/cm-ai/host-session.mjs +46 -6
- package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- package/runtime/js/cm-ai/log-rows.mjs +36 -0
- package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
- package/runtime/js/cm-ai/task-runner.mjs +6 -1
- 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 +189 -148
- package/runtime/js/cm-fix/finish.mjs +2 -19
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/log-events.mjs +29 -0
- package/runtime/js/cm-fix/metrics.mjs +3 -2
- package/runtime/js/cm-fix/progress.mjs +3 -1
- package/runtime/js/cm-prd/analysis.mjs +5 -2
- package/runtime/js/cm-prd/review-host.mjs +2 -1
- package/runtime/js/cm-test/recovery.mjs +4 -4
- package/runtime/js/notify-run.mjs +26 -0
- package/runtime/js/notify.mjs +388 -0
- package/runtime/model-efficiency.md +17 -0
- package/scripts/cm-ai-admission.mjs +14 -3
- package/scripts/cm-ai-batch-drive.mjs +2 -2
- package/scripts/cm-ai-batch-host.mjs +7 -2
- package/scripts/cm-ai-batch-run.mjs +11 -2
- package/scripts/cm-ai-batch-run.test.mjs +9 -1
- package/scripts/cm-ai-drive.mjs +18 -4
- package/scripts/cm-ai-drive.test.mjs +30 -0
- package/scripts/cm-ai-feature-selection.test.mjs +178 -0
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- package/scripts/cm-ai-host.mjs +20 -8
- package/scripts/cm-ai-host.test.mjs +88 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
- package/scripts/cm-ai-protected-scope.test.mjs +194 -0
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
- package/scripts/cm-ai-run.mjs +36 -5
- package/scripts/cm-fix-abandon.test.mjs +89 -3
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive.mjs +9 -1
- package/scripts/cm-fix-host.mjs +1 -1
- package/scripts/cm-fix-large-log.test.mjs +113 -0
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- package/scripts/cm-host-qa-executor.test.mjs +429 -3
- package/scripts/cm-log-event.mjs +53 -6
- package/scripts/cm-notify.test.mjs +468 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- package/scripts/cm-prd-host.mjs +13 -2
- package/scripts/cm-prd-host.test.mjs +4 -0
- package/scripts/cm-prd-review-host.test.mjs +17 -0
- package/scripts/cm-prd-session-recovery.test.mjs +44 -2
- package/scripts/cm-prd-task-grouping.test.mjs +206 -0
- package/scripts/cm-review-scope-recovery.test.mjs +5 -3
- package/scripts/cm-test-branch-impact.test.mjs +11 -0
- package/scripts/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- package/skills/cm-ai/SKILL.md +7 -3
- package/skills/cm-ai/references/N1-init.md +1 -1
- 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 +110 -0
- package/skills/cm-ai/references/js-host-recovery.md +199 -0
- package/skills/cm-ai/references/js-host.md +69 -330
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +16 -9
- package/skills/cm-prd/SKILL.md +7 -4
- package/skills/cm-prd/references/spec-self-check.md +3 -1
package/scripts/cm-log-event.mjs
CHANGED
|
@@ -200,9 +200,17 @@ export function unclosedResources(states){
|
|
|
200
200
|
return [...states].filter(([,value])=>['acquired','cleanup_failed'].includes(value[0])).map(([key])=>key).sort();
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
function applyTestRunTransition(active,openCases,phase,caseId){
|
|
203
|
+
function applyTestRunTransition(active,openCases,phase,caseId,incompleteReport=false,timedOut=false){
|
|
204
204
|
if(phase==='superseded'){
|
|
205
|
-
|
|
205
|
+
// A call stopped as a whole (see validateQaSupersession) may leave a case
|
|
206
|
+
// started; like abandonment, its own superseded row closes it.
|
|
207
|
+
if(timedOut){
|
|
208
|
+
if(!active)throw new UsageError('QA superseded of a timed-out invocation has no active test run');
|
|
209
|
+
openCases.clear();return false;
|
|
210
|
+
}
|
|
211
|
+
// incomplete_report: a call with its fixed report but no complete row (see
|
|
212
|
+
// validateQaSupersession) is closed by its own superseded row.
|
|
213
|
+
if(active!==incompleteReport||openCases.size)throw new UsageError('QA superseded requires a completed invocation');
|
|
206
214
|
return false;
|
|
207
215
|
}
|
|
208
216
|
if(phase==='start'){
|
|
@@ -353,6 +361,38 @@ function validateQaSupersession(state,event){
|
|
|
353
361
|
}
|
|
354
362
|
const caseList=(value,count)=>Array.isArray(value)&&value.length===count&&new Set(value).size===value.length
|
|
355
363
|
&&value.every(item=>typeof item==='string'&&RESOURCE_ID.test(item));
|
|
364
|
+
// A host before the stale_qa fix wrote the fixed report and then no complete
|
|
365
|
+
// row. The host re-reads that report under the blocked-evidence rules; here the
|
|
366
|
+
// structural part: the still active, otherwise unclosed latest invocation.
|
|
367
|
+
if(event.incomplete_report!==undefined){
|
|
368
|
+
if(event.incomplete_report!==true||!state.active||state.superseded||!start||complete||start.attempt>=3
|
|
369
|
+
||event.workflow!=='cm-ai'||event.node!=='N6'||event.reason!=='host_evidence_problem'
|
|
370
|
+
||event.previous_test_run_id!==start.operation_id||event.recovery_rule!==2
|
|
371
|
+
||!Array.isArray(event.blocked_cases)||event.blocked_cases.length===0||event.blocked_cases.length>start.case_count
|
|
372
|
+
||!caseList(event.blocked_cases,event.blocked_cases.length)
|
|
373
|
+
||!['repository_id','run_id','feature','task','package_digest','qa_decision_id','operation_id','attempt','mode','case_count']
|
|
374
|
+
.every(key=>event[key]!==undefined&&event[key]===start[key]))
|
|
375
|
+
throw new UsageError('QA superseded of an incomplete invocation requires its active start, no complete row and blocked_cases');
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
// A call stopped as a whole (qa_execution_timeout) with no complete row. The
|
|
379
|
+
// host re-reads its case rows (PASS or host request timeout only); here the
|
|
380
|
+
// structural part: the still active latest invocation and its PASS rows.
|
|
381
|
+
if(event.reason==='host_request_timeout'){
|
|
382
|
+
if(!state.active||state.superseded||!start||complete||start.attempt>=3
|
|
383
|
+
||event.workflow!=='cm-ai'||event.node!=='N6'||event.previous_test_run_id!==start.operation_id
|
|
384
|
+
||!Array.isArray(event.timed_out_cases)||event.timed_out_cases.length===0||event.timed_out_cases.length>start.case_count
|
|
385
|
+
||!caseList(event.timed_out_cases,event.timed_out_cases.length)
|
|
386
|
+
||JSON.stringify(event.partial_pass_cases)!==JSON.stringify([...state.partialPassCases].sort())
|
|
387
|
+
||event.request_timeout_ms!==undefined&&!(Number.isSafeInteger(event.request_timeout_ms)&&event.request_timeout_ms>0)
|
|
388
|
+
||event.legacy_timeout_attestation!==undefined&&(typeof event.legacy_timeout_attestation!=='string'
|
|
389
|
+
||!event.legacy_timeout_attestation.trim()||Buffer.byteLength(event.legacy_timeout_attestation,'utf8')>500
|
|
390
|
+
||/[\r\n\0]/.test(event.legacy_timeout_attestation))
|
|
391
|
+
||!['repository_id','run_id','feature','task','package_digest','qa_decision_id','operation_id','attempt','mode','case_count']
|
|
392
|
+
.every(key=>event[key]!==undefined&&event[key]===start[key]))
|
|
393
|
+
throw new UsageError('QA superseded of a timed-out invocation requires its active start, no complete row and timed_out_cases');
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
356
396
|
if(event.reason==='declared_environment_failure'){
|
|
357
397
|
const reason=event.environment_failure_reason;
|
|
358
398
|
if(state.active||state.superseded||!start||!complete||complete.result!=='FAIL'||!(complete.failed>0)
|
|
@@ -386,8 +426,9 @@ function loadTestRunState(file,runId){
|
|
|
386
426
|
throw new UsageError('test_run state log contains a malformed case event');
|
|
387
427
|
if(phase==='complete'&&!active&&!openCases.size)continue;
|
|
388
428
|
if(phase==='abandoned')validateQaAbandonment({active,start,hasNonPassResult,partialPassCases},value);
|
|
389
|
-
if(phase==='superseded')validateQaSupersession({active,start,complete,superseded},value);
|
|
390
|
-
active=applyTestRunTransition(active,openCases,phase,typeof caseId==='string'?caseId:null
|
|
429
|
+
if(phase==='superseded')validateQaSupersession({active,start,complete,superseded,partialPassCases},value);
|
|
430
|
+
active=applyTestRunTransition(active,openCases,phase,typeof caseId==='string'?caseId:null,value.incomplete_report===true,
|
|
431
|
+
phase==='superseded'&&value.reason==='host_request_timeout');
|
|
391
432
|
if(phase==='start'){start=value;complete=null;hasNonPassResult=false;partialPassCases.clear();abandoned=false;superseded=false;}
|
|
392
433
|
if(phase==='complete')complete=value;
|
|
393
434
|
if(phase==='case_complete'){
|
|
@@ -534,9 +575,15 @@ export function writeLogEvent(rawInput,{environment=process.env,now=new Date(),u
|
|
|
534
575
|
if(unclosedResources(loadResourceStates(authoritativeLog,built.runId)).length)
|
|
535
576
|
throw new UsageError('QA abandonment blocked by unclosed resources');
|
|
536
577
|
}
|
|
537
|
-
if(existing===null&&event.event==='test_run'&&event.phase==='superseded')
|
|
578
|
+
if(existing===null&&event.event==='test_run'&&event.phase==='superseded'){
|
|
579
|
+
validateQaSupersession(testRun,event);
|
|
580
|
+
if((event.incomplete_report===true||event.reason==='host_request_timeout')
|
|
581
|
+
&&unclosedResources(loadResourceStates(authoritativeLog,built.runId)).length)
|
|
582
|
+
throw new UsageError('QA superseded of an incomplete invocation blocked by unclosed resources');
|
|
583
|
+
}
|
|
538
584
|
if(existing===null&&event.event==='test_run'&&event.phase!==undefined)
|
|
539
|
-
applyTestRunTransition(testRun.active,testRun.openCases,event.phase,event.case_id??null
|
|
585
|
+
applyTestRunTransition(testRun.active,testRun.openCases,event.phase,event.case_id??null,
|
|
586
|
+
event.phase==='superseded'&&event.incomplete_report===true,event.phase==='superseded'&&event.reason==='host_request_timeout');
|
|
540
587
|
|
|
541
588
|
let projectDuplicate=false;
|
|
542
589
|
if(projectLog){
|
|
@@ -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
|
+
});
|