UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,143 lines (1,142 loc) • 47.6 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./paths-DAcAg5aV.mjs"; import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { i as normalizeMainKey, r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { C as isSubagentSessionKey, j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey, t as DEFAULT_AGENT_ID } from "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as isSameOpenClawAgentDatabasePath, n as createOpenClawAgentDatabasePathMatcher } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { f as resolveAgentWorkspaceDir, r as resolveAgentConfig, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs"; import { _ as sql, i as executeSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { a as normalizeExecSecurity, l as resolveExecModeFromPolicy, o as normalizeExecTarget, r as normalizeExecAsk } from "./exec-approvals-core-puBAw1bE.mjs"; import { o as closeOpenClawAgentDatabaseByPathAsync } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs"; import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs"; import { i as openOpenClawAgentDatabase, r as isOpenClawAgentDatabaseOpen } from "./openclaw-agent-db-CwXW4hGa.mjs"; import { l as preserveCreationStamp } from "./session-entry-provenance-01l9mXT0.mjs"; import { c as hasInterSessionUserProvenance } from "./input-provenance-DupvvURj.mjs"; import { t as applyExecPolicyLayer } from "./exec-policy-B0KOmSWr.mjs"; import { t as SESSION_PERMISSION_BY_EXEC_MODE } from "./session-permission-exec-mode-vqqWNPSg.mjs"; import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs"; import { o as resolveDeliveryProvenCanonicalSessionKey } from "./store-entry-BTUJi0xl.mjs"; import { i as toDatabaseOptions, t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import { o as resolveSqliteScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs"; import { i as resolveSqliteTranscriptArchiveDirectory } from "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { m as setCanonicalSqliteSessionMainKey, u as readStoredCanonicalSessionMainKey } from "./session-canonical-key-q6kSkP3K.mjs"; import { i as INTERNAL_WAKE_TRANSCRIPT_PROMPTS } from "./heartbeat-DHK32_6H.mjs"; import { n as projectSessionDisplayMessage } from "./session-display-projection-Gw_AmJmJ.mjs"; import { t as SessionTranscriptColdError } from "./session-transcript-cold-error-zvtkWn39.mjs"; import { r as isSessionTranscriptProjectionUnavailableError } from "./session-transcript-projection-error-D8lfGKCW.mjs"; import { t as resolveAgentSessionDirs } from "./session-dirs-De9GGhnR.mjs"; import { a as resolveAllAgentSessionStoreTargetsSync } from "./targets-BVE0__Jb.mjs"; import { s as writeTranscriptArchive } from "./session-accessor.sqlite-archive-artifact-DxAxsx2G.mjs"; import { r as parseReadableSqliteSessionEntryRow } from "./session-accessor.sqlite-entry-read-csOyyi3K.mjs"; import { _ as listCanonicalSessionRepairFacts, b as scanDoctorSessionEntriesTolerant, v as loadCanonicalSessionRepairEntries } from "./session-accessor-CizTbDQj.mjs"; import { n as collectSessionStateIdsForEntry } from "./session-accessor.sqlite-references-sJ03Zh3Z.mjs"; import { g as copySessionNodeArtifactsForRepair, v as deleteSessionMembersForRepair } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { i as resolveSessionStoreAgentId, s as resolveStoredSessionKeyForAgentStore } from "./session-store-key-CEwU3noi.mjs"; import { d as listSqliteSessionGenerationIdsForCanonicalRepair, f as rehomeSqliteSessionDeliveryReferencesForCanonicalRepair, l as copySqliteSessionOwnedStateForCanonicalRepair, p as rehomeSqliteSessionDeliveryReferencesForCanonicalRepairBatch, u as ensureSqliteTranscriptGenerationsForCanonicalRepair } from "./session-accessor.entry-f0bkn7cv.mjs"; import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs"; import { n as replaceSessionOwnerInTransaction } from "./session-accessor.sqlite-owner-BfpcingM.mjs"; import { g as applySessionEntryLifecycleMutation } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs"; import { t as loadSessionTranscriptEvents } from "./session-transcript-events-8GUhKWqo.mjs"; import { a as readSessionTranscriptBoundedMessageTailPage, o as readSessionTranscriptMessageEventPage } from "./session-accessor.sqlite-active-events-hAlJWczq.mjs"; import { t as deriveGoalSessionTitle } from "./derive-goal-session-title-DfSk--3F.mjs"; import { s as listRegistryWorktreesForMigration } from "./registry-C6O4gwRx.mjs"; import { t as hasExplicitSessionName } from "./session-title-state-nyOIuOVp.mjs"; import { i as resolveExecTarget } from "./bash-tools.exec-target-DBNJnOXQ.mjs"; import { n as createLegacyStateMigrationStepReceipt } from "./state-migrations.messages-CNB52OxC.mjs"; import { d as resolveTargetSqlitePath, i as projectExistingAgentDatabaseTargets, r as listExistingAgentDatabaseTargets, u as resolveTargetSqliteOptions } from "./session-sqlite-migration-readers-DbmEQzSW.mjs"; import { n as repairAcpSessionMetaKeysForDoctor } from "./state-migrations.plugin-doctor-context-BvHz_Kli.mjs"; import { a as normalizeLegacyOpenAICodexTranscriptMetadata, i as hasBrokenPromptRewriteBranch, o as selectActivePath } from "./session-sqlite-transcript-verification-Bdys-Rbk.mjs"; import { t as isHistoricalSessionSqliteMigrationIssue } from "./session-sqlite-migration-issues-aFS6aEaW.mjs"; import { a as runPostSessionPluginDoctorStateRepairs } from "./state-migrations.plugin-doctor-D3oQDmqh.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { i as withDoctorSqliteMaintenanceLock, t as DoctorSqliteMaintenanceLockUnavailableError } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs"; import { a as resolveProjectRegistry } from "./project-registry-CaveJtQj.mjs"; import { n as formatSessionSqliteMigrationWarnings, t as collectSessionSqliteMigrationFindings } from "./doctor-session-sqlite-warnings-C3cKZSAx.mjs"; import { n as repairReservedIncognitoSessionKeys } from "./doctor-session-incognito-key-repair-CbOGxRN3.mjs"; import { n as runDoctorAgentDatabaseOperationAsync, t as runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation-BYsIdRWr.mjs"; import { i as repairLegacySessionEntryStates, n as repairCanonicalSessionEntries, r as repairCanonicalSessionResolvedSkills, t as repairCanonicalSessionDeliveryStates } from "./doctor-session-delivery-state-BNQy7Xnc.mjs"; import { r as isInformationalMissingSessionIndex } from "./doctor-session-sqlite-types-CboC48LX.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { walkDirectory } from "@openclaw/fs-safe/walk"; //#region src/config/sessions/transcript-jsonl.ts function serializeJsonlLines(e) { return e.length > 0 ? `${e.join("\n")}\n` : ""; } //#endregion //#region src/commands/doctor-session-canonical-candidates.ts function collectCanonicalSessionCandidateFacts(e, t) { const n = !listAgentIds(e.cfg).includes(DEFAULT_AGENT_ID); const r = normalizeMainKey(e.cfg.session?.mainKey); const resolveStoredKey = (t, i) => { const a = parseAgentSessionKey(i); const o = normalizeLowercaseStringOrEmpty(a?.rest); const s = n && a?.agentId === "main" && normalizeAgentId(t) !== "main" && (o === "main" || o === r); return resolveStoredSessionKeyForAgentStore({ cfg: e.cfg, agentId: t, sessionKey: i, preserveQualifiedAddress: !s }); }; const i = t.flatMap((t) => listCanonicalSessionRepairFacts({ agentId: t.agentId, storePath: t.storePath }).map((n) => { const { canonicalOwnerSessionKey: r, sessionKey: i } = n; const a = resolveStoredKey(t.agentId, i); return { canonicalKey: a ? resolveDeliveryProvenCanonicalSessionKey(a, n) : resolveAgentMainSessionKey({ cfg: e.cfg, agentId: t.agentId }), canonicalOwnerSessionKey: r, inventoryFact: n, sessionKey: i, storedKey: a, target: t }; })); const a = new Map(i.map((e) => [`${e.target.sqlitePath}\0${e.sessionKey}`, e])); const o = /* @__PURE__ */ new Map(); const resolveCanonicalKey = (e) => { const t = /* @__PURE__ */ new Set(); let n = e; let r; for (;;) { const e = o.get(n); if (e !== void 0) { r = e; break; } if (t.has(n)) return n.canonicalKey; t.add(n); const i = n.canonicalOwnerSessionKey ? a.get(`${n.target.sqlitePath}\0${n.canonicalOwnerSessionKey}`) : void 0; if (!i) { r = n.canonicalKey; break; } n = i; } for (const e of t) o.set(e, r); return r; }; const s = /* @__PURE__ */ new Map(); for (const e of i) { e.canonicalKey = resolveCanonicalKey(e); const t = parseAgentSessionKey(e.storedKey)?.agentId ?? e.target.agentId; for (const n of [e.sessionKey, e.storedKey]) for (const r of [e.target.sqlitePath, "*"]) { const i = `${r}\0${t}\0${n}`; const a = s.get(i) ?? /* @__PURE__ */ new Set(); a.add(e.canonicalKey); s.set(i, a); } } return i.map(({ canonicalKey: t, canonicalOwnerSessionKey: n, inventoryFact: r, sessionKey: i, target: a }) => { const o = t === "global" || t === "unknown" ? a.agentId : resolveSessionStoreAgentId(e.cfg, t); const canonicalizeLineageKey = (e) => { if (!e) return; const t = resolveStoredKey(o, e); const n = parseAgentSessionKey(t)?.agentId ?? o; for (const r of [a.sqlitePath, "*"]) for (const i of [e, t]) { const e = s.get(`${r}\0${n}\0${i}`); if (e?.size === 1) return [...e][0]; } return t; }; const c = canonicalizeLineageKey(r.parentSessionKey); const l = canonicalizeLineageKey(r.spawnedBy); const u = canonicalizeLineageKey(r.forkSourceSessionKey); return Object.assign({ agentId: a.agentId, canonicalKey: t, inventoryFact: r, lineageRepairRequired: c !== r.parentSessionKey || l !== r.spawnedBy || u !== r.forkSourceSessionKey, ownerEvidenceOnly: n !== void 0, sessionKey: i, sqlitePath: a.sqlitePath, storePath: a.storePath }, u ? { normalizedForkSourceSessionKey: u } : {}, c ? { normalizedParentSessionKey: c } : {}, l ? { normalizedSpawnedBy: l } : {}); }); } function resolveCanonicalSessionDestination(e) { const t = e.canonicalKey === "global" || e.canonicalKey === "unknown" ? normalizeAgentId(e.sourceAgentId ?? resolveSessionStoreAgentId(e.cfg, e.canonicalKey)) : resolveSessionStoreAgentId(e.cfg, e.canonicalKey); const n = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: t, env: e.env }); return { agentId: t, storePath: n, sqlitePath: resolveTargetSqlitePath({ agentId: t, storePath: n }) }; } function collectCanonicalSessionRepairGroups(e, t) { const n = collectCanonicalSessionCandidateFacts(e, t); const r = createOpenClawAgentDatabasePathMatcher(); return [...groupPluginRecords(n, (e) => { const t = e.canonicalKey === "global" || e.canonicalKey === "unknown" ? e.agentId : ""; return `${e.canonicalKey}\0${t}`; }).values()].flatMap((t) => { const n = t[0]; const i = resolveCanonicalSessionDestination({ canonicalKey: n.canonicalKey, cfg: e.cfg, env: e.env, sourceAgentId: n.agentId }); if (!(t.length > 1 || t.some((e) => e.inventoryFact.rawCompareRequired || e.lineageRepairRequired || e.sessionKey !== e.canonicalKey || !r(e.sqlitePath, i.sqlitePath)))) return []; const a = t.some((e) => r(e.sqlitePath, i.sqlitePath) && e.sessionKey === e.canonicalKey); return [{ candidates: t, removedRows: t.length - (a ? 1 : 0) }]; }); } //#endregion //#region src/commands/doctor-session-canonical-keys.ts function createCanonicalRepairRemoval(e, t) { const n = { archiveRemovedTranscript: t.archiveRemovedTranscript, deleteOwnedWindows: t.deleteOwnedWindows, ...t.deliveryCleanupKeys ? { deliveryCleanupKeys: t.deliveryCleanupKeys } : {}, exactStoredKey: true, expectedEntry: e.expectedEntry, sessionKey: e.sessionKey }; return e.rawEntryJson === void 0 ? n : Object.assign(n, { expectedRawEntryJson: e.rawEntryJson, expectedSnapshotRevision: e.rawSnapshotRevision }); } const CANONICAL_SESSION_REPAIR_BATCH_GROUP_LIMIT = 64; function hydrateCanonicalSessionCandidate(e, t) { const n = { ...t.entry }; if (e.normalizedParentSessionKey) n.parentSessionKey = e.normalizedParentSessionKey; else delete n.parentSessionKey; if (e.normalizedSpawnedBy) n.spawnedBy = e.normalizedSpawnedBy; else delete n.spawnedBy; if (n.forkSource && e.normalizedForkSourceSessionKey) n.forkSource = { ...n.forkSource, sessionKey: e.normalizedForkSourceSessionKey }; else if (n.forkSource?.sessionKey !== void 0) { const { sessionKey: e, ...t } = n.forkSource; n.forkSource = t; } const r = { agentId: e.agentId, canonicalKey: e.canonicalKey, entry: n, expectedEntry: t.entry, ownerEvidenceOnly: e.ownerEvidenceOnly, sessionKey: e.sessionKey, sqlitePath: e.sqlitePath, storePath: e.storePath }; return t.rawEntryJson !== void 0 ? { ...r, rawEntryJson: t.rawEntryJson, rawSnapshotRevision: t.rawSnapshotRevision } : r; } function hydrateCanonicalSessionCandidates(e) { const t = /* @__PURE__ */ new Map(); const n = groupPluginRecords(e, (e) => `${e.agentId}\0${e.storePath}`); for (const e of n.values()) { const n = e[0]; const r = loadCanonicalSessionRepairEntries({ agentId: n.agentId, storePath: n.storePath }, e.map((e) => e.inventoryFact)); e.forEach((e, n) => t.set(e, r[n])); } return e.map((e) => hydrateCanonicalSessionCandidate(e, t.get(e))); } function mergeCanonicalSessionEntryCandidates(e, t) { let n; let r = false; for (const i of e) { const e = typeof i.entry.updatedAt === "number" && Number.isFinite(i.entry.updatedAt) ? i.entry.updatedAt : 0; const a = typeof n?.entry.updatedAt === "number" && Number.isFinite(n.entry.updatedAt) ? n.entry.updatedAt : 0; const o = isSameOpenClawAgentDatabasePath(i.sqlitePath, t) && i.sessionKey === i.canonicalKey; if (!n || e > a || e === a && (o ? !r : !r && Buffer.compare(Buffer.from(JSON.stringify(i.entry), "utf8"), Buffer.from(JSON.stringify(n.entry), "utf8")) > 0)) { n = i; r = o; } } return n ? { entry: n.entry, winner: n } : void 0; } function selectCanonicalSessionCandidate(e, t) { const n = e[0]; if (!n) return; const r = resolveCanonicalSessionDestination({ canonicalKey: n.canonicalKey, cfg: t.cfg, env: t.env, sourceAgentId: n.agentId }); const i = e.toSorted((e, t) => Buffer.compare(Buffer.from(`${e.sqlitePath}\0${e.sessionKey}`, "utf8"), Buffer.from(`${t.sqlitePath}\0${t.sessionKey}`, "utf8"))); const a = i.filter((e) => !e.ownerEvidenceOnly); const o = mergeCanonicalSessionEntryCandidates(a.length > 0 ? a : i, r.sqlitePath); if (!o) return; const s = i.filter(({ entry: e }) => e.sandbox === "required"); const c = s.find((e) => isSameOpenClawAgentDatabasePath(e.sqlitePath, r.sqlitePath) && e.sessionKey === e.canonicalKey)?.entry ?? mergeCanonicalSessionEntryCandidates(s, r.sqlitePath)?.entry; return { ...o, entry: preserveCreationStamp(o.entry, c), destination: r }; } function resolveSingleDatabaseCanonicalRepairGroup(e, t) { const n = selectCanonicalSessionCandidate(e, t); if (!n || e.some((e) => !isSameOpenClawAgentDatabasePath(e.sqlitePath, n.destination.sqlitePath))) return; return { candidates: e, selected: n }; } function createCanonicalDestinationRemovals(e, t) { const n = new Set([t.entry.sessionId, t.entry.previousSessionId].filter((e) => typeof e === "string" && e.length > 0)); return e.filter((e) => e.sessionKey !== t.winner.canonicalKey || e.rawEntryJson !== void 0).map((e) => createCanonicalRepairRemoval(e, { archiveRemovedTranscript: !n.has(e.entry.sessionId), deleteOwnedWindows: false })); } function listCanonicalDestinationAliasKeys(e, t) { return e.map((e) => e.sessionKey).filter((e) => e !== t.canonicalKey); } function applyCanonicalDestinationArtifacts(e) { replaceSessionOwnerInTransaction(e.database, e.winner.canonicalKey, e.winner.entry.owner); const t = listCanonicalDestinationAliasKeys(e.destinationStore, e.winner); if (t.length > 0) { if (e.rehomeDeliveries) rehomeSqliteSessionDeliveryReferencesForCanonicalRepair(e.database, e.winner.canonicalKey, t); copySessionNodeArtifactsForRepair(e.database, e.database, t, e.winner.canonicalKey, { includeMembers: false }); } if (!e.copyWinnerAlias || e.winner.sessionKey === e.winner.canonicalKey) return; deleteSessionMembersForRepair(e.database, e.winner.canonicalKey); copySessionNodeArtifactsForRepair(e.database, e.database, [e.winner.sessionKey], e.winner.canonicalKey, { includeParticipants: false }); } async function repairCanonicalSessionGroupsInSingleDatabase(e) { const t = e[0]; if (!t) return []; await ensureSqliteTranscriptGenerationsForCanonicalRepair(e.flatMap((e) => e.candidates)); const n = t.selected.destination; return (await applySessionEntryLifecycleMutation({ agentId: n.agentId, allowCanonicalRepair: true, afterUpsertsInTransaction: (t) => { rehomeSqliteSessionDeliveryReferencesForCanonicalRepairBatch(t, e.map((e) => ({ canonicalKey: e.selected.winner.canonicalKey, previousKeys: listCanonicalDestinationAliasKeys(e.candidates, e.selected.winner) }))); for (const n of e) applyCanonicalDestinationArtifacts({ copyWinnerAlias: true, database: t, destinationStore: n.candidates, rehomeDeliveries: false, winner: n.selected.winner }); }, removals: e.flatMap((e) => createCanonicalDestinationRemovals(e.candidates, e.selected)), skipMaintenance: true, storePath: n.storePath, upserts: e.map((e) => ({ entry: e.selected.entry, sessionKey: e.selected.winner.canonicalKey })) })).archivedTranscriptDirectories; } async function repairCanonicalSessionGroup(e, t) { const n = selectCanonicalSessionCandidate(e, t); if (!n) return []; await ensureSqliteTranscriptGenerationsForCanonicalRepair(e); const r = n.winner; const i = n.destination; const a = createOpenClawAgentDatabasePathMatcher(); const o = a.createIndex(); const s = groupPluginRecords(e, (e) => o(e.sqlitePath)); const c = s.get(o(i.sqlitePath)) ?? []; const l = /* @__PURE__ */ new Set(); const u = a(r.sqlitePath, i.sqlitePath); if (!u) { const e = /* @__PURE__ */ new Set([...listSqliteSessionGenerationIdsForCanonicalRepair({ agentId: r.agentId, canonicalKey: r.canonicalKey, sourceKeys: [r.sessionKey], storePath: r.storePath }), ...collectSessionStateIdsForEntry(r.entry)]); for (const n of e) { if (!n) continue; const e = c.find((e) => e.entry.sessionId === n); const [a, o] = await Promise.all([loadSessionTranscriptEvents({ agentId: e?.agentId ?? i.agentId, sessionId: n, sessionKey: e?.sessionKey ?? r.canonicalKey, storePath: e?.storePath ?? i.storePath }), loadSessionTranscriptEvents({ agentId: r.agentId, sessionId: n, sessionKey: r.sessionKey, storePath: r.storePath })]); const s = serializeJsonlLines(a.map((e) => JSON.stringify(e))); const u = serializeJsonlLines(o.map((e) => JSON.stringify(e))); if (!s || s === u) continue; const d = resolveSqliteTranscriptArchiveDirectory({ agentId: i.agentId, env: t.env, path: i.sqlitePath }); writeTranscriptArchive({ archiveDirectory: d, content: s, sessionId: n }); l.add(d); } } setCanonicalSqliteSessionMainKey(openOpenClawAgentDatabase(resolveTargetSqliteOptions(i, t.env)), t.cfg.session?.mainKey); const d = await applySessionEntryLifecycleMutation({ agentId: i.agentId, allowCanonicalRepair: true, afterUpsertsInTransaction: (e) => { applyCanonicalDestinationArtifacts({ copyWinnerAlias: u, database: e, destinationStore: c, rehomeDeliveries: true, winner: r }); if (!u) copySqliteSessionOwnedStateForCanonicalRepair({ canonicalKey: r.canonicalKey, destinationDatabase: e, preferredEntry: n.entry, preferredSessionKey: r.sessionKey, source: r, sourceEntries: [r.entry], sourceKeys: [r.sessionKey] }); }, removals: createCanonicalDestinationRemovals(c, n), skipMaintenance: true, storePath: i.storePath, upserts: [{ entry: n.entry, sessionKey: r.canonicalKey }] }); for (const e of d.archivedTranscriptDirectories) l.add(e); for (const [e, t] of s) { if (a(e, i.sqlitePath)) continue; const n = t[0]; const o = await applySessionEntryLifecycleMutation({ agentId: n.agentId, allowCanonicalRepair: true, removals: t.map((e) => createCanonicalRepairRemoval(e, { archiveRemovedTranscript: true, deleteOwnedWindows: true, deliveryCleanupKeys: [r.canonicalKey] })), skipMaintenance: true, storePath: n.storePath }); for (const e of o.archivedTranscriptDirectories) l.add(e); } return [...l]; } /** Doctor-owned durable repair; process-held incognito databases are intentionally excluded. */ async function repairCanonicalSessionKeys(e) { const t = e.env ?? process.env; const n = projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreTargetsSync(e.cfg, { env: t }), t, e.cfg); const r = /* @__PURE__ */ new Set(); let i = 0; let a = 0; if (e.apply) for (const r of n) { const n = resolveTargetSqliteOptions(r, t); const i = withOpenClawAgentDatabaseReadOnly(readStoredCanonicalSessionMainKey, n); if (!i.found || i.value !== normalizeMainKey(e.cfg.session?.mainKey)) setCanonicalSqliteSessionMainKey(openOpenClawAgentDatabase(n), e.cfg.session?.mainKey); } let o = collectCanonicalSessionRepairGroups({ cfg: e.cfg, env: t }, n); const s = o.length; const c = o.reduce((e, t) => e + t.removedRows, 0); if (e.apply) while (o.length > 0) { const s = o.slice(0, CANONICAL_SESSION_REPAIR_BATCH_GROUP_LIMIT); const c = hydrateCanonicalSessionCandidates(s.flatMap((e) => e.candidates)); let l = 0; const u = s.map((e) => { const t = c.slice(l, l + e.candidates.length); l += e.candidates.length; return t; }); const d = u[0]; const f = resolveSingleDatabaseCanonicalRepairGroup(d, { cfg: e.cfg, env: t }); const p = f ? [f] : []; if (f) for (const n of u.slice(1)) { const r = resolveSingleDatabaseCanonicalRepairGroup(n, { cfg: e.cfg, env: t }); if (!r || !isSameOpenClawAgentDatabasePath(r.selected.destination.sqlitePath, f.selected.destination.sqlitePath)) break; p.push(r); } const m = f ? await repairCanonicalSessionGroupsInSingleDatabase(p) : await repairCanonicalSessionGroup(d, { cfg: e.cfg, env: t }); for (const e of m) r.add(e); i += 1; a += f ? p.length : 1; o = collectCanonicalSessionRepairGroups({ cfg: e.cfg, env: t }, n); } return { archivedTranscriptDirectories: [...r].toSorted(), foundGroups: s, repairBatches: i, removedRows: c, repairedGroups: a, scannedStores: n.length }; } //#endregion //#region src/commands/doctor-session-dashboard-chat-type.ts /** * Return whether a row is provably a dashboard root that sessions.create would * now record as a direct chat, so it can receive the stamp it missed. * * The rule mirrors the creation-time dashboard-root condition from durable * facts only: operator-created, a generated `dashboard:` key, grouped under its * agent's main session, no external delivery route, and no spawn, fork, plugin * owner or incognito boundary. * Channel and group sessions are created via `channel`, never `operator`, and * never use a dashboard key, so they cannot match. Rows from before dashboard * roots were grouped under main lack the parent link and stay unstamped. */ function isUnstampedDashboardRoot(e, t, n) { if (e.chatType !== void 0 || e.createdVia !== "operator") return false; const r = parseAgentSessionKey(t); if (!r?.rest.startsWith("dashboard:") || isIncognitoSessionKey(t)) return false; if (e.incognito || e.spawnedBy || e.forkSource || e.pluginOwnerId) return false; if (e.delivery?.kind === "external") return false; return e.parentSessionKey === resolveAgentMainSessionKey({ cfg: n, agentId: r.agentId }); } /** Record dashboard roots created before creation-time stamping as direct chats. */ function repairLegacyDashboardChatTypes(e) { const t = []; const n = repairCanonicalSessionEntries({ ...e, updateDeliveryProjection: false, transform(n, r, i) { if (!isUnstampedDashboardRoot(n, r, e.cfg)) return n; if (i === (e.apply ? "repair" : "scan")) t.push(r); return { ...n, chatType: "direct" }; } }); if (t.length > 0) { const n = e.apply ? "Recorded" : "Would record"; note([ `- ${n} ${t.length} dashboard chat(s) as direct chats so their linked automations can use memory:`, ...t.map((e) => ` - ${e}`), ...e.apply ? [] : ["- Run \"openclaw doctor --fix\" to record them."] ].join("\n"), "Session chat type"); } return n; } //#endregion //#region src/commands/doctor-session-exec-policy.ts /** Retires session exec overrides without granting the full-mode approval-floor bypass. */ function repairLegacySessionExecPolicy(e) { const t = []; repairCanonicalSessionEntries({ ...e, updateDeliveryProjection: false, transform(n, r, i) { const { execSecurity: a, execAsk: o, ...s } = n; if (a === void 0 && o === void 0) return n; let c = normalizeExecAsk(o); if (!s.permissionMode) { const t = resolveSessionAgentId({ sessionKey: r, config: e.cfg }); const i = e.cfg.tools?.exec; const o = resolveAgentConfig(e.cfg, t)?.tools?.exec; const { effectiveHost: l } = resolveExecTarget({ configuredTarget: normalizeExecTarget(n.execHost) ?? o?.host ?? i?.host, elevatedRequested: false, sandboxRequired: n.sandbox === "required", sandboxAvailable: true }); const u = applyExecPolicyLayer(applyExecPolicyLayer({ security: l === "sandbox" ? "deny" : "full", ask: "off" }, i), o); c ??= u.ask; const d = resolveExecModeFromPolicy({ security: normalizeExecSecurity(a) ?? u.security, ask: c }); s.permissionMode = c === "always" ? "read-only" : d === "full" ? void 0 : SESSION_PERMISSION_BY_EXEC_MODE[d]; } if (i === (e.apply ? "repair" : "scan")) { const i = s.permissionMode ? `${n.permissionMode ? "kept" : "set"} permissionMode=${s.permissionMode}${c === "always" && !n.permissionMode ? " (ask=always has no mode equivalent; choose guarded or workspace to allow commands again)" : ""}` : "config default applies; full permission mode was not granted"; t.push(`- ${r}: ${e.apply ? "removed" : "would remove"} legacy exec policy; ${i}.`); } return s; } }); if (t.length > 0) { if (!e.apply) t.push("- Run \"openclaw doctor --fix\" to migrate legacy session exec policy."); note(t.join("\n"), "Session exec policy"); } } //#endregion //#region src/commands/doctor-session-title-repair.ts function readLegacySessionTitle(e) { try { const { totalMessages: t } = readSessionTranscriptMessageEventPage(e, { maxMessages: 0, offset: 0 }); if (!t) return; const n = readSessionTranscriptBoundedMessageTailPage(e, { maxMessages: 100, maxBytes: 65536, offset: Math.max(0, t - 100) }); if (n.totalMessages !== t || n.events.length !== n.scannedMessages) return; for (const e of n.events) { const t = asOptionalRecord(asOptionalRecord(e.event)?.message); const n = projectSessionDisplayMessage(t); if (n?.role === "user" && !hasInterSessionUserProvenance(t)) return deriveGoalSessionTitle(n.text) || void 0; } return; } catch (e) { if (isSessionTranscriptProjectionUnavailableError(e) || e instanceof SessionTranscriptColdError) return; throw e; } } /** Repair historical titles while Doctor owns session maintenance. */ async function repairLegacySessionTitles(e) { const t = e.authority; const assertRepairAuthority = () => { if (!t) throw new Error("Session title repair requires Doctor maintenance ownership."); t.assertCurrent(); }; if (e.apply) assertRepairAuthority(); const n = { found: 0, repaired: 0, scannedStores: 0, warnings: [] }; for (const t of e.targets ?? listExistingAgentDatabaseTargets(e.cfg, e.env)) { if (e.apply) assertRepairAuthority(); n.scannedStores++; const r = { agentId: t.agentId, storePath: t.storePath, env: e.env }; const i = runDoctorAgentDatabaseOperation({ agentId: t.agentId, path: t.sqlitePath, run: () => { const e = []; scanDoctorSessionEntriesTolerant(r, ({ entry: t, sessionKey: n, recoveredFromProjections: r }) => { const i = Object.values(INTERNAL_WAKE_TRANSCRIPT_PROMPTS).some((e) => t.displayName === e); if (!r && !t.incognito && !isIncognitoSessionKey(n) && !isSubagentSessionKey(n) && !hasExplicitSessionName(i ? { ...t, displayName: void 0 } : t)) e.push({ sessionKey: n, sessionId: t.sessionId, clearWakeTitle: i }); }); return e; } }); if (!i.ok) continue; for (const { sessionKey: t, sessionId: a, clearWakeTitle: o } of i.value) { if (e.apply) assertRepairAuthority(); try { const i = { ...r, sessionKey: t, sessionId: a }; const s = readLegacySessionTitle(i); if (!s && !o) continue; n.found++; if (!e.apply) continue; await patchSessionEntryCore(i, () => ({ displayName: s }), { preserveActivity: true, skipMaintenance: true, assertCommitAllowed: assertRepairAuthority, onCommitted: () => { n.repaired++; } }); assertRepairAuthority(); } catch (r) { if (e.apply) assertRepairAuthority(); n.warnings.push(`Could not repair the title for ${t}: ${String(r)}`); } } } return n; } //#endregion //#region src/config/sessions/worktree-workspace-migration.ts function isInside(e, t) { const n = path.relative(e, t); return n === "" || !n.startsWith("..") && !path.isAbsolute(n); } async function resolveLegacyCanonicalWorkspace(e) { const t = e.entry.worktree; if (!t || t.canonicalWorkspaceDir) return; const n = path.resolve(t.repoRoot); if (e.entry.projectId) { const t = await resolveProjectRegistry(e.cfg, e.entry.projectId, { env: e.env }); const r = t ? path.resolve(t.repoRoot) : void 0; return r && isInside(n, r) ? r : void 0; } const r = e.worktrees.find((e) => e.id === t.id); const i = e.entry.spawnedCwd; if (r?.ownerKind === "session" && r.ownerId === e.sessionKey && i && path.resolve(r.repoRoot) === path.resolve(t.repoRoot)) { const e = path.relative(path.resolve(r.path), path.resolve(i)); if (e === "" || !e.startsWith("..") && !path.isAbsolute(e)) return path.resolve(n, e); } const a = path.resolve(resolveAgentWorkspaceDir(e.cfg, e.agentId, e.env)); return a && a === n ? a : void 0; } function listLegacyWorktreeSessionEntries(e) { const t = resolveSqliteScope({ ...e, sessionKey: "" }); const n = withOpenClawAgentDatabaseReadOnly((e) => { const t = getSessionKysely(e.db); const n = isPostgresSqlConnection(e.db); return executeSqliteQuerySync(e.db, t.selectFrom("session_nodes").selectAll().$if(!n, (e) => e.where(sql`session_nodes.entry_valid != 1 OR ( json_valid(session_nodes.entry_json) AND json_type(session_nodes.entry_json, '$.worktree') = 'object' AND ( json_type(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') IS NULL OR json_extract(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') = '' ) )`)).orderBy("session_key", "asc")).rows.flatMap((t) => { const r = parseReadableSqliteSessionEntryRow(e, t); if (!r) return []; const i = r.worktree; const a = i !== null && typeof i === "object" && !Array.isArray(i) && (i.canonicalWorkspaceDir === void 0 || i.canonicalWorkspaceDir === ""); return !n || t.entry_valid !== 1 || a ? [{ databasePath: e.path, entry: r, sessionKey: t.session_key }] : []; }); }, toDatabaseOptions(t)); return n.found ? n.value : []; } async function migrateManagedWorktreeCanonicalWorkspaces(e) { const t = cloneEnvWithPlatformSemantics(e.env ?? process.env); t.OPENCLAW_STATE_DIR = resolveStateDir(t); const n = listLegacyWorktreeSessionEntries({ agentId: e.agentId, env: t, storePath: e.storePath }); if (e.mode !== "doctor-fix" || n.length === 0) return { found: n.length, repaired: 0 }; const r = listRegistryWorktreesForMigration(t); let i = 0; for (const { databasePath: a, entry: o, sessionKey: s } of n) { const n = resolveAgentIdFromSessionKey(s, e.agentId); const c = await resolveLegacyCanonicalWorkspace({ agentId: n, cfg: e.cfg, entry: o, env: t, sessionKey: s, worktrees: r }); if (!c) continue; if ((await patchSessionEntryCore({ agentId: n, env: t, sessionKey: s, storePath: a }, (e) => { if (!e.worktree || e.worktree.id !== o.worktree?.id || e.worktree.repoRoot !== o.worktree.repoRoot || e.projectId !== o.projectId || e.spawnedCwd !== o.spawnedCwd || e.worktree.canonicalWorkspaceDir) return null; return { worktree: { ...e.worktree, canonicalWorkspaceDir: c } }; }, { preserveActivity: true, skipMaintenance: true }))?.worktree?.canonicalWorkspaceDir === c) i += 1; } return { found: n.length, repaired: i }; } //#endregion //#region src/commands/doctor-session-worktree-workspace.ts /** Run after key repairs, whose source claims include workspace metadata. */ async function repairLegacySessionWorktreeWorkspaces(e) { const t = e.targets ?? listExistingAgentDatabaseTargets(e.cfg, e.env); let n = 0; let r = 0; for (const i of t) { const t = isOpenClawAgentDatabaseOpen(i.sqlitePath); try { const t = await runDoctorAgentDatabaseOperationAsync({ agentId: i.agentId, path: i.sqlitePath, run: () => migrateManagedWorktreeCanonicalWorkspaces({ agentId: i.agentId, cfg: e.cfg, env: e.env, storePath: i.sqlitePath, mode: e.apply ? "doctor-fix" : "detect" }) }); if (t.ok) { n += t.value.found; r += t.value.repaired; } } finally { if (!t) await closeOpenClawAgentDatabaseByPathAsync(i.sqlitePath); } } return { found: n, repaired: r, scannedStores: t.length }; } //#endregion //#region src/commands/doctor-session-transcripts.ts const SESSION_TRANSCRIPTS_CHECK_ID = "core/doctor/session-transcripts"; function parseTranscriptEntries(e) { const t = []; for (const n of e.split(/\r?\n/)) { if (!n.trim()) continue; try { const e = JSON.parse(n); if (e && typeof e === "object" && !Array.isArray(e)) t.push(e); } catch { return []; } } return t; } /** Classifies one legacy transcript without changing its contents. */ async function inspectSessionTranscriptFile(e) { const t = { filePath: e, broken: false, originalEntries: 0, activeEntries: 0, legacyOpenAICodexEntries: 0 }; try { if ((await fs.stat(e)).size > 1048576) { t.deferred = true; t.reason = "Detailed branch/provider classification deferred to offline staged import."; return t; } const n = parseTranscriptEntries(await fs.readFile(e, "utf-8")); t.originalEntries = n.length; t.legacyOpenAICodexEntries = normalizeLegacyOpenAICodexTranscriptMetadata(n); const r = selectActivePath(n); t.activeEntries = r?.entries.length ?? 0; t.broken = (r ? hasBrokenPromptRewriteBranch(n, r.entries) : false) || t.legacyOpenAICodexEntries > 0; } catch {} return t; } async function listSessionTranscriptFiles(e) { const t = []; for (const n of e) { const { entries: e } = await walkDirectory(n, { maxDepth: 1, include: (e) => e.kind === "file" && e.name.endsWith(".jsonl") }); for (const r of e) t.push(path.join(n, r.name)); } return t.toSorted((e, t) => e.localeCompare(t)); } async function detectSessionTranscriptHealthIssues() { let e; try { e = await resolveAgentSessionDirs(resolveStateDir(process.env)); } catch { return []; } const t = await listSessionTranscriptFiles(e); const n = []; for (const e of t) { const t = await inspectSessionTranscriptFile(e); if (t.broken || t.deferred) n.push(t); } return n; } function sessionTranscriptIssueToHealthFinding(e) { const t = e.legacyOpenAICodexEntries > 0 ? ` ${e.legacyOpenAICodexEntries} legacy OpenAI Codex metadata entr${e.legacyOpenAICodexEntries === 1 ? "y" : "ies"}` : ""; return { checkId: SESSION_TRANSCRIPTS_CHECK_ID, severity: "info", message: e.deferred ? e.reason : `Session transcript has legacy branch or provider metadata that can be cleaned up.${t}`, path: e.filePath, fixHint: "Run `openclaw doctor --fix` to repair legacy transcripts during their staged import into SQLite." }; } function sessionTranscriptIssueToRepairEffect(e) { return { kind: "file", action: "would-rewrite-session-transcript", target: e.filePath, dryRunSafe: false }; } /** Reports or repairs session state through the canonical SQLite migration owner. */ async function noteSessionTranscriptHealth(e) { const t = { ...e, env: e?.env ?? process.env, shouldRepair: e?.shouldRepair === true }; const { hasRetainedDoctorSessionSources: n, runDoctorSessionSqlite: r } = await import("./doctor-session-sqlite-BeIvR4an.mjs"); let i; const recordPostSessionRefusal = (e) => { if (!t.postSessionPluginMigration || i) return i; i = createLegacyStateMigrationStepReceipt({ ...t.postSessionPluginMigration.step, refusal: e }, { changes: [], warnings: [e.message] }); t.onStepReceipt?.(i); return i; }; const runSessionSqlite = async (e) => { const a = t.shouldRepair ? void 0 : listExistingAgentDatabaseTargets(t.cfg ?? {}, t.env); if (!t.shouldRepair) { const e = await repairLegacySessionEntryStates({ apply: false, cfg: t.cfg ?? {}, env: t.env, targets: a }); if (e.found > 0) return { entryStateReport: e }; } const o = await r({ allAgents: true, ...t.cfg ? { cfg: t.cfg } : {}, env: t.env, mode: t.shouldRepair ? "import" : "dry-run", integrityCheck: t.integrityCheck }, e); const { migrateLegacyMainSessionKeys: s } = await import("./legacy-main-session-migration-RFnuCOyR.mjs"); const c = await s({ cfg: t.cfg ?? {}, env: t.env, mode: t.shouldRepair ? "doctor-fix" : "detect" }); const l = { apply: t.shouldRepair, cfg: t.cfg ?? {}, env: t.env, integrityCheck: t.integrityCheck }; const u = await repairCanonicalSessionKeys(l); const d = { ...l, targets: a ?? listExistingAgentDatabaseTargets(l.cfg, t.env) }; const f = repairCanonicalSessionResolvedSkills(d); const p = await repairReservedIncognitoSessionKeys(d); const m = repairCanonicalSessionDeliveryStates(d); repairLegacySessionExecPolicy(d); repairLegacyDashboardChatTypes(d); const h = { entryStateReport: void 0, report: o, legacyMainSessionResult: c, canonicalKeyReport: u, resolvedSkillsReport: f, reservedKeyReport: p, deliveryReport: m, acpKeyReport: await repairAcpSessionMetaKeysForDoctor({ ...d, authority: e, integrityCheck: t.integrityCheck }), titleReport: await repairLegacySessionTitles({ ...d, authority: e }), worktreeWorkspaceReport: await repairLegacySessionWorktreeWorkspaces({ ...d, apply: t.shouldRepair && (!c.armed || c.complete) }) }; if (t.postSessionPluginMigrationPlanBound && !t.postSessionPluginMigration) return h; if (t.postSessionPluginMigration?.step.requiredness === "not-required") { i = createLegacyStateMigrationStepReceipt(t.postSessionPluginMigration.step, { changes: [], warnings: [] }); t.onStepReceipt?.(i); return h; } if (!t.shouldRepair && t.postSessionPluginMigration) { recordPostSessionRefusal({ code: "repair-not-authorized", message: "Post-session plugin repair was planned but Doctor repair was not authorized." }); return h; } let g; let _ = t.postSessionPluginMigration?.step; try { g = await runPostSessionPluginDoctorStateRepairs({ config: t.cfg ?? {}, env: t.env, maintenanceAuthority: e, ...e && n(o) ? { beforeCompletion: async (t, n) => { const { settleRetainedDoctorSessionSources: r } = await import("./doctor-session-sqlite-BeIvR4an.mjs"); await r(o, t, e, n); } } : {}, ...t.postSessionPluginMigration ? { plannedActions: t.postSessionPluginMigration.plannedActions, inventory: t.postSessionPluginMigration.inventory } : {} }); } catch (e) { const t = `Plugin session repair failed before the planned step completed: ${String(e)}`; g = { changes: [], warnings: [t] }; if (_) _ = { ..._, refusal: { code: "step-threw", message: t } }; } if (_) { i = createLegacyStateMigrationStepReceipt(_, g); t.onStepReceipt?.(i); } const v = [...g.changes, ...g.warnings]; if (v.length > 0) note(v.join("\n"), "Plugin session repair"); return h; }; let a; try { a = t.shouldRepair ? await withDoctorSqliteMaintenanceLock({ env: t.env, operation: "session SQLite import", run: runSessionSqlite }) : await runSessionSqlite(); } catch (e) { if (!(e instanceof DoctorSqliteMaintenanceLockUnavailableError)) { recordPostSessionRefusal({ code: "blocked-by-session-repair-failure", message: `Post-session plugin repair was blocked because prerequisite session repair failed: ${String(e)}` }); throw e; } const n = formatErrorMessage(e); note(`- Skipped: ${n} Then run "${formatCliCommand("openclaw doctor --fix", t.env)}" for session-store maintenance.`, "Session SQLite"); recordPostSessionRefusal({ code: "sqlite-maintenance-unavailable", message: n }); return i; } if (a.entryStateReport) { note(`- Found ${a.entryStateReport.found} durable session row(s) with legacy pending-delivery, fallback, or memory-flush state. Run "openclaw doctor --fix" before further session inspection.`, "Session SQLite"); return i; } const { report: o, worktreeWorkspaceReport: s, acpKeyReport: c, titleReport: l, reservedKeyReport: u, canonicalKeyReport: d, deliveryReport: f, resolvedSkillsReport: p, legacyMainSessionResult: m } = a; const noteRepair = (e, t, n) => { if (e > 0) note(n(), t); }; noteRepair(s.found, "Session worktrees", () => t.shouldRepair ? `- Repaired saved workspace metadata for ${s.repaired} of ${s.found} managed-worktree session(s). Check project/worktree ownership for any remaining entries.` : `- Found ${s.found} managed-worktree session(s) missing saved workspace metadata. Run "openclaw doctor --fix" to repair them.`); if (c.found > 0 || c.warnings.length > 0) { t.onWarnings?.(c.warnings); note([ t.shouldRepair ? `- Repaired ${c.repaired} of ${c.found} legacy ACP metadata record(s).` : `- Found ${c.found} legacy ACP metadata record(s). Run "openclaw doctor --fix" to repair them.`, ...(c.backups ?? []).map((e) => `- Saved ACP metadata backup: ${e}`), ...c.warnings ].join("\n"), "ACP session keys"); } if (l.found > 0 || l.warnings.length > 0) note([t.shouldRepair ? `- Repaired ${l.repaired} of ${l.found} missing or internal-wake session title(s) without changing activity.` : `- Found ${l.found} missing or internal-wake session title(s). Run "openclaw doctor --fix" to repair them.`, ...l.warnings].join("\n"), "Session titles"); noteRepair(u.found, "Session SQLite", () => t.shouldRepair ? `- Renamed ${u.repaired} durable session key(s) that collided with the reserved incognito namespace.` : `- Found ${u.found} durable session key(s) that collide with the reserved incognito namespace. Run "openclaw doctor --fix" to rename them.`); noteRepair(d.foundGroups, "Session SQLite", () => t.shouldRepair ? `- Canonicalized ${d.repairedGroups} session-key group(s) in ${d.repairBatches} transaction batch(es), removed ${d.removedRows} duplicate or alias row(s), and preserved cross-store history in ${d.archivedTranscriptDirectories.length} archive director${d.archivedTranscriptDirectories.length === 1 ? "y" : "ies"}.` : `- Found ${d.foundGroups} outdated or duplicate session-key group(s). Run "openclaw doctor --fix" to preserve their history and update the rows to use the current keys.`); noteRepair(f.found, "Session SQLite", () => t.shouldRepair ? `- Canonicalized delivery state for ${f.repaired} durable session row(s).` : `- Found ${f.found} durable session row(s) with legacy delivery fields. Run "openclaw doctor --fix" to canonicalize them.`); noteRepair(p.found, "Session SQLite", () => t.shouldRepair ? `- Stripped the runtime-only skills catalog from ${p.repaired} durable session row(s). Logical SQLite pages are freed; shrinking the on-disk database requires "openclaw doctor --session-sqlite compact --session-sqlite-all-agents".` : `- Found ${p.found} durable session row(s) carrying a runtime-only skills catalog. Run "openclaw doctor --fix" to strip it.`); if (m.changes.length > 0 || m.warnings.length > 0) note([...m.changes.map((e) => `- ${e}`), ...m.warnings.map((e) => `- ${e}`)].join("\n"), "Legacy main sessions"); if (o.totals.legacyEntries === 0 && o.totals.unreferencedJsonlFiles === 0 && o.totals.issues === 0) return i; const h = o.targets.filter(isInformationalMissingSessionIndex); const g = o.targets.filter((e) => !isInformationalMissingSessionIndex(e)); const _ = g.reduce((e, t) => e + t.issues.filter((e) => !isHistoricalSessionSqliteMigrationIssue(e)).length, 0); const v = [`- Legacy entries: ${o.totals.legacyEntries}; SQLite entries: ${o.totals.sqliteEntries}.`, `- Transcript events: imported=${o.totals.importedTranscriptEvents}; validated=${o.totals.validatedTranscriptEvents}.`]; for (const e of h) for (const t of e.issues) v.push(`- ${t.message}`); if (o.totals.archivedTranscriptFiles > 0) v.push(`- Archived ${o.totals.archivedTranscriptFiles} legacy transcript artifact(s).`); if (o.totals.archivedUnreferencedJsonlFiles > 0) v.push(`- Archived ${o.totals.archivedUnreferencedJsonlFiles} unreferenced JSONL artifact(s).`); const y = formatSessionSqliteMigrationWarnings(g, t.env); t.onWarnings?.(y); const b = collectSessionSqliteMigrationFindings(g, t.env); if (t.onFindings) t.onFindings(b); else for (const e of y) v.push(`- ${e}`); if (_ > 0) v.push(`- Found ${_} session SQLite issue(s). Inspect with "${formatCliCommand("openclaw doctor --session-sqlite dry-run --session-sqlite-all-agents", t.env)}".`); if (!t.shouldRepair && g.some((e) => e.legacyEntries > 0)) v.push("- Run \"openclaw doctor --fix\" to migrate legacy session metadata/transcripts to SQLite."); if (t.shouldRepair && o.migrationRun && o.totals.archivedTranscriptFiles > 0) v.push(`- After verifying the upgrade, preview rollback retirement with "${formatCliCommand("openclaw update cleanup --dry-run", t.env)}" for state ${resolveStateDir(t.env)}. Keep the same OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH overrides.`); note(v.join("\n"), "Session SQLite"); return i; } //#endregion export { detectSessionTranscriptHealthIssues, noteSessionTranscriptHealth, sessionTranscriptIssueToHealthFinding, sessionTranscriptIssueToRepairEffect };