UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

439 lines (438 loc) • 18.5 kB
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.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 { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, t as CLIENT_CREDENTIAL_CUTOVER_SCHEMA_VERSION } from "./openclaw-state-db-contract-DfPjvL0M.mjs"; import { c as resolveRuntimeServiceCommit, o as resolveRuntimeServiceBuildId, t as VERSION } from "./version-GlxUMdxI.mjs"; import { i as resolveImmutableSqliteFileUri, n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs"; import { p as syncDirectorySync, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs"; import { o as sameFileMutationFingerprint } from "./file-descriptor-DQ-v5bLt.mjs"; import { c as hashPublishedFileSync } from "./sqlite-snapshot-file-ClNY94fE.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { r as assertStateDatabaseAccessAllowed } from "./gateway-state-owner-Bnv5owvG.mjs"; import { l as resolveSqliteInspectionSignal } from "./sqlite-readonly-worker-D3pRJU7r.mjs"; import { o as isTerminalSqliteIntegrityError, r as assertSqliteIntegrity, u as sqliteIntegrityCheckSteps } from "./sqlite-integrity-CCmEgO_m.mjs"; import { i as getDoctorMigrationFullBackup, o as hasUpdateDoctorMigrationCapture, s as recordDoctorMigrationFullBackup } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs"; import { t as stateEngineInput } from "./openclaw-state-db-engine-input-Dy8v5WSG.mjs"; import { a as isStatePostgres } from "./openclaw-state-db-engine-sM0tpxNy.mjs"; import { a as needsOpenClawStateDatabaseSchemaRepair } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { h as resolveSchemaMigrationIntegrityCheck, m as resolveSchemaMigrationBackupTables } from "./openclaw-state-db-ARhwdPJg.mjs"; import { t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs"; import { n as agentEngineInput } from "./openclaw-agent-db-engine-CFD02117.mjs"; import { l as invalidateOpenClawAgentDatabaseIntegrityBeforeMutation } from "./openclaw-agent-db-lease-BZhGt_sk.mjs"; import { n as withSqliteIntegrityWorkerScope } from "./sqlite-integrity-worker-D_lHVvZY.mjs"; import { t as runSqliteIntegrityOperationInWorker } from "./sqlite-integrity-operation-Cqe4C-U7.mjs"; import { t as createDoctorRehearsalDatabaseCoverage } from "./doctor-rehearsal-databases-BTJBQN1P.mjs"; import { f as isUpdateDoctorLintPass } from "./update-phase-YdZvaQsy.mjs"; import { a as inspectScopedMigrationTables, i as inspectScopedMigrationSnapshot, n as createScopedMigrationSnapshot, r as createScopedMigrationSnapshotSync, s as scopedMigrationTablesMatchFullBackup, t as ScopedMigrationSnapshotUnsupportedError } from "./sqlite-migration-scoped-snapshot-p3QIp2zu.mjs"; import { n as recordDoctorMigrationBackups } from "./doctor-migration-backup-artifacts-DjxmWbF6.mjs"; import { closeSync, existsSync, fsyncSync, lstatSync, openSync, realpathSync, statSync, unlinkSync } from "node:fs"; import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; //#region src/commands/doctor-migration-backup.ts /** A standalone retirement needs a fresh snapshot from the same source transaction. */ function captureFreshDoctorMigrationTables(e, t) { const n = getOpenClawDatabaseMaintenanceScope(); if (hasUpdateDoctorMigrationCapture()) throw new Error("Updater migration requires its captured source generation."); if (!n?.ownsSchemaMaintenance || !e.isTransaction) throw new Error("Fresh migration backup requires schema maintenance and its source transaction."); const assertCurrent = () => { n.assertAdmission(); assertStateDatabaseAccessAllowed(t.path); if (!e.isOpen || !e.isTransaction) throw new Error("Fresh migration backup lost its source transaction."); }; assertCurrent(); const r = randomUUID(); let i; try { i = createScopedMigrationSnapshotSync(e, { sourcePath: t.path, targetPath: `${t.path}.pre-startup-migration-${r}.scoped.bak`, tables: t.tables, assertCurrent }); } catch (n) { const r = getDoctorMigrationFullBackup(t.path); if (!(n instanceof ScopedMigrationSnapshotUnsupportedError) || !r) throw n; if (!scopedMigrationTablesMatchFullBackup(e, t.path, r.path, t.tables)) throw new DoctorMaintenanceRefusalError(`Pre-migration backup no longer contains current credentials: ${r.path}. Preserve the database and its backup before retrying.`, { kind: "data-at-risk", reason: "incomplete-migration" }); assertCurrent(); return { capture: { path: t.path, generation: r.generation ?? hashPublishedFileSync(r.path, lstatSync(r.path, { bigint: true })).sha256, assertCurrent }, backupPath: r.path }; } recordDoctorMigrationBackups(t.env, r, [{ path: t.path, identity: statSync(t.path, { bigint: true }), archivePath: i.path }], true); return { capture: { path: t.path, generation: i.generation, assertCurrent }, backupPath: i.path }; } /** Preserve the old database generation before Doctor advances its schemas. */ async function backupDoctorMigrationDatabases(e) { const t = resolveOpenClawStateSqlitePath(e.env); const n = new Set(e.pendingDatabasePaths); if (!isStatePostgres() && existsSync(t) && needsOpenClawStateDatabaseSchemaRepair(t)) n.add(t); if (n.size === 0) return { changes: [], warnings: [] }; const r = getOpenClawDatabaseMaintenanceScope(); if (!r?.ownsSchemaMaintenance) throw new Error("Pre-migration SQLite backups require Doctor maintenance ownership."); const i = !hasUpdateDoctorMigrationCapture() && e.pendingMigrations?.some((e) => e.kind === "state" && e.foundVersion < 29) ? e.verifiedSnapshots?.filter((e) => e.role !== "global") : e.verifiedSnapshots; const a = /* @__PURE__ */ new Map(); for (const r of /* @__PURE__ */ new Set([ ...n, ...e.databasePaths, t ])) { if ((r === t ? stateEngineInput() : agentEngineInput()) || !existsSync(r)) continue; const i = e.pendingMigrations?.find((e) => e.path === r); if (e.versionMigrationsOnly && i?.kind === "agent" && e.agentDatabaseTargets?.some((e) => e.path === r)) invalidateOpenClawAgentDatabaseIntegrityBeforeMutation(r); if (i) a.set(realpathSync.native(r), resolveSchemaMigrationIntegrityCheck(i, e.check)); else if (e.versionMigrationsOnly && !n.has(r)) a.set(realpathSync.native(r), { check: e.check ?? "quick" }); } const o = new Map([.../* @__PURE__ */ new Set([ ...n, ...e.databasePaths, ...isStatePostgres() ? [t] : [] ])].flatMap((e) => { const n = e === t ? stateEngineInput() : agentEngineInput(); return n ? [[e, n]] : []; })); if (o.size > 0) { const { backupDoctorPostgresMigration: s } = await import("./doctor-postgres-migration-DjHQ_6ks.mjs"); const c = []; const l = {}; for (const [e, t] of o) { const n = await s(e, t, r); c.push(...n.changes); if (n.generation !== void 0) l[e] = n.generation; } const u = [...n].filter((e) => !o.has(e)); if (!o.has(t) && existsSync(t)) u.push(t); const d = await backupDoctorSqliteDatabases({ ...e, verifiedSnapshots: i, pendingDatabasePaths: u, databasePaths: e.databasePaths.filter((e) => !o.has(e)), authority: { assertCurrent: () => r.assertAdmission() }, stateFamilyBackedUp: o.has(t) ? true : void 0, integrityChecks: a }); return { ...d, changes: [...c, ...d.changes], versionMigrations: e.pendingMigrations, ...Object.keys(l).length > 0 ? { postgresGenerations: l } : {} }; } const s = /* @__PURE__ */ new Map(); if (e.versionMigrationsOnly && !isStatePostgres() && !isUpdateDoctorLintPass(e.env)) { for (const t of n) { const n = e.pendingMigrations?.find((e) => e.path === t); const r = n && resolveSchemaMigrationBackupTables(n); if (!r) { s.clear(); break; } s.set(realpathSync.native(t), r); } if ([...n].some((e) => e !== t) && existsSync(t)) s.delete(realpathSync.native(t)); } const backup = async () => { if (s.size > 0) await withSqliteIntegrityWorkerScope(() => r.assertAdmission(), async () => { const e = resolveSqliteInspectionSignal() ?? new AbortController().signal; for (const n of s.keys()) try { var t = _usingCtx(); const i = t.u(openNodeSqliteDatabase(n, { readOnly: true })); await runSqliteIntegrityOperationInWorker(sqliteIntegrityCheckSteps(i, n, void 0, a.get(n)), { busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, signal: e, beforeResume: () => r.assertAdmission() }); } catch (e) { t.e = e; } finally { t.d(); } }); return backupDoctorSqliteDatabases({ ...e, verifiedSnapshots: i, pendingDatabasePaths: [...n], authority: { assertCurrent: () => r.assertAdmission() }, migrationTables: s.size > 0 ? s : void 0, integrityChecks: a }); }; let c; try { c = await backup(); } catch (t) { if (t instanceof DoctorMaintenanceRefusalError || !e.agentDatabaseTargets?.length || !collectNestedErrorCandidates(t).some((e) => e instanceof Error && isTerminalSqliteIntegrityError(e))) throw t; const { repairDoctorSessionWindowsBeforeMigration: n } = await import("./state-migrations.session-window-repair-DsgiuDZi.mjs"); const r = await n({ env: e.env, targets: e.agentDatabaseTargets }); if (r.length === 0) throw t; c = await backup(); c.changes = [...r, ...c.changes]; } return { ...c, ...s.size > 0 ? { versionMigrations: e.pendingMigrations?.filter((n) => n.kind === "state" ? n.path === t : e.agentDatabaseTargets?.some((e) => e.path === n.path)) } : {} }; } /** Schema and same-schema repairs share verified snapshots under their existing Doctor owner. */ async function backupDoctorSqliteDatabases(e) { const t = new Set(e.pendingDatabasePaths); if (t.size === 0) return { changes: [], warnings: [] }; const n = resolveOpenClawStateSqlitePath(e.env); if (existsSync(n)) { if (isStatePostgres() && !e.stateFamilyBackedUp) throw new Error("PostgreSQL state requires an exact state-family backup before native database repairs. Run the Doctor migration backup phase first."); if (!isStatePostgres()) t.add(n); } const { authority: r } = e; r.assertCurrent(); const i = e.requireSnapshots ? void 0 : createDoctorRehearsalDatabaseCoverage(e.env); i?.admit([...t, ...e.databasePaths]); const a = [.../* @__PURE__ */ new Set([...t, ...e.databasePaths])].filter((e) => !i?.excludes(e)); if (a.length === 0) { i?.assertCurrent(); return { changes: [], warnings: [] }; } const { createVerifiedSqliteSnapshot: o } = await import("./sqlite-snapshot-DGhn22ul.mjs"); const { sanitizeOpenClawStateLeaseRows: s } = await import("./openclaw-state-snapshot-sanitizer-CTxg0eOm.mjs"); r.assertCurrent(); i?.assertCurrent(); const c = [...new Set([...t].filter((e) => !i?.excludes(e)).map((e) => realpathSync.native(e)))]; if (!e.requireSnapshots && c.length > 0 && c.every((t) => { const { dev: n, ino: r } = statSync(t, { bigint: true }); return n !== 0n && r !== 0n && e.verifiedSnapshots?.some((e) => e.dev === n && e.ino === r); })) return { changes: [], warnings: [] }; const l = [.../* @__PURE__ */ new Set([...c, ...a.map((e) => realpathSync.native(e))])].toSorted().map((e) => ({ path: e, identity: statSync(e, { bigint: true }) })); const u = createHash("sha256").update(JSON.stringify([ ...e.repair ? [e.repair.key] : [], ...e.migrationTables ? ["declared-schema-migrations"] : [], VERSION, resolveRuntimeServiceBuildId(), resolveRuntimeServiceCommit(), 36, 38, l.map(({ path: e, identity: t }) => [ e, String(t.dev), String(t.ino) ]) ])).digest("hex"); const d = [ u.slice(0, 8), u.slice(8, 12), `8${u.slice(13, 16)}`, `8${u.slice(17, 20)}`, u.slice(20, 32) ].join("-"); const assertInventory = () => { r.assertCurrent(); i?.assertCurrent(); for (const { path: e, identity: t } of l) { const n = statSync(e, { bigint: true }); if (!n.isFile() || n.dev !== t.dev || n.ino !== t.ino) throw new Error(`Pre-migration SQLite backup source changed: ${e}`); } }; const f = []; const fullTargetFor = (e) => `${e}.pre-startup-migration-${d}.bak`; const scopedTargetFor = (e) => `${e}.pre-startup-migration-${d}.scoped.bak`; const p = /* @__PURE__ */ new Map(); for (const { path: e } of l) { const t = fullTargetFor(e); const n = scopedTargetFor(e); if (lstatSync(t, { throwIfNoEntry: false }) && lstatSync(n, { throwIfNoEntry: false })) throw new Error(`Ambiguous pre-migration backup group for ${e}`); p.set(e, lstatSync(n, { throwIfNoEntry: false }) ? n : t); } const targetFor = (e) => p.get(e); const m = `${fullTargetFor(existsSync(n) ? realpathSync.native(n) : l[0].path)}.capturing`; let h = lstatSync(m, { bigint: true, throwIfNoEntry: false }); const g = l.some(({ path: e }) => lstatSync(targetFor(e), { throwIfNoEntry: false }) !== void 0); if (!h && !g) { assertInventory(); const e = openSync(m, "wx", 384); try { fsyncSync(e); } finally { closeSync(e); } h = lstatSync(m, { bigint: true }); } const assertCapture = () => { assertInventory(); if (h && (!h.isFile() || h.size !== 0n || !sameFileMutationFingerprint(h, lstatSync(m, { bigint: true })))) throw new DoctorMaintenanceRefusalError(`Pre-migration SQLite backup capture marker changed: ${m}`, { kind: "data-at-risk", reason: "incomplete-migration" }); }; const syncCaptureDirectory = () => requireDirectorySync(syncDirectorySync(path.dirname(m)), "Migration backup directory"); if (h) { assertCapture(); syncCaptureDirectory(); for (const { path: e } of l) { const t = targetFor(e); const n = lstatSync(t, { bigint: true, throwIfNoEntry: false }); if (!n) continue; assertCapture(); if (!n.isFile() || !sameFileMutationFingerprint(n, lstatSync(t, { bigint: true }))) throw new Error(`Incomplete pre-migration SQLite backup changed: ${t}`); unlinkSync(t); f.push(`Discarded incomplete pre-migration SQLite backup: ${t}`); } } const _ = /* @__PURE__ */ new Map(); if (h && e.migrationTables?.size) { const t = realpathSync.native(resolveStateDir(e.env)); try { for (const [n, r] of e.migrationTables) { if (!isPathInside(t, n)) throw new ScopedMigrationSnapshotUnsupportedError("source is outside offline restore custody"); _.set(n, inspectScopedMigrationTables(n, r)); } } catch (e) { if (!(e instanceof ScopedMigrationSnapshotUnsupportedError)) throw e; _.clear(); f.push(`Using full migration backups: ${e.message}`); } } if (h) for (const { path: e } of l) p.set(e, _.has(e) ? scopedTargetFor(e) : fullTargetFor(e)); const v = /* @__PURE__ */ new Map(); const afterPublish = (e) => { const t = e.assertTargetUnchanged(); v.set(`${t.stat.dev}:${t.stat.ino}`, t); return t.content.sha256; }; for (const { path: t } of l) { assertCapture(); const n = targetFor(t); const r = lstatSync(n, { bigint: true, throwIfNoEntry: false }); if (r) { try { if (!r.isFile()) throw new Error("Backup must be a regular file"); if (n === scopedTargetFor(t)) { if (inspectScopedMigrationSnapshot(n).sourcePath !== t) throw new Error("Scoped backup belongs to another database"); } else { const r = openNodeSqliteDatabase(resolveImmutableSqliteFileUri(n), { readOnly: true }); try { r.exec("PRAGMA trusted_schema = OFF;"); assertCapture(); assertSqliteIntegrity(r, n, e.integrityChecks?.get(t)); e.repair?.validate?.(r); } finally { r.close(); } } if (!sameFileMutationFingerprint(r, lstatSync(n, { bigint: true }))) throw new Error("Backup changed during verification"); } catch (e) { throw new DoctorMaintenanceRefusalError(`Cannot verify pre-migration SQLite backup: ${n}. ${formatErrorMessage(e)}. Restore the matching backup group before retrying; surviving snapshots were preserved.`, { kind: "data-at-risk", reason: "incomplete-migration" }, { cause: e }); } if (n === fullTargetFor(t)) recordDoctorMigrationFullBackup(t, { path: n }); f.push(`Reused pre-migration SQLite backup: ${n}`); continue; } if (!h) throw new DoctorMaintenanceRefusalError(`Completed pre-migration SQLite backup group is missing: ${n}. Restore the matching backup group before retrying; surviving snapshots were preserved.`, { kind: "data-at-risk", reason: "incomplete-migration" }); const i = _.get(t); const a = i ? await createScopedMigrationSnapshot({ sourcePath: t, targetPath: n, tables: i.tables.map((e) => e.name), inspection: i, beforePublish: assertCapture, afterPublish }) : await o({ sourcePath: t, targetPath: n, preserveRowIds: true, integrity: e.integrityChecks?.get(t), transform: s, beforePublish: assertCapture, afterPublish: (e) => recordDoctorMigrationFullBackup(t, { path: n, generation: afterPublish(e) }), validate: e.repair?.validate }); assertCapture(); f.push(`Saved pre-migration SQLite backup: ${a.path}`); } assertCapture(); if (h) unlinkSync(m); syncCaptureDirectory(); assertInventory(); if (lstatSync(m, { throwIfNoEntry: false })) throw new DoctorMaintenanceRefusalError(`Pre-migration SQLite backup capture marker appeared during verification: ${m}`, { kind: "data-at-risk", reason: "incomplete-migration" }); const y = []; try { recordDoctorMigrationBackups(e.env, d, l.map(({ path: e, identity: t }) => ({ path: e, identity: t, archivePath: targetFor(e) })), e.migrationTables !== void 0, v); } catch (e) { y.push(`Migration backups remain protected; cleanup registration failed: ${formatErrorMessage(e)}`); } return { changes: f, warnings: y, snapshots: l.map(({ path: e }) => ({ sourcePath: e, path: targetFor(e) })) }; } //#endregion export { backupDoctorSqliteDatabases as n, captureFreshDoctorMigrationTables as r, backupDoctorMigrationDatabases as t };