openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
253 lines (252 loc) • 10.9 kB
JavaScript
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { w as root } from "./fs-safe-BbWvmdVn.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs";
import { o as sameFileMutationFingerprint } from "./file-descriptor-DQ-v5bLt.mjs";
import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { d as resolvePrivateSqliteSnapshotStagingRoot, n as createSqliteSnapshotStagingDirectory } from "./sqlite-snapshot-staging-DVmPTRsc.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import "./crypto-digest-B2m8wIBj.mjs";
import { c as resolveSqliteInspectionBudget } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { n as resolveDatabaseFamilyEngines } from "./registry-Dd7FIY0t.mjs";
import { t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs";
import { g as withOpenClawStateDatabaseReadSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { d as preparePluginDoctorMigrationBackupResources } from "./doctor-contract-registry-CFzLZXmq.mjs";
import { r as resolveUpdateCaptureRoot } from "./update-capture-paths-B2WcdTCG.mjs";
import { i as withStateInspectionCleanup } from "./update-candidate-state.sizes-BDo08pQy.mjs";
import { r as resolveBackupConfigCapture } from "./backup-config-capture-C4dP9zCI.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 canonicalEntryPath } from "./update-recovery-path-jlkZQw9c.mjs";
import { a as withVerifiedUpdateRecoveryBackup } from "./update-recovery-backup-reader-CzkKDmJ9.mjs";
import { n as createUpdateDatabaseBackup } from "./update-database-backup-7OO4TMvT.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
//#region src/infra/doctor-capture-reuse.ts
const MAX_REUSE_ENTRIES = 4096;
/** Equality is content and inventory, not the age, size, or mtime of a capture. */
async function findReusableDoctorCapture(e) {
let t = performance.now() + resolveSqliteInspectionBudget("Doctor capture comparison", e.stateDir, 0).timeoutMs;
const check = () => {
e.signal?.throwIfAborted();
e.assertCurrent();
if (performance.now() > t) throw new Error("Standalone Doctor capture comparison exceeded its reuse budget.");
};
try {
return await withArtifactPreservingStateReads(async () => {
check();
if (!(await fs.lstat(resolveUpdateCaptureRoot(e.stateDir)).catch(ignoreMissingPath))?.isDirectory()) return;
const { captures: n, warnings: r } = await withOpenClawStateDatabaseReadSnapshot(async () => collectStandaloneDoctorCaptures(e), {
env: e.env,
signal: e.signal
});
if (r.length) return;
const [i] = [...n].toSorted(([, e], [, t]) => t.createdAt - e.createdAt);
if (!i || i[1].reason === "pending-update-recovery") return;
const [a] = i;
const o = await (await root(a, {
symlinks: "reject",
hardlinks: "reject"
})).readText("manifest.json", { maxBytes: 8388608 });
const s = parseUpdateRecoveryBackupManifest(o);
if (s.runId !== path.basename(a) || s.generation?.kind !== "baseline" || s.installRoot !== path.resolve(e.installRoot) || s.stateDir !== e.stateDir || s.configPath !== canonicalEntryPath(resolveConfigPath(e.env)) || s.excludedRoots.length > 0 || (s.warnings?.length ?? 0) > 0) return;
if (s.entries.length > MAX_REUSE_ENTRIES) return;
const c = s.entries.reduce((e, t) => e + (t.kind === "file" ? t.size : 0), 0);
t = performance.now() + resolveSqliteInspectionBudget("Doctor capture comparison", a, c).timeoutMs;
for (const e of s.entries) {
check();
if (e.kind === "file") {
const t = await fs.lstat(path.join(a, e.archivePath));
if (!t.isFile() || t.size !== e.size) return;
}
}
const l = {
directory: a,
manifestPath: path.join(a, "manifest.json"),
manifestSha256: sha256Hex(o)
};
return await withVerifiedUpdateRecoveryBackup(l, async (t) => {
check();
if (t.runId !== path.basename(a) || t.generation?.kind !== "baseline" || t.installRoot !== path.resolve(e.installRoot) || t.stateDir !== e.stateDir || t.configPath !== canonicalEntryPath(resolveConfigPath(e.env)) || t.excludedRoots.length || t.warnings?.length) return;
for (const e of [
"outcome.json",
"candidate",
"prepared"
]) if (await fs.lstat(path.join(a, e)).catch(ignoreMissingPath)) return;
await compareCurrentSources(t, e, check);
check();
return l;
});
});
} catch (t) {
e.assertCurrent();
if (hasCommandProcessCleanupError(t)) throw t;
e.signal?.throwIfAborted();
return;
}
}
async function compareCurrentSources(e, t, n) {
const changed = () => /* @__PURE__ */ new Error("Standalone Doctor original sources are not proven unchanged.");
const r = await createConfigIO({
env: t.env,
configPath: resolveConfigPath(t.env),
observe: false,
pluginValidation: "core-only"
}).readConfigFileSnapshotForWrite();
n();
if (Object.values(resolveDatabaseFamilyEngines(r.snapshot.sourceConfig)).includes("postgres")) throw changed();
const i = await resolveBackupConfigCapture(r, {
env: t.env,
pluginValidation: "core-only"
});
const a = /* @__PURE__ */ new Set([e.configPath]);
const o = /* @__PURE__ */ new Map([[e.configPath, "file"]]);
const declare = (e, t) => {
const n = canonicalEntryPath(e);
if (o.has(n) && o.get(n) !== t) throw changed();
o.set(n, t);
return n;
};
for (const e of i.files) {
a.add(declare(e.sourcePath, "file"));
a.add(declare(e.canonicalPath, "file"));
}
const s = [];
const c = await withOpenClawStateDatabaseReadSnapshot(() => preparePluginDoctorMigrationBackupResources({
config: r.snapshot.sourceConfig,
stateDir: t.stateDir,
env: t.env,
warnings: s,
requireLocalResources: true
}), {
env: t.env,
signal: t.signal
});
c.assertCurrent();
n();
if (s.length || c.deferredPluginIds.size) throw changed();
for (const e of c.resources) declare(e.path, e.kind);
if (!isDeepStrictEqual([...o.keys()].toSorted(), e.protectedPaths)) throw changed();
const l = /* @__PURE__ */ new Map();
for (const t of e.entries) if (t.kind === "file" && t.sqlite) l.set(t.sourcePath, await fs.lstat(t.sourcePath, { bigint: true }).catch(ignoreMissingPath));
const u = await createSqliteSnapshotStagingDirectory(resolvePrivateSqliteSnapshotStagingRoot(t.env), false, t.signal);
const d = await withStateInspectionCleanup(u, () => createUpdateDatabaseBackup({
backupRoot: path.join(u, "comparison"),
stateDir: t.stateDir,
config: r.snapshot.sourceConfig,
env: t.env,
signal: t.signal,
acquisition: { mode: "maintenance-owner" },
purpose: "original-state",
preserveSourceArtifacts: true,
integrityCheck: "quick",
additionalPaths: [...o].filter(([, e]) => e === "sqlite").map(([e]) => e),
additionalFiles: e.entries.flatMap((e) => e.kind === "file" && !a.has(e.sourcePath) ? [e.sourcePath] : []),
retryAdvice: false
}));
n();
const f = new Set(o.keys());
const p = /* @__PURE__ */ new Set([
...d.sourcePaths.map(canonicalEntryPath),
...d.databases.map((e) => e.path),
...d.missingPaths
]);
if (!isDeepStrictEqual(d.databaseOwners, e.databases)) throw changed();
const m = new Map(e.entries.map((e) => [e.sourcePath, e]));
const h = /* @__PURE__ */ new Set([...p, ...e.entries.filter((e) => (e.kind === "file" || e.kind === "missing") && e.sqlite).map((e) => e.sourcePath)]);
const g = new Set([...h].flatMap((e) => SQLITE_SIDECAR_SUFFIXES.map((t) => e + t)));
const matchesSqliteImage = (e, t, n) => {
const r = d.databases.find((t) => t.path === e);
return r?.sizeBytes === t && r.sha256 === n;
};
const _ = /* @__PURE__ */ new Map();
const inspect = async (e, t) => {
try {
var r = _usingCtx();
n();
const i = t ?? o.get(e);
if (_.has(e)) return;
const s = m.get(e);
if (!s || _.size >= MAX_REUSE_ENTRIES) throw changed();
const c = await fs.lstat(e, { bigint: true }).catch(ignoreMissingPath);
_.set(e, c);
if (!c) {
if (s.kind !== "missing" || s.sqlite !== (i === "sqlite") || s.directory !== (i === "directory")) throw changed();
return;
}
if (c.isSymbolicLink()) {
if (s.kind !== "symlink" || s.target !== await fs.readlink(e)) throw changed();
if (i) {
const t = await fs.realpath(e).catch((t) => {
ignoreMissingPath(t);
return canonicalEntryPath(path.resolve(path.dirname(e), s.target));
});
f.add(t);
if (a.has(e)) {
a.add(t);
if (s.contentPath !== t) throw changed();
}
await inspect(t, i);
}
return;
}
if (c.isDirectory()) {
if (s.kind !== "directory" || i && i !== "directory" || s.mode !== Number(c.mode & 511n)) throw changed();
const t = await fs.opendir(e);
for await (const n of t) {
const t = path.join(e, n.name);
if (!g.has(t)) await inspect(t);
}
return;
}
if (!c.isFile() || s.kind !== "file" || i === "directory" || i === "sqlite" && !s.sqlite || s.mode !== Number(c.mode & 511n) || s.size !== Number(c.size)) throw changed();
if (s.sqlite) {
f.add(e);
const t = l.get(e);
if (!t || !sameFileMutationFingerprint(t, c) || !matchesSqliteImage(e, s.size, s.sha256)) throw changed();
return;
}
const u = await (await root(path.dirname(e))).open(path.basename(e), {
symlinks: "reject",
hardlinks: "allow"
});
const d = r.a(u.handle);
if (!sameFileMutationFingerprint(c, await d.stat({ bigint: true }))) throw changed();
const p = await sha256File(d, { maxBytes: s.size });
if (p.bytes !== s.size || p.digest !== s.sha256 || !sameFileMutationFingerprint(c, await d.stat({ bigint: true }))) throw changed();
} catch (e) {
r.e = e;
} finally {
await r.d();
}
};
for (const [e, t] of o) {
if (g.has(e)) {
f.delete(e);
continue;
}
await inspect(e, t);
}
for (const e of p) {
f.add(e);
await inspect(e, "sqlite");
}
if (_.size !== m.size || !isDeepStrictEqual([...f].toSorted(), e.roots) || !isDeepStrictEqual([...a].toSorted(), e.configPaths)) throw changed();
await i.revalidate();
c.assertCurrent();
for (const e of h) for (const t of ["-wal", "-journal"]) {
const n = await fs.lstat(e + t).catch(ignoreMissingPath);
if (n && (!n.isFile() || n.size !== 0)) throw changed();
}
for (const [e, t] of _) {
n();
const r = await fs.lstat(e, { bigint: true }).catch(ignoreMissingPath);
if (t ? !r || !sameFileMutationFingerprint(t, r) || t.mode !== r.mode : r) throw changed();
}
}
//#endregion
export { findReusableDoctorCapture };