openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
239 lines (238 loc) • 8.98 kB
JavaScript
import { r as resolveOsHomeDir } from "./home-dir-zhqynwRJ.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { b as writeSessionSqliteMigrationManifest, i as canonicalMigrationFilePath, p as readSessionSqliteMigrationManifest, s as filterRestoreManifestTargets } from "./session-sqlite-migration-manifest-DwBodX3i.mjs";
import { n as prepareGithubIssue } from "./github-issue-Bxmnokng.mjs";
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
//#region src/commands/doctor-session-sqlite-failure.ts
/** Sanitized support reports for migration failure recovery. */
function writeSessionSqliteMigrationFailureReports(e, t) {
const n = readSessionSqliteMigrationManifest(e);
const { jsonPath: r, markdownPath: i } = resolveFailureReportPaths(e);
if (n?.failureReports?.githubIssue) return {
jsonPath: r,
markdownPath: i
};
const a = n ? t.trustedTargets ? filterRestoreManifestTargets(n, t.trustedTargets) : n.targets : [];
const o = resolveOsHomeDir();
const s = createFailureReportPayload(e, n, t.reason, a.map((e) => createFailureReportTarget(e, collectFailureReportIssues(e, o, t.recoveryTargets), o)), o);
fs.writeFileSync(r, `${JSON.stringify(s, null, 2)}\n`, { mode: 384 });
fs.writeFileSync(i, renderFailureMarkdown(s), { mode: 384 });
if (n) {
n.failureReports = {
jsonPath: r,
markdownPath: i
};
writeSessionSqliteMigrationManifest({
manifest: n,
manifestPath: e
});
}
return {
jsonPath: r,
markdownPath: i
};
}
function collectFailureReportIssues(e, t, n = []) {
const r = n.find((t) => t.agentId === e.agentId && canonicalMigrationFilePath(t.storePath) === canonicalMigrationFilePath(e.storePath) && canonicalMigrationFilePath(t.sqlitePath) === canonicalMigrationFilePath(e.sqlitePath));
const i = /* @__PURE__ */ new Map();
for (const t of [...e.issues, ...r?.issues ?? []]) i.set(JSON.stringify([
t.code,
t.message,
t.sessionKey
]), t);
const a = failureReportPathReplacements(e, t);
const sanitize = (e) => ({
code: e.code,
message: sanitizeFailureIssueMessage(e, a, t),
sessionKey: e.sessionKey ? redactSessionKey(e.sessionKey) : void 0
});
return {
issues: [...i.values()].map(sanitize),
recoveryIssues: r?.issues.map(sanitize)
};
}
function createSessionSqliteMigrationFailureIssue(e, t) {
const n = readSessionSqliteMigrationManifest(e);
if (!n) return;
const r = (n.failureReports?.githubIssue)?.title ?? `Session SQLite migration recovery report (${n.runId})`;
const i = n.failureReports ? resolveFailureReportPaths(e).markdownPath : void 0;
const a = t ? filterRestoreManifestTargets(n, t) : n.targets;
const o = i ? readFailureMarkdown(i) : void 0;
if (i && !o) return;
const s = resolveOsHomeDir();
const c = [
"OpenClaw doctor generated this sanitized report from a local session SQLite migration recovery.",
"",
o ?? renderFailureMarkdown(createFailureReportPayload(e, n, "session SQLite migration failed", a.map((e) => {
const t = failureReportPathReplacements(e, s);
return createFailureReportTarget(e, { issues: e.issues.map((e) => ({
code: e.code,
message: sanitizeFailureIssueMessage(e, t, s)
})) }, s);
}), s))
].join("\n");
return {
body: truncateUtf16Safe(c, 2e4),
...i ? { bodyPath: i } : {},
title: r
};
}
/** Claims one exact support payload before any request or browser handoff can publish it. */
function claimSessionSqliteMigrationGithubIssue(e, t, n) {
n.assertCurrent();
const r = readSessionSqliteMigrationManifest(e);
if (!r?.failureReports) return;
if (r.failureReports.githubIssue) return {
issue: r.failureReports.githubIssue,
status: "existing"
};
const i = createSessionSqliteMigrationFailureIssue(e);
if (!i || prepareGithubIssue(i).marker !== t.marker) return;
const a = {
marker: t.marker,
status: "attempted",
title: t.title
};
r.manifestVersion = 4;
r.failureReports.githubIssue = a;
writeSessionSqliteMigrationManifest({
manifest: r,
manifestPath: e
});
return {
issue: a,
status: "claimed"
};
}
/** Releases a claim only after the caller proves no public request or browser handoff occurred. */
function clearSessionSqliteMigrationGithubIssueClaim(e, t, n) {
n.assertCurrent();
const r = readSessionSqliteMigrationManifest(e);
const i = r?.failureReports;
const a = i?.githubIssue;
if (!r || !i || !a || a.marker !== t || a.status !== "attempted") return false;
delete i.githubIssue;
writeSessionSqliteMigrationManifest({
manifest: r,
manifestPath: e
});
return true;
}
function readFailureMarkdown(e) {
try {
return fs.readFileSync(e, "utf8");
} catch {
return;
}
}
function resolveFailureReportPaths(e) {
return {
jsonPath: e.replace(/\.json$/u, ".failure.json"),
markdownPath: e.replace(/\.json$/u, ".failure.md")
};
}
function createFailureReportTarget(e, t, n) {
return {
agentId: sanitizeFailureReportText(e.agentId),
completedMoves: e.completedMoves.length,
...t,
plannedMoves: e.plannedMoves.length,
sqlitePath: sanitizeFailureReportText(shortenFailureReportPath(e.sqlitePath, n)),
storePath: sanitizeFailureReportText(shortenFailureReportPath(e.storePath, n)),
validationBeforeArchive: e.validationBeforeArchive
};
}
function createFailureReportPayload(e, t, n, r, i) {
return {
failedAt: t?.failedAt,
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
manifestPath: sanitizeFailureReportText(shortenFailureReportPath(e, i)),
reason: n,
recoveryCommand: "openclaw doctor --session-sqlite recover --github-issue",
restoreStatus: t?.restore?.status ?? "not_attempted",
runId: t?.runId ?? path.basename(e, ".json"),
targets: r,
version: VERSION
};
}
function renderFailureMarkdown(e) {
const t = [
"# Session SQLite Migration Failure",
"",
`- Run: ${e.runId}`,
`- Failed: ${e.failedAt ?? "not recorded"}`,
`- Generated: ${e.generatedAt}`,
`- OpenClaw version: ${e.version}`,
`- Reason: ${sanitizeFailureReportText(e.reason)}`,
`- Restore status: ${e.restoreStatus}`,
`- Recovery command: \`${e.recoveryCommand}\``,
"",
"## Targets"
];
for (const n of e.targets) {
t.push("", `### ${n.agentId}`, "", `- Store: ${n.storePath}`, `- SQLite: ${n.sqlitePath}`, `- Planned moves: ${n.plannedMoves}`, `- Completed moves: ${n.completedMoves}`, `- Validation before archive: ${n.validationBeforeArchive}`);
const e = [["Recorded migration and recovery evidence", n.issues]];
if (n.recoveryIssues) e.unshift(["Current recovery issues", n.recoveryIssues]);
else t.push("- Current recovery: not assessed");
for (const [n, r] of e) {
t.push(`- ${n}: ${r.length}`);
for (const e of r) t.push(` - [${e.code}] ${e.sessionKey ? `${e.sessionKey}: ` : ""}${e.message}`);
}
}
t.push("");
return `${t.join("\n")}\n`;
}
function sanitizeFailureReportText(e) {
const t = e.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "[redacted-email]").replace(/(api[_-]?key|token|secret|password)[=-][A-Za-z0-9._-]+/gi, "$1-[redacted]").replace(/(api[_-]?key|token|secret|password)=\S+/gi, "$1=[redacted]");
return truncateUtf16Safe(t, 500);
}
function shortenFailureReportPath(e, t) {
if (t && e.startsWith(`${t}${path.sep}`)) return `~${path.sep}${path.relative(t, e)}`;
return e;
}
/**
* Resolves a target's path rewrites once. A target can carry one move per legacy file
* (tens of thousands), so rewriting every path inside every issue message was
* quadratic and could hold doctor recovery for hours (#194621). A plain home-prefix
* rewrite equals what redactAbsoluteHomePaths applies to every message anyway, so only
* rewrites that also normalize the path need a per-message pass.
*/
function failureReportPathReplacements(e, t) {
const n = /* @__PURE__ */ new Map();
for (const r of [
e.storePath,
e.sqlitePath,
...e.plannedMoves.flatMap((e) => [e.sourcePath, e.archivePath]),
...e.completedMoves.flatMap((e) => [e.sourcePath, e.archivePath])
]) {
const e = shortenFailureReportPath(r, t);
if (e !== r && (!t || e !== `~${r.slice(t.length)}`)) n.set(r, e);
}
return [...n];
}
function sanitizeFailureIssueMessage(e, t, n) {
let r = e.message;
for (const [e, n] of t) r = r.split(e).join(n);
if (e.sessionKey) r = r.split(e.sessionKey).join(redactSessionKey(e.sessionKey));
r = redactAbsoluteHomePaths(r, n);
return sanitizeFailureReportText(r);
}
function redactSessionKey(e) {
if (!e.trim()) return "[redacted-session-key]";
return `[redacted-session-key:${randomUUID().slice(0, 8)}]`;
}
function redactAbsoluteHomePaths(e, t) {
if (!t) return e;
let n = e;
for (const e of /* @__PURE__ */ new Set([
t,
t.replaceAll("\\", "/"),
t.replaceAll("/", "\\")
])) n = n.split(e).join("~");
return n;
}
//#endregion
export { writeSessionSqliteMigrationFailureReports as i, clearSessionSqliteMigrationGithubIssueClaim as n, createSessionSqliteMigrationFailureIssue as r, claimSessionSqliteMigrationGithubIssue as t };