// 원래 batch/child run과 실패 intent를 보존하는 명시 승인·같은 실행 재개 계약이다. // 설명 문서: docs/specs/batch-step-continuation.md (v0.4.0, R67 진행 중) 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-continuation-')),oldHome=os.homedir;os.homedir=()=>home; const ctx=require('../../src/context');ctx.currentCwd=home;require('../../src/config-manager').getKnowledgeConfig=()=>({devPreferenceAutoLearn:false,codeIntelEnabled:false,troubleshootAutoCapture:false});require('../../src/services/governance-client').cachedPolicy={enabled: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({laterWorkflow=false,paid=true,prefixSteps=()=>[],laterScript,failContinueStorage=false,betweenContinue=false}={}){ const project=fs.mkdtempSync(path.join(home,'case-')),child={id:randomUUID(),name:'child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},task={id:randomUUID(),project_id:project,name:'continue original batch',is_active:0,steps:[{id:'child',type:'workflow',config:{workflowId:child.id,timeoutMs:3000}},{id:'later',type:'transform',config:{script:'return {copied: {{steps.child.runData.work.output.value}}};'}}]}; db.saveWorkflow(project,child); if(laterWorkflow){const second={...child,id:randomUUID()};db.saveWorkflow(project,second);task.steps[1]={id:'later',type:'workflow',config:{workflowId:second.id,inputs:{previous:'{{steps.child.runData.work.output.value}}'},timeoutMs:3000}};task.steps.push({id:'tail',type:'transform',config:{script:'return {copied: {{steps.later.runData.work.output.value}}};'}});} if(betweenContinue)task.steps.splice(1,0,{id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('continued after first approval')"}}); if(laterScript)task.steps.at(-1).config.script=laterScript;const prefix=prefixSteps(project);task.steps.unshift(...prefix);const childKey=[0,prefix.length,0].join(':'); await batch.saveScheduledTask(project,task);let calls=0;engine.executeNode=async run=>{calls++;if(paid){require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.02,1,{id:'paid',costSource:'provider_reported',totalTokens:2});}return{value:42};}; const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(record,...args)=>{if(failContinueStorage&&record.continuations)throw Error('continued output disk failure');if(record.entries[childKey]?.status==='completed')throw Error('lost batch step result');return save(record,...args);}; try{const result=await batch.runTask(task);assert.equal(result.success,false);}finally{db.saveBatchCheckpoint=save;} assert.equal(calls,failContinueStorage?0:1);return{project,task,child,runId:db.getBatchRuns(task.id)[0].run_id,childId:db.getWorkflowRuns(child.id)[0]?.run_id}; } function service(f,overrides={}){const owner={},scope=require('../../src/services/mcp-project-scope').capture(f.project);return{owner,api:require('../../src/services/batch-continuation').create({owner,scope,authorize:()=>true,approve:async()=>({approved:true}),...overrides})};} async function prepare(f){const s=service(f),p=await s.api.preview(f.runId,{owner:s.owner});return s.api.commit(p.ticketId,{owner:s.owner,confirmed:true});} test('explicit approval resumes the original batch after a completed child with lost output, with no child replay',async()=>{ const f=await fixture(),before=db.getBatchCheckpoint(f.runId),row=db.getBatchRun(f.runId),usage=db.getRuntimeUsage(f.runId),tasks=db.getWorkflowTasks(f.childId);engine.executeNode=async()=>{throw Error('replayed child');}; const prepared=await prepare(f);assert.equal(prepared.status,'paused');assert.equal(db.getBatchRun(f.runId).status,'paused');assert.deepEqual(db.getBatchCheckpoint(f.runId).entries,before.entries); const result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(result.runId,f.runId);assert.equal(result.stepOutputs.later.copied,42); assert.equal(db.getBatchRuns(f.task.id).length,1);assert.equal(db.getWorkflowRuns(f.child.id).length,1);assert.deepEqual(db.getWorkflowTasks(f.childId),tasks);assert.deepEqual(db.getRuntimeUsage(f.runId),usage);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries['0:0:0'],before.entries['0:0:0']); const after=db.getBatchRun(f.runId);assert.equal(after.status,'success');assert.equal(after.started_at,row.started_at);assert.equal(after.log_path,row.log_path);assert.equal(after.work_dir,row.work_dir); assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,2); assert.equal(typeof result.stepOutputs.child._duration,'string'); }); test('a later completed child publication loss is recovered by a second immutable grant on the same batch and usage tree',async()=>{ const f=await fixture({laterWorkflow:true}),first=await prepare(f),save=db.saveBatchCheckpoint;let calls=0; engine.executeNode=async run=>{calls++;require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.03,1,{id:'paid',costSource:'provider_reported',totalTokens:3});return{value:43};}; db.saveBatchCheckpoint=(record,...args)=>{if(record.entries['0:1:0']?.status==='completed')throw Error('lost second child publication');return save(record,...args);}; try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:first.fingerprint})).success,false);}finally{db.saveBatchCheckpoint=save;} assert.equal(calls,1);const second=await prepare(f);engine.executeNode=async()=>{throw Error('replayed either child');};const result=await batch.resumeBatchRun(f.runId,{fingerprint:second.fingerprint}); assert.equal(result.success,true,result.error);assert.equal(result.stepOutputs.tail.copied,43);assert.equal(db.getBatchRuns(f.task.id).length,1);assert.equal(db.getRuntimeUsage(f.runId).usage.costUsd,.05);assert.equal(Object.keys(db.getBatchCheckpoint(f.runId).recoveries).length,2); assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,3); }); test('zero-cost original usage without an entries array prepares and resumes without resetting its shape',async()=>{ const f=await fixture({paid:false}),usage=db.getRuntimeUsage(f.runId);assert.equal(usage.usage.entries,undefined);const prepared=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.deepEqual(db.getRuntimeUsage(f.runId),usage);assert.equal(db.getWorkflowRuns(f.child.id).length,1); }); test('changed child evidence after workspace acquisition blocks dispatch and preserves a retryable prepared owner',async()=>{ const f=await fixture(),prepared=await prepare(f),row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),lease=require('../../src/utils/workspace-lease'),acquire=lease.acquire,tasks=db.getWorkflowTasks(f.childId);let dispatched=0; engine.executeNode=async()=>{dispatched++;throw Error('unexpected dispatch');};lease.acquire=async(...args)=>{const held=await acquire(...args);db.completeWorkflowTask(tasks[0].task_id,'failed',null,'changed after folder acquisition');return held;}; try{const result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,false);}finally{lease.acquire=acquire;} assert.equal(dispatched,0);assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint);assert.equal(require('../../src/utils/workspace-file-lock').inspect(f.project).ownerState,'released');const owners=require('../../src/services/batch-run-lease'),lock=require('../../src/db/reviewed-store-lock').readLock(owners.file(f.task.id));assert.equal(owners.reviewable(f.task.id,lock,f.runId),true); }); test('cancelling a resumed batch drains its new child and preserves the accepted original prefix',async()=>{ const f=await fixture({laterWorkflow:true}),prepared=await prepare(f),original=db.getBatchCheckpoint(f.runId).entries['0:0:0'];let enter,finish;const entered=new Promise(r=>{enter=r;}),release=new Promise(r=>{finish=r;});engine.executeNode=async()=>{enter();await release;return{late:true};}; const pending=batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});await entered;batch.abortTask(f.task.id);let settled=false;pending.then(()=>{settled=true;});try{await new Promise(r=>setImmediate(r));assert.equal(settled,false);}finally{finish();} const result=await pending;assert.equal(result.success,false);assert.equal(db.getBatchRun(f.runId).status,'aborted');const checkpoint=db.getBatchCheckpoint(f.runId);assert.deepEqual(checkpoint.entries['0:0:0'],original);assert.equal(checkpoint.entries['0:1:0'].status,'failed');assert.equal(checkpoint.entries['0:2:0'],undefined);assert.equal(db.getBatchRuns(f.task.id).length,1); }); test('cancellation before queued resume preserves the approved paused row and allows a later explicit attempt',async()=>{ const f=await fixture(),prepared=await prepare(f),row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),controller=new AbortController();controller.abort(); const result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint,signal:controller.signal});assert.equal(result.success,false);assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint})).success,true); }); test('prepared continuation blocks replacement runs, stale fingerprints and duplicate consumers',async()=>{ const f=await fixture(),prepared=await prepare(f),checkpoint=db.getBatchCheckpoint(f.runId);engine.executeNode=async()=>{throw Error('child replay');}; assert.equal((await batch.runTask(f.task)).success,false);assert.equal(db.getBatchRuns(f.task.id).length,1); assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:'0'.repeat(64)})).success,false);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); const results=await Promise.all([batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint}),batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint})]);assert.equal(results.filter(r=>r.success).length,1);assert.equal(db.getWorkflowRuns(f.child.id).length,1); }); test('denied or cancelled approval never changes the original row or checkpoint',async()=>{ for(const cancel of [false,true]){const f=await fixture(),row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),controller=new AbortController(),s=service(f,{approve:async()=>{if(cancel)controller.abort();return{approved:false};}}),p=s.api.preview(f.runId,{owner:s.owner}); await assert.rejects(s.api.commit(p.ticketId,{owner:s.owner,confirmed:true,signal:controller.signal}));assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); } }); test('wrong owner and another project cannot obtain a continuation ticket',async()=>{ const f=await fixture(),s=service(f);assert.throws(()=>s.api.preview(f.runId,{owner:{}}));const foreign=fs.mkdtempSync(path.join(home,'foreign-')),other=service({...f,project:foreign});assert.throws(()=>other.api.preview(f.runId,{owner:other.owner})); }); test('changed settings during approval and changed stored task after preparation block handoff and effects',async()=>{ const f=await fixture(),config=require('../../src/config-manager'),get=config.getConfig,s=service(f,{approve:async()=>{config.getConfig=()=>({...get(),locale:'changed'});return{approved:true};}}),row=db.getBatchRun(f.runId),p=s.api.preview(f.runId,{owner:s.owner}); try{await assert.rejects(s.api.commit(p.ticketId,{owner:s.owner,confirmed:true}));}finally{config.getConfig=get;} assert.deepEqual(db.getBatchRun(f.runId),row);const prepared=await prepare(f);db.saveBatchTask(f.project,{...db.getBatchTasks(f.project).find(t=>t.id===f.task.id),name:'changed after prepare'}); assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint})).success,false);assert.equal(db.getBatchRun(f.runId).status,'paused');assert.equal(db.getWorkflowRuns(f.child.id).length,1); }); test('approval receipts are immutable, cannot be appended without verification, and preserve original failure evidence',async()=>{ const f=await fixture(),row=db.getBatchRun(f.runId),before=db.getBatchCheckpoint(f.runId);await prepare(f);const checkpoint=db.getBatchCheckpoint(f.runId),grant=Object.values(checkpoint.recoveries)[0],hash=require('../../src/services/bong-browser-resolution').hash; assert.equal(grant.originalRun.error_message,row.error_message);assert.equal(grant.checkpointHash,hash(before));assert.deepEqual(checkpoint.entries,before.entries); const changed=structuredClone(checkpoint),g=Object.values(changed.recoveries)[0];g.reviewFingerprint='0'.repeat(64);const {approvalHash,...body}=g;g.approvalHash=hash(body);changed.revision++; assert.throws(()=>db.saveBatchCheckpoint(changed,checkpoint.revision,()=>true));const appended=structuredClone(checkpoint),copy={...grant,id:randomUUID()};const {approvalHash:_,...nextBody}=copy;copy.approvalHash=hash(nextBody);appended.recoveries[copy.id]=copy;appended.revision++; assert.throws(()=>db.saveBatchCheckpoint(appended,checkpoint.revision));assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); }); test('a child or original task changing during approval prevents receipt publication and preserves the failed batch',async()=>{ const f=await fixture(),row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),s=service(f,{approve:async()=>{const saved=db.getBatchTasks(f.project).find(t=>t.id===f.task.id);db.saveBatchTask(f.project,{...saved,name:'changed while approving'});return{approved:true};}}),p=await s.api.preview(f.runId,{owner:s.owner}); await assert.rejects(s.api.commit(p.ticketId,{owner:s.owner,confirmed:true}));assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); }); test('same-run handoff storage failure rolls back the original checkpoint and preserves a reviewable owner',async()=>{ const f=await fixture(),row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),s=service(f),p=await s.api.preview(f.runId,{owner:s.owner}),save=db.saveBatchCheckpoint; db.saveBatchCheckpoint=(record,...args)=>{if(record.recoveries)throw Error('receipt disk failure');return save(record,...args);}; try{await assert.rejects(s.api.commit(p.ticketId,{owner:s.owner,confirmed:true}));}finally{db.saveBatchCheckpoint=save;} assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint);assert.equal((await prepare(f)).status,'paused'); }); function ipc(f,approval=async()=>({response:1})){ const {EventEmitter}=require('events'),sender=new EventEmitter(),handlers=new Map(),context={currentCwd:f.project},dialogs=[];sender.isDestroyed=()=>false;sender.mainFrame={url:require('url').pathToFileURL(path.resolve('batch-scheduler.html')).href}; require('../../src/ipc/batch-continuation-ipc').register({handle:(name,fn)=>handlers.set(name,fn)},context,{BrowserWindow:{fromWebContents:s=>s===sender?{}:null},dialog:{showMessageBox:async(_parent,options)=>{dialogs.push(options);return approval(context,sender);}}}); return{sender,context,dialogs,invoke:(input,event={sender,senderFrame:sender.mainFrame})=>handlers.get('batch:continue-run')(event,f.runId,input)}; } test('desktop native preparation preserves the failed intent and requires a separate original-run resume',async()=>{ const f=await fixture(),api=ipc(f),before=db.getBatchCheckpoint(f.runId),read=await api.invoke({action:'review'});assert.equal(read.success,true);assert.equal(api.dialogs.length,0);assert.equal(read.review.ticketId,undefined); const accepted=await api.invoke({action:'accept',fingerprint:read.review.fingerprint});assert.equal(accepted.success,true);assert.equal(api.dialogs[0].defaultId,0);assert.match(api.dialogs[0].detail,/남은 단계: later/);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries,before.entries);assert.equal(db.getBatchRun(f.runId).status,'paused'); const prepared=await api.invoke({action:'review'});assert.equal(prepared.review.status,'paused');assert.equal((await api.invoke({action:'resume',fingerprint:prepared.review.fingerprint})).success,true);assert.equal(db.getBatchRun(f.runId).status,'success');assert.equal(db.getWorkflowRuns(f.child.id).length,1);assert.equal(api.sender.listenerCount('destroyed'),0);assert.equal(api.sender.listenerCount('did-start-navigation'),0); }); test('foreign frames, HTTP senders and stale fingerprints cannot approve or execute desktop batch continuation',async()=>{ const f=await fixture(),api=ipc(f),read=await api.invoke({action:'review'}),before=db.getBatchCheckpoint(f.runId),input={action:'accept',fingerprint:read.review.fingerprint}; assert.equal((await api.invoke(input,{sender:api.sender,senderFrame:{}})).success,false);assert.equal((await api.invoke({...input,fingerprint:'0'.repeat(64)})).success,false); const requests=require('../../src/web/ipc-request-owner'),{EventEmitter}=require('events'),http=requests.create(new EventEmitter(),new EventEmitter());try{assert.equal((await api.invoke(input,{sender:http.sender})).success,false);}finally{http.dispose();} assert.equal(api.dialogs.length,0);assert.deepEqual(db.getBatchCheckpoint(f.runId),before); }); test('native cancellation and changed window or project while approving never publish a receipt',async()=>{ for(const mode of ['cancel','navigation','project']){const f=await fixture(),before=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),api=ipc(f,async(ctx,sender)=>{if(mode==='navigation')sender.emit('did-start-navigation');if(mode==='project')ctx.currentCwd=home;return{response:mode==='cancel'?0:1};}),read=await api.invoke({action:'review'}); assert.equal((await api.invoke({action:'accept',fingerprint:read.review.fingerprint})).success,false);assert.deepEqual(db.getBatchRun(f.runId),before);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint); } }); test('one desktop window cannot open concurrent native approval dialogs',async()=>{ const f=await fixture();let release;const waiting=new Promise(r=>{release=r;}),api=ipc(f,async()=>{await waiting;return{response:1};}),read=await api.invoke({action:'review'}),input={action:'accept',fingerprint:read.review.fingerprint},first=api.invoke(input); try{assert.equal((await api.invoke(input)).success,false);assert.equal(api.dialogs.length,1);}finally{release();}assert.equal((await first).success,true); }); test('a fresh process takes over the verified dead prepared owner and resumes without another child run',async()=>{ const f=await fixture(),prepared=await prepare(f),owner=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock'),target=owner.file(f.task.id);owner.claimReview(f.task.id,locks.readLock(target),f.runId).release(); const cp=require('child_process'),dead=cp.spawnSync(process.execPath,['-e',"require('./src/db/store-write-lock').acquireStoreWriteLock(process.argv[1],{retainOnExit:true});",target],{encoding:'utf8',timeout:10000});assert.equal(dead.status,0,dead.stderr);assert.equal(locks.readLock(target).state,'dead'); const code="require('os').homedir=()=>process.argv[1];const ctx=require('./src/context');ctx.currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const engine=require('./src/workflow-manager');engine.executeNode=async()=>{throw Error('child replay')};const batch=require('./src/batch-manager');batch.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log(JSON.stringify({success:r.success,runId:r.runId,error:r.error,childCount:require('./knowledge-db').getWorkflowRuns(process.argv[5]).length}));await engine.cleanupAll();await batch.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});"; const fresh=cp.spawnSync(process.execPath,['-e',code,home,f.project,f.runId,prepared.fingerprint,f.child.id],{encoding:'utf8',timeout:15000});assert.equal(fresh.status,0,fresh.stdout+fresh.stderr);assert.match(fresh.stdout,/"childCount":1/);db.reloadJson();assert.equal(db.getBatchRun(f.runId).status,'success');assert.equal(db.getBatchRuns(f.task.id).length,1); }); test('a prepared continuation can be explicitly revoked after settings change without erasing its approval or replaying effects',async()=>{ const f=await fixture(),prepared=await prepare(f),checkpoint=db.getBatchCheckpoint(f.runId),config=require('../../src/config-manager'),get=config.getConfig;config.getConfig=()=>({...get(),locale:'changed after approval'}); try{ assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint})).success,false);const s=service(f),review=s.api.reviewRevocation(f.runId,{owner:s.owner}),result=await s.api.revoke(f.runId,{owner:s.owner,fingerprint:review.fingerprint,confirmed:true}); assert.equal(result.status,'aborted');const after=db.getBatchCheckpoint(f.runId);assert.deepEqual(after.entries,checkpoint.entries);assert.deepEqual(after.recoveries,checkpoint.recoveries);assert.equal(Object.keys(after.revocations).length,1);assert.equal(db.getBatchRun(f.runId).status,'aborted');assert.equal(db.getWorkflowRuns(f.child.id).length,1);assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint})).success,false); const owners=require('../../src/services/batch-run-lease');assert.equal(owners.inspect(f.task.id).canRun,true);owners.acquire(f.task.id,'unused-new-run')();assert.throws(()=>s.api.preview(f.runId,{owner:s.owner})); }finally{config.getConfig=get;} }); test('revocation cancellation and mutation during native approval preserve the prepared run',async()=>{ for(const mode of ['cancel','changed']){const f=await fixture();await prepare(f);const row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),s=service(f,{approve:async()=>{if(mode==='changed')db.completeBatchRun(f.runId,'failed','concurrent operator');return{approved:mode!=='cancel'};}}),review=s.api.reviewRevocation(f.runId,{owner:s.owner}); await assert.rejects(s.api.revoke(f.runId,{owner:s.owner,confirmed:true,fingerprint:review.fingerprint}));assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint);if(mode==='cancel')assert.deepEqual(db.getBatchRun(f.runId),row); } }); test('revocation publication failure rolls back row and checkpoint and keeps the original owner reviewable',async()=>{ const f=await fixture();await prepare(f);const row=db.getBatchRun(f.runId),checkpoint=db.getBatchCheckpoint(f.runId),s=service(f),review=s.api.reviewRevocation(f.runId,{owner:s.owner}),save=db.saveBatchCheckpoint; db.saveBatchCheckpoint=(value,...args)=>{if(value.revocations)throw Error('revocation disk failed');return save(value,...args);};try{await assert.rejects(s.api.revoke(f.runId,{owner:s.owner,confirmed:true,fingerprint:review.fingerprint}));}finally{db.saveBatchCheckpoint=save;} assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getBatchCheckpoint(f.runId),checkpoint);const fresh=s.api.reviewRevocation(f.runId,{owner:s.owner});assert.equal((await s.api.revoke(f.runId,{owner:s.owner,confirmed:true,fingerprint:fresh.fingerprint})).status,'aborted'); }); test('desktop review exposes revoke after a settings change and native confirmation does not undo or replay the child',async()=>{ const f=await fixture();await prepare(f);const api=ipc(f),config=require('../../src/config-manager'),get=config.getConfig;config.getConfig=()=>({...get(),locale:'changed'}); try{const review=await api.invoke({action:'review'});assert.equal(review.success,true);assert.equal(review.review.canResume,false);assert.equal(review.review.canRevoke,true); assert.equal((await api.invoke({action:'resume',fingerprint:review.review.fingerprint})).success,false);const result=await api.invoke({action:'revoke',fingerprint:review.review.revokeFingerprint});assert.equal(result.success,true);assert.equal(api.dialogs[0].defaultId,0);assert.match(api.dialogs[0].detail,/외부 효과를 되돌리거나 새 실행/);assert.equal(db.getBatchRun(f.runId).status,'aborted');assert.equal(db.getWorkflowRuns(f.child.id).length,1); }finally{config.getConfig=get;} }); test('live child ownership or a held workspace prevents revocation and original owner release',async()=>{ const f=await fixture();await prepare(f);const s=service(f),children=require('../../src/services/workflow-run-lease'),release=children.acquire(f.childId); try{assert.throws(()=>s.api.reviewRevocation(f.runId,{owner:s.owner}));}finally{release();} const held=await require('../../src/utils/workspace-lease').acquire(f.project,'other-owner');try{assert.throws(()=>s.api.reviewRevocation(f.runId,{owner:s.owner}));}finally{held.release();} assert.equal(db.getBatchRun(f.runId).status,'paused');assert.ok(s.api.reviewRevocation(f.runId,{owner:s.owner}).fingerprint); }); test('a published failed-continue output and exact duration survive original-run recovery and later interpolation',async()=>{ const f=await fixture({prefixSteps:()=>[{id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('optional controlled failure')"}}],laterScript:'return {error: "{{steps.optional.error}}",duration: "{{steps.optional._duration}}",copied: {{steps.child.runData.work.output.value}}};'}),before=db.getBatchCheckpoint(f.runId); assert.equal(before.entries['0:0:0'].status,'failed');assert.ok(before.continuations?.['0:0:0']);const prepared=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(result.stepOutputs.later.error,'optional controlled failure');assert.equal(result.stepOutputs.later.duration,before.continuations['0:0:0'].output._duration);assert.equal(result.stepOutputs.later.copied,42);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries['0:0:0'],before.entries['0:0:0']);assert.deepEqual(db.getBatchCheckpoint(f.runId).continuations,before.continuations); assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,2); }); test('a completed retry prefix is restored without repeating either original CLI attempt',async()=>{ let counter;const f=await fixture({prefixSteps:project=>{counter=path.join(project,'retry-counter.json');const code="const fs=require('fs'),f="+JSON.stringify(counter)+";const n=fs.existsSync(f)?JSON.parse(fs.readFileSync(f))+1:1;fs.writeFileSync(f,JSON.stringify(n));console.log(JSON.stringify({attempt:n}));process.exitCode=n===1?1:0;",escape=v=>require('../../src/utils/shell-helper').escapeShellArg(v,process.platform==='win32');return[{id:'retry',type:'cli',on_failure:'retry',retry_count:2,retry_delay:.001,config:{command:escape(process.execPath)+' -e '+escape(code)}}];},laterScript:'return {attempt: {{steps.retry.data.attempt}},copied: {{steps.child.runData.work.output.value}}};'}),before=db.getBatchCheckpoint(f.runId); assert.equal(before.entries['0:0:0'].status,'failed');assert.equal(before.entries['0:0:1'].status,'completed');assert.equal(JSON.parse(fs.readFileSync(counter)),2);const prepared=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(result.stepOutputs.later.attempt,2);assert.equal(JSON.parse(fs.readFileSync(counter)),2);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries['0:0:0'],before.entries['0:0:0']);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries['0:0:1'],before.entries['0:0:1']); }); test('failed-continue output publication failure stops before the next child and preserves the failed intent',async()=>{ const f=await fixture({prefixSteps:()=>[{id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('controlled optional failure')"}}],failContinueStorage:true}),checkpoint=db.getBatchCheckpoint(f.runId);assert.equal(checkpoint.entries['0:0:0'].status,'failed');assert.equal(checkpoint.entries['0:1:0'],undefined);assert.equal(checkpoint.continuations,undefined);assert.equal(db.getBatchRun(f.runId).status,'failed'); }); test('continued outputs are immutable and a missing publication cannot be inferred from a failed intent',async()=>{ const f=await fixture({prefixSteps:()=>[{id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('immutable continued failure')"}}]}),before=db.getBatchCheckpoint(f.runId),hash=require('../../src/services/bong-browser-resolution').hash,next=structuredClone(before); next.continuations['0:0:0'].output._duration='999.00';next.continuations['0:0:0'].outputHash=hash(next.continuations['0:0:0'].output);next.revision++;assert.throws(()=>db.saveBatchCheckpoint(next,before.revision));assert.deepEqual(db.getBatchCheckpoint(f.runId),before); const get=db.getBatchCheckpoint;db.getBatchCheckpoint=id=>{const c=get(id);if(id===f.runId)delete c.continuations;return c;};try{const s=service(f);assert.throws(()=>s.api.preview(f.runId,{owner:s.owner}));}finally{db.getBatchCheckpoint=get;} }); test('a continued output published after an earlier grant preserves that grant and a second child recovery',async()=>{ const f=await fixture({laterWorkflow:true,betweenContinue:true,laterScript:'return {error: "{{steps.optional.error}}",copied: {{steps.later.runData.work.output.value}}};'}),first=await prepare(f),original=db.getBatchCheckpoint(f.runId).recoveries,save=db.saveBatchCheckpoint;let calls=0; engine.executeNode=async()=>{calls++;return{value:43};};db.saveBatchCheckpoint=(record,...args)=>{if(record.entries['0:2:0']?.status==='completed')throw Error('lost second child after continued failure');return save(record,...args);}; try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:first.fingerprint})).success,false);}finally{db.saveBatchCheckpoint=save;} assert.equal(calls,1);assert.ok(db.getBatchCheckpoint(f.runId).continuations?.['0:1:0']);const second=await prepare(f);engine.executeNode=async()=>{throw Error('replayed original child');};const result=await batch.resumeBatchRun(f.runId,{fingerprint:second.fingerprint});assert.equal(result.success,true,result.error);assert.equal(result.stepOutputs.tail.error,'continued after first approval');assert.equal(result.stepOutputs.tail.copied,43);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.runId).recoveries)[0],Object.values(original)[0]);assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,3); });