UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,221 lines (1,220 loc) • 47.7 kB
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import { t as parseJsonWithJson5Fallback } from "./parse-json-compat-DoWUfD79.mjs"; import { i as resolveConfigEnvVars } from "./env-substitution-CgVeOqUd.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { T as resolveOAuthDir, m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds, r as listAgentEntriesWithSource } from "./agent-roster-t1ooUdXp.mjs"; import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { M as postgresStoreNamespace, o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { d as resolvePrivateSqliteSnapshotStagingRoot, l as createPrivateSqliteTempDirectory } from "./sqlite-snapshot-staging-DVmPTRsc.mjs"; import { i as resolvePathJournalPolicy } from "./sqlite-wal-filesystem-LJsoYuDu.mjs"; import { r as tryReadDiskSpace } from "./disk-space-B5Tl0OOd.mjs"; import { Et as _enum, Fn as object, Jn as string, Nt as array, lr as uuid, nr as tuple, or as union, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { l as hasActiveGatewayStateOwner } from "./gateway-state-owner-Bnv5owvG.mjs"; import { n as openSqliteReadOnlyDatabase } from "./sqlite-snapshot-source-Q9S7_uQN.mjs"; import { c as readHostFreeMemoryBytes, o as resolveWorkerPoolSize } from "./worker-pool-sizing-BAFxhrtU.mjs"; import { n as resolveDatabaseFamilyEngines, r as selectDatabaseEngine, t as listDatabaseEngineStores } from "./registry-Dd7FIY0t.mjs"; import { a as withDatabaseEngineSelection, r as getScopedDatabaseEngineSelection, t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs"; import { o as preparePluginMetadataMachineStateAsync } from "./installed-plugin-index-record-state-euCqi7PU.mjs"; import { n as resolveStateClientCredentialEnvironment, t as resolveClientCredentialStorePath } from "./client-credential-paths-CIYPaDgB.mjs"; import { i as readClientCredentialFileIdentity } from "./client-credential-receipt-yx56NK9z.mjs"; import { t as readBackupEngine } from "./physical-store-BRXG56Jw.mjs"; import { t as normalizeLegacyWorkboardDatabaseConfig } from "./legacy-workboard-database-C5tBV8hg.mjs"; import { i as withConfigWriteLock } from "./write-lock-Bg9nHsHM.mjs"; import { i as unsetConfigValueAtPath, r as setConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs"; import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import { r as discoverConfigSecretTargetsByIds } from "./target-registry-query-le6rMGHo.mjs"; import "./target-registry-C0PdHjLu.mjs"; import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs"; import { l as readConfigFileSnapshotForWrite, x as writeConfigFile } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs"; import { t as resolveDatabaseEngineInput } from "./config-1gpCgiFx.mjs"; import { c as prepareDatabasePortDirectory, d as writeDatabasePortManifest, i as assertDatabasePortRecoveryAllowed, l as syncDatabasePortPath, n as archiveDatabasePortManifest, o as databasePortArtifactSchema, r as assertDatabasePortPlatformSupported, s as databasePortManifestPath, u as writeDatabasePortArtifact } from "./database-port-recovery-DDaR-V_Q.mjs"; import { i as inspectOpenClawRegisteredAgentDatabases } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs"; import { s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs"; import { o as agentPortProvider, t as databasePortProviders } from "./port-provider-CZISFP-d.mjs"; import { n as statePortProvider } from "./state-port-CH03zZ8f.mjs"; import { l as listPluginDoctorStateMigrationEntries } from "./doctor-contract-registry-CFzLZXmq.mjs"; import { a as publishVerifiedSqliteFile, i as prepareVerifiedSqliteFile, r as createVerifiedSqliteSnapshot } from "./sqlite-snapshot-BQ91cQh_.mjs"; import { r as createPluginDoctorStateMigrationInput } from "./state-migrations.plugin-doctor-D3oQDmqh.mjs"; import { a as captureDatabaseArtifact, i as assertDatabaseArtifact } from "./database-backup.operations-BNuRDpZK.mjs"; import { a as preparePostgresRestore, n as capturePostgresBackup, o as readPostgresBackupFamily } from "./database-backup-B6k1k0NC.mjs"; import { t as listDefaultAgentDatabasePaths } from "./agent-database-path-discovery-DboXWm5d.mjs"; import { r as discoverBackupDatabasePaths } from "./backup-sqlite-snapshot-D5T0ii_w.mjs"; import { i as withStateInspectionCleanup } from "./update-candidate-state.sizes-BDo08pQy.mjs"; import { r as runDatabasePortTask, t as DatabasePortError } from "./port-command.worker-LM4Ze-86.mjs"; import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs"; import { n as assertDoctorSqliteMaintenancePathsNotAliased } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs"; import { i as readMemorySearchManagerStatus } from "./types-Bo5s7TN4.mjs"; import { o as getActiveMemorySearchManagerCore } from "./memory-runtime-C3z9zu-7.mjs"; import { t as resolveCommandSecretRefsViaGateway } from "./command-secret-gateway-Dh_PhH7v.mjs"; import { s as getMemoryEmbeddingCommandSecretTargetIds } from "./command-secret-targets-CH2XIeV_.mjs"; import { t as collectIncludePathsRecursive } from "./includes-scan-CrmHD_1P.mjs"; import { a as rebindPortedClientCredentials, n as capturePortClientCredentialBinding, t as PortClientCredentialMismatchError } from "./client-credential-restore-CZMFMeth.mjs"; import { r as readReservedIncognitoKeyRepairState, t as listReservedIncognitoKeys } from "./doctor-session-incognito-key-repair-CbOGxRN3.mjs"; import fs from "node:fs"; import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/doctor-database-port-context.ts const databasePortFamilySchema = _enum([ "state", "agent", "workboard", "logbook", "team-reports" ]); function assertPortSelection(e, t, n) { try { const r = resolveDatabaseFamilyEngines(e); if (!n && new Set(listDatabaseEngineStores().filter((e) => e.postgres).map((e) => r[e.id])).size > 1) throw new Error("Mixed-engine database port requires --family <state|agent|workboard|logbook|team-reports>; port one family at a time."); if (t && !n) { const n = resolveDatabaseFamilyEngines({ ...e, database: { ...e.database, engine: t } }); if (listDatabaseEngineStores().some((e) => e.postgres && n[e.id] !== t)) throw new Error("Engine-pinning family overrides require --family; port each configured family separately."); } } catch (e) { if (e instanceof Error) throw new DatabasePortError(e.message); throw e; } } const inputsSchema = object({ originalEngine: string().nullable().optional(), remainingSqlite: array(string()).optional(), selection: object({ path: union([tuple([literal("database"), literal("engine")]), tuple([ literal("database"), literal("families"), databasePortFamilySchema, literal("engine") ])]), originalValue: string().nullable(), effectiveSource: _enum(["sqlite", "postgres"]) }).optional(), outOfScope: array(object({ path: string(), engine: _enum(["sqlite", "postgres"]) })).optional(), stores: array(object({ dev: string(), ino: string(), image: string(), original: databasePortArtifactSchema })) }); function refuse(e, t, n) { throw new DatabasePortError(`Database port ${e.phase}: ${e.target}; observed ${t}; required ${n}. Stop the Gateway first; correct this fact and retry, or use --resume/--rollback with ${databasePortManifestPath(e.stateDir)}.`); } function refuseFailure(e, t) { if (t instanceof PortClientCredentialMismatchError) throw new DatabasePortError(`Database port ${e.phase}: ${e.target}; ${t.message} Restore the archive with openclaw backup restore before retrying.`); if (t instanceof DatabasePortError) throw t; const n = object({ code: string().regex(/^[A-Z0-9_]+$/) }).safeParse(t); return refuse(e, n.success ? n.data.code : "validation or I/O failure", "successful verified phase; preserve the recovery directory"); } const digest = (e) => createHash("sha256").update(stableStringify(e)).digest("hex"); function manifest(e) { return e.manifest; } function storeAt(e, t) { return { target: manifest(e).targets[t], input: e.inputs.stores[t] }; } const storeDirectory = (e, t) => path.join(e.directory, String(t)); const stagePath = (e, t) => path.join(storeDirectory(e, t), "target.sqlite"); const livePath = (e) => e.original.engine === "sqlite" ? e.original.path : e.original.anchorPath; function revise(e) { const t = manifest(e); writeDatabasePortManifest(e.stateDir, { ...t, revision: t.revision + 1 }, e.assertCurrent); t.revision++; } async function record(e, t, n) { const r = `${JSON.stringify(n)}\n`; if (fs.existsSync(t)) { if (fs.readFileSync(t, "utf8") !== r) refuse(e, "changed private artifact", "recorded artifact contents"); } else writeDatabasePortArtifact(t, r, e.assertCurrent); manifest(e).artifacts.push(await captureDatabaseArtifact(t)); revise(e); } function privatePaths(e, t) { for (const n of t) { e.target = n; try { assertDoctorSqliteMaintenancePathsNotAliased("database port", [n], [e.stateDir, path.dirname(e.configPath)]); } catch { refuse(e, "aliased or inaccessible path", "an owned path without symbolic or hard links"); } } } async function configInputs(e) { const t = fs.readFileSync(e.configPath, "utf8"); const n = [e.configPath, ...await collectIncludePathsRecursive({ configPath: e.configPath, parsed: parseJsonWithJson5Fallback(t), env: e.env })]; privatePaths(e, n); return await Promise.all(n.map(captureDatabaseArtifact)); } async function readDatabasePortConfigSnapshot(e) { e.assertCurrent(); const t = await readConfigFileSnapshotForWrite({ observe: false, skipPluginValidation: true }); if (!t.snapshot.valid || t.snapshot.path !== e.configPath) refuse(e, "invalid or changed configuration", "valid pinned config source"); privatePaths(e, Object.keys(t.writeOptions.includeFileTargetsForWrite ?? {})); return t; } function postgresConfig(e) { return { ...e, database: { ...e.database, engine: "postgres", families: void 0 } }; } function capacity(e, t) { const n = /* @__PURE__ */ new Map(); for (const e of t) { const t = fs.statSync(e.path).dev; const r = n.get(t) ?? { path: e.path, required: 1024 ** 3 }; r.required += e.size * 7; n.set(t, r); } for (const t of n.values()) { const n = tryReadDiskSpace(t.path); if (n && n.availableBytes < t.required) refuse(e, `${n.availableBytes} bytes free on ${t.path}`, `${t.required} bytes for captures, migration, indexes and publication`); } } function finalize(e, t) { e.phase = "finalize/archive"; const n = manifest(e); if (n.state !== "complete") { n.state = "complete"; n.outcome = t; revise(e); } const r = n.artifacts.find((t) => t.path === path.join(e.directory, "client-credential-binding.json")); const i = path.join(e.stateDir, "state", "openclaw.sqlite"); if (r && !n.targets.some((e) => livePath(e) === i)) refuse(e, "credential binding without shared target", "captured shared store"); for (const [a, o] of n.targets.entries()) { const s = livePath(o); const c = n.artifacts.find((t) => t.path === path.join(storeDirectory(e, a), "client-credential-binding.json")) ?? (s === i ? r : void 0); if (!c) continue; e.target = s; const l = e.inputs?.stores[a]; const u = resolveStateClientCredentialEnvironment({ path: s, env: e.env }); if (!l || !u) refuse(e, "credential binding without shared target", "captured shared store"); rebindPortedClientCredentials({ env: u, binding: JSON.parse(fs.readFileSync(c.path, "utf8")), sharedPath: s, sqliteSnapshotPath: l.image, engine: t === "ported" ? n.direction.to : n.direction.from, storeId: o.storeId, assertCurrent: e.assertCurrent }); } const a = archiveDatabasePortManifest(e.stateDir, n.operationId, e.assertCurrent); return { phase: "complete", engine: t === "ported" ? n.direction.to : n.direction.from, stores: n.targets.map(livePath), plannerStatistics: e.plannerStatistics ?? [], backup: e.directory, remainingSqlite: e.inputs?.outOfScope?.filter((e) => e.engine === "sqlite").map((e) => e.path) ?? e.inputs?.remainingSqlite ?? [], ...e.family ? { family: e.family, outOfScope: e.inputs?.outOfScope ?? [] } : {}, manifest: a, serverCapacity: "unknown; former PostgreSQL namespaces retained", restart: "Start the Gateway through its service owner." }; } //#endregion //#region src/commands/doctor-database-port-memory-concurrency.ts const MEMORY_REBUILD_BUDGET_BYTES = 536870912; /** Independent agent memory rebuilds share the host; small or busy hosts stay sequential. */ function resolveMemoryRebuildConcurrency() { const e = Math.floor(readHostFreeMemoryBytes() / 2 / MEMORY_REBUILD_BUDGET_BYTES); return Math.max(1, Math.min(resolveWorkerPoolSize("compute"), e)); } //#endregion //#region src/commands/doctor-database-port-memory.ts function failed(e, t) { return { ...e, status: "failed", warning: `${t} Run: openclaw memory index --agent ${e.agentId}` }; } /** Consume the published config under fresh offline custody, never the port's old selection. */ async function rebuildPortedAgentMemory(e) { const t = new Set(e.stores.map((e) => path.resolve(e))); let n = []; try { n = (await listDefaultAgentDatabasePaths(e.stateDir)).filter((e) => t.has(e.path)); return await runWithLocalStateOwner({ method: "memory.cli", params: {}, target: "ported memory stores", databaseEngine: "configured", onForeignOwner: "refuse", runLocal: async ({ env: e, assertCurrent: r }) => { const i = await createConfigIO({ env: e, configPath: e.OPENCLAW_CONFIG_PATH, observe: false, pluginValidation: "skip" }).loadConfigAsync({ assertCurrent: r }); const a = await inspectOpenClawRegisteredAgentDatabases({ env: e }); n = [...new Map([ ...a, ...n, ...resolveConfiguredAgentDatabaseTargets(i, { env: e, registeredDatabases: a }) ].map((e) => [path.resolve(e.path), { agentId: e.agentId, path: path.resolve(e.path) }])).values()].filter((e) => t.has(path.resolve(e.path))); const o = new Set(listAgentIds(i)); const s = listAgentEntriesWithSource(i); const c = getMemoryEmbeddingCommandSecretTargetIds(i); const l = discoverConfigSecretTargetsByIds(i, c); const rebuild = async (t) => { if (!o.has(t.agentId) || path.resolve(t.path) !== resolveOpenClawAgentSqlitePath({ agentId: t.agentId, env: e })) return failed(t, "Retained store needs its original agent configuration before rebuilding."); const n = performance.now(); try { const e = s.find(({ entry: e }) => normalizeAgentId(e.id) === t.agentId)?.source; const a = new Set(l.filter(({ pathSegments: [t, n, r] }) => t !== "agents" || n !== "entries" && n !== "list" ? true : e?.kind === n && r === (e.kind === "entries" ? e.key : e.index)).map(({ path: e }) => e)); const { resolvedConfig: o } = await resolveCommandSecretRefsViaGateway({ config: i, commandName: "memory index", targetIds: c, allowedPaths: a, agentId: t.agentId, mode: "enforce_resolved" }); r(); const { manager: u } = await getActiveMemorySearchManagerCore({ cfg: o, agentId: t.agentId, purpose: "cli", inspectSources: true }); if (!u) return failed(t, "The selected memory plugin is unavailable."); let d; try { if (!u.sync) d = failed(t, "The selected memory plugin does not support indexing."); else { r(); await u.sync({ reason: "cli", force: true }); const e = await readMemorySearchManagerStatus(u); d = e.lastSyncError || e.dirty ? failed(t, "The memory index rebuild did not complete.") : { ...t, status: "rebuilt", elapsedMs: Math.round(performance.now() - n), files: e.files, chunks: e.chunks }; } } finally { await u.close?.(); } if (getScopedDatabaseEngineSelection()?.effectiveEngines.agent === "postgres") try { d.plannerStatistics = await runDatabasePortTask({ operation: "analyze", sourcePath: t.path, config: i }, { assertCurrent: r }); } catch { d.plannerStatistics = { status: "warning", warning: "Post-port memory planner statistics could not be refreshed; autovacuum can refresh them later." }; } return d; } catch { return failed(t, "Memory rebuild failed after the database port completed."); } }; const { results: u } = await runTasksWithConcurrency({ tasks: n.map((e) => () => rebuild(e)), limit: resolveMemoryRebuildConcurrency() }); return n.map((e, t) => u[t] ?? failed(e, "Memory rebuild failed after the database port completed.")); } }); } catch { return n.map((e) => failed(e, "Memory rebuild could not acquire or finish offline ownership.")); } } //#endregion //#region src/commands/doctor-database-port-migrations.ts var DatabasePortReservedIncognitoKeysError = class extends DatabasePortError { constructor() { super("Database port found unrepaired reserved-incognito session keys. Run openclaw doctor --fix on the SQLite installation, then retry adoption."); this.code = "RESERVED_INCOGNITO_SESSION_KEYS"; } }; /** The global rename must finish on SQLite before any selected agent leaves that repair owner. */ function assertDatabasePortReservedIncognitoKeysRepaired(e) { for (const n of e.paths) try { var t = _usingCtx(); if (readBackupEngine(n).engine !== "sqlite") continue; const r = t.u(openSqliteReadOnlyDatabase(n)); admitSqliteSchema(r); const i = getAdmittedSqliteSchemaFacts(r).tables; let a = false; if (statePortProvider.matchesSqlite(i)) { const e = readReservedIncognitoKeyRepairState(r); a = e.reservedKeys.length > 0 || e.renames.length > 0; } else if (e.includeAgents && agentPortProvider.matchesSqlite(i)) a = listReservedIncognitoKeys(r).length > 0; if (a) throw new DatabasePortReservedIncognitoKeysError(); } catch (e) { t.e = e; } finally { t.d(); } } /** Metadata discovery can open shared state too; preserve sources before the repair gate. */ function inspectDatabasePortSources(e, t, n, r) { return withArtifactPreservingStateReads(async () => { const i = { stateDir: e.stateDir, config: t, env: e.env }; const a = resolvePluginMetadataSnapshot(i); const o = await Promise.all(databasePortProviders.map(async (e) => ({ id: e.id, roots: await e.resolveRoots({ ...i, plugins: a }) }))); const s = o.flatMap((e) => e.roots); privatePaths(e, s); const c = await discoverBackupDatabasePaths(i); const owner = (e) => o.find((t) => t.roots.some((t) => e === t || e.startsWith(`${t}${path.sep}`)))?.id; if (n === "sqlite" && r === "postgres" && (!e.family || e.family === "state" || e.family === "agent")) assertDatabasePortReservedIncognitoKeysRepaired({ paths: c, includeAgents: !e.family || e.family === "agent" }); return { all: c, owner }; }, { agentDatabases: true }); } /** Legacy imports must finish while their destination family still accepts SQLite writes. */ async function assertDatabasePortPluginMigrationsComplete(e) { const t = { ...e.config, database: { ...e.config.database, engine: e.to } }; const n = new Set(listDatabaseEngineStores().filter((n) => n.postgres && selectDatabaseEngine(n, e.config) === "sqlite" && (e.family ? n.id === e.family && e.to === "postgres" : selectDatabaseEngine(n, t) === "postgres")).map((e) => e.id)); if (n.size === 0) return; await withArtifactPreservingStateReads(async () => { let t; try { t = listPluginDoctorStateMigrationEntries({ ...e, includeDisabled: true }); } catch { throw new DatabasePortError("Database port could not inspect registered plugin migrations. Run openclaw doctor --fix first, then retry port."); } const r = []; for (const i of t) { const t = i.migration.sqliteOnly; if (!t || !n.has(t.family)) continue; const a = `${i.pluginId}/${i.migration.id} (${i.migration.label})`; try { if (await i.migration.detectLegacyState(createPluginDoctorStateMigrationInput({ ...e, oauthDir: resolveOAuthDir(e.env, e.stateDir) }, i)) !== null) r.push(a); } catch { throw new DatabasePortError(`Database port could not inspect SQLite migration ${a}. Run openclaw doctor --fix first, then retry port.`); } } if (r.length > 0) throw new DatabasePortError(`Database port requires pending SQLite migrations: ${r.join(", ")}. Run openclaw doctor --fix first, then retry port. If a named plugin is disabled, enable it for repair.`); }, { agentDatabases: true }); } //#endregion //#region src/commands/doctor-database-port-state.ts function assertLocalCredentialPortCompanion(e, t, n, r) { e.target = t; privatePaths(e, [t]); const i = readClientCredentialFileIdentity(n); const a = resolveStateClientCredentialEnvironment({ path: n, env: e.env }); if (r !== "state" || readBackupEngine(t).engine !== "sqlite" || !i || !a || !capturePortClientCredentialBinding({ env: a, sourcePath: n, sourceFile: i })) refuse(e, "unmatched local credentials", "an admitted shared target and its bound local store"); } async function withDatabasePortStateOwner(e, t, n) { const r = (await readDatabasePortConfigSnapshot(e)).snapshot.config; const i = path.join(e.stateDir, "state", "openclaw.sqlite"); await selectDatabasePortEngine(e, r, fs.existsSync(i) ? readBackupEngine(i).engine : resolveDatabaseFamilyEngines(r).state); return withDatabaseEngineSelection(e.engineSelection, () => runWithLocalStateOwner({ method: "database.port", params: {}, target: e.stateDir, onForeignOwner: "refuse", databasePortRecovery: t, databasePortMaintenance: true, runLocal: ({ env: t, assertCurrent: r, signal: i }) => { Object.assign(e, { env: t, stateDir: resolveStateDir(t), assertCurrent: r, signal: i }); return n(); } })); } async function selectDatabasePortEngine(e, t, n) { const r = { ...resolveDatabaseFamilyEngines(t), state: n ?? "sqlite" }; Object.assign(e.engineSelection, { effectiveEngines: Object.freeze(r), postgres: e.engineSelection.postgres ?? (Object.values(r).includes("postgres") ? await resolveDatabaseEngineInput(postgresConfig(t), e.env) : void 0) }); } async function closeDatabasePortState(e) { const { closeOpenClawStateDatabaseByPathAsync: t } = await import("./openclaw-state-db-cache-DIGS30x4.mjs"); await t(path.join(e.stateDir, "state", "openclaw.sqlite")); } async function prepareSharedStatePortSource(e, t, n, r) { const i = path.join(e.stateDir, "state", "openclaw.sqlite"); if (r || t !== "sqlite" || n !== "postgres" || fs.existsSync(i)) return; const { captureOpenClawStateWorkerContext: a } = await import("./openclaw-state-worker-context-B6c2qDAQ.mjs"); const { runOpenClawStateWorkerOperation: o } = await import("./openclaw-state-worker-store-BURqchns.mjs"); await o(a({ env: e.env }), async () => {}, { assertCurrent: e.assertCurrent }); await closeDatabasePortState(e); return i; } //#endregion //#region src/commands/doctor-database-port-publication.ts async function verify(e, t, n, r = false, i, a) { e.phase = "verify"; const o = manifest(e), { target: s } = storeAt(e, t); e.target = livePath(s); const c = path.join(storeDirectory(e, t), r && s.original.engine === "postgres" ? "postgres/manifest.json" : "verification.json"); const l = JSON.parse(fs.readFileSync(c, "utf8")); const u = a ?? (r && s.original.engine === "postgres" ? l.verification : l); const d = i && r && o.direction.from === "postgres" ? readBackupEngine(i) : r ? s.original : s.intended; await runDatabasePortTask({ operation: "verify", sourcePath: i ?? (r ? s.originalCapture.path : stagePath(e, t)), engine: r ? o.direction.from : o.direction.to, storeId: s.storeId, namespace: d.engine === "postgres" ? d.namespace : "", verification: u, config: postgresConfig(n) }, e); } async function assertOriginal(e, t, n) { const { target: r, input: i } = storeAt(e, t); e.target = i.original.path; privatePaths(e, [i.original.path]); const a = fs.lstatSync(i.original.path, { bigint: true }); if (String(a.dev) !== i.dev || String(a.ino) !== i.ino) refuse(e, "changed source identity", "captured device and inode"); if (e.stateReceipt?.path === e.target && e.stateReceipt.engine === manifest(e).direction.from) { await verify(e, t, n, true, e.target, e.stateReceipt.verification); return; } if (r.original.engine === "postgres") { await verify(e, t, n, true); return; } const o = path.join(storeDirectory(e, t), `source-check-${randomUUID()}.sqlite`); await createVerifiedSqliteSnapshot({ sourcePath: i.original.path, targetPath: o, preserveRowIds: true }); if ((await captureDatabaseArtifact(o)).sha256 !== (await captureDatabaseArtifact(i.image)).sha256) refuse(e, "changed source data", "captured original SQLite image"); } async function prepareStores(e, t, n) { e.phase = n ? "rollback" : "prepare stores"; const r = manifest(e); for (const [i, a] of r.targets.entries()) { e.target = livePath(a); privatePaths(e, [e.target]); const o = await captureDatabaseArtifact(e.target); const s = e.stateReceipt?.path === e.target ? e.stateReceipt : void 0; if (n && s) await verify(e, i, t, s.engine === r.direction.from, e.target, s.verification); const c = r.artifacts.find((t) => t.path === stagePath(e, i)); const l = s?.engine === r.direction.from || o.sha256 === a.originalCapture.sha256 || r.artifacts.some((e) => path.basename(e.path).startsWith("rollback-") && e.sha256 === o.sha256); const u = s?.engine === r.direction.to || c && o.sha256 === c.sha256; if (!u && !(n && l)) { if (n && a.original.engine === "postgres") await assertDatabaseArtifact(storeAt(e, i).input.original); else await assertOriginal(e, i, t); } if (!n && u) { await verify(e, i, t, false, s ? e.target : void 0, s?.verification); continue; } let d = n ? a.originalCapture.path : stagePath(e, i); if (n && a.original.engine === "postgres" && s?.engine !== r.direction.from) try { await verify(e, i, t, true, !u ? e.target : void 0); } catch { d = path.join(storeDirectory(e, i), `rollback-${randomUUID()}.sqlite`); await preparePostgresRestore({ directory: path.dirname(a.originalCapture.path), anchorPath: d, profile: "exact", config: postgresConfig(t), expectedSource: { storeId: a.storeId, namespace: a.original.namespace }, assertCurrent: e.assertCurrent }); r.artifacts.push(await captureDatabaseArtifact(d)); revise(e); } if (n && (l || !u) && d === a.originalCapture.path) continue; if (!n) await verify(e, i, t); e.phase = n ? "rollback" : "publish stores"; await runDatabasePortTask({ operation: "checkpoint", sourcePath: e.target }, e); const f = await captureDatabaseArtifact(e.target), p = await captureDatabaseArtifact(d); const m = await prepareVerifiedSqliteFile({ sourcePath: d, sourceIdentity: fs.lstatSync(d, { bigint: true }), targetPath: e.target, expectedContent: { sha256: p.sha256, sizeBytes: p.size }, replaceExisting: { expectedIdentity: fs.lstatSync(e.target, { bigint: true }), expectedContent: { sha256: f.sha256, sizeBytes: f.size }, assertCustody: e.assertCurrent } }); e.prepared.push([e.target, m]); } } async function publishStores(e) { e.phase = "publish stores"; const t = manifest(e); e.target = e.prepared[0]?.[0] ?? e.configPath; if (t.state === "preparing") { t.state = "publishing"; revise(e); } await closeDatabasePortState(e); for (const [t, n] of e.prepared) { e.target = t; await n.publish(); } } /** Config writes can change shared state after its immutable port capture. */ async function withDatabasePortConfigStateReceipt(e, t, n) { const r = path.join(e.stateDir, "state", "openclaw.sqlite"); if (!manifest(e).targets.some((e) => livePath(e) === r)) return await n(); try { return await n(); } finally { e.assertCurrent(); await closeDatabasePortState(e); const { engine: n } = readBackupEngine(r); const { verification: i } = await runDatabasePortTask({ operation: "inspect", sourcePath: r, config: postgresConfig(t), to: n }, e); const a = { path: r, engine: n, verification: i }; await record(e, path.join(e.directory, `config-state-${randomUUID()}.json`), a); e.stateReceipt = a; } } function loadDatabasePortStateReceipt(e) { const t = manifest(e).artifacts.findLast((t) => t.path.startsWith(path.join(e.directory, "config-state-"))); if (t) e.stateReceipt = JSON.parse(fs.readFileSync(t.path, "utf8")); } //#endregion //#region src/commands/doctor-database-port-working.ts async function copyPortArtifact(e, t, n) { await publishVerifiedSqliteFile({ sourcePath: t.path, sourceIdentity: fs.lstatSync(t.path, { bigint: true }), targetPath: n, expectedContent: { sha256: t.sha256, sizeBytes: t.size }, beforePublish: e.assertCurrent, afterPublish: (t) => { t.assertTargetUnchanged(e.assertCurrent); } }); } async function privateMigrate(e, t, n, r) { e.phase = "private migrate"; const i = manifest(e); const a = path.join(storeDirectory(e, t), "working-"); const o = i.artifacts.find((e) => e.path.startsWith(a)); const s = o ?? i.artifacts.find((n) => n.path === storeAt(e, t).input.image); if (!s) refuse(e, "missing recorded original image", "manifest-bound SQLite capture"); await copyPortArtifact(e, s, r); if (o) return; await runDatabasePortTask({ operation: "migrate", sourcePath: r, config: n }, e); await runDatabasePortTask({ operation: "checkpoint", sourcePath: r }, e); syncDatabasePortPath(r); const c = await captureDatabaseArtifact(r); const l = `${a}${randomUUID()}.sqlite`; await copyPortArtifact(e, c, l); i.artifacts.push({ ...c, path: l }); revise(e); } /** Preserve the durable journal while SQL consumes a rebuildable private image. */ async function withDatabasePortWorkingCopy(e, t, n, r) { const i = resolvePrivateSqliteSnapshotStagingRoot(e.env); if (resolvePathJournalPolicy(i) !== "wal") refuse(e, "nonlocal or unclassified working cache", "XDG_CACHE_HOME on a local filesystem"); const a = await createPrivateSqliteTempDirectory(i, "database-port-working-"); const o = path.join(a, "database.sqlite"); await privateMigrate(e, t, n, o); const s = await r(o); return withStateInspectionCleanup(a, async () => s); } //#endregion //#region src/commands/doctor-database-port.ts async function preflight(e, t) { e.phase = "preflight"; let n = await readDatabasePortConfigSnapshot(e); const r = n.snapshot.authoredConfig ?? n.snapshot.sourceConfig; const i = normalizeLegacyWorkboardDatabaseConfig(r, e.env); if (!t.dryRun && i !== r) { await writeConfigFile(i, { ...n.writeOptions, baseSnapshot: n.snapshot, inputBase: "source", assertCurrent: e.assertCurrent, observe: false, skipOutputLogs: true, skipRuntimeSnapshotRefresh: true }); n = await readDatabasePortConfigSnapshot(e); } const a = await configInputs(e); for (const e of a) await assertDatabaseArtifact(e); const o = n.snapshot.config; assertPortSelection(o, t.to, e.family); const s = resolveDatabaseFamilyEngines(o)[e.family ?? "state"], c = t.to; if (getDatabaseEngineInput("state")) (await preparePluginMetadataMachineStateAsync({ env: e.env, stateDir: e.stateDir, artifactPreservingReadOnly: true }))(); await assertDatabasePortPluginMigrationsComplete({ config: o, env: e.env, stateDir: e.stateDir, to: c, family: e.family }); const l = await inspectDatabasePortSources(e, o, s, c); let u = l.all; const d = l.owner; if ((!e.family || e.family === "state") && await prepareSharedStatePortSource(e, s, c, t.dryRun)) u = await discoverBackupDatabasePaths({ stateDir: e.stateDir, config: o, env: e.env }); const f = u.filter((t) => d(t) && (!e.family || d(t) === e.family)); const p = /* @__PURE__ */ new Map(); for (const t of f) { const n = d(t) === "state" ? resolveStateClientCredentialEnvironment({ path: t, env: e.env }) : void 0; if (n) { const e = resolveClientCredentialStorePath(n); if (u.includes(e)) p.set(e, t); } } const m = f.filter((e) => !p.has(e)); const h = []; const g = /* @__PURE__ */ new Map(); for (const t of u.filter((e) => !p.has(e))) { e.target = t; privatePaths(e, [t]); if (!m.includes(t)) { const n = readBackupEngine(t); if (n.engine === "postgres") { const n = await readPostgresBackupFamily(t, postgresConfig(o)); if (!d(t) || n !== d(t)) refuse(e, "unclassified PostgreSQL anchor", "registered ownership matching its physical family"); } h.push({ path: t, engine: n.engine }); continue; } const n = await runDatabasePortTask({ operation: "inspect", sourcePath: t, config: postgresConfig(o), to: c }, e); if (e.family && n.family !== e.family) refuse(e, "store outside its registered family", "matching physical family ownership"); if (n.engine !== s) refuse(e, `${n.engine} store with ${s} config`, "matching physical/config engines"); g.set(t, n); } for (const [t, n] of p) { assertLocalCredentialPortCompanion(e, t, n, g.get(n)?.family); h.push({ path: t, engine: "sqlite" }); } capacity(e, m.map((e) => ({ path: e, size: fs.statSync(e).size }))); if (m.length && s !== c) { e.engineSelection.postgres ??= await resolveDatabaseEngineInput(postgresConfig(o), e.env); await runDatabasePortTask({ operation: "preflight", config: postgresConfig(o), probe: false }, e); } return { snapshot: n, configInputs: a, from: s, to: c, stores: m, inspected: g, migrations: m.filter((e) => g.get(e)?.migrationRequired), outOfScope: h }; } async function captureOriginals(e, t) { e.phase = "capture originals"; e.assertCurrent(); const n = randomUUID(); e.directory = prepareDatabasePortDirectory(e.stateDir, n); const r = [], i = []; const a = t.snapshot.snapshot.authoredConfig ?? t.snapshot.snapshot.sourceConfig; e.inputs = { stores: [], selection: { path: e.family ? [ "database", "families", e.family, "engine" ] : ["database", "engine"], originalValue: (e.family ? a.database?.families?.[e.family]?.engine : a.database?.engine) ?? null, effectiveSource: t.from }, outOfScope: t.outOfScope }; for (const [n, [a, o]] of [...t.inspected].entries()) { e.target = a; e.assertCurrent(); const s = storeDirectory(e, n); fs.mkdirSync(s, { mode: 448 }); if (o.notes?.length) { const t = path.join(s, "inspection.json"); writeDatabasePortArtifact(t, `${JSON.stringify({ notes: o.notes })}\n`, e.assertCurrent); r.push(await captureDatabaseArtifact(t)); } const c = fs.lstatSync(a, { bigint: true }), l = await captureDatabaseArtifact(a); let u = path.join(s, "original.sqlite"), d = u; if (t.from === "postgres") { const n = path.join(s, "postgres"); await capturePostgresBackup({ sourcePath: a, directory: n, config: postgresConfig(t.snapshot.snapshot.config), profile: "exact", assertCurrent: e.assertCurrent }); u = path.join(n, "database.sqlite"); d = path.join(n, "anchor.sqlite"); r.push(...await Promise.all([ u, d, path.join(n, "manifest.json") ].map(captureDatabaseArtifact))); } else { await createVerifiedSqliteSnapshot({ sourcePath: a, targetPath: u, preserveRowIds: true }); r.push(await captureDatabaseArtifact(u)); } await assertDatabaseArtifact(l); e.inputs.stores.push({ dev: String(c.dev), ino: String(c.ino), original: l, image: u }); const f = o.storeId ?? randomUUID(); i.push({ storeId: f, sourceSchemaVersion: o.version, targetSchemaVersion: o.targetVersion, descriptorHash: o.descriptorHash, original: t.from === "sqlite" ? { engine: "sqlite", path: a } : { engine: "postgres", anchorPath: a, namespace: o.namespace }, intended: t.to === "sqlite" ? { engine: "sqlite", path: a } : { engine: "postgres", anchorPath: a, namespace: postgresStoreNamespace(e.engineSelection.postgres.schemaPrefix, o.family, f) }, originalCapture: await captureDatabaseArtifact(d), verification: null }); const p = o.family === "state" ? resolveStateClientCredentialEnvironment({ path: a, env: e.env }) : void 0; if (p) { const t = capturePortClientCredentialBinding({ env: p, sourcePath: d, sourceFile: { path: l.path, dev: String(c.dev), ino: String(c.ino) } }); const n = path.join(s, "client-credential-binding.json"); writeDatabasePortArtifact(n, `${JSON.stringify(t)}\n`, e.assertCurrent); r.push(await captureDatabaseArtifact(n)); } } for (const [n, i] of t.configInputs.entries()) { await assertDatabaseArtifact(i); const t = path.join(e.directory, `config-${n}.json`); writeDatabasePortArtifact(t, fs.readFileSync(i.path), e.assertCurrent); r.push(await captureDatabaseArtifact(t)); } const o = path.join(e.directory, "inputs.json"); writeDatabasePortArtifact(o, `${JSON.stringify(e.inputs)}\n`, e.assertCurrent); r.push(await captureDatabaseArtifact(o)); const s = fs.lstatSync(e.stateDir, { bigint: true }); e.manifest = { version: 1, operationId: n, revision: 1, state: "preparing", root: { stateDir: e.stateDir, dev: String(s.dev), ino: String(s.ino) }, direction: { from: t.from, to: t.to }, originalConfig: t.configInputs, artifacts: r, targets: i }; writeDatabasePortManifest(e.stateDir, e.manifest, e.assertCurrent); capacity(e, e.inputs.stores.map(({ original: e, image: t }) => ({ path: e.path, size: fs.statSync(t).size }))); } async function stageMaterialize(e, t, n) { const r = manifest(e), { target: i } = storeAt(e, t); e.target = livePath(i); if (i.verification) return; await withDatabasePortWorkingCopy(e, t, n, async (a) => { e.phase = "stage/materialize"; const o = await runDatabasePortTask({ operation: "stage", sourcePath: a, targetPath: stagePath(e, t), to: r.direction.to, storeId: i.storeId, namespace: i.intended.engine === "postgres" ? i.intended.namespace : "", config: postgresConfig(n), resume: true, sourceVerification: r.direction.from === "postgres" ? JSON.parse(fs.readFileSync(path.join(storeDirectory(e, t), "postgres/manifest.json"), "utf8")).verification : void 0 }, e); const s = o.verification; if (o.plannerStatistics) (e.plannerStatistics ??= []).push({ path: livePath(i), result: o.plannerStatistics }); i.verification = { contentHash: digest(s.tables), allocationHash: digest(s.allocations), catalogHash: o.descriptorHash, rowCount: Object.values(s.tables).reduce((e, t) => e + t.rows, 0), ownerAdmitted: true }; r.artifacts.push(await captureDatabaseArtifact(stagePath(e, t))); await record(e, path.join(storeDirectory(e, t), "verification.json"), s); }); } async function classifyConfig(e) { const t = await readDatabasePortConfigSnapshot(e), n = await configInputs(e), r = manifest(e); if (isDeepStrictEqual(n, r.originalConfig)) return { current: t, engine: r.direction.from }; if (!isDeepStrictEqual(n.map((e) => e.path), r.originalConfig.map((e) => e.path))) refuse(e, "changed config include graph", "captured config inputs"); for (const e of r.artifacts.filter((e) => path.basename(e.path).startsWith("config-intent-"))) { const n = object({ hash: string(), engine: _enum(["sqlite", "postgres"]) }).parse(JSON.parse(fs.readFileSync(e.path, "utf8"))); if (digest(t.snapshot.sourceConfig) === n.hash) return { current: t, engine: n.engine }; } return refuse(e, "unrecognized config contents", "recorded old or prepared new config"); } async function switchConfig(e, t) { e.phase = "switch config"; e.target = e.configPath; const { current: n, engine: r } = await classifyConfig(e), i = manifest(e); const a = t ? i.direction.from : i.direction.to; const o = e.inputs.selection; const s = o?.path ?? ["database", "engine"]; const c = t ? o?.originalValue ?? e.inputs.originalEngine ?? void 0 : e.family && a === (n.snapshot.config.database?.engine ?? "sqlite") ? void 0 : a; if (r !== a) { const t = structuredClone(n.snapshot.authoredConfig ?? n.snapshot.sourceConfig); const r = c === void 0; if (r) unsetConfigValueAtPath(t, s); else setConfigValueAtPath(t, s, c); const i = await withDatabasePortConfigStateReceipt(e, n.snapshot.config, () => writeConfigFile(t, { ...n.writeOptions, baseSnapshot: n.snapshot, inputBase: "source", explicitSetPaths: r ? [] : [s], unsetPaths: r ? [s] : void 0, assertCurrent: e.assertCurrent, observe: false, skipOutputLogs: true, skipRuntimeSnapshotRefresh: true, beforeCommit: async () => { await publishStores(e); await selectDatabasePortEngine(e, n.snapshot.config, !e.family || e.family === "state" ? a : e.engineSelection.effectiveEngines.state); e.phase = "switch config"; e.target = e.configPath; }, preCommitRuntimePreflight: async (t) => { await record(e, path.join(e.directory, `config-intent-${randomUUID()}.json`), { hash: digest(t), engine: a }); } })); if (!(await configInputs(e)).some((e) => e.sha256 === i.persistedHash)) refuse(e, "config receipt hash mismatch", "writer's persisted hash"); } else await publishStores(e); for (const t of i.originalConfig) { e.assertCurrent(); syncDatabasePortPath(t.path); syncDatabasePortPath(path.dirname(t.path)); } } async function resume(e) { const t = manifest(e), n = (await readDatabasePortConfigSnapshot(e)).snapshot.config; assertPortSelection(n, t.direction.to, e.family); if (t.state === "preparing") { for (const e of t.originalConfig) await assertDatabaseArtifact(e); e.engineSelection.postgres ??= await resolveDatabaseEngineInput(postgresConfig(n), e.env); for (const r of t.targets.keys()) await stageMaterialize(e, r, n); } return await finishPort(e, n, false); } async function rollback(e) { const t = e.inputs.selection; const n = (await readDatabasePortConfigSnapshot(e)).snapshot.config; const r = t?.originalValue ?? e.inputs.originalEngine; const i = t?.path.length === 4 ? n.database?.engine : void 0; if ((resolveConfigEnvVars(r ?? i, e.env) ?? "sqlite") !== manifest(e).direction.from) refuse(e, "changed engine environment", "original engine environment before rollback"); return await finishPort(e, (await readDatabasePortConfigSnapshot(e)).snapshot.config, true); } async function finishPort(e, t, n) { assertPortSelection(t, n ? manifest(e).direction.from : manifest(e).direction.to, e.family); try { const r = n && manifest(e).state === "preparing"; if (!r || manifest(e).direction.from === "postgres") e.engineSelection.postgres ??= await resolveDatabaseEngineInput(postgresConfig(t), e.env); if (r) for (const n of manifest(e).targets.keys()) await assertOriginal(e, n, t); else await prepareStores(e, t, n); await withConfigWriteLock(e.configPath, async () => { if (r) await classifyConfig(e); else await switchConfig(e, n); }, e.env, e.assertCurrent); } finally { for (const [, t] of e.prepared) await t.cleanup(); } return finalize(e, n ? "rolled-back" : "ported"); } async function loadRecovery(e) { const t = manifest(e); e.directory = path.join(path.dirname(databasePortManifestPath(e.stateDir)), t.operationId); for (const n of t.artifacts) { if (!n.path.startsWith(`${e.directory}${path.sep}`)) refuse(e, "artifact outside operation directory", "private operation-owned artifacts"); privatePaths(e, [n.path]); const t = fs.lstatSync(n.path); if ((t.mode & 511) !== 384 || process.getuid && t.uid !== process.getuid()) refuse(e, "nonprivate artifact", "0600 caller-owned file"); await assertDatabaseArtifact(n); } e.inputs = inputsSchema.parse(JSON.parse(fs.readFileSync(path.join(e.directory, "inputs.json"), "utf8"))); if (e.inputs.selection) { const n = e.inputs.selection; e.family = n.path.length === 4 ? n.path[2] : void 0; if (n.effectiveSource !== t.direction.from) refuse(e, "mismatched source engine", "captured effective source engine"); } if (e.inputs.stores.length !== t.targets.length || t.targets.some((t, n) => { const r = e.inputs?.stores[n]?.original.path; return !r || r !== livePath(t); })) refuse(e, "mismatched target set", "complete captured store set"); loadDatabasePortStateReceipt(e); } async function doctorDatabasePort(e) { assertDatabasePortPlatformSupported(); const t = path.resolve(resolveStateDir()); const n = { family: e.family === void 0 ? void 0 : databasePortFamilySchema.parse(e.family), stateDir: t, configPath: path.resolve(resolveConfigPath()), env: process.env, engineSelection: { effectiveEngines: resolveDatabaseFamilyEngines({}) }, assertCurrent: () => {}, phase: "preflight", target: t, directory: "", prepared: [] }; try { privatePaths(n, [t, n.configPath]); if (!e.resume && !e.rollback) assertPortSelection((await readDatabasePortConfigSnapshot(n)).snapshot.config, e.to, n.family); if (hasActiveGatewayStateOwner(path.join(t, "state", "openclaw.sqlite"))) refuse(n, "hosted Gateway owner", "exclusive offline custody"); const r = e.resume ?? e.rollback; const i = r ? { manifestPath: path.resolve(r), operationId: object({ operationId: uuid() }).parse(JSON.parse(fs.readFileSync(r, "utf8"))).operationId, action: e.rollback ? "rollback" : "resume" } : void 0; const a = await withDatabasePortStateOwner(n, i, async () => { if (i) { n.manifest = assertDatabasePortRecoveryAllowed(n.stateDir, i); await loadRecovery(n); if (n.manifest.state === "complete") return finalize(n, n.manifest.outcome); return i.action === "resume" ? await resume(n) : await rollback(n); } const t = await preflight(n, e); if (e.dryRun || t.from === t.to || !t.stores.length) return { phase: e.dryRun ? "preflight" : "complete", engine: t.from, to: t.to, stores: t.stores, migrations: t.migrations, notes: [...t.inspected].flatMap(([e, t]) => (t.notes ?? []).map((t) => `${e}: ${t}`)), remainingSqlite: t.outOfScope.filter((e) => e.engine === "sqlite").map((e) => e.path), ...n.family ? { family: n.family, outOfScope: t.outOfScope } : {}, verification: e.dryRun ? `${t.migrations.length} stores need private migration; copy and privilege probe not performed` : "verified no-op", serverCapacity: "unknown" }; await captureOriginals(n, t); return await resume(n); }); const o = n.manifest?.outcome === "ported" && (!n.family || n.family === "agent") ? await rebuildPortedAgentMemory({ stateDir: t, stores: a.stores }) : void 0; return o ? { ...a, memoryRebuilds: o } : a; } catch (e) { return refuseFailure(n, e); } } //#endregion export { doctorDatabasePort };