File size: 10,533 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ์›๋ž˜ ๊ด€์ธก์˜ ์ฝ๊ธฐ ๋Œ€์‚ฌ๊ฐ€ ์‹คํ–‰ยท์•Œ๋ฆผยทํ˜„์žฌ ํŒŒ์ผ ๊ฒ€์‚ฌ๋กœ ๋ฐ”๋€Œ์ง€ ์•Š๋Š”์ง€ ๊ฒ€์ฆํ•œ๋‹ค.
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/batch-loop-observations.md v0.2.0
const{test,after}=require('node:test'),assert=require('node:assert/strict'),fs=require('fs'),path=require('path'),os=require('os'),{randomUUID}=require('crypto');
const home=fs.mkdtempSync(path.resolve('scratch/batch-verification-')),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'),harness=require('../../src/harness-executor');
after(async()=>{await batch.cleanupAllActiveRuns();os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));});
async function fixture({goals,stages,configure}={}){const cwd=fs.mkdtempSync(path.join(home,'case-'));fs.writeFileSync(path.join(cwd,'READY'),'ORIGINAL');const script=path.join(cwd,'goal.cjs');fs.writeFileSync(script,"const fs=require('fs');let n=0;try{n=+fs.readFileSync('count')}catch{}fs.writeFileSync('count',String(n+1));console.log('GOAL_OK');");const quote=require('../../src/config/claude-execution-config').quoteShellArgument,command=quote(process.execPath)+' '+quote(script),harnessId=randomUUID();db.saveHarness(cwd,{id:harnessId,name:'proof harness',...(stages?{stages}:{validation_command:command,success_criteria:{regex_match:'GOAL_OK'}})});const item={id:randomUUID(),project_id:cwd,is_active:0,name:'read-only proof',steps:[{id:'value',type:'transform',config:{script:'return {score:3};'}}],loop_config:JSON.stringify({goals:goals||[{type:'composite',sub_goals:[{type:'file_exists',target:'READY'},{type:'file_regex',target:'READY',pattern:'ORIGINAL'},{type:'metric_threshold',metric_key:'value.score',operator:'>=',value:3},{type:'test_pass',test_command:command},{type:'harness_pass',harnessId}]}],max_iterations:2})};configure?.({cwd,item,harnessId});db.saveBatchTask(cwd,item);const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(Object.values(c.loopEvents||{}).at(-1)?.phase==='evaluated')throw Error('controlled aggregate loss');return save(c,...args);};try{assert.equal((await batch.runTask(item)).success,false);}finally{db.saveBatchCheckpoint=save;}const row=db.getBatchRuns(item.id)[0],c=db.getBatchCheckpoint(row.run_id),event=Object.values(c.loopEvents).at(-1);assert.equal(event.phase,'evaluation_intent');return{item,cwd,row,c,event,harnessId};}
const verify=f=>require('../../src/services/batch-loop-observation-proof').verify(db,f.row.run_id,f.event.key);
test('all original goal leaves are recomputed from bound observations without commands, current file reads, HUD or database writes',async()=>{
 const f=await fixture(),before=JSON.stringify([db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id),db.getBatchLoopObservations(f.row.run_id,f.event.key)]),commands=harness.runHarnessCommand,stages=harness.runHarnessStages,read=require('../../src/utils/regular-file-reader').readBounded,publish=require('../../src/services/loop-hud').publish;let effects=0;fs.unlinkSync(path.join(f.cwd,'READY'));fs.unlinkSync(path.join(f.cwd,'goal.cjs'));harness.runHarnessCommand=harness.runHarnessStages=()=>{effects++;throw Error('replayed');};require('../../src/utils/regular-file-reader').readBounded=()=>{effects++;throw Error('current file read');};require('../../src/services/loop-hud').publish=()=>{effects++;};let result;try{result=verify(f);}finally{harness.runHarnessCommand=commands;harness.runHarnessStages=stages;require('../../src/utils/regular-file-reader').readBounded=read;require('../../src/services/loop-hud').publish=publish;}assert.equal(result.kind,'evaluation');assert.equal(result.goalMet,true);assert.equal(result.verifiedGoals,6);assert.equal(result.controllerOutcomeCertified,false);assert.deepEqual(result.metricHistory,{});assert.equal(effects,0);assert.equal(fs.readFileSync(path.join(f.cwd,'count'),'utf8'),'2');assert.equal(JSON.stringify([db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id),db.getBatchLoopObservations(f.row.run_id,f.event.key)]),before);
 const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.cwd),authorize:()=>true,approve:async()=>{throw Error('read-only proof requested approval');}}),view=api.verifyLoopOutcome(f.row.run_id,{owner});assert.equal(view.goalMet,true);assert.equal(view.canResume,false);assert.doesNotMatch(JSON.stringify(view),/GOAL_OK|ORIGINAL|goal\.cjs/);assert.equal(api.preview(f.row.run_id,{owner}).reconstructedPhase,true);assert.equal(db.getBatchRun(f.row.run_id).status,'failed');
});
test('original failed metric advances only its own historical stagnation series',async()=>{const f=await fixture({goals:[{type:'metric_threshold',metric_key:'value.score',operator:'>',value:9}]}),result=verify(f);assert.equal(result.goalMet,false);assert.deepEqual(result.metricHistory,{'0':[3]});});
for(const optional of [false,true])test('stage gate verifies raw exit codes, ordered identity, optional policy and skips: '+optional,async()=>{const f=await fixture({stages:[{name:'first',command:'exit 1',required:!optional},{name:'second',command:'echo SECOND',required:true}]}),result=verify(f);assert.equal(result.goalMet,optional);});
function rehash(value){const hash=require('../../src/services/bong-browser-resolution').hash;for(let i=0;i<value.events.length;i++){const e=value.events[i];e.previousHash=value.events[i-1]?.hash||null;const{hash:_,...body}=e;e.hash=hash(body);}const{hash:_,...body}=value;value.hash=hash(body);return value;}
for(const mutation of ['goal-result','metric-value','input-hash','missing-return','extra-return'])test('semantic proof rejects '+mutation+' even with fresh observation checksums',async()=>{const f=await fixture(),get=db.getBatchLoopObservations,raw=get(f.row.run_id,f.event.key),copy=structuredClone(raw);if(mutation==='goal-result')copy.events.find(e=>e.operation==='goal:0.3:result'&&e.kind==='returned').data=false;if(mutation==='metric-value')copy.events.find(e=>e.operation==='goal:0.2:metric'&&e.kind==='returned').data.value=999;if(mutation==='input-hash')copy.events.find(e=>e.operation==='goal:0:result'&&e.kind==='intent').data.inputsHash='a'.repeat(64);if(mutation==='missing-return')copy.events.pop();if(mutation==='extra-return')copy.events.push({...copy.events.at(-1),index:copy.events.length});rehash(copy);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===f.event.key?copy:get(id,key);try{assert.throws(()=>verify(f));}finally{db.getBatchLoopObservations=get;}});
test('changed harness configuration cannot certify an old hash-bound observation',async()=>{const f=await fixture(),old=db.getHarness(f.harnessId);db.saveHarness(f.cwd,{...old,validation_command:'echo CHANGED'});assert.throws(()=>verify(f),/BATCH_OBSERVATION_VERIFICATION_FAILED/);});
test('read verification rejects another caller, project and changed authorization',async()=>{const f=await fixture(),owner={},create=require('../../src/services/batch-continuation').create,scope=require('../../src/services/mcp-project-scope').capture;const api=create({owner,scope:scope(f.cwd),authorize:()=>true,approve:async()=>({approved:true})});assert.throws(()=>api.verifyLoopOutcome(f.row.run_id,{owner:{}}),/DENIED/);assert.throws(()=>create({owner,scope:scope(home),authorize:()=>true,approve:async()=>({approved:true})}).verifyLoopOutcome(f.row.run_id,{owner}),/project|scope|DENIED/i);});
test('desktop read verification uses the owned scheduler frame without native approval or an implicit resume',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};let approvals=0;const ctx={currentCwd:f.cwd},runtime={BrowserWindow:{fromWebContents:s=>s===sender?{}:null},dialog:{showMessageBox:async()=>{approvals++;return{response:1};}}};require('../../src/ipc/batch-continuation-ipc').register({handle:(name,fn)=>handlers.set(name,fn)},ctx,runtime);const invoke=input=>handlers.get('batch:continue-run')(event,f.row.run_id,input),result=await invoke({action:'verify'});assert.equal(result.success,true);assert.equal(result.verification.goalMet,true);assert.equal(result.verification.canResume,false);assert.equal((await invoke({action:'accept',fingerprint:result.verification.fingerprint})).success,false);assert.equal(approvals,0);assert.equal(db.getBatchRun(f.row.run_id).status,'failed');event.senderFrame={};assert.equal((await invoke({action:'verify'})).success,false);});
test('a remote validation summary cannot stand in for independent response evidence and is not fetched again',async t=>{let requests=0;const server=require('http').createServer((_req,res)=>{requests++;res.end('ORIGINAL_REMOTE');});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(()=>{server.closeAllConnections();return new Promise(resolve=>server.close(resolve));});const f=await fixture({configure:({cwd,item,harnessId})=>{db.saveHarness(cwd,{id:harnessId,name:'remote',validation_command:'http://127.0.0.1:'+server.address().port,success_criteria:{expected_text:'ORIGINAL_REMOTE'}});item.loop_config=JSON.stringify({goals:[{type:'harness_pass',harnessId}],max_iterations:2});}});assert.equal(requests,1);assert.throws(()=>verify(f),/REMOTE_REQUIRES_INDEPENDENT_EVIDENCE/);assert.equal(requests,1);});
test('authorization and cancellation are rechecked for read-only verification',async()=>{const f=await fixture(),owner={},signal=new AbortController();let authorized=true;const api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.cwd),authorize:()=>authorized,approve:async()=>({approved:true})});authorized=false;assert.throws(()=>api.verifyLoopOutcome(f.row.run_id,{owner}),/DENIED/);authorized=true;signal.abort();assert.throws(()=>api.verifyLoopOutcome(f.row.run_id,{owner,signal:signal.signal}),/CANCELLED/);});