// 실행 소유자의 명시 승인을 checkpoint에 원자 게시한다. 효과를 실행하는 API와 분리한다. // 설명 문서: docs/specs/batch-step-continuation.md (v0.20.0, R67 진행 중) const {randomUUID}=require('crypto'),db=require('../../knowledge-db'),{hash,hex}=require('./bong-browser-resolution'); const owners=require('./batch-run-lease'),locks=require('../db/reviewed-store-lock'),scopePolicy=require('./mcp-project-scope'),record=require('../db/batch-recovery-record'),proof=require('./batch-recovery-proof'); const fail=code=>Object.assign(Error(code),{code,retryable:false}); const raw=row=>{const {usage,...value}=row;return value;}; function inspect(runId,{heldFingerprint,workspaceHeld=false}={}){ if(typeof runId!=='string'||!/^[-\w]{1,160}$/.test(runId))throw fail('BATCH_CONTINUATION_DENIED'); const row=db.getBatchRun(runId),checkpoint=db.getBatchCheckpoint(runId);if(!row||!checkpoint)throw fail('BATCH_CONTINUATION_BLOCKED'); const c=checkpoint,task=db.getBatchTasks(c.projectId).find(t=>t.id===c.taskId); const expectedLog=require('path').join(require('../config/cli-paths').getCliHomeFilePath('batch-logs'),String(c.taskId).replace(/[^a-zA-Z0-9_-]/g,'_')+'-'+runId+'.log'); const schedule=require('./batch-scheduled-origin'),scheduleState=c.scheduled&&task?schedule.review(c,task):null,workspaceState=require('./batch-workspace-proof').review(c,{workspaceHeld}); // 프로필 조회가 없는 원래 폴더를 준비하는 부수 효과보다 먼저 격리 신원을 확인한다. const context=require('./batch-recovery-context').capture(c.workDir); // 원래 controller/예약 occurrence를 대사한다. 격리 폴더는 별도 근거 없이 복원하지 않는다. if(!['failed','aborted','paused'].includes(row.status)||c.revocations||row.log_path!==expectedLog||!task||!hex(c.admissionHash)||!hex(c.contextHash)||c.admissionHash!==hash(require('./batch-admission').signature(schedule.originalTask(c,task)))||c.contextHash!==context)throw fail('BATCH_CONTINUATION_BLOCKED'); const tree=require('./workflow-invocation-tree').inspect(db,runId,c.projectId,{heldRunId:runId,heldFingerprint}),parent=tree.runs.get(runId),browser=require('./bong-browser-lifecycle').inspectRun(runId,c.projectId),workspace=require('../utils/workspace-file-lock').inspect(c.workDir); if(require('./bong-browser-lifecycle').unsafe(browser)||workspace.ownerState!=='released'&&!workspaceHeld)throw fail('BATCH_CONTINUATION_BLOCKED'); if(Object.keys(parent.memoryContinuations||{}).length)require('./batch-memory-continue-history').prefix(db,parent); const loopState=require('./batch-loop-resume').inspect(db,parent,tree),iteration=require('./batch-loop-first').isFirst(loopState)?1:loopState?c.loopEvents[loopState.eventKey].iteration:0,relevant=parent.entries.filter(e=>e.iteration===iteration); const outputs={};let nextIndex=0,resolved=null; for(const [index,e]of relevant.entries()){ if(e.stepIndex!==nextIndex)throw fail('BATCH_CONTINUATION_BLOCKED'); const prior=require('./batch-step-output').resolved(c,e.key,parent.memoryContinuations); if(e.status==='completed'||prior){outputs[e.stepId]=prior?prior.output:e.output;nextIndex++;continue;} const following=relevant[index+1],step=parent.steps[e.stepIndex]; if(e.status==='failed'&&following?.stepIndex===e.stepIndex&&following.attempt===e.attempt+1&&step.on_failure==='retry'&&following.attempt<=(step.retry_count||3)&&!require('../db/batch-continued-record').uncertain(e.error))continue; if(e!==relevant.at(-1)||parent.steps[e.stepIndex]?.type!=='workflow')throw fail('BATCH_CONTINUATION_BLOCKED'); resolved=proof.childResolution(db,parent,e,tree);outputs[e.stepId]=resolved.output;nextIndex++; } const lock=locks.readLock(owners.file(c.taskId)); const base=hash([raw(row),c,parent.usage,task,context,browser,[...tree.runs].filter(([id])=>id!==runId).map(([id,v])=>[id,v.row,v.tasks,v.usage,v.lock?.fingerprint||null]),outputs,nextIndex,loopState,parent.memoryContinuations,scheduleState,workspaceState]); return{row:raw(row),checkpoint:c,task,parent,tree,browser,workspace,lock,outputs,nextIndex,resolved,loopState,iteration,scheduleState,workspaceState,base,fingerprint:hash([base,lock?.fingerprint||null,workspace])}; } function receipt(state){ const c=state.checkpoint,u=state.parent.usage,entries=u.usage.entries||[],requests=u.requests||{},invocations=u.workflowInvocations||{}; const body={version:1,id:randomUUID(),runId:c.runId,checkpointHash:hash(c),checkpointRevision:c.revision,checkpointCurrentKey:c.currentKey,entryKeys:Object.keys(c.entries),priorRecoveryKeys:Object.keys(c.recoveries||{}),originalRun:state.row, taskHash:c.admissionHash,contextHash:c.contextHash,usageHash:hash({entries,requests,invocations}),usageIds:entries.map(e=>e.id),requestKeys:Object.keys(requests),invocationKeys:Object.keys(invocations),position:{stepIndex:state.nextIndex,iteration:state.iteration},resolved:state.resolved,...(state.scheduleState?{scheduleState:state.scheduleState}:{}),...(state.workspaceState?{workspaceState:state.workspaceState}:{}),...(Object.keys(state.parent.memoryContinuations||{}).length?{memoryContinuations:state.parent.memoryContinuations,originalTask:structuredClone(require('./batch-scheduled-origin').originalTask(c,state.task))}:{}),...(state.loopState?{loopState:state.loopState}:{}),reviewedAt:new Date().toISOString(),reviewFingerprint:state.fingerprint,operator:'approved_owner'}; return{...body,approvalHash:hash(body)}; } function prepared(runId,fingerprint,options){ const state=inspect(runId,options),c=state.checkpoint,g=Object.values(c.recoveries||{}).at(-1); if(state.row.status!=='paused'||!g||fingerprint!==g.approvalHash||state.resolved||c.revision!==g.checkpointRevision+1||Object.keys(c.entries).length!==g.entryKeys.length||state.nextIndex!==g.position.stepIndex||state.iteration!==g.position.iteration||!record.same(state.loopState,g.loopState||null)||!record.same(state.scheduleState,g.scheduleState||null)||!record.same(state.workspaceState,g.workspaceState||null) ||(state.parent.usage.usage.entries||[]).length!==g.usageIds.length||Object.keys(state.parent.usage.requests||{}).length!==g.requestKeys.length||Object.keys(state.parent.usage.workflowInvocations||{}).length!==g.invocationKeys.length ||!record.same(state.row,{...g.originalRun,status:'paused',error_message:null,completed_at:null}))throw fail('BATCH_CONTINUATION_CHANGED'); return state; } function create({owner,scope,authorize,approve}={}){ if(!owner||!scope||typeof authorize!=='function'||typeof approve!=='function')throw fail('BATCH_CONTINUATION_DENIED'); const captured=Object.freeze({...scope}),tickets=new Map();let committing=0; function guard(caller,signal){if(signal?.aborted)throw fail('BATCH_CONTINUATION_CANCELLED');try{if(caller!==owner||authorize()!==true)throw Error();scopePolicy.authorize(captured,'batch',{});}catch{throw fail('BATCH_CONTINUATION_DENIED');}} function snapshot(runId,caller,signal,heldFingerprint){guard(caller,signal);const c=db.getBatchCheckpoint(runId);if(!c)throw fail('BATCH_CONTINUATION_BLOCKED');scopePolicy.checkProject(captured,c.projectId);const s=inspect(runId,{heldFingerprint});require('./batch-workspace-proof').checkScope(captured,s.checkpoint);if(s.row.status==='paused')throw fail('BATCH_CONTINUATION_CHANGED');return s;} return Object.freeze({ ...require('./batch-revocation').create({owner,scope:captured,authorize,approve}), verifyMemoryContinue(runId,{owner:caller,signal}={}){ guard(caller,signal);return db.runInTransaction(()=>{ const c=db.getBatchCheckpoint(runId);if(!c)throw fail('BATCH_CONTINUATION_BLOCKED');require('./batch-workspace-proof').checkScope(captured,c); const value=require('./batch-memory-continue-proof').verify(db,runId);guard(caller,signal); return Object.freeze({runId,kind:'memory_continue',verifiedOutputs:Object.keys(value.records).length,goalEvidenceCount:value.goalEvidenceCount,steps:Object.freeze(Object.values(value.records).map(r=>Object.freeze({stepId:c.entries[r.entryKey].stepId,outputHash:r.outputHash,durationSource:r.durationSource,consumptionKinds:Object.freeze(r.consumers.map(v=>v.kind))}))),fingerprint:value.fingerprint,candidateConsumptionVerified:true,canResume:false,ancestryCertified:false,controllerOutcomeCertified:false}); }); }, verifyLoopOutcome(runId,{owner:caller,signal}={}){ guard(caller,signal);return db.runInTransaction(()=>{const c=db.getBatchCheckpoint(runId);if(!c)throw fail('BATCH_CONTINUATION_BLOCKED');require('./batch-workspace-proof').checkScope(captured,c); const event=Object.values(c.loopEvents||{}).at(-1),proof=require('./batch-loop-observation-proof').verify(db,runId,event?.key);guard(caller,signal); const result=proof.controllerReconstruction?.result; return Object.freeze({runId,phase:event.phase,kind:proof.kind,...(proof.kind==='evaluation'?{goalMet:proof.goalMet,verifiedGoals:proof.verifiedGoals}:proof.kind==='analysis'?{verifiedRequests:proof.verifiedRequests,metaHash:require('./bong-browser-resolution').hash(proof.meta)}:{verifiedSettlements:1}),controllerTransitionVerified:proof.controllerTransitionVerified===true,...(result?{decision:{shouldTerminate:result.shouldTerminate,reason:result.reason,breakReason:result.breakReason||null,iteration:result.iteration}}:{}),fingerprint:proof.fingerprint,canResume:false,controllerOutcomeCertified:false}); }); }, preview(runId,{owner:caller,signal}={}){ guard(caller,signal);for(const[k,v]of tickets)if(Date.now()-v.createdAt>120000)tickets.delete(k);if(tickets.size+committing>=32)throw fail('BATCH_CONTINUATION_LIMIT'); const s=db.runInTransaction(()=>snapshot(runId,caller,signal)),ticketId=randomUUID(),review=Object.freeze({runId,taskId:s.checkpoint.taskId,completedStepIds:Object.freeze(Object.keys(s.outputs)),remainingStepIds:Object.freeze(s.parent.steps.slice(s.nextIndex).map(e=>e.id)),costUsd:s.parent.usage.usage.costUsd,fingerprint:s.fingerprint,memoryContinueStepIds:Object.freeze(require('./batch-step-output').memorySteps(s.checkpoint,s.parent.memoryContinuations)),...(s.workspaceState?{workspace:require('./batch-workspace-proof').workspace(s.checkpoint.workspaceOrigin)}:{}),...(s.scheduleState?{scheduledOccurrence:require('./batch-scheduled-origin').summary(s.checkpoint,s.task)}:{}),...(s.loopState?{loopRunId:s.loopState.originalRun.run_id,iteration:s.iteration,...(s.loopState.reconciliation?.kind==='unstarted_first_iteration'?{reconciledFirstIteration:true,archivedFirstRow:s.loopState.originalIterations.length===1}:s.loopState.reconciliation?.kind==='unstarted_iteration'?{reconciledGhostIteration:true,ghostIteration:s.iteration+1}:s.loopState.reconciliation?{reconciledLoopRows:true,...(s.loopState.reconciliation.kind==='partial_phase_closure'?{reconciledLoopPhase:s.loopState.reconstruction?.phase||s.checkpoint.loopEvents[s.loopState.eventKey].phase}:{})}:{}),loopPublications:require('./batch-loop-outbox').summary(s.checkpoint),...(s.loopState.reconstruction?{reconstructedPhase:true,sourcePhase:s.checkpoint.loopEvents[s.loopState.eventKey].phase,reconstructedPhaseName:({evaluation_intent:'목표 평가',analysis_intent:'메타 분석',settlement_intent:'회차 정산'})[s.checkpoint.loopEvents[s.loopState.eventKey].phase]}:{} )}:{}),...(s.resolved?{recoveredChildId:s.resolved.childRunId,recoveredOutputHash:s.resolved.outputHash,durationReconstructed:true}:{})}); tickets.set(ticketId,{review,createdAt:Date.now()});return Object.freeze({ticketId,...review}); }, async commit(ticketId,{owner:caller,confirmed,signal}={}){ guard(caller,signal);const ticket=tickets.get(ticketId);if(!ticket||Date.now()-ticket.createdAt>120000)throw fail('BATCH_CONTINUATION_CHANGED');if(confirmed!==true)throw fail('BATCH_CONTINUATION_DENIED');tickets.delete(ticketId);committing++; let claim; try{ const before=db.runInTransaction(()=>snapshot(ticket.review.runId,caller,signal));if(before.fingerprint!==ticket.review.fingerprint)throw fail('BATCH_CONTINUATION_CHANGED'); const approved=await approve(Object.freeze({...ticket.review,signal}));guard(caller,signal);if(approved?.approved!==true)throw fail('BATCH_CONTINUATION_DENIED'); const current=db.runInTransaction(()=>snapshot(ticket.review.runId,caller,signal));if(current.fingerprint!==before.fingerprint)throw fail('BATCH_CONTINUATION_CHANGED'); claim=owners.claimReview(current.checkpoint.taskId,current.lock,current.row.run_id);const heldFingerprint=locks.readLock(owners.file(current.checkpoint.taskId)).fingerprint; const grant=require('./batch-scheduled-origin').locked(current.checkpoint,()=>db.runInTransaction(()=>{ const checked=snapshot(current.row.run_id,caller,signal,heldFingerprint);if(checked.base!==current.base)throw fail('BATCH_CONTINUATION_CHANGED'); const g=receipt(current),next=structuredClone(current.checkpoint);next.recoveries={...next.recoveries,[g.id]:g};next.revision++; db.transitionBatchRun(current.row.run_id,current.row,'paused');db.saveBatchCheckpoint(next,current.checkpoint.revision,actual=>record.same(actual,g)); prepared(current.row.run_id,g.approvalHash,{heldFingerprint});return g; },{mode:'immediate'})); return Object.freeze({runId:current.row.run_id,status:'paused',fingerprint:grant.approvalHash,remainingStepIds:ticket.review.remainingStepIds}); }finally{claim?.preserve();committing--;} } }); } module.exports={create,prepared,raw};