UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4,393 lines • 164 kB
import { c as hasErrnoCode, f as coerceErrorMessage, h as extractErrorCode } from "./paths-0xDagtub.mjs";
import { c as isAbortError, p as isRecord, r as resolveConfigDir } from "./utils-BclMknzT.mjs";
import { V as readGlobalSingleton, W as resolveGlobalSingleton, a as resolveStateDir, f as resolveRequiredOsHomeDir, n as isPathInside, v as MAX_TIMER_TIMEOUT_MS } from "./path-guards-quCEQx1i.mjs";
import { d as withSqliteNativeOpen, i as markSqliteInspectionOperation, n as isSqliteLockError, o as readSqliteInspectionOperation, t as isSqliteCorruptionError } from "./sqlite-error-diagnostics-DXQCgyiD.mjs";
import { t as mergeProcessEnv } from "./process-env-Bx8i77R6.mjs";
import "./sqlite-user-version-D-rYjp-A.mjs";
import { o as OPENCLAW_DATABASE_SCHEMA_DOCS_URL } from "./openclaw-state-db-contract-DpFGI8ZZ.mjs";
import { D as containsEnvVarReference, v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs";
import { C as removeTempDirectoryAsync, D as SQLITE_SNAPSHOT_PREFIX, F as sameFileMutationFingerprint, I as artifactPreservingReads, L as isArtifactPreservingStateRead, M as hashPublishedFileSync, N as sameFileStatFingerprint, O as acquireSqliteSnapshotToken, S as removeTempDirectory, T as retainSnapshotWork, _ as discardPreparedCopyPayload, a as resolveSqliteInspectionSignal, b as registerRetainedSnapshotTempDirectory, c as runSqliteReadOnlyWorkerSync, d as isPrivateDirectoryCreationRefused, f as markPrivateDirectoryCreationRefused, g as adoptPreparedLocation, i as isSqliteInspectionDeadlineOwnedByCaller, l as SqliteSnapshotCapacityError, n as captureSqliteReadOnlyWorkerLaunch, r as createScopedSqliteReadOnlyWorker, s as runSqliteReadOnlyWorkerOnce, t as captureSqliteSnapshotStagingOwner, u as hasSqliteSnapshotCapacityCode, v as preparationCleanupError, w as retainSnapshotTempDirectory, x as registerSnapshotTempDirectory, y as publishPreparedCopy } from "./sqlite-snapshot-staging-owner-D6iplEEs.mjs";
import { n as isDangerousHostEnvVarName, r as normalizeEnvVarKey, t as isDangerousHostEnvOverrideVarName } from "./host-env-security-Cdlya5OY.mjs";
import { a as resolvePreferredOpenClawTmpDir, f as runWithMainThreadTask, t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-G5_kmB_7.mjs";
import { i as runInDetachedAsyncContext } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { f as runOutsideAsyncWorkScope, u as AsyncWorkScope } from "./openclaw-root-l-fyeuXJ.mjs";
import { n as isPostgresSqlConnection, r as sqlPublicationAnchor } from "./sql-connection-VmV9pnJI.mjs";
import { c as registerNodeSqliteDisposeCallback, l as registerNodeSqliteDisposeGuard, t as clearNodeSqliteKyselyCacheForDatabase, u as registerNodeSqliteKyselyQueryErrorHandler } from "./kysely-sync-cache-state-D75yJYFp.mjs";
import { c as normalizeDatabasePath, f as readDatabasePathIdentitySync, l as readDatabaseFileIdentity, n as assertExistingDatabaseIdentity, t as assertDatabaseFileIdentity } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { o as resolveOpenClawStateSqlitePath, r as resolveDatabasePath, s as resolveQuarantineStorePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { S as getNodeSqliteKysely, b as executeSqliteQuerySync, i as tableExists, l as getStateRuntimeSchemaAdmission, x as executeSqliteQueryTakeFirstSync } from "./openclaw-state-db-schema-helpers-Bn-sHIhd.mjs";
import { a as clearFsSafeEnvFallback, i as resolveEnvNormalizationKeys, o as fsSafeEnvInput, r as normalizeZaiEnv, s as normalizeFsSafeNativeEnv, t as expandEnvNormalizationKeys } from "./env-C62NiKTo.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { a as SqliteSnapshotCleanupError, c as createSqliteLifecycleAggregateError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { Ct as stageSqliteTransactionState, D as revokeSqliteDatabaseAdmissionsForPath, E as revokeSqliteDatabaseAdmissions, J as normalizeSchemaSql, K as findSqlClosingParenthesis, S as recordSqliteDatabaseIntegrity, _ as publishSqliteDatabaseAdmission, a as getOrLoadSqliteDatabaseAdmissionForPath, b as readSqliteDatabaseWriteRevision, f as onSqliteDatabaseWriteSettled, g as prepareSqliteDatabaseCleanClose, ht as readSqliteReaderDiagnosticsForPath, o as getSqliteDatabaseAdmission, p as peekSqliteDatabaseAdmissionForPath, vt as sqliteReaderDatabasePathKey, x as readSqliteDatabaseWriteTokenForPath, z as requireNodeSqlite } from "./sqlite-database-admission-DMm34jqt.mjs";
import { a as setSqliteBusyTimeout, i as runWithSqliteBusyTimeout, t as normalizeSqliteNonNegativeInteger } from "./sqlite-busy-timeout-BbWQYMTz.mjs";
import { i as normalizeLegacyDotBetaVersion, t as compareOpenClawSemver } from "./semver-DUtldgR6.mjs";
import { c as runSqliteReadOperationSync, d as readSqliteSchemaObjects, f as schemaAdmission, o as readSqliteNativeMutationRevision, s as registerSqliteSchemaMutationListener } from "./sqlite-schema-facts-BFHoBJFZ.mjs";
import { i as resolveSqliteFilesystemPath, n as resolveExistingSqliteFileUri, r as resolveImmutableSqliteFileUri, t as openNodeSqliteDatabase } from "./node-sqlite-DrCtoYsd.mjs";
import { m as sha256FileSync } from "./gateway-process-argv-DB5Y-Mad.mjs";
import { u as getDatabaseEngineSelection } from "./worker-task-pool-DBu8jMlX.mjs";
import { d as flatMapRetainedOperation, f as mapRetainedOperation, l as createRetainedOperation } from "./worker-cpu-sx0tpDpz.mjs";
import { c as isOpenClawDatabaseMaintenanceResourceOwned, l as maintenanceOwnerHasSourceCustody, n as createOpenClawStateDatabaseAsyncLifecycle, o as getOpenClawDatabaseMaintenanceResourceScope, r as isStateDatabaseReadAdmissionInvalidatedError, s as getOpenClawDatabaseMaintenanceScope, t as StateDatabaseReadAdmissionInvalidatedError, u as observeOpenClawDatabaseMaintenanceResource } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import "./fs-safe-CQCGsM4r.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-DYxlAnZ2.mjs";
import { i as assertStateDatabaseReadAllowed, r as assertStateDatabaseAccessAllowed } from "./gateway-state-owner-CW5kvbov.mjs";
import { c as OpenClawQuarantineReadCleanupError, s as markOpenClawStateDatabaseFailure } from "./openclaw-state-worker-error-Blekn2XA.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-DjndFB3C.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import { promisify } from "node:util";
import fsSync, { existsSync, mkdirSync, realpathSync } from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { copyRootFileSync, createDirectorySync, createFileSync, readFileWindowFullySync, sameFileContentsSync, sameFileIdentity } from "@openclaw/fs-safe/advanced";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import fsPromises from "node:fs/promises";
import { performance as performance$1 } from "node:perf_hooks";
import { isMainThread, threadId } from "node:worker_threads";
import { expressionBuilder, sql } from "kysely";
import { parse } from "semver";
import { setImmediate } from "node:timers/promises";
import { probeTreeClone } from "@openclaw/fs-safe/copy";
import "kysely/helpers/sqlite";
//#region src/infra/sqlite-files.ts
/** SQLite main database plus every journal-mode sidecar that can contain database pages. */
const SQLITE_DATABASE_FILE_SUFFIXES = [
	"",
	"-wal",
	"-shm",
	"-journal"
];
const SQLITE_SIDECAR_SUFFIXES = SQLITE_DATABASE_FILE_SUFFIXES.slice(1);
const SQLITE_WAL_HEADER_BYTES = 32;
const APPLE_DOUBLE_MAGIC = Buffer.from([
	0,
	5,
	22,
	7
]);
const sqliteFilesLog = createSubsystemLogger("state/sqlite");
var SqliteOrphanedSidecarsError = class extends Error {
	constructor(e, t, n) {
		super(`SQLite database is missing at ${e}, and orphaned sidecars could not be copied: ${t.join(", ")}. Refusing to open because SQLite could delete orphan WAL or journal state. Preserve the sidecar bytes, restore the main database, and pair it with the matching sidecar before retrying.`, { cause: n });
		this.name = "SqliteOrphanedSidecarsError";
	}
};
/** Resolves the main database and all possible journal-mode sidecar paths. */
function resolveSqliteDatabaseFilePaths(e) {
	return SQLITE_DATABASE_FILE_SUFFIXES.map((t) => `${e}${t}`);
}
function findMatchingOrphanedSidecarCopy(e, t) {
	const n = path.dirname(e);
	const r = `${path.basename(e)}.orphaned-`;
	const i = fsSync.readdirSync(n, { withFileTypes: true }).filter((e) => e.isFile() && e.name.startsWith(r)).map((e) => path.join(n, e.name)).filter((e) => fsSync.statSync(e).size === t);
	if (i.length === 0) return;
	const a = sha256FileSync(e);
	for (const e of i) if (sha256FileSync(e) === a) return e;
}
function copyOrphanedSidecar(e, t) {
	const n = `${e}.orphaned-${t}`;
	for (let t = 0;; t += 1) {
		const r = t === 0 ? n : `${n}-${t}`;
		try {
			fsSync.copyFileSync(e, r, fsSync.constants.COPYFILE_EXCL);
			return r;
		} catch (e) {
			if (e.code !== "EEXIST") throw e;
		}
	}
}
/** Preserve durable orphan sidecars before SQLite creates a replacement main database. */
function quarantineOrphanedSqliteSidecars(e) {
	if (fsSync.existsSync(e)) return;
	const t = [{
		path: `${e}-wal`,
		minimumBytes: SQLITE_WAL_HEADER_BYTES
	}, {
		path: `${e}-journal`,
		minimumBytes: 0
	}].flatMap((e) => {
		const t = fsSync.statSync(e.path, { throwIfNoEntry: false });
		return t?.isFile() === true && t.size > e.minimumBytes ? [{
			path: e.path,
			size: t.size
		}] : [];
	});
	if (t.length === 0) return;
	const n = Date.now();
	const r = [];
	try {
		for (const e of t) {
			if (findMatchingOrphanedSidecarCopy(e.path, e.size)) continue;
			const t = copyOrphanedSidecar(e.path, n);
			r.push({
				quarantinePath: t,
				sourcePath: e.path
			});
		}
	} catch (n) {
		throw new SqliteOrphanedSidecarsError(e, t.map((e) => e.path), n);
	}
	if (r.length === 0) return;
	const i = r.map(({ sourcePath: e, quarantinePath: t }) => `${e} -> ${t}`);
	sqliteFilesLog.warn(`SQLite database is missing at ${e}; copied orphaned sidecars: ${i.join(", ")}. Committed frames could not be applied because the main database is missing. The bytes are preserved. Recovery requires restoring the main database and pairing it with the quarantined file.`, {
		databasePath: e,
		copiedSidecars: r
	});
}
//#endregion
//#region src/infra/update-rehearsal-paths.ts
/** Declare the private filesystem namespace shared by every rehearsal child. */
function buildUpdateRehearsalPathEnv(e) {
	return {
		HOME: e,
		USERPROFILE: e,
		TMPDIR: e,
		TMP: e,
		TEMP: e,
		XDG_CONFIG_HOME: path.join(e, "config"),
		XDG_CACHE_HOME: path.join(e, "cache"),
		XDG_DATA_HOME: path.join(e, "data"),
		XDG_STATE_HOME: path.join(e, "state"),
		OPENCLAW_HOME: e,
		OPENCLAW_STATE_DIR: e,
		OPENCLAW_CONFIG_PATH: path.join(e, "openclaw.json"),
		OPENCLAW_WORKSPACE_DIR: path.join(e, "workspace"),
		OPENCLAW_SKIP_CHANNELS: "1",
		OPENCLAW_SKIP_PROVIDERS: "1",
		OPENCLAW_SKIP_CRON: "1",
		OPENCLAW_SKIP_GMAIL_WATCHER: "1",
		OPENCLAW_SKIP_CANVAS_HOST: "1",
		OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
		OPENCLAW_SKIP_STARTUP_MODEL_PREWARM: "1",
		OPENCLAW_NO_AUTO_UPDATE: "1",
		NODE_DISABLE_COMPILE_CACHE: "1"
	};
}
/**
* Rehearsal copies are private SQLite images, never live PostgreSQL anchors.
* Current drivers already write this projection into the rehearsal config
* (update-candidate-rehearsal.ts isolatedConfig); 2026.11.3 and older drivers
* copy PostgreSQL selections unchanged, so the candidate's config read applies
* it too. Removable once those drivers are no longer supported update sources.
*/
function projectUpdateRehearsalDatabaseConfig(e, t) {
	if (!isRecord(e) || !isRecord(e.database) || !resolveUpdateRehearsalRoot(t)) return e;
	const { engine: n, families: r } = e.database;
	return n === "postgres" || isRecord(r) && Object.values(r).some((e) => isRecord(e) && e.engine === "postgres") ? {
		...e,
		database: { engine: "sqlite" }
	} : e;
}
/** Recognize the complete 9.3+ driver contract; update-in-progress alone is also used by live Doctor. */
function resolveUpdateRehearsalRoot(e) {
	const t = e.OPENCLAW_STATE_DIR;
	if (!t || !path.isAbsolute(t) || !["0", "1"].includes(e.OPENCLAW_UPDATE_IN_PROGRESS ?? "") || Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t, n]) => e[t] !== n) || e.OPENCLAW_SERVICE_REPAIR_POLICY !== "external" || e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR !== "0" || e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION !== "0" || Boolean(e.OPENCLAW_COMPATIBILITY_HOST_VERSION)) return;
	return path.resolve(t);
}
/** Uncopied absolute locators remain inventory; they cannot grant writes outside the private root. */
function isUpdateRehearsalReadOnlyPath(e, t) {
	const n = resolveUpdateRehearsalRoot(t);
	if (!n) return false;
	const r = path.resolve(e);
	return !isPathInside(n, r) || !isPathInside(resolveIdentityPathViaExistingAncestorSync(n), resolveIdentityPathViaExistingAncestorSync(r));
}
/** Reuse prepared images only when the entire SQLite family stays in the disposable namespace. */
function isUpdateRehearsalPrivateDatabase(e, t) {
	return resolveUpdateRehearsalRoot(t) !== void 0 && resolveSqliteDatabaseFilePaths(e).every((e) => !isUpdateRehearsalReadOnlyPath(e, t));
}
//#endregion
//#region src/config/version.ts
/** Parses stable, prerelease, and legacy dot-beta OpenClaw versions. */
function parseOpenClawVersion(e) {
	if (!e) return null;
	const t = normalizeLegacyDotBetaVersion(e.trim());
	return parse(t);
}
function compareOpenClawVersions(e, t) {
	const n = parseOpenClawVersion(e);
	const r = parseOpenClawVersion(t);
	if (!n || !r) return null;
	return compareOpenClawSemver(n, r);
}
//#endregion
//#region src/config/future-version-guard.ts
/** Override env var for intentional older-binary destructive config actions. */
const ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS_ENV = "OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS";
//#endregion
//#region src/config/config-env-values.ts
/** Returns whether a config-controlled environment entry is safe to apply at runtime. */
function isConfigRuntimeEnvVarAllowed(e, t) {
	const n = e.toUpperCase();
	return Boolean(t.trim()) && n !== "OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS" && n !== "OPENCLAW_INCLUDE_ROOTS" && n !== "OPENCLAW_CONFIG_READONLY" && n !== "OPENCLAW_CONFIG_READONLY_NOTICE" && n !== "OPENCLAW_DISABLE_GATEWAY_LOCAL_TERMINALS" && n !== "OPENCLAW_DISABLE_CRON_HOST_EXECUTION" && !isDangerousHostEnvVarName(e) && !isDangerousHostEnvOverrideVarName(e) && !containsEnvVarReference(t);
}
/** Collects config env vars safe to inject into runtime process environments. */
function collectConfigRuntimeEnvVars(e) {
	const t = e?.env;
	if (!t) return {};
	const n = {};
	const r = [...Object.entries(t.vars ?? {}), ...Object.entries(t).filter(([e]) => e !== "shellEnv" && e !== "vars")];
	for (const [e, t] of r) {
		if (typeof t !== "string") continue;
		const r = normalizeEnvVarKey(e, { portable: true });
		if (r && isConfigRuntimeEnvVarAllowed(r, t)) n[r] = t;
	}
	return n;
}
function findCaseInsensitiveEnvKey(e, t) {
	if (Object.hasOwn(e, t)) return t;
	const n = t.toUpperCase();
	return Object.keys(e).find((e) => e.toUpperCase() === n);
}
function envSnapshotKey(e) {
	return process.platform === "win32" ? e.toUpperCase() : e;
}
function indexConfigRuntimeEnvValues(e) {
	const t = /* @__PURE__ */ new Map();
	for (const [n, r] of Object.entries(e)) for (const e of resolveEnvNormalizationKeys(n)) {
		const n = t.get(e) ?? /* @__PURE__ */ new Set();
		n.add(r);
		t.set(e, n);
	}
	return t;
}
//#endregion
//#region src/config/config-env-vars.ts
const appliedConfigEnvOwnership = /* @__PURE__ */ new WeakMap();
function resolveAppliedConfigEnvOwnership(e) {
	return {
		...appliedConfigEnvOwnership.get(e),
		...e === process.env ? publishedConfigRuntimeEnvState.ownedEnv : {}
	};
}
const configReadEnvChanges = new AsyncLocalStorage();
function cloneEnvWithPlatformSemantics(e) {
	let t = { ...fsSafeEnvInput(e) };
	if (process.platform === "win32") t = new Proxy(t, {
		deleteProperty(e, t) {
			if (typeof t !== "string") return Reflect.deleteProperty(e, t);
			const n = findCaseInsensitiveEnvKey(e, t);
			return n ? Reflect.deleteProperty(e, n) : true;
		},
		get(e, t, n) {
			if (typeof t !== "string") return Reflect.get(e, t, n);
			const r = findCaseInsensitiveEnvKey(e, t);
			return r ? e[r] : Reflect.get(e, t, n);
		},
		getOwnPropertyDescriptor(e, t) {
			if (typeof t !== "string") return Reflect.getOwnPropertyDescriptor(e, t);
			const n = findCaseInsensitiveEnvKey(e, t);
			if (!n) return;
			return {
				configurable: true,
				enumerable: true,
				value: e[n],
				writable: true
			};
		},
		has(e, t) {
			return typeof t === "string" ? findCaseInsensitiveEnvKey(e, t) !== void 0 : Reflect.has(e, t);
		},
		set(e, t, n) {
			if (typeof t !== "string") return Reflect.set(e, t, n);
			e[findCaseInsensitiveEnvKey(e, t) ?? t] = n;
			return true;
		}
	});
	appliedConfigEnvOwnership.set(t, resolveAppliedConfigEnvOwnership(e));
	normalizeFsSafeNativeEnv(t);
	return t;
}
function createConfigRuntimeEnv(e, t = process.env) {
	const n = cloneEnvWithPlatformSemantics(t);
	applyConfigEnvVars(e, n);
	return n;
}
let publishedConfigRuntimeEnvState = {
	ownedEnv: {},
	sourceConfig: null
};
function collectConfigRuntimeEnvOwnership(e, t, n, r = {}) {
	const i = fsSafeEnvInput(t);
	const a = fsSafeEnvInput(n);
	const o = {};
	const s = new Set((r.replacedLowerPrecedenceKeys ?? []).map(envSnapshotKey));
	for (const [t, n] of Object.entries(collectConfigRuntimeEnvVars(e))) for (const e of resolveEnvNormalizationKeys(t)) {
		const t = findCaseInsensitiveEnvKey(a, e);
		if (!t || a[t] !== n) continue;
		const r = findCaseInsensitiveEnvKey(i, e);
		if (r && i[r] === n && !s.has(envSnapshotKey(t))) continue;
		o[t] = n;
	}
	return o;
}
function filterConfigRuntimeEnvOwnership(e, t, n) {
	const r = fsSafeEnvInput(t);
	const i = indexConfigRuntimeEnvValues(collectConfigRuntimeEnvVars(e));
	const a = {};
	for (const [e, t] of Object.entries(n)) {
		const n = resolveEnvNormalizationKeys(e)[0] ?? e;
		const o = findCaseInsensitiveEnvKey(r, e);
		if (o && r[o] === t && i.get(n)?.has(t)) a[o] = t;
	}
	return a;
}
/** Applies config env vars to an environment without overwriting existing non-empty values. */
function applyConfigEnvVars(e, t = process.env, n = {}) {
	clearFsSafeEnvFallback(t);
	const r = { ...t };
	const i = resolveAppliedConfigEnvOwnership(t);
	const a = collectConfigRuntimeEnvVars(e);
	const o = Object.entries(n.lowerPrecedenceEnv ?? {});
	const s = new Map(o.map(([e, t]) => [envSnapshotKey(e), t]));
	const c = expandEnvNormalizationKeys(Object.keys(a));
	const l = indexConfigRuntimeEnvValues(a);
	const u = /* @__PURE__ */ new Map();
	for (const e of Object.keys(a)) {
		const n = resolveEnvNormalizationKeys(e);
		const r = n.map((e) => [e, t[e]]).find(([e, t]) => t?.trim() && s.get(e) !== t && !l.get(e)?.has(t))?.[1];
		if (r !== void 0) for (const e of n) u.set(e, r);
	}
	const d = [];
	for (const [e, n] of o) if (c.has(envSnapshotKey(e)) && t[e] === n) {
		delete t[e];
		d.push(e);
	}
	if (d.length > 0) n.onLowerPrecedenceKeysReplaced?.(d);
	for (const [e, n] of Object.entries(a)) {
		const r = u.get(envSnapshotKey(e));
		if (r !== void 0) {
			t[e] = r;
			continue;
		}
		const i = t[e];
		if (i?.trim() && s.get(envSnapshotKey(e)) !== i) continue;
		t[e] = n;
	}
	normalizeZaiEnv(t);
	appliedConfigEnvOwnership.set(t, {
		...filterConfigRuntimeEnvOwnership(e, t, i),
		...collectConfigRuntimeEnvOwnership(e, r, t, { replacedLowerPrecedenceKeys: d })
	});
	normalizeFsSafeNativeEnv(t);
}
//#endregion
//#region src/infra/sqlite-backup.ts
async function backupNodeSqliteDatabase(e, t, n) {
	const r = setInterval(() => {}, 100);
	try {
		const r = await requireNodeSqlite().backup(e, resolveSqliteFilesystemPath(t), { progress: n });
		n?.({
			totalPages: r,
			remainingPages: 0
		});
		return r;
	} finally {
		clearInterval(r);
	}
}
//#endregion
//#region src/infra/windows-private-directory.ts
function createPrivateWindowsDirectory(e) {
	let t = false;
	try {
		createDirectorySync(path.resolve(e), {
			private: true,
			assertBeforeMutation() {
				t = true;
			}
		});
	} catch (e) {
		if (!t || e instanceof FsSafeError && e.code === "already-exists") throw markPrivateDirectoryCreationRefused(e);
		throw e;
	}
}
//#endregion
//#region src/infra/sqlite-private-directory.ts
function resolvePrivateSqliteSnapshotStagingRoot(e = process.env) {
	try {
		return resolveSnapshotStagingRoot(e);
	} catch (e) {
		if (e instanceof Error && hasSqliteSnapshotCapacityCode(e)) throw new SqliteSnapshotCapacityError(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`, { cause: e });
		throw e;
	}
}
function resolveSnapshotStagingRoot(e) {
	const t = e.OPENCLAW_UPDATE_IN_PROGRESS === "1" ? e.TMPDIR?.trim() : void 0;
	if (t && path.isAbsolute(t)) return resolvePreferredOpenClawTmpDir({
		preferredDir: path.join(t, "openclaw"),
		tmpdir: () => t
	});
	const n = process.platform === "win32" ? e.LOCALAPPDATA?.trim() : void 0;
	const r = process.platform === "win32" ? "AppData/Local" : ".cache";
	const i = process.platform === "darwin" ? "Library/Caches" : r;
	const a = [e.XDG_CACHE_HOME?.trim(), n].find((e) => e && path.isAbsolute(e)) ?? path.join(resolveRequiredOsHomeDir(e), i);
	return resolvePreferredOpenClawTmpDir({
		preferredDir: path.join(a, "openclaw"),
		tmpdir: () => a
	});
}
function createPrivateSqliteTempDirectorySync(e, t) {
	if (process.platform !== "win32") try {
		return fsSync.mkdtempSync(path.join(e, t));
	} catch (e) {
		throw markPrivateDirectoryCreationRefused(e);
	}
	const n = path.join(e, `${t}${randomUUID()}`);
	createPrivateWindowsDirectory(n);
	return n;
}
//#endregion
//#region src/sessions/session-controller.cleanup-context.ts
const cleanupContext = resolveGlobalSingleton(Symbol.for("openclaw.sessionControllerCleanupContext"), () => ({}));
/** Preserve request context while leaving turn custody for independently owned work. */
function runWithSessionControllerCleanup(e) {
	return cleanupContext.exit ? cleanupContext.exit(e) : e();
}
//#endregion
//#region src/infra/gateway-scheduler.ts
const log$3 = createSubsystemLogger("gateway/scheduler");
const hostClock = {
	now: () => Date.now(),
	monotonicNow: () => performance.now(),
	arm: (e, t) => {
		const n = setTimeout(() => {
			runWithMainThreadTask("scheduler:wake", () => {
				e();
			});
		}, t);
		n.unref();
		return () => clearTimeout(n);
	}
};
/** Next maintenance slot after a run, skipping missed slots without replay. */
function nextMaintenanceSlot(e, t, n) {
	return e + (Math.floor(Math.max(0, t - e) / n) + 1) * n;
}
/** Owns Gateway wakeups; stores and execution owners retain their deadlines and authority. */
var GatewayScheduler = class {
	constructor(e = {}) {
		this.jobs = /* @__PURE__ */ new Map();
		this.pending = /* @__PURE__ */ new Set();
		this.dispatching = false;
		this.fenced = false;
		this.controller = new AbortController();
		this.clock = e.clock ?? hostClock;
	}
	get signal() {
		return this.controller.signal;
	}
	now() {
		return this.clock.now();
	}
	get nextWakeAtMs() {
		const e = this.now();
		const t = this.clock.monotonicNow();
		let n = null;
		for (const r of this.jobs.values()) {
			if (r.running) continue;
			const i = e + this.remaining(r, e, t);
			n = n === null ? i : Math.min(n, i);
		}
		return n;
	}
	/** Closes one owner's timers without retiring siblings or losing in-flight joins. */
	scope() {
		const e = new AbortController();
		const t = {
			signal: AbortSignal.any([this.signal, e.signal]),
			jobs: /* @__PURE__ */ new Set()
		};
		const beginClose = () => {
			e.abort();
			materializeErrorStack(e.signal.reason);
			materializeErrorStack(t.signal.reason);
			for (const e of t.jobs) this.cancel(e);
		};
		const close = () => {
			beginClose();
			const e = [...t.jobs].flatMap((e) => e.running ?? []);
			return e.length > 0 ? Promise.all(e).then(() => void 0) : void 0;
		};
		return {
			signal: t.signal,
			now: () => this.now(),
			schedule: (e) => this.scheduleOwned(e, t),
			beginClose,
			close,
			stop: async () => {
				await close();
			}
		};
	}
	schedule(e) {
		return this.scheduleOwned(e);
	}
	scheduleOwned(e, t) {
		const n = "delayMs" in e;
		const r = this.now();
		const i = n ? r + e.delayMs : e.atMs;
		const a = e.phase === "maintenance" ? Math.max(r, Math.floor(i / 1e4) * 1e4) : i;
		if (!Number.isFinite(a) || e.everyMs !== void 0 && (!Number.isFinite(e.everyMs) || e.everyMs <= 0)) throw new Error(`Invalid Gateway schedule: ${e.id}`);
		const o = this.fenced || t?.signal.aborted === true;
		const s = o ? void 0 : this.jobs.get(e.id);
		const c = {
			id: e.id,
			diagnosticName: `scheduler:${e.id.startsWith("maintenance:") ? e.id.split(":").slice(0, 3).join(":") : e.id.split(/[:/]/u, 1)[0]}`,
			run: e.run,
			everyMs: e.everyMs,
			phase: e.phase,
			atMs: a,
			elapsedAtMs: e.phase !== "maintenance" && (n || e.everyMs !== void 0) ? this.clock.monotonicNow() + Math.max(0, a - r) : void 0,
			context: runOutsideAsyncWorkScope(() => runWithSessionControllerCleanup(() => AsyncLocalStorage.snapshot())),
			cancelled: o,
			owner: t
		};
		if (e.mode === "earliest" && s && !s.running) {
			c.atMs = Math.min(c.atMs, s.atMs);
			if (e.phase !== "maintenance" && s.elapsedAtMs !== void 0) c.elapsedAtMs = c.elapsedAtMs === void 0 ? s.elapsedAtMs : Math.min(c.elapsedAtMs, s.elapsedAtMs);
		}
		const cancel = () => this.cancel(c);
		if (!o) {
			t?.jobs.add(c);
			this.jobs.set(c.id, c);
			if (s) this.cancel(s);
			this.arm();
		}
		return {
			get atMs() {
				return c.atMs;
			},
			cancel,
			stop: async () => {
				cancel();
				await c.running;
			}
		};
	}
	cancel(e) {
		e.cancelled = true;
		if (!e.running) e.owner?.jobs.delete(e);
		if (this.jobs.get(e.id) === e) {
			this.jobs.delete(e.id);
			this.arm();
		}
	}
	/** Stop wakeups and admission without retiring authority held by accepted work. */
	fence() {
		this.fenced = true;
		this.cancelTimer?.();
		this.cancelTimer = void 0;
		for (const e of this.jobs.values()) this.cancel(e);
		this.jobs.clear();
	}
	beginClose() {
		this.fence();
		this.controller.abort();
		materializeErrorStack(this.controller.signal.reason);
	}
	async stop() {
		this.beginClose();
		await Promise.all(this.pending);
	}
	remaining(e, t, n) {
		const r = e.atMs - t;
		return e.elapsedAtMs === void 0 ? r : Math.min(r, e.elapsedAtMs - n);
	}
	arm() {
		if (this.fenced || this.dispatching) return;
		this.cancelTimer?.();
		this.cancelTimer = void 0;
		const e = this.nextWakeAtMs;
		if (e !== null) {
			const t = this.now();
			const n = Math.min(2147483647, Math.max(0, Math.ceil(e - t)));
			this.cancelTimer = runInDetachedAsyncContext(() => this.clock.arm(() => this.wake(t + n), n));
		}
	}
	wake(e) {
		this.cancelTimer = void 0;
		if (this.fenced) return;
		const t = this.now();
		const n = this.clock.monotonicNow();
		const r = [...this.jobs.values()].filter((e) => !e.running && this.remaining(e, t, n) <= 0).toSorted((e, r) => this.remaining(e, t, n) - this.remaining(r, t, n));
		let i;
		if (t - e > 6e4) log$3.debug(`late wake by ${t - e}ms; coalescing ${r.length} due jobs`);
		this.dispatching = true;
		try {
			for (const e of r) {
				if (this.fenced || e.cancelled || e.owner?.signal.aborted || this.jobs.get(e.id) !== e) continue;
				if (e.everyMs === void 0) this.jobs.delete(e.id);
				const t = this.run(e);
				if (t) (i ??= []).push(t);
			}
		} finally {
			this.dispatching = false;
			this.arm();
		}
		return i ? Promise.all(i).then(() => void 0) : void 0;
	}
	run(e) {
		log$3[e.everyMs === void 0 ? "debug" : "trace"](`running ${e.id}`);
		const t = createDeferredCore();
		const n = new AsyncWorkScope();
		e.running = t.promise;
		this.pending.add(t.promise);
		const finish = () => {
			e.running = void 0;
			this.pending.delete(t.promise);
			if (e.everyMs !== void 0 && !e.cancelled && !this.fenced) {
				if (e.phase === "maintenance") {
					e.atMs = Math.floor(e.atMs / 1e4) * 1e4;
					e.atMs = nextMaintenanceSlot(e.atMs, this.now(), e.everyMs);
				} else {
					e.atMs = this.now() + e.everyMs;
					e.elapsedAtMs = this.clock.monotonicNow() + e.everyMs;
				}
			} else e.owner?.jobs.delete(e);
			t.resolve();
			this.arm();
		};
		let r = void 0;
		try {
			r = e.context(() => runWithMainThreadTask(e.diagnosticName, () => n.run(e.run)));
		} catch (t) {
			log$3.error(`${e.id} failed: ${String(t)}`);
		}
		if (!r && !n.hasPendingWork) {
			finish();
			return;
		}
		Promise.resolve(r).catch((t) => log$3.error(`${e.id} failed: ${String(t)}`)).then(() => AsyncWorkScope.runWhenAllIdle(() => [n], () => n.drain())).finally(finish);
		return t.promise;
	}
};
//#endregion
//#region src/infra/sqlite-number.ts
const MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
function readFiniteSqliteNumber(e) {
	const t = typeof e === "bigint" ? Number(e) : e;
	return typeof t === "number" && Number.isFinite(t) ? t : void 0;
}
function coerceRequiredSqliteNumber(e) {
	return typeof e === "bigint" ? Number(e) : e;
}
/** Converts a SQLite number or safely representable bigint column into a JavaScript number. */
function normalizeSqliteNumber(e) {
	if (typeof e === "bigint") {
		if (e > MAX_SAFE_INTEGER_BIGINT || e < -MAX_SAFE_INTEGER_BIGINT) return;
		return Number(e);
	}
	return typeof e === "number" ? e : void 0;
}
//#endregion
//#region src/infra/sqlite-wal-checkpoint.ts
const checkpointListeners = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWalCheckpointListeners"), () => /* @__PURE__ */ new Set());
/** A relayed worker result adds host observations without claiming visibility into other threads. */
function observeSqliteWalCheckpointHealth(e, t) {
	const { activeReaders: n, readerDiagnostics: r, ...i } = t;
	if (t.state === "complete") return i;
	const { activeReaders: a, ...o } = readSqliteReaderDiagnosticsForPath(e);
	return {
		...i,
		activeReaders: [...(n ?? []).filter((e) => e.threadId !== o.threadId), ...a].toSorted((e, t) => t.ageMs - e.ageMs).slice(0, 8),
		readerDiagnostics: [...(r ?? []).filter((e) => e.threadId !== o.threadId), o].slice(-8)
	};
}
function notifyCheckpoint(e, t) {
	for (const n of checkpointListeners) try {
		n({
			databasePath: sqliteReaderDatabasePathKey(e),
			health: structuredClone(t.health),
			observedAtNs: t.observedAtNs,
			lastCompletedAtNs: t.lastCompletedAtNs
		});
	} catch {}
}
function sqliteFileBytes(e) {
	try {
		return fsSync.statSync(e).size;
	} catch (e) {
		if (hasErrnoCode(e, "ENOENT")) return 0;
		throw e;
	}
}
function readCheckpointResult(e) {
	const [t, n, r] = Object.values(e ?? {}).map((e) => normalizeSqliteNumber(typeof e === "number" || typeof e === "bigint" ? e : null));
	if (t === void 0 || n === void 0 || r === void 0) throw new Error("SQLite returned an invalid WAL checkpoint result");
	return {
		busy: t,
		logFrames: n,
		checkpointedFrames: r
	};
}
function checkpoint(e, t) {
	return e.prepare(`PRAGMA wal_checkpoint(${t});`).get();
}
/** Offline maintenance must stop before compaction or recovery if truncation remains busy. */
var SqliteWalCheckpointBusyError = class extends Error {};
function truncateSqliteWal(e, t) {
	const n = checkpoint(e, "TRUNCATE");
	const r = readFiniteSqliteNumber(n?.busy ?? (n ? Object.values(n)[0] : void 0));
	if (r === void 0) throw new Error(`SQLite checkpoint returned an invalid result for ${t}.`);
	if (r !== 0) throw new SqliteWalCheckpointBusyError(`SQLite checkpoint remained busy for ${t}. Stop OpenClaw and retry.`);
}
/** The maintenance lifecycle owns this checkpoint result and its last observation. */
function createSqliteWalCheckpoint(e, t, n) {
	let r;
	const checkpointObservation = () => ({
		state: "error",
		observedAtMs: Date.now(),
		walBytes: null,
		databaseBytes: null,
		logFrames: null,
		checkpointedFrames: null,
		lastCompletedAtMs: r?.health.lastCompletedAtMs ?? null,
		consecutiveBlocked: 0,
		warning: true
	});
	const recordCheckpointError = (e, n = checkpointObservation()) => {
		const i = {
			...n,
			observedAtMs: Date.now(),
			state: "error",
			consecutiveBlocked: 0,
			warning: true,
			error: formatErrorMessage(e)
		};
		r = {
			observedAtNs: process.hrtime.bigint(),
			lastCompletedAtNs: r?.lastCompletedAtNs,
			health: t.databasePath ? observeSqliteWalCheckpointHealth(t.databasePath, i) : i
		};
		if (t.databasePath) notifyCheckpoint(t.databasePath, r);
		t.onCheckpointError?.(e);
	};
	const recordCheckpoint = (e, i, a) => {
		const o = process.hrtime.bigint();
		const s = checkpointObservation();
		let c;
		let l;
		try {
			const { busy: e, logFrames: a, checkpointedFrames: u } = readCheckpointResult(i);
			c = e !== 0;
			s.logFrames = a;
			s.checkpointedFrames = u;
			s.state = c || u < a ? "blocked" : "complete";
			if (s.state === "complete") s.lastCompletedAtMs = s.observedAtMs;
			else s.consecutiveBlocked = (r?.health.consecutiveBlocked ?? 0) + 1;
			if (t.databasePath) try {
				s.databaseBytes = sqliteFileBytes(t.databasePath);
				s.walBytes = sqliteFileBytes(`${t.databasePath}-wal`);
			} catch (e) {
				l = e;
				s.error = formatErrorMessage(e);
			}
			s.warning = s.state === "blocked" && (s.consecutiveBlocked >= 2 || s.walBytes !== null && s.databaseBytes !== null && s.walBytes > Math.max(2 * s.databaseBytes, n));
			r = {
				observedAtNs: o,
				lastCompletedAtNs: s.state === "complete" ? o : r?.lastCompletedAtNs,
				health: t.databasePath ? observeSqliteWalCheckpointHealth(t.databasePath, s) : s
			};
			if (t.databasePath) notifyCheckpoint(t.databasePath, r);
		} catch (e) {
			recordCheckpointError(e, s);
			return false;
		}
		if (s.error !== void 0) t.onCheckpointError?.(l);
		if (s.warning && !a) {
			const n = t.databaseLabel ?? "sqlite database";
			t.onCheckpointError?.(/* @__PURE__ */ new Error(`${n} WAL checkpoint ${e} ${c ? "remained busy" : "blocked by a reader"}`));
		}
		return s.state === "complete";
	};
	return {
		adopt(e) {
			if (r && r.observedAtNs >= e.observedAtNs && (r.lastCompletedAtNs ?? 0n) >= (e.lastCompletedAtNs ?? 0n)) return;
			const n = (r?.lastCompletedAtNs ?? 0n) > (e.lastCompletedAtNs ?? 0n) ? r : e;
			if (!r || e.observedAtNs > r.observedAtNs) r = structuredClone(e);
			r.lastCompletedAtNs = n?.lastCompletedAtNs;
			r.health.lastCompletedAtMs = n?.health.lastCompletedAtMs ?? null;
			if (t.databasePath) {
				r.health = observeSqliteWalCheckpointHealth(t.databasePath, r.health);
				notifyCheckpoint(t.databasePath, r);
			}
		},
		checkpoint(t, n = {}) {
			try {
				return recordCheckpoint(t, checkpoint(e, t), n.quiet === true);
			} catch (e) {
				recordCheckpointError(e);
				return false;
			}
		},
		recordError: recordCheckpointError,
		inspectIdle() {
			const { busy: t, logFrames: n, checkpointedFrames: r } = readCheckpointResult(checkpoint(e, "PASSIVE"));
			return t === 0 && n >= 0 && r >= 0 && r <= n;
		},
		get health() {
			return r ? structuredClone(r.health) : void 0;
		},
		get snapshot() {
			return r ? structuredClone(r) : void 0;
		}
	};
}
//#endregion
//#region packages/normalization-core/src/mountinfo-path.ts
const MOUNT_PATH_OCTAL_ESCAPE_RE = /\\([0-7]{3})/g;
/** Decodes an octal-escaped path field from a Linux procfs mount table. */
function decodeMountInfoPath(e) {
	return e.replace(MOUNT_PATH_OCTAL_ESCAPE_RE, (e, t) => String.fromCharCode(Number.parseInt(t, 8)));
}
//#endregion
//#region src/infra/sqlite-wal-filesystem.ts
const NETWORK_FILESYSTEM_MAGIC = /* @__PURE__ */ new Set([
	26985,
	20859,
	4283649346,
	4266872130
]);
const ROLLBACK_FILESYSTEM_MAGIC = /* @__PURE__ */ new Set([...NETWORK_FILESYSTEM_MAGIC, 16914839]);
const LINUX_BTRFS_SUPER_MAGIC = 2435016766;
const PROC_MOUNTINFO_PATH = "/proc/self/mountinfo";
const MOUNT_COMMAND_TIMEOUT_MS = 1e3;
const NETWORK_FILESYSTEM_TYPES = /* @__PURE__ */ new Set([
	"cifs",
	"smbfs",
	"smb2",
	"smb3"
]);
const CROSS_VM_FILESYSTEM_TYPES = /* @__PURE__ */ new Set([
	"virtiofs",
	"fuse.virtiofs",
	"9p",
	"9p2000.l"
]);
const log$2 = createSubsystemLogger("infra/sqlite-wal");
let warnedNoCow = false;
function findExistingVolumePaths(e) {
	let t = path.resolve(e);
	while (true) {
		let e;
		try {
			e = fsSync.statSync(t);
		} catch {
			const e = path.dirname(t);
			if (e === t) return null;
			t = e;
			continue;
		}
		const n = fsSync.realpathSync(t);
		return {
			canonicalPath: e.isDirectory() ? n : path.dirname(n),
			originalPath: e.isDirectory() ? t : path.dirname(t)
		};
	}
}
function parseProcMountInfoEntries(e) {
	const t = [];
	for (const n of e.split("\n")) {
		const e = n.indexOf(" - ");
		if (e === -1) continue;
		const r = n.slice(0, e).split(" ");
		const i = n.slice(e + 3).split(" ");
		const a = r[4];
		const o = i[0];
		if (a && o) t.push({
			mountPoint: decodeMountInfoPath(a),
			fsType: o,
			...i[1] ? { source: decodeMountInfoPath(i[1]) } : {}
		});
	}
	return t;
}
function parseMountCommandEntries(e) {
	const t = [];
	for (const n of e.split("\n")) {
		const e = /^(.+) on (.+) type ([^,\s)]+) \(/.exec(n) ?? /^(.+) on (.+) \(([^,\s)]+)/.exec(n);
		if (e) {
			const [, n, r, i] = e;
			if (n && r && i) t.push({
				source: n,
				mountPoint: r,
				fsType: i
			});
		}
	}
	return t;
}
function readMountEntries() {
	try {
		return {
			ok: true,
			value: parseProcMountInfoEntries(fsSync.readFileSync(PROC_MOUNTINFO_PATH, "utf8"))
		};
	} catch {}
	try {
		return {
			ok: true,
			value: parseMountCommandEntries(String(process.getBuiltinModule("node:child_process").execFileSync("mount", [], {
				killSignal: "SIGKILL",
				timeout: MOUNT_COMMAND_TIMEOUT_MS
			})))
		};
	} catch (e) {
		return hasErrnoCode(e, "ETIMEDOUT") ? {
			ok: false,
			error: "timeout"
		} : {
			ok: true,
			value: []
		};
	}
}
function isPathWithinMount(e, t) {
	const n = path.resolve(e);
	const r = path.resolve(t);
	return n === r || r === path.parse(r).root || n.startsWith(`${r}${path.sep}`);
}
function isSshfsMountSource(e) {
	if (!e) return false;
	const t = e.toLowerCase();
	return t === "sshfs" || t.startsWith("sshfs#") || t.startsWith("sshfs@") || /^(?:[^/\s:]+@)?[^/\s:]+:.*/u.test(e);
}
function resolveNetworkMountJournalPolicy(e) {
	const t = e.fsType.toLowerCase();
	if (t.startsWith("nfs") || NETWORK_FILESYSTEM_TYPES.has(t)) return "rollback";
	if (t === "fuse.sshfs") return "unsupported";
	if ((t === "macfuse" || t === "osxfuse") && isSshfsMountSource(e.source)) return "unsupported";
}
function resolveMountTypeJournalPolicy(e) {
	const t = e.fsType.toLowerCase();
	return resolveNetworkMountJournalPolicy(e) ?? (CROSS_VM_FILESYSTEM_TYPES.has(t) || t.startsWith("9p") ? "rollback" : "wal");
}
function findMountEntry(e, t) {
	return t.filter((t) => isPathWithinMount(e, t.mountPoint)).toSorted((e, t) => t.mountPoint.length - e.mountPoint.length)[0];
}
function resolveMountEntryJournalPolicy(e, t) {
	const n = findMountEntry(e, t);
	return n ? resolveMountTypeJournalPolicy(n) : "wal";
}
/** Classify the physical store location, including a not-yet-created database. */
function isSqlitePathOnBtrfs(e) {
	if (process.platform !== "linux") return false;
	const t = findExistingVolumePaths(e);
	if (!t) return false;
	try {
		return fsSync.statfsSync(t.canonicalPath).type === LINUX_BTRFS_SUPER_MAGIC;
	} catch {
		const e = readMountEntries();
		return e.ok && findMountEntry(t.canonicalPath, e.value)?.fsType.toLowerCase() === "btrfs";
	}
}
/** Doctor requires failure to abort publication; never apply attributes to data files. */
function setSqliteDirectoryNoCow(e) {
	if (!fsSync.statSync(e).isDirectory()) throw new Error(`SQLite NOCOW target is not a directory: ${e}`);
	const t = process.getBuiltinModule("node:child_process").spawnSync("chattr", ["+C", e], {
		encoding: "utf8",
		killSignal: "SIGKILL",
		timeout: MOUNT_COMMAND_TIMEOUT_MS,
		maxBuffer: 4096
	});
	if (t.error || t.status !== 0) throw t.error ?? /* @__PURE__ */ new Error(`chattr +C failed: ${t.stderr.trim() || t.signal || t.status}`);
}
/** Called after directory permissions are established, before SQLite creates any files. */
function prepareSqliteDatabaseDirectory(e) {
	if (process.platform !== "linux" || fsSync.existsSync(e)) return;
	try {
		if (isSqlitePathOnBtrfs(e)) setSqliteDirectoryNoCow(path.dirname(e));
	} catch (t) {
		if (!warnedNoCow) {
			warnedNoCow = true;
			log$2.warn("Could not enable SQLite directory NOCOW; continuing with filesystem defaults", {
				databasePath: e,
				error: t instanceof Error ? t.message : String(t)
			});
		}
	}
}
function combineMountEntryJournalPolicies(e) {
	const t = readMountEntries();
	if (!t.ok) {
		const [t, n] = e;
		if (process.platform === "darwin" && t === n) try {
			if (probeTreeClone(n) === "apfs") return "wal";
		} catch {}
		return "rollback";
	}
	const n = new Set(e.map((e) => resolveMountEntryJournalPolicy(e, t.value)));
	if (n.has("unsupported")) return "unsupported";
	return n.has("rollback") ? "rollback" : "wal";
}
function isWindowsUncPath(e) {
	return /^\\\\\?\\UNC\\[^\\]+\\[^\\]+/i.test(e) || /^\\\\(?![?.]\\)[^\\]+\\[^\\]+/.test(e);
}
function isWindowsDrivePath(e) {
	return /^[A-Za-z]:[\\/]/.test(e) || /^\\\\\?\\[A-Za-z]:[\\/]/i.test(e);
}
function resolvePathJournalPolicy(e) {
	if (process.platform === "win32") {
		const t = path.win32.normalize(e);
		if (isWindowsUncPath(t)) return "rollback";
		if (isWindowsDrivePath(t)) try {
			return isWindowsUncPath(path.win32.normalize(fsSync.realpathSync.native(e))) ? "rollback" : "wal";
		} catch {
			return "rollback";
		}
	}
	const t = findExistingVolumePaths(e);
	if (!t) return "wal";
	const n = [t.originalPath, t.canonicalPath];
	try {
		if (ROLLBACK_FILESYSTEM_MAGIC.has(fsSync.statfsSync(t.canonicalPath).type)) return "rollback";
	} catch {}
	return combineMountEntryJournalPolicies(n);
}
//#endregion
//#region src/infra/sqlite-wal-reclamation.ts
const VACUUM_UNIT_TARGET_MS = 25;
const vacuumPageBudgets = /* @__PURE__ */ new WeakMap();
function createSqliteWalReclamationResult() {
	return {
		checkpointCompleted: false,
		freePagesBefore: null,
		remainingFreePages: null,
		checkpointCalls: 0,
		checkpointIncomplete: 0,
		checkpointMs: 0,
		checkpointMaxMs: 0,
		queryMs: 0,
		vacuumMs: 0,
		vacuumPasses: 0,
		vacuumPagesRequested: 0
	};
}
/** Physical page accounting for both reclamation and its read-only eligibility probe. */
function readSqliteFreePageCount(e, t) {
	const n = t ? performance$1.now() : 0;
	try {
		return Number(e.prepare("PRAGMA freelist_count").get()?.freelist_count ?? 0);
	} finally {
		if (t) t.queryMs += performance$1.now() - n;
	}
}
/** One online unit never waits for readers or adds vacuum frames behind a blocked checkpoint. */
function reclaimSqliteWalFreePages(e, t, n) {
	const r = createSqliteWalReclamationResult();
	const checkpoint = () => {
		n.beforeMutation?.();
		const e = performance$1.now();
		try {
			const e = n.checkpointMode ?? "TRUNCATE";
			let i = t(e);
			r.checkpointCalls++;
			if (!i && e === "TRUNCATE") {
				n.beforeMutation?.();
				i = t("PASSIVE");
				r.checkpointCalls++;
			}
			r.checkpointCompleted = i;
			r.checkpointIncomplete += Number(!i);
			return i;
		} finally {
			const t = performance$1.now() - e;
			r.checkpointMs += t;
			r.checkpointMaxMs = Math.max(r.checkpointMaxMs, t);
		}
	};
	if (n.maxPages === 0 && n.checkpointMode === "PASSIVE") {
		checkpoint();
		return r;
	}
	return runWithSqliteBusyTimeout(e, 0, () => {
		if (!checkpoint() || n.maxPages === 0) return r;
		const t = readSqliteFreePageCount(e, r);
		r.freePagesBefore = t;
		r.remainingFreePages = t;
		if (!Number.isSafeInteger(t) || t <= 0) return r;
		const i = Math.min(vacuumPageBudgets.get(e) ?? 8, t, n.maxPages ?? 512);
		if (!Number.isSafeInteger(i) || i <= 0) throw new Error("SQLite page reclamation requires a positive integer page limit");
		const a = performance$1.now();
		let o = false;
		let s = false;
		try {
			runSqliteImmediateTransactionSync(e, () => {
				o = true;
				n.beforeMutation?.();
				r.vacuumPasses++;
				r.vacuumPagesRequested += i;
				e.exec(`PRAGMA incremental_vacuum(${i});`);
				n.onCommit?.();
			}, {
				beginLockFailureReporting: "suppress",
				busyTimeoutMs: 0,
				operationLabel: "incremental-vacuum"
			});
			s = true;
		} catch (e) {
			if (o || !isSqliteLockError(e)) throw e;
			return r;
		} finally {
			const t = performance$1.now() - a;
			r.vacuumMs += t;
			if (s) vacuumPageBudgets.set(e, Math.max(1, Math.min(512, i * 2, Math.floor(i * VACUUM_UNIT_TARGET_MS / Math.max(t, .001)))));
		}
		n.afterCommit?.();
		if (checkpoint()) r.remainingFreePages = readSqliteFreePageCount(e, r);
		return r;
	});
}
//#endregion
//#region src/infra/sqlite-wal-split-brain.ts
const PROC_SELF_FD_PATH = "/proc/self/fd";
const SQLITE_WAL_SPLIT_BRAIN_FATAL_MESSAGE = "SQLite WAL sidecar identity mismatch; terminating without SQLite cleanup";
async function readUnlessMissing(e, t = false) {
	try {
		return await e();
	} catch (e) {
		if (t && hasErrnoCode(e, "EBADF") || hasErrnoCode(e, "ENOENT")) return;
		throw e;
	}
}
function isSqliteWalSidecarSplitBrain(e, t) {
	return e.nlink === 0n || !t || e.dev !== t.dev || e.ino !== t.ino;
}
async function detectSqliteWalSplitBrain(e) {
	const t = await readUnlessMissing(() => fsSync.promises.readdir(PROC_SELF_FD_PATH));
	const n = [`${e}-wal`, `${e}-shm`];
	for (const r of t ?? []) {
		const t = path.join(PROC_SELF_FD_PATH, r);
		const i = await readUnlessMissing(() => fsSync.promises.readlink(t));
		if (i === void 0) continue;
		const a = n.find((e) => i === e || i === `${e} (deleted)`);
		if (!a) continue;
		const o = await readUnlessMissing(() => promisify(fsSync.fstat)(Number(r), { bigint: true }), true);
		if (o === void 0 || await readUnlessMissing(() => fsSync.promises.readlink(t)) !== i) continue;
		const s = await readUnlessMissing(() => fsSync.promises.stat(a, { bigint: true }));
		if (!isSqliteWalSidecarSplitBrain(o, s)) continue;
		const c = await readUnlessMissing(() => promisify(fsSync.fstat)(Number(r), { bigint: true }), true);
		if (!c || c.dev !== o.dev || c.ino !== o.ino || await readUnlessMissing(() => fsSync.promises.readlink(t)) !== i) continue;
		return {
			event: "sqlite_wal_sidecar_identity_mismatch",
			databasePath: e,
			descriptorDevice: o.dev.toString(),
			descriptorInode: o.ino.toString(),
			sidecarPath: a,
			...s ? {
				targetDevice: s.dev.toString(),
				targetInode: s.ino.toString()
			} : {}
		};
	}
}
function terminateForSqliteWalSplitBrain(e, t) {
	try {
		fsSync.writeSync(2, `${JSON.stringify({
			level: "fatal",
			subsystem: "infra/sqlite-wal",
			message: SQLITE_WAL_SPLIT_BRAIN_FATAL_MESSAGE,
			...e,
			databaseLabel: t,
			pid: process.pid
		})}\n`);
	} catch {}
	try {
		process.kill(process.pid, "SIGKILL");
	} finally {
		process.abort();
	}
}
//#endregion
//#region src/infra/sqlite-wal-write-admission.ts
const admissions = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWalWriteAdmissions"), () => /* @__PURE__ */ new WeakMap());
/** A worker-maintained writer never checkpoints inline; its maintenance owner ticks instead. */
function registerSqliteWalWorkerMaintenance(e, t, n) {
	e.exec("PRAGMA wal_autocheckpoint = 0;");
	const r = admissions.get(e)?.stopCheckpointTick;
	admissions.set(e, {
		execute: t,
		cancel: n
	});
	r?.();
}
function isSqliteWalWorkerMaintained(e) {
	return admissions.get(e)?.execute !== void 0;
}
function cancelSqliteWalWriteAdmission(e) {
	return admissions.get(e)?.cancel?.();
}
function createSqliteWalMaintenanceScheduler(e, t, n, r, i, a, o) {
	const s = admissions.get(e);
	admissions.set(e, {
		...s,
		stopCheckpointTick: o
	});
	let c;
	return () => {
		if (!c) {
			const run = async () => {
				let i = a();
				let o = false;
				while (true) {
					const a = n(i);
					if (!a || i === 0 && admissions.get(e)?.execute) return;
					a.continuation = o;
					let s;
					const admitted = () => {
						if (n(i)) s = t(a);
					};
					const c = admissions.get(e);
					if (c?.execute) {
						s = await c.execute(a);
						if (s?.checkpoint) r(s.checkpoint);
					} else if (c?.admit) await c.admit(admitted);
					else admitted();
					const l = s?.reclaimedPages ?? 0;
					i -= l;
					if (l <= 0 || i <= 0) return;
					o = true;
					await setImmediate();
				}
			};
			c = run().catch(i).finally(() => {
				c = void 0;
			});
		}
		return c;
	};
}
//#endregion
//#region src/infra/sqlite-wal.ts
const DEFAULT_SQLITE_WAL_AUTOCHECKPOINT_PAGES = 16384;
const DEFAULT_SQLITE_WAL_CHECKPOINT_TICK_MS = 1e4;
const DEFAULT_SQLITE_WAL_CHECKPOINT_INTERVAL_MS = 18e5;
const DEFAULT_SQLITE_WAL_JOURNAL_SIZE_LIMIT_BYTES = 67108864;
const JOURNAL_MODE_RETRY_INTERVAL_MS = 10;
const JOURNAL_MODE_RETRY_SLEEP = new Int32Array(new SharedArrayBuffer(4));
const log$1 = createSubsystemLogger("infra/sqlite-wal");
const maintenanceScheduler = new GatewayScheduler();
let nextMaintenanceId = 0;
const completedCheckpointKey = {
	name: "sqlite-wal-completed-write-revision",
	read: (e) => e instanceof SharedArrayBuffer && e.byteLength === Int32Array.BYTES_PER_ELEMENT ? e : void 0
};
function sharedCompletedCheckpoint(e, t) {
	let n = getSqliteDatabaseAdmission(e, completedCheckpointKey);
	if (!n) {
		n = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
		Atomics.store(new Int32Array(n), 0, t - 1 | 0);
		publishSqliteDatabaseAdmission(e, completedCheckpointKey, n);
		n = getSqliteDatabaseAdmission(e, completedCheckpointKey);
	}
	return n ? new Int32Array(n) : void 0;
}
function enableIncrementalAutoVacuumForFreshDatabase(e) {
	const t = e.location();
	const n = t ? peekSqliteDatabaseAdmissionForPath(t, schemaAdmission) : void 0;
	if (n && (n.userVersion > 0 || n.tables.size > 0 || n.views.size > 0)) return;
	if (e.prepare("PRAGMA page_count").get()?.page_count === 0) e.exec("PRAGMA auto_vacuum = INCREMENTAL;");
}
/**
* Configure lock retry before inspecting or mutating a fresh database header.
* Concurrent first opens can otherwise fail before schema transactions begin.
*/
function configureSqlitePreSchemaPragmas(e, t = {}) {
	if (t.busyTimeoutMs !== void 0) setSqliteBusyTimeout(e, t.busyTimeoutMs);
	enableIncrementalAutoVacuumForFreshDatabase(e);
}
function readJournalModeResult(e) {
	if (!e || typeof e !== "object") return null;
	const t = e;
	const n = t.journal_mode ?? Object.values(t)[0];
	return typeof n === "string" ? n.toLowerCase() : null;
}
function hasInMemoryMainDatabase(e) {
	return e.prepare("PRAGMA database_list;").all().find((e) => e.name === "main")?.file === "";
}
function requireRollbackJournalMode(e, t) {
	const n = readJournalModeResult(e.prepare("PRAGMA journal_mode = DELETE;").get());
	if (n !== "delete") {
		const e = t.databaseLabel ?? "sqlite database";
		const r = t.databasePath ? ` at ${t.databasePath}` : "";
		throw new Error(`${e}${r} is on a network-backed volume but SQLite kept journal_mode=${n ?? "unknown"}; refusing to continue with WAL on network storage.`);
	}
}
function enableWalJournalMode(e, t, n) {
	const r = performance$1.now() + t;
	let i = false;
	try {
		while (true) try {
			const t = readJournalModeResult(e.prepare("PRAGMA journal_mode = WAL;").get());
			if (t === "wal") return true;
			if (t === "memory" && hasInMemoryMainDatabase(e)) return false;
			const r = n.databaseLabel ?? "sqlite database";
			const i = n.databasePath ? ` at ${n.databasePath}` : "";
			throw new Error(`${r}${i} could not enable WAL; SQLite kept journal_mode=${t ?? "unknown"}.`);
		} catch (t) {
			const n = Math.max(0, r - performance$1.now());
			if (!isSqliteLockError(t) || n <= 0) throw t;
			if (!i) {
				setSqliteBusyTimeout(e, 0);
				i = true;
			}
			Atomics.wait(JOURNAL_MODE_RETRY_SLEEP, 0, 0, Math.min(JOURNAL_MODE_RETRY_INTERVAL_MS, n));
		}
	} finally {
		if (i) setSqliteBusyTimeout(e, t);
	}
}
function enableMacosCheckpointFullfsync(e) {
	if (process.platform !== "darwin") return;
	try {
		e.exec("PRAGMA checkpoint_fullfsync = 1;");
	} catch {}
}
function refuseUnsupportedFilesystem(e) {
	const t = e.databaseLabel ?? "sqlite database";
	const n = e.databasePath ? ` at ${e.databasePath}` : "";
	throw new Error(`${t}${n} is on SSHFS, which cannot safely coordinate SQLite writes across mounts; refusing to open the database.`);
}
/** Configure safe journaling pragmas and return a handle for checkpoint/close maintenance. */
function configureSqliteWalMaintenance(e, t = {}) {
	const n = t.busyTimeoutMs ?? 0;
	if (t.busyTimeoutMs !== void 0) setSqliteBusyTimeout(e, t.busyTimeoutMs);
	const r = normalizeSqliteNonNegativeInteger(t.autoCheckpointPages ?? DEFAULT_SQLITE_WAL_AUTOCHECKPOINT_PAGES, "autoCheckpointPages");
	const i = normalizeSqliteNonNegativeInteger(t.checkpointIntervalMs ?? DEFAULT_SQLITE_WAL_CHECKPOINT_INTERVAL_MS, "checkpointIntervalMs");
	const a = Math.min(i, MAX_TIMER_TIMEOUT_MS);
	const o = i > DEFAULT_SQLITE_WAL_CHECKPOINT_TICK_MS ? DEFAULT_SQLITE_WAL_CHECKPOINT_TICK_MS : 0;
	const s = t.checkpointMode ?? "TRUNCATE";
	const c = t.checkpointMode ?? "PASSIVE";
	const l = t.databasePath ? resolvePathJournalPolicy(t.databasePath) : "wal";
	if (l === "unsupported") refuseUnsupportedFilesystem(t);
	if (l === "rollback") requireRollbackJournalMode(e, t);
	if (l === "rollback" || !enableWalJournalMode(e, n, t)) return {
		checkpoint: () => true,
		reclaimFreePages: (t = {}) => reclaimSqliteWalFreePages(e, () => true, t),
		stop: async () => {},
		close: () => true
	};
	enableMacosCheckpointFullfsync(e);
	e.exec(`PRAGMA wal_autocheckpoint = ${isSqliteWalWorkerMaintained(e) ? 0 : r};`);
	e.exec(`PRAGMA journal_size_limit = ${DEFAULT_SQLITE_WAL_JOURNAL_SIZE_LIMIT_BYTES};`);
	const u = process.platform === "linux" && t.databasePath && fsSync.existsSync(t.databasePath) ? fsSync.realpathSync.native(t.databasePath) : void 0;
	let d = false;
	let f = false;
	let p = Boolean(u);
	const m = createSqliteWalCheckpoint(e, t, DEFAULT_SQLITE_WAL_JOURNAL_SIZE_LIMIT_BYTES);
	const h = m.checkpoint;
	const runMaintenance = (e) => {
		if (d || f) return false;
		try {
			return t.runMaintenance ? t.runMaintenance(e) : e();
		} catch (e) {
			m.recordError(e);
			return false;
		}
	};
	const checkpoint = () => runMaintenance(() => h(s));
	const reclaimFreePages = (t = {}) => {
		let n;
		let r;
		runMaintenance(() => {
			try {
				n = reclaimSqliteWalFreePages(e, h, t);
				return n.checkpointCompleted;
			} catch (e) {
				r = { error: e };
				throw e;
			}
		});
		if (r) throw r.error;
		if (!n) throw new Error("SQLite page reclamation owner is unavailable");
		return {
			...n,
			checkpoint: m.snapshot
		};
	};
	const g = maintenanceScheduler.scope();
	const _ = `sqlite-wal:${++nextMaintenanceId}`;
	let v = 0;
	let y;
	const maintainPeriodic = (t, n, r) => {
		if (d) return { reclaimedPages: 0 };
		if (t.checkpoint) m.adopt(t.checkpoint);
		let i = 0;
		const a = t.maxPages === 0;
		const o = a && t.checkpointMode === "PASSIVE";
		const s = o ? readSqliteDatabaseWriteRevision(e) : void 0;
		const c = s === void 0 ? void 0 : sharedCompletedCheckpoint(e, s);
		const l = c !== void 0 && Atomics.load(c, 0) === s;
		if (s !== void 0 && (l || s === y && m.health?.state === "complete")) return {
			reclaimedPages: 0,
			checkpoint: m.health?.state === "complete" ? m.snapshot : void 0
		};
		const runTickCheckpoint = (e) => m.checkpoint(e, { quiet: a });
		y = runMaintenance(() => {
			let a;
			if (o) {
				n?.("transaction");
				a = runTickCheckpoint("PASSIVE");
			} else {
				const r = reclaimSqliteWalFreePages(e, runTickCheckpoint, {
					checkpointMode: t.checkpointMode,
					maxPages: t.maxPages,
					beforeMutation: () => n?.("transaction"),
					onCommit: () => n?.("commit")
				});
				a = r.checkpointCompleted;
				if (a && r.freePagesBefore !== null && r.remainingFreePages !== null) i = Math.min(r.vacuumPagesRequested, r.freePagesBefore - r.remainingFreePages);
			}
			if (a && t.checkpointMode === "PASSIVE" && (m.health?.walBytes ?? 0) > DEFAULT_SQLITE_WAL_JOURNAL_SIZE_LIMIT_BYTES) {
				n?.("transaction");
				runWithSqliteBusyTimeout(e, 0, () => runTickCheckpoint("TRUNCATE"));
			}
			if (a && t.maxPages > 0 && !t.continuation) try {
				r?.();
			} catch (e) {
				if (!isSqliteLockError(e)) throw e;
			}
			return a;
		}) && m.health?.state === "complete" ? s : void 0;
		if (c && y !== void 0) Atomics.store(c, 0, y);
		return {
			reclaimedPages: i,
			checkpoint: m.snapshot
		};
	};
	let stopCheckpointTick;
	const b = createSqliteWalMaintenanceScheduler(e, maintainPeriodic, (e) => a > 0 && !g.signal.aborted && !d && !f && !t.isScheduledMaintenanceSuspended?.() ? {
		maxPages: e,
		checkpointMode: c,
		checkpoint: m.snapshot
	} : void 0, m.adopt, (e) => m.recordError(e), () => {
		const e = v;
		v = 0;
		return e;
	}, () => stopCheckpointTick?.());
	const schedule = (e, t, n) => runInDetachedAsyncContext(() => g.schedule({
		id: `${_}:${e}`,
		delayMs: t,
		everyMs: t,
		run: n
	}));
	if (a > 0) schedule("periodic", a, async () => {
		if (u && p) {
			f = true;
			const n = registerNodeSqliteDisposeGuard(e, () => {
				throw new Error("SQLite WAL inspection is pending; await maintenance.stop() before close");
			});
			try {
				let e;
				try {
					e = await detectSqliteWalSplitBrain(u);
				} catch (e) {
					p = false;
					log$1.warn("SQLite WAL split-brain detection disabled", {
						databaseLabel: t.databaseLabel,
						databasePath: u,
						error: e instanceof Error ? e.message : String(e)
					});
				}
				if (e) {
					d = true;
					g.beginClose();
					terminateForSqliteWalSplitBrain(e, t.databaseLabel);
				}
			} finally {
				n();
				f = false;
			}
			if (g.signal.aborted) return;
		}
		v = 512;
		return b();
	});
	if (o > 0 && !isSqliteWalWorkerMaintained(e)) {
		let t = false;
		let n;
		const cancelTick = () => {
			n?.cancel();
			n = void 0;
		};
		const armTick = () => {
			if (!t && !n && !g.signal.aborted && !d) n = runInDetachedAsyncContext(() => g.schedule({
				id: `${_}:tick`,
				delayMs: o,
				run: runTick
			}));
		};
		const runTick = async () => {
			n = void 0;
			await b();
			if (t) return;
			const r = readSqliteDatabaseWriteRevision(e);
			const i = r === void 0 ? void 0 : sharedCompletedCheckpoint(e, r);
			if (i && Atomics.load(i, 0) === r) cancelTick();
			else armTick();
		};
		const r = c === "PASSIVE" ? onSqliteDatabaseWriteSettled(e, armTick) : void 0;
		if (r) {
			stopCheckpointTick = () => {
				t = true;
				r();
				cancelTick();
			};
			armTick();
		} else stopCheckpointTick = schedule("tick", o, b).cancel;
	}
	const beginClose = () => {
		stopCheckpointTick?.();
		runInDetachedAsyncContext(() => g.beginClose());
		return cancelSqliteWalWriteAdmission(e);
	};
	return {
		get health() {
			return m.health;
		},
		checkpoint,
		maintainPeriodic,
		reclaimFreePages,
		inspectIdle: () => runMaintenance(m.inspectIdle) ? "healthy" : "retire",
		stop: async () => {
			try {
				await beginClose();
			} finally {
				await runInDetachedAsyncContext(() => g.stop());
			}
		},
		close: (t) => {
			beginClose();
			if (d || isSqliteWalWorkerMaintained(e)) return false;
			return runMaintenance(() => h(t?.checkpointMode ?? s));
		}
	};
}
let lastSqliteExitGroup;
function detachEmptySqliteExitGroup(e) {
	if (e.pending.size > 0) return;
	if (lastSqliteExitGroup === e) lastSqliteExitGroup = void 0;
	process.removeListener("exit", e.dispatch);
}
/**
* Register a best-effort exit-time close for a SQLite handle cache. Returns an
* unregister callback the cache's orderly close path must invoke, so tests and
* runtime shutdowns do not accumulate listeners on shared worker processes.
*/
function registerSqliteCacheExitClose(e) {
	const t = { close: e };
	let n = lastSqliteExitGroup;
	if (!n || process.listeners("exit").at(-1) !== n.dispatch) {
		const e = /* @__PURE__ */ new Set([t]);
		const r = {
			pending: e,
			dispatch: () => {
				const t = [...e];
				e.clear();
				detachEmptySqliteExitGroup(r);
				for (const e of t) try {
					e.close();
				} catch {}
			}
		};
		process.on("exit", r.dispatch);
		lastSqliteExitGroup = n = r;
	} else n.pending.add(t);
	const r = n;
	return () => {
		r.pending.delete(t);
		detachEmptySqliteExitGroup(r);
	};
}
/** Configure per-connection SQLite pragmas in the safe lock-retry/WAL order. */
function configureSqliteConnectionPragmas(e, t = {}) {
	const { foreignKeys: n, synchronous: r, ...i } = t;
	const a = configureSqliteWalMaintenance(e, i);
	try {
		if (r) e.exec(`PRAGMA synchronous = ${r};`);
		if (n) e.exec("PRAGMA foreign_keys = ON;");
		return a;
	} catch (e) {
		try {
			a.close();
		} catch (t) {
			throw createSqliteLifecycleAggregateError([e, t], "SQLite connection pragma configuration and WAL maintenance cleanup both failed.", e);
		}
		throw e;
	}
}
//#endregion
//#region src/infra/sqlite-snapshot-policy.ts
const MAX_SNAPSHOT_ATTEMPTS = 10;
const SNAPSHOT_RETRY_BASE_MS = 10;
const SNAPSHOT_RETRY_MAX_MS = 80;
function sqliteSnapshotSourceFileSize(e) {
	try {
		const t = fsSync.statSync(e);
		return t.isFile() ? t.size : 0;
	} catch (e) {
		if (hasErrnoCode(e, "ENOENT")) return 0;
		throw e;
	}
}
function waitForSnapshotRetrySync(e) {
	if (e + 1 >= 10) return;
	const t = Math.min(SNAPSHOT_RETRY_MAX_MS, SNAPSHOT_RETRY_BASE_MS * 2 ** e);
	if (t > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, t);
}
//#endregion
//#region src/infra/disk-space.ts
function finiteNonNegativeNumber(e) {
	const t = Number(e);
	return Number.isFinite(t) && t >= 0 ? t : null;
}
function findExistingDiskSpacePath(e) {
	let t = path.resolve(e);
	while (true) try {
		return fsSync.statSync(t).isDirectory() ? t : path.dirname(t);
	} catch {
		const e = path.dirname(t);
		if (e === t) return null;
		t = e;
	}
}
/** Reads available bytes for the volume containing a target path. */
function tryReadDiskSpace(e) {
	const t = findExistingDiskSpacePath(e);
	if (!t) return null;
	try {
		const n = fsSync.statfsSync(t);
		const r = finiteNonNegativeNumber(n.bsize);
		const i = finiteNonNegativeNumber(n.bavail);
		if (r === null || i === null) return null;
		const a = finiteNonNegativeNumber(n.blocks);
		return {
			targetPath: e,
			checkedPath: t,
			availableBytes: r * i,
			totalBytes: a === null ? null : r * a
		};
	} catch {
		return null;
	}
}
//#endregion
//#region src/infra/sqlite-snapshot-staging.ts
/** A private reader protects its bytes independently of the staging child. */
function acquireSqliteSnapshotReadToken(e) {
	return acquireSqliteSnapshotToken(e, "read");
}
function sqliteSnapshotStagingError(e, t, n = false, r) {
	markSqliteInspectionOperation(t, "snapshot");
	let i = n;
	let a = false;
	let o = false;
	let s;
	for (let n = 0, r = t; n < 8 && r instanceof Error; n += 1) {
		o ||= r instanceof AggregateError || r instanceof SqliteSnapshotCleanupError;
		const { errcode: t, path: n } = r;
		a ||= hasSqliteSnapshotCapacityCode(r);
		if (a || typeof t === "number" && [
			13,
			778,
			1034,
			1290
		].includes(t) || `${n ?? ""}${path.sep}`.startsWith(`${e}${path.sep}`)) {
			i = true;
			if (typeof t === "number") s = t;
		}
		r = r.cause;
	}
	if (!i) return t;
	const c = a ? "free disk space/quota" : "check filesystem health and write permissions";
	let l = "";
	if (a && r) try {
		const t = sqliteSnapshotSourceFileSize(r) + sqliteSnapshotSourceFileSize(`${r}-wal`) + sqliteSnapshotSourceFileSize(`${r}-journal`);
		const n = tryReadDiskSpace(e)?.availableBytes;
		const i = fsSync.existsSync(`${r}-wal`) && fsSync.existsSync(`${r}-shm`);
		l = `; estimated ${t} bytes needed; ${n === void 0 ? "available bytes unknown" : `${n} bytes available`}; source ${i ? "has live WAL sidecars" : "has no live WAL sidecars"}`;
	} catch {}
	const u = process.env.OPENCLAW_UPDATE_IN_PROGRESS === "1" ? "TMPDIR" : "XDG_CACHE_HOME";
	const d = `${t instanceof Error ? t.message : String(t)}${s !== void 0 ? ` (SQLite errcode=${s})` : ""}; snapshot staging root ${n ? e : path.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`;
	const f = a && !o && readSqliteInspectionOperation(t) !== "source" ? new SqliteSnapshotCapacityError(d, { cause: t }) : new Error(d, { cause: t });
	return isPrivateDirectoryCreationRefused(t) ? markPrivateDirectoryCreationRefused(f) : f;
}
async function createSqliteSnapshotStagingDirectory(e = resolvePrivateSqliteSnapshotStagingRoot(), t = false, n, r = false) {
	n?.throwIfAborted();
	try {
		return await allocateSqliteSnapshotStagingDirectory(e, t, n, r);
	} catch (e) {
		if (e instanceof SqliteSnapshotCleanupError || r && e instanceof AggregateError) throw e;
		n?.throwIfAborted();
		markSqliteInspectionOperation(e, "snapshot");
		throw e;
	}
}
async function allocateSqliteSnapshotStagingDirectory(e = resolvePrivateSqliteSnapshotStagingRoot(), t = false, n, r = false) {
	n?.throwIfAborted();
	if (r) {
		const r = new AbortController();
		return retainSnapshotWork((async () => {
			const { allocateWorkerOwnedSqliteSnapshotDirectory: i } = await import("./sqlite-snapshot-staging-allocation-CiRWXqPP.mjs");
			n?.throwIfAborted();
			r.signal.throwIfAborted();
			const a = await i(e, t, n ? AbortSignal.any([n, r.signal]) : r.signal);
			registerSnapshotTempDirectory(a.directory);
			if (n?.aborted || r.signal.aborted) {
				if (!await removeTempDirectoryAsync(a.directory)) throw new SqliteSnapshotCleanupError(`SQLite snapshot cleanup failed: ${a.directory}`);
				n?.throwIfAborted();
				r.signal.throwIfAborted();
			}
			return a.directory;
		})(), () => r.abort(/* @__PURE__ */ new Error("SQLite snapshot allocation stopped")));
	}
	return createSqliteSnapshotStagingDirectorySync(e, t);
}
function createSqliteSnapshotStagingDirectorySync(e = resolvePrivateSqliteSnapshotStagingRoot(), t = false) {
	const n = createSqliteSnapshotStagingTokenSync(e, t);
	registerSnapshotTempDirectory(n.directory, n.release);
	return n.directory;
}
/** Token workers remove disposable payload under their own native retirement fences. */
function createSqliteSnapshotStagingTokenSync(e = resolvePrivateSqliteSnapshotStagingRoot(), t = false) {
	let n;
	try {
		try {
			n = createPrivateSqliteTempDirectorySync(e, t ? `openclaw-sqlite-readonly-${process.pid}-` : SQLITE_SNAPSHOT_PREFIX);
		} catch (t) {
			throw sqliteSnapshotStagingError(e, t, true);
		}
		return {
			directory: n,
			release: acquireSqliteSnapshotToken(n, "create")
		};
	} catch (e) {
		if (n) removeTempDirectory(n);
		throw e;
	}
}
//#endregion
//#region src/infra/sqlite-wal-checksum.ts
const SQLITE_WAL_MAGIC_LE = 931071618;
const SQLITE_WAL_MAGIC_BE = 931071619;
function readUint32(e, t, n) {
	return n === "LE" ? e.readUInt32LE(t) : e.readUInt32BE(t);
}
/** Frames chain their checksum from the previous frame (or the WAL header). */
function sqliteWalChecksum(e, t, n = [0, 0]) {
	let [r, i] = n;
	for (let n = 0; n < e.length; n += 8) {
		r = r + readUint32(e, n, t) + i >>> 0;
		i = i + readUint32(e, n + 4, t) + r >>> 0;
	}
	return [r, i];
}
//#endregion
//#region src/infra/sqlite-snapshot-wal-prefix.ts
const WAL_HEADER_BYTES = 32;
const WAL_FRAME_HEADER_BYTES = 24;
const COPY_BUFFER_BYTES = 1048576;
function readWalGeneration(e) {
	const t = Buffer.alloc(WAL_HEADER_BYTES);
	if (readFileWindowFullySync(e, t, 0) !== t.length) return;
	const n = t.readUInt32BE(0);
	if (n !== 931071618 && n !== 931071619) return;
	const r = n === 931071618 ? "LE" : "BE";
	const i = t.readUInt32BE(8);
	const [a, o] = sqliteWalChecksum(t.subarray(0, 24), r);
	if (i < 512 || i > 65536 || (i & i - 1) !== 0 || t.readUInt32BE(24) !== a || t.readUInt32BE(28) !== o) return;
	return {
		header: t,
		byteOrder: r,
		frameBytes: WAL_FRAME_HEADER_BYTES + i
	};
}
/**
* Copy the frames SQLite recovery would accept, up to the last commit frame
* within the file length observed at capture. A restarted WAL rewrites frames
* from offset 0 over a stale tail, so bytes past the last valid commit are
* neither part of this generation's committed state nor stable under writers.
*/
function copyCommittedWalFrames(e, t, n, r) {
	const { header: i, byteOrder: a, frameBytes: o } = n;
	if (readWalGeneration(e)?.header.equals(i) !== true) return false;
	const s = i.subarray(16, 24);
	let c = [i.readUInt32BE(24), i.readUInt32BE(28)];
	writeFully(t, i, 0);
	let l = WAL_HEADER_BYTES;
	const u = Math.max(1, Math.floor(COPY_BUFFER_BYTES / o));
	const d = Buffer.allocUnsafe(u * o);
	for (let n = WAL_HEADER_BYTES; n < r;) {
		const i = d.subarray(0, Math.min(d.length, r - n));
		const u = readFileWindowFullySync(e, i, n);
		let f = 0;
		let p = true;
		for (let e = 0; e + o <= u; e += o) {
			const t = i.subarray(e, e + o);
			if (t.readUInt32BE(0) === 0 || !t.subarray(8, 16).equals(s)) {
				p = false;
				break;
			}
			const r = sqliteWalChecksum(t.subarray(WAL_FRAME_HEADER_BYTES), a, sqliteWalChecksum(t.subarray(0, 8), a, c));
			if (t.readUInt32BE(16) !== r[0] || t.readUInt32BE(20) !== r[1]) {
				p = false;
				break;
			}
			c = r;
			f = e + o;
			if (t.readUInt32BE(4) !== 0) l = n + f;
		}
		if (f > 0) writeFully(t, i.subarray(0, f), n);
		if (!p || f < i.length) break;
		n += f;
	}
	fsSync.ftruncateSync(t, l);
	fsSync.fsyncSync(t);
	return l;
}
function writeFully(e, t, n) {
	for (let r = 0; r < t.length;) {
		const i = fsSync.writeSync(e, t, r, t.length - r, n + r);
		if (i <= 0) throw new Error("SQLite WAL snapshot write made no progress");
		r += i;
	}
}
function matchesCapturedWalPrefix(e, t, n) {
	const r = fsSync.openSync(t, "r");
	try {
		const t = fsSync.fstatSync(r);
		if (!t.isFile() || t.size !== n) return false;
		const i = Buffer.allocUnsafe(Math.min(COPY_BUFFER_BYTES, n));
		const a = Buffer.allocUnsafe(i.length);
		for (let t = 0; t < n; t += i.length) {
			const o = Math.min(i.length, n - t);
			const s = i.subarray(0, o);
			const c = a.subarray(0, o);
			if (readFileWindowFullySync(e, s, t) !== o || readFileWindowFullySync(r, c, t) !== o || !s.equals(c)) return false;
		}
		return true;
	} finally {
		fsSync.closeSync(r);
	}
}
/** Preserve source coordination bytes while SQLite interprets a bounded private WAL. */
function prepareSqliteWalPrefixCopy(e, t, n) {
	const r = readWalGeneration(e);
	if (!r) return;
	return () => {
		const i = fsSync.fstatSync(e).size;
		if (!Number.isSafeInteger(i) || i < WAL_HEADER_BYTES) return false;
		const a = fsSync.openSync(t, "wx", 384);
		let o;
		try {
			o = copyCommittedWalFrames(e, a, r, i);
		} finally {
			fsSync.closeSync(a);
		}
		return o !== false && n() && matchesCapturedWalPrefix(e, t, o) && readWalGeneration(e)?.header.equals(r.header) === true;
	};
}
//#endregion
//#region src/infra/sqlite-readonly-location.ts
const SQLITE_HEADER_BYTES = 20;
const SQLITE_JOURNAL_MAGIC = Buffer.from([
	217,
	213,
	5,
	249,
	32,
	161,
	99,
	215
]);
var SqliteSourceChangedError = class extends Error {
	constructor(e, t) {
		super(t?.attempts ? `SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection` : `SQLite source changed during read-only inspection (reason=${e})`, t);
		this.reason = e;
	}
};
function statIfPresent(e) {
	try {
		return fsSync.statSync(e, { bigint: true });
	} catch (e) {
		if (e.code === "ENOENT") return;
		throw e;
	}
}
function readSourceSidecars(e) {
	return {
		journal: Boolean(statIfPresent(`${e}-journal`)),
		shm: Boolean(statIfPresent(`${e}-shm`)),
		wal: Boolean(statIfPresent(`${e}-wal`))
	};
}
function openPinnedFile(e, t) {
	let n;
	try {
		n = fsSync.openSync(e, "r");
	} catch (e) {
		if (e.code === "ENOENT") throw new SqliteSourceChangedError("source-disappeared");
		throw e;
	}
	try {
		const r = fsSync.fstatSync(n, { bigint: true });
		if (t) assertDatabaseFileIdentity(r, t);
		const i = statIfPresent(e);
		if (!r.isFile() || !i?.isFile() || !sameFileIdentity(r, i)) throw new SqliteSourceChangedError("source-identity-changed");
		return {
			descriptor: n,
			identity: r,
			pathname: e
		};
	} catch (e) {
		fsSync.closeSync(n);
		throw e;
	}
}
function readSourceJournalMode(e, t) {
	const n = openPinnedFile(e, t);
	try {
		const e = Buffer.alloc(SQLITE_HEADER_BYTES);
		const t = fsSync.readSync(n.descriptor, e, 0, e.length, 0);
		assertPinnedIdentityUnchanged(n);
		if (t === 0) return "empty";
		if (t !== e.length || e.subarray(0, 16).toString("utf8") !== "SQLite format 3\0") return "unknown";
		return e[18] === 2 || e[19] === 2 ? "wal" : "rollback";
	} finally {
		fsSync.closeSync(n.descriptor);
	}
}
function assertPinnedIdentityUnchanged(e) {
	const t = fsSync.fstatSync(e.descriptor, { bigint: true });
	const n = statIfPresent(e.pathname);
	if (!t.isFile() || !n?.isFile() || !sameFileIdentity(e.identity, t) || !sameFileIdentity(e.identity, n)) throw new SqliteSourceChangedError("source-identity-changed");
}
function copySourceFile(e, t, n) {
	const r = openPinnedFile(e, n);
	try {
		let n;
		try {
			n = fsSync.realpathSync.native(e);
		} catch (e) {
			if (extractErrorCode(e) === "ENOENT") throw new SqliteSourceChangedError("source-disappeared", { cause: e });
			throw e;
		}
		const i = copyRootFileSync({
			source: {
				rootPath: path.dirname(n),
				absolutePath: n
			},
			destination: {
				rootPath: path.dirname(t),
				absolutePath: t
			},
			expectedSourceIdentity: r.identity,
			sourceHardlinks: "allow",
			clone: "auto",
			mode: 384
		});
		try {
			fsSync.fsyncSync(i.fd);
			assertPinnedIdentityUnchanged(r);
		} finally {
			i.close();
		}
	} finally {
		fsSync.closeSync(r.descriptor);
	}
}
function sourceMatchesCopy(e, t, n) {
	const r = openPinnedFile(e, n);
	try {
		const e = fsSync.openSync(t, "r");
		try {
			if (!fsSync.fstatSync(e).isFile()) return false;
			const t = sameFileContentsSync(r.descriptor, e);
			assertPinnedIdentityUnchanged(r);
			return t;
		} finally {
			fsSync.closeSync(e);
		}
	} finally {
		fsSync.closeSync(r.descriptor);
	}
}
function assertExpectedSidecars(e, t) {
	const n = readSourceSidecars(e);
	if (n.journal !== t.journal || n.wal !== t.wal) throw new SqliteSourceChangedError("journal-state-changed");
}
function rollbackJournalReferencesSuperJournal(e) {
	const t = fsSync.openSync(e, "r");
	try {
		const e = fsSync.fstatSync(t).size;
		if (e < 16) return false;
		const n = Buffer.allocUnsafe(16);
		if (fsSync.readSync(t, n, 0, n.length, e - n.length) !== n.length) return false;
		const r = n.readUInt32BE(0);
		return r > 0 && r <= e - 20 && n.subarray(8).equals(SQLITE_JOURNAL_MAGIC);
	} finally {
		fsSync.closeSync(t);
	}
}
function syncPrivateSnapshot(e) {
	const t = fsSync.openSync(e, "r+");
	try {
		fsSync.fsyncSync(t);
	} finally {
		fsSync.closeSync(t);
	}
}
function recoverPrivateJournalCopy(e) {
	if (rollbackJournalReferencesSuperJournal(`${e}-journal`)) throw new Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);
	const t = openNodeSqliteDatabase(e);
	try {
		t.exec("PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;");
		t.prepare("PRAGMA schema_version;").get();
	} finally {
		t.close();
	}
	fsSync.rmSync(`${e}-journal`, { force: true });
	syncPrivateSnapshot(e);
}
function* createStableReadOnlyCopyInTempDirectory(e, t, n, r = n ? path.dirname(n) : resolvePrivateSqliteSnapshotStagingRoot(), i, a) {
	let o = n;
	try {
		o ??= createSqliteSnapshotStagingDirectorySync(r);
		const n = path.join(o, "database.sqlite.partial");
		const s = path.join(o, "first");
		if (process.platform !== "win32") fsSync.chmodSync(o, 448);
		if (readSourceJournalMode(e, i) !== t) throw new SqliteSourceChangedError("journal-mode-changed");
		const c = readSourceSidecars(e);
		let l = false;
		if (t === "wal" && c.wal && !c.journal) {
			const t = openPinnedFile(`${e}-wal`);
			try {
				const r = prepareSqliteWalPrefixCopy(t.descriptor, `${n}-wal`, () => sourceMatchesCopy(e, n, i));
				if (r) yield {
					sourcePath: e,
					targetPath: n,
					expectedSourceIdentity: i
				};
				const a = r?.();
				assertPinnedIdentityUnchanged(t);
				if (a === false) throw new SqliteSourceChangedError("wal-copy-unstable");
				l = a === true;
			} finally {
				fsSync.closeSync(t.descriptor);
			}
		}
		const u = [...c.journal ? ["-journal"] : [], ...c.wal ? ["-wal"] : []];
		if (l) assertExpectedSidecars(e, c);
		else if (u.length > 0) {
			for (const t of u) yield {
				sourcePath: `${e}${t}`,
				targetPath: `${n}${t}`
			};
			yield {
				sourcePath: e,
				targetPath: n,
				expectedSourceIdentity: i
			};
			if (!sourceMatchesCopy(e, n, i)) throw new SqliteSourceChangedError("main-changed-during-copy");
			for (const t of u) if (!sourceMatchesCopy(`${e}${t}`, `${n}${t}`)) throw new SqliteSourceChangedError(t === "-wal" ? "wal-changed-during-copy" : "rollback-journal-changed-during-copy");
			assertExpectedSidecars(e, c);
		} else {
			yield {
				sourcePath: e,
				targetPath: s,
				expectedSourceIdentity: i
			};
			assertExpectedSidecars(e, c);
			const t = a !== void 0 || sourceMatchesCopy(e, s, i);
			assertExpectedSidecars(e, c);
			if (!t) throw new SqliteSourceChangedError("main-changed-during-copy");
			fsSync.rmSync(n, { force: true });
			fsSync.renameSync(s, n);
		}
		if (readSourceJournalMode(e, i) !== t) throw new SqliteSourceChangedError("journal-mode-changed");
		if (a && (c.journal || c.wal && fsSync.statSync(`${n}-wal`).size !== 0)) throw new SqliteSourceChangedError("recovery-data-appeared");
		if (c.journal) recoverPrivateJournalCopy(n);
		return publishPreparedCopy(o, a);
	} catch (t) {
		const r = o ? sqliteSnapshotStagingError(o, t, false, e) : t;
		if (o && n === void 0) {
			const e = [r];
			if (!removeTempDirectory(o, (t) => e.push(t))) throw preparationCleanupError(e, "SQLite snapshot preparation");
		}
		throw r;
	}
}
function copyPreparedLocationSync(e) {
	let t = e.next();
	while (!t.done) {
		try {
			const { sourcePath: e, targetPath: n, expectedSourceIdentity: r } = t.value;
			copySourceFile(e, n, r);
		} catch (n) {
			t = e.throw(n);
			continue;
		}
		t = e.next();
	}
	return t.value;
}
function* prepareArtifactPreservingCopy(e, t, n, r) {
	const i = fsSync.realpathSync.native(e);
	for (let e = 0;; e += 1) try {
		return yield* createStableReadOnlyCopyInTempDirectory(i, readSourceJournalMode(i, n), typeof t === "object" ? t.directory : void 0, typeof t === "string" ? t : void 0, n, r);
	} catch (n) {
		if (typeof t === "object") discardPreparedCopyPayload(t.directory, n);
		if (!(n instanceof SqliteSourceChangedError)) throw n;
		if (e + 1 >= 10) throw new SqliteSourceChangedError(n.reason, {
			cause: n,
			attempts: 10
		});
		waitForSnapshotRetrySync(e);
	}
}
function prepareSqliteReadOnlyLocationSyncInProcess(e, t, n, r) {
	return copyPreparedLocationSync(prepareArtifactPreservingCopy(e, t, n, r));
}
async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e, t, n, r) {
	const assertReady = () => {
		n?.throwIfAborted();
		t();
		if (!e.isOpen || e.isTransaction) throw new Error("SQLite inspection requires an open owner outside a transaction");
	};
	assertReady();
	const i = await createSqliteSnapshotStagingDirectory(void 0, false, n, r === "async");
	try {
		assertReady();
		const r = path.join(i, "database.sqlite.partial");
		await retainSnapshotWork(backupNodeSqliteDatabase(e, r));
		n?.throwIfAborted();
		t();
		return publishPreparedCopy(i);
	} catch (e) {
		const t = [e];
		if (!await removeTempDirectoryAsync(i, (e) => t.push(e)) && r === "async") throw preparationCleanupError(t, "Owned SQLite snapshot preparation");
		throw e;
	}
}
//#endregion
//#region src/infra/sqlite-snapshot-single-flight.ts
const snapshotFlights = resolveGlobalSingleton(Symbol.for("openclaw.sqliteSnapshotFlights"), () => ({
	unscoped: /* @__PURE__ */ new Map(),
	scoped: /* @__PURE__ */ new WeakMap()
}));
function completed(e) {
	const t = createRetainedOperation(() => {});
	t.resolve(e);
	return t.operation;
}
function serviceWhenSettled(e, t) {
	e.result.then(t, t);
}
function createFlight(e, t, n) {
	let r;
	let i = false;
	let a = false;
	let o;
	let s;
	let c;
	const l = createRetainedOperation(() => {
		if (a || l.operation.read().status !== "pending") return;
		a = true;
		try {
			if (!i) {
				i = true;
				r = n(d.controller.signal, (e) => c = e);
				serviceWhenSettled(r.operation, serviceFlight);
			}
			r.operation.service();
			const e = r.operation.read();
			if (e.status === "fulfilled") l.resolve(e.value);
			else if (e.status === "rejected") l.reject(e.error);
		} catch (e) {
			l.reject(e);
		} finally {
			a = false;
		}
	});
	const u = createRetainedOperation(() => {
		l.operation.service();
		const n = l.operation.read();
		if (n.status === "pending" || u.operation.read().status !== "pending") return;
		if (e.get(t) === d) e.delete(t);
		if (n.status === "rejected") u.reject(c ?? n.error);
		else if (d.references > 0) u.resolve(n.value);
		else {
			if (!o) {
				o = releaseSnapshot(d, n.value);
				serviceWhenSettled(o, () => u.operation.service());
			}
			o.service();
			const e = o.read();
			if (e.status === "fulfilled") {
				if (e.value) u.resolve(n.value);
				else u.reject(new SqliteSnapshotCleanupError("SQLite orphan snapshot cleanup did not complete"));
			} else if (e.status === "rejected") u.reject(e.error);
		}
	});
	function serviceFlight() {
		l.operation.service();
		for (const e of d.listeners) e();
		u.operation.service();
	}
	const d = {
		controller: new AbortController(),
		references: 0,
		listeners: /* @__PURE__ */ new Set(),
		production: l.operation,
		settled: u.operation,
		closeProducer() {
			s ??= r?.startClose?.() ?? completed(void 0);
			return s;
		}
	};
	retainSnapshotWork(u.operation.result, () => {
		d.controller.abort(/* @__PURE__ */ new Error("SQLite snapshot owner stopped"));
		serviceFlight();
	});
	return d;
}
function releaseSnapshot(e, t) {
	return flatMapRetainedOperation(t.startCleanup(), (t) => t ? mapRetainedOperation(e.closeProducer(), () => true) : completed(false));
}
function leaseFlight(e, t) {
	let n = false;
	let r;
	const releaseReference = () => {
		if (!n) {
			n = true;
			e.references--;
		}
		return e.references === 0;
	};
	const startCleanup = () => {
		r ??= !n && releaseReference() ? releaseSnapshot(e, t) : completed(true);
		return r;
	};
	return {
		location: t.location,
		cleanupRoot: t.cleanupRoot,
		privateFamily: t.privateFamily,
		cleanup() {
			if (n) {
				const e = r?.read();
				return !e || e.status === "fulfilled" && e.value;
			}
			if (e.references > 1) {
				releaseReference();
				return true;
			}
			const i = t.cleanup();
			if (i) releaseReference();
			return i;
		},
		cleanupAsync: () => startCleanup().result,
		startCleanup
	};
}
function startSnapshotFlight(e, t, n, r, i) {
	r?.throwIfAborted();
	const a = `${readDatabasePathIdentitySync(e).key}:${t}`;
	let o = snapshotFlights.unscoped;
	if (i?.scope) {
		let e = snapshotFlights.scoped.get(i.scope);
		if (!e) {
			e = /* @__PURE__ */ new Map();
			snapshotFlights.scoped.set(i.scope, e);
		}
		o = e;
	}
	let s = o.get(a);
	if (!s) {
		s = createFlight(o, a, n);
		o.set(a, s);
	}
	const c = s;
	c.references++;
	let l = false;
	let u = false;
	let d;
	const f = createRetainedOperation(() => {
		if (f.operation.read().status !== "pending") return;
		if (l || r?.aborted) {
			if (!u) {
				u = true;
				c.references--;
			}
			if (c.references === 0) {
				c.controller.abort(r?.reason);
				if (o.get(a) === c) o.delete(a);
				c.settled.service();
				if (c.settled.read().status === "pending") return;
			}
			f.reject(r?.reason ?? /* @__PURE__ */ new Error("SQLite snapshot preparation closed"));
		} else {
			c.production.service();
			const e = c.production.read();
			if (e.status === "pending") return;
			if (e.status === "fulfilled") f.resolve(leaseFlight(c, e.value));
			else {
				c.references--;
				f.reject(e.error);
			}
		}
		r?.removeEventListener("abort", service);
		c.listeners.delete(service);
		c.settled.service();
	});
	const service = () => f.operation.service();
	serviceWhenSettled(c.settled, service);
	c.listeners.add(service);
	r?.addEventListener("abort", service, { once: true });
	queueMicrotask(service);
	return {
		...f.operation,
		startClose() {
			l = true;
			f.operation.service();
			const e = f.operation.read();
			d ??= e.status === "fulfilled" ? mapRetainedOperation(e.value.startCleanup(), (e) => {
				if (!e) throw new SqliteSnapshotCleanupError("SQLite snapshot lease cleanup did not complete");
			}) : c.references === 0 ? c.closeProducer() : completed(void 0);
			return d;
		}
	};
}
/** Promise-only producers remain on their existing awaited path, never a sync bridge. */
function startAwaitedSnapshotWork(e) {
	const t = createRetainedOperation(() => {});
	Promise.resolve().then(e).then(t.resolve, t.reject);
	return t.operation;
}
async function prepareSingleFlightSqliteSnapshot(e, t, n, r, i) {
	return startSnapshotFlight(e, t, (e, t) => ({ operation: startAwaitedSnapshotWork(async () => {
		const r = await n(e, t);
		return {
			...r,
			startCleanup: () => startAwaitedSnapshotWork(() => r.cleanupAsync())
		};
	}) }), r, i).result;
}
function startSingleFlightSqliteSnapshot(e, t, n, r, i) {
	return startSnapshotFlight(e, t, (e, t) => {
		const r = n(e, t);
		return {
			operation: r,
			startClose: () => r.startClose()
		};
	}, r, i);
}
//#endregion
//#region src/infra/sqlite-live-snapshot.ts
const liveOwners = resolveGlobalSingleton(Symbol.for("openclaw.sqliteLiveSnapshotOwners"), () => /* @__PURE__ */ new Map());
function registerLiveSqliteSnapshotOwner(e) {
	const t = readDatabasePathIdentitySync(e.databasePath);
	const n = {
		assertCurrent: e.assertCurrent,
		database: e.database
	};
	liveOwners.set(t.key, n);
	return () => {
		if (liveOwners.get(t.key) === n) liveOwners.delete(t.key);
	};
}
//#endregion
//#region src/infra/sqlite-private-snapshot-fork.ts
function fingerprint(e) {
	return [
		e.dev,
		e.ino,
		e.birthtimeNs,
		e.ctimeNs,
		e.mtimeNs,
		e.size
	].join(":");
}
/**
* As root, SQLite fchowns the WAL on every native open, including read-only ones.
* That changes ctime (and birthtime where libuv derives it) but never the WAL's bytes.
*/
function walFingerprint(e) {
	return [
		e.dev,
		e.ino,
		e.mtimeNs,
		e.size
	].join(":");
}
function readFile$1(e) {
	const t = fsSync.lstatSync(e, {
		bigint: true,
		throwIfNoEntry: false
	});
	if (!t) return;
	if (!t.isFile() || t.nlink !== 1n) throw new Error(`Private SQLite snapshot must be an independent regular file: ${e}`);
	return t;
}
/** Only the retained read owner calls this, before lending its newly prepared image. */
function captureSqlitePrivateSnapshotFamily(e, t) {
	if (fsSync.lstatSync(`${e}-journal`, { throwIfNoEntry: false })) return;
	const n = readFile$1(e);
	const r = readFile$1(`${e}-wal`);
	return n ? {
		root: t,
		main: fingerprint(n),
		wal: r && r.size > 32n ? walFingerprint(r) : null
	} : void 0;
}
//#endregion
//#region src/infra/sqlite-snapshot-source.ts
/** A drained family under schema custody can be inspected without a whole-file copy. */
function readCustodiedDrainedSqliteSource(e) {
	if (!maintenanceOwnerHasSourceCustody(getOpenClawDatabaseMaintenanceScope(), e)) return;
	if (fsSync.existsSync(`${e}-journal`) || (fsSync.statSync(`${e}-wal`, { throwIfNoEntry: false })?.size ?? 0) > 0) return;
	return fsSync.statSync(e, { bigint: true });
}
function assertCustodiedSourceUnchanged(e, t) {
	const n = fsSync.statSync(e, {
		bigint: true,
		throwIfNoEntry: false
	});
	if (!n || n.ino !== t.ino || n.size !== t.size || n.mtimeNs !== t.mtimeNs || readCustodiedDrainedSqliteSource(e) === void 0) throw new Error(`SQLite source changed during in-place inspection: ${e}`);
}
/** The inspection scope owns private readers until native close and snapshot disposal settle. */
function openSqliteReadOnlyDatabase(e, t = {}) {
	const n = artifactPreservingReads.getStore();
	if (!n || !isArtifactPreservingStateRead("agent", e)) return openNodeSqliteDatabase(e, {
		...t,
		readOnly: true
	});
	const r = readCustodiedDrainedSqliteSource(e);
	const i = r || isUpdateRehearsalPrivateDatabase(e, process.env) ? void 0 : prepareSqliteReadOnlyLocationSync(e);
	const a = i ? retainSnapshotTempDirectory(i.cleanupRoot ?? path.dirname(i.location)) : void 0;
	const o = {};
	const close = () => {
		o.close?.();
		a?.();
		if (i && !i.cleanup()) throw new SqliteSnapshotCleanupError("SQLite inspection snapshot cleanup failed.");
		n.readers.delete(close);
	};
	n.readers.add(close);
	const s = i?.location ?? (r ? resolveImmutableSqliteFileUri(e) : e);
	const c = openNodeSqliteDatabase(s, {
		...t,
		readOnly: true
	});
	const l = c.close.bind(c);
	o.close = () => {
		if (c.isOpen) {
			l();
			if (r) assertCustodiedSourceUnchanged(e, r);
		}
	};
	c.close = close;
	return c;
}
function startSqliteReadOnlyLocationAsync(e, t = {}) {
	const n = resolveSqliteInspectionSignal(t.signal);
	n?.throwIfAborted();
	const r = path.resolve(e);
	const i = t.preserveSourceArtifacts === true || isArtifactPreservingStateRead("agent", r);
	const a = t.expectedSourceIdentity === void 0 ? void 0 : readDatabaseFileIdentity(t.expectedSourceIdentity);
	if (a && !i) throw new Error("SQLite source identity requires artifact-preserving preparation");
	const o = t.signal !== void 0;
	const { env: s, cwd: c } = captureSqliteReadOnlyWorkerLaunch();
	const l = resolvePrivateSqliteSnapshotStagingRoot();
	const u = isSqliteInspectionDeadlineOwnedByCaller();
	const d = captureSqliteSnapshotStagingOwner();
	const f = AsyncLocalStorage.snapshot();
	return startSingleFlightSqliteSnapshot(r, `${i ? "worker-sync" : "worker-async"}:${o ? "strict" : "best-effort"}:async-token${a ? `:${JSON.stringify(a)}` : ""}`, (e) => f(() => {
		const t = d.start({
			type: "prepare",
			root: l,
			pathname: r,
			allowLegacyWorker: false,
			preserveSourceArtifacts: i,
			expectedSourceIdentity: a,
			deadlineOwnedByCaller: u,
			launch: {
				env: s,
				cwd: c,
				transport: { kind: "native" }
			}
		}, e);
		return {
			...mapRetainedOperation(t, (e) => {
				if (e.type !== "prepared") throw new Error("SQLite snapshot producer returned an allocation without its prepared location");
				const t = adoptPreparedLocation(e.location, e.directory, o);
				t.privateFamily = i ? captureSqlitePrivateSnapshotFamily(e.location, e.directory) : void 0;
				return t;
			}),
			startClose: () => t.startClose()
		};
	}), n, { scope: d });
}
/** Metadata selects live backup in a one-shot child; strict snapshots retain their raw-copy child. */
async function prepareSqliteReadOnlyLocationAwaited(e, t) {
	const n = resolveSqliteInspectionSignal(t.signal);
	const r = path.resolve(e);
	const i = readDatabaseFileIdentity(t.expectedSourceIdentity);
	return prepareSingleFlightSqliteSnapshot(r, `worker-${t.allowLiveOwner ? "metadata" : "sync"}:strict:awaited-token:${JSON.stringify(i)}`, async (e, n) => {
		const a = t.allowLiveOwner;
		return useAwaitedSnapshotWorker(e, n, async (t, n) => {
			const o = {
				mode: a ? "metadata" : "sync",
				stagingRoot: n,
				expectedSourceIdentity: i,
				signal: e
			};
			const s = a ? await runSqliteReadOnlyWorkerOnce(r, o) : await t.run(r, o);
			if (typeof s !== "string") throw new Error("SQLite snapshot preparation returned an invalid location");
			e.throwIfAborted();
			return adoptPreparedLocation(s, n, true);
		});
	}, n);
}
async function useAwaitedSnapshotWorker(e, t, n) {
	e.throwIfAborted();
	const r = captureSqliteReadOnlyWorkerLaunch();
	let i = createScopedSqliteReadOnlyWorker({
		...r,
		retainOnOperationError: true
	});
	let a;
	let o;
	const retire = () => {
		if (o && o.read().status !== "rejected") return o;
		const e = createRetainedOperation(() => {});
		o = e.operation;
		(async () => {
			if (a) {
				const e = i.isRetired();
				if (e) {
					await i.close();
					i = createScopedSqliteReadOnlyWorker(r);
				}
				await i.run(a, { mode: e ? "staging-reconcile" : "staging-retire" });
			}
			await i.close();
			await i.closed;
			if (a) await fsSync.promises.rm(a, {
				recursive: true,
				force: true,
				maxRetries: 3,
				retryDelay: 20
			});
		})().then(e.resolve, e.reject);
		return o;
	};
	try {
		const t = await i.run(resolvePrivateSqliteSnapshotStagingRoot(), {
			mode: "staging-create",
			signal: e
		});
		if (typeof t !== "string") throw new Error("SQLite snapshot allocation returned an invalid directory");
		a = t;
		registerRetainedSnapshotTempDirectory(a, retire);
		e.throwIfAborted();
		const r = await n(i, a);
		e.throwIfAborted();
		return r;
	} catch (e) {
		try {
			if (a) {
				if (!await removeTempDirectoryAsync(a)) throw new SqliteSnapshotCleanupError(`SQLite snapshot cleanup failed: ${a}`);
			} else {
				await i.close();
				await i.closed;
			}
		} catch (n) {
			const r = new AggregateError([e, n], "SQLite snapshot preparation and cleanup failed");
			t?.(r);
			throw r;
		}
		throw e;
	}
}
function prepareSqliteReadOnlyLocationSync(e, t) {
	const n = createSqliteSnapshotStagingDirectorySync();
	try {
		return adoptPreparedLocation(runSqliteReadOnlyWorkerSync(e, n, "sync", t), n);
	} catch (e) {
		if (!removeTempDirectory(n)) throw new SqliteSnapshotCleanupError(`${coerceErrorMessage(e)}; SQLite snapshot cleanup failed: ${n}`, { cause: e });
		throw e;
	}
}
//#endregion
//#region src/infra/sqlite-terminal-open-latch.ts
/**
* Per-path latch for terminal database-open failures (newer schema, proven
* corruption). Recording quarantines the path: any live handle is closed and
* every later open fails fast until doctor repairs the file and clears it.
*/
function createSqliteTerminalOpenLatch(e) {
	const t = /* @__PURE__ */ new Map();
	return {
		/** Read the owner's recorded fact without running filesystem or database inspection. */
		peek: (e) => t.get(path.resolve(e)),
		get: (e) => t.get(path.resolve(e)),
		record: (n, r) => {
			const i = path.resolve(n);
			materializeErrorStack(r);
			t.set(i, r);
			e.closeByPath(i, r);
		},
		clear: (e) => {
			t.delete(path.resolve(e));
		},
		clearAll: (e) => {
			for (const n of t.keys()) if (e === void 0 || isPathInside(e, n)) t.delete(n);
		}
	};
}
//#endregion
//#region src/infra/sqlite-file-generation.ts
function canRetainDigest(e, t) {
	const n = t - 2000000000n;
	return typeof e.dev === "bigint" && typeof e.ino === "bigint" && typeof e.size === "bigint" && e.dev !== 0n && e.ino !== 0n && typeof e.birthtimeNs === "bigint" && typeof e.mtimeNs === "bigint" && typeof e.ctimeNs === "bigint" && e.mtimeNs > 0n && e.ctimeNs > 0n && e.mtimeNs < n && e.ctimeNs < n;
}
function timestampNs(e, t) {
	return e ?? (typeof t === "bigint" ? t * 1000000n : BigInt(Math.trunc(t * 1e6)));
}
function fingerprintFile(e, t) {
	const n = BigInt(Date.now()) * 1000000n;
	const r = fsSync.openSync(e, "r");
	try {
		const i = fsSync.fstatSync(r, { bigint: true });
		if (!i.isFile()) throw new Error("SQLite generation target must be a regular file");
		const a = t.get(e);
		if (a && canRetainDigest(i, n) && sameFileMutationFingerprint(a, i)) {
			const t = fsSync.fstatSync(r, { bigint: true });
			const n = fsSync.statSync(e, { bigint: true });
			if (n.isFile() && sameFileMutationFingerprint(i, t) && sameFileMutationFingerprint(t, n)) return a;
		}
		const { sha256: o } = hashPublishedFileSync(fsSync.realpathSync.native(e), i);
		const s = fsSync.fstatSync(r, { bigint: true });
		const c = fsSync.statSync(e, { bigint: true });
		if (!sameFileStatFingerprint(i, s) || !sameFileStatFingerprint(s, c)) throw new Error(`SQLite generation target changed while hashing: ${e}`);
		const l = {
			birthtimeNs: timestampNs(s.birthtimeNs, s.birthtimeMs),
			ctimeNs: timestampNs(s.ctimeNs, s.ctimeMs),
			dev: s.dev,
			ino: s.ino,
			mtimeNs: timestampNs(s.mtimeNs, s.mtimeMs),
			sha256: o,
			size: s.size
		};
		if (canRetainDigest(i, n) && sameFileMutationFingerprint(i, s) && sameFileMutationFingerprint(s, c)) t.set(e, l);
		else t.delete(e);
		return l;
	} finally {
		fsSync.closeSync(r);
	}
}
function readOptionalFile(e, t) {
	try {
		return fingerprintFile(e, t);
	} catch (n) {
		if (n.code === "ENOENT") {
			t.delete(e);
			return;
		}
		throw n;
	}
}
/** One observation owns its digests; every read still checks the complete family. */
function createSqliteFileGenerationReader() {
	const e = /* @__PURE__ */ new Map();
	return (t) => {
		const n = fingerprintFile(t, e);
		const r = readOptionalFile(`${t}-journal`, e);
		const i = readOptionalFile(`${t}-wal`, e);
		return {
			database: n,
			...r ? { journal: r } : {},
			...i ? { wal: i } : {}
		};
	};
}
/** Raw source reads require an isolated process or a drained database owner. */
function readStableSqliteFileGeneration(e, t = createSqliteFileGenerationReader()) {
	const n = t(e);
	const r = t(e);
	if (!sameSqliteFileGeneration(n, r)) throw new Error(`SQLite file generation changed while reading: ${e}`);
	return r;
}
function sameFileFingerprint(e, t) {
	return e.dev === t.dev && e.ino === t.ino && sameFileStatFingerprint(e, t) && e.sha256 === t.sha256;
}
function sameOptionalFileFingerprint(e, t) {
	return e === void 0 ? t === void 0 : t !== void 0 && sameFileFingerprint(e, t);
}
function sameSqliteFileGeneration(e, t) {
	return sameFileFingerprint(e.database, t.database) && sameOptionalFileFingerprint(e.journal, t.journal) && sameOptionalFileFingerprint(e.wal?.size === 0n ? void 0 : e.wal, t.wal?.size === 0n ? void 0 : t.wal);
}
function serializeFileFingerprint(e) {
	return {
		birthtimeNs: e.birthtimeNs.toString(),
		ctimeNs: e.ctimeNs.toString(),
		dev: e.dev.toString(),
		ino: e.ino.toString(),
		mtimeNs: e.mtimeNs.toString(),
		sha256: e.sha256,
		size: e.size.toString()
	};
}
function serializeSqliteFileGeneration(e) {
	return JSON.stringify({
		database: serializeFileFingerprint(e.database),
		...e.journal ? { journal: serializeFileFingerprint(e.journal) } : {},
		...e.wal ? { wal: serializeFileFingerprint(e.wal) } : {}
	});
}
function parseFileFingerprint(e) {
	if (!isRecord(e)) throw new Error("SQLite file fingerprint must be an object");
	for (const t of [
		"birthtimeNs",
		"ctimeNs",
		"dev",
		"ino",
		"mtimeNs",
		"size"
	]) if (typeof e[t] !== "string" || !/^-?\d+$/u.test(e[t])) throw new Error(`SQLite file fingerprint ${t} is invalid`);
	if (typeof e.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(e.sha256)) throw new Error("SQLite file fingerprint sha256 is invalid");
	return {
		birthtimeNs: BigInt(e.birthtimeNs),
		ctimeNs: BigInt(e.ctimeNs),
		dev: BigInt(e.dev),
		ino: BigInt(e.ino),
		mtimeNs: BigInt(e.mtimeNs),
		sha256: e.sha256,
		size: BigInt(e.size)
	};
}
function parseSqliteFileGeneration(e) {
	const t = JSON.parse(e);
	if (!isRecord(t)) throw new Error("SQLite file generation must be an object");
	return {
		database: parseFileFingerprint(t.database),
		...t.journal === void 0 ? {} : { journal: parseFileFingerprint(t.journal) },
		...t.wal === void 0 ? {} : { wal: parseFileFingerprint(t.wal) }
	};
}
//#endregion
//#region src/infra/sqlite-file-generation-worker.ts
/** Raw descriptor closes must not release a sibling connection's process-wide SQLite locks. */
function readSqliteFileGenerationSync(e) {
	return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e, void 0, "file-generation"));
}
//#endregion
//#region src/state/openclaw-quarantine-store.ts
const OPENCLAW_QUARANTINE_SCHEMA_VERSION = 2;
const OPENCLAW_QUARANTINE_BUSY_TIMEOUT_MS = 5e3;
const quarantineSchemaAdmission = {
	name: "openclaw.quarantine.schema",
	lifetime: "process",
	schemaDependent: true,
	read(e) {
		if (typeof e !== "object" || e === null || !("version" in e) || typeof e.version !== "number") return;
		return { version: e.version };
	}
};
function quarantineDecisionAdmission(e) {
	return {
		name: `openclaw.quarantine.decision:${path.resolve(e)}`,
		lifetime: "process",
		read: (e) => e === null || isQuarantineDecision(e) ? e : void 0
	};
}
function isQuarantineDecision(e) {
	return isRecord(e) && (e.kind === "agent" || e.kind === "state") && typeof e.reason === "string" && typeof e.quarantinedAt === "number" && (e.verifiedGenerationJson === null || typeof e.verifiedGenerationJson === "string");
}
function readQuarantineSchemaVersion(e, t, n = false) {
	const r = n ? void 0 : getSqliteDatabaseAdmission(e, quarantineSchemaAdmission);
	if (r) return r.version;
	const i = e.prepare("PRAGMA user_version").get()?.user_version;
	if (typeof i !== "number" || !Number.isInteger(i)) throw new Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);
	if (i > 2) throw new Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);
	if (i !== 0) publishSqliteDatabaseAdmission(e, quarantineSchemaAdmission, { version: i });
	return i;
}
/** Runtime guards share the owner's decision; explicit repair may inspect disk. */
function readOpenClawDatabaseQuarantine(e, t = {}) {
	const n = resolveQuarantineStorePath(t.env ?? process.env);
	const load = () => readPersistedQuarantineDecision(e, n, t.fresh) ?? null;
	const r = t.fresh ? load() : getOrLoadSqliteDatabaseAdmissionForPath(n, quarantineDecisionAdmission(e), load);
	return r ? resolveQuarantineDecision(r, e, n) : void 0;
}
function readPersistedQuarantineDecision(e, t, n = false) {
	if (!existsSync(t)) return;
	const r = openSqliteReadOnlyDatabase(t, { timeout: OPENCLAW_QUARANTINE_BUSY_TIMEOUT_MS });
	let i;
	try {
		i = { value: readQuarantineDecision(r, e, t, n) };
	} catch (e) {
		i = { error: e };
	}
	try {
		r.close();
	} catch (n) {
		let r;
		let a = "error" in i ? i.error : void 0;
		if ("value" in i && i.value) try {
			r = resolveQuarantineDecision(i.value, e, t);
		} catch (e) {
			a = e;
		}
		throw new OpenClawQuarantineReadCleanupError(a === void 0 ? [n] : [a, n], r);
	}
	if ("error" in i) throw i.error;
	return i.value;
}
function readQuarantineDecision(e, t, n, r = false) {
	const i = readQuarantineSchemaVersion(e, n, r);
	if (i === 0) return;
	const a = i >= 2 ? ", verified_generation" : "";
	const o = e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(path.resolve(t));
	if (!o) return;
	const s = i >= 2 ? o.verified_generation : void 0;
	if (o.kind !== "agent" && o.kind !== "state" || typeof o.reason !== "string" || typeof o.quarantined_at !== "number" || !Number.isInteger(o.quarantined_at) || s !== void 0 && s !== null && typeof s !== "string") throw new Error(`OpenClaw quarantine store ${n} contains an invalid row.`);
	return {
		kind: o.kind,
		quarantinedAt: o.quarantined_at,
		reason: o.reason,
		verifiedGenerationJson: typeof s === "string" ? s : null
	};
}
function resolveQuarantineDecision(e, t, n) {
	if (e.verifiedGenerationJson !== null) {
		let r;
		try {
			r = parseSqliteFileGeneration(e.verifiedGenerationJson);
		} catch {
			throw new Error(`OpenClaw quarantine store ${n} contains an invalid row.`);
		}
		try {
			const e = readSqliteFileGenerationSync(path.resolve(t));
			if (!sameSqliteFileGeneration(r, e)) return;
		} catch {
			return;
		}
	}
	return {
		kind: e.kind,
		quarantinedAt: e.quarantinedAt,
		reason: e.reason
	};
}
/** Runtime opens refuse recorded damage while tolerating a broken quarantine index. */
function readOpenClawDatabaseQuarantineFailure(e, t, n = {}) {
	let r;
	let i;
	try {
		r = readOpenClawDatabaseQuarantine(t, n);
	} catch (e) {
		if (!(e instanceof OpenClawQuarantineReadCleanupError)) return;
		if (!e.quarantine) throw e;
		r = e.quarantine;
		i = e;
	}
	if (!r) return;
	const a = /* @__PURE__ */ new Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason ?? "unknown integrity error"}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`);
	a.name = "SqliteIntegrityError";
	if (i) a.cause = i;
	return a;
}
//#endregion
//#region src/state/openclaw-state-db-borrow.ts
/** The canonical cache supplies identity and custody; this owner manages its native references. */
function createStateDatabaseRetainer(e, t) {
	const admit = (e, n, r) => {
		const i = getOpenClawDatabaseMaintenanceScope();
		if (n === "cached-read") i?.assertReadAdmission();
		else i?.assertAdmission();
		t.assertOpen(e, n, r);
		return i;
	};
	const retain = (n, r, i = false) => {
		t.capture(n.path).assertCurrent();
		if (e.cachedDatabases.get(n.path) !== n || !n.db.isOpen) throw new Error("OpenClaw state database borrow requires its current canonical handle");
		const a = e.borrowers.get(n.db) ?? {
			references: /* @__PURE__ */ new Set(),
			retiring: false,
			cleanupComplete: false
		};
		if (a.retiring) throw new Error("OpenClaw state database native owner is retiring");
		if (!i) observeOpenClawDatabaseMaintenanceResource(n.db);
		e.borrowers.set(n.db, a);
		const isCurrent = () => !r || isOpenClawDatabaseMaintenanceResourceOwned(n.db, r);
		/** Preserve the requesting owner's retirement when the last reference is only a read pin. */
		const o = i ? void 0 : {
			ordinary: r === void 0,
			isCurrent,
			retire: () => {
				if (!isCurrent()) {
					a.retiring = false;
					return;
				}
				t.retire(n, r === void 0);
			}
		};
		function createAsyncStateDatabaseRetirement() {
			const e = {};
			let r;
			let i;
			const finish = (r) => {
				a.references.delete(e);
				if (r?.isCurrent()) r.retire();
				else a.retiring = false;
				a.retirement = void 0;
				a.asyncRetirement = void 0;
				i?.();
				i = void 0;
				t.touch(n);
			};
			const run = () => {
				if (r) return r;
				if (a.cleanupComplete || a.references.size > (a.references.has(e) ? 1 : 0)) return Promise.resolve();
				if (!a.retirement?.isCurrent()) {
					finish();
					return Promise.resolve();
				}
				a.retiring = true;
				a.references.add(e);
				i ??= t.ownRetirement(n, close);
				r = Promise.resolve().then(async () => {
					await n.walMaintenance.stop();
					finish(a.retirement);
				}).catch((r) => {
					a.references.add(e);
					t.retainFailed(n);
					throw r;
				});
				r.catch(() => {});
				return r;
			};
			function close() {
				const e = run();
				return e.catch((t) => {
					if (r === e) r = void 0;
					throw t;
				});
			}
			return {
				start: () => void run(),
				close
			};
		}
		const s = {};
		a.references.add(s);
		let c = false;
		const release = () => {
			if (c || a.cleanupComplete) {
				c = true;
				return;
			}
			c = true;
			a.references.delete(s);
			if (a.retirement && !a.retirement.isCurrent()) {
				a.retirement = void 0;
				a.asyncRetirement = void 0;
				a.retiring = false;
			}
			if (o?.isCurrent() && !a.retirement?.ordinary) a.retirement = o;
			if (a.references.size > 0) return;
			if (!a.retirement) {
				t.touch(n);
				return;
			}
			a.retiring = true;
			if (a.asyncRetirement) {
				a.asyncRetirement.start();
				return;
			}
			try {
				a.retirement.retire();
			} catch (e) {
				c = false;
				t.retainFailed(n);
				throw e;
			}
			a.retirement = void 0;
			t.touch(n);
		};
		const l = {
			release,
			async releaseAsync() {
				if (a.cleanupComplete) return;
				if ((o?.isCurrent() && !a.retirement?.ordinary ? o : a.retirement)?.isCurrent()) a.asyncRetirement ??= createAsyncStateDatabaseRetirement();
				release();
				await a.asyncRetirement?.close();
			}
		};
		r?.own(l, "shared-references", () => l.releaseAsync());
		return l;
	};
	const findReadDatabase = (t, n, r) => {
		const i = resolveDatabasePath({ path: t });
		const a = e.cachedDatabases.get(i);
		if (!a?.db.isOpen) return {
			database: void 0,
			scope: void 0
		};
		return {
			database: a,
			scope: admit(i, n, r)
		};
	};
	const retainReadReference = (t, n) => {
		const r = retain(t, n, true);
		const assertCurrent = () => {
			if (e.cachedDatabases.get(t.path) !== t || !t.db.isOpen) throw new Error("Shared-state read lost its original native owner");
		};
		return {
			assertCurrent,
			observe() {
				assertCurrent();
				observeOpenClawDatabaseMaintenanceResource(t.db);
			},
			release: () => r.release()
		};
	};
	return {
		retain: (e) => retain(e, admit(e.path)),
		retainForIndependentRead(e, t, n) {
			const { database: r, scope: i } = findReadDatabase(e, t, n);
			return r ? retainReadReference(r, i) : void 0;
		},
		borrowForRead(e, t, n) {
			const { database: r, scope: i } = findReadDatabase(e, t, n);
			if (!r) return;
			if (r.db.isTransaction) throw new Error("Asynchronous shared-state reads cannot run inside a native transaction");
			return {
				database: r,
				...retainReadReference(r, i)
			};
		}
	};
}
function assertStateDatabaseBorrowersReleased(e, t) {
	if (e?.references.size) throw new Error(`OpenClaw state database still has active native borrowers: ${t}`);
}
//#endregion
//#region src/state/openclaw-state-db-cache.admission.ts
/** Keep cached reads and terminal failures with their exact native owner. */
function createStateDatabaseCacheAdmission(e) {
	return {
		closeTerminalFailure(t, n) {
			markOpenClawStateDatabaseFailure(n, t);
			revokeSqliteDatabaseAdmissionsForPath(t);
			e.invalidate(t);
			const r = e.cachedDatabases.get(t);
			const i = [];
			try {
				if (r) e.evict(r);
			} catch (e) {
				i.push(e);
			}
			try {
				e.notifyTerminalFailure(t, n);
			} catch (e) {
				i.push(e);
			}
			throwSqliteLifecycleErrors(i, "Terminal shared-state failure cleanup failed");
		},
		read(t, n) {
			if (!t.db.isOpen) return n(t);
			let r = false;
			try {
				return runSqliteReadOperationSync(t.db, () => {
					r = true;
					return n(t);
				});
			} catch (n) {
				if (r) throw n;
				const i = n instanceof Error ? n : new Error(String(n));
				if (isSqliteCorruptionError(i)) {
					e.evict(t);
					return;
				}
				throw i;
			}
		}
	};
}
//#endregion
//#region src/infra/database-engine/admission-scope.ts
const processRole = resolveGlobalSingleton(Symbol.for("openclaw.databaseProcessRole"), () => ({}));
/** Undefined until an entry point installs one; embedders keep the shared defaults. */
function getDatabaseProcessRole() {
	return processRole.role;
}
let admissionDepth = 0;
function assertEngineStoreExecutionAllowed() {
	if (threadId === 0 && admissionDepth === 0 && processRole.role !== "cli-oneshot") throw new Error("PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread");
}
//#endregion
//#region src/infra/sqlite-handle-lifecycle.ts
/** Idle native connections share one retention window across SQLite owners. */
const SQLITE_IDLE_HANDLE_TTL_MS = 18e5;
//#endregion
//#region src/state/openclaw-state-db-cache.idle.ts
const log = createSubsystemLogger("state/db");
/** Schedule native retirement against the canonical cache's handles and borrow pins. */
function createStateDatabaseIdleRetirement({ cachedDatabases: e, retainedDatabaseHandles: t, idleTimers: n, idleReferences: r, borrowers: i }, a) {
	const touch = (o) => {
		if (!(e.get(o.path) === o && o.db.isOpen) && t.get(o.db) !== o) return;
		const s = n.get(o.db);
		if (s) {
			s.refresh();
			return;
		}
		const c = runInDetachedAsyncContext(() => setTimeout(() => {
			n.delete(o.db);
			try {
				if (o.db.isOpen && o.db.isTransaction) touch(o);
				else if (!i.get(o.db)?.references.size && !r.get(o.db)?.size) a(o, false, {
					busyTimeoutMs: 0,
					checkpointMode: "PASSIVE"
				});
			} catch (e) {
				log.warn("Idle shared-state database cleanup failed", {
					path: o.path,
					error: e
				});
				touch(o);
			}
		}, SQLITE_IDLE_HANDLE_TTL_MS));
		c.unref();
		n.set(o.db, c);
	};
	return {
		touch,
		/** Retained consumers postpone idle eviction without blocking explicit retirement. */
		retain(t) {
			if (e.get(t.path) !== t || !t.db.isOpen || i.get(t.db)?.retiring) throw new Error("OpenClaw state database idle retention requires its current canonical handle");
			const n = r.get(t.db) ?? /* @__PURE__ */ new Set();
			const a = {};
			n.add(a);
			r.set(t.db, n);
			return () => {
				if (!n.delete(a)) return;
				if (e.get(t.path) === t && t.db.isOpen) touch(t);
			};
		}
	};
}
//#endregion
//#region src/infra/gateway-service-installation-context.ts
const installations = resolveGlobalSingleton(Symbol.for("openclaw.gatewayServiceInstallation"), () => new AsyncLocalStorage());
function getGatewayServiceInstallation() {
	return installations.getStore()?.installation;
}
//#endregion
//#region src/infra/gateway-supervision.ts
const GATEWAY_SUPERVISOR_MODE_ENV = "OPENCLAW_SUPERVISOR_MODE";
function isGatewayExternallySupervised(e = process.env) {
	return e[GATEWAY_SUPERVISOR_MODE_ENV]?.trim().toLowerCase() === "external";
}
//#endregion
//#region src/infra/database-engine/json-values.ts
/** SQLite JSON paths at these boundaries name object keys, including nested keys. */
function objectPath(e) {
	return sql`string_to_array(substr(${e}, 3), '.')`;
}
function jsonPathValue(e, t, n, r = "text") {
	if (!isPostgresSqlConnection(e)) return sql`json_extract(${t}, ${n})`;
	const i = sql`(${t}::jsonb ${sql.raw(r === "json" ? "#>" : "#>>")} ${objectPath(n)})`;
	return sql`${i}${sql.raw(r === "number" ? "::double precision" : r === "json" ? "::text" : "")}`;
}
function jsonValid(e, t) {
	return isPostgresSqlConnection(e) ? sql`pg_input_is_valid(${t}, 'json')` : sql`json_valid(${t})`;
}
function jsonPickObject(e, t, n) {
	return isPostgresSqlConnection(e) ? sql`(SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)::text
        FROM jsonb_each(CASE WHEN jsonb_typeof(${t}::jsonb) = 'object' THEN ${t}::jsonb ELSE '{}'::jsonb END)
        WHERE key IN (${sql.join(n)}))` : sql`(SELECT json_group_object(key, CASE type
    WHEN 'object' THEN json(value) WHEN 'array' THEN json(value)
    WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
    ELSE value END) FROM json_each(${t}) WHERE key IN (${sql.join(n)}))`;
}
//#endregion
//#region src/state/openclaw-state-db-schema-policy.ts
const schemaPolicies = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseSchemaPolicies"), () => ({
	scopes: new AsyncLocalStorage(),
	existingDatabases: /* @__PURE__ */ new WeakMap()
}));
function canonicalPath(e) {
	const t = resolveDatabasePath({ path: e });
	try {
		return normalizeDatabasePath(realpathSync.native(t));
	} catch (e) {
		if (hasErrnoCode(e, "ENOENT")) return t;
		throw e;
	}
}
function assertSchemaScopeActive(e) {
	if (e && !e.active) throw new Error("Existing shared-state schema admission has ended.");
}
function getExistingOpenClawStateSchemaPath() {
	const e = schemaPolicies.scopes.getStore();
	assertSchemaScopeActive(e);
	return e?.path;
}
/** Admit this source once; retained reads only need the original scope's live lifetime. */
function captureOpenClawStateSchemaReadAdmission(e) {
	const t = schemaPolicies.scopes.getStore();
	if (!t) return;
	isExistingOpenClawStateSchema(e);
	return {
		path: t.path,
		assertCurrent: () => assertSchemaScopeActive(t)
	};
}
/** Check supplied and cached handles before exposing them to another admission policy. */
function isExistingOpenClawStateSchema(e, t) {
	const n = getExistingOpenClawStateSchemaPath();
	const r = schemaPolicies.scopes.getStore();
	const i = t && schemaPolicies.existingDatabases.get(t);
	if (!r && !i) return false;
	const a = resolveDatabasePath({ path: e });
	const o = n !== void 0 && (n === a || r?.canonicalPath === a || r?.canonicalPath === canonicalPath(a));
	if (n && !o) throw new Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);
	if (i && (!o || i !== r?.canonicalPath)) throw new Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);
	return o;
}
function recordExistingOpenClawStateSchemaDatabase(e, t) {
	const n = schemaPolicies.scopes.getStore();
	if (!n || !isExistingOpenClawStateSchema(t, e)) throw new Error("Existing shared-state schema admission requires its active path scope.");
	schemaPolicies.existingDatabases.set(e, n.canonicalPath);
}
/** The cache owns the handle inventory, including owners retained after failed cleanup. */
function assertExistingOpenClawStateSchemaCacheAdmission(e, t) {
	const n = getExistingOpenClawStateSchemaPath();
	const r = schemaPolicies.scopes.getStore();
	const i = r ? resolveDatabasePath({ path: e }) : void 0;
	let a = r && (n === i || r.canonicalPath === i) ? r.canonicalPath : void 0;
	for (const n of [t.cachedDatabases, t.retainedDatabaseHandles]) for (const { db: t } of n.values()) {
		const n = schemaPolicies.existingDatabases.get(t);
		if (n && t.isOpen) {
			a ??= canonicalPath(e);
			if (n === a) isExistingOpenClawStateSchema(e, t);
		}
	}
}
//#endregion
//#region src/infra/sqlite-worker-state-context.ts
function captureSqliteWorkerStateContext(e) {
	return {
		databaseEngineSelection: e.databaseEngineSelection ?? getDatabaseEngineSelection(),
		environment: { ...e.environment },
		initializationCronDefaultStoreKey: e.initializationCronDefaultStoreKey,
		...e.initializationEnvironment ? { initializationEnvironment: { ...e.initializationEnvironment } } : {},
		...e.initializationAgentPaths ? { initializationAgentPaths: [...e.initializationAgentPaths] } : {},
		existingSchemaPath: e.existingSchemaPath,
		gatewayServiceInstallation: e.gatewayServiceInstallation,
		...e.stateIntegrity ? { stateIntegrity: e.stateIntegrity } : {},
		artifactPreservingReads: e.artifactPreservingReads,
		...e.scheduledMaintenanceSuspension ? { scheduledMaintenanceSuspension: e.scheduledMaintenanceSuspension } : {}
	};
}
/** Charge captured initialization facts together with the request bytes retained by admission. */
function sqliteWorkerRequestBytes(e, t, n) {
	const r = t?.initializationAgentPaths?.reduce((e, t) => e + Buffer.byteLength(t, "utf8"), 0) ?? 0;
	return [t?.environment, t?.initializationEnvironment].reduce((e, t) => Object.entries(t ?? {}).reduce((e, [t, n]) => e + Buffer.byteLength(t, "utf8") + Buffer.byteLength(n ?? "", "utf8"), e), e.byteLength + Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection) ?? "", "utf8") + Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation) ?? "", "utf8") + (n?.byteLength ?? 0) + r + Buffer.byteLength(t?.initializationCronDefaultStoreKey ?? "", "utf8") + (t?.scheduledMaintenanceSuspension?.byteLength ?? 0));
}
const stateContexts = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerStateContext"), () => new AsyncLocalStorage());
/** Keep the actor's live maintenance holds after the opening command returns. */
function captureSqliteWorkerWalMaintenanceSuspension() {
	const e = stateContexts.getStore()?.scheduledMaintenanceSuspension;
	if (!e) return;
	const t = new Int32Array(e);
	return () => Atomics.load(t, 0) > 0;
}
/** Original selector is an initialization fact, never a path to open or write authority. */
function getSqliteWorkerCronDefaultStoreKey() {
	return stateContexts.getStore()?.initializationCronDefaultStoreKey;
}
/** Only cold writable opens need this factory's prior-existence constraint. */
function getSqliteWorkerExistingDatabaseIdentity(e) {
	const t = stateContexts.getStore()?.existingDatabase;
	return t?.databasePath === e ? t.identity : void 0;
}
function getSqliteWorkerStateIntegrityAdmission() {
	return stateContexts.getStore()?.stateIntegrity;
}
//#endregion
//#region src/state/openclaw-state-db-cron-identity-migration.ts
const CRON_DEFAULT_STORE_KEY_STATE_KEY = "cron.defaultStoreKey";
const CRON_DEFAULT_STORE_IDENTITY_SCHEMA_VERSION = 34;
/** Capture the old selector before moving state; this value is never a path to open. */
function resolveLegacyCronDefaultStoreKey(e) {
	return path.resolve(resolveConfigDir(e), "cron", "jobs.json");
}
function resolveCronIdentityMigrationDefaultStoreKey(e) {
	return getSqliteWorkerCronDefaultStoreKey() ?? resolveLegacyCronDefaultStoreKey(e);
}
function readBindingRow(e, t) {
	if (!(t?.has("config_machine_state") ?? tableExists(e, "config_machine_state"))) return;
	return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("config_machine_state").select("value_json").where("state_key", "=", CRON_DEFAULT_STORE_KEY_STATE_KEY));
}
/** Only a matching original selector or an empty inventory proves a legacy default. */
function resolveUnboundCronDefaultStoreKey(e, t) {
	return e.length === 0 || e.some((e) => e.storeKey === t) ? t : void 0;
}
const keyedTables = [
	["cron_jobs", "jobs"],
	["cron_job_scratch", "scratch"],
	["cron_run_receipts", "receipts"]
];
const quarantinePrefix = "cron.quarantine:";
const proactivePrefix = "automation-default:";
/** Offline migration/Doctor inventory; ordinary ready selectors only read the binding. */
function readCronStorePartitionInventoryInDatabase(e, t) {
	const n = /* @__PURE__ */ new Map();
	const add = (e, t, r) => {
		if (typeof e !== "string" || e.length === 0) return;
		let i = n.get(e);
		if (!i) {
			i = {
				storeKey: e,
				jobs: 0,
				scratch: 0,
				receipts: 0,
				history: 0,
				quarantine: 0,
				proactiveReceipts: 0
			};
			n.set(e, i);
		}
		i[t] += r;
	};
	for (const [n, r] of keyedTables) if (t?.has(n) ?? tableExists(e, n)) {
		const t = getNodeSqliteKysely(e).selectFrom(n).select("store_key").select((e) => e.fn.countAll().as("count")).groupBy("store_key");
		for (const n of executeSqliteQuerySync(e, t).rows) add(n.store_key, r, Number(n.count));
	}
	if (t?.has("cron_run_logs") ?? tableExists(e, "cron_run_logs")) {
		const t = getNodeSqliteKysely(e).selectFrom("cron_run_logs").select("store_key").select((e) => e.fn.countAll().as("count")).groupBy("store_key");
		for (const n of executeSqliteQuerySync(e, t).rows) add(n.store_key, "history", Number(n.count));
	}
	if (t?.has("task_runs") ?? tableExists(e, "task_runs")) {
		const t = getNodeSqliteKysely(e).selectFrom("task_runs").select((t) => [sql`CASE WHEN ${jsonValid(e, t.ref("detail_json"))}
          THEN ${jsonPickObject(e, t.ref("detail_json"), ["storeKey"])} END`.as("detail_json")]).where("runtime", "=", "cron");
		for (const n of executeSqliteQuerySync(e, t).rows) {
			if (typeof n.detail_json !== "string") continue;
			try {
				const e = JSON.parse(n.detail_json);
				if (isRecord(e)) add(e.storeKey, "history", 1);
			} catch {}
		}
	}
	if (t?.has("diagnostic_events") ?? tableExists(e, "diagnostic_events")) {
		const t = getNodeSqliteKysely(e).selectFrom("diagnostic_events").select("scope").select((e) => e.fn.countAll().as("count")).where("scope", "like", `${quarantinePrefix}%`).groupBy("scope");
		for (const n of executeSqliteQuerySync(e, t).rows) if (typeof n.scope === "string") add(n.scope.slice(16), "quarantine", Number(n.count));
	}
	if (t?.has("config_machine_state") ?? tableExists(e, "config_machine_state")) {
		const t = getNodeSqliteKysely(e).selectFrom("config_machine_state").select("state_key").where("state_key", "like", `${proactivePrefix}%`);
		for (const n of executeSqliteQuerySync(e, t).rows) add(n.state_key.slice(19, n.state_key.lastIndexOf(":")), "proactiveReceipts", 1);
	}
	return [...n.values()].toSorted((e, t) => e.storeKey < t.storeKey ? -1 : e.storeKey > t.storeKey ? 1 : 0);
}
const stateCronIdentityMigration = {
	version: 34,
	tables: ["config_machine_state"],
	columns: [],
	migrate: (e, t, n) => migrateCronDefaultStoreIdentity(e, {
		previousVersion: t,
		legacyDefaultStoreKey: n.legacyCronDefaultStoreKey ?? resolveCronIdentityMigrationDefaultStoreKey(n.env)
	}),
	applied: "Introduced durable default cron partition selection (v34)"
};
/** Runs within the state owner's existing schema transaction, on both engines. */
function migrateCronDefaultStoreIdentity(e, t) {
	if (t.previousVersion >= 34 || readBindingRow(e, t.sourceTables)) return false;
	let n = t.fresh ? t.legacyDefaultStoreKey : void 0;
	if (!t.fresh) {
		if (keyedTables.some(([n]) => (t.sourceTables?.has(n) ?? tableExists(e, n)) && executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom(n).select("store_key").where("store_key", "=", t.legacyDefaultStoreKey).limit(1)))) n = t.legacyDefaultStoreKey;
		else {
			const r = readCronStorePartitionInventoryInDatabase(e, t.sourceTables);
			n = resolveUnboundCronDefaultStoreKey(r, t.legacyDefaultStoreKey) ?? (r.length === 1 ? r[0]?.storeKey : void 0);
		}
	}
	if (n === void 0) return false;
	executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("config_machine_state").values({
		state_key: CRON_DEFAULT_STORE_KEY_STATE_KEY,
		value_json: JSON.stringify(n),
		updated_at_ms: t.nowMs ?? Date.now()
	}));
	return true;
}
//#endregion
//#region src/state/openclaw-state-worker-context.capture.ts
/** Capture read authority without constructing a worker environment. */
function captureOpenClawStateReadContextWithAdmission(e, t, n) {
	const r = captureOpenClawStateSchemaReadAdmission(e);
	const i = t(e);
	const a = getGatewayServiceInstallation();
	const o = i.captureIntegrity?.();
	const s = i.assertCurrent;
	let c = i;
	let runInCapturedSchemaScope;
	if (r) {
		const e = AsyncLocalStorage.snapshot();
		c = {
			databasePath: i.databasePath,
			coordinationKey: i.coordinationKey,
			get identity() {
				return i.identity;
			},
			captureIntegrity: i.captureIntegrity,
			assertCurrent() {
				i.assertCurrent();
				r.assertCurrent();
			}
		};
		runInCapturedSchemaScope = (t) => e(() => {
			c.assertCurrent();
			return t();
		});
	}
	return {
		databaseEngineSelection: getDatabaseEngineSelection(),
		maintenanceScope: getOpenClawDatabaseMaintenanceScope(),
		admission: c,
		assertPublicationCurrent: s,
		existingSchemaPath: r?.path,
		gatewayServiceInstallation: a && n(a.databasePath)?.key === i.identity.key ? a : void 0,
		stateIntegrity: o,
		runInCapturedSchemaScope,
		artifactPreservingReads: isArtifactPreservingStateRead("agent", e) || void 0
	};
}
/** Read-only workers need resolved runtime facts, not the initialization environment. */
function captureOpenClawStateReadWorkerContextWithAdmission(e, t, n) {
	const r = e.env ?? process.env;
	const i = process.platform === "win32" ? cloneEnvWithPlatformSemantics(r) : r;
	const a = {
		OPENCLAW_STATE_DIR: resolveStateDir(i),
		...isGatewayExternallySupervised(i) ? { OPENCLAW_SUPERVISOR_MODE: "external" } : {}
	};
	return {
		...captureOpenClawStateReadContextWithAdmission(e.path ?? resolveOpenClawStateSqlitePath(a), t, n),
		environment: a
	};
}
/** Capture host facts before asynchronous work, without opening SQLite. */
function captureOpenClawStateWorkerContextWithAdmission(e, t, n) {
	const r = captureOpenClawStateReadWorkerContextWithAdmission(e, t, n);
	return {
		...r,
		initializationCronDefaultStoreKey: resolveLegacyCronDefaultStoreKey(e.env ?? process.env),
		initializationEnvironment: mergeProcessEnv([
			e.env ?? process.env,
			{
				OPENCLAW_STATE_DIR: void 0,
				OPENCLAW_SUPERVISOR_MODE: void 0
			},
			r.environment
		]),
		...e.initializationAgentPaths ? { initializationAgentPaths: e.initializationAgentPaths.map((e) => path.resolve(e)) } : {}
	};
}
//#endregion
//#region src/state/openclaw-state-db-cache.wal.ts
/** Bind periodic maintenance and its observations to the cache's exact native owner. */
function createStateDatabaseWalOwner({ cachedDatabases: e, retainedDatabaseHandles: t, databaseIdentities: n, asyncResources: r }, i, a) {
	return {
		ownRetirement(e, t) {
			const n = {
				admission: { identity: a(e) },
				close: t
			};
			const i = r.register(n);
			getOpenClawDatabaseMaintenanceResourceScope(e.db)?.own(n, "shared-references", () => n.close());
			return i;
		},
		async stop(r, i) {
			const a = /* @__PURE__ */ new Set([...t.values(), ...e.values()]);
			await Promise.all([...a].filter((e) => r === void 0 || e.path === r || i !== void 0 && n.get(e.db)?.key === i.key).flatMap(({ walMaintenance: e }) => e ? [e.stop()] : []));
		},
		register(t, n, a, o) {
			if (!isMainThread || isPostgresSqlConnection(t.db)) return;
			const s = captureOpenClawStateWorkerContextWithAdmission({
				path: t.path,
				env: o
			}, () => a, r.knownIdentity);
			const c = new AbortController();
			let l;
			const cancel = () => {
				c.abort();
				if (!l) {
					d();
					return;
				}
				return l.then(() => void 0, () => void 0);
			};
			const u = {
				admission: { identity: n },
				async close() {
					cancel();
					await t.walMaintenance.stop();
					d();
				}
			};
			const d = r.register(u);
			const run = async (r) => {
				const a = getOpenClawDatabaseMaintenanceResourceScope(t.db);
				const o = {
					...s,
					maintenanceScope: a
				};
				const assertCurrent = () => {
					c.signal.throwIfAborted();
					o.admission.assertCurrent();
					a?.assertAdmission();
					if (getOpenClawDatabaseMaintenanceResourceScope(t.db) !== a || e.get(t.path) !== t || !t.db.isOpen) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance owner changed");
				};
				let l;
				let u = false;
				try {
					assertCurrent();
					l = i(t);
					const { runOpenClawStateWorkerOperation: e } = await import("./openclaw-state-worker-store-Da4Nk7Zx.mjs");
					assertCurrent();
					return await e(o, (e) => e.execute({
						type: "database.walMaintenance",
						input: r
					}, { signal: c.signal }), {
						existingOnly: true,
						assertCurrent,
						createAdmission: () => ({
							nativeLocations: [t.path, n.canonicalPath],
							databaseIdentity: {
								databasePath: t.path,
								key: n.key,
								birthtime: n.birthtime
							},
							admission: createSqliteWorkerOperationAdmission((e, t) => {
								assertCurrent();
								if (!t()) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance authority expired");
								u = true;
							})
						})
					});
				} catch (e) {
					if (!u && (isStateDatabaseReadAdmissionInvalidatedError(e) || c.signal.aborted && isAbortError(e))) return;
					throw e;
				} finally {
					l?.();
				}
			};
			registerSqliteWalWorkerMaintenance(t.db, (e) => {
				if (c.signal.aborted) return Promise.resolve(void 0);
				const t = run(e);
				l = t;
				return t.finally(() => {
					if (l === t) l = void 0;
					if (c.signal.aborted) d();
				});
			}, cancel);
		},
		/** Report the last observation without opening or querying SQLite. */
		readHealth() {
			const t = e.get(path.resolve(resolveOpenClawStateSqlitePath()));
			return t?.db.isOpen ? t.walMaintenance.health : void 0;
		}
	};
}
//#endregion
//#region src/state/openclaw-state-db-handle.ts
const identities = resolveGlobalSingleton(Symbol.for("openclaw.stateNativeIdentities"), () => /* @__PURE__ */ new WeakMap());
/** Physical identity admitted by the native opener, never a later pathname observation. */
function readTrackedStateDatabaseIdentity(e) {
	return identities.get(sqlPublicationAnchor(e));
}
function openTrackedStateDatabase(e, t) {
	const n = openTrackedStateDatabaseResult(e, t);
	if (n.status === "unavailable") throw n.error;
	return n.database;
}
/** Native open failure is an ordinary read failure; admitted handles retain their own cleanup. */
function openTrackedStateDatabaseResult(e, t) {
	assertStateDatabaseAccessAllowed(e);
	try {
		if (t?.expectedIdentity !== void 0) assertExistingDatabaseIdentity(e, t.expectedIdentity);
		const n = t?.existingOnly || t?.expectedIdentity !== void 0 ? resolveExistingSqliteFileUri(e) : e;
		const r = t?.readOnly ? {
			readOnly: true,
			timeout: t.timeout
		} : { enableForeignKeyConstraints: t?.enableForeignKeyConstraints };
		const i = readDatabasePathIdentitySync(e);
		const a = withSqliteNativeOpen(() => openNodeSqliteDatabase(n, r));
		try {
			assertStateDatabaseAccessAllowed(e);
			if (i.key.startsWith("file:")) assertExistingDatabaseIdentity(e, i.key, i.birthtime);
			const t = i.key.startsWith("file:") ? i : readDatabasePathIdentitySync(e);
			if (t.key.startsWith("file:")) {
				identities.set(a, t);
				const e = registerNodeSqliteDisposeCallback(a, () => {
					identities.delete(a);
					e();
				});
			}
		} catch (e) {
			a.close();
			throw e;
		}
		return {
			status: "available",
			database: a
		};
	} catch (e) {
		return {
			status: "unavailable",
			error: e
		};
	}
}
function closeTrackedStateDatabase(e) {
	if (e.isOpen) e.close();
}
/** Finish all native close stages even when a previous stage failed. */
function closeStateDatabaseHandle(e, t) {
	try {
		var n = _usingCtx();
		const r = [];
		if (isPostgresSqlConnection(e.db)) {
			for (const t of [e.db, e.db.anchor]) {
				if (t === e.db.anchor && e.db.isOpen) break;
				try {
					if (t.isOpen) t.close();
				} catch (e) {
					r.push(e);
				}
			}
			let t = e.db.isOpen || e.db.anchor.isOpen;
			if (!t) try {
				e.afterClose?.();
			} catch (e) {
				r.push(e);
				t = true;
			}
			return {
				errors: r,
				cleanupPending: t
			};
		}
		const i = n.u(prepareSqliteDatabaseCleanClose(e.db));
		const a = isSqliteWalWorkerMaintained(e.db);
		const o = e.walMaintenance?.health?.state === "error";
		let s = false;
		try {
			if (e.db.isOpen && !a) setSqliteBusyTimeout(e.db, 0);
			s = e.walMaintenance?.close(t) === true && t?.checkpointMode !== "PASSIVE";
		} catch (e) {
			r.push(e);
		}
		try {
			clearNodeSqliteKyselyCacheForDatabase(e.db);
		} catch (e) {
			r.push(e);
		}
		try {
			closeTrackedStateDatabase(e.db);
		} catch (e) {
			r.push(e);
		}
		let c = false;
		if (!e.db.isOpen) try {
			e.afterClose?.();
		} catch (e) {
			r.push(e);
			c = true;
		}
		if (r.length === 0 && !c && t?.checkpointMode !== "PASSIVE" && (s || a && !o)) i.publish();
		return {
			errors: r,
			cleanupPending: c
		};
	} catch (e) {
		n.e = e;
	} finally {
		n.d();
	}
}
//#endregion
//#region src/infra/sqlite-table-integrity-cache.ts
const maintenanceChecks = /* @__PURE__ */ new WeakMap();
/** Passing scoped checks belong to the offline owner and the existing physical write receipt. */
function getMaintenanceSqliteTableChecks(e) {
	const t = getOpenClawDatabaseMaintenanceScope();
	if (!t?.ownsSchemaMaintenance || t.sqliteIntegrityCheck !== "quick") return;
	const n = readSqliteNativeMutationRevision(e);
	const r = e.location();
	if (n === void 0 || !r || readSqliteDatabaseWriteRevision(e) === void 0) return;
	const i = readSqliteDatabaseWriteTokenForPath(r);
	if (i === void 0) return;
	let a = maintenanceChecks.get(t);
	if (!a) {
		a = {
			committed: /* @__PURE__ */ new Map(),
			transactions: /* @__PURE__ */ new WeakMap()
		};
		maintenanceChecks.set(t, a);
	}
	if (!e.isTransaction) {
		let e = a.committed.get(i);
		if (!e) {
			e = /* @__PURE__ */ new Set();
			a.committed.set(i, e);
		}
		return e;
	}
	const o = `${i}:${n}`;
	let s = a.transactions.get(e);
	if (!s) {
		const n = /* @__PURE__ */ new Set();
		s = {
			token: o,
			tables: n
		};
		a.transactions.set(e, s);
		t.own(s, "shared-resources", registerSqliteSchemaMutationListener(e, () => n.clear()));
	} else if (s.token !== o) {
		s.token = o;
		s.tables.clear();
	}
	return s.tables;
}
//#endregion
//#region src/infra/sqlite-integrity.ts
const MAX_REPORTED_FOREIGN_KEY_VIOLATIONS = 5;
var SqliteRepairableForeignKeyError = class extends Error {
	constructor(e, t) {
		super(`SQLite foreign_key_check failed for ${e}: repairable task_delivery_state.task_id references task_runs.task_id cascade-owned orphans (${t} rows). Run openclaw doctor --fix to migrate this legacy state before retrying.`);
		this.name = "SqliteRepairableForeignKeyError";
		this.repair = {
			kind: "task-delivery-orphans",
			relation: "task_delivery_state.task_id",
			parentTable: "task_runs",
			orphanCount: t
		};
	}
};
/** Return whether a named integrity failure proves persistent database damage. */
function isTerminalSqliteIntegrityError(e) {
	if (e.name !== "SqliteIntegrityError") return false;
	if (!e.cause) return true;
	return isSqliteCorruptionError(e.cause);
}
/** Check structure and foreign keys, plus all indexes or the migration's selected tables. */
function assertSqliteIntegrity(e, t, n = {}) {
	const r = n.check === "quick" ? "quick_check" : "integrity_check";
	let i = false;
	try {
		runSqliteCheck(e, t, r, void 0, n.allFindings || n.ftsSchemas !== void 0);
	} catch (t) {
		if (!n.ftsSchemas || !(t instanceof SqliteIntegrityError) || !t.findings || !classifySqliteFtsIntegrityFindings(e, t.findings, n.ftsSchemas)) throw t;
		i = true;
	}
	if (r === "quick_check" && n.tables?.length) {
		const r = new Set(readSqliteSchemaObjects(e).filter((e) => e.type === "table").map((e) => e.name));
		for (const i of n.tables) if (r.has(i)) assertSqliteTableIntegrity(e, t, i);
	}
	runSqliteForeignKeyCheck(e, t);
	if (r === "integrity_check" && !i) recordSqliteDatabaseIntegrity(e);
	return { integrityCheck: "ok" };
}
/** Only exact, owned FTS definitions may treat their inverted index as derived data. */
function classifySqliteFtsIntegrityFindings(e, t, n) {
	const r = /* @__PURE__ */ new Set();
	for (const e of t) {
		if (e === "ok") continue;
		const t = typeof e === "string" ? /^malformed inverted index for FTS5 table main\.([A-Za-z_][A-Za-z0-9_]*)$/u.exec(e) : null;
		if (!t?.[1]) return;
		r.add(t[1]);
	}
	if (r.size === 0) return;
	const i = /* @__PURE__ */ new Map();
	for (const e of n) for (const t of e.matchAll(/CREATE VIRTUAL TABLE (?:IF NOT EXISTS )?([A-Za-z_][A-Za-z0-9_]*) USING fts5\s*\(/gu)) {
		const n = t[1];
		const r = findSqlClosingParenthesis(e, t.index + t[0].length - 1);
		const a = i.get(n) ?? /* @__PURE__ */ new Set();
		a.add(normalizeSchemaSql(e.slice(t.index, r + 1)));
		i.set(n, a);
	}
	const a = readSqliteSchemaObjects(e).filter((e) => e.type === "table");
	for (const e of r) {
		const t = a.find((t) => t.name === e)?.sql;
		if (typeof t !== "string" || !i.get(e)?.has(normalizeSchemaSql(t))) return;
	}
	return [...r].toSorted();
}
/** Require table and associated index consistency before trusting indexed reads. */
function assertSqliteTableIntegrity(e, t, n) {
	const r = getMaintenanceSqliteTableChecks(e);
	if (r?.has(n)) return;
	runSqliteCheck(e, `${t} table ${n}`, "integrity_check", n);
	r?.add(n);
}
function readSqliteCheckFindings(e, t, n, r = false) {
	const i = n ? `('${n.replaceAll("'", "''")}')` : r ? "(2147483647)" : "";
	return e.prepare(`PRAGMA ${t}${i};`).all().map((e) => e[t] ?? Object.values(e)[0]);
}
function runSqliteCheck(e, t, n, r, i = false) {
	let a;
	try {
		a = readSqliteCheckFindings(e, n, r, i);
	} catch (e) {
		const r = e instanceof Error ? e.message : String(e);
		throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${r}`, e);
	}
	if (a.length === 1 && a[0] === "ok") return "ok";
	const o = a.map((e) => String(e)).join("; ") || "no result";
	throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${o}`, void 0, a);
}
function runSqliteForeignKeyCheck(e, t) {
	let n = 0;
	let r = true;
	let i;
	const a = [];
	try {
		const t = e.prepare("PRAGMA foreign_key_check;");
		t.setReadBigInts(true);
		for (const o of t.iterate()) {
			n += 1;
			retainSortedForeignKeyViolation(a, o);
			if (r) {
				if (o.table === "task_delivery_state" && o.parent === "task_runs") {
					i ??= readTaskDeliveryCascadeForeignKeyId(e);
					r = o.fkid === i;
				} else r = false;
			}
		}
	} catch (e) {
		const n = e instanceof Error ? e.message : String(e);
		throw new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${n}`, e);
	}
	if (a.length === 0) return;
	if (r) throw new SqliteRepairableForeignKeyError(t, n);
	const o = a.map(formatSqliteForeignKeyViolation);
	if (n > MAX_REPORTED_FOREIGN_KEY_VIOLATIONS) o.push("additional violations omitted");
	throw new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${o.join("; ")}`);
}
function readTaskDeliveryCascadeForeignKeyId(e) {
	const t = e.prepare("PRAGMA foreign_key_list(task_delivery_state);");
	t.setReadBigInts(true);
	const n = t.all();
	const r = n.find((e) => e.table === "task_runs" && e.from === "task_id" && e.to === "task_id" && e.on_delete === "CASCADE");
	return r && typeof r.id === "bigint" && n.filter((e) => e.id === r.id).length === 1 ? r.id : void 0;
}
var SqliteIntegrityError = class extends Error {
	constructor(e, t, n) {
		super(t === void 0 ? `${e}. Stop the Gateway, run "openclaw doctor --fix" to inspect and repair this database, and restart. Only if Doctor still cannot repair the offline database, preserve the database and WAL and restore a verified backup.` : e, t === void 0 ? void 0 : { cause: t });
		this.findings = n;
		this.name = "SqliteIntegrityError";
	}
};
function retainSortedForeignKeyViolation(e, t) {
	e.push(t);
	e.sort(compareSqliteForeignKeyViolations);
	if (e.length > MAX_REPORTED_FOREIGN_KEY_VIOLATIONS) e.pop();
}
function compareSqliteForeignKeyViolations(e, t) {
	const n = Buffer.compare(Buffer.from(e.table), Buffer.from(t.table));
	if (n !== 0) return n;
	if (e.rowid === null || t.rowid === null) {
		if (e.rowid !== t.rowid) return e.rowid === null ? -1 : 1;
	} else if (e.rowid !== t.rowid) return e.rowid < t.rowid ? -1 : 1;
	const r = Buffer.compare(Buffer.from(e.parent), Buffer.from(t.parent));
	if (r !== 0) return r;
	if (e.fkid === t.fkid) return 0;
	return e.fkid < t.fkid ? -1 : 1;
}
function formatSqliteForeignKeyViolation(e) {
	const t = e.rowid === null ? "row without rowid" : `row ${e.rowid.toString()}`;
	return `${e.table} ${t} references ${e.parent} (foreign key ${e.fkid.toString()})`;
}
//#endregion
//#region src/state/openclaw-state-db-integrity-admission.ts
const bindings = resolveGlobalSingleton(Symbol.for("openclaw.stateIntegrityBindings"), () => /* @__PURE__ */ new WeakMap());
const integrityKey = {
	name: "state.integrity",
	lifetime: "process",
	read: (e) => e === true ? true : void 0
};
function hasStateDatabaseIntegrityAdmission(e) {
	return Boolean(getStateRuntimeSchemaAdmission(e) || getSqliteDatabaseAdmission(e, integrityKey));
}
/** Ordinary opens share physical-file proof; Doctor calls the uncached integrity owner. */
function assertStateDatabaseIntegrityOnce(e, t) {
	if (!hasStateDatabaseIntegrityAdmission(e)) {
		assertSqliteIntegrity(e, t);
		publishSqliteDatabaseAdmission(e, integrityKey, true);
	}
}
function invalidate(e) {
	let t = Atomics.load(e, 0);
	while (t >= 0n) {
		const n = Atomics.compareExchange(e, 0, t, t + 1n);
		if (n === t) return;
		t = n;
	}
}
/** Corruption observed in an isolate revokes the exact host proof borrowed by its native handle. */
function invalidateOpenClawStateRuntimeIntegrity(e) {
	revokeSqliteDatabaseAdmissions(e);
	const t = bindings.get(e);
	if (t) {
		invalidate(new BigInt64Array(t.revision));
		invalidate(new BigInt64Array(t.lifetimeRevision));
	}
}
/** Native bindings revoke borrowed proof; the host generation alone owns its lifetime. */
function bind(e, t) {
	if (bindings.get(e)?.revision === t.revision) return;
	bindings.get(e)?.release();
	const n = new BigInt64Array(t.revision);
	const r = registerSqliteSchemaMutationListener(e, () => invalidate(n));
	const release = () => {
		r();
		i();
	};
	const i = registerNodeSqliteDisposeCallback(e, (e) => {
		if (e === "replace") {
			invalidate(n);
			invalidate(new BigInt64Array(t.lifetime.revision));
		}
		release();
	});
	bindings.set(e, {
		revision: t.revision,
		lifetimeRevision: t.lifetime.revision,
		release
	});
}
/** Reuse only completed integrity proof; shape and mutable metadata retain their admission owners. */
function assertOpenClawStateRuntimeIntegrity(e, t, n, r, i = "verify") {
	const a = r && readTrackedStateDatabaseIdentity(e);
	if (!r || !a || !a.key.startsWith("file:") || a.key !== r.identity.key || a.birthtime !== r.identity.birthtime) {
		if (i === "require-proof") throw new Error("Shared-state reader requires current worker integrity proof");
		assertStateDatabaseIntegrityOnce(e, t);
		return;
	}
	bind(e, r);
	const o = new BigInt64Array(r.revision);
	const s = new BigInt64Array(r.proof);
	const c = BigInt.asIntN(64, BigInt(n.userVersion >>> 0) << 32n | BigInt(n.schemaVersion >>> 0));
	const l = Atomics.load(s, 0);
	if (Atomics.load(o, 0) === r.epoch && l !== -1n) {
		if (l === c && Atomics.load(o, 0) === r.epoch && hasStateDatabaseIntegrityAdmission(e)) return;
		invalidate(o);
	}
	if (i === "require-proof") throw new Error("Shared-state reader requires current worker integrity proof");
	assertStateDatabaseIntegrityOnce(e, t);
	const publish = () => {
		if (Atomics.load(o, 0) === r.epoch) Atomics.store(s, 0, c);
	};
	return () => {
		if (e.isTransaction) stageSqliteTransactionState(e, { commit: publish });
		else publish();
	};
}
//#endregion
//#region src/state/openclaw-state-db-snapshot-owner.ts
function createOpenClawStateSnapshotOwnerRegistry() {
	const e = /* @__PURE__ */ new WeakMap();
	return {
		register(t, n) {
			if (isPostgresSqlConnection(t.db)) return;
			e.set(t.db, registerLiveSqliteSnapshotOwner({
				database: t.db,
				databasePath: t.path,
				assertCurrent: () => {
					if (n() !== t || !t.db.isOpen) throw new Error("OpenClaw state snapshot owner is no longer current");
				}
			}));
		},
		release(t) {
			if (isPostgresSqlConnection(t)) return;
			e.get(t)?.();
			e.delete(t);
		}
	};
}
const openClawStateSnapshotOwners = resolveGlobalSingleton(Symbol.for("openclaw.stateSnapshotOwners"), createOpenClawStateSnapshotOwnerRegistry);
//#endregion
//#region src/state/openclaw-state-db-cache.ts
const STATE_DATABASE_LIFECYCLE_KEY = Symbol.for("openclaw.stateDatabaseLifecycle");
const stateDatabaseLifecycle = resolveGlobalSingleton(STATE_DATABASE_LIFECYCLE_KEY, () => ({
	cachedDatabases: /* @__PURE__ */ new Map(),
	retainedDatabaseHandles: /* @__PURE__ */ new Map(),
	idleTimers: /* @__PURE__ */ new WeakMap(),
	idleReferences: /* @__PURE__ */ new WeakMap(),
	unregisterRetainedExitClose: void 0,
	databaseIdentities: /* @__PURE__ */ new WeakMap(),
	borrowers: /* @__PURE__ */ new WeakMap(),
	databaseLifecycleListeners: /* @__PURE__ */ new Set(),
	terminalOpenLatch: createSqliteTerminalOpenLatch({ closeByPath: (e, t) => cacheAdmission.closeTerminalFailure(e, t) }),
	asyncResources: createOpenClawStateDatabaseAsyncLifecycle()
}), () => closeOpenClawStateDatabaseAsync(), "shared-state");
const { cachedDatabases, retainedDatabaseHandles, idleTimers, idleReferences, databaseIdentities, borrowers, databaseLifecycleListeners, terminalOpenLatch, asyncResources } = stateDatabaseLifecycle;
const { touch: touchStateDatabase, retain: retainOpenClawStateDatabaseForIdle } = createStateDatabaseIdleRetirement(stateDatabaseLifecycle, retireOpenClawStateDatabaseHandle);
const { register: registerStateDatabaseWalAdmission, readHealth: readOpenClawStateWalHealth, ownRetirement: ownStateDatabaseRetirement, stop: stopOpenClawStateDatabaseMaintenance } = createStateDatabaseWalOwner(stateDatabaseLifecycle, retainOpenClawStateDatabaseForIdle, requireOpenClawStateDatabaseIdentity);
function notifyOpenClawStateDatabaseLifecycle(e) {
	const t = e.kind === "open-error" ? {
		...e,
		identity: e.identity ?? asyncResources.knownIdentity(e.path)
	} : e;
	for (const e of databaseLifecycleListeners) e(t);
}
function notifyOpenClawStateDatabaseClosed(e) {
	notifyOpenClawStateDatabaseLifecycle({
		kind: "closed",
		path: e.path,
		identity: requireOpenClawStateDatabaseIdentity(e)
	});
}
function requireOpenClawStateDatabaseIdentity(e) {
	const t = databaseIdentities.get(e.db);
	if (!t) throw new Error("Published shared-state owner has no recorded database identity");
	return t;
}
const cacheAdmission = createStateDatabaseCacheAdmission({
	cachedDatabases,
	evict: evictCachedOpenClawStateDatabase,
	invalidate: (e) => asyncResources.invalidate(e),
	notifyTerminalFailure: (e, t) => notifyOpenClawStateDatabaseLifecycle({
		kind: "terminal-failure",
		path: e,
		error: t,
		identity: asyncResources.knownIdentity(e)
	})
});
function registerOpenClawStateDatabaseLifecycleListener(e) {
	databaseLifecycleListeners.add(e);
	for (const t of cachedDatabases.values()) if (t.db.isOpen) e({
		kind: "opened",
		database: t,
		identity: requireOpenClawStateDatabaseIdentity(t)
	});
	return () => databaseLifecycleListeners.delete(e);
}
function retainStateDatabaseClose(e) {
	retainedDatabaseHandles.set(e.db, e);
	stateDatabaseLifecycle.unregisterRetainedExitClose ??= registerSqliteCacheExitClose(closeOpenClawStateDatabase);
}
function ownMaintenanceStateDatabaseHandle(e) {
	getOpenClawDatabaseMaintenanceScope()?.own(e.db, "shared-handles", async () => {
		const t = getOpenClawDatabaseMaintenanceScope();
		if (!t || !isOpenClawDatabaseMaintenanceResourceOwned(e.db, t)) return;
		if (cachedDatabases.get(e.path) === e || retainedDatabaseHandles.get(e.db) === e) {
			await e.walMaintenance?.stop();
			if (isOpenClawDatabaseMaintenanceResourceOwned(e.db, t) && (cachedDatabases.get(e.path) === e || retainedDatabaseHandles.get(e.db) === e)) retireOpenClawStateDatabaseHandle(e, false);
		}
	});
}
function closeUnpublishedOpenClawStateDatabaseHandle(e) {
	const t = closeOpenClawStateDatabaseHandle(e);
	if (retainedDatabaseHandles.get(e.db) === e) ownMaintenanceStateDatabaseHandle(e);
	return t;
}
/** Retain one exact canonical native owner; only the final reference retires its handle. */
const { retain: retainOpenClawStateDatabase, borrowForRead: borrowOpenClawStateDatabaseForAsyncRead, retainForIndependentRead: retainOpenClawStateDatabaseForIndependentRead } = createStateDatabaseRetainer(stateDatabaseLifecycle, {
	assertOpen(e, t, n) {
		assertOpenClawStateDatabaseOpenAllowed(e, t, n);
		assertExistingOpenClawStateSchemaCacheAdmission(e, stateDatabaseLifecycle);
	},
	capture: (e) => asyncResources.capture(e),
	retire: retireOpenClawStateDatabaseHandle,
	retainFailed: retainStateDatabaseClose,
	ownRetirement: ownStateDatabaseRetirement,
	touch: touchStateDatabase
});
/** Close both physical-handle owners while retaining every cleanup failure. */
function closeOpenClawStateDatabaseHandle(e, t) {
	clearTimeout(idleTimers.get(e.db));
	idleTimers.delete(e.db);
	try {
		assertStateDatabaseBorrowersReleased(borrowers.get(e.db), e.path);
	} catch (n) {
		const r = borrowers.get(e.db);
		if (r) {
			r.retiring = true;
			r.retirement = {
				ordinary: true,
				isCurrent: () => true,
				retire: () => {
					throwSqliteLifecycleErrors(closeOpenClawStateDatabaseHandle(e, t), `OpenClaw state database cleanup failed for ${e.path}.`);
					r.cleanupComplete = true;
					borrowers.delete(e.db);
				}
			};
		}
		retainStateDatabaseClose(e);
		return [n];
	}
	idleReferences.delete(e.db);
	openClawStateSnapshotOwners.release(e.db);
	const { errors: n, cleanupPending: r } = closeStateDatabaseHandle(e, t);
	if (e.db.isOpen || r) retainStateDatabaseClose(e);
	else retainedDatabaseHandles.delete(e.db);
	if (cachedDatabases.get(e.path)?.db === e.db) cachedDatabases.delete(e.path);
	if (retainedDatabaseHandles.size === 0) {
		stateDatabaseLifecycle.unregisterRetainedExitClose?.();
		stateDatabaseLifecycle.unregisterRetainedExitClose = void 0;
	}
	return n;
}
function evictCachedOpenClawStateDatabase(e) {
	if (!isPostgresSqlConnection(e.db)) invalidateOpenClawStateRuntimeIntegrity(e.db);
	if (cachedDatabases.get(e.path) !== e) return false;
	asyncResources.invalidate(e.path);
	cachedDatabases.delete(e.path);
	notifyOpenClawStateDatabaseClosed(e);
	closeOpenClawStateDatabaseHandle(e, { checkpointMode: "PASSIVE" });
	return true;
}
/** Evict an exact cached shared-state owner after a proven corruption read. */
function evictOpenClawStateDatabaseAfterCorruption(e, t) {
	return isSqliteCorruptionError(t) && evictCachedOpenClawStateDatabase(e);
}
/** Publish a fully opened handle and bind query corruption to its exact cache owner. */
function publishOpenClawStateDatabase(e, t) {
	const { db: n, path: r } = e;
	const { identity: i, admission: a } = asyncResources.publish(r);
	databaseIdentities.set(n, readTrackedStateDatabaseIdentity(n) ?? i);
	cachedDatabases.set(r, e);
	registerStateDatabaseWalAdmission(e, i, a, t);
	touchStateDatabase(e);
	openClawStateSnapshotOwners.register(e, () => cachedDatabases.get(r));
	ownMaintenanceStateDatabaseHandle(e);
	notifyOpenClawStateDatabaseLifecycle({
		kind: "opened",
		database: e,
		identity: i
	});
	if (!isPostgresSqlConnection(n)) registerNodeSqliteKyselyQueryErrorHandler(n, (t) => {
		if (!n.isTransaction && isSqliteCorruptionError(t)) evictCachedOpenClawStateDatabase(e);
	});
	terminalOpenLatch.clear(r);
	return e;
}
/** Looking up an admitted handle does not consume schema or row facts. */
function getCachedOpenClawStateDatabase(e, t) {
	const n = resolveDatabasePath({ path: e });
	const r = terminalOpenLatch.get(n);
	if (r) throw r;
	return readCachedOpenClawStateDatabase(n, t);
}
function readCachedOpenClawStateDatabase(e, t) {
	const n = getOpenClawDatabaseMaintenanceScope();
	if (t?.readOnly) n?.assertReadAdmission();
	else n?.assertAdmission();
	assertExistingOpenClawStateSchemaCacheAdmission(e, stateDatabaseLifecycle);
	const r = cachedDatabases.get(e);
	if (r) {
		if (borrowers.get(r.db)?.retiring) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);
		touchStateDatabase(r);
	}
	return r;
}
/** Keep the admitted revision live while a synchronous reader consumes its row facts. */
function withCachedOpenClawStateDatabase(e, t, n) {
	const r = getCachedOpenClawStateDatabase(e, t);
	return r && cacheAdmission.read(r, n);
}
function getOpenClawStateDatabaseIfOpenAtPath(e) {
	const t = getCachedOpenClawStateDatabase(e);
	observeOpenClawDatabaseMaintenanceResource(t?.db.isOpen ? t.db : void 0);
	return t?.db.isOpen ? t : void 0;
}
/** Remove a closed cached owner while fresh-open access is held. */
function closeStaleCachedOpenClawStateDatabase(e) {
	if (cachedDatabases.get(e.path) !== e) return;
	asyncResources.invalidate(e.path);
	const t = closeOpenClawStateDatabaseHandle(e);
	notifyOpenClawStateDatabaseClosed(e);
	throwSqliteLifecycleErrors(t, `Stale OpenClaw state database cleanup failed for ${e.path}.`);
}
/** Latch integrity refusals so later opens fail without rescanning. */
function recordOpenClawStateDatabaseOpenFailure(e, t) {
	terminalOpenLatch.record(resolveDatabasePath({ path: e }), t);
}
/** Clear a terminal open failure after doctor rewrites the database file. */
function clearOpenClawStateDatabaseOpenFailure(e) {
	const t = resolveDatabasePath({ path: e });
	terminalOpenLatch.clear(t);
	asyncResources.invalidate(t);
	notifyOpenClawStateDatabaseLifecycle({
		kind: "failure-cleared",
		path: t,
		identity: asyncResources.knownIdentity(t)
	});
}
/** Validate the canonical terminal fact before acquiring a domain-operation lease. */
async function getOpenClawStateDatabaseTerminalFailureAsync(e, t) {
	e.admission.assertCurrent();
	t?.throwIfAborted();
	return terminalOpenLatch.get(e.admission.databasePath);
}
/** Reject shared-state access after a process-local terminal failure. */
function assertOpenClawStateDatabaseOpenAllowed(e, t, n) {
	const r = resolveDatabasePath({ path: e });
	const i = t === "cached-read" ? assertStateDatabaseReadAllowed : assertStateDatabaseAccessAllowed;
	if (t === "cached-read" && n) n.assertReadAllowed();
	else i(e);
	const { identity: a } = asyncResources.capture(r);
	const o = terminalOpenLatch.get(r);
	if (o) throw o;
	for (const t of retainedDatabaseHandles.values()) if (borrowers.get(t.db)?.retiring && (t.path === r || databaseIdentities.get(t.db)?.key === a.key)) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);
}
function recordOpenClawStateDatabaseLifecycleOpenError(e, t) {
	notifyOpenClawStateDatabaseLifecycle({
		kind: "open-error",
		path: resolveDatabasePath({ path: e }),
		error: t
	});
}
/** Reject a fresh shared-state open after known corruption until repair clears it. */
function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e, t, n) {
	assertOpenClawStateDatabaseOpenAllowed(e);
	let r;
	try {
		r = readOpenClawDatabaseQuarantineFailure("state", e, { env: t });
	} catch (e) {
		if (!(e instanceof OpenClawQuarantineReadCleanupError)) throw e;
		n?.(e);
		return;
	}
	if (r?.cause instanceof OpenClawQuarantineReadCleanupError) n?.(r.cause);
	if (r) {
		cacheAdmission.closeTerminalFailure(e, r);
		throw r;
	}
}
/** SQLite owns checkpoint exclusion; retirement joins the actual native handle. */
function retireOpenClawStateDatabaseHandle(e, t = true, n) {
	assertStateDatabaseBorrowersReleased(borrowers.get(e.db), e.path);
	const r = borrowers.get(e.db);
	try {
		const r = cachedDatabases.get(e.path)?.db === e.db;
		if (t) asyncResources.invalidate(e.path);
		const i = closeOpenClawStateDatabaseHandle(e, n);
		if (r && t) try {
			notifyOpenClawStateDatabaseClosed(e);
		} catch (e) {
			i.push(e);
		}
		throwSqliteLifecycleErrors(i, `OpenClaw state database cleanup failed for ${e.path}.`);
	} catch (t) {
		if (r) retainStateDatabaseClose(e);
		throw t;
	}
	if (r) {
		r.cleanupComplete = true;
		borrowers.delete(e.db);
	}
}
/** Close cached and disposal-only handles, preserving independent cleanup failures. */
function retireOpenClawStateDatabaseHandles(e, t, n) {
	const r = /* @__PURE__ */ new Set([...retainedDatabaseHandles.values(), ...cachedDatabases.values()]);
	const i = [];
	let a = false;
	for (const o of r) {
		if (e !== void 0 && o.path !== e && (n === void 0 || databaseIdentities.get(o.db)?.key !== n.key)) continue;
		a = true;
		try {
			retireOpenClawStateDatabaseHandle(o, true, t);
		} catch (e) {
			i.push(e);
		}
	}
	throwSqliteLifecycleErrors(i, "OpenClaw state database cleanup failed.");
	return a;
}
function closeOpenClawStateDatabaseByPath(e, t) {
	return retireOpenClawStateDatabaseHandles(resolveDatabasePath({ path: e }), t, asyncResources.identity(e));
}
function closeOpenClawStateDatabase(e) {
	retireOpenClawStateDatabaseHandles(void 0, e);
}
/** Register a resource owner before it can admit any shared-state worker opens. */
const registerOpenClawStateDatabaseAsyncResource = asyncResources.register;
/** Close the admitted file or its canonical path, retaining first-creation identity getters. */
function registerOpenClawStatePathAsyncResource(e, t) {
	return registerOpenClawStateDatabaseAsyncResource({ close(n) {
		if (!n || n.key === e.identity.key || n.canonicalPath === e.identity.canonicalPath) return t();
		return Promise.resolve();
	} });
}
/** Capture the canonical read generation before any asynchronous worker admission. */
const captureOpenClawStateDatabaseReadAdmission = asyncResources.capture;
const captureOpenClawStateIntegrityAdmission = asyncResources.integrity;
/** Bind worker-created storage to its captured admission without publishing a native handle. */
function publishOpenClawStateDatabaseWorkerAdmission(e, t) {
	if (t) e.assertCurrent();
	asyncResources.publish(e.databasePath, t);
	e.assertCurrent();
}
/** Orderly lifecycle close; synchronous close remains native/exit cleanup only. */
async function closeOpenClawStateDatabaseAsync(e) {
	await asyncResources.close(void 0, async () => {
		await stopOpenClawStateDatabaseMaintenance();
		return retireOpenClawStateDatabaseHandles(void 0, e);
	});
}
function isOpenClawStateDatabaseOpen(e) {
	if (e !== void 0) return cachedDatabases.get(resolveDatabasePath({ path: e }))?.db.isOpen === true;
	return Array.from(cachedDatabases.values()).some((e) => e.db.isOpen);
}
/**
* Close shared state handles and clear terminal failure latches for test isolation.
* Worker retirement continues after return; await closeOpenClawStateDatabaseAsync()
* before raw SQLite or file access to a database that workers have used.
*/
function closeOpenClawStateDatabaseForTest() {
	closeOpenClawStateDatabase();
	terminalOpenLatch.clearAll();
}
/**
* Owners that register with this cache must serve only the published lifecycle.
* Every runtime chunk shares that lifecycle; only a retired module generation
* (a re-evaluated test graph whose detached work outlived its file) can differ.
*/
function assertPublishedOpenClawStateDatabaseLifecycle() {
	if (readGlobalSingleton(STATE_DATABASE_LIFECYCLE_KEY) !== stateDatabaseLifecycle) throw new Error("OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle");
}
/** Process-wide owner for cached shared-state handles and terminal open failures. */
const openClawStateDatabaseCache = {
	assertOpenClawStateDatabaseFreshOpenAllowedAtPath,
	assertOpenClawStateDatabaseOpenAllowed,
	clearOpenClawStateDatabaseOpenFailure,
	closeOpenClawStateDatabase,
	closeOpenClawStateDatabaseByPath,
	closeOpenClawStateDatabaseForTest,
	closeOpenClawStateDatabaseHandle,
	closeUnpublishedOpenClawStateDatabaseHandle,
	closeStaleCachedOpenClawStateDatabase,
	evictCachedOpenClawStateDatabase,
	evictOpenClawStateDatabaseAfterCorruption,
	getCachedOpenClawStateDatabase,
	peekOpenClawStateDatabaseConnection: (e) => cachedDatabases.get(resolveDatabasePath({ path: e }))?.db,
	withCachedOpenClawStateDatabase,
	getOpenClawStateDatabaseRecordedFailure: terminalOpenLatch.peek,
	getOpenClawStateDatabaseIfOpenAtPath,
	getKnownOpenClawStateDatabaseIdentity: asyncResources.knownIdentity,
	isOpenClawStateDatabaseOpen,
	/** Only the exact published, open owner carries canonical schema readiness. */
	isOpenClawStateDatabaseSchemaReady: (e) => cachedDatabases.get(e.path) === e && e.db.isOpen,
	publishOpenClawStateDatabase,
	recordOpenClawStateDatabaseOpenFailure,
	recordOpenClawStateDatabaseLifecycleOpenError,
	touchStateDatabase
};
//#endregion
export { sameSqliteFileGeneration as $, captureOpenClawStateReadWorkerContextWithAdmission as A, getExistingOpenClawStateSchemaPath as B, invalidateOpenClawStateRuntimeIntegrity as C, projectUpdateRehearsalDatabaseConfig as Ct, openTrackedStateDatabase as D, isTerminalSqliteIntegrityError as E, resolveSqliteDatabaseFilePaths as Et, captureSqliteWorkerStateContext as F, isGatewayExternallySupervised as G, recordExistingOpenClawStateSchemaDatabase as H, captureSqliteWorkerWalMaintenanceSuspension as I, assertEngineStoreExecutionAllowed as J, getGatewayServiceInstallation as K, getSqliteWorkerExistingDatabaseIdentity as L, migrateCronDefaultStoreIdentity as M, resolveCronIdentityMigrationDefaultStoreKey as N, openTrackedStateDatabaseResult as O, stateCronIdentityMigration as P, readStableSqliteFileGeneration as Q, getSqliteWorkerStateIntegrityAdmission as R, assertStateDatabaseIntegrityOnce as S, isUpdateRehearsalPrivateDatabase as St, assertSqliteTableIntegrity as T, quarantineOrphanedSqliteSidecars as Tt, jsonPathValue as U, isExistingOpenClawStateSchema as V, jsonValid as W, createSqliteFileGenerationReader as X, getDatabaseProcessRole as Y, parseSqliteFileGeneration as Z, registerOpenClawStatePathAsyncResource as _, normalizeSqliteNumber as _t, clearOpenClawStateDatabaseOpenFailure as a, captureSqlitePrivateSnapshotFamily as at, retainOpenClawStateDatabaseForIndependentRead as b, createConfigRuntimeEnv as bt, closeOpenClawStateDatabaseByPath as c, acquireSqliteSnapshotReadToken as ct, isOpenClawStateDatabaseOpen as d, registerSqliteCacheExitClose as dt, serializeSqliteFileGeneration as et, openClawStateDatabaseCache as f, createSqliteWalReclamationResult as ft, registerOpenClawStateDatabaseLifecycleListener as g, coerceRequiredSqliteNumber as gt, registerOpenClawStateDatabaseAsyncResource as h, truncateSqliteWal as ht, captureOpenClawStateIntegrityAdmission as i, startSqliteReadOnlyLocationAsync as it, captureOpenClawStateWorkerContextWithAdmission as j, readTrackedStateDatabaseIdentity as k, closeOpenClawStateDatabaseForTest as l, configureSqliteConnectionPragmas as lt, recordOpenClawStateDatabaseOpenFailure as m, decodeMountInfoPath as mt, borrowOpenClawStateDatabaseForAsyncRead as n, prepareSqliteReadOnlyLocationAwaited as nt, closeOpenClawStateDatabase as o, prepareSqliteReadOnlyLocationFromOwnedDatabase as ot, publishOpenClawStateDatabaseWorkerAdmission as p, prepareSqliteDatabaseDirectory as pt, SQLITE_IDLE_HANDLE_TTL_MS as q, captureOpenClawStateDatabaseReadAdmission as r, prepareSqliteReadOnlyLocationSync as rt, closeOpenClawStateDatabaseAsync as s, prepareSqliteReadOnlyLocationSyncInProcess as st, assertPublishedOpenClawStateDatabaseLifecycle as t, openSqliteReadOnlyDatabase as tt, getOpenClawStateDatabaseTerminalFailureAsync as u, configureSqlitePreSchemaPragmas as ut, requireOpenClawStateDatabaseIdentity as v, applyConfigEnvVars as vt, assertSqliteIntegrity as w, SQLITE_SIDECAR_SUFFIXES as wt, assertOpenClawStateRuntimeIntegrity as x, compareOpenClawVersions as xt, retainOpenClawStateDatabaseForIdle as y, cloneEnvWithPlatformSemantics as yt, sqliteWorkerRequestBytes as z };