Download test/wrapper/batch-controller-observations.test.cjs from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 8.65 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/test/wrapper/batch-controller-observations.test.cjs
- Command line
-
hf download hf://VanyaJ/bada-terminal/test/wrapper/batch-controller-observations.test.cjs
-
curl -L -o batch-controller-observations.test.cjs https://huggingface.co/VanyaJ/bada-terminal/resolve/main/test/wrapper/batch-controller-observations.test.cjs
8.65 kB
| // ์ค๋ช ๋ฌธ์: 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');}); | |