openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
453 lines (452 loc) • 18.1 kB
JavaScript
import { a as asOptionalRecord } from "../record-coerce-CVPuDqcc.mjs";
import { t as hasErrnoCode } from "../errno-DFcoqIT9.mjs";
import { T as resolveOAuthDir } from "../paths-DAcAg5aV.mjs";
import { l as quoteSqliteIdentifier } from "../sqlite-schema-sql-CPyk_2Hd.mjs";
import { t as _usingCtx } from "../usingCtx-rhpPzaNq.mjs";
import { o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "../sqlite-schema-facts-B1bVE8IB.mjs";
import { n as openNodeSqliteDatabase } from "../node-sqlite-CU4puofF.mjs";
import { r as withArtifactPreservingStateReads } from "../artifact-preserving-state-reads-BfhmBr-V.mjs";
import { M as parseGatewayLockPayload, _ as isGatewayStateOwnerDefinitelyStale, a as captureGatewayStateOwner, d as resolveGatewayStateOwnerPath } from "../gateway-state-owner-Bnv5owvG.mjs";
import { r as prepareSqliteReadOnlyLocation } from "../sqlite-snapshot-source-Q9S7_uQN.mjs";
import { _ as withSqliteReadOnlyWorkerScope } from "../sqlite-readonly-worker-D3pRJU7r.mjs";
import { t as listDatabaseEngineStores } from "../registry-Dd7FIY0t.mjs";
import { a as withDatabaseEngineSelection } from "../context-DE59wyBs.mjs";
import { g as readGatewayOwnerLeaseFromDatabase, m as decodeGatewayOwnerLease } from "../openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import { o as withPluginSourceCaptureStorage } from "../plugin-source-capture-context-BU9oGeml.mjs";
import { n as loadBundledPluginManifestRegistry } from "../manifest-registry-build-BbYTyBDW.mjs";
import { p as resolvePluginMetadataSnapshot } from "../plugin-metadata-snapshot-By9ySblt.mjs";
import { n as resolveDatabaseEngineSelection } from "../config-1gpCgiFx.mjs";
import { s as resolveAgentPortRoots, t as databasePortProviders } from "../port-provider-CZISFP-d.mjs";
import { n as createDatabaseStoreDiagnostic, t as listLocalDatabaseDiagnosticStores } from "../local-diagnostics-Bhc6pVK7.mjs";
import { n as readBackupEngineImage } from "../physical-store-inspection-C7yPt-uR.mjs";
import { i as withPostgresConnection, r as readPostgresStoreMetadata } from "../postgres-store-metadata-CcC14HrG.mjs";
import { t as resolveStatePortRoots } from "../state-port-CH03zZ8f.mjs";
import { t as describeDatabaseEngineSelection } from "../report-zZFRy8iT.mjs";
import { n as serveWorkerTasks } from "../worker-task-server-J1vG-XRl.mjs";
import { h as resolvePluginDoctorStateMigrationRecords, l as listPluginDoctorStateMigrationEntries } from "../doctor-contract-registry-CFzLZXmq.mjs";
import { r as createPluginDoctorStateMigrationInput } from "../state-migrations.plugin-doctor-D3oQDmqh.mjs";
import fs from "node:fs";
import { walkDirectory } from "@openclaw/fs-safe/walk";
//#region src/infra/database-engine/diagnostics.ts
function observeLease(e, t) {
e.lease = !t || t.state === "dead" ? "none" : t.state === "live" ? "live-owner" : "unverifiable";
if (e.lease === "unverifiable") e.nextSteps.push("Inspect the recorded Gateway lease before offline maintenance.");
}
function observeVersion(e, t) {
e.schema.versioning = "versioned";
e.schema.version = t;
const n = e.schema.expectedVersion;
if (n === null) return;
e.schema.pending = Math.max(0, n - t);
if (t < n) {
e.issues.push(`Schema migrations pending: version ${t}, expected ${n}.`);
e.nextSteps.push("Run openclaw doctor --fix with the matching OpenClaw version.");
} else if (t > n) {
e.issues.push(`Schema version ${t} is newer than supported version ${n}.`);
e.nextSteps.push("Use an OpenClaw version that supports this schema, or restore its matching backup.");
}
}
function inspectSqlite(e, t, n) {
admitSqliteSchema(t);
const r = getAdmittedSqliteSchemaFacts(t);
e.connectivity = "local";
e.extensions = [];
if (n?.inspectSqliteSource) try {
const r = n.inspectSqliteSource(t);
observeVersion(e, r.version);
if (r.migrationRequired && r.version === e.schema.expectedVersion) {
e.issues.push("Store preparation is required before porting.");
e.nextSteps.push("Database porting performs this preparation on a private copy.");
}
} catch {
if (e.family === "state" || e.family === "agent") observeVersion(e, r.userVersion);
e.issues.push("The SQLite schema could not be admitted by its store owner.");
e.nextSteps.push("Run openclaw doctor --fix with the matching OpenClaw version.");
}
else if (e.schema.versioning === "versioned") observeVersion(e, r.userVersion);
if (e.family === "state") try {
observeLease(e, readGatewayOwnerLeaseFromDatabase(t));
} catch {
e.issues.push("The recorded Gateway lease could not be verified.");
e.nextSteps.push("Check the Gateway owner and rerun openclaw doctor.");
}
}
function inspectSearchMetadata(e, t) {
const n = asOptionalRecord(t);
if (!n) throw new Error("Invalid PostgreSQL metadata");
const r = typeof n.search_extensions === "string" ? JSON.parse(n.search_extensions) : n.search_extensions ?? {};
const i = asOptionalRecord(r);
if (!i) throw new Error("Invalid PostgreSQL search-extension metadata");
const a = [];
const o = [];
for (const [e, t] of Object.entries(i)) {
const n = asOptionalRecord(t);
if (!n) throw new Error("Invalid PostgreSQL search-extension definition");
a.push(e);
if (n.mode === "keyword-only") o.push(`${e}: keyword-only`);
}
e.admittedExtensions = a;
e.degraded = o.length ? o : null;
}
async function inspectPostgres(e, t, n) {
e.namespace = t.namespace;
e.storeId = t.storeId;
if (!n) {
e.issues.push("PostgreSQL connection is not resolved; connectivity and schema are unknown.");
e.nextSteps.push("Configure database.postgres.connection or repair its SecretRef, then rerun openclaw doctor.");
return;
}
try {
await withPostgresConnection(n, async (n) => {
e.connectivity = "reachable";
await n.query("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
try {
await n.query("SET LOCAL statement_timeout = '3000ms'");
const r = (await n.query("SELECT current_database() AS database, ARRAY(SELECT extname::text FROM pg_extension ORDER BY extname) AS extensions")).rows[0];
if (!r) throw new Error("PostgreSQL identity is unavailable");
e.database = r.database;
e.extensions = r.extensions;
const i = await readPostgresStoreMetadata(n, t);
if (i.store !== e.family) {
e.issues.push("PostgreSQL metadata belongs to a different store family.");
e.nextSteps.push("Restore the matching PostgreSQL schema and anchor before starting the Gateway.");
return;
}
observeVersion(e, i.version);
inspectSearchMetadata(e, (await n.query(`SELECT to_jsonb(meta) AS metadata FROM ${quoteSqliteIdentifier(t.namespace)}.openclaw_schema_meta AS meta`)).rows[0]?.metadata);
if (e.family === "agent" && !e.extensions.includes("vector")) {
e.degraded = [...e.degraded ?? [], "vector search unavailable: pgvector is not installed"];
e.nextSteps.push("Ask the database administrator to run CREATE EXTENSION vector; grant USAGE on its schema to the OpenClaw role.");
}
if (e.family === "state") {
const r = await n.query(`SELECT owner, created_at AS "createdAt", expires_at AS "expiresAt", heartbeat_at AS "heartbeatAt", payload_json AS "payloadJson" FROM ${quoteSqliteIdentifier(t.namespace)}.state_leases WHERE scope = $1 AND lease_key = $2 LIMIT 2`, ["gateway-owner", "global"]);
if (r.rows.length > 1) throw new Error("Ambiguous Gateway lease");
const i = r.rows[0];
observeLease(e, decodeGatewayOwnerLease(i ? {
owner: i.owner,
createdAt: Number(i.createdAt),
expiresAt: i.expiresAt === null ? null : Number(i.expiresAt),
heartbeatAt: i.heartbeatAt === null ? null : Number(i.heartbeatAt),
payloadJson: i.payloadJson
} : void 0));
}
} finally {
await n.query("ROLLBACK");
}
}, {
connectionTimeoutMillis: 3e3,
query_timeout: 3e3
});
} catch {
if (e.connectivity === "reachable") {
e.issues.push("PostgreSQL store metadata or owner lease could not be verified.");
e.nextSteps.push("Check the configured role's schema access and run openclaw doctor --fix with the matching version; restore the matching schema and anchor if verification fails.");
} else {
e.connectivity = "unreachable";
e.issues.push("PostgreSQL is unreachable; schema, extensions, and ownership are unknown.");
e.nextSteps.push("Check PostgreSQL service/port, network access, and database.postgres.connection or its SecretRef, then rerun openclaw doctor.");
}
}
}
/** Operator-only, read-only inspection: one private SQLite snapshot and at most one PG connection. */
async function inspectDatabaseStore(e) {
const t = createDatabaseStoreDiagnostic({
family: e.family,
path: e.path,
configured: e.configured
});
t.schema.versioning = e.schemaVersion === null ? "unversioned" : e.descriptor || e.schemaVersion !== void 0 ? "versioned" : "unknown";
t.schema.expectedVersion = e.schemaVersion === null ? null : e.schemaVersion ?? e.descriptor?.version ?? null;
t.legacyMigrations.state = e.configured.fixedLocal ? "none" : "unknown";
if (e.inspectionError === "unreadable-root") {
t.issues.push("The physical store root could not be read; its contents are unknown.");
t.nextSteps.push("Check store path permissions, then rerun openclaw doctor.");
return t;
}
let n = !e.path;
if (e.path) try {
fs.statSync(e.path);
} catch (e) {
if (hasErrnoCode(e, "ENOENT") || hasErrnoCode(e, "ENOTDIR")) n = true;
else {
t.issues.push("The physical store path could not be inspected.");
t.nextSteps.push("Check store path permissions, then rerun openclaw doctor.");
return t;
}
}
if (n || !e.path) {
t.nextSteps.push("Store is not present. Initialize it through its owning feature, then rerun openclaw doctor.");
return t;
}
try {
try {
const n = resolveGatewayStateOwnerPath(e.path);
let r;
try {
r = parseGatewayLockPayload(fs.readFileSync(n, "utf8"));
if (!r) throw new Error("Invalid owner record");
} catch (e) {
if (!hasErrnoCode(e, "ENOENT")) throw e;
}
t.custody = captureGatewayStateOwner(e.path) ? "live-owner" : e.family === "state" && (!r || isGatewayStateOwnerDefinitelyStale(r, n)) ? "none" : "unverifiable";
if (r && t.custody === "unverifiable") t.nextSteps.push("Inspect the recorded store owner's custody before offline maintenance.");
} catch {
t.issues.push("Physical store custody could not be verified.");
t.nextSteps.push("Check the Gateway owner and rerun openclaw doctor.");
}
const n = await prepareSqliteReadOnlyLocation(e.path, { preserveSourceArtifacts: true });
let i;
try {
i = readBackupEngineImage(n.location, e.path);
t.observed = i.engine;
t.mismatch = i.engine !== e.configured.effective;
if (t.mismatch) {
t.issues.push(`Configured ${e.configured.effective}, but the physical store is ${i.engine}.`);
t.nextSteps.push(e.configured.fixedLocal ? "Restore the fixed-local SQLite store from its verified backup." : `Stop the Gateway and run openclaw database port --family ${e.family} --to ${e.configured.effective}, or restore the matching engine configuration.`);
}
if (i.engine === "sqlite") try {
var r = _usingCtx();
inspectSqlite(t, r.u(openNodeSqliteDatabase(n.location, { readOnly: true })), e.descriptor);
} catch (e) {
r.e = e;
} finally {
r.d();
}
} finally {
await n.cleanupAsync();
}
if (i.engine === "postgres") await inspectPostgres(t, i, e.postgres);
} catch {
t.issues.push("The physical store could not be inspected safely.");
t.nextSteps.push("Run openclaw doctor --fix with the matching version, or restore this store's verified backup.");
}
if (t.observed === "postgres" && t.degraded === null) t.nextSteps.push("Search readiness was not verified; reopen the store through its owning feature to verify base search capabilities.");
if (t.schema.expectedVersion === null && t.schema.versioning !== "unversioned") t.nextSteps.push("The store owner did not provide an expected schema version; use the matching plugin or OpenClaw version for schema verification.");
t.nextSteps = [...new Set(t.nextSteps)];
return t;
}
//#endregion
//#region src/commands/doctor-database-legacy-inspection.ts
/** Inspect the same retained SQLite imports that gate database port, on either engine. */
async function inspectDoctorDatabaseLegacyMigrations(e) {
const t = listDatabaseEngineStores().filter((e) => e.postgres);
const n = {};
for (const e of t) n[e.id] = {
state: "none",
pending: []
};
const markUnknown = () => {
for (const e of t) n[e.id].state = "unknown";
};
try {
await withArtifactPreservingStateReads(async () => {
const t = resolvePluginDoctorStateMigrationRecords({
...e,
includeDisabled: true,
artifactPreservingReadOnly: true
});
const r = /* @__PURE__ */ new Set();
const i = listPluginDoctorStateMigrationEntries({
...e,
includeDisabled: true,
inventory: {
records: t,
knownPluginIds: t.map((e) => e.id),
sessionStoreOwnerPluginIds: [],
descriptors: [],
unresolvedPluginIds: []
},
onInspectedPlugin: (e) => r.add(e),
onInspectedStatelessPlugin: (e) => r.add(e)
});
if (t.some((e) => {
const t = e.doctorContract?.stateMigrations;
return (t === true || Array.isArray(t) && t.length > 0) && !r.has(e.id);
})) markUnknown();
for (const t of i) {
const r = t.migration.sqliteOnly?.family;
if (!r) continue;
const i = n[r];
try {
if (await t.migration.detectLegacyState(createPluginDoctorStateMigrationInput({
...e,
oauthDir: resolveOAuthDir(e.env, e.stateDir)
}, t)) !== null) {
i.pending.push(`${t.pluginId}/${t.migration.id} (${t.migration.label})`);
if (i.state !== "unknown") i.state = "pending";
}
} catch {
i.state = "unknown";
}
}
}, { agentDatabases: true });
} catch {
markUnknown();
}
return n;
}
//#endregion
//#region src/commands/doctor-database-engine-inspection.worker.ts
serveWorkerTasks(async (e) => {
const t = {
...e.env,
OPENCLAW_STATE_DIR: e.stateDir
};
const n = [];
const r = {
observed: {},
stateRoots: [],
discoveryFailed: false,
stores: n
};
let i;
try {
i = await resolveDatabaseEngineSelection(e.config, t);
} catch {
r.discoveryFailed = true;
}
const inspect = async () => {
let a;
try {
a = resolvePluginMetadataSnapshot({
...e,
env: t
});
} catch {
r.discoveryFailed = true;
try {
a = loadBundledPluginManifestRegistry({ env: t });
} catch {
a = { plugins: [] };
}
}
const o = await inspectDoctorDatabaseLegacyMigrations({
...e,
env: t
});
const s = /* @__PURE__ */ new Set();
for (const c of describeDatabaseEngineSelection(e.config)) {
const l = databasePortProviders.find((e) => e.id === c.id);
if (!l) continue;
let u;
try {
u = await l.resolveRoots({
...e,
env: t,
plugins: a
});
} catch {
r.discoveryFailed = true;
u = c.id === "state" ? resolveStatePortRoots(e) : c.id === "agent" ? await resolveAgentPortRoots({
...e,
env: t
}, []) : [];
}
const d = /* @__PURE__ */ new Set();
const f = /* @__PURE__ */ new Set();
let p = false;
for (const e of u) try {
const t = fs.statSync(e, { throwIfNoEntry: false });
if (t?.isFile()) {
d.add(fs.realpathSync(e));
p = true;
} else if (!t && e.endsWith(".sqlite")) d.add(e);
else if (t?.isDirectory()) {
const t = await walkDirectory(e, {
symlinks: "include",
include: (e) => (e.kind === "file" || e.kind === "symlink") && e.path.endsWith(".sqlite")
});
if (t.failedDirs.length) {
r.discoveryFailed = true;
for (const e of t.failedDirs) {
d.add(e.path);
f.add(e.path);
}
}
for (const e of t.entries) try {
d.add(fs.realpathSync(e.path));
p = true;
} catch {
r.discoveryFailed = true;
d.add(e.path);
f.add(e.path);
}
}
} catch {
r.discoveryFailed = true;
d.add(e);
f.add(e);
}
let m;
if (p) try {
m = await l.loadDescriptor(a.plugins.find((e) => e.id === l.id));
} catch {
r.discoveryFailed = true;
}
for (const e of d.size ? [...d].toSorted() : [null]) {
if (e && s.has(e)) continue;
if (e) s.add(e);
const t = await inspectDatabaseStore({
family: c.id,
path: e,
configured: {
default: c.default,
override: c.override,
effective: c.effective,
fixedLocal: c.fixedLocal
},
descriptor: m,
postgres: i?.postgres,
inspectionError: e && f.has(e) ? "unreadable-root" : void 0
});
t.legacyMigrations = o[c.id] ?? {
state: "unknown",
pending: []
};
if (t.legacyMigrations.state !== "none") t.nextSteps.push("Run openclaw doctor --fix before database port; enable any named disabled plugin for repair.");
n.push(t);
if (t.observed !== "unknown") {
const e = r.observed[c.id] ??= [];
if (!e.includes(t.observed)) e.push(t.observed);
}
if (c.id === "state" && e && t.observed !== "unknown") {
const n = t.observed === "sqlite" ? { engine: "sqlite" } : {
engine: "postgres",
namespace: t.namespace,
storeId: t.storeId
};
r.stateRoots.push({
path: e,
physical: n
});
}
}
}
for (const i of listLocalDatabaseDiagnosticStores()) {
let a = null;
try {
a = await i.resolvePath(t);
} catch {
r.discoveryFailed = true;
}
n.push(await inspectDatabaseStore({
family: i.id,
path: a,
schemaVersion: i.resolveSchemaVersion ? await i.resolveSchemaVersion() : null,
configured: {
default: e.config.database?.engine ?? "sqlite",
override: null,
effective: "sqlite",
fixedLocal: true
}
}));
}
};
await withPluginSourceCaptureStorage({
stateDir: e.stateDir,
placement: "temporary"
}, () => withArtifactPreservingStateReads(() => withSqliteReadOnlyWorkerScope(() => i ? withDatabaseEngineSelection(i, inspect) : inspect()), { agentDatabases: true }));
return r;
});
//#endregion
export {};