File size: 18,632 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // ์์ beginโcheckpoint ๋ถ๋ฆฌ ์ ์ฅ์ ์ค์ ๋ฐฐ์น ์คํ์ผ๋ก ์ฌํํ๋ค. ์ง์ ์ถ๋ ฅ carry-over๋ฅผ ์ ์์
์๋ฃ๋ก ๋ณด์ง ์๋๋ค.
// ์ค๋ช
๋ฌธ์: docs/specs/batch-loop-ghost.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-ghost-')),oldHome=os.homedir;os.homedir=()=>home;require('../../src/context').currentCwd=home;require('../../src/services/governance-client').cachedPolicy={enabled:false};require('../../src/config-manager').getKnowledgeConfig=()=>({devPreferenceAutoLearn:false,codeIntelEnabled:false,troubleshootAutoCapture:false});require('../../src/skills-manager').generateClaudeRules=async()=>{};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({legacy=false,empty=false,ghostNumber=2}={}){
const project=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'paid original child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},task={id:randomUUID(),project_id:project,is_active:0,name:'unstarted iteration',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})};db.saveWorkflow(project,workflow);db.saveBatchTask(project,task);let effects=0;engine.executeNode=async run=>{effects++;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 Ledger=require('../../src/services/batch-loop-ledger').BatchLoopLedger,begin=Ledger.prototype.beginIteration,save=db.saveBatchCheckpoint;Ledger.prototype.beginIteration=function(n,commit){if(n!==ghostNumber)return begin.call(this,n,commit);begin.call(this,n);commit?.();};db.saveBatchCheckpoint=(c,...args)=>{if(legacy&&c.revision===0){c=structuredClone(c);delete c.publicationVersion;}const e=Object.values(c.loopEvents||{}).at(-1);if(e?.phase==='steps'&&e.iteration===ghostNumber)throw Error('legacy next steps publication failure');return save(c,...args);};
try{assert.equal((await batch.runTask(task)).success,false);}finally{Ledger.prototype.beginIteration=begin;db.saveBatchCheckpoint=save;}
const row=db.getBatchRuns(task.id)[0],c=db.getBatchCheckpoint(row.run_id),event=Object.values(c.loopEvents).at(-1),id='looprun-'+row.run_id,ghost=db.getLoopIterations(id).at(-1);assert.equal(event.phase,'committed');assert.equal(event.result.shouldTerminate,false);assert.equal(effects,ghostNumber-1);assert.equal(ghost.iteration_number,ghostNumber);assert.equal(ghost.cost,0);assert.equal(ghost.tokens_used,0);if(empty)db.saveLoopIteration({...ghost,step_outputs:{}});
return{project,workflow,task,row,c,event,id,ghost:db.getLoopIterations(id).at(-1)};
}
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{api,owner};}
const snapshot=f=>JSON.stringify([db.getBatchRun(f.row.run_id),db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun(f.id),db.getLoopIterations(f.id)]);
for(const legacy of [false,true])test('owner-reviewed '+(legacy?'legacy':'modern')+' ghost is archived before only the intentional next iteration runs',async()=>{
const f=await fixture({legacy}),before=snapshot(f),rows=db.getLoopIterations(f.id),usage=db.getRuntimeUsage(f.row.run_id),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledGhostIteration,true);assert.equal(p.ghostIteration,2);assert.equal(p.iteration,1);assert.equal(snapshot(f),before);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});assert.deepEqual(db.getLoopIterations(f.id),rows);const grant=Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0];assert.deepEqual(grant.loopState.originalIterations,rows);
let effects=0;engine.executeNode=async()=>{effects++;fs.writeFileSync(path.join(f.project,'READY'),'ready');return{newWork:true};};const result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(effects,1);assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);assert.equal(db.getLoopIterations(f.id).length,2);assert.deepEqual(db.getLoopIterations(f.id)[0],rows[0]);assert.equal(db.getLoopRun(f.id).started_at,f.event.ledgerRun.started_at);assert.equal(db.getLoopRun(f.id).total_cost,.02);assert.deepEqual(db.getRuntimeUsage(f.row.run_id).usage,usage.usage);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0].loopState.originalIterations[1],f.ghost);assert.deepEqual(db.getBatchCheckpoint(f.row.run_id).loopEvents[f.event.key],f.event);
});
test('empty unstarted row is reconciled read-only without preparing or invoking another child',async()=>{
const f=await fixture({legacy:true,empty:true}),before=snapshot(f),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledGhostIteration,true);assert.equal(snapshot(f),before);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
for(const mutation of ['cost','tokens','goal','output','success','worktree','extra-row','message'])test('ghost '+mutation+' evidence blocks archival before approval or effects',async()=>{
const f=await fixture({legacy:true}),g=f.ghost;if(mutation==='cost')db.saveLoopIteration({...g,cost:1});if(mutation==='tokens')db.saveLoopIteration({...g,tokens_used:1});if(mutation==='goal')db.saveLoopIteration({...g,goal_evaluation_result:1});if(mutation==='output')db.saveLoopIteration({...g,step_outputs:{unknownEffect:true}});if(mutation==='success')db.saveLoopIteration({...g,status:'success'});if(mutation==='worktree')db.saveLoopIteration({...g,worktree_branch:'another-owned-worktree'});if(mutation==='extra-row')db.saveLoopIteration({...g,id:'iter-'+f.id+'-3',iteration_number:3});if(mutation==='message')db.saveLoopMessage({loop_run_id:f.id,iteration_number:2,sender_agent_id:'fixture',receiver_agent_id:'fixture',message_type:'status',content:'work started'});const before=snapshot(f);let approvals=0;const{api,owner}=service(f,async()=>{approvals++;return{approved:true};});assert.throws(()=>api.preview(f.row.run_id,{owner}));assert.equal(snapshot(f),before);assert.equal(approvals,0);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
for(const mutation of ['started-before-commit','closed-after-batch','unknown-field'])test('ghost shape/timestamp '+mutation+' cannot be certified from its zero cost',async()=>{
const f=await fixture({legacy:true}),get=db.getLoopIterations,{api,owner}=service(f),before=snapshot(f);db.getLoopIterations=id=>{const rows=structuredClone(get(id));if(id===f.id){const g=rows.at(-1);if(mutation==='started-before-commit')g.started_at='2000-01-01T00:00:00Z';if(mutation==='closed-after-batch')g.completed_at='2099-01-01T00:00:00Z';if(mutation==='unknown-field')g.extra='unverified';}return rows;};try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{db.getLoopIterations=get;}assert.equal(snapshot(f),before);
});
test('a safe-looking browser journal outside completed descendants prevents ghost archival',async()=>{
const f=await fixture({legacy:true}),lifecycle=require('../../src/services/bong-browser-lifecycle'),inspect=lifecycle.inspectRun,{api,owner}=service(f),before=snapshot(f);lifecycle.inspectRun=(id,project)=>id===f.row.run_id?{...inspect(id,project),cases:[{binding:{runId:'unlisted-owner'}}]}:inspect(id,project);try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{lifecycle.inspectRun=inspect;}assert.equal(snapshot(f),before);
});
test('missing original observation blocks a ghost even when all persisted phase hashes are intact',async()=>{
const f=await fixture({legacy:true}),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('cancelled native preparation keeps the ghost and original stopped publication byte-for-byte',async()=>{
const f=await fixture(),before=snapshot(f),{api,owner}=service(f,async()=>({approved:false})),p=api.preview(f.row.run_id,{owner});await assert.rejects(api.commit(p.ticketId,{owner,confirmed:true}));assert.equal(snapshot(f),before);
});
test('a ghost changing during approval refuses the grant and never starts another child',async()=>{
const f=await fixture({legacy:true}),{api,owner}=service(f,async()=>{db.saveLoopIteration({...f.ghost,cost:1});return{approved:true};}),p=api.preview(f.row.run_id,{owner});await assert.rejects(api.commit(p.ticketId,{owner,confirmed:true}));assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('failure after ghost removal rolls the row back with the paused grant before any new effect',async()=>{
const f=await fixture(),{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.saveLoopRun;let effects=0;engine.executeNode=async()=>{effects++;fs.writeFileSync(path.join(f.project,'READY'),'ready');return{next:true};};db.saveLoopRun=()=>{assert.equal(db.getLoopIterations(f.id).length,1);throw Error('handoff disk failure after archival');};try{assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:prepared.fingerprint})).success,false);}finally{db.saveLoopRun=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,1);
});
test('direct removal requires a writer transaction, latest grant and synchronous verification',async()=>{
const f=await fixture(),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});await api.commit(p.ticketId,{owner,confirmed:true});const c=db.getBatchCheckpoint(f.row.run_id),g=Object.values(c.recoveries)[0],before=snapshot(f);assert.throws(()=>db.removeBatchLoopGhost(f.row.run_id,g.id,()=>true));assert.throws(()=>db.runInTransaction(()=>db.removeBatchLoopGhost(f.row.run_id,g.id)));assert.throws(()=>db.runInTransaction(()=>db.removeBatchLoopGhost(f.row.run_id,'wrong',()=>true)));assert.throws(()=>db.runInTransaction(()=>db.removeBatchLoopGhost(f.row.run_id,g.id,()=>false)));assert.throws(()=>db.runInTransaction(()=>db.removeBatchLoopGhost(f.row.run_id,g.id,async()=>true)));assert.equal(snapshot(f),before);
});
test('preparation revocation preserves the ghost row and original immutable approval',async()=>{
const f=await fixture(),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});await api.commit(p.ticketId,{owner,confirmed:true});const c=db.getBatchCheckpoint(f.row.run_id),rows=db.getLoopIterations(f.id),review=api.reviewRevocation(f.row.run_id,{owner});assert.equal((await api.revoke(f.row.run_id,{owner,fingerprint:review.fingerprint,confirmed:true})).status,'aborted');assert.deepEqual(db.getLoopIterations(f.id),rows);assert.deepEqual(db.getBatchCheckpoint(f.row.run_id).recoveries,c.recoveries);assert.throws(()=>db.runInTransaction(()=>db.removeBatchLoopGhost(f.row.run_id,Object.keys(c.recoveries)[0],()=>true)));
});
test('rehashing the latest committed row does not replace independent closure evidence',async()=>{
const f=await fixture({legacy:true}),get=db.getBatchCheckpoint,getRows=db.getLoopIterations,{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),e=value.loopEvents[f.event.key];e.ledgerIteration.error_message='invented closure';const{eventHash:_,...body}=e;e.eventHash=hash(body);return value;};db.getLoopIterations=id=>{const rows=structuredClone(getRows(id));if(id===f.id)rows[0].error_message='invented closure';return rows;};try{assert.throws(()=>api.preview(f.row.run_id,{owner}));}finally{db.getBatchCheckpoint=get;db.getLoopIterations=getRows;}assert.equal(snapshot(f),before);
});
test('a fresh process archives the approved ghost and starts exactly one new child with the original epoch',async()=>{
const f=await fixture(),{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();
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');let calls=0;e.executeNode=async()=>{if(++calls>1)throw Error('child replay');require('fs').writeFileSync(require('path').join(process.argv[2],'READY'),'ready');return{newWork:true};};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,calls,error:r.error}));await e.cleanupAll();await b.cleanupAllActiveRuns();process.exitCode=r.success&&calls===1?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.getLoopRun(f.id).started_at,f.event.ledgerRun.started_at);assert.equal(db.getLoopRun(f.id).total_cost,.02);assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);assert.equal(db.getLoopIterations(f.id).length,2);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0].loopState.originalIterations[1],f.ghost);
});
test('owned scheduler discloses ghost archival before cancel-default native approval and paused continuation',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 allow=false,approvals=0;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,/์์ ๊ทผ๊ฑฐ๊ฐ ์๋ 2ํ์ฐจ ํ/);assert.match(options.detail,/์น์ธ ์ด๋ ฅ์ ๋ณด์กดํ๊ณ ์คํ ์์ฅ์์ ์ ์ธ/);assert.match(options.detail,/๋ค์ ํ์ฐจ๋ ์๋ก ์์/);return{response:allow?1:0};}}};require('../../src/ipc/batch-continuation-ipc').register({handle:(n,fn)=>handlers.set(n,fn)},{currentCwd:f.project},runtime);const invoke=input=>handlers.get('batch:continue-run')(event,f.row.run_id,input),r=await invoke({action:'review'});assert.equal(r.success,true);assert.equal(r.review.reconciledGhostIteration,true);assert.equal(r.review.reconciledLoopRows,undefined);assert.equal(approvals,0);assert.equal((await invoke({action:'accept',fingerprint:r.review.fingerprint})).success,false);assert.equal(snapshot(f),before);allow=true;assert.equal((await invoke({action:'accept',fingerprint:r.review.fingerprint})).success,true);const paused=await invoke({action:'review'});assert.equal(paused.review.canResume,true);assert.equal(paused.review.reconciledGhostIteration,true);assert.equal(paused.review.ghostIteration,2);assert.equal(approvals,2);assert.equal(db.getLoopIterations(f.id).length,2);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('a later ghost preserves every independently committed prior iteration and its original cumulative usage',async()=>{
const f=await fixture({ghostNumber:3}),rows=db.getLoopIterations(f.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.ghostIteration,3);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});let effects=0;engine.executeNode=async()=>{effects++;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(effects,1);assert.equal(db.getWorkflowRuns(f.workflow.id).length,3);assert.deepEqual(db.getLoopIterations(f.id).slice(0,2),rows.slice(0,2));assert.equal(db.getLoopRun(f.id).total_cost,.04);assert.deepEqual(db.getRuntimeUsage(f.row.run_id).usage,usage.usage);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0].loopState.originalIterations,rows);
});
for(const rootBaseline of [false,true])test('unclosed ghost '+(rootBaseline?'with committed run baseline':'with failed run aggregate')+' is archived only after explicit handoff',async()=>{
const f=await fixture({legacy:true});db.saveLoopIteration({...f.ghost,status:'running',step_outputs:{},error_message:null,completed_at:null});if(rootBaseline)db.saveLoopRun(f.event.ledgerRun,{replaceReceipt:true});const before=snapshot(f),{api,owner}=service(f),p=api.preview(f.row.run_id,{owner});assert.equal(p.reconciledGhostIteration,true);assert.equal(snapshot(f),before);const prepared=await api.commit(p.ticketId,{owner,confirmed:true});let effects=0;engine.executeNode=async()=>{effects++;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(effects,1);assert.equal(db.getLoopRun(f.id).total_cost,.02);assert.equal(Object.values(db.getBatchCheckpoint(f.row.run_id).recoveries)[0].loopState.originalIterations.at(-1).status,'running');
});
|