UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,622 lines • 108 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { c as readFileDescriptorBoundedSync } from "./boundary-file-read-BfaFLDqt.mjs";
import { i as resolveRealpathOrAbsolute } from "./boundary-path-C2gXEiXe.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside$1 } from "./path-guards-TIjxtj6H.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 FsSafeError } from "./fs-safe-BbWvmdVn.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { n as LEGACY_IMPLICIT_AGENT_ID } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { i as isPrimarySessionTranscriptFileName } from "./transcript-file-names-mCC_xfFb.mjs";
import { d as resolveTrajectoryPointerPath, s as isTrajectorySessionArtifactName, u as resolveTrajectoryPath } from "./artifacts-D7SzhQlr.mjs";
import { t as OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema-BDRJZxWF.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { p as syncDirectorySync, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs";
import { r as hashFileDescriptorSync } from "./file-descriptor-DQ-v5bLt.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { a as resolveSqliteDatabaseFilePaths, n as hasOrphanedSqliteSidecars } from "./sqlite-files-rWisKj_V.mjs";
import { a as classifySqliteFtsIntegrityFindings, r as assertSqliteIntegrity, t as SqliteIntegrityError } from "./sqlite-integrity-CCmEgO_m.mjs";
import { a as getCanonicalSqliteNamedIndexContracts } from "./sqlite-schema-contract-D3pR9vZs.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { d as tryReadJsonSync } from "./json-files-Cb1h8pYs.mjs";
import { n as createSqliteWorkerWriteAdmission } from "./sqlite-worker-store-D51tD0Vp.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs";
import { h as withDeferredPluginMigrationsCurrent, l as readDeferredPluginMigrations, t as DeferredPluginMigrationConflictError } from "./deferred-plugin-migrations-C_CU0aKR.mjs";
import { n as markLegacyMigrationSourceRemovedInDatabase } from "./state-migrations.receipts-CXYpigJ-.mjs";
import { r as loadConfig } from "./io.runtime-DsJ2dLCQ.mjs";
import { M as inspectSqliteRecoveryFiles, N as moveSqliteFilesAside } from "./agent-database-admission-CL6wHJ_N.mjs";
import { l as invalidateOpenClawAgentDatabaseIntegrityBeforeMutation } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { o as closeOpenClawAgentDatabaseByPathAsync } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import { n as clearOpenClawAgentDatabaseOpenFailure, r as isOpenClawAgentDatabaseOpen } from "./openclaw-agent-db-CwXW4hGa.mjs";
import { o as ensureOpenClawAgentDatabasePermissions } from "./openclaw-agent-db-schema-D-iWGl31.mjs";
import { a as resolveAllAgentSessionStoreTargetsSync, i as resolveAllAgentSessionStoreCandidateTargetsSync, l as resolveSessionStoreTargets, r as resolveAgentSessionStoreTargetsSync, s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs";
import { l as prepareLegacyAcpMigrationSource } from "./session-accessor.sqlite-acp-provenance-Clw97t0F.mjs";
import { t as loadExactSessionEntryCandidatesReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs";
import "./config-CMA-J084.mjs";
import { i as hasSqliteFileFamily, n as createRetainedAgentDatabaseMatcher } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { t as withAgentDatabaseMaintenanceLease } from "./openclaw-agent-db-maintenance-lease-Jvh6K3Fz.mjs";
import { i as normalizePersistedSessionEntryShape } from "./session-entry-shape-CqYv-iaf.mjs";
import { t as extractGeneratedTranscriptSessionId } from "./generated-transcript-session-id-CPClHaZf.mjs";
import { a as readLegacyPrimaryTranscriptIdentity, c as readSqliteEntryCount, d as resolveTargetSqlitePath, f as scanReadOnlySqliteActiveTranscriptFiles, i as projectExistingAgentDatabaseTargets, l as readTranscriptFingerprint, n as createTranscriptEventReader, o as readOnlySqliteDbStats, s as readOnlySqliteValidationSnapshot, t as countTranscriptEventsForPath, u as resolveTargetSqliteOptions } from "./session-sqlite-migration-readers-DbmEQzSW.mjs";
import { c as listLegacySessionTranscriptFiles, d as shouldFilterLegacySessionRecordsByTarget, l as readLegacySessionStoreEntries, s as isLegacySessionRecordOwnedByTarget, t as verifyCanonicalSessionTranscriptSources } from "./session-sqlite-transcript-verification-Bdys-Rbk.mjs";
import { C as moveMigrationArtifact, E as statMigrationPath, T as sameMigrationArtifact, a as collectRecordedConsumedArchives, b as writeSessionSqliteMigrationManifest, c as findLatestFailedSessionSqliteMigrationManifest, d as listSessionSqliteMigrationManifestPaths, f as migrationMoveKey, g as resolveSessionSqliteMigrationRunsDir, h as recordPlannedMigrationMoves, i as canonicalMigrationFilePath, l as hasSymbolicLinkInDirectoryPath, m as recordCompletedMigrationMoves, n as assertSafeSessionSqliteMigrationDirectory, o as createSessionSqliteMigrationRun, p as readSessionSqliteMigrationManifest, r as assertSafeSessionSqliteMigrationMove, s as filterRestoreManifestTargets, t as HISTORICAL_IMPORT_REASON, u as isRegularFileWithoutFollowingSymlinks, v as uniqueRestoreMoves, w as readMigrationArtifactIdentity, y as updateMigrationManifestTarget } from "./session-sqlite-migration-manifest-DwBodX3i.mjs";
import { c as recordDeferredPluginSessionImport, d as sessionSourceArchives, f as parseSessionImportReceipt, g as existingSessionSourcePaths, h as DeferredPluginSessionImportSchema, i as prepareSessionSourceVerification, m as readDeferredPluginSessionImportReceipt, n as hasDeferredPluginSessionImport, o as readDeferredPluginSessionImport, p as supersedeDeferredPluginSessionImport, s as readStaleDeferredPluginSessionImport, t as deferredPluginSessionStoreIds, u as resolveVerifiedSessionSource } from "./deferred-plugin-session-sources-BvErqlCR.mjs";
import { a as verifyDeferredSessionDatabase, i as sameSourceContent, n as databaseIdentity, o as verifyMissingDeferredSessionTranscript, r as preservesRecordedIndexValue, s as importSqliteSessionRowsBatch, t as captureDeferredPluginSessionSources } from "./deferred-plugin-session-verification-DM8JAFN6.mjs";
import { t as AGENT_FTS_SCHEMAS } from "./openclaw-agent-fts-schema-CoPVC2Y6.mjs";
import { r as migrateOpenClawAgentDatabaseForMaintenance, t as assertOpenClawAgentDatabaseForMaintenance } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs";
import { t as collectRecoveryInventory } from "./doctor-session-sqlite-recovery-inventory-nxlj5kaN.mjs";
import { a as validateLegacySessionRecords, c as gatherLegacyArchiveCoverage, l as listUnreferencedJsonlFiles, o as appendLegacyHistoricalTranscripts, r as settleDuplicateSessionSqliteArchives, s as collectHistoricalArchiveSources, u as readLegacySessionRecords } from "./doctor-session-sqlite-retirement-prAcoVwY.mjs";
import { n as assertDoctorSqliteMaintenancePathsNotAliased, r as isDestructiveDoctorSessionSqliteMode } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs";
import { t as selectSessionStoreMaintenanceTargets } from "./targets-maintenance-CIrepqtS.mjs";
import { t as resolveActiveSqliteTranscriptFile } from "./doctor-session-sqlite-transcript-file-B-CoR0xz.mjs";
import { i as writeSessionSqliteMigrationFailureReports, r as createSessionSqliteMigrationFailureIssue } from "./doctor-session-sqlite-failure-B-eegqk4.mjs";
import { a as isRetainedSourceSettlementIssue, i as isRetainedSourceIssue, n as createDoctorSessionSqliteTargetReport, r as isInformationalMissingSessionIndex, t as countBlockingSessionSqliteIssues } from "./doctor-session-sqlite-types-CboC48LX.mjs";
import { n as compactDoctorSqliteFile } from "./doctor-sqlite-compact-D8iufPYc.mjs";
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import os from "node:os";
import { isDeepStrictEqual } from "node:util";
import { safeStatSync } from "@openclaw/fs-safe/path";
import { setImmediate } from "node:timers/promises";
//#region src/commands/doctor-session-sqlite-compact.ts
/** Runs doctor-owned SQLite file compaction for migrated session stores. */
async function compactDoctorSessionSqliteTarget(e, t = {}) {
	const n = resolveTargetSqliteOptions(e, t.env);
	const r = resolveOpenClawAgentSqlitePath(n);
	const i = safeStatSync(`${r}-wal`)?.size ?? 0;
	const a = fs.lstatSync(r, { throwIfNoEntry: false });
	if (!a) return {
		dbSizeAfterBytes: 0,
		dbSizeBeforeBytes: 0,
		freelistAfterPages: 0,
		freelistBeforePages: 0,
		pageSizeBytes: 0,
		reclaimedBytes: 0,
		skipped: true,
		walSizeAfterBytes: i,
		walSizeBeforeBytes: i
	};
	if (!a.isFile()) throw new Error(`OpenClaw agent database is not a regular file: ${r}`);
	if (isOpenClawAgentDatabaseOpen(r)) throw new Error(`OpenClaw agent database ${r} is already open in this process. Stop OpenClaw and retry.`);
	const requireQuarantineCleared = () => {
		if (!clearOpenClawAgentDatabaseOpenFailure(r, { env: t.env })) throw new Error(`OpenClaw agent database ${r} was repaired, but its persisted quarantine record could not be cleared. Rerun openclaw doctor --fix so the database is not refused again.`);
	};
	const compactTarget = () => {
		invalidateOpenClawAgentDatabaseIntegrityBeforeMutation(r);
		const e = compactDoctorSqliteFile({
			operation: t.operation,
			afterSuccess: () => {
				requireQuarantineCleared();
				ensureOpenClawAgentDatabasePermissions(r, n);
			},
			sqlitePath: r,
			validateBeforeMutation: (e) => assertOpenClawAgentDatabaseForMaintenance(e, {
				agentId: n.agentId,
				pathname: r
			})
		});
		return {
			dbSizeAfterBytes: e.after.dbSizeBytes,
			dbSizeBeforeBytes: e.before.dbSizeBytes,
			freelistAfterPages: e.after.freelistPages,
			freelistBeforePages: e.before.freelistPages,
			pageSizeBytes: e.before.pageSizeBytes || e.after.pageSizeBytes,
			reclaimedBytes: e.reclaimedBytes,
			skipped: false,
			walSizeAfterBytes: e.after.walSizeBytes,
			walSizeBeforeBytes: e.before.walSizeBytes
		};
	};
	return t.operation === "import-finalize" ? withAgentDatabaseMaintenanceLease({ env: n.env }, async (e) => {
		await migrateOpenClawAgentDatabaseForMaintenance({
			agentId: n.agentId,
			pathname: r
		}, e);
		e.assertOwned();
		requireQuarantineCleared();
		return compactTarget();
	}) : compactTarget();
}
//#endregion
//#region src/commands/doctor-session-sqlite-diagnostics.ts
function countLegacyTranscript(e, t) {
	const n = countTranscriptEventsForPath(e.transcriptPath);
	if (n.status !== "ok") {
		t.issues.push({
			code: n.status === "missing" ? "transcript_missing" : "transcript_malformed",
			message: n.status === "missing" ? `Transcript file is missing: ${e.transcriptPath}` : n.message,
			sessionKey: e.sessionKey
		});
		return;
	}
	t.validatedEntries += 1;
	t.validatedTranscriptEvents += n.events;
}
function appendRetainedPluginSessionSourceIssue(e, t) {
	const n = t.length ? `remain pending for plugin(s): ${t.join(", ")}. Install the plugin and run openclaw doctor --fix to finish.` : "await archival. Run openclaw doctor --fix to finish.";
	e.issues.push({
		code: "plugin_migration_source_retained",
		message: `Session import is verified. Original session migration inputs, including unindexed history, ${n}`
	});
}
function appendActiveSqliteTranscriptFileIssues(e, t, n) {
	try {
		for (const { sessionKey: r, transcriptPath: i } of readActiveSqliteTranscriptFiles(e)) if (!n?.has(canonicalMigrationFilePath(i))) t.issues.push({
			code: "active_sqlite_transcript_jsonl",
			message: `SQLite-backed session has a legacy JSONL transcript awaiting verification: ${i}. Run openclaw doctor --fix or openclaw doctor --session-sqlite recover with the Gateway stopped to verify, import any missing events, and archive the original.`,
			sessionKey: r
		});
	} catch (e) {
		t.issues.push({
			code: "sqlite_active_transcript_scan_failed",
			message: `Could not scan SQLite-backed sessions for active JSONL transcript files: ${String(e)}`
		});
	}
}
function readActiveSqliteTranscriptFiles(e) {
	const t = [];
	const n = scanReadOnlySqliteActiveTranscriptFiles(e, (n, r, i) => {
		const a = resolveActiveSqliteTranscriptFile(e, {
			...i ? { sessionFile: i } : {},
			sessionId: r
		});
		if (a) t.push({
			sessionKey: n,
			sessionId: r,
			transcriptPath: a
		});
	});
	if (!n.ok) throw n.error;
	return t;
}
function appendSqliteDbStats(e, t) {
	const n = readOnlySqliteDbStats(e);
	if (!n.ok) {
		t.issues.push({
			code: "sqlite_corrupt",
			message: `SQLite database could not be inspected: ${String(n.error)}`
		});
		return;
	}
	t.dbStats = n.stats;
	if (n.stats.integrityCheck && n.stats.integrityCheck !== "ok") t.issues.push({
		code: "sqlite_integrity_check_failed",
		message: `SQLite quick_check reported: ${n.stats.integrityCheck}`
	});
}
async function compactSqliteDatabase(e, t, n = {}) {
	try {
		if (n.operation === "import-finalize") await closeOpenClawAgentDatabaseByPathAsync(resolveTargetSqlitePath(e));
		t.compact = await compactDoctorSessionSqliteTarget(e, n);
	} catch (e) {
		t.issues.push({
			code: "sqlite_compact_failed",
			message: `SQLite database compact failed: ${formatErrorMessage(e)}`
		});
	}
}
function summarizeDoctorSessionSqliteReport(e, t, n) {
	const sum = (e) => t.reduce((t, n) => t + e(n), 0);
	const archives = (e) => new Set(t.flatMap(e)).size;
	const r = /* @__PURE__ */ new Map();
	for (const e of t) r.set(e.sqlitePath, Math.max(r.get(e.sqlitePath) ?? 0, e.sqliteEntries));
	const i = e !== "restore" && e !== "recover";
	return {
		...n ? { migrationRun: {
			...n.manifest.failureReports ? {
				failureReportJsonPath: n.manifest.failureReports.jsonPath,
				failureReportMarkdownPath: n.manifest.failureReports.markdownPath
			} : {},
			manifestPath: n.manifestPath,
			runId: n.manifest.runId
		} } : {},
		mode: e,
		targets: t,
		totals: {
			...i ? { archivedLegacyStoreFiles: archives((e) => e.archivedLegacyStoreFiles ?? []) } : {},
			archivedTranscriptFiles: archives((e) => e.archivedTranscriptFiles),
			archivedUnreferencedJsonlFiles: archives((e) => e.archivedUnreferencedJsonlFiles),
			importedEntries: sum((e) => e.importedEntries),
			importedTranscriptEvents: sum((e) => e.importedTranscriptEvents),
			issues: sum((e) => e.issues.length),
			legacyEntries: sum((e) => e.legacyEntries),
			...i ? { reclaimedBytes: sum((e) => e.compact?.reclaimedBytes ?? 0) } : {},
			sqliteEntries: [...r.values()].reduce((e, t) => e + t, 0),
			targets: t.length,
			unreferencedJsonlFiles: sum((e) => e.unreferencedJsonlFiles.length),
			validatedEntries: sum((e) => e.validatedEntries),
			validatedTranscriptEvents: sum((e) => e.validatedTranscriptEvents)
		}
	};
}
//#endregion
//#region src/commands/doctor-session-sqlite-active.ts
/** Old imports can leave active originals outside a later plugin receipt. Never replay their index. */
async function prepareActiveSqliteTranscriptSettlement(e) {
	const t = [];
	const n = {
		...e.target,
		sqlitePath: resolveTargetSqlitePath(e.target, e.env)
	};
	let r;
	try {
		r = readActiveSqliteTranscriptFiles(n);
	} catch (n) {
		e.report.issues.push({
			code: "sqlite_active_transcript_scan_failed",
			message: formatErrorMessage(n)
		});
		return t;
	}
	for (const i of r) {
		if (e.excludedPaths.has(canonicalMigrationFilePath(i.transcriptPath))) continue;
		try {
			const r = readTranscriptFingerprint(i.transcriptPath);
			readMigrationArtifactIdentity(i.transcriptPath, 1n, r);
			const a = readLegacyPrimaryTranscriptIdentity(i.transcriptPath, i.transcriptPath, void 0, true);
			if (!a) continue;
			if (a.sessionId !== i.sessionId) throw new Error("Legacy transcript has no matching primary session identity");
			const o = [{
				path: i.transcriptPath,
				sessionId: i.sessionId
			}];
			const verify = (t = "contained") => verifyCanonicalSessionTranscriptSources({
				target: n,
				sources: o,
				env: e.env,
				mode: t
			});
			let s = verify("appendable");
			if (!s) throw new Error("Missing history requires legacy format or branch repair before it can be appended");
			if (s.missingEvents > 0) {
				const [t] = await importSqliteSessionRowsBatch([{
					agentId: n.agentId,
					storePath: n.sqlitePath,
					env: e.env,
					sessionKey: i.sessionKey,
					entry: {
						sessionId: i.sessionId,
						updatedAt: 0
					},
					historicalOnly: true,
					preserveExactStoredKey: true,
					readTranscriptEvents: createTranscriptEventReader(i.transcriptPath, i.sessionId, false, r)
				}]);
				e.report.importedTranscriptEvents += t.transcriptEvents;
				s = verify();
			}
			if (!s) throw new Error("The original transcript order and content could not be verified in SQLite");
			readMigrationArtifactIdentity(i.transcriptPath, 1n, r);
			e.report.validatedEntries += 1;
			e.report.validatedTranscriptEvents += s.events;
			t.push({
				sessionKey: i.sessionKey,
				entry: {
					sessionId: i.sessionId,
					updatedAt: 0
				},
				transcriptPath: i.transcriptPath,
				transcriptDependencies: [i.transcriptPath],
				sourceFingerprint: r,
				recovery: {
					complete: true,
					repaired: false,
					events: s.events,
					sqliteEvents: s.sqliteEvents
				}
			});
		} catch (t) {
			e.report.issues.push({
				code: "active_sqlite_transcript_verification_failed",
				sessionKey: i.sessionKey,
				message: `${i.transcriptPath}: ${formatErrorMessage(t)}. Original retained. Compare the named events with a verified backup, restore a corrected JSONL at this path, then rerun openclaw doctor --session-sqlite recover.`
			});
		}
	}
	return t;
}
//#endregion
//#region src/commands/doctor-session-sqlite-archive.ts
/** Plans Doctor archive paths; publication and receipts remain with the migration owner. */
function planImportedTranscriptArtifactsToArchive(e, t, n, r, i) {
	const a = [];
	const addMove = (n, o) => {
		if (i && !i.has(canonicalMigrationFilePath(n))) return;
		const s = planSessionJsonlArchiveMove({
			archiveKey: t,
			kind: o,
			reservedArchivePaths: r,
			sessionKey: t,
			sourcePathRaw: n,
			target: e
		});
		r.add(s.archivePath);
		a.push(s);
	};
	addMove(n, "transcript");
	for (const e of [resolveTrajectoryPath, resolveTrajectoryPointerPath]) {
		const t = e(n);
		if (t && fs.existsSync(t)) addMove(t, "trajectory");
	}
	return a;
}
function planSessionJsonlArchiveMove(e) {
	const t = path.resolve(e.sourcePathRaw);
	if (!fs.lstatSync(t).isFile()) throw new Error("source is not a regular file");
	const n = path.join(resolveRealpathOrAbsolute(path.dirname(t)), path.basename(t));
	const r = resolveRealpathOrAbsolute(path.dirname(path.resolve(e.target.storePath)));
	if (path.dirname(n) !== r) throw new Error(`Migration source is outside the target sessions directory: ${n}`);
	const i = path.join(path.dirname(r), "session-sqlite-import-archive");
	assertSafeSessionSqliteMigrationDirectory(i);
	fs.mkdirSync(i, { recursive: true });
	assertSafeSessionSqliteMigrationDirectory(i);
	const slug = (e, t, n) => e.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, t) || n;
	const a = slug(path.basename(e.sourcePathRaw), 160, "artifact");
	const o = `${slug(e.archiveKey, 120, "session")}.${a}`;
	const s = createHash("sha256").update(JSON.stringify([e.archiveKey, path.basename(n)])).digest("hex").slice(0, 16);
	const c = Date.now();
	for (let t = 0; t < 100; t += 1) {
		const r = `.imported-${c}${t === 0 ? "" : `.${t}`}`;
		const a = Buffer.byteLength(o + r, "utf8") <= 255 ? o + r : `${o.slice(0, 255 - Buffer.byteLength(`.${s}${r}`, "utf8"))}.${s}${r}`;
		const l = path.join(i, a);
		if (fs.existsSync(l) || e.reservedArchivePaths?.has(l)) continue;
		return {
			archivePath: l,
			kind: e.kind,
			...e.sessionKey ? { sessionKey: e.sessionKey } : {},
			sourcePath: n
		};
	}
	throw new Error(`Could not archive ${a} for ${e.archiveKey}`);
}
async function archiveImportedLegacySessionStores(e, t, n, r, i) {
	const a = groupPluginRecords(e, (e) => e.target.storePath);
	for (const [e, o] of a) {
		r?.();
		if (!n.indexIdentities.has(e) && !fs.existsSync(e)) continue;
		if (!n.selectedStorePaths.has(e) || o.some(({ report: e }) => countBlockingSessionSqliteIssues(e) > 0 || e.issues.some((e) => e.code === "active_sqlite_transcript_jsonl"))) continue;
		let a = false;
		try {
			const s = n.indexIdentities.get(e);
			if (!s || !sameMigrationArtifact(readMigrationArtifactIdentity(e), s)) throw new Error("Session index changed after import; retaining the unverified original");
			const c = planSessionJsonlArchiveMove({
				archiveKey: "legacy-store",
				kind: "legacy-store",
				sourcePathRaw: e,
				target: o[0].target
			});
			const l = t.manifest.targets.filter((t) => t.storePath === e).flatMap((e) => e.plannedMoves.filter((e) => e.kind === "transcript"));
			const u = o.every(({ validated: e, report: t }) => e && t.issues.every((e) => e.code === "historical_duplicate_settled")) && l.every((e) => e.artifact?.classification !== "protected");
			const d = o.flatMap(({ records: e }) => e.flatMap((e) => e.transcriptDependencies)).map(canonicalMigrationFilePath);
			c.artifact = {
				identity: s,
				classification: u ? "imported" : "protected",
				reason: u ? "verified-index-import" : "incomplete-index-import",
				dependencies: [...new Set(d)],
				disposal: { state: "retained" }
			};
			for (const { target: e } of o) {
				r?.();
				recordPlannedMigrationMoves(t, e, [c]);
				assertSafeSessionSqliteMigrationMove(c, e);
			}
			a = true;
			r?.();
			await moveMigrationArtifact(c.sourcePath, c.archivePath, s, r ? () => {
				r();
			} : void 0, i);
			r?.();
			for (const { target: e, report: n } of o) {
				recordCompletedMigrationMoves(t, e, [c]);
				n.archivedLegacyStoreFiles.push(c.archivePath);
			}
		} catch (n) {
			if (n instanceof DeferredPluginMigrationConflictError && n.pending.length > 0) break;
			for (const { report: i, target: s } of o) {
				i.issues.push({
					code: "legacy_store_archive_failed",
					message: `${e}: ${formatErrorMessage(n)}`
				});
				if (!a) {
					r?.();
					updateMigrationManifestTarget(t, s, i.issues);
				}
			}
		}
	}
}
//#endregion
//#region src/commands/doctor-session-sqlite-import.ts
const SESSION_IMPORT_BATCH_SIZE = 256;
async function importLegacySessionRecords({ target: e, env: t, expectedIndexIdentity: n, recoveryInventory: r }, i, a, o) {
	if (i.length === 0) return;
	try {
		const o = Boolean(r?.report.artifacts.some((e) => ["unreadable-manifest", "manifest-directory-alias"].includes(e.reason)));
		let s;
		try {
			if (!o) s = prepareRestoredSessionIndex({
				target: e,
				env: t,
				expectedIndexIdentity: n,
				recoveryInventory: r
			});
		} catch (e) {
			a.issues.push({
				code: "legacy_import_deferred",
				message: `${formatErrorMessage(e)}. Originals retained; preserve the files and receipts, restore verified recovery evidence, then rerun openclaw doctor --fix.`
			});
			return;
		}
		const c = /* @__PURE__ */ new Set();
		const l = readOnlySqliteValidationSnapshot(e);
		if (!l.ok) {
			a.issues.push({
				code: "legacy_import_deferred",
				message: `Cannot verify the destination for ${e.storePath}: ${formatErrorMessage(l.error)}. Originals retained; repair the named SQLite destination before retrying openclaw doctor --fix.`
			});
			return;
		}
		for (let n = 0; n < i.length; n += SESSION_IMPORT_BATCH_SIZE) {
			const r = i.slice(n, n + SESSION_IMPORT_BATCH_SIZE).flatMap((n) => {
				n.preserveCurrentSession ||= o || Boolean(s);
				try {
					const r = prepareLegacySessionImport(e, n, a, c, l.snapshot, t, o);
					return r ? [{
						...r,
						params: {
							...r.params,
							env: t
						},
						record: n
					}] : [];
				} catch (t) {
					a.issues.push({
						code: "legacy_import_deferred",
						sessionKey: n.sessionKey,
						message: `${n.transcriptPath ?? e.storePath}: ${formatErrorMessage(t)}. Original retained; verify this source against a backup and rerun openclaw doctor --fix.`
					});
					return [];
				}
			});
			const u = await importSqliteSessionRowsBatch(r.map((e, t) => ({
				...e.params,
				...t === 0 && s ? { beforePersistentApply: s } : {}
			})));
			for (const [e, t] of u.entries()) {
				const n = r[e]?.record;
				const i = r[e]?.recovery ?? t.recovery;
				if (n && i) n.recovery = i;
			}
			a.importedEntries += u.length;
			a.importedTranscriptEvents += u.reduce((e, t) => e + t.transcriptEvents, 0);
			a.issues.push(...r.flatMap((e) => e.issue ? [e.issue] : []));
			await setImmediate();
		}
	} catch (e) {
		let t = e;
		a.issues.push({
			code: "sqlite_import_failed",
			message: formatErrorMessage(e)
		});
		if (o) {
			o.manifest.failedAt = (/* @__PURE__ */ new Date()).toISOString();
			try {
				updateMigrationManifestTarget(o, a, a.issues);
			} catch (n) {
				t = new AggregateError([e, n], `${formatErrorMessage(e)}; could not record session SQLite migration failure: ${formatErrorMessage(n)}`, { cause: e });
			}
		}
		throw t;
	}
}
function prepareRestoredSessionIndex(e) {
	const { expectedIndexIdentity: t, recoveryInventory: n, target: r } = e;
	if (!t || !n) return;
	const i = canonicalMigrationFilePath(r.storePath);
	const a = resolveTargetSqlitePath(r, e.env);
	const o = /* @__PURE__ */ new Map();
	const s = /* @__PURE__ */ new Map();
	const hasCompletedMove = (e, t) => {
		let n = s.get(e);
		if (!n) {
			n = new Set(e.completedMoves.map(migrationMoveKey));
			s.set(e, n);
		}
		return n.has(t);
	};
	let c = false;
	for (const e of n.references.values()) for (const n of e) {
		if (n.move.kind !== "legacy-store" || n.move.sourcePath !== i || !n.consumedByRestore && !n.run.manifest.restore?.restoredFiles.includes(i) && !hasCompletedMove(n.target, migrationMoveKey(n.move))) continue;
		const e = n.move.artifact;
		if (!e) {
			assertSafeSessionSqliteMigrationMove(n.move, n.target);
			if (statMigrationPath(n.move.archivePath)) {
				const e = readMigrationArtifactIdentity(n.move.archivePath);
				if (e.size !== t.size || e.sha256 !== t.sha256) continue;
				o.set(n.move.archivePath, e);
			}
		}
		if (e && (e.identity.dev !== t.dev || e.identity.ino !== t.ino)) continue;
		const s = filterRestoreManifestTargets(n.run.manifest, [{
			agentId: r.agentId,
			storePath: i,
			sqlitePath: a
		}]).includes(n.target);
		if (e && (!sameMigrationArtifact(e.identity, t) || !n.consumedByRestore || e.disposal.state !== "retained") || n.target.storePath !== i || n.target.agentId === r.agentId && !s) throw new Error(`Restored session index evidence cannot be verified: ${i}`);
		assertSafeSessionSqliteMigrationMove(n.move, n.target);
		const l = readMigrationArtifactIdentity(n.run.manifestPath);
		if (JSON.stringify(readSessionSqliteMigrationManifest(n.run.manifestPath)) !== JSON.stringify(n.run.manifest) || !sameMigrationArtifact(l, readMigrationArtifactIdentity(n.run.manifestPath))) throw new Error(`Session restore receipt changed: ${n.run.manifestPath}`);
		o.set(n.run.manifestPath, l);
		c ||= s;
	}
	if (o.size === 0) return;
	if (!c) throw new Error(`Restored session index evidence cannot be verified: ${i}`);
	const assertCurrent = () => {
		for (const e of [
			i,
			a,
			...o.keys()
		]) if (hasSymbolicLinkInDirectoryPath(path.dirname(e))) throw new Error(`Session restore path changed: ${e}`);
		for (const [e, n] of [[i, t], ...o]) if (!sameMigrationArtifact(n, readMigrationArtifactIdentity(e))) throw new Error(`Session restore source or receipt changed: ${e}`);
	};
	assertCurrent();
	return assertCurrent;
}
function prepareLegacySessionImport(e, t, n, r, i, a, o) {
	if (t.historical && t.transcriptPath && !sameMigrationArtifact(t.historical.identity, readMigrationArtifactIdentity(t.transcriptPath))) {
		n.issues.push({
			code: "historical_transcript_deferred",
			sessionKey: t.sessionKey,
			message: `${t.historical.originalPath}: source changed after discovery; retained without importing`
		});
		return;
	}
	const s = t.transcriptPath ? `${t.entry.sessionId}\0${t.transcriptPath}` : void 0;
	const c = s !== void 0 && !r.has(s) && t.transcriptPath && fs.existsSync(t.transcriptPath) ? readTranscriptFingerprint(t.transcriptPath) : void 0;
	t.sourceFingerprint = c;
	const l = countTranscriptEventsForPath(t.transcriptPath);
	const u = i.sessionKeysBySessionId.get(t.entry.sessionId);
	if (t.preserveCurrentSession && u && u !== t.sessionKey) throw new Error(`Historical transcript ${t.entry.sessionId} already belongs to ${u}`);
	if (o && l.status === "malformed" && (i.transcriptEventCountsBySessionId.get(t.entry.sessionId) ?? 0) > 0) throw new Error(l.message);
	const d = readLegacyTranscriptMtimeMs(t);
	const f = normalizePersistedSessionEntryShape(t.entry, { sessionKey: t.sessionKey });
	const p = {
		historicalOnly: Boolean(t.historical || t.preserveCurrentSession),
		allowMalformedRowRepair: true,
		repairLegacyTranscript: true,
		agentId: e.agentId,
		entry: {
			...f ?? t.entry,
			sessionId: t.entry.sessionId
		},
		...!t.historical && f?.acp ? { legacyAcpMigrationSource: prepareLegacyAcpMigrationSource({
			sourcePath: e.storePath,
			sourceSessionKey: t.sessionKey,
			sessionId: f.sessionId,
			lifecycleRevision: f.lifecycleRevision,
			meta: f.acp
		}) } : {},
		preserveExactStoredKey: true,
		sessionKey: t.sessionKey,
		storePath: e.sqlitePath ?? e.storePath
	};
	let m;
	if (l.status === "missing") {
		if (i.sessionIdsBySessionKey.get(t.sessionKey) === t.entry.sessionId) {
			n.validatedEntries += 1;
			n.validatedTranscriptEvents += i.transcriptEventCountsBySessionId.get(t.entry.sessionId) ?? 0;
			return;
		}
		return {
			issue: {
				code: "transcript_missing",
				message: `Transcript file is missing: ${t.transcriptPath}`,
				sessionKey: t.sessionKey
			},
			params: p,
			recovery: m
		};
	}
	if (l.status === "ok" && c && t.transcriptPath && (i.transcriptEventCountsBySessionId.get(t.entry.sessionId) ?? 0) > 0) try {
		const r = verifyCanonicalSessionTranscriptSources({
			target: {
				...e,
				sqlitePath: n.sqlitePath
			},
			sources: [{
				path: t.transcriptPath,
				sessionId: t.entry.sessionId,
				originalPath: t.historical?.originalPath ?? t.transcriptPath
			}],
			env: a,
			mode: "appendable"
		});
		if (!r) throw new Error("Missing history requires legacy format or branch repair before it can be appended");
		if (r.missingEvents === 0) m = {
			complete: true,
			repaired: false,
			events: r.events,
			sqliteEvents: r.sqliteEvents
		};
	} catch (e) {
		n.issues.push({
			code: o ? "legacy_import_deferred" : "sqlite_transcript_count_mismatch",
			sessionKey: t.sessionKey,
			message: `${t.transcriptPath}: ${formatErrorMessage(e)}. Original retained. Compare the named events with a verified backup, restore a corrected JSONL at this path, then rerun openclaw doctor --session-sqlite recover.`
		});
		return;
	}
	if (s) r.add(s);
	return {
		recovery: m,
		...l.status === "malformed" ? { issue: {
			code: "transcript_malformed",
			message: l.message,
			sessionKey: t.sessionKey
		} } : {},
		params: {
			...p,
			...t.transcriptPath && c ? { readTranscriptEvents: createTranscriptEventReader(t.transcriptPath, t.entry.sessionId, l.status === "malformed", c, t.historical?.originalPath ?? t.transcriptPath) } : {},
			...d !== void 0 ? { transcriptMtimeMs: d } : {}
		}
	};
}
function readLegacyTranscriptMtimeMs(e) {
	if (!e.transcriptPath) return;
	try {
		const t = Math.floor(fs.statSync(e.transcriptPath).mtimeMs);
		return Number.isFinite(t) && t >= 0 ? t : void 0;
	} catch {
		return;
	}
}
//#endregion
//#region src/commands/doctor-session-sqlite-missing-index.ts
/** Missing index receipts describe history; only unimported transcript content requires action. */
function createMissingSessionIndexVerifier(e) {
	let t;
	return (n) => {
		if (n.issues.length > 0) return false;
		try {
			if (statMigrationPath(n.storePath)) return false;
			t ??= collectRecoveryInventory(e);
			const r = [...t.references.values()].filter((e) => e.every((e) => e.trusted && !e.consumedByRestore && e.target.agentId === n.agentId && e.target.storePath === n.storePath && e.target.sqlitePath === n.sqlitePath && e.move.kind === "legacy-store" && e.move.artifact?.classification === "protected" && e.move.artifact.reason === "incomplete-index-import" && e.move.artifact.disposal.state === "retained" && !statMigrationPath(e.move.sourcePath) && !statMigrationPath(e.move.archivePath)));
			if (r.length === 0) return false;
			const i = readOnlySqliteValidationSnapshot(n);
			const a = readOnlySqliteDbStats(n);
			if (!i.ok || !a.ok || a.stats.integrityCheck !== "ok") return false;
			const o = listLegacySessionTranscriptFiles(path.dirname(n.storePath)).map((e) => {
				readMigrationArtifactIdentity(e);
				const t = readLegacyPrimaryTranscriptIdentity(e, e);
				if (!t || !i.snapshot.sessionKeysBySessionId.has(t.sessionId)) throw new Error("Legacy transcript has no verified session owner");
				return {
					path: e,
					sessionId: t.sessionId
				};
			});
			const s = new Set(o.map((e) => e.path));
			const c = r.every((e) => e.every((e) => e.move.artifact.dependencies.every((e) => !isPrimarySessionTranscriptFileName(path.basename(e)) || s.has(e))));
			if (o.length === 0 || !c) return false;
			const l = verifyCanonicalSessionTranscriptSources({
				target: n,
				sources: o,
				env: e.env
			});
			if (!l) return false;
			n.validatedEntries = l.entries;
			n.validatedTranscriptEvents = l.events;
			n.issues.push({
				code: "legacy_index_informational",
				message: `${n.storePath}: Stored SQLite transcripts are complete. The legacy index source and archive are missing; legacy index entries are informational. No import is needed.`
			});
			return true;
		} catch {
			return false;
		}
	};
}
//#endregion
//#region src/commands/doctor-session-sqlite-restore.ts
async function restoreSessionSqliteMigrationRuns(e) {
	return restoreManifestContexts(loadRestoreManifestContexts(listSessionSqliteMigrationManifestPaths(e.env).toReversed(), e.trustedTargets), e.env);
}
async function restoreManifestContexts(e, t) {
	const n = emptyRestoreReport();
	await reconcileRestorePublications(e, t);
	const r = createRestorePlan(e);
	for (const { manifest: t, manifestPath: i, targets: a } of e) {
		const e = emptyRestoreReport(i);
		n.manifestPaths.push(i);
		for (const n of a) for (const a of uniqueRestoreMoves(n)) await restoreMigrationMove({
			manifest: t,
			manifestPath: i,
			target: n,
			move: a,
			restorePlan: r,
			restoreReport: e
		});
		const o = collectRecordedConsumedArchives(t);
		t.restore = {
			attemptedAt: (/* @__PURE__ */ new Date()).toISOString(),
			...o.size > 0 ? { consumedArchives: [...o].toSorted() } : {},
			conflicts: e.conflicts,
			restoredFiles: e.restoredFiles,
			skippedFiles: e.skippedFiles,
			status: resolveRestoreStatus(e)
		};
		for (const t of e.conflicts) n.conflicts.push(t);
		for (const t of e.restoredFiles) n.restoredFiles.push(t);
		for (const t of e.skippedFiles) n.skippedFiles.push(t);
		writeSessionSqliteMigrationManifest({
			manifest: t,
			manifestPath: i
		});
	}
	return n;
}
/** Undo only recorded, still-linked publication intermediates before a fresh import or restore. */
async function reconcileSessionSqliteMigrationPublications(e) {
	await reconcileRestorePublications(loadRestoreManifestContexts(listSessionSqliteMigrationManifestPaths(e.env), e.trustedTargets), e.env, e.sourcePath);
}
async function reconcileRestorePublications(e, t, n) {
	const r = path.dirname(canonicalMigrationFilePath(path.join(resolveStateDir(t), "anchor")));
	for (const t of e) for (const e of t.targets) for (const i of uniqueRestoreMoves(e)) {
		if (n && canonicalMigrationFilePath(n) !== i.sourcePath || !i.artifact || i.artifact.disposal.state !== "retained") continue;
		const a = statMigrationPath(i.sourcePath);
		const o = statMigrationPath(i.archivePath);
		if (!a || !o || !a.isFile() || !o.isFile() || a.dev !== o.dev || a.ino !== o.ino || a.nlink !== 2 || o.nlink !== 2) continue;
		if (![
			e.storePath,
			e.sqlitePath,
			i.archivePath
		].every((e) => isPathInside$1(r, e))) continue;
		assertSafeSessionSqliteMigrationMove(i, e);
		assertDoctorSqliteMaintenancePathsNotAliased("session recovery publication", [t.manifestPath, ...resolveSqliteDatabaseFilePaths(e.sqlitePath)], [r]);
		await moveMigrationArtifact(i.archivePath, i.sourcePath, readRestoreArchiveIdentity(i, 2n), () => {
			assertSafeSessionSqliteMigrationMove(i, e);
			recordRestoredMigrationMove(t.manifest, t.manifestPath, i);
		});
	}
}
function recordRestoredMigrationMove(e, t, n) {
	requireDirectorySync(syncDirectorySync(path.dirname(path.dirname(n.sourcePath))), "Restored session directory");
	const r = collectRecordedConsumedArchives(e);
	r.add(n.archivePath);
	e.restore = {
		attemptedAt: (/* @__PURE__ */ new Date()).toISOString(),
		consumedArchives: [...r].toSorted(),
		conflicts: [],
		restoredFiles: [.../* @__PURE__ */ new Set([...e.restore?.restoredFiles ?? [], n.sourcePath])],
		skippedFiles: [],
		status: "restored"
	};
	writeSessionSqliteMigrationManifest({
		manifest: e,
		manifestPath: t
	});
}
function loadRestoreManifestContexts(e, t) {
	const n = [];
	for (const r of e) {
		const e = statMigrationPath(r);
		const i = e?.isFile() && e.nlink === 1 && !hasSymbolicLinkInDirectoryPath(path.dirname(r)) ? readSessionSqliteMigrationManifest(r) : void 0;
		if (!i) continue;
		const a = filterRestoreManifestTargets(i, t);
		if (a.length > 0) n.push({
			manifest: i,
			manifestPath: r,
			targets: a
		});
	}
	return n;
}
/**
* Resolve every duplicate destination before moving an archive. A missing archive only disappears
* from the conflict set when its own manifest proves that an earlier restore consumed it.
*/
function createRestorePlan(e) {
	const t = /* @__PURE__ */ new Map();
	const n = /* @__PURE__ */ new Map();
	for (const r of e) {
		const e = collectRecordedConsumedArchives(r.manifest);
		for (const i of r.targets) for (const a of uniqueRestoreMoves(i)) {
			if (a.artifact && a.artifact.disposal.state !== "retained") {
				t.set(restoreMovePlanKey(r.manifestPath, a), {
					action: "conflict",
					reason: a.artifact.disposal.state === "disposed" ? "rollback original was intentionally disposed by update cleanup" : "rollback original has pending cleanup; finish cleanup before restore"
				});
				continue;
			}
			const i = n.get(a.sourcePath) ?? [];
			i.push({
				consumed: e.has(a.archivePath),
				context: r,
				move: a
			});
			n.set(a.sourcePath, i);
		}
	}
	for (const [e, r] of n) {
		if (fs.existsSync(e) || r.length === 1) {
			for (const e of r) t.set(restoreMovePlanKey(e.context.manifestPath, e.move), { action: "standard" });
			continue;
		}
		const n = [];
		let i = false;
		for (const e of r) {
			const r = restoreMovePlanKey(e.context.manifestPath, e.move);
			const a = inspectRestoreArchive(e.move);
			if (a.state === "available") {
				n.push({
					...e,
					snapshot: a.snapshot
				});
				continue;
			}
			if (a.state === "missing" && e.consumed) {
				t.set(r, { action: "skip-consumed" });
				continue;
			}
			i = true;
			t.set(r, {
				action: "conflict",
				reason: a.state === "missing" ? "archive is missing without a recorded prior restore; refusing another candidate" : a.reason
			});
		}
		if (i) {
			setRestoreCandidateConflicts(t, n, "another archive for this source is unavailable without prior restore evidence; refusing automatic selection");
			continue;
		}
		if (n.length === 0) continue;
		if (new Set(n.map((e) => e.move.kind)).size !== 1) {
			setRestoreCandidateConflicts(t, n, "recorded archives disagree on artifact kind; refusing automatic selection");
			continue;
		}
		const a = selectRestoreCandidate(n);
		if (!a) {
			setRestoreCandidateConflicts(t, n, n[0]?.move.kind === "legacy-store" ? "multiple distinct nonempty session indexes require explicit archive selection" : "multiple distinct archives require explicit archive selection");
			continue;
		}
		const o = restoreMovePlanKey(a.context.manifestPath, a.move);
		for (const e of n) {
			const n = restoreMovePlanKey(e.context.manifestPath, e.move);
			t.set(n, n === o ? {
				action: "restore",
				snapshot: e.snapshot
			} : { action: "skip-superseded" });
		}
	}
	return t;
}
function selectRestoreCandidate(e) {
	if (new Set(e.map((e) => e.snapshot.digest)).size === 1) return e[0];
	if (e[0]?.move.kind !== "legacy-store") return;
	const t = e.filter((e) => (e.snapshot.legacyEntryCount ?? 0) > 0);
	const n = new Set(t.map((e) => e.snapshot.digest));
	if (n.size === 0) return e[0];
	return n.size === 1 ? t[0] : void 0;
}
function setRestoreCandidateConflicts(e, t, n) {
	for (const r of t) e.set(restoreMovePlanKey(r.context.manifestPath, r.move), {
		action: "conflict",
		reason: n
	});
}
function restoreMovePlanKey(e, t) {
	return `${e}\u0000${migrationMoveKey(t)}`;
}
function inspectRestoreArchive(e) {
	if (hasSymbolicLinkInDirectoryPath(path.dirname(e.archivePath))) return {
		state: "invalid",
		reason: "archive parent is a symbolic link; refusing restore"
	};
	let t;
	try {
		t = fs.lstatSync(e.archivePath);
	} catch (e) {
		const t = isRecord(e) ? e.code : void 0;
		return t === "ENOENT" || t === "ENOTDIR" ? { state: "missing" } : {
			state: "invalid",
			reason: "archive could not be inspected; refusing restore"
		};
	}
	if (!t.isFile()) return {
		state: "invalid",
		reason: "archive is not a regular file; refusing restore"
	};
	const n = {
		state: "invalid",
		reason: "archive changed while it was inspected; refusing restore"
	};
	let r;
	try {
		const i = process.platform === "win32" ? "r" : fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
		r = fs.openSync(e.archivePath, i);
		const a = fs.fstatSync(r);
		if (!a.isFile() || a.dev !== t.dev || a.ino !== t.ino) return n;
		let o;
		let s;
		if (e.kind === "legacy-store") {
			const e = readFileDescriptorBoundedSync(r, a.size);
			o = createHash("sha256").update(e).digest("hex");
			let t;
			try {
				t = JSON.parse(e.toString("utf-8"));
			} catch {
				return {
					state: "invalid",
					reason: "session index archive is not valid JSON; refusing automatic selection"
				};
			}
			if (!isRecord(t)) return {
				state: "invalid",
				reason: "session index archive is not a JSON object; refusing automatic selection"
			};
			s = Object.keys(t).length;
		} else {
			const e = hashFileDescriptorSync(r, a.size);
			if (e.sizeBytes !== a.size) throw new Error("archive changed while it was inspected");
			o = e.sha256;
		}
		const c = fs.lstatSync(e.archivePath);
		if (c.dev !== a.dev || c.ino !== a.ino || c.size !== a.size) return n;
		return {
			state: "available",
			snapshot: {
				digest: o,
				...s === void 0 ? {} : { legacyEntryCount: s },
				size: a.size
			}
		};
	} catch (t) {
		if (e.kind !== "legacy-store" && t instanceof FsSafeError && t.code === "too-large") return n;
		const r = isRecord(t) ? t.code : void 0;
		return r === "ENOENT" || r === "ENOTDIR" ? { state: "missing" } : {
			state: "invalid",
			reason: "archive could not be read safely; refusing restore"
		};
	} finally {
		if (r !== void 0) fs.closeSync(r);
	}
}
async function restoreSessionSqliteMigrationRun(e) {
	const t = emptyRestoreReport(e.manifestPath);
	const n = readSessionSqliteMigrationManifest(e.manifestPath);
	const r = n ? filterRestoreManifestTargets(n, e.trustedTargets) : [];
	if (!n || r.length === 0) {
		t.conflicts.push({
			archivePath: e.manifestPath,
			reason: n ? "manifest does not match a trusted session target" : "manifest is missing or unreadable",
			sourcePath: e.manifestPath
		});
		return t;
	}
	return restoreManifestContexts([{
		manifest: n,
		manifestPath: e.manifestPath,
		targets: r
	}], e.env ?? process.env);
}
function emptyRestoreReport(e) {
	return {
		conflicts: [],
		manifestPaths: e === void 0 ? [] : [e],
		restoredFiles: [],
		skippedFiles: []
	};
}
function readRestoreArchiveIdentity(e, t = 1n) {
	const n = readMigrationArtifactIdentity(e.archivePath, t);
	if (e.artifact && !sameMigrationArtifact(n, e.artifact.identity, { ignoreDevice: true })) throw new Error("archive identity or contents changed; refusing restore");
	return n;
}
async function restoreMigrationMove(e) {
	const { manifest: t, manifestPath: n, target: r, move: i, restorePlan: a, restoreReport: o } = e;
	const recordConflict = (e) => {
		o.conflicts.push({
			archivePath: i.archivePath,
			reason: e,
			sourcePath: i.sourcePath
		});
	};
	const s = a.get(restoreMovePlanKey(n, i)) ?? { action: "standard" };
	if (s.action === "conflict") {
		recordConflict(s.reason);
		return;
	}
	if (s.action === "skip-consumed" || s.action === "skip-superseded") {
		o.skippedFiles.push(i.sourcePath);
		return;
	}
	const c = statMigrationPath(i.sourcePath) !== void 0;
	const l = statMigrationPath(i.archivePath) !== void 0;
	if (c || !l) {
		if (c && !l) o.skippedFiles.push(i.sourcePath);
		else recordConflict(c ? "source and archive both exist; refusing to overwrite source" : "source and archive are both missing");
		return;
	}
	try {
		if (!isRegularFileWithoutFollowingSymlinks(i.archivePath)) throw new Error("archive is not a regular file; refusing restore");
		assertRestoreDirectories(i);
		fs.mkdirSync(path.dirname(i.sourcePath), {
			recursive: true,
			mode: 448
		});
		assertRestoreDirectories(i);
		const e = readRestoreArchiveIdentity(i);
		if (s.action === "restore" && (e.sha256 !== s.snapshot.digest || e.size !== s.snapshot.size)) throw new Error("archive changed after restore planning; refusing restore");
		if (!i.artifact) {
			i.artifact = {
				identity: e,
				classification: "protected",
				reason: "historical-restore-original",
				dependencies: i.kind === "legacy-store" ? uniqueRestoreMoves(r).filter((e) => e.kind === "transcript").map((e) => e.sourcePath) : [],
				disposal: { state: "retained" }
			};
			for (const e of [...r.plannedMoves, ...r.completedMoves]) if (migrationMoveKey(e) === migrationMoveKey(i)) e.artifact = i.artifact;
			writeSessionSqliteMigrationManifest({
				manifest: t,
				manifestPath: n
			});
		}
		await moveMigrationArtifact(i.archivePath, i.sourcePath, e, () => {
			assertRestoreDirectories(i);
			recordRestoredMigrationMove(t, n, i);
		});
		o.restoredFiles.push(i.sourcePath);
	} catch (e) {
		recordConflict(e instanceof Error ? e.message : String(e));
	}
}
function assertRestoreDirectories(e) {
	if (hasSymbolicLinkInDirectoryPath(path.dirname(e.sourcePath)) || hasSymbolicLinkInDirectoryPath(path.dirname(e.archivePath))) throw new Error("source or archive parent is a symbolic link; refusing restore");
}
function resolveRestoreStatus(e) {
	if (e.conflicts.length > 0) return e.restoredFiles.length > 0 ? "partial" : "conflicts";
	if (e.restoredFiles.length > 0) return "restored";
	return "noop";
}
//#endregion
//#region src/commands/doctor-session-sqlite-recover-report.ts
const CANONICAL_AGENT_INDEX_NAMES = getCanonicalSqliteNamedIndexContracts(OPENCLAW_AGENT_SCHEMA_SQL).map((e) => e.name);
/** Restores the latest failed migration run and validates only selected manifest targets. */
async function recoverDoctorSessionSqliteTargets(e) {
	const t = e.targets.map((t) => ({
		...t,
		sqlitePath: resolveTargetSqlitePath(t, e.env)
	}));
	const { failedRun: n, recoveredCorruptTargets: r } = await withAgentDatabaseMaintenanceLease({ env: e.env }, async (n) => {
		rebindRestoredLegacyRegistries(e.recoveryInventory, t, n);
		const r = findLatestFailedSessionSqliteMigrationManifest(e.env, t);
		return {
			failedRun: r,
			recoveredCorruptTargets: r ? [] : await recoverCorruptSqliteTargets(e.targets, e.env, n)
		};
	});
	if (!n) {
		const n = [...r];
		for (const i of t) {
			const t = r.find((e) => e.sqlitePath === i.sqlitePath);
			if (t && t.issues.length > 0) continue;
			try {
				const r = await e.prepareTarget?.(i);
				if (t) continue;
				if (hasDeferredPluginSessionImport({
					target: i,
					sqlitePath: i.sqlitePath,
					env: e.env
				}) || readActiveSqliteTranscriptFiles(i).length > 0 || e.historicalArchiveStores?.has(i.storePath)) n.push(await e.validateTarget(i));
				else if (r?.repaired) n.push(createEmptyRecoverTargetReport(i, i.sqlitePath));
			} catch (e) {
				n.push(createRecoverInspectionFailureTargetReport(i, i.sqlitePath, e));
			}
		}
		if (n.length > 0 || e.recoveryInventory && !e.recoveryInventory.report.artifacts.some((e) => e.outcome === "blocked" || e.reason === "unsupported-target-ownership")) return summarizeDoctorSessionSqliteReport("recover", n);
		return summarizeDoctorSessionSqliteReport("recover", [createSyntheticRecoverTargetReport(e.env, "No failed session SQLite migration manifest found.")]);
	}
	const i = await restoreSessionSqliteMigrationRun({
		env: e.env,
		manifestPath: n.manifestPath,
		trustedTargets: t
	});
	const a = [];
	const o = t.filter((t) => n.targets.some((e) => e.agentId === t.agentId && e.storePath === t.storePath) || e.historicalArchiveStores?.has(t.storePath));
	for (const t of o) try {
		await e.prepareTarget?.(t);
		a.push(await e.validateTarget({
			agentId: t.agentId,
			sqlitePath: t.sqlitePath,
			storePath: t.storePath
		}));
	} catch (e) {
		a.push(createRecoverInspectionFailureTargetReport(t, t.sqlitePath, e));
	}
	const s = a[0] ?? createSyntheticRecoverTargetReport(e.env, n.manifestPath);
	s.restore = i;
	for (const e of i.conflicts) s.issues.push({
		code: "restore_conflict",
		message: `${e.sourcePath}: ${e.reason}`
	});
	const c = summarizeDoctorSessionSqliteReport("recover", a.length > 0 ? a : [s]);
	if (c.totals.issues === 0) {
		c.migrationRun = {
			manifestPath: n.manifestPath,
			runId: n.manifest.runId
		};
		return c;
	}
	const l = writeSessionSqliteMigrationFailureReports(n.manifestPath, {
		reason: "doctor recover completed with remaining issues",
		recoveryTargets: c.targets,
		trustedTargets: t
	});
	c.migrationRun = {
		failureReportJsonPath: l.jsonPath,
		failureReportMarkdownPath: l.markdownPath,
		manifestPath: n.manifestPath,
		runId: n.manifest.runId
	};
	c.supportIssue = createSessionSqliteMigrationFailureIssue(n.manifestPath, t);
	return c;
}
/** Explicit recovery can acknowledge a same-path copy without granting archive disposal. */
function rebindRestoredLegacyRegistries(e, t, n) {
	for (const [r, i] of e?.references ?? []) {
		const e = i[0];
		if (e.move.kind !== "legacy-store") continue;
		const a = t.find((t) => t.agentId === e.target.agentId && t.storePath === e.target.storePath && t.sqlitePath === e.target.sqlitePath);
		if (!a || i.some((e) => !e.trusted || e.consumedByRestore || !e.run.manifest.completedAt || e.run.manifest.failedAt || e.target.validationBeforeArchive !== "passed" || e.target.agentId !== a.agentId || e.target.storePath !== a.storePath || e.target.sqlitePath !== a.sqlitePath || e.move.kind !== "legacy-store" || !e.target.completedMoves.some((e) => e.archivePath === r))) continue;
		const o = i.flatMap((e) => [...e.target.plannedMoves, ...e.target.completedMoves].filter((e) => e.archivePath === r));
		let s;
		try {
			assertSafeSessionSqliteMigrationDirectory(path.dirname(r));
			s = readMigrationArtifactIdentity(r);
			if (o.every((e) => e.artifact && sameMigrationArtifact(e.artifact.identity, s)) || !o.every((e) => e.kind === "legacy-store" && e.artifact?.disposal.state === "retained" && [
				"dev",
				"mtimeNs",
				"size",
				"sha256"
			].every((t) => e.artifact.identity[t] === s[t]))) continue;
			const e = [];
			readLegacySessionRecords(a, e, { sourcePath: r });
			if (e.length || !sameMigrationArtifact(readMigrationArtifactIdentity(r), s)) continue;
		} catch {
			continue;
		}
		for (const e of new Set(i.map((e) => e.run))) {
			n.assertOwned();
			for (const t of i.filter((t) => t.run === e)) for (const e of [...t.target.plannedMoves, ...t.target.completedMoves]) if (e.archivePath === r) e.artifact.identity = s;
			writeSessionSqliteMigrationManifest(e);
		}
	}
}
async function recoverCorruptSqliteTargets(e, t, n) {
	const r = [];
	for (const i of e) {
		n.assertOwned();
		const e = resolveTargetSqliteOptions(i, t);
		const a = resolveOpenClawAgentSqlitePath(e);
		let o;
		try {
			o = inspectSqliteRecoveryFiles(a);
		} catch (e) {
			r.push(createRecoverInspectionFailureTargetReport(i, a, e));
			continue;
		}
		if (o.existing.length === 0) continue;
		const s = o.existing.includes(a);
		const c = s ? inspectSqliteForRecovery(a, o.existing) : {
			ok: false,
			ftsOnly: false,
			error: /* @__PURE__ */ new Error(`SQLite sidecars exist without their main database: ${a}`)
		};
		if (c.ok) continue;
		if (s && !isSqliteCorruptionError(c.error)) {
			r.push(createRecoverInspectionFailureTargetReport(i, a, c.error));
			continue;
		}
		if (!s || !c.ftsOnly && !isCanonicalAgentIndexCorruptionError(c.error)) {
			r.push(recoverCorruptSqliteTarget(i, a, c.error, () => n.assertOwned()));
			continue;
		}
		const l = await repairCanonicalIndexesForRecovery(e, a, n);
		r.push(l.ok ? createEmptyRecoverTargetReport(i, a) : createRecoverInspectionFailureTargetReport(i, a, l.error));
	}
	return r;
}
async function repairCanonicalIndexesForRecovery(e, t, n) {
	try {
		await migrateOpenClawAgentDatabaseForMaintenance({
			agentId: e.agentId,
			pathname: t
		}, n);
		n.assertOwned();
		const r = inspectSqliteRecoveryFiles(t).existing;
		const i = inspectSqliteForRecovery(t, r);
		if (!i.ok) return i;
		if (!clearOpenClawAgentDatabaseOpenFailure(t, { env: e.env })) throw new Error(`Repaired SQLite indexes, but could not clear the quarantine for ${t}.`);
		return { ok: true };
	} catch (e) {
		return {
			error: e,
			ok: false
		};
	}
}
function inspectSqliteForRecovery(e, t) {
	let n;
	let r;
	let i;
	let a = false;
	try {
		n = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sqlite-recovery-"));
		const i = path.join(n, path.basename(e));
		for (const n of t) {
			const t = `${i}${n.slice(e.length)}`;
			fs.copyFileSync(n, t, fs.constants.COPYFILE_EXCL);
			fs.chmodSync(t, 384);
		}
		r = openNodeSqliteDatabase(i);
		r.exec(`PRAGMA busy_timeout = ${OPENCLAW_SQLITE_BUSY_TIMEOUT_MS};`);
		r.exec("PRAGMA trusted_schema = OFF;");
		assertSqliteIntegrity(r, i, { allFindings: true });
	} catch (e) {
		i = e;
		if (r && e instanceof SqliteIntegrityError && e.findings) try {
			a = Boolean(classifySqliteFtsIntegrityFindings(r, e.findings, AGENT_FTS_SCHEMAS));
		} catch {}
	}
	try {
		r?.close();
	} catch (e) {
		i ??= e;
	}
	try {
		if (n) fs.rmSync(n, {
			force: true,
			recursive: true
		});
	} catch (e) {
		i ??= e;
	}
	return i === void 0 ? { ok: true } : {
		error: i,
		ok: false,
		ftsOnly: a
	};
}
function recoverCorruptSqliteTarget(e, t, n, r) {
	const i = createEmptyRecoverTargetReport(e, t);
	try {
		i.corruptRecovery = moveSqliteFilesAside(t, r);
	} catch (e) {
		i.issues.push({
			code: "sqlite_corrupt_recovery_failed",
			message: `${t}: ${String(e)}; original error: ${String(n)}`
		});
	}
	return i;
}
function createRecoverInspectionFailureTargetReport(e, t, n) {
	const r = createEmptyRecoverTargetReport(e, t);
	r.issues.push({
		code: "sqlite_recovery_inspect_failed",
		message: `${t}: ${String(n)}`
	});
	return r;
}
function isSqliteCorruptionError(e) {
	const t = e && typeof e === "object" ? e.code : void 0;
	if (t === "SQLITE_CORRUPT" || t === "SQLITE_NOTADB") return true;
	const n = String(e).toLowerCase();
	return n.includes("database disk image is malformed") || n.includes("not a database") || n.includes("sqlite quick_check failed") || n.includes("sqlite integrity_check failed") || n.includes("sqlite foreign_key_check failed");
}
function isCanonicalAgentIndexCorruptionError(e) {
	if (!(e instanceof Error) || e.name !== "SqliteIntegrityError") return false;
	return CANONICAL_AGENT_INDEX_NAMES.some((t) => e.message.includes(t));
}
function createSyntheticRecoverTargetReport(e, t) {
	return createDoctorSessionSqliteTargetReport({
		agentId: "recover",
		issues: [{
			code: "recover_manifest_missing",
			message: t
		}],
		sqlitePath: "",
		storePath: resolveSessionSqliteMigrationRunsDir(e)
	});
}
function createEmptyRecoverTargetReport(e, t) {
	return createDoctorSessionSqliteTargetReport({
		agentId: e.agentId,
		sqlitePath: t,
		storePath: e.storePath
	});
}
//#endregion
//#region src/commands/doctor-session-sqlite-restore-report.ts
async function restoreDoctorSessionSqliteTargets(e) {
	const t = e.targets.map((e) => createDoctorSessionSqliteTargetReport({
		agentId: e.agentId,
		sqliteEntries: readSqliteEntryCount(e),
		sqlitePath: resolveTargetSqlitePath(e),
		storePath: e.storePath
	}));
	const n = e.targets.map((e) => ({
		...e,
		sqlitePath: resolveTargetSqlitePath(e)
	}));
	const r = await restoreSessionSqliteMigrationRuns({
		env: e.env,
		trustedTargets: n
	});
	const i = t[0] ?? createDoctorSessionSqliteTargetReport({
		agentId: "restore",
		sqlitePath: "",
		storePath: r.manifestPaths[0] || resolveSessionSqliteMigrationRunsDir(e.env)
	});
	i.restore = r;
	for (const e of r.conflicts) i.issues.push({
		code: "restore_conflict",
		message: `${e.sourcePath}: ${e.reason}`
	});
	const a = t.length > 0 ? t : [i];
	return summarizeDoctorSessionSqliteReport("restore", a);
}
//#endregion
//#region src/infra/deferred-plugin-session-source-recovery.ts
/** Rebuild derived evidence from proven original index values or verified canonical transcripts. */
async function rebuildDeferredPluginSessionSourceIndex(e) {
	const t = readDeferredPluginSessionImportReceipt(e);
	if (!t) return false;
	const { recorded: n, currentDatabaseIdentity: r, physicalIdentity: i, stale: a } = parseSessionImportReceipt(e, t);
	if (n.superseded) return false;
	if (a) {
		supersedeDeferredPluginSessionImport({
			receipt: t,
			databaseIdentity: r,
			sqlitePath: e.sqlitePath,
			physicalIdentity: i,
			env: e.env
		});
		return true;
	}
	const o = {
		...e.target,
		sqlitePath: e.sqlitePath
	};
	const s = n.sources.find((e) => e.path === path.resolve(o.storePath));
	let c = s;
	const l = sessionSourceArchives(o, e.env, e.verification ?? /* @__PURE__ */ new Map());
	const u = new Set(n.sources.map((e) => e.path));
	const d = s && existingSessionSourcePaths(s.path, l).length === 0;
	const receiptStillBound = (n) => isDeepStrictEqual(n, t) && databaseIdentity(e.sqlitePath, "physical") === i && databaseIdentity(e.sqlitePath) === r;
	const assertCurrent = () => {
		if (!receiptStillBound(readDeferredPluginSessionImportReceipt(e)) || c && !d && !resolveVerifiedSessionSource(c, o, e.env, /* @__PURE__ */ new Map(), l) || d && existingSessionSourcePaths(s.path, l).length > 0) throw new Error("Retained session receipt, index, or database changed during recovery; sources remain protected.");
	};
	const f = [];
	const p = [...n.settledSources ?? []];
	for (const t of n.sources.filter((e) => (!d || e !== s) && (!isTrajectorySessionArtifactName(path.basename(e.path)) || existingSessionSourcePaths(e.path, l).length > 0))) {
		if (isPrimarySessionTranscriptFileName(path.basename(t.path)) && existingSessionSourcePaths(t.path, l).length === 0 && await verifyMissingDeferredSessionTranscript({
			target: o,
			env: e.env,
			identity: t.identity,
			sessionId: extractGeneratedTranscriptSessionId(t.path) ?? path.basename(t.path, ".jsonl")
		})) {
			p.push({
				...t,
				reason: "Missing original satisfied by an exact size and SHA-256 match of canonical SQLite history; no events replayed."
			});
			continue;
		}
		f.push(await (async () => {
			let i;
			const a = statMigrationPath(t.path) ? [t.path] : (l.get(t.path) ?? []).map((e) => e.path);
			for (const s of a) {
				if (!statMigrationPath(s)) continue;
				try {
					const i = readMigrationArtifactIdentity(s);
					const a = i.size === 0 && isPrimarySessionTranscriptFileName(path.basename(t.path));
					if ((!a || s !== t.path && r === n.databaseIdentity) && sameSourceContent(i, t.identity)) return {
						path: t.path,
						identity: i
					};
					if (!a && s !== t.path || t.path !== path.resolve(o.storePath) && !isPrimarySessionTranscriptFileName(path.basename(t.path))) continue;
					const d = t.path === path.resolve(o.storePath);
					const f = !d && c && resolveVerifiedSessionSource(c, o, e.env, /* @__PURE__ */ new Map(), l);
					if (d) {
						const n = [];
						const r = readLegacySessionStoreEntries(e.target, n, { sourcePath: s });
						if (!r.bytes || !preservesRecordedIndexValue(r.bytes, t.identity)) throw new Error(`Cannot prove the retained index preserves its original entries, metadata, and transcript links: ${s}. ${n.map((e) => e.message).join("; ")}`);
					} else {
						if (!a && (!f || !c)) throw new Error("Changed transcript has no verified retained index to establish its session owner.");
						await verifyDeferredSessionDatabase({
							...e,
							sources: [...c && f ? [{
								originalPath: c.path,
								path: f
							}] : [], {
								originalPath: t.path,
								path: s
							}],
							requireCompleteTranscript: true,
							verifiedSourcePaths: u,
							assertCurrent
						});
					}
					if (!sameMigrationArtifact(readMigrationArtifactIdentity(s), i) || f && c && !sameSourceContent(readMigrationArtifactIdentity(f), c.identity)) continue;
					if (d) c = {
						path: t.path,
						identity: i
					};
					return {
						path: t.path,
						identity: i
					};
				} catch (e) {
					if (statMigrationPath(s)?.size === 0 && isPrimarySessionTranscriptFileName(path.basename(t.path))) throw e;
					i = e;
				}
			}
			if (i !== void 0) e.onSourceConflict?.(t.path, void 0, i);
			return t;
		})());
	}
	const m = {
		...n,
		databaseIdentity: r,
		sources: f,
		...p.length ? { settledSources: p } : {}
	};
	if (isDeepStrictEqual(m, n)) return false;
	const h = captureOpenClawStateWorkerContext({ env: e.env });
	await runOpenClawStateWorkerOperation(h, (n) => n.execute({
		type: "deferredSessionImport.rebuildSources",
		input: {
			receipt: t,
			rebuilt: m,
			storePath: o.storePath,
			sqlitePath: e.sqlitePath,
			physicalIdentity: i
		}
	}), { createAdmission: createSqliteWorkerWriteAdmission(h.admission.assertCurrent, [h.admission.databasePath]) });
	for (const t of p.slice(n.settledSources?.length ?? 0)) e.onMissingSource?.(t.path, t.reason);
	return true;
}
//#endregion
//#region src/commands/doctor-session-sqlite-retained.ts
/** Sidecars settle with archived transcripts or terminally missing trajectory targets. */
function collectRetainedTrajectoryPointers(e, t) {
	return [...e].filter((n) => {
		const r = n.replace(/\.trajectory-path\.json$/u, ".jsonl");
		if (e.has(r)) return r !== n && !t?.has(r) && !fs.existsSync(r);
		const i = n.endsWith(".trajectory-path.json") && tryReadJsonSync(n);
		return isRecord(i) && i.traceSchema === "openclaw-trajectory-pointer" && typeof i.runtimeFile === "string" && !fs.existsSync(r) && !fs.existsSync(path.resolve(path.dirname(n), i.runtimeFile));
	});
}
/** Archival, not plugin completion alone, ends the original index's no-replay obligation. */
function retireDeferredPluginSessionImport(e) {
	const t = readDeferredPluginSessionImportReceipt(e);
	if (!t) return;
	const n = DeferredPluginSessionImportSchema.parse(JSON.parse(t.reportJson));
	if (n.superseded) return;
	const hasRemainingSources = () => statMigrationPath(e.target.storePath) || n.sources.some((e) => statMigrationPath(e.path));
	const r = readDeferredPluginMigrations({ env: e.env });
	if (r.some((t) => n.pluginIds.includes(t.pluginId) && !e.completedPluginIds?.includes(t.pluginId))) return;
	if (hasRemainingSources()) return;
	runOpenClawStateWriteTransaction(({ db: n }) => withDeferredPluginMigrationsCurrent({
		env: e.env,
		expectedPending: r,
		phase: "session source retirement"
	}, () => {
		e.assertCurrent?.();
		if (!isDeepStrictEqual(readDeferredPluginSessionImportReceipt({
			...e,
			database: n
		}), t)) throw new Error("Deferred session import receipt changed before retirement.");
		if (hasRemainingSources()) return;
		const { cfg: r, env: i, target: a, sqlitePath: o } = e;
		readDeferredPluginSessionImport({
			cfg: r,
			env: i,
			target: a,
			sqlitePath: o,
			database: n
		});
		markLegacyMigrationSourceRemovedInDatabase(n, t.sourceKey);
	}), { env: e.env }, { operationLabel: "state.retire-plugin-session-source" });
}
/** Receipt recovery belongs to offline Doctor; canonical session data is never replayed. */
async function prepareRetainedSessionImport(e, t) {
	const n = t.issues;
	const r = e.target.storePath.endsWith(".sqlite");
	const i = resolveTargetSqlitePath(e.target, e.env);
	if (!r && (e.mode === "import" || e.mode === "recover")) {
		const t = createRetainedAgentDatabaseMatcher(e.env, () => resolveConfiguredAgentDatabaseTargets(e.cfg, { env: e.env }), {
			kind: "legacy-database",
			readDatabasePaths: () => [i]
		});
		const r = t(e.target.storePath, e.target.agentId) || t(i, e.target.agentId);
		if (r && (r !== "unavailable" || hasSqliteFileFamily(i) || hasDeferredPluginSessionImport({
			target: {
				...e.target,
				sqlitePath: i
			},
			sqlitePath: i,
			env: e.env
		}))) {
			n.push({
				code: "plugin_migration_source_retained",
				message: `Retained session sources skipped: store held for agent ${e.target.agentId} database ${i}. Run openclaw doctor --fix for deletion-history repair and explicit restoration guidance.`
			});
			return;
		}
	}
	let a;
	const o = /* @__PURE__ */ new Map();
	const s = /* @__PURE__ */ new Map();
	const c = {
		...prepareSessionSourceVerification({
			...e,
			sqlitePath: i
		}),
		allowMissingIndex: true,
		onEmptySource: (e, t) => s.set(e, t),
		onMissingSource: (e, t) => n.push({
			code: "retained_missing_transcript_superseded",
			message: `${e}: ${t}`
		}),
		onSourceConflict: (t, r = t, i) => {
			if (o.has(r)) return;
			const a = i === void 0 ? "Retained plugin input no longer matches its verified source." : formatErrorMessage(i);
			o.set(t, a);
			o.set(r, a);
			n.push({
				code: fs.existsSync(e.target.storePath) ? "retained_plugin_source_conflict" : "historical_transcript_deferred",
				message: `${r}: ${a} The SQLite sessions remain the active records. Preserve this input and its backups. Restore the verified original at ${t}, then run openclaw doctor --session-sqlite recover --session-sqlite-all-agents against the same state/config.`
			});
		}
	};
	if (!r) try {
		if (e.mode === "import" || e.mode === "recover") {
			if (await rebuildDeferredPluginSessionSourceIndex(c)) {
				if (!readStaleDeferredPluginSessionImport(c)) n.push({
					code: "retained_plugin_source_index_rebuilt",
					message: `Rebuilt the verified source index and database binding from the deferred import receipt: ${e.target.storePath}. Existing SQLite sessions were not reimported.`
				});
			}
			retireDeferredPluginSessionImport(c);
		}
		a = readDeferredPluginSessionImport(c);
	} catch (e) {
		n.push({
			code: "retained_plugin_source_conflict",
			message: formatErrorMessage(e)
		});
		return;
	}
	const l = r ? void 0 : readStaleDeferredPluginSessionImport(c);
	if (l) {
		n.push({
			code: "retained_plugin_receipt_superseded",
			message: `Session import receipt is bound to a different database (${l.databaseIdentity}); it cannot certify ${i}. ${l.superseded ? "Preserved the superseded receipt in migration_runs." : "Doctor import will preserve and supersede it."} Retained originals will be checked against live session state without replacing current settings.`
		});
		for (const t of l.sources) {
			if (!isPrimarySessionTranscriptFileName(path.basename(t.path))) continue;
			let r = "";
			try {
				const n = statMigrationPath(t.path);
				if (n?.isFile() && n.size > 0) continue;
				if (resolveVerifiedSessionSource(t, c.resolvedTarget, e.env, c.verification)) continue;
			} catch (e) {
				r = ` ${formatErrorMessage(e)}`;
			}
			n.push({
				code: "historical_transcript_deferred",
				message: `Retained history source unavailable: ${t.path}.${r} The foreign receipt cannot prove its history exists in ${i}; restore this original from a verified backup and rerun openclaw doctor --fix.`
			});
		}
	}
	const u = a?.sources.find((t) => t.path === path.resolve(e.target.storePath));
	const d = u && resolveVerifiedSessionSource(u, c.resolvedTarget, e.env, c.verification);
	if (a && (e.mode === "import" || e.mode === "recover") && o.has(path.resolve(e.target.storePath))) appendRetainedIndexComparison(e, n);
	if (s.size) {
		await archiveConflictingRetainedSessionSources({
			...e,
			verifiedEmpty: true
		}, s, t);
		c.verification.clear();
	}
	return {
		retainedImport: a,
		staleImport: l,
		sourceConflicts: o,
		sourceVerification: c,
		retainedIndexPath: d
	};
}
/** Compare current rows for diagnosis only; changed index values never gain receipt authority. */
function appendRetainedIndexComparison(e, t) {
	try {
		const n = [];
		const r = readLegacySessionRecords(e.target, n).filter(({ sessionKey: t }) => !shouldFilterLegacySessionRecordsByTarget(e.target) || isLegacySessionRecordOwnedByTarget(e.cfg, e.target, t));
		if (n.length || !r.length) return;
		const i = new Map(loadExactSessionEntryCandidatesReadOnly({
			readOnly: true,
			env: e.env,
			readSource: {
				agentId: e.target.agentId,
				path: resolveTargetSqlitePath(e.target, e.env)
			},
			sessionKeys: r.map(({ sessionKey: e }) => e)
		}).map(({ sessionKey: e, entry: t }) => [e, t]));
		for (const { sessionKey: e, entry: n } of r) {
			const r = i.get(e);
			let a;
			if (!r || r.sessionId !== n.sessionId) a = "Retained session identity differs from the current SQLite row.";
			else {
				const e = new Map(Object.entries(n));
				const t = new Map(Object.entries(r));
				const i = [.../* @__PURE__ */ new Set([...e.keys(), ...t.keys()])].filter((n) => n !== "sessionFile" && !isDeepStrictEqual(e.get(n), t.get(n))).toSorted();
				if (!i.length) continue;
				a = `Retained session identity matches the SQLite records, but metadata differs: ${i.join(", ")}.`;
			}
			t.push({
				code: "retained_plugin_source_conflict",
				sessionKey: e,
				message: `${a} Existing values were kept; the retained index remains protected for recovery.`
			});
		}
	} catch (e) {
		t.push({
			code: "retained_plugin_source_conflict",
			message: `Could not compare retained session metadata: ${formatErrorMessage(e)}. Existing SQLite sessions were not changed.`
		});
	}
}
/** Preserve unverifiable plugin inputs through the existing reversible archive lifecycle. */
async function archiveConflictingRetainedSessionSources(e, t, n) {
	const r = {
		...e.target,
		sqlitePath: resolveTargetSqlitePath(e.target, e.env)
	};
	const i = [...t].filter(([t]) => !e.protectedPaths?.has(canonicalMigrationFilePath(t)) && fs.existsSync(t) && path.dirname(t) === path.dirname(r.storePath));
	if (!i.length) return;
	const a = e.activeRun ?? createSessionSqliteMigrationRun(e.env, [r]);
	const o = e.targets ?? [r];
	let s = r.storePath;
	const c = e.expectedIndexIdentity ?? (!e.activeRun && fs.existsSync(s) ? readMigrationArtifactIdentity(s) : void 0);
	const assertIndexCurrent = () => {
		if (s !== r.storePath && fs.existsSync(r.storePath) || (c ? !sameMigrationArtifact(readMigrationArtifactIdentity(s), c) : fs.existsSync(s))) throw new Error("Session index changed after owner discovery; original retained for a fresh Doctor pass.");
	};
	for (const [l, u] of i) try {
		assertIndexCurrent();
		const i = planSessionJsonlArchiveMove({
			target: r,
			sourcePathRaw: l,
			archiveKey: "retained-plugin-conflict",
			kind: l === r.storePath ? "legacy-store" : "transcript"
		});
		i.artifact = {
			identity: i.kind === "legacy-store" && c ? c : readMigrationArtifactIdentity(l),
			classification: "protected",
			reason: u,
			dependencies: [],
			disposal: { state: "retained" }
		};
		if (e.verifiedEmpty && i.artifact.identity.size !== 0) throw new Error("Retained transcript is no longer empty; source needs verification");
		for (const e of o) recordPlannedMigrationMoves(a, e, [i]);
		await moveMigrationArtifact(i.sourcePath, i.archivePath, i.artifact.identity, void 0, (e, t) => {
			if (i.kind !== "legacy-store") try {
				assertIndexCurrent();
			} catch (e) {
				t();
				throw e;
			}
			e();
		});
		for (const e of o) recordCompletedMigrationMoves(a, e, [i]);
		if (i.kind === "legacy-store") s = i.archivePath;
		t.set(i.archivePath, u);
		(i.kind === "legacy-store" ? n.archivedLegacyStoreFiles ??= [] : n.archivedTranscriptFiles).push(i.archivePath);
		n.issues.push({
			code: e.verifiedEmpty ? "retained_empty_transcript_superseded" : "retained_plugin_source_conflict",
			message: `${l}: ${u} Preserved at ${i.archivePath}; existing SQLite sessions were not reimported.`
		});
	} catch (e) {
		n.issues.push({
			code: "retained_plugin_source_conflict",
			message: `${l}: could not archive retained input: ${formatErrorMessage(e)}. Original remains protected.`
		});
	}
	updateMigrationManifestTarget(a, r, n.issues);
	if (!e.activeRun) {
		a.manifest.completedAt = (/* @__PURE__ */ new Date()).toISOString();
		writeSessionSqliteMigrationManifest(a);
	}
}
/** Historical discovery yields; verify the receipt again before counting or authorizing archival. */
function countRetainedSessionSources(e, t, n) {
	const { retainedImport: r, retainedIndexPath: i, sourceVerification: a, sourceConflicts: o } = e;
	if (!r) return;
	if (!i) {
		a.verification.clear();
		if (!isDeepStrictEqual(readDeferredPluginSessionImport(a), r)) throw new Error("Verified retained session import receipt changed during discovery.");
	}
	const s = new Map(r.sources.map((e) => [e.path, e]));
	for (const e of t) {
		const t = e.transcriptPath;
		if (!t || o.has(t)) continue;
		const r = s.get(path.resolve(t));
		if (!r) {
			n.issues.push({
				code: "transcript_missing",
				message: `Transcript file is missing: ${t}`,
				sessionKey: e.sessionKey
			});
			continue;
		}
		if (fs.existsSync(t)) e.sourceFingerprint = readTranscriptFingerprint(t);
		const i = resolveVerifiedSessionSource(r, a.resolvedTarget, a.env, a.verification);
		if (!i) throw new Error(`Retained session migration source changed: ${t}`);
		countLegacyTranscript({
			...e,
			transcriptPath: i
		}, n);
		e.recovery = {
			complete: !n.issues.some((t) => t.code === "transcript_malformed" && t.sessionKey === e.sessionKey),
			repaired: false,
			events: 0
		};
	}
}
//#endregion
//#region src/commands/doctor-session-sqlite-targets.ts
/** Offline Doctor target discovery and legacy-source admission. */
async function prepareDoctorSessionSqliteTargets(e) {
	if (isDestructiveDoctorSessionSqliteMode(e.mode)) {
		const t = resolveOpenClawStateSqlitePath(e.env);
		if (hasOrphanedSqliteSidecars(t)) throw new Error(`OpenClaw state database ${t} is unavailable: SQLite sidecars remain without the database. Restore its matching database before retrying Doctor; keep the sidecars intact.`);
	}
	const t = resolveDoctorSessionSqliteTargets(e);
	if (isDestructiveDoctorSessionSqliteMode(e.mode)) assertDoctorSessionSqliteTargetsNotAliased({
		...e,
		...t
	});
	const repairEntryStates = async (t) => {
		e.authority?.assertCurrent();
		const { repairLegacySessionEntryStates: n } = await import("./doctor-session-delivery-state-BYYA0Re-.mjs");
		return await n({
			apply: true,
			cfg: e.cfg,
			env: e.env,
			authority: e.authority,
			targets: projectExistingAgentDatabaseTargets(t, e.env, e.cfg),
			deferSchemaRepair: e.mode === "import",
			integrityCheck: e.mode === "import" ? e.integrityCheck : "full"
		});
	};
	if (e.mode === "import") await repairEntryStates(t.targets);
	return {
		...t,
		repairEntryStates
	};
}
function assertDoctorSessionSqliteTargetsNotAliased(e) {
	assertDoctorSqliteMaintenancePathsNotAliased(`session SQLite ${e.mode}`, resolveDoctorSessionSqliteMaintenancePaths(e.targets), resolveDoctorSessionSqliteMaintenanceRoots(e.targets, e.env), e.allAgents && !e.agent && !e.store && e.knownTargets ? {
		paths: resolveDoctorSessionSqliteMaintenancePaths(e.knownTargets),
		ownershipRoots: resolveDoctorSessionSqliteMaintenanceRoots(e.knownTargets, e.env)
	} : void 0);
}
function createMigrationTargetInput(e) {
	return {
		agentId: e.agentId,
		sqlitePath: canonicalMigrationFilePath(resolveTargetSqlitePath(e)),
		storePath: canonicalMigrationFilePath(e.storePath)
	};
}
function resolveDoctorSessionSqliteConfig(e) {
	if (e.cfg) return e.cfg;
	const t = normalizeAgentId(e.agent ?? "main");
	return e.store ? { agents: { entries: { [t]: {} } } } : loadConfig();
}
function resolveDoctorSessionSqliteMaintenancePaths(e) {
	return [...new Set(e.flatMap((e) => resolveSqliteDatabaseFilePaths(resolveTargetSqlitePath(e))))];
}
function resolveDoctorSessionSqliteMaintenanceRoots(e, t) {
	const n = path.resolve(resolveStateDir(t));
	const r = /* @__PURE__ */ new Set([n]);
	for (const t of e) {
		const e = resolveTargetSqlitePath(t);
		if (isPathWithin(n, t.storePath) && isPathWithin(n, e)) continue;
		const i = commonPathAncestor(path.dirname(t.storePath), path.dirname(e));
		const a = path.dirname(i);
		r.add(a === path.parse(i).root ? i : a);
	}
	return [...r];
}
function isPathWithin(e, t) {
	return isPathInside$1(e, path.resolve(t));
}
function commonPathAncestor(e, t) {
	let n = path.resolve(e);
	const r = path.resolve(t);
	while (!isPathWithin(n, r)) {
		const e = path.dirname(n);
		if (e === n) return n;
		n = e;
	}
	return n;
}
function resolveDoctorSessionSqliteTargets(e) {
	if (e.store) return { targets: resolveSessionStoreTargets(e.cfg, {
		store: e.store,
		agent: e.agent,
		allAgents: e.allAgents
	}, { env: e.env }) };
	const t = e.mode === "dry-run" || e.mode === "import" || e.mode === "validate";
	if (e.mode === "restore" || e.mode === "recover" || t && e.agent) {
		const t = resolveAllAgentSessionStoreCandidateTargetsSync(e.cfg, { env: e.env });
		if (!e.agent) return {
			targets: t,
			knownTargets: t
		};
		const n = normalizeAgentId(e.agent);
		return {
			targets: t.filter((e) => normalizeAgentId(e.agentId) === n),
			knownTargets: t
		};
	}
	if (e.agent) return { targets: resolveAgentSessionStoreTargetsSync(e.cfg, e.agent, { env: e.env }) };
	if (e.allAgents) {
		const n = t ? resolveAllAgentSessionStoreCandidateTargetsSync(e.cfg, { env: e.env }) : resolveAllAgentSessionStoreTargetsSync(e.cfg, { env: e.env });
		const r = n.map((t) => ({
			target: t,
			sqlitePath: resolveTargetSqlitePath(t, e.env)
		}));
		return {
			targets: selectSessionStoreMaintenanceTargets(r, e).map(({ target: e }) => e),
			knownTargets: n
		};
	}
	return { targets: resolveSessionStoreTargets(e.cfg, {}, { env: e.env }) };
}
function filterLegacySessionStoreTargets(e, t, n, r) {
	if (t === "inspect" || t === "compact" || t === "restore" || t === "recover") return e;
	return e.filter((e) => !e.storePath.endsWith(".sqlite") && (r.has(e.storePath) || fs.existsSync(e.storePath) || (n.get(canonicalMigrationFilePath(e.storePath))?.transcripts.length ?? 0) > 0 || fs.existsSync(path.dirname(e.storePath)) && fs.readdirSync(path.dirname(e.storePath)).some((e) => e.endsWith(".jsonl"))));
}
//#endregion
//#region src/commands/doctor-session-sqlite.ts
const retainedArchivePlans = /* @__PURE__ */ new WeakMap();
/** Destructive production callers hold the Gateway/SQLite-maintenance state lock for the full call. */
async function runDoctorSessionSqlite(e, t) {
	const n = e.env ?? process.env;
	const r = resolveDoctorSessionSqliteConfig(e);
	const i = new Set(listAgentIds(r));
	const a = readDeferredPluginMigrations({ env: n });
	const o = createMissingSessionIndexVerifier({
		cfg: r,
		env: n
	});
	const { targets: s, knownTargets: c, repairEntryStates: l } = await prepareDoctorSessionSqliteTargets({
		...e,
		cfg: r,
		env: n,
		authority: t
	});
	const u = e.mode === "import" || e.mode === "recover" ? await settleDuplicateSessionSqliteArchives({
		cfg: r,
		env: n,
		targets: s.map(createMigrationTargetInput)
	}) : [];
	const settlementIssuesForStore = (e) => u.filter((t) => t.target.storePath === e).flatMap((e) => e.issues);
	let d = [
		"import",
		"dry-run",
		"validate",
		"recover"
	].includes(e.mode) ? collectHistoricalArchiveSources({
		cfg: r,
		env: n
	}) : void 0;
	let f = d?.sources ?? /* @__PURE__ */ new Map();
	const p = filterLegacySessionStoreTargets(s, e.mode, f, new Set(u.map(({ target: e }) => e.storePath)));
	if (e.mode === "restore") return restoreDoctorSessionSqliteTargets({
		env: n,
		targets: p
	});
	if (e.mode === "recover") return recoverDoctorSessionSqliteTargets({
		env: n,
		targets: p,
		prepareTarget: (e) => l([e]),
		recoveryInventory: d?.inventory,
		historicalArchiveStores: /* @__PURE__ */ new Set([...f.keys(), ...u.map(({ target: e }) => e.storePath)]),
		validateTarget: async (e) => {
			t?.assertCurrent();
			const s = collectHistoricalArchiveSources({
				cfg: r,
				env: n
			}).sources.get(e.storePath)?.transcripts.length || readStaleDeferredPluginSessionImport({
				target: e,
				sqlitePath: e.sqlitePath,
				env: n
			}) ? (await runDoctorSessionSqlite({
				cfg: r,
				env: n,
				mode: "import",
				store: e.storePath,
				agent: e.agentId
			}, t)).targets[0] : await inspectOrMigrateTarget({
				configuredAgentIds: i,
				cfg: r,
				env: n,
				mode: "recover",
				target: e,
				verifyMissingIndex: o,
				deferredPluginIds: deferredPluginSessionStoreIds({
					target: e,
					pending: a
				})
			});
			settlementIssuesForStore(e.storePath).forEach((e) => s.issues.push(e));
			return s;
		}
	});
	if (e.mode === "import") {
		await reconcileSessionSqliteMigrationPublications({
			env: n,
			trustedTargets: p.map(createMigrationTargetInput)
		});
		d = collectHistoricalArchiveSources({
			cfg: r,
			env: n
		});
		f = d.sources;
	}
	const m = e.mode === "import" && p.length > 0 ? createSessionSqliteMigrationRun(n, p.map(createMigrationTargetInput)) : void 0;
	const h = e.mode === "import" || e.mode === "dry-run" || e.mode === "validate" ? gatherLegacyArchiveCoverage(r, n, p, c) : void 0;
	const g = [];
	const _ = [];
	for (const t of p) g.push(await inspectOrMigrateTarget({
		configuredAgentIds: i,
		activeRun: m,
		archiveTargets: _,
		verifyMissingIndex: o,
		cfg: r,
		env: n,
		mode: e.mode,
		target: t,
		historicalArchives: f,
		recoveryInventory: d?.inventory,
		referencedPaths: h?.referencedPaths,
		expectedIndexIdentity: h?.indexIdentities.get(canonicalMigrationFilePath(t.storePath)),
		deferredPluginIds: deferredPluginSessionStoreIds({
			target: t,
			pending: a
		})
	}));
	for (const e of g) settlementIssuesForStore(e.storePath).forEach((t) => e.issues.push(t));
	if (m && h) {
		for (const t of _) if (t.sourceConflicts?.size && (!shouldFilterLegacySessionRecordsByTarget(t.sourceTarget) || e.allAgents && !e.agent && !e.store && (h.selectedStorePaths.has(t.target.storePath) || h.incompleteDirectories.has(path.dirname(t.target.storePath))) && h.knownTargets.filter((e) => canonicalMigrationFilePath(e.storePath) === t.target.storePath).every((e) => _.some((n) => n.target.agentId === e.agentId && n.target.storePath === t.target.storePath && n.validated))) && p.filter((e) => canonicalMigrationFilePath(e.storePath) === t.target.storePath).every((e) => _.some((t) => t.sourceTarget === e && t.validated))) await archiveConflictingRetainedSessionSources({
			cfg: r,
			env: n,
			target: t.sourceTarget,
			activeRun: m,
			protectedPaths: h.retainedPaths,
			expectedIndexIdentity: h.indexIdentities.get(t.target.storePath),
			targets: _.filter((e) => e.target.storePath === t.target.storePath).map((e) => e.target)
		}, t.sourceConflicts, t.report);
		const t = /* @__PURE__ */ new Set();
		for (const e of g.filter(isInformationalMissingSessionIndex)) {
			h.selectedStorePaths.delete(canonicalMigrationFilePath(e.storePath));
			h.retainedDirectories.add(path.dirname(canonicalMigrationFilePath(e.storePath)));
		}
		for (const e of _) for (const n of e.sourceConflicts?.keys() ?? []) {
			h.retainedPaths.add(canonicalMigrationFilePath(n));
			t.add(canonicalMigrationFilePath(n));
		}
		const retainDeferredSources = () => {
			for (const e of _) if (e.deferredPluginIds.length > 0) {
				h.selectedStorePaths.delete(canonicalMigrationFilePath(e.target.storePath));
				h.retainedDirectories.add(path.dirname(canonicalMigrationFilePath(e.target.storePath)));
				if (e.retainedImportVerified) for (const n of e.verifiedSources ?? []) t.add(canonicalMigrationFilePath(n.path));
			}
		};
		const publishArchive = (e, t) => {
			const i = withDeferredPluginMigrationsCurrent({
				env: n,
				expectedPending: a,
				onConflict(e) {
					t();
					if (e.length > 0) {
						for (const t of _) if (!t.retainedImportVerified && t.verifiedSources) recordDeferredPluginSessionImport({
							cfg: r,
							target: t.sourceTarget,
							sqlitePath: t.target.sqlitePath,
							env: n,
							pluginIds: e.map((e) => e.pluginId),
							sources: t.verifiedSources,
							recordCount: t.report.legacyEntries
						});
					}
					return e;
				}
			}, () => {
				e();
			});
			if (i) {
				const e = new DeferredPluginMigrationConflictError(i, {
					expected: a,
					phase: "session archive publication"
				});
				for (const t of _) {
					t.deferredPluginIds = deferredPluginSessionStoreIds({
						target: t.target,
						pending: i
					});
					if (t.deferredPluginIds.length > 0) {
						t.retainedImportVerified ||= t.verifiedSources !== void 0;
						t.report.issues.push({
							code: "plugin_migration_source_retained",
							message: `${e.message} Original session migration inputs remain pending for plugin(s): ${t.deferredPluginIds.join(", ")}.`
						});
					}
				}
				retainDeferredSources();
				throw e;
			}
		};
		retainDeferredSources();
		await archiveLegacyArtifacts(_, h, m, void 0, void 0, publishArchive);
		for (const { target: e, report: n } of _) appendActiveSqliteTranscriptFileIssues(e, n, t);
		for (const e of g) updateMigrationManifestTarget(m, createMigrationTargetInput(e), e.issues);
		await archiveImportedLegacySessionStores(_, m, h, void 0, publishArchive);
		for (const e of _) if (e.retainedImportVerified && e.deferredPluginIds.length === 0) try {
			retireDeferredPluginSessionImport({
				cfg: r,
				env: n,
				target: e.sourceTarget,
				sqlitePath: e.target.sqlitePath
			});
		} catch (t) {
			e.report.issues.push({
				code: "retained_plugin_source_conflict",
				message: `Deferred import receipt awaits retirement: ${formatErrorMessage(t)}. Run openclaw doctor --fix to retry.`
			});
			updateMigrationManifestTarget(m, e.target, e.report.issues);
		}
		const i = g.some((e) => countBlockingSessionSqliteIssues(e) > 0);
		m.manifest.completedAt = (/* @__PURE__ */ new Date()).toISOString();
		if (i) {
			m.manifest.failedAt = m.manifest.completedAt;
			writeSessionSqliteMigrationManifest(m);
			const e = writeSessionSqliteMigrationFailureReports(m.manifestPath, { reason: "doctor import reported session SQLite migration issues" });
			m.manifest.failureReports = e;
		}
		writeSessionSqliteMigrationManifest(m);
	}
	const v = summarizeDoctorSessionSqliteReport(e.mode, g, m);
	if (m) {
		const e = _.filter((e) => e.retainedImportVerified && e.deferredPluginIds.length > 0 && !e.sourceConflicts?.size).map((e) => {
			const t = readDeferredPluginSessionImport({
				cfg: r,
				target: e.sourceTarget,
				sqlitePath: e.target.sqlitePath,
				env: n
			});
			if (!t) throw new Error("Verified retained session import receipt is missing.");
			return {
				owner: e,
				receipt: t
			};
		});
		if (e.length > 0) retainedArchivePlans.set(v, {
			cfg: r,
			env: { ...n },
			owners: e
		});
	}
	return v;
}
/** Verified originals retained for unavailable plugins still await settlement. */
function hasRetainedDoctorSessionSources(e) {
	return retainedArchivePlans.has(e);
}
/** Retire only this import's verified originals before the last plugin obligation clears. */
async function settleRetainedDoctorSessionSources(e, t, n, r) {
	const i = retainedArchivePlans.get(e);
	if (!i) return;
	const assertCurrent = () => {
		n.assertCurrent();
		r();
	};
	assertCurrent();
	retainedArchivePlans.delete(e);
	const a = new Set(t);
	const o = readDeferredPluginMigrations({ env: i.env });
	if (o.filter((e) => !a.has(e.pluginId)).length > 0) return;
	const publishArchive = (e, t) => {
		const r = withDeferredPluginMigrationsCurrent({
			env: i.env,
			expectedPending: o,
			onConflict(e) {
				n.assertCurrent();
				t();
				return e;
			}
		}, () => {
			e();
		});
		if (r) throw new DeferredPluginMigrationConflictError(r, {
			expected: o,
			phase: "session source retirement"
		});
	};
	const verifyImports = () => {
		assertCurrent();
		for (const { owner: e, receipt: t } of i.owners) {
			const n = readDeferredPluginSessionImport({
				cfg: i.cfg,
				target: e.sourceTarget,
				sqlitePath: e.target.sqlitePath,
				env: i.env
			});
			if (!n || !isDeepStrictEqual(n, t)) throw new Error("Verified retained session import receipt changed before settlement.");
		}
	};
	const s = i.owners.map(({ owner: e }) => ({
		...e,
		deferredPluginIds: [],
		report: {
			...e.report,
			archivedLegacyStoreFiles: [...e.report.archivedLegacyStoreFiles ?? []],
			archivedTranscriptFiles: [...e.report.archivedTranscriptFiles],
			archivedUnreferencedJsonlFiles: [...e.report.archivedUnreferencedJsonlFiles],
			issues: e.report.issues.filter((e) => e.code !== "plugin_migration_source_retained")
		}
	}));
	let c;
	let l;
	try {
		verifyImports();
		const e = gatherLegacyArchiveCoverage(i.cfg, i.env, s.map(({ sourceTarget: e }) => e));
		verifyImports();
		const n = s.map(({ target: e }) => e);
		assertDoctorSqliteMaintenancePathsNotAliased("retained session source settlement", resolveDoctorSessionSqliteMaintenancePaths(n), resolveDoctorSessionSqliteMaintenanceRoots(n, i.env));
		assertCurrent();
		c = createSessionSqliteMigrationRun(i.env, n);
		for (const e of s) updateMigrationManifestTarget(c, e.target, e.report.issues, { validationBeforeArchive: "passed" });
		const r = new Set(i.owners.flatMap(({ receipt: e }) => e.sources.map((e) => e.path)));
		await archiveLegacyArtifacts(s, e, c, assertCurrent, r, publishArchive);
		verifyImports();
		await archiveImportedLegacySessionStores(s.filter((e) => e.report.issues.every(isRetainedSourceSettlementIssue)), c, e, assertCurrent, publishArchive);
		verifyImports();
		const a = s.flatMap((e) => e.report.issues).find((e) => !isRetainedSourceSettlementIssue(e));
		if (a || s.some((e) => fs.existsSync(e.target.storePath))) throw new Error(a?.message ?? "Retained session sources could not be archived.");
		for (const { owner: e } of i.owners) retireDeferredPluginSessionImport({
			cfg: i.cfg,
			env: i.env,
			target: e.sourceTarget,
			sqlitePath: e.target.sqlitePath,
			completedPluginIds: t,
			assertCurrent
		});
	} catch (e) {
		l = e instanceof Error ? e : new Error(formatErrorMessage(e));
		const t = s.filter((e) => e.report.issues.some((e) => !isRetainedSourceSettlementIssue(e)));
		for (const [n, r] of s.entries()) {
			const a = r.report.issues.find((e) => !isRetainedSourceSettlementIssue(e));
			for (const e of i.owners[n].owner.report.issues) if (e.code === "plugin_migration_source_retained") r.report.issues.push(e);
			if (t.length === 0 || t.includes(r)) r.report.issues.push({
				code: "retained_plugin_source_settlement_failed",
				message: a?.message ?? formatErrorMessage(e)
			});
		}
	}
	for (const [e, t] of s.entries()) Object.assign(i.owners[e].owner.report, t.report);
	if (c) {
		assertCurrent();
		for (const e of s) updateMigrationManifestTarget(c, e.target, e.report.issues);
		c.manifest.completedAt = (/* @__PURE__ */ new Date()).toISOString();
		if (l) c.manifest.failedAt = c.manifest.completedAt;
		writeSessionSqliteMigrationManifest(c);
	}
	Object.assign(e, summarizeDoctorSessionSqliteReport(e.mode, e.targets, c));
	if (l) throw l;
}
/** Called only under the public maintenance lock, before its strict alias recheck. */
async function reconcileDoctorSessionSqlitePublication(e, t) {
	const n = e.env ?? process.env;
	const r = resolveDoctorSessionSqliteConfig(e);
	const i = resolveDoctorSessionSqliteTargets({
		...e,
		cfg: r,
		env: n
	});
	assertDoctorSessionSqliteTargetsNotAliased({
		...e,
		...i,
		env: n
	});
	await reconcileSessionSqliteMigrationPublications({
		env: n,
		sourcePath: t,
		trustedTargets: i.targets.map(createMigrationTargetInput)
	});
}
async function inspectOrMigrateTarget(e) {
	const t = [];
	const n = e.target.storePath.endsWith(".sqlite");
	const r = createDoctorSessionSqliteTargetReport({
		...e.target,
		sqlitePath: resolveTargetSqlitePath(e.target, e.env),
		sqliteEntries: readSqliteEntryCount(e.target),
		archivedLegacyStoreFiles: [],
		issues: t
	});
	const updateManifest = (t) => updateMigrationManifestTarget(e.activeRun, createMigrationTargetInput(e.target), r.issues, { validationBeforeArchive: t });
	const i = await prepareRetainedSessionImport(e, r);
	if (!i) return r;
	const { retainedImport: a, staleImport: o, sourceConflicts: s, retainedIndexPath: c } = i;
	if (e.mode === "recover" && !shouldFilterLegacySessionRecordsByTarget(e.target)) await archiveConflictingRetainedSessionSources(e, s, r);
	const l = n || s.has(path.resolve(e.target.storePath)) ? [] : readLegacySessionRecords(e.target, t, {
		allowMissingStore: true,
		...c ? { sourcePath: c } : {},
		verifiedSourcePaths: a ? new Set(a.sources.map((e) => e.path)) : void 0
	});
	if (!n && (!a || !c) && e.mode !== "inspect" && e.mode !== "compact" && (t.every(({ code: e }) => e === "retained_plugin_source_index_rebuilt") || a || o)) await appendLegacyHistoricalTranscripts({
		...e,
		allRecords: l,
		retainedImport: a,
		sourceConflicts: s,
		issues: t
	});
	let u = shouldFilterLegacySessionRecordsByTarget(e.target) ? l.filter((t) => isLegacySessionRecordOwnedByTarget(e.cfg, e.target, t.sessionKey)) : l;
	if (o) {
		const n = readOnlySqliteValidationSnapshot(e.target);
		if (!n.ok) {
			t.push({
				code: "sqlite_read_failed",
				message: String(n.error)
			});
			return r;
		}
		u = u.filter((e) => {
			if (!n.snapshot.archivedSessionIds.has(e.entry.sessionId)) {
				e.preserveCurrentSession = true;
				return true;
			}
			t.push({
				code: "historical_transcript_deferred",
				sessionKey: e.sessionKey,
				message: `${e.transcriptPath}: live SQLite already archives this history. Retained source was not replayed; existing deletion and archive state remain authoritative.`
			});
			return false;
		});
	}
	const d = new Set(l.flatMap((e) => e.transcriptPath ? [e.transcriptPath] : []));
	Object.assign(r, {
		legacyEntries: u.length,
		referencedTranscriptFiles: d.size,
		unreferencedJsonlFiles: n ? [] : listUnreferencedJsonlFiles(e.target.storePath, [...d])
	});
	const f = a ? new Set(a.sources.map((e) => canonicalMigrationFilePath(e.path))) : void 0;
	if (e.mode === "import" && a || e.mode === "recover") {
		const t = await prepareActiveSqliteTranscriptSettlement({
			target: e.target,
			env: e.env,
			report: r,
			excludedPaths: f ?? /* @__PURE__ */ new Set()
		});
		if (t.length > 0) {
			const i = createMigrationTargetInput(e.target);
			const a = e.activeRun ?? createSessionSqliteMigrationRun(e.env, [i]);
			const o = gatherLegacyArchiveCoverage(e.cfg, e.env, [e.target]);
			if (n) o.selectedStorePaths.add(i.storePath);
			await archiveLegacyArtifacts([{
				sourceTarget: e.target,
				target: i,
				report: r,
				validated: true,
				deferredPluginIds: [],
				retainedImportVerified: false,
				records: t.map(({ entry: e, ...t }) => ({
					...t,
					sessionId: e.sessionId
				}))
			}], o, a, void 0, new Set(t.map((e) => e.transcriptPath)));
			updateMigrationManifestTarget(a, i, r.issues, { validationBeforeArchive: "passed" });
			if (!e.activeRun) {
				a.manifest.completedAt = (/* @__PURE__ */ new Date()).toISOString();
				writeSessionSqliteMigrationManifest(a);
			}
		}
	}
	if (e.mode === "import" && a) {
		for (const t of r.unreferencedJsonlFiles) if (!f?.has(canonicalMigrationFilePath(t)) && fs.existsSync(t)) r.issues.push({
			code: "plugin_migration_source_retained",
			message: `${t}: skipped because the deferred-plugin-session-import receipt for ${e.target.storePath} still retains inputs for plugin(s): ${a.pluginIds.join(", ")}. Run openclaw doctor --fix to finish or retire the plugin migration, then rerun openclaw doctor --session-sqlite import. The new transcript remains in place.`
		});
	}
	if (a && e.mode !== "import" && a.sources.some((e) => fs.existsSync(e.path))) appendRetainedPluginSessionSourceIssue(r, e.deferredPluginIds ?? []);
	if (e.mode === "compact") {
		await compactSqliteDatabase(e.target, r, { env: e.env });
		r.sqliteEntries = readSqliteEntryCount(e.target);
	}
	if (n || e.mode === "inspect" || e.mode === "compact") {
		appendSqliteDbStats(e.target, r);
		if (e.mode !== "compact") appendActiveSqliteTranscriptFileIssues(e.target, r, f);
		return r;
	}
	if (u.length === 0 && r.unreferencedJsonlFiles.length === 0 && !fs.existsSync(e.target.storePath) && !a) {
		if (t.length === 0) r.sqliteEntries = 0;
		updateManifest();
		return r;
	}
	if (!a && e.verifyMissingIndex(r)) {
		updateManifest("passed");
		return r;
	}
	if (a) countRetainedSessionSources(i, u, r);
	else if (e.mode === "import") await importLegacySessionRecords(e, u, r, e.activeRun);
	else if (e.mode === "dry-run") for (const e of u) countLegacyTranscript(e, r);
	else validateLegacySessionRecords(e.target, u, r, "validate", e.env);
	let p = a !== void 0;
	if (e.mode === "import") updateManifest(a ? "passed" : "failed");
	if (e.mode === "import" && !a && countBlockingSessionSqliteIssues(r) === 0) {
		p = validateLegacySessionRecords(e.target, u, r, "before-archive", e.env);
		updateManifest(p ? "passed" : "failed");
		if (p && e.activeRun) {
			const t = u.flatMap((e) => e.historical?.archiveMove && e.recovery?.complete ? [{
				...e.historical.archiveMove,
				sessionKey: e.sessionKey,
				artifact: {
					...e.historical.archiveMove.artifact,
					classification: "protected",
					reason: HISTORICAL_IMPORT_REASON
				}
			}] : []);
			if (t.length > 0) {
				recordPlannedMigrationMoves(e.activeRun, createMigrationTargetInput(e.target), t);
				recordCompletedMigrationMoves(e.activeRun, createMigrationTargetInput(e.target), t);
			}
		}
		if (p) await compactSqliteDatabase(e.target, r, {
			env: e.env,
			operation: "import-finalize"
		});
	}
	if (e.mode === "import") {
		const t = e.expectedIndexIdentity;
		const n = !t && !fs.existsSync(e.target.storePath);
		const i = n && (!e.configuredAgentIds.has(e.target.agentId) || u.length === 0) ? [] : e.deferredPluginIds ?? [];
		const o = p && (a !== void 0 || u.length > 0 || fs.existsSync(resolveTargetSqlitePath(e.target, e.env)));
		let c = a !== void 0;
		let l = a?.sources;
		if (!a && o && (t || u.some((e) => !e.historical?.archiveMove) || r.unreferencedJsonlFiles.length > 0) && r.issues.every(isRetainedSourceIssue)) try {
			l = captureDeferredPluginSessionSources({
				storePath: e.target.storePath,
				indexIdentity: t,
				records: u,
				unreferencedJsonlFiles: r.unreferencedJsonlFiles,
				referencedPaths: e.referencedPaths
			});
		} catch (e) {
			r.issues.push({
				code: "transcript_archive_failed",
				message: formatErrorMessage(e)
			});
		}
		if (i.length > 0 && o && r.issues.every(isRetainedSourceIssue)) {
			if (!a) {
				if (!l) {
					r.sqliteEntries = readSqliteEntryCount(e.target);
					return r;
				}
				recordDeferredPluginSessionImport({
					cfg: e.cfg,
					target: e.target,
					sqlitePath: resolveTargetSqlitePath(e.target, e.env),
					env: e.env,
					pluginIds: i,
					sources: l,
					recordCount: u.length
				});
				c = true;
				if (n) r.issues.push({
					code: "retained_plugin_source_index_rebuilt",
					message: `Derived the retained source index from verified transcripts for ${path.dirname(e.target.storePath)}. Recorded their identities in the completed import receipt without creating sessions.json or replaying existing metadata.`
				});
			}
			appendRetainedPluginSessionSourceIssue(r, i);
		}
		e.archiveTargets?.push({
			sourceTarget: e.target,
			target: createMigrationTargetInput(e.target),
			report: r,
			validated: p,
			deferredPluginIds: i,
			retainedImportVerified: c,
			sourceConflicts: s,
			verifiedSources: l,
			records: u.filter((e) => !e.historical?.archiveMove && !s.has(e.transcriptPath ?? "")).map(({ entry: e, ...t }) => Object.assign(t, { sessionId: e.sessionId }))
		});
	}
	r.sqliteEntries = readSqliteEntryCount(e.target);
	if (e.mode !== "import") appendActiveSqliteTranscriptFileIssues(e.target, r, f);
	updateManifest();
	return r;
}
async function archiveLegacyArtifacts(e, t, n, r, i, a) {
	const { selectedStorePaths: o, referencedPaths: s, retainedPaths: c, incompleteDirectories: l, retainedDirectories: u } = t;
	const d = /* @__PURE__ */ new Map();
	for (const t of e) {
		if (!t.validated || countBlockingSessionSqliteIssues(t.report) > 0) o.delete(t.target.storePath);
		for (const e of t.records) {
			if (!e.transcriptPath) continue;
			const n = canonicalMigrationFilePath(e.transcriptPath);
			d.set(n, [...d.get(n) ?? [], {
				owner: t,
				record: e
			}]);
		}
	}
	const f = [...d].filter(([e, t]) => c.has(e) || u.has(path.dirname(e)) || t.some(({ owner: e }) => !o.has(e.target.storePath))).map(([e]) => e);
	for (const t of f) {
		for (const e of [
			t,
			resolveTrajectoryPath(t),
			resolveTrajectoryPointerPath(t)
		]) if (e) c.add(e);
		for (const { owner: n } of d.get(t) ?? []) {
			const t = n.target.storePath;
			if (!o.delete(t)) continue;
			for (const n of e.filter((e) => e.target.storePath === t)) for (const e of n.records) {
				if (!e.transcriptPath) continue;
				const t = canonicalMigrationFilePath(e.transcriptPath);
				if (!c.has(t)) {
					c.add(t);
					f.push(t);
				}
			}
		}
	}
	const p = /* @__PURE__ */ new Set();
	const m = /* @__PURE__ */ new Map();
	const recordFailure = (e, t, n, r = false) => {
		e.report.issues.push({
			code: r ? "unreferenced_jsonl_archive_failed" : "transcript_archive_failed",
			message: `${t}: ${formatErrorMessage(n)}`
		});
	};
	for (const [e, t] of d) {
		const n = t[0];
		if (!fs.existsSync(e)) {
			if (t.some(({ record: e }) => e.sourceFingerprint)) for (const n of new Set(t.map((e) => e.owner))) recordFailure(n, e, "Imported transcript disappeared before archival");
			continue;
		}
		if (c.has(e) || u.has(path.dirname(e))) {
			for (const { owner: n, record: r } of t) if (countBlockingSessionSqliteIssues(n.report) === 0 && n.deferredPluginIds.length === 0) n.report.issues.push({
				code: "transcript_archive_deferred",
				message: `${e}: retaining the original for an incomplete or unselected importing owner; rerun import for all known owners after resolving their index/import issues.`,
				sessionKey: r.sessionKey
			});
			continue;
		}
		try {
			const r = planImportedTranscriptArtifactsToArchive(n.owner.target, n.record.sessionKey, e, p, i);
			const a = t.map(({ owner: e, record: n }) => n.sourceFingerprint ? n : t.find((t) => t.owner === e && t.record.sessionId === n.sessionId && t.record.sourceFingerprint)?.record);
			const o = a.flatMap((e) => e?.sourceFingerprint ? [e.sourceFingerprint] : []);
			const s = o[0];
			if (s && o.some((e) => [
				"ctimeNs",
				"dev",
				"ino",
				"mtimeNs",
				"size"
			].some((t) => e[t] !== s[t]))) throw new Error("Transcript changed between imports; retaining the unverified original");
			const u = !l.has(path.dirname(e)) && a.every((e) => e?.sourceFingerprint && e.recovery?.complete) && t.every(({ owner: e, record: t }) => !e.report.issues.some((e) => e.code === "transcript_malformed" && e.sessionKey === t.sessionKey));
			for (const e of r) {
				if (c.has(e.sourcePath)) throw new Error("Artifact is required by an incomplete importing owner");
				e.artifact = {
					identity: readMigrationArtifactIdentity(e.sourcePath, 1n, e.kind === "transcript" ? s : void 0),
					classification: u && e.kind === "transcript" && !n.record.historical ? a.some((e) => e?.recovery?.repaired) ? "repair-original" : "imported" : "protected",
					reason: u && n.record.historical && e.kind === "transcript" ? HISTORICAL_IMPORT_REASON : u && e.kind === "transcript" ? "verified-import-original" : "unimported-or-unknown-history",
					...u && e.kind === "transcript" && n.record.recovery?.sqliteEvents !== void 0 ? { verification: `superseded by SQLite (${n.record.recovery.events} of ${n.record.recovery.sqliteEvents} events present)` } : {},
					dependencies: [],
					disposal: { state: "retained" }
				};
				const r = m.get(e.sourcePath);
				if (r) {
					if (e.artifact.classification === "protected") r.move.artifact = e.artifact;
					for (const e of t) r.owners.set(e.owner, e.record.sessionKey);
				} else m.set(e.sourcePath, {
					move: e,
					owners: new Map(t.map((e) => [e.owner, e.record.sessionKey]))
				});
			}
		} catch (n) {
			for (const r of new Set(t.map((e) => e.owner))) recordFailure(r, e, n);
		}
	}
	for (const t of e) {
		const e = t.target.storePath;
		if (!o.has(e) || countBlockingSessionSqliteIssues(t.report) > 0 || l.has(path.dirname(e))) continue;
		const planUnreferencedMove = (e, n) => {
			try {
				const r = planSessionJsonlArchiveMove({
					archiveKey: "archive-tier",
					kind: n,
					reservedArchivePaths: p,
					sourcePathRaw: e,
					target: t.target
				});
				r.artifact = {
					identity: readMigrationArtifactIdentity(e),
					classification: "protected",
					reason: "unreferenced-history",
					dependencies: [],
					disposal: { state: "retained" }
				};
				p.add(r.archivePath);
				m.set(e, {
					move: r,
					owners: /* @__PURE__ */ new Map([[t, void 0]])
				});
				return true;
			} catch (n) {
				recordFailure(t, e, n, true);
				return false;
			}
		};
		const n = /* @__PURE__ */ new Set();
		const r = new Set(t.retainedImportVerified ? (t.verifiedSources ?? []).map((e) => e.path) : []);
		for (const a of listUnreferencedJsonlFiles(e, [...s, ...m.keys()])) {
			if (c.has(a)) continue;
			if (i && !i.has(a) || t.retainedImportVerified && !r.has(a)) continue;
			const e = resolveTrajectoryPointerPath(a);
			if (planUnreferencedMove(a, "unreferenced-jsonl") && e) n.add(e);
		}
		for (const e of collectRetainedTrajectoryPointers(r, t.sourceConflicts)) n.add(e);
		for (const e of n) {
			const n = canonicalMigrationFilePath(e);
			if (fs.existsSync(n) && !m.has(n) && !s.has(n) && !c.has(n) && !t.sourceConflicts?.has(e) && (!i || i.has(n))) planUnreferencedMove(n, "trajectory");
		}
	}
	for (const t of e) for (const { path: e } of t.verifiedSources ?? []) {
		const n = m.get(e);
		if (n && !n.owners.has(t)) n.owners.set(t, void 0);
	}
	const movesForOwner = (e) => [...m.values()].filter((t) => t.owners.has(e)).map(({ move: t, owners: n }) => Object.assign({}, t, { sessionKey: n.get(e) }));
	for (const t of e) {
		r?.();
		recordPlannedMigrationMoves(n, t.target, movesForOwner(t));
	}
	const h = /* @__PURE__ */ new Set();
	for (const { move: e, owners: t } of m.values()) try {
		for (const n of t.keys()) assertSafeSessionSqliteMigrationMove(e, n.target);
		r?.();
		await moveMigrationArtifact(e.sourcePath, e.archivePath, e.artifact.identity, r, a);
		r?.();
		h.add(e.sourcePath);
		for (const { report: n } of t.keys()) (e.kind === "unreferenced-jsonl" ? n.archivedUnreferencedJsonlFiles : n.archivedTranscriptFiles).push(e.archivePath);
	} catch (n) {
		if (n instanceof DeferredPluginMigrationConflictError && n.pending.length > 0) break;
		for (const r of t.keys()) recordFailure(r, e.sourcePath, n, e.kind === "unreferenced-jsonl");
	}
	for (const t of e) {
		r?.();
		recordCompletedMigrationMoves(n, t.target, movesForOwner(t).filter((e) => h.has(e.sourcePath)));
		t.report.unreferencedJsonlFiles = listUnreferencedJsonlFiles(t.target.storePath, [...s]);
	}
}
//#endregion
export { hasRetainedDoctorSessionSources, reconcileDoctorSessionSqlitePublication, runDoctorSessionSqlite, settleRetainedDoctorSessionSources };