// committed/실패 마감과 대기 항목은 함께 저장한다. 외부 제출과 DB는 원자화할 수 없어 의도를 먼저 기록한다. // 설명 문서: docs/specs/batch-step-continuation.md (v0.12.0, R67 진행 중) const {hash}=require('./bong-browser-resolution'),{same}=require('../db/batch-recovery-record'),format=require('../db/batch-loop-publication-record'); const rows=(db,c)=>({run:db.getLoopRun('looprun-'+c.runId),iterations:db.getLoopIterations('looprun-'+c.runId)}); function packet(c,event){const r=event.result,warning=event.phase==='evaluated';return{runId:c.runId,loopRunId:event.ledgerRun.run_id,iteration:event.iteration,cost:warning?event.controller.cumulativeCost:event.ledgerRun.total_cost,status:warning?'warning':r.shouldTerminate?r.goalMet?'completed':'circuit_broken':'running',reason:warning?'budget_warning':r.reason,breakReason:r.breakReason||null,goalMet:warning?false:r.goalMet,shouldTerminate:warning?false:r.shouldTerminate,receiptSummary:warning?null:r.receiptSummary||null};} function summary(c){const result={pending:0,uncertain:0,submitted:0,unsupported:0,superseded:0,legacy:c?.publicationVersion!==1};for(const {ready,channels}of format.states(c||{}).values())for(const channel of ready.data.channels){const s=channels[channel]?.kind;if(!s)result.pending++;else if(s==='intent'||s==='uncertain')result.uncertain++;else result[s]++;}return result;} function verify(db,c){for(const {ready}of format.states(c).values()){ const {source,packet:p,channels}=ready.data;if(source.kind==='stopped'){ const actual=rows(db,c),old=Object.values(c.recoveries||{}).map(g=>g.loopState&&({run:g.loopState.originalRun,iterations:g.loopState.originalIterations})); if(![actual,...old].some(v=>v&&hash(v)===source.rowsHash))throw Error('Unverified loop stop publication'); const found=[actual,...old].find(v=>v&&hash(v)===source.rowsHash),r=found.run; if(!same(p,stopped(c,r))||!same(channels,['hud','ipc']))throw Error('Unverified loop stop payload'); }else{ const e=c.loopEvents[source.eventKey],expected=source.kind==='warning'?['warning']:e.result.shouldTerminate?['hud','ipc','native']:['hud']; if(!same(p,packet(c,e))||!same(channels,expected))throw Error('Unverified loop result publication'); } }} function stopped(c,r){return{runId:c.runId,loopRunId:r.run_id,iteration:r.total_iterations,cost:r.total_cost,status:r.status,reason:r.status==='aborted'?'cancelled':'execution_failed',breakReason:r.break_reason||null,goalMet:false,shouldTerminate:true,receiptSummary:null};} function create({db,run,checkpoint,controller,emit}){ function ready(source,p,channels){const c=checkpoint.get();if(c.publicationVersion!==1)return;const data={source,packet:p,channels},publicationId=hash(data);if(format.states(c).has(publicationId))return;checkpoint.publication({kind:'ready',publicationId,channel:null,data});} function warnings(){const c=checkpoint.get(),evaluated=Object.values(c.loopEvents||{}).filter(e=>e.phase==='evaluated');for(let i=0;i[channel,packets.filter(p=>p.ready.data.channels.includes(channel)).at(-1)?.ready.publicationId])); for(const {ready,channels}of packets)for(const channel of ready.data.channels){ if(channels[channel])continue;const {publicationId}=ready,p=ready.data.packet; checkpoint.publication({kind:'intent',publicationId,channel,data:null});let outcome='submitted'; if(['hud','ipc'].includes(channel)&&latest[channel]!==publicationId){checkpoint.publication({kind:'superseded',publicationId,channel,data:null});continue;} try{ if(channel==='hud'){ let failed=false;require('./loop-hud').publish(controller,p.status,p.breakReason,{publicationId,iteration:p.iteration,cost:p.cost,onFailure:()=>{failed=true;}});if(failed)outcome='uncertain'; } else if(channel==='ipc'){const result=emit('loop:complete',{...p,publicationId});if(result?.status==='uncertain')outcome='uncertain';} else{const notifier=require('../loop-notifier'),r=channel==='native'?notifier.notifyLoopComplete(p.runId,p.goalMet,p.breakReason||p.reason,p.cost):notifier.notifyLoopWarning(p.runId,`누적 비용($${p.cost.toFixed(2)})이 예산의 80%를 초과했습니다.`);outcome=['submitted','unsupported'].includes(r?.status)?r.status:'uncertain';} }catch{outcome='uncertain';run.logStream?.write('[Loop Outbox] 제출 결과를 확인할 수 없어 자동 재전송하지 않습니다.\n');} // 이 쓰기가 실패하면 intent만 남는다. 이미 제출했을 수 있으므로 다시 보내지 않는다. checkpoint.publication({kind:outcome,publicationId,channel,data:null}); } const result=summary(checkpoint.get());run.loopPublicationSummary=result;return result; } function initial(){const c=checkpoint.get(),e=Object.values(c.loopEvents||{}).at(-1),entry=[...format.states(c).values()].find(s=>s.ready.data.source.eventKey===e?.key&&s.ready.data.source.kind==='committed'); if(e?.phase==='committed'&&e.result.shouldTerminate&&(entry?.channels.hud||c.publicationVersion!==1)){const p=entry?entry.ready.data.packet:packet(c,e);require('./loop-hud').publish(controller,p.status,p.breakReason,{publicationId:entry?.ready.publicationId,iteration:p.iteration,cost:p.cost,silent:true});} else require('./loop-hud').publish(controller,'running'); } return{enqueue,flush,initial,summary:()=>summary(checkpoint.get())}; } module.exports={create,summary,verify,packet};