openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
223 lines (222 loc) • 9.37 kB
JavaScript
import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.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 createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs";
import { n as readUpdateRunDriver } from "./update-run-driver-BoURWp0g.mjs";
import { i as UPDATE_RUN_ID_ENV } from "./update-control-plane-sentinel-ThuSZh3z.mjs";
import { t as resolveDoctorUpdateAdmission } from "./doctor-maintenance-admission-CqCSvhaQ.mjs";
import { r as resolveUpdateCaptureRoot } from "./update-capture-paths-B2WcdTCG.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/commands/doctor-original-capture.ts
const IMAGE_ACTIVATION_MARKER_ENV = "OPENCLAW_IMAGE_ACTIVATION_CAPTURE_MARKER";
const STANDALONE_CAPTURE_RUN_ID = /^doctor-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
const ORIGINAL_CAPTURE_TIMEOUT_MS = 12e5;
/** A marker counts only while the sealed capture it names is still retained. */
async function readImageActivationCapture(e, t) {
try {
const n = await fs.lstat(e);
if (!n.isFile() || process.getuid !== void 0 && n.uid !== process.getuid()) return;
const r = (await fs.readFile(e, "utf8")).trim();
if (!STANDALONE_CAPTURE_RUN_ID.test(r)) return;
return (await fs.lstat(path.join(t, r, "manifest.json"))).isFile() ? r : void 0;
} catch {
return;
}
}
/** Preserve evidence before repair; neither a capture nor its lineage authorizes restoration. */
async function preserveDoctorOriginalState(e) {
const t = createSubsystemLogger("doctor");
const n = [];
const r = [];
const i = "https://docs.openclaw.ai/cli/doctor/state-migrations#plugin-migration-recovery-coverage";
const a = e.writeAuthority?.originalRecoveryCapture;
const o = a?.runId ?? e.env["OPENCLAW_UPDATE_RUN_ID"]?.trim();
const s = a !== void 0 || e.env.OPENCLAW_UPDATE_IN_PROGRESS === "1";
const assertCallerCurrent = () => {
e.signal.throwIfAborted();
e.assertCurrent();
e.writeAuthority?.assertCurrent();
};
assertCallerCurrent();
if (s && !o) {
t.debug("Original update recovery copy is unavailable. Doctor will continue without creating another copy or replacing retained originals.");
return {
findings: n,
warnings: r
};
}
let c;
const assertCurrent = () => {
assertCallerCurrent();
c?.assertCurrent();
};
try {
c = s && o ? resolveDoctorUpdateAdmission(e.env, a?.runId) : void 0;
if (c && o) {
const { readUpdateRecoveryBaselineIdentity: i } = await import("./update-recovery-backup-reader-CvFGu-71.mjs");
assertCurrent();
const s = await i({
runId: o,
env: e.env,
...a ? {
ref: a.ref,
installRoot: a.installRoot
} : {},
readContinuation: c.readContinuation,
assertCurrent
});
assertCurrent();
t.debug(s ? `Original update recovery copy retained. For manual recovery: ${s.ref.manifestPath}.` : "Original update recovery copy is unavailable. Doctor will continue without creating another copy or replacing retained originals.");
return {
findings: n,
warnings: r
};
}
const { captureUpdateRecoveryBaseline: l } = await import("./update-recovery-baseline-capture-C2x90X5Y.mjs");
const { retireExpiredStandaloneDoctorCaptures: u } = await import("./doctor-capture-retention-mlPMgkuM.mjs");
const d = resolvePathViaExistingAncestorSync(resolveStateDir(e.env));
const retireExpiredCaptures = async (a) => {
try {
const o = await u({
stateDir: d,
env: e.env,
keepRunId: a,
assertCurrent
});
for (const e of o.retired) t.debug(`Retired superseded or expired standalone Doctor capture: ${e}. Take a verified backup before an upgrade when you need a long-term recovery copy.`);
for (const e of o.warnings) {
r.push(e);
n.push({
checkId: "core/doctor/recovery-retirement",
severity: "warning",
category: "historical",
message: e,
docsUrl: i,
fixHint: "Keep the retained recovery data. Inspect the named directory and its permissions before manual recovery."
});
}
} catch (e) {
t.debug(`Standalone Doctor capture retirement unavailable: ${formatErrorMessage(e)}`);
}
};
const f = e.env[IMAGE_ACTIVATION_MARKER_ENV]?.trim() || void 0;
const p = f ? await readImageActivationCapture(f, resolveUpdateCaptureRoot(d)) : void 0;
if (p) {
assertCurrent();
t.debug(`This container already retained a pre-repair capture (${p}); Doctor skipped a repeated full capture. Repair-specific backups still apply.`);
await retireExpiredCaptures(p);
return {
findings: n,
warnings: r
};
}
const m = e.root;
if (!m) throw new Error("The installation could not be identified for the pre-repair capture.");
const h = readUpdateRunDriver();
if (!h) throw new Error("The Doctor process could not be identified for the pre-repair capture.");
assertCurrent();
const { findReusableDoctorCapture: g } = await import("./doctor-capture-reuse-BrpYcdJn.mjs");
const _ = new AbortController();
const v = performance.now() + ORIGINAL_CAPTURE_TIMEOUT_MS;
const y = /* @__PURE__ */ new Error("Original-state capture timed out after 1200 s");
const b = setTimeout(() => _.abort(y), ORIGINAL_CAPTURE_TIMEOUT_MS);
b.unref();
let x;
let S;
let C;
try {
const assertCaptureCurrent = () => {
if (performance.now() >= v) _.abort(y);
_.signal.throwIfAborted();
assertCurrent();
};
const t = AbortSignal.any([e.signal, _.signal]);
S = e.fullIntegrityCheck ? void 0 : await g({
stateDir: d,
installRoot: m,
env: e.env,
assertCurrent: assertCaptureCurrent,
signal: t
});
assertCaptureCurrent();
C = S ? path.basename(S.directory) : `doctor-${randomUUID()}`;
x = S ? {
ref: S,
warnings: [],
diagnostics: { databaseWarnings: [] }
} : await l({
runId: C,
installRoot: m,
env: e.env,
drivers: [h],
assertCurrent: assertCaptureCurrent,
signal: t,
acquisition: { mode: "maintenance-owner" },
fullIntegrityCheck: e.fullIntegrityCheck
});
assertCaptureCurrent();
} finally {
clearTimeout(b);
}
r.push(...x.warnings.map((e) => e.message));
n.push(...x.warnings.map((e) => ({
checkId: "core/doctor/migration-recovery",
severity: "warning",
category: "recommended",
message: e.kind === "undeclared-migration-resources" ? `${e.pluginId} migration recovery coverage is unknown because no backup inventory was declared.` : e.message,
target: e.pluginId,
errorCode: e.kind,
fixHint: "Update the plugin to a version with migration backup support. Until then, keep a separate backup of its configured data before relying on rollback; ask its maintainer to add backup support.",
docsUrl: i
})));
t.debug(S ? `Unchanged original recovery copy verified and retained before repair. For manual recovery: ${x.ref.manifestPath}.` : `Recovery copy saved before repair. No action needed. For manual recovery: ${x.ref.manifestPath}.`);
if (f) try {
await fs.rm(f, { force: true });
await fs.writeFile(f, C, {
flag: "wx",
mode: 384
});
} catch (t) {
e.runtime.log(`Container activation marker unavailable: ${formatErrorMessage(t)}. The next container start takes another full capture. Check write permissions for the container activation marker before restarting.`);
}
await retireExpiredCaptures(C);
r.push(...x.diagnostics.databaseWarnings);
n.push(...x.diagnostics.databaseWarnings.map((e) => ({
checkId: "core/doctor/recovery-database-verification",
severity: "warning",
category: "recommended",
message: e,
docsUrl: "https://docs.openclaw.ai/cli/update/repair-and-recovery#original-state-captures",
fixHint: "Keep the saved recovery copy. Check disk space and stop other OpenClaw processes before creating another verified backup; inspect the named database snapshot before manual restoration."
})));
} catch (e) {
assertCurrent();
if (hasCommandProcessCleanupError(e) || e instanceof DoctorMaintenanceRefusalError && e.refusal.kind === "deferred") throw e;
if (a?.ref) throw new DoctorMaintenanceRefusalError(`Doctor could not verify its admitted original recovery copy: ${formatErrorMessage(e)}. State repair has not started. Keep the original recovery copy, check the named paths and disk space, then inspect openclaw update status --json before retrying Doctor.`, {
kind: "data-at-risk",
reason: "unreadable-state"
}, { cause: e });
const t = `Pre-repair recovery copy was unavailable: ${formatErrorMessage(e)}.`;
const o = "Save a verified backup of your OpenClaw state and configured plugin data before further repairs. Check installation access and disk space, then rerun openclaw doctor --fix; inspect retained evidence before restoring state.";
r.push(`${t} ${o}`);
n.push({
checkId: "core/doctor/recovery-capture",
severity: "warning",
category: "fix-now",
message: t,
fixHint: o,
docsUrl: i
});
}
return {
findings: n,
warnings: r
};
}
//#endregion
export { preserveDoctorOriginalState };