fix(dsh): address intervention cancellation and verification review
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
de9cb2908d
commit
775bc23dc3
26 files changed
+1280
-119
No files matched your search
@@ -0,0 +1,109 @@
|
||||
/** Exercise production diagnosis orchestration with controlled session boundaries. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import vm from 'node:vm';
|
||||
import path from 'node:path';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
|
||||
const deferred=()=>{let resolve;const promise=new Promise(yes=>{resolve=yes;});return {promise,resolve};};
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const events=[],handlers=new Map(),routes=new Map(),sessions=new Map(),prompts=[],cancelled=[];
|
||||
let nextCreate=null,nextPrompt=null,latestTimeout;
|
||||
const context={task_id:'',revision:'current'};
|
||||
const ctx={on:(name,fn)=>handlers.set(name,fn),effect:()=>{},
|
||||
connection:{admit:()=>({})},tools:{register:()=>{},guard:()=>{}},
|
||||
webServer:{register:route=>routes.set(route.path,route.handler)},
|
||||
workspaceRegistry:{create:async()=>({id:'workspace'})},
|
||||
sessionController:{
|
||||
create:async()=>{
|
||||
if(nextCreate){const wait=nextCreate;nextCreate=null;await wait.promise;}
|
||||
const sessionId=randomUUID();
|
||||
const idle=deferred(),rows=[];
|
||||
const pending=[];
|
||||
sessions.set(sessionId,{idle,rows,pending,wakeRequested:false,session:{snapshotEvents:()=>rows},whenIdle:()=>idle.promise,
|
||||
cancel:(_cause,options={})=>{
|
||||
cancelled.push(sessionId);
|
||||
if(!options.keepInbox){pending.length=0;sessions.get(sessionId).wakeRequested=false;}
|
||||
}});
|
||||
return {sessionId};
|
||||
},rename:async()=>{},cancel:async({sessionId})=>{sessions.get(sessionId).cancel({kind:'user'},{keepInbox:true});},
|
||||
commands:{prompt:async({sessionId})=>{
|
||||
if(nextPrompt){const wait=nextPrompt;nextPrompt=null;await wait.promise;}
|
||||
prompts.push(sessionId);
|
||||
sessions.get(sessionId).pending.push('diagnosis');
|
||||
sessions.get(sessionId).wakeRequested=true;
|
||||
}}
|
||||
},agents:{get:id=>sessions.get(id)}};
|
||||
let source=await readFile(new URL('../integration/dsh/task-plugin/host.mjs',import.meta.url),'utf8');
|
||||
source=source.replace(/^import .*;\r?\n/gm,'').replace(/export /g,'');
|
||||
const sandbox={path,randomUUID,createHash,setTimeout:(callback,ms)=>{latestTimeout=callback;return setTimeout(callback,ms);},clearTimeout,console,
|
||||
readFile:async()=>JSON.stringify(context),appendFile:async()=>{},defineTool:value=>value,
|
||||
registerRuntimeUsage:async()=>({dispose:()=>{},snapshot:()=>({settings:{response_timeout_seconds:90}})}),
|
||||
registerLifecycle:()=>{},lifecycleNames:[],registerFileTools:()=>{},fileToolNames:[],modelSnapshot:value=>value,
|
||||
process:{env:{DX_DSH_HOME:'controlled',DX_DSH_WORKSPACE:'controlled'},stdout:{write:line=>{
|
||||
if(line.startsWith('DX_DSH_DIAGNOSIS '))events.push(JSON.parse(line.slice('DX_DSH_DIAGNOSIS '.length)));
|
||||
}}}};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(source+'\nglobalThis.applyPlugin=apply;',sandbox);
|
||||
await sandbox.applyPlugin(ctx);
|
||||
const start=id=>handlers.get('dx/diagnose-request')({request_id:id,incident_id:createHash('sha256').update(id).digest('hex').slice(0,24),
|
||||
phase:'diagnose',snapshot:{task_id:''},evidence:'controlled fixture'});
|
||||
const waitFor=async predicate=>{for(let i=0;i<100&&!predicate();i++)await tick();assert.ok(predicate(),'expected lifecycle event');};
|
||||
const terminal=id=>events.find(event=>event.request_id===id&&['completed','cancelled','failed'].includes(event.status));
|
||||
|
||||
start('cancel-active');start('keep-active');
|
||||
await waitFor(()=>prompts.length===2);
|
||||
const first=events.find(event=>event.request_id==='cancel-active'&&event.status==='started').session_id;
|
||||
const other=events.find(event=>event.request_id==='keep-active'&&event.status==='started').session_id;
|
||||
handlers.get('dx/diagnose-cancel')({request_id:'unknown'});
|
||||
assert.deepEqual(cancelled,[]);
|
||||
handlers.get('dx/diagnose-cancel')({request_id:'cancel-active'});
|
||||
await waitFor(()=>terminal('cancel-active'));
|
||||
assert.equal(terminal('cancel-active').status,'cancelled');
|
||||
assert.deepEqual(cancelled,[first]);
|
||||
assert.equal(terminal('keep-active'),undefined);
|
||||
sessions.get(other).rows.push({type:'assistant/message',data:{message:{content:[{type:'text',text:'{"action":"none"}'}]}}});
|
||||
sessions.get(other).idle.resolve();
|
||||
await waitFor(()=>terminal('keep-active'));
|
||||
assert.equal(terminal('keep-active').status,'completed');
|
||||
|
||||
nextCreate=deferred();const creating=nextCreate;
|
||||
start('cancel-creating');
|
||||
handlers.get('dx/diagnose-cancel')({request_id:'cancel-creating'});
|
||||
creating.resolve();
|
||||
await waitFor(()=>terminal('cancel-creating'));
|
||||
assert.equal(terminal('cancel-creating').status,'cancelled');
|
||||
assert.equal(prompts.length,2,'cancel during session creation must never enqueue a prompt');
|
||||
|
||||
nextPrompt=deferred();const admitting=nextPrompt;
|
||||
start('cancel-admitting');
|
||||
await waitFor(()=>events.some(event=>event.request_id==='cancel-admitting'&&event.status==='started'));
|
||||
const admittingSession=events.find(event=>event.request_id==='cancel-admitting'&&event.status==='started').session_id;
|
||||
handlers.get('dx/diagnose-cancel')({request_id:'cancel-admitting'});
|
||||
await waitFor(()=>terminal('cancel-admitting'));
|
||||
assert.equal(terminal('cancel-admitting').status,'cancelled');
|
||||
admitting.resolve();
|
||||
await waitFor(()=>cancelled.filter(id=>id===admittingSession).length===2);
|
||||
assert.ok(prompts.includes(admittingSession),'fixture admitted the delayed prompt');
|
||||
assert.equal(sessions.get(admittingSession).pending.length,0,'cancel must clear the late automatic inbox');
|
||||
assert.equal(sessions.get(admittingSession).wakeRequested,false,'cancelled diagnosis must not wake another turn');
|
||||
|
||||
nextPrompt=deferred();const timingOut=nextPrompt;
|
||||
start('timeout-admitting');
|
||||
await waitFor(()=>events.some(event=>event.request_id==='timeout-admitting'&&event.status==='started'));
|
||||
const timeoutSession=events.find(event=>event.request_id==='timeout-admitting'&&event.status==='started').session_id;
|
||||
latestTimeout();
|
||||
await waitFor(()=>terminal('timeout-admitting'));
|
||||
assert.equal(terminal('timeout-admitting').error,'diagnosis_timeout');
|
||||
timingOut.resolve();
|
||||
await waitFor(()=>cancelled.filter(id=>id===timeoutSession).length===2);
|
||||
assert.equal(sessions.get(timeoutSession).pending.length,0,'timeout must clear the late automatic inbox');
|
||||
|
||||
async function action(revision){
|
||||
const req={method:'POST',async *[Symbol.asyncIterator](){yield JSON.stringify({action:'cancel_diagnosis',task_id:'',revision});}};
|
||||
const res={status:200,writeHead(code){this.status=code;},end(){},setHeader(){}};
|
||||
await routes.get('/dx/action')(req,res);return res.status;
|
||||
}
|
||||
assert.equal(await action('stale'),409);
|
||||
assert.equal(await action('current'),200,'taskless incidents must remain cancellable');
|
||||
console.log('PASS native diagnosis cancellation, session isolation, creation race and action revision checks');
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Render the registered native incident panel and exercise its cancel action offline. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import vm from 'node:vm';
|
||||
|
||||
let plugin,TaskPanel,data,stateIndex;
|
||||
const requests=[];
|
||||
const React={
|
||||
createElement:(type,props,...children)=>({type,props:props||{},children}),
|
||||
useState:()=>[[data,'','overview',false,null][stateIndex++],()=>{}],
|
||||
useEffect:()=>{}
|
||||
};
|
||||
const sandbox={window:{__ModuleLoader__:{load:value=>{plugin=value;}}},
|
||||
fetch:async(url,options)=>{
|
||||
if(url==='/dx/context')return {ok:true,json:async()=>({...data,revision:'fresh-revision'})};
|
||||
requests.push({url,body:JSON.parse(options.body)});
|
||||
return {ok:true,status:200};
|
||||
}};
|
||||
vm.runInNewContext(await readFile(new URL('../integration/dsh/task-plugin/client.js',import.meta.url),'utf8'),sandbox);
|
||||
const exported=plugin.factory(name=>name==='react'?React:{});
|
||||
exported.apply({effect:()=>{},slots:{inject:(_name,callback)=>callback(),register:(slot,component)=>{
|
||||
if(slot.name==='sidebar.right.pane.tab')TaskPanel=component;
|
||||
}},sidebarRightTabs:{register:()=>{}},sidebarRight:{mounted:{}}});
|
||||
|
||||
function expand(node){
|
||||
if(Array.isArray(node))return node.flatMap(part=>expand(part));
|
||||
if(node===null||node===undefined||typeof node==='boolean')return [];
|
||||
if(typeof node!=='object')return [String(node)];
|
||||
if(typeof node.type==='function')return expand(node.type({...node.props,children:node.children}));
|
||||
return [{...node,children:node.children.flatMap(part=>expand(part))}];
|
||||
}
|
||||
const nodes=tree=>tree.flatMap(node=>typeof node==='object'?[node,...nodes(node.children)]:[]);
|
||||
const text=tree=>tree.map(node=>typeof node==='object'?text(node.children):node).join('');
|
||||
function render(automation){
|
||||
data={task_id:'selected-task',revision:'current-revision',progress:{},rules_count:0,
|
||||
automation:{incident_id:'incident',task_id:'',...automation}};
|
||||
stateIndex=0;
|
||||
return expand(TaskPanel());
|
||||
}
|
||||
const element=(tree,id)=>nodes(tree).find(node=>node.props['data-testid']===id);
|
||||
|
||||
let tree=render({status:'resolved',cleanup_attempts:1,verification:{resources_released:true,remaining_resources:[]}});
|
||||
assert.match(text([element(tree,'dx-auto-cleanup-attempts')]),/1/);
|
||||
assert.match(text([element(tree,'dx-auto-verification')]),/资源释放已独立核验通过/);
|
||||
assert.match(text([element(tree,'dx-auto-verification')]),/不代表 CAD 任务成功/);
|
||||
tree=render({status:'pending_issue',cleanup_attempts:1,verification:{resources_released:false,remaining_resources:[{}]}});
|
||||
assert.match(text([element(tree,'dx-auto-verification')]),/剩余 1 项资源/);
|
||||
tree=render({status:'pending_issue',cleanup_attempts:0,verification:{resources_released:false,remaining_resources:null}});
|
||||
assert.match(text([element(tree,'dx-auto-verification')]),/剩余资源数量未知/);
|
||||
tree=render({status:'pending_issue',cleanup_attempts:1,verification:{resources_released:false,remaining_resources:[{}, {__truncated__:true}]}});
|
||||
assert.match(text([element(tree,'dx-auto-verification')]),/至少 1 项资源/);
|
||||
tree=render({status:'observed_cleared',cleanup_attempts:0,verification:{resources_released:true,remaining_resources:[]}});
|
||||
assert.equal(text([element(tree,'dx-auto-status')]),'阻塞已自行解除,未执行清理');
|
||||
assert.ok(!text(tree).includes('正在保留现场'),'a cleared incident must not still claim diagnosis is running');
|
||||
assert.equal(element(tree,'dx-auto-cancel'),undefined);
|
||||
tree=render({status:'cancelled',cleanup_attempts:0,can_cancel:false});
|
||||
assert.equal(text([element(tree,'dx-auto-status')]),'诊断已取消,证据已保留');
|
||||
assert.ok(!text(tree).includes('正在保留现场'),'a cancelled incident must not still claim diagnosis is running');
|
||||
assert.equal(element(tree,'dx-auto-cancel'),undefined);
|
||||
tree=render({status:'analyzing',task_id:'other-incident-task',can_cancel:true});
|
||||
const cancel=element(tree,'dx-auto-cancel');
|
||||
assert.ok(cancel,'an active diagnosis can be cancelled after selecting another task');
|
||||
assert.equal(text([cancel]),'取消 AI 诊断');
|
||||
await cancel.props.onClick();
|
||||
assert.equal(requests.length,1);
|
||||
assert.deepEqual(requests[0],{url:'/dx/action',body:{action:'cancel_diagnosis',task_id:'selected-task',revision:'fresh-revision'}});
|
||||
console.log(JSON.stringify({status:'passed',cleanupEvidenceVisible:true,terminalStatusesAccurate:true,cancelActionRouted:true}));
|
||||
@@ -15,6 +15,11 @@ const snapshot=modelSnapshot({task_id:'owner',revision:'revision',status:'runnin
|
||||
assert.equal(snapshot.operations.runs.length,5);
|
||||
assert.equal(snapshot.operations.live_run.active,true);
|
||||
assert.equal(snapshot.task_id,'owner');
|
||||
const automation=modelSnapshot({task_id:'owner',automation:{incident_id:'i',status:'observed_cleared',cleanup_attempts:0,
|
||||
can_cancel:false,verification:{resources_released:true,remaining_resources:[]}}}).automation;
|
||||
assert.equal(automation.can_cancel,false);
|
||||
assert.equal(automation.cleanup_attempts,0);
|
||||
assert.equal(automation.verification.resources_released,true);
|
||||
assert.equal(JSON.stringify(snapshot),JSON.stringify(JSON.parse(JSON.stringify(snapshot))));
|
||||
assert.ok(Object.values(modelSnapshot({task_id:'empty',revision:'r'}).operations).every(v=>v!==undefined));
|
||||
assert.ok(JSON.stringify(snapshot).length<12000);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Verify cancellation through the real native Harness stdin/stdout protocol."""
|
||||
import json
|
||||
from time import monotonic
|
||||
from uuid import uuid4
|
||||
|
||||
from verify_dsh_blocker_recovery import NativeDiagnosis, REPO
|
||||
|
||||
|
||||
def main():
|
||||
root = REPO / 'build' / ('dsh-native-cancel-' + uuid4().hex[:8])
|
||||
native = NativeDiagnosis(root)
|
||||
report = {'status': 'failed', 'driver': 'real native Harness', 'remoteIssueWrites': 0}
|
||||
try:
|
||||
assert native.events.get(timeout=180)['status'] == 'ready', 'native_runtime_not_ready'
|
||||
request_id = uuid4().hex
|
||||
request = {'type': 'diagnose', 'request_id': request_id, 'incident_id': uuid4().hex[:24],
|
||||
'phase': 'diagnose', 'snapshot': {'task_id': '', 'issue_code': 'operation_stalled'},
|
||||
'evidence': 'Controlled cancellation acceptance; no engineering mutation is permitted.'}
|
||||
native.process.stdin.write(json.dumps(request) + '\n')
|
||||
native.process.stdin.flush()
|
||||
started = native.events.get(timeout=90)
|
||||
assert started.get('request_id') == request_id and started['status'] == 'started'
|
||||
before = monotonic()
|
||||
native.process.stdin.write(json.dumps({'type': 'diagnose_cancel', 'request_id': request_id}) + '\n')
|
||||
native.process.stdin.flush()
|
||||
terminal = native.events.get(timeout=15)
|
||||
assert terminal.get('request_id') == request_id and terminal['status'] == 'cancelled'
|
||||
assert terminal['error'] == 'diagnosis_cancelled'
|
||||
report.update(status='passed', cancellation_seconds=round(monotonic() - before, 3),
|
||||
terminal_status=terminal['status'], session_created=bool(started.get('session_id')))
|
||||
except Exception as error:
|
||||
report['error_type'] = type(error).__name__
|
||||
raise
|
||||
finally:
|
||||
native.close()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf8')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user