// 설명 문서: docs/specs/batch-step-continuation.md v0.11.0 // 이미 끝난 목표/분석 효과를 재실행하지 않고 소유자 승인으로 같은 실행을 이어간다. const{test,after}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os'),{randomUUID}=require('node:crypto'); const home=fs.mkdtempSync(path.resolve('scratch/batch-intent-continue-')),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()=>{};require('../../src/wiki-run-archiver').archiveBatchRun=async()=>({success:true}); const db=require('../../knowledge-db'),batch=require('../../src/batch-manager'); after(async()=>{await batch.cleanupAllActiveRuns();os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));}); async function fixture({phase='evaluated',iteration=1,ready=true,config={},failPublication=false}={}){ const cwd=fs.mkdtempSync(path.join(home,'case-')),quote=require('../../src/config/claude-execution-config').quoteShellArgument,script=path.join(cwd,'goal.cjs'); fs.writeFileSync(script,"const fs=require('fs');let n=0;try{n=+fs.readFileSync('goals')}catch{}fs.writeFileSync('goals',String(n+1));process.exitCode=fs.existsSync('READY')?0:1;");if(ready)fs.writeFileSync(path.join(cwd,'READY'),'original'); const task={id:randomUUID(),project_id:cwd,is_active:0,name:'original intent',steps:[{id:'one',type:'transform',config:{script:'return {score:3};'}}],loop_config:JSON.stringify({goals:[{type:'test_pass',test_command:quote(process.execPath)+' '+quote(script)}],max_iterations:4,token_budget:1,...config})};db.saveBatchTask(cwd,task); const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{const e=Object.values(c.loopEvents||{}).at(-1);if(e?.phase===phase&&e.iteration===iteration){if(failPublication){save(c,...args);throw Error('controlled outer transaction loss');}throw Error('controlled '+phase+' result loss');}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),source=Object.values(c.loopEvents).at(-1);return{cwd,task,row,c,source}; } 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.cwd),authorize:()=>true,approve});return{owner,api};} async function prepare(f,approve){const{owner,api}=service(f,approve),review=api.preview(f.row.run_id,{owner});assert.equal(review.reconstructedPhase,true);assert.equal(review.sourcePhase,f.source.phase);const before=JSON.stringify([db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id)]);assert.equal(db.getBatchRun(f.row.run_id).status,'failed');const prepared=await api.commit(review.ticketId,{owner,confirmed:true});assert.equal(prepared.status,'paused');assert.notEqual(before,JSON.stringify([db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id)]));assert.equal(db.getBatchCheckpoint(f.row.run_id).loopEvents[f.source.key].eventHash,f.source.eventHash);return{prepared,review,api,owner};} test('approved missing terminal evaluation completes the same original run with no goal/step replay or changed source evidence',async()=>{ const f=await fixture(),raw=db.getBatchLoopObservations(f.row.run_id,f.source.key),usage=db.getRuntimeUsage(f.row.run_id),loop=db.getLoopRun('looprun-'+f.row.run_id);assert.equal(f.source.phase,'evaluation_intent');const p=await prepare(f);fs.unlinkSync(path.join(f.cwd,'READY'));fs.unlinkSync(path.join(f.cwd,'goal.cjs')); const Controller=require('../../src/loop-controller').LoopController,evaluate=Controller.prototype.evaluateTermination;Controller.prototype.evaluateTermination=async()=>{throw Error('original goal replay');};let result;try{result=await batch.resumeBatchRun(f.row.run_id,{fingerprint:p.prepared.fingerprint});}finally{Controller.prototype.evaluateTermination=evaluate;} assert.equal(result.success,true,result.error);assert.equal(db.getBatchRuns(f.task.id).length,1);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');assert.deepEqual(db.getRuntimeUsage(f.row.run_id),usage);assert.deepEqual(db.getBatchLoopObservations(f.row.run_id,f.source.key),raw);const c=db.getBatchCheckpoint(f.row.run_id);assert.deepEqual(c.loopEvents[f.source.key],f.source);assert.equal(Object.keys(c.entries).length,1);assert.equal(Object.values(c.loopEvents).filter(e=>e.phase==='evaluated').length,1);assert.equal(db.getLoopRun(loop.run_id).started_at,loop.started_at);assert.equal(db.getLoopRun(loop.run_id).status,'completed');assert.equal(db.getLoopIterations(loop.run_id).length,1); }); for(const [phase,source]of [['evaluated','evaluation_intent'],['analyzed','analysis_intent'],['settled','settlement_intent']])test('approved '+source+' in a later iteration preserves full original prefix and performs only the intentional next iteration',async()=>{ const f=await fixture({phase,iteration:2,ready:false});assert.equal(f.source.phase,source);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'2');const prior=Object.values(f.c.loopEvents).filter(e=>e.iteration===1),p=await prepare(f);fs.writeFileSync(path.join(f.cwd,'READY'),'now ready');assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:p.prepared.fingerprint})).success,true);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'3');const c=db.getBatchCheckpoint(f.row.run_id);for(const e of prior)assert.deepEqual(c.loopEvents[e.key],e);assert.deepEqual(c.loopEvents[f.source.key],f.source);assert.equal(db.getLoopIterations('looprun-'+f.row.run_id).length,3); }); test('original source and loop rows survive reconstructed-phase claim rollback and can be explicitly retried',async()=>{const f=await fixture(),p=await prepare(f),row=db.getBatchRun(f.row.run_id),c=db.getBatchCheckpoint(f.row.run_id),loop=db.getLoopRun('looprun-'+f.row.run_id),save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(next,...args)=>{if(Object.values(next.loopEvents||{}).at(-1)?.phase==='evaluated')throw Error('controlled claim rollback');return save(next,...args);};try{assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:p.prepared.fingerprint})).success,false);}finally{db.saveBatchCheckpoint=save;}assert.deepEqual(db.getBatchRun(f.row.run_id),row);assert.deepEqual(db.getBatchCheckpoint(f.row.run_id),c);assert.deepEqual(db.getLoopRun(loop.run_id),loop);assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:p.prepared.fingerprint})).success,true);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');}); test('observation mutation during native approval rejects the grant without replay',async()=>{const f=await fixture(),get=db.getBatchLoopObservations;let changed=false;const{api,owner}=service(f,async()=>{changed=true;return{approved:true};}),view=api.preview(f.row.run_id,{owner});db.getBatchLoopObservations=(id,key)=>changed&&id===f.row.run_id&&key===f.source.key?null:get(id,key);try{await assert.rejects(api.commit(view.ticketId,{owner,confirmed:true}));}finally{db.getBatchLoopObservations=get;}assert.equal(db.getBatchRun(f.row.run_id).status,'failed');assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');}); test('expired nonterminal evaluation never obtains a fresh wall-time allowance',async()=>{const f=await fixture({ready:false}),{api,owner}=service(f),clock=Date.now;Date.now=()=>clock()+4000000;try{assert.throws(()=>api.preview(f.row.run_id,{owner}),/BATCH_LOOP_CONTINUATION_BLOCKED/);}finally{Date.now=clock;}assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');}); test('missing original clock cannot be manufactured into an approved outcome',async()=>{const f=await fixture(),get=db.getBatchLoopObservations,{api,owner}=service(f);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===f.source.key?null:get(id,key);try{assert.throws(()=>api.preview(f.row.run_id,{owner}),/BATCH_LOOP_CONTINUATION_BLOCKED/);}finally{db.getBatchLoopObservations=get;}assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');}); for(const phase of ['evaluation_intent','analysis_intent','settlement_intent'])test('a valid latest intent cannot hide missing '+phase+' evidence in an earlier committed iteration',async()=>{const f=await fixture({phase:'analyzed',iteration:2,ready:false}),old=Object.values(f.c.loopEvents).find(e=>e.iteration===1&&e.phase===phase),get=db.getBatchLoopObservations,{api,owner}=service(f);assert.ok(old);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===old.key?null:get(id,key);try{assert.throws(()=>api.preview(f.row.run_id,{owner}),/BATCH_LOOP_CONTINUATION_BLOCKED/);}finally{db.getBatchLoopObservations=get;}assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'2');}); test('an earlier rehashed false goal aggregate cannot authorize a later valid missing analysis outcome',async()=>{const f=await fixture({phase:'analyzed',iteration:2,ready:false}),old=Object.values(f.c.loopEvents).find(e=>e.iteration===1&&e.phase==='evaluation_intent'),get=db.getBatchLoopObservations,raw=get(f.row.run_id,old.key),hash=require('../../src/services/bong-browser-resolution').hash;raw.events.find(e=>e.operation==='goal:0:result'&&e.kind==='returned').data=true;for(const [index,e]of raw.events.entries()){e.previousHash=raw.events[index-1]?.hash||null;const{hash:_,...body}=e;e.hash=hash(body);}const{hash:_,...body}=raw;raw.hash=hash(body);const{api,owner}=service(f);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===old.key?raw:get(id,key);try{assert.throws(()=>api.preview(f.row.run_id,{owner}),/BATCH_LOOP_CONTINUATION_BLOCKED/);}finally{db.getBatchLoopObservations=get;}assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'2');}); test('nonterminal time guard is rechecked after approval before any recovered execution claim',async()=>{const f=await fixture({ready:false}),p=await prepare(f),before=JSON.stringify([db.getBatchRun(f.row.run_id),db.getBatchCheckpoint(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id)]),clock=Date.now;Date.now=()=>clock()+4000000;try{assert.equal((await batch.resumeBatchRun(f.row.run_id,{fingerprint:p.prepared.fingerprint})).success,false);}finally{Date.now=clock;}assert.equal(JSON.stringify([db.getBatchRun(f.row.run_id),db.getBatchCheckpoint(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id)]),before);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');}); test('a fresh process recovers a dead original intent owner with the approved source and zero command replay',async()=>{const f=await fixture(),p=await prepare(f),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock'),target=owners.file(f.task.id),cp=require('node:child_process');owners.claimReview(f.task.id,locks.readLock(target),f.row.run_id).release();const 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');fs.unlinkSync(path.join(f.cwd,'goal.cjs')); const code="require('os').homedir=()=>process.argv[1];require('./src/context').currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const batch=require('./src/batch-manager');batch.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log('RECOVERED:'+JSON.stringify({success:r.success}));await batch.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});",child=cp.spawnSync(process.execPath,['-e',code,home,f.cwd,f.row.run_id,p.prepared.fingerprint],{encoding:'utf8',timeout:15000});assert.equal(child.status,0,child.stdout+child.stderr);db.reloadJson();assert.equal(db.getBatchRun(f.row.run_id).status,'success');assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');assert.deepEqual(db.getBatchCheckpoint(f.row.run_id).loopEvents[f.source.key],f.source);}); test('owned desktop IPC explains the reconstructed phase, honors native cancel, then prepares and resumes separately',async()=>{const f=await fixture(),handlers=new Map(),sender={isDestroyed:()=>false,mainFrame:{url:require('node:url').pathToFileURL(path.resolve('batch-scheduler.html')).href}},event={sender,senderFrame:sender.mainFrame};let approved=false,approvals=0;const runtime={BrowserWindow:{fromWebContents:value=>value===sender?{}:null},dialog:{showMessageBox:async(_window,options)=>{approvals++;assert.equal(options.defaultId,0);assert.match(options.detail,/원래 관측으로 복원할 기록: 목표 평가/);assert.match(options.detail,/후속 분석·다음 회차/);assert.doesNotMatch(options.detail,/goal\.cjs|receiptSummary/);return{response:approved?1:0};}}};require('../../src/ipc/batch-continuation-ipc').register({handle:(name,fn)=>handlers.set(name,fn)},{currentCwd:f.cwd},runtime);const call=input=>handlers.get('batch:continue-run')(event,f.row.run_id,input),view=await call({action:'review'});assert.equal(view.success,true);assert.equal(view.review.reconstructedPhase,true);assert.equal((await call({action:'accept',fingerprint:view.review.fingerprint})).success,false);assert.equal(db.getBatchCheckpoint(f.row.run_id).recoveries,undefined);approved=true;assert.equal((await call({action:'accept',fingerprint:view.review.fingerprint})).success,true);assert.equal(db.getBatchRun(f.row.run_id).status,'paused');assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');const paused=await call({action:'review'});assert.equal(paused.review.canResume,true);assert.equal((await call({action:'resume',fingerprint:paused.review.fingerprint})).success,true);assert.equal(approvals,2);assert.equal(fs.readFileSync(path.join(f.cwd,'goals'),'utf8'),'1');});