openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
484 lines (483 loc) • 20.2 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import "./paths-DAcAg5aV.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { r as isMigrationArchiveArtifactName } from "./artifacts-D7SzhQlr.mjs";
import { a as resolveUnsuffixedSqliteTargetFromSessionStorePath } from "./session-sqlite-target-paths-Dw0pT36E.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { _ as withSynchronousArtifactPreservingStateSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { _ as isNeverActivatedFailedUpdate } from "./update-run-write-gdMM-b0r.mjs";
import { i as isUpdateRecoveryPending } from "./update-run-recovery-schema-C6o9exnN.mjs";
import { i as getUpdateRun, l as listUpdateRuns } from "./update-run-reader-7kFqqMpW.mjs";
import { E as statMigrationPath, S as isPendingMigrationArtifactClaim, T as sameMigrationArtifact, a as collectRecordedConsumedArchives, d as listSessionSqliteMigrationManifestPaths, g as resolveSessionSqliteMigrationRunsDir, i as canonicalMigrationFilePath, l as hasSymbolicLinkInDirectoryPath, p as readSessionSqliteMigrationManifest, v as uniqueRestoreMoves } from "./session-sqlite-migration-manifest-DwBodX3i.mjs";
import { n as isSessionSqliteMigrationWarning } from "./session-sqlite-migration-issues-aFS6aEaW.mjs";
import { i as UPDATE_CAPTURE_PRIVACY_MARKER, r as resolveUpdateCaptureRoot } from "./update-capture-paths-B2WcdTCG.mjs";
import { n as loadUpdateRecovery } from "./update-run-recovery-7wvn_ggB.mjs";
import { o as parseUpdateRecoveryBackupManifest } from "./backup-verify-manifest-CVAAAU_5.mjs";
import { t as collectStandaloneDoctorCaptures } from "./doctor-capture-retention-BbyuEgCY.mjs";
import { t as captureScopes } from "./update-recovery-backup-reader-CzkKDmJ9.mjs";
import fs from "node:fs";
import path from "node:path";
import { readRootStructuredFileSync } from "@openclaw/fs-safe/json";
//#region src/commands/update-capture-cleanup.ts
/** Original-state update and standalone Doctor captures in user-invoked cleanup. */
/** A rollback original is superseded only after a later update succeeded. */
function readCompletedUpdateHistory(e) {
try {
const [t] = listUpdateRuns({
limit: 1,
succeeded: true
}, { env: e });
return {
runs: listUpdateRuns({ limit: 100 }, { env: e }),
latestCompletedStartedAt: t && t.finishedAtMs !== null ? t.createdAtMs : 0
};
} catch {
return;
}
}
function logicalBytes(e) {
let t = 0;
for (const n of fs.readdirSync(e, { withFileTypes: true })) {
const r = path.join(e, n.name);
t += n.isDirectory() ? logicalBytes(r) : fs.lstatSync(r).size;
}
return t;
}
function classifyCapture(e, t, n, r) {
if (t.status === "running" || t.finishedAtMs === null) return {
outcome: "protected",
reason: "unfinished-update-run"
};
const i = loadUpdateRecovery(t.runId, { env: r });
if (i && isUpdateRecoveryPending(i)) return {
outcome: "protected",
reason: "pending-update-recovery"
};
if (isNeverActivatedFailedUpdate(t)) return {
outcome: "candidate",
reason: "never-activated-update-capture"
};
const a = fs.existsSync(path.join(e, "manifest.json")) && !fs.existsSync(path.join(e, "manifest.json.partial"));
const o = t.origin.updateRecoveryCapture;
if (a && (t.status === "failed" || t.status === "rolled-back") && !o?.restored && !o?.forwardResolution && !o?.retirement) return {
outcome: "protected",
reason: "unresolved-failed-update"
};
if (!(n > t.finishedAtMs)) return {
outcome: "protected",
reason: "awaiting-later-completed-update"
};
return {
outcome: "candidate",
reason: a ? "superseded-update-capture" : "unsealed-update-capture"
};
}
/** Lists every selected capture scope, including originals retained before state relocation. */
function collectUpdateCaptureInventory(e) {
const t = [];
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Set([e.stateDir, ...captureScopes(e.env).keys()]);
for (const i of r) {
if (e.scan && !e.scan.available()) break;
const r = collectCaptureRootInventory({
...e,
stateDir: i
});
t.push(...r.artifacts);
for (const [e, t] of r.identities) n.set(e, t);
}
return {
artifacts: t,
identities: n
};
}
function collectCaptureRootInventory(e) {
const t = resolveUpdateCaptureRoot(e.stateDir);
const n = [];
const r = /* @__PURE__ */ new Map();
const i = fs.lstatSync(t, { throwIfNoEntry: false });
if (!i) return {
artifacts: n,
identities: r
};
if (!i.isDirectory() || hasSymbolicLinkInDirectoryPath(t)) {
n.push({
kind: "update-capture",
path: t,
runs: [],
bytes: 0,
outcome: "blocked",
reason: "capture-directory-alias"
});
return {
artifacts: n,
identities: r
};
}
const a = e.readHistory === false ? void 0 : readCompletedUpdateHistory(e.env);
const o = e.scan ? [...e.scan.directory(t)] : fs.readdirSync(t, { withFileTypes: true });
const s = !e.scan || o.filter((e) => e.name.startsWith("doctor-")).every((n) => e.scan.metadata(path.join(t, n.name, "manifest.json")));
const c = e.readHistory === false || !s || e.scan?.incomplete ? /* @__PURE__ */ new Map() : collectStandaloneDoctorCaptures(e).captures;
const l = o.filter((e) => e.name !== UPDATE_CAPTURE_PRIVACY_MARKER).toSorted((e, t) => e.name.localeCompare(t.name));
for (const i of l) {
if (e.scan && !e.scan.available()) break;
const o = path.join(t, i.name);
const s = {
kind: "update-capture",
captureSource: i.name.startsWith("doctor-") ? "doctor" : "update",
path: o,
runs: [],
bytes: 0,
outcome: "protected",
reason: "unmanifested-update-capture"
};
n.push(s);
if (!i.isDirectory()) {
s.bytes = i.isFile() ? fs.lstatSync(o).size : 0;
continue;
}
s.bytes = e.scan ? e.scan.logicalBytes(o) : logicalBytes(o);
if (!/^[a-zA-Z0-9_-]{1,128}$/u.test(i.name) || !fs.lstatSync(path.join(o, ".openclaw-private-update-capture"), { throwIfNoEntry: false })?.isFile()) continue;
if (!a) {
s.reason = "unreadable-update-history";
continue;
}
try {
const t = a.runs.find((e) => e.runId === i.name) ?? getUpdateRun(i.name, { env: e.env });
const n = c.get(o);
if (!t && !n) {
if (i.name.startsWith("doctor-") || fs.existsSync(path.join(o, "manifest.json.partial"))) continue;
if (e.scan && !e.scan.metadata(path.join(o, "manifest.json"))) continue;
const t = readRootStructuredFileSync({
rootDir: o,
relativePath: "manifest.json",
boundaryLabel: "update capture",
rejectHardlinks: true,
maxBytes: 134217728,
parse: parseUpdateRecoveryBackupManifest
});
if (t.ok && t.value.runId === i.name) {
s.reason = "orphan-update-capture";
s.detail = `Sealed update capture created ${t.value.createdAt}; no matching update run. Retire only with an explicit --include-unmanifested path.`;
}
continue;
}
s.runs = [i.name];
Object.assign(s, n ? {
outcome: n.eligible ? "candidate" : "protected",
reason: n.reason
} : classifyCapture(o, t, a.latestCompletedStartedAt, e.env));
if (s.outcome === "candidate") {
s.detail = n ? "standalone Doctor capture" : `update ${t.status}`;
s.consequence = "Permanently deletes this original-state capture and any recovery generations inside it.";
const e = fs.lstatSync(o, { bigint: true });
r.set(o, {
dev: e.dev,
ino: e.ino
});
}
} catch (e) {
Object.assign(s, {
outcome: "protected",
reason: "unreadable-update-history",
detail: String(e)
});
}
}
return {
artifacts: n,
identities: r
};
}
/** Caller holds the cleanup maintenance lock and passes identities from the confirmed selection. */
async function retireUpdateCaptures(e) {
for (const [t, n] of e.selected.entries()) try {
e.onProgress?.(n, t);
e.assertCurrent();
const r = e.identities.get(n.path);
const i = fs.lstatSync(n.path, { bigint: true });
if (!r || hasSymbolicLinkInDirectoryPath(n.path) || !i.isDirectory() || i.dev !== r.dev || i.ino !== r.ino) throw new Error("update capture changed after selection");
for (const t of fs.readdirSync(n.path)) if (t !== ".openclaw-private-update-capture") {
e.assertCurrent();
await fs.promises.rm(path.join(n.path, t), { recursive: true });
}
e.assertCurrent();
await fs.promises.rm(n.path, { recursive: true });
n.outcome = "removed";
n.removedBytes = n.bytes;
n.reason = "update-capture-retired";
} catch (e) {
n.outcome = "failed";
n.reason = "update-capture-retirement-failed";
n.detail = String(e);
}
}
//#endregion
//#region src/commands/doctor-session-sqlite-recovery-inventory.ts
/** Read-only recovery inventory and dependency classification; never deletion authority. */
function resolveRecoveryArtifact(e) {
return e.find((e) => e.move.artifact?.disposal.state === "pending-disposal")?.move.artifact ?? e[0]?.move.artifact;
}
function collectRecoveryInventory(e) {
const entries = (t) => e.scan?.directory(t) ?? fs.readdirSync(t, { withFileTypes: true });
const t = canonicalMigrationFilePath(path.join(resolveStateDir(e.env), "anchor"));
const n = path.dirname(t);
const r = /* @__PURE__ */ new Set();
const i = /* @__PURE__ */ new Set();
const a = new Set(listAgentIds(e.cfg));
const o = path.join(n, "agents");
if (statMigrationPath(o)?.isDirectory() && !hasSymbolicLinkInDirectoryPath(o)) {
for (const e of entries(o)) if (e.isDirectory()) {
a.add(e.name);
r.add(path.join(o, e.name, "sessions", "sessions.json"));
}
}
for (const t of a) r.add(canonicalMigrationFilePath(resolveSessionStorePathCore(e.cfg.session?.store, {
agentId: t,
env: e.env
})));
r.add(path.join(n, "sessions", "sessions.json"));
for (const e of r) if (isPathInside(n, e)) i.add(path.join(path.dirname(path.dirname(e)), "session-sqlite-import-archive"));
const s = /* @__PURE__ */ new Map();
let c = [];
const l = [];
const u = /* @__PURE__ */ new Set();
const protectUnmanifested = (e, t, n) => {
l.push({
path: e,
runs: [],
bytes: t,
outcome: "protected",
reason: n
});
};
let d = 0;
const f = resolveSessionSqliteMigrationRunsDir(e.env);
if (hasSymbolicLinkInDirectoryPath(f)) l.push({
path: f,
runs: [],
bytes: 0,
outcome: "blocked",
reason: "manifest-directory-alias"
});
else {
c = e.scan ? [...e.scan.directory(f)].filter((e) => e.name.endsWith(".json") && !e.name.endsWith(".failure.json")).map((e) => path.join(f, e.name)) : listSessionSqliteMigrationManifestPaths(e.env);
for (const t of c) {
if (e.scan && !e.scan.metadata(t)) continue;
const i = statMigrationPath(t);
const a = i?.isFile() && i.nlink === 1 ? readSessionSqliteMigrationManifest(t) : void 0;
if (!a) {
l.push({
path: t,
runs: [],
bytes: i?.size ?? 0,
outcome: "blocked",
reason: "unreadable-manifest"
});
continue;
}
const o = {
manifest: a,
manifestPath: t
};
const c = collectRecordedConsumedArchives(a);
for (const t of a.targets) {
if (e.scan && !e.scan.available()) break;
const i = resolveUnsuffixedSqliteTargetFromSessionStorePath(t.storePath);
const a = isPathInside(n, t.sqlitePath) && isPathInside(n, t.storePath) && !hasSymbolicLinkInDirectoryPath(path.dirname(t.storePath)) && !hasSymbolicLinkInDirectoryPath(path.dirname(t.sqlitePath)) && (t.databaseIdentity || r.has(t.storePath) && (i.agentId ? t.sqlitePath === i.path && t.agentId === i.agentId : path.dirname(t.sqlitePath) === path.dirname(i.path)));
for (const e of uniqueRestoreMoves(t)) {
const n = s.get(e.archivePath) ?? [];
n.push({
run: o,
target: t,
move: e,
trusted: Boolean(a),
consumedByRestore: c.has(e.archivePath)
});
s.set(e.archivePath, n);
}
}
}
}
if (e.readHistory !== false && [...s.values()].some((e) => e.some((e) => e.target.databaseIdentity))) d = readCompletedUpdateHistory(e.env)?.latestCompletedStartedAt ?? 0;
for (const [e, t] of s) {
const n = resolveRecoveryArtifact(t);
const r = t.every((e) => e.trusted) ? statMigrationPath(e, { bigint: true }) : void 0;
const i = t.every((e) => e.trusted) && n?.disposal.state === "pending-disposal" ? statMigrationPath(n.disposal.claimPath, { bigint: true }) : void 0;
const a = r ?? i;
if (t.every((e) => e.trusted) && !a && n?.disposal.state !== "pending-disposal") u.add(e);
const o = {
path: e,
runs: [...new Set(t.map((e) => e.run.manifest.runId))],
bytes: a?.isFile() ? Number(a.size) : 0,
outcome: "candidate",
reason: "producer-verified-original",
consequence: "Permanently loses rollback to this original, including pre-repair branches and metadata."
};
const classify = (e, t) => {
o.outcome = e;
o.reason = t;
};
if (t.some((e) => !e.trusted)) classify("protected", "unsupported-target-ownership");
else if (t.every((e) => e.move.artifact?.disposal.state === "disposed")) classify(r ? "protected" : "disposed", r ? "recreated-after-disposal" : "intentionally-disposed");
else if (t.some((e) => e.consumedByRestore)) classify("protected", "archive-consumed-by-restore");
else if (hasSymbolicLinkInDirectoryPath(path.dirname(e)) || r && (!r.isFile() || r.nlink !== 1n && !isPendingMigrationArtifactClaim(e, n))) classify("blocked", "artifact-alias-or-nonregular");
else if (t.some(({ run: e, target: t }) => !e.manifest.completedAt || t.validationBeforeArchive !== "passed" || t.issues.some((e) => !isSessionSqliteMigrationWarning(e)))) classify("protected", "incomplete-recovery-operation");
else if (t.some(({ move: e }) => e.artifact?.classification === "protected")) classify("protected", t.find((e) => e.move.artifact?.classification === "protected").move.artifact.reason);
else if (t.some(({ target: e, run: t }) => e.databaseIdentity && !(d > Date.parse(t.manifest.completedAt)))) classify("protected", "awaiting-later-completed-update");
else if (t.some(({ move: e }) => !e.artifact)) classify("verification-required", "historical-manifest-without-import-proof");
else if (a && n && [
"ino",
"mtimeNs",
"size"
].some((e) => String(a[e]) !== String(n.identity[e]))) classify("blocked", "artifact-metadata-changed");
else if (t.some(({ move: e }) => !sameMigrationArtifact(e.artifact.identity, n.identity))) classify("blocked", "conflicting-artifact-identities");
else if (t.some(({ move: e }) => {
const t = e.artifact?.disposal;
return t?.state === "pending-disposal" && n?.disposal.state === "pending-disposal" && t.claimPath !== n.disposal.claimPath;
})) classify("blocked", "conflicting-disposal-claims");
else if (!r && !t.every(({ move: e }) => e.artifact?.disposal.state === "pending-disposal" || e.artifact?.disposal.state === "disposed")) classify("blocked", "unexpectedly-missing-artifact");
else if (t.some(({ move: e }) => e.artifact?.disposal.state === "pending-disposal")) o.reason = "resume-pending-disposal";
l.push(o);
}
const p = /* @__PURE__ */ new Set([
path.join(n, "state"),
...[...r].flatMap((e) => [path.dirname(e), path.dirname(resolveUnsuffixedSqliteTargetFromSessionStorePath(e).path)]),
...[...s.values()].flatMap((e) => e.filter((e) => e.trusted).map((e) => path.dirname(e.target.sqlitePath)))
]);
for (const e of p) {
if (!isPathInside(n, e) || !statMigrationPath(e)?.isDirectory() || hasSymbolicLinkInDirectoryPath(e)) continue;
for (const t of entries(e)) {
if (!isMigrationArchiveArtifactName(t.name) && !t.name.includes(".pre-doctor-") && !/^.+\.pre-startup-migration-.+\.bak$/.test(t.name)) continue;
const n = path.join(e, t.name);
if (s.has(n)) continue;
protectUnmanifested(n, t.isFile() ? fs.lstatSync(n).size : 0, "unmanifested-recovery-original");
}
}
const m = new Set(l.map((e) => e.path));
const h = /* @__PURE__ */ new Set();
for (const e of s.values()) for (const { move: t } of e) if (t.artifact?.disposal.state === "pending-disposal") h.add(t.artifact.disposal.claimPath);
for (const e of i) {
if (!statMigrationPath(e)?.isDirectory() || hasSymbolicLinkInDirectoryPath(e)) continue;
for (const t of entries(e)) {
const n = path.join(e, t.name);
if (m.has(n) || h.has(n)) continue;
m.add(n);
protectUnmanifested(n, t.isFile() ? fs.lstatSync(n).size : 0, "unmanifested-artifact");
}
}
if (l.some((e) => e.reason === "unreadable-manifest" || e.reason === "manifest-directory-alias")) {
for (const e of l) if (e.outcome === "candidate" || e.outcome === "verification-required") {
e.outcome = "blocked";
e.reason = "unreadable-recovery-dependencies";
}
}
if (e.scan?.incomplete) {
for (const e of l) if (e.outcome === "candidate" || e.outcome === "verification-required") {
e.outcome = "protected";
e.reason = "incomplete-recovery-inventory";
}
}
protectRecoveryDependencies(l, s);
return {
artifacts: l,
references: s,
manifestPaths: c,
report: summarizeRecoveryCleanup(n, l.filter((e) => !u.has(e.path)), "preview", u.size)
};
}
function protectRecoveryDependencies(e, t, n) {
const active = (e) => (!e.consumedByRestore || statMigrationPath(e.move.archivePath) !== void 0) && e.move.artifact?.disposal.state !== "disposed";
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
for (const [e, n] of t) for (const t of n.filter(active)) {
const n = r.get(t.move.sourcePath) ?? [];
n.push(e);
r.set(t.move.sourcePath, n);
}
const connect = (e, t) => {
const n = i.get(e) ?? /* @__PURE__ */ new Set();
n.add(t);
i.set(e, n);
};
const a = /* @__PURE__ */ new Map();
for (const [e, i] of t) for (const t of i.filter(active)) {
if (t.target.databaseIdentity) {
const n = a.get(t.run.manifestPath);
if (n) {
connect(e, n);
connect(n, e);
} else a.set(t.run.manifestPath, e);
}
const i = (t.move.artifact ?? n?.get(t))?.dependencies ?? (t.move.kind === "legacy-store" ? uniqueRestoreMoves(t.target).filter((e) => e.kind === "transcript").map((e) => e.sourcePath) : []);
for (const n of i) for (const i of r.get(n) ?? []) {
connect(e, i);
if (t.move.kind === "legacy-store") connect(i, e);
}
}
const o = new Map(e.map((e) => [e.path, e]));
const s = e.filter((e) => e.outcome !== "candidate" && e.outcome !== "verification-required" && e.outcome !== "disposed" && e.outcome !== "removed");
for (const e of s) for (const t of i.get(e.path) ?? []) {
const e = o.get(t);
if (e?.outcome !== "candidate" && e?.outcome !== "verification-required") continue;
e.outcome = "protected";
e.reason = "retained-recovery-dependency";
s.push(e);
}
}
function summarizeRecoveryCleanup(e, t, n, r = 0) {
const i = {
candidateBytes: 0,
verificationRequiredBytes: 0,
protectedBytes: 0,
blockedBytes: 0,
removedBytes: 0,
removedFiles: 0
};
const a = {
candidate: "candidateBytes",
"verification-required": "verificationRequiredBytes",
protected: "protectedBytes",
blocked: "blockedBytes",
failed: "blockedBytes"
};
for (const e of t) {
const t = a[e.outcome];
if (t) i[t] += e.bytes;
if (e.removedBytes !== void 0) {
i.removedBytes += e.removedBytes;
i.removedFiles += 1;
}
}
return {
stateDir: e,
artifacts: t,
totals: i,
status: n,
missingOriginals: r
};
}
/** Update cleanup also reviews original-state captures; Doctor's session repair does not. */
function collectUpdateCleanupInventory(e) {
return withSynchronousArtifactPreservingStateSnapshot(() => {
const t = collectRecoveryInventory(e);
const n = collectUpdateCaptureInventory({
stateDir: t.report.stateDir,
env: e.env,
scan: e.scan,
readHistory: e.readHistory
});
return {
...t,
captureIdentities: n.identities,
report: summarizeRecoveryCleanup(t.report.stateDir, [...t.report.artifacts, ...n.artifacts], "preview", t.report.missingOriginals)
};
}, { current: { env: e.env } });
}
function inspectSessionSqliteRecovery(e) {
return collectUpdateCleanupInventory(e).report;
}
//#endregion
export { resolveRecoveryArtifact as a, protectRecoveryDependencies as i, collectUpdateCleanupInventory as n, summarizeRecoveryCleanup as o, inspectSessionSqliteRecovery as r, retireUpdateCaptures as s, collectRecoveryInventory as t };