@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
|
@@ -31,16 +31,17 @@ export const batchTaskRunId=(batchId,taskKey)=>`task-${digest({batchId,task:task
|
|
|
31
31
|
// never advertise it for them. Name the exits that do exist instead. An idle
|
|
32
32
|
// cancel of a parallel group does not end its member runs, so a parallel
|
|
33
33
|
// member cannot be superseded afterwards and only the spec revert applies.
|
|
34
|
-
export function batchMemberResult(result,{parallel=false,taskKey=null}={}){
|
|
34
|
+
export function batchMemberResult(result,{parallel=false,taskKey=null,protocol='legacy'}={}){
|
|
35
35
|
const decorate=value=>{
|
|
36
|
-
const guidance=batchOperatorGuidance(value,{taskKey});
|
|
36
|
+
const guidance=batchOperatorGuidance(value,{taskKey,protocol});
|
|
37
37
|
return guidance?Object.freeze({...value,guidance}):value;
|
|
38
38
|
};
|
|
39
39
|
if(result?.pendingAction!=='spec_rebind')return decorate(result);
|
|
40
40
|
const files=/变更文件:([^;]+)/.exec(result.reason??'')?.[1]??'规格文件';
|
|
41
41
|
const revert=`规格已重新批准(变更:${files},只动了其他任务),但批次成员不能换绑。出口:还原这些规格改动并重新批准后继续本批次`;
|
|
42
42
|
return decorate(Object.freeze({...result,pendingAction:'none',
|
|
43
|
-
reason:
|
|
43
|
+
reason:protocol==='v2'?`${revert}。v2 不支持作废旧证据后新建运行;保留原记录,不改走旧入口。`
|
|
44
|
+
:parallel?`${revert}。并行组成员没有单独重做的出口。`
|
|
44
45
|
:`${revert};或取消本批次,还原该任务已改动的代码后,用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务。`}));
|
|
45
46
|
}
|
|
46
47
|
// Q24: single-task recovery operations a batch forwards to the member run it is
|
|
@@ -224,7 +225,9 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
|
|
|
224
225
|
const run=await openControlRun(definition,mode,execution,{...recovery,...permission,...(held.has(taskKey)?{holdRevision:true}:{}),
|
|
225
226
|
...(membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{})});
|
|
226
227
|
if(!run.host)return run;
|
|
227
|
-
|
|
228
|
+
const decorate=host=>({...host,handle:async request=>batchMemberResult(await host.handle(request),
|
|
229
|
+
{parallel:membership.has(taskKey),taskKey,protocol:controlPolicy?'v2':'legacy'})});
|
|
230
|
+
return {...run,host:decorate(run.host),...(run.controlHost?{controlHost:decorate(run.controlHost)}:{})};
|
|
228
231
|
}
|
|
229
232
|
function parallelProgress(rows){
|
|
230
233
|
const done=new Set(),ready=new Map(),merging=new Map(),blocked=new Map();let stopped=false,code=null;
|
|
@@ -488,7 +491,8 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
|
|
|
488
491
|
:!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state)?`supersede 不接受原始状态 ${raw}`
|
|
489
492
|
:`外部运行守卫会拒绝在这个代码根上新建运行(原严格运行仍为 ${raw} 或有未对账的调用),原调用对账也不可用`;
|
|
490
493
|
const exit=`只读核对 ${key} 原运行的记录、进程与 worktree(${location(key).worktree});`
|
|
491
|
-
+(
|
|
494
|
+
+(controlPolicy?'v2 不支持作废旧证据后新建运行;保留原批次、运行与 worktree,核对原调用与 reason 后交由维护者处理,不改走旧入口'
|
|
495
|
+
:supersedable?`确认旧宿主与该成员的会话或子进程已停止写入后,取消本批次,还原该任务已改动的代码,用单任务宿主 cm-ai-host.mjs(不加 --external-models、--execution-optimizations)以该 worktree 为代码根、--supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务`
|
|
492
496
|
:`批次与单任务宿主目前都没有能处理它的操作:${why}${original}。保留批次、原运行和 worktree,不要取消批次或手改存档,把 rawState 与本 reason 交给维护者处理`);
|
|
493
497
|
return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_unresolved',batchId:config.batchId,
|
|
494
498
|
currentTask:key,identity:status.identity,memberState:status.state,memberCode:status.code??null,pendingAction:status.pendingAction??null,
|
|
@@ -508,7 +512,9 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
|
|
|
508
512
|
}
|
|
509
513
|
function parallelRecoveryRequired(key,status){
|
|
510
514
|
const action=status.pendingAction,grant=BATCH_MEMBER_ACTIONS[action];
|
|
511
|
-
const exit=
|
|
515
|
+
const exit=controlPolicy
|
|
516
|
+
?`从原批次入口只读 status,展示并核对完整批次 controlTarget,按当前对话的具体决定固定为 expectedControl;发送 version:2 的批次操作 ${action}(taskKey ${key}、${action==='reconcile_review'?'原调用 invocationId':'单行 reason'});snapshot_changed 时停止,不自动刷新目标重试`
|
|
517
|
+
:action==='reconcile_review'
|
|
512
518
|
?`从批次入口发送 reconcile_review(taskKey ${key}、原调用 invocationId)对账原调用回执`
|
|
513
519
|
:`关闭批次宿主,带 ${grant.flag} ${key} 用同一批次配置重新启动,发送批次操作 ${action}(taskKey ${key}、单行 reason)`;
|
|
514
520
|
return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_recovery_required',batchId:config.batchId,
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
|
+
import {operatorGuidance,guidanceText} from '../runtime/js/cm-ai/operator-guidance.mjs';
|
|
2
3
|
import assert from 'node:assert/strict';
|
|
3
4
|
import fs from 'node:fs';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
import {createCmAiBatch,batchTaskRunId} from './cm-ai-batch-run.mjs';
|
|
4
7
|
import os from 'node:os';
|
|
5
8
|
import path from 'node:path';
|
|
6
9
|
import {buildManifest} from './cm-spec-manifest.mjs';
|
|
@@ -122,3 +125,68 @@ test('reused error codes do not swallow failures from the underlying host',async
|
|
|
122
125
|
?{expectedControl:controlTarget(status,snapshot())}:{})),error=>error===failure);
|
|
123
126
|
}
|
|
124
127
|
});
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
test('v2 wrapper re-renders recovery guidance without reads, mutations or journal changes',async()=>{
|
|
131
|
+
let reads=0;const current=snapshot(),before=JSON.stringify(current);
|
|
132
|
+
const native={workflow:'cm-ai',...status,pendingAction:'abandon_effect',outcome:'reported'};
|
|
133
|
+
native.guidance=operatorGuidance(native);const nativeBefore=JSON.stringify(native);
|
|
134
|
+
const requests=[];
|
|
135
|
+
const host=withControlPolicyHost({async handle(request){requests.push(request);return native;}},
|
|
136
|
+
{identity,snapshot:()=>{reads++;return current;}});
|
|
137
|
+
for(const operation of ['status','advance']){
|
|
138
|
+
const output=await host.handle(wire(operation));
|
|
139
|
+
assert.doesNotMatch(guidanceText(output),/--allow-/);assert.match(guidanceText(output),/expectedControl/);
|
|
140
|
+
const {guidance,controlTarget:target,...unchanged}=output;
|
|
141
|
+
const {guidance:original,...expected}=native;assert.deepEqual(unchanged,expected);
|
|
142
|
+
}
|
|
143
|
+
assert.equal(reads,1,'guidance does not read state');assert.equal(requests.length,2,'guidance does not dispatch');
|
|
144
|
+
assert.equal(JSON.stringify(current),before);assert.equal(JSON.stringify(native),nativeBefore);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('v2 wrapper preserves an active-operation suppression',async()=>{
|
|
148
|
+
const native={workflow:'cm-ai',...status,pendingAction:'abandon_effect',outcome:'reported'};
|
|
149
|
+
native.guidance=operatorGuidance(native,{executionActive:true});
|
|
150
|
+
const host=withControlPolicyHost({async handle(){return native;}},{identity,snapshot});
|
|
151
|
+
const output=await host.handle(wire('status'));
|
|
152
|
+
assert.equal(output.guidance.recoveryOperation,null);assert.match(guidanceText(output),/不重复派发/);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
test('real v2 batch status and recovery render the batch target and leave status history unchanged',async t=>{
|
|
157
|
+
const root=temp(t),codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),logHome=path.join(root,'logs');
|
|
158
|
+
const feature='1.work',taskKey=`${feature}/T-001`,batchId='guidance-batch';
|
|
159
|
+
fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
|
|
160
|
+
// A clean disposable Git root without a commit; explicit scope remains authoritative.
|
|
161
|
+
const initialized=spawnSync('git',['init','-q',codeProject],{encoding:'utf8'});assert.equal(initialized.status,0);
|
|
162
|
+
fs.writeFileSync(path.join(codeProject,'.git/info/exclude'),'*\n');
|
|
163
|
+
fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
|
|
164
|
+
for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
|
|
165
|
+
fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
|
|
166
|
+
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
|
|
167
|
+
let calls=0;
|
|
168
|
+
const configuration={version:1,repositoryId:identity.repositoryId,batchId,specsDir,codeProject,controlPolicy:policy,
|
|
169
|
+
tasks:[{feature,taskId:'T-001',scope:['target.mjs'],requirements:[]}]};
|
|
170
|
+
const batch=createCmAiBatch({configuration,logHome,executionFor:async definition=>createConversationExecution(
|
|
171
|
+
definition,'control-fixture-host',{async call(operation){
|
|
172
|
+
calls++;assert.equal(operation,'develop');fs.writeFileSync(path.join(codeProject,'target.mjs'),'// preserved edit\n');
|
|
173
|
+
throw Object.assign(new Error('Synthetic disconnect'),{code:'host_disconnected'});
|
|
174
|
+
}},{model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
|
|
175
|
+
config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}},null,null,false,'codex',{controlPolicy:policy,qaLogHome:logHome})});
|
|
176
|
+
const advance=await batch.handle({version:2,operation:'advance',requestId:'batch-advance'});
|
|
177
|
+
assert.equal(advance.pendingAction,'develop_redo',JSON.stringify(advance));
|
|
178
|
+
assert.match(guidanceText(advance),/完整批次 controlTarget/);assert.doesNotMatch(guidanceText(advance),/--allow-/);
|
|
179
|
+
const journal=path.join(specsDir,'.reviews/.execution',batchTaskRunId(batchId,taskKey),'state.json');
|
|
180
|
+
const before=fs.readFileSync(journal),log=path.join(specsDir,'运行日志.jsonl'),beforeLog=fs.readFileSync(log);
|
|
181
|
+
const reported=await batch.handle({version:2,operation:'status',requestId:'batch-status'});
|
|
182
|
+
assert.match(guidanceText(reported),/batchId、taskKey、member、batchDigest/);
|
|
183
|
+
assert.deepEqual(fs.readFileSync(journal),before);assert.deepEqual(fs.readFileSync(log),beforeLog);assert.equal(calls,1);
|
|
184
|
+
const expectedControl=await batch.controlTarget();
|
|
185
|
+
assert.deepEqual(fs.readFileSync(journal),before);assert.deepEqual(fs.readFileSync(log),beforeLog);
|
|
186
|
+
const recovered=await batch.handle({version:2,operation:'develop_redo',requestId:'batch-redo',taskKey,
|
|
187
|
+
reason:'Synthetic stopped conversation',expectedControl});
|
|
188
|
+
assert.equal(recovered.code,'develop_answer_missing',JSON.stringify(recovered));
|
|
189
|
+
assert.match(guidanceText(recovered),/原批次入口/);assert.doesNotMatch(guidanceText(recovered),/--allow-|恢复原运行/);
|
|
190
|
+
assert.equal(calls,1,'recovery only records confirmation');
|
|
191
|
+
assert.equal(fs.readFileSync(path.join(codeProject,'target.mjs'),'utf8'),'// preserved edit\n');
|
|
192
|
+
});
|
|
@@ -230,7 +230,7 @@ test('init-verify commands never run unless the host itself accepted the launch
|
|
|
230
230
|
{status:2,pattern:/T-002 现在不能新建运行:admission ready,nextTask T-001.*不运行 init-verify 命令/}],
|
|
231
231
|
// No driver replica: the host's own launch check refuses before host_ready.
|
|
232
232
|
['nested specs without protection',{nested:true},f=>rulesPermissions,
|
|
233
|
-
{status:
|
|
233
|
+
{status:71,pattern:/nested_specs_protection_required/}],
|
|
234
234
|
];
|
|
235
235
|
for(const [name,options,permissions,expected] of cases){
|
|
236
236
|
const f=fixture(t,{scaffolded:!options.pending,nested:options.nested});
|
|
@@ -239,6 +239,7 @@ test('init-verify commands never run unless the host itself accepted the launch
|
|
|
239
239
|
prepareRules(f,1,{commands:[{id:'marker',command:['/bin/sh','-c',`echo ran > ${marker}`]}]});
|
|
240
240
|
const run=f.drive(f.plan('T-002','create',permissions(f)),'advance');
|
|
241
241
|
assert.equal(run.status,expected.status,`${name}: ${run.stderr}`);assert.match(run.stderr,expected.pattern,name);
|
|
242
|
+
if(expected.status===71)assert.match(run.stderr,/host_exited/,name);
|
|
242
243
|
assert.equal(fs.existsSync(marker),false,`${name}: no command may run`);
|
|
243
244
|
assert.equal(fs.existsSync(f.store('T-002')),false,name);
|
|
244
245
|
assert.equal(fs.existsSync(path.join(f.codeProject,'.claude')),false,name);
|
|
@@ -407,7 +408,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
|
|
|
407
408
|
launchReview=['--review-config','wrong-runtime-review.json'];
|
|
408
409
|
}
|
|
409
410
|
run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...launchReview],extra),'start');
|
|
410
|
-
assert.equal(run.status,
|
|
411
|
+
assert.equal(run.status,71,run.stderr);assert.match(run.stderr,/host_exited/);assert.match(run.stderr,/fingerprint_mismatch/);
|
|
411
412
|
assert.doesNotMatch(run.stderr,/\[drive init_verify/);
|
|
412
413
|
assert.equal(fs.existsSync(marker),false);assert.deepEqual(fs.readFileSync(state),before);
|
|
413
414
|
}
|
|
@@ -449,17 +449,17 @@ test('same-session resume may omit originalHostContext and cross-session omissio
|
|
|
449
449
|
assert.equal(same.status,0,same.stderr);
|
|
450
450
|
assert.equal(JSON.parse(same.stdout).result.state,'fixture_completed');
|
|
451
451
|
const cross=f.drive(f.plan({mode:'resume',hostContext:'drive-host-b',answers:undefined,checks:undefined}),'status');
|
|
452
|
-
assert.equal(cross.status,
|
|
452
|
+
assert.equal(cross.status,71,cross.stderr);assert.match(cross.stderr,/host_exited/);assert.match(cross.stderr,/fingerprint_mismatch/);
|
|
453
453
|
assert.deepEqual(fs.readFileSync(f.store),before);
|
|
454
454
|
});
|
|
455
455
|
test('supersession flags reach create and incomplete or resume pairs stop before host launch',t=>{
|
|
456
456
|
const f=fixture(t);prepared(f);
|
|
457
457
|
const both=['--supersede-reviewed-evidence','--supersede-reason','operator restart'];
|
|
458
458
|
const create=f.drive(f.plan({permissions:both}),'advance');
|
|
459
|
-
assert.equal(create.status,
|
|
459
|
+
assert.equal(create.status,71,create.stderr);assert.match(create.stderr,/host_exited/);
|
|
460
460
|
assert.match(create.stderr,/supersede_unavailable/);
|
|
461
461
|
const accepted=f.drive(f.plan({permissions:[...both,'--accept-superseded-code-drift']}),'advance');
|
|
462
|
-
assert.equal(accepted.status,
|
|
462
|
+
assert.equal(accepted.status,71,accepted.stderr);assert.match(accepted.stderr,/host_exited/);
|
|
463
463
|
assert.match(accepted.stderr,/supersede_unavailable/);
|
|
464
464
|
for(const permissions of [['--supersede-reviewed-evidence'],['--supersede-reason','operator restart']]){
|
|
465
465
|
const refused=f.drive(f.plan({permissions}),'advance');
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
|
|
1
2
|
// Shared real-host fixture for the cm-ai-host*.test.mjs files (the Codex-sandbox
|
|
2
3
|
// set that CI cannot host). Importing it isolates CM_WORKFLOW_HOME/LOG_HOME for the
|
|
3
4
|
// importing test file and sweeps every fixture root for leaked processes when that
|
|
@@ -81,6 +82,8 @@ export function runCli(f,mode,action='create'){
|
|
|
81
82
|
const args=[...launchArgs(f)];args[4]=action;
|
|
82
83
|
const child=spawn(process.execPath,[cli,...args],{stdio:['pipe','pipe','pipe'],env:f.env??process.env});
|
|
83
84
|
let buffer='',stderr='',closed=false,sessionId;const rows=[],calls=[];
|
|
85
|
+
const timeoutMs=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
|
|
86
|
+
const trace=hostDiagnostic(child,{timeoutMs:f.watchdog?null:timeoutMs});
|
|
84
87
|
// Provider children run in their own process groups: stopping only the host
|
|
85
88
|
// would orphan a hung fake reviewer, so failure and watchdog paths stop the
|
|
86
89
|
// whole fixture tree. f.watchdog(expire) may replace the timer; it returns a disarm function.
|
|
@@ -88,13 +91,13 @@ export function runCli(f,mode,action='create'){
|
|
|
88
91
|
const fail=error=>{
|
|
89
92
|
disarm();child.kill('SIGKILL');
|
|
90
93
|
try{killFixtureProcesses(f.root);}catch(cleanup){error=new AggregateError([error,cleanup],String(error?.message??error));}
|
|
91
|
-
reject(error);
|
|
94
|
+
reject(trace.attach(error));
|
|
92
95
|
};
|
|
93
|
-
disarm=(f.watchdog??(expire=>{const timer=setTimeout(expire,
|
|
96
|
+
disarm=(f.watchdog??(expire=>{const timer=setTimeout(expire,timeoutMs);
|
|
94
97
|
return ()=>clearTimeout(timer);}))(()=>fail(new Error('host fixture timed out')));
|
|
95
98
|
child.stderr.on('data',chunk=>{stderr+=chunk;});
|
|
96
|
-
child.once('error',reject);
|
|
97
|
-
const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
|
|
99
|
+
child.once('error',error=>reject(trace.attach(error)));
|
|
100
|
+
const send=value=>{trace.send(value);child.stdin.write(JSON.stringify(value)+'\n');};
|
|
98
101
|
const response=(row,result)=>({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
|
|
99
102
|
child.stdout.on('data',chunk=>{
|
|
100
103
|
buffer+=chunk;
|
|
@@ -103,7 +106,7 @@ export function runCli(f,mode,action='create'){
|
|
|
103
106
|
const line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);
|
|
104
107
|
if(!line)continue;
|
|
105
108
|
try{
|
|
106
|
-
const row=JSON.parse(line);rows.push(row);
|
|
109
|
+
const row=JSON.parse(line);rows.push(row);trace.receive(row);
|
|
107
110
|
if(row.type==='host_ready')sessionId=row.sessionId;
|
|
108
111
|
if(row.type==='host_request'){
|
|
109
112
|
calls.push(row.kind);
|
|
@@ -181,7 +184,7 @@ export function runCli(f,mode,action='create'){
|
|
|
181
184
|
}catch(error){fail(error);return;}
|
|
182
185
|
}
|
|
183
186
|
});
|
|
184
|
-
child.once('close',code=>{disarm();resolve({code,stderr,rows,calls});});
|
|
187
|
+
child.once('close',code=>{disarm();resolve({code,stderr,rows,calls,diagnostic:trace.snapshot()});});
|
|
185
188
|
send(f.request??{...request(f.operation??'advance'),requestId:'advance'});
|
|
186
189
|
});
|
|
187
190
|
}
|
|
@@ -27,7 +27,7 @@ for(const [available,coder,reviewer,runtime] of [
|
|
|
27
27
|
assert(!fs.existsSync(path.join(f.codeProject,'target.mjs')));assert(!fs.existsSync(path.join(f.specsDir,'.reviews')));
|
|
28
28
|
f.args.push('--allow-provider-development-attempt','1');
|
|
29
29
|
const first=await runCli(f,'normal');assert.equal(first.code,0,first.stderr);
|
|
30
|
-
assert.equal(first.rows.find(row=>row.requestId==='advance').result.code,null);assert.deepEqual(first.calls,[]);
|
|
30
|
+
assert.equal(first.rows.find(row=>row.requestId==='advance').result.code,null,JSON.stringify(first.diagnostic));assert.deepEqual(first.calls,[]);
|
|
31
31
|
assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 42;\n');
|
|
32
32
|
const readRoutes=()=>fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)
|
|
33
33
|
.filter(row=>row.phase==='route'&&row.event==='decision');
|
|
@@ -597,3 +597,18 @@ test('ordinary CLI accepts --review-runtime claude under a Codex host and refuse
|
|
|
597
597
|
}finally{fs.rmSync(f.root,{recursive:true,force:true});}
|
|
598
598
|
}
|
|
599
599
|
});
|
|
600
|
+
|
|
601
|
+
// Diagnostics must survive a real child startup failure without printing its inputs.
|
|
602
|
+
test('host fixture startup failure retains bounded process diagnostics',async()=>{
|
|
603
|
+
const f=fixture();
|
|
604
|
+
try{
|
|
605
|
+
f.args.push('--synthetic-unknown-option');
|
|
606
|
+
const result=await runCli(f,'normal');
|
|
607
|
+
assert.equal(result.code,1);
|
|
608
|
+
assert.equal(result.diagnostic.exitCode,1);
|
|
609
|
+
assert.equal(result.diagnostic.lastOperation,'advance');
|
|
610
|
+
assert.equal(result.diagnostic.timeoutMs,Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
|
|
611
|
+
assert(result.diagnostic.stderrBytes>0);
|
|
612
|
+
assert(!JSON.stringify(result.diagnostic).includes(f.root));
|
|
613
|
+
}finally{fs.rmSync(f.root,{recursive:true,force:true});}
|
|
614
|
+
});
|
|
@@ -117,3 +117,59 @@ test('V5 the second no-result redispatch asks for the operator stop confirmation
|
|
|
117
117
|
const g=explain('blocked','review_transport_timeout','abandon_review',{reviewRedispatchStopRequired:true});
|
|
118
118
|
assert.equal(g.recoveryOperation,'abandon_review');assert.match(g.nextStep,/确认原审查进程/);assert.equal(g.authorizationGranted,false);
|
|
119
119
|
});
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
test('recovery guidance selects protocol and surface without changing native results',()=>{
|
|
123
|
+
const cases=[['unknown','execution_error','abandon_effect'],['unknown','execution_error','abandon_review'],
|
|
124
|
+
['blocked','bootstrap_review_mismatch','bootstrap_review_recover'],['blocked','develop_answer_missing','develop_redo'],
|
|
125
|
+
['blocked','documentation_sync_answer_missing','develop_redo']];
|
|
126
|
+
for(const protocol of ['legacy','v2'])for(const surface of ['single','batch'])for(const [state,code,action] of cases){
|
|
127
|
+
const input=result(state,code,action),before=JSON.stringify(input);
|
|
128
|
+
const value={...input,guidance:operatorGuidance(input,{protocol})};
|
|
129
|
+
const output=surface==='batch'?batchMemberResult(value,{protocol,taskKey:'1.work/T-001'}):value;
|
|
130
|
+
const rendered=guidanceText(output);
|
|
131
|
+
assert.equal(output.guidance.recoveryOperation,action);assert.equal(output.guidance.authorizationGranted,false);
|
|
132
|
+
assert.equal(JSON.stringify(input),before);
|
|
133
|
+
assert.equal(output.state,input.state);assert.equal(output.code,input.code);assert.equal(output.pendingAction,input.pendingAction);
|
|
134
|
+
if(protocol==='v2'){
|
|
135
|
+
assert.doesNotMatch(rendered,/--allow-|--supersede-reviewed-evidence/);
|
|
136
|
+
assert.match(rendered,/status/);assert.match(rendered,/expectedControl/);assert.match(rendered,/snapshot_changed/);
|
|
137
|
+
assert.match(rendered,/不自动刷新/);
|
|
138
|
+
}else assert.match(rendered,/--allow-/);
|
|
139
|
+
if(surface==='batch')assert.match(rendered,/批次/);
|
|
140
|
+
if(code==='documentation_sync_answer_missing')assert.match(rendered,/停止修改文档/);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('v2 exhausted recovery and launch recovery never advertise legacy exits',()=>{
|
|
145
|
+
for(const code of ['review_redispatch_limit','documentation_sync_retry_limit','check_answer_retry_limit','complete_recheck_limit','develop_redo_limit']){
|
|
146
|
+
for(const protocol of ['legacy','v2'])for(const surface of ['single','batch']){
|
|
147
|
+
const input=result('blocked',code,'none');input.guidance=operatorGuidance(input,{protocol});
|
|
148
|
+
const output=surface==='batch'?batchMemberResult(input,{protocol}):input;
|
|
149
|
+
assert.equal(output.guidance.recoveryOperation,null);
|
|
150
|
+
if(protocol==='v2'){assert.doesNotMatch(guidanceText(output),/--supersede-reviewed-evidence|--accept-superseded-code-drift/);
|
|
151
|
+
assert.match(guidanceText(output),/保留/);}
|
|
152
|
+
else assert.match(guidanceText(output),/--supersede-reviewed-evidence/);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for(const refusal of ['review_process_unverified','review_observation_invalid','review_boundary_unverified','review_abandon_budget_exhausted']){
|
|
156
|
+
const input=result('unknown','transport_incomplete','reconcile',{reviewAbandonRefusal:refusal});
|
|
157
|
+
input.guidance=operatorGuidance(input,{protocol:'v2'});
|
|
158
|
+
assert.doesNotMatch(guidanceText(input),/--supersede-reviewed-evidence/);
|
|
159
|
+
}
|
|
160
|
+
const qa=result('fixture_completed','qa_execution_unknown','reconcile');qa.guidance=operatorGuidance(qa,{protocol:'v2'});
|
|
161
|
+
assert.match(guidanceText(qa),/launchControlTarget/);assert.match(guidanceText(qa),/--expected-control/);
|
|
162
|
+
assert.doesNotMatch(guidanceText(qa),/--supersede-reviewed-evidence/);
|
|
163
|
+
const batch=batchMemberResult(qa,{protocol:'v2'});
|
|
164
|
+
assert.doesNotMatch(guidanceText(batch),/--rerun-unknown-qa|--expected-control/);
|
|
165
|
+
const drift=result('blocked','spec_drift','spec_rebind',{reason:'synthetic'});drift.guidance=operatorGuidance(drift,{protocol:'v2'});
|
|
166
|
+
assert.doesNotMatch(JSON.stringify(batchMemberResult(drift,{protocol:'v2'})),/--supersede-reviewed-evidence/);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test('batch advance guidance uses the batch entry for every native resume family',()=>{
|
|
170
|
+
for(const code of ['documentation_sync_interrupted','develop_answer_missing','develop_out_of_scope','check_answer_missing','develop_checks_not_passed']){
|
|
171
|
+
const input=result('blocked',code,'resume');input.guidance=operatorGuidance(input);
|
|
172
|
+
const output=batchMemberResult(input);
|
|
173
|
+
assert.match(guidanceText(output),/原批次入口/);assert.doesNotMatch(guidanceText(output),/恢复原运行/);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {withHostStageObserver} from '../runtime/js/cm-ai/host-stage-observer.mjs';
|
|
1
2
|
import test from 'node:test';
|
|
2
3
|
import assert from 'node:assert/strict';
|
|
3
4
|
import fs from 'node:fs';
|
|
@@ -514,3 +515,22 @@ test('review-redispatch replay refuses forged, duplicate and over-limit records'
|
|
|
514
515
|
assert.equal(projectedRunnerStatus(older,config).state,'blocked');assert.equal(projectedRunnerStatus(older,config).reviewRedispatchStopRequired,true);
|
|
515
516
|
assert.equal(projectedRunnerStatus(readRunnerHistory(records,config,3),config).code,'review_redispatch_limit');
|
|
516
517
|
},{timeoutMs:20,reviewRun:timeoutRun}));
|
|
518
|
+
|
|
519
|
+
// Transport telemetry must use the existing budgets without entering durable history.
|
|
520
|
+
test('native review telemetry reports its configured deadline and leaves original replay unchanged',()=>fixture(async f=>{
|
|
521
|
+
f.options.reviewInvocation.timeoutMs=2500;
|
|
522
|
+
const runner=f.make(),rows=[];
|
|
523
|
+
await withHostStageObserver(row=>rows.push(row),async()=>{
|
|
524
|
+
await runner.executeEffect(f.effect('develop'));
|
|
525
|
+
const result=await runner.executeEffect(f.effect('review'));
|
|
526
|
+
assert.equal(result.state,'approved');
|
|
527
|
+
});
|
|
528
|
+
const review=rows.find(row=>row?.kind==='review');assert.ok(review);
|
|
529
|
+
assert.equal(review.deadlineMs-Date.parse(review.startedAt),2500);
|
|
530
|
+
assert.ok(rows.some(row=>row?.kind==='develop'));
|
|
531
|
+
assert.ok(rows.some(row=>row?.kind==='check'));
|
|
532
|
+
const before=JSON.stringify(f.getStore().snapshot());
|
|
533
|
+
assert.doesNotMatch(before,/nativeStage|host_heartbeat|lastProgressAt|deadlineMs/);
|
|
534
|
+
const resumed=f.reopen();assert.equal(resumed.status().state,'approved');
|
|
535
|
+
assert.equal(JSON.stringify(f.getStore().snapshot()),before);
|
|
536
|
+
},{timeoutMs:5000}));
|
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
export const CHECK_DRIVE_COPIED_FILES=Object.freeze([
|
|
4
4
|
'scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-check-drive.mjs',
|
|
5
5
|
'scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs','runtime/js/cm-ai/drive-core.mjs',
|
|
6
|
-
'runtime/js/cm-ai/operator-guidance.mjs',
|
|
6
|
+
'runtime/js/cm-ai/operator-guidance.mjs','runtime/js/cm-ai/host-stage-observer.mjs',
|
|
7
7
|
'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/diagnostic-reason.mjs','runtime/js/cm-ai/effect-contract.mjs',
|
|
8
8
|
'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']);
|
|
@@ -19,7 +19,7 @@ function fixture(t,exitCode=0){
|
|
|
19
19
|
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-host-'))),project=path.join(dir,'project');fs.mkdirSync(project);
|
|
20
20
|
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
21
21
|
for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs',
|
|
22
|
-
'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/diagnostic-reason.mjs','runtime/js/cm-ai/effect-contract.mjs',
|
|
22
|
+
'runtime/js/cm-ai/host-stage-observer.mjs','runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/diagnostic-reason.mjs','runtime/js/cm-ai/effect-contract.mjs',
|
|
23
23
|
'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']){
|
|
24
24
|
fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
|
|
25
25
|
}
|
|
@@ -12,6 +12,32 @@ import {ownerGuardSource} from './fixtures/process-cleanup.mjs';
|
|
|
12
12
|
import {previewClaudeTools,claudeProbeSandbox,createClaudeModelMarkerDetector} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
|
|
13
13
|
import {previewPromptTransport,writePreviewPrompt} from '../runtime/js/cm-ai/tool-preview.mjs';
|
|
14
14
|
|
|
15
|
+
for(const sendMessage of [true,false])test(`UI invalidation before init ${sendMessage?'permits a validated POST':'cannot make startup-only preflight pass'}`,
|
|
16
|
+
{skip:process.platform!=='darwin'},async()=>{
|
|
17
|
+
// Emit the real CLI ordering before POST. Existing HTTP-first fixtures cannot
|
|
18
|
+
// detect a worker that kills the child while decoding its startup notice.
|
|
19
|
+
const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
|
|
20
|
+
await fetch(process.env.ANTHROPIC_BASE_URL+'/api/hello',{method:'HEAD'});
|
|
21
|
+
console.log(JSON.stringify({type:'system',subtype:'ui_invalidate',session_id:'probe-ui'}));
|
|
22
|
+
console.log(JSON.stringify({type:'system',subtype:'init',session_id:'probe-ui'}));
|
|
23
|
+
await new Promise(resolve=>setTimeout(resolve,100));
|
|
24
|
+
if(${sendMessage}){
|
|
25
|
+
await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
|
|
26
|
+
headers:{'x-api-key':'cm-synthetic-local-probe'},
|
|
27
|
+
body:JSON.stringify({model:'fixture',messages:[{role:'user',content:input}],tools:[]})});
|
|
28
|
+
}
|
|
29
|
+
process.exit(1);
|
|
30
|
+
});`;
|
|
31
|
+
const {preflight}=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
|
|
32
|
+
spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
|
|
33
|
+
assert.equal(preflight.passed,sendMessage);
|
|
34
|
+
assert.equal(preflight.message_requests,sendMessage?1:0);
|
|
35
|
+
assert.equal(preflight.local_requests,sendMessage?2:1);
|
|
36
|
+
assert.equal(preflight.stopped_by_probe,sendMessage);
|
|
37
|
+
assert.equal(preflight.listener_closed,true);
|
|
38
|
+
if(sendMessage)assert.equal(preflight.request_checks[1].synthetic_auth,true);
|
|
39
|
+
});
|
|
40
|
+
|
|
15
41
|
test('tool preview argument transport preserves a long Unicode argv prompt without stdin',()=>{
|
|
16
42
|
const prompt='参数\n🚀'+'界'.repeat(10000);
|
|
17
43
|
const transport=previewPromptTransport('argument',prompt);
|
|
@@ -9,6 +9,42 @@ const transcript = () => [
|
|
|
9
9
|
{type:'result', subtype:'success', session_id:'fresh-review', is_error:false,
|
|
10
10
|
num_turns:1, structured_output:{verdict:'approved'}},
|
|
11
11
|
];
|
|
12
|
+
const uiInvalidate = (over={}) => ({type:'system',subtype:'ui_invalidate',session_id:'fresh-review',...over});
|
|
13
|
+
test('UI invalidation before and after init is body-free and leaves review events unchanged',()=>{
|
|
14
|
+
const baseline=observe(transcript()),[init,...tail]=transcript();
|
|
15
|
+
for(const messages of [[uiInvalidate(),init,...tail],[init,uiInvalidate(),...tail],
|
|
16
|
+
[uiInvalidate({payload:{text:'do not forward'},structured_output:{verdict:'approved'}}),init,...tail]]){
|
|
17
|
+
const actual=observe(messages);
|
|
18
|
+
assert.deepEqual(actual.result,baseline.result);assert.deepEqual(actual.events,baseline.events);
|
|
19
|
+
assert.deepEqual(actual.notices,[{kind:'claude_system_notice',subtype:'ui_invalidate'}]);
|
|
20
|
+
}
|
|
21
|
+
const events=[],stream=createClaudeReviewStream(e=>events.push(e));stream.accept(uiInvalidate());
|
|
22
|
+
assert.deepEqual(events,[]);assert.throws(()=>stream.finish(),{code:'incomplete_result'});
|
|
23
|
+
});
|
|
24
|
+
test('UI invalidation preserves session, initialization and terminal boundaries',()=>{
|
|
25
|
+
const [init,text,result]=transcript();
|
|
26
|
+
for(const notice of [uiInvalidate({session_id:''}),uiInvalidate({session_id:null}),uiInvalidate({session_id:'x'.repeat(257)})])
|
|
27
|
+
assert.throws(()=>decode([notice,init,text,result]),{code:'invalid_session'});
|
|
28
|
+
assert.throws(()=>decode([uiInvalidate(),{...init,session_id:'other'}]),{code:'session_mismatch'});
|
|
29
|
+
assert.throws(()=>decode([init,uiInvalidate({session_id:'other'}),text,result]),{code:'session_mismatch'});
|
|
30
|
+
assert.throws(()=>decode([uiInvalidate(),text,result]),{code:'missing_init'});
|
|
31
|
+
assert.throws(()=>decode([init,uiInvalidate(),result]),{code:'unexpected_result'});
|
|
32
|
+
assert.throws(()=>decode([init,text,result,uiInvalidate()]),{code:'unexpected_event'});
|
|
33
|
+
assert.throws(()=>decode([uiInvalidate({subtype:'future_ui'}),init,text,result]),{code:'missing_init'});
|
|
34
|
+
});
|
|
35
|
+
test('UI invalidation shares the existing 32 notice slots across init',()=>{
|
|
36
|
+
const [init,...tail]=transcript(),dev={type:'system',subtype:'dev_intent',session_id:'fresh-review'};
|
|
37
|
+
const before=Array.from({length:16},(_,i)=>i%2?dev:uiInvalidate());
|
|
38
|
+
const after=Array.from({length:16},()=>uiInvalidate());
|
|
39
|
+
const actual=observe([...before,init,...after,...tail]);assert.equal(actual.notices.length,32);
|
|
40
|
+
assert.deepEqual(actual.events,observe(transcript()).events);
|
|
41
|
+
for(const callback of [null,()=>{throw Error('notice callback');}]){
|
|
42
|
+
const stream=createClaudeReviewStream(()=>{},callback);
|
|
43
|
+
[...before,init,...after].forEach(m=>stream.accept(m));
|
|
44
|
+
assert.throws(()=>stream.accept(uiInvalidate()),{code:'unexpected_event'});
|
|
45
|
+
assert.throws(()=>stream.finish(),{code:'incomplete_result'});
|
|
46
|
+
}
|
|
47
|
+
});
|
|
12
48
|
test('Claude result maps to original observer syntax, never invents process close', () => {
|
|
13
49
|
const events=[], stream=createClaudeReviewStream(event=>events.push(event));
|
|
14
50
|
transcript().forEach(message=>stream.accept(message));
|
|
@@ -75,6 +75,22 @@ async function runMessages(wireMessages,onNotice){
|
|
|
75
75
|
{signal:new AbortController().signal,onEvent:e=>events.push(e)});
|
|
76
76
|
return {result,events};
|
|
77
77
|
}
|
|
78
|
+
test('UI invalidation prefix does not stop the Claude reviewer before init',async()=>{
|
|
79
|
+
const notices=[],notice={type:'system',subtype:'ui_invalidate',session_id:'fresh-review',payload:{text:'not forwarded'}};
|
|
80
|
+
const actual=await runMessages([notice,...messages],n=>notices.push(n));
|
|
81
|
+
assert.deepEqual(actual,await runMessages(messages));
|
|
82
|
+
assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'ui_invalidate'}]);
|
|
83
|
+
});
|
|
84
|
+
test('UI invalidation without init or with a different session never produces review success',async()=>{
|
|
85
|
+
const notice={type:'system',subtype:'ui_invalidate',session_id:'fresh-review'};
|
|
86
|
+
for(const [wire,code] of [[[notice],'incomplete_result'],[[notice,{...messages[0],session_id:'other'}],'session_mismatch'],
|
|
87
|
+
[[notice,...messages.slice(1)],'missing_init']]){
|
|
88
|
+
const actual=await runMessages(wire);
|
|
89
|
+
assert.deepEqual(actual.result,{status:'failed',code});
|
|
90
|
+
assert(!actual.events.some(e=>e.event==='turn.completed'));
|
|
91
|
+
assert.equal(actual.events.at(-1).event,'process_closed');
|
|
92
|
+
}
|
|
93
|
+
});
|
|
78
94
|
test('worker accepts 88 and 4096 thinking heartbeats but rejects 4097 without completion',async()=>{
|
|
79
95
|
const baseline=await runMessages(messages);
|
|
80
96
|
for(const count of [88,4096,4097]){
|
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
const moduleUrl=process.env.CM_DRIVE_LIVENESS_MODULE??new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
|
|
8
|
+
function run(t,body,{answer='async()=>({ok:true})',liveness={}}={}){
|
|
9
|
+
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-liveness-'));
|
|
10
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
11
|
+
const host=path.join(dir,'host.mjs');
|
|
12
|
+
fs.writeFileSync(host,`import fs from 'node:fs';setTimeout(()=>process.exit(97),3500).unref();\nimport readline from 'node:readline';\nconst send=x=>process.stdout.write(JSON.stringify(x)+'\\n');\nconst ready=(heartbeat=false)=>send({type:'host_ready',sessionId:'fixture',...(heartbeat?{heartbeat:{intervalMs:20,timeoutMs:100}}:{})});\n${body}`);
|
|
13
|
+
const driver=path.join(dir,'driver.mjs');
|
|
14
|
+
fs.writeFileSync(driver,`import {driveHost} from ${JSON.stringify(moduleUrl)};\ndriveHost({host:${JSON.stringify(host)},args:[],cwd:${JSON.stringify(dir)},operation:'advance',answers:{},paths:{},answerFor:${answer},liveness:${JSON.stringify({startupMs:200,operationMs:700,heartbeatMs:100,graceMs:50,closeMs:150,killMs:100,pollMs:10,...liveness})}});`);
|
|
15
|
+
const started=Date.now();const result=spawnSync(process.execPath,[driver],{encoding:'utf8',timeout:4000,env:{...process.env,CM_WORKFLOW_HOME:path.join(dir,'home'),CM_WORKFLOW_LOG_HOME:path.join(dir,'logs'),CM_NOTIFY:'off'}});
|
|
16
|
+
return {...result,elapsedMs:Date.now()-started};
|
|
17
|
+
}
|
|
18
|
+
test('driver bounds a host that stays alive without ready',t=>{
|
|
19
|
+
const out=run(t,'setInterval(()=>{},1000);');assert.equal(out.status,70,out.stderr);assert.match(out.stderr,/host_start_timeout/);
|
|
20
|
+
});
|
|
21
|
+
test('driver detects host exit before result and does not invent success',t=>{
|
|
22
|
+
const out=run(t,'process.exit(7);');assert.equal(out.status,71,out.stderr);assert.match(out.stderr,/host_exited/);assert.equal(out.stdout,'');
|
|
23
|
+
});
|
|
24
|
+
test('advertised heartbeat loss expires independently of operation budget',t=>{
|
|
25
|
+
const out=run(t,'ready(true);setInterval(()=>{},1000);');assert.equal(out.status,72,out.stderr);assert.match(out.stderr,/host_heartbeat_timeout/);
|
|
26
|
+
});
|
|
27
|
+
test('heartbeats do not extend the deadline of a stuck bridge phase',t=>{
|
|
28
|
+
const out=run(t,`ready(true);const started=Date.now();setInterval(()=>send({type:'host_heartbeat',sessionId:'fixture',inFlight:{requestId:'drive',operation:'advance',stage:'review',call:{callId:'call',kind:'review',deadlineMs:started+150}}}),20);`);
|
|
29
|
+
assert.equal(out.status,73,out.stderr);assert.match(out.stderr,/host_stage_timeout/);
|
|
30
|
+
});
|
|
31
|
+
test('valid long bridge budget survives generic shorter operation budget',t=>{
|
|
32
|
+
const out=run(t,`ready(true);const started=Date.now();const timer=setInterval(()=>send({type:'host_heartbeat',sessionId:'fixture',inFlight:{requestId:'drive',operation:'advance',stage:'check',call:{callId:'call',kind:'check',deadlineMs:started+650}}}),20);setTimeout(()=>{clearInterval(timer);send({requestId:'drive',result:{state:'fixture_completed'}});},400);process.stdin.resume();process.stdin.on('end',()=>process.exit(0));`,{liveness:{operationMs:150}});
|
|
33
|
+
assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'fixture_completed');
|
|
34
|
+
});
|
|
35
|
+
test('host_busy waits for the named original result and never closes active work',t=>{
|
|
36
|
+
const out=run(t,`ready();readline.createInterface({input:process.stdin}).on('line',line=>{const row=JSON.parse(line);if(row.operation){send({requestId:'drive',error:{code:'host_busy',inFlight:{requestId:'original',operation:'advance',startedAt:new Date().toISOString(),stage:'review'}}});setTimeout(()=>send({requestId:'original',result:{state:'fixture_completed'}}),50);}else if(row.type==='host_close')process.exit(19);});process.stdin.on('end',()=>process.exit(0));`);
|
|
37
|
+
assert.equal(out.status,0,out.stderr);assert.match(out.stderr,/host_busy/);assert.equal(JSON.parse(out.stdout).requestId,'original');
|
|
38
|
+
});
|
|
39
|
+
test('legacy host with no heartbeat remains supported and bounded',t=>{
|
|
40
|
+
const good=run(t,`ready();process.stdin.once('data',()=>send({requestId:'drive',result:{state:'fixture_completed'}}));process.stdin.on('end',()=>process.exit(0));`);
|
|
41
|
+
assert.equal(good.status,0,good.stderr);
|
|
42
|
+
const stuck=run(t,`ready();process.stdin.resume();setInterval(()=>{},1000);`,{liveness:{operationMs:150}});
|
|
43
|
+
assert.equal(stuck.status,73,stuck.stderr);
|
|
44
|
+
});
|
|
45
|
+
test('unanswered request explicitly forces close instead of bypassing close protection with EOF',t=>{
|
|
46
|
+
const out=run(t,`ready(true);let acknowledged=false;readline.createInterface({input:process.stdin}).on('line',line=>{const row=JSON.parse(line);if(row.operation)send({type:'host_request',sessionId:'fixture',callId:'call',kind:'develop',requestDigest:'digest'});else if(row.type==='host_close'){if(row.force!==true)process.exit(19);setTimeout(()=>{acknowledged=true;send({type:'host_response',accepted:true,closing:true});},30);}});process.stdin.on('end',()=>process.exit(acknowledged?0:19));`,{answer:'async()=>null',liveness:{heartbeatMs:500}});
|
|
47
|
+
assert.equal(out.status,1,out.stderr);assert.match(out.stderr,/force.*unknown/);
|
|
48
|
+
});
|
|
49
|
+
test('driver handles absent pipe reader without uncaught EPIPE',t=>{
|
|
50
|
+
const out=run(t,`fs.closeSync(0);ready();setInterval(()=>{},1000);`);
|
|
51
|
+
assert.equal(out.status,74,out.stderr);assert.match(out.stderr,/host_pipe_closed/);assert.doesNotMatch(out.stderr,/Unhandled 'error'/);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('a final result cannot conceal a host that refuses to exit',t=>{
|
|
55
|
+
const out=run(t,`ready();process.stdin.once('data',()=>send({requestId:'drive',result:{state:'fixture_completed'}}));process.stdin.resume();setInterval(()=>{},1000);`);
|
|
56
|
+
assert.equal(out.status,75,out.stderr);assert.match(out.stderr,/host_close_timeout/);
|
|
57
|
+
});
|
|
58
|
+
test('watchdog terminates only its own spawned host group',t=>{
|
|
59
|
+
const unrelated=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});
|
|
60
|
+
t.after(()=>{if(unrelated.exitCode===null&&unrelated.signalCode===null)unrelated.kill('SIGKILL');});
|
|
61
|
+
const out=run(t,'process.on("SIGTERM",()=>{});setInterval(()=>{},1000);');
|
|
62
|
+
assert.equal(out.status,70,out.stderr);assert.equal(unrelated.exitCode,null);assert.doesNotThrow(()=>process.kill(unrelated.pid,0));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('native stage deadline wins over a longer live bridge deadline',t=>{
|
|
66
|
+
const out=run(t,`ready(true);const started=Date.now();setInterval(()=>send({type:'host_heartbeat',sessionId:'fixture',inFlight:{requestId:'drive',operation:'advance',nativeStage:{id:'native',kind:'check',deadlineMs:started+150},call:{callId:'call',kind:'develop',deadlineMs:started+1500}}}),20);`);
|
|
67
|
+
assert.equal(out.status,73,out.stderr);assert.match(out.stderr,/host_stage_timeout/);assert.ok(out.elapsedMs<1000,`native deadline lost: ${out.elapsedMs}ms`);
|
|
68
|
+
});
|
|
69
|
+
test('ending a nested call restores the original native deadline without extending it',t=>{
|
|
70
|
+
const out=run(t,`ready(true);const started=Date.now();setInterval(()=>{const age=Date.now()-started;send({type:'host_heartbeat',sessionId:'fixture',inFlight:{requestId:'drive',operation:'advance',nativeStage:{id:'outer',kind:'complete',deadlineMs:age<120?started+350:Date.now()+1500},call:age<120?{callId:'inner',kind:'check',deadlineMs:started+200}:null}});},20);`);
|
|
71
|
+
assert.equal(out.status,73,out.stderr);assert.match(out.stderr,/host_stage_timeout/);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
for(const mode of ['watchdog','unexpected-exit'])test(`owned same-group worker cannot outlive ${mode} host closure`,async t=>{
|
|
75
|
+
const body=`import {spawn} from 'node:child_process';
|
|
76
|
+
const worker=spawn(process.execPath,['-e', 'process.on("SIGTERM",()=>{});setTimeout(()=>process.exit(0),2500);setInterval(()=>{},20)'],{stdio:'ignore'});
|
|
77
|
+
console.log('worker:'+worker.pid);
|
|
78
|
+
${mode==='unexpected-exit'?'setTimeout(()=>process.exit(7),100);':'setInterval(()=>{},1000);'}`;
|
|
79
|
+
const out=run(t,body);assert.equal(out.status,mode==='watchdog'?70:71,out.stderr);
|
|
80
|
+
const pid=Number(out.stdout.trim().slice('worker:'.length));assert.ok(Number.isInteger(pid)&&pid>0);
|
|
81
|
+
await new Promise(resolve=>setTimeout(resolve,50));
|
|
82
|
+
assert.throws(()=>process.kill(pid,0),{code:'ESRCH'});
|
|
83
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {hostDiagnostic} from './fixtures/host-diagnostic.mjs';
|
|
1
2
|
import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
|
|
2
3
|
import test from 'node:test';
|
|
3
4
|
import assert from 'node:assert/strict';
|
|
@@ -59,16 +60,17 @@ function execute(f,{cancel=false,args=[]}={}){
|
|
|
59
60
|
const child=spawn(process.execPath,[cli,...f.args,...args],
|
|
60
61
|
{env:f.env,stdio:['pipe','pipe','pipe']});
|
|
61
62
|
let buffer='',stderr='',sessionId;const calls=[],rows=[];
|
|
62
|
-
const
|
|
63
|
-
child.
|
|
64
|
-
|
|
63
|
+
const timeoutMs=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000),trace=hostDiagnostic(child,{timeoutMs});
|
|
64
|
+
const timer=setTimeout(()=>{child.kill('SIGTERM');reject(trace.attach(Error('batch host timeout')));},timeoutMs);
|
|
65
|
+
child.stderr.on('data',part=>{stderr+=part;});child.once('error',error=>reject(trace.attach(error)));
|
|
66
|
+
const send=value=>{trace.send(value);child.stdin.write(JSON.stringify(value)+'\n');};
|
|
65
67
|
const respond=(row,result)=>send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
|
|
66
68
|
child.stdout.on('data',part=>{
|
|
67
69
|
buffer+=part;let newline;
|
|
68
70
|
while((newline=buffer.indexOf('\n'))!==-1){
|
|
69
71
|
const line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);if(!line)continue;
|
|
70
72
|
try{
|
|
71
|
-
const row=JSON.parse(line);rows.push(row);
|
|
73
|
+
const row=JSON.parse(line);rows.push(row);trace.receive(row);
|
|
72
74
|
if(row.type==='host_ready')sessionId=row.sessionId;
|
|
73
75
|
if(row.type==='host_request'){
|
|
74
76
|
const payload=row.payload,identity=payload.identity??payload.request.identity;
|
|
@@ -106,10 +108,10 @@ function execute(f,{cancel=false,args=[]}={}){
|
|
|
106
108
|
}else assert.fail(`Unexpected ${row.kind}`);
|
|
107
109
|
}
|
|
108
110
|
if(row.requestId==='advance'&&(row.result||row.error))send({type:'host_close',sessionId});
|
|
109
|
-
}catch(error){clearTimeout(timer);child.kill('SIGTERM');reject(error);}
|
|
111
|
+
}catch(error){clearTimeout(timer);child.kill('SIGTERM');reject(trace.attach(error));}
|
|
110
112
|
}
|
|
111
113
|
});
|
|
112
|
-
child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,result:rows.find(row=>row.requestId==='advance')?.result});});
|
|
114
|
+
child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,diagnostic:trace.snapshot(),result:rows.find(row=>row.requestId==='advance')?.result});});
|
|
113
115
|
send({operation:'advance',requestId:'advance'});
|
|
114
116
|
});
|
|
115
117
|
}
|