// 과거 continue 출력을 추정하지 않는다. 원래 원장의 값과 그 값을 소비한 입력/관측을 읽기 대사한다. // 설명 문서: docs/specs/batch-memory-continue.md v1.0.0 const {hash}=require('./bong-browser-resolution'),format=require('../db/batch-checkpoint-record'),recovery=require('../db/batch-recovery-record'),continued=require('../db/batch-continued-record'); const fail=reason=>{throw Object.assign(Error('BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED: '+reason),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason,retryable:false});}; const body=v=>typeof v==='string'?JSON.parse(v):v; function verify(db,runId){return db.runInTransaction(()=>{ if(typeof runId!=='string'||!/^[-\w]{1,160}$/.test(runId))fail('RUN_ID'); const c=format.decode(db.getBatchCheckpoint(runId)),row=db.getBatchRun(runId),usage=db.getRuntimeUsage(runId); if(!c||!row||!c.definition.loop||c.runId!==runId||row.task_id!==c.taskId||row.work_dir!==c.workDir||!['failed','aborted','paused'].includes(row.status)||usage?.version!==1||usage.runId!==runId||usage.parentRunId!==null)fail('IDENTITY'); const task=db.getBatchTasks(c.projectId).find(t=>t.id===c.taskId),definition=require('../utils/batch-definition'); if(!task||task.project_id!==c.projectId||definition.fingerprint(task)!==c.definitionHash)fail('DEFINITION_CHANGED'); const steps=format.stepsFor(task),entries=Object.values(c.entries),loop=db.getLoopRun('looprun-'+runId),rows=db.getLoopIterations('looprun-'+runId),records={},goalEvidence=[]; if(loop?.run_id!=='looprun-'+runId||loop.parent_run_id!==runId||!rows.length||rows.length>4096||rows.some((r,i)=>r.id!=='iter-looprun-'+runId+'-'+(i+1)||r.loop_run_id!==loop.run_id||r.iteration_number!==i+1))fail('LOOP_IDENTITY'); const u=usage.usage?.entries,requests=usage.requests; if(!Array.isArray(u)||!requests||new Set(u.map(e=>e.id)).size!==u.length||u.some(e=>!['cli_reported','provider_reported','operator_reported','not_submitted'].includes(e.costSource)||!Number.isFinite(e.costUsd)||e.costUsd<0||e.totalTokens!==null&&e.totalTokens!==undefined&&(!Number.isSafeInteger(e.totalTokens)||e.totalTokens<0))||Object.values(requests).some(q=>!q||!['settled','not_submitted'].includes(q.state)||q.costKnown!==true))fail('UNKNOWN_USAGE'); if(!Number.isFinite(usage.usage.costUsd)||Math.abs(u.reduce((sum,e)=>sum+e.costUsd,0)-usage.usage.costUsd)>1e-9)fail('USAGE_TOTAL'); for(const e of entries){ if(e.status!=='failed'||steps[e.stepIndex].on_failure!=='continue'||continued.resolved(c,e.key)||recovery.resolved(c,e.key))continue; if(continued.uncertain(e.error)||e.attempt!==0)fail('UNCERTAIN_FAILURE'); const source=rows[e.iteration-1],outputs=body(source?.step_outputs),output=outputs?.[e.stepId]; if(!output||Array.isArray(output)||Object.keys(output).length!==2||!Object.hasOwn(output,'error')||!Object.hasOwn(output,'_duration')||typeof output.error!=='string'||output.error.slice(0,2000)!==e.error.message||typeof output._duration!=='string'||!/^\d+\.\d{2}$/.test(output._duration)||!Number.isFinite(Number(output._duration)))fail('ORIGINAL_OUTPUT_MISSING'); format.json(output); records[e.key]={entryKey:e.key,originalEntryHash:hash(e),output:structuredClone(output),outputHash:hash(output),durationSource:'original_consumed_output',source:{kind:'loop_iteration',id:source.id,hash:hash(source)},consumers:[]}; } if(!Object.keys(records).length)fail('NO_MEMORY_OUTPUTS'); let revision=Object.keys(c.recoveries||{}).length+Object.keys(c.revocations||{}).length+Object.keys(c.continuations||{}).length+Object.keys(c.loopEvents||{}).length+Object.keys(c.loopPublications||{}).length+Number(!!c.loopOrigin),prior,iteration,outputs={}; for(const e of entries){ const resolution=recovery.resolved(c,e.key),published=e.status==='completed'?e:c.continuations?.[e.key],candidate=records[e.key],approved=continued.resolved(c,e.key); if(prior?.status==='running')fail('RUNNING_PREFIX');format.sequence(prior,e,c.definition.loop);revision+=e.status==='running'?1:2; if(prior?.status==='failed'){ const policy=steps[prior.stepIndex]; if(e.iteration===prior.iteration&&e.stepIndex===prior.stepIndex){if(policy.on_failure!=='retry'||e.attempt>(policy.retry_count||3)||continued.uncertain(prior.error)||continued.resolved(c,prior.key)||records[prior.key])fail('RETRY_POLICY');} else if(!continued.resolved(c,prior.key)&&!records[prior.key])fail('FAILED_PREFIX'); } if(e.iteration!==iteration){outputs={};iteration=e.iteration;} const step=steps[e.stepIndex],escape=step.type==='cli'?v=>require('../utils/shell-helper').escapeShellArg(v,process.platform==='win32'):null,config=require('../batch-step-runners').interpolateConfig(step.config,outputs,escape); if(e.inputsHash!==hash(outputs)||e.configHash!==hash(config))fail('CONSUMED_INPUTS'); if(prior&&prior.iteration===e.iteration&&records[prior.key]){ if(Date.parse(e.startedAt)[k,requests[k]])),invocations=Object.fromEntries(Object.entries(usage.workflowInvocations||{}).filter(([,d])=>d.kind==='batch'&&d.stepId===e.stepId&&d.stepIndex===e.stepIndex&&d.iteration===e.iteration)); if(hash(prefix.map(v=>v.id))!==hash(published.usageIds)||hash({entries:prefix,requests:saved})!==published.usageHash||hash(invocations)!==published.invocationsHash)fail('PUBLISHED_USAGE');outputs[e.stepId]=published.output; } if(resolution||approved||candidate)outputs[e.stepId]=(resolution||approved||candidate).output; prior=resolution?{...e,status:'completed'}:e; } if(revision!==c.revision||(prior?.key||null)!==c.currentKey)fail('REVISION'); // 마지막 실패 출력은 다음 entry가 없다. 전체 원래 목표 관측이 같은 입력을 소비했을 때만 인정한다. for(const [key,record]of Object.entries(records))if(!record.consumers.length){ const entry=c.entries[key],event=Object.values(c.loopEvents||{}).find(e=>e.iteration===entry.iteration&&e.phase==='evaluation_intent'); if(!event||!event.entryKeys.includes(key)||Date.parse(event.recordedAt)!Object.hasOwn(inputs,s.id)))fail('INCOMPLETE_GOAL_INPUTS'); const observations=require('../db/batch-loop-observation-record').decode(db,runId,event.key,db.getBatchLoopObservations(runId,event.key));if(!observations)fail('MISSING_OBSERVATIONS'); const parent={checkpoint:c,row,usage,task,steps,memoryContinuations:records},config=require('../config/loop-configuration').normalize(task.loop_config,{requireGoals:false}),proof=require('./batch-goal-observation-proof').verify(db,{parent,event,observations,outputs:inputs,config}); if(!proof.controllerTransitionVerified)fail('MISSING_CONTROLLER_EVIDENCE'); record.consumers.push({kind:'goal_observations',key:event.key,eventHash:event.eventHash,observationsHash:observations.hash,inputsHash:hash(inputs)});goalEvidence.push([event.key,observations.hash]); } return{version:1,runId,records,goalEvidenceCount:goalEvidence.length,knownCostUsd:usage.usage.costUsd,usageHash:hash(usage),fingerprint:hash([c,row,usage,loop,rows,records,goalEvidence]),candidateConsumptionVerified:true,canResume:false,ancestryCertified:false,controllerOutcomeCertified:false}; });} module.exports={verify};