openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 26 kB
JavaScript
import{r as e}from"./openclaw-state-read-semver-CqfGj9gv.mjs";import{v as t}from"./openclaw-state-read-home-dir-BQZX1pD2.mjs";import"./openclaw-state-read-tmp-openclaw-dir-C3Ynn93H.mjs";import"./openclaw-state-read-logger-Ix7jXPG1.mjs";import{_ as n,a as r,b as i,c as a,f as o,g as s,h as c,l,n as u,o as d,p as f,s as ee,v as te,x as p,y as m}from"./openclaw-state-read-schemas-CLrAtqTl.mjs";import{a as h,r as g}from"./openclaw-state-read-kysely-sync-DQyYiAw5.mjs";import{a as ne}from"./openclaw-state-read-sqlite-transaction-V1rK3HH2.mjs";import{o as _}from"./openclaw-state-read-openclaw-state-db-schema-helpers-BkqUYEFY.mjs";import"./openclaw-state-read-openclaw-state-db-readonly-CDG18cNK.mjs";import"./openclaw-state-read-sqlite-handle-lifecycle-DQ13SM2U.mjs";import"./openclaw-state-read-boundary-path-CCynIYBo.mjs";import"./openclaw-state-read.worker.js";import{t as re}from"./openclaw-state-read-openclaw-state-feature-schema-BPVIIoAx.mjs";import"./openclaw-state-read-openclaw-state-db-existing-write-BFFt_1Yy.mjs";import"./openclaw-state-read-config-machine-state-write-CU2Cxsvy.mjs";import{n as v,t as ie}from"./openclaw-state-read-update-run-recovery-keys-DvrupUfL.mjs";import"node:fs";import y from"node:path";import"node:os";import"node:crypto";import{AsyncLocalStorage as ae}from"node:async_hooks";import{isDeepStrictEqual as b}from"node:util";const x=m([l(`npm`),l(`archive`),l(`path`),l(`clawhub`),l(`git`)]),S={source:x,spec:n().optional(),sourcePath:n().optional(),installPath:n().optional(),version:n().optional(),resolvedName:n().optional(),resolvedVersion:n().optional(),resolvedSpec:n().optional(),integrity:n().optional(),shasum:n().optional(),resolvedAt:n().optional(),installedAt:n().optional(),clawhubUrl:n().optional(),clawhubPackage:n().optional(),clawhubFamily:m([l(`code-plugin`),l(`bundle-plugin`)]).optional(),clawhubChannel:m([l(`official`),l(`community`),l(`private`)]).optional(),clawhubTrustDisposition:m([l(`clean`),l(`review-recommended`),l(`review-required`),l(`blocked`)]).optional(),clawhubTrustScanStatus:n().optional(),clawhubTrustModerationState:n().optional(),clawhubTrustReasons:r(n()).optional(),clawhubTrustPending:d().optional(),clawhubTrustStale:d().optional(),clawhubTrustCheckedAt:n().optional(),clawhubTrustAcknowledgedAt:n().optional(),artifactKind:m([l(`legacy-zip`),l(`npm-pack`)]).optional(),artifactFormat:m([l(`zip`),l(`tgz`)]).optional(),npmIntegrity:n().optional(),npmShasum:n().optional(),npmTarballName:n().optional(),clawpackSha256:n().optional(),clawpackSpecVersion:o().int().nonnegative().optional(),clawpackManifestSha256:n().optional(),clawpackSize:o().int().nonnegative().optional(),gitUrl:n().optional(),gitRef:n().optional(),gitCommit:n().optional()};f(S);const oe=s({contentDigest:n().regex(/^[a-f0-9]{64}$/),dependencyClosureDigest:n().regex(/^[a-f0-9]{64}$/)}),se=c(n(),i()),ce=ee(e=>se.safeParse(e).success).transform(e=>Object.entries(e)).pipe(r(te([n().min(1),oe]))).transform(e=>Object.fromEntries(e)),le=f({...S,source:m([x,l(`marketplace`)]),contextEngineIdsByPlugin:c(n().min(1),r(n().min(1))).optional(),marketplaceName:n().optional(),marketplaceSource:n().optional(),marketplacePlugin:n().optional(),acceptedSurface:s({channels:r(n().min(1)),providers:r(n().min(1)),tools:r(n().min(1)),contracts:r(n().min(1)),hooks:r(n().min(1)),mcpServers:r(n().min(1)),cliCommands:r(n().min(1)),cliBackends:r(n().min(1)),skills:r(n().min(1)),dangerousConfigFlags:r(n().min(1))}).optional(),acceptedSurfaceHash:n().optional(),acceptedSurfaceAt:n().optional(),acceptedSurfaceIntegrity:n().optional(),sourceSnapshotDigests:ce.optional()});f({artifact:f({path:n()})}),s({formatVersion:o().int().positive(),generation:n().min(1),installedRevision:o().int().nonnegative(),installRecordHash:n().min(1),packageIntegrity:n().min(1).optional(),contentDigest:n().min(1),dependencyClosureDigest:n().min(1),buildResolutionDigest:n().min(1),platform:n().min(1),arch:n().min(1),abi:n().min(1),artifact:s({path:n().min(1),identity:n().min(1),manifestIdentity:n().min(1),manifestDigest:n().min(1),tokenIdentity:n().min(1)})});const ue=s({installOwner:n().min(1).optional(),rootDir:n().min(1),installRecordHash:n().min(1).optional(),sourceSnapshot:i().optional(),sourceSnapshotWarning:s({artifactPath:n(),message:n()}).optional()}),de=s({pluginId:n().min(1),before:ue.nullable(),after:ue.nullable()}),C=`update.pluginCohort.`,w=1048576,T=n().min(1).max(32768),E=T.refine(e=>y.isAbsolute(e)),D=o().int().nonnegative().max(2**53-1),O=s({realPath:E,dev:n().regex(/^\d+$/u),ino:n().regex(/^\d+$/u),manifestSha256:n().regex(/^[a-f0-9]{64}$/u)}),fe=O.extend({manifestSha256:O.shape.manifestSha256.nullable()}),k=le.passthrough(),pe=s({targetPath:E,entries:r(a(`kind`,[s({path:E,kind:l(`missing-directory`)}),s({path:E,kind:l(`existing`),dev:T,ino:T,link:T.optional()})])).max(1024)}),me=s({rootConfigPath:E,filePath:E,targetPath:E,pathSnapshot:pe,beforeRaw:n().max(w).nullable(),afterRaw:n().max(w),include:s({boundaryPath:r(T).min(1).max(256),includePath:E}).optional()}).refine(e=>e.targetPath===e.pathSnapshot.targetPath&&(e.include?e.filePath===e.include.includePath:e.filePath===e.rootConfigPath),{message:`Plugin cohort configuration publication target differs from its owning path`}),A=s({startedAt:D,finishedAt:D.nullable(),status:u([`pending`,`completed`,`superseded`,`deferred`]),reportJson:n().max(w)}),he=s({kind:l(`plugin-migrations`),rows:r(s({pluginId:T,before:A.optional(),after:A})).max(4096).refine(e=>new Set(e.map(e=>e.pluginId)).size===e.length,{message:`Plugin migration publication repeats an owner`})}),ge=s({runId:p(),transactionId:p(),revision:D,disposition:u([`pending`,`commit`,`rollback`]),installKey:E,priorArtifacts:r(s({pluginId:T,packageDir:E,identity:fe.nullable(),record:k.optional(),markerBefore:n().max(w).nullable(),markerAfter:n().max(w).nullable()}).refine(e=>e.identity!==null||e.record?.source===`npm`&&e.record.installPath===e.packageDir&&e.markerBefore===null&&e.markerAfter===null,{message:`Absent plugin cohort payload must retain its matching record without markers`})).max(4096),artifacts:r(s({pluginId:T,packageName:T,targetNpmRoot:E,targetPackageDir:E,stagedIdentity:O,identity:O.optional(),markerAfter:n().max(w).nullable().optional()})).max(4096),publications:r(a(`kind`,[s({kind:l(`records`),sourceSnapshots:r(de).max(4096).optional(),records:r(s({pluginId:T,before:k.optional(),after:k.optional()})).max(4096)}),s({kind:l(`config`),file:me}),he])).max(4096),settledPublications:D}).refine(e=>e.settledPublications<=e.publications.length,{message:`Plugin cohort settlement exceeds its publications`});s({runId:p(),transactionId:p(),installKey:E});function assertPluginCohortReservation(e){if(!e.source)throw Error(`Plugin cohort reservation requires its original state source`);let t=/* @__PURE__ */ new Set([`runId`,`transactionId`,`revision`,`claimId`,`claimKind`,`handoff`,`source`,`from`,`to`,`createdAtMs`,`updatedAtMs`,`effects`,`restore`,`verification`,`primaryFailure`]);if(Object.keys(e).some(e=>!t.has(e))||e.effects.length!==0||e.handoff!==null||e.restore!==null||e.verification!==null||e.primaryFailure!==null)throw Error(`Plugin cohort reservation contains full-state recovery`)}function decodePluginCohortRecovery(e,t){if(Buffer.byteLength(e)>w)throw Error(`Plugin cohort recovery exceeds its storage limit`);let n=ge.parse(JSON.parse(e));if(n.runId!==t)throw Error(`Plugin cohort recovery does not match its history run`);return n}function assertPluginCohortRecoveryBinding(e){if(assertPluginCohortReservation(e.reservation),e.reservation.runId!==e.cohort.runId||e.reservation.transactionId!==e.cohort.transactionId)throw Error(`Plugin cohort recovery does not match its reservation`)}t(Symbol.for(`openclaw.pluginInstallRootContext`),()=>new ae);const j=n().min(1).max(4096),M=j.refine(e=>y.isAbsolute(e)),N=o().int().nonnegative().max(2**53-1),P={runId:p(),stateDir:M,configPath:M,profile:n().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/iu).nullable()},F=s({...P,platform:l(`linux`),scope:u([`user`,`system`]),unitName:j}),_e=a(`platform`,[s({...P,platform:l(`win32`),taskName:j}),s({...P,platform:l(`darwin`),domain:j,label:j}),a(`scope`,[F.extend({scope:l(`user`),uid:N}),F.extend({scope:l(`system`)})])]),I=s({exists:d(),enabled:d().nullable(),loaded:d(),stopped:d()}).refine(e=>e.exists?e.enabled!==null&&(e.loaded||e.stopped):e.enabled===null&&!e.loaded&&e.stopped),ve=u([`suppress`,`stop`,`restore`,`enable-for-start`]),ye=s({effectId:p(),action:ve,before:I,after:I,state:u([`intent`,`observed`,`not-applied`,`reconciled`]),reconciledStop:s({facts:I,revision:N}).optional(),intentRevision:N,observedRevision:N.optional()}),be=s({identity:_e,original:I,boundAtRevision:N,effects:r(ye).max(128)}).superRefine((e,t)=>{let n=e.boundAtRevision,r=/* @__PURE__ */ new Set,i=e.original;for(let[a,o]of e.effects.entries())(!b(o.before,i)||r.has(o.effectId)||o.state===`not-applied`&&b(o.before,o.after)||o.intentRevision<=n||(o.state===`intent`?o.observedRevision!==void 0||a!==e.effects.length-1:o.state===`reconciled`?o.observedRevision!==void 0||!o.reconciledStop:o.observedRevision===void 0||o.observedRevision<=o.intentRevision)||o.reconciledStop!==void 0&&(o.state!==`reconciled`&&o.state!==`observed`||o.reconciledStop.revision<=(o.observedRevision??o.intentRevision)||e.identity.platform!==`linux`||o.action!==`suppress`||!o.before.exists||!o.before.loaded||o.before.enabled!==!0||o.before.stopped||!b(o.after,{...o.before,enabled:!1})||!b(o.reconciledStop.facts,{...o.after,stopped:!0}))||!validNativeTransition(o.action,o.before,o.after,e.original,e.identity.platform))&&t.addIssue({code:`custom`,message:`Invalid native manager effect history`}),r.add(o.effectId),i=o.reconciledStop?.facts??(o.state===`not-applied`?o.before:o.after),n=o.reconciledStop?.revision??o.observedRevision??o.intentRevision});function validNativeTransition(e,t,n,r,i){return e===`enable-for-start`?(i===`win32`||i===`darwin`)&&r.exists&&r.loaded&&!r.stopped&&r.enabled===!1&&t.exists&&t.stopped&&t.enabled===!1&&b(n,{...t,enabled:!0}):e===`restore`?!t.exists||!r.exists?b(n,r):b(n,{...t,enabled:r.enabled})||b(n,{...t,loaded:r.loaded,stopped:r.stopped}):!t.exists||!n.exists?b(t,n):e===`suppress`?n.enabled===!1&&t.loaded===n.loaded&&t.stopped===n.stopped:n.stopped&&n.enabled===t.enabled&&(!n.loaded||t.loaded)}function currentUpdateRecoveryNativeFacts(e){let t=e.effects.at(-1);return t?.reconciledStop?.facts??(t?.state===`not-applied`?t.before:t?.after??e.original)}function isRecoverablePreparationNative(e){let{original:t,effects:n}=e;if(n.length===0)return!0;let[r,i]=n;return t.exists&&t.enabled===!0&&t.loaded&&!t.stopped&&n.length===2&&r?.action===`stop`&&b(r.before,t)&&b(r.after,{...t,stopped:!0,loaded:e.identity.platform!==`darwin`})&&r.state===`observed`&&i?.action===`restore`&&i.state===`observed`&&b(i.before,r.after)&&b(i.after,t)}const L=n().min(1).max(32768),R=L.refine(e=>y.isAbsolute(e)&&y.resolve(e)===e),z=L.refine(e=>e!==`.`&&e!==`..`&&!/[\\/]/u.test(e)),B=s({digest:n().regex(/^[a-f0-9]{64}$/u),identity:n().regex(/^\d+:\d+$/u),version:L}),V=s({pairId:p(),ownerRevision:o().int().nonnegative().max(2**53-1)}),xe=a(`state`,[V.extend({state:l(`selected`)}),s({state:l(`unselected`),ownerRevision:V.shape.ownerRevision}),V.extend({state:l(`superseded`),replacement:s({pairId:p(),transactionId:p(),live:B,retainedRoot:R,retained:B,launchers:r(s({name:z,fingerprint:L})).max(64)})})]),H=s({version:l(1),transactionId:p(),packageName:n().regex(/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/iu).max(214),liveRoot:R,stageRoot:R,backupRoot:R,binDir:R,shimBackupRoot:R.nullable(),shimBackupIdentity:L.nullable(),previous:B.nullable(),candidate:B,launchers:r(s({name:z,previous:L.nullable(),candidate:L})).max(64),interruptedLaunchers:r(z).max(64),retention:xe.nullable()}).superRefine((e,t)=>{let n=y.resolve(e.liveRoot,...e.packageName.split(`/`).map(()=>`..`));(e.liveRoot===y.parse(e.liveRoot).root||e.stageRoot===y.parse(e.stageRoot).root||e.binDir===y.parse(e.binDir).root||y.join(n,e.packageName)!==e.liveRoot||e.packageName===`.`||e.packageName===`..`||e.shimBackupRoot===null!=(e.shimBackupIdentity===null)||y.dirname(e.backupRoot)!==n||!y.basename(e.backupRoot).startsWith(`.openclaw.package-backup-`)||e.stageRoot===e.liveRoot||e.stageRoot.startsWith(`${e.liveRoot}${y.sep}`)||e.liveRoot.startsWith(`${e.stageRoot}${y.sep}`)||e.shimBackupRoot!==null&&(y.dirname(e.shimBackupRoot)!==n||!y.basename(e.shimBackupRoot).startsWith(`.openclaw.shim-backup-`))||e.launchers.some(t=>t.previous!==null&&!e.shimBackupRoot)||e.interruptedLaunchers.some(t=>!e.launchers.some(e=>e.name===t))||new Set(e.launchers.map(e=>e.name)).size!==e.launchers.length)&&t.addIssue({code:`custom`,message:`Invalid package recovery paths or launcher inventory`})}),Se=s({effectId:p(),action:u([`activate`,`restore`,`retire`]),descriptor:H}),U=s({status:l(`verified`),descriptor:H,observation:s({previous:u([`live`,`retained`,`absent`]),candidate:u([`live`,`staged`,`displaced`,`absent`]),launchers:u([`previous`,`candidate`,`both`,`mixed`,`interrupted`]),successorLive:d()}),observedIdentity:n().regex(/^[a-f0-9]{64}$/u)}),Ce=s({descriptor:H,observed:U}),we=s({intent:Se,observed:U.optional(),outcome:u([`completed`,`interrupted`]).optional()}),W=n().min(1).max(32768),G=W.refine(e=>y.isAbsolute(e)),K=o().int().nonnegative().max(2**53-1),q=s({root:G,nodePath:G,version:W,buildId:W.nullable()}),J=s({kind:l(`readiness`,{error:`Legacy update verification is not readiness evidence; explicit reconciliation is required.`}),runId:p(),transactionId:p(),claimId:p(),revision:K,effectId:p(),runtime:u([`candidate`,`previous`]),gateway:s({bootId:n().min(1).max(96),version:n().min(1).max(256),buildId:n().min(1).max(256).nullable()}),checks:s({serviceRunning:l(!0),pluginsReady:l(!0),channelsReady:l(!0),settled:l(!0),readyz:l(!0)}),verifiedAtMs:K}),Te=s({effectId:p(),kind:u([`package-activation`,`runtime-mutation`,`checkpoint-restore`,`package-restore`,`service-restart`,`retirement`]),resourceId:W,runtime:u([`candidate`,`previous`]),state:u([`intent`,`observed`,`cancelled`]),cancelledByNativeEffectId:p().optional(),package:we.optional(),observedIdentity:W.nullable()}).refine(e=>e.state===`observed`==(e.observedIdentity!==null)&&(e.state===`cancelled`?e.kind===`service-restart`&&!e.package&&e.cancelledByNativeEffectId!==void 0:e.cancelledByNativeEffectId===void 0)),Ee=s({restoreId:p(),checkpointId:p(),planPath:G,planSha256:n().regex(/^[a-f0-9]{64}$/u).nullable(),resourceCursor:K,phase:u([`preparing`,`intent`,`observed`])}).refine(e=>e.phase===`preparing`||e.planSha256!==null),Y=s({checkpointId:p(),manifestPath:G,manifestSha256:n().regex(/^[a-f0-9]{64}$/u)}),X=s({ref:Y,preimageRef:Y.optional(),binding:s({runId:p(),stateDir:G,configPath:G,fromRuntime:q.omit({buildId:!0})})}),De=s({checkpointRef:Y,afterUpdate:X,effectIds:r(p()).min(1).max(4096),boundAtRevision:K}),Z=n().min(1).max(256),Oe=s({entryId:Z,seq:K}),ke=s({runId:p(),gateway:J.shape.gateway,agentId:Z,sessionKey:n().min(1).max(512),sessionId:Z,agentRunId:p(),transcript:s({generation:Z,maxSeq:K,user:Oe,assistant:Oe}),verifiedAtMs:K}).refine(e=>e.transcript.user.seq<e.transcript.assistant.seq&&e.transcript.assistant.seq<=e.transcript.maxSeq,{message:`Invalid legacy serving transcript sequence`}),Ae=m([J,ke]),Q=s({runId:p(),transactionId:p(),revision:K,claimId:p(),claimKind:u([`initial`,`recovery`,`handoff`]),handoff:s({handoffId:p(),state:u([`prepared`,`accepted`])}).nullable(),source:s({stateDir:G,configPath:G,profile:W.nullable().optional()}).optional(),from:q,to:q,createdAtMs:K,updatedAtMs:K,effects:r(Te).max(4096),preimages:X.omit({preimageRef:!0}).extend({boundAtRevision:K}).optional(),nativeManager:be.optional(),checkpoint:X.optional(),afterImages:r(De).max(4096).optional(),restore:Ee.nullable().default(null),publication:s({revision:K,sha256:n().regex(/^[a-f0-9]{64}$/u)}).optional(),verification:s({runtime:u([`candidate`,`previous`]),effectId:p(),receipt:Ae}).nullable(),package:Ce.optional(),terminal:s({status:u([`succeeded`,`rolled-back`]),committedAtMs:K,commitRevision:K,receipt:Ae,pairId:p().nullable()}).optional(),preparationAborted:s({reason:l(`interrupted-preparation`),committedAtMs:K,commitRevision:K,observedIdentity:n().regex(/^[a-f0-9]{64}$/u)}).optional(),retainedPair:s({pairId:p(),state:u([`selected`,`superseded`]),replacementRunId:p().optional()}).optional(),primaryFailure:s({code:W,effectId:p().nullable()}).nullable()}).superRefine((e,t)=>{let reportIssue=e=>t.addIssue({code:`custom`,message:e}),n=e.preparationAborted;n&&(!e.source||!e.preimages||!e.nativeManager||!e.package||e.claimKind!==`recovery`||e.effects.length!==0||!isRecoverablePreparationNative(e.nativeManager)||e.handoff||e.checkpoint||e.afterImages!==void 0||e.restore||e.publication||e.verification||e.terminal||e.retainedPair||e.primaryFailure?.code!==n.reason||e.primaryFailure.effectId!==null||n.commitRevision!==e.revision||n.committedAtMs>e.updatedAtMs||n.observedIdentity!==e.package.observed.observedIdentity||e.package.descriptor.retention!==null||e.package.descriptor.interruptedLaunchers.length!==0||e.package.observed.observation.previous!==`live`||e.package.observed.observation.candidate!==`staged`||![`previous`,`both`].includes(e.package.observed.observation.launchers)||e.package.observed.observation.successorLive)&&reportIssue(`Preparation settlement cannot carry effects or serving authority`);let r=e.verification;if(r){let t=r.receipt,n=r.runtime===`candidate`?e.to:e.from,i=e.effects.find(e=>e.effectId===r.effectId);(t.runId!==e.runId||`kind`in t&&(t.transactionId!==e.transactionId||t.claimId!==e.claimId||t.revision>=e.revision||t.runtime!==r.runtime||t.effectId!==r.effectId)||t.gateway.version!==n.version||t.gateway.buildId!==n.buildId||i?.kind!==`service-restart`||i.state!==`observed`||i.runtime!==r.runtime||i.observedIdentity!==t.gateway.bootId||!e.terminal&&i!==e.effects.at(-1))&&reportIssue(`Verification evidence does not match recovery and restart`)}r&&e.terminal&&!b(r.receipt,e.terminal.receipt)&&reportIssue(`Terminal and verification receipts differ`);let i=e.nativeManager,a=i?currentUpdateRecoveryNativeFacts(i):void 0;i&&(!e.preimages||!e.source||i.identity.runId!==e.runId||i.identity.stateDir!==e.source.stateDir||i.identity.configPath!==e.source.configPath||i.identity.profile!==e.source.profile||i.boundAtRevision>e.revision||!e.primaryFailure&&i.effects.some(e=>e.state===`not-applied`||e.state===`reconciled`)||i.effects.some((t,n)=>{if(!t.reconciledStop)return!1;let r=i.effects[n-1],a=e.effects.find(e=>e.effectId===r?.effectId);return!e.primaryFailure||!e.checkpoint||!r||r.action!==`restore`||r.state!==`observed`||!r.before.stopped||r.after.stopped||a?.kind!==`service-restart`||a.runtime!==`candidate`})||i.effects.some(t=>(t.reconciledStop?.revision??t.observedRevision??t.intentRevision)>e.revision)||i.effects.at(-1)?.state===`intent`&&(e.terminal||e.verification)||!a?.stopped&&e.effects.some(e=>e.state===`intent`&&(e.kind===`package-activation`||e.kind===`runtime-mutation`||e.kind===`package-restore`||e.kind===`checkpoint-restore`))||e.terminal&&a&&!b(a,i.original))&&reportIssue(`Native manager evidence must match admitted source and revision`);let o=e.preimages;(o&&(o.boundAtRevision>e.revision||!e.source||o.binding.runId!==e.runId||o.binding.stateDir!==e.source.stateDir||o.binding.configPath!==e.source.configPath||o.binding.fromRuntime.root!==e.from.root||o.binding.fromRuntime.nodePath!==e.from.nodePath||o.binding.fromRuntime.version!==e.from.version)||e.checkpoint&&(o&&(!b(e.checkpoint.preimageRef,o.ref)||!b(e.checkpoint.binding,o.binding)||e.checkpoint.ref.checkpointId===o.ref.checkpointId||e.checkpoint.ref.manifestPath===o.ref.manifestPath||e.checkpoint.ref.manifestSha256===o.ref.manifestSha256)||!o&&e.checkpoint.preimageRef))&&reportIssue(`Early file preimages must remain distinct from the full checkpoint`),e.package&&e.package.descriptor.transactionId!==e.transactionId&&reportIssue(`Package transaction differs from recovery`);for(let t of e.effects){if(t.state===`cancelled`){let n=i?.effects.findIndex(e=>e.effectId===t.effectId)??-1,r=i?.effects.findIndex(e=>e.effectId===t.cancelledByNativeEffectId)??-1,a=i?.effects[n],o=i?.effects[r],s=r===n&&o?.state===`not-applied`&&o.before.stopped,c=r>n&&o?.action===`stop`&&o.state===`observed`&&o.after.stopped;e.primaryFailure&&a&&a.action===`restore`&&a.before.stopped&&!a.after.stopped&&(s||c)||reportIssue(`Cancelled restart requires resolved native quiescence`)}t.package&&(t.package.intent.effectId!==t.effectId||t.package.intent.descriptor.transactionId!==e.transactionId||t.state===`observed`!=!!(t.package.observed&&t.package.outcome)||t.package.observed&&t.observedIdentity!==t.package.observed.observedIdentity)&&reportIssue(`Invalid typed package effect`)}if(e.terminal&&(e.terminal.commitRevision>e.revision||e.terminal.receipt.runId!==e.runId||e.terminal.pairId!==(e.retainedPair?.pairId??null))&&reportIssue(`Terminal outcome and selected pair differ`),e.terminal){let t=e.terminal.receipt,n=e.terminal.status===`succeeded`?`candidate`:`previous`,i=n===`candidate`?e.to:e.from,a=`kind`in t?e.effects.find(e=>e.effectId===t.effectId):e.effects.findLast(e=>e.kind===`service-restart`);((`kind`in t?t.transactionId!==e.transactionId||t.runtime!==n||t.revision+2!==e.terminal.commitRevision||a?.kind!==`service-restart`||r&&!b(r.receipt,t):r&&(r.runtime!==n||r.effectId!==a?.effectId))||t.gateway.version!==i.version||t.gateway.buildId!==i.buildId||a?.state!==`observed`||a.runtime!==n||a.observedIdentity!==t.gateway.bootId)&&reportIssue(`kind`in t?`Terminal readiness does not match its recorded restart`:`Legacy terminal evidence differs from its recorded restart`)}let s=e.retainedPair,c=e.package?.descriptor.retention;(s&&(!e.terminal||e.terminal.status!==`succeeded`||!c||c.state===`unselected`||c.state!==s.state||c.pairId!==s.pairId||s.state===`superseded`!=!!s.replacementRunId)||e.terminal?.status===`succeeded`&&!s||e.terminal?.status===`rolled-back`&&(s||c?.state!==`unselected`))&&reportIssue(`Recovery selection does not match committed package roles`);let l=0,u=-1,d=e.checkpoint?[e.checkpoint.ref]:[];for(let[n,r]of(e.afterImages??[]).entries()){let i=e.effects.slice(l,l+r.effectIds.length);(!e.checkpoint||!b(r.checkpointRef,e.checkpoint.ref)||!b(r.afterUpdate.binding,e.checkpoint.binding)||r.boundAtRevision<=u||r.boundAtRevision>e.revision||!b(r.effectIds,i.map(e=>e.effectId))||i.some(e=>e.state!==`observed`||e.package?.outcome===`interrupted`||e.runtime!==`candidate`||e.kind===`checkpoint-restore`||e.kind===`package-restore`||e.kind===`retirement`)||d.some(e=>e.checkpointId===r.afterUpdate.ref.checkpointId||e.manifestPath===r.afterUpdate.ref.manifestPath||e.manifestSha256===r.afterUpdate.ref.manifestSha256))&&t.addIssue({code:`custom`,path:[`afterImages`,n],message:`After-image must bind a distinct checkpoint to the exact completed mutation interval`}),l+=r.effectIds.length,u=r.boundAtRevision,d.push(r.afterUpdate.ref)}}),je=Q.safeExtend({verification:Q.shape.verification.unwrap().extend({receipt:J}).nullable(),terminal:Q.shape.terminal.unwrap().extend({receipt:J}).optional()});function inspectUpdateRecovery(e,t){if(Buffer.byteLength(e)>$)throw Error(`Update recovery record exceeds its storage limit`);let n=Q.parse(JSON.parse(e));if(n.runId!==t)throw Error(`Update recovery record does not match its history run`);return{format:[n.verification?.receipt,n.terminal?.receipt].some(e=>e&&!(`kind`in e))?`legacy-serving`:`current`,raw:e,record:n}}const $=1048576;function decodeUpdateRecovery(e,t){if(Buffer.byteLength(e)>$)throw Error(`Update recovery record exceeds its storage limit`);let n=je.parse(JSON.parse(e));if(n.runId!==t)throw Error(`Update recovery record does not match its history run`);return n}function isUpdateRecoveryPending(e){return!e.preparationAborted&&(!e.terminal||e.restore!==null&&e.restore.phase!==`observed`||e.effects.some(e=>e.state===`intent`&&(e.kind!==`retirement`||e.package?.intent.action!==`retire`)))}var Me=/* @__PURE__ */ e({canCollectPluginSourceSnapshotsInDatabase:()=>canCollectPluginSourceSnapshotsInDatabase,inspectPluginCohortRecoveryRows:()=>inspectPluginCohortRecoveryRows,inspectRecoveryRows:()=>inspectRecoveryRows,readUpdateRecoveryAdmissionFacts:()=>readUpdateRecoveryAdmissionFacts});function readUpdateRecoveryAdmissionFacts(e){return ne(e,()=>({cohorts:inspectPluginCohortRecoveryRows(e),recoveries:inspectRecoveryRows(e)}))}function readRecoveryRows(e,t){if(!_(e,`config_machine_state`))return[];let n=h(e).selectFrom(`config_machine_state`).select([`state_key`,`value_json`]);return g(e,t===void 0?n.where(`state_key`,`>=`,v).where(`state_key`,`<`,ie).orderBy(`state_key`,`asc`):n.where(`state_key`,`=`,v+t)).rows}function inspectRecoveryRows(e){return readRecoveryRows(e).map(({value_json:e,state_key:t})=>inspectUpdateRecovery(e,t.slice(v.length)))}re(`config_machine_state`);function readPluginCohortPairRows(e,t){return _(e,`config_machine_state`)?g(e,h(e).selectFrom(`config_machine_state`).select([`state_key`,`value_json`,`updated_at_ms`]).where(`state_key`,`in`,[v+t,C+t])).rows:[]}function decodePluginCohortPair(e,t){let n=e.find(e=>e.state_key===v+t),r=e.find(e=>e.state_key===C+t);if(!n||!r)throw Error(`Plugin cohort recovery is missing its matching reservation`);let i={reservation:decodeUpdateRecovery(n.value_json,t),cohort:decodePluginCohortRecovery(r.value_json,t)};return assertPluginCohortRecoveryBinding(i),i}function canCollectPluginSourceSnapshotsInDatabase(e){return inspectPluginCohortRecoveryRows(e).length===0&&!inspectRecoveryRows(e).some(({record:e})=>isUpdateRecoveryPending(e))}function inspectPluginCohortRecoveryRows(e){return _(e,`config_machine_state`)?g(e,h(e).selectFrom(`config_machine_state`).select(`state_key`).where(`state_key`,`>=`,C).where(`state_key`,`<`,`update.pluginCohort/`).orderBy(`state_key`,`asc`)).rows.map(t=>{let n=t.state_key.slice(20);return decodePluginCohortPair(readPluginCohortPairRows(e,n),n)}):[]}export{Me as n,le as r,readUpdateRecoveryAdmissionFacts as t};