UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,247 lines (1,246 loc) • 46.4 kB
import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { o as writeRuntimeJson, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs"; import { a as lstatIfExists } from "./path-existence-Co7-GyVr.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as canonicalPathFromExistingAncestor, c as isPathInside$1 } from "./fs-safe-BbWvmdVn.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { h as resolveConfiguredAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { c as normalizeSqlWhitespace, l as quoteSqliteIdentifier, n as findSqlCharacter, t as extractSqliteTableSchema } from "./sqlite-schema-sql-CPyk_2Hd.mjs"; import { n as OPENCLAW_STATE_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import "./openclaw-state-db-contract-DfPjvL0M.mjs"; import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs"; import { l as createPrivateSqliteTempDirectory } from "./sqlite-snapshot-staging-DVmPTRsc.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { t as applyPrivateModeSync } from "./private-mode-D8ql0tOD.mjs"; import { r as selectDatabaseEngine, t as listDatabaseEngineStores } from "./registry-Dd7FIY0t.mjs"; import { r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs"; import { i as assertSupportedStateSchemaVersion, o as readStateSchemaContentVersion } from "./openclaw-state-db-schema-version-uNbDFl6T.mjs"; import { s as getCanonicalSqliteTableNames } from "./sqlite-schema-contract-D3pR9vZs.mjs"; import { b as getOpenClawStateRuntimeSchema, s as openClawStateMigrationAssertions } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs"; import { t as readBackupEngine } from "./physical-store-BRXG56Jw.mjs"; import { b as repairCanonicalSqliteIndexes } from "./openclaw-state-db-ARhwdPJg.mjs"; import { n as decodeUtf8Chunks } from "./utf8-input-BHczGT8v.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { c as spawnCommand, f as withCommandProcessScope } from "./exec-spawn-DMKoejF-.mjs"; import { i as assertSupportedAgentSchemaVersion } from "./openclaw-agent-db-schema-read-U5-_81Kg.mjs"; import { _ as getOpenClawAgentMigrationSchema } from "./openclaw-agent-progress-card-schema-CDOtPrpA.mjs"; import { r as assertAgentSchemaVersion } from "./openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs"; import { i as formatCommandResult, r as formatCommandOutput } from "./command-error-BbCvU7oG.mjs"; import "./config-CMA-J084.mjs"; import { a as executeGitCommand, d as normalizeGitPathForFilesystem, m as requireGitCommandOutput, p as requireGitCommand, t as GIT_TIMEOUT_MS } from "./git-exec-DHBL622T.mjs"; import { t as beginLifecycleWriteCustody } from "./lifecycle-write-custody-B171kU9T.mjs"; import { a as publishVerifiedSqliteFile } from "./sqlite-snapshot-BQ91cQh_.mjs"; import { t as assertNotUpdateCapturePath } from "./update-capture-paths-B2WcdTCG.mjs"; import { c as encodeSqliteValue, l as escapedSqliteText } from "./port.worker-BIwiDJ3h.mjs"; import { f as hashSnapshotArtifact, g as SNAPSHOT_SQLITE_FILENAME, l as assertFreshRestoreTarget, u as assertNoSqliteSidecarsSync } from "./database-backup.operations-BNuRDpZK.mjs"; import { n as gitBackupRedaction, r as redactGitBackupRow } from "./git-backup-sanitizer-CN-7TbHt.mjs"; import { o as readPostgresBackupFamily } from "./database-backup-B6k1k0NC.mjs"; import { n as assertOpenClawAgentDatabaseOwner } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs"; import { r as discoverBackupDatabasePaths } from "./backup-sqlite-snapshot-D5T0ii_w.mjs"; import { t as BACKUP_RUN_ERROR_MAX_LENGTH } from "./backup-run-records.contract.js"; import { a as recordBackupOutcomeBestEffort, o as resolveBackupAgentRoot, u as resolveRequiredBackupPath } from "./backup-shared-BmR-itzA.mjs"; import { t as preparePostgresBackupDiscovery } from "./backup-database-discovery-B1Is2zHI.mjs"; import { a as createOpenClawSnapshotCopy, i as buildSnapshotValidator, r as ensurePrivateSnapshotRepositoryRoot, t as createLocalSnapshotProvider } from "./local-repository-C3N4pLx_.mjs"; import fs from "node:fs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs$1 from "node:fs/promises"; import { hasNodeErrorCode } from "@openclaw/fs-safe/path"; import { tempWorkspace } from "@openclaw/fs-safe/temp"; import { finished } from "node:stream/promises"; //#region src/snapshot/git-backup-codec.ts const GIT_BACKUP_MANIFEST = "manifest.json"; const GIT_BACKUP_SCHEMA = "schema.sql"; const GIT_BACKUP_TABLES = "tables"; const SAFE_TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; const GIT_BACKUP_PROJECTION_TABLES = [ "backup_runs", "session_transcript_fts_rows", "session_transcript_index_state" ]; function requireSafeTableName(e) { if (!SAFE_TABLE_NAME.test(e)) throw new Error(`Git backup table name is not filesystem-safe: ${e}`); return e; } function normalizeIdentity(e) { if (e.role === "global") return e; if (e.role === "generic") { if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(e.id)) throw new Error(`Git backup store id is not filesystem-safe: ${e.id}`); return e; } const t = normalizeAgentId(e.agentId); if (t !== e.agentId) throw new Error(`Git backup agent id must be canonical: ${e.agentId}`); return { role: "agent", agentId: t }; } function gitBackupScopePath(e) { const t = normalizeIdentity(e); return t.role === "generic" ? path.join("stores", t.id) : t.role === "global" ? "global" : path.join("agents", t.agentId); } function readSchemaEntries(e) { return e.prepare(`SELECT type, name, tbl_name AS tableName, sql FROM sqlite_master WHERE type IN ('table', 'index', 'trigger') AND name NOT LIKE 'sqlite_%' AND sql IS NOT NULL ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'index' THEN 1 ELSE 2 END, name`).all().map((e) => e); } function isVirtualShadow(e, t) { return t.some((t) => e === t || e.startsWith(`${t}_`)); } const TABLE_BATCH_BYTES = 1048576; function readTableColumns(e, t) { return e.prepare(`PRAGMA table_info(${quoteSqliteIdentifier(t)})`).all().map((e) => { const n = e; if (typeof n.name !== "string" || typeof n.pk !== "number") throw new Error(`Unable to read columns for Git backup table ${t}.`); return { name: n.name, pk: n.pk }; }); } async function serializeGitBackupTable(e, t, n, r) { const i = readTableColumns(e, t); if (i.length === 0) throw new Error(`Git backup table has no readable columns: ${t}`); const a = i.filter((e) => e.pk > 0).toSorted((e, t) => e.pk - t.pk).map((e) => `source.${quoteSqliteIdentifier(e.name)}`); const o = a.length > 0 ? a.join(", ") : "source.rowid"; const s = i.map(({ name: e }) => { const t = quoteSqliteIdentifier(e); return `${escapedSqliteText(t)} AS ${t}`; }); const c = e.prepare(`SELECT ${s.join(", ")} FROM ${quoteSqliteIdentifier(t)} AS source ORDER BY ${o}`); c.setReadBigInts(true); const l = n ? await fs$1.open(n, "wx", 384) : void 0; const u = createHash("sha256"); const d = []; let f = 0; let p = 0; const flush = async () => { if (l && d.length > 0) { await l.writeFile(d.join("")); d.length = 0; f = 0; } }; try { for (const e of c.iterate()) { const t = {}; for (const [n, r] of Object.entries(e)) t[n] = typeof r === "string" ? JSON.parse(r) : r; if (r && !r(t)) continue; const n = {}; for (const e of i) n[e.name] = encodeSqliteValue(t[e.name]); const a = `${JSON.stringify(n)}\n`; u.update(a); p += 1; if (l) { d.push(a); f += Buffer.byteLength(a); if (f >= TABLE_BATCH_BYTES) await flush(); } } await flush(); return { rows: p, sha256: u.digest("hex") }; } finally { await l?.close(); } } function schemaText(e, t) { return `${e.map((e) => e.sql.trimEnd().endsWith(";") ? e.sql : `${e.sql};`).join("\n\n")}\n-- PRAGMA user_version = ${t}\n`; } /** Dump one verified SQLite copy into the deterministic Git repository layout. */ async function dumpGitBackupDatabase(e) { const t = normalizeIdentity(e.identity); const { captureGitPostgresBackup: n } = await import("./database-backup-ZFHLPLfI.mjs"); const r = await n({ ...e, identity: t }); if (r) return r; const i = openNodeSqliteDatabase(e.snapshotPath, { readOnly: true }); try { const n = readSchemaEntries(i); const r = n.filter((e) => /^\s*CREATE\s+VIRTUAL\s+TABLE\b/iu.test(e.sql)).map((e) => e.name); const a = new Set(n.filter((e) => e.type === "table").map((e) => e.name)); const { excludedTables: o, excludedConfigStateKeyPrefixes: s } = gitBackupRedaction(t, a, e.excludeSecrets === true); const c = /* @__PURE__ */ new Set([...o, ...GIT_BACKUP_PROJECTION_TABLES]); const l = n.filter((e) => !c.has(e.name) && !c.has(e.tableName)); const u = n.filter((e) => e.type === "table" && !isVirtualShadow(e.name, r) && !c.has(e.name)).map((e) => requireSafeTableName(e.name)).toSorted(); const d = i.prepare("PRAGMA user_version").get(); if (typeof d.user_version !== "number") throw new Error("Unable to read SQLite user_version for Git backup."); await fs$1.rm(e.outputPath, { recursive: true, force: true }); const f = path.join(e.outputPath, GIT_BACKUP_TABLES); await fs$1.mkdir(f, { recursive: true, mode: 448 }); const p = {}; for (const n of u) { const r = e.excludeSecrets === true ? (e) => redactGitBackupRow(n, e, t, s) : void 0; p[n] = await serializeGitBackupTable(i, n, path.join(f, `${n}.jsonl`), r); } const m = { schemaVersion: 1, identity: t, userVersion: d.user_version, excludedTables: o, excludedConfigStateKeyPrefixes: s, tables: p }; await fs$1.writeFile(path.join(e.outputPath, GIT_BACKUP_SCHEMA), schemaText(l, m.userVersion), { encoding: "utf8", mode: 384 }); await fs$1.writeFile(path.join(e.outputPath, GIT_BACKUP_MANIFEST), `${JSON.stringify(m, null, 2)}\n`, { encoding: "utf8", mode: 384 }); return m; } finally { i.close(); } } function parseGitBackupManifest(e, t) { let n; try { n = JSON.parse(e); } catch (e) { throw new Error(`Git backup manifest is invalid JSON: ${t}`, { cause: e }); } if (!n || typeof n !== "object" || Array.isArray(n)) throw new Error(`Git backup manifest is invalid: ${t}`); const r = n; if (r.schemaVersion !== 1 && r.schemaVersion !== 2 || !r.identity || r.identity.role !== "global" && r.identity.role !== "agent" && r.identity.role !== "generic" || !Number.isSafeInteger(r.userVersion) || !Array.isArray(r.excludedTables) || r.excludedConfigStateKeyPrefixes !== void 0 && (!Array.isArray(r.excludedConfigStateKeyPrefixes) || r.excludedConfigStateKeyPrefixes.some((e) => typeof e !== "string")) || !r.tables || typeof r.tables !== "object" || r.postgresSource !== void 0 && (!r.postgresSource || typeof r.postgresSource !== "object" || Array.isArray(r.postgresSource) || typeof r.postgresSource.storeId !== "string" || !r.postgresSource.storeId || typeof r.postgresSource.namespace !== "string" || !r.postgresSource.namespace)) throw new Error(`Git backup manifest has unsupported fields: ${t}`); const i = { ...r, excludedConfigStateKeyPrefixes: r.excludedConfigStateKeyPrefixes ?? [] }; normalizeIdentity(i.identity); for (const [e, t] of Object.entries(i.tables)) { requireSafeTableName(e); if (!Number.isSafeInteger(t.rows) || t.rows < 0 || !/^[a-f0-9]{64}$/u.test(t.sha256)) throw new Error(`Git backup manifest has an invalid table entry: ${e}`); } return i; } function splitSchemaStatements(e) { const t = []; let n = 0; let r = 0; while (r < e.length) { const i = findSqlCharacter(e.slice(r), ";"); if (i === -1) break; const a = e.slice(r, r + i + 1); r += i + 1; const o = e.slice(n, r).trim(); if (/^CREATE\s+TRIGGER\b/iu.test(o) && !/^END\s*;$/iu.test(normalizeSqlWhitespace(a))) continue; if (o && !o.startsWith("-- PRAGMA user_version")) t.push(o); n = r; } const i = e.slice(n).trim(); if (/^CREATE\s+TRIGGER\b/iu.test(i)) t.push(i); return t; } function unquoteSqlIdentifier(e) { const t = e[0]; if (t === "'" || t === "\"" || t === "`") return e.slice(1, -1).replaceAll(t + t, t); if (t === "[") return e.slice(1, -1); return e; } function schemaObjectName(e, t) { const n = new RegExp(`^${t === "virtual" ? "CREATE\\s+VIRTUAL\\s+TABLE" : "CREATE\\s+TABLE"}\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?('(?:[^']|'')*'|"(?:[^"]|"")*"|\\[[^\\]]+\\]|\`(?:[^\`]|\`\`)*\`|[^\\s(]+)`, "iu").exec(e); return n?.[1] ? unquoteSqlIdentifier(n[1]) : void 0; } function decodeSqliteValue(e) { if (e === null || typeof e === "string" || typeof e === "number") return e; if (!e || typeof e !== "object" || Array.isArray(e)) throw new Error("Git backup row contains an invalid encoded value."); const t = e; if (Object.keys(t).length === 1 && typeof t.$int === "string") return BigInt(t.$int); if (Object.keys(t).length === 1 && typeof t.$hex === "string" && /^(?:[a-f0-9]{2})*$/u.test(t.$hex)) return Buffer.from(t.$hex, "hex"); throw new Error("Git backup row contains an invalid encoded object."); } function validateRestoredOwner(e, t, n, r) { assertSqliteIntegrity(e, t); if (n.role === "generic") return; if (n.role === "agent") { assertOpenClawAgentDatabaseOwner(e, { agentId: n.agentId, pathname: t }); assertSupportedAgentSchemaVersion(e, t); assertAgentSchemaVersion(e, { agentId: n.agentId, pathname: t, version: r }, getOpenClawAgentMigrationSchema(r)); } else { assertSupportedStateSchemaVersion(e, t); const r = openClawStateMigrationAssertions.get(readStateSchemaContentVersion(e)); if (r) r(e, { pathname: t }); else buildSnapshotValidator(n)(e, t); } } /** Load and hash one JSONL table without retaining the whole artifact. */ async function loadGitBackupTable(e, t, n) { const r = readTableColumns(e, t); const i = e.prepare(`INSERT INTO ${quoteSqliteIdentifier(t)} (${r.map((e) => quoteSqliteIdentifier(e.name)).join(", ")}) VALUES (${r.map(() => "?").join(", ")})`); const a = fs.createReadStream(n); const o = createHash("sha256"); a.on("data", (e) => o.update(e)); const s = []; let c = 0; let l = 0; const flush = () => { if (s.length === 0) return; e.exec("BEGIN IMMEDIATE;"); try { for (const e of s) i.run(...e); e.exec("COMMIT;"); } catch (t) { e.exec("ROLLBACK;"); throw t; } s.length = 0; c = 0; }; const loadLine = (e) => { const t = e.endsWith("\r") ? e.slice(0, -1) : e; if (!t) return; const n = JSON.parse(t); s.push(r.map((e) => decodeSqliteValue(n[e.name]))); c += Buffer.byteLength(t); l += 1; if (c >= TABLE_BATCH_BYTES) flush(); }; try { let e = ""; for await (const t of decodeUtf8Chunks(a, n)) { e += t; let n = 0; for (let t = e.indexOf("\n"); t !== -1; t = e.indexOf("\n", n)) { loadLine(e.slice(n, t)); n = t + 1; } e = e.slice(n); } loadLine(e); flush(); return { rows: l, sha256: o.digest("hex") }; } finally { a.destroy(); await finished(a).catch(() => void 0); } } /** Restore one materialized Git snapshot scope into a fresh SQLite file. */ async function restoreGitBackupDirectory(e) { const t = path.resolve(e.targetPath); await assertFreshRestoreTarget(t); const n = parseGitBackupManifest(await fs$1.readFile(path.join(e.sourcePath, GIT_BACKUP_MANIFEST), "utf8"), e.sourcePath); const r = normalizeIdentity(e.expectedIdentity ?? n.identity); if (e.expectedIdentity && JSON.stringify(normalizeIdentity(n.identity)) !== JSON.stringify(r)) throw new Error("Git backup manifest database identity does not match the requested scope."); if (n.schemaVersion === 2) { const { createLocalSnapshotProvider: r } = await import("./local-repository-BoYqqrop.mjs"); await r({ repositoryPath: e.sourcePath, expectedPostgresSource: n.postgresSource }).restoreFresh({ path: path.join(e.sourcePath, "postgres") }, t); return { manifest: n, targetPath: t, tables: [], excludedTables: n.excludedTables, excludedConfigStateKeyPrefixes: n.excludedConfigStateKeyPrefixes }; } const i = splitSchemaStatements(await fs$1.readFile(path.join(e.sourcePath, GIT_BACKUP_SCHEMA), "utf8")); const a = i.filter((e) => /^CREATE\s+VIRTUAL\s+TABLE\b/iu.test(e)); const o = i.filter((e) => /^CREATE\s+TRIGGER\b/iu.test(e)); const s = a.map((e) => schemaObjectName(e, "virtual")).filter((e) => Boolean(e)); const c = i.filter((e) => { if (!/^CREATE\s+TABLE\b/iu.test(e)) return false; const t = schemaObjectName(e, "table"); return !t || !isVirtualShadow(t, s); }); const l = i.filter((e) => /^CREATE\s+(?:UNIQUE\s+)?INDEX\b/iu.test(e)); const u = path.dirname(t); await fs$1.mkdir(u, { recursive: true, mode: 448 }); const d = await createPrivateSqliteTempDirectory(u, ".git-backup-restore-"); let f; try { applyPrivateModeSync(d, 448); const i = path.join(d, SNAPSHOT_SQLITE_FILENAME); await (await fs$1.open(i, "wx", 384)).close(); f = openNodeSqliteDatabase(i); f.exec("PRAGMA foreign_keys = OFF; PRAGMA journal_mode = DELETE;"); for (const e of [...c, ...l]) f.exec(e); for (const [t, r] of Object.entries(n.tables)) { requireSafeTableName(t); const n = await loadGitBackupTable(f, t, path.join(e.sourcePath, GIT_BACKUP_TABLES, `${t}.jsonl`)); if (n.sha256 !== r.sha256) throw new Error(`Git backup table hash mismatch: ${t}`); if (n.rows !== r.rows) throw new Error(`Git backup table row count mismatch: ${t}`); } for (const e of a) { if (/\bUSING\s+vec0\b/iu.test(e)) continue; f.exec(e); } for (const e of o) f.exec(e); for (const e of a) { const t = schemaObjectName(e, "virtual"); if (t && /\bUSING\s+fts5\b/iu.test(e) && /\bcontent\s*=/iu.test(e)) f.prepare(`INSERT INTO ${quoteSqliteIdentifier(t)} (${quoteSqliteIdentifier(t)}) VALUES ('rebuild')`).run(); } f.exec(`PRAGMA user_version = ${n.userVersion};`); const s = r.role === "global" ? getOpenClawStateRuntimeSchema({ includeVersionLazyAdditiveTables: false }) : getOpenClawAgentMigrationSchema(n.userVersion); if (r.role === "global" && readStateSchemaContentVersion(f) < 36) { const e = /* @__PURE__ */ new Set([...n.excludedTables, ...GIT_BACKUP_PROJECTION_TABLES]); for (const t of getCanonicalSqliteTableNames(s)) if (e.has(t)) f.exec(extractSqliteTableSchema(s, t)); } else f.exec(s); if (r.role === "agent") repairCanonicalSqliteIndexes(f, i, s); validateRestoredOwner(f, i, r, n.userVersion); const u = []; for (const [e, t] of Object.entries(n.tables)) { const n = await serializeGitBackupTable(f, e); u.push({ table: e, ...n, ok: n.rows === t.rows && n.sha256 === t.sha256 }); } if (u.some((e) => !e.ok)) throw new Error(`Restored Git backup does not match its table manifest: ${i}`); f.close(); applyPrivateModeSync(i, 384); const p = await hashSnapshotArtifact(d); await publishVerifiedSqliteFile({ sourceIdentity: p.identity, sourcePath: i, targetPath: t, expectedContent: p, requireAtomicPublication: true, beforePublish: async () => await assertFreshRestoreTarget(t), validatePublished: async (e) => { const t = openNodeSqliteDatabase(e, { readOnly: true }); try { validateRestoredOwner(t, e, r, n.userVersion); } finally { t.close(); } }, afterPublish: (e) => { e.assertTargetMatchesExpectedContent(() => assertNoSqliteSidecarsSync(t, "Fresh SQLite restore path already exists")); } }); return { manifest: n, targetPath: t, tables: u, excludedTables: n.excludedTables, excludedConfigStateKeyPrefixes: n.excludedConfigStateKeyPrefixes }; } catch (e) { if (f?.isOpen) f.close(); throw e; } finally { await fs$1.rm(d, { recursive: true, force: true }).catch(() => { defaultRuntime.error(`Warning: Git backup temporary files may remain under ${d}; cleanup failed: inspect and remove the directory when safe.`); }); } } //#endregion //#region src/snapshot/git-backup-artifacts.ts function gitBackupArtifactFiles(e) { if (e.schemaVersion === 2) return [GIT_BACKUP_MANIFEST, ...[ "manifest.json", "anchor.sqlite", "database.sqlite" ].map((e) => path.join("postgres", e))]; return [ GIT_BACKUP_MANIFEST, GIT_BACKUP_SCHEMA, ...Object.keys(e.tables).map((e) => path.join(GIT_BACKUP_TABLES, `${e}.jsonl`)) ]; } async function readGitBackupRepositoryState(e) { const t = normalizeGitPathForFilesystem(await requireGitCommand(e, ["rev-parse", "--absolute-git-dir"])); const n = await Promise.all([ "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer" ].map((e) => lstatIfExists(path.join(t, e), "ENOENT"))); const r = (await requireGitCommand(e, [ "ls-files", "--stage", "-z" ])).split("\0").filter(Boolean); if (n.some(Boolean) || r.some((e) => e.split(" ")[0]?.split(" ")[2] !== "0")) throw new Error("Git operation is in progress; finish or abort it before creating a backup."); const i = await executeGitCommand(e, [ "rev-parse", "--verify", "--quiet", "HEAD" ]); if (i.code !== 0 && i.code !== 1) requireGitCommandOutput("git rev-parse HEAD", i); const a = i.code === 0 ? (await requireGitCommand(e, [ "ls-tree", "-r", "-z", i.stdout.trim(), "--", "global", "agents", "stores" ])).split("\0").filter(Boolean) : []; const o = new Map(a.map((e) => [e.slice(e.indexOf(" ") + 1), e])); const s = /* @__PURE__ */ new Set([...o.keys(), ...r.map((e) => e.slice(e.indexOf(" ") + 1))]); const c = /* @__PURE__ */ new Set(); for (const e of s) for (let t = path.posix.dirname(e); t !== "."; t = path.posix.dirname(t)) c.add(t); return { head: i.code === 0 ? i.stdout.trim() : void 0, headFiles: o, files: s, directories: c }; } function refuseBackupOverwrite(e) { throw new Error(`Refusing to replace non-backup-owned path ${e}; preserve or move it before refreshing this scope.`); } async function assertBackupDirectory(e, t, n) { const r = path.join(e, t); const i = await lstatIfExists(r, "ENOENT"); if (i && !i.isDirectory() || n.files.has(t.split(path.sep).join("/"))) refuseBackupOverwrite(r); } async function readOwnedScopeManifest(e, t, n) { const r = path.join(e, t, GIT_BACKUP_MANIFEST); const i = await lstatIfExists(r, "ENOENT"); let a; if (i) { if (!i.isFile()) return; a = await fs$1.readFile(r, "utf8"); } else { const r = path.join(t, GIT_BACKUP_MANIFEST).split(path.sep).join("/"); const i = n.headFiles.get(r); if (!i?.startsWith("100644 blob ") && !i?.startsWith("100755 blob ")) return; a = await requireGitCommand(e, ["show", `${n.head}:${r}`]); } try { const e = parseGitBackupManifest(a, r); return gitBackupScopePath(e.identity) === t ? e : void 0; } catch { return; } } async function prepareScopeUpdate(e, t, n, r) { if (t !== "global") await assertBackupDirectory(e, t.startsWith("stores") ? "stores" : "agents", n); const i = path.join(e, t); await assertBackupDirectory(e, t, n); const a = await readOwnedScopeManifest(e, t, n); if (!r && !a) return; await assertBackupDirectory(e, path.join(t, GIT_BACKUP_TABLES), n); if (r?.schemaVersion === 2 || a?.schemaVersion === 2) await assertBackupDirectory(e, path.join(t, "postgres"), n); const o = a ? gitBackupArtifactFiles(a) : []; const s = r ? gitBackupArtifactFiles(r) : []; const c = new Set(o); for (const e of /* @__PURE__ */ new Set([...o, ...s])) { const r = path.join(i, e); const a = await lstatIfExists(r, "ENOENT"); const o = path.join(t, e).split(path.sep).join("/"); if (a && (!a.isFile() || !c.has(e)) || n.directories.has(o) || !c.has(e) && n.files.has(o)) refuseBackupOverwrite(r); } return { relative: t, previousFiles: o, files: s }; } async function prepareStaleScopeUpdates(e, t, n) { const r = /* @__PURE__ */ new Set(); for (const t of ["agents", "stores"]) { const i = path.join(e, t); const a = await lstatIfExists(i, "ENOENT"); if (a && !a.isDirectory()) continue; if (a) { for (const e of await fs$1.readdir(i, { withFileTypes: true })) if (e.isDirectory()) r.add(path.join(t, e.name)); } for (const e of n.headFiles.keys()) { const n = e.split("/"); const i = n[1]; if (n.length === 3 && n[0] === t && n[2] === "manifest.json" && i) r.add(path.join(t, i)); } } const i = []; for (const a of r) if (!t.has(a)) { const t = await prepareScopeUpdate(e, a, n); if (t) i.push(t); } return i; } async function applyScopeUpdate(e, t, n) { const r = path.join(t, n.relative); if (n.files.length > 0) await fs$1.mkdir(path.join(r, GIT_BACKUP_TABLES), { recursive: true, mode: 448 }); for (const e of n.previousFiles) await fs$1.rm(path.join(r, e), { force: true }); for (const t of n.files) { await fs$1.mkdir(path.dirname(path.join(r, t)), { recursive: true, mode: 448 }); await fs$1.cp(path.join(e, n.relative, t), path.join(r, t), { force: false, errorOnExist: true }); } if (n.files.length === 0) for (const e of [path.join(r, GIT_BACKUP_TABLES), r]) await fs$1.rmdir(e).catch((e) => { if (![ "ENOENT", "ENOTEMPTY", "EEXIST" ].some((t) => hasNodeErrorCode(e, t))) throw e; }); } //#endregion //#region src/snapshot/git-backup.ts const GIT_BACKUP_DIAGNOSTIC_MAX_LENGTH = 500; const GIT_BACKUP_NON_BACKUP_HISTORY_WARNING = "repository history contains non-backup commits; use a dedicated backup repository"; function gitBackupContentTimeout(e) { return Math.min(864e5, Math.max(GIT_TIMEOUT_MS, Math.ceil(e / 1024 ** 2) * 1e3)); } function redactGitBackupText(e) { return e.split("\n").map((e) => redactSensitiveUrlLikeString(e)).join("\n"); } function sanitizeGitBackupDiagnostic(e) { return truncateUtf16Safe(redactGitBackupText(e), GIT_BACKUP_DIAGNOSTIC_MAX_LENGTH); } async function cleanupGitBackupWorkspace(e) { let t; try { const n = await e.cleanup(); if (n === "removed" || n === "missing") return; t = n; } catch (e) { t = formatErrorMessage(e); } defaultRuntime.error(`Warning: Git backup temporary files may remain under ${path.dirname(e.dir)}; cleanup failed: ${sanitizeGitBackupDiagnostic(t)}`); } function formatGitBackupCommandResult(e, t) { const n = { ...t, stderr: redactGitBackupText(t.stderr), stdout: redactGitBackupText(t.stdout) }; const r = formatCommandResult(e, { ...n, stderr: "", stdout: "" }); const i = ["stderr", "stdout"].flatMap((e) => { const t = formatCommandOutput(n[e]); return t ? [{ stream: e, output: t }] : []; }); const a = r.length + i.reduce((e, { stream: t }) => e + 1 + `${t}: `.length, 0); if (i.length === 0 || a >= 1200) return truncateUtf16Safe(r, BACKUP_RUN_ERROR_MAX_LENGTH); const o = BACKUP_RUN_ERROR_MAX_LENGTH - a; const s = i.map(({ output: e }) => e.length); const c = Math.min(s[0] ?? 0, Math.max(Math.ceil(o / 2), o - (s[1] ?? 0))); const l = [c, Math.min(s[1] ?? 0, o - c)]; const fit = (e, t) => { if (e.length <= t) return e; if (t <= 1) return truncateUtf16Safe("…", t); const n = e.startsWith("…\n") ? e.slice(2) : e; return `…\n${sliceUtf16Safe(n, Math.max(0, n.length - (t - 2)))}`; }; return [r, ...i.map(({ stream: e, output: t }, n) => `${e}: ${fit(t, l[n] ?? 0)}`)].join("\n"); } function gitBackupRepositoryPrivacyRemediation(e, t) { if (process.platform === "win32") return `${t instanceof Error && t.message ? ` ${sanitizeGitBackupDiagnostic(t.message)}` : ""} Remove non-user ACL grants from ${e} or choose a private local directory. Do not use a shared or synced folder for SQLite backups.`; return `Fix its ownership and run chmod 700 ${e}.`; } async function assertGitRepository(e) { const t = await requireGitCommand(e, ["rev-parse", "--show-toplevel"]); const [n, r] = await Promise.all([fs$1.realpath(normalizeGitPathForFilesystem(t)), fs$1.realpath(e)]); if (n !== r) throw new Error(`Backup repository must be the Git worktree root: ${e}`); } /** Initialize or adopt an operator-owned Git backup repository. */ async function initializeGitBackupRepository(e) { const t = path.resolve(e.repositoryPath); const n = path.resolve(e.stateDir); const [r, i] = await Promise.all([canonicalPathFromExistingAncestor(t), canonicalPathFromExistingAncestor(n)]); if (isPathInside$1(i, r) || isPathInside$1(r, i)) throw new Error(`Git backup repository must be outside the OpenClaw state directory: ${n}`); try { await ensurePrivateSnapshotRepositoryRoot(t); } catch (e) { throw new Error(`Git backup repository must be owned by the current user and not writable by other users: ${t}. ${gitBackupRepositoryPrivacyRemediation(t, e)}`, { cause: e }); } if ((await executeGitCommand(t, ["rev-parse", "--show-toplevel"])).code !== 0) await requireGitCommand(t, ["init"]); await assertGitRepository(t); const a = e.remote?.trim(); if (a) { const e = await executeGitCommand(t, [ "remote", "get-url", "origin" ]); if (e.code === 0 && e.stdout.trim() !== a) throw new Error(`Git backup repository already has a different origin: ${sanitizeGitBackupDiagnostic(e.stdout.trim())}`); if (e.code !== 0) await requireGitCommand(t, [ "remote", "add", "origin", a ]); } return { repositoryPath: t }; } async function commitGitBackup(e) { let t = 0; for (const n of e.paths) t += (await lstatIfExists(path.join(e.repositoryPath, n)))?.size ?? 0; const n = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-git-backup-index-" }); try { const r = { ...process.env, GIT_INDEX_FILE: n.path("index") }; const i = await executeGitCommand(e.repositoryPath, [ "rev-parse", "--verify", "--quiet", "HEAD" ], { env: r }); if (i.code !== 0 && i.code !== 1) requireGitCommandOutput("git rev-parse HEAD", i); if ((i.code === 0 ? i.stdout.trim() : void 0) !== e.head) throw new Error("Git backup repository HEAD changed during the snapshot; retry the backup."); await requireGitCommand(e.repositoryPath, ["read-tree", e.head ?? "--empty"], { env: r }); await requireGitCommand(e.repositoryPath, [ "update-index", "--add", "--remove", "-z", "--stdin" ], { env: r, input: e.paths.join("\0") + "\0", timeoutMs: gitBackupContentTimeout(t) }); const a = await executeGitCommand(e.repositoryPath, [ "diff", "--cached", "--quiet" ], { env: r }); if (a.code === 0) return; if (a.code !== 1) requireGitCommandOutput("git diff --cached", a); const o = await executeGitCommand(e.repositoryPath, [ "config", "--get", "user.email" ]); const s = o.code === 0 && o.stdout.trim() ? [] : [ "-c", "user.name=OpenClaw", "-c", "user.email=backup@openclaw.local" ]; await requireGitCommand(e.repositoryPath, [ ...s, "commit", "-m", `openclaw backup ${(/* @__PURE__ */ new Date()).toISOString()}` ], { env: r }); await requireGitCommand(e.repositoryPath, [ "reset", "--quiet", "HEAD", "--pathspec-from-file=-", "--pathspec-file-nul" ], { input: e.paths.map((e) => `:(literal)${e}\0`).join("") }); return await requireGitCommand(e.repositoryPath, ["rev-parse", "HEAD"]); } finally { await cleanupGitBackupWorkspace(n); } } /** Snapshot selected databases, update the deterministic tree, and commit one Git revision. */ async function createGitBackup(e) { const t = [...e.databases]; if (e.all) { const { captureRuntimeConfigAsyncReader: n } = await import("./io-DeTUDO0h.mjs"); const r = await n({ skipPluginValidation: true })(); const i = listDatabaseEngineStores().some((e) => selectDatabaseEngine(e, r) === "postgres") ? await preparePostgresBackupDiscovery({ stateDir: e.stateDir, config: r }) : { paths: await discoverBackupDatabasePaths({ stateDir: e.stateDir, config: r }), resources: [] }; for (const n of i.paths) if (!t.some((e) => e.path === n) && readBackupEngine(n).engine === "postgres") { const a = await readPostgresBackupFamily(n, r); const o = i.resources.filter((e) => e.family === a && isPathInside$1(e.path, n)).toSorted((e, t) => t.path.length - e.path.length)[0]; const s = o?.path === n && o.pluginId === a && i.resources.filter((e) => e.family === a && e.path.endsWith(".sqlite")).length === 1; const c = path.relative(e.stateDir, n).split(path.sep).join("/"); const l = o?.pluginId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64); const u = s ? a : `${a}${l ? `__${l}` : ""}__${sha256Hex(c)}`; t.push({ path: n, identity: { role: "generic", id: u } }); } } const n = /* @__PURE__ */ new Set(); for (const r of t) { assertNotUpdateCapturePath(r.path, e.stateDir); const t = gitBackupScopePath(r.identity); if (n.has(t)) throw new Error(`Multiple backup databases use the same Git scope: ${t}`); n.add(t); } const r = path.resolve(e.repositoryPath); await initializeGitBackupRepository({ repositoryPath: r, stateDir: e.stateDir }); const i = await readGitBackupRepositoryState(r); const a = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-git-backup-" }); const o = []; const s = []; const c = []; try { for (const [n, r] of t.entries()) { const t = path.join(a.dir, gitBackupScopePath(r.identity)); await fs$1.mkdir(path.dirname(t), { recursive: true, mode: 448 }); const i = a.path(`${r.identity.role}-${n}.sqlite`); try { const n = readBackupEngine(r.path).engine === "postgres"; if (!n) await createOpenClawSnapshotCopy({ database: { ...r, path: await fs$1.realpath(r.path) }, targetPath: i }); o.push(await dumpGitBackupDatabase({ snapshotPath: n ? r.path : i, outputPath: t, identity: r.identity, physicalEngine: n ? "postgres" : "sqlite", excludeSecrets: e.excludeSecrets })); } catch (t) { if (!e.all || r.identity.role !== "agent") throw t; s.push(`Agent ${r.identity.agentId} degraded; keeping previous backup scope if present: ${sanitizeGitBackupDiagnostic(formatErrorMessage(t))}`); continue; } await fs$1.rm(i, { force: true }); } if (o.length === 0) throw new Error("No Git backup databases were found for the selected scope."); for (const e of o) { const t = await prepareScopeUpdate(r, gitBackupScopePath(e.identity), i, e); if (t) c.push(t); } if (e.all) c.push(...await prepareStaleScopeUpdates(r, n, i)); for (const e of c) await applyScopeUpdate(a.dir, r, e); } finally { await cleanupGitBackupWorkspace(a); } const l = await commitGitBackup({ repositoryPath: r, head: i.head, paths: [...new Set(c.flatMap(({ relative: e, previousFiles: t, files: n }) => [...t, ...n].map((t) => path.join(e, t).split(path.sep).join("/"))))] }); let u = false; let d; if (e.push) { if (await requireGitCommand(r, [ "rev-list", "HEAD", "--invert-grep", "--grep=^openclaw backup ", "--count" ]) !== "0") d = GIT_BACKUP_NON_BACKUP_HISTORY_WARNING; else { const e = await executeGitCommand(r, [ "push", "-u", "origin", "HEAD" ]); if (e.code === 0) u = true; else d = formatGitBackupCommandResult("git push", e); } } return { repositoryPath: r, ...l ? { commit: l } : {}, noChanges: !l, pushed: u, ...d ? { pushWarning: d } : {}, manifests: o, warnings: s }; } /** Materialize one database scope from a Git ref into a private temporary directory. */ async function materializeGitBackupRef(e) { const t = path.resolve(e.repositoryPath); await assertGitRepository(t); const n = await requireGitCommand(t, [ "rev-parse", "--verify", `${e.ref?.trim() || "HEAD"}^{commit}` ]); const r = gitBackupScopePath(e.identity).split(path.sep).join("/"); const i = (await requireGitCommand(t, [ "ls-tree", "-r", "-l", "-z", n, "--", r ])).split("\0").filter(Boolean); const a = new Map(i.map((e) => [e.slice(e.indexOf(" ") + 1), e])); const assertRegularArtifact = (e) => { const t = a.get(e); if (!t) throw new Error(`Git backup ref ${n} does not contain ${e}.`); if (!t.startsWith("100644 blob ") && !t.startsWith("100755 blob ")) throw new Error(`Git backup ref contains a non-regular artifact: ${e}`); return Number(t.slice(0, t.indexOf(" ")).trim().split(/\s+/).at(-1)); }; const o = `${r}/${GIT_BACKUP_MANIFEST}`; assertRegularArtifact(o); const s = parseGitBackupManifest(await requireGitCommand(t, ["show", `${n}:${o}`]), o); const c = gitBackupArtifactFiles(s).map((e) => { const t = `${r}/${e.split(path.sep).join("/")}`; return { file: t, timeout: gitBackupContentTimeout(assertRegularArtifact(t)) }; }); const l = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-git-restore-" }); const u = path.join(l.dir, r); try { for (const { file: e, timeout: i } of c) { const a = e.slice(r.length + 1); const o = path.join(u, a); await fs$1.mkdir(path.dirname(o), { recursive: true, mode: 448 }); await fs$1.writeFile(o, "", { flag: "wx", mode: 384 }); await spawnCommand([ "git", "-C", t, "show", `${n}:${e}` ], { stdin: "ignore", stdout: { file: o }, buffer: { stdout: false }, maxBuffer: { stderr: 1048576 }, timeout: i }); } return { commit: n, path: u, manifest: s, [Symbol.asyncDispose]: async () => await cleanupGitBackupWorkspace(l) }; } catch (e) { await cleanupGitBackupWorkspace(l); throw e; } } /** Restore one database from a Git ref to a caller-selected fresh path. */ async function restoreGitBackupRef(e) { try { var t = _usingCtx(); const n = t.a(await materializeGitBackupRef(e)); return { ...await restoreGitBackupDirectory({ sourcePath: n.path, targetPath: e.targetPath, expectedIdentity: e.identity }), commit: n.commit }; } catch (e) { t.e = e; } finally { await t.d(); } } /** Verify PostgreSQL's matched artifacts or SQLite's private round-trip table digests. */ async function verifyGitBackupRef(e) { const t = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-git-verify-" }); try { try { var n = _usingCtx(); const r = n.a(await materializeGitBackupRef(e)); const { manifest: i } = r; if (gitBackupScopePath(i.identity) !== gitBackupScopePath(e.identity)) throw new Error("Git backup manifest database identity does not match the requested scope."); const a = t.path("database.sqlite"); if (i.schemaVersion === 2) { await createLocalSnapshotProvider({ repositoryPath: r.path, expectedPostgresSource: i.postgresSource }).verify({ path: path.join(r.path, "postgres") }); return { manifest: i, targetPath: a, tables: [], excludedTables: i.excludedTables, excludedConfigStateKeyPrefixes: i.excludedConfigStateKeyPrefixes, commit: r.commit }; } return { ...await restoreGitBackupDirectory({ sourcePath: r.path, targetPath: a, expectedIdentity: e.identity }), commit: r.commit }; } catch (e) { n.e = e; } finally { await n.d(); } } finally { await cleanupGitBackupWorkspace(t); } } /** Return bounded Git backup log entries for CLI rendering. */ async function readGitBackupLog(e) { await assertGitRepository(e.repositoryPath); const t = await executeGitCommand(e.repositoryPath, [ "symbolic-ref", "--quiet", "HEAD" ]); if (t.code === 0) { const n = t.stdout.trim(); const r = await executeGitCommand(e.repositoryPath, [ "show-ref", "--verify", "--quiet", n ]); if (r.code === 1 && n.startsWith("refs/heads/")) return []; if (r.code !== 0) throw new Error(formatGitBackupCommandResult("git show-ref HEAD", r)); } else if (t.code !== 1) throw new Error(formatGitBackupCommandResult("git symbolic-ref HEAD", t)); const n = await executeGitCommand(e.repositoryPath, [ "log", `--max-count=${e.limit}`, "--pretty=format:%H%x09%cI%x09%s" ]); return requireGitCommandOutput("git log", n, (e, t) => new Error(formatGitBackupCommandResult(e, t))).split("\n").filter(Boolean).map((e) => { const [t = "", n = "", ...r] = e.split(" "); return { commit: t, date: n, message: r.join(" ") }; }); } //#endregion //#region src/commands/backup-git.ts const GIT_BACKUP_PUSH_CREDENTIAL_WARNING = "Warning: pushed backup history contains credential material; keep the Git remote private."; async function resolveCreateDatabases(e) { const t = [...new Set((e.agents ?? []).map((e) => { const t = e.trim(); if (!t) throw new Error("--agent must not be blank"); return normalizeAgentId(t); }))]; const n = e.global === true || t.length > 0; if (e.all && n) throw new Error("Use --all by itself, or select --global and --agent scopes explicitly."); if (!e.all && !n) throw new Error("Choose at least one Git backup scope: --all, --global, or --agent <id>."); const r = e.all || e.global ? resolveOpenClawStateSqlitePath() : void 0; if (r) assertNotUpdateCapturePath(r, resolveStateDir()); const i = await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })(); let a = []; if (e.all || t.length > 0) { const n = e.all ? listAgentIds(i).toSorted() : t.map((e) => resolveConfiguredAgentId(i, e)); a = await Promise.all(n.map((e) => resolveBackupAgentRoot(i, e))); } const o = []; if (r) o.push({ path: r, identity: { role: "global" } }); for (const { agentId: e, databasePath: t } of a) { assertNotUpdateCapturePath(t, resolveStateDir()); o.push({ path: t, identity: { role: "agent", agentId: e } }); } return o; } function resolveOneIdentity(e) { const t = e.agent?.trim(); const n = e.store?.trim(); if (e.store !== void 0 && !n) throw new Error("--store must not be blank"); const r = Number(e.global === true) + Number(Boolean(t)) + Number(Boolean(n)); if (r > 1) throw new Error("Choose exactly one Git backup scope: --global, --agent <id>, or --store <id>."); if (r === 0) throw new Error("Choose a Git backup scope: --global, --agent <id>, or --store <id>."); if (n) return { role: "generic", id: n }; return e.global === true ? { role: "global" } : { role: "agent", agentId: normalizeAgentId(t) }; } async function backupGitInitCommand(e, t) { const n = await initializeGitBackupRepository({ repositoryPath: resolveRequiredBackupPath(t.repository, "--repository"), stateDir: resolveStateDir(), remote: t.remote }); if (t.json) writeRuntimeJson(e, n); else e.log(terminalText`Git backup repository ready: ${shortenHomePath(n.repositoryPath)}`); return n; } async function backupGitCreateCommand(e, t) { const n = resolveRequiredBackupPath(t.repository, "--repository"); const r = await resolveCreateDatabases(t); if (t.push && !t.excludeSecrets) e.error(GIT_BACKUP_PUSH_CREDENTIAL_WARNING); const i = beginLifecycleWriteCustody("backup"); let a; try { const i = await withCommandProcessScope(async () => createGitBackup({ repositoryPath: n, stateDir: resolveStateDir(), databases: r, all: t.all, excludeSecrets: t.excludeSecrets, push: t.push })); await recordBackupOutcomeBestEffort(e, { kind: "git", archivePath: n, status: "ok", target: i.commit, error: [...i.warnings, ...i.pushWarning ? [i.pushWarning] : []].join("\n") || void 0, ...i.pushWarning ? { pushFailed: true } : {} }); if (t.json) writeRuntimeJson(e, i); else if (i.noChanges) e.log(terminalText`Git backup: no changes (${shortenHomePath(n)})`); else e.log(terminalText`Git backup committed: ${i.commit}`); if (i.pushWarning) { const t = i.pushWarning.split("\n").join(" \\n "); e.error(terminalText`Warning: Git backup committed, but push failed: ${t}`); } for (const t of i.warnings) e.error(terminalText`Warning: ${t}`); return i; } catch (t) { a = t; await recordBackupOutcomeBestEffort(e, { kind: "git", archivePath: n, status: "failed", error: formatErrorMessage(t) }); throw t; } finally { i(a); } } async function backupGitLogCommand(e, t) { const n = resolveRequiredBackupPath(t.repository, "--repository"); const r = await readGitBackupLog({ repositoryPath: n, limit: t.limit ?? 20 }); if (t.json) writeRuntimeJson(e, { repositoryPath: n, entries: r }); else if (r.length === 0) e.log(terminalText`No Git backup commits in ${shortenHomePath(n)}.`); else e.log(r.map((e) => terminalText`${e.commit}\t${e.date}\t${e.message}`).join("\n")); return r; } async function backupGitVerifyCommand(e, t) { const n = await verifyGitBackupRef({ repositoryPath: resolveRequiredBackupPath(t.repository, "--repository"), identity: resolveOneIdentity(t), ref: t.ref }); if (t.json) writeRuntimeJson(e, n); else { for (const t of n.tables) e.log(terminalText`${t.ok ? "ok" : "failed"}\t${t.table}\t${t.rows}\t${t.sha256}`); e.log(terminalText`Git backup verified: ${n.commit}`); } return n; } async function backupGitRestoreCommand(e, t) { const n = await restoreGitBackupRef({ repositoryPath: resolveRequiredBackupPath(t.repository, "--repository"), identity: resolveOneIdentity(t), ref: t.ref, targetPath: resolveRequiredBackupPath(t.target, "--target") }); if (t.json) writeRuntimeJson(e, n); else { e.log(terminalText`Git backup restored: ${shortenHomePath(n.targetPath)} (${n.commit})`); if (n.excludedTables.length > 0) e.error(terminalText`Warning: this redacted backup omits tables: ${n.excludedTables.join(", ")}`); if (n.excludedConfigStateKeyPrefixes.length > 0) e.error(terminalText`Warning: this redacted backup omits machine-state values under: ${n.excludedConfigStateKeyPrefixes.join(", ")}`); } return n; } //#endregion export { backupGitRestoreCommand as a, backupGitLogCommand as i, backupGitCreateCommand as n, backupGitVerifyCommand as o, backupGitInitCommand as r, GIT_BACKUP_PUSH_CREDENTIAL_WARNING as t };