UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

581 lines (580 loc) • 25.7 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { n as ignoreMissingPath, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { f as shortenHomeInString, p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { v as resolveGatewayLockDir } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { w as root } from "./fs-safe-BbWvmdVn.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl, n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-DRDkoS4J.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs"; import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs"; import { a as resolveOpenClawRegisteredAgentDatabasePath, c as resolveQuarantineStorePath, s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { r as selectDatabaseEngine, t as listDatabaseEngineStores } from "./registry-Dd7FIY0t.mjs"; import { a as resolveSqliteDatabaseFilePaths, r as isAppleDoubleMetadataFile, t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs"; import { m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { n as readEngineAnchor } from "./open-jth9KEHn.mjs"; import { r as assertOpenClawStateDatabaseOwner } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs"; import { t as resolveClientCredentialStorePath } from "./client-credential-paths-CIYPaDgB.mjs"; import { n as CONFIG_AUDIT_SCOPE } from "./io.audit-Bump5vFv.mjs"; import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import { n as readOpenClawAgentDatabaseRegistryRows } from "./openclaw-agent-db-registry.read-DpiFiW8m.mjs"; import { i as engineStringPosition } from "./scalar-Bs87vfbL.mjs"; import { n as SYSTEM_AGENT_AUDIT_SCOPE } from "./audit-nBEMz_02.mjs"; import { s as resolveAgentPortRoots } from "./port-provider-CZISFP-d.mjs"; import { n as readBackupEngineImage } from "./physical-store-inspection-C7yPt-uR.mjs"; import { r as createVerifiedSqliteSnapshot } from "./sqlite-snapshot-BQ91cQh_.mjs"; import { n as sanitizeOpenClawStateLeaseRows, t as sanitizeOpenClawGlobalStateSnapshot } from "./openclaw-state-snapshot-sanitizer-Du5mPaOv.mjs"; import { n as isTransientSqliteBackupPath } from "./backup-volatile-filter-Wvq7R1eh.mjs"; import { t as assertNotUpdateCapturePath } from "./update-capture-paths-B2WcdTCG.mjs"; import { r as sealBackupResourceInventory, t as createBackupResourcePlan } from "./backup-resource-inventory-BFHpUA98.mjs"; import { t as embedSessionColdArchivesInSnapshot } from "./session-cold-storage-backup-DFwa30Tk.mjs"; import { a as resolveDaemonRuntimePinStorePath } from "./runtime-pin-store-DsK1nV34.mjs"; import { n as capturePostgresBackup } from "./database-backup-B6k1k0NC.mjs"; import { t as listDefaultAgentDatabasePaths } from "./agent-database-path-discovery-DboXWm5d.mjs"; import { n as assertOpenClawAgentDatabaseOwner } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs"; import { n as captureBackupSqliteSourceGroup, r as planBackupSqliteSourceGroups, t as assertBackupSqliteSourceGroup } from "./backup-sqlite-source-groups-k2YrXQx2.mjs"; import { a as readLegacyAuditSourcePrefixSnapshotForBackup, d as serializePreparedAuditRecords, g as detectLegacyAuditLogs, i as readLegacyAuditRecoverySourceForBackup, m as legacyAuditMoveCandidates, r as findPreviousLegacyAuditRawCheckpoint, u as prepareLegacyAuditRecords, v as legacyAuditSourceGenerationKey } from "./state-migrations.audit-recovery-CM7Fuwco.mjs"; import { n as inspectLegacyMigrationLinkedMove } from "./state-migrations.no-replace-move-lOvjzyuT.mjs"; import { i as collectStateDatabasePaths } from "./update-candidate-state-BcxW3ei8.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import { isMainThread } from "node:worker_threads"; import childProcess from "node:child_process"; import { sameFileIdentity } from "@openclaw/fs-safe/advanced"; import { isPathInside } from "@openclaw/fs-safe/path"; import { walkDirectory } from "@openclaw/fs-safe/walk"; //#region src/infra/sqlite-header-probe.ts const SQLITE_HEADER_PROBE_BATCH_SIZE = 4096; const SQLITE_HEADER_PROBE_TIMEOUT_MS = 1e4; const log = createSubsystemLogger("backup"); function probeSqliteHeaderBatch(e, t, n) { const r = childProcess.spawnSync(process.execPath, e, { input: JSON.stringify(t), encoding: "utf8", maxBuffer: 67108864, timeout: SQLITE_HEADER_PROBE_TIMEOUT_MS }); if (r.error) { if (hasErrnoCode(r.error, "ETIMEDOUT") && t.length > 1) { const r = Math.ceil(t.length / 2); probeSqliteHeaderBatch(e, t.slice(0, r), n); probeSqliteHeaderBatch(e, t.slice(r), n); return; } throw r.error; } if (r.status === 3) { const e = asOptionalRecord(JSON.parse(r.stderr)); throw Object.assign(/* @__PURE__ */ new Error("Header probe could not read a source"), { code: e?.code, errno: e?.errno, path: e?.path }); } if (r.status !== 0) throw new Error(`Header probe exited with status ${r.status}: ${r.stderr.trim()}`); const i = JSON.parse(r.stdout); if (!Array.isArray(i) || i.length !== t.length || !i.every((e) => typeof e === "boolean")) throw new Error("Header probe returned an incomplete result"); if (r.stderr.trim()) { const e = `SQLite header probe recovered after retrying source reads: ${r.stderr.trim()}`; log.warn(e, { consoleMessage: shortenHomeInString(e) }); } for (let e = 0; e < t.length; e++) n.set(t[e], i[e]); } /** Probe discovery batches without disturbing live SQLite file locks. */ function probeSqliteDatabaseHeaders(e) { const t = [...new Set(e)]; if (t.length === 0) return /* @__PURE__ */ new Map(); const n = /* @__PURE__ */ new Map(); try { const e = resolveRuntimeWorkerArgv(resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.sqliteHeaderProbe)); for (let r = 0; r < t.length; r += SQLITE_HEADER_PROBE_BATCH_SIZE) probeSqliteHeaderBatch(e, t.slice(r, r + SQLITE_HEADER_PROBE_BATCH_SIZE), n); return n; } catch (e) { const n = asOptionalRecord(e); const r = typeof n?.path === "string" ? ` Backup source ${shortenHomePath(n.path)} could not be read (${typeof n.code === "string" ? n.code : "unknown error"}). Check read permissions or close the program using it, then retry the backup or update.` : " Check that the backup worker can run and the source files are readable, then retry the backup."; throw new Error(hasErrnoCode(e, "ETIMEDOUT") ? `SQLite header probe timed out after ${SQLITE_HEADER_PROBE_TIMEOUT_MS} ms while checking ${t.length} backup paths. For a blocked update, preserve a verified backup and follow the manual package-manager hop: https://docs.openclaw.ai/install/updating/update-methods#alternative-manual-npm-pnpm-or-bun` : `Could not determine whether backup files are SQLite databases.${r}`, { cause: e }); } } //#endregion //#region src/infra/state-migrations.audit-backup.ts var LegacyAuditBackupStateChangedError = class extends Error { constructor(e = "Legacy audit state changed while backup was capturing it") { super(e); this.name = "LegacyAuditBackupStateChangedError"; } }; const LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE = "migration.legacy-audit-raw"; function createLegacyAuditDatabaseWitness(e) { const t = executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("diagnostic_events").select([ "scope", "event_key", "payload_json", "created_at", "sequence" ]).where((t) => t.or([t.and([t("scope", "in", [CONFIG_AUDIT_SCOPE, SYSTEM_AGENT_AUDIT_SCOPE]), t(engineStringPosition(e, t.ref("event_key"), t.val("legacy:")), "=", 1)]), t("scope", "=", LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE)])).orderBy("scope").orderBy("event_key").orderBy("sequence")).rows; return createHash("sha256").update(JSON.stringify(t)).digest("hex"); } function legacyAuditBackupCapturesMatch(e, t) { return e.filesystemWitness === t.filesystemWitness && e.databaseWitness === t.databaseWitness; } /** Replaces live raw checkpoints with metadata for the transformed backup files. */ function rewriteLegacyAuditBackupCheckpoints(e, t) { if (e.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get("diagnostic_events")?.ok !== 1) return; const n = LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE; e.prepare("DELETE FROM diagnostic_events WHERE scope = ?").run(n); const r = e.prepare(`INSERT INTO diagnostic_events ( scope, event_key, payload_json, created_at, sequence ) VALUES (?, ?, ?, ?, ?)`); let i = 1; for (const e of t) { if (!e.checkpoint) continue; r.run(n, e.checkpoint.key, JSON.stringify(e.checkpoint.value), 0, i); i += 1; } } async function createLegacyAuditBackupSnapshotsOnce(e) { const t = detectLegacyAuditLogs({ stateDir: e.stateDir, doctorOnlyStateMigrations: true }); if (t.sources.length === 0) return { snapshots: [], filesystemWitness: createHash("sha256").digest("hex") }; const n = await root(e.stateDir, { hardlinks: "reject", maxBytes: Number.MAX_SAFE_INTEGER, mkdir: false, mode: 384, symlinks: "reject" }); const r = []; const i = createHash("sha256"); for (const [a, o] of t.sources.entries()) { const t = path.relative(path.resolve(e.stateDir), o.sourcePath); let s; for (const e of await legacyAuditMoveCandidates(n, o)) if ((e.retained === t || e.removed === t) && await inspectLegacyMigrationLinkedMove(n, e.retained, e.removed)) { s = e; break; } if (s && s.retained !== t) continue; const c = o.storage === "raw-archive" ? await readLegacyAuditRecoverySourceForBackup(n, t, s?.removed) : await readLegacyAuditSourcePrefixSnapshotForBackup(n, t, s?.removed); const l = legacyAuditSourceGenerationKey(t); const u = o.storage === "raw-archive" ? findPreviousLegacyAuditRawCheckpoint(e.stateDir, t) : void 0; const d = prepareLegacyAuditRecords(o, c.raw, l, u?.recordOrdinalBase ?? 0); if (!d.ok) throw new Error(`Legacy ${o.label} append archive cannot be sanitized for backup: ${d.warnings.join("; ")}`); const f = path.join(e.tempDir, `legacy-audit-raw-${a}.jsonl`); await fs.writeFile(f, d.sanitizedJsonl, { mode: 384 }); let p; if (u) { if (u.recordCount > d.records.length) throw new Error(`Legacy ${o.label} append archive is shorter than its durable checkpoint`); const e = Buffer.from(serializePreparedAuditRecords(d.records.slice(0, u.recordCount)), "utf8"); const t = { ...u, dev: "0", ino: "0", mtimeMs: 0, size: e.length, contentHash: createHash("sha256").update(e).digest("hex") }; p = { key: t.generationKey, value: t }; } const m = { sourcePath: f, archiveSourcePath: o.sourcePath, ...p ? { checkpoint: p } : {}, skippedSourcePaths: /* @__PURE__ */ new Set([ path.resolve(o.sourcePath), ...s ? [path.resolve(e.stateDir, s.removed)] : [], path.resolve(`${o.sourcePath}.doctor-scrub-progress`), path.resolve(`${o.sourcePath}.doctor-scrub-restore`), path.resolve(`${o.sourcePath}.doctor-scrub-staging`) ]) }; const h = JSON.stringify([ m.archiveSourcePath, c.dev, c.ino, c.mtimeMs, c.size, m.checkpoint ]); for (const e of [h, d.sanitizedJsonl]) i.update(String(Buffer.byteLength(e))).update(":").update(e); r.push(m); } return { snapshots: r, filesystemWitness: i.digest("hex") }; } async function createLegacyAuditBackupCapture(e) { let t; for (let n = 0;; n += 1) try { t = await createLegacyAuditBackupSnapshotsOnce(e); break; } catch (e) { if (n === 2) throw e; await new Promise((e) => { setTimeout(e, 25); }); } const n = withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => createLegacyAuditDatabaseWitness(e), { env: { ...process.env, OPENCLAW_STATE_DIR: e.stateDir } }) ?? createHash("sha256").digest("hex"); return { ...t, databaseWitness: n }; } //#endregion //#region src/infra/backup-sqlite-snapshot.ts function findLegacyAuditBackupStateChange(e) { return collectErrorGraphCandidates(e, (e) => e instanceof Error ? [e.cause] : []).find((e) => e instanceof LegacyAuditBackupStateChangedError); } const sqliteHeaderAnswers = /* @__PURE__ */ new WeakMap(); function stripSqliteSidecarSuffix(e) { const t = SQLITE_SIDECAR_SUFFIXES.find((t) => e.endsWith(t)); return t ? e.slice(0, -t.length) : e; } function headerAnswers(e) { let t = sqliteHeaderAnswers.get(e); if (!t) { t = /* @__PURE__ */ new Map(); sqliteHeaderAnswers.set(e, t); } return t; } function classifyBackupSqliteSource(e, t) { const n = path.resolve(e); if (!(isPathInside(t.stateDir, n) || t.agentRoots.some(({ sourcePath: e }) => isPathInside(e, n))) || t.isPackageContent(n)) return; const r = isTransientSqliteBackupPath(n); const i = stripSqliteSidecarSuffix(n); const a = i.endsWith(".sqlite"); if (!t.isIncludedByOwner(n)) return a ? "excluded" : void 0; if (!r && !a) { const e = headerAnswers(t); if (!e.has(i)) for (const [t, n] of probeSqliteDatabaseHeaders([i])) e.set(t, n); if (!e.get(i)) return; } if (r) return "excluded"; if (!t.isIncluded(n)) return a ? "excluded" : void 0; if (isAppleDoubleMetadataFile(n)) return "excluded"; const o = t.resolveSqliteSource(i); if (o && o.role === "unresolvable-link") return n === i ? "opaque-skip" : "opaque"; return o ? "sqlite" : "opaque"; } async function discoverBackupSqliteSources(e) { const t = /* @__PURE__ */ new Set(); const n = /* @__PURE__ */ new Set(); const r = /* @__PURE__ */ new Set(); const i = []; const a = resolveGatewayLockDir(e.inventory.stateDir); const isRetainedPath = (t) => !isPathInside(a, t) && !e.inventory.isVolatile(t); const isSelectedPath = (t) => !e.resourceRoots || e.resourceRoots.some((e) => isPathInside(e, t) || isPathInside(t, e)); for (const t of [e.inventory.stateDir, ...e.inventory.agentRoots.map(({ sourcePath: e }) => e)]) { const n = path.resolve(t); if (r.has(n)) continue; r.add(n); const { entries: a, failedDirs: o } = await walkDirectory(n, { symlinks: "include", include: (t) => (t.kind === "file" || t.kind === "symlink") && isSelectedPath(t.path) && isRetainedPath(t.path) && e.inventory.isIncludedByOwner(t.path), descend: (t) => { if (r.has(t.path) || !isSelectedPath(t.path) || !isRetainedPath(t.path) || !e.inventory.isTraversable(t.path) || e.inventory.isPackageContent(t.path)) return false; r.add(t.path); return true; } }); const s = o.find(({ error: e }) => !hasErrnoCode(e, "ENOENT")); if (s) throw s.error; for (const e of a) i.push(e); } const o = headerAnswers(e.inventory); const s = [...i.map((e) => e.path), ...r].map(stripSqliteSidecarSuffix).filter((e) => !e.endsWith(".sqlite")); for (const [e, t] of probeSqliteDatabaseHeaders(s)) o.set(e, t); for (const r of i) { if (classifyBackupSqliteSource(r.path, e.inventory) !== "sqlite") continue; n.add(r.path); if (!SQLITE_SIDECAR_SUFFIXES.some((e) => r.name.endsWith(e))) t.add(r.path); } for (const r of e.inventory.coreDatabaseSourcePaths) if (e.inventory.isIncluded(r)) { t.add(r); n.add(r); } return { snapshotPaths: [...t].toSorted((e, t) => e.localeCompare(t)), discoveredSourcePaths: n }; } async function discoverBackupDatabasePaths(e) { if (isMainThread && selectDatabaseEngine({ id: "state", postgres: true }, e.config) === "postgres") { const { preparePostgresBackupDiscovery: t } = await import("./backup-database-discovery-CYhLn5Yb.mjs"); return (await t(e)).paths; } const t = [...(await collectStateDatabasePaths(e)).values()].flatMap((e) => e.spellings); t.push(...await resolveAgentPortRoots({ ...e, env: e.env ?? process.env }, e.agentRegistry)); const n = resolvePluginMetadataSnapshot(e); const r = new Set(listDatabaseEngineStores().filter((e) => e.postgres).map((e) => e.id)); const i = n.plugins.flatMap((e) => (e.backupResources ?? []).filter((t) => r.has(t.databaseFamily ?? e.id)).map((t) => Object.assign({}, t, { pluginId: e.id }))); const a = await createBackupResourcePlan({ stateDir: e.stateDir, configPaths: [], oauthDirs: [], workspaceDirs: [], excludedWorkspaceDirs: [], agentRoots: [], pluginResources: i, pluginRoots: n.plugins.map((e) => e.rootDir) }); const o = sealBackupResourceInventory(a, []); t.push(...(await discoverBackupSqliteSources({ inventory: o, resourceRoots: a.pluginResourceRoots })).snapshotPaths); const s = []; for (const e of new Set(t)) if ((await fs.stat(e).catch(ignoreMissingPath))?.isFile()) s.push(await fs.realpath(e)); return [...new Set(s)].toSorted(); } async function planBackupSqliteSources(e, t) { const n = []; for (const r of t) { const t = await fs.stat(r, { bigint: true }); const i = e.resolveSqliteSource(r, t); if (!i || i.role === "unresolvable-link") throw new Error(`SQLite ownership changed after discovery: ${r}`); let a; if (i.role !== "plugin") { if (!i.identity || !sameFileIdentity(i.identity, t)) throw new Error(`Canonical SQLite path changed after discovery: ${r}`); a = { ...i, archiveSourcePath: i.sourcePath, sourcePath: await fs.realpath(i.sourcePath), identity: i.identity }; assertNotUpdateCapturePath(a.sourcePath, e.stateDir); } n.push({ archiveSourcePath: r, path: a ? await fs.realpath(r) : r, identity: t, canonicalSource: a }); } return { sources: n, groups: await planBackupSqliteSourceGroups(n) }; } async function createBackupSqliteSnapshotPlan(e) { const t = /* @__PURE__ */ new Map(); const n = []; const r = []; let i; let a = []; function captureAgentRegistry(e, t) { a = readOpenClawAgentDatabaseRegistryRows(e, t).map((e) => ({ role: "agent", agentId: normalizeAgentId(e.agent_id), sourcePath: resolveOpenClawRegisteredAgentDatabasePath(t, e.path) })); } async function captureSource(i, a, o) { if (!a) throw new Error(`SQLite ownership changed after discovery: ${i}`); if (o && !sameFileIdentity(o.identity, await fs.stat(i, { bigint: true }))) throw new Error(`Canonical SQLite path changed after discovery: ${i}`); const s = a.sourcePath; assertNotUpdateCapturePath(i, e.resources.stateDir); assertNotUpdateCapturePath(s, e.resources.stateDir); const c = path.join(e.tempDir, `openclaw-state-db-${n.length}.sqlite`); let l; try { const capture = () => createVerifiedSqliteSnapshot({ sourcePath: s, targetPath: c, requireNonEmptySource: Boolean(o), validate: o ? (e, t) => { l ??= readEngineAnchor(e) !== void 0; if (l) return; if (o.role === "global") assertOpenClawStateDatabaseOwner(e, { pathname: t }); else if (o.role === "agent") assertOpenClawAgentDatabaseOwner(e, { agentId: o.agentId, pathname: t }); } : void 0, transform: async (t) => { l ??= readEngineAnchor(t) !== void 0; if (l) return; if (o?.role === "global") { captureAgentRegistry(t, o.archiveSourcePath); if (e.legacyAuditDatabaseWitness !== void 0 && createLegacyAuditDatabaseWitness(t) !== e.legacyAuditDatabaseWitness) throw new LegacyAuditBackupStateChangedError("Legacy audit database rows changed during SQLite backup"); sanitizeOpenClawGlobalStateSnapshot(t); rewriteLegacyAuditBackupCheckpoints(t, e.legacyAuditSnapshots); } else if (o?.role === "agent") sanitizeOpenClawStateLeaseRows(t); else if (o?.role === "client" && tableExists(t, "native_exec_socket_credentials")) executeSqliteQuerySync(t, getNodeSqliteKysely(t).updateTable("native_exec_socket_credentials").set({ socket_token: null })); await embedSessionColdArchivesInSnapshot({ database: t, sourceStorePath: o?.archiveSourcePath ?? s }); } }); const n = t.get(a); await captureBackupSqliteSourceGroup(a, () => n ? fs.copyFile(n, c, fs.constants.COPYFILE_EXCL) : capture()); t.set(a, c); } catch (e) { const t = findLegacyAuditBackupStateChange(e); if (t) throw t; throw new Error(`SQLite database cannot be compacted safely for backup: ${i}. ${formatErrorMessage(e)}. The source must pass full integrity checks, online SQLite backup, and offline compaction with its required SQLite capabilities; a direct file copy was refused because it can retain deleted data. For a plugin-owned database, restore the required SQLite capabilities or use the plugin's own backup procedure before retrying.`, { cause: e }); } if (readBackupEngineImage(c, s).engine === "postgres") { const e = path.join(`${c}.postgres`, path.basename(`${i}.postgres`)); await fs.mkdir(path.dirname(e), { mode: 448 }); await capturePostgresBackup({ sourcePath: s, directory: e }); if (o?.role === "global") try { var u = _usingCtx(); captureAgentRegistry(u.u(openNodeSqliteDatabase(path.join(e, "database.sqlite"), { readOnly: true })), o.archiveSourcePath); } catch (e) { u.e = e; } finally { u.d(); } for (const t of [ "anchor.sqlite", "database.sqlite", "manifest.json" ]) n.push({ sourcePath: path.join(e, t), archiveSourcePath: `${i}.postgres/${t}`, skippedSourcePaths: /* @__PURE__ */ new Set() }); const t = `${c}.anchor`; await fs.copyFile(path.join(e, "anchor.sqlite"), t, fs.constants.COPYFILE_EXCL); n.push({ sourcePath: t, archiveSourcePath: i, skippedSourcePaths: new Set(resolveSqliteDatabaseFilePaths(s)) }); r.push({ sourcePath: i, manifestSha256: (await sha256File(path.join(e, "manifest.json"))).digest }); return; } n.push({ sourcePath: c, archiveSourcePath: i, skippedSourcePaths: new Set([i, s].flatMap((e) => resolveSqliteDatabaseFilePaths(e).map((e) => path.resolve(e)))) }); } const o = resolveOpenClawStateSqlitePath({ ...process.env, OPENCLAW_STATE_DIR: e.resources.stateDir }); const s = await fs.lstat(o, { bigint: true }).catch(ignoreMissingPath); let c; let l; if (s) { c = s.isSymbolicLink() ? await fs.stat(o, { bigint: true }) : s; if (!c.isFile()) throw new Error(`Canonical global SQLite path must be a regular file or symlink to one: ${o}`); const t = { role: "global", archiveSourcePath: o, sourcePath: await fs.realpath(o), identity: c }; const n = sealBackupResourceInventory(e.resources, [{ role: "global", sourcePath: o, identity: c }]); const { snapshotPaths: r } = await discoverBackupSqliteSources({ inventory: n }); const { groups: a } = await planBackupSqliteSources(n, r.filter((e) => n.resolveSqliteSource(e)?.role === "global")); l = a.get(t.sourcePath); await captureSource(o, l, t); i = t.sourcePath; } else for (const e of resolveSqliteDatabaseFilePaths(o).slice(1)) if (await fs.lstat(e).catch(ignoreMissingPath)) throw new Error(`Canonical global SQLite database is missing but a sidecar remains: ${e}`); const u = [{ role: "global", sourcePath: o, identity: c }]; const d = await listDefaultAgentDatabasePaths(e.resources.stateDir); const f = []; const p = [ { role: "client", sourcePath: resolveClientCredentialStorePath({ OPENCLAW_STATE_DIR: e.resources.stateDir }) }, { role: "services", sourcePath: resolveDaemonRuntimePinStorePath({ OPENCLAW_STATE_DIR: e.resources.stateDir }) }, { role: "quarantine", sourcePath: resolveQuarantineStorePath({ ...process.env, OPENCLAW_STATE_DIR: e.resources.stateDir }) }, ...a, ...e.resources.agentRoots.map(({ agentId: e, databasePath: t }) => ({ role: "agent", agentId: e, sourcePath: t })), ...d.toSorted((e, t) => e.path.localeCompare(t.path)).map(({ agentId: e, path: t }) => ({ role: "agent", agentId: normalizeAgentId(e), sourcePath: t, discoveredPath: t })) ]; for (const { discoveredPath: e, ...t } of p) { const n = await fs.stat(t.sourcePath, { bigint: true }).catch(ignoreMissingPath); if (n && !n.isFile()) throw new Error(`Core SQLite path must resolve to a regular file: ${t.sourcePath}`); if (e && !n) continue; if (e) { f.push(e); t.sourcePath = await fs.realpath(t.sourcePath); } u.push(Object.freeze({ ...t, identity: n })); } const m = sealBackupResourceInventory({ ...e.resources, protectedPaths: [...e.resources.protectedPaths, ...f] }, u); const h = await discoverBackupSqliteSources({ inventory: m }); const { sources: g, groups: _ } = await planBackupSqliteSources(m, h.snapshotPaths); for (const e of g) if (e.archiveSourcePath !== o) await captureSource(e.archiveSourcePath, e.canonicalSource?.role === "global" ? l : _.get(e.path), e.canonicalSource); if (l) await assertBackupSqliteSourceGroup(l); for (const e of u) if (e.identity && !sameFileIdentity(e.identity, await fs.stat(e.sourcePath, { bigint: true }))) throw new Error(`Canonical SQLite path changed after discovery: ${e.sourcePath}`); return { inventory: m, snapshots: n, postgresSnapshots: r, discoveredSourcePaths: h.discoveredSourcePaths, sharedDatabaseSourcePath: i }; } //#endregion export { createLegacyAuditBackupCapture as a, LegacyAuditBackupStateChangedError as i, createBackupSqliteSnapshotPlan as n, legacyAuditBackupCapturesMatch as o, discoverBackupDatabasePaths as r, classifyBackupSqliteSource as t };