UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

38 lines • 46.4 kB
import{g as isLiveStateRead,h as isArtifactPreservingStateRead,i as readSqliteInspectionBudget,l as sqliteInspectionTimeoutError,r as isSqliteInspectionDeadlineOwnedByCaller,u as withSqliteReadOnlyWorkerScope,y as toStringifiedError}from"./sqlite-readonly-worker-BWA2KeVB.mjs";import{r as normalizeNullableString}from"./string-coerce-BBqv4GXj.mjs";import{a as collectSqliteSchemaIssues}from"./sqlite-source-handle-94Qt8Oy_.mjs";import{u as isStateDatabaseAdmissionClosedError}from"./sql-connection-D2qSU3Um.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{c as toRetryError,r as createRetryRunner}from"./src-CY_qXgOR.mjs";import"./sleep-BeLUM6My.mjs";import{t as restoreNativeErrorResponse}from"./native-error-response-BJQNEk2V.mjs";import{i as isNewerSqliteWriterVersion,o as readSqliteUserVersion,r as describeRunningOpenClawBuild,s as readSqliteWriterAppVersion,t as SqliteSchemaVersionError}from"./sqlite-user-version-B1PC_YBu.mjs";import{o as OPENCLAW_DATABASE_SCHEMA_DOCS_URL,s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS}from"./openclaw-state-db-contract-lz-66XzZ.mjs";import"./redact-LQdRaLFO.mjs";import{i as resolveSchemaMigrationIntegrityCheck,s as resolveOpenClawAgentDatabaseDiscoveryPaths}from"./openclaw-state-db-CiEOXNt-.mjs";import{c as isPathInside,o as hasNodeErrorCode,t as resolveStateDir}from"./state-dir-C22DK7p0.mjs";import{a as resolveUserPath}from"./home-dir-C2A7IM0a.mjs";import{c as sanitizeForLog}from"./utils-CfSlIBx_.mjs";import"./paths-BFN5qw21.mjs";import{t as createSubsystemLogger}from"./subsystem-BMw5Czn-.mjs";import{t as formatErrorMessage}from"./errors-BKYtsKt6.mjs";import"./path-existence-4c3xWldM.mjs";import{t as VERSION}from"./version-D4mobxtZ.mjs";import"./plugin-instance-invocation-D2U32-yV.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{n as clearNodeSqliteKyselyCacheForDatabase}from"./kysely-sync-cache-state-CObqh5XE.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-BAgG4Sc_.mjs";import"./kysely-sync-BHQlXmVT.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{a as SqliteSnapshotCleanupError,u as throwSqliteLifecycleErrors}from"./sqlite-lifecycle-errors-BKA8AtC6.mjs";import{S as readSqliteDatabaseCleanCloseRefusal,Y as OPENCLAW_STATE_SCHEMA_SQL,g as prepareSqliteDatabaseAdmission,o as getOrLoadSqliteDatabaseAdmissionForPath,x as readSqliteDatabaseCleanClose}from"./sqlite-database-admission-BikxIIFA.mjs";import{r as getAdmittedSqliteSchemaFacts,t as admitSqliteSchema}from"./sqlite-schema-facts-x2rWNNBl.mjs";import{c as quoteSqliteIdentifier}from"./sqlite-schema-sql-D2HdV_QG.mjs";import{t as openNodeSqliteDatabase}from"./node-sqlite-CX_zY7OF.mjs";import{t as SqliteSchemaMismatchError}from"./sqlite-schema-issues-CTIzzA67.mjs";import{l as getStateRuntimeSchemaAdmission,u as getStateSchemaVersionAdmission}from"./openclaw-state-db-schema-helpers-BKB_fYhN.mjs";import{n as annotateStartupStateInspectionFailure,r as normalizeOpenClawStateSchemaReadError}from"./openclaw-state-db-schema-migration-required-7GgH-T_Y.mjs";import{o as readStateSchemaContentVersion}from"./openclaw-state-db-schema-version-BLKpwqKQ.mjs";import{n as normalizeAgentId,t as isValidAgentId}from"./agent-id-0RKGHEYi.mjs";import{t as formatCliCommand}from"./command-format-D4NTwCWL.mjs";import{g as listGatewayOwnedAgentIds,p as resolveUnsuffixedSqliteTargetFromSessionStorePath}from"./agent-scope-config-CGe7-g8s.mjs";import"./session-key-B7vzF6rJ.mjs";import{g as createOpenClawAgentDatabasePathMatcher,v as isPersistentOpenClawAgentDatabasePath,x as resolveOpenClawAgentSqlitePath}from"./openclaw-agent-db-resources-Ce80pC0J.mjs";import{o as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-D05pNtC5.mjs";import{n as resolveRuntimeWorkerArgv}from"./runtime-worker-url-DanP1ElR.mjs";import{s as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-db-async-lifecycle-CLe5OGzr.mjs";import{n as getDatabaseEngineSelection,t as getDatabaseEngineInput}from"./context-B7I7J9si.mjs";import{h as createSqliteTableContractReader}from"./sqlite-handle-lifecycle-CnxVxCkX.mjs";import{i as resolveSqliteInspectionSignal,s as deferSqliteSnapshotCleanupAfterRead}from"./sqlite-readonly-worker-context-Nl3i9Fck.mjs";import{at as readSqliteIntegrityFileIdentity,ct as assertSqliteIntegrity,ft as prepareSqliteReadOnlyLocation}from"./openclaw-state-db-cache-btIGXlEI.mjs";import{r as observeChildRuntime,t as assertChildRuntimeAvailable}from"./child-runtime-viability-Bjpxcz74.mjs";import{n as hydrateOpenClawStateWorkerError,r as retainOpenClawStateWorkerErrorPayload}from"./openclaw-state-worker-error-DBsl8KO0.mjs";import{A as isOpenClawStateFirstUseSchemaIssue,C as openClawStateMigrationAssertions,O as OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY,P as inspectOpenClawStateOwnershipFromDatabase,j as isOpenClawStateStartupRepairableSchemaIssue,k as STATE_RUNTIME_SCHEMA_COMPATIBILITY,lt as readStateSchemaPublicationBlocker,mt as assertCanonicalStateSchemaShape,r as getActiveOpenClawStateDatabaseReadSnapshotAsync,t as executeExistingOpenClawStateRead,v as assertOpenClawStateDatabaseForMaintenance,y as assertOpenClawStateDatabaseOwner}from"./openclaw-state-db-readonly-Bf0X4q2Y.mjs";import{i as SQLITE_SIDECAR_SUFFIXES,o as resolveSqliteDatabaseFilePaths}from"./update-rehearsal-paths-BO303u2t.mjs";import{i as inspectAgentDatabaseAdmission,n as createAgentDatabaseHeldRefusal,r as createAgentDatabaseInspectionRefusal,t as canIsolateAgentDatabase}from"./agent-database-admission-DQGethEB.mjs";import"./session-row-changes-CbypkYZd.mjs";import{r as runSqliteDeferredTransactionSync}from"./sqlite-transaction-mIYX7gvt.mjs";import"./config-env-vars-DC4WV43c.mjs";import{r as readAgentDatabasePreflightTargets,y as agentSchemaMetadataKey}from"./openclaw-agent-db-registry-listing-WHiEZ120.mjs";import"./backoff-CJvCP7wh.mjs";import{i as readRetainedAgentDeletionsFromDatabase,n as agentDatabaseValidationKey,r as readAgentDatabaseDeletionSnapshot}from"./agent-database-startup-integrity-D2A0JyeQ.mjs";import{t as listConfiguredSessionStoreAgentIds}from"./targets-configured-agents-BoIHWeCk.mjs";import"./agent-database-preparation-context-D4UanyMQ.mjs";import{i as resolveAgentSessionDirsFromAgentsDirSync,n as resolveConfiguredAgentDatabaseCandidatePaths,r as resolveConfiguredSessionStoreTargets,t as isConfiguredAgentDatabaseTarget}from"./targets-reBAlVAy.mjs";import{AsyncLocalStorage}from"node:async_hooks";import{fork}from"node:child_process";import fsSync,{existsSync,realpathSync,statSync}from"node:fs";import path from"node:path";import{randomBytes,randomUUID}from"node:crypto";import fsPromises from"node:fs/promises";import{availableParallelism}from"node:os"; //!src/infra/retry-attempt-errors.ts const retryAttemptErrors=/* @__PURE__ */ new WeakMap;function recordRetryAttemptErrors(e,t){retryAttemptErrors.set(e,[...t])}function getRetryAttemptErrors(e){return e!==null&&(typeof e===`object`||typeof e===`function`)?retryAttemptErrors.get(e):void 0} //!src/infra/secure-random.ts function generateSecureFraction(){return randomBytes(4).readUInt32BE(0)/4294967296} //!src/infra/retry.ts function createRetryFailure(e){const t=e.flatMap(e=>getRetryAttemptErrors(e)??[e]);const n=toRetryError(t.at(-1)??/* @__PURE__ */ new Error(`Retry failed`),`Non-Error thrown`);if(t.length>1)recordRetryAttemptErrors(n,t);return n}const retryAsync=createRetryRunner({shouldRetry:e=>!isStateDatabaseAdmissionClosedError(e),random:generateSecureFraction,createFailure:createRetryFailure}); //!src/state/agent-database-startup.ts const log=createSubsystemLogger(`state/agent-admission`);const startupAdmission=new AsyncLocalStorage;function getAgentDatabaseStartupAdmission(){const e=startupAdmission.getStore();return e?.isStopped?void 0:e} //!src/state/openclaw-agent-schema-inspection-response.ts function restoreAgentSchemaInspectionError(e){const t=restoreNativeErrorResponse(e);if(e.stateError)retainOpenClawStateWorkerErrorPayload(t,e.stateError);const n=hydrateOpenClawStateWorkerError(t);n.message=e.message;return n} //!src/state/openclaw-agent-schema-inspection-worker.ts function retireReader(e){if(e.retired)return;e.retired=true;if(e.child.connected)e.child.send({type:`close`},t=>{if(t)e.child.kill(`SIGKILL`)})}function createAgentSchemaInspectionWorker(){let e;let t=false;let n=false;let r=0;let i=0;let a=0;let o=0;let s;const startReader=e=>{const t=resolveRuntimeProcessEntrypointUrl(`agentSchemaInspection`);assertChildRuntimeAvailable();const n=fork(t,[],{execArgv:resolveRuntimeWorkerArgv(t).slice(0,-1),serialization:`advanced`,stdio:[`ignore`,`ignore`,`pipe`,`ipc`]});r+=1;const i=observeChildRuntime(n);const a=createDeferredCore();const o={child:n,closed:a.promise.then(async()=>{o.runtimeFailure=await i().catch(toStringifiedError)}),retired:false,closeBudgetMs:e};n.on(`error`,e=>{o.failure??=e;retireReader(o)});n.once(`close`,()=>{o.retired=true;a.resolve()});return o};const c={inspect:async(r,c,l)=>{const{input:u,kind:d}=r;const f=resolveSqliteInspectionSignal(c);f?.throwIfAborted();if(t||n)throw new Error(t?`Agent schema inspection worker is closed`:`Agent schema inspection worker is busy`);n=true;try{const n=d===`agent`&&!u.verifyCurrentSchemaShape&&!u.requireStartupMigrationReadiness&&!u.inspectEmptyStore;let r=Boolean(getDatabaseEngineInput(`agent`));let c;const p=getDatabaseEngineSelection();if(n&&p?.postgres){if(!existsSync(l??u.pathname))return null;const[{readBackupEngine:e},{readBackupEngineImage:t}]=await Promise.all([import(`./physical-store-DTJZ158Q.mjs`),import(`./physical-store-inspection-CT0tp6Nv.mjs`)]);const n=l?t(l,u.pathname):e(u.pathname);f?.throwIfAborted();if(n.engine===`sqlite`){if(r&&!l)return null;r=false}else{const{withPostgresStoreMetadata:e}=await import(`./postgres-store-metadata-DwrlEeCy.mjs`);const t=await e(p.postgres,n,async(e,t)=>{if(t.store!==`agent`)throw new Error(`PostgreSQL agent inspection requires an agent store.`);if(!u.inspectOwnership)return{version:t.version};const{rows:r}=await e.query(`SELECT agent_id, role, schema_version::integer AS schema_version FROM ${quoteSqliteIdentifier(n.namespace)}.schema_meta WHERE meta_key = 'primary'`);const i=r[0];return{version:t.version,agentSchemaMeta:i?{agentId:normalizeNullableString(i.agent_id),role:i.role,schemaVersion:i.schema_version}:null}});f?.throwIfAborted();i+=1;return t}}if(d===`agent`&&r){if(l)throw new Error(`PostgreSQL agent inspection requires its live engine owner, not a SQLite snapshot.`);const{getPendingOpenClawAgentDatabasePreparation:e}=await import(`./openclaw-agent-execution-p2UUw-rq.mjs`);await e(u.pathname);f?.throwIfAborted();let t=u.agentId??getOrLoadSqliteDatabaseAdmissionForPath(u.pathname,agentSchemaMetadataKey,()=>void 0)?.agentId;if(!t){const{prepareSqliteTargetFromSessionStorePath:e}=await import(`./session-sqlite-target-DMIA7nkz.mjs`);const n=await e(u.pathname,{env:u.env??process.env},f);if(!n.agentId||n.ownerSource!==void 0&&n.ownerSource!==`database-path`&&n.ownerSource!==`database-registry`)throw new Error(`PostgreSQL schema inspection could not establish the custom store owner.`);t=n.agentId}c=t}if(d!==`state`&&!r&&!l&&u.requireStartupMigrationReadiness&&readSqliteDatabaseCleanClose(u.pathname)){const e=getOrLoadSqliteDatabaseAdmissionForPath(u.pathname,agentDatabaseValidationKey,()=>void 0);const t=getOrLoadSqliteDatabaseAdmissionForPath(u.pathname,agentSchemaMetadataKey,()=>void 0);if(e?.schema?.facts?.userVersion===u.supportedVersion&&Atomics.load(new Int32Array(e.valid),0)===1&&Atomics.load(new Int32Array(e.schema.valid),0)===1&&prepareSqliteDatabaseAdmission(u.pathname)===`${e.identity}:${e.birthtime}`&&t?.agentId===e.agentId&&(u.agentId===void 0||u.agentId===e.agentId)&&t.role===`agent`&&t.schemaVersion===u.supportedVersion)return{version:u.supportedVersion,integrityGateOutcome:`cached`,agentSchemaMeta:t}}const m=l?{pathname:l,identity:readSqliteIntegrityFileIdentity(l)}:void 0;if(e?.retired){await e.closed;e=void 0}f?.throwIfAborted();if(t)throw new Error(`Agent schema inspection worker is closed`);const{timeoutMs:h,size:g}=readSqliteInspectionBudget(u.requireStartupMigrationReadiness?`startup readiness`:`schema inspection`,u.pathname);const _=e??=startReader(h);_.closeBudgetMs=h;s?.();s=void 0;const v=++o;const y=createDeferredCore();let b;const kill=()=>{_.retired=true;_.child.kill(`SIGKILL`)};const onAbort=()=>{b=toStringifiedError(f?.reason);kill()};const onMessage=e=>{if(b)return;if(e.requestId!==v){b=/* @__PURE__ */ new Error(`Invalid agent schema inspection response`);kill()}else if(!e.ok){b=restoreAgentSchemaInspectionError(e.error);retireReader(_)}else{if(d===`state`){const t=e.stateInspection;if(t===null){y.resolve(null);return}if(t===void 0){b=/* @__PURE__ */ new Error(`Invalid state schema inspection response`);kill();return}y.resolve({...t,inspectionErrors:t.inspectionErrors.map(restoreAgentSchemaInspectionError)});return}const t=e.inspection;y.resolve(t?{...t,failure:t.failure?restoreAgentSchemaInspectionError(t.failure):void 0}:null)}};const finishClose=async(e,t)=>{clearTimeout(x);await _.closed;y.reject(f?.aborted?toStringifiedError(f.reason):_.runtimeFailure??b??_.failure??(t===`SIGKILL`?sqliteInspectionTimeoutError(`schema inspection`,u.pathname,h,g):/* @__PURE__ */ new Error(`Agent schema inspection exited ${e} without a completed result`)))};const onClose=(e,t)=>{finishClose(e,t)};const x=isSqliteInspectionDeadlineOwnedByCaller()?void 0:setTimeout(()=>{b??=sqliteInspectionTimeoutError(`schema inspection`,u.pathname,h,g);kill()},h);x?.unref();_.child.on(`message`,onMessage);_.child.once(`close`,onClose);f?.addEventListener(`abort`,onAbort,{once:true});try{_.child.send({type:d===`state`?`inspect-state`:`inspect`,requestId:v,input:{...u,...c?{agentId:c}:{},...`env`in u&&u.env?{env:{...u.env}}:{}},snapshot:m,...d===`agent`&&r?{databaseEngineSelection:p}:{}},e=>{if(e){b??=e;kill()}});const e=await y.promise;if(f?.aborted){kill();await _.closed;throw toStringifiedError(f.reason)}if(m)readSqliteIntegrityFileIdentity(m.pathname,m.identity);if(e){i+=1;a+=m?1:0}return e}finally{clearTimeout(x);_.child.off(`message`,onMessage);_.child.off(`close`,onClose);f?.removeEventListener(`abort`,onAbort)}}finally{n=false}}};return{prestart(r){const i=resolveSqliteInspectionSignal(r);i?.throwIfAborted();if(t||n)throw new Error(`Agent schema inspection worker is unavailable for prestart`);if(e)return;const a=e=startReader(0);const onAbort=()=>{a.retired=true;a.child.kill(`SIGKILL`)};i?.addEventListener(`abort`,onAbort,{once:true});const release=()=>i?.removeEventListener(`abort`,onAbort);s=release;a.closed.then(release)},get processCount(){return r},get inspectionCount(){return i},get snapshotCount(){return a},inspect:async(e,t,n)=>{const r=await c.inspect({kind:`agent`,input:e},t,n);if(r&&`schemas`in r)throw new Error(`Unexpected state schema inspection result`);return r},inspectState:async(e,t,n)=>{const r=await c.inspect({kind:`state`,input:e},t,n);if(r&&!(`schemas`in r))throw new Error(`Unexpected agent schema inspection result`);return r},async[Symbol.asyncDispose](){t=true;s?.();s=void 0;if(!e)return;const n=e;const r=setTimeout(()=>n.child.kill(`SIGKILL`),n.closeBudgetMs);r.unref();try{retireReader(n);await n.closed}finally{clearTimeout(r)}}}} //!src/state/openclaw-database-preflight-agent-scheduler.ts const AGENT_DATABASE_STARTUP_WAIT_MS=5e3;async function preflightAgentDatabasesBounded(e,t,n,r,i,a){const o=/* @__PURE__ */ new Set;const s=/* @__PURE__ */ new Set;const claimAgentTarget=(e,t)=>{const n=`${e}\0${t??``}`;if(s.has(n)||t===void 0&&o.has(e))return false;o.add(e);s.add(n);return true};const c=i?.cleanClose;const l=e.map((e,t)=>t);if(c){const t=e.map(e=>c(e));l.sort((e,n)=>Number(t[n])-Number(t[e]))}const u=[];const d=/* @__PURE__ */ new Map;let f=0;const p=[];const m=createDeferredCore();const h=e.map(()=>createDeferredCore());for(const e of h)e.promise.catch(()=>{});const g=/* @__PURE__ */ new Set;const _=Math.min(2,availableParallelism(),e.length);let v=[];const y=i?r?AbortSignal.any([i.signal,r]):i.signal:resolveSqliteInspectionSignal(r);const b=i!==void 0||isSqliteInspectionDeadlineOwnedByCaller();const settleForeground=()=>{if(!i||g.size===0||v.length>0||d.size>0)return;if(e.some((e,t)=>u[t]===void 0&&!g.has(t)))return;try{v=i.defer([...g].map(t=>({target:e[t],result:h[t].promise})),`Inspection and writable admission continue after the Gateway listener binds.`);m.resolve()}catch(e){m.reject(e)}};const worker=async()=>{try{var n=_usingCtx();const r=n.a(a?.()??createAgentSchemaInspectionWorker());p.push(r);while(true){if(y?.aborted||d.size>0)return;if(f>=l.length)return;const n=l[f];f+=1;const a=e[n];if(a===void 0)continue;const o={incompatible:[],indeterminate:[]};try{const e=await t(a,o,claimAgentTarget,(e,t,n)=>r.inspect(e,y??t,n));u[n]=o;h[n].resolve(o);if(e===`defer`&&i?.canDefer(a))g.add(n)}catch(e){d.set(n,e);h[n].reject(e);return}finally{settleForeground()}}}catch(e){n.e=e}finally{await n.d()}};const x=Promise.all(Array.from({length:_},()=>withSqliteReadOnlyWorkerScope(worker,{signal:y??new AbortController().signal,deadlineOwnedByCaller:b}))).finally(()=>{for(let t=0;t<e.length;t+=1)if(u[t]===void 0)h[t].reject(y?.reason??d.values().next().value??/* @__PURE__ */ new Error(`Inspection cancelled`))});i?.track(x);const S=i&&setTimeout(()=>{if(d.size>0||y?.aborted)return;e.forEach((e,t)=>{if(u[t]===void 0&&i.canDefer(e))g.add(t)});settleForeground()},AGENT_DATABASE_STARTUP_WAIT_MS);S?.unref();try{await(i?Promise.race([x,m.promise]):x)}finally{clearTimeout(S)}for(let t=0;t<e.length;t+=1)if(d.has(t)&&(!g.has(t)||v.length===0))throw d.get(t);y?.throwIfAborted();for(const[e,t]of u.entries()){if(t===void 0||g.has(e))continue;n.incompatible.push(...t.incompatible);n.indeterminate.push(...t.indeterminate);if(t.agentRefusals?.length)(n.agentRefusals??=[]).push(...t.agentRefusals);if(t.pendingMigrations?.length)(n.pendingMigrations??=[]).push(...t.pendingMigrations)}if(v.length)(n.agentRefusals??=[]).push(...v);return{schemaProcessCount:p.reduce((e,t)=>e+t.processCount,0),schemaInspectionCount:p.reduce((e,t)=>e+t.inspectionCount,0),schemaSnapshotCount:p.reduce((e,t)=>e+t.snapshotCount,0)}} //!src/state/openclaw-database-preflight-cleanup.ts async function cleanupOpenClawStatePreflight(e){const t=[];if(e.database){try{e.closeAdmission?.()}catch(e){t.push(e)}try{clearNodeSqliteKyselyCacheForDatabase(e.database);e.database.close()}catch(e){t.push(e)}}try{if(e.snapshot&&!await e.snapshot.cleanupAsync())t.push(new SqliteSnapshotCleanupError(`SQLite read-only worker snapshot cleanup failed: ${e.snapshot.location}`))}catch(n){if(e.inspectionErrors.length>0||t.length>0||!deferSqliteSnapshotCleanupAfterRead(n,e.snapshot?.cleanupRoot))t.push(n)}if(t.length>0)throwSqliteLifecycleErrors([...e.inspectionErrors,...t],`State database schema inspection cleanup failed`)} //!src/state/openclaw-database-preflight-in-place.ts async function inspectAgentSchemaInPlace(e,t,n){const r=n.purpose===`maintenance`&&isLiveStateRead()&&!getOpenClawDatabaseMaintenanceScope();return await t({...e,allowClosedWal:n.purpose===`runtime`&&isLiveStateRead()||r,snapshotAfterClosedWalFailure:r,preserveSourceArtifacts:n.preserveSourceArtifacts===true&&!getDatabaseEngineInput(`agent`)},n.signal)} //!src/state/agent-deletion-discovery.ts function createAgentDatabaseDeletionClassifier(e){const t=e.artifactDirectories;const n=e.retainedDeletions;const r=n.status===`present`?n:n.status===`unavailable`?n.known:void 0;const i=r?.entries??[];const a=n.status===`unavailable`?`unavailable`:void 0;const o=createOpenClawAgentDatabasePathMatcher();const s=!r?[]:t?r.held.flatMap(n=>{const r=path.dirname(resolveOpenClawAgentSqlitePath({agentId:n.agentId,env:e.env}));const i=path.dirname(n.path);const a=path.basename(n.path)===`openclaw-agent.sqlite`;const s=[{agentId:n.agentId,path:r},...t.filter(e=>normalizeAgentId(e.agentId)===n.agentId||a&&o(e.path,i))];if(a&&[e.env.OPENCLAW_AGENT_DIR,e.env.PI_CODING_AGENT_DIR].some(t=>t?.trim()&&o(resolveUserPath(t,e.env),i))||a&&path.basename(i)===`agent`&&o(path.dirname(path.dirname(i)),path.dirname(path.dirname(r))))s.push({agentId:n.agentId,path:i});return s}):r.held;const isHeld=(e,n)=>s.some(r=>t&&r.agentId===n||o(r.path,e));let c;const configuredTargets=()=>c??=typeof e.configuredAgentDatabaseTargets===`function`?e.configuredAgentDatabaseTargets((e,t)=>isHeld(e,t)||i.some(e=>e.agentId===t)):e.configuredAgentDatabaseTargets;return(n,r)=>{if(isHeld(n,r))return`held`;let c=[];if(s.length&&!t&&r!==void 0){const t=normalizeAgentId(r);c=configuredTargets().filter(e=>normalizeAgentId(e.agentId)===t);if(c.length===0)c=[...e.registeredAgentDatabases.filter(e=>normalizeAgentId(e.agentId)===t),{agentId:t,path:resolveUnsuffixedSqliteTargetFromSessionStorePath(n).path}]}if(c.some(e=>isHeld(e.path,e.agentId)))return`held`;const l=i.find(e=>e.agentId===r||(t?[e.agentDir]:e.databasePaths).some(e=>o(e,n)));if(!l)return a;if(r===l.agentId)return l;return!(t??[...configuredTargets(),...e.registeredAgentDatabases]).some(r=>!i.some(e=>e.agentId===normalizeAgentId(r.agentId))&&o(r.path,n)&&(t!==void 0||isPersistentOpenClawAgentDatabasePath(r.path,e.env)&&(configuredTargets().includes(r)||isPathInside(fsSync.realpathSync.native(resolveStateDir(e.env)),fsSync.realpathSync.native(r.path)))))?l:a}} //!src/infra/backup-audit-paths.ts const LEGACY_AUDIT_PATHS=[{directory:`logs`,basename:`config-audit.jsonl`},{directory:`audit`,basename:`system-agent.jsonl`},{directory:`audit`,basename:`crestodian.jsonl`}].map(({directory:e,basename:t})=>{const n=t.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`);return{directory:e,pattern:new RegExp(`^(?:${n}|\\.${n}\\.doctor-importing(?:\\.(?:[2-9]|[1-9][0-9]+))?|${n}\\.migrated(?:\\.(?:[2-9]|[1-9][0-9]+))?\\.raw(?:\\.doctor-scrub-(?:progress|restore|staging))?)$`,`u`)}}); //!src/infra/backup-volatile-filter.ts const SQLITE_MEMORY_TRANSIENT_PATH_PATTERN=/(?:^|\/)(?:[^/]+\.sqlite\.(?:generation-(?:lock|writer)|reindex-lock)\.sqlite|[^/]+\.sqlite\.(?:backup|memory-reindex|tmp)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:-wal|-shm|-journal)?$/iu;function normalizePosix(e){if(!e)return e;return path.posix.normalize(e.replaceAll(`\\`,`/`))}function isTransientSqliteBackupPath(e){const t=normalizePosix(e);return SQLITE_MEMORY_TRANSIENT_PATH_PATTERN.test(t)} //!src/infra/state-migrations.media-persistence-targets.ts function discoverAgentDatabaseMigrationTargets(e){const t=[];const n=[];const r=e.deletionJournal??readAgentDatabaseDeletionSnapshot(e.env)?.retainedDeletions??{status:`unavailable`,cause:`missing`,reason:`shared state database missing`};const i=r.status===`present`?r:r.status===`unavailable`?r.known:void 0;const a=i?.entries??[];const o=createAgentDatabaseDeletionClassifier({...e,retainedDeletions:r});const s=[];const c=[];const l=/* @__PURE__ */ new Map;const failure=(e,n)=>{t.push(n);s.push({path:e,reason:n})};const discard=(e,t)=>{if(e.source===`registry`&&r.status!==`unavailable`&&o(e.path)!==`held`)c.push({agentId:e.agentId,path:e.path,change:t})};const u=[...e.configuredAgentDatabaseTargets.map(e=>({...e,source:`configured`})),...e.registeredAgentDatabases.map(e=>({...e,source:`registry`})),...a.flatMap(e=>{const t=new Set(e.databasePaths);return e.databasePaths.filter(e=>!SQLITE_SIDECAR_SUFFIXES.some(n=>e.endsWith(n)&&t.has(e.slice(0,-n.length)))).map(t=>({agentId:e.agentId,path:t,source:`disk`}))}),...(i?.held??[]).map(e=>({agentId:e.agentId,path:e.path,source:`deletion`}))];const d=resolveStateDir(e.env);const f=path.join(d,`agents`);try{for(const t of resolveAgentSessionDirsFromAgentsDirSync(f)){const n=path.dirname(t);const r=path.join(n,`agent`);const i=normalizeAgentId(path.basename(n));for(const t of resolveOpenClawAgentDatabaseDiscoveryPaths({agentDir:r,agentId:i,env:e.env}))u.push({agentId:i,path:t,source:`disk`})}}catch(e){failure(f,`Could not enumerate agent databases under ${f}: ${String(e)}`)}let p;try{p=fsSync.realpathSync.native(d)}catch(e){if(!hasErrnoCode(e,`ENOENT`))failure(d,`Could not resolve active state directory ${d}: ${String(e)}`)}const m=createOpenClawAgentDatabasePathMatcher();const h=[];const g=[];const _=[];const v=[];const y=/* @__PURE__ */ new Set;for(const i of u){const a=i.path;if(isTransientSqliteBackupPath(a))continue;if(!isPersistentOpenClawAgentDatabasePath(a,e.env)){discard(i,`Removed archived or transient agent database registry entry ${a}.`);continue}let s;try{s=fsSync.realpathSync.native(a)}catch(e){if(!hasErrnoCode(e,`ENOENT`))failure(a,`Could not resolve agent database ${a}: ${String(e)}`)}l.set(a,{realPath:s});const c=o(a,i.agentId);const u=s!==void 0&&e.configuredAgentDatabaseTargets.some(e=>{if(normalizeAgentId(e.agentId)!==normalizeAgentId(i.agentId))return false;try{return m(a,e.path)}catch{return false}});const d=Boolean(s&&p&&(s===p||isPathInside(p,s)));if(s&&!d&&!u&&!c){discard(i);const e=`Skipped foreign agent database ${sanitizeForLog(a)}; it is outside the active state directory and is not a configured session store.`;t.push(e);n.push(e);continue}let f;try{f=fsSync.statSync(a,{bigint:true})}catch(e){if(!hasErrnoCode(e,`ENOENT`)){failure(a,`Could not inspect ${i.source===`registry`?`registered `:``}agent database ${a}: ${String(e)}`);continue}}if(!f?.isFile()){if(r.status===`unavailable`)try{if(resolveSqliteDatabaseFilePaths(a).some(e=>fsSync.lstatSync(e,{throwIfNoEntry:false})))failure(a,`Could not verify held database ${a}: SQLite family artifacts remain without a regular main database. Restore the matching main database before reconstructing deletion history.`)}catch(e){failure(a,`Could not inspect held database family ${a}: ${String(e)}`)}if(i.source===`registry`)t.push(`Skipped missing registered agent database ${a}.`);continue}if(!s){discard(i);failure(a,`Skipped agent database ${a}; its filesystem boundary is unresolved.`);continue}const b=typeof c===`string`?JSON.stringify([normalizeAgentId(i.agentId),a]):`${f.dev}:${f.ino}`;if(y.has(b))continue;if(c){if(o(a)){y.add(b);if(typeof c===`string`)v.push({...i,realPath:s});else{const e={...i,agentId:c.agentId,realPath:s};if(!c.cleanupCompleted&&!c.manualTemplateRemoval)g.push(e);else _.push(e)}if(typeof c===`string`||c.cleanupCompleted||c.manualTemplateRemoval)t.push(`Held agent ${sanitizeForLog(typeof c===`string`?i.agentId:c.agentId)} database ${sanitizeForLog(a)} (${typeof c===`string`?c===`held`?`deletion journal reconstructed`:`deletion journal unavailable`:`retained-by-deletion`}); run ${formatCliCommand(`openclaw doctor --fix`,e.env)} to inspect restoration.`)}continue}y.add(b);h.push({...i,path:a,realPath:s})}if(v.length>0)t.push(`Agent deletion journal ${r.status===`unavailable`?`missing`:`reconstructed`}; ${v.length} store${v.length===1?``:`s`} held back. Run ${formatCliCommand(`openclaw doctor --fix`,e.env)} to record recovery, then restore or delete each held agent explicitly.`);return{targets:h,pendingDeletionTargets:g,schemaTargets:[...h,...g],retainedTargets:_,unverifiedTargets:v,deletionJournal:r,registryRemovals:c,warnings:t,externalWarnings:n,failures:s,sourceIdentities:l}} //!src/state/openclaw-database-preflight-targets.ts function selectAgentDatabaseInspectionTargets(e,t,n){const r=e.agentAdmissionConfig&&(e.purpose===`runtime`||e.requireStartupMigrationReadiness||e.reuseStartupSchemaPreparation)?[...n,...(e.configuredAgentDatabaseCandidatePaths??resolveConfiguredAgentDatabaseCandidatePaths(e.agentAdmissionConfig,{env:e.env})).map(e=>({path:e}))]:void 0;const i=/* @__PURE__ */ new Set;return{admissionTargets:r,inspectionTargets:t.filter(t=>{if(!r||isConfiguredAgentDatabaseTarget(r,t.agentId,t.path))return true;if(e.requireStartupMigrationReadiness&&!i.has(t.path)){createSubsystemLogger(`state/agent-admission`).warn(`Skipped ${t.path}${t.agentId?` (agent ${t.agentId})`:``}: database is not a configured target; run openclaw doctor to inspect retained data.`);i.add(t.path)}return false}).map(e=>Object.assign({},e,{presence:inspectDatabaseCandidatePresence(e.path)})).filter(e=>e.presence.status!==`absent`)}}function inspectDatabaseCandidatePresence(e){try{statSync(e);return{status:`present`}}catch(e){return hasNodeErrorCode(e,`ENOENT`)?{status:`absent`}:{status:`indeterminate`,reason:formatErrorMessage(e)}}}function recordAgentDatabaseRecoveryInspection(e,t,n,r){const i=r.agentSchemaMeta;if(r.failure||r.reason||i?.role!==`agent`||!i.agentId||!isValidAgentId(i.agentId))e?.discovery.failures.push({path:t,reason:`Could not verify the owner of a held custom session store.`});else e?.discovery.unverifiedTargets.push({agentId:normalizeAgentId(i.agentId),path:t,realPath:n,source:`configured`})}function collectAgentDatabasePreflightTargets(e){const{registeredDatabases:t,deletionJournal:n,purpose:r}=e;const i=n.status===`present`?n.entries:[];let a=t;let o=[];const s=new Set(i.filter(e=>e.cleanupCompleted||e.manualTemplateRemoval).map(e=>e.agentId));const c=/* @__PURE__ */ new Set;const l=[];let u;if(e.configuredAgentDatabaseTargets!==void 0)o=typeof e.configuredAgentDatabaseTargets===`function`?e.configuredAgentDatabaseTargets(t):e.configuredAgentDatabaseTargets;if(r===`maintenance`&&e.configuredAgentDatabaseTargets!==void 0){const r=discoverAgentDatabaseMigrationTargets({env:e.env,configuredAgentDatabaseTargets:o,registeredAgentDatabases:t,deletionJournal:n});u={stateDir:resolveStateDir(e.env),configuredAgentDatabaseTargets:o,registeredAgentDatabases:t,discovery:r};a=r.schemaTargets;for(const e of[...r.retainedTargets,...r.unverifiedTargets])c.add(e.realPath);l.push(...r.failures)}const d=[...o,...a,...r===`runtime`?(n.status===`present`?n.held:n.status===`unavailable`?n.known?.held:void 0)??[]:[],...e.configuredAgentDatabaseTargets!==void 0?t.filter(t=>isPersistentOpenClawAgentDatabasePath(t.path,e.env)):[],...(e.configuredAgentDatabaseCandidatePaths??[]).map(t=>({agentId:e.requireStartupMigrationReadiness||e.agentAdmissionConfig?resolveUnsuffixedSqliteTargetFromSessionStorePath(t).agentId:void 0,path:t}))];const f=createOpenClawAgentDatabasePathMatcher();const p=[...c];const m=createAgentDatabaseDeletionClassifier({env:e.env,retainedDeletions:n,configuredAgentDatabaseTargets:o,registeredAgentDatabases:t});if(r===`runtime`&&e.agentAdmissionConfig)for(const t of resolveConfiguredSessionStoreTargets(e.agentAdmissionConfig,e.env)){const e=resolveUnsuffixedSqliteTargetFromSessionStorePath(t.storePath).path;if(m(e,t.agentId)===`held`)d.push({agentId:t.agentId,path:e,held:true})}return{configuredTargets:o,candidates:r===`runtime`?d.flatMap(e=>{const t=m(e.path,e.agentId);return t===`held`?[{...e,held:true}]:typeof t===`object`?[]:[e]}):n.status===`unavailable`?u&&e.onAgentDatabaseDiscovery?(e.configuredAgentDatabaseCandidatePaths??[]).filter(e=>!p.some(t=>f(t,e))).map(e=>({agentId:void 0,path:e,holdForDeletionRecovery:true})):[]:d.filter(t=>{if(n.status===`present`&&n.held.some(e=>f(e.path,t.path)))return e.inspectHeldAgentDatabaseTargets?.some(e=>e.agentId===t.agentId&&f(e.path,t.path))===true;return t.agentId===void 0||!s.has(t.agentId)}),isRetainedPath:e=>{if(r===`runtime`){const t=m(e);return t===`held`||typeof t===`object`}return p.some(t=>f(t,e))},failures:l,preparedDiscovery:u}} //!src/state/openclaw-database-preflight.messages.ts var OpenClawDatabaseSchemaPreflightError=class extends SqliteSchemaVersionError{constructor(e,t={}){const n=t.operation??`gateway-startup`;super(formatIncompatibleDatabaseSchemas(e,n));this.incompatibleDatabases=e;this.name=`OpenClawDatabaseSchemaPreflightError`}};function formatIncompatibleDatabase(e){const t=e.agentId?` for agent ${e.agentId}`:``;const n=isNewerSqliteWriterVersion(e.writerAppVersion)?`It was written by OpenClaw ${e.writerAppVersion}; it is newer than this Gateway (${VERSION}).`:`writer build ${e.writerAppVersion??`unknown`}.`;return`${e.kind} database${t} ${e.path} uses schema ${e.foundVersion}; this build supports ${e.supportedVersion}; ${n}`}function formatIncompatibleDatabaseSchemas(e,t){return`${t===`doctor`?`Doctor refused to continue`:t===`gateway-restart`?`Gateway refused restart`:`Gateway refused startup`} because ${e.length} OpenClaw database schema(s) are newer than this build. ${e.map(formatIncompatibleDatabase).join(` `)} Refused by ${describeRunningOpenClawBuild()}. `+(e.some(e=>isNewerSqliteWriterVersion(e.writerAppVersion))?`Use the newer install that supports these schemas, or run openclaw update to update this Gateway service before restarting. To use an older build, stop the service and restore your pre-upgrade backup created with openclaw backup create. `:`Run a build at least as new as the writer that supports these schemas, or stop the service and restore your pre-upgrade backup created with openclaw backup create. `)+`See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`}function describeDeferredStateSchemaPublication(e,t,n,r){return{kind:`state`,path:t,foundVersion:n,contentVersion:r,...e?{runId:e.runId,publishAfterMs:e.publishAfterMs}:{},message:e?`Schema content applied; version publication deferred until update run ${e.runId} finishes and its five-minute grace expires (or the running driver is abandoned for 30 minutes).`:`Schema content applied; version publication will complete on the next writable database open.`}} //!src/state/openclaw-state-schema-inspection.ts function deduplicateSchemaIssues(e){return[...new Map(e.map(e=>[`${e.code}\0${e.objectName}`,e])).values()]}function inspectCurrentStateStartupSchema(e,t,n){const r=assertOpenClawStateDatabaseOwner(e,{pathname:t});if(r?.schema_version!==n)throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} metadata schema version ${typeof r?.schema_version===`number`?r.schema_version:`invalid`} does not match ${n}.`);const i=createSqliteTableContractReader(e);const a=deduplicateSchemaIssues([...collectSqliteSchemaIssues(e,OPENCLAW_STATE_SCHEMA_SQL,OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY,i),...collectSqliteSchemaIssues(e,OPENCLAW_STATE_SCHEMA_SQL,STATE_RUNTIME_SCHEMA_COMPATIBILITY,i)]);return{blockingIssues:a.filter(e=>!isOpenClawStateStartupRepairableSchemaIssue(e)&&!isOpenClawStateFirstUseSchemaIssue(e)),startupRepairableIssues:a.filter(isOpenClawStateStartupRepairableSchemaIssue)}} //!src/state/openclaw-state-schema-preflight.ts function inspectStateDatabaseSchema(e,t){const{pathname:n,supportedVersion:r}=t;const i={incompatible:[],indeterminate:[]};const a={schemas:i,inspectionErrors:[]};try{let o=false;if(t.purpose===`runtime`&&readSqliteDatabaseCleanClose(n)){admitSqliteSchema(e);o=getStateRuntimeSchemaAdmission(e)?.startupReady===true}const s=t.requireStartupMigrationReadiness?a.startupMetrics={stateIntegrityCheckCount:0,stateIntegrityMs:0,stateSealCount:Number(o)}:void 0;const c=(t.purpose===`maintenance`&&t.verifyCurrentSchemaShape?void 0:getStateSchemaVersionAdmission(e)?.userVersion??getAdmittedSqliteSchemaFacts(e)?.userVersion)??readSqliteUserVersion(e);const l=c>r?c:readStateSchemaContentVersion(e,c);if(l>r){const t=readSqliteWriterAppVersion(e);i.incompatible.push({kind:`state`,path:n,foundVersion:l,supportedVersion:r,...t?{writerAppVersion:t}:{}});if(l>40)return a}const u=c>r?readStateSchemaContentVersion(e,c):l;if(u<r)i.pendingMigrations=[{kind:`state`,path:n,foundVersion:c,supportedVersion:r}];if(c<l&&u===l)i.deferredSchemaPublications=[describeDeferredStateSchemaPublication(readStateSchemaPublicationBlocker(e),n,c,l)];if(!o&&t.requireStartupMigrationReadiness&&l<=40){const i=performance.now();if(s){s.stateIntegrityCheckCount++;s.stateIntegrityReason=t.purpose===`maintenance`?`maintenance`:readSqliteDatabaseCleanCloseRefusal(e)??`startup-not-ready`}assertSqliteIntegrity(e,n,l<r?resolveSchemaMigrationIntegrityCheck({kind:`state`,foundVersion:l,supportedVersion:r}):void 0);if(s)s.stateIntegrityMs=performance.now()-i;assertCanonicalStateSchemaShape(e,n);inspectOpenClawStateOwnershipFromDatabase(e,n);if(u===40){const{blockingIssues:t}=inspectCurrentStateStartupSchema(e,n,c);if(t.length>0)throw new SqliteSchemaMismatchError(`OpenClaw state database ${n} requires repair: ${t.map(e=>e.message).join(`; `)}; run openclaw doctor --fix.`)}else openClawStateMigrationAssertions.get(u)?.(e,{pathname:n})}else if(!o&&t.verifyCurrentSchemaShape&&u===40)try{assertOpenClawStateDatabaseForMaintenance(e,{pathname:n,schemaVersions:{userVersion:c,contentVersion:u}})}catch(e){a.inspectionErrors.push(e);i.indeterminate.push({kind:`state`,path:n,reason:formatErrorMessage(e)})}if(t.scope===`state`)return a;try{a.registeredDatabases=readAgentDatabasePreflightTargets(e,n);a.deletionJournal=readRetainedAgentDeletionsFromDatabase(e,n,t.purpose)}catch(e){a.inspectionErrors.push(e);i.indeterminate.push({kind:`state`,path:n,reason:`agent database registry query failed: ${formatErrorMessage(e)}`})}return a}catch(e){if(t.requireStartupMigrationReadiness)throw e;const r=normalizeOpenClawStateSchemaReadError(e,n);a.inspectionErrors.push(r);i.indeterminate.push({kind:`state`,path:n,reason:formatErrorMessage(r)});return a}} //!src/state/openclaw-database-preflight.ts const indeterminateCauses=/* @__PURE__ */ new WeakMap;async function preflightOpenClawDatabaseSchemas(e,t=`maintenance`){try{var n=_usingCtx();const i=performance.now();const a={};const o=isArtifactPreservingStateRead(`agent`)?{...e,preserveSourceArtifacts:true}:e;o.signal?.throwIfAborted();const s=o.supportedVersions??{state:40,agent:42};const c={incompatible:[],indeterminate:[]};const l=o.requireStartupMigrationReadiness?getAgentDatabaseStartupAdmission():void 0;const u=o.agentAdmissionConfig;const d=new Set(u?[...listConfiguredSessionStoreAgentIds(u),...listGatewayOwnedAgentIds(u)]:[]);const f=l?.scheduling(o.env,u?o.configuredAgentDatabaseCandidatePaths??resolveConfiguredAgentDatabaseCandidatePaths(u,{env:o.env}):[],d);let p;const m=n.a({take(){const e=p;p=void 0;return e},async[Symbol.asyncDispose](){await p?.[Symbol.asyncDispose]()}});if(o.requireStartupMigrationReadiness&&o.scope!==`state`&&getDatabaseEngineInput(`agent`)){p=createAgentSchemaInspectionWorker();p.prestart(f&&o.signal?AbortSignal.any([f.signal,o.signal]):f?.signal??o.signal)}const h=l?.prepareSchemaHeaders(o.env);const g=o.reuseStartupSchemaPreparation&&!o.requireStartupMigrationReadiness&&!o.verifyCurrentSchemaShape&&!o.openStateSchemaReadAdmission?getAgentDatabaseStartupAdmission():void 0;const _=g?.takePreparedStateSchema(o.env);const v=g?.takePreparedSchemaHeaders(o.env);const y=l??g;const b=y?.captureRefusals(o.env);const x=path.resolve(resolveOpenClawStateSqlitePath(o.env));let S=[];let C={status:`unavailable`,cause:`missing`,reason:`shared state database missing`};let w;let T;let E;const D=[];const O=inspectDatabaseCandidatePresence(x);if(O.status===`indeterminate`){c.indeterminate.push({kind:`state`,path:x,reason:O.reason});return c}try{if(O.status===`present`){if(getDatabaseEngineInput(`state`)){const e=await executeExistingOpenClawStateRead({env:o.env},{type:`stateBootstrap.inspect`,input:{pathname:x,supportedVersion:s.state,purpose:t,scope:o.scope}},{signal:o.signal,current:true});if(!e)throw new Error(`Shared state disappeared during PostgreSQL startup admission`);Object.assign(c,e.inspection.schemas);S=e.inspection.registeredDatabases??[];C=e.inspection.deletionJournal??C}else try{var r=_usingCtx();const e=await getActiveOpenClawStateDatabaseReadSnapshotAsync({env:o.env});const n=e?void 0:_;const i=t===`runtime`&&(isLiveStateRead()||!getOpenClawDatabaseMaintenanceScope()&&o.preserveSourceArtifacts!==true)&&(!e||e.location===x);let u=e?.location??(i||n?x:void 0);o.signal?.throwIfAborted();const d={pathname:x,supportedVersion:s.state,requireStartupMigrationReadiness:o.requireStartupMigrationReadiness,verifyCurrentSchemaShape:o.verifyCurrentSchemaShape,scope:o.scope,purpose:t};const f=u===void 0&&o.preserveSourceArtifacts===false;const p=r.a(!n&&(t===`runtime`||f)&&(!o.requireStartupMigrationReadiness||i)&&!o.openStateSchemaReadAdmission?createAgentSchemaInspectionWorker():void 0);let m=p&&(f||i)?await p.inspectState(d,o.signal):null;if(!m){if(u===void 0){E=await prepareSqliteReadOnlyLocation(realpathSync.native(x),{preserveSourceArtifacts:o.preserveSourceArtifacts??true,allowLiveOwner:o.preserveSourceArtifacts!==false,signal:o.signal,requireCleanup:true,reuse:true});u=E.location}o.signal?.throwIfAborted();if(p)m=await p.inspectState(d,o.signal,u);else{w=openNodeSqliteDatabase(u,{readOnly:true,timeout:OPENCLAW_SQLITE_BUSY_TIMEOUT_MS});T=o.openStateSchemaReadAdmission?.(w);const e=w;n?.();m=n||u===x?runSqliteDeferredTransactionSync(e,()=>inspectStateDatabaseSchema(e,d),{operationLabel:`state.schema-preflight`}):inspectStateDatabaseSchema(w,d);n?.()}}if(!m)throw new Error(`Missing state schema inspection result`);Object.assign(c,m.schemas);Object.assign(a,m.startupMetrics);D.push(...m.inspectionErrors);m.schemas.indeterminate.forEach((e,t)=>{const n=m.inspectionErrors[t];indeterminateCauses.set(e,o.requireStartupMigrationReadiness?annotateStartupStateInspectionFailure(n,x,o.signal):n)});if(l&&m.inspectionErrors.length===0&&m.schemas.incompatible.length===0&&m.schemas.indeterminate.length===0&&!m.schemas.pendingMigrations?.length)l.recordStateSchemaPreparation(o.env);if(o.scope===`state`||!m.deletionJournal)return c;S=m.registeredDatabases??[];C=m.deletionJournal}catch(e){r.e=e}finally{await r.d()}}}catch(e){const t=normalizeOpenClawStateSchemaReadError(e,x);D.push(t);if(o.signal?.aborted||o.requireStartupMigrationReadiness)throw annotateStartupStateInspectionFailure(t,x,o.signal);const n={kind:`state`,path:x,reason:formatErrorMessage(t)};indeterminateCauses.set(n,t);c.indeterminate.push(n);return c}finally{await cleanupOpenClawStatePreflight({database:w,closeAdmission:T,snapshot:E,inspectionErrors:D})}if(o.scope===`state`)return c;const k=performance.now();const{candidates:A,configuredTargets:j,isRetainedPath:M,failures:N,preparedDiscovery:P}=collectAgentDatabasePreflightTargets({...o,registeredDatabases:S,deletionJournal:C,purpose:t});const recordRecoveryFailure=(e,t)=>{P?.discovery.failures.push({path:e,reason:t})};for(const e of N)c.indeterminate.push({kind:`agent`,...e});const{admissionTargets:F,inspectionTargets:I}=selectAgentDatabaseInspectionTargets({...o,purpose:t},A,j);const L=/* @__PURE__ */ new Map;const R=I.filter(e=>{if(!e.held)return true;if(e.agentId){const t=L.get(e.agentId)??/* @__PURE__ */ new Set;t.add(e.path);L.set(e.agentId,t)}return false});const recordInspectionFailure=(e,t,n)=>{if(l?.recordInspectionFailure(e,t,n))return true;if(!F||!u||o.requireStartupMigrationReadiness||!e.agentId||!canIsolateAgentDatabase(u,e.agentId))return false;(t.agentRefusals??=[]).push(createAgentDatabaseInspectionRefusal({agentId:e.agentId,paths:[e.path],reason:formatErrorMessage(n),cause:n}));return true};const z=await preflightAgentDatabasesBounded(R,async(e,n,r,i)=>{const a=e.path;if(y?.reuseRefusal(e,n,b))return;const{presence:c}=e;if(c.status===`indeterminate`){if(e.holdForDeletionRecovery){recordRecoveryFailure(a,c.reason);return}if(!recordInspectionFailure(e,n,new Error(c.reason)))n.indeterminate.push({kind:`agent`,path:a,reason:c.reason});return}let p;let m=false;try{const c=realpathSync.native(a);if(e.agentId===void 0&&M(c))return;if(!r(c,e.agentId))return;let g=v?.(c,s.agent)??null;const _=h?.(c);const y=e.holdForDeletionRecovery||e.agentId!==void 0&&d.has(e.agentId);const b={pathname:c,agentId:e.agentId,env:o.env,supportedVersion:s.agent,inspectOwnership:y,verifyCurrentSchemaShape:e.holdForDeletionRecovery?false:o.verifyCurrentSchemaShape,requireStartupMigrationReadiness:e.holdForDeletionRecovery?false:o.requireStartupMigrationReadiness,deferRuntimeIntegrity:t===`runtime`&&o.preserveSourceArtifacts!==true&&f?.canDefer(e)};g??=await inspectAgentSchemaInPlace(b,i,{purpose:t,preserveSourceArtifacts:o.preserveSourceArtifacts,signal:o.signal});if(!g){p=await prepareSqliteReadOnlyLocation(c,{preserveSourceArtifacts:o.preserveSourceArtifacts??true,allowLiveOwner:o.preserveSourceArtifacts!==false,signal:o.signal,requireCleanup:true});o.signal?.throwIfAborted();g=await i(b,o.signal,p.location)}if(!g)throw new Error(`Agent database inspection returned no result: ${a}`);m=!g.failure&&!g.reason;const{version:x,writerAppVersion:S,agentSchemaMeta:C}=g;if(e.holdForDeletionRecovery){recordAgentDatabaseRecoveryInspection(P,a,c,g);return}if(x<=s.agent&&y&&e.agentId){const t=inspectAgentDatabaseAdmission({agentId:e.agentId,path:a,metadata:C??null});if(t){(n.agentRefusals??=[]).push(t);return}}if(x<s.agent)(n.pendingMigrations??=[]).push({kind:`agent`,path:a,...e.agentId!==void 0?{agentId:e.agentId}:{},foundVersion:x,supportedVersion:s.agent});if(g.failure&&!g.reason)throw g.failure;if(g?.reason){if(l||F&&!o.requireStartupMigrationReadiness)throw g.failure??new Error(g.reason);const t={kind:`agent`,path:a,reason:g.reason,...o.requireStartupMigrationReadiness?{agentId:e.agentId}:{}};if(g.failure)indeterminateCauses.set(t,g.failure);n.indeterminate.push(t);return}if(x>s.agent){const t={kind:`agent`,path:a,...e.agentId!==void 0?{agentId:e.agentId}:{},foundVersion:x,supportedVersion:s.agent,...S?{writerAppVersion:S}:{}};if(!F||!u||!e.agentId||!canIsolateAgentDatabase(u,e.agentId)||!recordInspectionFailure(e,n,new OpenClawDatabaseSchemaPreflightError([t])))n.incompatible.push(t)}_?.(g);if(g.readReady)(n.readReadyAgentPaths??=[]).push(c);return g.preparationPending?`defer`:void 0}catch(t){if(o.signal?.aborted)throw t;if(e.holdForDeletionRecovery){recordRecoveryFailure(a,formatErrorMessage(t));return}if(recordInspectionFailure(e,n,t))return;if(o.requireStartupMigrationReadiness)throw t;const r={kind:`agent`,path:a,reason:formatErrorMessage(t)};indeterminateCauses.set(r,t);n.indeterminate.push(r)}finally{if(p){let t;try{if(!await p.cleanupAsync())t={error:/* @__PURE__ */ new Error(`SQLite read-only worker snapshot cleanup failed: ${p.location}`)}}catch(e){if(!m||!deferSqliteSnapshotCleanupAfterRead(e,p.cleanupRoot))t={error:e}}if(t&&!recordInspectionFailure(e,n,t.error)){if(e.holdForDeletionRecovery)recordRecoveryFailure(a,formatErrorMessage(t.error));else n.indeterminate.push({kind:`agent`,path:a,reason:formatErrorMessage(t.error)})}}}},c,o.signal,f,m.take);if(P)o.onAgentDatabaseDiscovery?.(P);for(const[e,t]of L)(c.agentRefusals??=[]).push(createAgentDatabaseHeldRefusal(e,[...t]));z.schemaProcessCount+=p?.processCount??0;o.onAgentInspection?.({...z,...a,statePreflightMs:k-i,agentPreflightMs:performance.now()-k});o.onRegisteredAgentDatabases?.(S);return c}catch(e){n.e=e}finally{await n.d()}}export{preflightOpenClawDatabaseSchemas};