// 실제 실행의 출력/요청/관측에서 과거 메모리 전용 continue 저장 형식만 재현한다. 제품 저장을 우회하지 않는다. // 설명 문서: docs/specs/batch-memory-continue.md v0.1.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-memory-proof-')),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,{hash}=require('../../src/services/bong-browser-resolution'); 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({last=false}={}){ const project=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'paid child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},optional={id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('original optional failure')"}},child={id:'child',type:'workflow',config:{workflowId:workflow.id,timeoutMs:3000}},task={id:randomUUID(),project_id:project,name:'memory output',is_active:0,loop_config:JSON.stringify({goals:[{type:'metric_threshold',metric_key:'optional._duration',operator:'>=',value:0}],max_iterations:3,token_budget:1}),steps:last?[child,optional]:[optional,child]}; db.saveWorkflow(project,workflow);await batch.saveScheduledTask(project,task);let calls=0;engine.executeNode=async run=>{calls++;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=(c,...args)=>{if(last?Object.values(c.loopEvents||{}).at(-1)?.phase==='evaluated':c.entries['1:1:0']?.status==='completed')throw Error('injected final publication loss');return save(c,...args);};let result;try{result=await batch.runTask(task);}finally{db.saveBatchCheckpoint=save;}assert.equal(result.success,false);assert.equal(calls,1); const runId=db.getBatchRuns(task.id)[0].run_id,original=db.getBatchCheckpoint(runId),c=structuredClone(original),key=last?'1:1:0':'1:0:0',output=original.continuations[key].output,removed=[...Object.values(c.continuations).map(r=>r.recordedRevision),...Object.values(c.loopPublications||{}).map(r=>r.revision)],eventMap=new Map();delete c.continuations;delete c.loopPublications;delete c.publicationVersion;c.revision-=removed.length; // 과거 fixture의 revision/hash는 제거한 새 게시 기록만큼 재배치한다. 실제 출력/시각/입력 hash는 보존한다. let prior=null;for(const e of Object.values(c.loopEvents)){const oldKey=e.key;e.revision-=removed.filter(r=>r[e.key,e])); const observations=new Map();for(const[oldKey,e]of eventMap){if(!e.phase.endsWith('_intent'))continue;const o=db.getBatchLoopObservations(runId,oldKey);if(o){o.eventKey=e.key;o.eventHash=e.eventHash;delete o.hash;o.hash=hash(o);observations.set(e.key,o);}} const view=Object.create(db);view.getBatchCheckpoint=id=>id===runId?structuredClone(c):db.getBatchCheckpoint(id);view.getBatchLoopObservations=(id,eventKey)=>id===runId?structuredClone(observations.get(eventKey)||null):db.getBatchLoopObservations(id,eventKey); return{project,workflow,task,runId,c,original,key,output,view,observations}; } const verify=f=>require('../../src/services/batch-memory-continue-proof').verify(f.view,f.runId); test('raw loop output is certified only when the next original step consumed its exact duration and error',async()=>{ const f=await fixture(),before=hash([db.getBatchCheckpoint(f.runId),db.getRuntimeUsage(f.runId),db.getLoopIterations('looprun-'+f.runId)]),p=verify(f);assert.equal(p.records[f.key].outputHash,hash(f.output));assert.equal(p.records[f.key].durationSource,'original_consumed_output');assert.equal(p.records[f.key].consumers[0].kind,'entry_inputs');assert.equal(p.records[f.key].consumers[0].key,'1:1:0');assert.equal(p.canResume,false);assert.equal(p.ancestryCertified,false);assert.equal(p.controllerOutcomeCertified,false);assert.equal(hash([db.getBatchCheckpoint(f.runId),db.getRuntimeUsage(f.runId),db.getLoopIterations('looprun-'+f.runId)]),before); }); test('a final continued step requires complete independent goal observations to certify its original output',async()=>{ const f=await fixture({last:true}),p=verify(f);assert.deepEqual(p.records[f.key].output,f.output);assert.equal(p.records[f.key].consumers[0].kind,'goal_observations');assert.equal(p.goalEvidenceCount,1);assert.equal(p.canResume,false);assert.equal(p.controllerOutcomeCertified,false);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1); }); function rows(f,change){const list=db.getLoopIterations('looprun-'+f.runId);change(list);f.view.getLoopIterations=id=>id==='looprun-'+f.runId?structuredClone(list):db.getLoopIterations(id);} for(const [name,change]of[ ['duration replaced but not consumed',list=>{const o=JSON.parse(list[0].step_outputs);o.optional._duration='999.99';list[0].step_outputs=JSON.stringify(o);}], ['error differs from original failure',list=>{const o=JSON.parse(list[0].step_outputs);o.optional.error='invented error';list[0].step_outputs=JSON.stringify(o);}], ['extra output property',list=>{const o=JSON.parse(list[0].step_outputs);o.optional.status='success';list[0].step_outputs=JSON.stringify(o);}], ['unbounded duration number',list=>{const o=JSON.parse(list[0].step_outputs);o.optional._duration='9'.repeat(400)+'.00';list[0].step_outputs=JSON.stringify(o);}], ['missing raw source output',list=>{list[0].step_outputs='{}';}], ['another loop identity',list=>{list[0].loop_run_id='another-loop';}] ])test('memory output refuses '+name,async()=>{const f=await fixture();rows(f,change);assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED'});}); test('an output checksum alone cannot replace a missing next entry and independent goal consumption',async()=>{const f=await fixture();delete f.c.entries['1:1:0'];f.c.currentKey=f.key;f.c.revision--;assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason:'MISSING_CONSUMER'});}); test('later input and interpolated configuration must both match the original candidate',async()=>{for(const field of['inputsHash','configHash']){const f=await fixture();f.c.entries['1:1:0'][field]='a'.repeat(64);assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason:'CONSUMED_INPUTS'});}}); test('uncertain failed effects cannot be certified by an existing original output',async()=>{const f=await fixture();f.c.entries[f.key].error.code='CLI_STORAGE_BUSY';assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason:'UNCERTAIN_FAILURE'});}); test('unknown or unsettled costs block output certification without changing their ledger',async()=>{for(const mode of['unknown','open','total']){const f=await fixture(),u=db.getRuntimeUsage(f.runId);if(mode==='unknown')u.usage.entries[0].costSource='unknown';else if(mode==='open')Object.values(u.requests)[0].state='pending';else u.usage.costUsd=99;f.view.getRuntimeUsage=id=>id===f.runId?structuredClone(u):db.getRuntimeUsage(id);assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED'});}}); test('missing final goal observations cannot be replaced by a saved raw duration',async()=>{const f=await fixture({last:true});f.view.getBatchLoopObservations=()=>null;assert.throws(()=>verify(f),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason:'MISSING_OBSERVATIONS'});}); test('a complete hash chain with an incomplete final goal outcome still fails',async()=>{const f=await fixture({last:true}),[key,o]=[...f.observations][0];o.events.pop();delete o.hash;o.hash=hash(o);f.observations.set(key,o);assert.throws(()=>verify(f),{code:'BATCH_OBSERVATION_VERIFICATION_FAILED'});}); test('the final goal must consume exactly the original duration rather than a rehashed candidate',async()=>{const f=await fixture({last:true});rows(f,list=>{const o=JSON.parse(list[0].step_outputs);o.optional._duration='888.88';list[0].step_outputs=JSON.stringify(o);});assert.throws(()=>verify(f),{code:'BATCH_OBSERVATION_VERIFICATION_FAILED'});}); function withView(f,action){const get=db.getBatchCheckpoint,observations=db.getBatchLoopObservations;db.getBatchCheckpoint=id=>id===f.runId?structuredClone(f.c):get(id);db.getBatchLoopObservations=(id,key)=>id===f.runId?structuredClone(f.observations.get(key)||null):observations(id,key);try{return action();}finally{db.getBatchCheckpoint=get;db.getBatchLoopObservations=observations;}} test('owned read verification returns bounded evidence without preparing a grant or overwriting the failed intent',async()=>{const f=await fixture(),owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.project),authorize:()=>true,approve:async()=>{throw Error('read requested approval');}}),before=db.getBatchCheckpoint(f.runId);withView(f,()=>{const p=api.verifyMemoryContinue(f.runId,{owner});assert.equal(p.verifiedOutputs,1);assert.equal(p.steps[0].outputHash,hash(f.output));assert.equal(p.steps[0].output,undefined);assert.equal(p.canResume,false);assert.equal(p.ancestryCertified,false);assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);assert.throws(()=>api.verifyMemoryContinue(f.runId,{owner:{}}));assert.throws(()=>api.verifyMemoryContinue(f.runId,{owner,signal:AbortSignal.abort()}));});assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.equal(before.recoveries,undefined);}); test('another project cannot read memory-continue candidates through the owned service',async()=>{const f=await fixture(),owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(home),authorize:()=>true,approve:async()=>({approved:true})});withView(f,()=>assert.throws(()=>api.verifyMemoryContinue(f.runId,{owner})));}); test('desktop read action never opens native approval and rejects foreign frames without replay',async()=>{const f=await fixture({last:true}),{EventEmitter}=require('events'),sender=new EventEmitter(),handlers=new Map(),context={currentCwd:f.project};let dialogs=0;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()=>{dialogs++;throw Error('read opened approval');}}});const invoke=handlers.get('batch:continue-run'),get=db.getBatchCheckpoint,observations=db.getBatchLoopObservations;db.getBatchCheckpoint=id=>id===f.runId?structuredClone(f.c):get(id);db.getBatchLoopObservations=(id,key)=>id===f.runId?structuredClone(f.observations.get(key)||null):observations(id,key);try{const r=await invoke({sender,senderFrame:sender.mainFrame},f.runId,{action:'verify-continue'});assert.equal(r.success,true);assert.equal(r.verification.verifiedOutputs,1);assert.equal(r.verification.canResume,false);assert.equal((await invoke({sender,senderFrame:{}},f.runId,{action:'verify-continue'})).success,false);context.currentCwd=home;assert.equal((await invoke({sender,senderFrame:sender.mainFrame},f.runId,{action:'verify-continue'})).success,false);assert.equal(dialogs,0);assert.equal(sender.listenerCount('destroyed'),0);assert.equal(sender.listenerCount('did-start-navigation'),0);}finally{db.getBatchCheckpoint=get;db.getBatchLoopObservations=observations;}assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);});