UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,901 lines • 85 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as withEngineStoreAdmission } from "./admission-scope-DmxaPNhm.mjs";
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { n as safeParseJsonRecord, t as safeParseJson } from "./json-coercion-CaJLaav-.mjs";
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import "./utils-C8YECn2Q.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { i as listAgentIds, s as readAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { c as resolveOpenClawAgentSqlitePath, s as resolveIncognitoOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { n as listSqliteTargetCandidatePathsForSessionStorePath } from "./session-sqlite-target-paths-Dw0pT36E.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { v as resolveEffectiveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-DRDkoS4J.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, d as observeOpenClawDatabaseMaintenanceResource } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { f as readDatabaseIdentityBirthtime } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { rt as OPENCLAW_STATE_SCHEMA_SQL, y as prepareSqliteDatabaseCleanClose, z as revokeSqliteDatabaseAdmissions } from "./sqlite-database-admission-DQIqro3d.mjs";
import { l as quoteSqliteIdentifier } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { n as OPENCLAW_STATE_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { n as formatSqliteErrorCodeSuffix } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { c as createSqliteLifecycleAggregateError, n as OpenClawStateOwnershipError } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { c as withSqlitePostCommitPublications } from "./sqlite-post-commit-BrUVQObC.mjs";
import { a as executeSqliteQueryTakeFirstSync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { a as enableNodeSqliteKyselyStatementCache, n as clearNodeSqliteKyselyCacheForDatabase } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { n as captureSqliteReaderOwner } from "./sqlite-reader-lifecycle-Cug3fDqm.mjs";
import { D as requireNativeDatabaseFile, S as runSqliteSchemaReadSnapshotSync, d as invalidateSqliteSchemaFacts, o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists, n as ensureColumn, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { a as isSqliteSchemaVersionError, o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, n as DOCTOR_OWNED_STATE_TABLES, o as LAZY_ADDITIVE_STATE_TABLES, t as CLIENT_CREDENTIAL_CUTOVER_SCHEMA_VERSION, u as OPENCLAW_STATE_STRICT_SCHEMA_VERSION } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { n as StartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs";
import { i as getStateSchemaVersionAdmission, n as createStateSchemaAdmission, o as publishStateRuntimeSchemaAdmission, r as getStateRuntimeSchemaAdmission } from "./openclaw-state-db-admission-Bw1Mtc4x.mjs";
import { a as setSqliteBusyTimeout, i as runWithSqliteBusyTimeout, t as normalizeSqliteNonNegativeInteger } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { n as openNodeSqliteDatabase, r as resolveExistingSqliteFileUri } from "./node-sqlite-CU4puofF.mjs";
import { p as syncDirectorySync, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs";
import { n as flushAndHashFileSync } from "./file-descriptor-DQ-v5bLt.mjs";
import { s as deferSqliteSnapshotCleanupAfterRead } from "./sqlite-snapshot-capacity-error-DlgtEr8c.mjs";
import { n as isArtifactPreservingStateRead } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { u as createPrivateSqliteTempDirectorySync } from "./sqlite-snapshot-staging-DVmPTRsc.mjs";
import { a as runSqliteImmediateTransactionSync, r as runSqliteDeferredTransactionSync, t as assertTransactionUsable } from "./sqlite-transaction-BHHu6P5-.mjs";
import { n as normalizeSqliteNumber, t as coerceRequiredSqliteNumber } from "./sqlite-number-D8n3srri.mjs";
import { n as configureSqlitePreSchemaPragmas, p as truncateSqliteWal, s as createSqliteWalReclamationResult, t as configureSqliteConnectionPragmas } from "./sqlite-wal-DGPrWPl6.mjs";
import { r as prepareSqliteDatabaseDirectory } from "./sqlite-wal-filesystem-LJsoYuDu.mjs";
import { c as resolveQuarantineStorePath, l as warnAgentPathMigration, o as resolveOpenClawStateDirForDatabasePath, r as resolveDatabasePath, t as describeAgentPathMigration } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { b as withPersistedStateOwnerInspection, c as getStateDatabaseSchemaLease, m as withStateDatabaseColdAdmission, r as assertStateDatabaseAccessAllowed } from "./gateway-state-owner-Bnv5owvG.mjs";
import { a as StateDatabaseOfflineMaintenanceError, r as StateDatabaseAdmissionPendingError } from "./gateway-state-owner-errors-DI3mhN4z.mjs";
import { n as captureRuntimeWorkerSource } from "./runtime-worker-generation-DBZgwXBG.mjs";
import { a as prepareSqliteReadOnlyLocationSync, n as openSqliteReadOnlyDatabase, r as prepareSqliteReadOnlyLocation } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { d as runScopedSqliteInspection, u as runOneShotSqliteInspection } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { a as createSqliteReadOnlyWorkerError } from "./sqlite-readonly-worker-session-CnCHtSE5.mjs";
import { n as hydrateOpenClawStateWorkerError, r as retainOpenClawStateWorkerErrorPayload } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs";
import { a as resolveSqliteDatabaseFilePaths, i as quarantineOrphanedSqliteSidecars, n as hasOrphanedSqliteSidecars } from "./sqlite-files-rWisKj_V.mjs";
import { a as clearOpenClawStateDatabaseOpenFailure, i as captureOpenClawStateIntegrityAdmission, k as assertStateDatabaseIntegrityOnce, l as closeOpenClawStateDatabaseByPathAsync, m as openClawStateDatabaseCache, y as recordOpenClawStateDatabaseOpenFailure } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { i as readOpenClawDatabaseQuarantineFailure, n as clearOpenClawDatabaseQuarantine } from "./openclaw-quarantine-store-Bi4DSTmN.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { t as getGatewayServiceInstallation } from "./gateway-service-installation-context-CHlb7Eod.mjs";
import { a as isExistingOpenClawStateSchema, n as assertOpenClawStateSchemaRepairAllowed, o as recordExistingOpenClawStateSchemaDatabase } from "./openclaw-state-db-schema-policy-DvHzXD76.mjs";
import { i as getSqliteWorkerExistingDatabaseIdentity, n as captureSqliteWorkerWalMaintenanceSuspension, o as getSqliteWorkerStateIntegrityAdmission } from "./sqlite-worker-state-context-CR8h__Vh.mjs";
import { a as resolveCronIdentityMigrationDefaultStoreKey, t as migrateCronDefaultStoreIdentity } from "./openclaw-state-db-cron-identity-migration-XoyKZWfG.mjs";
import { a as readTrackedStateDatabaseIdentity, r as openTrackedStateDatabase } from "./openclaw-state-db-handle-BxpEWiaT.mjs";
import { a as classifySqliteFtsIntegrityFindings, i as assertSqliteTableIntegrity, n as SqliteRepairableForeignKeyError, o as isTerminalSqliteIntegrityError, r as assertSqliteIntegrity, s as readSqliteIntegrityFindings, u as sqliteIntegrityCheckSteps } from "./sqlite-integrity-CCmEgO_m.mjs";
import { d as withExistingOpenClawStateDatabaseArtifactPreservingReadOnly, m as withExistingOpenClawStateDatabaseReadOnly, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { c as runUpdateSqliteMigration, o as hasUpdateDoctorMigrationCapture } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs";
import { t as createSqliteTableContractReader } from "./sqlite-schema-catalog-BK5o5Jvf.mjs";
import { t as openEngineStore } from "./open-jth9KEHn.mjs";
import { t as stateEngineInput } from "./openclaw-state-db-engine-input-Dy8v5WSG.mjs";
import { a as isStatePostgres, c as stateEngineSchema, f as readStateSchemaPublicationBlocker, i as inspectStateSqlite, n as assertStateFileSnapshotAllowed, t as admitStatePostgres, u as advanceStateSchemaContentVersion } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { i as assertSupportedStateSchemaVersion, o as readStateSchemaContentVersion, r as admitStateSchemaFacts } from "./openclaw-state-db-schema-version-uNbDFl6T.mjs";
import { a as getCanonicalSqliteNamedIndexContracts, c as hasCanonicalSqliteSchemaFingerprint, l as readSqliteSchemaCookie, n as assertSqliteSchemaTablesPresent, s as getCanonicalSqliteTableNames } from "./sqlite-schema-contract-D3pR9vZs.mjs";
import { a as needsOpenClawStateDatabaseSchemaRepair, d as hasLegacyCronRunLogs, i as isOpenClawStateSchemaFastPathEligible, n as assertCurrentStateRuntimeSchema, r as assertNoLegacyStateRuntimeRepair, t as assertExistingOpenClawStateRuntimeSchema } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import { C as migrateHistoricalStateImports, a as markCurrentStateSchemaVersion, b as getOpenClawStateRuntimeSchema, c as prepareStateDatabaseSchemaRepair, d as writeCurrentStateSchemaMetadata, f as resolveSchemaMigrationIntegrityTables, i as executeCanonicalStateSchema, l as runStateSchemaMigrationTransaction, n as assertOpenClawStateDatabaseForMaintenance, o as migrateBoundedStateSchema, p as SCHEMA_MIGRATION_BACKUP_TABLES, r as assertOpenClawStateDatabaseOwner, s as openClawStateMigrationAssertions, t as assertMigratedStateTableIntegrity, u as versionedStateMigrations, w as migratePredicateColumnsV21 } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs";
import { n as openDoctorStateSchemaReadAdmission, t as hasDanglingSkillWorkshopCollectionReviewIndex } from "./openclaw-state-db-doctor-schema-C5bP-XwE.mjs";
import { i as repairOperatorApprovalSchema } from "./openclaw-state-db-operator-approval-migration-bHbKjHAr.mjs";
import { n as withStateDatabaseSchemaMaintenance, t as StateSchemaMutationConflictError } from "./state-database-maintenance-Z49n3wcg.mjs";
import { c as isOpenClawStateWriteContentionError, n as assertOpenClawStateWriteAllowed, r as assertOwnershipAllowsWrite, s as inspectOwnershipThroughConnection, u as parseExternalOwnership } from "./openclaw-state-ownership-Wv4JBQVJ.mjs";
import { t as UpdateSchemaRefusalError } from "./openclaw-update-schema-refusal-DQDN1MLl.mjs";
import { a as dropLegacyStateTables, c as repairLegacyGatewayRestartHandoffsForStrictMigration, d as runRetiredStateTableMigrations, f as migrateSessionWatchCursorProvenance, g as repairAuditEventsSchema, h as migrateSingletonStateFoldInV12, i as detectOpenClawStateDatabaseSchemaMigrationsFromDatabase, m as createStateConfigMachineTable, n as assertCanonicalAgentDatabasesPrimaryKey, o as migrateAgentDatabaseRelativePaths, p as needsSessionWatchCursorProvenanceMigration, r as assertCanonicalStateSchemaShape, s as migrateWorkerPlacementExecutionModeSchema, u as logRetiredStateTableMigration } from "./openclaw-state-db-schema-repair-aWqRraBE.mjs";
import { r as openOpenClawStateReadConnection } from "./openclaw-state-db-read-connection-DoTwzEPO.mjs";
import { n as runManagedStateTransaction } from "./openclaw-state-db-transaction-Bho3XfIN.mjs";
import { l as isNativeClientCredentialBootstrap } from "./client-credential-store-rd7DZXgD.mjs";
import { i as recoverClientCredentialStore, n as prepareClientCredentialMigration, t as bindFreshClientCredentialStore } from "./client-credential-migration-DMZoz4E1.mjs";
import { d as resolveConfigIncludesForRead, o as normalizeConfigIoDeps, s as parseConfigJson5, t as coerceConfig, u as resolveConfigForRead } from "./io.read-helpers-qAcqsRC0.mjs";
import { n as listConfiguredSessionStoreAgentIds } from "./targets-configured-agents-CQxugAIz.mjs";
import { t as ensureOpenClawStatePermissions } from "./openclaw-state-db-permissions-yFUWKbh-.mjs";
import { t as configureSqliteMaintenanceCache } from "./sqlite-maintenance-cache-E5FQa1nK.mjs";
import { r as migrateSqliteSchemaToStrictInTransaction, t as hasNonStrictSqliteTables } from "./sqlite-strict-BeSerG73.mjs";
import { c as cronRunStorageStatus, f as parseCronRunLogEntryObject, r as cronRunLogEntryToDetail } from "./run-history-detail-rOrjKG4Z.mjs";
import { l as ensureFirstUseAdditiveStateColumnsForStrictMigration, n as ensureAdditiveStateColumns } from "./openclaw-state-db-schema-additive-BOxd1NE5.mjs";
import { t as recoverOrphanTaskDeliveryRows } from "./openclaw-state-db-task-delivery-recovery-BhaIXO-A.mjs";
import fs, { existsSync, statSync } from "node:fs";
import path from "node:path";
import { isMainThread } from "node:worker_threads";
import { performance } from "node:perf_hooks";
//#region src/config/agent-store-source.ts
/** Inspect authored SQLite locators without runtime config, plugin loading, or state access. */
function readAgentStorePathsFromConfig(e, t) {
	const n = cloneEnvWithPlatformSemantics(e);
	n.OPENCLAW_STATE_DIR = t;
	const r = resolveConfigPath(n, t);
	let i = "{}";
	try {
		i = fs.readFileSync(r, "utf8");
	} catch (e) {
		ignoreMissingPath(e);
	}
	const a = parseConfigJson5(i);
	if (!a.ok) throw new Error(`Cannot parse agent storage configuration at ${r}.`);
	const o = normalizeConfigIoDeps({
		env: n,
		configPath: r,
		observe: false
	});
	const s = resolveConfigIncludesForRead(a.parsed, r, o);
	if (!isRecord(s) || ["agents", "session"].some((e) => s[e] !== void 0 && !isRecord(s[e]))) throw new Error(`Invalid agent storage configuration at ${r}.`);
	const c = readAgentRosterProperty(s);
	const hasValidStorageLocator = (e) => isRecord(e) && (e.agentDir === void 0 || typeof e.agentDir === "string");
	if (c && (c.kind === "entries" ? !isRecord(c.value) || Object.values(c.value).some((e) => !hasValidStorageLocator(e)) : !Array.isArray(c.value) || c.value.some((e) => !hasValidStorageLocator(e) || typeof e.id !== "string"))) throw new Error(`Invalid agent roster at ${r}.`);
	if (isRecord(s.session) && s.session.store !== void 0 && typeof s.session.store !== "string") throw new Error(`Invalid session storage configuration at ${r}.`);
	const l = resolveConfigForRead(s, n);
	if (l.envWarnings.some((e) => e.configPath === "session.store" || e.configPath.endsWith(".agentDir") || e.configPath.startsWith("agents.list[") && e.configPath.endsWith(".id") || e.configPath === "acp.defaultAgent" || e.configPath.startsWith("acp.allowedAgents") || e.configPath.endsWith(".runtime.type") || e.configPath.endsWith(".runtime.acp.agent"))) throw new Error(`Unresolved environment reference in agent storage configuration at ${r}.`);
	const u = coerceConfig(l.resolvedConfigRaw);
	const d = listAgentIds(u);
	const f = new Set(d.map((e) => path.join(resolveEffectiveAgentDir(u, e, { env: n }), "openclaw-agent.sqlite")));
	const p = new Set(listConfiguredSessionStoreAgentIds(u).map((e) => resolveSessionStorePathCore(u.session?.store, {
		agentId: e,
		env: n
	})));
	for (const e of p) for (const t of listSqliteTargetCandidatePathsForSessionStorePath(e)) f.add(t);
	for (const e of [n.OPENCLAW_AGENT_DIR, n.PI_CODING_AGENT_DIR]) if (e?.trim()) f.add(path.join(resolveUserPath(e, n), "openclaw-agent.sqlite"));
	return [...f];
}
//#endregion
//#region src/state/openclaw-agent-db-discovery-paths.ts
/** Recovery also inventories disk collisions at the reserved incognito filename. */
function resolveOpenClawAgentDatabaseDiscoveryPaths(e) {
	return [resolveOpenClawAgentSqlitePath(e), resolveIncognitoOpenClawAgentSqlitePath(e)].map((t) => path.join(e.agentDir, path.basename(t)));
}
//#endregion
//#region src/state/openclaw-state-db-initialization.ts
/** Capture deletion-history evidence before a native open can create the shared database. */
function prepareStateDatabaseInitialization(e, t, n = []) {
	try {
		if (resolveSqliteDatabaseFilePaths(resolveQuarantineStorePath(t)).some((e) => fs.lstatSync(e, { throwIfNoEntry: false }))) return { kind: "existing" };
		const r = resolveOpenClawStateDirForDatabasePath(e);
		const i = /* @__PURE__ */ new Set([...n, ...readAgentStorePathsFromConfig(t, r)]);
		const a = path.join(r, "agents");
		if (fs.lstatSync(a, { throwIfNoEntry: false })?.isSymbolicLink()) return { kind: "unavailable" };
		let o = [];
		try {
			o = fs.readdirSync(a, { withFileTypes: true });
		} catch (e) {
			ignoreMissingPath(e);
		}
		for (const e of o) {
			if (!e.isDirectory() && !e.isSymbolicLink()) continue;
			const n = path.join(a, e.name, "agent");
			if (e.isSymbolicLink() || fs.lstatSync(n, { throwIfNoEntry: false })?.isSymbolicLink()) return { kind: "unavailable" };
			for (const r of resolveOpenClawAgentDatabaseDiscoveryPaths({
				agentDir: n,
				agentId: e.name,
				env: t
			})) i.add(r);
		}
		for (const e of i) {
			const t = resolveSqliteDatabaseFilePaths(e);
			const n = fs.lstatSync(e, { throwIfNoEntry: false });
			if (n && (!n.isFile() || n.size > 0) || t.slice(1).some((e) => fs.lstatSync(e, { throwIfNoEntry: false }))) return { kind: "existing" };
		}
		if (resolveSqliteDatabaseFilePaths(e).some((e) => fs.lstatSync(e, { throwIfNoEntry: false }))) return {
			kind: "existing",
			nativeBootstrapEligible: true
		};
		return { kind: "fresh" };
	} catch {
		return { kind: "unavailable" };
	}
}
//#endregion
//#region src/state/openclaw-state-db-open.ts
const stateDbLog$1 = createSubsystemLogger("state/db");
function assertStateDatabaseIntegrityBeforeMutation(e, t) {
	if (getStateRuntimeSchemaAdmission(e)) return;
	const n = readStateSchemaContentVersion(e);
	if (n === 36) return;
	if (n === 0 && inspectStateSqlite(e).hasExistingData || n > 0 && n < 36) stateDbLog$1.info("state database schema migration pending; verifying integrity first", {
		fromVersion: n,
		path: t,
		toVersion: 36
	});
	assertStateDatabaseIntegrityOnce(e, t);
}
function openUnpublishedStateDatabase(e) {
	const open = (t) => {
		const n = getSqliteWorkerExistingDatabaseIdentity(e.pathname);
		const r = e.existingSchema || n ? statSync(e.pathname, { bigint: true }) : statSync(e.pathname, {
			bigint: true,
			throwIfNoEntry: false
		});
		if (n && (!r || `file:${r.dev}:${r.ino}` !== n)) throw new Error("SQLite database file identity changed before existing-only open");
		if (!r && !t) return withStateDatabaseSchemaMaintenance({
			databasePath: e.pathname,
			busyTimeoutMs: e.busyTimeoutMs
		}, () => open(true));
		if (r && !r.isFile()) throw new Error(`Existing shared-state database must be a regular file: ${e.pathname}`);
		const i = prepareStateDatabaseInitialization(e.pathname, e.env, e.initializationAgentPaths);
		if (!r) {
			quarantineOrphanedSqliteSidecars(e.pathname);
			ensureOpenClawStatePermissions(e.pathname, e.env, { createDirectory: true });
			prepareSqliteDatabaseDirectory(e.pathname);
		}
		return openNativeStateDatabase(e, i, r);
	};
	return open(false);
}
function openNativeStateDatabase(e, t, n) {
	const { busyTimeoutMs: r, lockFailureReporting: i } = e;
	const assertSameFile = () => {
		if (n) {
			const t = statSync(e.pathname, { bigint: true });
			if (!t.isFile() || t.dev !== n.dev || t.ino !== n.ino || readDatabaseIdentityBirthtime(t) !== readDatabaseIdentityBirthtime(n)) throw new Error(`Existing shared-state database generation changed: ${e.pathname}`);
		}
	};
	const a = openTrackedStateDatabase(e.pathname, {
		existingOnly: n !== void 0,
		expectedIdentity: n ? `file:${n.dev}:${n.ino}` : void 0
	});
	let o;
	let s = a;
	let c;
	try {
		assertSameFile();
		enableNodeSqliteKyselyStatementCache(a);
		setSqliteBusyTimeout(a, r);
		const l = stateEngineInput();
		const openSelected = () => {
			admitStateSchemaFacts(a, e.pathname);
			if (l && isNativeClientCredentialBootstrap(a)) throw new Error("Native credential bootstrap cannot become a PostgreSQL anchor. Start the Gateway once on SQLite and run openclaw doctor --fix, then use openclaw database port before selecting PostgreSQL.");
			return openEngineStore({
				anchor: a,
				schema: stateEngineSchema,
				input: l,
				existingOnly: e.existingSchema,
				inspectSqlite: () => inspectStateSqlite(a),
				prepareAnchor: () => {},
				onFreshAnchor: (t) => bindFreshClientCredentialStore(t, {
					path: e.pathname,
					env: e.env
				}),
				admitPostgres: (t, n) => {
					admitStatePostgres(t, n);
					if (n) {
						migrateCronDefaultStoreIdentity(t, {
							previousVersion: 0,
							legacyDefaultStoreKey: resolveCronIdentityMigrationDefaultStoreKey(e.env),
							fresh: true
						});
						bindFreshClientCredentialStore(t, {
							path: e.pathname,
							env: e.env
						});
					}
				},
				beforeMigrate: (t, n, r) => {
					prepareClientCredentialMigration(t, {
						path: e.pathname,
						env: e.env,
						fromVersion: n
					});
					if (n === 29 - 1) advanceStateSchemaContentVersion(t, {
						fromVersion: n,
						toVersion: 29
					});
					if (n === 34 - 1) migrateCronDefaultStoreIdentity(t, {
						previousVersion: n,
						legacyDefaultStoreKey: resolveCronIdentityMigrationDefaultStoreKey(e.env),
						sourceTables: r
					});
				},
				closeOnFailure: (e, t) => {
					s = e;
					throw t;
				},
				openSqlite: () => {
					assertOpenClawStateWriteAllowed({
						database: a,
						databasePath: e.pathname,
						env: e.env
					});
					if (e.existingSchema) {
						assertSameFile();
						e.ensureSchema(a, t);
						assertSameFile();
						c = {
							db: a,
							path: e.pathname,
							walMaintenance: {
								checkpoint: () => false,
								stop: async () => {},
								close: () => true,
								reclaimFreePages: createSqliteWalReclamationResult
							}
						};
						return;
					}
					ensureOpenClawStatePermissions(e.pathname, e.env);
					const n = runWithSqliteBusyTimeout(a, r, () => {
						assertSupportedStateSchemaVersion(a, e.pathname);
						assertStateDatabaseIntegrityBeforeMutation(a, e.pathname);
						configureSqlitePreSchemaPragmas(a, { busyTimeoutMs: r });
						o = configureSqliteConnectionPragmas(a, {
							busyTimeoutMs: r,
							databaseLabel: "openclaw-state",
							databasePath: e.pathname,
							onCheckpointError: (t) => stateDbLog$1.warn("Shared-state WAL maintenance failed", {
								error: formatErrorMessage(t),
								path: e.pathname,
								checkpoint: o?.health
							}),
							runMaintenance: (t) => {
								try {
									assertStateDatabaseAccessAllowed(e.pathname);
								} catch (t) {
									if (!(t instanceof StateDatabaseAdmissionPendingError) && !(t instanceof StateDatabaseOfflineMaintenanceError)) throw t;
									stateDbLog$1.debug("Shared-state WAL maintenance deferred during offline maintenance", { path: e.pathname });
									return false;
								}
								return t();
							},
							isScheduledMaintenanceSuspended: captureSqliteWorkerWalMaintenanceSuspension(),
							foreignKeys: true,
							synchronous: "NORMAL"
						});
						e.ensureSchema(a, t);
						return o;
					}, { lockFailureReporting: i });
					ensureOpenClawStatePermissions(e.pathname, e.env);
					assertSameFile();
					c = {
						db: a,
						path: e.pathname,
						walMaintenance: n
					};
				}
			});
		};
		s = l ? openSelected() : runUpdateSqliteMigration(a, e.pathname, openSelected, { created: n === void 0 });
		if (c) return c;
		assertOpenClawStateWriteAllowed({
			database: s,
			databasePath: e.pathname,
			env: e.env
		});
		return {
			db: s,
			path: e.pathname,
			walMaintenance: {
				checkpoint: () => false,
				stop: async () => {},
				close: () => true,
				reclaimFreePages: createSqliteWalReclamationResult
			}
		};
	} catch (t) {
		const n = openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle({
			db: s,
			path: e.pathname,
			walMaintenance: o
		});
		if (t instanceof Error && (isSqliteSchemaVersionError(t) || isTerminalSqliteIntegrityError(t))) e.recordOpenFailure(e.pathname, t);
		if (n.length > 0) throw createSqliteLifecycleAggregateError([t, ...n], `OpenClaw state database acquisition and cleanup failed for ${e.pathname}.`, t);
		throw t;
	}
}
//#endregion
//#region src/infra/schema-migration-diagnostics.ts
const SCHEMA_RECOVERY = "Stop the Gateway, preserve the database and its SQLite sidecars, resolve the reported cause, then rerun \"openclaw doctor --fix\" against the same state/config.";
/** Keep the cause before the location: support redaction consumes a pathname's suffix. */
function formatSchemaMigrationFailure(e, t, n) {
	const r = String(n).replace(`SQLite schema is incomplete or noncanonical for ${t}: `, "").replaceAll(t, "[redacted-path]").replace(/; run openclaw doctor --fix to repair it\.$/u, ".");
	const i = /[.!?]$/u.test(r) ? r : `${r}.`;
	return `${e}${formatSqliteErrorCodeSuffix(n)}: ${i} Database: ${t}`;
}
//#endregion
//#region src/infra/sqlite-index-schema.ts
const SQLITE_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
function foreignKeyMismatch(e) {
	if (!(e instanceof Error) || e.name !== "SqliteIntegrityError" || !e.message.startsWith("SQLite foreign_key_check failed for ") || !(e.cause instanceof Error) || !("code" in e.cause) || e.cause.code !== "ERR_SQLITE_ERROR") return;
	const t = /^foreign key mismatch - "[A-Za-z_][A-Za-z0-9_]*" referencing "([A-Za-z_][A-Za-z0-9_]*)"$/u.exec(e.cause.message);
	return t?.[1] ? {
		error: e,
		parentTable: t[1]
	} : void 0;
}
/**
* Verify the whole file before schema convergence. Physical corruption belongs
* to explicit Doctor maintenance, including when only an index is damaged.
*/
function* verifyAndRepairCanonicalSqliteIndexSteps(e, t, n, r = {}) {
	const { diagnostics: i, reuseIntegrity: a, ...o } = r;
	let s;
	if (a) {
		if (i) i.integrityGateOutcome = "cached";
	} else try {
		yield* sqliteIntegrityCheckSteps(e, t, i, r.integrity);
	} catch (e) {
		s = foreignKeyMismatch(e);
		if (!s) throw e;
	}
	const c = performance.now();
	const l = repairCanonicalSqliteIndexes(e, t, n, {
		...o,
		verifyPhysicalIntegrity: false,
		deferredForeignKeyMismatch: s
	});
	if (i) {
		i.canonicalIndexMs = Math.floor(performance.now() - c);
		i.repairedIndexCount = l.length;
		if (s) i.integrityGateOutcome = "healthy";
	}
	return l;
}
/**
* Restore every named index when SQLite's IF NOT EXISTS semantics preserve a
* same-name definition that no longer matches the committed schema.
*/
function repairCanonicalSqliteIndexes(e, t, n, r = {}) {
	const i = /* @__PURE__ */ new Set();
	let a = r.deferredForeignKeyMismatch;
	runSqliteSchemaReadSnapshotSync(e, () => {
		const o = createSqliteTableContractReader(e);
		if (!hasCanonicalSqliteSchemaFingerprint(n, o)) {
			const e = getCanonicalSqliteNamedIndexContracts(n);
			const r = /* @__PURE__ */ new Map();
			for (const t of e) {
				assertSqliteIdentifier(t.name);
				assertSqliteIdentifier(t.tableName);
				const e = r.get(t.tableName) ?? [];
				e.push(t);
				r.set(t.tableName, e);
			}
			for (const e of getCanonicalSqliteTableNames(n)) {
				assertSqliteIdentifier(e);
				const n = o(e);
				if (!n) continue;
				const a = r.get(e) ?? [];
				const s = new Set(a.map((e) => e.name));
				const c = n.indexes;
				const l = c.find((e) => e.unique === 1 && e.origin === "c" && e.name !== null && !s.has(e.name));
				if (l) throw new Error(`SQLite schema is incomplete or noncanonical for ${t}: unexpected unique index ${l.name}`);
				for (const e of a) {
					const t = c.find((t) => t.name === e.name);
					if (JSON.stringify(t) !== JSON.stringify(e.fingerprint)) i.add(e);
				}
			}
		}
		if (r.verifyPhysicalIntegrity !== false) try {
			assertSqliteIntegrity(e, t, r.integrity);
		} catch (e) {
			a = foreignKeyMismatch(e);
			if (!a) throw e;
		}
		if (a && ![...i].some((e) => e.unique && e.tableName === a?.parentTable)) throw a.error;
		if (i.size === 0) r.validateUnchanged?.(o);
	});
	if (i.size === 0) return [];
	const o = "repair_canonical_indexes";
	let s;
	e.exec(`SAVEPOINT ${o};`);
	try {
		for (const t of i) {
			s = t;
			e.exec("SAVEPOINT repair_canonical_index;");
			try {
				e.exec(`DROP INDEX IF EXISTS main.${t.name};`);
				const n = t.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
				e.exec(`${n} main.${t.name} ${t.definition};`);
			} catch (n) {
				e.exec("ROLLBACK TO SAVEPOINT repair_canonical_index;");
				if (r.allowMissingColumns && isMissingColumnError(n)) {
					i.delete(t);
					continue;
				}
				throw n;
			} finally {
				e.exec("RELEASE SAVEPOINT repair_canonical_index;");
			}
		}
		if (i.size === 0) {
			if (a) throw a.error;
			r.validateUnchanged?.();
			e.exec(`RELEASE SAVEPOINT ${o};`);
			return [];
		}
		for (const n of new Set([...i].map((e) => e.tableName))) assertSqliteTableIntegrity(e, t, n);
		r.validateAfterRepair?.();
		if (a) assertSqliteIntegrity(e, t, r.integrity);
		e.exec(`RELEASE SAVEPOINT ${o};`);
	} catch (n) {
		try {
			e.exec(`ROLLBACK TO SAVEPOINT ${o};`);
		} finally {
			e.exec(`RELEASE SAVEPOINT ${o};`);
		}
		if (n instanceof Error && isTerminalSqliteIntegrityError(n)) throw n;
		const r = n instanceof Error ? n.message : String(n);
		throw new Error(`SQLite canonical index ${s?.name ?? "repair"} failed for ${t}: ${r}`, { cause: n });
	}
	return [...i].map((e) => e.name).toSorted();
}
/** Explicit maintenance only: preserve the damaged image before rebuilding derived indexes. */
function repairSqliteIndexCorruption(e, t, n) {
	let r = [];
	return runSqliteImmediateTransactionSync(e, () => {
		const i = /* @__PURE__ */ new Set();
		const a = readSqliteIntegrityFindings(e);
		const o = classifySqliteFtsIntegrityFindings(e, a, n.ftsSchemas ?? []);
		if (n.ftsOnly && !o) throw new Error("Startup repair requires only canonical FTS integrity findings");
		for (const e of o ? [] : a) {
			if (e === "ok") continue;
			const t = (typeof e === "string" ? /^(?:row \d+ missing from index|wrong # of entries in index|non-unique entry in index) (.+)$/u.exec(e) : null)?.[1];
			if (!t) throw new Error(`Unrecognized SQLite integrity finding: ${String(e)}`);
			i.add(t);
		}
		if (i.size === 0 && !o) return [];
		const s = /* @__PURE__ */ new Set();
		for (const n of i) {
			const r = e.prepare("SELECT tbl_name FROM main.sqlite_schema WHERE type = 'index' AND name = ?").get(n);
			if (typeof r?.tbl_name !== "string") throw new Error(`SQLite index repair refused unknown index ${n} for ${t}.`);
			s.add(r.tbl_name);
		}
		for (const t of s) {
			const n = e.prepare(`SELECT * FROM main.${quoteSqliteIdentifier(t)} NOT INDEXED`);
			n.setReadBigInts(true);
			const r = n.iterate();
			while (!r.next().done);
		}
		n.backup();
		r = o ?? [...i].toSorted();
		for (const t of r) {
			const n = quoteSqliteIdentifier(t);
			e.exec(o ? `INSERT INTO main.${n}(${n}) VALUES('rebuild')` : `REINDEX main.${n}`);
		}
		assertSqliteIntegrity(e, t);
		return r;
	}, {
		databaseLabel: t,
		operationLabel: "sqlite.index-corruption-repair",
		withCommit: (e) => {
			if (r.length > 0) n.assertCurrent();
			e();
		}
	});
}
function assertSqliteIdentifier(e) {
	if (!SQLITE_IDENTIFIER_PATTERN.test(e)) throw new Error(`invalid SQLite identifier: ${e}`);
}
function isMissingColumnError(e) {
	return e instanceof Error && e.code === "ERR_SQLITE_ERROR" && /^no such column:/iu.test(e.message);
}
//#endregion
//#region src/infra/sqlite-index-recovery.ts
/** Preserve original pages through the snapshot owner before a Doctor repair writes. */
function backupDoctorSqliteRepair(e, t) {
	const n = prepareSqliteReadOnlyLocationSync(e);
	try {
		const r = openNodeSqliteDatabase(n.location);
		try {
			r.exec("PRAGMA journal_mode = DELETE;");
		} finally {
			r.close();
		}
		const i = createPrivateSqliteTempDirectorySync(path.dirname(e), `openclaw-${t}-recovery-`);
		const a = path.join(i, "database.sqlite");
		const o = flushAndHashFileSync(n.location);
		fs.copyFileSync(n.location, a, fs.constants.COPYFILE_EXCL);
		fs.chmodSync(a, 384);
		if (JSON.stringify(flushAndHashFileSync(a)) !== JSON.stringify(o)) throw new Error(`SQLite ${t} recovery backup verification failed: ${a}`);
		requireDirectorySync(syncDirectorySync(i), "SQLite recovery directory");
		requireDirectorySync(syncDirectorySync(path.dirname(i)), "SQLite recovery parent");
		return a;
	} finally {
		n.cleanup();
	}
}
/** Doctor holds maintenance authority; the snapshot owner preserves the damaged image. */
function repairDoctorSqliteIndexCorruption(e, t, n) {
	let r;
	let i;
	try {
		i = repairSqliteIndexCorruption(e, t, {
			ftsSchemas: n.ftsSchemas,
			ftsOnly: n.ftsOnly,
			assertCurrent: n.assertCurrent,
			backup: () => {
				n.assertCurrent();
				r = backupDoctorSqliteRepair(t, "index");
				n.assertCurrent();
			}
		});
	} catch (e) {
		const n = r ? ` Preserved pre-repair database: ${r}.` : "";
		throw new Error(`SQLite index repair refused for ${t}.${n} Preserve the database and its WAL; restore a verified backup or use SQLite recovery. ${String(e)}`, { cause: e });
	}
	return i.length > 0 ? [`Saved pre-repair SQLite backup: ${r}`, n.describeRepair?.(i) ?? `Warning: Rebuilt corrupt ${n.label} SQLite indexes: ${i.join(", ")}. No table rows were removed.`] : [];
}
//#endregion
//#region src/infra/state-migrations.cron-run-logs.ts
const CRON_RUN_LOG_TASK_IMPORT_MIGRATION_ID = "state:cron-run-logs-to-task-runs:v1";
const CRON_RUN_LOG_IMPORT_BATCH_SIZE = 500;
function collectMirroredTasks(e) {
	const t = e.prepare(`SELECT source_id, ended_at, detail_json
       FROM task_runs
       WHERE runtime = 'cron' AND source_id IS NOT NULL AND detail_json IS NOT NULL`).all();
	const n = /* @__PURE__ */ new Map();
	for (const e of t) {
		const t = e.detail_json ? safeParseJsonRecord(e.detail_json) : void 0;
		if (!e.source_id || t?.kind !== "cron-run") continue;
		const r = n.get(e.source_id) ?? [];
		r.push({
			endedAt: normalizeSqliteNumber(e.ended_at) ?? null,
			...typeof t.runId === "string" && t.runId ? { runId: t.runId } : {}
		});
		n.set(e.source_id, r);
	}
	return n;
}
function hasMirroredIdentity(e, t, n) {
	return e.some((e) => t && e.runId ? e.runId === t : e.endedAt === n);
}
function integerToBoolean(e) {
	return e === null || e === void 0 ? void 0 : coerceRequiredSqliteNumber(e) !== 0;
}
/** Legacy rows trust write-time errorReason and diagnostic redaction without recomputation. */
function parseLegacyRow(e) {
	const t = parseCronRunLogEntryObject(safeParseJson(e.entry_json ?? ""), { jobId: e.job_id });
	if (!t) return null;
	return {
		...t,
		ts: normalizeSqliteNumber(e.ts) ?? t.ts,
		jobId: e.job_id,
		status: e.status ?? t.status,
		error: e.error ?? t.error,
		summary: e.summary ?? t.summary,
		delivered: integerToBoolean(e.delivered) ?? t.delivered,
		deliveryStatus: e.delivery_status ?? t.deliveryStatus,
		deliveryError: e.delivery_error ?? t.deliveryError,
		sessionId: e.session_id ?? t.sessionId,
		sessionKey: e.session_key ?? t.sessionKey,
		runId: e.run_id ?? t.runId,
		runAtMs: normalizeSqliteNumber(e.run_at_ms ?? null) ?? t.runAtMs,
		durationMs: normalizeSqliteNumber(e.duration_ms ?? null) ?? t.durationMs,
		nextRunAtMs: normalizeSqliteNumber(e.next_run_at_ms ?? null) ?? t.nextRunAtMs,
		model: e.model ?? t.model,
		provider: e.provider ?? t.provider
	};
}
/** Runs inside the state schema transaction and removes the retired table after import. */
function migrateLegacyCronRunLogsToTaskRuns(e) {
	if (!hasLegacyCronRunLogs(e)) return {
		imported: 0,
		alreadyMirrored: 0,
		malformed: 0,
		skipped: true
	};
	const t = collectMirroredTasks(e);
	const n = /* @__PURE__ */ new Map();
	const r = e.prepare(`
    INSERT INTO task_runs (
      task_id, runtime, task_kind, source_id, requester_session_key, owner_key, scope_kind,
      child_session_key, parent_flow_id, parent_task_id, agent_id, requester_agent_id, run_id,
      label, task, status, delivery_status, notify_policy, created_at, started_at, ended_at,
      last_event_at, cleanup_after, error, progress_summary, terminal_summary, terminal_outcome,
      detail_json
    ) VALUES (
      @task_id, 'cron', NULL, @source_id, '', '', 'system', @child_session_key, NULL, NULL,
      NULL, NULL, @run_id, NULL, @task, @status, 'not_applicable', 'silent', @created_at,
      @started_at, @ended_at, @ended_at, NULL, @error, NULL, @terminal_summary,
      @terminal_outcome, @detail_json
    )
  `);
	let i = 0;
	let a = 0;
	let o = 0;
	let s = 0;
	while (true) {
		const c = e.prepare(`SELECT * FROM cron_run_logs
         ORDER BY job_id, ts, store_key, seq
         LIMIT ? OFFSET ?`).all(CRON_RUN_LOG_IMPORT_BATCH_SIZE, s);
		if (c.length === 0) break;
		s += c.length;
		for (const e of c) {
			const s = parseLegacyRow(e);
			if (!s) {
				o++;
				continue;
			}
			const c = `${s.jobId}\0${s.ts}`;
			const l = (n.get(c) ?? 0) + 1;
			n.set(c, l);
			if (hasMirroredIdentity(t.get(s.jobId) ?? [], s.runId, s.ts)) {
				a++;
				continue;
			}
			const u = `cron-runlog-import:${s.jobId}:${s.ts}:${l}`;
			const d = cronRunStorageStatus(s);
			r.run({
				task_id: u,
				source_id: s.jobId,
				child_session_key: s.sessionKey?.trim() || null,
				run_id: u,
				task: s.jobId,
				status: d,
				created_at: s.runAtMs ?? s.ts,
				started_at: s.runAtMs ?? null,
				ended_at: s.ts,
				error: s.error ?? null,
				terminal_summary: s.summary ?? null,
				terminal_outcome: d === "succeeded" ? "succeeded" : null,
				detail_json: JSON.stringify(cronRunLogEntryToDetail(s, { storeKey: e.store_key }))
			});
			i++;
		}
	}
	e.exec(`
    DROP INDEX IF EXISTS idx_cron_run_logs_store_ts;
    DROP INDEX IF EXISTS idx_cron_run_logs_job_status;
    DROP INDEX IF EXISTS idx_cron_run_logs_delivery;
    DROP TABLE cron_run_logs;
  `);
	const c = {
		imported: i,
		alreadyMirrored: a,
		malformed: o,
		skipped: false
	};
	const l = Date.now();
	e.prepare(`INSERT INTO migration_runs (id, started_at, finished_at, status, report_json)
     VALUES (?, ?, ?, 'completed', ?)
     ON CONFLICT(id) DO UPDATE SET
       finished_at = excluded.finished_at,
       status = excluded.status,
       report_json = excluded.report_json`).run(CRON_RUN_LOG_TASK_IMPORT_MIGRATION_ID, l, l, JSON.stringify(c));
	return c;
}
//#endregion
//#region src/state/agent-deletion-journal-history.ts
function hasPreJournalStateSchema(e) {
	if (isPostgresSqlConnection(e)) return false;
	if (readStateSchemaContentVersion(e) !== 1 || tableExists(e, "config_machine_state") || tableExists(e, "agent_database_leases") || !tableExists(e, "agent_databases") || !tableExists(e, "migration_sources")) return false;
	const t = getNodeSqliteKysely(e);
	const n = executeSqliteQueryTakeFirstSync(e, t.selectFrom("schema_meta").selectAll().where("meta_key", "=", "primary"));
	return n?.role === "global" && n.schema_version === 1 && n.agent_id === null && !executeSqliteQueryTakeFirstSync(e, t.selectFrom("migration_sources").select("source_key").where("target_table", "=", "agent_deletion_journal").limit(1));
}
//#endregion
//#region src/state/openclaw-state-db-startup-checkpoint.ts
const NATIVE_STARTUP_BOOTSTRAP_OBJECTS = /* @__PURE__ */ new Set([
	"table:device_auth_tokens",
	"index:idx_device_auth_tokens_updated",
	"table:device_identities",
	"index:idx_device_identities_device",
	"table:exec_approvals_config",
	"table:macos_port_guardian_records",
	"index:idx_macos_port_guardian_records_port",
	"table:schema_meta",
	"table:state_leases",
	"index:idx_state_leases_expiry",
	"index:idx_state_leases_owner"
]);
const STARTUP_CHECKPOINT_SCHEMA = `
  CREATE TABLE IF NOT EXISTS schema_meta (
    meta_key TEXT NOT NULL PRIMARY KEY,
    role TEXT NOT NULL,
    schema_version INTEGER NOT NULL,
    agent_id TEXT,
    app_version TEXT,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
  );
  CREATE TABLE IF NOT EXISTS state_leases (
    scope TEXT NOT NULL,
    lease_key TEXT NOT NULL,
    owner TEXT NOT NULL,
    expires_at INTEGER,
    heartbeat_at INTEGER,
    payload_json TEXT,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL,
    PRIMARY KEY (scope, lease_key)
  );
  CREATE INDEX IF NOT EXISTS idx_state_leases_expiry
    ON state_leases(expires_at, scope, lease_key)
    WHERE expires_at IS NOT NULL;
  CREATE INDEX IF NOT EXISTS idx_state_leases_owner
    ON state_leases(owner);
`;
const checkpointAdmission = createStateSchemaAdmission("state.startup-checkpoint", (e) => e === true ? true : void 0);
function isUninitializedNativeStartupDatabase(e, t) {
	const n = getAdmittedSqliteSchemaFacts(e);
	if ((t ?? getStateSchemaVersionAdmission(e)?.userVersion ?? n?.userVersion ?? readSqliteUserVersion(e)) !== 0) return false;
	const r = n ? [
		...[...n.tables].map((e) => ({
			type: "table",
			name: e
		})),
		...[...n.indexes].map((e) => ({
			type: "index",
			name: e
		})),
		...[...n.views].map((e) => ({
			type: "view",
			name: e
		})),
		...[...n.triggers.keys()].map((e) => ({
			type: "trigger",
			name: e
		}))
	].filter(({ name: e }) => !e.startsWith("sqlite_")) : e.prepare("SELECT type, name FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").all();
	if (r.some(({ type: e, name: t }) => typeof e !== "string" || typeof t !== "string" || !NATIVE_STARTUP_BOOTSTRAP_OBJECTS.has(`${e}:${t}`))) return false;
	const i = new Set(r.filter(({ type: e }) => e === "table").map(({ name: e }) => e));
	if (i.has("schema_meta") && e.prepare("SELECT 1 FROM schema_meta LIMIT 1").get()) return false;
	return !(i.has("state_leases") && e.prepare("SELECT 1 FROM state_leases LIMIT 1").get());
}
function ensureStartupMigrationCheckpointSchema(e, t, n) {
	runSqliteImmediateTransactionSync(e, () => {
		assertOpenClawStateWriteAllowed({
			database: e,
			databasePath: t,
			env: n
		});
		assertSupportedStateSchemaVersion(e, t);
		e.exec(STARTUP_CHECKPOINT_SCHEMA);
		ensureColumn(e, "schema_meta", "app_version TEXT");
	}, {
		busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
		databaseLabel: t,
		operationLabel: "state.schema.ensure-startup-checkpoint"
	});
}
function hasStartupMigrationCheckpointSchema(e) {
	const t = getAdmittedSqliteSchemaFacts(e);
	if (t) return t.tables.has("schema_meta") && t.tables.has("state_leases") && t.indexes.has("idx_state_leases_expiry") && t.indexes.has("idx_state_leases_owner") && tableHasColumn(e, "schema_meta", "app_version");
	const n = e.prepare(`SELECT type, name FROM sqlite_schema WHERE name IN (
      'schema_meta', 'state_leases', 'idx_state_leases_expiry', 'idx_state_leases_owner'
    )`).all();
	const has = (e, t) => n.some((n) => n.type === e && n.name === t);
	return has("table", "schema_meta") && has("table", "state_leases") && has("index", "idx_state_leases_expiry") && has("index", "idx_state_leases_owner") && tableHasColumn(e, "schema_meta", "app_version");
}
function withOpenClawStateStartupCheckpointConnection(e, t, n) {
	const r = t.env ?? process.env;
	const i = resolveDatabasePath(t);
	assertOpenClawStateSchemaRepairAllowed(i);
	const open = (a) => {
		assertStateDatabaseAccessAllowed(i);
		const o = existsSync(i);
		if (!o && !a) return withStateDatabaseSchemaMaintenance({ databasePath: i }, () => open(true));
		const s = prepareStateDatabaseInitialization(i, r, t.initializationAgentPaths);
		if (!o) {
			quarantineOrphanedSqliteSidecars(i);
			ensureOpenClawStatePermissions(i, r, { createDirectory: true });
		}
		const c = openNodeSqliteDatabase(o ? resolveExistingSqliteFileUri(i) : i, { timeout: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS });
		let l = false;
		let u;
		let d;
		try {
			if (getStateRuntimeSchemaAdmission(c) || checkpointAdmission.get(c)) admitSqliteSchema(c);
			openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(i, r);
			assertOpenClawStateWriteAllowed({
				database: c,
				databasePath: i,
				env: r
			});
			l = true;
			ensureOpenClawStatePermissions(i, r);
			if (a) configureSqlitePreSchemaPragmas(c, { busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS });
			const operate = () => {
				if (getStateRuntimeSchemaAdmission(c) || checkpointAdmission.get(c)) return { value: e(c) };
				assertStateDatabaseIntegrityOnce(c, i);
				const o = assertSupportedStateSchemaVersion(c, i);
				const l = isUninitializedNativeStartupDatabase(c, o);
				const u = l || !hasStartupMigrationCheckpointSchema(c);
				if (u && !a) return;
				const d = t.atomic && u ? readSqliteSchemaCookie(c) : void 0;
				if (l) n(c, i, r, s);
				if (u) ensureStartupMigrationCheckpointSchema(c, i, r);
				if (d !== void 0 && readSqliteSchemaCookie(c) !== d) assertSqliteIntegrity(c, i);
				admitSqliteSchema(c);
				checkpointAdmission.publish(c, true);
				return { value: e(c) };
			};
			const o = t.atomic === true && !getStateRuntimeSchemaAdmission(c) && !checkpointAdmission.get(c) && isUninitializedNativeStartupDatabase(c) && Number(c.prepare("PRAGMA foreign_keys").get()?.foreign_keys) === 1;
			if (o) c.exec("PRAGMA foreign_keys = OFF;");
			try {
				u = t.atomic ? withSqlitePostCommitPublications(c, () => runSqliteDeferredTransactionSync(c, operate, {
					busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
					databaseLabel: i,
					operationLabel: "state.startup-checkpoint.inspect-and-claim"
				})) : operate();
			} finally {
				if (o && c.isOpen) c.exec("PRAGMA foreign_keys = ON;");
			}
			if (u) try {
				truncateSqliteWal(c, i);
				d = prepareSqliteDatabaseCleanClose(c);
			} catch (e) {
				process.emitWarning(`Shared-state clean-close checkpoint failed: ${String(e)}`);
			}
		} finally {
			try {
				var f = _usingCtx();
				const e = f.u(d);
				c.close();
				e?.publish();
				if (l) ensureOpenClawStatePermissions(i, r);
			} catch (e) {
				f.e = e;
			} finally {
				f.d();
			}
		}
		if (u) return u.value;
		return withStateDatabaseSchemaMaintenance({ databasePath: i }, () => open(true));
	};
	return open(false);
}
/** Admit only recognized native bootstrap; versioned state stays on the read-only path. */
function initializeNativeOpenClawStateConnection(e, t) {
	assertOpenClawStateSchemaRepairAllowed(resolveDatabasePath(e));
	if (!withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => {
		if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
		return isUninitializedNativeStartupDatabase(e);
	}, e)) return;
	const n = e.env ?? process.env;
	const r = resolveDatabasePath(e);
	withStateDatabaseSchemaMaintenance({ databasePath: r }, () => {
		const i = prepareStateDatabaseInitialization(r, n, e.initializationAgentPaths);
		const a = openNodeSqliteDatabase(r);
		try {
			assertOpenClawStateWriteAllowed({
				database: a,
				databasePath: r,
				env: n
			});
			admitStateSchemaFacts(a, r);
			if (!isUninitializedNativeStartupDatabase(a)) return;
			assertStateDatabaseIntegrityOnce(a, r);
			t(a, r, n, i);
		} finally {
			clearNodeSqliteKyselyCacheForDatabase(a);
			a.close();
		}
		ensureOpenClawStatePermissions(r, n);
	});
}
//#endregion
//#region src/state/openclaw-state-service-installation.ts
/** Keep filesystem and refusal dependencies out of the eager CLI/worker context graph. */
function assertGatewayServiceSchemaMigrationAllowed(e, t, n) {
	const r = getGatewayServiceInstallation();
	if (r && t > 0 && t < n && r.databasePath === resolveIdentityPathViaExistingAncestorSync(e)) throw new StartupMaintenanceRequiredError("state-migrations", `Refusing a forward database schema migration: this CLI is ${r.cliVersion} but the Gateway service runs ${r.version} from ${r.root}; run openclaw update (or the CLI from ${r.root}).`);
}
//#endregion
//#region src/state/schema-migration-backup-scope.ts
/** Missing steps and same-version repairs retain the full-file recovery contract. */
function resolveSchemaMigrationBackupTables(e) {
	if (e.foundVersion <= 0 || e.foundVersion >= e.supportedVersion) return;
	const t = /* @__PURE__ */ new Set(["schema_meta"]);
	for (let n = e.foundVersion + 1; n <= e.supportedVersion; n++) {
		const r = SCHEMA_MIGRATION_BACKUP_TABLES[e.kind][n];
		if (!r) return;
		for (const e of r) t.add(e);
	}
	if (e.kind === "state") t.add("config_machine_state");
	return [...t].toSorted();
}
/** Backup format does not select integrity coverage, including same-version repair. */
function resolveSchemaMigrationIntegrityCheck(e, t = "quick") {
	if (t === "full") return { check: "full" };
	return {
		check: t,
		tables: resolveSchemaMigrationIntegrityTables(e)
	};
}
//#endregion
//#region src/state/openclaw-state-db-schema-runtime.ts
const stateDbLog = createSubsystemLogger("state/db");
/** Runtime converges schema; historical row repair belongs to explicit Doctor maintenance. */
function ensureOpenClawStateRuntimeSchema(e, t, n, r, i = OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, a = false, o) {
	const s = getSqliteWorkerStateIntegrityAdmission() ?? (isMainThread ? captureOpenClawStateIntegrityAdmission(t) : void 0);
	if (isExistingOpenClawStateSchema(t, e)) {
		assertExistingOpenClawStateRuntimeSchema(e, t, s);
		assertOpenClawStateWriteAllowed({
			database: e,
			databasePath: t,
			env: n
		});
		return [];
	}
	try {
		if (isOpenClawStateSchemaFastPathEligible(e, t, s)) {
			assertOpenClawStateWriteAllowed({
				database: e,
				databasePath: t,
				env: n
			});
			return [];
		}
	} catch (t) {
		if (!e.isOpen || t instanceof StartupMaintenanceRequiredError) throw t;
	}
	return withStateDatabaseSchemaMaintenance({
		databasePath: t,
		busyTimeoutMs: i
	}, () => {
		const s = Date.now();
		const c = [];
		let l = false;
		const u = runStateSchemaMigrationTransaction(e, t, () => {
			assertOpenClawStateWriteAllowed({
				database: e,
				databasePath: t,
				env: n
			});
			assertSupportedStateSchemaVersion(e, t);
			if (a && !isUninitializedNativeStartupDatabase(e)) return [];
			const i = readStateSchemaContentVersion(e);
			if (!getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance) assertGatewayServiceSchemaMigrationAllowed(t, i, 36);
			if (i === 0 && !isUninitializedNativeStartupDatabase(e)) throw new Error("Unrecognized native bootstrap database; preserve it and run openclaw doctor --fix.");
			if (i > 0) assertCanonicalStateSchemaShape(e, t);
			prepareClientCredentialMigration(e, {
				path: t,
				env: n,
				fromVersion: i
			});
			const u = getAdmittedSqliteSchemaFacts(e);
			if (i === 0 && u?.tables.size === 0 && u.views.size === 0) {
				createStateConfigMachineTable(e);
				executeCanonicalStateSchema(e, {
					includeVersionLazyAdditiveTables: true,
					includeAgentDeletionJournal: r.kind === "fresh" || r.nativeBootstrapEligible === true
				});
				migrateCronDefaultStoreIdentity(e, {
					previousVersion: i,
					legacyDefaultStoreKey: o ?? resolveCronIdentityMigrationDefaultStoreKey(n),
					fresh: true,
					nowMs: s
				});
				writeCurrentStateSchemaMetadata(e, s);
				l = true;
				return [];
			}
			if (i === 36) {
				assertNoLegacyStateRuntimeRepair(e, t);
				assertStateDatabaseIntegrityOnce(e, t);
				const n = repairCanonicalSqliteIndexes(e, t, OPENCLAW_STATE_SCHEMA_SQL, {
					verifyPhysicalIntegrity: false,
					allowMissingColumns: true,
					validateAfterRepair: () => {
						assertCanonicalStateSchemaShape(e, t);
						assertOpenClawStateDatabaseForMaintenance(e, { pathname: t });
					}
				});
				ensureAdditiveStateColumns(e, "runtime");
				assertCurrentStateRuntimeSchema(e, t);
				writeCurrentStateSchemaMetadata(e, s);
				l = true;
				return n.length > 0 ? [`Rebuilt canonical shared-state SQLite indexes (${n.length})`] : [];
			}
			openClawStateMigrationAssertions.get(i)?.(e, { pathname: t });
			const d = resolveSchemaMigrationIntegrityCheck({
				kind: "state",
				foundVersion: i,
				supportedVersion: 36
			});
			if (d.check === "quick") assertSqliteIntegrity(e, t, d);
			else assertStateDatabaseIntegrityOnce(e, t);
			const f = migrateBoundedStateSchema(e, i, {
				env: n,
				legacyCronDefaultStoreKey: o
			});
			if (f) {
				writeCurrentStateSchemaMetadata(e, s);
				assertCurrentStateRuntimeSchema(e, t);
				assertMigratedStateTableIntegrity(e, t, i);
				l = true;
				return f;
			}
			const p = migrateHistoricalStateImports(e, i);
			const m = tableExists(e, "agent_deletion_journal") || hasPreJournalStateSchema(e) || (r.kind === "fresh" || r.nativeBootstrapEligible === true) && isUninitializedNativeStartupDatabase(e);
			dropLegacyStateTables(e);
			const h = runRetiredStateTableMigrations(e, i);
			c.push(...h);
			if (migrateSingletonStateFoldInV12(e, i)) h.push("Folded singleton state tables into config_machine_state (v12)");
			if (migrateWorkerPlacementExecutionModeSchema(e, i)) h.push("Migrated cloud worker placements to execution modes");
			const g = migrateAgentDatabaseRelativePaths(e, i, t);
			h.push(...describeAgentPathMigration(g));
			if (migratePredicateColumnsV21(e, i)) h.push("Derived meeting transcript selectors and bounded delivery retention columns (v21)");
			ensureAdditiveStateColumns(e, i < 20 ? "repair" : "runtime");
			for (const t of versionedStateMigrations) if (t.migrate(e, i, {
				env: n,
				legacyCronDefaultStoreKey: o
			})) h.push(t.applied);
			migrateSessionWatchCursorProvenance(e);
			assertCanonicalStateSchemaShape(e, t);
			executeCanonicalStateSchema(e, {
				includeVersionLazyAdditiveTables: true,
				includeAgentDeletionJournal: m
			});
			migrateLegacyCronRunLogsToTaskRuns(e);
			if (i < 3 && hasNonStrictSqliteTables(e)) {
				repairLegacyGatewayRestartHandoffsForStrictMigration(e);
				ensureFirstUseAdditiveStateColumnsForStrictMigration(e);
				const n = migrateSqliteSchemaToStrictInTransaction(e, getOpenClawStateRuntimeSchema({
					includeVersionLazyAdditiveTables: true,
					includeAgentDeletionJournal: m
				}), { databaseLabel: t });
				if (n.migratedTables.length > 0) h.push(`Migrated shared state tables to SQLite STRICT typing (${n.migratedTables.length})`);
			}
			repairCanonicalSqliteIndexes(e, t, OPENCLAW_STATE_SCHEMA_SQL, { verifyPhysicalIntegrity: false });
			writeCurrentStateSchemaMetadata(e, s);
			assertOpenClawStateDatabaseForMaintenance(e, { pathname: t });
			assertMigratedStateTableIntegrity(e, t, i, true);
			l = true;
			warnAgentPathMigration(stateDbLog, g, t);
			return [...p, ...h];
		}, {
			busyTimeoutMs: i,
			databaseLabel: t,
			operationLabel: "state.schema.ensure"
		});
		if (l) publishStateRuntimeSchemaAdmission(e, true);
		c.forEach(logRetiredStateTableMigration);
		return u;
	});
}
//#endregion
//#region src/state/openclaw-state-db-repair.ts
function repairStateSchema(e, t, n, r = "quick", i) {
	assertOpenClawStateSchemaRepairAllowed(e);
	const a = openNodeSqliteDatabase(e, { enableForeignKeyConstraints: false });
	try {
		return runUpdateSqliteMigration(a, e, () => repairOpenedStateSchema(a, e, t, n, r, i));
	} finally {
		if (a.isOpen) {
			clearNodeSqliteKyselyCacheForDatabase(a);
			a.close();
		}
	}
}
function repairOpenedStateSchema(e, t, n, r, i, a) {
	const o = /* @__PURE__ */ new Set();
	let s = [];
	let c = false;
	try {
		if (r !== "automatic") revokeSqliteDatabaseAdmissions(e);
		setSqliteBusyTimeout(e, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
		const c = r === "automatic" ? void 0 : openDoctorStateSchemaReadAdmission(e);
		try {
			assertOpenClawStateWriteAllowed({
				database: e,
				databasePath: t,
				env: n,
				inspectOwnership: r === "automatic" ? void 0 : true
			});
			assertCanonicalAgentDatabasesPrimaryKey(e, t);
		} finally {
			c?.();
		}
		ensureOpenClawStatePermissions(t, n);
		if (r === "automatic") return {
			changes: ensureOpenClawStateRuntimeSchema(e, t, n, { kind: "existing" }, void 0, false, a),
			warnings: []
		};
		if (r === "version") return {
			changes: runStateSchemaMigrationTransaction(e, t, () => {
				assertOpenClawStateDatabaseOwner(e, { pathname: t });
				const r = readStateSchemaContentVersion(e);
				if (r === 0 && !isUninitializedNativeStartupDatabase(e)) throw new Error("Unrecognized native bootstrap database; preserve it for explicit recovery.");
				prepareClientCredentialMigration(e, {
					path: t,
					env: n,
					fromVersion: r
				});
				if (r === 36) {
					recoverClientCredentialStore(e, {
						path: t,
						env: n
					});
					return [];
				}
				const i = migrateBoundedStateSchema(e, r, {
					env: n,
					legacyCronDefaultStoreKey: a,
					versionMigrationOnly: true
				});
				if (!i) throw new Error(`No bounded shared-state migration from v${r}.`);
				markCurrentStateSchemaVersion(e);
				assertMigratedStateTableIntegrity(e, t, r);
				return i;
			}, {
				busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
				databaseLabel: t,
				operationLabel: "state.schema.version-migration"
			}),
			warnings: []
		};
		const l = prepareStateDatabaseSchemaRepair(e, t, n);
		const u = r !== "readability" && !hasDanglingSkillWorkshopCollectionReviewIndex(e);
		let d = u ? readStateSchemaContentVersion(e) : void 0;
		let f = d === void 0 ? void 0 : resolveSchemaMigrationIntegrityCheck({
			kind: "state",
			foundVersion: d,
			supportedVersion: 36
		}, i);
		const assertIndexRepairCurrent = () => {
			assertOpenClawStateDatabaseOwner(e, { pathname: t });
			assertOpenClawStateWriteAllowed({
				database: e,
				databasePath: t,
				env: n,
				inspectOwnership: true
			});
		};
		const p = u && Boolean(openClawStateDatabaseCache.getOpenClawStateDatabaseRecordedFailure(t) || readOpenClawDatabaseQuarantineFailure("state", t, {
			env: n,
			fresh: true
		}));
		let m = p || r === "indexes" && i === "full";
		let h = false;
		if (u && !m) try {
			assertSqliteIntegrity(e, t, f);
			h = true;
		} catch (e) {
			if (e instanceof Error && isTerminalSqliteIntegrityError(e)) m = true;
			else if (!(e instanceof SqliteRepairableForeignKeyError)) throw e;
		}
		s = u && m ? repairDoctorSqliteIndexCorruption(e, t, {
			label: "shared-state",
			assertCurrent: assertIndexRepairCurrent
		}) : [];
		if (s.length > 0) h = true;
		else if (p) {
			assertSqliteIntegrity(e, t);
			h = true;
		}
		if (r === "indexes") {
			if (u && (s.length > 0 || p)) runSqliteImmediateTransactionSync(e, () => {
				assertIndexRepairCurrent();
				if (!clearOpenClawDatabaseQuarantine(t, { env: n })) throw new Error(`Repaired ${t}, but its quarantine record could not be cleared.`);
				clearOpenClawStateDatabaseOpenFailure(t);
			}, {
				databaseLabel: t,
				operationLabel: "state.schema.quarantine-clear"
			});
			return {
				changes: s,
				warnings: []
			};
		}
		if (r === "readability") {
			const r = runSqliteImmediateTransactionSync(e, () => {
				const n = l();
				if (n.length > 0) {
					assertOpenClawStateDatabaseOwner(e, { pathname: t });
					assertSqliteTableIntegrity(e, t, "skill_workshop_collection_reviews");
				}
				return n;
			}, {
				busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
				databaseLabel: t,
				operationLabel: "state.schema.readability-repair"
			});
			r.push(...runSqliteImmediateTransactionSync(e, () => {
				assertOpenClawStateWriteAllowed({
					database: e,
					databasePath: t,
					env: n,
					inspectOwnership: true
				});
				return recoverOrphanTaskDeliveryRows(e, t);
			}, {
				busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
				databaseLabel: t,
				operationLabel: "state.schema.readability-recovery"
			}));
			return {
				changes: r,
				warnings: []
			};
		}
		const g = [...s];
		const _ = runStateSchemaMigrationTransaction(e, t, () => {
			d ??= readStateSchemaContentVersion(e);
			f ??= resolveSchemaMigrationIntegrityCheck({
				kind: "state",
				foundVersion: d,
				supportedVersion: 36
			}, i);
			if (d === 0 && !isUninitializedNativeStartupDatabase(e)) throw new Error("Unrecognized native bootstrap database; preserve it for explicit recovery.");
			const r = d === 1 && !tableExists(e, "audit_events");
			if (r) assertOpenClawStateDatabaseOwner(e, { pathname: t });
			prepareClientCredentialMigration(e, {
				path: t,
				env: n,
				fromVersion: d
			});
			g.push(...recoverOrphanTaskDeliveryRows(e, t));
			if (!h) assertSqliteIntegrity(e, t, f);
			g.push(...migrateHistoricalStateImports(e, d, "doctor"));
			if (d !== 36) {
				openClawStateMigrationAssertions.get(d)?.(e, { pathname: t });
				const r = migrateBoundedStateSchema(e, d, {
					env: n,
					legacyCronDefaultStoreKey: a
				});
				if (r) {
					g.push(...r);
					markCurrentStateSchemaVersion(e);
					assertCurrentStateRuntimeSchema(e, t);
					assertMigratedStateTableIntegrity(e, t, d);
					return g;
				}
			}
			const s = tableExists(e, "agent_deletion_journal") || hasPreJournalStateSchema(e);
			if (d === 36) {
				recoverClientCredentialStore(e, {
					path: t,
					env: n
				});
				assertSqliteSchemaTablesPresent(e, t, OPENCLAW_STATE_SCHEMA_SQL, { allowedMissingTables: [...LAZY_ADDITIVE_STATE_TABLES, ...DOCTOR_OWNED_STATE_TABLES] });
			}
			dropLegacyStateTables(e);
			g.push(...runRetiredStateTableMigrations(e, d));
			if (migrateSingletonStateFoldInV12(e, d)) g.push("Folded singleton state tables into config_machine_state (v12)");
			if (migrateWorkerPlacementExecutionModeSchema(e, d)) g.push("Migrated cloud worker placements to execution modes");
			g.push(...describeAgentPathMigration(migrateAgentDatabaseRelativePaths(e, d, t)));
			if (repairAuditEventsSchema(e)) g.push(`Migrated shared state audit event ledger → versioned message lifecycle schema`);
			g.push(...repairOperatorApprovalSchema(e));
			const c = needsSessionWatchCursorProvenanceMigration(e, d);
			const l = migrateSessionWatchCursorProvenance(e);
			if (c) g.push(`Migrated shared state session watch cursors → provenance column (${l.migratedAmbientWatches} ambient, ${l.removedLegacySentinels} sentinels removed)`);
			assertCanonicalStateSchemaShape(e, t);
			if (d === 0 || r || tableExists(e, "audit_events")) {
				if (migratePredicateColumnsV21(e, d)) g.push("Derived meeting transcript selectors and bounded delivery retention columns (v21)");
				ensureAdditiveStateColumns(e, "repair");
				for (const t of versionedStateMigrations) if (t.migrate(e, d, {
					env: n,
					legacyCronDefaultStoreKey: a
				})) g.push(t.applied);
				executeCanonicalStateSchema(e, {
					includeVersionLazyAdditiveTables: d !== 36,
					includeAgentDeletionJournal: s
				});
				migrateLegacyCronRunLogsToTaskRuns(e);
				if (d < 3) {
					repairLegacyGatewayRestartHandoffsForStrictMigration(e);
					ensureFirstUseAdditiveStateColumnsForStrictMigration(e);
				}
				const r = migrateSqliteSchemaToStrictInTransaction(e, getOpenClawStateRuntimeSchema({
					includeVersionLazyAdditiveTables: d !== 36,
					includeAgentDeletionJournal: tableExists(e, "agent_deletion_journal")
				}), {
					databaseLabel: t,
					integrityCheck: i
				});
				if (r.migratedTables.length > 0) g.push(`Migrated shared state tables to SQLite STRICT typing (${r.migratedTables.length})`);
				for (const n of repairCanonicalSqliteIndexes(e, t, OPENCLAW_STATE_SCHEMA_SQL, {
					verifyPhysicalIntegrity: false,
					integrity: f
				})) o.add(n);
			}
			markCurrentStateSchemaVersion(e, { createMetadataIfMissing: d < 36 });
			if (readStateSchemaContentVersion(e) === 36) assertCurrentStateRuntimeSchema(e, t);
			if (d < 36) assertMigratedStateTableIntegrity(e, t, d, true);
			if (o.size > 0) g.push(`Rebuilt canonical shared-state SQLite indexes (${o.size})`);
			return g;
		}, {
			busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
			databaseLabel: t,
			operationLabel: "state.schema.repair"
		}, () => {
			g.push(...l());
			configureSqliteMaintenanceCache(e);
		});
		const v = clearOpenClawDatabaseQuarantine(t, { env: n });
		clearOpenClawStateDatabaseOpenFailure(t);
		if (readStateSchemaContentVersion(e) === 36) publishStateRuntimeSchemaAdmission(e, true);
		return {
			changes: _,
			warnings: v ? [] : [`Persisted quarantine record for ${t} could not be cleared; rerun openclaw doctor --fix so the repaired database is not refused again.`]
		};
	} catch (e) {
		if (e instanceof UpdateSchemaRefusalError) throw e;
		if (e instanceof OpenClawStateOwnershipError) {
			c = true;
			throw e;
		}
		const n = formatSchemaMigrationFailure("Failed migrating shared state database schema", t, e);
		const i = r === "automatic" ? n : n.replace(/has a legacy ([a-z ]+) schema; run openclaw doctor --fix to migrate it\.?/u, "has a legacy $1 schema; automatic repair refused the unrecognized schema shape.");
		const a = extractErrorCode(e) === "CLIENT_CREDENTIAL_SOCKET_INVALID" ? "Client credential socket material is invalid.\n" : "";
		return {
			changes: s,
			warnings: [`${a}${i}`]
		};
	} finally {
		if (!c) ensureOpenClawStatePermissions(t, n);
	}
}
//#endregion
//#region src/state/openclaw-state-ownership-worker.ts
function readOwnershipWorkerReply(e, t) {
	let n;
	try {
		n = JSON.parse(e);
	} catch {
		throw createSqliteReadOnlyWorkerError("returned invalid ownership JSON", t);
	}
	if (!isRecord(n) || Object.keys(n).length !== 2 || typeof n.ok !== "boolean") throw createSqliteReadOnlyWorkerError("returned an invalid ownership result", t);
	if (n.ok && typeof n.ownershipJson === "string") return n.ownershipJson;
	if (!n.ok && "workerError" in n) {
		const e = /* @__PURE__ */ new Error("Shared-state ownership inspection failed");
		retainOpenClawStateWorkerErrorPayload(e, n.workerError);
		throw hydrateOpenClawStateWorkerError(e, { includeOrdinary: true });
	}
	throw createSqliteReadOnlyWorkerError("returned an invalid ownership result", t);
}
/** Read live ownership in a child so closing the reader cannot release this process's locks. */
function inspectOpenClawStateOwnershipWithWorker(e, t) {
	return runScopedSqliteInspection(t, (t) => {
		t?.throwIfAborted();
		const { moduleUrl: n, runtimeGeneration: r } = captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl("stateOwnership"));
		return runOneShotSqliteInspection({
			pathname: e,
			operation: "state ownership",
			argv: [...resolveRuntimeWorkerArgv(n), e],
			runtimeGeneration: r,
			signal: t,
			stoppedFailure: "ownership owner stopped",
			read: (e) => {
				t?.throwIfAborted();
				if (e.failure) throw createSqliteReadOnlyWorkerError(e.failure, e.stderr);
				return readOwnershipWorkerReply(e.stdout, e.stderr);
			}
		});
	});
}
//#endregion
//#region src/state/openclaw-state-ownership-preflight.ts
/** Check write admission; callers may defer orphan-sidecar recovery until mutation is certain. */
function assertOpenClawStateWriteAllowedAtPath(e) {
	return withPersistedStateOwnerInspection(() => assertWriteAllowed(e));
}
async function assertWriteAllowed(e) {
	e.signal?.throwIfAborted();
	const t = path.resolve(e.databasePath);
	assertStateDatabaseAccessAllowed(t);
	if (e.recoverOrphanedSidecars !== false && hasOrphanedSqliteSidecars(t)) withStateDatabaseSchemaMaintenance({ databasePath: t }, () => quarantineOrphanedSqliteSidecars(t));
	if (!existsSync(t)) return;
	const n = e.env ?? process.env;
	if (getDatabaseEngineInput("state")) {
		const r = await executeExistingOpenClawStateRead({
			path: t,
			env: n
		}, {
			type: "stateBootstrap.ownership",
			input: { pathname: t }
		}, {
			current: true,
			signal: e.signal
		});
		e.signal?.throwIfAborted();
		assertStateDatabaseAccessAllowed(t);
		assertOwnershipAllowsWrite(r?.ownership ?? null, t, n);
		return;
	}
	if (!e.openStateSchemaReadAdmission && !getOpenClawDatabaseMaintenanceScope() && !getStateDatabaseSchemaLease(t)) {
		const r = await inspectOpenClawStateOwnershipWithWorker(t, e.signal);
		e.signal?.throwIfAborted();
		assertStateDatabaseAccessAllowed(t);
		assertOwnershipAllowsWrite(r === "null" ? null : parseExternalOwnership(r, t), t, n);
		return;
	}
	const r = await prepareSqliteReadOnlyLocation(t, {
		preserveSourceArtifacts: true,
		signal: e.signal
	});
	let i = false;
	try {
		e.signal?.throwIfAborted();
		assertStateDatabaseAccessAllowed(t);
		assertOwnershipAllowsWrite(inspectOwnershipThroughConnection(r.location, t, e.openStateSchemaReadAdmission), t, n);
		i = true;
	} finally {
		await r.cleanupAsync().catch((e) => {
			if (!i || !deferSqliteSnapshotCleanupAfterRead(e, r.cleanupRoot)) throw e;
		});
	}
}
//#endregion
//#region src/state/openclaw-state-db-schema-discovery.ts
function detectOpenClawStateDatabaseSchemaMigrations(e = {}, t = {}) {
	const n = resolveDatabasePath(e);
	if (!existsSync(n)) return [];
	if (isStatePostgres() || t.artifactPreservingReadOnly || hasUpdateDoctorMigrationCapture()) return withExistingOpenClawStateDatabaseArtifactPreservingReadOnly(({ db: e }) => {
		if (isPostgresSqlConnection(e)) return [];
		return detectOpenClawStateDatabaseSchemaMigrationsFromDatabase(e, n);
	}, {
		...e,
		path: n
	}) ?? [];
	const r = openSqliteReadOnlyDatabase(n, { readOnly: true });
	try {
		return detectOpenClawStateDatabaseSchemaMigrationsFromDatabase(r, n);
	} finally {
		r.close();
	}
}
//#endregion
//#region src/state/openclaw-state-db.ts
const deferredStateDatabases = /* @__PURE__ */ new WeakSet();
function readPublishedStateSchemaVersion(e) {
	const t = getStateSchemaVersionAdmission(e);
	if (t) return t.userVersion;
	if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
	return readSqliteUserVersion(e);
}
function repairDoctorStateDatabase(e, t) {
	if (isStatePostgres()) {
		openOpenClawStateDatabase(e);
		return {
			changes: [],
			warnings: []
		};
	}
	const n = e.env ?? process.env;
	const r = resolveDatabasePath(e);
	assertOpenClawStateSchemaRepairAllowed(r);
	if (!existsSync(r)) return {
		changes: [],
		warnings: []
	};
	if (t === "readability") openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(r, n);
	return withStateDatabaseSchemaMaintenance({ databasePath: r }, () => repairStateSchema(r, n, t, e.integrityCheck));
}
function repairOpenClawStateDatabaseSchema(e = {}) {
	return repairDoctorStateDatabase(e, e.versionMigrationOnly ? "version" : "doctor");
}
/** Explicit Doctor maintenance before config readers encounter a quarantined index. */
function repairOpenClawStateDatabaseIndexesForDoctor(e = {}) {
	return repairDoctorStateDatabase({
		...e,
		integrityCheck: e.integrityCheck ?? "full"
	}, "indexes");
}
/** Repair known catalog damage and preserve orphan rows before Doctor backs up or loads state. */
function repairOpenClawStateDatabaseReadabilityForDoctor(e = {}) {
	return repairDoctorStateDatabase(e, "readability");
}
/** Prepare schema and retire resources only when the admitted operation actually repairs it. */
async function prepareOpenClawStateDatabaseSchema(e = {}, t = "automatic") {
	if (isStatePostgres()) {
		openOpenClawStateDatabase(e);
		return {
			changes: [],
			warnings: []
		};
	}
	const n = e.env ?? process.env;
	const r = resolveDatabasePath(e);
	assertOpenClawStateSchemaRepairAllowed(r);
	if (!existsSync(r)) return {
		changes: [],
		warnings: []
	};
	const i = t === "automatic" ? "automatic" : "doctor";
	await assertOpenClawStateWriteAllowedAtPath({
		databasePath: r,
		env: n,
		recoverOrphanedSidecars: false,
		...i === "doctor" ? { openStateSchemaReadAdmission: openDoctorStateSchemaReadAdmission } : {}
	});
	let a = false;
	try {
		let o = t === "doctor";
		if (t === "doctor-preparation") try {
			openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(r, n);
		} catch {
			o = true;
		}
		if (!o && !needsOpenClawStateDatabaseSchemaRepair(r, i, e.integrityCheck)) return {
			changes: [],
			warnings: []
		};
		a = true;
		await closeOpenClawStateDatabaseByPathAsync(r);
		return withStateDatabaseSchemaMaintenance({ databasePath: r }, () => repairStateSchema(r, n, i, e.integrityCheck, e.legacyCronDefaultStoreKey));
	} finally {
		if (a) await closeOpenClawStateDatabaseByPathAsync(r);
	}
}
/** Bootstrap fresh/native-only state canonically before startup checkpoint access. */
function withOpenClawStateStartupMigrationCheckpointDatabase(e, t = {}) {
	assertOpenClawStateSchemaRepairAllowed(resolveDatabasePath(t));
	if (isStatePostgres()) return withEngineStoreAdmission(() => {
		const n = openOpenClawStateDatabase(t);
		try {
			return runOpenClawStateWriteTransaction(({ db: t }) => e(t), {
				...t,
				database: n
			});
		} finally {
			if (t.sealOnClose) openClawStateDatabaseCache.closeOpenClawStateDatabaseByPath(n.path);
		}
	});
	const n = getOpenClawStateDatabaseIfOpen(t);
	if (n && isPostgresSqlConnection(n.db)) requireNativeDatabaseFile("postgres", "repair");
	if (n && getAdmittedSqliteSchemaFacts(n.db)?.userVersion === 36) {
		const r = runOpenClawStateWriteTransaction(({ db: t }) => {
			if (isPostgresSqlConnection(t)) requireNativeDatabaseFile("postgres", "repair");
			return e(t);
		}, {
			env: t.env,
			path: n.path
		}, {
			operationLabel: "state.startup-checkpoint.write",
			singleStatement: t.singleStatement
		});
		if (t.sealOnClose) openClawStateDatabaseCache.closeOpenClawStateDatabaseByPath(n.path);
		return r;
	}
	return withOpenClawStateStartupCheckpointConnection(e, t, ensureOpenClawStateRuntimeSchema);
}
/** Complete native bootstrap without migrating mature shared state. */
function initializeNativeOpenClawStateDatabase(e = {}) {
	if (isStatePostgres()) requireNativeDatabaseFile("postgres", "repair");
	initializeNativeOpenClawStateConnection(e, (e, t, n, r) => ensureOpenClawStateRuntimeSchema(e, t, n, r, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, true));
}
/** Open existing shared state without creating, migrating, chmodding, or configuring it. */
async function openExistingOpenClawStateDatabaseReadOnly(e = {}) {
	const t = resolveDatabasePath(e);
	isExistingOpenClawStateSchema(t);
	if (!existsSync(t)) return;
	openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t, e.env ?? process.env);
	const n = isStatePostgres() ? t : await prepareSqliteReadOnlyLocation(t);
	const r = openOpenClawStateReadConnection(t, n);
	const { db: i } = r.database;
	try {
		if (isPostgresSqlConnection(i)) assertSupportedStateSchemaVersion(i, t);
		else if (isExistingOpenClawStateSchema(t, i) || e.requireCanonicalSchema) assertExistingOpenClawStateRuntimeSchema(i, t);
		else {
			assertSupportedStateSchemaVersion(i, t);
			assertSqliteIntegrity(i, t, { check: e.integrityCheck });
			if (readStateSchemaContentVersion(i) === 36) assertOpenClawStateDatabaseForMaintenance(i, { pathname: t });
		}
	} catch (e) {
		try {
			r.close();
		} catch {}
		throw e;
	}
	return readOnlyStateDatabase(r.database, r.close);
}
function readOnlyStateDatabase(e, t) {
	return {
		...e,
		walMaintenance: {
			checkpoint: () => false,
			stop: async () => {},
			reclaimFreePages: createSqliteWalReclamationResult,
			close: t
		}
	};
}
function openOpenClawStateDatabaseWithBusyTimeout(e = {}, t = OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, n = "report", r) {
	getOpenClawDatabaseMaintenanceScope()?.assertAdmission();
	const i = e.env ?? process.env;
	const a = e.database?.path ?? resolveDatabasePath(e);
	if (isArtifactPreservingStateRead("agent", a)) {
		assertStateFileSnapshotAllowed();
		openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(a, i);
		const e = openSqliteReadOnlyDatabase(a, { timeout: t });
		assertSupportedStateSchemaVersion(e, a);
		return readOnlyStateDatabase({
			db: e,
			path: a
		}, () => {
			e.close();
			return true;
		});
	}
	const o = !e.database && isExistingOpenClawStateSchema(a);
	const s = e.database ?? openClawStateDatabaseCache.getCachedOpenClawStateDatabase(a);
	if (s && (e.database || s.db.isOpen)) {
		if (!e.database) openClawStateDatabaseCache.assertOpenClawStateDatabaseOpenAllowed(a);
		assertStateDatabaseSchemaAdmission(s);
		assertOpenClawStateWriteAllowed({
			database: s.db,
			databasePath: a,
			env: i,
			schemaReady: openClawStateDatabaseCache.isOpenClawStateDatabaseSchemaReady(s)
		});
		observeOpenClawDatabaseMaintenanceResource(s.db);
		if (e.database) openClawStateDatabaseCache.touchStateDatabase(s);
		else if (!o && deferredStateDatabases.has(s.db)) {
			reconcileOpenClawStateSchemaPublication(e);
			if (getStateSchemaVersionAdmission(s.db)?.userVersion === 36) deferredStateDatabases.delete(s.db);
		}
		return s;
	}
	let c;
	try {
		const open = (t) => {
			getOpenClawDatabaseMaintenanceScope()?.assertAdmission();
			openClawStateDatabaseCache.assertOpenClawStateDatabaseOpenAllowed(a);
			openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(a, i);
			if (s) openClawStateDatabaseCache.closeStaleCachedOpenClawStateDatabase(s);
			return openUnpublishedStateDatabase({
				pathname: a,
				env: i,
				busyTimeoutMs: t(),
				lockFailureReporting: n,
				existingSchema: o,
				initializationAgentPaths: e.initializationAgentPaths,
				ensureSchema: (e, n) => ensureOpenClawStateRuntimeSchema(e, a, i, n, t()),
				recordOpenFailure: recordOpenClawStateDatabaseOpenFailure
			});
		};
		c = r ? open(r) : withStateDatabaseColdAdmission({
			databasePath: a,
			busyTimeoutMs: t
		}, open);
		if (!isPostgresSqlConnection(c.db)) setSqliteBusyTimeout(c.db, t);
	} catch (e) {
		if (n === "report" || !isOpenClawStateWriteContentionError(e)) openClawStateDatabaseCache.recordOpenClawStateDatabaseLifecycleOpenError(a, e);
		if (c) {
			const t = openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle(c);
			if (t.length > 0) throw createSqliteLifecycleAggregateError([e, ...t], `Fresh OpenClaw state database open failed releasing access and closing its unpublished handle for ${a}.`, e);
		}
		throw e;
	}
	if (o) recordExistingOpenClawStateSchemaDatabase(c.db, a);
	const l = openClawStateDatabaseCache.publishOpenClawStateDatabase(c, i);
	try {
		if (!o && readPublishedStateSchemaVersion(l.db) < 36) {
			deferredStateDatabases.add(l.db);
			reconcileOpenClawStateSchemaPublication(e);
		}
		return l;
	} catch (e) {
		if (l.db.isOpen && !isPostgresSqlConnection(l.db)) setSqliteBusyTimeout(l.db, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
		throw e;
	}
}
function openOpenClawStateDatabase(e = {}) {
	return openOpenClawStateDatabaseWithBusyTimeout(e);
}
/** The Gateway watcher also publishes without requiring a new physical database open. */
function reconcileOpenClawStateSchemaPublication(e = {}) {
	if (isExistingOpenClawStateSchema(e.database?.path ?? resolveDatabasePath(e))) return;
	const t = withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => {
		if (readPublishedStateSchemaVersion(e) >= 36 || readStateSchemaContentVersion(e) < 36) return;
		if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
		return { blocker: readStateSchemaPublicationBlocker(e) };
	}, e);
	if (!t || t.blocker) return t?.blocker;
	const n = resolveDatabasePath(e);
	try {
		return withStateDatabaseSchemaMaintenance({ databasePath: n }, () => runOpenClawStateWriteTransaction(({ db: e }) => {
			if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
			const t = readStateSchemaPublicationBlocker(e);
			if (t) return t;
			assertOpenClawStateDatabaseForMaintenance(e, { pathname: n });
			markCurrentStateSchemaVersion(e);
		}, e, { operationLabel: "state.schema.publish" }));
	} catch (e) {
		if (e instanceof StateSchemaMutationConflictError) return;
		throw e;
	}
}
/** Run one operation through the shared owner without waiting synchronously on SQLite locks. */
function runWithOpenClawStateBusyTimeout(e, t, n) {
	if (isArtifactPreservingStateRead("agent", t.database?.path ?? resolveDatabasePath(t))) return e(openOpenClawStateDatabaseWithBusyTimeout(t, n));
	getOpenClawDatabaseMaintenanceScope()?.assertAdmission();
	const r = normalizeSqliteNonNegativeInteger(n, "busyTimeoutMs");
	const i = t.database ?? getOpenClawStateDatabaseIfOpen(t);
	if (i) {
		assertStateDatabaseSchemaAdmission(i);
		const execute = () => {
			observeOpenClawDatabaseMaintenanceResource(i.db);
			openClawStateDatabaseCache.touchStateDatabase(i);
			return e(i);
		};
		if (isPostgresSqlConnection(i.db)) return execute();
		return runWithSqliteBusyTimeout(i.db, r, execute, { lockFailureReporting: "suppress" });
	}
	const a = openOpenClawStateDatabaseWithBusyTimeout(t, r, "suppress");
	try {
		if (isPostgresSqlConnection(a.db)) return e(a);
		return runWithSqliteBusyTimeout(a.db, r, () => e(a), { lockFailureReporting: "suppress" });
	} finally {
		if (a.db.isOpen && !isPostgresSqlConnection(a.db)) setSqliteBusyTimeout(a.db, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
	}
}
/** Run an admitted shared-state write; complete single statements may use autocommit. */
function runOpenClawStateWriteTransaction(e, t = {}, n = {}) {
	if (isArtifactPreservingStateRead("agent", t.database?.path ?? resolveDatabasePath(t))) throw new Error("Programming error: shared-state write during artifact-preserving inspection.");
	getOpenClawDatabaseMaintenanceScope()?.assertAdmission();
	const r = t.database ?? getOpenClawStateDatabaseIfOpen(t);
	if (r) {
		isExistingOpenClawStateSchema(r.path, r.db);
		if (t.database) assertStateDatabaseAccessAllowed(r.path);
	}
	let i = r;
	let a = false;
	let o;
	const execute = (r) => {
		const o = i ?? openOpenClawStateDatabaseWithBusyTimeout(t, 5e3, "report", r);
		i = o;
		return {
			database: o,
			value: runManagedStateTransaction(o.db, () => {
				assertStateDatabaseSchemaAdmission(o);
				if (!t.database) getOpenClawStateDatabaseIfOpen(t);
				assertOpenClawStateWriteAllowed({
					database: o.db,
					databasePath: o.path,
					env: t.env ?? process.env,
					schemaReady: openClawStateDatabaseCache.isOpenClawStateDatabaseSchemaReady(o)
				});
				observeOpenClawDatabaseMaintenanceResource(o.db);
				if (t.database) openClawStateDatabaseCache.touchStateDatabase(o);
				a = true;
				return e(o);
			}, {
				databaseLabel: o.path,
				...n,
				...r ? { busyTimeoutMs: r() } : {},
				operationLabel: n.operationLabel ?? captureSqliteReaderOwner()?.operation ?? "state.write"
			})
		};
	};
	try {
		o = r ? execute() : withStateDatabaseColdAdmission({
			databasePath: resolveDatabasePath(t),
			busyTimeoutMs: n.busyTimeoutMs ?? 5e3,
			canRetry() {
				if (a || i && (!i.db.isOpen || i.db.isTransaction)) return false;
				if (i) {
					assertTransactionUsable(i.db);
					if (!isPostgresSqlConnection(i.db)) invalidateSqliteSchemaFacts(i.db);
					openClawStateDatabaseCache.closeOpenClawStateDatabaseByPath(i.path);
					i = void 0;
				}
				return true;
			}
		}, execute);
	} catch (e) {
		if (i) openClawStateDatabaseCache.evictOpenClawStateDatabaseAfterCorruption(i, e);
		throw e;
	}
	try {
		if (!isExistingOpenClawStateSchema(o.database.path, o.database.db)) ensureOpenClawStatePermissions(o.database.path, t.env ?? process.env);
	} catch {}
	return o.value;
}
/**
* Return a shared state handle this process already holds open, if any.
*
* Read-only callers use this to avoid opening a connection per call; it never
* creates, repairs, or registers a handle.
*/
function getOpenClawStateDatabaseIfOpen(e = {}) {
	const t = resolveDatabasePath(e);
	isExistingOpenClawStateSchema(t);
	const n = openClawStateDatabaseCache.getCachedOpenClawStateDatabase(t);
	if (n?.db.isOpen) isExistingOpenClawStateSchema(n.path, n.db);
	return n?.db.isOpen ? n : void 0;
}
function assertStateDatabaseSchemaAdmission(e) {
	if (isExistingOpenClawStateSchema(e.path, e.db)) {
		const t = readTrackedStateDatabaseIdentity(e.db)?.canonicalPath;
		if (!t) throw new Error("Existing shared-state schema admission requires a filesystem-backed database.");
		if (!isExistingOpenClawStateSchema(t, e.db)) throw new Error("Existing shared-state schema admission requires its selected physical database.");
		if (isPostgresSqlConnection(e.db)) {
			assertSupportedStateSchemaVersion(e.db, e.path);
			return;
		}
		assertExistingOpenClawStateRuntimeSchema(e.db, e.path);
	}
}
//#endregion
export { formatSchemaMigrationFailure as C, SCHEMA_RECOVERY as S, resolveOpenClawAgentDatabaseDiscoveryPaths as T, hasPreJournalStateSchema as _, reconcileOpenClawStateSchemaPublication as a, repairCanonicalSqliteIndexes as b, repairOpenClawStateDatabaseSchema as c, withOpenClawStateStartupMigrationCheckpointDatabase as d, detectOpenClawStateDatabaseSchemaMigrations as f, assertGatewayServiceSchemaMigrationAllowed as g, resolveSchemaMigrationIntegrityCheck as h, prepareOpenClawStateDatabaseSchema as i, runOpenClawStateWriteTransaction as l, resolveSchemaMigrationBackupTables as m, openExistingOpenClawStateDatabaseReadOnly as n, repairOpenClawStateDatabaseIndexesForDoctor as o, assertOpenClawStateWriteAllowedAtPath as p, openOpenClawStateDatabase as r, repairOpenClawStateDatabaseReadabilityForDoctor as s, initializeNativeOpenClawStateDatabase as t, runWithOpenClawStateBusyTimeout as u, backupDoctorSqliteRepair as v, prepareStateDatabaseInitialization as w, verifyAndRepairCanonicalSqliteIndexSteps as x, repairDoctorSqliteIndexCorruption as y };