openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
772 lines (771 loc) • 31.4 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as hasNodeErrorCode } from "./path-guards-TIjxtj6H.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as normalizeAgentId, t as isValidAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { a as listGatewayOwnedAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { i as isPersistentOpenClawAgentDatabasePath, n as createOpenClawAgentDatabasePathMatcher } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { a as resolveUnsuffixedSqliteTargetFromSessionStorePath } from "./session-sqlite-target-paths-Dw0pT36E.mjs";
import { S as readSqliteDatabaseCleanClose } from "./sqlite-database-admission-DQIqro3d.mjs";
import { n as OPENCLAW_STATE_SCHEMA_VERSION, t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as SqliteSnapshotCleanupError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import "./kysely-sync-YJo2lmGV.mjs";
import { n as clearNodeSqliteKyselyCacheForDatabase } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { n as createNewerSqliteSchemaVersionError, o as readSqliteUserVersion, s as readSqliteWriterAppVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { a as setSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { i as resolveImmutableSqliteFileUri, n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { s as deferSqliteSnapshotCleanupAfterRead } from "./sqlite-snapshot-capacity-error-DlgtEr8c.mjs";
import { n as isArtifactPreservingStateRead } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { r as runSqliteDeferredTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { r as configureSqliteReadOnlyPragmas } from "./sqlite-wal-DGPrWPl6.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { r as prepareSqliteReadOnlyLocation } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { _ as withSqliteReadOnlyWorkerScope, i as isSqliteInspectionDeadlineOwnedByCaller, l as resolveSqliteInspectionSignal } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { i as normalizeOpenClawStateSchemaReadError, r as annotateStartupStateInspectionFailure } from "./openclaw-state-db-schema-migration-required-D2P85VUd.mjs";
import { t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs";
import { r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs";
import { i as getActiveOpenClawStateDatabaseReadSnapshot, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { f as readStateSchemaPublicationBlocker } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { o as readStateSchemaContentVersion } from "./openclaw-state-db-schema-version-uNbDFl6T.mjs";
import { r as assertNoLegacyStateRuntimeRepair } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import { a as inspectOpenClawStateOwnershipFromDatabase } from "./openclaw-state-ownership-Wv4JBQVJ.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import { n as listConfiguredSessionStoreAgentIds } from "./targets-configured-agents-CQxugAIz.mjs";
import "./openclaw-state-db-ARhwdPJg.mjs";
import { i as canIsolateAgentDatabase, l as createAgentDatabaseHeldRefusal, m as inspectAgentDatabaseAdmission, t as AgentDatabaseAdmissionError, u as createAgentDatabaseInspectionRefusal, w as recordAgentDatabaseAdmissions } from "./agent-database-admission-CL6wHJ_N.mjs";
import { n as getAgentDatabaseStartupAdmission } from "./agent-database-startup-C_V1xkCB.mjs";
import { c as resolveConfiguredSessionStoreTargets, o as resolveConfiguredAgentDatabaseCandidatePaths, t as isConfiguredAgentDatabaseTarget } from "./targets-BVE0__Jb.mjs";
import { t as createAgentDatabaseDeletionClassifier } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { t as createAgentSchemaInspectionWorker } from "./openclaw-agent-schema-inspection-worker-J31vzzWl.mjs";
import { n as discoverAgentDatabaseMigrationTargets } from "./state-migrations.media-persistence-targets-C3oqX64B.mjs";
import { n as describeDeferredStateSchemaPublication, r as formatIndeterminateDatabaseReadiness, t as OpenClawDatabaseSchemaPreflightError } from "./openclaw-database-preflight.messages-BJ_R-IcZ.mjs";
import { n as inspectCurrentStateStartupSchema, t as inspectStateDatabaseSchema } from "./openclaw-state-schema-preflight-CHT1IcGB.mjs";
import { existsSync, realpathSync, statSync } from "node:fs";
import path from "node:path";
import { availableParallelism } from "node:os";
//#region 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)
};
}
//#endregion
//#region src/state/openclaw-database-preflight-cleanup.ts
/** Failed retirement keeps its existing snapshot owner and cannot admit more schemas. */
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");
}
//#endregion
//#region 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)
};
}
}
/** An inspected custom path supplies recovery ownership, never migration admission. */
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"
});
}
/** Select read-only inspection targets from the captured shared-state ownership facts. */
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
};
}
//#endregion
//#region src/state/openclaw-database-preflight-state-path.ts
/** Compare one explicit SQLite file with this release's canonical shared-state schema. */
async function preflightOpenClawStateDatabasePath(e) {
const t = path.resolve(e);
const n = {
schema: "openclaw.state-schema-preflight.v1",
databasePath: t,
targetVersion: 36
};
let r;
let i = null;
let a;
let o;
let s = null;
const result = (e, t = {}) => ({
...n,
foundVersion: i,
...a !== void 0 && a !== i ? { contentVersion: a } : {},
...o ? { deferredPublication: o } : {},
ownership: s,
issues: t.issues ?? [],
status: e,
requiresWrite: t.requiresWrite ?? false,
...t.reason ? { reason: t.reason } : {}
});
try {
const e = realpathSync.native(t);
const n = [
"-wal",
"-shm",
"-journal"
].filter((t) => existsSync(`${e}${t}`));
if (n.length > 0) throw new Error(`SQLite preflight requires a consolidated snapshot with no sidecars; found ${n.join(", ")}. Create a WAL-aware online backup and preflight the resulting standalone file.`);
r = openNodeSqliteDatabase(resolveImmutableSqliteFileUri(e), { readOnly: true });
setSqliteBusyTimeout(r, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
configureSqliteReadOnlyPragmas(r);
i = readSqliteUserVersion(r);
if (!Number.isSafeInteger(i) || i < 0) throw new Error(`OpenClaw state database ${t} has invalid schema version metadata.`);
a = i > 36 ? i : readStateSchemaContentVersion(r);
if (a > 36) {
try {
s = inspectOpenClawStateOwnershipFromDatabase(r, t);
} catch {}
return result("incompatible", { reason: createNewerSqliteSchemaVersionError("OpenClaw state database", t, a, 36, readSqliteWriterAppVersion(r)).message });
}
assertSqliteIntegrity(r, t);
s = inspectOpenClawStateOwnershipFromDatabase(r, t);
if (readStateSchemaContentVersion(r) < 36) return result("migration-required", { requiresWrite: true });
if (i < a) o = describeDeferredStateSchemaPublication(readStateSchemaPublicationBlocker(r), t, i, a);
const { blockingIssues: c, startupRepairableIssues: l } = inspectCurrentStateStartupSchema(r, t, i);
if (c.length > 0) return result("incompatible", { issues: c });
assertNoLegacyStateRuntimeRepair(r, t);
return result(l.length > 0 ? "startup-repairable" : "exact", {
issues: l,
requiresWrite: l.length > 0
});
} catch (e) {
return result("indeterminate", { reason: formatErrorMessage(e) });
} finally {
r?.close();
}
}
//#endregion
//#region src/state/openclaw-database-preflight.ts
const indeterminateCauses = /* @__PURE__ */ new WeakMap();
function getOpenClawDatabaseReadinessFailure(e) {
return indeterminateCauses.get(e);
}
/** Verify persisted runtime schemas before certifying repair or accepting restart. */
async function assertOpenClawDatabasesReady(e) {
const t = await preflightOpenClawDatabaseSchemas({
env: e.env,
onAgentInspection: e.onAgentInspection,
onRegisteredAgentDatabases: e.onRegisteredAgentDatabases,
verifyCurrentSchemaShape: true,
...e.config ? {
agentAdmissionConfig: e.config,
configuredAgentDatabaseTargets: [],
configuredAgentDatabaseCandidatePaths: resolveConfiguredAgentDatabaseCandidatePaths(e.config, { env: e.env })
} : {},
...e.operation === "gateway-startup" ? { requireStartupMigrationReadiness: true } : {},
...e.operation === "doctor" ? {
configuredAgentDatabaseTargets: e.configuredAgentDatabaseTargets,
inspectHeldAgentDatabaseTargets: e.configuredAgentDatabaseTargets.filter((t) => !e.config || !canIsolateAgentDatabase(e.config, t.agentId))
} : {}
}, e.operation === "doctor" ? "maintenance" : "runtime");
const n = [];
for (const r of t.agentRefusals ?? []) {
if (r.code === "agent-database-held") continue;
const t = new AgentDatabaseAdmissionError(r);
if (!e.config || (r.code === "agent-database-ownership-mismatch" || e.operation === "gateway-startup" && r.code !== "agent-database-inspection-pending") && !canIsolateAgentDatabase(e.config, r.agentId)) n.push(t);
}
if (t.incompatible.length > 0) n.push(new OpenClawDatabaseSchemaPreflightError(t.incompatible, { operation: e.operation }));
if (t.indeterminate.length > 0) {
const r = t.indeterminate.flatMap((e) => indeterminateCauses.has(e) ? [indeterminateCauses.get(e)] : []);
n.push(e.operation === "gateway-startup" && t.indeterminate.length === 1 && r.length === 1 ? r[0] : new Error(formatIndeterminateDatabaseReadiness(t.indeterminate, e.operation, indeterminateCauses), { cause: new AggregateError(r) }));
}
if (n.length > 0) throw n.length === 1 ? n[0] : new AggregateError(n, n.map((e) => formatErrorMessage(e)).join("\n"));
if (e.operation === "gateway-startup") recordAgentDatabaseAdmissions(t.agentRefusals ?? [], {
env: e.env,
source: "startup"
});
if (e.operation === "doctor") {
for (const n of t.deferredSchemaPublications ?? []) e.onDeferredSchemaPublication?.(n);
e.onVerified?.(t);
}
}
/** Read schema headers and optionally verify current schema shape without repairing it. */
async function preflightOpenClawDatabaseSchemas(e, t = "maintenance") {
try {
var n = _usingCtx();
const i = isArtifactPreservingStateRead("agent") ? {
...e,
preserveSourceArtifacts: true
} : e;
i.signal?.throwIfAborted();
const a = i.supportedVersions ?? {
state: 36,
agent: 38
};
const o = {
incompatible: [],
indeterminate: []
};
const s = i.requireStartupMigrationReadiness ? getAgentDatabaseStartupAdmission() : void 0;
const c = i.agentAdmissionConfig;
const l = new Set(c ? [...listConfiguredSessionStoreAgentIds(c), ...listGatewayOwnedAgentIds(c)] : []);
const u = s?.scheduling(i.env, c ? i.configuredAgentDatabaseCandidatePaths ?? resolveConfiguredAgentDatabaseCandidatePaths(c, { env: i.env }) : [], l);
let d;
const f = n.a({
take() {
const e = d;
d = void 0;
return e;
},
async [Symbol.asyncDispose]() {
await d?.[Symbol.asyncDispose]();
}
});
if (i.requireStartupMigrationReadiness && i.scope !== "state" && getDatabaseEngineInput("agent")) {
d = createAgentSchemaInspectionWorker();
d.prestart(u && i.signal ? AbortSignal.any([u.signal, i.signal]) : u?.signal ?? i.signal);
}
const p = s?.prepareSchemaHeaders(i.env);
const m = i.reuseStartupSchemaPreparation && !i.requireStartupMigrationReadiness && !i.verifyCurrentSchemaShape && !i.openStateSchemaReadAdmission ? getAgentDatabaseStartupAdmission() : void 0;
const h = m?.takePreparedStateSchema(i.env);
const g = m?.takePreparedSchemaHeaders(i.env);
const _ = s ?? m;
const v = _?.captureRefusals(i.env);
const y = path.resolve(resolveOpenClawStateSqlitePath(i.env));
let b = [];
let x = {
status: "unavailable",
cause: "missing",
reason: "shared state database missing"
};
let S;
let C;
let w;
const T = [];
const E = inspectDatabaseCandidatePresence(y);
if (E.status === "indeterminate") {
o.indeterminate.push({
kind: "state",
path: y,
reason: E.reason
});
return o;
}
try {
if (E.status === "present") {
if (getDatabaseEngineInput("state")) {
const e = await executeExistingOpenClawStateRead({ env: i.env }, {
type: "stateBootstrap.inspect",
input: {
pathname: y,
supportedVersion: a.state,
purpose: t,
scope: i.scope
}
}, {
signal: i.signal,
current: true
});
if (!e) throw new Error("Shared state disappeared during PostgreSQL startup admission");
Object.assign(o, e.inspection.schemas);
b = e.inspection.registeredDatabases ?? [];
x = e.inspection.deletionJournal ?? x;
} else try {
var r = _usingCtx();
const e = getActiveOpenClawStateDatabaseReadSnapshot({ env: i.env });
const n = e ? void 0 : h;
const c = t === "runtime" && readSqliteDatabaseCleanClose(y);
let l = e?.location ?? (c || n ? y : void 0);
i.signal?.throwIfAborted();
const u = {
pathname: y,
supportedVersion: a.state,
requireStartupMigrationReadiness: i.requireStartupMigrationReadiness,
verifyCurrentSchemaShape: i.verifyCurrentSchemaShape,
scope: i.scope,
purpose: t
};
const d = l === void 0 && i.preserveSourceArtifacts === false;
const f = r.a(!n && (t === "runtime" || d) && !i.requireStartupMigrationReadiness && !i.openStateSchemaReadAdmission ? createAgentSchemaInspectionWorker() : void 0);
let p = f && d ? await f.inspectState(u, i.signal) : null;
if (!p) {
if (l === void 0) {
w = await prepareSqliteReadOnlyLocation(realpathSync.native(y), {
preserveSourceArtifacts: i.preserveSourceArtifacts ?? true,
allowLiveOwner: i.preserveSourceArtifacts !== false,
signal: i.signal,
requireCleanup: true
});
l = w.location;
}
i.signal?.throwIfAborted();
if (f) p = await f.inspectState(u, i.signal, l);
else {
S = openNodeSqliteDatabase(c ? resolveImmutableSqliteFileUri(l) : l, {
readOnly: true,
timeout: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS
});
C = i.openStateSchemaReadAdmission?.(S);
const e = S;
n?.();
p = n ? runSqliteDeferredTransactionSync(e, () => inspectStateDatabaseSchema(e, u), { operationLabel: "state.startup-prepared-schema" }) : inspectStateDatabaseSchema(S, u);
n?.();
}
}
if (!p) throw new Error("Missing state schema inspection result");
Object.assign(o, p.schemas);
T.push(...p.inspectionErrors);
p.schemas.indeterminate.forEach((e, t) => {
const n = p.inspectionErrors[t];
indeterminateCauses.set(e, i.requireStartupMigrationReadiness ? annotateStartupStateInspectionFailure(n, y, i.signal) : n);
});
if (s && p.inspectionErrors.length === 0 && p.schemas.incompatible.length === 0 && p.schemas.indeterminate.length === 0 && !p.schemas.pendingMigrations?.length) s.recordStateSchemaPreparation(i.env);
if (i.scope === "state" || !p.deletionJournal) return o;
b = p.registeredDatabases ?? [];
x = p.deletionJournal;
} catch (e) {
r.e = e;
} finally {
await r.d();
}
}
} catch (e) {
const t = normalizeOpenClawStateSchemaReadError(e, y);
T.push(t);
if (i.signal?.aborted || i.requireStartupMigrationReadiness) throw annotateStartupStateInspectionFailure(t, y, i.signal);
const n = {
kind: "state",
path: y,
reason: formatErrorMessage(t)
};
indeterminateCauses.set(n, t);
o.indeterminate.push(n);
return o;
} finally {
await cleanupOpenClawStatePreflight({
database: S,
closeAdmission: C,
snapshot: w,
inspectionErrors: T
});
}
if (i.scope === "state") return o;
const { candidates: D, configuredTargets: O, isRetainedPath: k, failures: A, preparedDiscovery: j } = collectAgentDatabasePreflightTargets({
...i,
registeredDatabases: b,
deletionJournal: x,
purpose: t
});
const recordRecoveryFailure = (e, t) => {
j?.discovery.failures.push({
path: e,
reason: t
});
};
for (const e of A) o.indeterminate.push({
kind: "agent",
...e
});
const { admissionTargets: M, inspectionTargets: N } = selectAgentDatabaseInspectionTargets({
...i,
purpose: t
}, D, O);
const P = /* @__PURE__ */ new Map();
const F = N.filter((e) => {
if (!e.held) return true;
if (e.agentId) {
const t = P.get(e.agentId) ?? /* @__PURE__ */ new Set();
t.add(e.path);
P.set(e.agentId, t);
}
return false;
});
const recordInspectionFailure = (e, t, n) => {
if (s?.recordInspectionFailure(e, t, n)) return true;
if (!M || !c || i.requireStartupMigrationReadiness || !e.agentId || !canIsolateAgentDatabase(c, e.agentId)) return false;
(t.agentRefusals ??= []).push(createAgentDatabaseInspectionRefusal({
agentId: e.agentId,
paths: [e.path],
reason: formatErrorMessage(n),
cause: n
}));
return true;
};
const I = await preflightAgentDatabasesBounded(F, async (e, n, r, o) => {
const d = e.path;
if (_?.reuseRefusal(e, n, v)) return;
const { presence: f } = e;
if (f.status === "indeterminate") {
if (e.holdForDeletionRecovery) {
recordRecoveryFailure(d, f.reason);
return;
}
if (!recordInspectionFailure(e, n, new Error(f.reason))) n.indeterminate.push({
kind: "agent",
path: d,
reason: f.reason
});
return;
}
let m;
let h = false;
try {
const f = realpathSync.native(d);
if (e.agentId === void 0 && k(f)) return;
if (!r(f, e.agentId)) return;
let _ = g?.(f, a.agent) ?? null;
const v = p?.(f);
const y = e.holdForDeletionRecovery || e.agentId !== void 0 && l.has(e.agentId);
const b = {
pathname: f,
agentId: e.agentId,
env: i.env,
supportedVersion: a.agent,
inspectOwnership: y,
verifyCurrentSchemaShape: e.holdForDeletionRecovery ? false : i.verifyCurrentSchemaShape,
requireStartupMigrationReadiness: e.holdForDeletionRecovery ? false : i.requireStartupMigrationReadiness,
deferRuntimeIntegrity: t === "runtime" && i.preserveSourceArtifacts !== true && u?.canDefer(e)
};
if (!_) _ = await o({
...b,
preserveSourceArtifacts: i.preserveSourceArtifacts === true && !getDatabaseEngineInput("agent")
}, i.signal);
if (!_) {
m = await prepareSqliteReadOnlyLocation(f, {
preserveSourceArtifacts: i.preserveSourceArtifacts ?? true,
allowLiveOwner: i.preserveSourceArtifacts !== false,
signal: i.signal,
requireCleanup: true
});
i.signal?.throwIfAborted();
_ = await o(b, i.signal, m.location);
}
if (!_) throw new Error(`Agent database inspection returned no result: ${d}`);
h = !_.failure && !_.reason;
const { version: x, writerAppVersion: S, agentSchemaMeta: C } = _;
if (e.holdForDeletionRecovery) {
recordAgentDatabaseRecoveryInspection(j, d, f, _);
return;
}
if (x <= a.agent && y && e.agentId) {
const t = inspectAgentDatabaseAdmission({
agentId: e.agentId,
path: d,
metadata: C ?? null
});
if (t) {
(n.agentRefusals ??= []).push(t);
return;
}
}
if (x < a.agent) (n.pendingMigrations ??= []).push({
kind: "agent",
path: d,
...e.agentId !== void 0 ? { agentId: e.agentId } : {},
foundVersion: x,
supportedVersion: a.agent
});
if (_.failure && !_.reason) throw _.failure;
if (_?.reason) {
if (s || M && !i.requireStartupMigrationReadiness) throw _.failure ?? new Error(_.reason);
const t = {
kind: "agent",
path: d,
reason: _.reason,
...i.requireStartupMigrationReadiness ? { agentId: e.agentId } : {}
};
if (_.failure) indeterminateCauses.set(t, _.failure);
n.indeterminate.push(t);
return;
}
if (x > a.agent) {
const t = {
kind: "agent",
path: d,
...e.agentId !== void 0 ? { agentId: e.agentId } : {},
foundVersion: x,
supportedVersion: a.agent,
...S ? { writerAppVersion: S } : {}
};
if (!M || !c || !e.agentId || !canIsolateAgentDatabase(c, e.agentId) || !recordInspectionFailure(e, n, new OpenClawDatabaseSchemaPreflightError([t]))) n.incompatible.push(t);
}
v?.(_);
if (_.readReady) (n.readReadyAgentPaths ??= []).push(f);
return _.preparationPending ? "defer" : void 0;
} catch (t) {
if (i.signal?.aborted) throw t;
if (e.holdForDeletionRecovery) {
recordRecoveryFailure(d, formatErrorMessage(t));
return;
}
if (recordInspectionFailure(e, n, t)) return;
if (i.requireStartupMigrationReadiness) throw t;
const r = {
kind: "agent",
path: d,
reason: formatErrorMessage(t)
};
indeterminateCauses.set(r, t);
n.indeterminate.push(r);
} finally {
if (m) {
let t;
try {
if (!await m.cleanupAsync()) t = { error: /* @__PURE__ */ new Error(`SQLite read-only worker snapshot cleanup failed: ${m.location}`) };
} catch (e) {
if (!h || !deferSqliteSnapshotCleanupAfterRead(e, m.cleanupRoot)) t = { error: e };
}
if (t && !recordInspectionFailure(e, n, t.error)) {
if (e.holdForDeletionRecovery) recordRecoveryFailure(d, formatErrorMessage(t.error));
else n.indeterminate.push({
kind: "agent",
path: d,
reason: formatErrorMessage(t.error)
});
}
}
}
}, o, i.signal, u, f.take);
if (j) i.onAgentDatabaseDiscovery?.(j);
for (const [e, t] of P) (o.agentRefusals ??= []).push(createAgentDatabaseHeldRefusal(e, [...t]));
I.schemaProcessCount += d?.processCount ?? 0;
i.onAgentInspection?.(I);
i.onRegisteredAgentDatabases?.(b);
return o;
} catch (e) {
n.e = e;
} finally {
await n.d();
}
}
//#endregion
export { preflightOpenClawStateDatabasePath as i, getOpenClawDatabaseReadinessFailure as n, preflightOpenClawDatabaseSchemas as r, assertOpenClawDatabasesReady as t };