openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
157 lines (156 loc) • 6.26 kB
JavaScript
import { V as timestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as executeSqliteQueryTakeFirstSync } from "./kysely-sync-YJo2lmGV.mjs";
import { v as backupDoctorSqliteRepair } from "./openclaw-state-db-ARhwdPJg.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { s as runOpenClawAgentWriteTransaction } from "./openclaw-agent-db-CwXW4hGa.mjs";
import { a as isIndexedSessionEntry } from "./session-entry-codec-CQ_dNjQf.mjs";
import { t as createSessionTranscriptHeader } from "./transcript-header-BkiaySSQ.mjs";
import { t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { n as isSessionTranscriptLeafControl, t as isCanonicalSessionTranscriptEntry } from "./transcript-tree-CyUZzlQ1.mjs";
import { r as replaceSqliteTranscriptEventsInTransaction } from "./session-accessor.sqlite-transcript-store-DRtj0wNT.mjs";
import { x as readTranscriptStorageRows } from "./session-accessor.sqlite-read-DA1Bsaij.mjs";
import "./session-manager-codec-DTi9FkQE.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { t as countLabel } from "./doctor-state-integrity-format-XVQ-DkEv.mjs";
import { n as transcriptSnapshotsMatch, t as scanDoctorSessionTranscripts } from "./doctor-session-transcript-scan-DFw1p_PR.mjs";
//#region src/commands/doctor-session-transcript-headers.ts
const NOTE_TITLE = "Session transcript headers";
function createCanonicalHeaderlessEventParser(e) {
const t = /* @__PURE__ */ new Set([e]);
const n = [];
let r = 0;
return {
events: n,
hasIndexedEntries: () => r > 0,
parse(e) {
let i;
try {
i = JSON.parse(e.eventJson);
} catch {
return;
}
if (!isRecord(i) || i.type === "session") return;
if (isCanonicalSessionTranscriptEntry(i)) {
if (!isIndexedSessionEntry(i)) return;
r += 1;
} else if (i.type === "leaf" && !isSessionTranscriptLeafControl(i)) return;
if (typeof i.id === "string") {
const e = i.id.trim();
if (!e || t.has(e)) return;
t.add(e);
}
n.push(i);
return i;
}
};
}
function readHeaderRepairContext(e, t) {
const n = getSessionKysely(e.db);
const r = executeSqliteQueryTakeFirstSync(e.db, n.selectFrom("session_windows").leftJoin("session_nodes", "session_nodes.session_key", "session_windows.session_key").select([
"session_windows.session_key",
"session_nodes.current_session_id",
"session_nodes.entry_json"
]).where("session_windows.session_id", "=", t).limit(1));
if (!r?.session_key) return;
let i;
if (r.current_session_id === t && r.entry_json) try {
const e = JSON.parse(r.entry_json);
if (e.sessionId === t && typeof e.spawnedCwd === "string" && e.spawnedCwd.trim()) i = e.spawnedCwd.trim();
} catch {}
return {
sessionKey: r.session_key,
...i ? { spawnedCwd: i } : {}
};
}
async function noteSessionTranscriptHeaderHealth(e) {
const t = e.env ?? process.env;
let n = 0;
let r = 0;
const i = /* @__PURE__ */ new Set();
scanDoctorSessionTranscripts({
cfg: e.cfg,
env: t,
title: NOTE_TITLE,
failureLabel: "Failed to inspect transcript headers",
selectSessionIds: (e, t) => e.headerlessSessionIds(t)
}, ({ reader: a, target: o, databaseOptions: s, reportError: c, sessionId: l }) => {
const u = o.sqlitePath;
const d = createCanonicalHeaderlessEventParser(l);
const f = a.headerlessSnapshot(l, (e) => d.parse(e) !== void 0);
if (!f.ok) {
c(`- Failed to read transcript ${l} (${o.agentId})`, f.error);
return;
}
if (!f.sessionKey || !d.hasIndexedEntries() || f.rows.length === 0) return;
const p = timestampMsToIsoString(f.rows[0]?.createdAt ?? NaN);
if (!p) {
note(`- Failed to repair transcript ${l} (${o.agentId}): invalid first-row timestamp`, NOTE_TITLE);
return;
}
n += 1;
if (!e.shouldRepair) return;
const m = parseAgentSessionKey(f.sessionKey)?.agentId ?? o.agentId;
const h = resolveAgentWorkspaceDir(e.cfg, m, t);
try {
runOpenClawAgentWriteTransaction((e) => {
const n = readTranscriptStorageRows(e, l);
if (!transcriptSnapshotsMatch(f.rows, n, true)) throw new Error(`transcript changed while preparing header repair for ${l}`);
const r = readHeaderRepairContext(e, l);
if (!r || r.sessionKey !== f.sessionKey) throw new Error(`session binding changed while preparing header repair for ${l}`);
const a = createSessionTranscriptHeader({
version: 3,
cwd: r.spawnedCwd ?? h,
sessionId: l,
timestamp: p
});
if (!i.has(u)) {
const e = backupDoctorSqliteRepair(u, "transcript-headers");
i.add(u);
note(`- Saved pre-repair SQLite backup: ${e}`, NOTE_TITLE);
}
replaceSqliteTranscriptEventsInTransaction(e, {
agentId: o.agentId,
env: t,
path: u,
sessionId: l,
sessionKey: r.sessionKey
}, [a, ...d.events], {
createdAtByIndex: [n[0]?.createdAt ?? Date.parse(p), ...n.map((e) => e.createdAt)],
preserveSessionWindowRecency: true
});
}, s, {
operationLabel: "doctor.session-transcript-headers",
repairAdmission: {
integrityCheck: e.integrityCheck ?? "quick",
integrityTables: [
"transcript_events",
"transcript_rewrite_watermarks",
"session_windows",
"session_transcript_index_state",
"session_transcript_active_events",
"session_transcript_fts_rows",
"session_transcript_fts",
"transcript_event_identities",
"session_reactions",
"session_nodes"
]
}
});
r += 1;
} catch (e) {
c(`- Failed to repair transcript ${l} (${o.agentId})`, e);
}
});
if (e.shouldRepair && r > 0) note(`- Prepended missing headers to ${countLabel(r, "session transcript")}.`, NOTE_TITLE);
else if (!e.shouldRepair && n > 0) note([`- Found ${countLabel(n, "stored session transcript")} without a header.`, `- Run "openclaw doctor --fix" to repair ${n === 1 ? "it" : "them"} before resuming the session.`].join("\n"), NOTE_TITLE);
return {
found: n,
repaired: r
};
}
//#endregion
export { noteSessionTranscriptHeaderHealth };