bada-terminal / test /wrapper /batch-loop-reconciliation.test.cjs
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
17.1 kB
// 예전 분리 저장의 절반 마감을 실제 배치/child/usage/관측으로 재현한다.
// 설명 문서: docs/specs/batch-loop-reconciliation.md v1.0.0
const{test,after}=require('node:test'),assert=require('node:assert/strict'),fs=require('fs'),os=require('os'),path=require('path'),{randomUUID}=require('crypto');
const home=fs.mkdtempSync(path.resolve('scratch/batch-loop-reconcile-')),oldHome=os.homedir;os.homedir=()=>home;
require('../../src/context').currentCwd=home;require('../../src/services/governance-client').cachedPolicy={enabled:false};require('../../src/skills-manager').generateClaudeRules=async()=>{};require('../../src/config-manager').getKnowledgeConfig=()=>({devPreferenceAutoLearn:false,codeIntelEnabled:false,troubleshootAutoCapture:false});
const archive=require('../../src/wiki-run-archiver');archive.archiveWorkflowRun=async()=>{};archive.archiveBatchRun=async()=>({success:true});
const db=require('../../knowledge-db'),engine=require('../../src/workflow-manager'),batch=require('../../src/batch-manager'),execute=engine.executeNode;
after(async()=>{await engine.cleanupAll();await batch.cleanupAllActiveRuns();engine.executeNode=execute;os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));});
async function fixture({mode='iteration',terminal=true,modern=false,targetIteration=1}={}){
const project=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'original child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},task={id:randomUUID(),project_id:project,is_active:0,name:'legacy partial close',steps:[{id:'child',type:'workflow',config:{workflowId:workflow.id,timeoutMs:3000}}],loop_config:JSON.stringify({goals:[{type:'file_exists',target:'READY'}],max_iterations:3,token_budget:1})};
if(terminal&&targetIteration===1)fs.writeFileSync(path.join(project,'READY'),'ready');db.saveWorkflow(project,workflow);db.saveBatchTask(project,task);
let executed=0;engine.executeNode=async run=>{if(terminal&&++executed===targetIteration)fs.writeFileSync(path.join(project,'READY'),'ready');require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.02,1,{id:'paid',costSource:'provider_reported',totalTokens:2});return{original:true};};
const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(!modern&&c.revision===0){c=structuredClone(c);delete c.publicationVersion;}if(Object.values(c.loopEvents||{}).at(-1)?.phase==='committed'&&Object.values(c.loopEvents).at(-1).iteration===targetIteration)throw Error('legacy split publication failure');return save(c,...args);};
try{assert.equal((await batch.runTask(task)).success,false);}finally{db.saveBatchCheckpoint=save;}
const row=db.getBatchRuns(task.id)[0],c=db.getBatchCheckpoint(row.run_id),events=Object.values(c.loopEvents),event=events.at(-1),first=events.find(e=>e.iteration===targetIteration&&e.phase==='steps'),actual=db.getLoopIterations('looprun-'+row.run_id).at(-1),outputs=Object.fromEntries(Object.values(c.entries).filter(e=>e.iteration===targetIteration).map(e=>[e.stepId,e.output]));assert.equal(event.phase,'settled');
const closedIteration={...first.ledgerIteration,status:terminal?'success':'failed',step_outputs:outputs,goal_evaluation_result:terminal?1:0,cost:.02,tokens_used:2,error_message:null,completed_at:actual.completed_at},closedRun={...first.ledgerRun,total_iterations:targetIteration,total_cost:.02*targetIteration,total_tokens_used:2*targetIteration,...(terminal?{status:'completed',goal_met:1,break_reason:null,receipt_summary:event.result.receiptSummary||null,completed_at:actual.completed_at}:{})};
if(mode==='iteration'||mode==='both')db.saveLoopIteration(closedIteration);if(mode==='run'||mode==='both')db.saveLoopRun(closedRun);
return{project,workflow,task,row,event,first,closedIteration,closedRun};
}
function service(f,approve=async()=>({approved:true})){const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.project),authorize:()=>true,approve});return{owner,api};}
const snapshot=f=>JSON.stringify([db.getBatchRun(f.row.run_id),db.getBatchCheckpoint(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id),db.getLoopIterations('looprun-'+f.row.run_id),db.getRuntimeUsage(f.row.run_id)]);
for(const mode of ['iteration','run','both'])test('approved '+mode+' ahead of settled checkpoint closes the same terminal loop without replay',async()=>{
const f=await fixture({mode}),before=snapshot(f),originalRows={run:db.getLoopRun('looprun-'+f.row.run_id),iterations:db.getLoopIterations('looprun-'+f.row.run_id)},usage=db.getRuntimeUsage(f.row.run_id),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledLoopRows,true);assert.equal(snapshot(f),before);
const prepared=await api.commit(p.ticketId,{owner,confirmed:true});assert.deepEqual(db.getLoopRun('looprun-'+f.row.run_id),originalRows.run);const grant=Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0];assert.deepEqual(grant.loopState.originalIterations,originalRows.iterations);assert.deepEqual(grant.loopState.originalRun,originalRows.run);
engine.executeNode=async()=>{throw Error('original child replayed');};const Controller=require('../../src/loop-controller').LoopController,evaluate=Controller.prototype.evaluateTermination;Controller.prototype.evaluateTermination=async()=>{throw Error('original goal replayed');};fs.unlinkSync(path.join(f.project,'READY'));
try{const result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);}finally{Controller.prototype.evaluateTermination=evaluate;}
assert.equal(db.getBatchRun(f.row.run_id).status,'success');assert.equal(db.getLoopRun('looprun-'+f.row.run_id).status,'completed');assert.equal(db.getLoopRun('looprun-'+f.row.run_id).started_at,originalRows.run.started_at);assert.equal(db.getLoopIterations('looprun-'+f.row.run_id).length,1);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);assert.deepEqual(db.getRuntimeUsage(f.row.run_id),usage);assert.deepEqual(db.getBatchCheckpoint(f.row.run_id).loopEvents[f.event.key],f.event);
});
test('a nonterminal half closure consumes the saved settlement and executes only the intentional next iteration',async()=>{
const f=await fixture({terminal:false}),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledLoopRows,true);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});let calls=0;engine.executeNode=async()=>{calls++;fs.writeFileSync(path.join(f.project,'READY'),'ready');return{next:true};};const result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(calls,1);assert.equal(db.getLoopIterations('looprun-'+f.row.run_id).length,2);assert.equal(db.getLoopRun('looprun-'+f.row.run_id).total_cost,.02);assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);
});
for(const baseline of ['run','iteration'])test('partial closure preserves the original '+baseline+' baseline until approved handoff',async()=>{
const f=await fixture({mode:baseline==='run'?'iteration':'run'});if(baseline==='run')db.saveLoopRun(f.first.ledgerRun,{replaceReceipt:true});else db.saveLoopIteration(f.first.ledgerIteration);
const before=snapshot(f),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledLoopRows,true);assert.equal(snapshot(f),before);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});engine.executeNode=async()=>{throw Error('baseline child replayed');};const result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(db.getLoopRun('looprun-'+f.row.run_id).total_cost,.02);
});
for(const mutation of ['cost','tokens','outputs','close-time','run-close-time','ghost'])test('partial closure refuses '+mutation+' without changing the original source',async()=>{
const f=await fixture(),id='looprun-'+f.row.run_id,row=db.getLoopIterations(id)[0];
if(mutation==='cost')db.saveLoopIteration({...row,cost:99});if(mutation==='tokens')db.saveLoopRun({...db.getLoopRun(id),total_tokens_used:99});if(mutation==='outputs')db.saveLoopIteration({...row,step_outputs:{invented:true}});if(mutation==='close-time')db.saveLoopIteration({...row,completed_at:'2000-01-01T00:00:00Z'});if(mutation==='run-close-time')db.saveLoopRun({...db.getLoopRun(id),completed_at:'2000-01-01T00:00:00Z'});if(mutation==='ghost')db.saveLoopIteration({...f.first.ledgerIteration,id:'iter-'+id+'-2',iteration_number:2});
const before=snapshot(f),{api,owner}=service(f);assert.throws(()=>api.preview(f.row.run_id,{owner}));assert.equal(snapshot(f),before);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('missing independent observations refuse a checksum-consistent settled phase',async()=>{
const f=await fixture(),get=db.getBatchLoopObservations,{api,owner}=service(f),before=snapshot(f);db.getBatchLoopObservations=(id,...args)=>id===f.row.run_id?null:get(id,...args);try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{db.getBatchLoopObservations=get;}assert.equal(snapshot(f),before);
});
test('a contradictory modern stopped outbox is not bypassed by partial-row reconciliation',async()=>{
const f=await fixture({modern:true}),before=snapshot(f),{api,owner}=service(f);assert.throws(()=>api.preview(f.row.run_id,{owner}));assert.equal(snapshot(f),before);
});
test('cancelled approval and source changes during approval publish no recovery grant',async()=>{
const f=await fixture(),before=snapshot(f),cancel=service(f,async()=>({approved:false})),p=cancel.api.preview(f.row.run_id,{owner:cancel.owner});await assert.rejects(cancel.api.commit(p.ticketId,{owner:cancel.owner,confirmed:true}));assert.equal(snapshot(f),before);
const changed=service(f,async()=>{db.saveLoopRun({...db.getLoopRun('looprun-'+f.row.run_id),total_cost:7});return{approved:true};}),next=changed.api.preview(f.row.run_id,{owner:changed.owner});await assert.rejects(changed.api.commit(next.ticketId,{owner:changed.owner,confirmed:true}));assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);assert.equal(db.getBatchRun(f.row.run_id).status,'failed');
});
test('handoff disk failure rolls back repaired rows and keeps the prepared grant retryable without effects',async()=>{
const f=await fixture({mode:'both'}),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner}),prepared=await api.commit(p.ticketId,{owner,confirmed:true}),before=snapshot(f),save=db.saveLoopIteration;let effects=0;engine.executeNode=async()=>{effects++;throw Error('replay');};db.saveLoopIteration=()=>{throw Error('controlled handoff failure');};try{assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint})).success,false);}finally{db.saveLoopIteration=save;}assert.equal(snapshot(f),before);assert.equal(effects,0);assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint})).success,true);assert.equal(effects,0);
});
test('only an explicit receipt replacement clears a superseded loop summary',async()=>{
const f=await fixture(),id='looprun-'+f.row.run_id,r=db.getLoopRun(id);db.saveLoopRun({...r,receipt_summary:'old closure receipt'});db.saveLoopRun({...r,receipt_summary:null});assert.equal(db.getLoopRun(id).receipt_summary,'old closure receipt');db.saveLoopRun({...r,receipt_summary:null},{replaceReceipt:true});assert.equal(db.getLoopRun(id).receipt_summary,null);
});
test('a fresh process consumes the approved half closure with the same original run and zero child replay',async()=>{
const f=await fixture({mode:'run'}),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner}),prepared=await api.commit(p.ticketId,{owner,confirmed:true}),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock');owners.claimReview(f.task.id,locks.readLock(owners.file(f.task.id)),f.row.run_id).release();fs.unlinkSync(path.join(f.project,'READY'));
const code="require('os').homedir=()=>process.argv[1];require('./src/context').currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const e=require('./src/workflow-manager');e.executeNode=async()=>{throw Error('fresh child replay')};const b=require('./src/batch-manager');b.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log('RESULT:'+JSON.stringify({success:r.success,error:r.error}));await e.cleanupAll();await b.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});";
const result=require('child_process').spawnSync(process.execPath,['-e',code,home,f.project,f.row.run_id,prepared.fingerprint],{encoding:'utf8',timeout:15000});assert.equal(result.status,0,result.stdout+result.stderr);db.reloadJson();assert.equal(db.getBatchRun(f.row.run_id).status,'success');assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);assert.equal(db.getLoopRun('looprun-'+f.row.run_id).started_at,f.first.ledgerRun.started_at);assert.equal(db.getLoopRun('looprun-'+f.row.run_id).total_cost,.02);
});
test('owned scheduler shows reconciliation before native approval and preserves the same paused review',async()=>{
const f=await fixture(),handlers=new Map(),sender={isDestroyed:()=>false,mainFrame:{url:require('url').pathToFileURL(path.resolve('batch-scheduler.html')).href}},event={sender,senderFrame:sender.mainFrame},before=snapshot(f);let approvals=0,allow=false;const runtime={BrowserWindow:{fromWebContents:s=>s===sender?{}:null},dialog:{showMessageBox:async(_w,options)=>{approvals++;assert.equal(options.defaultId,0);assert.equal(options.cancelId,0);assert.match(options.detail,/독립 관측과 대사한 부분 마감 행/);assert.match(options.detail,/원래 행은 승인 기록에 보존/);return{response:allow?1:0};}}};require('../../src/ipc/batch-continuation-ipc').register({handle:(name,fn)=>handlers.set(name,fn)},{currentCwd:f.project},runtime);const invoke=input=>handlers.get('batch:continue-run')(event,f.row.run_id,input),review=await invoke({action:'review'});assert.equal(review.success,true);assert.equal(review.review.reconciledLoopRows,true);assert.equal(approvals,0);assert.equal((await invoke({action:'accept',fingerprint:review.review.fingerprint})).success,false);assert.equal(snapshot(f),before);allow=true;assert.equal((await invoke({action:'accept',fingerprint:review.review.fingerprint})).success,true);const paused=await invoke({action:'review'});assert.equal(paused.review.reconciledLoopRows,true);assert.equal(paused.review.status,'paused');assert.equal(paused.review.canResume,true);assert.equal(approvals,2);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);event.senderFrame={};assert.equal((await invoke({action:'review'})).success,false);
});
test('a later half closure independently reconciles the original committed prefix and preserves prior rows',async()=>{
const f=await fixture({targetIteration:2}),id='looprun-'+f.row.run_id,rows=db.getLoopIterations(id),usage=db.getRuntimeUsage(f.row.run_id),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.iteration,2);assert.equal(p.reconciledLoopRows,true);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});engine.executeNode=async()=>{throw Error('prior iteration replay');};const result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.deepEqual(db.getLoopIterations(id)[0],rows[0]);assert.equal(db.getLoopIterations(id).length,2);assert.equal(db.getLoopRun(id).total_cost,.04);assert.deepEqual(db.getRuntimeUsage(f.row.run_id),usage);assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);
});
test('missing earlier independent evidence refuses a later half closure despite a valid latest observation',async()=>{
const f=await fixture({targetIteration:2}),get=db.getBatchLoopObservations,c=db.getBatchCheckpoint(f.row.run_id),keys=new Set(Object.values(c.loopEvents).filter(e=>e.iteration===1).map(e=>e.key)),{api,owner}=service(f),before=snapshot(f);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&keys.has(key)?null:get(id,key);try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{db.getBatchLoopObservations=get;}assert.equal(snapshot(f),before);
});
test('rehashing a forged settled controller does not replace independent transition evidence',async()=>{
const f=await fixture(),get=db.getBatchCheckpoint,{hash}=require('../../src/services/bong-browser-resolution'),{api,owner}=service(f),before=snapshot(f);db.getBatchCheckpoint=id=>{const c=get(id);if(id!==f.row.run_id)return c;const value=structuredClone(c),event=value.loopEvents[f.event.key];event.controller.metricHistory={invented:[9]};const{eventHash:_,...body}=event;event.eventHash=hash(body);return value;};try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{db.getBatchCheckpoint=get;}assert.equal(snapshot(f),before);
});