// 원래 목표 효과와 별도 관측 기록을 비교한다. 최종 phase 유실을 성공으로 바꾸지 않는다. // 설명 문서: docs/specs/batch-loop-observations.md v0.1.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-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}); 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}));}); function fixture(){const cwd=fs.mkdtempSync(path.join(home,'case-')),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));process.stdout.write('ORIGINAL_GOAL_RESULT');");const command=require('../../src/config/claude-execution-config').quoteShellArgument(process.execPath)+' '+require('../../src/config/claude-execution-config').quoteShellArgument(script),item={id:randomUUID(),project_id:cwd,is_active:0,name:'original observations',steps:[{id:'value',type:'transform',config:{script:'return {score:3};'}}],loop_config:JSON.stringify({goals:[{type:'test_pass',test_command:command}],max_iterations:2,token_budget:1})};db.saveBatchTask(cwd,item);return{item,cwd};} function state(item){const row=db.getBatchRuns(item.id)[0],c=db.getBatchCheckpoint(row.run_id),e=Object.values(c.loopEvents).find(v=>v.phase==='evaluation_intent');return{row,c,e};} test('original command observations survive aggregate evaluation storage failure and reopen without executing commands',async()=>{ const{item,cwd}=fixture(),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);};let result;try{result=await batch.runTask(item);}finally{db.saveBatchCheckpoint=save;}assert.equal(result.success,false);const{row,e}=state(item),observations=db.getBatchLoopObservations(row.run_id,e.key);assert.equal(fs.readFileSync(path.join(cwd,'count'),'utf8'),'1');assert.ok(observations);const command=observations.events.find(v=>v.kind==='intent'&&v.operation==='goal:0:command');const returned=observations.events.find(v=>v.operationId===command.index&&v.kind==='returned');assert.equal(returned.data.stdout,'ORIGINAL_GOAL_RESULT');assert.equal(returned.data.exitCode,0);assert.equal(Object.values(db.getBatchCheckpoint(row.run_id).loopEvents).at(-1).phase,'evaluation_intent'); const code="const os=require('os');os.homedir=()=>process.argv[1];const db=require('./knowledge-db');console.log('OBS:'+JSON.stringify(db.getBatchLoopObservations(process.argv[2],process.argv[3])));";const child=require('node:child_process').spawnSync(process.execPath,['-e',code,home,row.run_id,e.key],{encoding:'utf8',timeout:15000});assert.equal(child.status,0,child.stdout+child.stderr);assert.deepEqual(JSON.parse(child.stdout.split('\n').find(v=>v.startsWith('OBS:')).slice(4)),observations);assert.equal(fs.readFileSync(path.join(cwd,'count'),'utf8'),'1'); const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(cwd),authorize:()=>true,approve:async()=>({approved:true})});assert.equal(api.preview(row.run_id,{owner}).reconstructedPhase,true);assert.equal(db.getBatchRun(row.run_id).status,'failed'); }); for(const kind of ['intent','returned'])test('observation '+kind+' storage failure stops later effects and never certifies a goal',async()=>{ const{item,cwd}=fixture(),append=db.appendBatchLoopObservation;let calls=0;db.appendBatchLoopObservation=(...args)=>{if(args[2].kind===kind&&args[2].operation==='goal:0:command'){calls++;throw Error('controlled observation storage loss');}return append(...args);};let result;try{result=await batch.runTask(item);}finally{db.appendBatchLoopObservation=append;}assert.equal(calls,1);assert.equal(result.success,false);assert.equal(fs.existsSync(path.join(cwd,'count')),kind==='returned');if(kind==='returned')assert.equal(fs.readFileSync(path.join(cwd,'count'),'utf8'),'1');const{row,c,e}=state(item);assert.equal(Object.values(c.loopEvents).at(-1).phase,'evaluation_intent');const saved=db.getBatchLoopObservations(row.run_id,e.key);assert.equal(saved.events.some(v=>v.operation==='goal:0:command'&&v.kind==='returned'),false); }); test('observed files, metrics and composite leaf results retain original values after filesystem changes',async()=>{ const{item,cwd}=fixture();fs.writeFileSync(path.join(cwd,'READY'),'original content');item.loop_config=JSON.stringify({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}]}],max_iterations:2});db.saveBatchTask(cwd,item);assert.equal((await batch.runTask(item)).success,true);const{row,e}=state(item);fs.writeFileSync(path.join(cwd,'READY'),'changed');const observed=db.getBatchLoopObservations(row.run_id,e.key),returned=observed.events.filter(v=>v.kind==='returned');assert.ok(returned.some(v=>v.operation==='goal:0.0:file_exists'&&v.data===true));assert.ok(returned.some(v=>v.operation==='goal:0.1:file_content'&&v.data==='original content'));assert.ok(returned.some(v=>v.operation==='goal:0.2:metric'&&v.data.value===3));assert.ok(returned.some(v=>v.operation==='goal:0:result'&&v.data===true)); }); test('append CAS and single outcome reject stale writers, duplicate responses and observations after phase closure',async()=>{ const{item}=fixture(),append=db.appendBatchLoopObservation;let checked=0,original; db.appendBatchLoopObservation=(...args)=>{const saved=append(...args);if(args[2].operation==='goal:0:command'&&args[2].kind==='returned'){original={args,saved};assert.throws(()=>append(...args),/관측/);assert.throws(()=>append(args[0],args[1],args[2],saved.hash),/관측/);const invalid={...args[2],kind:'intent',operationId:0};assert.throws(()=>append(args[0],args[1],invalid,saved.hash),/관측/);checked++;}return saved;};try{assert.equal((await batch.runTask(item)).success,true);}finally{db.appendBatchLoopObservation=append;}assert.equal(checked,1);assert.throws(()=>append(original.args[0],original.args[1],{kind:'intent',operation:'late',operationId:original.saved.events.length,data:null},original.saved.hash),/관측/); }); for(const stages of [false,true])test('original '+(stages?'multi-stage':'single')+' harness output and definition hash survive a lost aggregate result',async()=>{ const{item,cwd}=fixture(),definition={id:randomUUID(),name:'original harness',...(stages?{stages:[{name:'gate',command:'echo ORIGINAL_STAGE',required:true}]}:{validation_command:'echo ORIGINAL_SINGLE',success_criteria:{regex_match:'ORIGINAL_SINGLE'}})};db.saveHarness(cwd,definition);item.loop_config=JSON.stringify({goals:[{type:'harness_pass',harnessId:definition.id}],max_iterations:2});db.saveBatchTask(cwd,item);const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(Object.values(c.loopEvents||{}).at(-1)?.phase==='evaluated')throw Error('controlled harness aggregate loss');return save(c,...args);};try{assert.equal((await batch.runTask(item)).success,false);}finally{db.saveBatchCheckpoint=save;}const{row,e}=state(item),saved=db.getBatchLoopObservations(row.run_id,e.key),raw=saved.events.find(v=>v.kind==='returned'&&v.operation===(stages?'goal:0:harness_stages':'goal:0:command'));assert.ok(raw);assert.match(JSON.stringify(raw.data),stages?/ORIGINAL_STAGE/:/ORIGINAL_SINGLE/);const intent=saved.events.find(v=>v.index===raw.operationId);assert.equal(intent.data.definitionHash,require('../../src/services/bong-browser-resolution').hash(db.getHarness(definition.id)));assert.ok(saved.events.some(v=>v.kind==='returned'&&v.operation==='goal:0:result'&&v.data===true)); }); for(const stages of [false,true])test('harness '+(stages?'stages':'command')+' does not swallow observation storage failures as an ordinary failed goal',async()=>{ const{item,cwd}=fixture(),id=randomUUID(),operation=stages?'goal:0:harness_stages':'goal:0:command';db.saveHarness(cwd,{id,name:'storage boundary',...(stages?{stages:[{name:'gate',command:'echo ORIGINAL',required:true}]}:{validation_command:'echo ORIGINAL'})});item.loop_config=JSON.stringify({goals:[{type:'harness_pass',harnessId:id},{type:'test_pass',test_command:JSON.parse(item.loop_config).goals[0].test_command}],max_iterations:2});db.saveBatchTask(cwd,item);const append=db.appendBatchLoopObservation;let calls=0;db.appendBatchLoopObservation=(...args)=>{if(args[2].kind==='returned'&&args[2].operation===operation){calls++;throw Error('controlled harness observation loss');}return append(...args);};try{assert.equal((await batch.runTask(item)).success,false);}finally{db.appendBatchLoopObservation=append;}assert.equal(calls,1);assert.equal(fs.existsSync(path.join(cwd,'count')),false);const{c}=state(item);assert.equal(Object.values(c.loopEvents).at(-1).phase,'evaluation_intent'); }); test('remote harness keeps its original bounded validation summary without copying the response body',async t=>{ const{item,cwd}=fixture(),id=randomUUID();let calls=0;const server=require('node:http').createServer((_req,res)=>{calls++;res.end('ORIGINAL_REMOTE_BODY');});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(()=>{server.closeAllConnections();return new Promise(resolve=>server.close(resolve));});db.saveHarness(cwd,{id,name:'remote evidence',validation_command:'http://127.0.0.1:'+server.address().port,success_criteria:{expected_text:'ORIGINAL_REMOTE_BODY'}});item.loop_config=JSON.stringify({goals:[{type:'harness_pass',harnessId:id}],max_iterations:2});db.saveBatchTask(cwd,item);assert.equal((await batch.runTask(item)).success,true);const{row,e}=state(item),saved=db.getBatchLoopObservations(row.run_id,e.key),raw=saved.events.find(v=>v.operation==='goal:0:remote_harness'&&v.kind==='returned');assert.equal(calls,1);assert.equal(raw.data.success,true);assert.match(raw.data.stdout,/HTTP 200/);assert.equal(JSON.stringify(saved).includes('ORIGINAL_REMOTE_BODY'),false); });