openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
448 lines (447 loc) • 20.8 kB
JavaScript
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { g as isReservedSystemAgentId, i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { c as resolveOpenClawAgentSqlitePath, n as createOpenClawAgentDatabasePathMatcher } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { a as isSqliteCorruptionError } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { D as requireNativeDatabaseFile, d as invalidateSqliteSchemaFacts } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { a as prepareSqliteReadOnlyLocationSync, r as prepareSqliteReadOnlyLocation } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs";
import { m as withExistingOpenClawStateDatabaseReadOnly, p as withExistingOpenClawStateDatabaseCurrentReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { a as isStatePostgres } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import { h as writeTextAtomic } from "./json-files-Cb1h8pYs.mjs";
import { T as resolveOpenClawAgentDatabaseDiscoveryPaths, l as runOpenClawStateWriteTransaction, w as prepareStateDatabaseInitialization } from "./openclaw-state-db-ARhwdPJg.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import "./io-4QsrsWTJ.mjs";
import { n as quotePowerShellArg, t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { n as parseAgentDeletionDatabasePaths } from "./agent-deletion-journal.read-DjOO2RZM.mjs";
import { _ as recordAgentDeletionRecoveryHolds, g as reconstructAgentDeletionJournal, p as readAgentDeletionJournalInDatabase, u as parseCleanupPaths, v as resolveAgentDeletionRecoveryHolds } from "./agent-deletion-journal-DgNbVVSp.mjs";
import { o as readAgentDeletionMissingJournalHolds, s as readAgentDeletionRecoveryHolds } from "./agent-deletion-journal-recovery.kernel-BMlEn3jf.mjs";
import { o as invalidateAgentDeletionJournalStatus } from "./agent-deletion-journal-status-CZ5XyH3P.mjs";
import { s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs";
import { i as hasSqliteFileFamily } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { n as isTransientSqliteBackupPath } from "./backup-volatile-filter-Wvq7R1eh.mjs";
import { t as createAgentSchemaInspectionWorker } from "./openclaw-agent-schema-inspection-worker-J31vzzWl.mjs";
import { n as backupDoctorSqliteDatabases } from "./doctor-migration-backup-DwSvhlqi.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
//#region src/commands/doctor-agent-deletion-journal-quarantine.ts
function readRecoverySource(e) {
const t = e.db;
const n = isPostgresSqlConnection(t);
if (!n) invalidateSqliteSchemaFacts(t);
const r = tableExists(e.db, "migration_sources") ? readAgentDeletionRecoveryHolds(e) : [];
if (!tableExists(e.db, "agent_deletion_journal")) {
if (n) requireNativeDatabaseFile("postgres", "repair");
return {
missing: true,
rows: [],
invalid: [],
held: r
};
}
const i = executeSqliteQuerySync(e.db, getNodeSqliteKysely(e.db).selectFrom("agent_deletion_journal").selectAll().orderBy("agent_id")).rows;
const a = i.filter((t) => {
if (isReservedSystemAgentId(t.agent_id)) return true;
try {
readAgentDeletionJournalInDatabase(e, t.agent_id);
return false;
} catch (e) {
if (isSqliteCorruptionError(e)) throw e;
return true;
}
});
if (n && a.length > 0) requireNativeDatabaseFile("postgres", "repair");
return {
missing: false,
rows: i,
invalid: a,
held: r
};
}
/** Doctor preserves unusable journal rows before trading cleanup authority for repair holds. */
async function quarantineAgentDeletionJournal(e) {
const { env: t } = e;
const n = withExistingOpenClawStateDatabaseReadOnly(readRecoverySource, { env: t }) ?? {
missing: true,
rows: [],
invalid: [],
held: []
};
if (!n.missing && n.invalid.length === 0) return;
let r = n.missing ? [...e.inventory] : [...n.held];
if (n.missing && n.held.length === 0) try {
var i = _usingCtx();
const n = createOpenClawAgentDatabasePathMatcher();
const a = [];
const o = i.a(createAgentSchemaInspectionWorker());
for (const i of r) {
if (e.configuredTargets.some((e) => e.agentId === i.agentId && n(e.path, i.path))) try {
const e = {
pathname: i.path,
agentId: i.agentId,
env: t,
supportedVersion: 38,
inspectOwnership: true,
inspectEmptyStore: true
};
let n = await o.inspect(e);
if (!n) {
const t = await prepareSqliteReadOnlyLocation(i.path, {
preserveSourceArtifacts: true,
requireCleanup: true
});
try {
n = await o.inspect(e, void 0, t.location);
} finally {
if (!await t.cleanupAsync()) n = null;
}
}
if (n?.emptyStore === true) continue;
} catch {}
a.push(i);
}
r = a;
} catch (e) {
i.e = e;
} finally {
await i.d();
}
for (const i of n.invalid) {
const n = /* @__PURE__ */ new Set([...resolveOpenClawAgentDatabaseDiscoveryPaths({
agentDir: i.agent_dir,
agentId: i.agent_id,
env: t
}).filter(hasSqliteFileFamily), ...e.inventory.filter((e) => normalizeAgentId(e.agentId) === normalizeAgentId(i.agent_id)).map((e) => e.path)]);
try {
for (const e of parseAgentDeletionDatabasePaths(i.database_paths_json)) n.add(e);
} catch {}
try {
for (const e of parseCleanupPaths(i.cleanup_paths_json)) for (const t of e.sourcePaths) n.add(t);
} catch {}
r.push(...[...n].filter((e) => !SQLITE_SIDECAR_SUFFIXES.some((t) => e.endsWith(t) && n.has(e.slice(0, -t.length)))).map((e) => ({
agentId: i.agent_id,
path: e
})));
}
const a = getOpenClawDatabaseMaintenanceScope();
const assertCurrent = () => a?.assertAdmission();
const o = [];
const s = [];
const c = new Set(r.map((e) => normalizeAgentId(e.agentId)));
for (const e of c) {
const i = path.join(resolveStateDir(t), "agents", e, "recovery", `deletion-journal-${randomUUID()}.json`);
assertCurrent();
try {
await writeTextAtomic(i, JSON.stringify({
source: resolveOpenClawStateSqlitePath(t),
reason: n.missing ? "missing deletion journal" : "unusable deletion journal",
journal: n.invalid.filter((t) => normalizeAgentId(t.agent_id) === e),
held: r.filter((t) => normalizeAgentId(t.agentId) === e)
}, null, 2), {
mode: 384,
dirMode: 448,
durable: true,
beforeRename: async () => {
assertCurrent();
}
});
o.push(i);
} catch (e) {
s.push(`Warning: Could not save deletion recovery receipt ${i}: ${formatErrorMessage(e)}. Original journal records remain in place and stores remain held; repair the recovery directory, then run openclaw doctor --fix.`);
}
}
assertCurrent();
if (s.length > 0) r.push(...e.inventory);
return {
held: runOpenClawStateWriteTransaction((e) => {
assertCurrent();
if (!isDeepStrictEqual(readRecoverySource(e), n)) throw new Error("Agent deletion journal changed before quarantine; stores were left untouched.");
if (n.missing) return reconstructAgentDeletionJournal(e, r);
const t = getNodeSqliteKysely(e.db);
for (const i of s.length === 0 ? n.invalid : []) {
if (isReservedSystemAgentId(i.agent_id)) {
executeSqliteQuerySync(e.db, t.deleteFrom("agent_deletion_journal").where("agent_id", "=", i.agent_id));
invalidateAgentDeletionJournalStatus(e.db, i.agent_id);
continue;
}
executeSqliteQuerySync(e.db, t.updateTable("agent_deletion_journal").set({
operation_id: randomUUID(),
database_paths_json: JSON.stringify([...new Set(r.filter((e) => normalizeAgentId(e.agentId) === normalizeAgentId(i.agent_id)).map((e) => e.path))]),
cleanup_paths_json: "[]",
cleanup_completed: 1,
delete_files: 0
}).where("agent_id", "=", i.agent_id));
invalidateAgentDeletionJournalStatus(e.db, i.agent_id);
}
return recordAgentDeletionRecoveryHolds(e, r, {
excludeMissingJournal: r.filter((e) => n.invalid.some((t) => normalizeAgentId(t.agent_id) === normalizeAgentId(e.agentId))),
description: s.length === 0 ? "Quarantined unusable agent deletion records; stores remain held for explicit recovery." : "Preserved unusable agent deletion records in place; stores remain held for explicit recovery."
});
}, { env: t }),
archives: o,
warnings: s
};
}
//#endregion
//#region src/commands/doctor-agent-deletion-journal-restore.ts
function readVerifiedOwner(e, t) {
const n = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("schema_meta").selectAll().where("meta_key", "=", "primary"));
if (n?.role !== "agent" || n.agent_id !== t || readSqliteUserVersion(e) !== n.schema_version) return;
return n;
}
function inspectOwner(e, t) {
const n = prepareSqliteReadOnlyLocationSync(e);
let r;
let i;
try {
try {
var a = _usingCtx();
r = readVerifiedOwner(a.u(openNodeSqliteDatabase(n.location, { readOnly: true })), t);
} catch (e) {
a.e = e;
} finally {
a.d();
}
} finally {
i = n.cleanup();
}
if (!i) throw new Error(`Could not release agent recovery inspection snapshot: ${n.location}`);
return r;
}
/** Restore configured, verified stores after journal loss; quarantine still needs explicit consent. */
async function restoreDoctorMissingJournalStores(e) {
const t = [];
const n = [];
const r = [];
if (e.held.length === 0 || isStatePostgres()) return {
changes: t,
warnings: n,
restored: r
};
const i = getOpenClawDatabaseMaintenanceScope();
if (!i?.ownsSchemaMaintenance) return {
changes: t,
warnings: n,
restored: r
};
const a = await createConfigIO({
env: e.env,
observe: false,
pluginValidation: "core-only"
}).readConfigFileSnapshot();
if (!a.valid) return {
changes: t,
warnings: n,
restored: r
};
const o = createOpenClawAgentDatabasePathMatcher();
const s = resolveConfiguredAgentDatabaseTargets(a.sourceConfig, {
env: e.env,
registeredDatabases: e.held
});
const c = listAgentIds(a.sourceConfig);
const readEligibleHolds = (e, t) => isReservedSystemAgentId(t) ? readAgentDeletionRecoveryHolds(e) : readAgentDeletionMissingJournalHolds(e);
const matchesReceipt = (t, n) => {
const matches = (e) => readEligibleHolds(e, t.agentId).some((e) => e.agentId === t.agentId && o(e.path, t.path)) && !readAgentDeletionJournalInDatabase(e, t.agentId);
return n ? matches(n) : withExistingOpenClawStateDatabaseCurrentReadOnly(matches, {
env: e.env,
allowNativeRead: true
}) === true;
};
const l = e.held.flatMap((t) => {
if (!(isReservedSystemAgentId(t.agentId) ? o(t.path, resolveOpenClawAgentSqlitePath({
agentId: t.agentId,
env: e.env
})) : c.includes(t.agentId) && s.some((e) => e.agentId === t.agentId && o(e.path, t.path))) || !matchesReceipt(t)) return [];
try {
const e = inspectOwner(t.path, t.agentId);
return e ? [{
...t,
producer: e
}] : [];
} catch (e) {
n.push(`Agent ${t.agentId} remains held; could not verify its database ownership: ${formatErrorMessage(e)}`);
return [];
}
});
if (l.length === 0) return {
changes: t,
warnings: n,
restored: r
};
const u = new Set(l);
const assertCurrent = (e) => {
i.assertAdmission();
if (!o.isCurrent() || [...u].some((t) => !matchesReceipt(t, e))) throw new Error("Agent deletion recovery changed; preserved stores remain held. Rerun Doctor.");
};
assertCurrent();
const d = await backupDoctorSqliteDatabases({
env: e.env,
pendingDatabasePaths: l.map((e) => e.path),
databasePaths: l.map((e) => e.path),
authority: { assertCurrent },
requireSnapshots: true,
repair: {
key: "published-missing-agent-deletion-journal",
validate: (t) => {
const n = executeSqliteQueryTakeFirstSync(t, getNodeSqliteKysely(t).selectFrom("schema_meta").select(["role", "agent_id"]).where("meta_key", "=", "primary"));
if (n?.role === "global") {
const n = {
db: t,
path: resolveOpenClawStateSqlitePath(e.env)
};
if (l.some((e) => !readEligibleHolds(n, e.agentId).some((t) => t.agentId === e.agentId && o(t.path, e.path)) || readAgentDeletionJournalInDatabase(n, e.agentId))) throw new Error("Recovery backup does not preserve the deletion reconstruction records.");
} else if (!l.some((e) => e.agentId === n?.agent_id && isDeepStrictEqual(readVerifiedOwner(t, e.agentId), e.producer))) throw new Error("Recovery backup does not preserve the verified agent ownership metadata.");
}
}
});
t.push(...d.changes);
n.push(...d.warnings);
const f = d.snapshots ?? [];
const p = f.find((t) => o(t.sourcePath, resolveOpenClawStateSqlitePath(e.env)));
if (!p) throw new Error("Agent restoration requires a verified shared-state and reconstruction-record backup.");
const { createAgent: m } = await import("./agent-create-DRw9RYIb.mjs");
let h = a.hash ?? null;
for (const t of new Set(l.map((e) => e.agentId))) {
const i = l.filter((e) => e.agentId === t);
assertCurrent();
if (isReservedSystemAgentId(t)) {
for (const e of i) if (!isDeepStrictEqual(inspectOwner(e.path, t), e.producer)) throw new Error(`System agent ${t} ownership changed before recovery.`);
runOpenClawStateWriteTransaction((e) => {
assertCurrent(e);
resolveAgentDeletionRecoveryHolds(e, t, i.map((e) => e.path));
}, { env: e.env });
} else {
const e = await m({
name: t,
expectedConfigHash: h,
restorePaths: i.map((e) => e.path),
beforePersistentApply: assertCurrent
});
if (e.status === "error") {
n.push(`Agent ${t} remains held: ${e.message}`);
continue;
}
h = e.configHash ?? h;
}
for (const a of i) {
if (withExistingOpenClawStateDatabaseCurrentReadOnly((e) => readAgentDeletionRecoveryHolds(e).some((e) => e.agentId === a.agentId && o(e.path, a.path)), {
env: e.env,
allowNativeRead: true
}) !== false) throw new Error(`Agent ${t} restoration left ${a.path} held.`);
u.delete(a);
r.push(a);
n.push(`Warning: Automatically restored agent ${t} database ${a.path}${isReservedSystemAgentId(t) ? " after verifying reserved system-agent ownership" : " after verifying configured ownership and missing deletion history"}. Verified backup: ${f.find((e) => o(e.sourcePath, a.path)).path}; shared state and reconstruction records: ${p.path}.`);
}
}
return {
changes: t,
warnings: n,
restored: r
};
}
//#endregion
//#region src/commands/doctor-agent-deletion-journal.ts
/** Doctor alone reconstructs lost deletion history and records the stores it cannot verify. */
async function repairDoctorAgentDeletionJournal(e) {
const t = e.preflight.agentDatabaseMigrationDiscovery?.discovery;
const n = [];
const r = [];
let i = false;
if (!t) return {
changes: n,
warnings: []
};
if (t.deletionJournal.status === "unavailable" && t.deletionJournal.cause === "unreadable" && !e.shouldRepair) return {
changes: n,
warnings: [sanitizeForLog(`${resolveOpenClawStateSqlitePath(e.env)}: ${t.deletionJournal.reason}. Stores remain held; restore verified deletion history, then rerun openclaw doctor --fix.`), ...[...t.retainedTargets, ...t.unverifiedTargets].map(({ agentId: e, path: t }) => sanitizeForLog(`Held agent ${e} database ${t}; deletion history needs repair.`))]
};
const a = t.deletionJournal.status === "unavailable" && t.deletionJournal.cause === "missing";
if (a && t.unverifiedTargets.length === 0 && t.failures.length === 0 && prepareStateDatabaseInitialization(resolveOpenClawStateSqlitePath(e.env), e.env).kind === "fresh") return {
changes: n,
warnings: []
};
let o = t.unverifiedTargets.map(({ agentId: e, path: t }) => ({
agentId: e,
path: t
}));
if (a && t.failures.length > 0) return {
changes: n,
warnings: ["Agent deletion journal missing; stores remain held because their recovery inventory is incomplete. Repair the listed paths, then rerun openclaw doctor --fix.", ...t.failures.map(({ path: e, reason: t }) => sanitizeForLog(`${e}: ${t}`))]
};
if (a && e.preflight.agentDatabaseRecoveryConfigValid !== true) return {
changes: n,
warnings: ["Agent deletion journal missing; stores remain held because the ownership configuration could not be verified. Repair the configuration, then rerun openclaw doctor --fix."]
};
if (e.shouldRepair) {
const s = await quarantineAgentDeletionJournal({
inventory: [
...t.targets,
...t.retainedTargets,
...o
],
configuredTargets: e.preflight.agentDatabaseMigrationDiscovery?.configuredAgentDatabaseTargets ?? [],
env: e.env
});
if (s) {
i = !a && s.warnings.length === 0;
r.push(...s.warnings.map((e) => sanitizeForLog(e)));
o = s.held;
n.push(a ? "Reconstructed the missing agent deletion journal and recorded a Doctor receipt listing held stores." : i ? "Quarantined unusable agent deletion journal records and recorded a Doctor receipt listing held stores." : "Preserved unusable agent deletion journal records in place and recorded a Doctor receipt listing held stores.");
n.push(...s.archives.map((e) => sanitizeForLog(`Saved deletion recovery receipt: ${e}`)));
}
const c = await restoreDoctorMissingJournalStores({
env: e.env,
held: o
});
n.push(...c.changes.map(sanitizeForLog));
r.push(...c.warnings.map(sanitizeForLog));
o = o.filter((e) => !c.restored.some((t) => t.agentId === e.agentId && t.path === e.path));
}
if (o.length === 0 && (!a || e.shouldRepair)) return {
changes: n,
warnings: r
};
const s = await createConfigIO({
env: e.env,
observe: false,
pluginValidation: "core-only"
}).readConfigFileSnapshot();
const c = process.platform === "win32" ? quotePowerShellArg : quoteCliArg;
return {
changes: n,
warnings: [
...r,
`Warning: Agent deletion journal ${a && !e.shouldRepair ? "missing" : i ? "quarantined" : r.length > 0 ? "unusable" : "reconstructed"}; ${o.length} store${o.length === 1 ? "" : "s"} held back. Updates can continue; held stores remain untouched.`,
...o.map((t) => {
if (isTransientSqliteBackupPath(t.path)) return sanitizeForLog(`${t.path}: internal SQLite coordination artifact; preserved without agent restoration or deletion.`);
if (isReservedSystemAgentId(t.agentId)) return sanitizeForLog(`${t.path}: ${t.agentId} is a reserved system agent and cannot be added or deleted. Run ${formatCliCommand("openclaw doctor --fix", e.env)} to restore its canonical store after ownership, integrity, and backup verification; unverified stores remain untouched.`);
const n = resolveAgentWorkspaceDir(s.sourceConfig, t.agentId, e.env);
const r = listAgentIds(s.sourceConfig).includes(t.agentId) ? resolveAgentDir(s.sourceConfig, t.agentId, e.env) : path.dirname(t.path);
const i = formatCliCommand(`openclaw agents add ${c(t.agentId)} --workspace ${c(n)} --agent-dir ${c(r)} --non-interactive`, e.env);
return sanitizeForLog(`${t.path}: ${path.basename(t.path) === "openclaw-agent.sqlite" ? "verify the workspace" : "restore the original session.store configuration for this database and verify the workspace"}, then run ${i} to abort deletion and restore; after restoration, run ${formatCliCommand(`openclaw agents delete ${c(t.agentId)} --force`, e.env)} to confirm deletion instead.`);
}),
...a && !e.shouldRepair ? [`Run ${formatCliCommand("openclaw doctor --fix", e.env)} to reconstruct the journal and restore verified configured stores automatically after verified backups. Other stores remain held.`] : []
]
};
}
//#endregion
export { repairDoctorAgentDeletionJournal };