// 원래 intent에 묶인 관측은 최종 controller 결과와 별도 저장한다. 과거 기록을 보충·교체하지 않는다. // 설명 문서: docs/specs/batch-loop-observations.md v0.4.0 const {hash}=require('../services/bong-browser-resolution'),format=require('./batch-checkpoint-record'); const fail=()=>{throw Object.assign(Error('배치 루프 관측 기록을 저장·검증할 수 없습니다.'),{code:'BATCH_OBSERVATION_STORAGE_FAILED',retryable:false});}; function source(db,runId,eventKey){ if(typeof runId!=='string'||!/^[-\w]{1,256}$/.test(runId)||typeof eventKey!=='string'||!/^\d{1,12}$/.test(eventKey))fail(); const c=db.getBatchCheckpoint(runId),event=c?.loopEvents?.[eventKey]; if(!event||!['evaluation_intent','analysis_intent','settlement_intent'].includes(event.phase))fail(); return{c,event}; } function decode(db,runId,eventKey,value){ const{event}=source(db,runId,eventKey);if(!value)return null; const r=format.json(typeof value==='string'?JSON.parse(value):value,16777216),{hash:checksum,...body}=r; if(r.version!==1||r.runId!==runId||r.eventKey!==eventKey||r.eventHash!==event.eventHash||r.phase!==event.phase||Object.keys(r).length!==7||Object.keys(r).some(k=>!['version','runId','eventKey','eventHash','phase','events','hash'].includes(k))||!Array.isArray(r.events)||!r.events.length||r.events.length>2048||hash(body)!==checksum)fail(); const completed=new Set(); for(const [index,e]of r.events.entries()){ const {hash:check,...data}=e; if(Object.keys(e).length!==8||Object.keys(e).some(k=>!['kind','operation','operationId','data','index','recordedAt','previousHash','hash'].includes(k))||e.index!==index||e.previousHash!==(r.events[index-1]?.hash||null)||hash(data)!==check||!['intent','returned','threw'].includes(e.kind)||!Number.isFinite(Date.parse(e.recordedAt)) ||typeof e.operation!=='string'||!e.operation||e.operation.length>256||!Number.isSafeInteger(e.operationId)||e.operationId<0||e.operationId>index)fail(); const original=r.events[e.operationId]; if(e.kind==='intent'?e.operationId!==index:!original||original.kind!=='intent'||original.operation!==e.operation||completed.has(e.operationId))fail(); if(e.kind!=='intent')completed.add(e.operationId); } return r; } function append(db,runId,eventKey,input,previous,expectedHash){ const{c,event}=source(db,runId,eventKey),old=decode(db,runId,eventKey,previous); const row=db.getBatchRun(runId); if(row?.status!=='running'||row.task_id!==c.taskId||row.work_dir!==c.workDir||Object.values(c.loopEvents).at(-1).key!==eventKey||(old?.hash||null)!==expectedHash)fail(); const value=format.json(input,8388608); if(Object.keys(value).length!==4||!['kind','operation','operationId','data'].every(k=>Object.hasOwn(value,k)))fail(); const events=old?.events||[],item={...value,index:events.length,recordedAt:new Date().toISOString(),previousHash:events.at(-1)?.hash||null}; const body={version:1,runId,eventKey,eventHash:event.eventHash,phase:event.phase,events:[...events,{...item,hash:hash(item)}]}; return decode(db,runId,eventKey,{...body,hash:hash(body)}); } module.exports={decode,append,source,fail};