@aibyzero/cm-workflow 0.17.0 → 0.17.1
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/AGENTS.md +4 -0
- package/CHANGELOG.md +6 -1
- package/CONTRIBUTING.md +47 -0
- package/README.md +8 -1
- package/VERSION +1 -1
- package/docs/architecture.md +29 -13
- package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +3 -1
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
- package/runtime/js/cm-ai/control-policy.mjs +3 -2
- package/runtime/js/cm-ai/drive-core.mjs +124 -25
- package/runtime/js/cm-ai/host-check.mjs +3 -1
- package/runtime/js/cm-ai/host-session.mjs +41 -8
- package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
- package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
- package/runtime/js/cm-ai/operator-guidance.mjs +56 -30
- package/runtime/js/cm-ai/task-runner.mjs +5 -2
- package/runtime/js/cm-prd/summary.mjs +27 -12
- package/runtime/review.md +9 -0
- package/scripts/cm-ai-batch-host.test.mjs +21 -9
- package/scripts/cm-ai-batch-run.mjs +12 -6
- package/scripts/cm-ai-control-policy.test.mjs +68 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
- package/scripts/cm-ai-drive.test.mjs +3 -3
- package/scripts/cm-ai-host-fixture.mjs +9 -6
- package/scripts/cm-ai-host-protected.test.mjs +1 -1
- package/scripts/cm-ai-host.test.mjs +15 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
- package/scripts/cm-ai-review-timeout.test.mjs +20 -0
- package/scripts/cm-check-drive-files.mjs +1 -1
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-claude-probe.test.mjs +26 -0
- package/scripts/cm-claude-review-stream.test.mjs +36 -0
- package/scripts/cm-claude-worker.test.mjs +16 -0
- package/scripts/cm-drive-liveness.test.mjs +83 -0
- package/scripts/cm-external-batch-host.test.mjs +8 -6
- package/scripts/cm-host-diagnostic.test.mjs +33 -0
- package/scripts/cm-host-liveness.test.mjs +150 -0
- package/scripts/cm-host-stage-observer.test.mjs +41 -0
- package/scripts/cm-notify.test.mjs +50 -16
- package/scripts/cm-prd-drive.test.mjs +1 -1
- package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
- package/scripts/cm-prd-session-recovery.test.mjs +5 -3
- package/scripts/cm-prd-summary.test.mjs +31 -0
- package/scripts/cm-release-smoke.sh +2 -14
- package/scripts/cm-test-suite.mjs +109 -0
- package/scripts/cm-test-suite.test.mjs +162 -0
- package/scripts/fixtures/host-diagnostic.mjs +33 -0
- package/skills/cm-ai/references/js-host.md +33 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {EventEmitter} from 'node:events';
|
|
4
|
+
import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
|
|
5
|
+
|
|
6
|
+
function fixture(){
|
|
7
|
+
const child=new EventEmitter();child.pid=123;child.stdout=new EventEmitter();child.stderr=new EventEmitter();
|
|
8
|
+
let clock=10;const trace=hostDiagnostic(child,{timeoutMs:60000,now:()=>clock});
|
|
9
|
+
return {child,trace,tick:ms=>{clock+=ms;}};
|
|
10
|
+
}
|
|
11
|
+
test('fixture diagnostics retain last stage, time budget and child exit without changing the failure',()=>{
|
|
12
|
+
const {child,trace,tick}=fixture();trace.send({operation:'advance',requestId:'private-request'});tick(30);
|
|
13
|
+
trace.receive({type:'host_request',kind:'develop',payload:{private:'source'}});tick(50);
|
|
14
|
+
trace.receive({result:{state:'blocked',code:'develop_answer_missing'}});
|
|
15
|
+
child.stderr.emit('data',Buffer.from('private stderr'));child.emit('close',7,'SIGTERM');
|
|
16
|
+
const failure=new Error('fixture failure');assert.equal(trace.attach(failure),failure);
|
|
17
|
+
const data=failure.diagnostic;
|
|
18
|
+
assert.equal(data.timeoutMs,60000);assert.equal(data.elapsedMs,80);assert.equal(data.lastKind,'develop');
|
|
19
|
+
assert.equal(data.lastState,'blocked');assert.equal(data.lastCode,'develop_answer_missing');
|
|
20
|
+
assert.equal(data.exitCode,7);assert.equal(data.signal,'SIGTERM');assert.equal(data.closed,true);
|
|
21
|
+
assert.equal(data.stderrBytes,14);assert.equal(data.lastOperation,'advance');
|
|
22
|
+
assert(!JSON.stringify(data).includes('private'));
|
|
23
|
+
});
|
|
24
|
+
test('fixture diagnostics bound history and allowlist even hostile metadata',()=>{
|
|
25
|
+
const {child,trace}=fixture(),secret='private-synthetic-secret';
|
|
26
|
+
for(let i=0;i<80;i++)trace.receive({type:secret,kind:secret,requestId:secret,
|
|
27
|
+
result:{state:secret,code:secret},payload:{text:secret}});
|
|
28
|
+
child.stdout.emit('data',Buffer.from(secret));child.stderr.emit('data',Buffer.from(secret));child.emit('close',null,secret);
|
|
29
|
+
const data=trace.snapshot();assert.equal(data.events.length,32);assert.equal(data.eventCount,80);
|
|
30
|
+
assert.equal(data.lastKind,'other');assert.equal(data.lastCode,'other');assert.equal(data.signal,'other');
|
|
31
|
+
assert(!JSON.stringify(data).includes(secret));assert(JSON.stringify(data).length<6000);
|
|
32
|
+
data.events[0].kind=secret;assert(!JSON.stringify(trace.snapshot()).includes(secret));
|
|
33
|
+
});
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {PassThrough} from 'node:stream';
|
|
4
|
+
import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
5
|
+
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
6
|
+
import {beginHostStage} from '../runtime/js/cm-ai/host-stage-observer.mjs';
|
|
7
|
+
|
|
8
|
+
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
|
9
|
+
async function waitFor(rows,predicate,timeout=1500){
|
|
10
|
+
const end=Date.now()+timeout;
|
|
11
|
+
while(Date.now()<end){const found=rows.find(predicate);if(found)return found;await new Promise(resolve=>setTimeout(resolve,5));}
|
|
12
|
+
assert.fail(`missing row: ${JSON.stringify(rows)}`);
|
|
13
|
+
}
|
|
14
|
+
function session(handle,{heartbeat=false}={}){
|
|
15
|
+
const input=new PassThrough(),output=new PassThrough(),rows=[],bridge=createHostToolBridge();
|
|
16
|
+
output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line)rows.push(JSON.parse(line));});
|
|
17
|
+
const serving=serveCmAiHost({host:{handle:(request)=>handle(request,bridge)},input,output,toolBridge:bridge,heartbeat});
|
|
18
|
+
return {rows,bridge,input,serving,send:row=>input.write(JSON.stringify(row)+'\n')};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
test('host busy explains active request and close refuses a running operation without stopping it',async()=>{
|
|
22
|
+
let resolve;const done=new Promise(r=>{resolve=r;});
|
|
23
|
+
const s=session(async()=>{await done;return {outcome:'complete'};});
|
|
24
|
+
try{
|
|
25
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');
|
|
26
|
+
s.send({requestId:'first',operation:'advance'});await tick();
|
|
27
|
+
s.send({requestId:'second',operation:'advance'});
|
|
28
|
+
const busy=await waitFor(s.rows,r=>r.requestId==='second');
|
|
29
|
+
assert.equal(busy.error.code,'host_busy');assert.equal(busy.error.inFlight.requestId,'first');
|
|
30
|
+
assert.equal(busy.error.inFlight.operation,'advance');assert.equal(busy.error.inFlight.stage,'advance');
|
|
31
|
+
assert.ok(Number.isFinite(Date.parse(busy.error.inFlight.startedAt)));assert.match(busy.error.message,/继续等待/);
|
|
32
|
+
s.send({type:'host_close',sessionId:ready.sessionId});
|
|
33
|
+
const refused=await waitFor(s.rows,r=>r.type==='host_response');
|
|
34
|
+
assert.equal(refused.code,'host_close_busy');assert.equal(refused.accepted,false);
|
|
35
|
+
assert.equal(refused.inFlight.requestId,'first');
|
|
36
|
+
resolve();await waitFor(s.rows,r=>r.requestId==='first');
|
|
37
|
+
s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
|
|
38
|
+
assert.equal(s.rows.at(-1).closing,true);
|
|
39
|
+
}finally{resolve();s.input.end();await s.serving;}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('bridge close validates session and force, exposes metadata only and preserves pending reply',async()=>{
|
|
43
|
+
const bridge=createHostToolBridge(),rows=[];bridge.attach(row=>{rows.push(row);});
|
|
44
|
+
const pending=bridge.call('develop',{secret:'never expose this'},new AbortController().signal,{timeoutMs:1000});
|
|
45
|
+
try{
|
|
46
|
+
await tick();const request=rows.find(r=>r.type==='host_request'),snapshot=bridge.inFlight();
|
|
47
|
+
assert.deepEqual(Object.keys(snapshot).sort(),['callId','deadlineMs','kind','startedAt']);
|
|
48
|
+
assert.equal(snapshot.kind,'develop');assert.equal(snapshot.deadlineMs-Date.parse(snapshot.startedAt),1000);
|
|
49
|
+
assert.equal(bridge.accept({type:'host_close',sessionId:'wrong',force:true}).code,'host_response_mismatch');
|
|
50
|
+
assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId,force:'true'}).code,'host_response_mismatch');
|
|
51
|
+
assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId}).code,'host_close_busy');
|
|
52
|
+
assert.equal(bridge.accept({...request,type:'host_result',kind:undefined,payload:undefined}).accepted,false);
|
|
53
|
+
const result={type:'host_result',sessionId:request.sessionId,callId:request.callId,requestDigest:request.requestDigest,result:{ok:true}};
|
|
54
|
+
assert.equal(bridge.accept(result).accepted,true);assert.deepEqual(await pending,{ok:true});
|
|
55
|
+
assert.equal(bridge.inFlight(),null);assert.equal(bridge.accept({type:'host_close',sessionId:request.sessionId}).closing,true);
|
|
56
|
+
}finally{bridge.close();await pending.catch(()=>{});}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('forced close explicitly warns and interrupts a pending bridge call',{timeout:3000},async()=>{
|
|
60
|
+
const s=session(async(request,bridge)=>{try{await bridge.call('develop',{},new AbortController().signal);return {bad:true};}catch(error){return {code:error.code};}});
|
|
61
|
+
try{
|
|
62
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'active',operation:'advance'});
|
|
63
|
+
await waitFor(s.rows,r=>r.type==='host_request');s.send({type:'host_close',sessionId:ready.sessionId,force:true});
|
|
64
|
+
const closed=await waitFor(s.rows,r=>r.type==='host_response');assert.equal(closed.closing,true);
|
|
65
|
+
await s.serving;assert.match(closed.warning,/unknown/);
|
|
66
|
+
assert.equal(s.rows.find(r=>r.requestId==='active').result.code,'host_disconnected');
|
|
67
|
+
}finally{s.input.end();await s.serving;}
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('heartbeat is opt-in, contains no payload, and idle ticks do not claim progress or poll runner',{timeout:14000},async()=>{
|
|
71
|
+
let calls=0;const s=session(async(request,bridge)=>{calls++;return bridge.call('check',{private:'payload'},new AbortController().signal,{timeoutMs:13000});},{heartbeat:true});
|
|
72
|
+
try{
|
|
73
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');assert.deepEqual(ready.heartbeat,{intervalMs:5000,timeoutMs:30000});
|
|
74
|
+
const first=await waitFor(s.rows,r=>r.type==='host_heartbeat');assert.equal(first.inFlight,null);
|
|
75
|
+
s.send({requestId:'check',operation:'advance'});const request=await waitFor(s.rows,r=>r.type==='host_request');
|
|
76
|
+
const beat=await waitFor(s.rows,r=>r.type==='host_heartbeat'&&r.inFlight?.call,6000);
|
|
77
|
+
assert.equal(beat.inFlight.stage,'check');assert.equal(beat.inFlight.call.kind,'check');assert.equal(beat.pid,process.pid);
|
|
78
|
+
assert.equal(beat.sessionId,ready.sessionId);assert.equal(calls,1);assert.equal(JSON.stringify(beat).includes('payload'),false);
|
|
79
|
+
assert.equal(beat.lastProgressAt,beat.inFlight.call.startedAt);
|
|
80
|
+
const second=await waitFor(s.rows,r=>r.type==='host_heartbeat'&&r.at!==beat.at&&r.inFlight?.call,6000);
|
|
81
|
+
assert.equal(second.lastProgressAt,beat.lastProgressAt);assert.deepEqual(second.inFlight,beat.inFlight);
|
|
82
|
+
s.send({type:'host_result',sessionId:ready.sessionId,callId:request.callId,requestDigest:request.requestDigest,result:{ok:true}});
|
|
83
|
+
await waitFor(s.rows,r=>r.requestId==='check');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
|
|
84
|
+
const old=session(async()=>({ok:true}));const oldReady=await waitFor(old.rows,r=>r.type==='host_ready');
|
|
85
|
+
assert.equal(oldReady.heartbeat,undefined);assert.equal(old.rows.some(r=>r.type==='host_heartbeat'),false);
|
|
86
|
+
old.send({type:'host_close',sessionId:oldReady.sessionId});await old.serving;
|
|
87
|
+
}finally{s.input.end();await s.serving;}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
for(const operation of ['status','cancel'])test(`close refuses in-flight ${operation} control`,async()=>{
|
|
91
|
+
let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async()=>{await done;return {ok:true};});
|
|
92
|
+
try{
|
|
93
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'control',operation});await tick();
|
|
94
|
+
s.send({type:'host_close',sessionId:ready.sessionId});
|
|
95
|
+
const refused=await waitFor(s.rows,r=>r.type==='host_response');
|
|
96
|
+
assert.equal(refused.code,'host_close_busy');assert.equal(refused.inFlight.operation,operation);
|
|
97
|
+
resolve();await waitFor(s.rows,r=>r.requestId==='control');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
|
|
98
|
+
}finally{resolve();s.input.end();await s.serving;}
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('poll reusing requestId cannot release a different running operation',async()=>{
|
|
102
|
+
let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async request=>{
|
|
103
|
+
if(request.operation==='advance')await done;return {operation:request.operation};
|
|
104
|
+
});
|
|
105
|
+
try{
|
|
106
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'same',operation:'advance'});await tick();
|
|
107
|
+
s.send({requestId:'same',operation:'status'});await waitFor(s.rows,r=>r.result?.operation==='status');
|
|
108
|
+
s.send({type:'host_close',sessionId:ready.sessionId});
|
|
109
|
+
const refused=await waitFor(s.rows,r=>r.type==='host_response');assert.equal(refused.code,'host_close_busy');
|
|
110
|
+
assert.equal(refused.inFlight.operation,'advance');resolve();await waitFor(s.rows,r=>r.result?.operation==='advance');
|
|
111
|
+
s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
|
|
112
|
+
}finally{resolve();s.input.end();await s.serving;}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('close sent synchronously when the result is written is allowed',async()=>{
|
|
116
|
+
const input=new PassThrough(),output=new PassThrough(),bridge=createHostToolBridge(),rows=[];let sessionId;
|
|
117
|
+
output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line){
|
|
118
|
+
const row=JSON.parse(line);rows.push(row);
|
|
119
|
+
if(row.type==='host_ready'){sessionId=row.sessionId;input.write(JSON.stringify({requestId:'instant',operation:'advance'})+'\n');}
|
|
120
|
+
if(row.requestId==='instant')input.write(JSON.stringify({type:'host_close',sessionId})+'\n');
|
|
121
|
+
}});
|
|
122
|
+
const serving=serveCmAiHost({host:{handle:async()=>({ok:true})},input,output,toolBridge:bridge});
|
|
123
|
+
try{const closed=await waitFor(rows,r=>r.type==='host_response');assert.equal(closed.closing,true);await serving;assert.equal(rows.some(r=>r.code==='host_close_busy'),false);}
|
|
124
|
+
finally{input.end();await serving;}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('CM_HOST_HEARTBEAT enables the wire contract without changing host operations',async()=>{
|
|
128
|
+
const previous=process.env.CM_HOST_HEARTBEAT;process.env.CM_HOST_HEARTBEAT='1';
|
|
129
|
+
const input=new PassThrough(),output=new PassThrough(),bridge=createHostToolBridge(),rows=[];
|
|
130
|
+
output.on('data',chunk=>{for(const line of chunk.toString().trim().split('\n'))if(line)rows.push(JSON.parse(line));});
|
|
131
|
+
const serving=serveCmAiHost({host:{handle:async()=>assert.fail('heartbeat must not invoke host')},input,output,toolBridge:bridge});
|
|
132
|
+
try{
|
|
133
|
+
const ready=await waitFor(rows,r=>r.type==='host_ready');assert.deepEqual(ready.heartbeat,{intervalMs:5000,timeoutMs:30000});
|
|
134
|
+
await waitFor(rows,r=>r.type==='host_heartbeat');input.write(JSON.stringify({type:'host_close',sessionId:ready.sessionId})+'\n');await serving;
|
|
135
|
+
}finally{input.end();await serving;if(previous===undefined)delete process.env.CM_HOST_HEARTBEAT;else process.env.CM_HOST_HEARTBEAT=previous;}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('native stage exposes its real budget without requiring a bridge call',async()=>{
|
|
139
|
+
let resolve;const done=new Promise(r=>{resolve=r;});const s=session(async()=>{
|
|
140
|
+
const end=beginHostStage('check',5000);try{await done;return {ok:true};}finally{end();}
|
|
141
|
+
});
|
|
142
|
+
try{
|
|
143
|
+
const ready=await waitFor(s.rows,r=>r.type==='host_ready');s.send({requestId:'native',operation:'advance'});await tick();
|
|
144
|
+
s.send({requestId:'duplicate',operation:'advance'});const busy=await waitFor(s.rows,r=>r.requestId==='duplicate');
|
|
145
|
+
assert.equal(busy.error.inFlight.stage,'check');assert.equal(busy.error.inFlight.call,null);
|
|
146
|
+
const stage=busy.error.inFlight.nativeStage;assert.equal(stage.kind,'check');assert.equal(stage.deadlineMs-Date.parse(stage.startedAt),5000);
|
|
147
|
+
s.send({type:'host_close',sessionId:ready.sessionId});assert.equal((await waitFor(s.rows,r=>r.type==='host_response')).code,'host_close_busy');
|
|
148
|
+
resolve();await waitFor(s.rows,r=>r.requestId==='native');s.send({type:'host_close',sessionId:ready.sessionId});await s.serving;
|
|
149
|
+
}finally{resolve();s.input.end();await s.serving;}
|
|
150
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
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 {withHostStageObserver,beginHostStage} from '../runtime/js/cm-ai/host-stage-observer.mjs';
|
|
7
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
8
|
+
|
|
9
|
+
test('nested native stage preserves outer deadline and restores its identity',async()=>{
|
|
10
|
+
const rows=[];
|
|
11
|
+
await withHostStageObserver(row=>rows.push(row),async()=>{
|
|
12
|
+
const outer=beginHostStage('develop',1000),parent=rows.at(-1);
|
|
13
|
+
const inner=beginHostStage('check',5000),child=rows.at(-1);
|
|
14
|
+
assert.equal(child.kind,'check');assert.notEqual(child.id,parent.id);assert.equal(child.deadlineMs,parent.deadlineMs);
|
|
15
|
+
inner();assert.deepEqual(rows.at(-1),parent);outer();assert.equal(rows.at(-1),null);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
test('overlapping operations and late stages cannot replace another operation telemetry',async()=>{
|
|
19
|
+
const a=[],b=[];let wake,late;
|
|
20
|
+
const waiting=new Promise(resolve=>{wake=resolve;});
|
|
21
|
+
const first=withHostStageObserver(row=>a.push(row),async()=>{late=beginHostStage('review',1000);await waiting;});
|
|
22
|
+
await withHostStageObserver(row=>b.push(row),async()=>{const end=beginHostStage('check',2000);assert.equal(a.at(-1).kind,'review');end();});
|
|
23
|
+
const before=b.length;wake();await first;late();assert.equal(b.length,before);assert.equal(a.at(-1),null);
|
|
24
|
+
});
|
|
25
|
+
test('observer failures and absent observers never alter original result or error',async()=>{
|
|
26
|
+
beginHostStage('check',1)();
|
|
27
|
+
assert.equal(await withHostStageObserver(()=>{throw Error('observer');},async()=>{beginHostStage('check',1)();return 7;}),7);
|
|
28
|
+
const failure=Error('original');
|
|
29
|
+
await assert.rejects(withHostStageObserver(()=>{throw Error('observer');},async()=>{beginHostStage('review',1);throw failure;}),error=>error===failure);
|
|
30
|
+
});
|
|
31
|
+
test('real native checks publish a distinct configured deadline per command without changing checks',async t=>{
|
|
32
|
+
const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-native-stage-')));
|
|
33
|
+
t.after(()=>fs.rmSync(cwd,{recursive:true,force:true}));const rows=[];
|
|
34
|
+
const check=createHostCheck({cwd,timeoutMs:2500,commands:['first','second'].map(id=>({id,command:[process.execPath,'-e','0']}))});
|
|
35
|
+
const result=await withHostStageObserver(row=>rows.push(row),()=>check({identity:{repositoryId:'stage-fixture',runId:'stage-fixture-run',taskId:'T-001',attempt:1}},{signal:new AbortController().signal}));
|
|
36
|
+
assert.deepEqual(result.map(row=>row.outcome),['passed','passed']);
|
|
37
|
+
const stages=rows.filter(Boolean);assert.equal(stages.length,2);
|
|
38
|
+
assert.equal(new Set(stages.map(row=>row.id)).size,2);
|
|
39
|
+
for(const row of stages){assert.equal(row.kind,'check');assert.equal(row.deadlineMs-Date.parse(row.startedAt),2500);assert.deepEqual(Object.keys(row).sort(),['deadlineMs','id','kind','startedAt']);}
|
|
40
|
+
assert.equal(rows.at(-1),null);
|
|
41
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
|
|
1
2
|
import test from 'node:test';
|
|
2
3
|
import assert from 'node:assert/strict';
|
|
3
4
|
import fs from 'node:fs';
|
|
@@ -22,7 +23,13 @@ process.stdin.on('end',()=>{setTimeout(()=>{fs.appendFileSync(${JSON.stringify(s
|
|
|
22
23
|
body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');process.exit(${exit});},${sleepMs});});`);
|
|
23
24
|
fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script],...config}));
|
|
24
25
|
const env={...process.env,CM_WORKFLOW_HOME:dir};
|
|
25
|
-
const rows=()=>
|
|
26
|
+
const rows=()=>{
|
|
27
|
+
if(!fs.existsSync(sent))return [];
|
|
28
|
+
const contents=fs.readFileSync(sent,'utf8'),completeEnd=contents.lastIndexOf('\n')+1;
|
|
29
|
+
// appendFileSync may expose an empty file or an unfinished final record.
|
|
30
|
+
// Only complete JSONL records are consumable; malformed complete JSON fails.
|
|
31
|
+
return contents.slice(0,completeEnd).split('\n').slice(0,-1).map(line=>JSON.parse(line));
|
|
32
|
+
};
|
|
26
33
|
const log=()=>fs.existsSync(path.join(dir,'notify.log'))?fs.readFileSync(path.join(dir,'notify.log'),'utf8'):'';
|
|
27
34
|
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
35
|
return {dir,env,rows,log,until};
|
|
@@ -30,6 +37,16 @@ body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');p
|
|
|
30
37
|
const fields=(key,over={})=>({key,event:'stuck',project:'/srv/work/demo-app',workflow:'cm-fix',runId:'run-1',
|
|
31
38
|
task:'T-001',stage:'blocked',code:'checks_not_passed',nextAction:'核对 reason 后恢复原运行',...over});
|
|
32
39
|
|
|
40
|
+
test('fixture JSONL reader waits for complete records and rejects malformed complete JSON',t=>{
|
|
41
|
+
const h=home(t),file=path.join(h.dir,'sent.jsonl');
|
|
42
|
+
assert.deepEqual(h.rows(),[]);
|
|
43
|
+
fs.writeFileSync(file,'');assert.deepEqual(h.rows(),[]);
|
|
44
|
+
fs.writeFileSync(file,'{"marker":1');assert.deepEqual(h.rows(),[]);
|
|
45
|
+
fs.appendFileSync(file,'}\n{"marker":');assert.deepEqual(h.rows(),[{marker:1}]);
|
|
46
|
+
fs.appendFileSync(file,'2}\n');assert.deepEqual(h.rows(),[{marker:1},{marker:2}]);
|
|
47
|
+
fs.appendFileSync(file,'{"bad":}\n');assert.throws(()=>h.rows(),SyntaxError);
|
|
48
|
+
});
|
|
49
|
+
|
|
33
50
|
test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME is explicit',async t=>{
|
|
34
51
|
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-empty-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
35
52
|
assert.equal(readNotifyConfig({CM_WORKFLOW_HOME:dir}),null);
|
|
@@ -630,34 +647,46 @@ test('checkWaitMinutes is validated like waitMinutes',t=>{
|
|
|
630
647
|
// session sends no next operation for idleMinutes, one notice says so. A last
|
|
631
648
|
// result that waits on a person says "在等你" instead. Any next operation or
|
|
632
649
|
// session end clears it; status polls are not progress.
|
|
633
|
-
function idleHost(h){
|
|
650
|
+
function idleHost(h,{startupDelayMs=0}={}){
|
|
634
651
|
const script=path.join(h.dir,'cm-prd-host.mjs');
|
|
635
652
|
fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
|
|
636
653
|
const host={handle:async request=>{
|
|
637
654
|
if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
|
|
638
655
|
if(['status','fix_status'].includes(request.operation))return {stage:'status_only',doneAt:Date.now()};
|
|
639
656
|
return request.answer;}};
|
|
657
|
+
if(${startupDelayMs})await new Promise(resolve=>setTimeout(resolve,${startupDelayMs}));
|
|
640
658
|
await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
|
|
641
659
|
const env={...h.env};delete env.NODE_TEST_CONTEXT;
|
|
642
660
|
// steps: [delayMs, request object | raw line string | null to end stdin];
|
|
643
661
|
// delay 'reply:<id>' waits until that requestId has been answered instead.
|
|
644
|
-
|
|
662
|
+
const history=[];
|
|
663
|
+
const run=async steps=>{
|
|
645
664
|
const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
|
|
646
|
-
|
|
665
|
+
const trace=hostDiagnostic(child);
|
|
666
|
+
let stdout='',buffer='';child.stdout.on('data',chunk=>{
|
|
667
|
+
stdout+=chunk;buffer+=chunk;let end;
|
|
668
|
+
while((end=buffer.indexOf('\n'))!==-1){
|
|
669
|
+
const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
|
|
670
|
+
try{trace.receive(JSON.parse(line));}catch{/* Raw lines are never retained in diagnostics. */}
|
|
671
|
+
}
|
|
672
|
+
});
|
|
647
673
|
const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
|
|
648
674
|
const replied=id=>stdout.includes(`"requestId":"${id}"`);
|
|
649
675
|
for(const [delay,request] of steps){
|
|
650
676
|
if(typeof delay==='string'){
|
|
651
677
|
const id=delay.slice(6),deadline=Date.now()+15000;
|
|
652
|
-
while(!replied(id)){if(Date.now()>deadline){child.kill();throw new Error(
|
|
678
|
+
while(!replied(id)){if(Date.now()>deadline){child.kill();throw trace.attach(new Error('host fixture reply timeout'));}await new Promise(resolve=>setTimeout(resolve,10));}
|
|
653
679
|
}
|
|
654
680
|
else await new Promise(resolve=>setTimeout(resolve,delay));
|
|
655
|
-
if(request===null){child.stdin.end();break;}
|
|
681
|
+
if(request===null){trace.send({operation:'eof'});child.stdin.end();break;}
|
|
682
|
+
if(request!==undefined)trace.send(typeof request==='string'?{}:request);
|
|
656
683
|
if(request!==undefined)child.stdin.write((typeof request==='string'?request:JSON.stringify(request))+'\n');
|
|
657
684
|
}
|
|
658
685
|
const started=Date.now(),code=await exited;
|
|
659
|
-
|
|
686
|
+
const diagnostic=trace.snapshot();history.push(diagnostic);if(history.length>8)history.shift();
|
|
687
|
+
return {code,stdout,exitMs:Date.now()-started,diagnostic};
|
|
660
688
|
};
|
|
689
|
+
run.diagnostics=()=>history;return run;
|
|
661
690
|
}
|
|
662
691
|
const op=(n,answer,extra={})=>({requestId:`r${n}`,operation:'advance',answer,...extra});
|
|
663
692
|
|
|
@@ -680,28 +709,33 @@ test('host session idle after a finished step notifies once: 疑似空转 for pr
|
|
|
680
709
|
assert.equal(h.rows().length,1);assert.equal(waiting.rows().length,1);
|
|
681
710
|
});
|
|
682
711
|
|
|
683
|
-
test(
|
|
684
|
-
const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h);
|
|
712
|
+
for(const startupDelayMs of [0,750])test(`host session idle: next step, in-flight step and session end clear it; status polls do not (startup ${startupDelayMs}ms)`,async t=>{
|
|
713
|
+
const h=home(t,{config:{idleMinutes:0.009}}),run=idleHost(h,{startupDelayMs});
|
|
714
|
+
// Sending is not completion: a slow startup can otherwise batch the next
|
|
715
|
+
// line before the first reply, exercising host_busy instead of idle clearing.
|
|
685
716
|
// Steady progress: each next operation arrives before the threshold.
|
|
686
|
-
const steady=[];for(let n=1;n<=6;n++)
|
|
687
|
-
|
|
717
|
+
const steady=[];for(let n=1;n<=6;n++){
|
|
718
|
+
if(n>1)steady.push([`reply:r${n-1}`,undefined]);
|
|
719
|
+
steady.push([n===1?0:180,op(n,{stage:'requirements_analysis'})]);
|
|
720
|
+
}
|
|
721
|
+
assert.equal((await run([...steady,['reply:r6',undefined],[180,null]])).code,0);
|
|
688
722
|
// A long in-flight operation is not idleness; ending right after its reply clears the timer.
|
|
689
723
|
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
|
|
690
724
|
// A slow next operation: its arrival clears the timer armed by the previous reply.
|
|
691
|
-
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,op(2,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
|
|
725
|
+
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,op(2,{stage:'requirements_analysis'},{slowMs:2700})],[2850,null]])).code,0);
|
|
692
726
|
// A cancel reply while another operation is still in flight does not arm it.
|
|
693
727
|
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:2700})],[180,{requestId:'c1',operation:'cancel'}],[2700,null]])).code,0);
|
|
694
728
|
// Driver shape: EOF right after the reply arrived.
|
|
695
729
|
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',null]])).code,0);
|
|
696
730
|
// A line the host rejects (not JSON, unknown operation) is still the session's next step.
|
|
697
|
-
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,'not json'],[2700,null]])).code,0);
|
|
698
|
-
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[180,{requestId:'x',operation:'no_such_op'}],[2700,null]])).code,0);
|
|
731
|
+
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,'not json'],[2700,null]])).code,0);
|
|
732
|
+
assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',undefined],[180,{requestId:'x',operation:'no_such_op'}],[2700,null]])).code,0);
|
|
699
733
|
await new Promise(resolve=>setTimeout(resolve,1500));
|
|
700
|
-
assert.equal(h.rows().length,0,
|
|
734
|
+
assert.equal(h.rows().length,0,JSON.stringify(run.diagnostics()));
|
|
701
735
|
// Polls (status via the control path, fix_status via the normal path) neither
|
|
702
736
|
// hold the timer off nor replace the last real step's result.
|
|
703
737
|
for(const poll of ['status','fix_status']){
|
|
704
|
-
const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})]];
|
|
738
|
+
const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})],['reply:r1',undefined]];
|
|
705
739
|
for(let n=0;n<12;n++)polls.push([180,{requestId:`s${n}`,operation:poll}]);
|
|
706
740
|
assert.equal((await run([...polls,[180,null]])).code,0);
|
|
707
741
|
assert(await h.until(()=>h.rows().some(row=>row.stdin.runId===`run-${poll}`)));
|
|
@@ -166,7 +166,7 @@ test('real host unknown call resumes with its original callId and requestDigest'
|
|
|
166
166
|
if(row.type==='host_ready'){
|
|
167
167
|
hostSession=row.sessionId;host.stdin.write(JSON.stringify({requestId:'one',operation:'start',text:'Analyze'})+'\n');
|
|
168
168
|
}else if(row.type==='host_request'){
|
|
169
|
-
pending=row;host.stdin.write(JSON.stringify({type:'host_close',sessionId:hostSession})+'\n');break;
|
|
169
|
+
pending=row;host.stdin.write(JSON.stringify({type:'host_close',sessionId:hostSession,force:true})+'\n');break;
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
172
|
assert.ok(pending,diagnostics);host.stdin.end();await closed;
|
|
@@ -300,3 +300,18 @@ test('saving after an unchanged feature split preserves pending revised features
|
|
|
300
300
|
const f=await regenerate(await fixture(t));f.save();f.dispose(await f.review('split','2.second'));
|
|
301
301
|
assert.equal(f.save().status,'draft_saved');await finish(f);assert.doesNotThrow(()=>f.host.validateCurrent());
|
|
302
302
|
});
|
|
303
|
+
|
|
304
|
+
// 2026-10-12 交叉审查 P2:历史 feature 带自检修订记录时,摘要还会经 inspectPrdSplitDesign 再查同一旧拆分回执。
|
|
305
|
+
test('historical feature with a self-check revision is registered after a later approved change; current stays strict',async t=>{
|
|
306
|
+
const f=await regenerate(await fixture(t));await finish(f);
|
|
307
|
+
assert.doesNotThrow(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}));
|
|
308
|
+
fs.appendFileSync(path.join(f.specs,'1.guide/requirements.md'),'\nLater approved change');
|
|
309
|
+
const evidence=inspectPrdSummaryEvidence(f.specs,{currentFeatures:['2.second']});
|
|
310
|
+
const guide=evidence.features.find(item=>item.directory==='1.guide');
|
|
311
|
+
assert.equal(guide.historical,true);assert.equal(guide.reviews.split.archive,'unavailable');
|
|
312
|
+
assert.match(guide.reviews.split.reason,/^prd_review_artifact_changed; self_check_revision:\S+$/);
|
|
313
|
+
assert.ok(evidence.evidenceFiles.some(item=>item.path==='.reviews/prd-guide-self-check-revision.json'));
|
|
314
|
+
assert.equal(evidence.features.find(item=>item.directory==='2.second').reviews.split.gate.outcome,'completed');
|
|
315
|
+
assert.throws(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}),{code:'prd_review_artifact_changed'});
|
|
316
|
+
assert.throws(()=>inspectPrdSummaryEvidence(f.specs),{code:'prd_review_artifact_changed'});
|
|
317
|
+
});
|
|
@@ -49,7 +49,7 @@ async function client(t,f){
|
|
|
49
49
|
const ready=await wait(m=>m.type==='host_ready');
|
|
50
50
|
return {wait,send,requests,request:(operation,fields={})=>{const requestId=`request-${++seq}`;
|
|
51
51
|
const reply=wait(m=>m.requestId===requestId);send({requestId,operation,...fields});return reply;},
|
|
52
|
-
close:async()=>{send({type:'host_close',sessionId:ready.sessionId});assert.equal((await closed)[0],0,stderr);},
|
|
52
|
+
close:async({force=false}={})=>{send({type:'host_close',sessionId:ready.sessionId,...(force?{force:true}:{})});assert.equal((await closed)[0],0,stderr);},
|
|
53
53
|
result:(call,result)=>send({type:'host_result',sessionId:ready.sessionId,callId:call.callId,requestDigest:call.requestDigest,result})};
|
|
54
54
|
}
|
|
55
55
|
function blocked(reply,reason){
|
|
@@ -59,7 +59,8 @@ function blocked(reply,reason){
|
|
|
59
59
|
async function unknownSummary(t,f){
|
|
60
60
|
const c=await client(t,f),pending=c.request('prepare_summary');
|
|
61
61
|
const call=await c.wait(m=>m.type==='host_request');assert.equal(call.kind,'prd_summary');
|
|
62
|
-
|
|
62
|
+
// This fixture intentionally interrupts the unanswered summary; ordinary closes remain protected.
|
|
63
|
+
await c.close({force:true});assert.equal((await pending).error.code,'host_request_failed');return call;
|
|
63
64
|
}
|
|
64
65
|
const abandon=call=>({callId:call.payload.recovery.callId,requestDigest:call.payload.recovery.requestDigest,
|
|
65
66
|
abandon:true,evidence:'Synthetic original call unavailable; explicit discard reference'});
|
|
@@ -94,7 +95,8 @@ test('unknown summary exposes session reasons, abandon restores before and permi
|
|
|
94
95
|
const retry=c.request('prepare_summary'),fresh=await c.wait(m=>m.type==='host_request');
|
|
95
96
|
assert.equal(fresh.kind,'prd_summary');assert.notEqual(fresh.payload.recovery.callId,resolution.callId);
|
|
96
97
|
assert.deepEqual(fresh.payload.evidence.currentFeatures,['1.guide']);
|
|
97
|
-
|
|
98
|
+
// The fresh dispatch is deliberately left unanswered to exercise its interrupted history.
|
|
99
|
+
await c.close({force:true});await retry;
|
|
98
100
|
});
|
|
99
101
|
|
|
100
102
|
for(const mode of ['summary','analysis','change'])test(`cancel clears pending ${mode} and stays terminal across restart`,{timeout:FIXTURE_TIMEOUT_MS},async t=>{
|
|
@@ -229,3 +229,34 @@ for(const extra of ['none','same-feature','other-feature'])test(`failed-check me
|
|
|
229
229
|
}
|
|
230
230
|
evidenceFiles.forEach((file,i)=>assert.deepEqual(fs.readFileSync(file),before[i]));
|
|
231
231
|
});
|
|
232
|
+
|
|
233
|
+
// 2026-10-12 AI潮 dogfood:历史 feature 的拆分回执之后,需求经 --change 正常修改过;新建 feature 的
|
|
234
|
+
// prepare_summary 在历史回执闸门处直接抛出 prd_review_artifact_changed,整批无法发布。
|
|
235
|
+
test('historical receipt artifact changed by a later revision is a note; current and unscoped drift stay strict',async t=>{
|
|
236
|
+
const {specs}=fixture(t);
|
|
237
|
+
fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\n- [ ] [AC-002] Later approved change');
|
|
238
|
+
const evidence=inspectPrdSummaryEvidence(specs,currentScope);
|
|
239
|
+
const split=evidence.features[0].reviews.split;
|
|
240
|
+
assert.equal(evidence.features[0].historical,true);
|
|
241
|
+
assert.equal(split.gate.outcome,'unavailable');assert.equal(split.archive,'unavailable');
|
|
242
|
+
assert.match(split.reason,/^prd_review_artifact_changed$/);
|
|
243
|
+
assert.equal(evidence.features[1].reviews.split.gate.outcome,'completed');
|
|
244
|
+
const summary=await summaryOwner()(specs,currentScope);
|
|
245
|
+
assert.equal(summary.readyForAwaitingReview,true);assert.deepEqual(summary.blockers,[]);
|
|
246
|
+
assert.match(summary.notes.join('\n'),/历史 feature 1\.guide:split 审查归档不可用,已登记未重审(prd_review_artifact_changed)/);
|
|
247
|
+
assert.doesNotMatch(summary.notes.join('\n'),/无处置回执|prd_summary_receipt_missing/);
|
|
248
|
+
assert.equal(publishPrdAwaitingReview({specs,summary,writeEnabled:true}).status,'awaiting_review');
|
|
249
|
+
const status=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8'));
|
|
250
|
+
assert.deepEqual(status.features,['1.guide','2.appendix']);assert.deepEqual(status.specFiles,evidence.specFiles);
|
|
251
|
+
assert.throws(()=>inspectPrdSummaryEvidence(specs),{code:'prd_review_artifact_changed'});
|
|
252
|
+
assert.throws(()=>inspectPrdSummaryEvidence(specs,{currentFeatures:['1.guide']}),{code:'prd_review_artifact_changed'});
|
|
253
|
+
fs.appendFileSync(path.join(specs,'2.appendix/design.md'),'\nUnreviewed current edit');
|
|
254
|
+
assert.throws(()=>inspectPrdSummaryEvidence(specs,currentScope),{code:'prd_review_artifact_changed'});
|
|
255
|
+
});
|
|
256
|
+
test('historical gate failure still rejects publication when history changes after preparation',async t=>{
|
|
257
|
+
const {specs}=fixture(t);
|
|
258
|
+
fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nLater approved change');
|
|
259
|
+
const summary=await summaryOwner()(specs,currentScope);assert.equal(summary.readyForAwaitingReview,true);
|
|
260
|
+
fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nAnother edit after preparation');
|
|
261
|
+
assert.throws(()=>publishPrdAwaitingReview({specs,summary,writeEnabled:true}),/prd_summary_inputs_changed/);
|
|
262
|
+
});
|
|
@@ -47,21 +47,9 @@ for candidate in python3 python; do
|
|
|
47
47
|
done
|
|
48
48
|
[ -n "$PYTHON_BIN" ] || blocked "Python 3.9+ not found"
|
|
49
49
|
|
|
50
|
-
# CI
|
|
51
|
-
# 建不了网络隔离(bwrap: loopback: Failed RTM_NEWADDR),装上 codex 也没用。
|
|
52
|
-
# 这个脚本上面已经要求本机装了 codex,所以这里是它们唯一稳定的落点——发版必过。
|
|
53
|
-
# 名单要和 .github/workflows/ci.yml 的 js-tests 排除名单保持一致。
|
|
50
|
+
# Shared with the CI partition; contributors can run this group without BYZ or installation.
|
|
54
51
|
printf '%s\n' '==> Running the Codex-sandbox tests that CI cannot host'
|
|
55
|
-
|
|
56
|
-
scripts/cm-ai-batch-host.test.mjs \
|
|
57
|
-
scripts/cm-ai-bootstrap.test.mjs \
|
|
58
|
-
scripts/cm-ai-host.test.mjs \
|
|
59
|
-
scripts/cm-ai-host-cli-workflow.test.mjs \
|
|
60
|
-
scripts/cm-ai-host-protected.test.mjs \
|
|
61
|
-
scripts/cm-ai-multi-root.test.mjs \
|
|
62
|
-
scripts/cm-ai-nested-execution.test.mjs \
|
|
63
|
-
scripts/cm-fix-protected-edits.test.mjs \
|
|
64
|
-
scripts/cm-host-check.test.mjs )
|
|
52
|
+
node "$ROOT/scripts/cm-test-suite.mjs" run native
|
|
65
53
|
|
|
66
54
|
printf '%s\n' '==> Validating the public Pi/BYZ package manifest'
|
|
67
55
|
"$PYTHON_BIN" "$ROOT/scripts/validate-public-repo.py"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// One native sandbox inventory for CI exclusions, local runs and release smoke.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {spawn} from 'node:child_process';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {assignShards, readWeights} from './ci-test-shards.mjs';
|
|
9
|
+
|
|
10
|
+
const root = fileURLToPath(new URL('..', import.meta.url));
|
|
11
|
+
export const nativeTests = Object.freeze([
|
|
12
|
+
'scripts/cm-ai-batch-host.test.mjs',
|
|
13
|
+
'scripts/cm-ai-bootstrap.test.mjs',
|
|
14
|
+
'scripts/cm-ai-host.test.mjs',
|
|
15
|
+
'scripts/cm-ai-host-cli-workflow.test.mjs',
|
|
16
|
+
'scripts/cm-ai-host-protected.test.mjs',
|
|
17
|
+
'scripts/cm-ai-multi-root.test.mjs',
|
|
18
|
+
'scripts/cm-ai-nested-execution.test.mjs',
|
|
19
|
+
'scripts/cm-fix-protected-edits.test.mjs',
|
|
20
|
+
'scripts/cm-host-check.test.mjs',
|
|
21
|
+
].sort());
|
|
22
|
+
|
|
23
|
+
export function inventory(repo = root) {
|
|
24
|
+
const discover = dir => fs.readdirSync(path.join(repo, dir), {withFileTypes: true})
|
|
25
|
+
.filter(entry => entry.isFile() && entry.name.endsWith('.test.mjs'))
|
|
26
|
+
.map(entry => `${dir}/${entry.name}`).sort();
|
|
27
|
+
const all = discover('scripts');
|
|
28
|
+
const native = [...nativeTests];
|
|
29
|
+
if (native.length !== 9 || new Set(native).size !== 9) throw new Error('native inventory must contain exactly nine unique tests');
|
|
30
|
+
for (const file of native) if (!all.includes(file)) throw new Error(`missing native test: ${file}`);
|
|
31
|
+
const ordinary = all.filter(file => !native.includes(file));
|
|
32
|
+
const combined = [...ordinary, ...native];
|
|
33
|
+
if (new Set(combined).size !== all.length || combined.length !== all.length ||
|
|
34
|
+
combined.some(file => !all.includes(file))) throw new Error('test groups must cover scripts tests exactly once');
|
|
35
|
+
const history = discover('experiments/js-orchestration');
|
|
36
|
+
return {ordinary, native, history};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function selectTests(groups, group, {shards, index} = {}) {
|
|
40
|
+
if (!Object.hasOwn(groups, group)) throw new Error('group must be ordinary, native or history');
|
|
41
|
+
const files = groups[group];
|
|
42
|
+
if (shards === undefined && index === undefined) return files;
|
|
43
|
+
if (!Number.isInteger(shards) || shards < 1 || !Number.isInteger(index) || index < 0 || index >= shards)
|
|
44
|
+
throw new Error('--shards and --index must specify a positive count and an index in [0, shards)');
|
|
45
|
+
return assignShards(files, shards, readWeights())[index].files;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function runTests(files, concurrency) {
|
|
49
|
+
if (files.length === 0) throw new Error('selected test group or shard is empty');
|
|
50
|
+
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-test-suite-'));
|
|
51
|
+
const workflowHome = path.join(temp, 'workflow'), logHome = path.join(temp, 'logs');
|
|
52
|
+
fs.mkdirSync(workflowHome); fs.mkdirSync(logHome);
|
|
53
|
+
const args = ['--test', ...(concurrency === undefined ? [] : [`--test-concurrency=${concurrency}`]), ...files];
|
|
54
|
+
let child, requestedSignal;
|
|
55
|
+
const handlers = new Map();
|
|
56
|
+
try {
|
|
57
|
+
child = spawn(process.execPath, args, {cwd: root, stdio: 'inherit', detached: process.platform !== 'win32',
|
|
58
|
+
env: {...process.env, CM_WORKFLOW_HOME: workflowHome, CM_WORKFLOW_LOG_HOME: logHome}});
|
|
59
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
60
|
+
const handler = () => {
|
|
61
|
+
requestedSignal ??= signal;
|
|
62
|
+
if (!child.pid) return;
|
|
63
|
+
try {
|
|
64
|
+
if (process.platform === 'win32') child.kill(signal);
|
|
65
|
+
else process.kill(-child.pid, signal);
|
|
66
|
+
} catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
67
|
+
};
|
|
68
|
+
handlers.set(signal, handler); process.on(signal, handler);
|
|
69
|
+
}
|
|
70
|
+
const result = await new Promise((resolve, reject) => {
|
|
71
|
+
child.once('error', reject);
|
|
72
|
+
child.once('close', (code, signal) => resolve({code, signal}));
|
|
73
|
+
});
|
|
74
|
+
return {code: result.code ?? 1, signal: requestedSignal ?? result.signal};
|
|
75
|
+
} finally {
|
|
76
|
+
for (const [signal, handler] of handlers) process.off(signal, handler);
|
|
77
|
+
fs.rmSync(temp, {recursive: true, force: true});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function main(argv) {
|
|
82
|
+
const [command, ...rest] = argv;
|
|
83
|
+
if (!['check', 'list', 'run'].includes(command)) throw new Error('usage: cm-test-suite.mjs check | list|run ordinary|native|history [--shards N --index I] [--concurrency N]');
|
|
84
|
+
if (command === 'check') {
|
|
85
|
+
if (rest.length) throw new Error('check takes no arguments');
|
|
86
|
+
const groups = inventory();
|
|
87
|
+
for (const [group, files] of Object.entries(groups)) process.stdout.write(`${group}: ${files.length} files\n`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const group = rest.shift(), options = {};
|
|
91
|
+
for (let i = 0; i < rest.length; i += 2) {
|
|
92
|
+
const key = rest[i];
|
|
93
|
+
if (!['--shards', '--index', '--concurrency'].includes(key) || Object.hasOwn(options, key.slice(2)))
|
|
94
|
+
throw new Error(`unknown or repeated option: ${key}`);
|
|
95
|
+
if (!/^\d+$/.test(rest[i + 1] ?? '')) throw new Error(`invalid value for ${key}`);
|
|
96
|
+
options[key.slice(2)] = Number(rest[i + 1]);
|
|
97
|
+
}
|
|
98
|
+
if (options.concurrency !== undefined && (command !== 'run' || !Number.isSafeInteger(options.concurrency) || options.concurrency < 1))
|
|
99
|
+
throw new Error('--concurrency must be a positive integer for run');
|
|
100
|
+
const files = selectTests(inventory(), group, options);
|
|
101
|
+
if (command === 'list') { for (const file of files) process.stdout.write(`${file}\n`); return; }
|
|
102
|
+
const result = await runTests(files, options.concurrency);
|
|
103
|
+
if (result.signal) process.kill(process.pid, result.signal);
|
|
104
|
+
else process.exitCode = result.code;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
108
|
+
main(process.argv.slice(2)).catch(error => { process.stderr.write(`cm-test-suite: ${error.message}\n`); process.exitCode = 1; });
|
|
109
|
+
}
|