UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,109 lines (1,108 loc) • 49.3 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { c as readFileDescriptorBoundedSync } from "./boundary-file-read-BfaFLDqt.mjs"; import { i as resolveRealpathOrAbsolute, r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { i as isPrimarySessionTranscriptFileName } from "./transcript-file-names-mCC_xfFb.mjs"; import { d as resolveTrajectoryPointerPath, u as resolveTrajectoryPath } from "./artifacts-D7SzhQlr.mjs"; import { a as resolveUnsuffixedSqliteTargetFromSessionStorePath } from "./session-sqlite-target-paths-Dw0pT36E.mjs"; import { a as executeSqliteQueryTakeFirstSync } from "./kysely-sync-YJo2lmGV.mjs"; import { l as syncDirectory, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs"; import { o as sameFileMutationFingerprint } from "./file-descriptor-DQ-v5bLt.mjs"; import { a as resolveSqliteDatabaseFilePaths, t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs"; import { a as readSqliteFileGenerationSync } from "./openclaw-quarantine-store-Bi4DSTmN.mjs"; import { _ as withSynchronousArtifactPreservingStateSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { p as assertOpenClawStateWriteAllowedAtPath } from "./openclaw-state-db-ARhwdPJg.mjs"; import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs"; import { E as migrateLegacySessionCreator } from "./openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs"; import "./openclaw-agent-db-CwXW4hGa.mjs"; import { t as attachSessionEntrySnapshots } from "./session-entry-snapshot-values-CTzX9hmQ.mjs"; import { n as sessionEntrySnapshotColumns } from "./session-entry-snapshots-BIxBwjSA.mjs"; import { t as inspectOpenClawAgentDatabaseOwner } from "./openclaw-agent-db-owner-read-BF5eClGm.mjs"; import { a as normalizeStoreSessionKey } from "./store-entry-BTUJi0xl.mjs"; import { t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { i as resolveAllAgentSessionStoreCandidateTargetsSync } from "./targets-BVE0__Jb.mjs"; import { n as collectSessionStateIdsForEntry } from "./session-accessor.sqlite-references-sJ03Zh3Z.mjs"; import { i as isUpdateRecoveryPending } from "./update-run-recovery-schema-C6o9exnN.mjs"; import { n as inspectUpdateRecoveries } from "./update-run-recovery-store-jirLrGiS.mjs"; import { a as readLegacyPrimaryTranscriptIdentity, d as resolveTargetSqlitePath, s as readOnlySqliteValidationSnapshot, t as countTranscriptEventsForPath } from "./session-sqlite-migration-readers-DbmEQzSW.mjs"; import { c as listLegacySessionTranscriptFiles, d as shouldFilterLegacySessionRecordsByTarget, l as readLegacySessionStoreEntries, n as verifyTranscriptEvents, s as isLegacySessionRecordOwnedByTarget, t as verifyCanonicalSessionTranscriptSources, u as resolveLegacyTranscriptPaths } from "./session-sqlite-transcript-verification-Bdys-Rbk.mjs"; import { C as moveMigrationArtifact, E as statMigrationPath, S as isPendingMigrationArtifactClaim, T as sameMigrationArtifact, _ as sessionSqliteMigrationTargetKey, b as writeSessionSqliteMigrationManifest, f as migrationMoveKey, i as canonicalMigrationFilePath, l as hasSymbolicLinkInDirectoryPath, n as assertSafeSessionSqliteMigrationDirectory, t as HISTORICAL_IMPORT_REASON, v as uniqueRestoreMoves, w as readMigrationArtifactIdentity } from "./session-sqlite-migration-manifest-DwBodX3i.mjs"; import { n as isSessionSqliteMigrationWarning } from "./session-sqlite-migration-issues-aFS6aEaW.mjs"; import "./update-run-recovery-7wvn_ggB.mjs"; import { a as resolveRecoveryArtifact, i as protectRecoveryDependencies, n as collectUpdateCleanupInventory, o as summarizeRecoveryCleanup, s as retireUpdateCaptures, t as collectRecoveryInventory } from "./doctor-session-sqlite-recovery-inventory-nxlj5kaN.mjs"; import { n as normalizeLegacySessionEntryDelivery } from "./state-migrations.legacy-session-store-D6luaLu_.mjs"; import { i as withDoctorSqliteMaintenanceLock, n as assertDoctorSqliteMaintenancePathsNotAliased } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs"; import fs from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { setImmediate } from "node:timers/promises"; //#region src/commands/doctor-session-sqlite-discovery.ts /** Historical discovery belongs to offline Doctor, never runtime path resolution. */ /** Retained manifests bind archive files to their original agent, path, and bytes. */ function collectHistoricalArchiveSources(e) { const t = /* @__PURE__ */ new Map(); const n = collectRecoveryInventory(e); const r = /* @__PURE__ */ new Map(); const i = /* @__PURE__ */ new Map(); for (const e of n.references.values()) { if (e.some((e) => !e.trusted || e.consumedByRestore)) continue; const n = e[0]; if (!e.every(({ target: e, move: t }) => e.agentId === n.target.agentId && e.storePath === n.target.storePath && e.sqlitePath === n.target.sqlitePath && t.sourcePath === n.move.sourcePath)) continue; if (n.move.kind !== "legacy-store" && (n.move.kind !== "unreferenced-jsonl" || !isPrimarySessionTranscriptFileName(path.basename(n.move.sourcePath)))) continue; if (!e.every(({ move: e }) => e.artifact && (e.kind === "legacy-store" || e.artifact.classification === "protected") && sameMigrationArtifact(e.artifact.identity, n.move.artifact.identity))) continue; if (n.move.kind === "unreferenced-jsonl") { const t = n.move.artifact.identity; const i = JSON.stringify([ n.target.agentId, n.target.storePath, n.target.sqlitePath, n.move.sourcePath, t.size, t.sha256 ]); const a = r.get(i) ?? []; a.push(e); r.set(i, a); } if (e.some((e) => e.move.artifact?.disposal.state !== "retained")) continue; if (e.some(({ target: e, move: t }) => { if (t.artifact?.reason !== "indexed-historical-primary") return false; let n = i.get(e); if (!n) { n = new Set(e.completedMoves.map((e) => e.archivePath)); i.set(e, n); } return n.has(t.archivePath); })) continue; const a = t.get(n.target.storePath) ?? { transcripts: [], stores: [] }; (n.move.kind === "legacy-store" ? a.stores : a.transcripts).push(n.move); t.set(n.target.storePath, a); } if (n.report.artifacts.some((e) => ["unreadable-manifest", "manifest-directory-alias"].includes(e.reason))) r.clear(); return { sources: t, claims: [...r.values()].filter((e) => e.length > 1), inventory: n }; } /** Archived registries supply lineage only; never replay their entries over live SQLite state. */ function readArchivedSessionOwnership(e, t, n) { const r = []; let i = true; for (const a of t) { if (!fs.existsSync(a.archivePath)) continue; const t = []; try { const n = readMigrationArtifactIdentity(a.archivePath); if (!sameMigrationArtifact(n, a.artifact.identity, { ignoreDevice: true })) throw new Error("Archived session registry no longer matches its migration receipt (file metadata or contents changed)."); for (const n of readLegacySessionRecords(e, t, { sourcePath: a.archivePath })) r.push(n); if (t.length || !sameMigrationArtifact(readMigrationArtifactIdentity(a.archivePath), n)) throw new Error("Archived session registry changed during verification or contains invalid entries."); } catch (e) { i = false; n.push({ code: "historical_transcript_deferred", message: `${a.archivePath}: ${formatErrorMessage(e)} Historical transcript import skipped for this store; originals retained. This archive warning does not indicate SQLite corruption. No action is needed if all expected conversations are present. If history is missing, preserve the archive and migration manifests and follow https://docs.openclaw.ai/cli/doctor/sqlite-maintenance#changed-archived-registry` }); } } return i ? r : void 0; } async function discoverLegacyHistoricalTranscripts(e) { const t = path.dirname(canonicalMigrationFilePath(e.target.storePath)); assertSafeSessionSqliteMigrationDirectory(t); const n = /* @__PURE__ */ new Map(); const r = new Set(e.records.flatMap((e) => e.transcriptPath ? [canonicalMigrationFilePath(e.transcriptPath)] : [])); for (const i of listLegacySessionTranscriptFiles(t)) if ((!e.verifiedSourcePaths || e.verifiedSourcePaths.has(i)) && !r.has(canonicalMigrationFilePath(i)) && !e.referencedPaths?.has(canonicalMigrationFilePath(i))) n.set(i, { path: i, originalPath: i }); const i = new Set((e.ownershipRecords ?? []).flatMap((e) => e.transcriptDependencies.map(canonicalMigrationFilePath))); for (const t of e.archiveSources ?? []) { if (i.has(canonicalMigrationFilePath(t.sourcePath))) continue; n.set(t.archivePath, { path: t.archivePath, originalPath: t.sourcePath, archiveMove: t }); } const a = /* @__PURE__ */ new Map(); try { for (const t of [...e.records, ...e.ownershipRecords ?? []]) for (const e of collectSessionStateIdsForEntry(t.entry)) { const n = a.get(e) ?? /* @__PURE__ */ new Set(); n.add(t.sessionKey); a.set(e, n); } } catch (t) { e.issues.push({ code: "historical_transcript_deferred", message: `${e.target.storePath}: invalid legacy lineage; originals retained: ${String(t)}` }); return []; } const o = new Set([...a].filter(([, e]) => e.size > 1).map(([e]) => e)); const s = []; const c = /* @__PURE__ */ new Map(); for (const t of n.values()) { await setImmediate(); try { const n = readMigrationArtifactIdentity(t.path); if (t.archiveMove && !sameMigrationArtifact(n, t.archiveMove.artifact.identity, { ignoreDevice: true })) throw new Error("Archived original changed since migration; retained without importing"); const r = readLegacyPrimaryTranscriptIdentity(t.path, t.originalPath, t.archiveMove ? o : void 0); if (!r) continue; if (!sameMigrationArtifact(n, readMigrationArtifactIdentity(t.path))) throw new Error("Primary transcript changed during discovery"); if (r.sessionId !== r.filenameId) e.issues.push({ code: "transcript_filename_mismatch", message: `${t.originalPath}: Header session ID ${r.sessionId} differs from filename ID ${r.filenameId}; using the header identity and preserving the original.` }); if (e.records.some((e) => e.entry.sessionId === r.sessionId && e.transcriptPath && fs.existsSync(e.transcriptPath))) throw new Error("A registered primary already claims this identity; extra original retained"); const i = e.snapshot.sessionKeysBySessionId.get(r.sessionId); const s = a.get(r.sessionId); if (s && (s.size !== 1 || i && !s.has(i))) throw new Error("Conflicting logical owners; retained without importing"); const l = i ?? s?.values().next().value; const u = resolveUnsuffixedSqliteTargetFromSessionStorePath(e.target.storePath).agentId; if (!l && u !== e.target.agentId) throw new Error("No unambiguous agent owner for unregistered history"); const d = { sessionKey: l ?? `agent:${e.target.agentId}:recovered:${r.sessionId}`, entry: { sessionId: r.sessionId, updatedAt: r.updatedAt, archivedAt: r.updatedAt || 1 }, transcriptPath: t.path, transcriptDependencies: [t.originalPath], historical: { originalPath: t.originalPath, identity: n, ...t.archiveMove ? { archiveMove: t.archiveMove } : {} } }; const f = c.get(r.sessionId) ?? []; f.push(d); c.set(r.sessionId, f); } catch (n) { e.issues.push({ code: "historical_transcript_deferred", message: `${t.originalPath}: ${String(n)}` }); } } for (const [t, n] of c) { const r = n[0]; const i = n.every((e) => e.historical?.archiveMove && e.historical.originalPath === r.historical.originalPath && e.historical.identity.size === r.historical.identity.size && e.historical.identity.sha256 === r.historical.identity.sha256); if (n.length > 1 && !i) e.issues.push({ code: "historical_transcript_deferred", message: `${t}: multiple primary files claim this identity; originals retained without importing: ${n.map((e) => e.historical.originalPath).join(", ")}` }); else s.push(r); } return s; } function gatherLegacyArchiveCoverage(e, t, n, r = resolveAllAgentSessionStoreCandidateTargetsSync(e, { env: t })) { const i = /* @__PURE__ */ new Set(); const a = /* @__PURE__ */ new Set(); const o = /* @__PURE__ */ new Set(); const s = /* @__PURE__ */ new Set(); const c = /* @__PURE__ */ new Set(); const l = /* @__PURE__ */ new Map(); const u = /* @__PURE__ */ new Map(); for (const e of n) { const t = canonicalMigrationFilePath(e.storePath); u.set(t, [...u.get(t) ?? [], e]); } const d = new Set([...u.keys()].map((e) => path.dirname(e))); const f = new Map([...r, ...n].map((e) => [canonicalMigrationFilePath(e.storePath), e])); for (const [t, n] of f) { if (t.endsWith(".sqlite") || !d.has(path.dirname(t)) || !fs.existsSync(t)) continue; const r = u.get(t) ?? []; const f = []; let p; try { assertSafeSessionSqliteMigrationDirectory(path.dirname(t)); l.set(t, readMigrationArtifactIdentity(t)); p = readLegacySessionRecords(n, f); } catch (e) { if (r.length > 0) throw e; s.add(path.dirname(t)); c.add(path.dirname(t)); continue; } const m = [...p.map((e) => e.sessionKey), ...f.flatMap((e) => e.sessionKey ? [e.sessionKey] : [])]; const h = r.length > 0 && f.every(isSessionSqliteMigrationWarning) && m.every((t) => r.some((n) => !shouldFilterLegacySessionRecordsByTarget(n) || isLegacySessionRecordOwnedByTarget(e, n, t))); if (f.length > 0) { s.add(path.dirname(t)); if (!h) c.add(path.dirname(t)); } if (h) i.add(t); for (const e of p) { if (!e.transcriptPath) continue; for (const t of [ e.transcriptPath, resolveTrajectoryPath(e.transcriptPath), resolveTrajectoryPointerPath(e.transcriptPath) ]) { if (!t) continue; const e = canonicalMigrationFilePath(t); a.add(e); if (!h) o.add(e); } } } for (const [e, t] of u) if (!fs.existsSync(e) && t.every((e) => !shouldFilterLegacySessionRecordsByTarget(e))) i.add(e); return { knownTargets: r, selectedStorePaths: i, referencedPaths: a, retainedPaths: o, incompleteDirectories: s, retainedDirectories: c, indexIdentities: l }; } function readLegacySessionRecords(e, t, n = {}) { return readLegacySessionStoreEntries(e, t, n).entries.map(({ entry: t, sessionKey: r }) => { const { transcriptPath: i, transcriptDependencies: a } = resolveLegacyTranscriptPaths(e, t, n.verifiedSourcePaths); return { entry: migrateLegacySessionCreator(normalizeLegacySessionEntryDelivery(t)), sessionKey: r, transcriptPath: i, transcriptDependencies: a }; }); } function listUnreferencedJsonlFiles(e, t) { const n = path.dirname(e); let r; try { r = fs.readdirSync(n); } catch { return []; } const i = new Set(t.map((e) => resolveRealpathOrAbsolute(e))); return r.filter((e) => e.endsWith(".jsonl")).map((e) => path.join(n, e)).filter((e) => !i.has(resolveRealpathOrAbsolute(e))).toSorted((e, t) => e.localeCompare(t)); } /** Complete indexless discovery before import, keeping current ownership authoritative. */ async function appendLegacyHistoricalTranscripts(e) { const { allRecords: t, retainedImport: n, sourceConflicts: r, issues: i } = e; const a = e.historicalArchives?.get(canonicalMigrationFilePath(e.target.storePath)); const o = readArchivedSessionOwnership(e.target, n ? [] : a?.stores ?? [], i); const s = readOnlySqliteValidationSnapshot(e.target); if (s.ok && o) { const c = await discoverLegacyHistoricalTranscripts({ target: e.target, records: t, ownershipRecords: o, referencedPaths: e.referencedPaths, archiveSources: !n ? a?.transcripts : [], verifiedSourcePaths: n ? new Set(n.sources.filter((e) => !r.has(e.path)).map((e) => e.path)) : void 0, snapshot: s.snapshot, issues: i }); for (const e of c) { const n = t.find((t) => t.sessionKey === e.sessionKey && t.entry.sessionId === e.entry.sessionId && (!t.transcriptPath || !fs.existsSync(t.transcriptPath))); if (n) { n.transcriptPath = e.transcriptPath; n.transcriptDependencies.push(...e.transcriptDependencies); n.historical = e.historical; } else t.push(e); } } else if (!s.ok) i.push({ code: "sqlite_read_failed", message: String(s.error) }); } //#endregion //#region src/commands/doctor-session-sqlite-migration-coalesce.ts /** Manifest-owned redirection of verified redundant archive references. */ /** Replace retired duplicate references without removing any run's rollback coverage. */ function coalesceSessionSqliteArchiveReferences(e, t) { const n = /* @__PURE__ */ new Map(); const r = /* @__PURE__ */ new Set(); const i = /* @__PURE__ */ new Map(); for (const [t, n] of e) for (const e of [t, n.archivePath]) { const n = i.get(e) ?? []; n.push(t); i.set(e, n); } for (const a of t) for (const t of a.manifest.targets) { const o = /* @__PURE__ */ new Set(); for (const e of uniqueRestoreMoves(t)) for (const t of i.get(e.archivePath) ?? []) o.add(t); if (o.size === 0) continue; const s = sessionSqliteMigrationTargetKey(t); const c = n.get(s) ?? { target: t, archives: /* @__PURE__ */ new Set(), issues: [{ code: "historical_duplicate_settled", message: "" }] }; n.set(s, c); o.forEach((e) => c.archives.add(e)); t.issues.push(...c.issues); for (const n of ["plannedMoves", "completedMoves"]) { const r = /* @__PURE__ */ new Map(); for (const i of t[n]) { const t = e.get(i.archivePath); if (t && i.artifact?.disposal.state === "disposed") { i.archivePath = t.archivePath; i.artifact = { ...i.artifact, identity: t.artifact.identity, disposal: { state: "retained" } }; } const n = migrationMoveKey(i); if (r.get(n)?.artifact?.reason !== "indexed-historical-primary") r.set(n, i); } t[n] = [...r.values()]; } r.add(a); } for (const { archives: e, issues: t } of n.values()) t[0].message = `Retired ${e.size} byte-identical duplicate archive(s); rollback references now use the verified surviving originals.`; for (const e of r) writeSessionSqliteMigrationManifest(e); return [...n.values()].map(({ target: e, issues: t }) => ({ target: e, issues: t })); } //#endregion //#region src/commands/doctor-session-sqlite-verification.ts /** Offline destination ownership and conservative adoption of historical import evidence. */ /** * A reboot can renumber a volume's st_dev. The original sits beside its destination, so when its * recorded inode and metadata are still on the destination's current device, both files moved * together: the volume was renumbered, not swapped for another one with a colliding inode. * Callers verify the original's bytes separately; a replaced destination still fails its inode check. */ function isOriginalBesideDestination(e, t, n) { const r = e.kind === "database-backup" ? e.artifact : void 0; const i = r?.disposal.state === "pending-disposal" && !statMigrationPath(e.archivePath) ? r.disposal.claimPath : e.archivePath; const a = statMigrationPath(i, { bigint: true }); return Boolean(r && path.dirname(i) === path.dirname(t) && a?.isFile() && a.dev === n.dev && String(a.ino) === r.identity.ino && String(a.mtimeNs) === r.identity.mtimeNs && a.size === BigInt(r.identity.size)); } /** Keep one owner proof per database; fence in-place writes and sidecar changes after awaits. */ function createRecoveryDestinationVerifier(e, t, n = {}) { const r = /* @__PURE__ */ new Map(); return (i) => { for (const { target: a, run: o, move: s } of i) { const i = s.artifact?.disposal; if (i?.state === "pending-disposal" && !statMigrationPath(s.archivePath) && !statMigrationPath(i.claimPath)) continue; const c = resolveSqliteDatabaseFilePaths(a.sqlitePath); assertDoctorSqliteMaintenancePathsNotAliased("update recovery cleanup", c, [e]); const l = r.get(a.sqlitePath); let u = l?.agentId; if (!l) { const e = inspectOpenClawAgentDatabaseOwner(a.sqlitePath); u = e.status === "owned" ? e.agentId : void 0; } if (!a.databaseIdentity && u !== a.agentId) throw new Error("destination database ownership cannot be verified"); const d = c.map((e) => fs.lstatSync(e, { bigint: true, throwIfNoEntry: false })); if (!d[0]?.isFile() || a.databaseIdentity && String(d[0]?.ino) !== a.databaseIdentity.ino || d.some((e) => e && (!e.isFile() || e.nlink !== 1n)) || l && ["dev", "ino"].some((e) => d[0]?.[e] !== l.files[0]?.[e]) || l && !n.allowOwnedMutation && d.some((e, t) => (t === 0 ? [ "ctimeNs", "mtimeNs", "size" ] : [ "dev", "ino", "size" ]).some((n) => e?.[n] !== l.files[t]?.[n]))) throw new Error(`Recovery destination database changed (stage=file-stat, ownedMutation=${Boolean(n.allowOwnedMutation)}); preview cleanup again.`); const f = a.databaseIdentity; const p = f !== void 0 && f.dev !== String(d[0].dev); const m = p && isOriginalBesideDestination(s, a.sqlitePath, d[0]); const h = n.allowOwnedMutation && (!p || m) ? void 0 : readSqliteFileGenerationSync(a.sqlitePath); if (h && [ ["database", 0], ["wal", 1], ["journal", 3] ].some(([e, t]) => h[e]?.dev !== d[t]?.dev || h[e]?.ino !== d[t]?.ino || h[e]?.size !== d[t]?.size || l && !n.allowOwnedMutation && h[e]?.sha256 !== l.generation?.[e]?.sha256)) throw new Error(`Recovery destination database changed (stage=generation, ownedMutation=${Boolean(n.allowOwnedMutation)}); preview cleanup again.`); if (f && p) { const e = s.kind === "database-backup" && s.sourcePath === a.sqlitePath && !s.archivePath.endsWith(".scoped.bak") && s.artifact?.classification === "repair-original" ? s.artifact.identity : void 0; if (!m && (!h || (h.wal?.size ?? 0n) > 32n || (h.journal?.size ?? 0n) > 0n || h.database.sha256 !== (f.sha256 ?? e?.sha256))) throw new Error(`Recovery destination device changed from ${f.dev} to ${d[0].dev}; destination contents could not be verified against recorded recovery evidence. Originals retained. Run openclaw doctor --fix to check current state; retain the originals for manual verification.`); t(); a.databaseIdentity = { ...f, dev: String(d[0].dev), ...h && !m && { sha256: h.database.sha256 } }; writeSessionSqliteMigrationManifest(o); } r.set(a.sqlitePath, { agentId: u, files: d, generation: h }); } }; } function verifyHistoricalMigrationArtifact(e) { const { target: t, move: n, env: r } = e; if (n.kind !== "legacy-store" && n.kind !== "transcript") return; const i = readMigrationArtifactIdentity(n.archivePath); const a = n.kind === "legacy-store" ? n : uniqueRestoreMoves(t).find((e) => e.kind === "legacy-store"); if (!a) return; readMigrationArtifactIdentity(a.archivePath); const o = fs.openSync(a.archivePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); let s; try { s = JSON.parse(readFileDescriptorBoundedSync(o, fs.fstatSync(o).size).toString("utf8")); } finally { fs.closeSync(o); } if (!isRecord(s)) return; const c = n.kind === "legacy-store" ? Object.entries(s) : n.sessionKey ? [[n.sessionKey, s[n.sessionKey]]] : []; if (n.kind === "transcript" && c.length !== 1) return; const l = new Set(n.kind === "legacy-store" ? uniqueRestoreMoves(t).filter((e) => e.kind === "transcript").map((e) => e.sourcePath) : []); const u = withOpenClawAgentDatabaseReadOnly((e) => { const r = getSessionKysely(e.db); for (const [i, a] of c) { if (typeof i !== "string" || !isRecord(a) || typeof a.sessionId !== "string" || !a.sessionId.trim() || typeof a.updatedAt !== "number") return false; const o = a.sessionId; const s = executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("session_nodes").select(["current_session_id", "entry_json"]).select(sessionEntrySnapshotColumns).where("session_key", "=", i)); if (!s || s.current_session_id !== a.sessionId) return false; const c = JSON.parse(s.entry_json); if (!isRecord(c)) return false; attachSessionEntrySnapshots(c, s); const u = { ...a, sessionId: o, updatedAt: a.updatedAt }; const d = migrateLegacySessionCreator(normalizeLegacySessionEntryDelivery(u)); if (Object.entries(d).some(([e, t]) => e !== "sessionFile" && JSON.stringify(c[e]) !== JSON.stringify(t))) return false; if (n.kind !== "transcript") { for (const e of resolveLegacyTranscriptPaths(t, u).transcriptDependencies) l.add(canonicalMigrationFilePath(e)); continue; } if (!verifyTranscriptEvents(e.db, { path: n.archivePath, originalPath: n.sourcePath, sessionId: o })) return false; } return true; }, { agentId: t.agentId, path: t.sqlitePath, env: r }); if (!u.found || !u.value) return; return { identity: i, classification: "imported", reason: "verified-historical-import", dependencies: [...l], disposal: { state: "retained" } }; } function validateLegacySessionRecords(e, t, n, r, i) { if (n.issues.some((e) => e.code === "legacy_import_deferred" && !e.sessionKey)) return false; if (r === "before-archive" && t.length === 0) return true; const a = n.issues.length; const o = readOnlySqliteValidationSnapshot(e); if (!o.ok) { n.issues.push({ code: "sqlite_read_failed", message: `SQLite validation read failed: ${String(o.error)}` }); return false; } for (const e of t) validateLegacySessionRecord(e, n, o.snapshot, r, i); return n.issues.length === a; } function validateLegacySessionRecord(e, t, n, r, i) { const a = r === "before-archive"; const hasIssue = (n) => t.issues.some((t) => t.code === n && t.sessionKey === e.sessionKey); const recordIssue = (n, r) => t.issues.push({ code: n, message: r, sessionKey: e.sessionKey }); const o = a ? e.sessionKey : normalizeStoreSessionKey(e.sessionKey); const s = e.historical || e.preserveCurrentSession ? n.sessionKeysBySessionId.get(e.entry.sessionId) === o ? e.entry.sessionId : void 0 : n.sessionIdsBySessionKey.get(o); if (!s) { recordIssue("sqlite_entry_missing", `SQLite entry is missing for ${o}.`); return; } if (s !== e.entry.sessionId) { recordIssue("sqlite_entry_mismatch", `SQLite sessionId ${s} does not match ${e.entry.sessionId}.`); return; } if (a && e.preserveCurrentSession && hasIssue("legacy_import_deferred")) return; if (!a) t.validatedEntries += 1; const c = countTranscriptEventsForPath(e.transcriptPath); if (c.status === "missing") { if (!a) t.validatedTranscriptEvents += n.transcriptEventCountsBySessionId.get(e.entry.sessionId) ?? 0; return; } if (c.status !== "ok") { if (!hasIssue("transcript_malformed")) recordIssue("transcript_malformed", c.message); return; } const l = n.transcriptEventCountsBySessionId.get(e.entry.sessionId) ?? 0; const u = a ? e.recovery?.sqliteEvents ?? e.recovery?.events ?? c.events : c.events; if (!(a || !e.transcriptPath ? l >= u : verifyCanonicalSessionTranscriptSources({ target: t, mode: "contained", sources: [{ path: e.transcriptPath, sessionId: e.entry.sessionId, originalPath: e.historical?.originalPath }], env: i }))) { recordIssue("sqlite_transcript_count_mismatch", a ? `SQLite transcript has ${l} events; verified import expects ${u}.` : `SQLite transcript has ${l} events; source has ${c.events}, but its events are not all present with matching content. Run openclaw doctor --session-sqlite recover to import a missing suffix or identify conflicting events.`); return; } if (!a) t.validatedTranscriptEvents += l; } //#endregion //#region src/commands/update-cleanup-unmanifested.ts /** Explicit per-path retirement, never automatic eligibility or suffix-based discovery. */ function overlaps(e, t) { const n = resolvePathViaExistingAncestorSync(t); return isPathInside(e, n) || isPathInside(n, e); } function pendingRecoveryRoots(e) { return inspectUpdateRecoveries({ env: e }).filter(({ record: e }) => isUpdateRecoveryPending(e)).flatMap(({ record: t }) => { return [ t.preimages?.ref.manifestPath, t.checkpoint?.ref.manifestPath, t.checkpoint?.preimageRef?.manifestPath, t.restore?.planPath, ...(t.afterImages ?? []).flatMap((e) => [ e.checkpointRef.manifestPath, e.afterUpdate.ref.manifestPath, e.afterUpdate.preimageRef?.manifestPath ]) ].filter((e) => Boolean(e)).map((e) => path.dirname(resolvePathViaExistingAncestorSync(e))).concat(absolutePaths(t.package, e), t.effects.flatMap((t) => absolutePaths(t.package, e)), t.effects.map((e) => e.resourceId).filter((e) => path.isAbsolute(e))); }); } /** Configured paths can name an active store even when its filename resembles an original. */ function absolutePaths(e, t) { if (typeof e === "string") return path.isAbsolute(e) || e.startsWith("~/") ? [resolveUserPath(e, t)] : []; if (!e || typeof e !== "object") return []; return Object.values(e).flatMap((e) => absolutePaths(e, t)); } function activePaths(e, t, n) { return [ path.join(n.report.stateDir, "state", "openclaw.sqlite"), ...absolutePaths(e, t), ...resolveAllAgentSessionStoreCandidateTargetsSync(e, { env: t }).flatMap((e) => [e.storePath, resolveTargetSqlitePath(e, t)]), ...[...n.references.values()].flatMap((e) => e.flatMap(({ target: e }) => [e.storePath, e.sqlitePath])) ].flatMap((e) => { const t = path.resolve(e); const n = fs.existsSync(t) ? fs.realpathSync(t) : t; return resolveSqliteDatabaseFilePaths(t).concat(resolveSqliteDatabaseFilePaths(n)); }); } function assertNotDatabase(e, t) { if (t.some((t) => isPathInside(e, t)) || SQLITE_SIDECAR_SUFFIXES.some((t) => e.endsWith(t)) || SQLITE_SIDECAR_SUFFIXES.some((t) => fs.lstatSync(`${e}${t}`, { throwIfNoEntry: false }))) throw new Error("Active database path or database sidecar; keep the database family intact."); } /** No following links and no recursive rm over uninspected files. */ function inspectSelection(e, t) { const n = /* @__PURE__ */ new Map(); if (hasSymbolicLinkInDirectoryPath(path.dirname(e.path)) || fs.realpathSync(e.path) !== e.path) throw new Error("Recovery path is aliased."); const r = [e.path]; while (r.length > 0) { const i = r.pop(); const a = fs.lstatSync(i, { bigint: true }); assertNotDatabase(i, t); if (a.isDirectory() && e.kind === "update-capture") { n.set(i, { stat: a }); for (const e of fs.readdirSync(i).toSorted().toReversed()) r.push(path.join(i, e)); } else if (a.isFile() && a.nlink === 1n) { if (e.kind !== "update-capture" && /\.(?:sqlite(?:3)?|db)$/iu.test(i)) throw new Error("Live database filename is not an unmanifested recovery original."); n.set(i, { stat: a, sha256: readMigrationArtifactIdentity(i).sha256 }); } else throw new Error("Recovery selection contains a symlink, hardlink, or nonregular file."); } return n; } /** Selection consumes the inventory owner's known paths; it never discovers new deletion roots. */ function selectUnmanifestedRecovery(e) { const t = /* @__PURE__ */ new Map(); if (!e.paths?.length) return t; const { inventory: n } = e; const r = [...new Set(e.paths.map((e) => path.resolve(e)))]; withSynchronousArtifactPreservingStateSnapshot(() => { const i = pendingRecoveryRoots(e.env); const a = activePaths(e.cfg, e.env, n); for (const e of r) { const r = n.report.artifacts.find((t) => t.path === e); if (!r || r.outcome !== "protected" || !["unmanifested-recovery-original", "orphan-update-capture"].includes(r.reason)) throw new Error(`Cannot include unmanifested path ${e}: not an eligible known recovery original or orphan capture.`); if (n.report.artifacts.some((e) => ["unreadable-manifest", "manifest-directory-alias"].includes(e.reason))) throw new Error("Cannot include unmanifested recovery with unreadable recovery dependencies."); if (i.some((t) => overlaps(e, t)) || [...n.references.values()].some((t) => t.some(({ move: t }) => [ t.sourcePath, t.archivePath, ...t.artifact?.dependencies ?? [], ...t.artifact?.disposal.state === "pending-disposal" ? [t.artifact.disposal.claimPath] : [] ].some((t) => overlaps(e, t))))) throw new Error(`Cannot include ${e}: pending or retained recovery references this path.`); t.set(e, inspectSelection(r, a)); } }, { current: { env: e.env } }); for (const [e, r] of t) { const t = n.report.artifacts.find((t) => t.path === e); const { stat: i } = r.get(e); t.outcome = "candidate"; t.reason = "explicit-unmanifested-selection"; t.bytes = [...r.values()].reduce((e, { stat: t }) => e + (t.isFile() ? Number(t.size) : 0), 0); t.modifiedAt = new Date(Number(i.mtimeMs)).toISOString(); t.detail = "Explicitly selected with --include-unmanifested. No import or rollback proof is inferred."; t.consequence = t.kind === "update-capture" ? "Permanently deletes this orphan original-state capture and all recovery generations inside it." : "Permanently deletes this unmanifested original; pre-repair history, branches, and metadata may be unrecoverable."; } n.report = summarizeRecoveryCleanup(n.report.stateDir, n.report.artifacts, "preview", n.report.missingOriginals); return t; } function assertUnmanifestedSelectionCurrent(e, t) { for (const [n, r] of e) { const e = t.get(n); if (!e || r.size !== e.size || [...r].some(([t, { stat: n, sha256: r }]) => { const i = e.get(t); return !i || !sameFileMutationFingerprint(n, i.stat) || r !== i.sha256; })) throw new Error(`Explicit recovery selection changed: ${n}; preview cleanup again.`); } } /** Existing maintenance/owner custody remains held through every synchronous point of effect. */ async function retireUnmanifestedRecovery(e) { for (const [t, n] of e.selected.entries()) try { e.onProgress?.(n, t); e.assertCurrent(); await e.assertReferences(n); e.assertCurrent(); const r = e.identities.get(n.path); const i = inspectSelection(n, []); assertUnmanifestedSelectionCurrent(/* @__PURE__ */ new Map([[n.path, r]]), /* @__PURE__ */ new Map([[n.path, i]])); for (const [t, { stat: i, sha256: a }] of [...r].toReversed()) { e.assertCurrent(); if (hasSymbolicLinkInDirectoryPath(path.dirname(t))) throw new Error("Recovery directory changed before removal."); const r = fs.lstatSync(t, { bigint: true }); if (i.isDirectory()) { if (!r.isDirectory() || r.dev !== i.dev || r.ino !== i.ino) throw new Error("Recovery directory changed before removal."); fs.rmdirSync(t); } else { if (!r.isFile() || r.nlink !== 1n || !sameFileMutationFingerprint(i, r) || readMigrationArtifactIdentity(t).sha256 !== a) throw new Error("Recovery original changed before removal."); assertNotDatabase(t, []); fs.unlinkSync(t); n.removedBytes = (n.removedBytes ?? 0) + Number(i.size); } } n.outcome = "removed"; n.reason = "explicit-unmanifested-retired"; requireDirectorySync(await syncDirectory(path.dirname(n.path)), "Explicit recovery retirement"); } catch (r) { n.outcome = "failed"; n.reason = "explicit-unmanifested-retirement-failed"; n.detail = String(r); for (const n of e.selected.slice(t + 1)) { n.outcome = "blocked"; n.reason = "retirement-stopped"; } break; } } //#endregion //#region src/commands/doctor-session-sqlite-retirement.ts /** Retirement of producer-verified originals; never a suffix deletion policy. */ function assertRecoveryOriginal(e, t, n) { const r = statMigrationPath(e) ? e : t.disposal.state === "pending-disposal" ? t.disposal.claimPath : e; if (!statMigrationPath(r)) { if (t.disposal.state === "pending-disposal") return; throw new Error("artifact is unexpectedly missing"); } const i = isPendingMigrationArtifactClaim(e, t) ? 2n : 1n; const a = readMigrationArtifactIdentity(r, i, void 0, n); if (!sameMigrationArtifact(a, t.identity, { ignoreDevice: true })) throw new Error("artifact identity or contents changed"); return a; } /** Coalesce only exact raw copies; the surviving original preserves every rollback byte. */ async function settleDuplicateSessionSqliteArchives(e) { const { claims: t, inventory: { artifacts: n, references: r } } = collectHistoricalArchiveSources(e); const i = []; const recordFailure = (e, t) => { i.push({ target: e, issues: [{ code: "historical_transcript_deferred", message: `${t}; original retained.` }] }); }; const a = /* @__PURE__ */ new Map(); const o = []; const s = /* @__PURE__ */ new Map(); for (const e of n) if (!s.has(e.path)) s.set(e.path, e); const c = /* @__PURE__ */ new Map(); const assertSurvivor = (e) => { const t = a.get(e[0].move.archivePath)[0].move; if (hasSymbolicLinkInDirectoryPath(path.dirname(t.archivePath))) throw new Error("Retained duplicate archive directory changed."); assertRecoveryOriginal(t.archivePath, t.artifact); }; for (const n of t) { const t = n[0][0].target; if (!e.targets.some((e) => e.agentId === t.agentId && e.storePath === t.storePath && e.sqlitePath === t.sqlitePath)) continue; const r = n.find((e) => e.every((e) => e.move.artifact.disposal.state === "retained")); if (!r) continue; for (const e of n.filter((e) => e !== r)) { const n = s.get(e[0].move.archivePath); a.set(n.path, r); try { assertSurvivor(e); const t = resolveRecoveryArtifact(e); if (e.some((e) => e.move.artifact.disposal.state === "disposed") && statMigrationPath(n.path)) throw new Error("Archive was recreated after disposal."); if (t.disposal.state !== "disposed") { assertRecoveryOriginal(n.path, t); n.outcome = "candidate"; o.push(n); } c.set(n.path, r[0].move); } catch (e) { recordFailure(t, `${n.path}: ${String(e)}`); } } } await disposeRecoveryArtifacts({ selected: o, references: r, assertDestinations: assertSurvivor }); for (const [e] of c) { const t = r.get(e); if (t.every((e) => e.move.artifact.disposal.state === "disposed")) assertSurvivor(t); else { c.delete(e); const n = s.get(e); recordFailure(t[0].target, `${e}: ${n.detail ?? n.reason}`); } } return [...i, ...coalesceSessionSqliteArchiveReferences(c, [...new Set([...r.values()].flatMap((e) => e.map((e) => e.run)))])]; } function assertRecoveryStateWriteAllowed(e, t) { return assertOpenClawStateWriteAllowedAtPath({ databasePath: path.join(e, "state", "openclaw.sqlite"), env: t, recoverOrphanedSidecars: false }); } /** Manual cleanup still requires the Gateway to be stopped. */ async function retireSessionSqliteRecovery(e) { await assertRecoveryStateWriteAllowed(e.preview.stateDir, e.env); return withDoctorSqliteMaintenanceLock({ env: e.env, operation: "update recovery cleanup", run: (t) => retireOwnedSessionSqliteRecovery(e, t) }); } /** Shared retirement under exclusive offline custody or the serving Gateway's live authority. */ async function retireOwnedSessionSqliteRecovery(e, t) { t.assertCurrent(); const n = await e.readConfig(); const r = collectUpdateCleanupInventory({ cfg: n, env: e.env }); const i = selectUnmanifestedRecovery({ inventory: r, cfg: n, env: e.env, paths: e.includeUnmanifested }); const { report: a, references: o, manifestPaths: s, captureIdentities: c } = r; t.assertCurrent(); if (a.stateDir !== e.preview.stateDir || JSON.stringify(a.artifacts) !== JSON.stringify(e.preview.artifacts)) throw new Error("Recovery selection changed; preview cleanup again."); await assertRecoveryStateWriteAllowed(a.stateDir, e.env); const l = /* @__PURE__ */ new Map(); const u = /* @__PURE__ */ new Map(); const d = createRecoveryDestinationVerifier(a.stateDir, () => t.assertCurrent(), { allowOwnedMutation: e.allowOwnedDestinationMutation }); const f = a.artifacts.filter((e) => e.kind !== "update-capture" && !i.has(e.path) && (e.outcome === "candidate" || e.outcome === "verification-required")); const p = e.verifyHistorical === false && a.artifacts.some((e) => o.get(e.path)?.some((e) => !e.move.artifact)); for (const [t, n] of f.entries()) { e.onProgress?.({ phase: "verifying", path: n.path, index: t + 1, total: f.length, bytes: n.bytes }); if (p) { if (n.outcome === "candidate") n.reason = "historical-recovery-dependencies-unverified"; n.outcome = "protected"; continue; } if (n.outcome === "verification-required") { const t = o.get(n.path); try { for (const n of t) { if (n.move.artifact) continue; const t = verifyHistoricalMigrationArtifact({ target: n.target, move: n.move, env: e.env }); if (!t) throw new Error("historical-import-proof-unavailable"); l.set(n, t); } n.outcome = "candidate"; n.reason = "verified-historical-import"; } catch (e) { n.outcome = "protected"; n.reason = "historical-import-proof-unavailable"; n.detail = String(e); } } if (n.outcome !== "candidate") continue; try { const e = o.get(n.path); const t = resolveRecoveryArtifact(e) ?? l.get(e[0]); assertRecoveryOriginal(n.path, t, u); } catch (e) { n.outcome = "blocked"; n.reason = "artifact-verification-failed"; n.detail = String(e); } } for (const e of a.artifacts) { if (e.outcome !== "candidate" || e.kind === "update-capture" || i.has(e.path)) continue; try { d(o.get(e.path)); } catch (t) { e.outcome = "blocked"; e.reason = "destination-verification-failed"; e.detail = String(t); } } protectRecoveryDependencies(a.artifacts, o, l); const m = summarizeRecoveryCleanup(a.stateDir, a.artifacts, "preview", a.missingOriginals); const h = m.artifacts.filter((e) => e.outcome === "candidate"); const g = h.filter((e) => i.has(e.path)); const _ = h.filter((e) => e.kind !== "update-capture" && !i.has(e.path)); const v = h.filter((e) => e.kind === "update-capture" && !i.has(e.path)); if (!await e.confirm(m)) return { ...m, status: "refused" }; t.assertCurrent(); const y = await e.readConfig(); const b = collectUpdateCleanupInventory({ cfg: y, env: e.env }); const x = selectUnmanifestedRecovery({ inventory: b, cfg: y, env: e.env, paths: e.includeUnmanifested }); assertUnmanifestedSelectionCurrent(i, x); if (b.report.stateDir !== a.stateDir || JSON.stringify(b.manifestPaths) !== JSON.stringify(s) || JSON.stringify(b.report.artifacts) !== JSON.stringify(e.preview.artifacts)) throw new Error("Recovery selection changed during confirmation; preview again."); const manifests = (e) => new Map([...e.values()].flat().map(({ run: e }) => [e.manifestPath, e.manifest])); const S = manifests(b.references); for (const [e, t] of manifests(o)) if (JSON.stringify(S.get(e)) !== JSON.stringify(t)) throw new Error("Recovery manifest changed during confirmation; preview again."); for (const e of [...o.values()].flat()) if (!(b.references.get(e.move.archivePath) ?? []).some((t) => t.trusted === e.trusted && t.target.storePath === e.target.storePath && t.target.sqlitePath === e.target.sqlitePath)) throw new Error("Recovery target changed during confirmation; preview again."); await assertRecoveryStateWriteAllowed(a.stateDir, e.env); t.assertCurrent(); for (const e of _) { const t = o.get(e.path); d(t); assertRecoveryOriginal(e.path, resolveRecoveryArtifact(t) ?? l.get(t[0]), u); } for (const [e, t] of l) { if (!_.some((t) => t.path === e.move.archivePath)) continue; if (e.run.manifest.manifestVersion !== 4) e.run.manifest.manifestVersion = 3; for (const n of [...e.target.plannedMoves, ...e.target.completedMoves]) if (n.archivePath === e.move.archivePath) n.artifact = t; } await disposeRecoveryArtifacts({ selected: _, references: o, assertDestinations: d, assertCurrent: () => t.assertCurrent(), verification: u, onProgress: e.onProgress }); await retireUpdateCaptures({ selected: v, identities: c, assertCurrent: () => t.assertCurrent(), onProgress: (t, n) => e.onProgress?.({ phase: "removing-capture", path: t.path, index: n + 1, total: v.length, bytes: t.bytes }) }); await retireUnmanifestedRecovery({ selected: g, identities: i, assertCurrent: () => t.assertCurrent(), assertReferences: async (n) => { const r = await e.readConfig(); t.assertCurrent(); const a = collectUpdateCleanupInventory({ cfg: r, env: e.env }); const o = selectUnmanifestedRecovery({ inventory: a, cfg: r, env: e.env, paths: [n.path] }); assertUnmanifestedSelectionCurrent(/* @__PURE__ */ new Map([[n.path, i.get(n.path)]]), o); }, onProgress: (t, n) => e.onProgress?.({ phase: "removing-unmanifested", path: t.path, index: n + 1, total: g.length, bytes: t.bytes }) }); return summarizeRecoveryCleanup(a.stateDir, a.artifacts, a.artifacts.some((e) => e.outcome === "failed" || e.outcome === "blocked") ? "blocked" : "complete", a.missingOriginals); } async function disposeRecoveryArtifacts({ selected: e, references: t, assertDestinations: n, assertCurrent: r, verification: i, onProgress: a }) { const o = /* @__PURE__ */ new Set(); const s = /* @__PURE__ */ new Map(); const movesFor = (e, t) => { let n = s.get(e.target); if (!n) { n = /* @__PURE__ */ new Map(); for (const t of [...e.target.plannedMoves, ...e.target.completedMoves]) if (t.artifact) { const e = n.get(t.archivePath) ?? []; e.push(t); n.set(t.archivePath, e); } s.set(e.target, n); } return n.get(t) ?? []; }; for (const n of e) { const e = t.get(n.path); const r = e.map(({ move: e }) => e.artifact.disposal).find((e) => e.state === "pending-disposal") ?? { state: "pending-disposal", intendedAt: (/* @__PURE__ */ new Date()).toISOString(), phase: "intent", claimPath: path.join(path.dirname(n.path), `.cleanup-${randomUUID()}`) }; for (const t of e) { for (const e of movesFor(t, n.path)) e.artifact.disposal = r; o.add(t.run); } } for (const e of o) { r?.(); writeSessionSqliteMigrationManifest(e); } let c; const l = e.map((e) => { const n = t.get(e.path); const r = n[0].move.artifact; const i = r.disposal; if (i.state !== "pending-disposal" || path.dirname(i.claimPath) !== path.dirname(e.path) || !path.basename(i.claimPath).startsWith(".cleanup-")) throw new Error("invalid disposal claim"); return { item: e, refs: n, artifact: r, disposal: i, present: false }; }); try { for (const [e, t] of l.entries()) { const { item: o, refs: s, artifact: u, disposal: d } = t; c = o; a?.({ phase: "claiming", path: o.path, index: e + 1, total: l.length, bytes: o.bytes }); r?.(); n(s); if (hasSymbolicLinkInDirectoryPath(path.dirname(o.path))) throw new Error("archive directory changed"); if (statMigrationPath(o.path)) { if (d.phase === "unlink-pending") throw new Error("archive was recreated after claim"); const e = assertRecoveryOriginal(o.path, u, i); if (!e) throw new Error("artifact is unexpectedly missing"); await moveMigrationArtifact(o.path, d.claimPath, e, () => { r?.(); }, void 0, i); } r?.(); n(s); assertRecoveryOriginal(o.path, u, i); t.present = statMigrationPath(d.claimPath) !== void 0; d.phase = "unlink-pending"; } for (const e of o) { r?.(); writeSessionSqliteMigrationManifest(e); } for (const { item: e, artifact: t, disposal: n, present: r } of l) { c = e; if (hasSymbolicLinkInDirectoryPath(path.dirname(e.path))) throw new Error("archive directory changed"); if (statMigrationPath(e.path)) throw new Error("archive was recreated after claim"); assertRecoveryOriginal(e.path, t, i); if (r !== (statMigrationPath(n.claimPath) !== void 0)) throw new Error("disposal claim changed after intent"); } r?.(); for (const { item: e, refs: t } of l) { c = e; n(t); } for (const { item: e, artifact: t, disposal: n } of l) { c = e; const i = statMigrationPath(n.claimPath); if (i) { r?.(); fs.unlinkSync(n.claimPath); e.removedBytes = t.identity.size; } e.outcome = i ? "removed" : "disposed"; e.bytes = i ? t.identity.size : 0; e.reason = i ? "rollback-original-retired" : "completed-interrupted-disposal"; } const e = /* @__PURE__ */ new Set(); for (const { item: t, refs: i } of l) { c = t; const a = path.dirname(t.path); if (t.outcome === "removed" && !e.has(a)) { requireDirectorySync(await syncDirectory(a), "Recovery artifact removal"); e.add(a); } r?.(); n(i); for (const e of i) for (const n of movesFor(e, t.path)) n.artifact.disposal = { state: "disposed", disposedAt: (/* @__PURE__ */ new Date()).toISOString() }; } for (const e of o) { r?.(); writeSessionSqliteMigrationManifest(e); } } catch (t) { if (c) { c.outcome = "failed"; c.reason = "artifact-retirement-failed"; c.detail = String(t); } for (const t of e) if (t.outcome === "candidate") { t.outcome = "blocked"; t.reason = "retirement-stopped"; } } } //#endregion export { validateLegacySessionRecords as a, gatherLegacyArchiveCoverage as c, selectUnmanifestedRecovery as i, listUnreferencedJsonlFiles as l, retireSessionSqliteRecovery as n, appendLegacyHistoricalTranscripts as o, settleDuplicateSessionSqliteArchives as r, collectHistoricalArchiveSources as s, retireOwnedSessionSqliteRecovery as t, readLegacySessionRecords as u };