File size: 8,653 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
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/batch-loop-observations.md v0.3.0
// ์‹ค์ œ controller๊ฐ€ ์žƒ์€ ๊ฒฐ๊ณผ์™€ ๋…๋ฆฝ ์žฌ๊ตฌ์„ฑ ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค. ๋ณต๊ตฌ ์Šน์ธ์€ ๋ณ„๋„๋‹ค.
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-controller-observations-')),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});require('../../src/wiki-run-archiver').archiveWorkflowRun=async()=>{};
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({config={},cost=0,optionalFailure=false,delay=0,clockFailure}={}){
 const cwd=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'historical usage',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},item={id:randomUUID(),project_id:cwd,is_active:0,name:'controller outcome',steps:[...(optionalFailure?[{id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('original optional failure')"}}]:[]),{id:'value',type:'workflow',config:{workflowId:workflow.id,timeoutMs:5000}}],loop_config:JSON.stringify({goals:[{type:'metric_threshold',metric_key:'value.runData.work.output.score',operator:'>',value:9}],max_iterations:10,token_budget:1,consecutive_failure_threshold:5,stagnation_window:5,...config})};
 let calls=0;engine.executeNode=async run=>{calls++;if(delay)await new Promise(resolve=>setTimeout(resolve,delay));if(cost){require('../../src/services/usage-request').begin(run,'cli','original-cost');engine.addRunUsage(run.runId,cost,1,{id:'original-cost',costSource:'provider_reported',totalTokens:7});}return{score:3};};
 db.saveWorkflow(cwd,workflow);db.saveBatchTask(cwd,item);const save=db.saveBatchCheckpoint,append=db.appendBatchLoopObservation;let attempted;
 db.saveBatchCheckpoint=(c,...args)=>{const event=Object.values(c.loopEvents||{}).at(-1);if(event?.phase==='evaluated'){attempted=structuredClone(event);throw Error('controlled final evaluation loss');}return save(c,...args);};
 db.appendBatchLoopObservation=(...args)=>{if(clockFailure&&args[2].operation==='controller:evaluation_clock'&&args[2].kind===clockFailure)throw Error('controlled decision clock storage loss');return append(...args);};
 try{assert.equal((await batch.runTask(item)).success,false);}finally{db.saveBatchCheckpoint=save;db.appendBatchLoopObservation=append;}
 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');assert.equal(calls,1);return{cwd,item,row,c,event,attempted};
}
const verify=f=>require('../../src/services/batch-loop-observation-proof').verify(db,f.row.run_id,f.event.key);
const capture=f=>JSON.stringify([db.getBatchCheckpoint(f.row.run_id),db.getRuntimeUsage(f.row.run_id),db.getLoopRun('looprun-'+f.row.run_id),db.getLoopIterations('looprun-'+f.row.run_id),db.getBatchLoopObservations(f.row.run_id,f.event.key)]);
for(const [name,options,reason]of[
 ['goal precedence',{config:{goals:[{type:'metric_threshold',metric_key:'value.runData.work.output.score',operator:'>=',value:3}],max_iterations:1},cost:1},'goal_achieved'],
 ['continue',{cost:.2},'continue'],['budget warning',{cost:.85},'continue'],
 ['max iterations',{config:{max_iterations:1},cost:1},'MAX_ITERATIONS'],
 ['cost budget',{cost:1},'TOKEN_BUDGET_EXCEEDED'],
 ['wall time',{config:{max_wall_time:.04},delay:80},'WALL_TIME_EXCEEDED'],
 ['continued failure',{optionalFailure:true,config:{consecutive_failure_threshold:1}},'CONSECUTIVE_FAILURES'],
 ['metric stagnation',{config:{stagnation_window:1}},'STAGNATED']
])test('original controller '+name+' is reconstructed with exact usage, metric history and receipt without a new decision clock',async()=>{
 const f=await fixture(options),before=capture(f),now=Date.now,publish=require('../../src/services/loop-hud').publish;let effects=0;
 // JSON ์ €์žฅ์†Œ๋Š” ์ฝ๊ธฐ transaction์˜ reload/lock์— ํ˜„์žฌ ์‹œ๊ฐ์„ ์“ด๋‹ค. ๋ฏธ๋ž˜๋กœ ๋ฐ”๊ฟ”๋„ ํŒ์ •/๋ฆฌ์‹œํŠธ๋Š” ์›๋ž˜ ์‹œ๊ฐ๊ณผ ์ •ํ™•ํžˆ ๊ฐ™์•„์•ผ ํ•œ๋‹ค.
 Date.now=db.isJsonFallback()?()=>now()+4000000:()=>{throw Error('current clock read');};require('../../src/services/loop-hud').publish=()=>{effects++;};let proof;
 try{proof=verify(f);}finally{Date.now=now;require('../../src/services/loop-hud').publish=publish;}
 assert.ok(proof.controllerReconstruction,'missing historical controller reconstruction');assert.equal(proof.controllerTransitionVerified,true);assert.deepEqual(proof.controllerReconstruction.controller,f.attempted.controller);assert.deepEqual(proof.controllerReconstruction.result,f.attempted.result);assert.equal(proof.controllerReconstruction.result.breakReason||proof.controllerReconstruction.result.reason,reason);assert.equal(proof.canResume,false);assert.equal(proof.controllerOutcomeCertified,false);assert.equal(effects,0);assert.equal(capture(f),before);
 if(name==='budget warning')assert.equal(proof.controllerReconstruction.controller.hasWarnedBudget,true);
 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('unexpected approval');}}),view=api.verifyLoopOutcome(f.row.run_id,{owner});assert.equal(view.controllerTransitionVerified,true);assert.equal(view.decision.reason,f.attempted.result.reason);assert.equal(view.canResume,false);assert.doesNotMatch(JSON.stringify(view),/receiptSummary|original optional failure/);assert.equal(api.preview(f.row.run_id,{owner}).reconstructedPhase,true);assert.equal(db.getBatchRun(f.row.run_id).status,'failed');
});
function rehash(value){const hash=require('../../src/services/bong-browser-resolution').hash;for(const [index,e]of value.events.entries()){e.index=index;e.operationId=e.kind==='intent'?index:e.operationId;e.previousHash=value.events[index-1]?.hash||null;const{hash:_,...body}=e;e.hash=hash(body);}const{hash:_,...body}=value;value.hash=hash(body);return value;}
test('old observations without a decision clock remain readable but cannot invent a controller outcome',async()=>{const f=await fixture(),get=db.getBatchLoopObservations,raw=get(f.row.run_id,f.event.key);raw.events=raw.events.filter(e=>!e.operation.startsWith('controller:'));for(const e of raw.events)e.operationId-=2;rehash(raw);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===f.event.key?raw:get(id,key);try{const proof=verify(f);assert.equal(proof.goalMet,false);assert.equal(proof.controllerTransitionVerified,false);assert.equal(proof.controllerReconstruction,undefined);assert.equal(proof.canResume,false);}finally{db.getBatchLoopObservations=get;}});
for(const mutation of ['future-clock','usage','success'])test('rehashed '+mutation+' cannot certify a different original controller decision',async()=>{const f=await fixture(),get=db.getBatchLoopObservations,raw=get(f.row.run_id,f.event.key),e=raw.events.find(e=>e.operation==='controller:evaluation_clock'&&e.kind===(mutation==='future-clock'?'returned':'intent'));assert.ok(e,'missing decision clock observation');if(mutation==='future-clock')e.data+=100000;if(mutation==='usage')e.data.iterationInfo.cost+=.5;if(mutation==='success')e.data.iterationInfo.success=false;rehash(raw);db.getBatchLoopObservations=(id,key)=>id===f.row.run_id&&key===f.event.key?raw:get(id,key);try{assert.throws(()=>verify(f),/BATCH_OBSERVATION_VERIFICATION_FAILED/);}finally{db.getBatchLoopObservations=get;}});
for(const kind of ['intent','returned'])test('decision clock '+kind+' persistence failure cannot advance controller result or enable a replay',async()=>{const f=await fixture({clockFailure:kind});assert.equal(f.attempted,undefined);assert.throws(()=>verify(f),/BATCH_OBSERVATION_VERIFICATION_FAILED/);assert.equal(Object.values(db.getBatchCheckpoint(f.row.run_id).loopEvents).at(-1).phase,'evaluation_intent');});