UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

36,117 lines • 1.02 MB
import { a as resolveIncludeRoots, c as hasErrnoCode, h as extractErrorCode, l as ignoreMissingPath, p as collectErrorGraphCandidates, t as resolveConfigPath } from "./paths-0xDagtub.mjs";
import { d as asOptionalRecord, l as asNullableRecord, p as isRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString, H as resolveGlobalMap, M as resolveNonNegativeIntegerOption, O as parseDateStringTimestampMs, T as asSafeIntegerInRange, W as resolveGlobalSingleton, _ as MAX_DATE_TIMESTAMP_MS$1, a as resolveStateDir, c as resolveProfileStateDir, d as resolveRequiredHomeDir, l as expandHomePrefix, p as resolveUserPath, v as MAX_TIMER_TIMEOUT_MS, w as asPositiveSafeInteger, y as asFiniteNumber, z as normalizeOptionalLowercaseString } from "./path-guards-quCEQx1i.mjs";
import { r as hasSqliteWorkerOutcomeUnknown, t as SqliteWorkerError } from "./sqlite-worker-error-Q7g0aE9t.mjs";
import { n as isSqliteLockError, t as isSqliteCorruptionError } from "./sqlite-error-diagnostics-DXQCgyiD.mjs";
import { i as isPidDefinitelyDead, t as getFileLockProcessStartTime } from "./pid-alive-TveEV-hP.mjs";
import { o as sleepWithAbort } from "./src-DIZdnDBl.mjs";
import { c as VERSION, i as readSqliteUserVersion, o as writeSqliteUserVersion, r as isSqliteSchemaVersionError, s as StartupMaintenanceRequiredError } from "./sqlite-user-version-D-rYjp-A.mjs";
import { a as LAZY_ADDITIVE_STATE_TABLES, i as LAZY_ADDITIVE_STATE_INDEXES, n as FIRST_USE_STATE_INDEXES, r as FIRST_USE_STATE_TABLES, s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, t as DOCTOR_OWNED_STATE_TABLES } from "./openclaw-state-db-contract-DpFGI8ZZ.mjs";
import { G as parseJsonWithJson5Fallback, J as pruneMapToMaxSize, M as parseSecretRef, O as resolveConfigEnvVars, P as DEFAULT_SECRET_PROVIDER_ALIAS, X as truncateUtf16Safe, f as hashConfigIncludeRaw, h as resolveConfigIncludes, l as groupPluginRecords, m as resolveConfigIncludeWritePath, p as readConfigIncludeFileWithGuards, r as redactSensitiveText, v as resolveIdentityPathViaExistingAncestorSync, w as openRootFileSync, y as resolvePathViaExistingAncestorSync$1 } from "./redact-BRF0hr6G.mjs";
import { I as artifactPreservingReads, L as isArtifactPreservingStateRead, N as sameFileStatFingerprint, P as hashFileDescriptorSync, R as withArtifactPreservingStateReads, T as retainSnapshotWork, c as runSqliteReadOnlyWorkerSync, j as assertPublishedFileIdentitySync, o as runSqliteReadOnlyOperation, w as retainSnapshotTempDirectory } from "./sqlite-snapshot-staging-owner-D6iplEEs.mjs";
import { t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { i as runInDetachedAsyncContext } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { d as getAsyncWorkSignal } from "./openclaw-root-l-fyeuXJ.mjs";
import { n as isPostgresSqlConnection, r as sqlPublicationAnchor, t as assertSyncTransactionResult } from "./sql-connection-VmV9pnJI.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { i as executeWithCachedStatement, r as enableNodeSqliteKyselyStatementCache } from "./kysely-sync-cache-state-D75yJYFp.mjs";
import { f as readDatabasePathIdentitySync, n as assertExistingDatabaseIdentity, p as resolveDatabasePathKey, r as databaseFileIdentityKey, t as assertDatabaseFileIdentity, u as readDatabaseIdentityBirthtime } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { a as resolveOpenClawStateDirForDatabasePath, c as warnAgentPathMigration, i as resolveOpenClawAgentDatabaseStoredPath, n as existingPathOrUndefined, o as resolveOpenClawStateSqlitePath, r as resolveDatabasePath, s as resolveQuarantineStorePath, t as describeAgentPathMigration } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { C as iterateSqliteQuerySync, S as getNodeSqliteKysely, _ as throwSqliteSchemaMismatches, a as tableHasColumn, b as executeSqliteQuerySync, c as createStateSchemaAdmission, d as publishStateRuntimeSchemaAdmission, f as publishStateSchemaVersionAdmission, g as legacySqliteSchemaIssueMessages, h as createSqliteSchemaIssue, i as tableExists, l as getStateRuntimeSchemaAdmission, m as SqliteSchemaMismatchError, n as ensureColumn, o as tablePrimaryKeyColumns, r as readTableColumns$1, s as adoptPeerPublishedStateSchemaVersion, t as classifySqliteTableReadError, u as getStateSchemaVersionAdmission, w as prepareSqliteQuerySync, x as executeSqliteQueryTakeFirstSync, y as createSqliteQueryCache } from "./openclaw-state-db-schema-helpers-Bn-sHIhd.mjs";
import { n as isTruthyEnvValue } from "./env-C62NiKTo.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { a as SqliteSnapshotCleanupError, c as createSqliteLifecycleAggregateError, i as SqliteCoordinatorError, l as runWithSqliteCleanup, n as OpenClawStateOwnershipError, r as OpenClawStateOwnershipMetadataError, t as OpenClawStateExternalOwnershipError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { B as STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS, Ct as stageSqliteTransactionState, G as findSqlCharacter, H as createSqliteTableContract, J as normalizeSchemaSql, K as findSqlClosingParenthesis, L as OPENCLAW_STATE_SCHEMA_SQL, Q as readSqlToken, St as prepareSqliteTransactionCommit, U as parseSqliteTableDefinition, V as createSqliteIndexContract, W as extractSqliteTableSchema, X as normalizeSqlWhitespace, Y as normalizeSqlIdentifier, Z as quoteSqliteIdentifier, _ as publishSqliteDatabaseAdmission, bt as discardSqliteTransactionState, d as invalidateLocalSqliteSchemaAdmissions, dt as ensureSqliteLibrarySelected, et as splitSqlList, ft as getSqliteRuntimeCapabilities, i as finishSqliteDatabaseWrite, nt as resolveSqliteDatabaseFilePath, o as getSqliteDatabaseAdmission, pt as captureSqliteReaderOwner, t as beginSqliteDatabaseWrite, v as publishSqliteDatabaseSchemaChange, wt as withSqlitePostCommitPublications, xt as hasSqlitePostCommitScope, y as readSqliteDatabaseCleanClose, yt as deferSqlitePostCommitPublication } from "./sqlite-database-admission-DMm34jqt.mjs";
import { a as setSqliteBusyTimeout, i as runWithSqliteBusyTimeout } from "./sqlite-busy-timeout-BbWQYMTz.mjs";
import { C as readPostgresSchema, D as admitPostgresSearch, E as withPostgresSearchExtensions, O as assertPostgresCatalog, S as postgresStoreNamespace, T as verifyPostgresSchema, _ as requireNativeDatabaseFile, b as postgresSchemaMetadataSql, c as runSqliteReadOperationSync, d as readSqliteSchemaObjects, g as getPostgresPhysicalFacts, h as admitPostgresPhysicalFacts, i as invalidateSqliteSchemaFacts, m as runSqliteSchemaReadSnapshotSync, n as beginPostgresReadSnapshotScope, p as getSqlitePinnedReadSnapshot, r as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema, u as captureSqliteSchemaFacts, v as admitPostgresCapabilities, w as verifyAndRecordPostgresSchema, x as postgresSchemaSql, y as getAdmittedPostgresSchema } from "./sqlite-schema-facts-BFHoBJFZ.mjs";
import { n as resolveExistingSqliteFileUri, r as resolveImmutableSqliteFileUri, t as openNodeSqliteDatabase } from "./node-sqlite-DrCtoYsd.mjs";
import { n as normalizeOpenClawStateSchemaReadError, t as OpenClawStateDatabaseSchemaMigrationRequiredError } from "./openclaw-state-db-schema-migration-required-wTocmCbq.mjs";
import { a as parseStateSchemaContentVersion, i as assertSupportedStateSchemaVersion, n as PostgresSchemaAdmissionUnavailableError, o as readStateSchemaContentVersion, r as admitStateSchemaFacts, t as CONTENT_VERSION_KEY } from "./openclaw-state-db-schema-version-86tJzspq.mjs";
import { t as sha256Hex } from "./node-crypto-CWAQhBWK.mjs";
import { p as sha256Base64Url } from "./gateway-process-argv-DB5Y-Mad.mjs";
import { $ as sameSqliteFileGeneration, C as invalidateOpenClawStateRuntimeIntegrity, Ct as projectUpdateRehearsalDatabaseConfig, D as openTrackedStateDatabase, E as isTerminalSqliteIntegrityError, Et as resolveSqliteDatabaseFilePaths, G as isGatewayExternallySupervised, H as recordExistingOpenClawStateSchemaDatabase, I as captureSqliteWorkerWalMaintenanceSuspension, J as assertEngineStoreExecutionAllowed, K as getGatewayServiceInstallation, L as getSqliteWorkerExistingDatabaseIdentity, M as migrateCronDefaultStoreIdentity, N as resolveCronIdentityMigrationDefaultStoreKey, O as openTrackedStateDatabaseResult, P as stateCronIdentityMigration, Q as readStableSqliteFileGeneration, R as getSqliteWorkerStateIntegrityAdmission, S as assertStateDatabaseIntegrityOnce, St as isUpdateRehearsalPrivateDatabase, T as assertSqliteTableIntegrity, Tt as quarantineOrphanedSqliteSidecars, U as jsonPathValue, V as isExistingOpenClawStateSchema, W as jsonValid, X as createSqliteFileGenerationReader, Y as getDatabaseProcessRole, Z as parseSqliteFileGeneration, _ as registerOpenClawStatePathAsyncResource, _t as normalizeSqliteNumber, at as captureSqlitePrivateSnapshotFamily, b as retainOpenClawStateDatabaseForIndependentRead, ct as acquireSqliteSnapshotReadToken, dt as registerSqliteCacheExitClose, et as serializeSqliteFileGeneration, f as openClawStateDatabaseCache, ft as createSqliteWalReclamationResult, g as registerOpenClawStateDatabaseLifecycleListener, gt as coerceRequiredSqliteNumber, h as registerOpenClawStateDatabaseAsyncResource, ht as truncateSqliteWal, i as captureOpenClawStateIntegrityAdmission, it as startSqliteReadOnlyLocationAsync, k as readTrackedStateDatabaseIdentity, lt as configureSqliteConnectionPragmas, m as recordOpenClawStateDatabaseOpenFailure, n as borrowOpenClawStateDatabaseForAsyncRead, nt as prepareSqliteReadOnlyLocationAwaited, ot as prepareSqliteReadOnlyLocationFromOwnedDatabase, pt as prepareSqliteDatabaseDirectory, q as SQLITE_IDLE_HANDLE_TTL_MS, r as captureOpenClawStateDatabaseReadAdmission, rt as prepareSqliteReadOnlyLocationSync, st as prepareSqliteReadOnlyLocationSyncInProcess, tt as openSqliteReadOnlyDatabase, ut as configureSqlitePreSchemaPragmas, v as requireOpenClawStateDatabaseIdentity, vt as applyConfigEnvVars, w as assertSqliteIntegrity, wt as SQLITE_SIDECAR_SUFFIXES, x as assertOpenClawStateRuntimeIntegrity, yt as cloneEnvWithPlatformSemantics } from "./openclaw-state-db-cache-D7C7Hg5y.mjs";
import "./runtime-process-entrypoints-EnWn_nGl.mjs";
import "./host-CAR9TGXT.mjs";
import "./runtime-worker-url-BEfqe_m6.mjs";
import { a as getPostgresPool, c as recordPostgresPoolFailure, h as captureRetainedNativeWorkerSource, l as getDatabaseEngineInput, m as resolveStateReadWorkerCount, n as createOwnedWorkerTaskPool, s as selectPostgresPoolService, u as getDatabaseEngineSelection, v as WorkerTaskError, y as DEFAULT_WORKER_PENDING_BYTES } from "./worker-task-pool-DBu8jMlX.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-sztU0Vcb.mjs";
import { p as captureRuntimeWorkerSource } from "./worker-cpu-sx0tpDpz.mjs";
import { f as resolveIncognitoOpenClawAgentSqlitePath, m as normalizeAgentId, p as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db-resources-TIBz7nIz.mjs";
import { i as allowsMaintenanceLiveAuthorityReads, s as getOpenClawDatabaseMaintenanceScope, t as StateDatabaseReadAdmissionInvalidatedError, u as observeOpenClawDatabaseMaintenanceResource } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import { r as recordWorkerMessage } from "./worker-message-metrics-DnNsI1Wf.mjs";
import { n as deriveCanonicalEd25519PublicKeyRaw, t as deriveCanonicalEd25519PrivateKeyRaw } from "./ed25519-signature-CQ3Kb-UR.mjs";
import { a as runSqliteImmediateTransactionSync, c as runSqliteSingleStatementSync, o as runSqliteReadSnapshotSync, r as runSqliteDeferredTransactionSync, t as assertTransactionUsable } from "./sqlite-transaction-DYxlAnZ2.mjs";
import { a as custom, c as looseObject, d as object, f as record, g as unknown, h as union, i as boolean, l as never, m as string, o as discriminatedUnion, r as array, s as literal$1, t as _enum, u as number } from "./schemas-DA6xYxQu.mjs";
import { _ as GatewayLockNamespaceError, b as classifyGatewayOwnerProcessNamespace, c as getStateDatabaseSchemaLease, d as resolveGatewayStateOwnerPath, g as applyPrivateModeSync, m as withStateDatabaseColdAdmission, n as acquireStateDatabaseSchemaLease, r as assertStateDatabaseAccessAllowed, u as prepareStateDatabaseReadAccess, v as GatewayProcessNamespaceSchema, x as parseGatewayLockPayload, y as MachineIdentitySchema } from "./gateway-state-owner-CW5kvbov.mjs";
import { a as StateDatabaseOfflineMaintenanceError, r as StateDatabaseAdmissionPendingError, t as GatewayStateOwnerContentionError } from "./gateway-state-owner-errors-ccLhqQIq.mjs";
import { n as hydrateOpenClawStateWorkerError, r as retainOpenClawStateWorkerErrorPayload } from "./openclaw-state-worker-error-Blekn2XA.mjs";
import { b as readSqliteDatabaseAdmissionDeadline, h as currentSqliteWorkerOperationAdmission, s as requestSqliteWorkerSchemaMaintenance, v as SqliteDatabaseAdmissionTimeoutError, x as withSqliteDatabaseAdmissionWait, y as assertSqliteDatabaseAdmissionWaitActive } from "./sqlite-worker-operation-admission-DjndFB3C.mjs";
import { a as acquireWithWait, i as acquireSqliteDatabaseAdmissionTurn, o as runPluginSharedStateWork } from "./openclaw-state-worker-store-CpJWs6Nu.mjs";
import { t as captureOpenClawStateReadWorkerContext } from "./openclaw-state-worker-context-GPo8ZZmA.mjs";
import { createRequire } from "node:module";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { isProxy } from "node:util/types";
import { spawn } from "node:child_process";
import fsSync, { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import crypto$1, { createHash, randomUUID } from "node:crypto";
import { assertDirectoryIdentitySync, createDirectorySync, createFileSync, sameFileIdentity } from "@openclaw/fs-safe/advanced";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import { stat } from "node:fs/promises";
import os, { hostname } from "node:os";
import { channel } from "node:diagnostics_channel";
import { performance as performance$1 } from "node:perf_hooks";
import { MessageChannel, getEnvironmentData, isMainThread, receiveMessageOnPort, threadId } from "node:worker_threads";
import { SqliteQueryCompiler, expressionBuilder, sql } from "kysely";
import { parse } from "semver";
import JSON5 from "json5";
import { serialize } from "node:v8";
import { EventEmitter } from "node:events";
import { inspectDarwinAcl } from "@openclaw/fs-safe/permissions";
import { Value } from "typebox/value";
import { Type } from "typebox";
//#region src/infra/postgres-sync/protocol.ts
/** Prepare bindings and mutation hints without interpreting quoted text as SQL. */
function preparePostgresQuery(e) {
	let t = "";
	let n = 0;
	let r = true;
	let i;
	let a;
	for (let o = 0; o < e.length;) {
		const s = e.slice(o);
		const c = /^(?:[eE]'(?:\\[\s\S]|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*(?:\n|$))/.exec(s);
		const l = /^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(s)?.[0];
		if (s.startsWith("/*")) {
			let n = o + 2;
			let r = 1;
			while (n < e.length && r > 0) if (e.startsWith("/*", n)) {
				r++;
				n += 2;
			} else if (e.startsWith("*/", n)) {
				r--;
				n += 2;
			} else n++;
			t += e.slice(o, n);
			o = n;
		} else if (l) {
			const n = e.indexOf(l, o + l.length);
			const a = n < 0 ? e.length : n + l.length;
			t += e.slice(o, a);
			o = a;
			i = void 0;
			r = false;
		} else if (c) {
			t += c[0];
			o += c[0].length;
			if (!c[0].startsWith("--")) {
				i = void 0;
				r = false;
			}
		} else {
			if (r && /^pragma\b/i.test(s)) throw new Error("The PostgreSQL engine does not support PRAGMA statements");
			const c = /^(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?/.exec(s)?.[0];
			if (c) {
				t += c;
				o += c.length;
				i = void 0;
				r = false;
				continue;
			}
			const l = /^[A-Za-z_][A-Za-z_0-9$]*/.exec(s)?.[0];
			if (l) {
				const e = l.toUpperCase();
				if (i !== "AS" && i !== ".") {
					if (e === "INTO" && i !== "INSERT" && i !== "MERGE") a = "unscoped";
					else if (a === void 0 && /^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e) && !(e === "UPDATE" && (i === "FOR" || i === "KEY"))) a = "scoped";
				}
				i = e;
				t += l;
				o += l.length;
				r = false;
				continue;
			}
			const u = e.charAt(o);
			if (!/\s/.test(u)) i = u;
			if (u === "?" && e[o + 1] === "?") {
				t += "?";
				o += 2;
			} else if (u === "?") {
				t += `$${++n}`;
				o++;
			} else {
				t += u;
				o++;
			}
			if (u === ";") r = true;
			else if (!/\s/.test(u)) r = false;
		}
	}
	return {
		sql: t,
		mutation: a
	};
}
function validatePostgresBindings(e) {
	for (const t of e) if (t !== null && typeof t !== "string" && typeof t !== "number" && typeof t !== "bigint" && !ArrayBuffer.isView(t)) throw new TypeError("SQL bindings must be null, numbers, bigints, strings, or ArrayBuffer views");
}
function decodePostgresRows(e, t) {
	return e.rows.map((n) => Object.fromEntries(e.fields.map((e) => {
		const r = n[e.name];
		let i;
		if (r === null) i = null;
		else if (e.dataTypeID === 20) {
			if (typeof r !== "string") throw new TypeError("PostgreSQL int8 results must be text");
			const e = BigInt(r);
			if (t) i = e;
			else {
				const t = Number(e);
				if (!Number.isSafeInteger(t)) throw new RangeError(`PostgreSQL int8 ${e} cannot be represented safely as a number`);
				i = t;
			}
		} else if (r instanceof Uint8Array) i = new Uint8Array(r);
		else if (typeof r === "boolean") i = Number(r);
		else if (typeof r === "string" || typeof r === "number" || typeof r === "bigint") i = r;
		else throw new TypeError(`Unsupported PostgreSQL result type for column ${e.name}`);
		return [e.name, i];
	})));
}
function isPostgresConnectionError(e) {
	return !e || e.startsWith("08") || /^57P0[123]$/.test(e);
}
const POSTGRES_QUERY_CANCELED_ERROR_NAME = "PostgresQueryCanceledError";
function decodePostgresError(e) {
	const t = Object.assign(new Error(e.message), e);
	if (e.code === "57014") t.name = POSTGRES_QUERY_CANCELED_ERROR_NAME;
	const n = {
		"23505": [2067, "UNIQUE"],
		"23503": [787, "FOREIGN KEY"],
		"23502": [1299, "NOT NULL"],
		"23514": [275, "CHECK"]
	}[e.code ?? ""];
	return n ? Object.assign(new Error(`${n[1]} constraint failed: ${e.constraint ?? e.column ?? "unknown"}`, { cause: t }), {
		code: "ERR_SQLITE_ERROR",
		errcode: n[0]
	}) : t;
}
//#endregion
//#region packages/normalization-core/src/json-coercion.ts
/** Parses JSON without throwing, returning undefined for invalid input. */
function safeParseJson(e) {
	try {
		return JSON.parse(e);
	} catch {
		return;
	}
}
/** Parses JSON into a non-array record, returning undefined for every other result. */
function safeParseJsonRecord(e) {
	return /^[\t\n\r ]*\{/.test(e) ? asOptionalRecord(safeParseJson(e)) : void 0;
}
//#endregion
//#region packages/normalization-core/src/stable-stringify.ts
const preserveString = (e) => e;
/** Deterministically stringifies values, optionally normalizing strings before key ordering. */
function stableStringify(e, t = preserveString) {
	return stringifyStableValue(e, /* @__PURE__ */ new WeakSet(), t);
}
function stringifyStableValue(e, t, n, r) {
	if (e === null || e === void 0) return String(e);
	if (typeof e === "number" && !Number.isFinite(e)) return JSON.stringify(String(e));
	if (typeof e === "bigint") return JSON.stringify(e.toString());
	if (typeof e === "string") return JSON.stringify(n(e));
	if (typeof e !== "object") return JSON.stringify(e) ?? "null";
	if (t.has(e)) return JSON.stringify("[Circular]");
	t.add(e);
	try {
		if (e instanceof Error) return stringifyStableValue({
			name: e.name,
			message: e.message,
			stack: e.stack
		}, t, n, r);
		if (e instanceof Uint8Array) return stringifyStableValue({
			type: "Uint8Array",
			data: encodeBase64(e)
		}, t, n, r);
		if (Array.isArray(e)) {
			if (r) {
				r("[");
				let i = "";
				for (const a of e) {
					r(i);
					r(stringifyStableValue(a, t, n, r));
					i = ",";
				}
				r("]");
				return "";
			}
			const i = [];
			for (const r of e) i.push(stringifyStableValue(r, t, n));
			return `[${i.join(",")}]`;
		}
		const i = e;
		const a = Object.keys(i);
		const o = n === preserveString ? a.sort() : a.map((e) => ({
			key: e,
			normalizedKey: n(e)
		})).sort((e, t) => {
			return compareStableStrings(e.normalizedKey, t.normalizedKey) || compareStableStrings(e.key, t.key);
		});
		r?.("{");
		const s = n === preserveString ? a : [];
		let c = "";
		let l = 0;
		for (const e of o) {
			const a = typeof e === "string" ? e : e.key;
			const o = `${JSON.stringify(typeof e === "string" ? e : e.normalizedKey)}:`;
			if (r) {
				r(`${c}${o}`);
				r(stringifyStableValue(i[a], t, n, r));
				c = ",";
			} else s[l++] = `${o}${stringifyStableValue(i[a], t, n)}`;
		}
		if (r) {
			r("}");
			return "";
		}
		return `{${s.join(",")}}`;
	} finally {
		t.delete(e);
	}
}
function encodeBase64(e) {
	let t = "";
	for (const n of e) t += String.fromCharCode(n);
	return btoa(t);
}
function compareStableStrings(e, t) {
	return e < t ? -1 : e > t ? 1 : 0;
}
//#endregion
//#region src/infra/database-engine/physical-store.ts
/** Source opens and closes stay in a child to preserve the caller's live POSIX locks. */
function readBackupEngine(e) {
	return runSqliteReadOnlyWorkerSync(e, void 0, isArtifactPreservingStateRead("shared", e) ? "backup-engine-preserving" : "backup-engine");
}
//#endregion
//#region src/config/legacy-workboard-database.ts
const log$1 = createSubsystemLogger("config");
function normalizeLegacyWorkboardDatabaseConfig(e, t) {
	if (!isRecord(e) || !isRecord(e.database)) return e;
	const n = e.database;
	if (resolveConfigEnvVars(n.engine, t) !== "postgres" || n.families !== void 0) return e;
	const r = resolveStateDir(t);
	const i = path.join(r, "state/openclaw.sqlite");
	const a = path.join(r, "plugins/workboard/workboard.sqlite");
	if (!fsSync.existsSync(i) || !fsSync.existsSync(a)) return e;
	if (!runSqliteReadOnlyWorkerSync(i, void 0, "state-sqlite-populated") || readBackupEngine(a).engine !== "postgres") return e;
	log$1.warn("Preserving the 2026.11.1 Workboard-only PostgreSQL setting: Workboard remains on PostgreSQL; shared state and other families remain on SQLite. The next config write records this explicitly.");
	return {
		...e,
		database: {
			...n,
			engine: "sqlite",
			families: { workboard: { engine: "postgres" } }
		}
	};
}
//#endregion
//#region src/config/resolution-facts.ts
const configResolutionFacts = /* @__PURE__ */ new WeakMap();
const envSecretRefsByFacts = /* @__PURE__ */ new WeakMap();
function createConfigResolutionFacts(e, t = /* @__PURE__ */ new Map(), n = DEFAULT_SECRET_PROVIDER_ALIAS, r = /* @__PURE__ */ new Map()) {
	const i = new Set(e.map(({ configPath: e }) => e));
	const a = n?.trim() || "default";
	if (t.size > 0 || r.size > 0) {
		const e = /* @__PURE__ */ new Map();
		for (const [n, i] of [["pending", t], ["resolved", r]]) for (const [t, r] of i) e.set(t, {
			ref: {
				source: "env",
				provider: a,
				id: r
			},
			state: n
		});
		envSecretRefsByFacts.set(i, e);
	}
	return i;
}
function setConfigResolutionFacts(e, t) {
	if (!e || typeof e !== "object") return;
	if (t === null) {
		configResolutionFacts.delete(e);
		return;
	}
	configResolutionFacts.set(e, t);
}
function getConfigResolutionFacts(e) {
	return e && typeof e === "object" ? configResolutionFacts.get(e) ?? null : null;
}
function copyConfigResolutionFacts(e, t) {
	setConfigResolutionFacts(t, getConfigResolutionFacts(e));
}
function cloneConfigWithResolutionFacts(e) {
	const t = structuredClone(e);
	copyConfigResolutionFacts(e, t);
	return t;
}
function copyConfigResolutionFactsExcept(e, t, n) {
	applyConfigResolutionFactsExcept(getConfigResolutionFacts(e), t, n);
}
function applyConfigResolutionFactsExcept(e, t, n) {
	if (e === null) {
		setConfigResolutionFacts(t, null);
		return;
	}
	const r = envSecretRefsByFacts.get(e);
	if (!n.some((t) => e.has(t) || r?.has(t) === true)) {
		setConfigResolutionFacts(t, e);
		return;
	}
	const i = new Set(e);
	n.forEach((e) => i.delete(e));
	if (r) {
		const e = new Map(r);
		n.forEach((t) => e.delete(t));
		if (e.size > 0) envSecretRefsByFacts.set(i, e);
	}
	setConfigResolutionFacts(t, i);
}
function hasUnresolvedConfigPath(e, t) {
	return getConfigResolutionFacts(e)?.has(t) === true;
}
/** Returns only a still-pending reference recorded from the authored config source. */
function getAuthoredConfigSecretRef(e, t) {
	const n = getConfigResolutionFacts(e);
	const r = n ? envSecretRefsByFacts.get(n)?.get(t) : void 0;
	return r?.state === "pending" ? r.ref : null;
}
/** Returns the env source of a value that config substitution already materialized. */
function getResolvedConfigEnvSecretRef(e, t) {
	const n = getConfigResolutionFacts(e);
	const r = n ? envSecretRefsByFacts.get(n)?.get(t) : void 0;
	return r?.state === "resolved" ? r.ref : null;
}
/** Reads inline references from authored facts and structured references from their values. */
function resolveConfigSecretRef(e) {
	return typeof e.value === "string" && getConfigResolutionFacts(e.config) !== null ? getAuthoredConfigSecretRef(e.config, e.path) ?? (e.includeResolved ? getResolvedConfigEnvSecretRef(e.config, e.path) : null) : parseSecretRef(e.value, e.defaults);
}
//#endregion
//#region src/config/io.read-helpers.ts
function coerceConfig(e) {
	return asOptionalRecord(e) ?? {};
}
function normalizeConfigIoDeps(e = {}) {
	const t = e.env ?? process.env;
	return {
		fs: e.fs ?? fsSync,
		env: t,
		lowerPrecedenceEnv: e.lowerPrecedenceEnv ?? {},
		homedir: e.homedir ?? (() => resolveRequiredHomeDir(t, os.homedir)),
		configPath: e.configPath ?? "",
		mapIncludePath: e.mapIncludePath ?? ((e) => e),
		logger: e.logger ?? console,
		measure: e.measure ?? (async (e, t) => await t()),
		suppressFutureVersionWarning: e.suppressFutureVersionWarning ?? (isTruthyEnvValue(t.OPENCLAW_UPDATE_IN_PROGRESS) || isTruthyEnvValue(t.OPENCLAW_UPDATE_POST_CORE)),
		observe: e.observe ?? true
	};
}
function parseConfigJson5(e) {
	try {
		return {
			ok: true,
			parsed: parseJsonWithJson5Fallback(e, JSON5)
		};
	} catch (e) {
		return {
			ok: false,
			error: String(e)
		};
	}
}
function resolveConfigIncludesForRead(e, t, n, r, i, a, o) {
	const s = resolveIncludeRoots(n.env, n.homedir);
	const recordIncludeWatchPath = (e) => {
		a?.add(path.normalize(e));
	};
	const recordIncludeTarget = (e, n) => {
		if (!i) return;
		const r = path.normalize(e);
		try {
			i[r] = path.normalize(n ?? resolveConfigIncludeWritePath({
				configPath: t,
				includePath: e,
				allowedRoots: s
			}));
		} catch {}
	};
	return resolveConfigIncludes(e, t, {
		readFile: (e) => n.fs.readFileSync(e, "utf-8"),
		mapPath: n.mapIncludePath,
		onLexicalPath: recordIncludeWatchPath,
		onIncludeResolved: o,
		readFileWithGuards: ({ includePath: e, resolvedPath: t, rootRealDir: i }) => {
			try {
				const a = readConfigIncludeFileWithGuards({
					includePath: e,
					resolvedPath: t,
					rootRealDir: i,
					ioFs: n.fs,
					onResolvedPath: (e) => {
						recordIncludeWatchPath(e);
						recordIncludeTarget(t, e);
					}
				});
				if (r) r[path.normalize(t)] = hashConfigIncludeRaw(a);
				return a;
			} catch (e) {
				const n = collectErrorGraphCandidates(e, (e) => [e.cause]).some((e) => extractErrorCode(e) === "ENOENT");
				if (r && n) r[path.normalize(t)] = hashConfigIncludeRaw(null);
				if (n) recordIncludeTarget(t);
				throw e;
			}
		},
		parseJson: (e) => JSON5.parse(e)
	}, { allowedRoots: s });
}
function resolveConfigForRead(e, t, n = {}) {
	if (e && typeof e === "object" && "env" in e) applyConfigEnvVars(e, t, { lowerPrecedenceEnv: n });
	const r = [];
	const i = /* @__PURE__ */ new Map();
	const a = /* @__PURE__ */ new Map();
	const o = resolveConfigEnvVars(e, t, {
		onMissing: (e) => r.push(e),
		onPendingEnvSecretRef: (e, t) => i.set(t, e),
		onResolvedEnvSecretRef: (e, t) => a.set(t, e)
	});
	return {
		resolvedConfigRaw: normalizeLegacyWorkboardDatabaseConfig(projectUpdateRehearsalDatabaseConfig(o, t), t),
		envSnapshotForRestore: cloneEnvWithPlatformSemantics(t),
		envWarnings: r,
		resolutionFacts: createConfigResolutionFacts(r, i, coerceConfig(o).secrets?.defaults?.env, a)
	};
}
//#endregion
//#region src/shared/immutable-data.ts
const MAX_FROZEN_PLAIN_DATA_ADMISSIONS = 262144;
let deeplyFrozenPlainData = /* @__PURE__ */ new WeakSet();
let frozenPlainDataAdmissions = 0;
function boundFrozenPlainData(e) {
	if (frozenPlainDataAdmissions > MAX_FROZEN_PLAIN_DATA_ADMISSIONS) {
		deeplyFrozenPlainData = new WeakSet([e]);
		frozenPlainDataAdmissions = 1;
	}
}
function isPlainDataObject(e) {
	if (isProxy(e)) return false;
	const t = Object.getPrototypeOf(e);
	return t === null || t === Object.prototype || Array.isArray(e) && t === Array.prototype;
}
function inspectPlainData(e, t, n = true) {
	if (!e || typeof e !== "object") return typeof e !== "function";
	if (deeplyFrozenPlainData.has(e)) return true;
	if (!t && n && (isProxy(e) || !Object.isFrozen(e))) return false;
	let r = true;
	const i = /* @__PURE__ */ new Set();
	const a = [e];
	while (a.length) {
		const e = a.pop();
		if (i.has(e)) continue;
		if (!isPlainDataObject(e)) {
			if (!t) return false;
			r = false;
			continue;
		}
		if (!t && n && !Object.isFrozen(e)) return false;
		i.add(e);
		for (const n of Reflect.ownKeys(e)) {
			const i = Object.getOwnPropertyDescriptor(e, n);
			const o = i.value;
			if (!("value" in i) || typeof o === "function") {
				if (!t) return false;
				r = false;
				continue;
			}
			if (o && typeof o === "object" && !deeplyFrozenPlainData.has(o)) a.push(o);
		}
		if (t) Object.freeze(e);
	}
	if (r && (t || n)) {
		for (const e of i) deeplyFrozenPlainData.add(e);
		frozenPlainDataAdmissions += i.size;
		boundFrozenPlainData(e);
	}
	return r;
}
/** Memoized proofs use weak keys and can be evicted without changing graph immutability. */
function isDeeplyFrozenPlainData(e) {
	return inspectPlainData(e, false);
}
/** Freeze an owner's cloned JSON snapshot without executing opaque members. */
function freezeJsonSnapshot(e) {
	inspectPlainData(e, true);
	return e;
}
//#endregion
//#region src/config/runtime-config-publication.ts
/** The runtime config owner publishes identity facts before notifying consumers. */
const runtimeConfigPublication = {};
//#endregion
//#region src/infra/client-credential-paths.ts
/** Local inventory must resolve this family without loading its credential writer. */
function resolveClientCredentialStorePath(e) {
	return path.join(resolveStateDir(e), "client", "credentials.sqlite");
}
/** Only the canonical shared file owns the native client's local companion. */
function resolveStateClientCredentialEnvironment(e) {
	const t = resolveDatabasePath({ path: e.path });
	const n = {
		...e.env,
		OPENCLAW_STATE_DIR: resolveOpenClawStateDirForDatabasePath(t)
	};
	return t === resolveOpenClawStateSqlitePath(n) ? n : void 0;
}
//#endregion
//#region src/infra/device-identity-material.ts
const PRIMARY_DEVICE_IDENTITY_KEY = "primary";
var DeviceIdentityStorageError = class extends Error {
	constructor(e, t) {
		super(e, t);
		this.name = "DeviceIdentityStorageError";
	}
};
function normalizeIdentityKey(e) {
	const t = e ?? PRIMARY_DEVICE_IDENTITY_KEY;
	if (t.length === 0 || t !== t.trim()) throw new DeviceIdentityStorageError("Device identity key must be a non-empty string without surrounding whitespace.");
	if (t.length > 128) throw new DeviceIdentityStorageError("Device identity key exceeds 128 characters.");
	return t;
}
function invalidStoredIdentityError(e, t) {
	return new DeviceIdentityStorageError(`SQLite contains an invalid persisted device identity "${e}". Run "openclaw doctor --fix" before starting the gateway or connecting this client.`, t === void 0 ? void 0 : { cause: t });
}
function fingerprintPublicKey(e) {
	const t = deriveCanonicalEd25519PublicKeyRaw(e);
	return crypto$1.createHash("sha256").update(t).digest("hex");
}
/** Generate canonical Ed25519 material before entering a synchronous write transaction. */
function generateStoredDeviceIdentity(e = Date.now()) {
	const { publicKey: t, privateKey: n } = crypto$1.generateKeyPairSync("ed25519");
	const r = t.export({
		type: "spki",
		format: "pem"
	});
	const i = n.export({
		type: "pkcs8",
		format: "pem"
	});
	return {
		deviceId: fingerprintPublicKey(r),
		publicKeyPem: r,
		privateKeyPem: i,
		createdAtMs: e
	};
}
function keyPairMatches(e, t) {
	try {
		deriveCanonicalEd25519PublicKeyRaw(e);
		deriveCanonicalEd25519PrivateKeyRaw(t);
		return crypto$1.createPublicKey(t).export({
			type: "spki",
			format: "pem"
		}) === e;
	} catch {
		return false;
	}
}
function parseCreatedAtMs(e) {
	return asSafeIntegerInRange(e, { min: 0 }) ?? null;
}
/** Validate persisted key material and return the canonical runtime shape. */
function validateStoredDeviceIdentity(e, t = PRIMARY_DEVICE_IDENTITY_KEY) {
	try {
		if (!e.deviceId || !/^[a-f0-9]{64}$/.test(e.deviceId) || !e.publicKeyPem || !e.privateKeyPem || parseCreatedAtMs(e.createdAtMs) === null || !keyPairMatches(e.publicKeyPem, e.privateKeyPem)) throw invalidStoredIdentityError(t);
		if (fingerprintPublicKey(e.publicKeyPem) !== e.deviceId) throw invalidStoredIdentityError(t);
		return {
			deviceId: e.deviceId,
			publicKeyPem: e.publicKeyPem,
			privateKeyPem: e.privateKeyPem
		};
	} catch (e) {
		if (e instanceof DeviceIdentityStorageError) throw e;
		throw invalidStoredIdentityError(t, e);
	}
}
function storedDeviceIdentityFromRow(e, t) {
	if (e.identity_key !== t || typeof e.device_id !== "string" || typeof e.public_key_pem !== "string" || typeof e.private_key_pem !== "string" || parseCreatedAtMs(e.created_at_ms) === null || parseCreatedAtMs(e.updated_at_ms) === null) throw invalidStoredIdentityError(t);
	const n = {
		deviceId: e.device_id,
		publicKeyPem: e.public_key_pem,
		privateKeyPem: e.private_key_pem,
		createdAtMs: e.created_at_ms
	};
	validateStoredDeviceIdentity(n, t);
	return n;
}
function salvageStoredIdentityRow(e, t, n) {
	if (e.identity_key !== t || typeof e.public_key_pem !== "string" || typeof e.private_key_pem !== "string") return null;
	try {
		const r = crypto$1.createPublicKey(e.public_key_pem);
		const i = crypto$1.createPrivateKey(e.private_key_pem);
		if (r.asymmetricKeyType !== "ed25519" || i.asymmetricKeyType !== "ed25519") return null;
		const a = r.export({
			type: "spki",
			format: "pem"
		});
		const o = i.export({
			type: "pkcs8",
			format: "pem"
		});
		if (crypto$1.createPublicKey(o).export({
			type: "spki",
			format: "pem"
		}) !== a) return null;
		const s = parseCreatedAtMs(e.created_at_ms) ?? parseCreatedAtMs(e.updated_at_ms) ?? n;
		const c = {
			deviceId: fingerprintPublicKey(a),
			publicKeyPem: a,
			privateKeyPem: o,
			createdAtMs: s
		};
		validateStoredDeviceIdentity(c, t);
		return c;
	} catch {
		return null;
	}
}
function storedDeviceIdentityToRow(e, t, n = t.createdAtMs) {
	return {
		identity_key: e,
		device_id: t.deviceId,
		public_key_pem: t.publicKeyPem,
		private_key_pem: t.privateKeyPem,
		created_at_ms: t.createdAtMs,
		updated_at_ms: n
	};
}
function identityFromCredentialResult(e) {
	if (e.kind !== "identity") throw new Error("Client credential owner returned an unexpected identity result.");
	const t = e.identity;
	return t ? {
		deviceId: t.device_id,
		publicKeyPem: t.public_key_pem,
		privateKeyPem: t.private_key_pem,
		createdAtMs: t.created_at_ms
	} : null;
}
//#endregion
//#region src/config/model-policy-allowlist-migration.ts
/** A per-agent policy replaces inherited defaults only when it owns `allow`. */
function hasExplicitModelPolicyAllow(e) {
	return isRecord(e) && Object.hasOwn(e, "allow");
}
//#endregion
//#region packages/session-url-contract/src/share.ts
const CONTROL_UI_RESERVED_ROUTE_SEGMENTS = Object.freeze([
	"activity",
	"ai-agents",
	"appearance",
	"approve",
	"apps",
	"ask",
	"automation",
	"automations",
	"channels",
	"chat",
	"templates",
	"communications",
	"config",
	"cron",
	"custodian",
	"dashboard",
	"dashboards",
	"debug",
	"focus",
	"infrastructure",
	"lobsterdex",
	"logs",
	"mcp",
	"meetings",
	"memory-import",
	"model-providers",
	"model-setup",
	"new",
	"nodes",
	"plugin",
	"plugins",
	"portals",
	"profile",
	"sessions",
	"settings",
	"share",
	"skills",
	"systems",
	"terminal",
	"usage",
	"workboard",
	"worktrees"
]);
//#endregion
//#region src/routing/session-key.ts
/** Legacy on-disk identity used only by doctor/migration and their fixtures. */
const LEGACY_IMPLICIT_AGENT_ID = "main";
//#endregion
//#region src/system-agent/agent-id.ts
const SYSTEM_AGENT_ID = "openclaw";
const SYSTEM_AGENT_ROSTER_ENTRIES = [{
	id: SYSTEM_AGENT_ID,
	kind: "system"
}, {
	id: "crestodian",
	kind: "system"
}];
const RESERVED_SYSTEM_AGENT_IDS = new Set(SYSTEM_AGENT_ROSTER_ENTRIES.map((e) => normalizeAgentId(e.id)));
//#endregion
//#region src/agents/agent-roster.ts
let activeAgentRosterFactsBatch;
const agentRosterFacts = /* @__PURE__ */ new WeakMap();
function readAgentRosterFacts(e) {
	if (activeAgentRosterFactsBatch?.config === e) return activeAgentRosterFactsBatch.facts;
	const t = runtimeConfigPublication.current;
	const n = t?.config === e ? t.revision : void 0;
	if (n === void 0 && !isDeeplyFrozenPlainData(e)) return;
	let r = agentRosterFacts.get(e);
	if (!r || r.publication !== n) {
		r = {
			publication: n,
			facts: {}
		};
		agentRosterFacts.set(e, r);
	}
	return r.facts;
}
function collectAgentEntries(e, t, n) {
	const r = readAgentRosterProperty(e);
	if (r?.kind === "entries" && isRecord(r.value)) {
		const e = [];
		for (const i in r.value) {
			if (!Object.hasOwn(r.value, i)) continue;
			const a = r.value[i];
			if (isRecord(a)) {
				const r = {
					...a,
					id: i
				};
				e.push(t ? {
					entry: r,
					source: {
						kind: "entries",
						key: i
					}
				} : r);
				if (e.length === n) break;
			}
		}
		return e;
	}
	if (r?.kind !== "list" || !Array.isArray(r.value)) return [];
	const i = [];
	r.value.some((e, t) => {
		if (e !== null && typeof e === "object") i.push({
			entry: e,
			source: {
				kind: "list",
				index: t
			}
		});
		return i.length === n;
	});
	return t ? i : i.map(({ entry: e }) => e);
}
/** Lists valid configured agent entries from config. */
function listAgentEntriesWithSource(e) {
	return collectAgentEntries(e, true);
}
/** Lists valid configured agent entries from either supported representation. */
function listAgentEntries(e) {
	return collectAgentEntries(e, false);
}
/** Reads the explicitly owned raw roster without normalizing malformed values. */
function readAgentRosterProperty(e) {
	if (!isRecord(e)) return;
	const t = e.agents;
	if (!isRecord(t)) return;
	for (const e of ["entries", "list"]) {
		const n = t[e];
		if (Object.hasOwn(t, e) && n !== void 0) return {
			kind: e,
			value: n
		};
	}
}
/** True when raw config explicitly owns either supported roster representation. */
function hasAgentRosterProperty(e) {
	return readAgentRosterProperty(e) !== void 0;
}
/** Lists unique configured agent ids. */
function listAgentIds(e) {
	const t = readAgentRosterFacts(e);
	if (t?.agentIds) return t.agentIds;
	const n = listAgentEntries(e);
	const r = n.length === 0 && !hasAgentRosterProperty(e) ? [LEGACY_IMPLICIT_AGENT_ID] : [...new Set(n.map((e) => normalizeAgentId(e?.id)))];
	if (t) {
		Object.freeze(r);
		t.agentIds = r;
	}
	return r;
}
function tryResolveSoleAgentId(e) {
	const t = collectAgentEntries(e, false, 2);
	if (t.length === 0) {
		if (!hasAgentRosterProperty(e)) return LEGACY_IMPLICIT_AGENT_ID;
		return;
	}
	return t.length === 1 ? normalizeAgentId(t[0].id) : void 0;
}
function tryResolveRawLegacyDefaultAgentId(e) {
	if (e.agents?.ownership === "explicit") return;
	const t = collectAgentEntries(e, false).filter((e) => e.default === true);
	return t.length === 1 ? normalizeAgentId(t[0].id) : void 0;
}
/** @deprecated Use tryResolveSoleAgentId; accepts raw shipped markers only for input compatibility. */
function tryResolveDefaultAgentId(e) {
	return tryResolveRawLegacyDefaultAgentId(e) ?? tryResolveSoleAgentId(e);
}
/** Preserves legacy data locators independently of the configured runtime owner. */
function tryResolveLegacyDataOwner(e) {
	return tryResolveDefaultAgentId(e);
}
//#endregion
//#region src/config/sessions/session-sqlite-target-paths.ts
const MULTI_STORE_PATH_SENTINEL = "(multiple)";
function resolveConcreteSessionStorePath(e) {
	const t = e?.trim();
	if (!t || t === "(multiple)" || t.includes("{agentId}")) return;
	return t;
}
/** Resolves only the legacy unsuffixed target, without reading ownership state. */
function resolveUnsuffixedSqliteTargetFromSessionStorePath(e) {
	const t = resolveConcreteSessionStorePath(e);
	if (!t) throw new Error("Session storage requires a concrete store path");
	const n = path.resolve(t);
	if (n.endsWith(".sqlite")) {
		const e = resolveAgentIdFromSqliteDatabasePath(n);
		return {
			path: n,
			...e ? { agentId: e } : { shared: true }
		};
	}
	const r = path.dirname(n);
	if (path.basename(n) !== "sessions.json") {
		const e = path.basename(n, path.extname(n)) || "openclaw-agent";
		return { path: path.join(r, `${e}.sqlite`) };
	}
	if (path.basename(r) !== "sessions") return { path: path.join(r, "openclaw-agent.sqlite") };
	const i = path.dirname(r);
	if (path.basename(path.dirname(i)) !== "agents") return { path: path.join(r, "openclaw-agent.sqlite") };
	return {
		agentId: normalizeAgentId(path.basename(i)),
		path: path.join(i, "agent", "openclaw-agent.sqlite")
	};
}
/** List inspection candidates without opening stores or assigning writable ownership. */
function listSqliteTargetCandidatePathsForSessionStorePath(e, t) {
	const n = resolveUnsuffixedSqliteTargetFromSessionStorePath(e);
	if (n.agentId || n.shared) return [n.path];
	const r = path.dirname(n.path);
	const i = path.basename(n.path, ".sqlite");
	const a = t ? `${i}.${normalizeAgentId(t)}` : void 0;
	const o = /* @__PURE__ */ new Set([path.basename(n.path)]);
	try {
		for (const e of readdirSync(r)) {
			const t = e.replace(/-(?:wal|shm|journal)$/u, "");
			if (t.startsWith(`${i}.`) && t.endsWith(".sqlite") && (!a || parseSqliteTargetSuffixIndex(t, a) !== void 0)) o.add(t);
		}
	} catch (e) {
		ignoreMissingPath(e);
	}
	return [...o].map((e) => path.join(r, e));
}
function parseSqliteTargetSuffixIndex(e, t) {
	if (e === `${t}.sqlite`) return 1;
	if (!e.startsWith(`${t}.`) || !e.endsWith(".sqlite")) return;
	const n = e.slice(t.length + 1, -7);
	if (!/^[1-9]\d*$/.test(n)) return;
	const r = Number(n);
	return Number.isSafeInteger(r) && r >= 2 && String(r) === n ? r : void 0;
}
/** Extracts the agent id from the canonical per-agent SQLite database path. */
function resolveAgentIdFromSqliteDatabasePath(e) {
	if (path.basename(e) !== "openclaw-agent.sqlite") return;
	const t = path.dirname(e);
	if (path.basename(t) !== "agent") return;
	const n = path.dirname(t);
	if (path.basename(path.dirname(n)) !== "agents") return;
	return normalizeAgentId(path.basename(n));
}
//#endregion
//#region src/config/sessions/paths.ts
function resolveSessionTranscriptsDirForAgent(e, t = process.env, n = () => resolveRequiredHomeDir(t, os.homedir)) {
	if (!e?.trim()) throw new Error("Session storage path requires an explicit agent id.");
	const r = resolveStateDir(t, n);
	const i = normalizeAgentId(e);
	return path.join(r, "agents", i, "sessions");
}
var SessionStoreAgentIdRequiredError = class extends Error {
	constructor() {
		super("Session store path requires an explicit agent id.");
		this.name = "SessionStoreAgentIdRequiredError";
	}
};
/** Resolves fixed literal paths without an owner; derived or templated paths require agentId. */
function resolveSessionStorePathCore(e, t) {
	const n = t?.env ?? process.env;
	const homedir = () => resolveRequiredHomeDir(n, os.homedir);
	if (!e) {
		if (!t?.agentId?.trim()) throw new SessionStoreAgentIdRequiredError();
		const e = normalizeAgentId(t.agentId);
		return path.join(resolveSessionTranscriptsDirForAgent(e, n, homedir), "sessions.json");
	}
	let r = e;
	if (r.includes("{agentId}")) {
		if (!t?.agentId?.trim()) throw new SessionStoreAgentIdRequiredError();
		const e = normalizeAgentId(t.agentId);
		r = r.replaceAll("{agentId}", e);
	}
	if (r.startsWith("~")) r = expandHomePrefix(r, {
		home: resolveRequiredHomeDir(n, homedir),
		env: n,
		homedir
	});
	return path.isAbsolute(r) ? path.resolve(r) : path.resolve(resolveStateDir(n, homedir), r);
}
//#endregion
//#region src/agents/agent-dir-registry.ts
const preparedPaths = resolveGlobalMap(Symbol.for("openclaw.agentDirPreparedPaths"), (e) => {
	for (const t of e.values()) t.close();
	e.clear();
}, "shared-state");
//#endregion
//#region src/agents/workspace-default-path.ts
function resolveDefaultAgentWorkspaceDir(e = process.env, t = os.homedir) {
	const n = e.OPENCLAW_WORKSPACE_DIR?.trim();
	if (n) return path.resolve(n);
	if (e.OPENCLAW_STATE_DIR?.trim()) return path.join(resolveStateDir(e, t), "workspace");
	const r = resolveRequiredHomeDir(e, t);
	const i = e.OPENCLAW_PROFILE?.trim();
	if (i && normalizeOptionalLowercaseString(i) !== "default") return path.join(resolveProfileStateDir(i, e, t), "workspace");
	return path.join(r, ".openclaw", "workspace");
}
//#endregion
//#region src/agents/workspace-default.ts
/** Default agent workspace directory for the current process environment. */
const DEFAULT_AGENT_WORKSPACE_DIR = resolveDefaultAgentWorkspaceDir();
//#endregion
//#region src/agents/agent-scope-config.ts
/** Resolves configured agent ids, directories, workspaces, and merged agent defaults. */
/** Strip null bytes from paths to prevent ENOTDIR errors. */
function stripNullBytes(e) {
	return e.replaceAll("\0", "");
}
/** Preserves legacy data locators independently of the configured runtime owner. */
function tryResolveLegacyDataOwnerAgentId(e) {
	const t = readAgentRosterFacts(e);
	if (t?.legacyDataOwnerAgentId) return t.legacyDataOwnerAgentId.value;
	const n = tryResolveLegacyDataOwner(e);
	if (t) t.legacyDataOwnerAgentId = { value: n };
	return n;
}
function resolveAgentEntry(e, t) {
	const n = normalizeAgentId(t);
	const r = readAgentRosterFacts(e);
	if (r) {
		const t = (r.entryByNormalizedId ??= buildAgentEntryIndex(e)).get(n);
		return t ? t.clone ? { ...t.entry } : t.entry : void 0;
	}
	const i = readAgentRosterProperty(e);
	if (i?.kind === "entries" && isRecord(i.value)) {
		const e = i.value;
		for (const t in e) {
			if (!Object.hasOwn(e, t)) continue;
			const r = e[t];
			if (isRecord(r) && normalizeAgentId(t) === n) return {
				...r,
				id: t
			};
		}
		return;
	}
	if (i?.kind === "list" && Array.isArray(i.value)) return i.value.find((e) => e !== null && typeof e === "object" && normalizeAgentId(e.id) === n);
}
/**
* First-match index over the projected roster for batch point lookups.
*
* Keyed entries must stay clone-on-read (callers may mutate the returned
* entry); list entries keep the original object, matching the direct
* traversal semantics of `resolveAgentEntry` outside a batch.
*/
function buildAgentEntryIndex(e) {
	const t = /* @__PURE__ */ new Map();
	for (const { entry: n, source: r } of listAgentEntriesWithSource(e)) {
		const e = normalizeAgentId(n?.id);
		if (!t.has(e)) t.set(e, {
			clone: r.kind === "entries",
			entry: n
		});
	}
	return t;
}
/** Resolves merged config for one agent id. */
function resolveAgentConfig(e, t) {
	const n = normalizeAgentId(t);
	const r = resolveAgentEntry(e, n) ?? (!hasAgentRosterProperty(e) && n === "main" ? { id: n } : void 0);
	if (!r) return;
	const i = e.agents?.defaults;
	return {
		name: r.name,
		workspace: r.workspace,
		agentDir: r.agentDir,
		model: r.model,
		...r.models ? { models: r.models } : {},
		...r.params ? { params: r.params } : {},
		...r.runtime ? { runtime: r.runtime } : {},
		...hasExplicitModelPolicyAllow(r.modelPolicy) ? { modelPolicy: r.modelPolicy } : {},
		utilityModel: r.utilityModel,
		decisionModel: r.decisionModel,
		thinkingDefault: r.thinkingDefault,
		verboseDefault: r.verboseDefault ?? i?.verboseDefault,
		toolProgressDetail: r.toolProgressDetail ?? i?.toolProgressDetail,
		reasoningDefault: r.reasoningDefault,
		fastModeDefault: r.fastModeDefault ?? i?.fastModeDefault,
		contextInjection: r.contextInjection,
		bootstrapMaxChars: r.bootstrapMaxChars,
		bootstrapTotalMaxChars: r.bootstrapTotalMaxChars,
		experimental: r.experimental ? {
			...i?.experimental,
			...r.experimental
		} : i?.experimental,
		skills: r.skills,
		memory: r.memory,
		humanDelay: r.humanDelay,
		typingMode: r.typingMode ?? i?.typingMode,
		tts: r.tts,
		...r.compaction ? { compaction: r.compaction } : {},
		contextLimits: r.contextLimits ? {
			...i?.contextLimits,
			...r.contextLimits
		} : i?.contextLimits,
		heartbeat: r.heartbeat,
		identity: r.identity,
		groupChat: r.groupChat,
		subagents: r.subagents,
		embeddedAgent: r.embeddedAgent,
		sandbox: r.sandbox,
		tools: r.tools
	};
}
function resolveAgentWorkspaceDir(e, t, n = process.env) {
	const r = normalizeAgentId(t);
	const i = resolveAgentConfig(e, r)?.workspace?.trim();
	if (i) return stripNullBytes(resolveUserPath(i, n));
	const a = tryResolveLegacyDataOwnerAgentId(e);
	const o = e.agents?.defaults?.workspace?.trim();
	if (a && r === a) {
		if (o) return stripNullBytes(resolveUserPath(o, n));
		return stripNullBytes(resolveDefaultAgentWorkspaceDir(n));
	}
	if (o) return stripNullBytes(path.join(resolveUserPath(o, n), r));
	const s = resolveStateDir(n);
	return stripNullBytes(path.join(s, `workspace-${r}`));
}
function resolveEffectiveAgentDir(e, t, n) {
	const r = normalizeAgentId(t);
	const i = resolveAgentConfig(e, r)?.agentDir?.trim();
	const a = n?.env ?? process.env;
	return i ? resolveUserPath(i, a, n?.homedir) : path.join(resolveStateDir(a, n?.homedir), "agents", r, "agent");
}
//#endregion
//#region src/infra/update-database-generations.ts
function readCommittedContent(e, t, n, r) {
	const i = openNodeSqliteDatabase(t.location);
	runWithSqliteCleanup({ release: () => i.close() }, "Database generation checkpoint", () => truncateSqliteWal(i, t.location));
	n?.(t.location, e);
	const a = r?.();
	const o = a ? captureSqlitePrivateSnapshotFamily(t.location, t.cleanupRoot ?? path.dirname(t.location)) : void 0;
	if (a && !o) throw new Error("Database generation private image cannot be retained");
	const s = t.journalFreeContent;
	if (s) {
		assertPublishedFileIdentitySync(t.location, s.identity, s);
		return {
			sha256: s.sha256,
			family: o
		};
	}
	const c = fsSync.openSync(t.location, "r");
	return {
		sha256: runWithSqliteCleanup({ release: () => fsSync.closeSync(c) }, "Database generation digest", () => hashFileDescriptorSync(c).sha256),
		family: o
	};
}
/** Native admission of a family with no sidecar bytes to interpret, in place of its copy. */
function inspectDrainedSource(e, t) {
	const n = resolveImmutableSqliteFileUri(e);
	if (t) {
		t(n, e);
		return;
	}
	const r = openNodeSqliteDatabase(n, { readOnly: true });
	runWithSqliteCleanup({ release: () => r.close() }, "Database generation admission", () => readSqliteSchemaObjects(r));
}
function readWalIndexHeader(e) {
	const t = `${e}-shm`;
	let n;
	try {
		n = fsSync.openSync(t, "r");
	} catch (e) {
		return ignoreMissingPath(e) ?? null;
	}
	try {
		const r = fsSync.fstatSync(n, { bigint: true });
		const i = Buffer.alloc(96);
		const a = fsSync.readSync(n, i, 0, 48, 0);
		const o = fsSync.readSync(n, i, 48, 48, 48);
		const s = fsSync.fstatSync(n, { bigint: true });
		const c = fsSync.lstatSync(t, { bigint: true });
		if (!r.isFile() || !c.isFile() || [s, c].some((e) => r.dev !== e.dev || r.ino !== e.ino) || a !== 48 || o !== 48 || !i.subarray(0, 48).equals(i.subarray(48, 96))) throw new Error(`SQLite WAL commit header is unavailable or changing: ${e}`);
		return i;
	} finally {
		fsSync.closeSync(n);
	}
}
/**
* A native open after every index user leaves rebuilds the index over the retained
* frames: iChange restarts at zero and only the header checksum follows it. A commit
* changes the frame count and checksum; a WAL restart changes the salts.
*/
function isRebuiltWalIndex(e, t) {
	return t.readUInt32LE(8) === 0 && t.subarray(0, 8).equals(e.subarray(0, 8)) && t.subarray(12, 40).equals(e.subarray(12, 40));
}
/** Without journal data or WAL frames, the verified family proves no commit; the index can come or go. */
function sameWalCommitPublication(e, t, n) {
	if (e === null ? t === null : t !== null && (t.equals(e) || isRebuiltWalIndex(e, t))) return true;
	if (n.journal || (n.wal?.size ?? 0n) !== 0n) return false;
	return t === null || e === null && t.readUInt32LE(8) === 0 && t.readBigUInt64LE(24) === 0n;
}
function readGenerationFamily(e) {
	const t = [
		"",
		"-journal",
		"-wal"
	].map((t) => fsSync.lstatSync(`${e}${t}`, {
		bigint: true,
		throwIfNoEntry: false
	}));
	if (!t[0] && t.slice(1).some(Boolean)) throw new Error(`Database is absent but retained journal data exists: ${e}`);
	if (t.some((e) => e && !e.isFile())) throw new Error(`Database generation requires a regular file: ${e}`);
	return t.map((e, t) => t === 2 && e?.size === 0n ? void 0 : e);
}
function verifyGenerationFamily(e, t, n) {
	const r = readGenerationFamily(e);
	if ([
		n.database,
		n.journal,
		n.wal?.size === 0n ? void 0 : n.wal
	].some((e, n) => [t[n], r[n]].some((t) => e === void 0 ? t !== void 0 : !t || !sameFileStatFingerprint(t, e)))) throw new Error(`SQLite file generation changed while reading: ${e}`);
}
function serializePhysicalGeneration(e, t) {
	return sha256Hex(JSON.stringify([serializeSqliteFileGeneration(e.wal?.size === 0n ? {
		...e,
		wal: void 0
	} : e), t?.toString("hex") ?? null]));
}
/** Isolated raw-close owner; retained images must stay inside a retained snapshot-work scope. */
function readUpdateDatabaseGeneration(e, t, n) {
	const r = readGenerationFamily(e);
	const i = r[0];
	if (!i) return {
		generation: null,
		physical: null
	};
	const a = readWalIndexHeader(e);
	const o = createSqliteFileGenerationReader();
	const s = o(e);
	const observe = (t, n) => {
		const c = readStableSqliteFileGeneration(e, n ? o : void 0);
		const l = readWalIndexHeader(e);
		verifyGenerationFamily(e, r, c);
		if (!sameSqliteFileGeneration(s, c) || !sameWalCommitPublication(a, l, c) || s.wal && s.wal.size > 0n && l?.[12] !== 1) throw new Error(`SQLite WAL commit publication could not be verified: ${e}`);
		const u = [
			s.database.dev.toString(),
			s.database.ino.toString(),
			readDatabaseIdentityBirthtime(i),
			t.sha256
		];
		const d = l?.subarray(8, 12).toString("hex") ?? null;
		const f = l?.subarray(24, 32).toString("hex") ?? null;
		const fingerprint = (e, t) => sha256Hex(JSON.stringify([
			...u,
			e,
			t
		]));
		const p = !s.journal && (s.wal?.size ?? 0n) === 0n && (l === null || d === "00000000" && f === "0000000000000000");
		let m;
		if (t.family && n) {
			const r = captureSqlitePrivateSnapshotFamily(n.location, n.cleanupRoot ?? path.dirname(n.location));
			if (r?.main !== t.family.main || r?.wal !== t.family.wal) throw new Error("Database generation private image changed before retention");
			m = {
				sourcePath: e,
				prepared: n,
				family: t.family
			};
		}
		return {
			retained: m !== void 0,
			observation: {
				generation: fingerprint(d, f),
				physical: serializePhysicalGeneration(c, l),
				...l !== null && (s.wal?.size ?? 0n) !== 0n && d !== "00000000" ? { rebuiltIndexAlternate: fingerprint("00000000", f) } : {},
				...p ? { emptyReaderAlternate: l === null ? fingerprint("00000000", "0000000000000000") : fingerprint(null, null) } : {},
				...m ? { preparedSource: m } : {}
			}
		};
	};
	const c = !s.journal && (s.wal?.size ?? 0n) === 0n;
	if (c && !n) try {
		inspectDrainedSource(e, t);
		return observe({ sha256: s.database.sha256 }).observation;
	} catch {}
	const l = prepareSqliteReadOnlyLocationSyncInProcess(e, n?.stagingRoot, { key: `file:${databaseFileIdentityKey(s.database)}` }, c ? {
		sha256: s.database.sha256,
		sizeBytes: Number(s.database.size)
	} : void 0);
	let u = false;
	return runWithSqliteCleanup({ release: () => {
		if (u) return;
		if (!n) {
			l.cleanup();
			return;
		}
		try {
			if (!l.cleanup()) throw new Error("Database generation snapshot cleanup did not settle");
		} catch (e) {
			throw new SqliteSnapshotCleanupError("Database generation snapshot cleanup failed", { cause: e });
		}
	} }, "Database generation snapshot", () => {
		const r = readCommittedContent(e, l, t, n?.accept);
		const i = observe(r, l);
		u = i.retained;
		return i.observation;
	});
}
/**
* Same raw-close restrictions as readUpdateDatabaseGenerations; never under native exclusion.
* `accepted` holds the expected generation and its no-write equivalents.
*/
function readMatchingUpdateDatabaseGeneration(e, t) {
	const { generation: n, emptyReaderAlternate: r } = readUpdateDatabaseGeneration(e);
	return n !== null && t.includes(n) || r !== void 0 && t.includes(r) ? n ?? void 0 : void 0;
}
//#endregion
//#region src/infra/update-database-path.ts
/** Match capture inventory keys, including stores created during Doctor. */
function resolveUpdateSqlitePath(e) {
	try {
		return realpathSync.native(e);
	} catch (t) {
		ignoreMissingPath(t);
		return resolvePathViaExistingAncestorSync$1(e);
	}
}
//#endregion
//#region src/infra/update-doctor-migration-attribution.ts
const captures = new AsyncLocalStorage();
function getDoctorMigrationBackup(e, t) {
	const n = captures.getStore();
	if (n?.capture) {
		if (n.capture.expected(resolveUpdateSqlitePath(t.path)) !== void 0) throw new Error("Updater migration requires its captured source generation.");
		n.capture.refuse("The migration source path is outside the updater's captured paths.");
		return captures.run({
			...n,
			capture: void 0,
			source: void 0
		}, () => n.backup?.(e, t));
	}
	return n?.backup?.(e, t);
}
function migrationAuthority(e, t, n) {
	const r = getOpenClawDatabaseMaintenanceScope();
	if (!r?.ownsSchemaMaintenance) {
		e.refuse("Migration did not retain schema maintenance custody.");
		throw new Error("Database migration requires schema maintenance custody.");
	}
	return () => {
		r.assertAdmission();
		if (n) n();
		else assertStateDatabaseAccessAllowed(t);
		e.assertCurrent();
	};
}
function readSqliteGeneration(e) {
	const t = JSON.parse(runSqliteReadOnlyWorkerSync(e, void 0, "update-generation"));
	if (t !== null && (typeof t !== "string" || !/^[a-f0-9]{64}$/u.test(t))) throw new Error("Database generation child returned an invalid generation.");
	return t;
}
function readSqliteFiles(e) {
	return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e, void 0, "file-generation"));
}
/** A source proof exists only within its verified migration's lexical interval. */
function getUpdateDoctorMigrationSource(e) {
	const t = captures.getStore()?.source;
	if (!t || t.path !== resolveUpdateSqlitePath(e)) return;
	const { generation: n, assertCurrent: r } = t;
	r();
	return {
		path: e,
		generation: n,
		assertCurrent: r
	};
}
/** Retain the source's native exclusion across its commits and isolated postimage read. */
function runUpdateSqliteMigration(e, t, n, r) {
	const i = captures.getStore();
	if (!i?.capture) return n();
	const a = resolveUpdateSqlitePath(t);
	if (i.source?.path === a) {
		i.source.assertCurrent();
		return n();
	}
	const { capture: o } = i;
	const s = o.expected(a);
	const c = o.openedSqlitePaths?.has(a);
	if (typeof s !== "string" && !(s === null && r?.created)) return n();
	const l = migrationAuthority(o, t);
	l();
	if (e.isTransaction) throw new Error("Update migration exclusion must precede the source transaction.");
	const u = e.prepare("PRAGMA locking_mode").get()?.locking_mode;
	return runWithSqliteCleanup({ release() {
		if (r?.close) o.openedSqlitePaths?.delete(a);
		try {
			if (e.isOpen && u !== "exclusive" && !r?.retainExclusive) {
				if (e.isTransaction) throw new Error("Update migration left its source transaction open.");
				e.exec("PRAGMA locking_mode=NORMAL; PRAGMA page_count;");
			}
		} catch (e) {
			o.refuse("SQLite migration native custody could not be released.");
			throw e;
		}
	} }, "Update migration exclusion", () => {
		try {
			if (s === null) {
				const e = readSqliteFiles(t);
				if (e.database.size !== 0n || e.journal || e.wal) throw new Error("Created SQLite migration family is no longer empty.");
			}
			const i = o.rebuiltIndex(a);
			const d = s === null ? null : c || u === "exclusive" ? readSqliteGeneration(t) : readMatchingUpdateDatabaseGeneration(t, i === void 0 ? [s] : [s, i]);
			l();
			if (d === void 0 || !c && u === "exclusive" && d !== s && d !== i) throw new Error(`SQLite migration source changed after update capture: ${t}`);
			o.openedSqlitePaths?.add(a);
			if (d !== s) o.accept(a, s, d);
			if (u !== "exclusive") e.prepare("PRAGMA schema_version").get();
			e.exec("PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;");
			l();
			const f = d === null ? void 0 : {
				path: a,
				generation: d,
				assertCurrent: l
			};
			return captures.run({
				capture: o,
				source: f,
				assertMigrationCurrent: l
			}, () => {
				const i = n();
				if (isPromiseLike(i)) throw new Error("Update migration callbacks must remain synchronous.");
				if (e.isTransaction) throw new Error("Update migration publication requires its committed native owner.");
				l();
				truncateSqliteWal(e, t);
				r?.close?.();
				const s = readSqliteGeneration(t);
				l();
				o.accept(a, d, s);
				return i;
			});
		} catch (e) {
			o.refuse(`SQLite migration publication could not be verified: ${formatErrorMessage(e)}`);
			throw e;
		}
	});
}
/** Unknown companions remain outside an older driver's inventory. Their caller retains custody. */
function beginUpdateSqliteCompanion(e, t, n) {
	const r = captures.getStore();
	const i = r?.capture;
	if (!i) return;
	const a = resolveUpdateSqlitePath(t);
	const o = i.expected(a);
	if (o === void 0) return;
	const s = r?.assertMigrationCurrent;
	if (!s) {
		i.refuse("Migration companion has no verified source custody.");
		throw new Error("Migration companion requires verified source custody.");
	}
	s();
	if (e.prepare("PRAGMA locking_mode").get()?.locking_mode !== "exclusive") throw new Error("Migration companion requires its exclusive native owner.");
	const c = n && o === null ? null : readSqliteGeneration(t);
	s();
	if (!i.openedSqlitePaths?.has(a) && c !== o && c !== i.rebuiltIndex(a)) {
		i.refuse("Migration companion changed after update capture.");
		throw new Error("Database migration companion no longer matches its capture.");
	}
	i.openedSqlitePaths?.add(a);
	return { complete() {
		s();
		if (!e.isOpen || e.isTransaction) throw new Error("Migration companion publication requires its committed native owner.");
		const n = readSqliteGeneration(t);
		s();
		i.accept(a, c, n);
	} };
}
/** Called inside the engine's migration transaction, before its first mutation. */
function beginUpdatePostgresMigration(e, t) {
	const n = captures.getStore()?.capture;
	const r = e.anchor.location();
	const i = r && n?.expected(r);
	if (!n || !r || typeof i !== "string") return;
	if (!getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance) {
		n.refuse("PostgreSQL migration did not retain schema maintenance custody.");
		return;
	}
	const a = migrationAuthority(n, r, t);
	a();
	const o = e.readRecoveryGeneration(true);
	if (o !== i) {
		n.refuse("PostgreSQL changed before migration acquired native custody.");
		throw new Error("PostgreSQL migration source changed after update capture.");
	}
	const s = {
		path: r,
		generation: o,
		assertCurrent: a
	};
	let publish;
	return {
		run(e) {
			return captures.run({
				capture: n,
				source: s,
				assertMigrationCurrent: a
			}, e);
		},
		beforeCommit() {
			a();
			const t = e.readRecoveryGeneration(false);
			publish = () => n.accept(r, o, t);
			a();
		},
		committed() {
			a();
			publish?.();
		}
	};
}
//#endregion
//#region src/infra/database-engine/observation.ts
const channels = {
	statement: channel("openclaw.database.statement"),
	request: channel("openclaw.database.request")
};
const observedConnections = /* @__PURE__ */ new WeakSet();
function normalizeSql(e, t) {
	let n = "";
	for (let r = 0; r < t.length;) {
		const i = t.slice(r);
		if (i.startsWith("/*")) {
			let e = 1;
			r += 2;
			while (r < t.length && e) if (t.startsWith("/*", r)) {
				e++;
				r += 2;
			} else if (t.startsWith("*/", r)) {
				e--;
				r += 2;
			} else r++;
			n += " ";
			continue;
		}
		const a = /^--[^\r\n]*/.exec(i)?.[0];
		const o = (e === "postgres" ? /^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0] : void 0) ?? /^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0];
		const s = /^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0];
		const c = /^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0];
		const l = !/[\w$]/.test(t[r - 1] ?? "") ? /^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0] : void 0;
		if (s) {
			const e = t.indexOf(s, r + s.length);
			r = e < 0 ? t.length : e + s.length;
			n += "?";
		} else if (a || o || c || l) {
			const e = a ?? o ?? c ?? l ?? "";
			r += e.length;
			n += a ? " " : c ? e : "?";
		} else n += t[r++];
	}
	return n.replace(/\s+/g, " ").trim();
}
function observeDatabaseOperation(e, t, n, r) {
	const i = channels[t];
	if (!i.hasSubscribers) return r();
	const a = performance.now();
	let o = "error";
	try {
		const e = r();
		o = "ok";
		return e;
	} finally {
		const t = performance.now() - a;
		i.publish({
			engine: e,
			sql: n === void 0 ? void 0 : normalizeSql(e, n),
			threadId,
			outcome: o,
			durationMs: t
		});
	}
}
function observeConnection(e) {
	if (observedConnections.has(e)) return e;
	observedConnections.add(e);
	const t = e.exec.bind(e);
	const n = e.prepare.bind(e);
	e.exec = (e) => observeDatabaseOperation("sqlite", "statement", e, () => t(e));
	e.prepare = (e) => {
		const t = n(e);
		for (const n of [
			"get",
			"all",
			"run"
		]) {
			const r = t[n].bind(t);
			Object.defineProperty(t, n, {
				configurable: true,
				writable: true,
				value: (...t) => observeDatabaseOperation("sqlite", "statement", e, () => r(...t))
			});
		}
		const r = t.iterate.bind(t);
		t.iterate = (...t) => {
			const n = r(...t);
			if (!channels.statement.hasSubscribers) return n;
			let i = 0;
			let a = false;
			let o = false;
			const finish = (t) => {
				if (o) return;
				o = true;
				if (a) channels.statement.publish({
					engine: "sqlite",
					sql: normalizeSql("sqlite", e),
					threadId,
					outcome: t,
					durationMs: i
				});
			};
			const step = (e) => {
				if (o) return e();
				const t = performance.now();
				try {
					const n = e();
					i += performance.now() - t;
					if (n.done) finish("ok");
					return n;
				} catch (e) {
					i += performance.now() - t;
					finish("error");
					throw e;
				}
			};
			const s = {
				next: (...e) => {
					a = true;
					return step(() => n.next(...e));
				},
				return: (e) => step(() => n.return?.(e) ?? {
					done: true,
					value: e
				}),
				[Symbol.iterator]() {
					return this;
				}
			};
			Object.setPrototypeOf(s, Object.getPrototypeOf(n));
			return s;
		};
		return t;
	};
	return e;
}
//#endregion
//#region src/infra/database-engine/policy.ts
const POSTGRES_CONNECT_TIMEOUT_MS = 6e4;
const POSTGRES_LOCK_TIMEOUT_MS = 6e4;
const POSTGRES_STATEMENT_TIMEOUT_MS = 9e4;
//#endregion
//#region src/infra/postgres-sync/idle-bridges.ts
const idleBridges = /* @__PURE__ */ new Map();
const maxIdleBridges = 2;
const idleBridgeTimeoutMs = 18e4;
function closeBridge(e) {
	e.port.close();
}
function closeIdleBridges() {
	const e = [...idleBridges.values()];
	idleBridges.clear();
	unwatch();
	for (const { bridge: t, timeout: n } of e) {
		clearTimeout(n);
		closeBridge(t);
	}
}
function unwatch() {
	if (!idleBridges.size) {
		process.off("beforeExit", closeIdleBridges);
		process.off("exit", closeIdleBridges);
	}
}
function removeIdleBridge(e) {
	const t = idleBridges.get(e);
	idleBridges.delete(e);
	if (t) clearTimeout(t.timeout);
	unwatch();
	return t?.bridge;
}
function takeIdlePostgresBridge(e) {
	const t = removeIdleBridge(e);
	if (t) {
		if (Atomics.load(t.service, 1)) {
			closeBridge(t);
			return;
		}
	}
	return t;
}
function retainIdlePostgresBridge(e, t) {
	const n = removeIdleBridge(e);
	if (n) closeBridge(n);
	if (idleBridges.size === maxIdleBridges) {
		const e = idleBridges.keys().next().value;
		closeBridge(removeIdleBridge(e));
	}
	if (!idleBridges.size) {
		process.once("beforeExit", closeIdleBridges);
		process.once("exit", closeIdleBridges);
	}
	const r = setTimeout(() => {
		const t = removeIdleBridge(e);
		if (t) closeBridge(t);
	}, idleBridgeTimeoutMs);
	r.unref();
	idleBridges.set(e, {
		bridge: t,
		timeout: r
	});
}
//#endregion
//#region src/infra/postgres-sync/bridge-prestart.ts
function postgresBridgeReuseKey(e) {
	return sha256Hex(JSON.stringify([
		e.url,
		e.lockTimeoutMs ?? 6e4,
		e.statementTimeoutMs ?? 9e4
	]));
}
function preparedBridgeKey(e) {
	return JSON.stringify([
		postgresBridgeReuseKey(e),
		e.schema,
		e.storeId
	]);
}
function createPostgresBridge(e) {
	const { port1: t, port2: n } = new MessageChannel();
	const r = new SharedArrayBuffer(8);
	const i = new Int32Array(r);
	const { port: a, signal: o, nextStep: s } = selectPostgresPoolService();
	const c = new Int32Array(o);
	if (Atomics.load(c, 1)) {
		t.close();
		n.close();
		const e = /* @__PURE__ */ new Error(`PostgreSQL I/O service is unavailable.${s ? ` Run ${s}.` : ""}`);
		recordPostgresPoolFailure(e);
		throw e;
	}
	try {
		a.postMessage({ connection: {
			port: n,
			signal: r,
			url: e.url,
			schema: e.schema,
			connectTimeoutMs: POSTGRES_CONNECT_TIMEOUT_MS,
			lockTimeoutMs: e.lockTimeoutMs ?? 6e4,
			statementTimeoutMs: e.statementTimeoutMs ?? 9e4
		} }, [n]);
	} catch (e) {
		t.close();
		n.close();
		throw e;
	}
	t.unref();
	return {
		port: t,
		control: i,
		service: c,
		nextStep: s,
		requestId: 0
	};
}
const preparedBridgeScope = new AsyncLocalStorage();
function findPreparedBridge(e) {
	let t = preparedBridgeScope.getStore();
	while (t) {
		if (t.key === e && t.bridge && !Atomics.load(t.bridge.service, 1)) return t;
		t = t.parent;
	}
}
function takePreparedPostgresBridge(e) {
	const t = findPreparedBridge(preparedBridgeKey(e));
	const n = t?.bridge;
	if (t && n) {
		t.bridge = void 0;
		t.detachAbort();
	}
	return n;
}
//#endregion
//#region src/infra/postgres-sync/transaction.ts
function assertPostgresOperationCurrent() {
	const e = currentSqliteWorkerOperationAdmission.getStore();
	if (e && (!e.active || e.owner.refusal)) throw e.owner.refusal ?? /* @__PURE__ */ new Error("PostgreSQL worker operation is no longer active");
}
function runPostgresTransactionSync(e, t, n, r = false, i = false) {
	assertPostgresOperationCurrent();
	const a = sqlPublicationAnchor(e);
	return withSqlitePostCommitPublications(a, () => {
		const a = e.isTransaction && !i;
		let o = false;
		let s;
		try {
			if (a) e.exec("SAVEPOINT openclaw_tx_nested");
			else if (!e.isTransaction) e.exec(r ? "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY" : `BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);
			if (r && !a) s = beginPostgresReadSnapshotScope(e);
			const i = t();
			assertSyncTransactionResult(i);
			if (a) e.exec("RELEASE SAVEPOINT openclaw_tx_nested");
			else {
				const commit = () => {
					assertPostgresOperationCurrent();
					if (!r) prepareSqliteTransactionCommit(e);
					e.exec(r ? "ROLLBACK" : "COMMIT");
					o = !r;
				};
				if (n?.withCommit) assertSyncTransactionResult(n.withCommit(commit));
				else commit();
			}
			return i;
		} catch (t) {
			let n = hasSqliteWorkerOutcomeUnknown(t) || o;
			if (!n) try {
				if (a) {
					e.exec("ROLLBACK TO SAVEPOINT openclaw_tx_nested");
					e.exec("RELEASE SAVEPOINT openclaw_tx_nested");
				} else if (e.isTransaction) e.exec("ROLLBACK");
			} catch {
				n = true;
			}
			if (n) try {
				discardSqliteTransactionState(e, t, "unknown");
			} finally {
				try {
					e.close();
				} catch {}
			}
			throw t;
		} finally {
			s?.();
		}
	});
}
//#endregion
//#region src/infra/postgres-sync/connection.ts
var PostgresSyncConnection = class {
	constructor(e, t, n, r, i) {
		this.schema = t;
		this.anchor = n;
		this.storeId = r;
		this.isOpen = true;
		this.isTransaction = false;
		this.mutationRevision = 0;
		this.idleCheckout = false;
		this.lastResponseAt = Date.now();
		this.outcomeUnknown = true;
		this.readOnlyTransaction = false;
		this.pendingWrite = false;
		this.mainThread = threadId === 0;
		assertEngineStoreExecutionAllowed();
		Object.defineProperty(this, Symbol.for("openclaw.postgres-sync-connection"), { value: true });
		this.advisoryLockKey = createHash("sha256").update(r).digest().readBigInt64BE();
		this.bridgeParameters = {
			url: e,
			schema: t,
			storeId: r,
			...i
		};
		this.reuseKey = i?.reuse ? postgresBridgeReuseKey(this.bridgeParameters) : void 0;
		this.connect();
	}
	connect() {
		const e = this.reuseKey ? takeIdlePostgresBridge(this.reuseKey) : void 0;
		const t = e ?? takePreparedPostgresBridge(this.bridgeParameters) ?? createPostgresBridge(this.bridgeParameters);
		this.bridge = t;
		this.idleCheckout = e !== void 0;
		t.port.unref();
		if (e) return t;
		try {
			this.request({
				operation: "connect",
				schema: this.schema
			});
		} catch (e) {
			this.isOpen = false;
			this.isTransaction = false;
			this.bridge = void 0;
			t.port.close();
			throw e;
		}
		return t;
	}
	runTransaction(e, t, ...n) {
		return runPostgresTransactionSync(this, e, t, ...n);
	}
	readRecoveryGeneration(e = false) {
		return this.request({
			operation: "recovery-generation",
			schema: this.schema,
			storeId: this.storeId,
			lock: e
		}, false);
	}
	loseConnection() {
		if (!this.failure && this.outcomeUnknown) {
			this.pendingWrite = true;
			beginSqliteDatabaseWrite(sqlPublicationAnchor(this), true);
		}
		this.finishWrite();
		this.failure ??= this.outcomeUnknown ? new SqliteWorkerError("PostgreSQL connection lost; outcome unknown", "outcome-unknown") : /* @__PURE__ */ new Error("PostgreSQL connection lost; transaction rolled back");
		const e = this.bridge;
		if (e?.nextStep && !this.failure.message.includes(e.nextStep)) this.failure.message += ` Run ${e.nextStep}.`;
		if (e && Atomics.load(e.service, 1)) recordPostgresPoolFailure(this.failure);
		this.isOpen = false;
		this.isTransaction = false;
		e?.port.close();
		this.bridge = void 0;
		return this.failure;
	}
	finishWrite() {
		if (this.pendingWrite) {
			this.pendingWrite = false;
			finishSqliteDatabaseWrite(sqlPublicationAnchor(this));
		}
	}
	assertOpen() {
		if (this.failure) throw this.failure;
		if (!this.isOpen) throw new Error("PostgreSQL connection is closed");
	}
	request(e, t = true) {
		if (this.mainThread && e.operation !== "close" && e.operation !== "release") assertEngineStoreExecutionAllowed();
		this.assertOpen();
		const n = this.bridge ?? this.connect();
		this.outcomeUnknown = t;
		const r = ++n.requestId;
		if (r > 2147483647) throw this.loseConnection();
		const i = performance.now() + 12e4;
		const a = n.inTransaction === false;
		const o = (this.idleCheckout || a) && (e.operation === "query" || e.operation === "recovery-generation");
		const s = o && (this.idleCheckout || a && Date.now() - this.lastResponseAt >= 1e3);
		n.inTransaction = void 0;
		this.idleCheckout = false;
		n.port.postMessage({
			...e,
			...o ? { reconnectIfIdle: o } : {},
			...s ? { validateIfIdle: s } : {},
			id: r
		}, []);
		recordWorkerMessage("sqlite_request", "to_worker");
		for (let e = Atomics.load(n.control, 0); e !== r; e = Atomics.load(n.control, 0)) {
			if (Atomics.load(n.service, 1)) throw this.loseConnection();
			const t = i - performance.now();
			if (t <= 0) {
				Atomics.store(n.service, 1, 1);
				Atomics.notify(n.service, 1);
				throw this.loseConnection();
			}
			Atomics.wait(n.control, 0, e, Math.min(t, 50));
		}
		const c = receiveMessageOnPort(n.port)?.message;
		if (c) recordWorkerMessage("sqlite_reply", "from_worker");
		if (!c || c.id !== r) throw this.loseConnection();
		if ("error" in c) {
			if (e.operation === "connect") throw decodePostgresError(c.error);
			if (isPostgresConnectionError(c.error.code)) throw this.loseConnection();
			if (e.operation === "query" && /^\s*COMMIT\b/i.test(e.sql)) {
				this.isTransaction = false;
				this.finishWrite();
			}
			throw decodePostgresError(c.error);
		}
		this.lastResponseAt = Date.now();
		if ("reusable" in c) {
			n.inTransaction = !c.reusable;
			return c.reusable;
		}
		n.inTransaction = "generation" in c ? c.inTransaction : c.result.inTransaction;
		return "generation" in c ? c.generation : c.result;
	}
	query(e, t = [], n = false) {
		return observeDatabaseOperation("postgres", "statement", e, () => this.execute(preparePostgresQuery(e), t, n));
	}
	execute({ sql: e, mutation: t }, n, r) {
		validatePostgresBindings(n);
		const i = this.isTransaction;
		if (/^\s*BEGIN\b/i.test(e)) this.isTransaction = true;
		const a = this.request({
			operation: "query",
			schema: this.schema,
			sql: e,
			parameters: n
		}, !i || /^\s*COMMIT\b/i.test(e));
		const o = this.readOnlyTransaction;
		this.isTransaction = a.inTransaction;
		this.readOnlyTransaction = this.isTransaction && (o || /^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e));
		if (/^\s*COMMIT\s*;?\s*$/i.test(e) && a.command !== "COMMIT") {
			this.finishWrite();
			throw new Error("PostgreSQL transaction rolled back instead of committing");
		}
		const s = a.mutation === "unscoped" || t === "unscoped" ? "unscoped" : a.mutation ?? t;
		const c = s !== void 0;
		if (c) {
			if (o || this.readOnlyTransaction) throw new Error("PostgreSQL read snapshot cannot execute a mutation");
			this.mutationRevision++;
			this.pendingWrite = true;
			beginSqliteDatabaseWrite(sqlPublicationAnchor(this), s === "unscoped");
		}
		if (!this.isTransaction && (c || i)) withSqlitePostCommitPublications(sqlPublicationAnchor(this), () => {
			this.finishWrite();
		});
		this.outcomeUnknown = !this.isTransaction;
		return {
			rows: decodePostgresRows(a, r),
			rowCount: a.rowCount,
			columns: a.fields.map(({ name: e }) => ({ name: e }))
		};
	}
	exec(e) {
		this.query(e);
	}
	prepare(e) {
		this.assertOpen();
		const t = preparePostgresQuery(e);
		let n = false;
		let r = [];
		const execute = (i) => {
			const a = observeDatabaseOperation("postgres", "statement", e, () => this.execute(t, i, n));
			r = a.columns;
			return a;
		};
		return {
			get: (...e) => execute(e).rows[0],
			all: (...e) => execute(e).rows,
			iterate: (...e) => execute(e).rows[Symbol.iterator](),
			run: (...e) => ({
				changes: execute(e).rowCount,
				lastInsertRowid: 0
			}),
			columns: () => r,
			setReadBigInts: (e) => {
				n = e;
			}
		};
	}
	/** Release only the idle backend; the logical reader keeps its admitted facts and anchor. */
	releaseIdleTransport() {
		const e = this.bridge;
		if (!this.isOpen || !e || !this.reuseKey || this.isTransaction) return;
		let t = false;
		try {
			if (e.inTransaction === false || this.request({ operation: "release" })) {
				retainIdlePostgresBridge(this.reuseKey, e);
				t = true;
			} else {
				this.isOpen = false;
				this.finishWrite();
			}
		} finally {
			this.bridge = void 0;
			if (!t) e.port.close();
		}
	}
	close() {
		if (!this.isOpen) return;
		try {
			if (this.reuseKey && !this.isTransaction) this.releaseIdleTransport();
			else if (this.bridge) this.request({ operation: "close" });
		} finally {
			this.finishWrite();
			this.isOpen = false;
			this.isTransaction = false;
			this.bridge?.port.close();
			this.bridge = void 0;
		}
	}
};
//#endregion
//#region src/infra/sqlite-schema-catalog.ts
/** Reuse actual catalog facts only within one unchanged read transaction on this connection. */
function createSqliteTableContractReader(e, t = [], n = []) {
	let r;
	let i;
	const a = /* @__PURE__ */ new Set();
	const readCatalog = (o = []) => {
		if (!r) {
			const i = [...n, ...o];
			r = readSqliteSchemaCatalog(e, {
				viewNames: t,
				virtualTableNames: i
			});
			for (const e of r.tables) if (e.sql && /^CREATE VIRTUAL TABLE /iu.test(e.sql) && !i.includes(e.name)) a.add(e.name);
		} else for (const t of o) {
			if (!a.has(t)) continue;
			const n = readSqliteColumnCatalog(e, t);
			r = {
				...r,
				tables: r.tables.map((e) => e.name === t ? {
					...e,
					columns: n
				} : e)
			};
			a.delete(t);
			i = void 0;
		}
		return r;
	};
	return Object.assign((e) => {
		const t = readCatalog([e]);
		return (i ??= sqliteSchemaContractFromCatalog(t)).get(e);
	}, {
		readCatalog: (n, r) => n.every((e) => t.includes(e)) ? readCatalog(r) : readSqliteSchemaCatalog(e, {
			viewNames: n,
			virtualTableNames: r
		}),
		readView: (n) => {
			return (t.includes(n) ? readCatalog().views : readSqliteSchemaCatalog(e, {
				viewNames: [n],
				virtualTableNames: []
			}).views).find((e) => e.name === n);
		}
	});
}
/** Preserve admission's historical column-order and automatic-index-name compatibility. */
function sqliteSchemaContractFromCatalog(e) {
	return new Map(e.tables.map((e) => [e.name, createSqliteTableContract(e.name, e, {
		schema: "main",
		name: e.name,
		strict: e.strict,
		wr: e.withoutRowid
	}, e.indexes.map((e) => createSqliteIndexContract(e, e.sql, e.terms)).toSorted(compareJson), e.triggers, e.columns, e.foreignKeys)]));
}
/** Read one native catalog in five statements, independent of its table count. */
function readSqliteSchemaCatalog(e, t = {}) {
	const n = e.prepare("SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name").all();
	const r = n.filter((e) => e.type === "table" && !e.name.startsWith("sqlite_"));
	const i = n.filter((e) => e.type === "view" && (!t.viewNames || t.viewNames.includes(e.name)));
	if (r.length === 0 && i.length === 0) return {
		tables: [],
		views: []
	};
	const a = e.prepare("PRAGMA table_list").all();
	const o = a.filter((e) => e.schema === "main" && e.type === "virtual" && t.virtualTableNames && !t.virtualTableNames.includes(e.name)).map((e) => e.name);
	const s = a.some((e) => [
		"pragma_index_list",
		"pragma_index_xinfo",
		"pragma_table_xinfo",
		"pragma_foreign_key_list"
	].includes(e.name.toLowerCase()));
	let c;
	let l;
	if (!s) {
		c = /* @__PURE__ */ new Map();
		l = /* @__PURE__ */ new Map();
		const t = e.prepare(`
        SELECT t.name AS table_name, i.seq AS index_seq,
          i.name AS index_name, i.origin, i.partial, i."unique",
          x.seqno, x.cid, x.name, x."desc", x.coll, x."key"
        FROM main.sqlite_schema AS t
        CROSS JOIN pragma_index_list(t.name, 'main') AS i
        LEFT JOIN pragma_index_xinfo(i.name, 'main') AS x ON 1 = 1
        WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
        ORDER BY t.name, i.seq, x.seqno
      `).all();
		for (const e of t) {
			const t = c.get(e.table_name) ?? [];
			if (t.at(-1)?.index_seq !== e.index_seq) {
				t.push({
					table_name: e.table_name,
					index_seq: e.index_seq,
					name: e.index_name,
					origin: e.origin,
					partial: e.partial,
					unique: e.unique
				});
				c.set(e.table_name, t);
			}
			if (e.seqno !== null) {
				const t = l.get(e.table_name) ?? [];
				t.push({
					table_name: e.table_name,
					index_seq: e.index_seq,
					seqno: e.seqno,
					cid: e.cid,
					name: e.name,
					desc: e.desc,
					coll: e.coll,
					key: e.key
				});
				l.set(e.table_name, t);
			}
		}
	}
	const u = !t.viewNames ? "t.type IN ('table', 'view')" : t.viewNames.length > 0 ? `t.type = 'table' OR (t.type = 'view' AND t.name IN (${t.viewNames.map(() => "?").join(", ")}))` : "t.type = 'table'";
	const d = o.length ? `AND t.name NOT IN (${o.map(() => "?").join(", ")})` : "";
	const f = s ? void 0 : groupPluginRecords(e.prepare(`
          SELECT t.name AS table_name, x.cid, x.name, x.type, x."notnull", x.dflt_value, x.pk, x.hidden
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_table_xinfo(t.name, 'main') AS x
          WHERE (${u}) AND substr(t.name, 1, 7) <> 'sqlite_'
            ${d}
          ORDER BY t.name, x.cid
        `).all(...t.viewNames ?? [], ...o), (e) => e.table_name);
	const p = s ? void 0 : groupPluginRecords(e.prepare(`
          SELECT t.name AS table_name, f.id, f.seq, f."table", f."from", f."to",
            f.on_update, f.on_delete, f."match"
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_foreign_key_list(t.name, 'main') AS f
          WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
          ORDER BY t.name, f.id, f.seq
        `).all(), (e) => e.table_name);
	const m = groupPluginRecords(n.filter((e) => e.type === "trigger"), (e) => e.tbl_name);
	const h = new Map(n.filter((e) => e.type === "index").map((e) => [e.name, e.sql]));
	const normalizedRow = (e) => ({
		name: e.name,
		sql: normalizeSchemaSql(e.sql)
	});
	const readColumns = (t) => o.includes(t) ? [] : f ? (f.get(t) ?? []).map(({ table_name: e, ...t }) => t) : readSqliteColumnCatalog(e, t);
	const readTriggers = (e) => (m.get(e) ?? []).map(normalizedRow);
	return {
		tables: r.map((t) => {
			const n = a.find((e) => e.schema === "main" && e.name === t.name);
			if (!n) throw new Error(`Could not inspect SQLite table options for ${t.name}.`);
			const r = c ? c.get(t.name) ?? [] : e.prepare(`PRAGMA main.index_list(${quoteSqliteIdentifier(t.name)})`).all().map(({ name: e, origin: t, partial: n, unique: r, seq: i }) => ({
				name: e,
				origin: t,
				partial: n,
				unique: r,
				index_seq: i
			}));
			const i = groupPluginRecords(l?.get(t.name) ?? [], (e) => e.index_seq);
			return {
				name: t.name,
				sql: normalizeSchemaSql(t.sql),
				strict: n.strict,
				withoutRowid: n.wr,
				columns: readColumns(t.name),
				foreignKeys: p ? (p.get(t.name) ?? []).map(({ table_name: e, ...t }) => t) : e.prepare(`PRAGMA main.foreign_key_list(${quoteSqliteIdentifier(t.name)})`).all(),
				indexes: r.map((t) => ({
					name: t.name,
					origin: t.origin,
					partial: t.partial,
					unique: t.unique,
					sql: normalizeSchemaSql(h.get(t.name) ?? null),
					terms: l ? (i.get(t.index_seq) ?? []).map(({ table_name: e, index_seq: t, ...n }) => n) : e.prepare(`PRAGMA main.index_xinfo(${quoteSqliteIdentifier(t.name)})`).all()
				})).toSorted((e, t) => e.name.localeCompare(t.name)),
				triggers: readTriggers(t.name)
			};
		}),
		views: i.map((e) => ({
			name: e.name,
			sql: normalizeSchemaSql(e.sql),
			columns: readColumns(e.name),
			triggers: readTriggers(e.name)
		}))
	};
}
function readSqliteColumnCatalog(e, t) {
	return e.prepare(`PRAGMA main.table_xinfo(${quoteSqliteIdentifier(t)})`).all();
}
function compareJson(e, t) {
	return JSON.stringify(e).localeCompare(JSON.stringify(t));
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-agent-catalogs.ts
const tableNames$4 = [
	["acp_parent_stream_events", ["idx_agent_acp_parent_stream_run"]],
	["auth_profile_state", []],
	["auth_profile_store", []],
	["board_tabs", []],
	["board_widgets", ["idx_agent_board_widgets_tab_position"]],
	["cache_entries", [
		"idx_agent_cache_expiry",
		"idx_agent_cache_updated",
		"idx_agent_voice_session_open_scope",
		"idx_agent_voice_session_open_updated"
	]],
	["context_engine_turn_outbox", ["idx_agent_context_engine_turn_outbox_engine"]],
	["conversation_deliveries", [
		"idx_agent_conversation_deliveries_reply",
		"idx_agent_conversation_deliveries_source_session",
		"idx_agent_conversation_deliveries_updated"
	]],
	["conversations", [
		"idx_agent_conversations_identity",
		"idx_agent_conversations_lookup",
		"idx_agent_conversations_updated"
	]],
	["heartbeat_outcomes", []],
	["memory_embedding_cache", ["idx_memory_embedding_cache_updated_at"]],
	["memory_entry_origins", []],
	["memory_index_chunk_provenance", []],
	["memory_index_chunk_recall_metadata", []],
	["memory_index_chunks", ["idx_memory_index_chunks_path_source", "idx_memory_index_chunks_source"]],
	["memory_index_meta", []],
	["memory_index_sources", ["idx_memory_index_sources_source"]],
	["memory_index_state", []],
	["memory_session_tombstones", []],
	["message_tool_run_outcomes", ["idx_agent_message_tool_run_outcomes_occurred"]],
	["schema_meta", []],
	["session_canonical_validation_pending", []],
	["session_conversations", ["idx_agent_session_conversations_conversation", "idx_agent_session_conversations_primary"]],
	["session_entry_snapshots", []],
	["session_goal_operations", ["idx_agent_session_goal_operations_expiry"]],
	["session_input_completions", ["idx_agent_session_input_completions_session_key"]],
	["session_key_contract", []],
	["session_members", ["idx_agent_session_members_identity"]],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["session_participants", []],
	["session_pending_inputs", ["idx_agent_session_pending_inputs_session"]],
	["session_progress_cards", []],
	["session_reactions", []],
	["session_suggestions", ["idx_agent_session_suggestions_author_created", "idx_agent_session_suggestions_session_state_created"]],
	["session_transcript_active_events", [
		"idx_agent_transcript_active_event_seq",
		"idx_agent_transcript_active_messages",
		"idx_agent_transcript_context_pending"
	]],
	["session_transcript_archives", ["idx_agent_session_transcript_archives_pending", "idx_agent_session_transcript_archives_retention"]],
	["session_transcript_cold_archive_chunks", []],
	["session_transcript_cold_archives", []],
	["session_transcript_fts", []],
	["session_transcript_fts_config", []],
	["session_transcript_fts_content", []],
	["session_transcript_fts_data", []],
	["session_transcript_fts_docsize", []],
	["session_transcript_fts_idx", []],
	["session_transcript_fts_rows", ["idx_session_transcript_fts_rows_session_message"]],
	["session_transcript_index_state", []],
	["session_windows", [
		"idx_agent_session_windows_conversation",
		"idx_agent_session_windows_created_at",
		"idx_agent_session_windows_session_key",
		"idx_agent_session_windows_updated_at"
	]],
	["standing_intents", ["idx_standing_intents_lifecycle", "idx_standing_intents_scope"]],
	["standing_intents_fts", []],
	["standing_intents_fts_config", []],
	["standing_intents_fts_data", []],
	["standing_intents_fts_docsize", []],
	["standing_intents_fts_idx", []],
	["trajectory_runtime_events", ["idx_agent_trajectory_runtime_run"]],
	["transcript_event_identities", [
		"idx_agent_transcript_event_identity_sequence",
		"idx_agent_transcript_event_sequence",
		"idx_agent_transcript_message_idempotency"
	]],
	["transcript_events", []],
	["transcript_rewrite_watermarks", []],
	["context_engine_turn_outbox", ["idx_agent_context_engine_turn_outbox_engine"]],
	["conversation_deliveries", ["idx_agent_conversation_deliveries_reply", "idx_agent_conversation_deliveries_updated"]],
	["memory_embedding_cache", ["idx_memory_embedding_cache_updated_at"]],
	["memory_entry_origins", []],
	["memory_index_chunks", ["idx_memory_index_chunks_path_source", "idx_memory_index_chunks_source"]],
	["memory_index_sources", ["idx_memory_index_sources_source"]],
	["session_input_completions", []],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_last_interaction_at",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["session_participants", []],
	["session_reactions", ["idx_agent_session_reactions_message"]],
	["session_windows", [
		"idx_agent_session_windows_conversation",
		"idx_agent_session_windows_created_at",
		"idx_agent_session_windows_session_key",
		"idx_agent_session_windows_updated_at"
	]],
	["trajectory_runtime_events", ["idx_agent_trajectory_runtime_run"]],
	["transcript_event_identities", [
		"idx_agent_transcript_event_identity_sequence",
		"idx_agent_transcript_event_parent",
		"idx_agent_transcript_event_sequence",
		"idx_agent_transcript_message_idempotency"
	]],
	["transcript_events", []],
	["session_key_contract", []],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_last_interaction_at",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["session_windows", [
		"idx_agent_session_windows_conversation",
		"idx_agent_session_windows_created_at",
		"idx_agent_session_windows_session_key",
		"idx_agent_session_windows_updated_at"
	]],
	["session_transcript_fts_rows", ["idx_agent_transcript_fts_rows_session"]],
	["session_transcript_index_state", []],
	["memory_index_chunks", ["idx_memory_index_chunks_path_source", "idx_memory_index_chunks_source"]],
	["transcript_events", []],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_last_interaction_at",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_last_interaction_at",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["context_engine_turn_outbox", ["idx_agent_context_engine_turn_outbox_engine"]],
	["session_nodes", [
		"idx_agent_session_nodes_active",
		"idx_agent_session_nodes_archived_at",
		"idx_agent_session_nodes_current_session_id",
		"idx_agent_session_nodes_entry_not_valid",
		"idx_agent_session_nodes_entry_valid_pending",
		"idx_agent_session_nodes_label",
		"idx_agent_session_nodes_last_interaction_at",
		"idx_agent_session_nodes_parent_session_key",
		"idx_agent_session_nodes_spawned_by",
		"idx_agent_session_nodes_status",
		"idx_agent_session_nodes_updated_at"
	]],
	["state_leases", []]
];
const fingerprints$4 = {
	d6ea4f25014de415b806f2b77b529b838444f8aacf44cb2192ba6990fdfab566: [
		"agent",
		"22365c27fbdfb45c71d0df7692b8c8c1dee844c2b27297710612cb2484f52e1b",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56
		],
		[]
	],
	"0d8863d033ed867b9e5410fbf5653fff5668cde5bc9933efdc54a948ef28b3a7": [
		"agent-version-1",
		"0ac0c6eca2bd401dba88942343f73a31b0c1fa320b4ef72672a421775667f341",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			59,
			60,
			12,
			13,
			61,
			15,
			62,
			17,
			18,
			19,
			20,
			22,
			24,
			63,
			26,
			27,
			64,
			65,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			70,
			56
		],
		[]
	],
	"987c7895f0acfaa27bdd4af5532a6a9d7364cbbefe8fe63fa9775b9520b25f85": [
		"agent-version-18",
		"516c6a0cbc9a63134e84a65c3af806fbc6b526292c614c84109f4a2b2c106afc",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			59,
			60,
			12,
			13,
			61,
			15,
			62,
			17,
			18,
			19,
			20,
			22,
			24,
			63,
			26,
			27,
			64,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			70,
			56
		],
		[]
	],
	"7a92498057481f996a0c0716dd078ea69694645fbdb3a011dadaee411478b7ad": [
		"agent-version-21",
		"fd83bd56e757e27046bc16f16e0dfd056a4bdb4c187672807f9286089fd4c130",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			59,
			60,
			12,
			13,
			61,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			24,
			63,
			71,
			27,
			72,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			45,
			73,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			70,
			56
		],
		[]
	],
	"789a67b22bc47d0b58acb19a6041b3ba55bd68c7e7271a4043573739edae02d1": [
		"agent-version-22",
		"1571750d60d036d5b09e53c9d062396551d72f79642ee52ae104e9213da8592c",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			59,
			60,
			12,
			13,
			61,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			24,
			63,
			71,
			27,
			72,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			74,
			75,
			73,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			70,
			56
		],
		[]
	],
	dd91f9df477a6b80f156003269b951f0d4e55d62e6dec37ad23dc909ed61f71f: [
		"agent-version-23",
		"4cd5cf45ce55fd199d3025021381ad10187c3a5db5340aec56aa108c5a315611",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			10,
			60,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			24,
			63,
			71,
			27,
			72,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			73,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			77,
			56
		],
		[]
	],
	"9b51fb6f3b7692ed5b1d114c9123184aacb35d5c8450f896b5d289fd46f0ae60": [
		"agent-version-24",
		"7ba969c7ed61eb3596c809150d7c46676bfb3d8310052ca5f07141762b345e9b",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			10,
			60,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			71,
			27,
			78,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			73,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			77,
			56
		],
		[]
	],
	"17cbb50319db12e22248e0397cb068ce670687a96328f502ce3577e4798ae299": [
		"agent-version-25",
		"f4118fc6b09e2d36542335eec66c82e9846b7f50e69e56076814dea6e1244aeb",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			57,
			58,
			8,
			9,
			10,
			60,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			79,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			77,
			56
		],
		[]
	],
	ff21eb3fb5a5836d520af3ea0777944cbcfa61aff52a64d0726a4d6b527823c3: [
		"agent-version-26",
		"86dbc086643d83045d9397da12e5e7a5d197b08a10a8aea4942ee7473f03d9ee",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			80,
			58,
			8,
			9,
			10,
			60,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			81,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			55,
			56
		],
		[]
	],
	"227fcd299f5dfd3012abd0f110cd028ba6add9155bc74e2e558aadeae2761349": [
		"agent-version-27",
		"40d0b84e2467b65ff57c4e8171af1a6b0cc54e0e1b5602b6abbe53fc8c10e151",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			60,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			81,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			55,
			56
		],
		[]
	],
	b2e17ebad450773253e5dddaeb87e6baef26b1c20a48982ed9df7ffea4210511: [
		"agent-version-28",
		"a48c6c4d7bc63bb0c14eb2010893f31aa216e4a0ee135e40c81598a39c64b61f",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			11,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			81,
			29,
			30,
			31,
			66,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			54,
			55,
			56
		],
		[]
	],
	abf65b8c18ccb84f0e65b8e4faa6fef6abc23b6bab5e93086339f640d2146082: [
		"agent-version-29",
		"ede47c9558c7c22dfd89ed56f0bc28a9d22e512aa69af0ae3acacc989337dc0e",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			11,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			54,
			55,
			56
		],
		[]
	],
	dbab54723ad6be5e0146085df0789ef92d03b867c53bed915d804fb4c60b3068: [
		"agent-version-30",
		"afa4044fdeabdb3042002c27a39be73d1f2edf8c4135515266cf6613adc7f0ba",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			11,
			12,
			13,
			76,
			15,
			62,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56
		],
		[]
	],
	"57f4523156caf6b8446afbd95e0fede01f1c917771242cd05c61c1b48b7e157e": [
		"agent-version-31",
		"4ac0d88399760668d6021213299ff6897bcfd672d2373d5c47b6f0afa31e04a1",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56
		],
		[]
	],
	"9ffa671518cafee606f88dd17bfdfa9792d9deece5f6773e3cae4de2c10fc84b": [
		"agent-version-37",
		"08f828422ad38a4ad92a46abdd793fd45ce6c9e09e72d83177130079588ea41e",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			58,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			63,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56
		],
		[]
	],
	"067f95cffb76737d9084b726b640bc79b266b19279e6b1a3d2322d0e298c6ab6": [
		"agent-v14-core",
		"14b30834a4c01ee92da4b3390aebbd49d9a8f4d0fb3a40fb517b8093ffb11c76",
		[
			0,
			1,
			2,
			5,
			57,
			58,
			8,
			9,
			59,
			60,
			12,
			13,
			61,
			15,
			62,
			17,
			18,
			19,
			20,
			22,
			24,
			63,
			26,
			64,
			65,
			30,
			34,
			35,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			45,
			67,
			47,
			48,
			49,
			50,
			51,
			52,
			68,
			69,
			70,
			56
		],
		[]
	],
	aca181a3ea4d5a94d263653e1b75d2327bd449673d631e9d22c6cb9fe25e40ea: [
		"agent-v14-session-sharing",
		"dcd6c30e5c80fa6647cf4b3257fc0c5a6e3440c20333797263b813add4f43fa2",
		[27],
		[]
	],
	be5d39d4389597fcfe2942f51a97d5b1f4e0aa1d6b184677e6abcedc162a2cf0: [
		"agent-v14-additive",
		"08e596f53eef1390bb3048a8c3807ea2413fde157899e0feb314aeebeb26e132",
		[66, 33],
		[]
	],
	"9b07b30dc725415736f5873babff2b98a1e8bf40e0afbf4eb8cf3d3cf700dc0b": [
		"agent-v14-board",
		"535e952ff0024800a42260733be4f1ab5095d5f7578d78555e351c3c336b4f5a",
		[3, 4],
		[]
	],
	"83673559dc6bba9fdf13d5a9131b030103935b04d7c81620b0a67f43cb49f970": [
		"agent-progress-card",
		"cbda56cf07f5a79268f761f3c0478fd5c3a6ddefde2cb72a933d9eef110a17a1",
		[31],
		[]
	],
	fdc21b6dc361c491311c11d91fbda296535a9c34dd20f0ab03b949b8a698ded0: [
		"agent-retired-state-leases",
		"6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc",
		[82],
		[]
	],
	c45b82b3c3aa8ecc3b2cc09dcf38bd568edfa8305f54b5bb959c975a55571ece: [
		"agent-legacy-participants",
		"30851780a54c5bd9b7bd3be1f420fc2b3e61839901e1a726e6cb24a10f8d4276",
		[65],
		[]
	],
	"6ce6f0ae658b1b77759d335e07e75d9371e27363c998bbf9b0e5fc5a132bc4cb": [
		"agent-deployed-fts-rows",
		"81df0b00eeb5ae756a6acce81b099c432f6127233d47582dd60ca32eed304768",
		[74],
		[]
	],
	"0e9e5f47efa71d187ed505aee8d1e423865a5de8df5387a15759194561307e72": [
		"agent-legacy-transcript-events",
		"6e5d060cc60439ef893bf9bcf395552be213733a1021f82d9ea1173e6103ed2e",
		[70],
		[]
	]
};
let data$4;
function readSqliteAgentFingerprint(e) {
	const t = fingerprints$4[e];
	if (!t) return;
	const [n, r, i, a] = t;
	return {
		id: n,
		fingerprint: r,
		viewNames: a,
		tableNames: i.map((e) => tableNames$4[e][0]),
		indexNames: i.flatMap((e) => tableNames$4[e][1])
	};
}
function readSqliteAgentCatalog(e) {
	if (!fingerprints$4[e]) return;
	data$4 ??= createRequire(import.meta.url)(fileURLToPath(new URL("../assets/sqlite-schema/sqlite-agent-catalogs.json", import.meta.url).href));
	const t = data$4.catalogs[e];
	return {
		tables: t.tables.map((e) => data$4.tables[e]),
		views: t.views
	};
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-client-catalogs.ts
const tableNames$3 = [
	["client_credential_migration", []],
	["device_auth_tokens", ["idx_device_auth_tokens_updated"]],
	["device_identities", ["idx_device_identities_device"]],
	["gateway_origin_device_tokens", []],
	["native_exec_socket_credentials", []]
];
const fingerprints$3 = { "8e4004e9307fcb7ad18d0b12c076f008afd89a8dcacff53e9d40a3b7881acab9": [
	"client-credentials-v1",
	"a00fccb1a356c0d0f77c40341f320602e4f73396bd88865a238b7f4187edd949",
	[
		0,
		1,
		2,
		3,
		4
	],
	[]
] };
let data$3;
function readSqliteClientFingerprint(e) {
	const t = fingerprints$3[e];
	if (!t) return;
	const [n, r, i, a] = t;
	return {
		id: n,
		fingerprint: r,
		viewNames: a,
		tableNames: i.map((e) => tableNames$3[e][0]),
		indexNames: i.flatMap((e) => tableNames$3[e][1])
	};
}
function readSqliteClientCatalog(e) {
	if (!fingerprints$3[e]) return;
	data$3 ??= createRequire(import.meta.url)(fileURLToPath(new URL("../assets/sqlite-schema/sqlite-client-catalogs.json", import.meta.url).href));
	const t = data$3.catalogs[e];
	return {
		tables: t.tables.map((e) => data$3.tables[e]),
		views: t.views
	};
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-daemon-catalogs.ts
const tableNames$2 = [["daemon_runtime_pin_migration", []], ["daemon_runtime_pins", []]];
const fingerprints$2 = { "2da8e5914c65eb868e035a1ebbab7a104fceca3c4b4c1e44dccd14c3387c3376": [
	"daemon-runtime-pins-v1",
	"126cb31aa1921bcac9c54618fdbb59cc157d4d86a456508eea2879db32a716e0",
	[0, 1],
	[]
] };
let data$2;
function readSqliteDaemonFingerprint(e) {
	const t = fingerprints$2[e];
	if (!t) return;
	const [n, r, i, a] = t;
	return {
		id: n,
		fingerprint: r,
		viewNames: a,
		tableNames: i.map((e) => tableNames$2[e][0]),
		indexNames: i.flatMap((e) => tableNames$2[e][1])
	};
}
function readSqliteDaemonCatalog(e) {
	if (!fingerprints$2[e]) return;
	data$2 ??= createRequire(import.meta.url)(fileURLToPath(new URL("../assets/sqlite-schema/sqlite-daemon-catalogs.json", import.meta.url).href));
	const t = data$2.catalogs[e];
	return {
		tables: t.tables.map((e) => data$2.tables[e]),
		views: t.views
	};
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-memory-catalogs.ts
const tableNames$1 = [
	["memory_index_chunk_provenance", []],
	["memory_index_chunk_recall_metadata", []],
	["memory_index_chunks", []],
	["memory_index_meta", []],
	["memory_index_sources", []],
	["memory_index_state", []],
	["memory_embedding_cache", []],
	["memory_embedding_cache", ["idx_memory_embedding_cache_updated_at"]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_embedding_cache", ["idx_memory_embedding_cache_updated_at"]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_embedding_cache", ["idx_memory_embedding_cache_updated_at"]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks", [
		"idx_memory_index_chunks_path",
		"idx_memory_index_chunks_path_source",
		"idx_memory_index_chunks_source"
	]],
	["memory_index_chunks_fts", []],
	["memory_index_chunks_fts_config", []],
	["memory_index_chunks_fts_content", []],
	["memory_index_chunks_fts_data", []],
	["memory_index_chunks_fts_docsize", []],
	["memory_index_chunks_fts_idx", []],
	["memory_index_paths_fts", []],
	["memory_index_paths_fts_config", []],
	["memory_index_paths_fts_content", []],
	["memory_index_paths_fts_data", []],
	["memory_index_paths_fts_docsize", []],
	["memory_index_paths_fts_idx", []],
	["memory_index_chunks_fts", []],
	["memory_index_paths_fts", []],
	["memory_index_chunks_vec", []],
	["memory_index_chunks_vec_chunks", []],
	["memory_index_chunks_vec_info", []],
	["memory_index_chunks_vec_rowids", []],
	["memory_index_chunks_vec_vector_chunks00", []]
];
const fingerprints$1 = {
	"27ef93ea7e9facb77b3eead587fd5cb7647bade7c4a0dbc8b03c8f34ba64386c": [
		"memory-index-v1-cache-0",
		"59289b93110d1d3eaf27f0e6d5bef8bc45987a70842597a67302ace145717ec9",
		[
			0,
			1,
			2,
			3,
			4,
			5
		],
		[]
	],
	"93a3fb3dfbcf93f896dd17b298be4c18d2b6d6ee8ab14e46872ecbeadd557654": [
		"memory-index-v1-cache-1",
		"a2cc43111506fdc355121bec101f93d7035cdd20d870dfc5fc5c75ce36eddee8",
		[
			6,
			0,
			1,
			2,
			3,
			4,
			5
		],
		[]
	],
	b53e7fcdaab29e825534bce175eef96cff2c705bc465308f369f67627a5b53bb: [
		"memory-cache-binary-strict-1",
		"43fea47c3ea00e8ff457540564e0915cb72e75b8f14b119ece1bd74746425ff8",
		[7],
		[]
	],
	ac226e0f177ccc01aa1d3df066f10277676100bd8cd01588b860c5d89e8e2269: [
		"memory-chunks-binary-strict-1-recall-0",
		"0e8704d882f34e24b97613115d6552258400608839065e8da56df4b336cfca51",
		[8],
		[]
	],
	"257f0fa39f94ca852ed0887002bd286e34727ff73b4825ac5b53cafcb174f453": [
		"memory-chunks-binary-strict-1-recall-1",
		"ed5c454b17073742bf3343b99baec45c854a0927ccd95ab1131ec6856ef08d60",
		[9],
		[]
	],
	de46110eea2bb88cd753b7c0efa7aa1becddcb90b1a4b5c9502d5acc41d50939: [
		"memory-chunks-binary-strict-1-recall-2",
		"7c8785c42572cc6669a29704d2079f13a47479484250495898dc3b82e2b8f169",
		[10],
		[]
	],
	cc79633111488622f8cf8d50157280d4f9ce002ddf8b731ea7bfce3c1acbc7e9: [
		"memory-chunks-binary-strict-1-recall-3",
		"37b37df7f7ec34ba7fb38ea652c85d9db954b648b3b8b0f2cee1136ace8c4d52",
		[11],
		[]
	],
	b12e9eee6fc308eb0d125008d0f4a8a6a7921f87cb0ad03c0dcbabc0f4c9e30b: [
		"memory-chunks-binary-strict-1-recall-4",
		"ded3749dc75f0b9853570d3a29f52e3296835f164d7c7e1471a368e2d79523d3",
		[12],
		[]
	],
	b74546436177f3480bbfd0ca7d6f7558e50671a41041aa3b02a4a1d70d4e0124: [
		"memory-chunks-binary-strict-1-recall-5",
		"596ee273523cdc7922a0718a926cff468a4e740a8c653a3e0bebe601037eee7f",
		[13],
		[]
	],
	"7b8739ff03a7dabf85ff3846c7cb172a402613024754e064cfd775441b037d2e": [
		"memory-chunks-binary-strict-1-recall-6",
		"126e55c1ce40d42ccb97cdf3f4e35497cf712948f36d794dca163e6a8e0559c4",
		[14],
		[]
	],
	"6055ec94ab523719e18078aee8fa973f92d8ba968ecb104f0d61bee314739152": [
		"memory-chunks-binary-strict-1-recall-7",
		"05b66c0fd58af7228e74cb7e881a9ddfe4bc77445ae6215ebf1c38463155d430",
		[15],
		[]
	],
	f8f4dda5eccd6ef9b6e82a2187a7dfad76ae3783a0fcfe9623eadc18eecf44b0: [
		"memory-cache-text-strict-0",
		"ca38a58fc93a8fb71370dae23cb0ef9b9d7376b6d48b0cef0b28a1bd9433e8fe",
		[16],
		[]
	],
	b9b96c68cff42faadc99ad35ff55d2df4e432e87adf8d5d512c4f2d8e01477e6: [
		"memory-chunks-text-strict-0-recall-0",
		"f62e05b1dac229e56f6bd08d3115e2ea93aec01aa558b17d94ea5bc47cc76cc4",
		[17],
		[]
	],
	"572644cd115904fabec76e50a6d81b73b5a738b11e879a1c07bc7f83b12fac8f": [
		"memory-chunks-text-strict-0-recall-1",
		"557db378be09c17e06988bb635f5c1eeac94a0780251f379ca0636c6f955befd",
		[18],
		[]
	],
	dc69ef337a630e1c40398b494826d3ef6d8ca67e8a42d5f5b40142cd00e51012: [
		"memory-chunks-text-strict-0-recall-2",
		"f6dea371a0755a537b45176e3219b0fb5123d9bda94527e1e967a63ff1678cfa",
		[19],
		[]
	],
	d3e0bbf0a82ae4ca0ae435e0a9943fa32a48ac8d37421809d9fd36d4c0680b13: [
		"memory-chunks-text-strict-0-recall-3",
		"60c4185a64288b050f8ddc89727ff13a6103baeda976c67c791e3c7f7b3e6c95",
		[20],
		[]
	],
	f1dbb03304f512a8a7a0e1606d23e7ff1c97223599d3a889850ad0ed69299af3: [
		"memory-chunks-text-strict-0-recall-4",
		"f0061cf0170bf18527093f950d0496fd4601058bc99e9c29dafd6b305dd87296",
		[21],
		[]
	],
	"454eb2147f9c1adc93e9210a7aabc5c1fc6a4f937f9e712d632f1b7c76b28b7c": [
		"memory-chunks-text-strict-0-recall-5",
		"2f9c2c14d4995f96d632ba23438b90a607c6345080b59c06fa6fe18fbc1ef789",
		[22],
		[]
	],
	"2b12ceffe3ff69a67629d2e195143f53fe0d7f947108f4ee7ce068fa7b288dcf": [
		"memory-chunks-text-strict-0-recall-6",
		"9e7d3aa7fbfd911601a9c372bca6099062bef2a24e26a5d08c21db34abb3e937",
		[23],
		[]
	],
	"39602ef462e71c3c485358a1572c7c3f82cda5fe147dbbca5ecf601f72009238": [
		"memory-chunks-text-strict-0-recall-7",
		"5764f18a476a4e6a6aa6f40f9538ac70e10fe5344309dd245d0db339913fbc5d",
		[24],
		[]
	],
	"16de82c2873083fc417acc8e09140fd32cbdfb1a6633a82e8746cfe9650c18db": [
		"memory-cache-text-strict-1",
		"aacfccd3fbb3a171753d866a2dbcac2e6ab0cf26d94fa2fa8bd17f7b555c8857",
		[25],
		[]
	],
	"50709191e29c47d2702efd82ba0b62cdd7f1b027d532848c2cb08c77b69fa679": [
		"memory-chunks-text-strict-1-recall-0",
		"3477ae66bf655ea65812a5e2dcedeae255314ba79214740c03c2a7fab99e1daa",
		[26],
		[]
	],
	bbc96ed43fce73bc3051d0c510bdc3fbfec16c6dd4fa557bd349ac7b60d325f7: [
		"memory-chunks-text-strict-1-recall-1",
		"c672e90a018dba96b0d27706a9aeacc809781009464fcb767a9c4304ae6494b0",
		[27],
		[]
	],
	"14b7b7910dc0afdcc0bdd78b889d487bd4281ba57342ba21fbc17e2ac4ab7a5c": [
		"memory-chunks-text-strict-1-recall-2",
		"6070f3ccf01a8815f7cb924aff58ce3ec1a215cb01782915a93b6dc2c334991d",
		[28],
		[]
	],
	"671a11689fc7970d79b4be242cf747d6831e32ae4adf3d0cde360d0c43427e2c": [
		"memory-chunks-text-strict-1-recall-3",
		"455f88a45ca48ac0a6a4233d483731d0b0960d2d3610db7f298c39da1c568ae4",
		[29],
		[]
	],
	"11a2dca1aa8a69e4db87d79208841dff4abd20d943a3910afc8cc80d92912e9a": [
		"memory-chunks-text-strict-1-recall-4",
		"abcc7d9bd0fb27f1b592b729a59c6a81fbd352917b0996f472ea42bac6dfeef2",
		[30],
		[]
	],
	cb98ad487e0d9599983c000d5bdf096ee1f323b982e4afc44229111e5aef2cd1: [
		"memory-chunks-text-strict-1-recall-5",
		"cb12b76fbe6f986bd1f4e7f727731515068c6a6b83d8fb0def4d041f404830c5",
		[31],
		[]
	],
	"4a5393a69f56db40e0ada5dc8577a88c91c44f65900e234d46d487d0b5294781": [
		"memory-chunks-text-strict-1-recall-6",
		"64fbd15911fb40635818b4f3397e0749b0b62b92b87fc6c0d067079125ce8f8a",
		[32],
		[]
	],
	"05e8eaf13a81810f99cc62d7d25a202c115743c80ebd80c625a0beab0960b892": [
		"memory-chunks-text-strict-1-recall-7",
		"8422ba9c6185a2156a9345807b90032db6858b2f5a12541268d9f4c7967d32e9",
		[33],
		[]
	],
	"0ab7773eb3198fc86adb541fe032581ce24b93cd39b7aa229fdf50c8b3f9fe6c": [
		"memory-body-fts-v1-unicode61",
		"c16bed5072a5a006ca243b73fefb1fc86bce894f87a6c8713e87dced77493eb2",
		[
			34,
			35,
			36,
			37,
			38,
			39
		],
		[]
	],
	"315cb6d0263f5aff152863d03d253f867104d86d5028ad2c51e348d10fba2f1a": [
		"memory-path-fts-v1-unicode61",
		"b18b06cf6a1ea0655eeff9c0451fae13336f2ac280468680e7d91370016cf23b",
		[
			40,
			41,
			42,
			43,
			44,
			45
		],
		[]
	],
	"32a102b66f747e2fb75d4b23b2a83928c69d086604e997a29a713eac7a62ec46": [
		"memory-body-fts-v1-trigram",
		"15c47771111fc5beb3af779b2f20333755c0069b7bb113ac6aac160f6aabef7f",
		[
			46,
			35,
			36,
			37,
			38,
			39
		],
		[]
	],
	"02ae4f88ed6c87a22d6eaeb0e4e0a4ececc8d7dd37017aa04659494fd8481ccd": [
		"memory-path-fts-v1-trigram",
		"e2b47e11cf4fa6228471d8f6be5654a6d35ec80d5e0c9e7fd5d6654f47ac200e",
		[
			47,
			41,
			42,
			43,
			44,
			45
		],
		[]
	],
	"8a70e5b7bb1c8163cf6d4f38a6a69165a01f3f44204bbd910428f371ebc376c7": [
		"memory-vector-v1",
		"ebe6798602214794cd87d21d200eaa88c4864fcb30bf8fc0b902246a7fce5023",
		[
			48,
			49,
			50,
			51,
			52
		],
		[]
	]
};
let data$1;
function readSqliteMemoryFingerprint(e) {
	const t = fingerprints$1[e];
	if (!t) return;
	const [n, r, i, a] = t;
	return {
		id: n,
		fingerprint: r,
		viewNames: a,
		tableNames: i.map((e) => tableNames$1[e][0]),
		indexNames: i.flatMap((e) => tableNames$1[e][1])
	};
}
function readSqliteMemoryCatalog(e) {
	if (!fingerprints$1[e]) return;
	data$1 ??= createRequire(import.meta.url)(fileURLToPath(new URL("../assets/sqlite-schema/sqlite-memory-catalogs.json", import.meta.url).href));
	const t = data$1.catalogs[e];
	return {
		tables: t.tables.map((e) => data$1.tables[e]),
		views: t.views
	};
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-state-catalogs.ts
const tableNames = [
	["acp_replay_events", []],
	["acp_replay_sessions", ["idx_acp_replay_sessions_key_updated", "idx_acp_replay_sessions_updated"]],
	["acp_sessions", [
		"idx_acp_sessions_agent_activity",
		"idx_acp_sessions_resume_acpx",
		"idx_acp_sessions_resume_agent",
		"idx_acp_sessions_state_activity"
	]],
	["agent_database_leases", []],
	["agent_databases", []],
	["agent_deletion_journal", []],
	["agent_provenance", []],
	["apns_registration_tombstones", []],
	["apns_registrations", ["idx_apns_registrations_updated"]],
	["audit_events", [
		"idx_audit_events_agent_sequence",
		"idx_audit_events_channel_sequence",
		"idx_audit_events_direction_sequence",
		"idx_audit_events_kind_sequence",
		"idx_audit_events_run_sequence",
		"idx_audit_events_session_sequence",
		"idx_audit_events_status_sequence",
		"idx_audit_events_time"
	]],
	["audit_identity_keys", []],
	["backup_runs", ["idx_backup_runs_created"]],
	["capture_blobs", []],
	["capture_events", ["capture_events_flow_idx", "capture_events_session_ts_idx"]],
	["capture_sessions", []],
	["channel_ingress_events", [
		"idx_channel_ingress_claims",
		"idx_channel_ingress_lane",
		"idx_channel_ingress_pending"
	]],
	["channel_pairing_allow_entries", ["idx_channel_pairing_allow_account"]],
	["channel_pairing_requests", ["idx_channel_pairing_requests_code", "idx_channel_pairing_requests_created"]],
	["clawhub_promotion_claims", []],
	["config_health_entries", []],
	["config_machine_state", []],
	["config_revision_keys", []],
	["cron_job_runtime_authorities", []],
	["cron_job_scratch", ["idx_cron_job_scratch_store_updated"]],
	["cron_jobs", ["idx_cron_jobs_store_order"]],
	["cron_run_receipts", [
		"cron_run_receipts_cursor_id_idx",
		"idx_cron_run_receipts_active_job",
		"idx_cron_run_receipts_job_history"
	]],
	["cron_run_trigger_state_retirements", []],
	["current_conversation_bindings", [
		"idx_current_conversation_bindings_conversation",
		"idx_current_conversation_bindings_expires",
		"idx_current_conversation_bindings_target"
	]],
	["delivery_queue_entries", [
		"idx_delivery_queue_bounded_retention",
		"idx_delivery_queue_failed",
		"idx_delivery_queue_pending",
		"idx_delivery_queue_session",
		"idx_delivery_queue_target"
	]],
	["device_bootstrap_tokens", ["idx_device_bootstrap_tokens_ts"]],
	["device_pair_setup_completions", []],
	["device_pairing_join_codes", []],
	["device_pairing_paired", ["idx_device_pairing_paired_approved"]],
	["device_pairing_pending", ["idx_device_pairing_pending_device"]],
	["diagnostic_events", ["idx_diagnostic_events_scope_sequence"]],
	["exec_approvals_config", []],
	["execution_decision_facts", [
		"execution_decision_facts_context_occurred_idx",
		"execution_decision_facts_cursor_id_idx",
		"execution_decision_facts_run_occurred_idx"
	]],
	["execution_identity_contexts", ["execution_identity_contexts_run_created_idx"]],
	["execution_owner_lifecycle_bindings", []],
	["flow_runs", [
		"idx_flow_runs_owner_key",
		"idx_flow_runs_status",
		"idx_flow_runs_updated_at"
	]],
	["gateway_boot_lifecycle", ["idx_gateway_boot_lifecycle_started"]],
	["gateway_restart_handoff", ["idx_gateway_restart_handoff_expiry"]],
	["gateway_restart_intent", []],
	["gateway_restart_sentinel", ["idx_gateway_restart_sentinel_ts"]],
	["github_personal_publication_requests", ["idx_github_personal_publication_owner_session", "idx_github_personal_publication_pending"]],
	["github_publication_requests", ["idx_github_publication_requests_pending"]],
	["github_publication_session_lifecycles", []],
	["github_repository_publication_requests", ["idx_github_repository_publication_personal_request", "idx_github_repository_publication_shared_request"]],
	["local_workspace_manifest_nodes", []],
	["local_workspace_projections", []],
	["local_workspace_source_path_sets", []],
	["local_workspace_tree_packs", []],
	["macos_port_guardian_records", ["idx_macos_port_guardian_records_port"]],
	["managed_outgoing_image_records", [
		"idx_managed_outgoing_images_agent_message",
		"idx_managed_outgoing_images_agent_session",
		"idx_managed_outgoing_images_message",
		"idx_managed_outgoing_images_session"
	]],
	["mcp_oauth_pending_authorizations", []],
	["mcp_oauth_stores", []],
	["meeting_transcript_sessions", [
		"idx_meeting_transcript_sessions_account",
		"idx_meeting_transcript_sessions_agent",
		"idx_meeting_transcript_sessions_chronology",
		"idx_meeting_transcript_sessions_export_key",
		"idx_meeting_transcript_sessions_id",
		"idx_meeting_transcript_sessions_slug",
		"idx_meeting_transcript_sessions_source",
		"idx_meeting_transcript_sessions_started"
	]],
	["meeting_transcript_summaries", []],
	["meeting_transcript_utterances", ["idx_meeting_transcript_utterances_id"]],
	["migration_runs", ["idx_migration_runs_started"]],
	["migration_sources", ["idx_migration_sources_path", "idx_migration_sources_run"]],
	["native_hook_relay_bridges", ["idx_native_hook_relay_bridges_expires"]],
	["node_worker_launch_boots", []],
	["node_worker_launch_cleanup", []],
	["node_worker_launch_containers", []],
	["node_worker_launch_process_scopes", []],
	["node_worker_launches", ["idx_node_worker_launches_terminal_completed"]],
	["node_worker_prepared_workspaces", []],
	["node_worker_turns", ["idx_node_worker_turns_active_owner", "idx_node_worker_turns_terminal_completed"]],
	["official_external_plugin_catalog_snapshots", ["idx_official_external_plugin_catalog_snapshots_updated"]],
	["operator_approval_execution_identities", []],
	["operator_approval_standing_grant_generations", []],
	["operator_approval_standing_grants", ["idx_operator_approval_standing_grants_binding"]],
	["operator_approvals", [
		"idx_operator_approvals_cursor_id",
		"idx_operator_approvals_resolution_ref",
		"idx_operator_approvals_resolved",
		"idx_operator_approvals_runtime_pending",
		"idx_operator_approvals_source_run_resolved",
		"idx_operator_approvals_source_session_created",
		"idx_operator_approvals_status_expiry"
	]],
	["outbound_media_provenance", []],
	["outbound_message_execution_bindings", ["outbound_message_execution_bindings_execution_event_idx"]],
	["outbound_message_progress", ["outbound_message_progress_occurred_idx", "outbound_message_progress_run_occurred_idx"]],
	["plugin_binding_approvals", ["idx_plugin_binding_approvals_plugin"]],
	["plugin_blob_entries", ["idx_plugin_blob_expiry", "idx_plugin_blob_listing"]],
	["plugin_state_entries", ["idx_plugin_state_expiry", "idx_plugin_state_listing"]],
	["projects", []],
	["sandbox_persistent_execs", [
		"idx_sandbox_persistent_execs_container",
		"idx_sandbox_persistent_execs_container_name",
		"idx_sandbox_persistent_execs_source"
	]],
	["sandbox_registry_entries", [
		"idx_sandbox_registry_last_used",
		"idx_sandbox_registry_session",
		"idx_sandbox_registry_updated"
	]],
	["schema_meta", []],
	["secret_store_entries", ["secret_store_entries_live_idx"]],
	["session_groups", []],
	["session_repository_workspaces", []],
	["session_state_events", ["idx_session_state_events_session_sequence", "idx_session_state_events_time"]],
	["session_state_heads", []],
	["session_upstream_links", ["idx_session_upstream_links_catalog_id"]],
	["session_watch_cursors", ["idx_session_watch_cursors_target"]],
	["skill_library_entries", []],
	["skill_library_events", []],
	["skill_library_revisions", []],
	["skill_library_uploads", []],
	["skill_upload_chunks", []],
	["skill_uploads", ["idx_skill_uploads_expiry", "idx_skill_uploads_idempotency"]],
	["skill_usage", []],
	["skill_workshop_changes", ["idx_skill_workshop_changes_agent_time", "skill_workshop_changes_cursor_id_idx"]],
	["state_leases", ["idx_state_leases_expiry", "idx_state_leases_owner"]],
	["subagent_runs", [
		"idx_subagent_runs_child_session_key",
		"idx_subagent_runs_controller_session_key",
		"idx_subagent_runs_requester_session_key"
	]],
	["task_delivery_state", []],
	["task_runs", [
		"idx_task_runs_cron_runtime_order",
		"idx_task_runs_cron_source_order",
		"idx_task_runs_runtime_run"
	]],
	["template_cron_refs", []],
	["template_installs", []],
	["template_mcp_server_refs", []],
	["template_package_refs", []],
	["template_workspace_files", []],
	["update_runs", ["idx_update_runs_active", "idx_update_runs_created"]],
	["user_background_images", []],
	["user_preferences", []],
	["user_profile_identities", ["idx_user_profile_identities_authorization", "idx_user_profile_identities_profile_id"]],
	["web_push_approval_deliveries", ["idx_web_push_approval_deliveries_subscription"]],
	["web_push_subscriptions", ["idx_web_push_subscriptions_updated"]],
	["worker_environment_credentials", []],
	["worker_environment_ssh_fallback_ports", []],
	["worker_environments", ["idx_worker_environments_provider_lease", "idx_worker_environments_terminal_changed"]],
	["worker_inference_turns", ["idx_worker_inference_turns_pending_run"]],
	["worker_session_placement_moves", []],
	["worker_session_placements", [
		"idx_worker_session_placements_environment",
		"idx_worker_session_placements_reconcile",
		"idx_worker_session_placements_session_key"
	]],
	["worker_session_tool_operations", []],
	["worker_transcript_commit_heads", []],
	["worker_transcript_commits", []],
	["worker_turn_tool_authorities", []],
	["worker_workspace_pending_results", []],
	["worker_workspace_reconciliations", []],
	["workspace_generated_bootstrap_hashes", []],
	["workspace_path_aliases", ["idx_workspace_path_aliases_workspace"]],
	["workspace_setup_state", ["idx_workspace_setup_state_path"]],
	["worktree_provisioned_file_chunks", []],
	["worktree_templates", []],
	["worktrees", ["idx_worktrees_removed_at", "idx_worktrees_repo_fingerprint"]],
	["agent_provenance", []],
	["claw_cron_refs", []],
	["claw_installs", []],
	["claw_mcp_server_refs", []],
	["claw_package_refs", []],
	["claw_workspace_files", []],
	["local_workspace_projections", []],
	["local_workspace_projections", []],
	["acp_replay_events", ["idx_acp_replay_events_session_seq"]],
	["skill_usage", ["idx_skill_usage_key"]],
	["state_leases", ["idx_state_leases_expiry", "idx_state_leases_owner"]],
	["session_state_heads", []],
	["user_profile_emails", ["idx_user_profile_emails_profile_id"]],
	["user_profiles", []],
	["user_profile_identities", []],
	["user_profile_emails", []],
	["worker_environment_session_attachments", ["worker_environment_session_attachments_session_key"]],
	["sandbox_persistent_execs", []],
	["update_runs", []],
	["github_repository_publication_requests", []],
	["github_personal_publication_requests", []],
	["execution_identity_contexts", []],
	["node_worker_launches", []],
	["node_worker_turns", []],
	["web_push_approval_deliveries", []],
	["execution_decision_facts", []],
	["outbound_message_execution_bindings", []],
	["outbound_message_progress", []],
	["cron_run_receipts", []],
	["secret_store_entries", []],
	["github_publication_requests", []],
	["skill_workshop_changes", []],
	["state_leases", []],
	["commitments", [
		"idx_commitments_agent_due",
		"idx_commitments_agent_sent",
		"idx_commitments_scope_dedupe",
		"idx_commitments_scope_due",
		"idx_commitments_status_due"
	]],
	["commitments", [
		"idx_commitments_scope_dedupe",
		"idx_commitments_scope_due",
		"idx_commitments_status_due"
	]]
];
const fingerprints = {
	b2ec9b58da4e49ede387db0c7345fe2dcf3a2e228736ca92a5223fc8bf518a6b: [
		"state",
		"d331f5ba5e6b472b8358da366fe5cd66dd556f78630b407e7cd5fe8104edba06",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			88,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			103,
			104,
			105,
			106,
			107,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	d436399d596dabc437f6a66024912269ba78d4cebcdb8603202b041185ba4d2d: [
		"state-before-v36",
		"5c2559369839679bb534edddc847180532b37bd1b0ae419a715a860d0be92972",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			132,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			133,
			134,
			135,
			136,
			137,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			49,
			50,
			51,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			88,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	"9a869616f3471fe3b5f06a7c5d026a1940080a5df0e58a4b6c2088ab5ca745ff": [
		"state-before-v35",
		"9f90b9db5bceba7fba5559f518caea2b58e6fc363d6ddf160e4793ab4a08aa33",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			132,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			133,
			134,
			135,
			136,
			137,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			48,
			138,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			88,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	"36936a3edd8896ac1f8a0f73b6c8334385f9262f8eb7f1ddb1e83298554e2656": [
		"state-before-v31",
		"587dd22498db1b171f12a7838200384e50360089996b15307855845552be952d",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			132,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			133,
			134,
			135,
			136,
			137,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			139,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			88,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	"0fd39f9f198388f809574b23fd5532e4c762071e830d1da5c26a0ff7629c8032": [
		"state-before-v27",
		"7c96f5aeee1c1410ac0dd23b2a9534ab346f6528f34ab00fb9d724b74d6a3f59",
		[
			140,
			1,
			2,
			3,
			4,
			5,
			132,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			133,
			134,
			135,
			136,
			137,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			139,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			88,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			141,
			98,
			142,
			100,
			101,
			102,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	"79517c2d72c03b744524b3dd9d78389ec065e25ff619698a3b10e8cb252f5255": [
		"state-before-v26",
		"13c4baab95b591ab2bb07e7e06557f456b0b2207741bb7554e0f08e5d247b12e",
		[
			140,
			1,
			2,
			3,
			4,
			5,
			132,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			133,
			134,
			135,
			136,
			137,
			18,
			19,
			20,
			21,
			22,
			23,
			24,
			25,
			26,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			36,
			37,
			38,
			39,
			40,
			41,
			42,
			43,
			44,
			45,
			46,
			47,
			139,
			52,
			53,
			54,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			62,
			63,
			64,
			65,
			66,
			67,
			68,
			69,
			70,
			71,
			72,
			73,
			74,
			75,
			76,
			77,
			78,
			79,
			80,
			81,
			82,
			83,
			84,
			85,
			86,
			87,
			143,
			89,
			90,
			91,
			92,
			93,
			94,
			95,
			96,
			141,
			98,
			142,
			100,
			101,
			102,
			108,
			109,
			110,
			111,
			112,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	"54911300fd4efbb44a652d781badc61c60be05619fba7bd6a64b1d1bc2121a81": [
		"fragment-local_workspace_projections",
		"39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497",
		[
			48,
			49,
			50,
			51
		],
		[]
	],
	f0e11a6fff0a4b79b69a28a0f2ec4694fa1ee88672cac3b7338bc0a3bb9f8d19: [
		"state-feature-local_workspace_projections",
		"39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497",
		[
			48,
			49,
			50,
			51
		],
		[]
	],
	e119e5203e18e9fba13d43368408775eca1d809807579a697482ab2b7011e840: [
		"state-feature-local_workspace_manifest_nodes",
		"8db5abfb2c2f4c380c80647305b1e4bb5e6af7ac2fec71205a52a97d86835291",
		[48],
		[]
	],
	"3142caa54d9bd7d285b37ed3338ed9f4307ad3b32469bd88deecb8725301861e": [
		"state-feature-local_workspace_tree_packs",
		"a63984593fd118417812466c9ee0c189fd7d819401af1943a6f9c11730c47d87",
		[51],
		[]
	],
	e95059f2306c8231ee92ef3d76dfcb434a80885f08cbf39380f88a287f98bade: [
		"state-feature-local_workspace_source_path_sets",
		"ead9623df4d41d649f8e4af2351694db5bc8c4e70edb7d2322ba76c11d0dfddb",
		[50],
		[]
	],
	bc86e378ea153c42527b6106b01ba4cb8285cca40378ffa0142656577309723e: [
		"fragment-user_profiles",
		"268e6f3b53eb2048a3edf527da424f8df229a01166befc8137ea94dbb560227e",
		[
			144,
			111,
			145
		],
		[]
	],
	f5b54f0fedd88d94c24add8a1fd987ac8592b05d4615424bab9dbc0d19c9cd4a: [
		"state-feature-user_profiles",
		"2c2611b7d0c64f467494ae3922f763dee7fc023a5ee6b92d5821639b18e825aa",
		[
			144,
			146,
			145
		],
		[]
	],
	"9eaae0feb245733106045a2c6766d2a2a729a9bdb22b98ec4434c09d76663264": [
		"state-feature-user_profile_emails",
		"202fadb0df4fc5da385edddbda27e96126d0d7a2db6a63375fa506221163a4fb",
		[147],
		[]
	],
	"45451969c6ea5bebf37bbfba310467e482af74731a7cb0f2affb316059e21528": [
		"state-feature-user_profile_identities",
		"3a24e89bd446dffbef50b7bd4b87288abc6eb470c290eaabcb1761fbe5244c06",
		[146],
		[]
	],
	"561e14603e294368a12a2b5f6ecb0cc509d0b8847a93817286bd5a14d076ad0f": [
		"fragment-skill_library_entries",
		"c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d",
		[
			91,
			92,
			93,
			94
		],
		[]
	],
	"6b07280274e87ca0fa5bbc1887818497375298fa700b24852dc981f3da1da555": [
		"state-feature-skill_library_entries",
		"c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d",
		[
			91,
			92,
			93,
			94
		],
		[]
	],
	"43645abd05379894c2982bcd88b8dff0cd6c9802e5bf2ab6cc54af87a7e6a37d": [
		"state-feature-skill_library_revisions",
		"533218405c3e483d687da824cf15f9ebcb76ba69675946e95c134702dc199890",
		[93],
		[]
	],
	ea1b1fb7d6d8256ec58bc7c28541312c1a543e88bf9ed7e4366791ea243d8ec0: [
		"state-feature-skill_library_events",
		"e5269a0f2846007c0b3eef62963979fa7a2cdd01ced20906ec4ac407ace66c03",
		[92],
		[]
	],
	"31318a62bdb75dccad514a02adde07df11d26b756f51d1d50d0e6b19d399b26e": [
		"state-feature-skill_library_uploads",
		"ba066e91b42e768b5f705703783cce87eb90fac71a37cad9dfdf308a19ccceb6",
		[94],
		[]
	],
	ed3d9e7b13809b3a9b91d48d63816b26354681d727b96e39496d02c775343e1f: [
		"fragment-operator_approval_standing_grants",
		"9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa",
		[71, 72],
		[]
	],
	be37db3a4634164c401b2d8e5ac3c2d712cd9eb973e3f2b39daa578adedff0ae: [
		"state-feature-operator_approval_standing_grants",
		"9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa",
		[71, 72],
		[]
	],
	e23a5880a289da464471db5cfff10b9a6962b4d52c99260a3e366746c023de76: [
		"state-feature-operator_approval_standing_grant_generations",
		"0d525f0400a30f0582698e91e78f63063c08a8c06b3bcfe624dbd2f2fbe7834c",
		[71],
		[]
	],
	"7b8bf2fd3ae786c589bf138b32270450c1a2582bcb9a825c1eaf7fb3a7bcea06": [
		"fragment-worker_environment_session_attachments",
		"b95d7054311f0f2d1e0885104c66ff243dfe4f68b84ed2d814ae68e748574417",
		[148],
		[]
	],
	"6496f80e29da252472af802873996fc3cd761f245f4dcf6fefb1c7aee38e720b": [
		"fragment-sandbox_persistent_execs",
		"f885f117e199277aa5c23a9095f55e742797249d13e2f4e4df8fbef1daba399d",
		[81],
		[]
	],
	"156673e9396f27223073abdbbd2e13269bd7f45f577ed6aff00e017ab232d940": [
		"state-feature-sandbox_persistent_execs",
		"026ac7355b83187c8f7eef5cbd48ab36ba7de1b4fe40413ee1168ebff6c2d67a",
		[149],
		[]
	],
	"61e308c5a715e5ee5ff29b65a31d2e7ccd039498494d9afe120129f62f86b764": [
		"fragment-user_background_images",
		"1da03995969350f59b3f8a64d9144b781d467e6ea75f70d5abcd6e18734678e1",
		[109],
		[]
	],
	b36f4fc0be0d53e48e207f50a3cba34df76c4028a2d85201f7b262b1c7a4c2ab: [
		"fragment-update_runs",
		"7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55",
		[108],
		[]
	],
	c3db4ffcf4092146e5d923b60516a00a8db41825f8bffb138b848195576b987b: [
		"state-feature-update_runs",
		"4caad814f837565106a1a17b982bf4ff004bbdba00a6ff05a3b9c5ef2e5a5945",
		[150],
		[]
	],
	"7d47dc1ae79e1c40ab11a56da183af8e8e5dd1435e044ac4e44be2c6595783e0": [
		"fragment-session_repository_workspaces",
		"7f1a1b36d06c7c4cb5e84d6a16ca23de89dbac6b68c97c31897d1d1825a17d01",
		[86],
		[]
	],
	d62b52a34e2626a7983ae5c48268f04567e93170457e63502b7096486a6ce9f7: [
		"fragment-github_repository_publication_requests",
		"1ae034bde6e00a9b919bcbb987df8aebc5856ab6f4c979743355ecb682418a99",
		[47],
		[]
	],
	"6d205ed705fcf89e34e2679f192b2dd50e4cbcb9b06b473c3e81dd48c8811102": [
		"state-feature-github_repository_publication_requests",
		"bc5c46f3cc22c0572b25d10344108465509d7189e1d51b0f6fa335b1d86497cf",
		[151],
		[]
	],
	"079ee34fc1ed4ca27e807b01c7456deceacc57fead388917ff1b275b5047ab06": [
		"fragment-github_publication_session_lifecycles",
		"755e9a26722c11b5edd9d4f6bf270bfdc706428593de4216c311f85fad0a8e69",
		[46],
		[]
	],
	fc4d434c6c76c4e5c5b1fb9c54ebe7e98a395fea6370ada7ac4767ad755051ac: [
		"fragment-github_personal_publication_requests",
		"eda486fc6d1c12adfe86012cfa6d0f6afb64906b1d4c75e3785bda082281a4e1",
		[44],
		[]
	],
	"8a4a42e9e8549a0f2e73b33b4031673e2e939624d95586693bc2ac43742bf30f": [
		"state-feature-github_personal_publication_requests",
		"aeb05b8ff41f64e5bab165feac6f1abcdb6dfefc2a5bfbbe88e34861cc40922e",
		[152],
		[]
	],
	"0f3d662483be17f95f492157a8ba28b163afab9c52429ab6ff277ebe8b0a27fd": [
		"fragment-cron_job_runtime_authorities",
		"ebce08da69716c0011c0db38decb38e5eaa0069c6f8360e85afdec8c624a360e",
		[22],
		[]
	],
	e16c741ca5371718cf7d95114ee1043ad33db04c470f268ccbe3130f699998d9: [
		"fragment-cron_run_trigger_state_retirements",
		"0e85a9fecddeef5129569f503fb32cc0d94e9c98877286be10e15eb657e682bb",
		[26],
		[]
	],
	"632466e72325a428d8b4c4dfa1b7a14be9f57236bee791e9412ea07b24fca254": [
		"fragment-execution_identity_contexts",
		"15be6a7de30d2ecb9b15fed1eb13dd65da858f1eb378e95f737f14241c11b3d9",
		[37],
		[]
	],
	"7683ab1fd0bccb8e29499c3b6df0070d9cc7cd6249c8c103d654b015ce309417": [
		"state-feature-execution_identity_contexts",
		"2dc283d04b315fd0199a9e13653edb03c8614d12be2ca6f005c7e110aab62d2a",
		[153],
		[]
	],
	b796607c50ccb0e85abdec5d76b88b8076596077afe71e238b7831edd061f9e8: [
		"fragment-mcp_oauth_pending_authorizations",
		"39eae7dacb98a3cc36bd7598c4e416fc3f180c95aa78b7fd5a1f11afecf2d5b9",
		[54],
		[]
	],
	"15f660904a6ff5b2e08b57e7e1979ae85d7476426da0e6aa8fc35a013d557501": [
		"fragment-node_worker_launch_containers",
		"bae513184057ef120b3b7ff1f08fc0affa1293461353ac060f1c0148346225f5",
		[64],
		[]
	],
	"2703e870e99174d91597e44b5619574373f3da7030c4cd9907a8ac341f00802f": [
		"fragment-node_worker_launch_boots",
		"ce110d8dd52daad838b24137dc43979dafe784dd08348e09482093f47dd5d98b",
		[62],
		[]
	],
	"7c1c6d4fbba2f48e6ad4003bbc7d22b3b543034a8c2456fc542d2dac90c46aad": [
		"fragment-node_worker_launch_cleanup",
		"d45196104873c5924d0fddabdce7a4f08b8fab2c68880492de968c978ef031c8",
		[63],
		[]
	],
	"16bb8bbf8eb97d4a3895c031f758ca37106c072cd78e18b99e4f68463679c153": [
		"fragment-node_worker_launch_process_scopes",
		"d9ce1d80156505cb99854d410b48f37b0cf82d0259417bd3c64e1ff91d5b05b2",
		[65],
		[]
	],
	b6d0283d081e77179a54f4e54847168156095e3ec4a487d17feea8dfe26a1626: [
		"fragment-node_worker_launches",
		"cac88014114f03cee09470505617bc58f893efc072306d0b4c6fb48e259fb17c",
		[66],
		[]
	],
	"5dc1cf9bb59834e9497e191514c7bfb850e062f7744047c7a4289516b4b0e214": [
		"state-feature-node_worker_launches",
		"f07514c3996f79e89f46d771b58859826342f72a12f024b29726a82f6481d6f9",
		[154],
		[]
	],
	"5e238c5c57f8e1bfc2d5fc91ad2a4ad3ae421ca1f36a84f973a8299f99ee7015": [
		"fragment-node_worker_prepared_workspaces",
		"1ab2c378547ad29580b84dcebbc4ed9c99008c8a242446cdad0553a24bf06eec",
		[67],
		[]
	],
	"865397a51b0e47eda5349293c3fc590226718cdad61afe420c578ab3ec786732": [
		"fragment-node_worker_turns",
		"cb3eaac1dc2492905a55c037ba7c09748bbdbc9c6a13cbb92e3cbec80c94f5d6",
		[68],
		[]
	],
	"64cf0d044c7dede24d58a370a2f52cf19616efc9523343a698f7127c4d187f1d": [
		"state-feature-node_worker_turns",
		"d1d9be01c96d9dd47e4e23d0099074f561aedb976de062622daffd173443c17d",
		[155],
		[]
	],
	eee176fa30fb315a218b50f12be8d9e4e5561441d59250cf7029aac4edd9eb38: [
		"fragment-operator_approval_execution_identities",
		"0f2bc5e4d656eda1ad36b778905e7e55f8685c0b41a68883f6e9fb1b838a874c",
		[70],
		[]
	],
	"57562a3e6f834f876e5c03711f50dc514c8bdd432a87f1f54cbac2901642d5d4": [
		"fragment-web_push_approval_deliveries",
		"f11526f4044590884acc313f8a8fb921ce93fb2372e2e64a635989af93d3012e",
		[112],
		[]
	],
	"74b05c720f6b4a8ff88824c9843816992d5233b93ccd85bea66c2fbd2a3480c5": [
		"state-feature-web_push_approval_deliveries",
		"92bd2e9265be63167980a22960aa201502864ec59e283821ad3eab6e765744ce",
		[156],
		[]
	],
	"0b710f9ea230c2d23182de151edebc06dfb2800ad6207647d27ccb2c900b5d6a": [
		"fragment-execution_decision_facts",
		"251fe6aa9c0c1ef726ab36810df59e644d472757b269b7e6ac36a5b7b1864ccc",
		[36],
		[]
	],
	"9cd9f63b1002094a7e0538c52b75f2c8d26664937ff5559f64a004feabe47816": [
		"state-feature-execution_decision_facts",
		"8235ed3d9eb951894768fa49670db7390f7950e96618daded2851a55c2e827ed",
		[157],
		[]
	],
	"49e2b7094b1bf25586bc63b3ce3e971873c26584de40bd96654a31b945b3881f": [
		"fragment-execution_owner_lifecycle_bindings",
		"83228457b7900a349a7a60693f5be9fe5ce2b86f8ea3be6bd1b3bcbae9381c73",
		[38],
		[]
	],
	c222191b2157eb84fae227b67417210870ff546ce38b799805cd32e63e198bcd: [
		"fragment-outbound_message_execution_bindings",
		"90715ffad8419a713baa7a63aa0d15038b16391bba0c3739bdae7c3196cc5fe5",
		[75],
		[]
	],
	f782e56e1dca81426ff88a94a9702580d0c6bdd1a420e8c1741fef3aa7c18b81: [
		"state-feature-outbound_message_execution_bindings",
		"c29af535c3d6cf16bb31a085c7b68d150c132921b51f560495e75dd1f5451f2d",
		[158],
		[]
	],
	"733bbcfcce8373ce968a993fc1f4d3f911d0011c8a60833f613f9cdb7de22d9e": [
		"fragment-outbound_message_progress",
		"07938ecb7fa35203a80bf93cb28900b5eb0c35dcf47bfa476b436fd39d881135",
		[76],
		[]
	],
	"6e2c6c197a77c179716d6ddead9a7226c49db5e8b69c1775ea8808e5e24cf271": [
		"state-feature-outbound_message_progress",
		"b1fdd16f1d29ceeed6d32e873b0ef54831ad693b4e910c1fe55bc59aa60c4709",
		[159],
		[]
	],
	ab3748daca8019e0908cc9906304f50a26cffd9d5e9ea3ba1ea3a759315737cb: [
		"fragment-agent_provenance",
		"da5d017b6840d65ebd1bc234ae3fdf4540bd00256bfc50c599a4195d15066c17",
		[6],
		[]
	],
	be11d3e5a672ca34875c1f06cfc6d5d5a1293a7077302a759c12c2c17b2cdcb6: [
		"fragment-cron_run_receipts",
		"593a0b293257e23cf22f14e308c7f75a7032d5f0bdbba0fa3d307f3382e3bd4c",
		[25],
		[]
	],
	"41824738e9d17ef8abfa9bda96824ab259ca9e81d3ad647b16b407a6bc4dc28f": [
		"state-feature-cron_run_receipts",
		"1c1c9f4b60d18e51e0db6940a6813c5a7a1a14dffbe38921318e61c295597112",
		[160],
		[]
	],
	"8b28fd18dffd5b09fb5a09d8e0d04b2dbf1372081b356131f1df2f4c41895745": [
		"fragment-config_revision_keys",
		"8b416bf248c7702519e58249d29725d42d52a95d8a22084964637f3ed57cae9d",
		[21],
		[]
	],
	"443ee39ca023c21d0234f2897e3790e8e9757daf427989b731f97074c5bf28fe": [
		"fragment-secret_store_entries",
		"45f2e66f10baf9470316cb216a91ef6ffa865a2c2f25b181e37f20171348576b",
		[84],
		[]
	],
	"10e3ba9552ac35206e3f3d467a44f71602f4b1d3404204836f72106155b5fe6d": [
		"state-feature-secret_store_entries",
		"1eefc2ba0eecf91c8fd96442e750b4e555fb97485569f3bd2bf7205c02466cee",
		[161],
		[]
	],
	ecb98cd64bfc2fc0828eaaac59c122a4a9381d752dfdc4166d1fe287e9f1cecb: [
		"fragment-projects",
		"9ac5c2cc1d8a72b975287fe40d1f9cf5929671ee033dd68538315e9770df9f36",
		[80],
		[]
	],
	"7b5e9bd4ec7f91f71f2fcea1deaa9058d06f907e460e2d1a2a8fa333bf6942c0": [
		"fragment-worktree_templates",
		"a9481ceaf044b2db824f5df1823d0619c7b9e53310b83a32c4399421cc6a7e18",
		[130],
		[]
	],
	"85b0f3fbf9815fa0125a5a823eacebc68306ac4864d89047bb2699611b0044c5": [
		"fragment-user_preferences",
		"24c5cd67b1014eb8ca50a492d93a9b9ec5e5a3b936722c35c7b0768a8b1823e2",
		[110],
		[]
	],
	"1f164add8aeb9d28f7c779f88fe40dc7a344e14479fe9a017181151330bca6fd": [
		"fragment-device_pair_setup_completions",
		"3400a6259bccdb3546a778b36215284bd14c9613a1ece543e9deaf3539e3b288",
		[30],
		[]
	],
	"54a593978142e9fdd957d9aff2368fd3b9d26702968b4ede856df3a933023139": [
		"fragment-github_publication_requests",
		"81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e",
		[45],
		[]
	],
	"4c1eb061476b0ecbfc022fb1bd4c927c7c4b3868f40702507c9911ccd3504b2f": [
		"state-feature-github_publication_requests",
		"0375d1a5a88363e5cd216f3addbf170f8be1098ea8626e0e0f95ebb91768588d",
		[162],
		[]
	],
	"1f844843f7e4c042331e07eb663873d85bfb1291db181f98c0834a0d01bbf2e2": [
		"fragment-device_pairing_join_codes",
		"4ada0f17fe210baff80cc7da940a58ef4bd27911312469dd15a3473ef1119ad0",
		[31],
		[]
	],
	ddfc4231357afb56d903eca77fbfebf817ffafa47d491193e6948b5032ccfefe: [
		"fragment-skill_workshop_changes",
		"993cb9d62f11305ca322f0c76e895a37604132572f2f651c635d0d72eb416b85",
		[98],
		[]
	],
	d3bf805006eb83550c1d4a662610e8897cd41ce52de6e370424d3f3ed26e3d80: [
		"state-feature-skill_workshop_changes",
		"01b83680a33b4f2e7d46a70f3e122ebe40044b44ff733891a29a340bdcbba3fb",
		[163],
		[]
	],
	"59c7fa24ee5aa93144f936173f6efde68e9d2af33d074d5e208f971d500ac5d3": [
		"fragment-worker_environment_ssh_fallback_ports",
		"18ead5da9eec5f58b75326fdaf9ed55a3d0433facc14dad465add6bd80dff080",
		[115],
		[]
	],
	"62bf1862f7ce3c0abcaaf4cc070834c5f402e1696b78d22e7ca7bd23b0fec36d": [
		"fragment-worker_session_placement_moves",
		"8188e7a581a51d08faad38cdf6b07041e2b2e760d17bcfa109df49ec0c83c430",
		[118],
		[]
	],
	"8763a734bf095bbda0f3fa1a7d1631a65323a168bf2030ed9dd9621f0103317d": [
		"state-runtime-0-0",
		"1f1007124ef4e9db30a71d38092481cada2fdf2aef59351ee8b475b405bd3dee",
		[
			0,
			1,
			2,
			3,
			4,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			23,
			24,
			27,
			28,
			29,
			32,
			33,
			34,
			35,
			39,
			40,
			41,
			42,
			43,
			52,
			53,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			69,
			73,
			74,
			77,
			78,
			79,
			82,
			83,
			85,
			87,
			88,
			89,
			90,
			95,
			96,
			97,
			99,
			100,
			101,
			102,
			103,
			104,
			105,
			106,
			107,
			113,
			114,
			116,
			117,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			131
		],
		[]
	],
	"7031b5e534f38b6cdc4a012878201c32a79d5e515e11e83081bfe9935a2f06ad": [
		"state-runtime-0-1",
		"741627bdc2f473f47e87dd3b3ca67742bf56a22066820db2c5ed2952d438cdc1",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			23,
			24,
			27,
			28,
			29,
			32,
			33,
			34,
			35,
			39,
			40,
			41,
			42,
			43,
			52,
			53,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			69,
			73,
			74,
			77,
			78,
			79,
			82,
			83,
			85,
			87,
			88,
			89,
			90,
			95,
			96,
			97,
			99,
			100,
			101,
			102,
			103,
			104,
			105,
			106,
			107,
			113,
			114,
			116,
			117,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			131
		],
		[]
	],
	a2808797bda845d26c780b295629ca43bc8e1b38e6fc95e70af677a570f077d7: [
		"state-runtime-1-0",
		"a8c7ee28ea1e28d3b3af47cdf9d8a04deb4af779a63c9c0a5c4414be3bd971f7",
		[
			0,
			1,
			2,
			3,
			4,
			6,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			23,
			24,
			25,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			39,
			40,
			41,
			42,
			43,
			45,
			52,
			53,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			69,
			73,
			74,
			77,
			78,
			79,
			80,
			82,
			83,
			84,
			85,
			87,
			88,
			89,
			90,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			103,
			104,
			105,
			106,
			107,
			110,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	e806fdb2b73d6e4f80d506dfe64875f70b8818e8a6457694a76d40804adc8e39: [
		"state-runtime-1-1",
		"9f6ac7b37f192e6c559b25e3a9cc61899135fcfdb8bd24bda7458a33462fcbb8",
		[
			0,
			1,
			2,
			3,
			4,
			5,
			6,
			7,
			8,
			9,
			10,
			11,
			12,
			13,
			14,
			15,
			16,
			17,
			18,
			19,
			20,
			21,
			23,
			24,
			25,
			27,
			28,
			29,
			30,
			31,
			32,
			33,
			34,
			35,
			39,
			40,
			41,
			42,
			43,
			45,
			52,
			53,
			55,
			56,
			57,
			58,
			59,
			60,
			61,
			69,
			73,
			74,
			77,
			78,
			79,
			80,
			82,
			83,
			84,
			85,
			87,
			88,
			89,
			90,
			95,
			96,
			97,
			98,
			99,
			100,
			101,
			102,
			103,
			104,
			105,
			106,
			107,
			110,
			113,
			114,
			115,
			116,
			117,
			118,
			119,
			120,
			121,
			122,
			123,
			124,
			125,
			126,
			127,
			128,
			129,
			130,
			131
		],
		[]
	],
	d285aca718d789bb5f8799fd148a30792ae63c7ce10fa0f0c757391806d83cac: [
		"state-table-agent_database_leases",
		"fed699717b3ff6f0f406750e7ef2e57c0e047f4a8aa9669855cd001f4eecb4b9",
		[3],
		[]
	],
	cac005273b1563f1269aa41ff5cc8a4d7b94a4cb7d9f82be2917853a736168de: [
		"state-table-agent_deletion_journal",
		"6c66fbe42d4b3d671ea3212b0024f65af05cbf9ea67dc8ce1763542f2ce245f2",
		[5],
		[]
	],
	dc1f04127c4146d414429aba7f0f055680178ac035c1566f8202cb8ba6ba2575: [
		"state-table-config_machine_state",
		"21025ec6d7ee6da8951d3f519c48e44744b0392597ce821984dd3a9e5abb1787",
		[20],
		[]
	],
	"246e73f17e8b92383ee8d6dfe4b657ee3dc3040e8c6398ff36c17ee14222eb37": [
		"state-table-gateway_restart_intent",
		"91a30a8d1423b5d855a975ceb40e2ef07bdfa21f284c59bee6d189679ca8dba9",
		[42],
		[]
	],
	df93d6687254de2f31ff263b2dafdd67656caa6ac10180f95801bde2dce8f7f0: [
		"state-table-schema_meta",
		"df4efc2e7d50f8bde377f55f5a020ae5ba98cfda938879054cf02d9b4905b793",
		[83],
		[]
	],
	cb1f3279e7e3b90290d5ab10856edf532f9c69f278116dd1a8002a4b050f2c1c: [
		"state-table-state_leases",
		"6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc",
		[164],
		[]
	],
	a503e610cfb224030ab2473b374631cefa4972377d9d04e07b5d5efb07cee14c: [
		"state-table-worker_session_tool_operations",
		"a146f78ad23ec99bfcb50819c65478b5e94c4a8e4159086ef5073fc76e26cc2d",
		[120],
		[]
	],
	"4f45746754bef21a88b4fdfc0932df58b22bf31590a961e4a53957cce7ccd873": [
		"state-table-worker_turn_tool_authorities",
		"fef54ec7cc72bf3869c78b67f31ce96ed842a1ba872f7090e52feff5f547560c",
		[123],
		[]
	],
	"8cbef48665eec155650765377478b38fde1c87ef57fadb423438f85f8c91ad66": [
		"state-indexed-github_publication_requests",
		"81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e",
		[45],
		[]
	],
	c7c1408a52e8649cf030b636ee3d984e969c5fdb96f6834634e7cb4807e624f2: [
		"state-indexed-update_runs",
		"7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55",
		[108],
		[]
	],
	d40fd26bedb861443248d33289dc8d89a1750f3631730dfde2ae285f2c7988ca: [
		"state-existing-state_leases",
		"4289076cebb114b14ac96672941b2be0679f1033e23fe059eedce8dc2b1eea57",
		[83, 164],
		[]
	],
	"13150d745ef24ab5e6aafe0b365af15d6c5d471a659e5eb2a1c38e359984a47f": [
		"state-existing-agent_database_leases",
		"9fe50268db674b01265b7e77701aedcfffe36567086fc763de8b89f87f4cb67d",
		[
			3,
			83,
			164
		],
		[]
	],
	"789bdcc904f4b35b57f9cb829909f2c9cda541c86179beb6904977146665c0c9": [
		"state-node-worker-lineage",
		"f235501e3f5767c362c7aebce3e678d33cdb45e3b776391980019cdf7cc0f37d",
		[63, 154],
		[]
	],
	"7c5c2640b3ec45cbac611c07c67f478f0ddc85a4bbfceb9c3576f0d7aa3bd14a": [
		"state-node-worker-descendants",
		"0991532bbc3ca042fc5c1c2026b8aa8d50b24a5bccf26e53675340a4853a665e",
		[
			63,
			65,
			154
		],
		[]
	],
	"72c354791974ce88794c96c16135a89f07b48b9b03542f968beadf05b76aae1e": [
		"state-retired-commitments",
		"19bef9367d336bb367e75740610741cb67deeef86a7f54065758609d67ae8a38",
		[165],
		[]
	],
	"2309aff06f4bac77072697764926a0042e6b6069c9504d5bb8c6a0601e9d1314": [
		"state-retired-commitments-shipped",
		"f4d088664f133eea8b1e83fd342d1effaa86d836f8593e02778531468372a303",
		[166],
		[]
	]
};
let data;
function readSqliteStateFingerprint(e) {
	const t = fingerprints[e];
	if (!t) return;
	const [n, r, i, a] = t;
	return {
		id: n,
		fingerprint: r,
		viewNames: a,
		tableNames: i.map((e) => tableNames[e][0]),
		indexNames: i.flatMap((e) => tableNames[e][1])
	};
}
function readSqliteStateCatalog(e) {
	if (!fingerprints[e]) return;
	data ??= createRequire(import.meta.url)(fileURLToPath(new URL("../assets/sqlite-schema/sqlite-state-catalogs.json", import.meta.url).href));
	const t = data.catalogs[e];
	return {
		tables: t.tables.map((e) => data.tables[e]),
		views: t.views
	};
}
//#endregion
//#region src/state/postgres-schema.generated/sqlite-catalogs.ts
function readGeneratedSqliteFingerprint(e) {
	const t = createHash("sha256").update(e).digest("hex");
	return readSqliteStateFingerprint(t) ?? readSqliteAgentFingerprint(t) ?? readSqliteDaemonFingerprint(t) ?? readSqliteClientFingerprint(t) ?? readSqliteMemoryFingerprint(t);
}
function readGeneratedSqliteCatalog(e) {
	const t = createHash("sha256").update(e).digest("hex");
	return readSqliteStateCatalog(t) ?? readSqliteAgentCatalog(t) ?? readSqliteDaemonCatalog(t) ?? readSqliteClientCatalog(t) ?? readSqliteMemoryCatalog(t);
}
//#endregion
//#region src/infra/sqlite-schema-fingerprint.ts
/** Hash native facts, retaining expression text rather than interpreting SQL expressions. */
function fingerprintSqliteSchemaCatalog(e, t) {
	const n = t && new Set(t.tableNames);
	const r = t && new Set(t.viewNames);
	const i = t && new Set(t.indexNames);
	const triggers = (e) => e.map(({ name: e, sql: t }) => ({
		name: e,
		sql: normalizeSchemaSql(t)
	})).toSorted(byName);
	const columns = (e) => e.map(({ cid: e, name: t, type: n, notnull: r, dflt_value: i, pk: a, hidden: o }) => ({
		cid: e,
		name: t,
		type: n,
		notnull: r,
		dflt_value: i,
		pk: a,
		hidden: o
	})).toSorted((e, t) => e.cid - t.cid);
	const a = {
		tables: e.tables.filter((e) => !n || n.has(e.name)).map((e) => ({
			name: e.name,
			sql: normalizeSchemaSql(e.sql),
			strict: e.strict,
			withoutRowid: e.withoutRowid,
			columns: columns(e.columns),
			foreignKeys: e.foreignKeys.map(({ id: e, seq: t, table: n, from: r, to: i, on_update: a, on_delete: o, match: s }) => ({
				id: e,
				seq: t,
				table: n,
				from: r,
				to: i,
				on_update: a,
				on_delete: o,
				match: s
			})).toSorted((e, t) => e.id - t.id || e.seq - t.seq),
			indexes: e.indexes.filter((e) => !i || e.unique === 1 || i.has(e.name)).map((e) => ({
				name: e.name,
				origin: e.origin,
				partial: e.partial,
				unique: e.unique,
				sql: normalizeSchemaSql(e.sql),
				terms: e.terms.map(({ seqno: e, cid: t, name: n, desc: r, coll: i, key: a }) => ({
					seqno: e,
					cid: t,
					name: n,
					desc: r,
					coll: i,
					key: a
				})).toSorted((e, t) => e.seqno - t.seqno)
			})).toSorted(byName),
			triggers: triggers(e.triggers)
		})).toSorted(byName),
		views: e.views.filter((e) => !r || r.has(e.name)).map((e) => ({
			name: e.name,
			sql: normalizeSchemaSql(e.sql),
			columns: columns(e.columns),
			triggers: triggers(e.triggers)
		})).toSorted(byName)
	};
	return sha256Hex(JSON.stringify(a));
}
function byName(e, t) {
	return e.name < t.name ? -1 : e.name > t.name ? 1 : 0;
}
//#endregion
//#region src/utils/absolute-deadline.ts
/** Rechecks the selected clock because timers can run early or overflow long delays. */
function scheduleAbsoluteDeadline(e, t, n = () => Date.now(), { unref: r = false } = {}) {
	let i;
	const checkDeadline = () => {
		const a = Math.max(0, e - n());
		if (a === 0) {
			t();
			return;
		}
		i = setTimeout(checkDeadline, Math.min(a, MAX_TIMER_TIMEOUT_MS));
		if (r) i.unref();
	};
	checkDeadline();
	return () => {
		clearTimeout(i);
	};
}
//#endregion
//#region src/shared/permit-pool.ts
/**
* FIFO admission with caller-owned lifetime. Cancellation/deadlines only stop
* waiting: an acquired permit stays held until its idempotent release is called.
* acquire returns null on cancellation/expiry; tryAcquire returns null when busy.
*/
function createPermitPool(e) {
	let t = 0;
	const n = [];
	let r = 0;
	const compactWaiters = () => {
		if (r >= n.length) {
			n.length = 0;
			r = 0;
		} else if (r > 256 && r * 2 > n.length) {
			n.splice(0, r);
			r = 0;
		}
	};
	const createRelease = () => {
		t += 1;
		let e = false;
		return () => {
			if (e) return;
			e = true;
			t -= 1;
			for (let e = n[r]; e; e = n[r]) {
				r += 1;
				const t = e.expired();
				e.settle(t ? null : createRelease());
				if (!t) break;
			}
			compactWaiters();
		};
	};
	const tryAcquire = () => t < e ? createRelease() : null;
	return {
		get pendingCount() {
			return n.length - r;
		},
		tryAcquire,
		async acquire({ signal: e, deadlineAtMs: t } = {}) {
			const expired = () => e?.aborted === true || t !== void 0 && Date.now() >= t;
			if (expired()) return null;
			const i = tryAcquire();
			if (i) return i;
			return await new Promise((i) => {
				let a;
				const cancel = () => {
					const e = n.indexOf(o, r);
					if (e >= r) {
						n.splice(e, 1);
						compactWaiters();
					}
					o.settle(null);
				};
				const o = {
					expired,
					settle: (t) => {
						a?.();
						e?.removeEventListener("abort", cancel);
						i(t);
					}
				};
				e?.addEventListener("abort", cancel, { once: true });
				n.push(o);
				if (t !== void 0) a = scheduleAbsoluteDeadline(t, cancel, void 0, { unref: true });
			});
		}
	};
}
//#endregion
//#region src/infra/database-engine/sqlite-vector-subprocess.ts
const MAX_CONCURRENT_VECTOR_KNN_CHILDREN = 2;
const vectorKnnAdmission = createPermitPool(MAX_CONCURRENT_VECTOR_KNN_CHILDREN);
//#endregion
//#region src/infra/database-engine/sqlite-vector.ts
const compiler = new SqliteQueryCompiler();
//#endregion
//#region src/infra/database-engine/sqlite-search-schema.ts
const MEMORY_INDEX_SOURCES_TABLE = "memory_index_sources";
const MEMORY_INDEX_CHUNKS_TABLE = "memory_index_chunks";
const MEMORY_INDEX_FTS_TABLE = "memory_index_chunks_fts";
const MEMORY_INDEX_PATHS_FTS_TABLE = "memory_index_paths_fts";
function buildMemoryFtsTriggers(e, t, n, r, i) {
	const trigger = (n, r, i) => ({
		name: `${e}_after_${n}`,
		sql: `
      CREATE TRIGGER IF NOT EXISTS main.${e}_after_${n}
      AFTER ${r} ON ${t}
      BEGIN
${i}
      END;
    `
	});
	return [
		trigger("insert", "INSERT", r),
		trigger("update", `UPDATE OF ${n}`, `${i}
${r}`),
		trigger("delete", "DELETE", i)
	];
}
/** Optional canonical triggers owned by the derived path FTS index. */
const MEMORY_PATH_FTS_TRIGGER_DEFINITIONS = buildMemoryFtsTriggers(MEMORY_INDEX_PATHS_FTS_TABLE, MEMORY_INDEX_SOURCES_TABLE, "id, path, source", `        INSERT INTO ${MEMORY_INDEX_PATHS_FTS_TABLE} (rowid, path, source)
        VALUES (NEW.id, NEW.path, NEW.source);`, `        DELETE FROM ${MEMORY_INDEX_PATHS_FTS_TABLE}
        WHERE rowid = OLD.id;`);
/** Canonical chunks own the optional body index; every mutation addresses its rowid. */
const MEMORY_CHUNK_FTS_TRIGGER_DEFINITIONS = buildMemoryFtsTriggers(MEMORY_INDEX_FTS_TABLE, MEMORY_INDEX_CHUNKS_TABLE, "chunk_rowid, text, id, path, source, model, start_line, end_line", `        INSERT INTO ${MEMORY_INDEX_FTS_TABLE} (rowid, text, id, path, source, model, start_line, end_line)
        VALUES (NEW.chunk_rowid, NEW.text, NEW.id, NEW.path, NEW.source, NEW.model, NEW.start_line, NEW.end_line);`, `        DELETE FROM ${MEMORY_INDEX_FTS_TABLE} WHERE rowid = OLD.chunk_rowid;`);
//#endregion
//#region src/infra/database-engine/adapters.ts
const databaseEngineAdapters = {
	sqlite: {
		openConnection: ({ anchor: e }) => observeConnection(e),
		schema: { bootstrap: (e) => e.openSqlite() }
	},
	postgres: {
		openConnection: (e) => {
			if (!e.input || !e.storeId || !e.namespace) throw new Error("PostgreSQL store is not admitted");
			try {
				return new PostgresSyncConnection(e.input.connection, e.namespace, e.anchor, e.storeId, {
					reuse: e.reusePostgresConnection,
					lockTimeoutMs: POSTGRES_LOCK_TIMEOUT_MS,
					statementTimeoutMs: POSTGRES_STATEMENT_TIMEOUT_MS
				});
			} catch (t) {
				const n = t instanceof Error && "code" in t && typeof t.code === "string" ? `${t.code}: ` : "";
				const r = redactSensitiveText(`${n}${t instanceof Error ? t.message : String(t)}`.replaceAll(e.input.connection, "[REDACTED]"), { mode: "tools" });
				throw new Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`, { cause: t });
			}
		},
		schema: {
			bootstrap: (e, t) => {
				if (!e.schema.postgres) throw new Error("Store has no PostgreSQL schema");
				t.exec(postgresSchemaSql(e.schema, e.namespace));
				t.prepare("INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)").run(e.schema.id, e.schema.version, e.storeId);
			},
			migrate: (e, t, n) => {
				if (t > e.schema.version) throw new Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);
				for (let r = t + 1; r <= e.schema.version; r++) {
					const t = e.schema.postgresMigrations?.find((e) => e.version === r);
					if (!t) throw new Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);
					const i = readPostgresSchema(n, e.namespace, e.schema.id);
					const a = withPostgresSearchExtensions(e.schema, i);
					verifyPostgresSchema(n, e.namespace, {
						...a,
						version: r - 1,
						postgres: t.fromSchema.postgres,
						postgresFragments: t.fromSchema.postgresFragments,
						postgresVectorDecoderVersion: t.fromSchema.postgresVectorDecoderVersion,
						postgresVectorSearchVersion: t.fromSchema.postgresVectorSearchVersion,
						postgresTextSearchVersion: t.fromSchema.postgresTextSearchVersion
					}, i);
					if (t.schema.postgresVectorSearchVersion === 2 && t.fromSchema.postgresVectorSearchVersion !== 2) {
						for (const t of [a.search, ...Object.values(a.searchExtensions ?? {})]) if (t) admitPostgresSearch(n, t, e.namespace, 2);
					}
					e.beforeMigrate?.(n, r - 1, new Set(i.catalog.filter((e) => e.kind === "table").map((e) => e.table)));
					n.exec(t.sql);
					n.prepare("UPDATE openclaw_schema_meta SET version = ? WHERE store = ?").run(r, e.schema.id);
					verifyAndRecordPostgresSchema(n, e.namespace, {
						...a,
						version: r,
						postgres: t.schema.postgres,
						postgresFragments: t.schema.postgresFragments,
						postgresVectorDecoderVersion: t.schema.postgresVectorDecoderVersion,
						postgresVectorSearchVersion: t.schema.postgresVectorSearchVersion,
						postgresTextSearchVersion: t.schema.postgresTextSearchVersion
					});
				}
			}
		}
	}
};
//#endregion
//#region src/infra/database-engine/open.ts
const admissionKey = { name: "database.engine" };
function readEngineAnchor(e, t = "identity", n = false) {
	try {
		return t === "schema" ? [e.prepare("SELECT schema FROM openclaw_engine_anchor LIMIT 1").get()] : e.prepare("SELECT store_id, engine, schema FROM openclaw_engine_anchor").all();
	} catch (e) {
		if (n || !(e instanceof Error) || e.message !== "no such table: openclaw_engine_anchor") throw e;
		return;
	}
}
function familySetting(e) {
	return `database.families.${e.id === "team_reports" ? "team-reports" : e.id}.engine`;
}
function refusePostgresAnchor(e, t) {
	const n = readEngineAnchor(e, "schema");
	if (n) throw new Error(`This store lives in PostgreSQL schema ${String(n[0]?.schema ?? "unknown")}; set ${familySetting(t)} to postgres and configure database.postgres.connection.`);
}
/** Reuses the physical SQLite admission exchange across worker handles and idle reopen. */
function openEngineStore(e) {
	const { anchor: t } = e;
	let n = e.schema;
	observeConnection(t);
	const r = e.input !== void 0 && n.postgres !== void 0;
	const i = getSqliteDatabaseAdmission(t, admissionKey);
	if (!r) {
		if (i?.engine === "postgres") throw new Error(`This store lives in PostgreSQL schema ${i.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);
		if (!i && e.inspectSqlite().hasEngineAnchor) refusePostgresAnchor(t, n);
		e.prepareAnchor();
		databaseEngineAdapters.sqlite.schema.bootstrap({
			...e,
			input: e.input
		}, t);
		publishSqliteDatabaseAdmission(t, admissionKey, { engine: "sqlite" });
		return databaseEngineAdapters.sqlite.openConnection({
			...e,
			input: e.input
		});
	}
	if (i?.engine === "sqlite") throw new Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);
	e.prepareAnchor();
	const readOrCreateAnchor = () => {
		const r = e.inspectSqlite();
		if (r.hasExistingData) throw new Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);
		if (!r.hasEngineAnchor && e.existingOnly) throw new Error("Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.");
		if (!r.hasEngineAnchor) t.exec("CREATE TABLE IF NOT EXISTS openclaw_engine_anchor (store_id TEXT NOT NULL, engine TEXT NOT NULL CHECK (engine = 'postgres'), schema TEXT NOT NULL)");
		const i = readEngineAnchor(t, "identity", true) ?? [];
		if (i.length > 1 || r.hasEngineAnchor && i.length === 0) throw new Error("Invalid engine anchor: expected exactly one identity. Restore a matching backup.");
		const a = i[0];
		if (a) {
			if (typeof a.store_id !== "string" || a.engine !== "postgres" || typeof a.schema !== "string") throw new Error("Invalid PostgreSQL anchor identity. Restore a matching backup.");
			return {
				storeId: a.store_id,
				namespace: a.schema
			};
		}
		const o = randomUUID();
		const s = postgresStoreNamespace(e.input.schemaPrefix, n.id, o);
		t.prepare("INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)").run(o, s);
		e.onFreshAnchor?.(t);
		return {
			storeId: o,
			namespace: s
		};
	};
	const a = i?.engine === "postgres" ? i : e.existingOnly ? readOrCreateAnchor() : runSqliteImmediateTransactionSync(t, readOrCreateAnchor);
	const o = {
		...e,
		input: e.input,
		...a
	};
	const s = databaseEngineAdapters.postgres;
	const c = s.openConnection(o);
	const admit = (t) => {
		admitPostgresPhysicalFacts({
			db: c,
			namespace: a.namespace,
			storeId: a.storeId,
			store: n.id,
			version: n.version,
			schema: n,
			recordSchema: t,
			preserveSchemaSeal: e.existingVersion
		});
		e.admitPostgres?.(c, t);
	};
	try {
		const r = n.search ? admitPostgresSearch(c, n.search, a.namespace, e.existingVersion ? 1 : n.postgresVectorSearchVersion) : void 0;
		if (!i || i.engine === "postgres" && i.version !== n.version) {
			admitPostgresCapabilities(c);
			let t;
			let r;
			c.runTransaction(() => {
				const i = !c.prepare("SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?").get(a.namespace);
				if (i && !e.existingOnly) {
					c.exec(`CREATE SCHEMA IF NOT EXISTS "${a.namespace.replaceAll("\"", "\"\"")}"`);
					c.exec(postgresSchemaMetadataSql);
				}
				let l;
				try {
					l = c.prepare("SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?").get(n.id);
				} catch (e) {
					throw new Error("Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.", { cause: e });
				}
				if (!l) {
					if (e.existingOnly || !i) throw new Error("Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.");
					s.schema.bootstrap(o, c);
				} else {
					if (l.store_id !== a.storeId) throw new Error(`PostgreSQL database identity mismatch: expected ${a.storeId}, found ${String(l.store_id)}. Restore the matching anchor and PostgreSQL backup.`);
					if (l.version !== n.version) {
						if (e.existingVersion) {
							const e = n.postgresMigrations?.find((e) => e.version === Number(l.version) + 1)?.fromSchema;
							if (!e) throw new Error("Missing PostgreSQL source schema for inspection");
							n = {
								...n,
								...e,
								postgresVectorDecoderVersion: e.postgresVectorDecoderVersion,
								postgresVectorSearchVersion: e.postgresVectorSearchVersion,
								postgresTextSearchVersion: e.postgresTextSearchVersion,
								version: Number(l.version)
							};
						} else {
							r = e.assertMigrationCurrent;
							r?.();
							t = beginUpdatePostgresMigration(c, r);
							invalidateLocalSqliteSchemaAdmissions(c);
							stageSqliteTransactionState(c, {
								stage: () => {},
								rollback: () => {},
								commit: () => publishSqliteDatabaseSchemaChange(c),
								invalidate: () => publishSqliteDatabaseSchemaChange(c)
							});
							const migrate = () => s.schema.migrate(o, Number(l.version), c);
							if (t) t.run(migrate);
							else migrate();
						}
					}
				}
				admit(!l);
			}, { withCommit(e) {
				r?.();
				t?.beforeCommit();
				e();
			} }, false);
			t?.committed();
		} else admit(false);
		if (!i || i.engine === "postgres" && i.version !== n.version) publishSqliteDatabaseAdmission(t, admissionKey, {
			engine: "postgres",
			...a,
			version: n.version
		});
		r?.();
		for (const e of Object.values(getAdmittedPostgresSchema(c)?.searchExtensions ?? {})) admitPostgresSearch(c, e, a.namespace, n.postgresVectorSearchVersion)?.();
		return c;
	} catch (t) {
		if (e.closeOnFailure) return e.closeOnFailure(c, t);
		c.close();
		throw t;
	}
}
//#endregion
//#region src/infra/database-engine/postgres-index-ordering.ts
const generatedIndexes = /CREATE (?:UNIQUE )?INDEX ("(?:[^"]|"")+") ON ("(?:[^"]|"")+") (?:'(?:[^']|'')*'|"(?:[^"]|"")*"|[^;'"])*;/g;
const orderedKeys = /'(?:[^']|'')*'|"(?:[^"]|"")*"|\) (ASC|DESC)(?=,|\))/g;
/** Restore a predecessor's index policy; generated table DDL owns column nullability. */
function withLegacyPostgresIndexOrdering(e, t = "sqlite", n = e) {
	const r = /* @__PURE__ */ new Map();
	if (t === "schema-nullability") for (const [, e, t] of n.matchAll(/CREATE TABLE ("(?:[^"]|"")+") \(\n([\s\S]*?)\n\);/g)) r.set(e, new Set([...t.matchAll(/^ {2}("(?:[^"]|"")+") (?:text|bigint|bytea|double precision)([^\n]*)/gm)].filter((e) => !/\bNOT NULL\b/.test(e[2].replace("GENERATED BY DEFAULT AS IDENTITY", "").split(/\bDEFAULT\b/)[0])).map(([, e]) => e)));
	return e.replace(generatedIndexes, (e, n, i) => {
		if (t === "schema-nullability") return e.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|\(("(?:[^"]|"")+")\) (ASC|DESC)(?=,|\))/g, (e, t, n) => t && r.get(i)?.has(t) ? `${e} NULLS ${n === "DESC" ? "LAST" : "FIRST"}` : e);
		return e.replace(orderedKeys, (e, t) => t ? `${e} NULLS ${t === "DESC" ? "LAST" : "FIRST"}` : e);
	});
}
/** The schema owner runs this under its existing versioned admission transaction. */
function postgresIndexOrderingMigration(e, t = "sqlite") {
	const n = withLegacyPostgresIndexOrdering(e, t);
	const r = new Map([...n.matchAll(generatedIndexes)].map(([e, t]) => [t, e]));
	return [...e.matchAll(generatedIndexes)].filter(([e, t]) => r.get(t) !== e).map(([e, t, n]) => `DO $index_order$
BEGIN
  IF to_regclass('${n.replaceAll("'", "''")}') IS NOT NULL THEN
    DROP INDEX ${t};
    ${e}
  END IF;
END $index_order$;`).join("\n");
}
//#endregion
//#region src/state/openclaw-state-db-engine-input.ts
function stateEngineInput() {
	if (getDatabaseEngineSelection()) return getDatabaseEngineInput("state");
}
//#endregion
//#region src/state/openclaw-state-db-schema-v28-publication.ts
const publicationDraftTables = [
	"github_publication_requests",
	"github_personal_publication_requests",
	"github_repository_publication_requests"
];
/** A published version can retain the recognized predecessor column layout. */
function needsPublicationDraftMigration(e) {
	return publicationDraftTables.some((t) => tableExists(e, t) && !tableHasColumn(e, t, "draft"));
}
const statePublicationDraftMigration = {
	version: 28,
	tables: publicationDraftTables,
	columns: publicationDraftTables.map((e) => `${e}.draft`),
	migrate: (e) => {
		let t = false;
		for (const n of publicationDraftTables) t = ensureColumn(e, n, "draft INTEGER") || t;
		return t;
	},
	applied: "Retained the requested GitHub PR draft choice (v28)"
};
/** Exact predecessor shape for publication migration admission and PostgreSQL backups. */
function withLegacyPublicationDraft(e) {
	return e.replace(/(CREATE TABLE(?: IF NOT EXISTS)? "?github_(?:personal_|repository_)?publication_requests"? \([\s\S]*?)\n {2}(?:"draft" bigint|draft INTEGER),/gu, "$1");
}
//#endregion
//#region src/state/openclaw-state-db-schema-v35-workspace-cas.ts
const WORKSPACE_CAS_TABLES = ["local_workspace_tree_packs", "local_workspace_source_path_sets"];
const WORKSPACE_CAS_COLUMNS = [
	"tree_root_digest",
	"source_paths_digest",
	"canonical_fingerprints",
	"projection_fingerprints"
];
/** DDL only: reconciliation converts retained baselines one projection at a time. */
function migrateLocalWorkspaceCas(e, t) {
	if (t >= 35 || !tableExists(e, "local_workspace_projections")) return false;
	for (const t of WORKSPACE_CAS_COLUMNS) ensureColumn(e, "local_workspace_projections", `${t} BLOB`);
	for (const t of WORKSPACE_CAS_TABLES) e.exec(extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, t));
	return true;
}
const stateLocalWorkspaceCasMigration = {
	version: 35,
	tables: ["local_workspace_projections", ...WORKSPACE_CAS_TABLES],
	columns: WORKSPACE_CAS_COLUMNS.map((e) => `local_workspace_projections.${e}`),
	migrate: migrateLocalWorkspaceCas,
	applied: "Prepared shared content-addressed workspace trees and compact scan fingerprints (v35)"
};
/** Exact predecessor declarations for admission, migration backups and ports. */
function withLegacyLocalWorkspaceCas(e) {
	return e.replace(/\n {2}(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints) BLOB,/gu, "").replace(/\n {2}"(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints)" bytea,/gu, "").replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_(?:tree_packs|source_path_sets)"? \([\s\S]*?\n\)(?: STRICT(?:, WITHOUT ROWID)?)?;\n?/gu, "");
}
//#endregion
//#region src/state/openclaw-state-db-schema-v31-workspace-manifests.ts
const projectionTable = "local_workspace_projections";
const nodeTable = "local_workspace_manifest_nodes";
const legacyBaselineCheck = "CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL))";
const incrementalBaselineCheck = "CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL)";
/** The schema transaction preserves legacy bytes; the projection owner converts each baseline. */
function migrateLocalWorkspaceManifests(e, t) {
	if (t >= 31 || !tableExists(e, projectionTable)) return false;
	ensureColumn(e, projectionTable, "checkpoint_json TEXT");
	const n = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e);
	const r = n.tableSql.get(projectionTable);
	if (typeof r !== "string") throw new Error("Local workspace projection migration schema is missing");
	if (r.includes(legacyBaselineCheck)) {
		const t = quoteSqliteIdentifier(`${projectionTable}_migration_v31`);
		const i = quoteSqliteIdentifier(projectionTable);
		const a = [...readTableColumns$1(e, projectionTable)].map(quoteSqliteIdentifier).join(", ");
		const o = r.slice(r.indexOf("(")).replace(legacyBaselineCheck, incrementalBaselineCheck);
		e.exec(`CREATE TABLE ${t} ${o};
      INSERT INTO ${t} (rowid, ${a}) SELECT rowid, ${a} FROM ${i};
      DROP TABLE ${i};
      ALTER TABLE ${t} RENAME TO ${i};`);
		for (const t of [...n.indexDefinitions.values(), ...n.triggers.values()]) if (t.table === projectionTable && typeof t.sql === "string") e.exec(t.sql);
	} else if (!r.includes(incrementalBaselineCheck)) throw new Error("Local workspace baseline constraint is not recognized; preserve it for Doctor");
	e.exec(extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, nodeTable));
	return true;
}
const stateLocalWorkspaceManifestMigration = {
	version: 31,
	tables: [projectionTable, nodeTable],
	columns: [`${projectionTable}.checkpoint_json`],
	migrate: migrateLocalWorkspaceManifests,
	applied: "Prepared resumable per-path local workspace baselines and checkpoint deltas (v31)"
};
/** Keep exact predecessor declarations for SQLite admission and PostgreSQL backups. */
function withLegacyLocalWorkspaceManifests(e) {
	return withLegacyLocalWorkspaceCas(e).replace(/\n {2}(?:checkpoint_json TEXT|"checkpoint_json" text COLLATE "C"),/gu, "").replace(/^ {2}CHECK \([^\n]*baseline_json[^\n]*baseline_ref[^\n]*\),$/gmu, (e) => e.includes("\"") ? "  CHECK (((\"baseline_json\" IS NULL) = (\"baseline_ref\" IS NULL)))," : `  ${legacyBaselineCheck},`).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_manifest_nodes"? \([\s\S]*?\n\)(?: STRICT)?;\n?/gu, "").replace(/ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY[^;]*;\n?/gu, "");
}
//#endregion
//#region src/state/openclaw-state-db-additive-columns.ts
const lazyColumns = [
	[
		"agent_deletion_journal",
		"phase",
		"TEXT",
		true
	],
	[
		"agent_database_leases",
		"provenance",
		"TEXT",
		true
	],
	[
		"user_profile_identities",
		"canonical_login",
		"TEXT"
	],
	[
		"user_profile_identities",
		"authorization_id",
		"TEXT"
	],
	[
		"user_profile_identities",
		"authorization_basis_json",
		"TEXT"
	],
	[
		"user_profile_identities",
		"verified_email_json",
		"TEXT",
		true
	],
	[
		"template_installs",
		"bootstrap_content_digest",
		"TEXT"
	],
	[
		"template_installs",
		"bootstrap_source_path",
		"TEXT"
	],
	[
		"worker_environments",
		"desktop_json",
		"TEXT"
	],
	[
		"worker_environments",
		"bootstrap_install_kind",
		"TEXT"
	],
	[
		"worker_environments",
		"preparation_purpose",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_adapter_identity",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_detected_format",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_format",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_id",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_mapped_json",
		"TEXT"
	],
	[
		"template_package_refs",
		"extension_unavailable_json",
		"TEXT"
	],
	[
		"worker_environments",
		"shared_host",
		"INTEGER"
	],
	[
		"worker_environments",
		"node_setup_id",
		"TEXT"
	],
	[
		"worker_environments",
		"node_device_id",
		"TEXT"
	],
	[
		"worker_session_placements",
		"terminal_reason",
		"TEXT"
	],
	[
		"worker_session_placements",
		"terminal_at_ms",
		"INTEGER"
	],
	[
		"worker_workspace_pending_results",
		"repository_workspace_id",
		"TEXT",
		true
	],
	[
		"worker_session_placement_moves",
		"abandon_source",
		"INTEGER",
		true
	],
	[
		"worker_session_placement_moves",
		"target_machine_class",
		"TEXT",
		true
	],
	[
		"worker_session_placement_moves",
		"target_os",
		"TEXT",
		true
	],
	[
		"worktrees",
		"run_end_cleanup_json",
		"TEXT"
	],
	[
		"worktrees",
		"gc_protection_json",
		"TEXT"
	],
	[
		"device_bootstrap_tokens",
		"setup_id",
		"TEXT",
		true
	],
	[
		"session_groups",
		"cwd",
		"TEXT",
		true
	],
	[
		"session_groups",
		"worktree",
		"INTEGER",
		true
	],
	[
		"secret_store_entries",
		"allowed_hosts",
		"TEXT"
	],
	[
		"web_push_subscriptions",
		"device_id",
		"TEXT",
		true
	],
	[
		"web_push_subscriptions",
		"user_profile_id",
		"TEXT",
		true
	],
	[
		"web_push_subscriptions",
		"preferences_json",
		"TEXT",
		true
	],
	[
		"task_runs",
		"execution_owner_host",
		"TEXT",
		true
	],
	[
		"task_runs",
		"execution_owner_pid",
		"INTEGER",
		true
	],
	[
		"task_runs",
		"execution_owner_start_identity",
		"INTEGER",
		true
	],
	[
		"session_watch_cursors",
		"watcher_store_path",
		"TEXT",
		true
	],
	[
		"subagent_runs",
		"requester_store_path",
		"TEXT",
		true
	],
	[
		"subagent_runs",
		"controller_store_path",
		"TEXT",
		true
	],
	[
		"cron_jobs",
		"grant_definition_revision",
		"TEXT"
	],
	[
		"cron_jobs",
		"grant_definition_generation",
		"INTEGER"
	],
	[
		"cron_jobs",
		"grant_definition_updated_at",
		"INTEGER"
	]
];
function lazyColumnDefinitions(e) {
	return lazyColumns.filter((t) => e === void 0 || Boolean(t[3]) === e).map(([e, t, n]) => ({
		columnName: t,
		dataType: n,
		tableName: e
	}));
}
const CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions();
const CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions(false);
const CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions(true);
const ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS = {
	packageUpdatedAt: [["template_package_refs", "updated_at_ms INTEGER NOT NULL DEFAULT 0"]],
	packageIntegrity: [["template_package_refs", "package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'"]],
	diagnosticSequence: [["diagnostic_events", "sequence INTEGER NOT NULL DEFAULT 0"]],
	cronRunLogs: [
		["worktrees", "provisioned_paths_json TEXT"],
		["apns_registrations", "relay_origin TEXT"],
		["device_pairing_pending", "refreshed_at_ms INTEGER"],
		["device_pairing_pending", "browser_origin TEXT"],
		["device_pairing_paired", "approved_via TEXT"],
		["device_pairing_paired", "browser_origin TEXT"],
		["device_pairing_paired", "operator_label TEXT"],
		["device_pairing_paired", "node_surface_json TEXT"],
		["device_pairing_paired", "pending_node_surface_json TEXT"],
		["cron_run_logs", "status TEXT"],
		["cron_run_logs", "error TEXT"],
		["cron_run_logs", "summary TEXT"],
		["cron_run_logs", "diagnostics_summary TEXT"],
		["cron_run_logs", "delivery_status TEXT"],
		["cron_run_logs", "delivery_error TEXT"],
		["cron_run_logs", "delivered INTEGER"],
		["cron_run_logs", "session_id TEXT"],
		["cron_run_logs", "session_key TEXT"],
		["cron_run_logs", "run_id TEXT"],
		["cron_run_logs", "run_at_ms INTEGER"],
		["cron_run_logs", "duration_ms INTEGER"],
		["cron_run_logs", "next_run_at_ms INTEGER"],
		["cron_run_logs", "model TEXT"],
		["cron_run_logs", "provider TEXT"],
		["cron_run_logs", "total_tokens INTEGER"],
		["cron_run_logs", "entry_json TEXT NOT NULL DEFAULT '{}'"],
		["cron_run_logs", "created_at INTEGER NOT NULL DEFAULT 0"]
	],
	acpReplay: [["acp_replay_events", "estimated_bytes INTEGER NOT NULL DEFAULT 0"], ["acp_replay_sessions", "estimated_bytes INTEGER NOT NULL DEFAULT 0"]],
	cronJobs: [
		["cron_jobs", "description TEXT"],
		["cron_jobs", "declaration_key TEXT"],
		["cron_jobs", "owner_agent_id TEXT"],
		["cron_jobs", "name TEXT NOT NULL DEFAULT ''"],
		["cron_jobs", "enabled INTEGER NOT NULL DEFAULT 1"],
		["cron_jobs", "agent_id TEXT"],
		["cron_jobs", "payload_kind TEXT NOT NULL DEFAULT 'message'"],
		["cron_jobs", "state_json TEXT NOT NULL DEFAULT '{}'"],
		["cron_jobs", "runtime_updated_at_ms INTEGER"],
		["cron_jobs", "schedule_identity TEXT"],
		["cron_jobs", "sort_order INTEGER NOT NULL DEFAULT 0"]
	],
	deliveryQueue: [
		["sandbox_registry_entries", "session_key TEXT"],
		["sandbox_registry_entries", "backend_id TEXT"],
		["sandbox_registry_entries", "runtime_label TEXT"],
		["sandbox_registry_entries", "image TEXT"],
		["sandbox_registry_entries", "created_at_ms INTEGER"],
		["sandbox_registry_entries", "last_used_at_ms INTEGER"],
		["sandbox_registry_entries", "config_label_kind TEXT"],
		["sandbox_registry_entries", "config_hash TEXT"],
		["sandbox_registry_entries", "cdp_port INTEGER"],
		["sandbox_registry_entries", "no_vnc_port INTEGER"],
		["delivery_queue_entries", "entry_kind TEXT"],
		["delivery_queue_entries", "session_key TEXT"],
		["delivery_queue_entries", "channel TEXT"],
		["delivery_queue_entries", "target TEXT"],
		["delivery_queue_entries", "account_id TEXT"],
		["delivery_queue_entries", "retry_count INTEGER NOT NULL DEFAULT 0"],
		["delivery_queue_entries", "last_attempt_at INTEGER"],
		["delivery_queue_entries", "last_error TEXT"],
		["delivery_queue_entries", "recovery_state TEXT"],
		["delivery_queue_entries", "platform_send_started_at INTEGER"]
	],
	originalMediaRoot: [["managed_outgoing_image_records", "original_media_root TEXT NOT NULL DEFAULT ''"]],
	beforeTaskAttribution: [
		["managed_outgoing_image_records", "agent_id TEXT"],
		["managed_outgoing_image_records", "cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))"],
		["current_conversation_bindings", "conversation_kind TEXT NOT NULL DEFAULT 'channel'"],
		["device_bootstrap_tokens", "pending_profile_json TEXT"],
		["gateway_restart_handoff", "restart_trace_started_at INTEGER"],
		["gateway_restart_handoff", "restart_trace_last_at INTEGER"],
		["gateway_restart_intent", "reason TEXT"],
		["gateway_restart_sentinel", "delivery_channel TEXT"],
		["gateway_restart_sentinel", "delivery_to TEXT"],
		["gateway_restart_sentinel", "delivery_account_id TEXT"],
		["gateway_restart_sentinel", "message TEXT"],
		["gateway_restart_sentinel", "continuation_json TEXT"],
		["gateway_restart_sentinel", "doctor_hint TEXT"],
		["gateway_restart_sentinel", "stats_json TEXT"],
		["gateway_boot_lifecycle", "startup_reason TEXT"],
		["official_external_plugin_catalog_snapshots", "trust_mode TEXT"],
		["official_external_plugin_catalog_snapshots", "trust_key_id TEXT"],
		["official_external_plugin_catalog_snapshots", "trust_signature_count INTEGER"],
		["official_external_plugin_catalog_snapshots", "trust_threshold INTEGER"],
		["official_external_plugin_catalog_snapshots", "trust_verified_at TEXT"]
	],
	taskRequester: [["task_runs", "requester_agent_id TEXT"]],
	taskRunDetails: [
		["task_runs", "tool_use_count INTEGER"],
		["task_runs", "last_tool_name TEXT"],
		["task_runs", "detail_json TEXT"]
	],
	workerEnvironments: [
		["worker_environments", "bootstrap_bundle_hash TEXT"],
		["worker_environments", "bootstrap_openclaw_version TEXT"],
		["worker_environments", "bootstrap_protocol_features_json TEXT"],
		["worker_environments", "bootstrap_install_kind TEXT"],
		["worker_environments", "owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0)"],
		["worker_environments", "ssh_host_key TEXT"],
		["worker_workspace_pending_results", "staged_result_ref TEXT"],
		["worker_environments", "teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed'))"]
	]
};
//#endregion
//#region src/state/openclaw-state-db-schema-v36-template-names.ts
const TEMPLATE_STATE_TABLE_RENAMES = [
	["claw_installs", "template_installs"],
	["claw_workspace_files", "template_workspace_files"],
	["claw_package_refs", "template_package_refs"],
	["claw_cron_refs", "template_cron_refs"],
	["claw_mcp_server_refs", "template_mcp_server_refs"]
];
const columns = [
	[
		"template_installs",
		"claw_name",
		"template_name"
	],
	[
		"template_installs",
		"claw_version",
		"template_version"
	],
	[
		"template_package_refs",
		"claw_name",
		"template_name"
	]
];
const targetTables = new Set(TEMPLATE_STATE_TABLE_RENAMES.map(([, e]) => e));
const additiveColumns = CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.filter(({ tableName: e }) => targetTables.has(e));
const orderedColumns = [...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageUpdatedAt, ...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageIntegrity];
const recordVersions = [
	["template_installs", [
		1,
		2,
		3
	].map((e) => [`openclaw.clawInstallRecord.v${e}`, `openclaw.templateInstallRecord.v${e}`])],
	["template_workspace_files", [["openclaw.clawWorkspaceFileRecord.v1", "openclaw.templateWorkspaceFileRecord.v1"]]],
	["template_package_refs", [["openclaw.clawPackageRef.v1", "openclaw.templatePackageRef.v1"]]],
	["template_cron_refs", [["openclaw.clawCronRef.v1", "openclaw.templateCronRef.v1"]]],
	["template_mcp_server_refs", [["openclaw.clawMcpServerRef.v1", "openclaw.templateMcpServerRef.v1"]]]
];
const literal = (e) => `'${e.replaceAll("'", "''")}'`;
/** Historical schema/backup metadata only; runtime readers use canonical names. */
function legacyTemplateStateIdentifier(e) {
	for (const [t, n] of [...TEMPLATE_STATE_TABLE_RENAMES, ...columns.map(([, e, t]) => [e, t])]) if (e === n) return t;
	return e;
}
/** Exact predecessor DDL, not a live alias or a data-string rewrite. */
function withLegacyTemplateStateSchema(e) {
	return e.replace(/\btemplate_(?:installs|workspace_files|package_refs|cron_refs|mcp_server_refs|name|version)\b/gu, legacyTemplateStateIdentifier).replaceAll("'template-introduced'", "'claw-introduced'").replaceAll("'template'", "'claw'");
}
function withLegacyTemplateStateCompatibility(e) {
	return {
		...e,
		excludedTables: e.excludedTables?.map(withLegacyTemplateStateSchema),
		allowedMissingTables: e.allowedMissingTables?.map(withLegacyTemplateStateSchema),
		allowedMissingColumns: e.allowedMissingColumns?.map(withLegacyTemplateStateSchema),
		allowedColumnDefinitions: e.allowedColumnDefinitions && Object.fromEntries(Object.entries(e.allowedColumnDefinitions).map(([e, t]) => [withLegacyTemplateStateSchema(e), t.map(withLegacyTemplateStateSchema)]))
	};
}
function versionUpdates(e, t) {
	return `UPDATE ${quoteSqliteIdentifier(e)} SET schema_version = CASE schema_version
    ${t.map(([e, t]) => `WHEN ${literal(e)} THEN ${literal(t)}`).join("\n")}
    ELSE schema_version END WHERE schema_version IN (${t.map(([e]) => literal(e)).join(", ")});`;
}
/** The existing schema owner has disabled foreign keys before BEGIN. */
function migrateTemplateStateNames(e, t) {
	if (t >= 36) return false;
	const n = captureSqliteSchemaFacts(e);
	const r = new Set(n.tables);
	const i = /* @__PURE__ */ new Set([...TEMPLATE_STATE_TABLE_RENAMES.flat(), "agent_provenance"]);
	const a = new Map([...n.tableSql].flatMap(([e, t]) => t && i.has(e) ? [[e, new Set(parseSqliteTableDefinition(t, e).columns.keys())]] : []));
	const addColumn = (t, n) => {
		const r = n.trim().split(/\s+/, 1)[0];
		const i = a.get(t);
		if (!r || !i || i.has(r)) return false;
		e.exec(`ALTER TABLE ${quoteSqliteIdentifier(t)} ADD COLUMN ${n};`);
		i.add(r);
		return true;
	};
	let o = false;
	for (const [t, n] of TEMPLATE_STATE_TABLE_RENAMES) if (r.has(t)) {
		if (r.has(n)) throw new Error(`Both ${t} and ${n} exist; preserve the store for Doctor inspection.`);
		e.exec(`ALTER TABLE ${quoteSqliteIdentifier(t)} RENAME TO ${quoteSqliteIdentifier(n)};`);
		r.delete(t);
		r.add(n);
		const i = a.get(t);
		if (!i) throw new Error(`Missing predecessor column contract for ${t}`);
		a.set(n, i);
		a.delete(t);
		o = true;
	}
	for (const [t, n, r] of columns) if (a.get(t)?.has(n)) {
		e.exec(`ALTER TABLE ${quoteSqliteIdentifier(t)} RENAME COLUMN ${quoteSqliteIdentifier(n)} TO ${quoteSqliteIdentifier(r)};`);
		a.get(t)?.delete(n);
		a.get(t)?.add(r);
		o = true;
	}
	for (const { tableName: e, columnName: t, dataType: n } of additiveColumns) addColumn(e, `${t} ${n}`);
	const s = getNodeSqliteKysely(e);
	if (addColumn(...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageUpdatedAt[0])) executeSqliteQuerySync(e, s.updateTable("template_package_refs").set((e) => ({ updated_at_ms: e.ref("installed_at_ms") })));
	for (const [e, t] of ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageIntegrity) addColumn(e, t);
	const c = captureSqliteSchemaFacts(e);
	const l = {
		template_package_refs: [
			"origin",
			"claw-introduced",
			"template-introduced"
		],
		template_mcp_server_refs: [
			"origin",
			"claw-introduced",
			"template-introduced"
		],
		agent_provenance: [
			"created_via",
			"claw",
			"template"
		]
	};
	for (const t of ["template_installs", ...Object.keys(l)]) {
		const n = c.tableSql.get(t);
		if (!n) continue;
		const r = n.slice(n.indexOf("("));
		let i = r;
		for (const [e, , n] of columns) if (e === t) i = i.replaceAll(quoteSqliteIdentifier(n), n);
		const a = l[t];
		if (a) i = i.replaceAll(literal(a[1]), literal(a[2]));
		if (i === r) continue;
		const s = quoteSqliteIdentifier(`${t}_migration_v36`);
		const u = [...parseSqliteTableDefinition(n, t).columns.keys()];
		const d = /\bWITHOUT\s+ROWID\b/iu.test(n) ? [] : ["rowid"];
		const f = [...d, ...u].map(quoteSqliteIdentifier).join(", ");
		const p = [...d.map(quoteSqliteIdentifier), ...u.map((e) => a && e === a[0] ? `CASE ${quoteSqliteIdentifier(e)} WHEN ${literal(a[1])} THEN ${literal(a[2])} ELSE ${quoteSqliteIdentifier(e)} END` : quoteSqliteIdentifier(e))].join(", ");
		e.exec(`CREATE TABLE ${s} ${i};
      INSERT INTO ${s} (${f}) SELECT ${p} FROM ${quoteSqliteIdentifier(t)};
      DROP TABLE ${quoteSqliteIdentifier(t)};
      ALTER TABLE ${s} RENAME TO ${quoteSqliteIdentifier(t)};`);
		for (const n of [...c.indexDefinitions.values(), ...c.triggers.values()]) if (n.table === t && typeof n.sql === "string") e.exec(n.sql);
		o = true;
	}
	for (const [t, n] of recordVersions) if (r.has(t)) for (const [r, i] of n) executeSqliteQuerySync(e, s.updateTable(t).set({ schema_version: i }).where("schema_version", "=", r));
	return o;
}
const stateTemplateNamesMigration = {
	version: 36,
	tables: [
		...TEMPLATE_STATE_TABLE_RENAMES.flat(),
		"agent_provenance",
		"sqlite_stat1",
		"sqlite_stat4"
	],
	columns: [...additiveColumns.map(({ tableName: e, columnName: t }) => `${e}.${t}`), ...orderedColumns.map(([e, t]) => `${e}.${t.split(" ", 1)[0]}`)],
	migrate: migrateTemplateStateNames,
	applied: "Migrated released starter tables and provenance to canonical Template names (v36)"
};
const TEMPLATE_STATE_POSTGRES_MIGRATION_SQL = `DO $template_names_v36$
DECLARE item record; column_item record; constraint_name text; next_constraint_name text;
BEGIN
  FOR item IN SELECT * FROM (VALUES
    ${TEMPLATE_STATE_TABLE_RENAMES.map(([e, t]) => `(${literal(e)}, ${literal(t)})`).join(",\n")}
  ) AS names(old_name, new_name) LOOP
    EXECUTE format('ALTER TABLE %I RENAME TO %I', item.old_name, item.new_name);
    FOR column_item IN SELECT * FROM (VALUES
      ${columns.map(([e, t, n]) => `(${literal(e)}, ${literal(t)}, ${literal(n)})`).join(",\n")}
    ) AS columns(table_name, old_name, new_name) WHERE table_name = item.new_name LOOP
      EXECUTE format('ALTER TABLE %I RENAME COLUMN %I TO %I', item.new_name, column_item.old_name, column_item.new_name);
    END LOOP;
    FOR constraint_name IN SELECT conname FROM pg_constraint
      WHERE conrelid = to_regclass(item.new_name) LOOP
      next_constraint_name := constraint_name;
      IF left(constraint_name, length(item.old_name) + 1) = item.old_name || '_' THEN
        next_constraint_name := item.new_name || substr(constraint_name, length(item.old_name) + 1);
      END IF;
      next_constraint_name := replace(replace(next_constraint_name, '_claw_name_', '_template_name_'), '_claw_version_', '_template_version_');
      IF next_constraint_name <> constraint_name THEN
        EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', item.new_name, constraint_name, next_constraint_name);
      END IF;
    END LOOP;
  END LOOP;
  ${["template_package_refs", "template_mcp_server_refs"].map((e) => `
    ALTER TABLE ${quoteSqliteIdentifier(e)} DROP CONSTRAINT ${quoteSqliteIdentifier(`${e}_origin_check`)};
    UPDATE ${quoteSqliteIdentifier(e)} SET origin = 'template-introduced' WHERE origin = 'claw-introduced';
    ALTER TABLE ${quoteSqliteIdentifier(e)} ADD CONSTRAINT ${quoteSqliteIdentifier(`${e}_origin_check`)}
      CHECK (origin IN ('template-introduced', 'pre-existing'));`).join("\n")}
  IF to_regclass('agent_provenance') IS NOT NULL THEN
    ALTER TABLE agent_provenance DROP CONSTRAINT agent_provenance_created_via_check;
    UPDATE agent_provenance SET created_via = 'template' WHERE created_via = 'claw';
    ALTER TABLE agent_provenance ADD CONSTRAINT agent_provenance_created_via_check
      CHECK (created_via IN ('operator', 'agent', 'template'));
  END IF;
  ${recordVersions.map(([e, t]) => versionUpdates(e, t)).join("\n")}
END $template_names_v36$;`;
//#endregion
//#region src/state/openclaw-state-postgres-admission.ts
/** Callers own replay safety; retries require a settled PostgreSQL transaction. */
function withPostgresSchemaAdmissionRetry(e, t, n) {
	try {
		return t();
	} catch (r) {
		if (!(r instanceof PostgresSchemaAdmissionUnavailableError) || !isPostgresSqlConnection(e) || n?.() === false || !e.isOpen || e.isTransaction) throw r;
		const i = Math.min(Date.now() + 1e3, readSqliteDatabaseAdmissionDeadline() ?? Infinity);
		const a = performance.now() + Math.max(0, i - Date.now());
		const o = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
		return withSqliteDatabaseAdmissionWait({ deadlineAtMs: i }, () => {
			for (let s = 10;; s = Math.min(s * 2, 100)) {
				assertSqliteDatabaseAdmissionWaitActive();
				const c = Math.min(a - performance.now(), i - Date.now());
				if (c <= 0) throw r;
				Atomics.wait(o, 0, 0, Math.min(s, c));
				assertSqliteDatabaseAdmissionWaitActive();
				if (performance.now() >= a || Date.now() >= i) throw r;
				if (n?.() === false || !e.isOpen || e.isTransaction) throw r;
				try {
					if (!getPostgresPhysicalFacts(e, { refresh: true })) continue;
					return t();
				} catch (t) {
					if (t instanceof SqliteDatabaseAdmissionTimeoutError && (performance.now() >= a || Date.now() >= i)) throw r;
					if (!(t instanceof PostgresSchemaAdmissionUnavailableError) || n?.() === false || !e.isOpen || e.isTransaction) throw t;
				}
			}
		});
	}
}
//#endregion
//#region src/infra/update-run-timeouts.ts
/** Shared legacy-reader grace and inactive update reconciliation threshold. */
const ABANDONED_UPDATE_RUN_MS = 18e5;
//#endregion
//#region src/state/openclaw-state-schema-publication.ts
const TERMINAL_GRACE_MS = 3e5;
/** Only the 2026.9.2 release line reopens the ledger without the transaction fence. */
function isUnfencedUpdateDriver(e) {
	const t = typeof e === "string" ? parse(e) : null;
	return t !== null && `${t.major}.${t.minor}.${t.patch}` === "2026.9.2";
}
/** Every unfenced driver must clear its own deadline; a newer run cannot hide an older one. */
function readStateSchemaPublicationBlocker(e, t = Date.now()) {
	if (!tableExists(e, "update_runs")) return;
	const n = executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("update_runs").select([
		"run_id",
		"before_json",
		"status",
		"updated_at_ms",
		"finished_at_ms"
	]).where((e) => e.or([e.and([e("status", "=", "running"), e("updated_at_ms", ">=", t - ABANDONED_UPDATE_RUN_MS)]), e.and([e("status", "!=", "running"), e.or([e("finished_at_ms", ">", t - TERMINAL_GRACE_MS), e("finished_at_ms", "is", null)])])])).orderBy("run_id")).rows;
	let r;
	for (const e of n) {
		const t = JSON.parse(e.before_json);
		if (!isRecord(t) || typeof t.version !== "string" || !isUnfencedUpdateDriver(t.version)) continue;
		const n = e.status === "running" ? e.updated_at_ms + ABANDONED_UPDATE_RUN_MS + 1 : e.finished_at_ms === null ? null : e.finished_at_ms + TERMINAL_GRACE_MS;
		if (!r || n === null || r.publishAfterMs !== null && n > r.publishAfterMs) r = {
			runId: e.run_id,
			updaterVersion: t.version,
			publishAfterMs: n
		};
	}
	return r;
}
/** Called inside the schema write transaction, after all content migrations succeed. */
function resolveStateSchemaVersionToPublish(e) {
	const t = readSqliteUserVersion(e);
	if (t >= 36 || !readStateSchemaPublicationBlocker(e)) return 36;
	if (!tableExists(e, "config_machine_state")) throw new Error("Shared state schema publication cannot be deferred without config_machine_state.");
	writeStateSchemaContentVersion(e);
	invalidateSqliteSchemaFacts(e);
	return t;
}
/** Persist the content marker inside the schema owner's transaction. */
function writeStateSchemaContentVersion(e) {
	executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("config_machine_state").values({
		state_key: CONTENT_VERSION_KEY,
		value_json: String(36),
		updated_at_ms: Date.now()
	}).onConflict((e) => e.column("state_key").doUpdateSet({
		value_json: String(36),
		updated_at_ms: Date.now()
	}).where("config_machine_state.value_json", "!=", String(36))));
}
/** Advance an existing migration marker without changing its original timestamp. */
function advanceStateSchemaContentVersion(e, t) {
	executeSqliteQuerySync(e, getNodeSqliteKysely(e).updateTable("config_machine_state").set({ value_json: String(t.toVersion) }).where("state_key", "=", CONTENT_VERSION_KEY).where("value_json", "=", String(t.fromVersion)));
}
//#endregion
//#region src/state/postgres-schema.generated/runtime.ts
const statePostgresRuntime = {
	eagerSql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"acp_replay_events\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"seq\" bigint NOT NULL,\n  \"at\" bigint NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\",\n  \"update_json\" text COLLATE \"C\" NOT NULL,\n  \"estimated_bytes\" bigint NOT NULL DEFAULT 0,\n  PRIMARY KEY (\"session_id\", \"seq\")\n);\n\nCREATE TABLE \"acp_replay_sessions\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"cwd\" text COLLATE \"C\" NOT NULL,\n  \"complete\" bigint NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  \"next_seq\" bigint NOT NULL,\n  \"estimated_bytes\" bigint NOT NULL DEFAULT 0,\n  PRIMARY KEY (\"session_id\")\n);\n\nCREATE TABLE \"acp_sessions\" (\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\",\n  \"backend\" text COLLATE \"C\" NOT NULL,\n  \"agent\" text COLLATE \"C\" NOT NULL,\n  \"runtime_session_name\" text COLLATE \"C\" NOT NULL,\n  \"identity_json\" text COLLATE \"C\",\n  \"resume_agent_session_id\" text COLLATE \"C\",\n  \"resume_acpx_session_id\" text COLLATE \"C\",\n  \"mode\" text COLLATE \"C\" NOT NULL,\n  \"runtime_options_json\" text COLLATE \"C\",\n  \"cwd\" text COLLATE \"C\",\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"last_activity_at\" bigint NOT NULL,\n  \"last_error\" text COLLATE \"C\",\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"session_key\")\n);\n\nCREATE TABLE \"agent_database_leases\" (\n  \"lease_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"owner_pid\" bigint NOT NULL,\n  \"owner_start_time\" bigint,\n  \"opened_at\" bigint NOT NULL,\n  \"provenance\" text COLLATE \"C\",\n  PRIMARY KEY (\"lease_id\")\n);\n\nCREATE TABLE \"agent_databases\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" bigint NOT NULL,\n  \"last_seen_at\" bigint NOT NULL,\n  \"size_bytes\" bigint,\n  PRIMARY KEY (\"agent_id\", \"path\")\n);\n\nCREATE TABLE \"apns_registration_tombstones\" (\n  \"node_id\" text COLLATE \"C\" NOT NULL,\n  \"deleted_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"node_id\")\n);\n\nCREATE TABLE \"apns_registrations\" (\n  \"node_id\" text COLLATE \"C\" NOT NULL,\n  \"transport\" text COLLATE \"C\" NOT NULL,\n  \"token\" text COLLATE \"C\",\n  \"relay_handle\" text COLLATE \"C\",\n  \"send_grant\" text COLLATE \"C\",\n  \"installation_id\" text COLLATE \"C\",\n  \"relay_origin\" text COLLATE \"C\",\n  \"topic\" text COLLATE \"C\" NOT NULL,\n  \"environment\" text COLLATE \"C\" NOT NULL,\n  \"distribution\" text COLLATE \"C\",\n  \"token_debug_suffix\" text COLLATE \"C\",\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"node_id\")\n);\n\nCREATE TABLE \"audit_events\" (\n  \"sequence\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"event_id\" text COLLATE \"C\" NOT NULL,\n  \"source_id\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" bigint NOT NULL DEFAULT 1,\n  \"source_sequence\" bigint NOT NULL,\n  \"occurred_at\" bigint NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"action\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"error_code\" text COLLATE \"C\",\n  \"actor_type\" text COLLATE \"C\" NOT NULL,\n  \"actor_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\",\n  \"session_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"tool_call_id\" text COLLATE \"C\",\n  \"tool_name\" text COLLATE \"C\",\n  \"direction\" text COLLATE \"C\",\n  \"channel\" text COLLATE \"C\",\n  \"conversation_kind\" text COLLATE \"C\",\n  \"message_outcome\" text COLLATE \"C\",\n  \"reason_code\" text COLLATE \"C\",\n  \"delivery_kind\" text COLLATE \"C\",\n  \"failure_stage\" text COLLATE \"C\",\n  \"duration_ms\" bigint,\n  \"result_count\" bigint,\n  \"account_ref\" text COLLATE \"C\",\n  \"conversation_ref\" text COLLATE \"C\",\n  \"message_ref\" text COLLATE \"C\",\n  \"target_ref\" text COLLATE \"C\",\n  PRIMARY KEY (\"sequence\"),\n  UNIQUE (\"event_id\"),\n  UNIQUE (\"source_id\")\n);\n\nCREATE TABLE \"audit_identity_keys\" (\n  \"id\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"key_id\" text COLLATE \"C\" NOT NULL,\n  \"key\" bytea NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  PRIMARY KEY (\"id\"),\n  CHECK ((\"id\" = 1))\n);\n\nCREATE TABLE \"backup_runs\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"archive_path\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"manifest_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"id\")\n);\n\nCREATE TABLE \"capture_blobs\" (\n  \"blob_id\" text COLLATE \"C\" NOT NULL,\n  \"content_type\" text COLLATE \"C\",\n  \"encoding\" text COLLATE \"C\" NOT NULL,\n  \"size_bytes\" bigint NOT NULL,\n  \"sha256\" text COLLATE \"C\" NOT NULL,\n  \"data\" bytea NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  PRIMARY KEY (\"blob_id\")\n);\n\nCREATE TABLE \"capture_events\" (\n  \"id\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"ts\" bigint NOT NULL,\n  \"source_scope\" text COLLATE \"C\" NOT NULL,\n  \"source_process\" text COLLATE \"C\" NOT NULL,\n  \"protocol\" text COLLATE \"C\" NOT NULL,\n  \"direction\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"flow_id\" text COLLATE \"C\" NOT NULL,\n  \"method\" text COLLATE \"C\",\n  \"host\" text COLLATE \"C\",\n  \"path\" text COLLATE \"C\",\n  \"status\" bigint,\n  \"close_code\" bigint,\n  \"content_type\" text COLLATE \"C\",\n  \"headers_json\" text COLLATE \"C\",\n  \"data_text\" text COLLATE \"C\",\n  \"data_blob_id\" text COLLATE \"C\",\n  \"data_sha256\" text COLLATE \"C\",\n  \"error_text\" text COLLATE \"C\",\n  \"meta_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"id\")\n);\n\nCREATE TABLE \"capture_sessions\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"started_at\" bigint NOT NULL,\n  \"ended_at\" bigint,\n  \"mode\" text COLLATE \"C\" NOT NULL,\n  \"source_scope\" text COLLATE \"C\" NOT NULL,\n  \"source_process\" text COLLATE \"C\" NOT NULL,\n  \"proxy_url\" text COLLATE \"C\",\n  PRIMARY KEY (\"id\")\n);\n\nCREATE TABLE \"channel_ingress_events\" (\n  \"queue_name\" text COLLATE \"C\" NOT NULL,\n  \"event_id\" text COLLATE \"C\" NOT NULL,\n  \"channel_id\" text COLLATE \"C\" NOT NULL,\n  \"account_id\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"lane_key\" text COLLATE \"C\",\n  \"payload_json\" text COLLATE \"C\" NOT NULL,\n  \"metadata_json\" text COLLATE \"C\",\n  \"received_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  \"claim_token\" text COLLATE \"C\",\n  \"claim_owner\" text COLLATE \"C\",\n  \"claimed_at\" bigint,\n  \"attempts\" bigint NOT NULL DEFAULT 0,\n  \"last_attempt_at\" bigint,\n  \"last_error\" text COLLATE \"C\",\n  \"failed_reason\" text COLLATE \"C\",\n  \"failed_at\" bigint,\n  \"completed_at\" bigint,\n  \"completed_metadata_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"queue_name\", \"event_id\")\n);\n\nCREATE TABLE \"channel_pairing_allow_entries\" (\n  \"channel_key\" text COLLATE \"C\" NOT NULL,\n  \"account_id\" text COLLATE \"C\" NOT NULL,\n  \"entry\" text COLLATE \"C\" NOT NULL,\n  \"sort_order\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"channel_key\", \"account_id\", \"entry\")\n);\n\nCREATE TABLE \"channel_pairing_requests\" (\n  \"channel_key\" text COLLATE \"C\" NOT NULL,\n  \"account_id\" text COLLATE \"C\" NOT NULL,\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"code\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" text COLLATE \"C\" NOT NULL,\n  \"last_seen_at\" text COLLATE \"C\" NOT NULL,\n  \"meta_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"channel_key\", \"account_id\", \"request_id\")\n);\n\nCREATE TABLE \"clawhub_promotion_claims\" (\n  \"slug\" text COLLATE \"C\" NOT NULL,\n  \"provider\" text COLLATE \"C\",\n  \"model_keys_json\" text COLLATE \"C\" NOT NULL,\n  \"ends_at_ms\" bigint NOT NULL,\n  \"claimed_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"slug\")\n);\n\nCREATE TABLE \"config_health_entries\" (\n  \"config_path\" text COLLATE \"C\" NOT NULL,\n  \"last_known_good_json\" text COLLATE \"C\",\n  \"last_promoted_good_json\" text COLLATE \"C\",\n  \"last_observed_suspicious_signature\" text COLLATE \"C\",\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"config_path\")\n);\n\nCREATE TABLE \"config_machine_state\" (\n  \"state_key\" text COLLATE \"C\" NOT NULL,\n  \"value_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"state_key\")\n);\n\nCREATE TABLE \"cron_job_scratch\" (\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"job_id\" text COLLATE \"C\" NOT NULL,\n  \"content\" text COLLATE \"C\",\n  \"revision\" bigint NOT NULL,\n  \"source_sha256\" text COLLATE \"C\",\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"store_key\", \"job_id\"),\n  CHECK ((\"revision\" >= 1)),\n  CHECK (\"content\" IS NULL OR (octet_length(convert_to(\"content\", 'UTF8')) <= 262144))\n);\n\nCREATE TABLE \"cron_jobs\" (\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"job_id\" text COLLATE \"C\" NOT NULL,\n  \"declaration_key\" text COLLATE \"C\",\n  \"owner_agent_id\" text COLLATE \"C\",\n  \"name\" text COLLATE \"C\" NOT NULL,\n  \"description\" text COLLATE \"C\",\n  \"enabled\" bigint NOT NULL,\n  \"agent_id\" text COLLATE \"C\",\n  \"payload_kind\" text COLLATE \"C\" NOT NULL,\n  \"job_json\" text COLLATE \"C\" NOT NULL,\n  \"grant_definition_revision\" text COLLATE \"C\",\n  \"grant_definition_generation\" bigint,\n  \"grant_definition_updated_at\" bigint,\n  \"state_json\" text COLLATE \"C\" NOT NULL DEFAULT '{}',\n  \"runtime_updated_at_ms\" bigint,\n  \"schedule_identity\" text COLLATE \"C\",\n  \"sort_order\" bigint NOT NULL DEFAULT 0,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"store_key\", \"job_id\")\n);\n\nCREATE TABLE \"current_conversation_bindings\" (\n  \"binding_key\" text COLLATE \"C\" NOT NULL,\n  \"binding_id\" text COLLATE \"C\" NOT NULL,\n  \"target_session_key\" text COLLATE \"C\" NOT NULL,\n  \"channel\" text COLLATE \"C\" NOT NULL,\n  \"account_id\" text COLLATE \"C\" NOT NULL,\n  \"conversation_kind\" text COLLATE \"C\" NOT NULL,\n  \"parent_conversation_id\" text COLLATE \"C\",\n  \"conversation_id\" text COLLATE \"C\" NOT NULL,\n  \"target_kind\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"bound_at\" bigint NOT NULL,\n  \"expires_at\" bigint,\n  \"metadata_json\" text COLLATE \"C\",\n  \"record_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"binding_key\")\n);\n\nCREATE TABLE \"delivery_queue_entries\" (\n  \"queue_name\" text COLLATE \"C\" NOT NULL,\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"entry_kind\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\",\n  \"channel\" text COLLATE \"C\",\n  \"target\" text COLLATE \"C\",\n  \"account_id\" text COLLATE \"C\",\n  \"retry_count\" bigint NOT NULL DEFAULT 0,\n  \"last_attempt_at\" bigint,\n  \"last_error\" text COLLATE \"C\",\n  \"recovery_state\" text COLLATE \"C\",\n  \"platform_send_started_at\" bigint,\n  \"entry_json\" text COLLATE \"C\" NOT NULL,\n  \"retention_id_prefix\" text COLLATE \"C\",\n  \"retention_max_age_ms\" bigint,\n  \"retention_max_entries\" bigint,\n  \"enqueued_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  \"failed_at\" bigint,\n  PRIMARY KEY (\"queue_name\", \"id\")\n);\n\nCREATE TABLE \"device_bootstrap_tokens\" (\n  \"token_key\" text COLLATE \"C\" NOT NULL,\n  \"token\" text COLLATE \"C\" NOT NULL,\n  \"setup_id\" text COLLATE \"C\",\n  \"ts\" bigint NOT NULL,\n  \"device_id\" text COLLATE \"C\",\n  \"public_key\" text COLLATE \"C\",\n  \"profile_json\" text COLLATE \"C\",\n  \"redeemed_profile_json\" text COLLATE \"C\",\n  \"pending_profile_json\" text COLLATE \"C\",\n  \"issued_at_ms\" bigint NOT NULL,\n  \"last_used_at_ms\" bigint,\n  PRIMARY KEY (\"token_key\")\n);\n\nCREATE TABLE \"device_pairing_paired\" (\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"public_key\" text COLLATE \"C\" NOT NULL,\n  \"display_name\" text COLLATE \"C\",\n  \"operator_label\" text COLLATE \"C\",\n  \"platform\" text COLLATE \"C\",\n  \"device_family\" text COLLATE \"C\",\n  \"client_id\" text COLLATE \"C\",\n  \"client_mode\" text COLLATE \"C\",\n  \"browser_origin\" text COLLATE \"C\",\n  \"role\" text COLLATE \"C\",\n  \"roles_json\" text COLLATE \"C\",\n  \"scopes_json\" text COLLATE \"C\",\n  \"approved_scopes_json\" text COLLATE \"C\",\n  \"remote_ip\" text COLLATE \"C\",\n  \"tokens_json\" text COLLATE \"C\",\n  \"approved_via\" text COLLATE \"C\",\n  \"node_surface_json\" text COLLATE \"C\",\n  \"pending_node_surface_json\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"approved_at_ms\" bigint NOT NULL,\n  \"last_seen_at_ms\" bigint,\n  \"last_seen_reason\" text COLLATE \"C\",\n  PRIMARY KEY (\"device_id\")\n);\n\nCREATE TABLE \"device_pairing_pending\" (\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"public_key\" text COLLATE \"C\" NOT NULL,\n  \"display_name\" text COLLATE \"C\",\n  \"platform\" text COLLATE \"C\",\n  \"device_family\" text COLLATE \"C\",\n  \"client_id\" text COLLATE \"C\",\n  \"client_mode\" text COLLATE \"C\",\n  \"browser_origin\" text COLLATE \"C\",\n  \"role\" text COLLATE \"C\",\n  \"roles_json\" text COLLATE \"C\",\n  \"scopes_json\" text COLLATE \"C\",\n  \"remote_ip\" text COLLATE \"C\",\n  \"silent\" bigint,\n  \"is_repair\" bigint,\n  \"ts\" bigint NOT NULL,\n  \"refreshed_at_ms\" bigint,\n  PRIMARY KEY (\"request_id\")\n);\n\nCREATE TABLE \"diagnostic_events\" (\n  \"scope\" text COLLATE \"C\" NOT NULL,\n  \"event_key\" text COLLATE \"C\" NOT NULL,\n  \"payload_json\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"sequence\" bigint NOT NULL DEFAULT 0,\n  PRIMARY KEY (\"scope\", \"event_key\")\n);\n\nCREATE TABLE \"exec_approvals_config\" (\n  \"config_key\" text COLLATE \"C\" NOT NULL,\n  \"raw_json\" text COLLATE \"C\" NOT NULL,\n  \"socket_path\" text COLLATE \"C\",\n  \"has_socket_token\" bigint NOT NULL,\n  \"default_security\" text COLLATE \"C\",\n  \"default_ask\" text COLLATE \"C\",\n  \"default_ask_fallback\" text COLLATE \"C\",\n  \"auto_allow_skills\" bigint,\n  \"agent_count\" bigint NOT NULL,\n  \"allowlist_count\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"config_key\")\n);\n\nCREATE TABLE \"flow_runs\" (\n  \"flow_id\" text COLLATE \"C\" NOT NULL,\n  \"shape\" text COLLATE \"C\",\n  \"sync_mode\" text COLLATE \"C\" NOT NULL DEFAULT 'managed',\n  \"owner_key\" text COLLATE \"C\" NOT NULL,\n  \"requester_origin_json\" text COLLATE \"C\",\n  \"controller_id\" text COLLATE \"C\",\n  \"revision\" bigint NOT NULL DEFAULT 0,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"notify_policy\" text COLLATE \"C\" NOT NULL,\n  \"goal\" text COLLATE \"C\" NOT NULL,\n  \"current_step\" text COLLATE \"C\",\n  \"blocked_task_id\" text COLLATE \"C\",\n  \"blocked_summary\" text COLLATE \"C\",\n  \"state_json\" text COLLATE \"C\",\n  \"wait_json\" text COLLATE \"C\",\n  \"cancel_requested_at\" bigint,\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  \"ended_at\" bigint,\n  PRIMARY KEY (\"flow_id\")\n);\n\nCREATE TABLE \"gateway_boot_lifecycle\" (\n  \"boot_id\" text COLLATE \"C\" NOT NULL,\n  \"pid\" bigint NOT NULL,\n  \"started_at_ms\" bigint NOT NULL,\n  \"completed_at_ms\" bigint,\n  \"outcome\" text COLLATE \"C\",\n  \"startup_reason\" text COLLATE \"C\",\n  \"reason\" text COLLATE \"C\",\n  PRIMARY KEY (\"boot_id\")\n);\n\nCREATE TABLE \"gateway_restart_handoff\" (\n  \"handoff_key\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"version\" bigint NOT NULL,\n  \"intent_id\" text COLLATE \"C\" NOT NULL,\n  \"pid\" bigint NOT NULL,\n  \"process_instance_id\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"expires_at\" bigint NOT NULL,\n  \"reason\" text COLLATE \"C\",\n  \"restart_trace_started_at\" bigint,\n  \"restart_trace_last_at\" bigint,\n  \"source\" text COLLATE \"C\" NOT NULL,\n  \"restart_kind\" text COLLATE \"C\" NOT NULL,\n  \"supervisor_mode\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"handoff_key\")\n);\n\nCREATE TABLE \"gateway_restart_intent\" (\n  \"intent_key\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"pid\" bigint NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"reason\" text COLLATE \"C\",\n  \"force\" bigint,\n  \"wait_ms\" bigint,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"intent_key\")\n);\n\nCREATE TABLE \"gateway_restart_sentinel\" (\n  \"sentinel_key\" text COLLATE \"C\" NOT NULL,\n  \"version\" bigint NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"ts\" bigint NOT NULL,\n  \"session_key\" text COLLATE \"C\",\n  \"thread_id\" text COLLATE \"C\",\n  \"delivery_channel\" text COLLATE \"C\",\n  \"delivery_to\" text COLLATE \"C\",\n  \"delivery_account_id\" text COLLATE \"C\",\n  \"message\" text COLLATE \"C\",\n  \"continuation_json\" text COLLATE \"C\",\n  \"doctor_hint\" text COLLATE \"C\",\n  \"stats_json\" text COLLATE \"C\",\n  \"payload_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"sentinel_key\")\n);\n\nCREATE TABLE \"macos_port_guardian_records\" (\n  \"pid\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"port\" bigint NOT NULL,\n  \"command\" text COLLATE \"C\" NOT NULL,\n  \"mode\" text COLLATE \"C\" NOT NULL,\n  \"timestamp\" double precision NOT NULL,\n  PRIMARY KEY (\"pid\")\n);\n\nCREATE TABLE \"managed_outgoing_image_records\" (\n  \"attachment_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\",\n  \"message_id\" text COLLATE \"C\",\n  \"created_at\" text COLLATE \"C\" NOT NULL,\n  \"updated_at\" text COLLATE \"C\",\n  \"retention_class\" text COLLATE \"C\",\n  \"alt\" text COLLATE \"C\" NOT NULL,\n  \"original_media_root\" text COLLATE \"C\" NOT NULL,\n  \"original_media_id\" text COLLATE \"C\" NOT NULL,\n  \"original_media_subdir\" text COLLATE \"C\" NOT NULL,\n  \"original_content_type\" text COLLATE \"C\" NOT NULL,\n  \"original_width\" bigint,\n  \"original_height\" bigint,\n  \"original_size_bytes\" bigint,\n  \"original_filename\" text COLLATE \"C\",\n  \"record_json\" text COLLATE \"C\" NOT NULL,\n  \"cleanup_pending\" bigint NOT NULL DEFAULT 0,\n  PRIMARY KEY (\"attachment_id\"),\n  CHECK ((\"cleanup_pending\" IN (0, 1)))\n);\n\nCREATE TABLE \"mcp_oauth_stores\" (\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"format_version\" bigint NOT NULL,\n  \"store_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"store_key\"),\n  CHECK ((\"format_version\" = 1))\n);\n\nCREATE TABLE \"meeting_transcript_sessions\" (\n  \"started_at_ms\" bigint,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"started_at\" text COLLATE \"C\" NOT NULL,\n  \"selector\" text COLLATE \"C\" NOT NULL,\n  \"export_key\" text COLLATE \"C\" NOT NULL,\n  \"session_slug\" text COLLATE \"C\" NOT NULL,\n  \"provider_id\" text COLLATE \"C\" NOT NULL,\n  \"title\" text COLLATE \"C\",\n  \"source_json\" text COLLATE \"C\" NOT NULL,\n  \"source_account_id\" text COLLATE \"C\",\n  \"source_guild_id\" text COLLATE \"C\",\n  \"source_channel_id\" text COLLATE \"C\",\n  \"source_meeting_url\" text COLLATE \"C\",\n  \"source_thread_ts\" text COLLATE \"C\",\n  \"source_file_id\" text COLLATE \"C\",\n  \"stopped_at\" text COLLATE \"C\",\n  \"metadata_json\" text COLLATE \"C\",\n  \"metadata_agent_id\" text COLLATE \"C\",\n  \"export_manifest_json\" text COLLATE \"C\" NOT NULL DEFAULT '{}',\n  \"export_pending_json\" text COLLATE \"C\" NOT NULL DEFAULT '[]',\n  \"next_utterance_seq\" bigint NOT NULL DEFAULT 0,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\", \"started_at\"),\n  CHECK ((\"next_utterance_seq\" >= 0)),\n  CHECK ((\"created_at_ms\" >= 0)),\n  CHECK ((\"updated_at_ms\" >= 0)),\n  UNIQUE (\"selector\")\n);\n\nCREATE TABLE \"meeting_transcript_summaries\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_started_at\" text COLLATE \"C\" NOT NULL,\n  \"generated_at\" text COLLATE \"C\",\n  \"summary_json\" text COLLATE \"C\",\n  \"overview\" text COLLATE \"C\",\n  \"markdown\" text COLLATE \"C\",\n  \"utterance_count\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\", \"session_started_at\"),\n  CHECK ((\"utterance_count\" >= 0)),\n  CHECK (\"summary_json\" IS NOT NULL OR \"markdown\" IS NOT NULL)\n);\n\nCREATE TABLE \"meeting_transcript_utterances\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_started_at\" text COLLATE \"C\" NOT NULL,\n  \"sequence\" bigint NOT NULL,\n  \"utterance_id\" text COLLATE \"C\",\n  \"started_at\" text COLLATE \"C\",\n  \"ended_at\" text COLLATE \"C\",\n  \"speaker_id\" text COLLATE \"C\",\n  \"speaker_label\" text COLLATE \"C\",\n  \"text\" text COLLATE \"C\" NOT NULL,\n  \"final\" bigint,\n  \"metadata_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"session_id\", \"session_started_at\", \"sequence\"),\n  CHECK ((\"sequence\" >= 0)),\n  CHECK ((\"final\" IN (0, 1)))\n);\n\nCREATE TABLE \"migration_runs\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"started_at\" bigint NOT NULL,\n  \"finished_at\" bigint,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"report_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"id\")\n);\n\nCREATE TABLE \"migration_sources\" (\n  \"source_key\" text COLLATE \"C\" NOT NULL,\n  \"migration_kind\" text COLLATE \"C\" NOT NULL,\n  \"source_path\" text COLLATE \"C\" NOT NULL,\n  \"target_table\" text COLLATE \"C\" NOT NULL,\n  \"source_sha256\" text COLLATE \"C\",\n  \"source_size_bytes\" bigint,\n  \"source_record_count\" bigint,\n  \"last_run_id\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"imported_at\" bigint NOT NULL,\n  \"removed_source\" bigint NOT NULL DEFAULT 0,\n  \"report_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"source_key\")\n);\n\nCREATE TABLE \"native_hook_relay_bridges\" (\n  \"relay_id\" text COLLATE \"C\" NOT NULL,\n  \"pid\" bigint NOT NULL,\n  \"hostname\" text COLLATE \"C\" NOT NULL,\n  \"port\" bigint NOT NULL,\n  \"token\" text COLLATE \"C\" NOT NULL,\n  \"expires_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"relay_id\")\n);\n\nCREATE TABLE \"official_external_plugin_catalog_snapshots\" (\n  \"feed_url\" text COLLATE \"C\" NOT NULL,\n  \"body\" text COLLATE \"C\" NOT NULL,\n  \"status\" bigint NOT NULL,\n  \"etag\" text COLLATE \"C\",\n  \"last_modified\" text COLLATE \"C\",\n  \"checksum\" text COLLATE \"C\" NOT NULL,\n  \"saved_at\" text COLLATE \"C\" NOT NULL,\n  \"trust_mode\" text COLLATE \"C\",\n  \"trust_key_id\" text COLLATE \"C\",\n  \"trust_signature_count\" bigint,\n  \"trust_threshold\" bigint,\n  \"trust_verified_at\" text COLLATE \"C\",\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"feed_url\")\n);\n\nCREATE TABLE \"operator_approvals\" (\n  \"cursor_id\" bigint NOT NULL,\n  \"approval_id\" text COLLATE \"C\" NOT NULL,\n  \"resolution_ref\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"presentation_json\" text COLLATE \"C\" NOT NULL,\n  \"requested_by_device_id\" text COLLATE \"C\",\n  \"requested_by_client_id\" text COLLATE \"C\",\n  \"requested_by_device_token_auth\" bigint NOT NULL DEFAULT 0,\n  \"reviewer_device_ids_json\" text COLLATE \"C\" NOT NULL,\n  \"source_agent_id\" text COLLATE \"C\",\n  \"source_session_key\" text COLLATE \"C\",\n  \"source_session_id\" text COLLATE \"C\",\n  \"source_run_id\" text COLLATE \"C\",\n  \"source_tool_call_id\" text COLLATE \"C\",\n  \"source_tool_name\" text COLLATE \"C\",\n  \"audience_session_keys_json\" text COLLATE \"C\" NOT NULL,\n  \"runtime_epoch\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"expires_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"decision\" text COLLATE \"C\",\n  \"terminal_reason\" text COLLATE \"C\",\n  \"resolved_at_ms\" bigint,\n  \"resolver_kind\" text COLLATE \"C\",\n  \"resolver_id\" text COLLATE \"C\",\n  \"consumed_at_ms\" bigint,\n  \"consumed_by\" text COLLATE \"C\",\n  PRIMARY KEY (\"approval_id\"),\n  CHECK ((char_length(\"approval_id\") > 0) AND (\"approval_id\" NOT IN ('.', '..'))),\n  CHECK ((char_length(\"resolution_ref\") = 43) AND (\"resolution_ref\" COLLATE \"C\" !~ '\\A.*[^A-Za-z0-9_-].*\\Z')),\n  CHECK ((\"kind\" IN ('exec', 'plugin', 'system-agent'))),\n  CHECK ((\"status\" IN ('pending', 'allowed', 'denied', 'expired', 'cancelled'))),\n  CHECK ((\"decision\" IN ('allow-once', 'allow-always', 'deny'))),\n  CHECK ((\"terminal_reason\" IN ('user', 'timeout', 'malformed-verdict', 'no-route', 'run-aborted', 'gateway-restart', 'storage-corrupt'))),\n  CHECK ((\"resolver_kind\" IN ('device', 'channel', 'runtime', 'system'))),\n  CHECK ((\"expires_at_ms\" >= \"created_at_ms\")),\n  CHECK ((\"updated_at_ms\" >= \"created_at_ms\")),\n  CHECK (\"resolved_at_ms\" IS NULL OR (\"resolved_at_ms\" >= \"created_at_ms\")),\n  CHECK (\"resolved_at_ms\" IS NULL OR (\"resolved_at_ms\" <= \"updated_at_ms\")),\n  CHECK (\"consumed_at_ms\" IS NULL OR (\"consumed_at_ms\" >= \"resolved_at_ms\")),\n  CHECK (\"consumed_at_ms\" IS NULL OR (\"consumed_at_ms\" <= \"updated_at_ms\")),\n  CHECK ((\"requested_by_device_token_auth\" IN (0, 1))),\n  CHECK (((\"status\" = 'pending') AND \"decision\" IS NULL AND \"terminal_reason\" IS NULL AND \"resolved_at_ms\" IS NULL AND \"resolver_kind\" IS NULL AND \"resolver_id\" IS NULL AND \"consumed_at_ms\" IS NULL AND \"consumed_by\" IS NULL) OR ((\"status\" = 'allowed') AND (\"decision\" IN ('allow-once', 'allow-always')) AND (\"terminal_reason\" = 'user') AND \"resolved_at_ms\" IS NOT NULL AND \"resolver_kind\" IS NOT NULL) OR ((\"status\" = 'denied') AND (\"decision\" = 'deny') AND (\"terminal_reason\" IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')) AND \"resolved_at_ms\" IS NOT NULL AND \"resolver_kind\" IS NOT NULL AND \"consumed_at_ms\" IS NULL AND \"consumed_by\" IS NULL) OR ((\"status\" = 'expired') AND (\"decision\" = 'deny') AND (\"terminal_reason\" = 'timeout') AND \"resolved_at_ms\" IS NOT NULL AND \"resolver_kind\" IS NOT NULL AND \"consumed_at_ms\" IS NULL AND \"consumed_by\" IS NULL) OR ((\"status\" = 'cancelled') AND (\"decision\" = 'deny') AND (\"terminal_reason\" IN ('run-aborted', 'gateway-restart')) AND \"resolved_at_ms\" IS NOT NULL AND \"resolver_kind\" IS NOT NULL AND \"consumed_at_ms\" IS NULL AND \"consumed_by\" IS NULL)),\n  CHECK ((\"consumed_at_ms\" IS NULL AND \"consumed_by\" IS NULL) OR ((\"status\" = 'allowed') AND (\"decision\" = 'allow-once') AND \"consumed_at_ms\" IS NOT NULL AND \"consumed_by\" IS NOT NULL))\n);\n\nCREATE TABLE \"outbound_media_provenance\" (\n  \"realpath\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"version\" bigint NOT NULL,\n  \"sha256\" text COLLATE \"C\" NOT NULL,\n  \"size_bytes\" bigint NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"realpath\")\n);\n\nCREATE TABLE \"plugin_binding_approvals\" (\n  \"plugin_root\" text COLLATE \"C\" NOT NULL,\n  \"channel\" text COLLATE \"C\" NOT NULL,\n  \"account_id\" text COLLATE \"C\" NOT NULL,\n  \"plugin_id\" text COLLATE \"C\" NOT NULL,\n  \"plugin_name\" text COLLATE \"C\",\n  \"approved_at\" bigint NOT NULL,\n  PRIMARY KEY (\"plugin_root\", \"channel\", \"account_id\")\n);\n\nCREATE TABLE \"plugin_blob_entries\" (\n  \"plugin_id\" text COLLATE \"C\" NOT NULL,\n  \"namespace\" text COLLATE \"C\" NOT NULL,\n  \"entry_key\" text COLLATE \"C\" NOT NULL,\n  \"metadata_json\" text COLLATE \"C\" NOT NULL,\n  \"blob\" bytea NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"expires_at\" bigint,\n  PRIMARY KEY (\"plugin_id\", \"namespace\", \"entry_key\")\n);\n\nCREATE TABLE \"plugin_state_entries\" (\n  \"plugin_id\" text COLLATE \"C\" NOT NULL,\n  \"namespace\" text COLLATE \"C\" NOT NULL,\n  \"entry_key\" text COLLATE \"C\" NOT NULL,\n  \"value_json\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"expires_at\" bigint,\n  PRIMARY KEY (\"plugin_id\", \"namespace\", \"entry_key\")\n);\n\nCREATE TABLE \"sandbox_registry_entries\" (\n  \"registry_kind\" text COLLATE \"C\" NOT NULL,\n  \"container_name\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\",\n  \"backend_id\" text COLLATE \"C\",\n  \"runtime_label\" text COLLATE \"C\",\n  \"image\" text COLLATE \"C\",\n  \"created_at_ms\" bigint,\n  \"last_used_at_ms\" bigint,\n  \"config_label_kind\" text COLLATE \"C\",\n  \"config_hash\" text COLLATE \"C\",\n  \"cdp_port\" bigint,\n  \"no_vnc_port\" bigint,\n  \"entry_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"registry_kind\", \"container_name\")\n);\n\nCREATE TABLE \"schema_meta\" (\n  \"meta_key\" text COLLATE \"C\" NOT NULL,\n  \"role\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" bigint NOT NULL,\n  \"agent_id\" text COLLATE \"C\",\n  \"app_version\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"meta_key\")\n);\n\nCREATE TABLE \"session_groups\" (\n  \"name\" text COLLATE \"C\" NOT NULL,\n  \"position\" bigint NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"cwd\" text COLLATE \"C\",\n  \"worktree\" bigint,\n  PRIMARY KEY (\"name\")\n);\n\nCREATE TABLE \"session_state_events\" (\n  \"sequence\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"dedupe_key\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\",\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"actor_type\" text COLLATE \"C\" NOT NULL,\n  \"actor_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"occurred_at\" bigint NOT NULL,\n  \"summary\" text COLLATE \"C\" NOT NULL,\n  \"payload_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"sequence\"),\n  UNIQUE (\"dedupe_key\")\n);\n\nCREATE TABLE \"session_state_heads\" (\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"last_sequence\" bigint NOT NULL,\n  \"pruned_max_sequence\" bigint NOT NULL DEFAULT 0,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"session_key\", \"agent_id\")\n);\n\nCREATE TABLE \"session_upstream_links\" (\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"catalog_id\" text COLLATE \"C\" NOT NULL,\n  \"host_id\" text COLLATE \"C\" NOT NULL,\n  \"thread_id\" text COLLATE \"C\" NOT NULL,\n  \"upstream_kind\" text COLLATE \"C\" NOT NULL,\n  \"upstream_ref_json\" text COLLATE \"C\",\n  \"last_marker_json\" text COLLATE \"C\",\n  \"last_scanned_at\" bigint,\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"session_key\", \"agent_id\")\n);\n\nCREATE TABLE \"session_watch_cursors\" (\n  \"watcher_session_key\" text COLLATE \"C\" NOT NULL,\n  \"watcher_store_path\" text COLLATE \"C\",\n  \"target_session_key\" text COLLATE \"C\" NOT NULL,\n  \"last_seen_sequence\" bigint NOT NULL DEFAULT 0,\n  \"notified_sequence\" bigint NOT NULL DEFAULT 0,\n  \"material_sequence\" bigint NOT NULL DEFAULT 0,\n  \"provenance\" text COLLATE \"C\" NOT NULL DEFAULT 'explicit',\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"watcher_session_key\", \"target_session_key\"),\n  CHECK ((\"provenance\" IN ('explicit', 'ambient-group')))\n);\n\nCREATE TABLE \"skill_upload_chunks\" (\n  \"upload_id\" text COLLATE \"C\" NOT NULL,\n  \"byte_offset\" bigint NOT NULL,\n  \"size_bytes\" bigint NOT NULL,\n  \"chunk_blob\" bytea NOT NULL,\n  PRIMARY KEY (\"upload_id\", \"byte_offset\"),\n  CHECK ((\"byte_offset\" >= 0)),\n  CHECK ((\"size_bytes\" > 0)),\n  CHECK ((octet_length(\"chunk_blob\") = \"size_bytes\"))\n);\n\nCREATE TABLE \"skill_uploads\" (\n  \"upload_id\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"slug\" text COLLATE \"C\" NOT NULL,\n  \"force\" bigint NOT NULL,\n  \"size_bytes\" bigint NOT NULL,\n  \"sha256\" text COLLATE \"C\",\n  \"actual_sha256\" text COLLATE \"C\",\n  \"received_bytes\" bigint NOT NULL,\n  \"archive_blob\" bytea NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"expires_at\" bigint NOT NULL,\n  \"committed\" bigint NOT NULL,\n  \"committed_at\" bigint,\n  \"idempotency_key_hash\" text COLLATE \"C\",\n  PRIMARY KEY (\"upload_id\"),\n  UNIQUE (\"idempotency_key_hash\")\n);\n\nCREATE TABLE \"skill_usage\" (\n  \"skill_file\" text COLLATE \"C\" NOT NULL,\n  \"skill_key\" text COLLATE \"C\" NOT NULL,\n  \"skill_name\" text COLLATE \"C\" NOT NULL,\n  \"skill_source\" text COLLATE \"C\" NOT NULL,\n  \"first_used_at_ms\" bigint NOT NULL,\n  \"last_used_at_ms\" bigint NOT NULL,\n  \"use_count\" bigint NOT NULL,\n  \"last_agent_id\" text COLLATE \"C\",\n  PRIMARY KEY (\"skill_file\")\n);\n\nCREATE TABLE \"state_leases\" (\n  \"scope\" text COLLATE \"C\" NOT NULL,\n  \"lease_key\" text COLLATE \"C\" NOT NULL,\n  \"owner\" text COLLATE \"C\" NOT NULL,\n  \"expires_at\" bigint,\n  \"heartbeat_at\" bigint,\n  \"payload_json\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"scope\", \"lease_key\")\n);\n\nCREATE TABLE \"subagent_runs\" (\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"child_session_key\" text COLLATE \"C\" NOT NULL,\n  \"controller_session_key\" text COLLATE \"C\",\n  \"controller_store_path\" text COLLATE \"C\",\n  \"requester_session_key\" text COLLATE \"C\" NOT NULL,\n  \"requester_store_path\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"payload_json\" text COLLATE \"C\" NOT NULL DEFAULT '{}',\n  PRIMARY KEY (\"run_id\")\n);\n\nCREATE TABLE \"task_delivery_state\" (\n  \"task_id\" text COLLATE \"C\" NOT NULL,\n  \"requester_origin_json\" text COLLATE \"C\",\n  \"last_notified_event_at\" bigint,\n  PRIMARY KEY (\"task_id\")\n);\n\nCREATE TABLE \"task_runs\" (\n  \"task_id\" text COLLATE \"C\" NOT NULL,\n  \"runtime\" text COLLATE \"C\" NOT NULL,\n  \"task_kind\" text COLLATE \"C\",\n  \"source_id\" text COLLATE \"C\",\n  \"requester_session_key\" text COLLATE \"C\",\n  \"owner_key\" text COLLATE \"C\" NOT NULL,\n  \"scope_kind\" text COLLATE \"C\" NOT NULL,\n  \"child_session_key\" text COLLATE \"C\",\n  \"parent_flow_id\" text COLLATE \"C\",\n  \"parent_task_id\" text COLLATE \"C\",\n  \"agent_id\" text COLLATE \"C\",\n  \"requester_agent_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"execution_owner_host\" text COLLATE \"C\",\n  \"execution_owner_pid\" bigint,\n  \"execution_owner_start_identity\" bigint,\n  \"label\" text COLLATE \"C\",\n  \"task\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"delivery_status\" text COLLATE \"C\" NOT NULL,\n  \"notify_policy\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"started_at\" bigint,\n  \"ended_at\" bigint,\n  \"last_event_at\" bigint,\n  \"cleanup_after\" bigint,\n  \"tool_use_count\" bigint,\n  \"last_tool_name\" text COLLATE \"C\",\n  \"error\" text COLLATE \"C\",\n  \"progress_summary\" text COLLATE \"C\",\n  \"terminal_summary\" text COLLATE \"C\",\n  \"terminal_outcome\" text COLLATE \"C\",\n  \"detail_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"task_id\")\n);\n\nCREATE TABLE \"template_cron_refs\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"manifest_id\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" text COLLATE \"C\" NOT NULL,\n  \"declaration_key\" text COLLATE \"C\" NOT NULL,\n  \"scheduler_job_id\" text COLLATE \"C\",\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"job_json\" text COLLATE \"C\" NOT NULL,\n  \"error\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\", \"manifest_id\"),\n  UNIQUE (\"declaration_key\"),\n  UNIQUE (\"scheduler_job_id\")\n);\n\nCREATE TABLE \"template_installs\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" text COLLATE \"C\" NOT NULL,\n  \"source_kind\" text COLLATE \"C\" NOT NULL,\n  \"template_name\" text COLLATE \"C\" NOT NULL,\n  \"template_version\" text COLLATE \"C\" NOT NULL,\n  \"package_root\" text COLLATE \"C\" NOT NULL,\n  \"manifest_path\" text COLLATE \"C\" NOT NULL,\n  \"integrity_kind\" text COLLATE \"C\" NOT NULL,\n  \"integrity\" text COLLATE \"C\" NOT NULL,\n  \"source_byte_length\" bigint NOT NULL,\n  \"manifest_schema_version\" bigint NOT NULL,\n  \"plan_integrity\" text COLLATE \"C\" NOT NULL,\n  \"workspace\" text COLLATE \"C\" NOT NULL,\n  \"agent_config_digest\" text COLLATE \"C\" NOT NULL,\n  \"agent_owned_paths_json\" text COLLATE \"C\" NOT NULL,\n  \"bootstrap_source_path\" text COLLATE \"C\",\n  \"bootstrap_content_digest\" text COLLATE \"C\",\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"added_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\"),\n  CHECK ((\"status\" IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial'))),\n  UNIQUE (\"workspace\")\n);\n\nCREATE TABLE \"template_mcp_server_refs\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"name\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" text COLLATE \"C\" NOT NULL,\n  \"config_digest\" text COLLATE \"C\" NOT NULL,\n  \"relationship\" text COLLATE \"C\" NOT NULL,\n  \"origin\" text COLLATE \"C\" NOT NULL,\n  \"independent_owner\" bigint NOT NULL DEFAULT 0,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"error\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\", \"name\"),\n  CHECK ((\"relationship\" IN ('managed', 'referenced'))),\n  CHECK ((\"origin\" IN ('template-introduced', 'pre-existing'))),\n  CHECK ((\"independent_owner\" IN (0, 1)))\n);\n\nCREATE TABLE \"template_package_refs\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"package_kind\" text COLLATE \"C\" NOT NULL,\n  \"package_source\" text COLLATE \"C\" NOT NULL,\n  \"package_ref\" text COLLATE \"C\" NOT NULL,\n  \"package_version\" text COLLATE \"C\" NOT NULL,\n  \"package_integrity\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" text COLLATE \"C\" NOT NULL,\n  \"template_name\" text COLLATE \"C\" NOT NULL,\n  \"package_status\" text COLLATE \"C\" NOT NULL,\n  \"relationship\" text COLLATE \"C\" NOT NULL,\n  \"origin\" text COLLATE \"C\" NOT NULL,\n  \"independent_owner\" bigint NOT NULL,\n  \"extension_id\" text COLLATE \"C\",\n  \"extension_format\" text COLLATE \"C\",\n  \"extension_detected_format\" text COLLATE \"C\",\n  \"extension_mapped_json\" text COLLATE \"C\",\n  \"extension_unavailable_json\" text COLLATE \"C\",\n  \"extension_adapter_identity\" text COLLATE \"C\",\n  \"installed_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\", \"package_kind\", \"package_source\", \"package_ref\", \"package_version\"),\n  CHECK ((\"relationship\" IN ('managed', 'referenced'))),\n  CHECK ((\"origin\" IN ('template-introduced', 'pre-existing'))),\n  CHECK ((\"independent_owner\" IN (0, 1)))\n);\n\nCREATE TABLE \"template_workspace_files\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"target_path\" text COLLATE \"C\" NOT NULL,\n  \"schema_version\" text COLLATE \"C\" NOT NULL,\n  \"workspace\" text COLLATE \"C\" NOT NULL,\n  \"source_path\" text COLLATE \"C\" NOT NULL,\n  \"content_digest\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\", \"target_path\")\n);\n\nCREATE TABLE \"web_push_subscriptions\" (\n  \"endpoint_hash\" text COLLATE \"C\" NOT NULL,\n  \"subscription_id\" text COLLATE \"C\" NOT NULL,\n  \"endpoint\" text COLLATE \"C\" NOT NULL,\n  \"p256dh\" text COLLATE \"C\" NOT NULL,\n  \"auth\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\",\n  \"user_profile_id\" text COLLATE \"C\",\n  \"preferences_json\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"endpoint_hash\"),\n  UNIQUE (\"subscription_id\")\n);\n\nCREATE TABLE \"worker_environment_credentials\" (\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"credential_hash\" text COLLATE \"C\" NOT NULL,\n  \"bundle_hash\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\",\n  \"rpc_set_version\" bigint NOT NULL,\n  \"owner_epoch\" bigint NOT NULL,\n  \"expires_at_ms\" bigint NOT NULL,\n  \"delivered_at_ms\" bigint,\n  PRIMARY KEY (\"environment_id\"),\n  CHECK ((\"rpc_set_version\" >= 1)),\n  CHECK ((\"owner_epoch\" >= 0)),\n  CHECK ((\"expires_at_ms\" >= 0)),\n  CHECK ((\"delivered_at_ms\" >= 0)),\n  UNIQUE (\"credential_hash\")\n);\n\nCREATE TABLE \"worker_environments\" (\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"provider_id\" text COLLATE \"C\" NOT NULL,\n  \"profile_id\" text COLLATE \"C\" NOT NULL,\n  \"profile_snapshot_json\" text COLLATE \"C\" NOT NULL,\n  \"last_activated_at_ms\" bigint,\n  \"preparation_key\" text COLLATE \"C\",\n  \"preparation_purpose\" text COLLATE \"C\",\n  \"preparation_demand_at_ms\" bigint,\n  \"preparation_expires_at_ms\" bigint,\n  \"preparation_consumed_at_ms\" bigint,\n  \"provision_operation_id\" text COLLATE \"C\" NOT NULL,\n  \"lease_id\" text COLLATE \"C\",\n  \"node_setup_id\" text COLLATE \"C\",\n  \"node_device_id\" text COLLATE \"C\",\n  \"ssh_host\" text COLLATE \"C\",\n  \"ssh_port\" bigint,\n  \"ssh_user\" text COLLATE \"C\",\n  \"ssh_host_key\" text COLLATE \"C\",\n  \"ssh_key_ref_json\" text COLLATE \"C\",\n  \"desktop_json\" text COLLATE \"C\",\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"bootstrap_bundle_hash\" text COLLATE \"C\",\n  \"bootstrap_openclaw_version\" text COLLATE \"C\",\n  \"bootstrap_protocol_features_json\" text COLLATE \"C\",\n  \"bootstrap_install_kind\" text COLLATE \"C\",\n  \"owner_epoch\" bigint NOT NULL DEFAULT 0,\n  \"teardown_terminal_state\" text COLLATE \"C\",\n  \"attached_session_ids_json\" text COLLATE \"C\" NOT NULL DEFAULT '[]',\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"state_changed_at_ms\" bigint NOT NULL,\n  \"idle_since_at_ms\" bigint,\n  \"destroy_requested_at_ms\" bigint,\n  \"last_error\" text COLLATE \"C\",\n  \"shared_host\" bigint,\n  PRIMARY KEY (\"environment_id\"),\n  CHECK ((\"preparation_key\" IS NULL AND \"preparation_demand_at_ms\" IS NULL AND \"preparation_expires_at_ms\" IS NULL AND \"preparation_consumed_at_ms\" IS NULL) OR (\"preparation_key\" IS NOT NULL AND (char_length(\"preparation_key\") = 64) AND (\"preparation_key\" COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z') AND \"preparation_demand_at_ms\" IS NOT NULL AND (\"preparation_demand_at_ms\" BETWEEN 0 AND 9007199254740991) AND \"preparation_expires_at_ms\" IS NOT NULL AND (\"preparation_expires_at_ms\" > \"preparation_demand_at_ms\") AND (\"preparation_expires_at_ms\" <= 9007199254740991) AND (\"preparation_consumed_at_ms\" IS NULL OR ((\"preparation_consumed_at_ms\" >= \"preparation_demand_at_ms\") AND (\"preparation_consumed_at_ms\" < \"preparation_expires_at_ms\"))))),\n  CHECK (\"ssh_port\" IS NULL OR ((\"ssh_port\" >= 1) AND (\"ssh_port\" <= 65535))),\n  CHECK ((\"state\" IN ('requested', 'provisioning', 'bootstrapping', 'ready', 'attached', 'idle', 'draining', 'destroying', 'destroyed', 'failed', 'orphaned'))),\n  CHECK ((\"owner_epoch\" >= 0)),\n  CHECK ((\"teardown_terminal_state\" IN ('destroyed', 'failed'))),\n  UNIQUE (\"provision_operation_id\")\n);\n\nCREATE TABLE \"worker_inference_turns\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"run_epoch\" bigint NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"turn_id\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"request_hash\" text COLLATE \"C\" NOT NULL,\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"terminal_json\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\", \"run_epoch\", \"run_id\", \"turn_id\"),\n  CHECK ((\"run_epoch\" >= 0)),\n  CHECK ((\"state\" IN ('pending', 'terminal'))),\n  CHECK ((\"created_at_ms\" >= 0)),\n  CHECK ((\"updated_at_ms\" >= 0)),\n  CHECK (((\"state\" = 'pending') AND \"terminal_json\" IS NULL) OR ((\"state\" = 'terminal') AND \"terminal_json\" IS NOT NULL))\n);\n\nCREATE TABLE \"worker_session_placements\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"execution_mode\" text COLLATE \"C\",\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\",\n  \"transition_generation\" bigint NOT NULL DEFAULT 0,\n  \"active_owner_epoch\" bigint,\n  \"workspace_base_manifest_ref\" text COLLATE \"C\",\n  \"remote_workspace_dir\" text COLLATE \"C\",\n  \"worker_bundle_hash\" text COLLATE \"C\",\n  \"last_transcript_ack_cursor\" bigint,\n  \"last_live_event_ack_cursor\" bigint,\n  \"recovery_error\" text COLLATE \"C\",\n  \"turn_claim_owner\" text COLLATE \"C\",\n  \"turn_claim_id\" text COLLATE \"C\",\n  \"turn_claim_run_id\" text COLLATE \"C\",\n  \"turn_claim_generation\" bigint,\n  \"turn_claim_owner_epoch\" bigint,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"state_changed_at_ms\" bigint NOT NULL,\n  \"terminal_reason\" text COLLATE \"C\",\n  \"terminal_at_ms\" bigint,\n  PRIMARY KEY (\"session_id\"),\n  CHECK ((\"execution_mode\" IN ('worker-turn', 'remote-exec'))),\n  CHECK ((\"state\" IN ('local', 'requested', 'provisioning', 'syncing', 'starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),\n  CHECK ((\"transition_generation\" >= 0)),\n  CHECK (\"active_owner_epoch\" IS NULL OR (\"active_owner_epoch\" >= 1)),\n  CHECK (\"last_transcript_ack_cursor\" IS NULL OR (\"last_transcript_ack_cursor\" >= 0)),\n  CHECK (\"last_live_event_ack_cursor\" IS NULL OR (\"last_live_event_ack_cursor\" >= 0)),\n  CHECK ((\"turn_claim_owner\" IN ('local', 'worker'))),\n  CHECK (\"turn_claim_generation\" IS NULL OR (\"turn_claim_generation\" >= 0)),\n  CHECK (\"turn_claim_owner_epoch\" IS NULL OR (\"turn_claim_owner_epoch\" >= 1)),\n  CHECK (((\"state\" IN ('local', 'requested')) AND \"environment_id\" IS NULL AND \"active_owner_epoch\" IS NULL AND \"workspace_base_manifest_ref\" IS NULL AND \"remote_workspace_dir\" IS NULL AND \"worker_bundle_hash\" IS NULL AND \"last_transcript_ack_cursor\" IS NULL AND \"last_live_event_ack_cursor\" IS NULL AND \"recovery_error\" IS NULL) OR (\"state\" IS NOT DISTINCT FROM 'provisioning' AND \"active_owner_epoch\" IS NULL AND \"workspace_base_manifest_ref\" IS NULL AND \"remote_workspace_dir\" IS NULL AND \"worker_bundle_hash\" IS NULL AND \"last_transcript_ack_cursor\" IS NULL AND \"last_live_event_ack_cursor\" IS NULL AND \"recovery_error\" IS NULL) OR (\"state\" IS NOT DISTINCT FROM 'syncing' AND \"environment_id\" IS NOT NULL AND \"active_owner_epoch\" IS NULL AND \"workspace_base_manifest_ref\" IS NULL AND \"remote_workspace_dir\" IS NULL AND \"worker_bundle_hash\" IS NOT NULL AND \"last_transcript_ack_cursor\" IS NULL AND \"last_live_event_ack_cursor\" IS NULL AND \"recovery_error\" IS NULL) OR (\"state\" IS NOT DISTINCT FROM 'starting' AND \"environment_id\" IS NOT NULL AND \"active_owner_epoch\" IS NULL AND \"workspace_base_manifest_ref\" IS NOT NULL AND \"remote_workspace_dir\" IS NOT NULL AND \"worker_bundle_hash\" IS NOT NULL AND \"last_transcript_ack_cursor\" IS NULL AND \"last_live_event_ack_cursor\" IS NULL AND \"recovery_error\" IS NULL) OR ((\"state\" IN ('active', 'draining', 'reconciling')) AND \"environment_id\" IS NOT NULL AND \"active_owner_epoch\" IS NOT NULL AND \"workspace_base_manifest_ref\" IS NOT NULL AND \"remote_workspace_dir\" IS NOT NULL AND \"worker_bundle_hash\" IS NOT NULL AND \"recovery_error\" IS NULL) OR (\"state\" IS NOT DISTINCT FROM 'reclaimed' AND \"environment_id\" IS NOT NULL AND \"active_owner_epoch\" IS NOT NULL AND \"workspace_base_manifest_ref\" IS NOT NULL AND \"remote_workspace_dir\" IS NOT NULL AND \"worker_bundle_hash\" IS NOT NULL AND \"recovery_error\" IS NULL AND \"turn_claim_owner\" IS NULL AND \"turn_claim_id\" IS NULL AND \"turn_claim_run_id\" IS NULL AND \"turn_claim_generation\" IS NULL AND \"turn_claim_owner_epoch\" IS NULL) OR (\"state\" IS NOT DISTINCT FROM 'failed' AND \"recovery_error\" IS NOT NULL)),\n  CHECK ((\"turn_claim_owner\" IS NULL AND \"turn_claim_id\" IS NULL AND \"turn_claim_run_id\" IS NULL AND \"turn_claim_generation\" IS NULL AND \"turn_claim_owner_epoch\" IS NULL) OR (\"turn_claim_owner\" IS NOT DISTINCT FROM 'local' AND \"turn_claim_id\" IS NOT NULL AND \"turn_claim_run_id\" IS NOT NULL AND \"turn_claim_generation\" IS NOT NULL AND \"turn_claim_owner_epoch\" IS NULL) OR (\"turn_claim_owner\" IS NOT DISTINCT FROM 'worker' AND \"turn_claim_id\" IS NOT NULL AND \"turn_claim_run_id\" IS NOT NULL AND \"turn_claim_generation\" IS NOT NULL AND \"turn_claim_owner_epoch\" IS NOT NULL)),\n  CHECK (\"turn_claim_owner\" IS NULL OR (\"turn_claim_owner\" IS NOT DISTINCT FROM 'local' AND ((\"state\" IN ('local', 'requested', 'failed')) OR ((\"state\" IN ('active', 'draining')) AND \"execution_mode\" IS NOT DISTINCT FROM 'remote-exec'))) OR (\"turn_claim_owner\" IS NOT DISTINCT FROM 'worker' AND (\"state\" IN ('active', 'draining')) AND (\"execution_mode\" IS NULL OR \"execution_mode\" IS NOT DISTINCT FROM 'worker-turn') AND \"turn_claim_owner_epoch\" IS NOT DISTINCT FROM \"active_owner_epoch\"))\n);\n\nCREATE TABLE \"worker_session_tool_operations\" (\n  \"source_session_id\" text COLLATE \"C\" NOT NULL,\n  \"source_claim_id\" text COLLATE \"C\" NOT NULL,\n  \"tool_call_id\" text COLLATE \"C\" NOT NULL,\n  \"tool_name\" text COLLATE \"C\" NOT NULL,\n  \"request_digest\" text COLLATE \"C\" NOT NULL,\n  \"operation_seed\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"child_session_key\" text COLLATE \"C\",\n  \"result_json\" text COLLATE \"C\",\n  \"gateway_instance_id\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"source_session_id\", \"source_claim_id\", \"tool_call_id\"),\n  CHECK ((\"tool_name\" IN ('sessions_spawn', 'sessions_send'))),\n  CHECK ((\"status\" IN ('running', 'succeeded', 'failed', 'unknown')))\n);\n\nCREATE TABLE \"worker_transcript_commit_heads\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"run_epoch\" bigint NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"next_seq\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\", \"run_epoch\"),\n  CHECK ((\"run_epoch\" >= 0)),\n  CHECK ((\"next_seq\" >= 1)),\n  CHECK ((\"updated_at_ms\" >= 0))\n);\n\nCREATE TABLE \"worker_transcript_commits\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"run_epoch\" bigint NOT NULL,\n  \"seq\" bigint NOT NULL,\n  \"request_hash\" text COLLATE \"C\" NOT NULL,\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"result_json\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\", \"run_epoch\", \"seq\"),\n  CHECK ((\"run_epoch\" >= 0)),\n  CHECK ((\"seq\" >= 1)),\n  CHECK ((\"state\" IN ('pending', 'terminal'))),\n  CHECK ((\"created_at_ms\" >= 0)),\n  CHECK ((\"updated_at_ms\" >= 0)),\n  CHECK (((\"state\" = 'pending') AND \"result_json\" IS NULL) OR ((\"state\" = 'terminal') AND \"result_json\" IS NOT NULL))\n);\n\nCREATE TABLE \"worker_turn_tool_authorities\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_epoch\" bigint NOT NULL,\n  \"placement_generation\" bigint NOT NULL,\n  \"claim_id\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"tool_names_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\"),\n  CHECK ((\"owner_epoch\" >= 1)),\n  CHECK ((\"placement_generation\" >= 0))\n);\n\nCREATE TABLE \"worker_workspace_pending_results\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_epoch\" bigint NOT NULL,\n  \"placement_generation\" bigint NOT NULL,\n  \"claim_id\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"gateway_instance_id\" text COLLATE \"C\" NOT NULL,\n  \"recovery_requested_at_ms\" bigint,\n  \"workspace_accepted_at_ms\" bigint,\n  \"staged_result_ref\" text COLLATE \"C\",\n  \"repository_workspace_id\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\"),\n  CHECK ((\"owner_epoch\" >= 1)),\n  CHECK ((\"placement_generation\" >= 0))\n);\n\nCREATE TABLE \"worker_workspace_reconciliations\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_epoch\" bigint NOT NULL,\n  \"placement_generation\" bigint NOT NULL,\n  \"base_manifest_ref\" text COLLATE \"C\" NOT NULL,\n  \"current_manifest_ref\" text COLLATE \"C\" NOT NULL,\n  \"plan_json\" text COLLATE \"C\" NOT NULL,\n  \"base_pack\" bytea NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"session_id\"),\n  CHECK ((\"owner_epoch\" >= 1)),\n  CHECK ((\"placement_generation\" >= 0)),\n  CHECK ((octet_length(\"base_pack\") <= 268435456))\n);\n\nCREATE TABLE \"workspace_generated_bootstrap_hashes\" (\n  \"workspace_key\" text COLLATE \"C\" NOT NULL,\n  \"filename\" text COLLATE \"C\" NOT NULL,\n  \"sha256\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"workspace_key\", \"filename\")\n);\n\nCREATE TABLE \"workspace_path_aliases\" (\n  \"alias_key\" text COLLATE \"C\" NOT NULL,\n  \"alias_path\" text COLLATE \"C\" NOT NULL,\n  \"workspace_key\" text COLLATE \"C\" NOT NULL,\n  \"workspace_path\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"alias_key\")\n);\n\nCREATE TABLE \"workspace_setup_state\" (\n  \"workspace_key\" text COLLATE \"C\" NOT NULL,\n  \"workspace_path\" text COLLATE \"C\",\n  \"version\" bigint,\n  \"bootstrap_seeded_at\" text COLLATE \"C\",\n  \"setup_completed_at\" text COLLATE \"C\",\n  \"updated_at\" bigint,\n  \"attested_at_ms\" bigint,\n  \"attestation_updated_at_ms\" bigint,\n  PRIMARY KEY (\"workspace_key\"),\n  CHECK (\"version\" IS NULL OR \"workspace_path\" IS NOT NULL)\n);\n\nCREATE TABLE \"worktree_provisioned_file_chunks\" (\n  \"worktree_id\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"chunk_index\" bigint NOT NULL,\n  \"data\" bytea NOT NULL,\n  PRIMARY KEY (\"worktree_id\", \"path\", \"chunk_index\"),\n  CHECK ((\"chunk_index\" >= 0))\n);\n\nCREATE TABLE \"worktrees\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"repo_fingerprint\" text COLLATE \"C\" NOT NULL,\n  \"repo_root\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"branch\" text COLLATE \"C\" NOT NULL,\n  \"base_ref\" text COLLATE \"C\" NOT NULL,\n  \"owner_kind\" text COLLATE \"C\" NOT NULL,\n  \"owner_id\" text COLLATE \"C\",\n  \"snapshot_ref\" text COLLATE \"C\",\n  \"provisioned_paths_json\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"last_active_at\" bigint NOT NULL,\n  \"removed_at\" bigint,\n  \"run_end_cleanup_json\" text COLLATE \"C\",\n  \"gc_protection_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"id\"),\n  CHECK ((\"owner_kind\" IN ('manual', 'workboard', 'session')))\n);\n\nCREATE INDEX \"idx_acp_replay_sessions_key_updated\" ON \"acp_replay_sessions\" ((\"session_key\") ASC, (\"complete\") ASC, (\"updated_at\") DESC, (\"session_id\") ASC);\n\nCREATE INDEX \"idx_acp_replay_sessions_updated\" ON \"acp_replay_sessions\" ((\"updated_at\") DESC, (\"session_id\") ASC);\n\nCREATE INDEX \"idx_acp_sessions_agent_activity\" ON \"acp_sessions\" ((\"agent\") ASC, (\"last_activity_at\") DESC, (\"session_key\") ASC);\n\nCREATE INDEX \"idx_acp_sessions_resume_acpx\" ON \"acp_sessions\" ((\"resume_acpx_session_id\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_acp_sessions_resume_agent\" ON \"acp_sessions\" ((\"resume_agent_session_id\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_acp_sessions_state_activity\" ON \"acp_sessions\" ((\"state\") ASC, (\"last_activity_at\") DESC, (\"session_key\") ASC);\n\nCREATE INDEX \"idx_apns_registrations_updated\" ON \"apns_registrations\" ((\"updated_at_ms\") DESC, (\"node_id\") ASC);\n\nCREATE INDEX \"idx_audit_events_agent_sequence\" ON \"audit_events\" ((\"agent_id\") ASC NULLS FIRST, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_channel_sequence\" ON \"audit_events\" ((\"channel\") ASC NULLS FIRST, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_direction_sequence\" ON \"audit_events\" ((\"direction\") ASC NULLS FIRST, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_kind_sequence\" ON \"audit_events\" ((\"kind\") ASC, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_run_sequence\" ON \"audit_events\" ((\"run_id\") ASC NULLS FIRST, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_session_sequence\" ON \"audit_events\" ((\"session_key\") ASC NULLS FIRST, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_status_sequence\" ON \"audit_events\" ((\"status\") ASC, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_audit_events_time\" ON \"audit_events\" ((\"occurred_at\") DESC, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_backup_runs_created\" ON \"backup_runs\" ((\"created_at\") DESC, (\"id\") ASC);\n\nCREATE INDEX \"capture_events_flow_idx\" ON \"capture_events\" ((\"flow_id\") ASC, (\"ts\") ASC);\n\nCREATE INDEX \"capture_events_session_ts_idx\" ON \"capture_events\" ((\"session_id\") ASC, (\"ts\") ASC);\n\nCREATE INDEX \"idx_channel_ingress_claims\" ON \"channel_ingress_events\" ((\"queue_name\") ASC, (\"status\") ASC, (\"claimed_at\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_channel_ingress_lane\" ON \"channel_ingress_events\" ((\"queue_name\") ASC, (\"status\") ASC, (\"lane_key\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_channel_ingress_pending\" ON \"channel_ingress_events\" ((\"queue_name\") ASC, (\"status\") ASC, (\"received_at\") ASC, (\"event_id\") ASC);\n\nCREATE INDEX \"idx_channel_pairing_allow_account\" ON \"channel_pairing_allow_entries\" ((\"channel_key\") ASC, (\"account_id\") ASC, (\"sort_order\") ASC, (\"entry\") ASC);\n\nCREATE INDEX \"idx_channel_pairing_requests_code\" ON \"channel_pairing_requests\" ((\"channel_key\") ASC, (\"code\") ASC);\n\nCREATE INDEX \"idx_channel_pairing_requests_created\" ON \"channel_pairing_requests\" ((\"channel_key\") ASC, (\"created_at\") ASC, (\"request_id\") ASC);\n\nCREATE INDEX \"idx_cron_job_scratch_store_updated\" ON \"cron_job_scratch\" ((\"store_key\") ASC, (\"updated_at_ms\") DESC, (\"job_id\") ASC);\n\nCREATE INDEX \"idx_cron_jobs_store_order\" ON \"cron_jobs\" ((\"store_key\") ASC, (\"sort_order\") ASC, (\"updated_at\") ASC, (\"job_id\") ASC);\n\nCREATE INDEX \"idx_current_conversation_bindings_conversation\" ON \"current_conversation_bindings\" ((\"channel\") ASC, (\"account_id\") ASC, (\"conversation_kind\") ASC, (\"conversation_id\") ASC);\n\nCREATE INDEX \"idx_current_conversation_bindings_expires\" ON \"current_conversation_bindings\" ((\"expires_at\") ASC NULLS FIRST, (\"binding_key\") ASC);\n\nCREATE INDEX \"idx_current_conversation_bindings_target\" ON \"current_conversation_bindings\" ((\"target_session_key\") ASC, (\"updated_at\") DESC, (\"binding_key\") ASC);\n\nCREATE INDEX \"idx_delivery_queue_bounded_retention\" ON \"delivery_queue_entries\" ((\"queue_name\") ASC, (\"retention_id_prefix\") ASC, (\"enqueued_at\") DESC, (\"id\") DESC) WHERE (\"status\" IN ('completed', 'failed')) AND (\"recovery_state\" = 'completed_bounded') AND \"retention_id_prefix\" IS NOT NULL;\n\nCREATE INDEX \"idx_delivery_queue_failed\" ON \"delivery_queue_entries\" ((\"status\") ASC, (\"queue_name\") ASC, (\"failed_at\") ASC NULLS FIRST, (\"id\") ASC);\n\nCREATE INDEX \"idx_delivery_queue_pending\" ON \"delivery_queue_entries\" ((\"queue_name\") ASC, (\"status\") ASC, (\"enqueued_at\") ASC, (\"id\") ASC);\n\nCREATE INDEX \"idx_delivery_queue_session\" ON \"delivery_queue_entries\" ((\"queue_name\") ASC, (\"status\") ASC, (\"session_key\") ASC, (\"enqueued_at\") ASC, (\"id\") ASC) WHERE \"session_key\" IS NOT NULL;\n\nCREATE INDEX \"idx_delivery_queue_target\" ON \"delivery_queue_entries\" ((\"queue_name\") ASC, (\"status\") ASC, (\"channel\") ASC, (\"target\") ASC, (\"enqueued_at\") ASC, (\"id\") ASC) WHERE \"channel\" IS NOT NULL AND \"target\" IS NOT NULL;\n\nCREATE INDEX \"idx_device_bootstrap_tokens_ts\" ON \"device_bootstrap_tokens\" ((\"ts\") ASC);\n\nCREATE INDEX \"idx_device_pairing_paired_approved\" ON \"device_pairing_paired\" ((\"approved_at_ms\") DESC, (\"device_id\") ASC);\n\nCREATE INDEX \"idx_device_pairing_pending_device\" ON \"device_pairing_pending\" ((\"device_id\") ASC, (\"ts\") DESC);\n\nCREATE INDEX \"idx_diagnostic_events_scope_sequence\" ON \"diagnostic_events\" ((\"scope\") ASC, (\"sequence\") ASC, (\"event_key\") ASC);\n\nCREATE INDEX \"idx_flow_runs_owner_key\" ON \"flow_runs\" ((\"owner_key\") ASC);\n\nCREATE INDEX \"idx_flow_runs_status\" ON \"flow_runs\" ((\"status\") ASC);\n\nCREATE INDEX \"idx_flow_runs_updated_at\" ON \"flow_runs\" ((\"updated_at\") ASC);\n\nCREATE INDEX \"idx_gateway_boot_lifecycle_started\" ON \"gateway_boot_lifecycle\" ((\"started_at_ms\") ASC);\n\nCREATE INDEX \"idx_gateway_restart_handoff_expiry\" ON \"gateway_restart_handoff\" ((\"expires_at\") ASC, (\"pid\") ASC);\n\nCREATE INDEX \"idx_gateway_restart_sentinel_ts\" ON \"gateway_restart_sentinel\" ((\"ts\") DESC, (\"sentinel_key\") ASC);\n\nCREATE INDEX \"idx_macos_port_guardian_records_port\" ON \"macos_port_guardian_records\" ((\"port\") ASC, (\"timestamp\") DESC);\n\nCREATE INDEX \"idx_managed_outgoing_images_agent_message\" ON \"managed_outgoing_image_records\" ((\"session_key\") ASC, (\"agent_id\") ASC NULLS FIRST, (\"message_id\") ASC, (\"attachment_id\") ASC) WHERE \"message_id\" IS NOT NULL;\n\nCREATE INDEX \"idx_managed_outgoing_images_agent_session\" ON \"managed_outgoing_image_records\" ((\"session_key\") ASC, (\"agent_id\") ASC NULLS FIRST, (\"created_at\") DESC, (\"attachment_id\") ASC);\n\nCREATE INDEX \"idx_managed_outgoing_images_message\" ON \"managed_outgoing_image_records\" ((\"session_key\") ASC, (\"message_id\") ASC, (\"attachment_id\") ASC) WHERE \"message_id\" IS NOT NULL;\n\nCREATE INDEX \"idx_managed_outgoing_images_session\" ON \"managed_outgoing_image_records\" ((\"session_key\") ASC, (\"created_at\") DESC, (\"attachment_id\") ASC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_account\" ON \"meeting_transcript_sessions\" ((\"source_account_id\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_agent\" ON \"meeting_transcript_sessions\" ((\"metadata_agent_id\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_chronology\" ON \"meeting_transcript_sessions\" ((\"started_at_ms\") DESC NULLS LAST, (\"session_id\") ASC, (\"started_at\") ASC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_export_key\" ON \"meeting_transcript_sessions\" ((\"export_key\") ASC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_id\" ON \"meeting_transcript_sessions\" ((\"session_id\") ASC, (\"started_at\") DESC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_slug\" ON \"meeting_transcript_sessions\" ((\"session_slug\") ASC, (\"started_at\") DESC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_source\" ON \"meeting_transcript_sessions\" ((\"provider_id\") ASC, (\"source_account_id\") ASC NULLS FIRST, (\"source_guild_id\") ASC NULLS FIRST, (\"source_channel_id\") ASC NULLS FIRST, (\"source_meeting_url\") ASC NULLS FIRST, (\"source_thread_ts\") ASC NULLS FIRST, (\"source_file_id\") ASC NULLS FIRST, (\"stopped_at\") DESC NULLS LAST, (\"started_at\") DESC, (\"session_id\") ASC);\n\nCREATE INDEX \"idx_meeting_transcript_sessions_started\" ON \"meeting_transcript_sessions\" ((\"started_at\") DESC, (\"session_id\") ASC);\n\nCREATE INDEX \"idx_meeting_transcript_utterances_id\" ON \"meeting_transcript_utterances\" ((\"session_id\") ASC, (\"session_started_at\") ASC, (\"utterance_id\") ASC) WHERE \"utterance_id\" IS NOT NULL;\n\nCREATE INDEX \"idx_migration_runs_started\" ON \"migration_runs\" ((\"started_at\") DESC, (\"id\") ASC);\n\nCREATE INDEX \"idx_migration_sources_path\" ON \"migration_sources\" ((\"source_path\") ASC, (\"migration_kind\") ASC, (\"target_table\") ASC);\n\nCREATE INDEX \"idx_migration_sources_run\" ON \"migration_sources\" ((\"last_run_id\") ASC, (\"source_path\") ASC);\n\nCREATE INDEX \"idx_native_hook_relay_bridges_expires\" ON \"native_hook_relay_bridges\" ((\"expires_at_ms\") ASC, (\"relay_id\") ASC);\n\nCREATE INDEX \"idx_official_external_plugin_catalog_snapshots_updated\" ON \"official_external_plugin_catalog_snapshots\" ((\"updated_at_ms\") DESC, (\"feed_url\") ASC);\n\nCREATE UNIQUE INDEX \"idx_operator_approvals_cursor_id\" ON \"operator_approvals\" ((\"cursor_id\") ASC);\n\nCREATE UNIQUE INDEX \"idx_operator_approvals_resolution_ref\" ON \"operator_approvals\" ((\"resolution_ref\") ASC);\n\nCREATE INDEX \"idx_operator_approvals_resolved\" ON \"operator_approvals\" ((\"resolved_at_ms\") ASC, (\"approval_id\") ASC) WHERE \"resolved_at_ms\" IS NOT NULL;\n\nCREATE INDEX \"idx_operator_approvals_runtime_pending\" ON \"operator_approvals\" ((\"runtime_epoch\") ASC, (\"approval_id\") ASC) WHERE (\"status\" = 'pending');\n\nCREATE INDEX \"idx_operator_approvals_source_run_resolved\" ON \"operator_approvals\" ((\"source_run_id\") ASC, (\"resolved_at_ms\") ASC, (\"approval_id\") ASC) WHERE \"source_run_id\" IS NOT NULL AND \"resolved_at_ms\" IS NOT NULL;\n\nCREATE INDEX \"idx_operator_approvals_source_session_created\" ON \"operator_approvals\" ((\"source_session_key\") ASC NULLS FIRST, (\"created_at_ms\") DESC, (\"approval_id\") ASC);\n\nCREATE INDEX \"idx_operator_approvals_status_expiry\" ON \"operator_approvals\" ((\"status\") ASC, (\"expires_at_ms\") ASC, (\"approval_id\") ASC);\n\nCREATE INDEX \"idx_plugin_binding_approvals_plugin\" ON \"plugin_binding_approvals\" ((\"plugin_id\") ASC, (\"approved_at\") DESC);\n\nCREATE INDEX \"idx_plugin_blob_expiry\" ON \"plugin_blob_entries\" ((\"expires_at\") ASC) WHERE \"expires_at\" IS NOT NULL;\n\nCREATE INDEX \"idx_plugin_blob_listing\" ON \"plugin_blob_entries\" ((\"plugin_id\") ASC, (\"namespace\") ASC, (\"created_at\") ASC, (\"entry_key\") ASC);\n\nCREATE INDEX \"idx_plugin_state_expiry\" ON \"plugin_state_entries\" ((\"expires_at\") ASC) WHERE \"expires_at\" IS NOT NULL;\n\nCREATE INDEX \"idx_plugin_state_listing\" ON \"plugin_state_entries\" ((\"plugin_id\") ASC, (\"namespace\") ASC, (\"created_at\") ASC, (\"entry_key\") ASC, (\"expires_at\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_sandbox_registry_last_used\" ON \"sandbox_registry_entries\" ((\"registry_kind\") ASC, (\"last_used_at_ms\") DESC, (\"container_name\") ASC) WHERE \"last_used_at_ms\" IS NOT NULL;\n\nCREATE INDEX \"idx_sandbox_registry_session\" ON \"sandbox_registry_entries\" ((\"registry_kind\") ASC, (\"session_key\") ASC, (\"last_used_at_ms\") DESC NULLS LAST, (\"container_name\") ASC) WHERE \"session_key\" IS NOT NULL;\n\nCREATE INDEX \"idx_sandbox_registry_updated\" ON \"sandbox_registry_entries\" ((\"registry_kind\") ASC, (\"updated_at\") DESC, (\"container_name\") ASC);\n\nCREATE INDEX \"idx_session_state_events_session_sequence\" ON \"session_state_events\" ((\"session_key\") ASC, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_session_state_events_time\" ON \"session_state_events\" ((\"occurred_at\") DESC, (\"sequence\") DESC);\n\nCREATE INDEX \"idx_session_upstream_links_catalog_id\" ON \"session_upstream_links\" ((\"catalog_id\") ASC);\n\nCREATE INDEX \"idx_session_watch_cursors_target\" ON \"session_watch_cursors\" ((\"target_session_key\") ASC);\n\nCREATE INDEX \"idx_skill_uploads_expiry\" ON \"skill_uploads\" ((\"expires_at\") ASC);\n\nCREATE INDEX \"idx_skill_uploads_idempotency\" ON \"skill_uploads\" ((\"idempotency_key_hash\") ASC) WHERE \"idempotency_key_hash\" IS NOT NULL;\n\nCREATE INDEX \"idx_state_leases_expiry\" ON \"state_leases\" ((\"expires_at\") ASC, (\"scope\") ASC, (\"lease_key\") ASC) WHERE \"expires_at\" IS NOT NULL;\n\nCREATE INDEX \"idx_state_leases_owner\" ON \"state_leases\" ((\"owner\") ASC);\n\nCREATE INDEX \"idx_subagent_runs_child_session_key\" ON \"subagent_runs\" ((\"child_session_key\") ASC, (\"created_at\") DESC, (\"run_id\") ASC);\n\nCREATE INDEX \"idx_subagent_runs_controller_session_key\" ON \"subagent_runs\" ((\"controller_session_key\") ASC NULLS FIRST, (\"created_at\") DESC, (\"run_id\") ASC);\n\nCREATE INDEX \"idx_subagent_runs_requester_session_key\" ON \"subagent_runs\" ((\"requester_session_key\") ASC, (\"created_at\") DESC, (\"run_id\") ASC);\n\nCREATE INDEX \"idx_task_runs_cron_runtime_order\" ON \"task_runs\" ((\"runtime\") ASC, (\"created_at\") ASC, (\"task_id\") ASC) WHERE (\"runtime\" = 'cron');\n\nCREATE INDEX \"idx_task_runs_cron_source_order\" ON \"task_runs\" ((\"source_id\") ASC NULLS FIRST, (\"created_at\") ASC, (\"task_id\") ASC) WHERE (\"runtime\" = 'cron');\n\nCREATE INDEX \"idx_task_runs_runtime_run\" ON \"task_runs\" ((\"runtime\") ASC, (\"run_id\") ASC NULLS FIRST, (\"source_id\") ASC NULLS FIRST, (\"created_at\") ASC, (\"task_id\") ASC);\n\nCREATE INDEX \"idx_web_push_subscriptions_updated\" ON \"web_push_subscriptions\" ((\"updated_at_ms\") DESC, (\"subscription_id\") ASC);\n\nCREATE UNIQUE INDEX \"idx_worker_environments_provider_lease\" ON \"worker_environments\" ((\"provider_id\") ASC, (\"lease_id\") ASC) WHERE \"lease_id\" IS NOT NULL;\n\nCREATE INDEX \"idx_worker_environments_terminal_changed\" ON \"worker_environments\" ((\"state_changed_at_ms\") ASC, (\"environment_id\") ASC);\n\nCREATE UNIQUE INDEX \"idx_worker_inference_turns_pending_run\" ON \"worker_inference_turns\" ((\"session_id\") ASC, (\"run_epoch\") ASC, (\"run_id\") ASC) WHERE (\"state\" = 'pending');\n\nCREATE INDEX \"idx_worker_session_placements_environment\" ON \"worker_session_placements\" ((\"environment_id\") ASC) WHERE \"environment_id\" IS NOT NULL;\n\nCREATE INDEX \"idx_worker_session_placements_reconcile\" ON \"worker_session_placements\" ((\"updated_at_ms\") ASC, (\"session_id\") ASC);\n\nCREATE INDEX \"idx_worker_session_placements_session_key\" ON \"worker_session_placements\" ((\"agent_id\") ASC, (\"session_key\") ASC);\n\nCREATE INDEX \"idx_workspace_path_aliases_workspace\" ON \"workspace_path_aliases\" ((\"workspace_key\") ASC);\n\nCREATE INDEX \"idx_workspace_setup_state_path\" ON \"workspace_setup_state\" ((\"workspace_path\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_worktrees_removed_at\" ON \"worktrees\" ((\"removed_at\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_worktrees_repo_fingerprint\" ON \"worktrees\" ((\"repo_fingerprint\") ASC);\n\nALTER TABLE \"acp_replay_events\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"acp_replay_sessions\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"capture_events\" ADD FOREIGN KEY (\"data_blob_id\") REFERENCES \"capture_blobs\" (\"blob_id\") ON UPDATE NO ACTION ON DELETE SET NULL NOT DEFERRABLE;\n\nALTER TABLE \"capture_events\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"capture_sessions\" (\"id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"meeting_transcript_summaries\" ADD FOREIGN KEY (\"session_id\", \"session_started_at\") REFERENCES \"meeting_transcript_sessions\" (\"session_id\", \"started_at\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"meeting_transcript_utterances\" ADD FOREIGN KEY (\"session_id\", \"session_started_at\") REFERENCES \"meeting_transcript_sessions\" (\"session_id\", \"started_at\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"migration_sources\" ADD FOREIGN KEY (\"last_run_id\") REFERENCES \"migration_runs\" (\"id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"skill_upload_chunks\" ADD FOREIGN KEY (\"upload_id\") REFERENCES \"skill_uploads\" (\"upload_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"task_delivery_state\" ADD FOREIGN KEY (\"task_id\") REFERENCES \"task_runs\" (\"task_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_environment_credentials\" ADD FOREIGN KEY (\"environment_id\") REFERENCES \"worker_environments\" (\"environment_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_inference_turns\" ADD FOREIGN KEY (\"environment_id\") REFERENCES \"worker_environments\" (\"environment_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_session_tool_operations\" ADD FOREIGN KEY (\"source_session_id\") REFERENCES \"worker_session_placements\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_transcript_commits\" ADD FOREIGN KEY (\"session_id\", \"run_epoch\") REFERENCES \"worker_transcript_commit_heads\" (\"session_id\", \"run_epoch\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_turn_tool_authorities\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"worker_session_placements\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_workspace_pending_results\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"worker_session_placements\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"worker_workspace_reconciliations\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"worker_session_placements\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"workspace_generated_bootstrap_hashes\" ADD FOREIGN KEY (\"workspace_key\") REFERENCES \"workspace_setup_state\" (\"workspace_key\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n",
	operatorRecoveryV25Sql: "-- Generated v24-to-v25 metadata-only transition; the engine owner publishes openclaw_schema_meta.\n-- Subagent operator recovery requires the new reader; catalog and retained rows are unchanged.\nUPDATE schema_meta SET schema_version = 25 WHERE meta_key = 'primary' AND schema_version = 24;\nUPDATE config_machine_state SET value_json = '25' WHERE state_key = 'state.schema.contentVersion' AND value_json = '24';\n",
	preWriteIndexesV27Sql: {
		acp_replay_events: "CREATE INDEX \"idx_acp_replay_events_session_seq\" ON \"acp_replay_events\" ((\"session_id\") ASC NULLS FIRST, (\"seq\") ASC NULLS FIRST);",
		skill_usage: "CREATE INDEX \"idx_skill_usage_key\" ON \"skill_usage\" ((\"skill_key\") ASC NULLS FIRST, (\"skill_file\") ASC NULLS FIRST);",
		state_leases: "CREATE INDEX \"idx_state_leases_owner\" ON \"state_leases\" ((\"owner\") ASC NULLS FIRST, (\"updated_at\") DESC NULLS LAST);"
	},
	writeIndexesV27Sql: "\n  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;\n  DROP INDEX IF EXISTS idx_skill_usage_key;\n  DROP INDEX IF EXISTS idx_state_leases_owner;\n\nCREATE INDEX \"idx_state_leases_owner\" ON \"state_leases\" ((\"owner\") ASC NULLS FIRST);",
	clientCredentialV29Sql: "-- Generated v28-to-v29 publication after the local credential owner has verified and retired source rows.\nUPDATE schema_meta SET schema_version = 29 WHERE meta_key = 'primary' AND schema_version = 28;\n",
	workspaceCasV35Sql: "-- Generated DDL-only v34-to-v35 transition; reconciliation converts retained rows online.\nDO $workspace_cas$ BEGIN\nIF to_regclass('local_workspace_projections') IS NOT NULL THEN\nALTER TABLE \"local_workspace_projections\" ADD COLUMN \"tree_root_digest\" bytea;\nALTER TABLE \"local_workspace_projections\" ADD COLUMN \"source_paths_digest\" bytea;\nALTER TABLE \"local_workspace_projections\" ADD COLUMN \"canonical_fingerprints\" bytea;\nALTER TABLE \"local_workspace_projections\" ADD COLUMN \"projection_fingerprints\" bytea;\nCREATE TABLE \"local_workspace_source_path_sets\" (\n  \"path_digest\" bytea NOT NULL,\n  \"paths_zstd\" bytea NOT NULL,\n  \"sweep_epoch\" bigint NOT NULL,\n  PRIMARY KEY (\"path_digest\"),\n  CHECK ((octet_length(\"path_digest\") = 32))\n);\nCREATE TABLE \"local_workspace_tree_packs\" (\n  \"tree_digest\" bytea NOT NULL,\n  \"records_json\" text COLLATE \"C\" NOT NULL,\n  \"children_json\" text COLLATE \"C\" NOT NULL,\n  \"sweep_epoch\" bigint NOT NULL,\n  PRIMARY KEY (\"tree_digest\"),\n  CHECK ((octet_length(\"tree_digest\") = 32))\n);\nEND IF; END $workspace_cas$;\n",
	clientCredentialSource: {
		sql: "CREATE TABLE \"device_auth_tokens\" (\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"role\" text COLLATE \"C\" NOT NULL,\n  \"token\" text COLLATE \"C\" NOT NULL,\n  \"scopes_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"device_id\", \"role\")\n);\n\nCREATE TABLE \"device_identities\" (\n  \"identity_key\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"public_key_pem\" text COLLATE \"C\" NOT NULL,\n  \"private_key_pem\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"identity_key\")\n);\n\nCREATE TABLE \"gateway_origin_device_tokens\" (\n  \"gateway_scope\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"role\" text COLLATE \"C\" NOT NULL,\n  \"token\" text COLLATE \"C\" NOT NULL,\n  \"scopes_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"gateway_scope\", \"device_id\", \"role\")\n);\n\nCREATE INDEX \"idx_device_auth_tokens_updated\" ON \"device_auth_tokens\" ((\"updated_at_ms\") DESC NULLS LAST, (\"device_id\") ASC NULLS FIRST, (\"role\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_device_identities_device\" ON \"device_identities\" ((\"device_id\") ASC NULLS FIRST, (\"updated_at_ms\") DESC NULLS LAST);",
		preData: [0, 926],
		postData: [926, 1225],
		tables: [
			{
				name: "device_auth_tokens",
				identities: []
			},
			{
				name: "device_identities",
				identities: []
			},
			{
				name: "gateway_origin_device_tokens",
				identities: []
			}
		],
		expectedCatalog: [
			{
				table: "device_auth_tokens",
				kind: "table",
				value: null
			},
			{
				table: "device_auth_tokens",
				kind: "column",
				value: {
					name: "device_id",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 1
				}
			},
			{
				table: "device_auth_tokens",
				kind: "column",
				value: {
					name: "role",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 2
				}
			},
			{
				table: "device_auth_tokens",
				kind: "column",
				value: {
					name: "token",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 3
				}
			},
			{
				table: "device_auth_tokens",
				kind: "column",
				value: {
					name: "scopes_json",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 4
				}
			},
			{
				table: "device_auth_tokens",
				kind: "column",
				value: {
					name: "updated_at_ms",
					type: "bigint",
					nullable: false,
					identity: false,
					default: null,
					position: 5
				}
			},
			{
				table: "device_auth_tokens",
				kind: "primaryKey",
				value: ["device_id", "role"]
			},
			{
				table: "device_auth_tokens",
				kind: "indexes",
				value: 2
			},
			{
				table: "device_auth_tokens",
				kind: "checks",
				value: 0
			},
			{
				table: "device_identities",
				kind: "table",
				value: null
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "identity_key",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 1
				}
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "device_id",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 2
				}
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "public_key_pem",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 3
				}
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "private_key_pem",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 4
				}
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "created_at_ms",
					type: "bigint",
					nullable: false,
					identity: false,
					default: null,
					position: 5
				}
			},
			{
				table: "device_identities",
				kind: "column",
				value: {
					name: "updated_at_ms",
					type: "bigint",
					nullable: false,
					identity: false,
					default: null,
					position: 6
				}
			},
			{
				table: "device_identities",
				kind: "primaryKey",
				value: ["identity_key"]
			},
			{
				table: "device_identities",
				kind: "indexes",
				value: 2
			},
			{
				table: "device_identities",
				kind: "checks",
				value: 0
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "table",
				value: null
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "gateway_scope",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 1
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "device_id",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 2
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "role",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 3
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "token",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 4
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "scopes_json",
					type: "text",
					nullable: false,
					identity: false,
					default: null,
					position: 5
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "column",
				value: {
					name: "updated_at_ms",
					type: "bigint",
					nullable: false,
					identity: false,
					default: null,
					position: 6
				}
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "primaryKey",
				value: [
					"gateway_scope",
					"device_id",
					"role"
				]
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "indexes",
				value: 1
			},
			{
				table: "gateway_origin_device_tokens",
				kind: "checks",
				value: 0
			}
		]
	},
	fragments: [
		{
			id: "local_workspace_projections",
			tables: [
				"local_workspace_projections",
				"local_workspace_manifest_nodes",
				"local_workspace_tree_packs",
				"local_workspace_source_path_sets"
			],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"local_workspace_manifest_nodes\" (\n  \"worktree_id\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"node_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"worktree_id\", \"path\")\n);\n\nCREATE TABLE \"local_workspace_projections\" (\n  \"worktree_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"lifecycle_revision\" text COLLATE \"C\",\n  \"projection_path\" text COLLATE \"C\" NOT NULL,\n  \"base_commit\" text COLLATE \"C\" NOT NULL,\n  \"source_paths_json\" text COLLATE \"C\" NOT NULL,\n  \"baseline_json\" text COLLATE \"C\",\n  \"baseline_ref\" text COLLATE \"C\",\n  \"pending_ref\" text COLLATE \"C\",\n  \"pending_target\" text COLLATE \"C\",\n  \"paused_runtimes_json\" text COLLATE \"C\",\n  \"journal_json\" text COLLATE \"C\",\n  \"journal_pack\" bytea,\n  \"revision\" bigint NOT NULL DEFAULT 0,\n  \"created_at_ms\" bigint NOT NULL,\n  \"checkpoint_json\" text COLLATE \"C\",\n  \"tree_root_digest\" bytea,\n  \"source_paths_digest\" bytea,\n  \"canonical_fingerprints\" bytea,\n  \"projection_fingerprints\" bytea,\n  PRIMARY KEY (\"worktree_id\"),\n  CHECK ((\"pending_target\" IN ('canonical', 'projection'))),\n  CHECK (\"journal_pack\" IS NULL OR (octet_length(\"journal_pack\") <= 268435456)),\n  CHECK ((\"revision\" >= 0)),\n  CHECK (\"baseline_json\" IS NULL OR \"baseline_ref\" IS NOT NULL),\n  CHECK (((\"journal_json\" IS NULL) = (\"journal_pack\" IS NULL))),\n  UNIQUE (\"projection_path\")\n);\n\nCREATE TABLE \"local_workspace_source_path_sets\" (\n  \"path_digest\" bytea NOT NULL,\n  \"paths_zstd\" bytea NOT NULL,\n  \"sweep_epoch\" bigint NOT NULL,\n  PRIMARY KEY (\"path_digest\"),\n  CHECK ((octet_length(\"path_digest\") = 32))\n);\n\nCREATE TABLE \"local_workspace_tree_packs\" (\n  \"tree_digest\" bytea NOT NULL,\n  \"records_json\" text COLLATE \"C\" NOT NULL,\n  \"children_json\" text COLLATE \"C\" NOT NULL,\n  \"sweep_epoch\" bigint NOT NULL,\n  PRIMARY KEY (\"tree_digest\"),\n  CHECK ((octet_length(\"tree_digest\") = 32))\n);\n\nALTER TABLE \"local_workspace_manifest_nodes\" ADD FOREIGN KEY (\"worktree_id\") REFERENCES \"local_workspace_projections\" (\"worktree_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "user_profiles",
			tables: [
				"user_profiles",
				"user_profile_emails",
				"user_profile_identities"
			],
			indexes: [
				"idx_user_profile_emails_profile_id",
				"idx_user_profile_identities_profile_id",
				"idx_user_profile_identities_authorization"
			],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"user_profile_emails\" (\n  \"email\" text COLLATE \"C\" NOT NULL,\n  \"profile_id\" text COLLATE \"C\" NOT NULL,\n  \"binding_id\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  PRIMARY KEY (\"email\")\n);\n\nCREATE TABLE \"user_profile_identities\" (\n  \"provider\" text COLLATE \"C\" NOT NULL,\n  \"subject\" text COLLATE \"C\" NOT NULL,\n  \"profile_id\" text COLLATE \"C\" NOT NULL,\n  \"canonical_login\" text COLLATE \"C\",\n  \"verified_email_json\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"authorization_id\" text COLLATE \"C\",\n  \"authorization_basis_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"provider\", \"subject\")\n);\n\nCREATE TABLE \"user_profiles\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"display_name\" text COLLATE \"C\",\n  \"primary_github_account_id\" bigint,\n  \"avatar\" bytea,\n  \"avatar_mime\" text COLLATE \"C\",\n  \"avatar_sha256\" text COLLATE \"C\",\n  \"merged_into\" text COLLATE \"C\",\n  \"role\" text COLLATE \"C\",\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"id\")\n);\n\nCREATE INDEX \"idx_user_profile_emails_profile_id\" ON \"user_profile_emails\" ((\"profile_id\") ASC);\n\nCREATE UNIQUE INDEX \"idx_user_profile_identities_authorization\" ON \"user_profile_identities\" ((\"authorization_id\") ASC NULLS FIRST);\n\nCREATE INDEX \"idx_user_profile_identities_profile_id\" ON \"user_profile_identities\" ((\"profile_id\") ASC);\n"
		},
		{
			id: "skill_library_entries",
			tables: [
				"skill_library_entries",
				"skill_library_revisions",
				"skill_library_events",
				"skill_library_uploads"
			],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"skill_library_entries\" (\n  \"skill_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_profile_id\" text COLLATE \"C\",\n  \"author_profile_id\" text COLLATE \"C\" NOT NULL,\n  \"slug\" text COLLATE \"C\" NOT NULL,\n  \"current_revision\" text COLLATE \"C\" NOT NULL,\n  \"shared\" bigint NOT NULL,\n  \"enabled\" bigint NOT NULL,\n  \"removed\" bigint NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"updated_at\" bigint NOT NULL,\n  PRIMARY KEY (\"skill_id\")\n);\n\nCREATE TABLE \"skill_library_events\" (\n  \"event_id\" text COLLATE \"C\" NOT NULL,\n  \"skill_id\" text COLLATE \"C\" NOT NULL,\n  \"revision\" text COLLATE \"C\" NOT NULL,\n  \"action\" text COLLATE \"C\" NOT NULL,\n  \"actor_profile_id\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  PRIMARY KEY (\"event_id\")\n);\n\nCREATE TABLE \"skill_library_revisions\" (\n  \"skill_id\" text COLLATE \"C\" NOT NULL,\n  \"revision\" text COLLATE \"C\" NOT NULL,\n  \"description\" text COLLATE \"C\" NOT NULL,\n  \"files_json\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  PRIMARY KEY (\"skill_id\", \"revision\")\n);\n\nCREATE TABLE \"skill_library_uploads\" (\n  \"upload_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_profile_id\" text COLLATE \"C\" NOT NULL,\n  \"slug\" text COLLATE \"C\" NOT NULL,\n  \"size_bytes\" bigint NOT NULL,\n  \"sha256\" text COLLATE \"C\" NOT NULL,\n  \"archive_blob\" bytea NOT NULL,\n  \"expires_at\" bigint NOT NULL,\n  \"published_skill_id\" text COLLATE \"C\",\n  PRIMARY KEY (\"upload_id\")\n);\n"
		},
		{
			id: "operator_approval_standing_grants",
			tables: ["operator_approval_standing_grants", "operator_approval_standing_grant_generations"],
			indexes: ["idx_operator_approval_standing_grants_binding"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"operator_approval_standing_grant_generations\" (\n  \"grant_id\" text COLLATE \"C\" NOT NULL,\n  \"job_definition_generation\" bigint NOT NULL,\n  PRIMARY KEY (\"grant_id\"),\n  CHECK ((\"job_definition_generation\" >= 1))\n);\n\nCREATE TABLE \"operator_approval_standing_grants\" (\n  \"grant_id\" text COLLATE \"C\" NOT NULL,\n  \"minted_by_approval_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"cron_job_id\" text COLLATE \"C\" NOT NULL,\n  \"job_config_revision\" text COLLATE \"C\" NOT NULL,\n  \"operation_binding\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"expires_at_ms\" bigint,\n  \"revoked_at_ms\" bigint,\n  \"revoked_by\" text COLLATE \"C\",\n  \"last_used_at_ms\" bigint,\n  \"use_count\" bigint NOT NULL DEFAULT 0,\n  PRIMARY KEY (\"grant_id\"),\n  CHECK ((char_length(\"grant_id\") > 0)),\n  CHECK ((char_length(\"agent_id\") > 0)),\n  CHECK ((char_length(\"cron_job_id\") > 0)),\n  CHECK ((char_length(\"job_config_revision\") > 0)),\n  CHECK ((char_length(\"operation_binding\") > 0)),\n  CHECK (\"expires_at_ms\" IS NULL OR (\"expires_at_ms\" >= \"created_at_ms\"))\n);\n\nCREATE INDEX \"idx_operator_approval_standing_grants_binding\" ON \"operator_approval_standing_grants\" ((\"agent_id\") ASC, (\"cron_job_id\") ASC, (\"operation_binding\") ASC, (\"created_at_ms\") DESC);\n\nALTER TABLE \"operator_approval_standing_grant_generations\" ADD FOREIGN KEY (\"grant_id\") REFERENCES \"operator_approval_standing_grants\" (\"grant_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"operator_approval_standing_grants\" ADD FOREIGN KEY (\"minted_by_approval_id\") REFERENCES \"operator_approvals\" (\"approval_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "worker_environment_session_attachments",
			tables: ["worker_environment_session_attachments"],
			indexes: ["worker_environment_session_attachments_session_key"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"worker_environment_session_attachments\" (\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"session_lifecycle_revision\" text COLLATE \"C\",\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"generation\" bigint NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"last_used_at_ms\" bigint NOT NULL,\n  \"closed_at_ms\" bigint,\n  PRIMARY KEY (\"session_id\"),\n  CHECK ((\"generation\" >= 1)),\n  UNIQUE (\"environment_id\")\n);\n\nCREATE INDEX \"worker_environment_session_attachments_session_key\" ON \"worker_environment_session_attachments\" ((\"agent_id\") ASC, (\"session_key\") ASC);\n\nALTER TABLE \"worker_environment_session_attachments\" ADD FOREIGN KEY (\"environment_id\") REFERENCES \"worker_environments\" (\"environment_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "sandbox_persistent_execs",
			tables: ["sandbox_persistent_execs"],
			indexes: [
				"idx_sandbox_persistent_execs_container",
				"idx_sandbox_persistent_execs_container_name",
				"idx_sandbox_persistent_execs_source"
			],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"sandbox_persistent_execs\" (\n  \"owner_key\" text COLLATE \"C\" NOT NULL,\n  \"source_identity\" text COLLATE \"C\" NOT NULL,\n  \"attempt_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_json\" text COLLATE \"C\" NOT NULL,\n  \"backend_id\" text COLLATE \"C\" NOT NULL,\n  \"backend_target_json\" text COLLATE \"C\" NOT NULL,\n  \"workspace_binding_json\" text COLLATE \"C\" NOT NULL,\n  \"container_id\" text COLLATE \"C\" NOT NULL,\n  \"container_name\" text COLLATE \"C\" NOT NULL,\n  \"container_started_at\" text COLLATE \"C\" NOT NULL,\n  \"revision\" bigint NOT NULL,\n  \"phase\" text COLLATE \"C\" NOT NULL,\n  \"receipt_json\" text COLLATE \"C\",\n  \"error\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"owner_key\"),\n  CHECK ((\"backend_id\" = 'docker')),\n  CHECK ((\"revision\" > 0)),\n  CHECK ((\"phase\" IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped'))),\n  CHECK ((\"phase\" NOT IN ('prepared', 'running')) OR \"receipt_json\" IS NOT NULL),\n  UNIQUE (\"attempt_id\")\n);\n\nCREATE INDEX \"idx_sandbox_persistent_execs_container\" ON \"sandbox_persistent_execs\" ((\"container_id\") ASC, (\"owner_key\") ASC);\n\nCREATE INDEX \"idx_sandbox_persistent_execs_container_name\" ON \"sandbox_persistent_execs\" ((\"container_name\") ASC, (\"owner_key\") ASC);\n\nCREATE INDEX \"idx_sandbox_persistent_execs_source\" ON \"sandbox_persistent_execs\" ((\"source_identity\") ASC, (\"owner_key\") ASC);\n"
		},
		{
			id: "user_background_images",
			tables: ["user_background_images"],
			indexes: [],
			dependencies: ["user_profiles"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"user_background_images\" (\n  \"profile_id\" text COLLATE \"C\" NOT NULL,\n  \"asset_id\" text COLLATE \"C\" NOT NULL,\n  \"image\" bytea NOT NULL,\n  \"width\" bigint NOT NULL,\n  \"height\" bigint NOT NULL,\n  PRIMARY KEY (\"profile_id\"),\n  CHECK ((octet_length(\"image\") BETWEEN 1 AND 2097152)),\n  CHECK ((\"width\" BETWEEN 1 AND 2560)),\n  CHECK ((\"height\" BETWEEN 1 AND 2560)),\n  UNIQUE (\"asset_id\")\n);\n\nALTER TABLE \"user_background_images\" ADD FOREIGN KEY (\"profile_id\") REFERENCES \"user_profiles\" (\"id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "update_runs",
			tables: ["update_runs"],
			indexes: ["idx_update_runs_created", "idx_update_runs_active"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"update_runs\" (\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"trigger\" text COLLATE \"C\" NOT NULL,\n  \"phase\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"reason\" text COLLATE \"C\",\n  \"origin_json\" text COLLATE \"C\" NOT NULL,\n  \"target_json\" text COLLATE \"C\" NOT NULL,\n  \"before_json\" text COLLATE \"C\" NOT NULL,\n  \"after_json\" text COLLATE \"C\" NOT NULL,\n  \"steps_json\" text COLLATE \"C\" NOT NULL,\n  \"verification_json\" text COLLATE \"C\" NOT NULL,\n  \"repair_json\" text COLLATE \"C\" NOT NULL,\n  \"confirmed_at_ms\" bigint,\n  \"finished_at_ms\" bigint,\n  \"downtime_ms\" bigint,\n  PRIMARY KEY (\"run_id\"),\n  CHECK ((\"trigger\" IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api'))),\n  CHECK ((\"phase\" IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished'))),\n  CHECK ((\"status\" IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped'))),\n  CHECK ((octet_length(convert_to(\"origin_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"target_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"before_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"after_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"steps_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"verification_json\", 'UTF8')) <= 16384)),\n  CHECK ((octet_length(convert_to(\"repair_json\", 'UTF8')) <= 16384)),\n  CHECK (((\"status\" = 'running') AND (\"phase\" != 'finished') AND \"finished_at_ms\" IS NULL) OR ((\"status\" != 'running') AND (\"phase\" = 'finished') AND \"finished_at_ms\" IS NOT NULL))\n);\n\nCREATE INDEX \"idx_update_runs_active\" ON \"update_runs\" ((\"status\") ASC, (\"created_at_ms\") DESC, (\"run_id\") ASC);\n\nCREATE INDEX \"idx_update_runs_created\" ON \"update_runs\" ((\"created_at_ms\") DESC, (\"run_id\") ASC);\n"
		},
		{
			id: "session_repository_workspaces",
			tables: ["session_repository_workspaces"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"session_repository_workspaces\" (\n  \"workspace_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"url\" text COLLATE \"C\" NOT NULL,\n  \"requested_ref\" text COLLATE \"C\",\n  \"run_setup_script\" bigint NOT NULL DEFAULT 0,\n  \"base_commit\" text COLLATE \"C\",\n  \"base_manifest_hash\" text COLLATE \"C\",\n  \"branch\" text COLLATE \"C\" NOT NULL,\n  \"checkpoint_ref\" text COLLATE \"C\",\n  \"manifest_hash\" text COLLATE \"C\",\n  \"revision\" bigint NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"workspace_id\"),\n  CHECK ((char_length(\"workspace_id\") = 36)),\n  CHECK ((char_length(\"agent_id\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"session_key\") BETWEEN 1 AND 1024)),\n  CHECK ((char_length(\"url\") BETWEEN 1 AND 4096)),\n  CHECK (\"requested_ref\" IS NULL OR (char_length(\"requested_ref\") BETWEEN 1 AND 1024)),\n  CHECK ((\"run_setup_script\" IN (0, 1))),\n  CHECK (\"base_commit\" IS NULL OR (char_length(\"base_commit\") IN (40, 64))),\n  CHECK ((char_length(\"branch\") BETWEEN 1 AND 256)),\n  CHECK ((\"revision\" >= 0)),\n  CHECK (\"base_manifest_hash\" IS NULL OR \"base_commit\" IS NOT NULL),\n  CHECK ((\"checkpoint_ref\" IS NULL AND \"manifest_hash\" IS NULL) OR (\"checkpoint_ref\" IS NOT NULL AND \"manifest_hash\" IS NOT NULL AND \"base_manifest_hash\" IS NOT NULL)),\n  UNIQUE (\"agent_id\", \"session_key\")\n);\n"
		},
		{
			id: "github_repository_publication_requests",
			tables: ["github_repository_publication_requests"],
			indexes: ["idx_github_repository_publication_shared_request", "idx_github_repository_publication_personal_request"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"github_repository_publication_requests\" (\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_profile_id\" text COLLATE \"C\",\n  \"connection_generation\" text COLLATE \"C\",\n  \"idempotency_key\" text COLLATE \"C\" NOT NULL,\n  \"request_digest\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_lifecycle_revision\" text COLLATE \"C\",\n  \"requester_authority_json\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"workspace_id\" text COLLATE \"C\" NOT NULL,\n  \"checkpoint_ref\" text COLLATE \"C\",\n  \"checkpoint_digest\" text COLLATE \"C\",\n  \"claim_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"environment_id\" text COLLATE \"C\",\n  \"owner_epoch\" bigint,\n  \"placement_generation\" bigint,\n  \"identity_source\" text COLLATE \"C\" NOT NULL,\n  \"identity_profile_id\" text COLLATE \"C\",\n  \"identity_account_id\" bigint NOT NULL,\n  \"identity_login\" text COLLATE \"C\" NOT NULL,\n  \"title\" text COLLATE \"C\",\n  \"body\" text COLLATE \"C\",\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"gateway_instance_id\" text COLLATE \"C\",\n  \"execution_id\" text COLLATE \"C\",\n  \"last_effect\" text COLLATE \"C\",\n  \"effect_state\" text COLLATE \"C\",\n  \"push_repository\" text COLLATE \"C\",\n  \"repository\" text COLLATE \"C\",\n  \"branch\" text COLLATE \"C\" NOT NULL,\n  \"base_branch\" text COLLATE \"C\",\n  \"source_head_commit\" text COLLATE \"C\",\n  \"source_index_tree\" text COLLATE \"C\",\n  \"workspace_tree\" text COLLATE \"C\",\n  \"previous_head_commit\" text COLLATE \"C\",\n  \"pushed_head_commit\" text COLLATE \"C\",\n  \"head_commit\" text COLLATE \"C\",\n  \"pull_request_url\" text COLLATE \"C\",\n  \"error_code\" text COLLATE \"C\",\n  \"next_action\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"reported_at_ms\" bigint,\n  \"draft\" bigint,\n  PRIMARY KEY (\"request_id\"),\n  CHECK ((\"identity_source\" IN ('system-detected', 'system-configured', 'agent-override', 'personal'))),\n  CHECK ((\"status\" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),\n  CHECK ((\"last_effect\" IN ('push', 'pull_request'))),\n  CHECK ((\"effect_state\" IN ('dispatched', 'observed'))),\n  CHECK (((\"identity_source\" = 'personal') AND \"owner_profile_id\" IS NOT NULL AND \"connection_generation\" IS NOT NULL) OR ((\"identity_source\" <> 'personal') AND \"owner_profile_id\" IS NULL AND \"connection_generation\" IS NULL)),\n  CHECK ((\"checkpoint_ref\" IS NULL AND \"checkpoint_digest\" IS NULL) OR (\"checkpoint_ref\" IS NOT NULL AND \"checkpoint_digest\" IS NOT NULL)),\n  CHECK ((\"last_effect\" IS NULL AND \"effect_state\" IS NULL) OR (\"last_effect\" IS NOT NULL AND \"effect_state\" IS NOT NULL))\n);\n\nCREATE UNIQUE INDEX \"idx_github_repository_publication_personal_request\" ON \"github_repository_publication_requests\" ((\"owner_profile_id\") ASC, (\"session_id\") ASC, (\"idempotency_key\") ASC) WHERE \"owner_profile_id\" IS NOT NULL;\n\nCREATE UNIQUE INDEX \"idx_github_repository_publication_shared_request\" ON \"github_repository_publication_requests\" ((\"session_id\") ASC, (\"idempotency_key\") ASC) WHERE \"owner_profile_id\" IS NULL;\n"
		},
		{
			id: "github_publication_session_lifecycles",
			tables: ["github_publication_session_lifecycles"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"github_publication_session_lifecycles\" (\n  \"publication_kind\" text COLLATE \"C\" NOT NULL,\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"lifecycle_revision\" text COLLATE \"C\",\n  \"requester_authority_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"publication_kind\", \"request_id\"),\n  CHECK ((\"publication_kind\" IN ('shared', 'personal')))\n);\n"
		},
		{
			id: "github_personal_publication_requests",
			tables: ["github_personal_publication_requests"],
			indexes: ["idx_github_personal_publication_owner_session", "idx_github_personal_publication_pending"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"github_personal_publication_requests\" (\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_profile_id\" text COLLATE \"C\" NOT NULL,\n  \"connection_generation\" text COLLATE \"C\" NOT NULL,\n  \"idempotency_key\" text COLLATE \"C\" NOT NULL,\n  \"request_digest\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"worktree_id\" text COLLATE \"C\" NOT NULL,\n  \"repository_fingerprint\" text COLLATE \"C\" NOT NULL,\n  \"identity_source\" text COLLATE \"C\" NOT NULL,\n  \"identity_profile_id\" text COLLATE \"C\" NOT NULL,\n  \"identity_account_id\" bigint NOT NULL,\n  \"identity_login\" text COLLATE \"C\" NOT NULL,\n  \"title\" text COLLATE \"C\",\n  \"body\" text COLLATE \"C\",\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"gateway_instance_id\" text COLLATE \"C\",\n  \"execution_id\" text COLLATE \"C\",\n  \"last_effect\" text COLLATE \"C\",\n  \"effect_state\" text COLLATE \"C\",\n  \"push_repository\" text COLLATE \"C\" NOT NULL,\n  \"repository\" text COLLATE \"C\" NOT NULL,\n  \"branch\" text COLLATE \"C\" NOT NULL,\n  \"base_branch\" text COLLATE \"C\" NOT NULL,\n  \"source_head_commit\" text COLLATE \"C\" NOT NULL,\n  \"source_index_tree\" text COLLATE \"C\" NOT NULL,\n  \"workspace_tree\" text COLLATE \"C\" NOT NULL,\n  \"head_commit\" text COLLATE \"C\",\n  \"pull_request_url\" text COLLATE \"C\",\n  \"error_code\" text COLLATE \"C\",\n  \"next_action\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"reported_at_ms\" bigint,\n  \"draft\" bigint,\n  PRIMARY KEY (\"request_id\"),\n  CHECK ((char_length(\"request_id\") = 36)),\n  CHECK ((char_length(\"owner_profile_id\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"connection_generation\") = 36)),\n  CHECK ((char_length(\"idempotency_key\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"request_digest\") = 64)),\n  CHECK ((char_length(\"session_id\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"session_key\") BETWEEN 1 AND 1024)),\n  CHECK ((char_length(\"agent_id\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"worktree_id\") BETWEEN 1 AND 128)),\n  CHECK ((char_length(\"repository_fingerprint\") BETWEEN 1 AND 256)),\n  CHECK ((\"identity_source\" = 'personal')),\n  CHECK ((char_length(\"identity_profile_id\") = 36)),\n  CHECK ((\"identity_account_id\" >= 1)),\n  CHECK ((char_length(\"identity_login\") BETWEEN 1 AND 39)),\n  CHECK (\"title\" IS NULL OR (char_length(\"title\") BETWEEN 1 AND 256)),\n  CHECK (\"body\" IS NULL OR (char_length(\"body\") BETWEEN 1 AND 8192)),\n  CHECK ((\"status\" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),\n  CHECK (\"gateway_instance_id\" IS NULL OR (char_length(\"gateway_instance_id\") BETWEEN 1 AND 128)),\n  CHECK (\"execution_id\" IS NULL OR (char_length(\"execution_id\") = 36)),\n  CHECK (\"last_effect\" IS NULL OR (\"last_effect\" IN ('push', 'pull_request'))),\n  CHECK (\"effect_state\" IS NULL OR (\"effect_state\" IN ('dispatched', 'observed'))),\n  CHECK ((char_length(\"push_repository\") BETWEEN 3 AND 256)),\n  CHECK ((char_length(\"repository\") BETWEEN 3 AND 256)),\n  CHECK ((char_length(\"branch\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"base_branch\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"source_head_commit\") IN (40, 64))),\n  CHECK ((char_length(\"source_index_tree\") IN (40, 64))),\n  CHECK ((char_length(\"workspace_tree\") IN (40, 64))),\n  CHECK (\"head_commit\" IS NULL OR (char_length(\"head_commit\") IN (40, 64))),\n  CHECK (\"pull_request_url\" IS NULL OR (char_length(\"pull_request_url\") BETWEEN 1 AND 2048)),\n  CHECK (\"error_code\" IS NULL OR (char_length(\"error_code\") BETWEEN 1 AND 64)),\n  CHECK (\"next_action\" IS NULL OR (char_length(\"next_action\") BETWEEN 1 AND 1024)),\n  CHECK ((\"created_at_ms\" >= 0)),\n  CHECK ((\"updated_at_ms\" >= \"created_at_ms\")),\n  CHECK (((\"status\" = 'publishing') AND \"gateway_instance_id\" IS NOT NULL AND \"execution_id\" IS NOT NULL) OR (\"status\" <> 'publishing')),\n  CHECK ((\"last_effect\" IS NULL AND \"effect_state\" IS NULL) OR (\"last_effect\" IS NOT NULL AND \"effect_state\" IS NOT NULL)),\n  CHECK (((\"status\" = 'published') AND \"pull_request_url\" IS NOT NULL AND \"head_commit\" IS NOT NULL AND \"error_code\" IS NULL AND \"next_action\" IS NULL) OR ((\"status\" = 'failed') AND \"error_code\" IS NOT NULL AND \"next_action\" IS NOT NULL) OR ((\"status\" IN ('requested', 'publishing', 'needs_confirmation')) AND \"error_code\" IS NULL AND \"next_action\" IS NULL)),\n  UNIQUE (\"owner_profile_id\", \"session_id\", \"idempotency_key\")\n);\n\nCREATE INDEX \"idx_github_personal_publication_owner_session\" ON \"github_personal_publication_requests\" ((\"owner_profile_id\") ASC, (\"session_id\") ASC, (\"created_at_ms\") ASC);\n\nCREATE INDEX \"idx_github_personal_publication_pending\" ON \"github_personal_publication_requests\" ((\"status\") ASC, (\"updated_at_ms\") ASC, (\"request_id\") ASC);\n"
		},
		{
			id: "cron_job_runtime_authorities",
			tables: ["cron_job_runtime_authorities"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"cron_job_runtime_authorities\" (\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"job_id\" text COLLATE \"C\" NOT NULL,\n  \"authority_json\" text COLLATE \"C\",\n  \"authority_input_fingerprint\" text COLLATE \"C\",\n  \"recovery_required\" bigint NOT NULL,\n  PRIMARY KEY (\"store_key\", \"job_id\"),\n  CHECK ((\"recovery_required\" IN (0, 1))),\n  CHECK (((\"recovery_required\" = 0) AND \"authority_json\" IS NOT NULL AND \"authority_input_fingerprint\" IS NOT NULL) OR ((\"recovery_required\" = 1) AND \"authority_json\" IS NULL AND \"authority_input_fingerprint\" IS NULL))\n);\n\nALTER TABLE \"cron_job_runtime_authorities\" ADD FOREIGN KEY (\"store_key\", \"job_id\") REFERENCES \"cron_jobs\" (\"store_key\", \"job_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "cron_run_trigger_state_retirements",
			tables: ["cron_run_trigger_state_retirements"],
			indexes: [],
			dependencies: ["cron_run_receipts"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"cron_run_trigger_state_retirements\" (\n  \"receipt_id\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"receipt_id\")\n);\n\nALTER TABLE \"cron_run_trigger_state_retirements\" ADD FOREIGN KEY (\"receipt_id\") REFERENCES \"cron_run_receipts\" (\"receipt_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "execution_identity_contexts",
			tables: ["execution_identity_contexts"],
			indexes: ["execution_identity_contexts_run_created_idx"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"execution_identity_contexts\" (\n  \"context_id\" text COLLATE \"C\" NOT NULL,\n  \"execution_id\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"coverage_state\" text COLLATE \"C\" NOT NULL,\n  \"context_bytes\" bigint NOT NULL,\n  \"context_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"context_id\"),\n  CHECK ((char_length(\"context_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"execution_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"run_id\") BETWEEN 1 AND 256)),\n  CHECK ((\"created_at\" >= 0)),\n  CHECK ((\"coverage_state\" IN ('attribution-only', 'unattributed', 'unknown', 'unsupported'))),\n  CHECK ((\"context_bytes\" BETWEEN 1 AND 16384)),\n  CHECK ((char_length(\"context_json\") > 0)),\n  UNIQUE (\"execution_id\"),\n  UNIQUE (\"created_at\", \"context_id\")\n);\n\nCREATE INDEX \"execution_identity_contexts_run_created_idx\" ON \"execution_identity_contexts\" ((\"run_id\") ASC, (\"created_at\") ASC, (\"execution_id\") ASC);\n"
		},
		{
			id: "mcp_oauth_pending_authorizations",
			tables: ["mcp_oauth_pending_authorizations"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"mcp_oauth_pending_authorizations\" (\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"create_time\" bigint NOT NULL,\n  PRIMARY KEY (\"state\")\n);\n"
		},
		{
			id: "node_worker_launch_containers",
			tables: ["node_worker_launch_containers"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_launch_containers\" (\n  \"launch_id\" text COLLATE \"C\" NOT NULL,\n  \"container_json\" text COLLATE \"C\",\n  PRIMARY KEY (\"launch_id\")\n);\n"
		},
		{
			id: "node_worker_launch_boots",
			tables: ["node_worker_launch_boots"],
			indexes: [],
			dependencies: ["node_worker_launches"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_launch_boots\" (\n  \"launch_id\" text COLLATE \"C\" NOT NULL,\n  \"boot_id\" text COLLATE \"C\",\n  PRIMARY KEY (\"launch_id\"),\n  CHECK (\"boot_id\" IS NULL OR (char_length(\"boot_id\") BETWEEN 1 AND 128))\n);\n\nALTER TABLE \"node_worker_launch_boots\" ADD FOREIGN KEY (\"launch_id\") REFERENCES \"node_worker_launches\" (\"launch_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "node_worker_launch_cleanup",
			tables: ["node_worker_launch_cleanup"],
			indexes: [],
			dependencies: ["node_worker_launches"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_launch_cleanup\" (\n  \"launch_id\" text COLLATE \"C\" NOT NULL,\n  \"cleanup_mode\" text COLLATE \"C\" NOT NULL,\n  \"lineage_settled\" bigint,\n  PRIMARY KEY (\"launch_id\"),\n  CHECK ((\"cleanup_mode\" IN ('process-group', 'owned-anchor'))),\n  CHECK (\"lineage_settled\" IS NULL OR (\"lineage_settled\" = 1))\n);\n\nALTER TABLE \"node_worker_launch_cleanup\" ADD FOREIGN KEY (\"launch_id\") REFERENCES \"node_worker_launches\" (\"launch_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "node_worker_launch_process_scopes",
			tables: ["node_worker_launch_process_scopes"],
			indexes: [],
			dependencies: ["node_worker_launches"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_launch_process_scopes\" (\n  \"launch_id\" text COLLATE \"C\" NOT NULL,\n  \"scope_kind\" text COLLATE \"C\" NOT NULL,\n  \"descendants_reaped\" bigint,\n  PRIMARY KEY (\"launch_id\"),\n  CHECK ((\"scope_kind\" = 'linux-subreaper')),\n  CHECK (\"descendants_reaped\" IS NULL OR (\"descendants_reaped\" = 1))\n);\n\nALTER TABLE \"node_worker_launch_process_scopes\" ADD FOREIGN KEY (\"launch_id\") REFERENCES \"node_worker_launches\" (\"launch_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "node_worker_launches",
			tables: ["node_worker_launches"],
			indexes: ["idx_node_worker_launches_terminal_completed"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_launches\" (\n  \"launch_id\" text COLLATE \"C\" NOT NULL,\n  \"plan_hash\" text COLLATE \"C\" NOT NULL,\n  \"gateway_namespace\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_epoch\" bigint NOT NULL,\n  \"placement_generation\" bigint NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"supervisor_pid\" bigint NOT NULL,\n  \"supervisor_start_time\" bigint NOT NULL,\n  \"worker_pid\" bigint,\n  \"worker_start_time\" bigint,\n  \"result_json\" text COLLATE \"C\",\n  \"error_text\" text COLLATE \"C\",\n  \"completed_at_ms\" bigint,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"launch_id\"),\n  CHECK ((char_length(\"launch_id\") BETWEEN 1 AND 256) AND (\"launch_id\" IS NOT NULL OR NULL)),\n  CHECK ((char_length(\"plan_hash\") = 64) AND (\"plan_hash\" COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((char_length(\"gateway_namespace\") BETWEEN 1 AND 128) AND (\"gateway_namespace\" COLLATE \"C\" !~ '\\A.*[^A-Za-z0-9._-].*\\Z') AND (\"gateway_namespace\" COLLATE \"C\" ~ '\\A[A-Za-z0-9].*\\Z')),\n  CHECK ((char_length(\"environment_id\") BETWEEN 1 AND 256) AND (\"environment_id\" IS NOT NULL OR NULL)),\n  CHECK ((char_length(\"session_id\") BETWEEN 1 AND 256) AND (\"session_id\" IS NOT NULL OR NULL)),\n  CHECK ((\"owner_epoch\" BETWEEN 1 AND 9007199254740991)),\n  CHECK ((\"placement_generation\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((char_length(\"run_id\") BETWEEN 1 AND 256) AND (\"run_id\" IS NOT NULL OR NULL)),\n  CHECK ((\"state\" IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled'))),\n  CHECK ((\"supervisor_pid\" BETWEEN 1 AND 2147483647)),\n  CHECK ((\"supervisor_start_time\" BETWEEN 0 AND 9007199254740991)),\n  CHECK (\"worker_pid\" IS NULL OR (\"worker_pid\" BETWEEN 1 AND 2147483647)),\n  CHECK (\"worker_start_time\" IS NULL OR (\"worker_start_time\" BETWEEN 0 AND 9007199254740991)),\n  CHECK (\"result_json\" IS NULL OR ((octet_length(convert_to(\"result_json\", 'UTF8')) BETWEEN 1 AND 65536) AND (\"result_json\" IS NOT NULL OR NULL) AND (\"result_json\" IS JSON))),\n  CHECK (\"error_text\" IS NULL OR ((octet_length(convert_to(\"error_text\", 'UTF8')) BETWEEN 1 AND 4096) AND (\"error_text\" IS NOT NULL OR NULL) AND (strpos(\"error_text\", '\n') = 0) AND (strpos(\"error_text\", '\r') = 0))),\n  CHECK (\"completed_at_ms\" IS NULL OR (\"completed_at_ms\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((\"created_at_ms\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((\"updated_at_ms\" BETWEEN \"created_at_ms\" AND 9007199254740991)),\n  CHECK (((\"worker_pid\" IS NULL) = (\"worker_start_time\" IS NULL))),\n  CHECK (((\"state\" = 'pending') AND \"worker_pid\" IS NULL AND \"result_json\" IS NULL AND \"error_text\" IS NULL AND \"completed_at_ms\" IS NULL) OR ((\"state\" = 'running') AND \"worker_pid\" IS NOT NULL AND \"result_json\" IS NULL AND \"error_text\" IS NULL AND \"completed_at_ms\" IS NULL) OR ((\"state\" = 'completed') AND \"result_json\" IS NOT NULL AND \"error_text\" IS NULL AND (\"completed_at_ms\" BETWEEN \"created_at_ms\" AND \"updated_at_ms\")) OR ((\"state\" IN ('failed', 'interrupted', 'cancelled')) AND \"result_json\" IS NULL AND \"error_text\" IS NOT NULL AND (\"completed_at_ms\" BETWEEN \"created_at_ms\" AND \"updated_at_ms\")))\n);\n\nCREATE INDEX \"idx_node_worker_launches_terminal_completed\" ON \"node_worker_launches\" ((\"completed_at_ms\") ASC, (\"launch_id\") ASC) WHERE \"completed_at_ms\" IS NOT NULL;\n"
		},
		{
			id: "node_worker_prepared_workspaces",
			tables: ["node_worker_prepared_workspaces"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_prepared_workspaces\" (\n  \"preparation_key\" text COLLATE \"C\" NOT NULL,\n  \"cache_key\" text COLLATE \"C\" NOT NULL,\n  \"gateway_namespace\" text COLLATE \"C\" NOT NULL,\n  \"workspace_dir\" text COLLATE \"C\" NOT NULL,\n  \"home_dir\" text COLLATE \"C\" NOT NULL,\n  \"source_manifest_ref\" text COLLATE \"C\" NOT NULL,\n  \"prepared_manifest_ref\" text COLLATE \"C\" NOT NULL,\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\",\n  \"owner_epoch\" bigint,\n  \"created_at_ms\" bigint NOT NULL,\n  \"bound_at_ms\" bigint,\n  \"retired_at_ms\" bigint,\n  PRIMARY KEY (\"preparation_key\"),\n  CHECK ((char_length(\"preparation_key\") = 64) AND (\"preparation_key\" COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((char_length(\"cache_key\") = 64) AND (\"cache_key\" COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((char_length(\"gateway_namespace\") > 0)),\n  CHECK ((char_length(\"workspace_dir\") > 0)),\n  CHECK ((char_length(\"home_dir\") > 0)),\n  CHECK ((char_length(\"source_manifest_ref\") = 71) AND (substr(\"source_manifest_ref\", 1, 7) = 'sha256:') AND (substr(\"source_manifest_ref\", 8) COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((char_length(\"prepared_manifest_ref\") = 71) AND (substr(\"prepared_manifest_ref\", 1, 7) = 'sha256:') AND (substr(\"prepared_manifest_ref\", 8) COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((\"state\" IN ('available', 'bound', 'retiring', 'retired'))),\n  CHECK ((char_length(\"environment_id\") > 0)),\n  CHECK ((\"owner_epoch\" BETWEEN 1 AND 9007199254740991)),\n  CHECK ((\"created_at_ms\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((\"bound_at_ms\" BETWEEN \"created_at_ms\" AND 9007199254740991)),\n  CHECK ((\"retired_at_ms\" BETWEEN coalesce(\"bound_at_ms\", \"created_at_ms\") AND 9007199254740991)),\n  CHECK ((\"session_id\" IS NULL AND \"session_key\" IS NULL AND \"owner_epoch\" IS NULL AND \"bound_at_ms\" IS NULL) OR (\"session_id\" IS NOT NULL AND (char_length(\"session_id\") > 0) AND \"session_key\" IS NOT NULL AND (char_length(\"session_key\") > 0) AND \"owner_epoch\" IS NOT NULL AND \"bound_at_ms\" IS NOT NULL)),\n  CHECK (((\"state\" = 'available') AND \"bound_at_ms\" IS NULL AND \"retired_at_ms\" IS NULL) OR ((\"state\" = 'bound') AND \"bound_at_ms\" IS NOT NULL AND \"retired_at_ms\" IS NULL) OR ((\"state\" = 'retiring') AND \"retired_at_ms\" IS NULL) OR ((\"state\" = 'retired') AND \"retired_at_ms\" IS NOT NULL)),\n  UNIQUE (\"workspace_dir\")\n);\n"
		},
		{
			id: "node_worker_turns",
			tables: ["node_worker_turns"],
			indexes: ["idx_node_worker_turns_terminal_completed", "idx_node_worker_turns_active_owner"],
			dependencies: ["node_worker_launches"],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"node_worker_turns\" (\n  \"turn_id\" text COLLATE \"C\" NOT NULL,\n  \"owner_launch_id\" text COLLATE \"C\" NOT NULL,\n  \"plan_hash\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"state\" text COLLATE \"C\" NOT NULL,\n  \"result_json\" text COLLATE \"C\",\n  \"error_text\" text COLLATE \"C\",\n  \"completed_at_ms\" bigint,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"turn_id\"),\n  CHECK ((char_length(\"turn_id\") BETWEEN 1 AND 256) AND (\"turn_id\" IS NOT NULL OR NULL)),\n  CHECK ((char_length(\"plan_hash\") = 64) AND (\"plan_hash\" COLLATE \"C\" !~ '\\A.*[^0-9a-f].*\\Z')),\n  CHECK ((char_length(\"run_id\") BETWEEN 1 AND 256) AND (\"run_id\" IS NOT NULL OR NULL)),\n  CHECK ((\"state\" IN ('running', 'completed', 'failed', 'interrupted', 'cancelled'))),\n  CHECK (\"result_json\" IS NULL OR ((octet_length(convert_to(\"result_json\", 'UTF8')) BETWEEN 1 AND 65536) AND (\"result_json\" IS NOT NULL OR NULL) AND (\"result_json\" IS JSON))),\n  CHECK (\"error_text\" IS NULL OR ((octet_length(convert_to(\"error_text\", 'UTF8')) BETWEEN 1 AND 4096) AND (\"error_text\" IS NOT NULL OR NULL) AND (strpos(\"error_text\", '\n') = 0) AND (strpos(\"error_text\", '\r') = 0))),\n  CHECK (\"completed_at_ms\" IS NULL OR (\"completed_at_ms\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((\"created_at_ms\" BETWEEN 0 AND 9007199254740991)),\n  CHECK ((\"updated_at_ms\" BETWEEN \"created_at_ms\" AND 9007199254740991)),\n  CHECK (((\"state\" = 'running') AND \"result_json\" IS NULL AND \"error_text\" IS NULL AND \"completed_at_ms\" IS NULL) OR ((\"state\" = 'completed') AND \"result_json\" IS NOT NULL AND \"error_text\" IS NULL AND (\"completed_at_ms\" BETWEEN \"created_at_ms\" AND \"updated_at_ms\")) OR ((\"state\" IN ('failed', 'interrupted', 'cancelled')) AND \"result_json\" IS NULL AND \"error_text\" IS NOT NULL AND (\"completed_at_ms\" BETWEEN \"created_at_ms\" AND \"updated_at_ms\")))\n);\n\nCREATE UNIQUE INDEX \"idx_node_worker_turns_active_owner\" ON \"node_worker_turns\" ((\"owner_launch_id\") ASC) WHERE (\"state\" = 'running');\n\nCREATE INDEX \"idx_node_worker_turns_terminal_completed\" ON \"node_worker_turns\" ((\"completed_at_ms\") ASC, (\"turn_id\") ASC) WHERE \"completed_at_ms\" IS NOT NULL;\n\nALTER TABLE \"node_worker_turns\" ADD FOREIGN KEY (\"owner_launch_id\") REFERENCES \"node_worker_launches\" (\"launch_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "operator_approval_execution_identities",
			tables: ["operator_approval_execution_identities"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"operator_approval_execution_identities\" (\n  \"approval_id\" text COLLATE \"C\" NOT NULL,\n  \"source_context_id\" text COLLATE \"C\" NOT NULL,\n  \"source_execution_id\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"approval_id\"),\n  CHECK ((char_length(\"source_context_id\") BETWEEN 1 AND 256) AND (\"source_context_id\" = btrim(\"source_context_id\"))),\n  CHECK ((char_length(\"source_execution_id\") BETWEEN 1 AND 256) AND (\"source_execution_id\" = btrim(\"source_execution_id\")))\n);\n\nALTER TABLE \"operator_approval_execution_identities\" ADD FOREIGN KEY (\"approval_id\") REFERENCES \"operator_approvals\" (\"approval_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "web_push_approval_deliveries",
			tables: ["web_push_approval_deliveries"],
			indexes: ["idx_web_push_approval_deliveries_subscription"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"web_push_approval_deliveries\" (\n  \"approval_id\" text COLLATE \"C\" NOT NULL,\n  \"subscription_id\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"user_profile_id\" text COLLATE \"C\",\n  \"prepared_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"approval_id\", \"subscription_id\")\n);\n\nCREATE INDEX \"idx_web_push_approval_deliveries_subscription\" ON \"web_push_approval_deliveries\" ((\"subscription_id\") ASC, (\"approval_id\") ASC);\n\nALTER TABLE \"web_push_approval_deliveries\" ADD FOREIGN KEY (\"subscription_id\") REFERENCES \"web_push_subscriptions\" (\"subscription_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n\nALTER TABLE \"web_push_approval_deliveries\" ADD FOREIGN KEY (\"approval_id\") REFERENCES \"operator_approvals\" (\"approval_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "execution_decision_facts",
			tables: ["execution_decision_facts"],
			indexes: [
				"execution_decision_facts_cursor_id_idx",
				"execution_decision_facts_context_occurred_idx",
				"execution_decision_facts_run_occurred_idx"
			],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"execution_decision_facts\" (\n  \"cursor_id\" bigint NOT NULL,\n  \"receipt_id\" text COLLATE \"C\" NOT NULL,\n  \"context_id\" text COLLATE \"C\" NOT NULL,\n  \"execution_id\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  \"action_id\" text COLLATE \"C\",\n  \"action_family\" text COLLATE \"C\" NOT NULL,\n  \"decision_outcome\" text COLLATE \"C\" NOT NULL,\n  \"coverage_state\" text COLLATE \"C\" NOT NULL,\n  \"reason_code\" text COLLATE \"C\" NOT NULL,\n  \"owner\" text COLLATE \"C\" NOT NULL,\n  \"source_ref\" text COLLATE \"C\" NOT NULL,\n  \"occurred_at\" bigint NOT NULL,\n  \"receipt_bytes\" bigint NOT NULL,\n  \"receipt_json\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"receipt_id\"),\n  CHECK ((char_length(\"receipt_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"context_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"execution_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"run_id\") BETWEEN 1 AND 256)),\n  CHECK (\"action_id\" IS NULL OR (char_length(\"action_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"action_family\") BETWEEN 1 AND 256)),\n  CHECK ((\"decision_outcome\" IN ('allowed', 'denied', 'not-applicable', 'unknown'))),\n  CHECK ((\"coverage_state\" IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported'))),\n  CHECK ((char_length(\"reason_code\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"owner\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"source_ref\") BETWEEN 1 AND 256)),\n  CHECK ((\"occurred_at\" >= 0)),\n  CHECK ((\"receipt_bytes\" BETWEEN 1 AND 16384)),\n  CHECK ((char_length(\"receipt_json\") > 0)),\n  UNIQUE (\"occurred_at\", \"receipt_id\")\n);\n\nCREATE INDEX \"execution_decision_facts_context_occurred_idx\" ON \"execution_decision_facts\" ((\"context_id\") ASC, (\"occurred_at\") ASC, (\"receipt_id\") ASC);\n\nCREATE UNIQUE INDEX \"execution_decision_facts_cursor_id_idx\" ON \"execution_decision_facts\" ((\"cursor_id\") ASC);\n\nCREATE INDEX \"execution_decision_facts_run_occurred_idx\" ON \"execution_decision_facts\" ((\"run_id\") ASC, (\"occurred_at\") ASC, (\"receipt_id\") ASC);\n"
		},
		{
			id: "execution_owner_lifecycle_bindings",
			tables: ["execution_owner_lifecycle_bindings"],
			indexes: [],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"execution_owner_lifecycle_bindings\" (\n  \"owner_kind\" text COLLATE \"C\" NOT NULL,\n  \"owner_id\" text COLLATE \"C\" NOT NULL,\n  \"context_id\" text COLLATE \"C\" NOT NULL,\n  \"execution_id\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"owner_kind\", \"owner_id\")\n);\n"
		},
		{
			id: "outbound_message_execution_bindings",
			tables: ["outbound_message_execution_bindings"],
			indexes: ["outbound_message_execution_bindings_execution_event_idx"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"outbound_message_execution_bindings\" (\n  \"event_id\" text COLLATE \"C\" NOT NULL,\n  \"context_id\" text COLLATE \"C\" NOT NULL,\n  \"execution_id\" text COLLATE \"C\" NOT NULL,\n  \"run_id\" text COLLATE \"C\" NOT NULL,\n  PRIMARY KEY (\"event_id\"),\n  CHECK ((char_length(\"context_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"execution_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"run_id\") BETWEEN 1 AND 256))\n);\n\nCREATE INDEX \"outbound_message_execution_bindings_execution_event_idx\" ON \"outbound_message_execution_bindings\" ((\"context_id\") ASC, (\"execution_id\") ASC, (\"run_id\") ASC, (\"event_id\") ASC);\n\nALTER TABLE \"outbound_message_execution_bindings\" ADD FOREIGN KEY (\"event_id\") REFERENCES \"audit_events\" (\"event_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "outbound_message_progress",
			tables: ["outbound_message_progress"],
			indexes: ["outbound_message_progress_occurred_idx", "outbound_message_progress_run_occurred_idx"],
			dependencies: [],
			activation: "first-use",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"outbound_message_progress\" (\n  \"sequence\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"progress_id\" text COLLATE \"C\" NOT NULL,\n  \"source_id\" text COLLATE \"C\" NOT NULL,\n  \"source_sequence\" bigint NOT NULL,\n  \"schema_version\" bigint NOT NULL,\n  \"occurred_at\" bigint NOT NULL,\n  \"action\" text COLLATE \"C\" NOT NULL,\n  \"outcome\" text COLLATE \"C\" NOT NULL,\n  \"actor_type\" text COLLATE \"C\" NOT NULL,\n  \"actor_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"context_id\" text COLLATE \"C\",\n  \"execution_id\" text COLLATE \"C\",\n  \"channel\" text COLLATE \"C\" NOT NULL,\n  \"conversation_kind\" text COLLATE \"C\" NOT NULL,\n  \"duration_ms\" bigint,\n  \"account_ref\" text COLLATE \"C\",\n  \"conversation_ref\" text COLLATE \"C\",\n  \"target_ref\" text COLLATE \"C\",\n  PRIMARY KEY (\"sequence\"),\n  CHECK ((char_length(\"progress_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"source_id\") BETWEEN 1 AND 512)),\n  CHECK ((\"source_sequence\" >= 1)),\n  CHECK ((\"schema_version\" = 1)),\n  CHECK ((\"occurred_at\" >= 0)),\n  CHECK ((\"action\" IN ('message.outbound.queued', 'message.outbound.platform-started'))),\n  CHECK ((\"outcome\" IN ('queued', 'platform_started'))),\n  CHECK ((\"actor_type\" IN ('agent', 'system'))),\n  CHECK ((char_length(\"actor_id\") BETWEEN 1 AND 256)),\n  CHECK (\"agent_id\" IS NULL OR (char_length(\"agent_id\") BETWEEN 1 AND 256)),\n  CHECK (\"run_id\" IS NULL OR (char_length(\"run_id\") BETWEEN 1 AND 256)),\n  CHECK ((char_length(\"channel\") BETWEEN 1 AND 256)),\n  CHECK ((\"conversation_kind\" IN ('direct', 'group', 'channel', 'unknown'))),\n  CHECK (\"duration_ms\" IS NULL OR (\"duration_ms\" >= 0)),\n  UNIQUE (\"progress_id\"),\n  UNIQUE (\"source_id\"),\n  UNIQUE (\"occurred_at\", \"progress_id\")\n);\n\nCREATE INDEX \"outbound_message_progress_occurred_idx\" ON \"outbound_message_progress\" ((\"occurred_at\") ASC, (\"sequence\") ASC);\n\nCREATE INDEX \"outbound_message_progress_run_occurred_idx\" ON \"outbound_message_progress\" ((\"run_id\") ASC NULLS FIRST, (\"occurred_at\") ASC, (\"sequence\") ASC);\n"
		},
		{
			id: "agent_provenance",
			tables: ["agent_provenance"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"agent_provenance\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"created_via\" text COLLATE \"C\" NOT NULL,\n  \"creator_agent_id\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"agent_id\"),\n  CHECK ((\"created_via\" IN ('operator', 'agent', 'template')))\n);\n"
		},
		{
			id: "cron_run_receipts",
			tables: ["cron_run_receipts"],
			indexes: [
				"cron_run_receipts_cursor_id_idx",
				"idx_cron_run_receipts_active_job",
				"idx_cron_run_receipts_job_history"
			],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"cron_run_receipts\" (\n  \"cursor_id\" bigint NOT NULL,\n  \"receipt_id\" text COLLATE \"C\" NOT NULL,\n  \"store_key\" text COLLATE \"C\" NOT NULL,\n  \"job_id\" text COLLATE \"C\" NOT NULL,\n  \"config_revision\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"request_run_id\" text COLLATE \"C\",\n  \"delivery_attempt_state\" text COLLATE \"C\" NOT NULL DEFAULT 'unknown',\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"owner_pid\" bigint NOT NULL,\n  \"owner_start_time\" bigint,\n  \"started_at_ms\" bigint NOT NULL,\n  \"finished_at_ms\" bigint,\n  \"error_text\" text COLLATE \"C\",\n  PRIMARY KEY (\"receipt_id\"),\n  CHECK ((\"delivery_attempt_state\" IN ('unknown', 'not-started', 'started'))),\n  CHECK ((\"status\" IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded'))),\n  CHECK (((\"status\" = 'running') AND \"finished_at_ms\" IS NULL) OR ((\"status\" != 'running') AND \"finished_at_ms\" IS NOT NULL))\n);\n\nCREATE UNIQUE INDEX \"cron_run_receipts_cursor_id_idx\" ON \"cron_run_receipts\" ((\"cursor_id\") ASC);\n\nCREATE UNIQUE INDEX \"idx_cron_run_receipts_active_job\" ON \"cron_run_receipts\" ((\"store_key\") ASC, (\"job_id\") ASC) WHERE (\"status\" = 'running');\n\nCREATE INDEX \"idx_cron_run_receipts_job_history\" ON \"cron_run_receipts\" ((\"store_key\") ASC, (\"job_id\") ASC, (\"started_at_ms\") DESC, (\"receipt_id\") DESC);\n"
		},
		{
			id: "config_revision_keys",
			tables: ["config_revision_keys"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"config_revision_keys\" (\n  \"id\" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,\n  \"hmac_key\" bytea NOT NULL,\n  PRIMARY KEY (\"id\"),\n  CHECK ((\"id\" = 1)),\n  CHECK ((octet_length(\"hmac_key\") = 32))\n);\n"
		},
		{
			id: "secret_store_entries",
			tables: ["secret_store_entries"],
			indexes: ["secret_store_entries_live_idx"],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"secret_store_entries\" (\n  \"scope_kind\" text COLLATE \"C\" NOT NULL,\n  \"scope_id\" text COLLATE \"C\" NOT NULL,\n  \"name\" text COLLATE \"C\" NOT NULL,\n  \"value\" text COLLATE \"C\" NOT NULL,\n  \"kind\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"updated_by\" text COLLATE \"C\",\n  \"deleted_at_ms\" bigint,\n  \"allowed_hosts\" text COLLATE \"C\",\n  PRIMARY KEY (\"scope_kind\", \"scope_id\", \"name\"),\n  CHECK ((\"scope_kind\" IN ('team', 'identity'))),\n  CHECK ((\"kind\" IN ('secret', 'env'))),\n  CHECK ((\"created_at_ms\" >= 0)),\n  CHECK ((\"updated_at_ms\" >= 0)),\n  CHECK (((\"scope_kind\" = 'team') AND (\"scope_id\" = '')) OR ((\"scope_kind\" = 'identity') AND (char_length(\"scope_id\") > 0)))\n);\n\nCREATE INDEX \"secret_store_entries_live_idx\" ON \"secret_store_entries\" ((\"scope_kind\") ASC, (\"scope_id\") ASC, (\"name\") ASC) WHERE \"deleted_at_ms\" IS NULL;\n"
		},
		{
			id: "projects",
			tables: ["projects"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"projects\" (\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"display_name\" text COLLATE \"C\" NOT NULL,\n  \"repo_root\" text COLLATE \"C\" NOT NULL,\n  \"origin_url\" text COLLATE \"C\",\n  \"source\" text COLLATE \"C\" NOT NULL,\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"id\"),\n  CHECK ((\"source\" IN ('registered', 'cloned')))\n);\n"
		},
		{
			id: "worktree_templates",
			tables: ["worktree_templates"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"worktree_templates\" (\n  \"cache_key\" text COLLATE \"C\" NOT NULL,\n  \"id\" text COLLATE \"C\" NOT NULL,\n  \"repo_root\" text COLLATE \"C\" NOT NULL,\n  \"common_dir\" text COLLATE \"C\" NOT NULL,\n  \"worktree_root\" text COLLATE \"C\" NOT NULL,\n  \"path\" text COLLATE \"C\" NOT NULL,\n  \"backend\" text COLLATE \"C\" NOT NULL,\n  \"source_commit\" text COLLATE \"C\" NOT NULL,\n  \"content_key\" text COLLATE \"C\" NOT NULL,\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"created_at\" bigint NOT NULL,\n  \"last_used_at\" bigint NOT NULL,\n  PRIMARY KEY (\"cache_key\"),\n  CHECK ((\"status\" IN ('preparing', 'ready'))),\n  UNIQUE (\"id\")\n);\n"
		},
		{
			id: "user_preferences",
			tables: ["user_preferences"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"user_preferences\" (\n  \"profile_id\" text COLLATE \"C\" NOT NULL,\n  \"pref_key\" text COLLATE \"C\" NOT NULL,\n  \"value_json\" text COLLATE \"C\" NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"profile_id\", \"pref_key\")\n);\n"
		},
		{
			id: "device_pair_setup_completions",
			tables: ["device_pair_setup_completions"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"device_pair_setup_completions\" (\n  \"setup_id\" text COLLATE \"C\" NOT NULL,\n  \"device_id\" text COLLATE \"C\" NOT NULL,\n  \"device_name\" text COLLATE \"C\",\n  \"access\" text COLLATE \"C\" NOT NULL,\n  \"completed_at_ms\" bigint NOT NULL,\n  \"delivery_state\" text COLLATE \"C\" NOT NULL,\n  \"retain_until_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"setup_id\"),\n  CHECK ((\"delivery_state\" IN ('uncertain', 'confirmed')))\n);\n"
		},
		{
			id: "github_publication_requests",
			tables: ["github_publication_requests"],
			indexes: ["idx_github_publication_requests_pending"],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"github_publication_requests\" (\n  \"request_id\" text COLLATE \"C\" NOT NULL,\n  \"idempotency_key\" text COLLATE \"C\" NOT NULL,\n  \"request_digest\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"session_key\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"worktree_id\" text COLLATE \"C\" NOT NULL,\n  \"repository_fingerprint\" text COLLATE \"C\" NOT NULL,\n  \"claim_id\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"environment_id\" text COLLATE \"C\",\n  \"owner_epoch\" bigint,\n  \"placement_generation\" bigint,\n  \"identity_source\" text COLLATE \"C\" NOT NULL,\n  \"identity_profile_id\" text COLLATE \"C\",\n  \"identity_account_id\" bigint NOT NULL,\n  \"identity_login\" text COLLATE \"C\" NOT NULL,\n  \"title\" text COLLATE \"C\",\n  \"body\" text COLLATE \"C\",\n  \"status\" text COLLATE \"C\" NOT NULL,\n  \"gateway_instance_id\" text COLLATE \"C\",\n  \"repository\" text COLLATE \"C\",\n  \"branch\" text COLLATE \"C\" NOT NULL,\n  \"base_branch\" text COLLATE \"C\",\n  \"source_head_commit\" text COLLATE \"C\",\n  \"source_index_tree\" text COLLATE \"C\",\n  \"workspace_tree\" text COLLATE \"C\",\n  \"head_commit\" text COLLATE \"C\",\n  \"pull_request_url\" text COLLATE \"C\",\n  \"error_code\" text COLLATE \"C\",\n  \"next_action\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  \"reported_at_ms\" bigint,\n  \"draft\" bigint,\n  PRIMARY KEY (\"request_id\"),\n  CHECK (\"owner_epoch\" IS NULL OR (\"owner_epoch\" >= 1)),\n  CHECK (\"placement_generation\" IS NULL OR (\"placement_generation\" >= 0)),\n  CHECK ((\"identity_source\" IN ('system-detected', 'system-configured', 'agent-override'))),\n  CHECK ((\"identity_account_id\" >= 1)),\n  CHECK ((\"status\" IN ('requested', 'publishing', 'published', 'failed'))),\n  CHECK ((\"claim_id\" IS NULL AND \"run_id\" IS NULL AND \"environment_id\" IS NULL AND \"owner_epoch\" IS NULL AND \"placement_generation\" IS NULL) OR (\"claim_id\" IS NOT NULL AND \"run_id\" IS NOT NULL AND \"placement_generation\" IS NOT NULL AND ((\"environment_id\" IS NULL AND \"owner_epoch\" IS NULL) OR (\"environment_id\" IS NOT NULL AND \"owner_epoch\" IS NOT NULL)))),\n  CHECK ((\"identity_source\" IS NOT DISTINCT FROM 'system-detected' AND \"identity_profile_id\" IS NULL) OR ((\"identity_source\" IN ('system-configured', 'agent-override')) AND \"identity_profile_id\" IS NOT NULL)),\n  CHECK ((\"source_head_commit\" IS NULL AND \"source_index_tree\" IS NULL AND \"workspace_tree\" IS NULL) OR (\"source_head_commit\" IS NOT NULL AND \"workspace_tree\" IS NOT NULL)),\n  CHECK ((\"status\" IS NOT DISTINCT FROM 'published' AND \"pull_request_url\" IS NOT NULL AND \"error_code\" IS NULL AND \"next_action\" IS NULL) OR (\"status\" IS NOT DISTINCT FROM 'failed' AND \"pull_request_url\" IS NULL AND \"error_code\" IS NOT NULL AND \"next_action\" IS NOT NULL) OR ((\"status\" IN ('requested', 'publishing')) AND \"pull_request_url\" IS NULL AND \"error_code\" IS NULL AND \"next_action\" IS NULL)),\n  UNIQUE (\"session_id\", \"idempotency_key\")\n);\n\nCREATE INDEX \"idx_github_publication_requests_pending\" ON \"github_publication_requests\" ((\"status\") ASC, (\"updated_at_ms\") ASC, (\"request_id\") ASC);\n"
		},
		{
			id: "device_pairing_join_codes",
			tables: ["device_pairing_join_codes"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"device_pairing_join_codes\" (\n  \"shortcode\" text COLLATE \"C\",\n  \"payload_json\" text COLLATE \"C\",\n  \"created_at_ms\" bigint,\n  \"expires_at_ms\" bigint\n);\n"
		},
		{
			id: "skill_workshop_changes",
			tables: ["skill_workshop_changes"],
			indexes: ["skill_workshop_changes_cursor_id_idx", "idx_skill_workshop_changes_agent_time"],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"skill_workshop_changes\" (\n  \"cursor_id\" bigint NOT NULL,\n  \"change_id\" text COLLATE \"C\" NOT NULL,\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"skill_name\" text COLLATE \"C\" NOT NULL,\n  \"action\" text COLLATE \"C\" NOT NULL,\n  \"actor\" text COLLATE \"C\" NOT NULL,\n  \"summary\" text COLLATE \"C\" NOT NULL,\n  \"version_id\" text COLLATE \"C\",\n  \"session_key\" text COLLATE \"C\",\n  \"run_id\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"change_id\"),\n  CHECK ((\"action\" IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore'))),\n  CHECK ((\"actor\" IN ('agent', 'review', 'curator', 'user')))\n);\n\nCREATE INDEX \"idx_skill_workshop_changes_agent_time\" ON \"skill_workshop_changes\" ((\"agent_id\") ASC, (\"created_at_ms\") ASC);\n\nCREATE UNIQUE INDEX \"skill_workshop_changes_cursor_id_idx\" ON \"skill_workshop_changes\" ((\"cursor_id\") ASC);\n"
		},
		{
			id: "worker_environment_ssh_fallback_ports",
			tables: ["worker_environment_ssh_fallback_ports"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"worker_environment_ssh_fallback_ports\" (\n  \"environment_id\" text COLLATE \"C\" NOT NULL,\n  \"position\" bigint NOT NULL,\n  \"port\" bigint NOT NULL,\n  PRIMARY KEY (\"environment_id\", \"position\"),\n  CHECK ((\"position\" >= 0) AND (\"position\" <= 9)),\n  CHECK ((\"port\" >= 1) AND (\"port\" <= 65535)),\n  UNIQUE (\"environment_id\", \"port\")\n);\n\nALTER TABLE \"worker_environment_ssh_fallback_ports\" ADD FOREIGN KEY (\"environment_id\") REFERENCES \"worker_environments\" (\"environment_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "worker_session_placement_moves",
			tables: ["worker_session_placement_moves"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"worker_session_placement_moves\" (\n  \"operation_id\" text COLLATE \"C\" NOT NULL,\n  \"session_id\" text COLLATE \"C\" NOT NULL,\n  \"source_generation\" bigint NOT NULL,\n  \"source_environment_id\" text COLLATE \"C\" NOT NULL,\n  \"source_owner_epoch\" bigint NOT NULL,\n  \"target_kind\" text COLLATE \"C\" NOT NULL,\n  \"target_id\" text COLLATE \"C\",\n  \"target_machine_class\" text COLLATE \"C\",\n  \"target_os\" text COLLATE \"C\",\n  \"abandon_source\" bigint,\n  \"last_error\" text COLLATE \"C\",\n  \"created_at_ms\" bigint NOT NULL,\n  \"updated_at_ms\" bigint NOT NULL,\n  PRIMARY KEY (\"operation_id\"),\n  CHECK ((\"source_generation\" >= 0)),\n  CHECK ((char_length(\"source_environment_id\") BETWEEN 1 AND 256) AND (\"source_environment_id\" = btrim(\"source_environment_id\"))),\n  CHECK ((\"source_owner_epoch\" >= 1)),\n  CHECK ((\"target_kind\" IN ('gateway', 'profile', 'device'))),\n  CHECK ((\"target_kind\" IS NOT DISTINCT FROM 'gateway' AND \"target_id\" IS NULL) OR ((\"target_kind\" IN ('profile', 'device')) AND \"target_id\" IS NOT NULL AND (char_length(\"target_id\") BETWEEN 1 AND 256) AND (\"target_id\" = btrim(\"target_id\")))),\n  UNIQUE (\"session_id\")\n);\n\nALTER TABLE \"worker_session_placement_moves\" ADD FOREIGN KEY (\"session_id\") REFERENCES \"worker_session_placements\" (\"session_id\") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;\n"
		},
		{
			id: "agent_deletion_journal",
			tables: ["agent_deletion_journal"],
			indexes: [],
			dependencies: [],
			activation: "version-additive",
			sql: "-- Generated runtime DDL; the owner supplies search_path and the transaction.\n\nCREATE TABLE \"agent_deletion_journal\" (\n  \"agent_id\" text COLLATE \"C\" NOT NULL,\n  \"operation_id\" text COLLATE \"C\" NOT NULL DEFAULT '',\n  \"phase\" text COLLATE \"C\",\n  \"agent_dir\" text COLLATE \"C\" NOT NULL,\n  \"workspace_dir\" text COLLATE \"C\" NOT NULL,\n  \"sessions_dir\" text COLLATE \"C\" NOT NULL,\n  \"database_paths_json\" text COLLATE \"C\" NOT NULL DEFAULT '[]',\n  \"cleanup_paths_json\" text COLLATE \"C\" NOT NULL DEFAULT '[]',\n  \"created_at\" bigint NOT NULL,\n  \"cleanup_completed\" bigint NOT NULL DEFAULT 0,\n  \"delete_files\" bigint NOT NULL DEFAULT 1,\n  PRIMARY KEY (\"agent_id\")\n);\n"
		}
	],
	expectedCatalog: [
		{
			table: "acp_replay_events",
			kind: "table",
			value: null
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "seq",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "update_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "acp_replay_events",
			kind: "column",
			value: {
				name: "estimated_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 7
			}
		},
		{
			table: "acp_replay_events",
			kind: "primaryKey",
			value: ["session_id", "seq"]
		},
		{
			table: "acp_replay_events",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "acp_replay_sessions",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "acp_replay_events",
			kind: "indexes",
			value: 1
		},
		{
			table: "acp_replay_events",
			kind: "checks",
			value: 0
		},
		{
			table: "acp_replay_sessions",
			kind: "table",
			value: null
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "cwd",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "complete",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "next_seq",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "column",
			value: {
				name: "estimated_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 8
			}
		},
		{
			table: "acp_replay_sessions",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "acp_replay_sessions",
			kind: "indexes",
			value: 3
		},
		{
			table: "acp_replay_sessions",
			kind: "checks",
			value: 0
		},
		{
			table: "acp_sessions",
			kind: "table",
			value: null
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "backend",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "agent",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "runtime_session_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "identity_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "resume_agent_session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "resume_acpx_session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "mode",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "runtime_options_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "cwd",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "last_activity_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "last_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "acp_sessions",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "acp_sessions",
			kind: "primaryKey",
			value: ["session_key"]
		},
		{
			table: "acp_sessions",
			kind: "indexes",
			value: 5
		},
		{
			table: "acp_sessions",
			kind: "checks",
			value: 0
		},
		{
			table: "agent_database_leases",
			kind: "table",
			value: null
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "lease_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "owner_pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "owner_start_time",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "opened_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "agent_database_leases",
			kind: "column",
			value: {
				name: "provenance",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "agent_database_leases",
			kind: "primaryKey",
			value: ["lease_id"]
		},
		{
			table: "agent_database_leases",
			kind: "indexes",
			value: 1
		},
		{
			table: "agent_database_leases",
			kind: "checks",
			value: 0
		},
		{
			table: "agent_databases",
			kind: "table",
			value: null
		},
		{
			table: "agent_databases",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "agent_databases",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "agent_databases",
			kind: "column",
			value: {
				name: "schema_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "agent_databases",
			kind: "column",
			value: {
				name: "last_seen_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "agent_databases",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "agent_databases",
			kind: "primaryKey",
			value: ["agent_id", "path"]
		},
		{
			table: "agent_databases",
			kind: "indexes",
			value: 1
		},
		{
			table: "agent_databases",
			kind: "checks",
			value: 0
		},
		{
			table: "agent_deletion_journal",
			kind: "table",
			value: null
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "operation_id",
				type: "text",
				nullable: false,
				identity: false,
				default: "''",
				position: 2
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "phase",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "agent_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "workspace_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "sessions_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "database_paths_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'[]'",
				position: 7
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "cleanup_paths_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'[]'",
				position: 8
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "cleanup_completed",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 10
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "column",
			value: {
				name: "delete_files",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "1",
				position: 11
			}
		},
		{
			table: "agent_deletion_journal",
			kind: "primaryKey",
			value: ["agent_id"]
		},
		{
			table: "agent_deletion_journal",
			kind: "indexes",
			value: 1
		},
		{
			table: "agent_deletion_journal",
			kind: "checks",
			value: 0
		},
		{
			table: "agent_provenance",
			kind: "table",
			value: null
		},
		{
			table: "agent_provenance",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "agent_provenance",
			kind: "column",
			value: {
				name: "created_via",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "agent_provenance",
			kind: "column",
			value: {
				name: "creator_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "agent_provenance",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "agent_provenance",
			kind: "primaryKey",
			value: ["agent_id"]
		},
		{
			table: "agent_provenance",
			kind: "indexes",
			value: 1
		},
		{
			table: "agent_provenance",
			kind: "checks",
			value: 1
		},
		{
			table: "apns_registration_tombstones",
			kind: "table",
			value: null
		},
		{
			table: "apns_registration_tombstones",
			kind: "column",
			value: {
				name: "node_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "apns_registration_tombstones",
			kind: "column",
			value: {
				name: "deleted_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "apns_registration_tombstones",
			kind: "primaryKey",
			value: ["node_id"]
		},
		{
			table: "apns_registration_tombstones",
			kind: "indexes",
			value: 1
		},
		{
			table: "apns_registration_tombstones",
			kind: "checks",
			value: 0
		},
		{
			table: "apns_registrations",
			kind: "table",
			value: null
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "node_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "transport",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "token",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "relay_handle",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "send_grant",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "installation_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "relay_origin",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "topic",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "environment",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "distribution",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "token_debug_suffix",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "apns_registrations",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "apns_registrations",
			kind: "primaryKey",
			value: ["node_id"]
		},
		{
			table: "apns_registrations",
			kind: "indexes",
			value: 2
		},
		{
			table: "apns_registrations",
			kind: "checks",
			value: 0
		},
		{
			table: "audit_events",
			kind: "table",
			value: null
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "sequence",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "event_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "source_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "schema_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "1",
				position: 4
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "source_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "occurred_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "action",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "error_code",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "actor_type",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "actor_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "tool_call_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "tool_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "direction",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "channel",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "conversation_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "message_outcome",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "reason_code",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "delivery_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "failure_stage",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "duration_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "result_count",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "account_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "conversation_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "message_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "audit_events",
			kind: "column",
			value: {
				name: "target_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "audit_events",
			kind: "primaryKey",
			value: ["sequence"]
		},
		{
			table: "audit_events",
			kind: "unique",
			value: ["event_id"]
		},
		{
			table: "audit_events",
			kind: "unique",
			value: ["source_id"]
		},
		{
			table: "audit_events",
			kind: "indexes",
			value: 11
		},
		{
			table: "audit_events",
			kind: "checks",
			value: 0
		},
		{
			table: "audit_identity_keys",
			kind: "table",
			value: null
		},
		{
			table: "audit_identity_keys",
			kind: "column",
			value: {
				name: "id",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "audit_identity_keys",
			kind: "column",
			value: {
				name: "key_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "audit_identity_keys",
			kind: "column",
			value: {
				name: "key",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "audit_identity_keys",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "audit_identity_keys",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "audit_identity_keys",
			kind: "indexes",
			value: 1
		},
		{
			table: "audit_identity_keys",
			kind: "checks",
			value: 1
		},
		{
			table: "backup_runs",
			kind: "table",
			value: null
		},
		{
			table: "backup_runs",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "backup_runs",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "backup_runs",
			kind: "column",
			value: {
				name: "archive_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "backup_runs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "backup_runs",
			kind: "column",
			value: {
				name: "manifest_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "backup_runs",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "backup_runs",
			kind: "indexes",
			value: 2
		},
		{
			table: "backup_runs",
			kind: "checks",
			value: 0
		},
		{
			table: "capture_blobs",
			kind: "table",
			value: null
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "blob_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "content_type",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "encoding",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "sha256",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "data",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "capture_blobs",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "capture_blobs",
			kind: "primaryKey",
			value: ["blob_id"]
		},
		{
			table: "capture_blobs",
			kind: "indexes",
			value: 1
		},
		{
			table: "capture_blobs",
			kind: "checks",
			value: 0
		},
		{
			table: "capture_events",
			kind: "table",
			value: null
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "id",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "ts",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "source_scope",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "source_process",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "protocol",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "direction",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "flow_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "method",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "host",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "status",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "close_code",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "content_type",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "headers_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "data_text",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "data_blob_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "data_sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "error_text",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "capture_events",
			kind: "column",
			value: {
				name: "meta_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "capture_events",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "capture_events",
			kind: "foreignKey",
			value: {
				columns: ["data_blob_id"],
				target: "capture_blobs",
				targetColumns: ["blob_id"],
				onUpdate: "NO ACTION",
				onDelete: "SET NULL",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "capture_events",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "capture_sessions",
				targetColumns: ["id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "capture_events",
			kind: "indexes",
			value: 3
		},
		{
			table: "capture_events",
			kind: "checks",
			value: 0
		},
		{
			table: "capture_sessions",
			kind: "table",
			value: null
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "started_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "ended_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "mode",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "source_scope",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "source_process",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "capture_sessions",
			kind: "column",
			value: {
				name: "proxy_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "capture_sessions",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "capture_sessions",
			kind: "indexes",
			value: 1
		},
		{
			table: "capture_sessions",
			kind: "checks",
			value: 0
		},
		{
			table: "channel_ingress_events",
			kind: "table",
			value: null
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "queue_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "event_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "channel_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "lane_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "metadata_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "received_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "claim_token",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "claim_owner",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "claimed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "attempts",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 14
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "last_attempt_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "last_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "failed_reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "failed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "completed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "channel_ingress_events",
			kind: "column",
			value: {
				name: "completed_metadata_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "channel_ingress_events",
			kind: "primaryKey",
			value: ["queue_name", "event_id"]
		},
		{
			table: "channel_ingress_events",
			kind: "indexes",
			value: 4
		},
		{
			table: "channel_ingress_events",
			kind: "checks",
			value: 0
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "table",
			value: null
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "column",
			value: {
				name: "channel_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "column",
			value: {
				name: "entry",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "column",
			value: {
				name: "sort_order",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "primaryKey",
			value: [
				"channel_key",
				"account_id",
				"entry"
			]
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "indexes",
			value: 2
		},
		{
			table: "channel_pairing_allow_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "channel_pairing_requests",
			kind: "table",
			value: null
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "channel_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "code",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "created_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "last_seen_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "column",
			value: {
				name: "meta_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "channel_pairing_requests",
			kind: "primaryKey",
			value: [
				"channel_key",
				"account_id",
				"request_id"
			]
		},
		{
			table: "channel_pairing_requests",
			kind: "indexes",
			value: 3
		},
		{
			table: "channel_pairing_requests",
			kind: "checks",
			value: 0
		},
		{
			table: "clawhub_promotion_claims",
			kind: "table",
			value: null
		},
		{
			table: "clawhub_promotion_claims",
			kind: "column",
			value: {
				name: "slug",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "clawhub_promotion_claims",
			kind: "column",
			value: {
				name: "provider",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "clawhub_promotion_claims",
			kind: "column",
			value: {
				name: "model_keys_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "clawhub_promotion_claims",
			kind: "column",
			value: {
				name: "ends_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "clawhub_promotion_claims",
			kind: "column",
			value: {
				name: "claimed_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "clawhub_promotion_claims",
			kind: "primaryKey",
			value: ["slug"]
		},
		{
			table: "clawhub_promotion_claims",
			kind: "indexes",
			value: 1
		},
		{
			table: "clawhub_promotion_claims",
			kind: "checks",
			value: 0
		},
		{
			table: "config_health_entries",
			kind: "table",
			value: null
		},
		{
			table: "config_health_entries",
			kind: "column",
			value: {
				name: "config_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "config_health_entries",
			kind: "column",
			value: {
				name: "last_known_good_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "config_health_entries",
			kind: "column",
			value: {
				name: "last_promoted_good_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "config_health_entries",
			kind: "column",
			value: {
				name: "last_observed_suspicious_signature",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "config_health_entries",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "config_health_entries",
			kind: "primaryKey",
			value: ["config_path"]
		},
		{
			table: "config_health_entries",
			kind: "indexes",
			value: 1
		},
		{
			table: "config_health_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "config_machine_state",
			kind: "table",
			value: null
		},
		{
			table: "config_machine_state",
			kind: "column",
			value: {
				name: "state_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "config_machine_state",
			kind: "column",
			value: {
				name: "value_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "config_machine_state",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "config_machine_state",
			kind: "primaryKey",
			value: ["state_key"]
		},
		{
			table: "config_machine_state",
			kind: "indexes",
			value: 1
		},
		{
			table: "config_machine_state",
			kind: "checks",
			value: 0
		},
		{
			table: "config_revision_keys",
			kind: "table",
			value: null
		},
		{
			table: "config_revision_keys",
			kind: "column",
			value: {
				name: "id",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "config_revision_keys",
			kind: "column",
			value: {
				name: "hmac_key",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "config_revision_keys",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "config_revision_keys",
			kind: "indexes",
			value: 1
		},
		{
			table: "config_revision_keys",
			kind: "checks",
			value: 2
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "table",
			value: null
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "column",
			value: {
				name: "job_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "column",
			value: {
				name: "authority_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "column",
			value: {
				name: "authority_input_fingerprint",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "column",
			value: {
				name: "recovery_required",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "primaryKey",
			value: ["store_key", "job_id"]
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "foreignKey",
			value: {
				columns: ["store_key", "job_id"],
				target: "cron_jobs",
				targetColumns: ["store_key", "job_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "indexes",
			value: 1
		},
		{
			table: "cron_job_runtime_authorities",
			kind: "checks",
			value: 2
		},
		{
			table: "cron_job_scratch",
			kind: "table",
			value: null
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "job_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "content",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "revision",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "source_sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "cron_job_scratch",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "cron_job_scratch",
			kind: "primaryKey",
			value: ["store_key", "job_id"]
		},
		{
			table: "cron_job_scratch",
			kind: "indexes",
			value: 2
		},
		{
			table: "cron_job_scratch",
			kind: "checks",
			value: 2
		},
		{
			table: "cron_jobs",
			kind: "table",
			value: null
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "job_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "declaration_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "owner_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "description",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "enabled",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "payload_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "job_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "grant_definition_revision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "grant_definition_generation",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "grant_definition_updated_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "state_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'{}'",
				position: 14
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "runtime_updated_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "schedule_identity",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "sort_order",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 17
			}
		},
		{
			table: "cron_jobs",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "cron_jobs",
			kind: "primaryKey",
			value: ["store_key", "job_id"]
		},
		{
			table: "cron_jobs",
			kind: "indexes",
			value: 2
		},
		{
			table: "cron_jobs",
			kind: "checks",
			value: 0
		},
		{
			table: "cron_run_receipts",
			kind: "table",
			value: null
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "cursor_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "receipt_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "job_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "config_revision",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "request_run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "delivery_attempt_state",
				type: "text",
				nullable: false,
				identity: false,
				default: "'unknown'",
				position: 8
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "owner_pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "owner_start_time",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "started_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "finished_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "cron_run_receipts",
			kind: "column",
			value: {
				name: "error_text",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "cron_run_receipts",
			kind: "primaryKey",
			value: ["receipt_id"]
		},
		{
			table: "cron_run_receipts",
			kind: "indexes",
			value: 4
		},
		{
			table: "cron_run_receipts",
			kind: "checks",
			value: 3
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "table",
			value: null
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "column",
			value: {
				name: "receipt_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "primaryKey",
			value: ["receipt_id"]
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "foreignKey",
			value: {
				columns: ["receipt_id"],
				target: "cron_run_receipts",
				targetColumns: ["receipt_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "indexes",
			value: 1
		},
		{
			table: "cron_run_trigger_state_retirements",
			kind: "checks",
			value: 0
		},
		{
			table: "current_conversation_bindings",
			kind: "table",
			value: null
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "binding_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "binding_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "target_session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "channel",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "conversation_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "parent_conversation_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "conversation_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "target_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "bound_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "metadata_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "record_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "current_conversation_bindings",
			kind: "primaryKey",
			value: ["binding_key"]
		},
		{
			table: "current_conversation_bindings",
			kind: "indexes",
			value: 4
		},
		{
			table: "current_conversation_bindings",
			kind: "checks",
			value: 0
		},
		{
			table: "delivery_queue_entries",
			kind: "table",
			value: null
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "queue_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "entry_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "channel",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "target",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "retry_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 9
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "last_attempt_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "last_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "recovery_state",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "platform_send_started_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "entry_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "retention_id_prefix",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "retention_max_age_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "retention_max_entries",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "enqueued_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "column",
			value: {
				name: "failed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "delivery_queue_entries",
			kind: "primaryKey",
			value: ["queue_name", "id"]
		},
		{
			table: "delivery_queue_entries",
			kind: "indexes",
			value: 6
		},
		{
			table: "delivery_queue_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "device_bootstrap_tokens",
			kind: "table",
			value: null
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "token_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "token",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "setup_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "ts",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "public_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "profile_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "redeemed_profile_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "pending_profile_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "issued_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "column",
			value: {
				name: "last_used_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "device_bootstrap_tokens",
			kind: "primaryKey",
			value: ["token_key"]
		},
		{
			table: "device_bootstrap_tokens",
			kind: "indexes",
			value: 2
		},
		{
			table: "device_bootstrap_tokens",
			kind: "checks",
			value: 0
		},
		{
			table: "device_pair_setup_completions",
			kind: "table",
			value: null
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "setup_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "device_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "access",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "completed_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "delivery_state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "column",
			value: {
				name: "retain_until_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "device_pair_setup_completions",
			kind: "primaryKey",
			value: ["setup_id"]
		},
		{
			table: "device_pair_setup_completions",
			kind: "indexes",
			value: 1
		},
		{
			table: "device_pair_setup_completions",
			kind: "checks",
			value: 1
		},
		{
			table: "device_pairing_join_codes",
			kind: "table",
			value: null
		},
		{
			table: "device_pairing_join_codes",
			kind: "column",
			value: {
				name: "shortcode",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "device_pairing_join_codes",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "device_pairing_join_codes",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "device_pairing_join_codes",
			kind: "column",
			value: {
				name: "expires_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "device_pairing_join_codes",
			kind: "indexes",
			value: 0
		},
		{
			table: "device_pairing_join_codes",
			kind: "checks",
			value: 0
		},
		{
			table: "device_pairing_paired",
			kind: "table",
			value: null
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "public_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "display_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "operator_label",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "platform",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "device_family",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "client_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "client_mode",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "browser_origin",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "role",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "roles_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "scopes_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "approved_scopes_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "remote_ip",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "tokens_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "approved_via",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "node_surface_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "pending_node_surface_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "approved_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "last_seen_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "device_pairing_paired",
			kind: "column",
			value: {
				name: "last_seen_reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "device_pairing_paired",
			kind: "primaryKey",
			value: ["device_id"]
		},
		{
			table: "device_pairing_paired",
			kind: "indexes",
			value: 2
		},
		{
			table: "device_pairing_paired",
			kind: "checks",
			value: 0
		},
		{
			table: "device_pairing_pending",
			kind: "table",
			value: null
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "public_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "display_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "platform",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "device_family",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "client_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "client_mode",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "browser_origin",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "role",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "roles_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "scopes_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "remote_ip",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "silent",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "is_repair",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "ts",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "device_pairing_pending",
			kind: "column",
			value: {
				name: "refreshed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "device_pairing_pending",
			kind: "primaryKey",
			value: ["request_id"]
		},
		{
			table: "device_pairing_pending",
			kind: "indexes",
			value: 2
		},
		{
			table: "device_pairing_pending",
			kind: "checks",
			value: 0
		},
		{
			table: "diagnostic_events",
			kind: "table",
			value: null
		},
		{
			table: "diagnostic_events",
			kind: "column",
			value: {
				name: "scope",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "diagnostic_events",
			kind: "column",
			value: {
				name: "event_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "diagnostic_events",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "diagnostic_events",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "diagnostic_events",
			kind: "column",
			value: {
				name: "sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 5
			}
		},
		{
			table: "diagnostic_events",
			kind: "primaryKey",
			value: ["scope", "event_key"]
		},
		{
			table: "diagnostic_events",
			kind: "indexes",
			value: 2
		},
		{
			table: "diagnostic_events",
			kind: "checks",
			value: 0
		},
		{
			table: "exec_approvals_config",
			kind: "table",
			value: null
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "config_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "raw_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "socket_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "has_socket_token",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "default_security",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "default_ask",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "default_ask_fallback",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "auto_allow_skills",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "agent_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "allowlist_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "exec_approvals_config",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "exec_approvals_config",
			kind: "primaryKey",
			value: ["config_key"]
		},
		{
			table: "exec_approvals_config",
			kind: "indexes",
			value: 1
		},
		{
			table: "exec_approvals_config",
			kind: "checks",
			value: 0
		},
		{
			table: "execution_decision_facts",
			kind: "table",
			value: null
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "cursor_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "receipt_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "context_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "action_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "action_family",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "decision_outcome",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "coverage_state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "reason_code",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "owner",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "source_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "occurred_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "receipt_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "execution_decision_facts",
			kind: "column",
			value: {
				name: "receipt_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "execution_decision_facts",
			kind: "primaryKey",
			value: ["receipt_id"]
		},
		{
			table: "execution_decision_facts",
			kind: "unique",
			value: ["occurred_at", "receipt_id"]
		},
		{
			table: "execution_decision_facts",
			kind: "indexes",
			value: 5
		},
		{
			table: "execution_decision_facts",
			kind: "checks",
			value: 14
		},
		{
			table: "execution_identity_contexts",
			kind: "table",
			value: null
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "context_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "coverage_state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "context_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "column",
			value: {
				name: "context_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "execution_identity_contexts",
			kind: "primaryKey",
			value: ["context_id"]
		},
		{
			table: "execution_identity_contexts",
			kind: "unique",
			value: ["execution_id"]
		},
		{
			table: "execution_identity_contexts",
			kind: "unique",
			value: ["created_at", "context_id"]
		},
		{
			table: "execution_identity_contexts",
			kind: "indexes",
			value: 4
		},
		{
			table: "execution_identity_contexts",
			kind: "checks",
			value: 7
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "table",
			value: null
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "column",
			value: {
				name: "owner_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "column",
			value: {
				name: "owner_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "column",
			value: {
				name: "context_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "primaryKey",
			value: ["owner_kind", "owner_id"]
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "indexes",
			value: 1
		},
		{
			table: "execution_owner_lifecycle_bindings",
			kind: "checks",
			value: 0
		},
		{
			table: "flow_runs",
			kind: "table",
			value: null
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "flow_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "shape",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "sync_mode",
				type: "text",
				nullable: false,
				identity: false,
				default: "'managed'",
				position: 3
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "owner_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "requester_origin_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "controller_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "revision",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 7
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "notify_policy",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "goal",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "current_step",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "blocked_task_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "blocked_summary",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "state_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "wait_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "cancel_requested_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "flow_runs",
			kind: "column",
			value: {
				name: "ended_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "flow_runs",
			kind: "primaryKey",
			value: ["flow_id"]
		},
		{
			table: "flow_runs",
			kind: "indexes",
			value: 4
		},
		{
			table: "flow_runs",
			kind: "checks",
			value: 0
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "table",
			value: null
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "boot_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "started_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "completed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "outcome",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "startup_reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "column",
			value: {
				name: "reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "primaryKey",
			value: ["boot_id"]
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "indexes",
			value: 2
		},
		{
			table: "gateway_boot_lifecycle",
			kind: "checks",
			value: 0
		},
		{
			table: "gateway_restart_handoff",
			kind: "table",
			value: null
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "handoff_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "intent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "process_instance_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "restart_trace_started_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "restart_trace_last_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "restart_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "supervisor_mode",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "gateway_restart_handoff",
			kind: "primaryKey",
			value: ["handoff_key"]
		},
		{
			table: "gateway_restart_handoff",
			kind: "indexes",
			value: 2
		},
		{
			table: "gateway_restart_handoff",
			kind: "checks",
			value: 0
		},
		{
			table: "gateway_restart_intent",
			kind: "table",
			value: null
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "intent_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "force",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "wait_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "gateway_restart_intent",
			kind: "primaryKey",
			value: ["intent_key"]
		},
		{
			table: "gateway_restart_intent",
			kind: "indexes",
			value: 1
		},
		{
			table: "gateway_restart_intent",
			kind: "checks",
			value: 0
		},
		{
			table: "gateway_restart_sentinel",
			kind: "table",
			value: null
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "sentinel_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "ts",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "thread_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "delivery_channel",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "delivery_to",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "delivery_account_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "message",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "continuation_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "doctor_hint",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "stats_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "gateway_restart_sentinel",
			kind: "primaryKey",
			value: ["sentinel_key"]
		},
		{
			table: "gateway_restart_sentinel",
			kind: "indexes",
			value: 2
		},
		{
			table: "gateway_restart_sentinel",
			kind: "checks",
			value: 0
		},
		{
			table: "github_personal_publication_requests",
			kind: "table",
			value: null
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "owner_profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "connection_generation",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "idempotency_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "request_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "worktree_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "repository_fingerprint",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "identity_source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "identity_profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "identity_account_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "identity_login",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "title",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "body",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "gateway_instance_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "last_effect",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "effect_state",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "push_repository",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "repository",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "base_branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "source_head_commit",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "source_index_tree",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "workspace_tree",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "pull_request_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "error_code",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "next_action",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 32
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 33
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 34
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "reported_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 35
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "column",
			value: {
				name: "draft",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 36
			}
		},
		{
			table: "github_personal_publication_requests",
			kind: "primaryKey",
			value: ["request_id"]
		},
		{
			table: "github_personal_publication_requests",
			kind: "unique",
			value: [
				"owner_profile_id",
				"session_id",
				"idempotency_key"
			]
		},
		{
			table: "github_personal_publication_requests",
			kind: "indexes",
			value: 4
		},
		{
			table: "github_personal_publication_requests",
			kind: "checks",
			value: 37
		},
		{
			table: "github_publication_requests",
			kind: "table",
			value: null
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "idempotency_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "request_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "worktree_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "repository_fingerprint",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "claim_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "identity_source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "identity_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "identity_account_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "identity_login",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "title",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "body",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "gateway_instance_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "repository",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "base_branch",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "source_head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "source_index_tree",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "workspace_tree",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "pull_request_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "error_code",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "next_action",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 32
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 33
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "reported_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 34
			}
		},
		{
			table: "github_publication_requests",
			kind: "column",
			value: {
				name: "draft",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 35
			}
		},
		{
			table: "github_publication_requests",
			kind: "primaryKey",
			value: ["request_id"]
		},
		{
			table: "github_publication_requests",
			kind: "unique",
			value: ["session_id", "idempotency_key"]
		},
		{
			table: "github_publication_requests",
			kind: "indexes",
			value: 3
		},
		{
			table: "github_publication_requests",
			kind: "checks",
			value: 9
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "table",
			value: null
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "column",
			value: {
				name: "publication_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "column",
			value: {
				name: "lifecycle_revision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "column",
			value: {
				name: "requester_authority_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "primaryKey",
			value: ["publication_kind", "request_id"]
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "indexes",
			value: 1
		},
		{
			table: "github_publication_session_lifecycles",
			kind: "checks",
			value: 1
		},
		{
			table: "github_repository_publication_requests",
			kind: "table",
			value: null
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "request_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "owner_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "connection_generation",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "idempotency_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "request_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "session_lifecycle_revision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "requester_authority_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "workspace_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "checkpoint_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "checkpoint_digest",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "claim_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "identity_source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "identity_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "identity_account_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "identity_login",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "title",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "body",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "gateway_instance_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "last_effect",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "effect_state",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "push_repository",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "repository",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 32
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "base_branch",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 33
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "source_head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 34
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "source_index_tree",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 35
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "workspace_tree",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 36
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "previous_head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 37
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "pushed_head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 38
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "head_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 39
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "pull_request_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 40
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "error_code",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 41
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "next_action",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 42
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 43
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 44
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "reported_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 45
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "column",
			value: {
				name: "draft",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 46
			}
		},
		{
			table: "github_repository_publication_requests",
			kind: "primaryKey",
			value: ["request_id"]
		},
		{
			table: "github_repository_publication_requests",
			kind: "indexes",
			value: 3
		},
		{
			table: "github_repository_publication_requests",
			kind: "checks",
			value: 7
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "table",
			value: null
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "column",
			value: {
				name: "worktree_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "column",
			value: {
				name: "node_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "primaryKey",
			value: ["worktree_id", "path"]
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "foreignKey",
			value: {
				columns: ["worktree_id"],
				target: "local_workspace_projections",
				targetColumns: ["worktree_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "indexes",
			value: 1
		},
		{
			table: "local_workspace_manifest_nodes",
			kind: "checks",
			value: 0
		},
		{
			table: "local_workspace_projections",
			kind: "table",
			value: null
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "worktree_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "lifecycle_revision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "projection_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "base_commit",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "source_paths_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "baseline_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "baseline_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "pending_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "pending_target",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "paused_runtimes_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "journal_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "journal_pack",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "revision",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 16
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "checkpoint_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "tree_root_digest",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "source_paths_digest",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "canonical_fingerprints",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "local_workspace_projections",
			kind: "column",
			value: {
				name: "projection_fingerprints",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "local_workspace_projections",
			kind: "primaryKey",
			value: ["worktree_id"]
		},
		{
			table: "local_workspace_projections",
			kind: "unique",
			value: ["projection_path"]
		},
		{
			table: "local_workspace_projections",
			kind: "indexes",
			value: 2
		},
		{
			table: "local_workspace_projections",
			kind: "checks",
			value: 5
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "table",
			value: null
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "column",
			value: {
				name: "path_digest",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "column",
			value: {
				name: "paths_zstd",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "column",
			value: {
				name: "sweep_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "primaryKey",
			value: ["path_digest"]
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "indexes",
			value: 1
		},
		{
			table: "local_workspace_source_path_sets",
			kind: "checks",
			value: 1
		},
		{
			table: "local_workspace_tree_packs",
			kind: "table",
			value: null
		},
		{
			table: "local_workspace_tree_packs",
			kind: "column",
			value: {
				name: "tree_digest",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "local_workspace_tree_packs",
			kind: "column",
			value: {
				name: "records_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "local_workspace_tree_packs",
			kind: "column",
			value: {
				name: "children_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "local_workspace_tree_packs",
			kind: "column",
			value: {
				name: "sweep_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "local_workspace_tree_packs",
			kind: "primaryKey",
			value: ["tree_digest"]
		},
		{
			table: "local_workspace_tree_packs",
			kind: "indexes",
			value: 1
		},
		{
			table: "local_workspace_tree_packs",
			kind: "checks",
			value: 1
		},
		{
			table: "macos_port_guardian_records",
			kind: "table",
			value: null
		},
		{
			table: "macos_port_guardian_records",
			kind: "column",
			value: {
				name: "pid",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "macos_port_guardian_records",
			kind: "column",
			value: {
				name: "port",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "macos_port_guardian_records",
			kind: "column",
			value: {
				name: "command",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "macos_port_guardian_records",
			kind: "column",
			value: {
				name: "mode",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "macos_port_guardian_records",
			kind: "column",
			value: {
				name: "timestamp",
				type: "double precision",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "macos_port_guardian_records",
			kind: "primaryKey",
			value: ["pid"]
		},
		{
			table: "macos_port_guardian_records",
			kind: "indexes",
			value: 2
		},
		{
			table: "macos_port_guardian_records",
			kind: "checks",
			value: 0
		},
		{
			table: "managed_outgoing_image_records",
			kind: "table",
			value: null
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "attachment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "message_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "created_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "updated_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "retention_class",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "alt",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_media_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_media_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_media_subdir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_content_type",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_width",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_height",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_size_bytes",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "original_filename",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "record_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "column",
			value: {
				name: "cleanup_pending",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 18
			}
		},
		{
			table: "managed_outgoing_image_records",
			kind: "primaryKey",
			value: ["attachment_id"]
		},
		{
			table: "managed_outgoing_image_records",
			kind: "indexes",
			value: 5
		},
		{
			table: "managed_outgoing_image_records",
			kind: "checks",
			value: 1
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "table",
			value: null
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "column",
			value: {
				name: "create_time",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "primaryKey",
			value: ["state"]
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "indexes",
			value: 1
		},
		{
			table: "mcp_oauth_pending_authorizations",
			kind: "checks",
			value: 0
		},
		{
			table: "mcp_oauth_stores",
			kind: "table",
			value: null
		},
		{
			table: "mcp_oauth_stores",
			kind: "column",
			value: {
				name: "store_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "mcp_oauth_stores",
			kind: "column",
			value: {
				name: "format_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "mcp_oauth_stores",
			kind: "column",
			value: {
				name: "store_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "mcp_oauth_stores",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "mcp_oauth_stores",
			kind: "primaryKey",
			value: ["store_key"]
		},
		{
			table: "mcp_oauth_stores",
			kind: "indexes",
			value: 1
		},
		{
			table: "mcp_oauth_stores",
			kind: "checks",
			value: 1
		},
		{
			table: "meeting_transcript_sessions",
			kind: "table",
			value: null
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "started_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "started_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "selector",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "export_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "session_slug",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "provider_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "title",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_account_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_guild_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_channel_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_meeting_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_thread_ts",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "source_file_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "stopped_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "metadata_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "metadata_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "export_manifest_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'{}'",
				position: 19
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "export_pending_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'[]'",
				position: 20
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "next_utterance_seq",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 21
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "meeting_transcript_sessions",
			kind: "primaryKey",
			value: ["session_id", "started_at"]
		},
		{
			table: "meeting_transcript_sessions",
			kind: "unique",
			value: ["selector"]
		},
		{
			table: "meeting_transcript_sessions",
			kind: "indexes",
			value: 10
		},
		{
			table: "meeting_transcript_sessions",
			kind: "checks",
			value: 3
		},
		{
			table: "meeting_transcript_summaries",
			kind: "table",
			value: null
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "session_started_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "generated_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "summary_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "overview",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "markdown",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "column",
			value: {
				name: "utterance_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "primaryKey",
			value: ["session_id", "session_started_at"]
		},
		{
			table: "meeting_transcript_summaries",
			kind: "foreignKey",
			value: {
				columns: ["session_id", "session_started_at"],
				target: "meeting_transcript_sessions",
				targetColumns: ["session_id", "started_at"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "meeting_transcript_summaries",
			kind: "indexes",
			value: 1
		},
		{
			table: "meeting_transcript_summaries",
			kind: "checks",
			value: 2
		},
		{
			table: "meeting_transcript_utterances",
			kind: "table",
			value: null
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "session_started_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "utterance_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "started_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "ended_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "speaker_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "speaker_label",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "text",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "final",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "column",
			value: {
				name: "metadata_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "primaryKey",
			value: [
				"session_id",
				"session_started_at",
				"sequence"
			]
		},
		{
			table: "meeting_transcript_utterances",
			kind: "foreignKey",
			value: {
				columns: ["session_id", "session_started_at"],
				target: "meeting_transcript_sessions",
				targetColumns: ["session_id", "started_at"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "meeting_transcript_utterances",
			kind: "indexes",
			value: 2
		},
		{
			table: "meeting_transcript_utterances",
			kind: "checks",
			value: 2
		},
		{
			table: "migration_runs",
			kind: "table",
			value: null
		},
		{
			table: "migration_runs",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "migration_runs",
			kind: "column",
			value: {
				name: "started_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "migration_runs",
			kind: "column",
			value: {
				name: "finished_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "migration_runs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "migration_runs",
			kind: "column",
			value: {
				name: "report_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "migration_runs",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "migration_runs",
			kind: "indexes",
			value: 2
		},
		{
			table: "migration_runs",
			kind: "checks",
			value: 0
		},
		{
			table: "migration_sources",
			kind: "table",
			value: null
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "source_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "migration_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "source_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "target_table",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "source_sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "source_size_bytes",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "source_record_count",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "last_run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "imported_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "removed_source",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 11
			}
		},
		{
			table: "migration_sources",
			kind: "column",
			value: {
				name: "report_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "migration_sources",
			kind: "primaryKey",
			value: ["source_key"]
		},
		{
			table: "migration_sources",
			kind: "foreignKey",
			value: {
				columns: ["last_run_id"],
				target: "migration_runs",
				targetColumns: ["id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "migration_sources",
			kind: "indexes",
			value: 3
		},
		{
			table: "migration_sources",
			kind: "checks",
			value: 0
		},
		{
			table: "native_hook_relay_bridges",
			kind: "table",
			value: null
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "relay_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "hostname",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "port",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "token",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "expires_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "native_hook_relay_bridges",
			kind: "primaryKey",
			value: ["relay_id"]
		},
		{
			table: "native_hook_relay_bridges",
			kind: "indexes",
			value: 2
		},
		{
			table: "native_hook_relay_bridges",
			kind: "checks",
			value: 0
		},
		{
			table: "node_worker_launch_boots",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_launch_boots",
			kind: "column",
			value: {
				name: "launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_launch_boots",
			kind: "column",
			value: {
				name: "boot_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_launch_boots",
			kind: "primaryKey",
			value: ["launch_id"]
		},
		{
			table: "node_worker_launch_boots",
			kind: "foreignKey",
			value: {
				columns: ["launch_id"],
				target: "node_worker_launches",
				targetColumns: ["launch_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "node_worker_launch_boots",
			kind: "indexes",
			value: 1
		},
		{
			table: "node_worker_launch_boots",
			kind: "checks",
			value: 1
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "column",
			value: {
				name: "launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "column",
			value: {
				name: "cleanup_mode",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "column",
			value: {
				name: "lineage_settled",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "primaryKey",
			value: ["launch_id"]
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "foreignKey",
			value: {
				columns: ["launch_id"],
				target: "node_worker_launches",
				targetColumns: ["launch_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "indexes",
			value: 1
		},
		{
			table: "node_worker_launch_cleanup",
			kind: "checks",
			value: 2
		},
		{
			table: "node_worker_launch_containers",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_launch_containers",
			kind: "column",
			value: {
				name: "launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_launch_containers",
			kind: "column",
			value: {
				name: "container_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_launch_containers",
			kind: "primaryKey",
			value: ["launch_id"]
		},
		{
			table: "node_worker_launch_containers",
			kind: "indexes",
			value: 1
		},
		{
			table: "node_worker_launch_containers",
			kind: "checks",
			value: 0
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "column",
			value: {
				name: "launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "column",
			value: {
				name: "scope_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "column",
			value: {
				name: "descendants_reaped",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "primaryKey",
			value: ["launch_id"]
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "foreignKey",
			value: {
				columns: ["launch_id"],
				target: "node_worker_launches",
				targetColumns: ["launch_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "indexes",
			value: 1
		},
		{
			table: "node_worker_launch_process_scopes",
			kind: "checks",
			value: 2
		},
		{
			table: "node_worker_launches",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "plan_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "gateway_namespace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "supervisor_pid",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "supervisor_start_time",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "worker_pid",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "worker_start_time",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "result_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "error_text",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "completed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "node_worker_launches",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "node_worker_launches",
			kind: "primaryKey",
			value: ["launch_id"]
		},
		{
			table: "node_worker_launches",
			kind: "indexes",
			value: 2
		},
		{
			table: "node_worker_launches",
			kind: "checks",
			value: 20
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "preparation_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "cache_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "gateway_namespace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "workspace_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "home_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "source_manifest_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "prepared_manifest_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "bound_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "column",
			value: {
				name: "retired_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "primaryKey",
			value: ["preparation_key"]
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "unique",
			value: ["workspace_dir"]
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "indexes",
			value: 2
		},
		{
			table: "node_worker_prepared_workspaces",
			kind: "checks",
			value: 15
		},
		{
			table: "node_worker_turns",
			kind: "table",
			value: null
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "turn_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "owner_launch_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "plan_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "result_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "error_text",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "completed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "node_worker_turns",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "node_worker_turns",
			kind: "primaryKey",
			value: ["turn_id"]
		},
		{
			table: "node_worker_turns",
			kind: "foreignKey",
			value: {
				columns: ["owner_launch_id"],
				target: "node_worker_launches",
				targetColumns: ["launch_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "node_worker_turns",
			kind: "indexes",
			value: 3
		},
		{
			table: "node_worker_turns",
			kind: "checks",
			value: 10
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "table",
			value: null
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "feed_url",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "body",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "status",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "etag",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "last_modified",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "checksum",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "saved_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "trust_mode",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "trust_key_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "trust_signature_count",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "trust_threshold",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "trust_verified_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "primaryKey",
			value: ["feed_url"]
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "indexes",
			value: 2
		},
		{
			table: "official_external_plugin_catalog_snapshots",
			kind: "checks",
			value: 0
		},
		{
			table: "operator_approval_execution_identities",
			kind: "table",
			value: null
		},
		{
			table: "operator_approval_execution_identities",
			kind: "column",
			value: {
				name: "approval_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "operator_approval_execution_identities",
			kind: "column",
			value: {
				name: "source_context_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "operator_approval_execution_identities",
			kind: "column",
			value: {
				name: "source_execution_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "operator_approval_execution_identities",
			kind: "primaryKey",
			value: ["approval_id"]
		},
		{
			table: "operator_approval_execution_identities",
			kind: "foreignKey",
			value: {
				columns: ["approval_id"],
				target: "operator_approvals",
				targetColumns: ["approval_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "operator_approval_execution_identities",
			kind: "indexes",
			value: 1
		},
		{
			table: "operator_approval_execution_identities",
			kind: "checks",
			value: 2
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "table",
			value: null
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "column",
			value: {
				name: "grant_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "column",
			value: {
				name: "job_definition_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "primaryKey",
			value: ["grant_id"]
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "foreignKey",
			value: {
				columns: ["grant_id"],
				target: "operator_approval_standing_grants",
				targetColumns: ["grant_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "indexes",
			value: 1
		},
		{
			table: "operator_approval_standing_grant_generations",
			kind: "checks",
			value: 1
		},
		{
			table: "operator_approval_standing_grants",
			kind: "table",
			value: null
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "grant_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "minted_by_approval_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "cron_job_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "job_config_revision",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "operation_binding",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "expires_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "revoked_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "revoked_by",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "last_used_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "column",
			value: {
				name: "use_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 12
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "primaryKey",
			value: ["grant_id"]
		},
		{
			table: "operator_approval_standing_grants",
			kind: "foreignKey",
			value: {
				columns: ["minted_by_approval_id"],
				target: "operator_approvals",
				targetColumns: ["approval_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "operator_approval_standing_grants",
			kind: "indexes",
			value: 2
		},
		{
			table: "operator_approval_standing_grants",
			kind: "checks",
			value: 6
		},
		{
			table: "operator_approvals",
			kind: "table",
			value: null
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "cursor_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "approval_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "resolution_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "presentation_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "requested_by_device_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "requested_by_client_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "requested_by_device_token_auth",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 9
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "reviewer_device_ids_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_tool_call_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "source_tool_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "audience_session_keys_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "runtime_epoch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "expires_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "decision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "terminal_reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "resolved_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "resolver_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "resolver_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "consumed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "operator_approvals",
			kind: "column",
			value: {
				name: "consumed_by",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "operator_approvals",
			kind: "primaryKey",
			value: ["approval_id"]
		},
		{
			table: "operator_approvals",
			kind: "indexes",
			value: 8
		},
		{
			table: "operator_approvals",
			kind: "checks",
			value: 16
		},
		{
			table: "outbound_media_provenance",
			kind: "table",
			value: null
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "realpath",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "sha256",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "outbound_media_provenance",
			kind: "primaryKey",
			value: ["realpath"]
		},
		{
			table: "outbound_media_provenance",
			kind: "indexes",
			value: 1
		},
		{
			table: "outbound_media_provenance",
			kind: "checks",
			value: 0
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "table",
			value: null
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "column",
			value: {
				name: "event_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "column",
			value: {
				name: "context_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "primaryKey",
			value: ["event_id"]
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "foreignKey",
			value: {
				columns: ["event_id"],
				target: "audit_events",
				targetColumns: ["event_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "indexes",
			value: 2
		},
		{
			table: "outbound_message_execution_bindings",
			kind: "checks",
			value: 3
		},
		{
			table: "outbound_message_progress",
			kind: "table",
			value: null
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "sequence",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "progress_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "source_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "source_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "schema_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "occurred_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "action",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "outcome",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "actor_type",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "actor_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "context_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "execution_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "channel",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "conversation_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "duration_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "account_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "conversation_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "outbound_message_progress",
			kind: "column",
			value: {
				name: "target_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "outbound_message_progress",
			kind: "primaryKey",
			value: ["sequence"]
		},
		{
			table: "outbound_message_progress",
			kind: "unique",
			value: ["progress_id"]
		},
		{
			table: "outbound_message_progress",
			kind: "unique",
			value: ["source_id"]
		},
		{
			table: "outbound_message_progress",
			kind: "unique",
			value: ["occurred_at", "progress_id"]
		},
		{
			table: "outbound_message_progress",
			kind: "indexes",
			value: 6
		},
		{
			table: "outbound_message_progress",
			kind: "checks",
			value: 14
		},
		{
			table: "plugin_binding_approvals",
			kind: "table",
			value: null
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "plugin_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "channel",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "account_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "plugin_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "plugin_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "column",
			value: {
				name: "approved_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "plugin_binding_approvals",
			kind: "primaryKey",
			value: [
				"plugin_root",
				"channel",
				"account_id"
			]
		},
		{
			table: "plugin_binding_approvals",
			kind: "indexes",
			value: 2
		},
		{
			table: "plugin_binding_approvals",
			kind: "checks",
			value: 0
		},
		{
			table: "plugin_blob_entries",
			kind: "table",
			value: null
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "plugin_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "namespace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "entry_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "metadata_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "blob",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "plugin_blob_entries",
			kind: "primaryKey",
			value: [
				"plugin_id",
				"namespace",
				"entry_key"
			]
		},
		{
			table: "plugin_blob_entries",
			kind: "indexes",
			value: 3
		},
		{
			table: "plugin_blob_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "plugin_state_entries",
			kind: "table",
			value: null
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "plugin_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "namespace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "entry_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "value_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "plugin_state_entries",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "plugin_state_entries",
			kind: "primaryKey",
			value: [
				"plugin_id",
				"namespace",
				"entry_key"
			]
		},
		{
			table: "plugin_state_entries",
			kind: "indexes",
			value: 3
		},
		{
			table: "plugin_state_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "projects",
			kind: "table",
			value: null
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "display_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "repo_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "origin_url",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "projects",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "projects",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "projects",
			kind: "indexes",
			value: 1
		},
		{
			table: "projects",
			kind: "checks",
			value: 1
		},
		{
			table: "sandbox_persistent_execs",
			kind: "table",
			value: null
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "owner_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "source_identity",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "attempt_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "owner_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "backend_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "backend_target_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "workspace_binding_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "container_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "container_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "container_started_at",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "revision",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "phase",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "receipt_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "sandbox_persistent_execs",
			kind: "primaryKey",
			value: ["owner_key"]
		},
		{
			table: "sandbox_persistent_execs",
			kind: "unique",
			value: ["attempt_id"]
		},
		{
			table: "sandbox_persistent_execs",
			kind: "indexes",
			value: 5
		},
		{
			table: "sandbox_persistent_execs",
			kind: "checks",
			value: 4
		},
		{
			table: "sandbox_registry_entries",
			kind: "table",
			value: null
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "registry_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "container_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "backend_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "runtime_label",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "image",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "last_used_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "config_label_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "config_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "cdp_port",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "no_vnc_port",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "entry_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "sandbox_registry_entries",
			kind: "primaryKey",
			value: ["registry_kind", "container_name"]
		},
		{
			table: "sandbox_registry_entries",
			kind: "indexes",
			value: 4
		},
		{
			table: "sandbox_registry_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "schema_meta",
			kind: "table",
			value: null
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "meta_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "role",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "schema_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "app_version",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "schema_meta",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "schema_meta",
			kind: "primaryKey",
			value: ["meta_key"]
		},
		{
			table: "schema_meta",
			kind: "indexes",
			value: 1
		},
		{
			table: "schema_meta",
			kind: "checks",
			value: 0
		},
		{
			table: "secret_store_entries",
			kind: "table",
			value: null
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "scope_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "scope_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "value",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "updated_by",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "deleted_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "secret_store_entries",
			kind: "column",
			value: {
				name: "allowed_hosts",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "secret_store_entries",
			kind: "primaryKey",
			value: [
				"scope_kind",
				"scope_id",
				"name"
			]
		},
		{
			table: "secret_store_entries",
			kind: "indexes",
			value: 2
		},
		{
			table: "secret_store_entries",
			kind: "checks",
			value: 5
		},
		{
			table: "session_groups",
			kind: "table",
			value: null
		},
		{
			table: "session_groups",
			kind: "column",
			value: {
				name: "name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "session_groups",
			kind: "column",
			value: {
				name: "position",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_groups",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_groups",
			kind: "column",
			value: {
				name: "cwd",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "session_groups",
			kind: "column",
			value: {
				name: "worktree",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "session_groups",
			kind: "primaryKey",
			value: ["name"]
		},
		{
			table: "session_groups",
			kind: "indexes",
			value: 1
		},
		{
			table: "session_groups",
			kind: "checks",
			value: 0
		},
		{
			table: "session_repository_workspaces",
			kind: "table",
			value: null
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "workspace_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "url",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "requested_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "run_setup_script",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 6
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "base_commit",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "base_manifest_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "checkpoint_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "manifest_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "revision",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "session_repository_workspaces",
			kind: "primaryKey",
			value: ["workspace_id"]
		},
		{
			table: "session_repository_workspaces",
			kind: "unique",
			value: ["agent_id", "session_key"]
		},
		{
			table: "session_repository_workspaces",
			kind: "indexes",
			value: 2
		},
		{
			table: "session_repository_workspaces",
			kind: "checks",
			value: 11
		},
		{
			table: "session_state_events",
			kind: "table",
			value: null
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "sequence",
				type: "bigint",
				nullable: false,
				identity: true,
				default: null,
				position: 1
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "dedupe_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "actor_type",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "actor_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "occurred_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "summary",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "session_state_events",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "session_state_events",
			kind: "primaryKey",
			value: ["sequence"]
		},
		{
			table: "session_state_events",
			kind: "unique",
			value: ["dedupe_key"]
		},
		{
			table: "session_state_events",
			kind: "indexes",
			value: 4
		},
		{
			table: "session_state_events",
			kind: "checks",
			value: 0
		},
		{
			table: "session_state_heads",
			kind: "table",
			value: null
		},
		{
			table: "session_state_heads",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "session_state_heads",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_state_heads",
			kind: "column",
			value: {
				name: "last_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_state_heads",
			kind: "column",
			value: {
				name: "pruned_max_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 4
			}
		},
		{
			table: "session_state_heads",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "session_state_heads",
			kind: "primaryKey",
			value: ["session_key", "agent_id"]
		},
		{
			table: "session_state_heads",
			kind: "indexes",
			value: 1
		},
		{
			table: "session_state_heads",
			kind: "checks",
			value: 0
		},
		{
			table: "session_upstream_links",
			kind: "table",
			value: null
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "catalog_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "host_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "thread_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "upstream_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "upstream_ref_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "last_marker_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "last_scanned_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "session_upstream_links",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "session_upstream_links",
			kind: "primaryKey",
			value: ["session_key", "agent_id"]
		},
		{
			table: "session_upstream_links",
			kind: "indexes",
			value: 2
		},
		{
			table: "session_upstream_links",
			kind: "checks",
			value: 0
		},
		{
			table: "session_watch_cursors",
			kind: "table",
			value: null
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "watcher_session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "watcher_store_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "target_session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "last_seen_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 4
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "notified_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 5
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "material_sequence",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 6
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "provenance",
				type: "text",
				nullable: false,
				identity: false,
				default: "'explicit'",
				position: 7
			}
		},
		{
			table: "session_watch_cursors",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "session_watch_cursors",
			kind: "primaryKey",
			value: ["watcher_session_key", "target_session_key"]
		},
		{
			table: "session_watch_cursors",
			kind: "indexes",
			value: 2
		},
		{
			table: "session_watch_cursors",
			kind: "checks",
			value: 1
		},
		{
			table: "skill_library_entries",
			kind: "table",
			value: null
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "skill_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "owner_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "author_profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "slug",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "current_revision",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "shared",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "enabled",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "removed",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "skill_library_entries",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "skill_library_entries",
			kind: "primaryKey",
			value: ["skill_id"]
		},
		{
			table: "skill_library_entries",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_library_entries",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_library_events",
			kind: "table",
			value: null
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "event_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "skill_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "revision",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "action",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "actor_profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_library_events",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_library_events",
			kind: "primaryKey",
			value: ["event_id"]
		},
		{
			table: "skill_library_events",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_library_events",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_library_revisions",
			kind: "table",
			value: null
		},
		{
			table: "skill_library_revisions",
			kind: "column",
			value: {
				name: "skill_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_library_revisions",
			kind: "column",
			value: {
				name: "revision",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_library_revisions",
			kind: "column",
			value: {
				name: "description",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_library_revisions",
			kind: "column",
			value: {
				name: "files_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_library_revisions",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_library_revisions",
			kind: "primaryKey",
			value: ["skill_id", "revision"]
		},
		{
			table: "skill_library_revisions",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_library_revisions",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_library_uploads",
			kind: "table",
			value: null
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "upload_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "owner_profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "slug",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "sha256",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "archive_blob",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "skill_library_uploads",
			kind: "column",
			value: {
				name: "published_skill_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "skill_library_uploads",
			kind: "primaryKey",
			value: ["upload_id"]
		},
		{
			table: "skill_library_uploads",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_library_uploads",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_upload_chunks",
			kind: "table",
			value: null
		},
		{
			table: "skill_upload_chunks",
			kind: "column",
			value: {
				name: "upload_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_upload_chunks",
			kind: "column",
			value: {
				name: "byte_offset",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_upload_chunks",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_upload_chunks",
			kind: "column",
			value: {
				name: "chunk_blob",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_upload_chunks",
			kind: "primaryKey",
			value: ["upload_id", "byte_offset"]
		},
		{
			table: "skill_upload_chunks",
			kind: "foreignKey",
			value: {
				columns: ["upload_id"],
				target: "skill_uploads",
				targetColumns: ["upload_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "skill_upload_chunks",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_upload_chunks",
			kind: "checks",
			value: 3
		},
		{
			table: "skill_uploads",
			kind: "table",
			value: null
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "upload_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "slug",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "force",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "size_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "actual_sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "received_bytes",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "archive_blob",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "committed",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "committed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "skill_uploads",
			kind: "column",
			value: {
				name: "idempotency_key_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "skill_uploads",
			kind: "primaryKey",
			value: ["upload_id"]
		},
		{
			table: "skill_uploads",
			kind: "unique",
			value: ["idempotency_key_hash"]
		},
		{
			table: "skill_uploads",
			kind: "indexes",
			value: 4
		},
		{
			table: "skill_uploads",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_usage",
			kind: "table",
			value: null
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "skill_file",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "skill_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "skill_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "skill_source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "first_used_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "last_used_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "use_count",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "skill_usage",
			kind: "column",
			value: {
				name: "last_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "skill_usage",
			kind: "primaryKey",
			value: ["skill_file"]
		},
		{
			table: "skill_usage",
			kind: "indexes",
			value: 1
		},
		{
			table: "skill_usage",
			kind: "checks",
			value: 0
		},
		{
			table: "skill_workshop_changes",
			kind: "table",
			value: null
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "cursor_id",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "change_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "skill_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "action",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "actor",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "summary",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "version_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "skill_workshop_changes",
			kind: "primaryKey",
			value: ["change_id"]
		},
		{
			table: "skill_workshop_changes",
			kind: "indexes",
			value: 3
		},
		{
			table: "skill_workshop_changes",
			kind: "checks",
			value: 2
		},
		{
			table: "state_leases",
			kind: "table",
			value: null
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "scope",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "lease_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "owner",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "expires_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "heartbeat_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "state_leases",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "state_leases",
			kind: "primaryKey",
			value: ["scope", "lease_key"]
		},
		{
			table: "state_leases",
			kind: "indexes",
			value: 3
		},
		{
			table: "state_leases",
			kind: "checks",
			value: 0
		},
		{
			table: "subagent_runs",
			kind: "table",
			value: null
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "child_session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "controller_session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "controller_store_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "requester_session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "requester_store_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "subagent_runs",
			kind: "column",
			value: {
				name: "payload_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'{}'",
				position: 8
			}
		},
		{
			table: "subagent_runs",
			kind: "primaryKey",
			value: ["run_id"]
		},
		{
			table: "subagent_runs",
			kind: "indexes",
			value: 4
		},
		{
			table: "subagent_runs",
			kind: "checks",
			value: 0
		},
		{
			table: "task_delivery_state",
			kind: "table",
			value: null
		},
		{
			table: "task_delivery_state",
			kind: "column",
			value: {
				name: "task_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "task_delivery_state",
			kind: "column",
			value: {
				name: "requester_origin_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "task_delivery_state",
			kind: "column",
			value: {
				name: "last_notified_event_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "task_delivery_state",
			kind: "primaryKey",
			value: ["task_id"]
		},
		{
			table: "task_delivery_state",
			kind: "foreignKey",
			value: {
				columns: ["task_id"],
				target: "task_runs",
				targetColumns: ["task_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "task_delivery_state",
			kind: "indexes",
			value: 1
		},
		{
			table: "task_delivery_state",
			kind: "checks",
			value: 0
		},
		{
			table: "task_runs",
			kind: "table",
			value: null
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "task_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "runtime",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "task_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "source_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "requester_session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "owner_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "scope_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "child_session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "parent_flow_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "parent_task_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "requester_agent_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "execution_owner_host",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "execution_owner_pid",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "execution_owner_start_identity",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "label",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "task",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "delivery_status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "notify_policy",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "started_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "ended_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "last_event_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "cleanup_after",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 26
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "tool_use_count",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "last_tool_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 28
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "progress_summary",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "terminal_summary",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "terminal_outcome",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 32
			}
		},
		{
			table: "task_runs",
			kind: "column",
			value: {
				name: "detail_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 33
			}
		},
		{
			table: "task_runs",
			kind: "primaryKey",
			value: ["task_id"]
		},
		{
			table: "task_runs",
			kind: "indexes",
			value: 4
		},
		{
			table: "task_runs",
			kind: "checks",
			value: 0
		},
		{
			table: "template_cron_refs",
			kind: "table",
			value: null
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "manifest_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "schema_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "declaration_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "scheduler_job_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "job_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "template_cron_refs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "template_cron_refs",
			kind: "primaryKey",
			value: ["agent_id", "manifest_id"]
		},
		{
			table: "template_cron_refs",
			kind: "unique",
			value: ["declaration_key"]
		},
		{
			table: "template_cron_refs",
			kind: "unique",
			value: ["scheduler_job_id"]
		},
		{
			table: "template_cron_refs",
			kind: "indexes",
			value: 3
		},
		{
			table: "template_cron_refs",
			kind: "checks",
			value: 0
		},
		{
			table: "template_installs",
			kind: "table",
			value: null
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "schema_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "source_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "template_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "template_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "package_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "manifest_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "integrity_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "integrity",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "source_byte_length",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "manifest_schema_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "plan_integrity",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "workspace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "agent_config_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "agent_owned_paths_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "bootstrap_source_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "bootstrap_content_digest",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "added_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "template_installs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "template_installs",
			kind: "primaryKey",
			value: ["agent_id"]
		},
		{
			table: "template_installs",
			kind: "unique",
			value: ["workspace"]
		},
		{
			table: "template_installs",
			kind: "indexes",
			value: 2
		},
		{
			table: "template_installs",
			kind: "checks",
			value: 1
		},
		{
			table: "template_mcp_server_refs",
			kind: "table",
			value: null
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "schema_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "config_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "relationship",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "origin",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "independent_owner",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 7
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "template_mcp_server_refs",
			kind: "primaryKey",
			value: ["agent_id", "name"]
		},
		{
			table: "template_mcp_server_refs",
			kind: "indexes",
			value: 1
		},
		{
			table: "template_mcp_server_refs",
			kind: "checks",
			value: 3
		},
		{
			table: "template_package_refs",
			kind: "table",
			value: null
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_source",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_integrity",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "schema_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "template_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "package_status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "relationship",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "origin",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "independent_owner",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_format",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_detected_format",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_mapped_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_unavailable_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "extension_adapter_identity",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "installed_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "template_package_refs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "template_package_refs",
			kind: "primaryKey",
			value: [
				"agent_id",
				"package_kind",
				"package_source",
				"package_ref",
				"package_version"
			]
		},
		{
			table: "template_package_refs",
			kind: "indexes",
			value: 1
		},
		{
			table: "template_package_refs",
			kind: "checks",
			value: 3
		},
		{
			table: "template_workspace_files",
			kind: "table",
			value: null
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "target_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "schema_version",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "workspace",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "source_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "content_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "template_workspace_files",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "template_workspace_files",
			kind: "primaryKey",
			value: ["agent_id", "target_path"]
		},
		{
			table: "template_workspace_files",
			kind: "indexes",
			value: 1
		},
		{
			table: "template_workspace_files",
			kind: "checks",
			value: 0
		},
		{
			table: "update_runs",
			kind: "table",
			value: null
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "trigger",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "phase",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "origin_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "target_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "before_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "after_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "steps_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "verification_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "repair_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "confirmed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "finished_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "update_runs",
			kind: "column",
			value: {
				name: "downtime_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "update_runs",
			kind: "primaryKey",
			value: ["run_id"]
		},
		{
			table: "update_runs",
			kind: "indexes",
			value: 3
		},
		{
			table: "update_runs",
			kind: "checks",
			value: 11
		},
		{
			table: "user_background_images",
			kind: "table",
			value: null
		},
		{
			table: "user_background_images",
			kind: "column",
			value: {
				name: "profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "user_background_images",
			kind: "column",
			value: {
				name: "asset_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "user_background_images",
			kind: "column",
			value: {
				name: "image",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "user_background_images",
			kind: "column",
			value: {
				name: "width",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "user_background_images",
			kind: "column",
			value: {
				name: "height",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "user_background_images",
			kind: "primaryKey",
			value: ["profile_id"]
		},
		{
			table: "user_background_images",
			kind: "unique",
			value: ["asset_id"]
		},
		{
			table: "user_background_images",
			kind: "foreignKey",
			value: {
				columns: ["profile_id"],
				target: "user_profiles",
				targetColumns: ["id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "user_background_images",
			kind: "indexes",
			value: 2
		},
		{
			table: "user_background_images",
			kind: "checks",
			value: 3
		},
		{
			table: "user_preferences",
			kind: "table",
			value: null
		},
		{
			table: "user_preferences",
			kind: "column",
			value: {
				name: "profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "user_preferences",
			kind: "column",
			value: {
				name: "pref_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "user_preferences",
			kind: "column",
			value: {
				name: "value_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "user_preferences",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "user_preferences",
			kind: "primaryKey",
			value: ["profile_id", "pref_key"]
		},
		{
			table: "user_preferences",
			kind: "indexes",
			value: 1
		},
		{
			table: "user_preferences",
			kind: "checks",
			value: 0
		},
		{
			table: "user_profile_emails",
			kind: "table",
			value: null
		},
		{
			table: "user_profile_emails",
			kind: "column",
			value: {
				name: "email",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "user_profile_emails",
			kind: "column",
			value: {
				name: "profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "user_profile_emails",
			kind: "column",
			value: {
				name: "binding_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "user_profile_emails",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "user_profile_emails",
			kind: "primaryKey",
			value: ["email"]
		},
		{
			table: "user_profile_emails",
			kind: "indexes",
			value: 2
		},
		{
			table: "user_profile_emails",
			kind: "checks",
			value: 0
		},
		{
			table: "user_profile_identities",
			kind: "table",
			value: null
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "provider",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "subject",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "canonical_login",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "verified_email_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "authorization_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "user_profile_identities",
			kind: "column",
			value: {
				name: "authorization_basis_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "user_profile_identities",
			kind: "primaryKey",
			value: ["provider", "subject"]
		},
		{
			table: "user_profile_identities",
			kind: "indexes",
			value: 3
		},
		{
			table: "user_profile_identities",
			kind: "checks",
			value: 0
		},
		{
			table: "user_profiles",
			kind: "table",
			value: null
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "display_name",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "primary_github_account_id",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "avatar",
				type: "bytea",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "avatar_mime",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "avatar_sha256",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "merged_into",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "role",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "user_profiles",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "user_profiles",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "user_profiles",
			kind: "indexes",
			value: 1
		},
		{
			table: "user_profiles",
			kind: "checks",
			value: 0
		},
		{
			table: "web_push_approval_deliveries",
			kind: "table",
			value: null
		},
		{
			table: "web_push_approval_deliveries",
			kind: "column",
			value: {
				name: "approval_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "column",
			value: {
				name: "subscription_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "column",
			value: {
				name: "user_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "column",
			value: {
				name: "prepared_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "primaryKey",
			value: ["approval_id", "subscription_id"]
		},
		{
			table: "web_push_approval_deliveries",
			kind: "foreignKey",
			value: {
				columns: ["subscription_id"],
				target: "web_push_subscriptions",
				targetColumns: ["subscription_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "foreignKey",
			value: {
				columns: ["approval_id"],
				target: "operator_approvals",
				targetColumns: ["approval_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "web_push_approval_deliveries",
			kind: "indexes",
			value: 2
		},
		{
			table: "web_push_approval_deliveries",
			kind: "checks",
			value: 0
		},
		{
			table: "web_push_subscriptions",
			kind: "table",
			value: null
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "endpoint_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "subscription_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "endpoint",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "p256dh",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "auth",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "device_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "user_profile_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "preferences_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "web_push_subscriptions",
			kind: "primaryKey",
			value: ["endpoint_hash"]
		},
		{
			table: "web_push_subscriptions",
			kind: "unique",
			value: ["subscription_id"]
		},
		{
			table: "web_push_subscriptions",
			kind: "indexes",
			value: 3
		},
		{
			table: "web_push_subscriptions",
			kind: "checks",
			value: 0
		},
		{
			table: "worker_environment_credentials",
			kind: "table",
			value: null
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "credential_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "bundle_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "rpc_set_version",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "expires_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "column",
			value: {
				name: "delivered_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "primaryKey",
			value: ["environment_id"]
		},
		{
			table: "worker_environment_credentials",
			kind: "unique",
			value: ["credential_hash"]
		},
		{
			table: "worker_environment_credentials",
			kind: "foreignKey",
			value: {
				columns: ["environment_id"],
				target: "worker_environments",
				targetColumns: ["environment_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_environment_credentials",
			kind: "indexes",
			value: 2
		},
		{
			table: "worker_environment_credentials",
			kind: "checks",
			value: 4
		},
		{
			table: "worker_environment_session_attachments",
			kind: "table",
			value: null
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "session_lifecycle_revision",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "last_used_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "column",
			value: {
				name: "closed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "worker_environment_session_attachments",
			kind: "unique",
			value: ["environment_id"]
		},
		{
			table: "worker_environment_session_attachments",
			kind: "foreignKey",
			value: {
				columns: ["environment_id"],
				target: "worker_environments",
				targetColumns: ["environment_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_environment_session_attachments",
			kind: "indexes",
			value: 3
		},
		{
			table: "worker_environment_session_attachments",
			kind: "checks",
			value: 1
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "table",
			value: null
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "column",
			value: {
				name: "position",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "column",
			value: {
				name: "port",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "primaryKey",
			value: ["environment_id", "position"]
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "unique",
			value: ["environment_id", "port"]
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "foreignKey",
			value: {
				columns: ["environment_id"],
				target: "worker_environments",
				targetColumns: ["environment_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "indexes",
			value: 2
		},
		{
			table: "worker_environment_ssh_fallback_ports",
			kind: "checks",
			value: 2
		},
		{
			table: "worker_environments",
			kind: "table",
			value: null
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "provider_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "profile_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "profile_snapshot_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "last_activated_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "preparation_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "preparation_purpose",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "preparation_demand_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "preparation_expires_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "preparation_consumed_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "provision_operation_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "lease_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "node_setup_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "node_device_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "ssh_host",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "ssh_port",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "ssh_user",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "ssh_host_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "ssh_key_ref_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "desktop_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "bootstrap_bundle_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "bootstrap_openclaw_version",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "bootstrap_protocol_features_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "bootstrap_install_kind",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 25
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 26
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "teardown_terminal_state",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 27
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "attached_session_ids_json",
				type: "text",
				nullable: false,
				identity: false,
				default: "'[]'",
				position: 28
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 29
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 30
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "state_changed_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 31
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "idle_since_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 32
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "destroy_requested_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 33
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "last_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 34
			}
		},
		{
			table: "worker_environments",
			kind: "column",
			value: {
				name: "shared_host",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 35
			}
		},
		{
			table: "worker_environments",
			kind: "primaryKey",
			value: ["environment_id"]
		},
		{
			table: "worker_environments",
			kind: "unique",
			value: ["provision_operation_id"]
		},
		{
			table: "worker_environments",
			kind: "indexes",
			value: 4
		},
		{
			table: "worker_environments",
			kind: "checks",
			value: 5
		},
		{
			table: "worker_inference_turns",
			kind: "table",
			value: null
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "run_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "turn_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "request_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "terminal_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_inference_turns",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_inference_turns",
			kind: "primaryKey",
			value: [
				"session_id",
				"run_epoch",
				"run_id",
				"turn_id"
			]
		},
		{
			table: "worker_inference_turns",
			kind: "foreignKey",
			value: {
				columns: ["environment_id"],
				target: "worker_environments",
				targetColumns: ["environment_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_inference_turns",
			kind: "indexes",
			value: 2
		},
		{
			table: "worker_inference_turns",
			kind: "checks",
			value: 5
		},
		{
			table: "worker_session_placement_moves",
			kind: "table",
			value: null
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "operation_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "source_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "source_environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "source_owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "target_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "target_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "target_machine_class",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "target_os",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "abandon_source",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "last_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "primaryKey",
			value: ["operation_id"]
		},
		{
			table: "worker_session_placement_moves",
			kind: "unique",
			value: ["session_id"]
		},
		{
			table: "worker_session_placement_moves",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "worker_session_placements",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_session_placement_moves",
			kind: "indexes",
			value: 2
		},
		{
			table: "worker_session_placement_moves",
			kind: "checks",
			value: 5
		},
		{
			table: "worker_session_placements",
			kind: "table",
			value: null
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "agent_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "session_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "execution_mode",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "transition_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: "0",
				position: 7
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "active_owner_epoch",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "workspace_base_manifest_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "remote_workspace_dir",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "worker_bundle_hash",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "last_transcript_ack_cursor",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "last_live_event_ack_cursor",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "recovery_error",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "turn_claim_owner",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "turn_claim_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 16
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "turn_claim_run_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 17
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "turn_claim_generation",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 18
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "turn_claim_owner_epoch",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 19
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 20
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 21
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "state_changed_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 22
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "terminal_reason",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 23
			}
		},
		{
			table: "worker_session_placements",
			kind: "column",
			value: {
				name: "terminal_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 24
			}
		},
		{
			table: "worker_session_placements",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "worker_session_placements",
			kind: "indexes",
			value: 4
		},
		{
			table: "worker_session_placements",
			kind: "checks",
			value: 12
		},
		{
			table: "worker_session_tool_operations",
			kind: "table",
			value: null
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "source_session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "source_claim_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "tool_call_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "tool_name",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "request_digest",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "operation_seed",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "child_session_key",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "result_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "gateway_instance_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "primaryKey",
			value: [
				"source_session_id",
				"source_claim_id",
				"tool_call_id"
			]
		},
		{
			table: "worker_session_tool_operations",
			kind: "foreignKey",
			value: {
				columns: ["source_session_id"],
				target: "worker_session_placements",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_session_tool_operations",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_session_tool_operations",
			kind: "checks",
			value: 2
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "table",
			value: null
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "column",
			value: {
				name: "run_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "column",
			value: {
				name: "next_seq",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "primaryKey",
			value: ["session_id", "run_epoch"]
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_transcript_commit_heads",
			kind: "checks",
			value: 3
		},
		{
			table: "worker_transcript_commits",
			kind: "table",
			value: null
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "run_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "seq",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "request_hash",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "state",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "result_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "primaryKey",
			value: [
				"session_id",
				"run_epoch",
				"seq"
			]
		},
		{
			table: "worker_transcript_commits",
			kind: "foreignKey",
			value: {
				columns: ["session_id", "run_epoch"],
				target: "worker_transcript_commit_heads",
				targetColumns: ["session_id", "run_epoch"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_transcript_commits",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_transcript_commits",
			kind: "checks",
			value: 6
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "table",
			value: null
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "claim_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "tool_names_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "worker_session_placements",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_turn_tool_authorities",
			kind: "checks",
			value: 2
		},
		{
			table: "worker_workspace_pending_results",
			kind: "table",
			value: null
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "claim_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "run_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "gateway_instance_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "recovery_requested_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "workspace_accepted_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "staged_result_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "repository_workspace_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "worker_workspace_pending_results",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "worker_session_placements",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_workspace_pending_results",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_workspace_pending_results",
			kind: "checks",
			value: 2
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "table",
			value: null
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "session_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "environment_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "owner_epoch",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "placement_generation",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "base_manifest_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "current_manifest_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "plan_json",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "base_pack",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "column",
			value: {
				name: "created_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "primaryKey",
			value: ["session_id"]
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "foreignKey",
			value: {
				columns: ["session_id"],
				target: "worker_session_placements",
				targetColumns: ["session_id"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "indexes",
			value: 1
		},
		{
			table: "worker_workspace_reconciliations",
			kind: "checks",
			value: 3
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "table",
			value: null
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "column",
			value: {
				name: "workspace_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "column",
			value: {
				name: "filename",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "column",
			value: {
				name: "sha256",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "primaryKey",
			value: ["workspace_key", "filename"]
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "foreignKey",
			value: {
				columns: ["workspace_key"],
				target: "workspace_setup_state",
				targetColumns: ["workspace_key"],
				onUpdate: "NO ACTION",
				onDelete: "CASCADE",
				deferrable: false,
				deferred: false
			}
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "indexes",
			value: 1
		},
		{
			table: "workspace_generated_bootstrap_hashes",
			kind: "checks",
			value: 0
		},
		{
			table: "workspace_path_aliases",
			kind: "table",
			value: null
		},
		{
			table: "workspace_path_aliases",
			kind: "column",
			value: {
				name: "alias_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "workspace_path_aliases",
			kind: "column",
			value: {
				name: "alias_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "workspace_path_aliases",
			kind: "column",
			value: {
				name: "workspace_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "workspace_path_aliases",
			kind: "column",
			value: {
				name: "workspace_path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "workspace_path_aliases",
			kind: "column",
			value: {
				name: "updated_at_ms",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "workspace_path_aliases",
			kind: "primaryKey",
			value: ["alias_key"]
		},
		{
			table: "workspace_path_aliases",
			kind: "indexes",
			value: 2
		},
		{
			table: "workspace_path_aliases",
			kind: "checks",
			value: 0
		},
		{
			table: "workspace_setup_state",
			kind: "table",
			value: null
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "workspace_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "workspace_path",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "version",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "bootstrap_seeded_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "setup_completed_at",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "updated_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "attested_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "workspace_setup_state",
			kind: "column",
			value: {
				name: "attestation_updated_at_ms",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "workspace_setup_state",
			kind: "primaryKey",
			value: ["workspace_key"]
		},
		{
			table: "workspace_setup_state",
			kind: "indexes",
			value: 2
		},
		{
			table: "workspace_setup_state",
			kind: "checks",
			value: 1
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "table",
			value: null
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "column",
			value: {
				name: "worktree_id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "column",
			value: {
				name: "chunk_index",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "column",
			value: {
				name: "data",
				type: "bytea",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "primaryKey",
			value: [
				"worktree_id",
				"path",
				"chunk_index"
			]
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "indexes",
			value: 1
		},
		{
			table: "worktree_provisioned_file_chunks",
			kind: "checks",
			value: 1
		},
		{
			table: "worktree_templates",
			kind: "table",
			value: null
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "cache_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "repo_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "common_dir",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "worktree_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "backend",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "source_commit",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "content_key",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "status",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worktree_templates",
			kind: "column",
			value: {
				name: "last_used_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worktree_templates",
			kind: "primaryKey",
			value: ["cache_key"]
		},
		{
			table: "worktree_templates",
			kind: "unique",
			value: ["id"]
		},
		{
			table: "worktree_templates",
			kind: "indexes",
			value: 2
		},
		{
			table: "worktree_templates",
			kind: "checks",
			value: 1
		},
		{
			table: "worktrees",
			kind: "table",
			value: null
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "id",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 1
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "repo_fingerprint",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 2
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "repo_root",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 3
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "path",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 4
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "branch",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 5
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "base_ref",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 6
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "owner_kind",
				type: "text",
				nullable: false,
				identity: false,
				default: null,
				position: 7
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "owner_id",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 8
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "snapshot_ref",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 9
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "provisioned_paths_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 10
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "created_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 11
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "last_active_at",
				type: "bigint",
				nullable: false,
				identity: false,
				default: null,
				position: 12
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "removed_at",
				type: "bigint",
				nullable: true,
				identity: false,
				default: null,
				position: 13
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "run_end_cleanup_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 14
			}
		},
		{
			table: "worktrees",
			kind: "column",
			value: {
				name: "gc_protection_json",
				type: "text",
				nullable: true,
				identity: false,
				default: null,
				position: 15
			}
		},
		{
			table: "worktrees",
			kind: "primaryKey",
			value: ["id"]
		},
		{
			table: "worktrees",
			kind: "indexes",
			value: 3
		},
		{
			table: "worktrees",
			kind: "checks",
			value: 1
		}
	]
};
//#endregion
//#region src/state/openclaw-state-db-engine.ts
const recovery = "Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.";
function isStatePostgres() {
	return stateEngineInput() !== void 0;
}
function assertStateFileSnapshotAllowed() {
	if (stateEngineInput()) requireNativeDatabaseFile("postgres", "file-snapshot");
}
function inspectStateSqlite(e) {
	const t = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e);
	return {
		hasEngineAnchor: t.tables.has("openclaw_engine_anchor"),
		hasExistingData: [
			...t.tables,
			...t.views,
			...t.triggers.keys()
		].some((e) => e !== "openclaw_engine_anchor" && !e.startsWith("sqlite_"))
	};
}
function admitStatePostgres(e, t) {
	if (!t && getStateRuntimeSchemaAdmission(e)?.startupReady) return;
	const n = withPostgresSchemaAdmissionRetry(e, () => {
		const t = getPostgresPhysicalFacts(e);
		if (!t) throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${recovery}`);
		return t;
	});
	const r = new Set(n.catalog.filter((e) => e.kind === "table").map((e) => e.table));
	const i = new Set(statePostgresRuntime.fragments.flatMap((e) => e.tables.some((e) => r.has(e)) ? [] : e.tables));
	if (n.version === 36) assertPostgresCatalog(n.catalog.filter((e) => !e.kind.endsWith("Definition") && e.table !== "openclaw_schema_meta"), statePostgresRuntime.expectedCatalog.filter((e) => !i.has(e.table)));
	if (t) {
		const t = Date.now();
		e.prepare(`INSERT INTO schema_meta
        (meta_key, role, schema_version, agent_id, app_version, created_at, updated_at)
        VALUES ('primary', 'global', ?, NULL, ?, ?, ?)`).run(36, VERSION, t, t);
		writeStateSchemaContentVersion(e);
	}
	const a = e.prepare("SELECT schema_version, role, agent_id FROM schema_meta WHERE meta_key = 'primary'").get();
	const o = e.prepare("SELECT value_json FROM config_machine_state WHERE state_key = 'state.schema.contentVersion'").get();
	let s;
	try {
		const e = o?.value_json;
		if (e !== void 0 && e !== null && typeof e !== "string") throw new Error("Invalid PostgreSQL state content marker");
		s = parseStateSchemaContentVersion(e);
	} catch {
		throw new Error("PostgreSQL state metadata mismatch. " + recovery);
	}
	if (a?.schema_version !== n.version || a.role !== "global" || a.agent_id !== null || s > n.version) throw new Error(`PostgreSQL state metadata mismatch. ${recovery}`);
	publishStateSchemaVersionAdmission(e, {
		userVersion: n.version,
		contentVersion: n.version
	});
	publishStateRuntimeSchemaAdmission(e, true);
}
const statePostgresSchema = {
	postgres: statePostgresRuntime.eagerSql,
	postgresFragments: statePostgresRuntime.fragments.map((e) => {
		const { activation: t } = e;
		if (t !== "first-use" && t !== "version-additive") throw new Error(`Unknown PostgreSQL state fragment activation: ${t}`);
		return {
			id: e.id,
			tables: e.tables,
			sql: e.sql,
			dependencies: e.dependencies,
			activation: t
		};
	})
};
function statePostgresVersionSql(e) {
	return `UPDATE schema_meta
        SET schema_version = ${e},
          app_version = '${VERSION.replaceAll("'", "''")}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';
        INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
        VALUES ('state.schema.contentVersion', '${e}',
          CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint))
        ON CONFLICT (state_key) DO UPDATE
          SET value_json = EXCLUDED.value_json, updated_at_ms = EXCLUDED.updated_at_ms;`;
}
function createStatePostgresMigrations() {
	const e = {
		postgres: withLegacyTemplateStateSchema(statePostgresSchema.postgres),
		postgresFragments: statePostgresSchema.postgresFragments.map((e) => ({
			...e,
			tables: e.tables.map(legacyTemplateStateIdentifier),
			sql: withLegacyTemplateStateSchema(e.sql)
		}))
	};
	const t = {
		postgres: withLegacyLocalWorkspaceCas(e.postgres),
		postgresFragments: e.postgresFragments.map((e) => ({
			...e,
			tables: e.tables.filter((e) => !WORKSPACE_CAS_TABLES.some((t) => t === e)),
			sql: withLegacyLocalWorkspaceCas(e.sql)
		}))
	};
	const n = {
		postgres: withLegacyPostgresIndexOrdering(t.postgres, "schema-nullability"),
		postgresFragments: t.postgresFragments.map((e) => ({
			...e,
			sql: withLegacyPostgresIndexOrdering(e.sql, "schema-nullability")
		}))
	};
	const r = {
		postgres: withLegacyPostgresIndexOrdering(n.postgres),
		postgresFragments: n.postgresFragments.map((e) => ({
			...e,
			sql: withLegacyPostgresIndexOrdering(e.sql)
		}))
	};
	const i = {
		postgres: withLegacyLocalWorkspaceManifests(r.postgres),
		postgresFragments: r.postgresFragments.map((e) => ({
			...e,
			tables: e.tables.filter((e) => e !== "local_workspace_manifest_nodes"),
			sql: withLegacyLocalWorkspaceManifests(e.sql)
		}))
	};
	const a = {
		...i,
		postgres: `${i.postgres}\n${statePostgresRuntime.clientCredentialSource.sql}`
	};
	const o = {
		postgres: withLegacyPublicationDraft(a.postgres),
		postgresFragments: a.postgresFragments.map((e) => ({
			...e,
			sql: withLegacyPublicationDraft(e.sql)
		}))
	};
	const s = {
		...o,
		postgres: o.postgres.replace(/CREATE INDEX "idx_state_leases_owner"[^;]*;/u, statePostgresRuntime.preWriteIndexesV27Sql.state_leases) + statePostgresRuntime.preWriteIndexesV27Sql.skill_usage + statePostgresRuntime.preWriteIndexesV27Sql.acp_replay_events,
		postgresFragments: o.postgresFragments
	};
	return [
		{
			version: 25,
			sql: statePostgresRuntime.operatorRecoveryV25Sql,
			fromSchema: s,
			schema: s
		},
		{
			version: 26,
			fromSchema: s,
			schema: s,
			sql: statePostgresVersionSql(26)
		},
		{
			version: 27,
			fromSchema: s,
			schema: o,
			sql: `${statePostgresRuntime.writeIndexesV27Sql}
        ${statePostgresVersionSql(27)}`
		},
		{
			version: 28,
			fromSchema: o,
			schema: a,
			sql: `ALTER TABLE IF EXISTS github_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_personal_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_repository_publication_requests ADD COLUMN draft bigint;
        ${statePostgresVersionSql(28)}`
		},
		{
			version: 29,
			fromSchema: a,
			schema: i,
			sql: statePostgresRuntime.clientCredentialV29Sql
		},
		{
			version: 30,
			fromSchema: i,
			schema: i,
			sql: statePostgresVersionSql(30)
		},
		{
			version: 31,
			fromSchema: i,
			schema: r,
			sql: `DO $workspace$
        DECLARE baseline_constraint text;
        BEGIN
          IF to_regclass('local_workspace_projections') IS NOT NULL THEN
            SELECT conname INTO STRICT baseline_constraint FROM pg_constraint
              WHERE conrelid = 'local_workspace_projections'::regclass AND contype = 'c'
                AND pg_get_constraintdef(oid) LIKE '%baseline_json%baseline_ref%';
            EXECUTE format('ALTER TABLE local_workspace_projections DROP CONSTRAINT %I', baseline_constraint);
            ALTER TABLE local_workspace_projections
              ADD COLUMN checkpoint_json text COLLATE "C",
              ADD CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL);
            CREATE TABLE local_workspace_manifest_nodes (
              worktree_id text COLLATE "C" NOT NULL,
              path text COLLATE "C" NOT NULL,
              node_json text COLLATE "C" NOT NULL,
              PRIMARY KEY (worktree_id, path),
              FOREIGN KEY (worktree_id) REFERENCES local_workspace_projections(worktree_id)
                ON DELETE CASCADE
            );
          END IF;
        END $workspace$;
        ${statePostgresVersionSql(31)}`
		},
		{
			version: 32,
			fromSchema: r,
			schema: n,
			sql: `${postgresIndexOrderingMigration([n.postgres, ...n.postgresFragments.map((e) => e.sql)].join("\n"))}
        ${statePostgresVersionSql(32)}`
		},
		{
			version: 33,
			fromSchema: n,
			schema: t,
			sql: `${postgresIndexOrderingMigration([t.postgres, ...t.postgresFragments.map((e) => e.sql)].join("\n"), "schema-nullability")}
        ${statePostgresVersionSql(33)}`
		},
		{
			version: 34,
			fromSchema: t,
			schema: t,
			sql: statePostgresVersionSql(34)
		},
		{
			version: 35,
			fromSchema: t,
			schema: e,
			sql: `${statePostgresRuntime.workspaceCasV35Sql}\n${statePostgresVersionSql(35)}`
		},
		{
			version: 36,
			fromSchema: e,
			schema: statePostgresSchema,
			sql: `${TEMPLATE_STATE_POSTGRES_MIGRATION_SQL}\n${statePostgresVersionSql(36)}`
		}
	];
}
const stateEngineSchema = {
	id: "state",
	version: 36,
	sqlite: "",
	...statePostgresSchema,
	get postgresMigrations() {
		const e = createStatePostgresMigrations();
		Object.defineProperty(this, "postgresMigrations", {
			value: e,
			enumerable: true,
			configurable: true,
			writable: true
		});
		return e;
	}
};
function ensureStatePostgresFragment(e, t) {
	const n = getPostgresPhysicalFacts(e);
	if (!n) throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${recovery}`);
	const r = statePostgresRuntime.fragments.find((e) => e.tables.includes(t));
	if (!r) {
		if (statePostgresRuntime.expectedCatalog.some((e) => e.kind === "table" && e.table === t) && n.catalog.some((e) => e.kind === "table" && e.table === t)) return;
		throw new Error(`No PostgreSQL state fragment owns ${t}`);
	}
	if (r.tables.filter((e) => n.version >= 35 || !WORKSPACE_CAS_TABLES.some((t) => t === e)).every((e) => n.catalog.some((t) => t.kind === "table" && t.table === e))) return;
	for (const t of r.dependencies) {
		const n = statePostgresRuntime.fragments.find((e) => e.id === t);
		if (!n) throw new Error(`Unknown state fragment dependency ${t}`);
		ensureStatePostgresFragment(e, n.tables[0]);
	}
	if (!stageSqliteTransactionState(e, {
		commit: () => publishSqliteDatabaseSchemaChange(e),
		invalidate: () => publishSqliteDatabaseSchemaChange(e)
	})) throw new Error("PostgreSQL state fragments require the owner's transaction");
	invalidateLocalSqliteSchemaAdmissions(e);
	const i = n.version < 36 ? withLegacyTemplateStateSchema(r.sql) : r.sql;
	const a = n.version < 35 ? withLegacyLocalWorkspaceCas(i) : i;
	e.exec(n.version < 33 ? withLegacyPostgresIndexOrdering(a, n.version < 32 ? "sqlite" : "schema-nullability") : a);
	admitPostgresPhysicalFacts({
		db: e,
		namespace: n.namespace,
		storeId: n.storeId,
		store: n.store,
		version: n.version,
		schema: stateEngineSchema,
		recordSchema: true
	});
	admitStatePostgres(e, false);
}
function openExistingStatePostgresConnection(e, t) {
	if (!stateEngineInput()) return;
	return openExistingStatePostgresConnectionFromAnchor(openTrackedStateDatabase(e, {
		existingOnly: true,
		expectedIdentity: t
	}), e);
}
/** Consumes an anchor whose caller owns path admission, including updater read-only custody. */
function openExistingStatePostgresConnectionFromAnchor(e, t) {
	let n;
	try {
		const r = stateEngineInput();
		if (!r) throw new Error("PostgreSQL state inspection requires the configured state connection.");
		admitStateSchemaFacts(e, t);
		const i = openEngineStore({
			anchor: e,
			schema: stateEngineSchema,
			input: r,
			inspectSqlite: () => inspectStateSqlite(e),
			prepareAnchor: () => {},
			openSqlite: () => {},
			existingOnly: true,
			reusePostgresConnection: true,
			existingVersion: true,
			admitPostgres: admitStatePostgres,
			closeOnFailure: (e, t) => {
				n = e;
				throw t;
			}
		});
		if (!isPostgresSqlConnection(i)) throw new Error("Expected PostgreSQL state connection");
		n = i;
		return {
			database: {
				db: n,
				path: t
			},
			close() {
				throwSqliteLifecycleErrors(openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle({
					db: i,
					path: t
				}), "PostgreSQL state connection cleanup failed.");
				return !i.isOpen && !e.isOpen;
			}
		};
	} catch (r) {
		const i = openClawStateDatabaseCache.closeUnpublishedOpenClawStateDatabaseHandle({
			db: n ?? e,
			path: t
		});
		if (i.length) throw createSqliteLifecycleAggregateError([r, ...i], "PostgreSQL state connection acquisition and cleanup failed.", r);
		throw r;
	}
}
//#endregion
//#region src/infra/sqlite-schema-contract.ts
/**
* Require every object from one committed schema while allowing unrelated
* tables and indexes that do not replace a canonical object.
*/
function assertSqliteSchemaContains(e, t, n, r = {}, i) {
	const a = collectSqliteSchemaIssues(e, n, r, i);
	if (a.length > 0) throwSqliteSchemaMismatches(t, legacySqliteSchemaIssueMessages(a));
}
/** Collect stable, machine-readable differences from one committed schema. */
function collectSqliteSchemaIssues(e, t, n = {}, r) {
	if (!getSqlitePinnedReadSnapshot(e)) return runSqliteSchemaReadSnapshotSync(e, () => collectSqliteSchemaIssues(e, t, n, r));
	const i = typeof t === "string" ? readGeneratedSqliteFingerprint(t) : void 0;
	const a = i?.viewNames ?? getSqliteSchemaContract(t).catalog.views.map((e) => e.name);
	const o = r ?? createSqliteTableContractReader(e, a, i?.tableNames ?? getSqliteSchemaContract(t).catalog.tables.map((e) => e.name));
	if (hasCanonicalSqliteSchemaFingerprint(t, o, n)) return [];
	const s = getSqliteSchemaContract(t);
	const c = new Set(n.excludedTables ?? []);
	const l = new Set(n.excludedIndexes ?? []);
	const u = new Set(n.allowedMissingTables ?? []);
	const d = new Set(n.allowedMissingIndexes ?? []);
	const f = [];
	const add = (e, t, n) => {
		f.push(createSqliteSchemaIssue(e, t, n));
	};
	for (const [t, r] of s.tables) {
		if (c.has(t)) continue;
		const i = o(t);
		if (!i) {
			if (u.has(t)) continue;
			add("missing-table", t);
			continue;
		}
		f.push(...compareTableDefinitions(t, i.definition, r.definition, n, !u.has(t)));
		for (const e of compareTablePragmaFacts(t, i, r, n)) if (!f.some((t) => t.code === e.code && t.objectName === e.objectName)) f.push(e);
		const a = new Set(i.indexes.map((e) => JSON.stringify(e)));
		const s = /* @__PURE__ */ new Set();
		for (const n of r.indexes) {
			if (n.name !== null && l.has(n.name)) continue;
			const r = JSON.stringify(n);
			s.add(r);
			if (!a.has(r)) {
				const r = n.name ?? t;
				if (n.name && d.has(n.name) && !e.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'index' AND name = ? COLLATE NOCASE LIMIT 1").get(n.name)) continue;
				add("missing-or-drifted-index", r, `missing or drifted index ${n.name ?? `on ${t}`}`);
			}
		}
		for (const e of i.indexes) if (e.unique === 1 && !s.has(JSON.stringify(e))) add("unexpected-unique-index", e.name ?? t, `unexpected unique index ${e.name ?? `on ${t}`}`);
		const p = collectOptionalCanonicalTriggerGroups(e, n, t);
		const m = p.flatMap((e) => e.triggers);
		const h = p.filter((e) => e.optional).flatMap((e) => e.triggers);
		for (const e of r.triggers) {
			if (h.some((t) => t.name === e.name)) continue;
			if (!containsTrigger(i.triggers, e)) add("missing-or-drifted-trigger", e.name);
		}
		for (const e of p) {
			const t = i.triggers.some((t) => e.triggers.some((e) => t.name === e.name));
			if (e.optional && !t) continue;
			for (const t of e.triggers) if (!containsTrigger(i.triggers, t)) add("missing-or-drifted-trigger", t.name);
		}
		for (const e of i.triggers) if (!containsTrigger(r.triggers, e) && !containsTrigger(m, e)) add("unexpected-trigger", e.name);
		if (i.virtualTableSql !== r.virtualTableSql) add("virtual-table-definition-drift", t);
		if (i.strict !== r.strict || i.withoutRowid !== r.withoutRowid) add("table-options-drift", t);
	}
	const p = o.readView ?? createSqliteTableContractReader(e, a).readView;
	for (const e of s.catalog.views) {
		const t = p(e.name);
		if (!t || t.sql !== e.sql || JSON.stringify(normalizeColumns(t.columns)) !== JSON.stringify(normalizeColumns(e.columns))) {
			add("missing-or-drifted-view", e.name);
			continue;
		}
		for (const n of e.triggers) if (!containsTrigger(t.triggers, n)) add("missing-or-drifted-trigger", n.name);
		for (const n of t.triggers) if (!containsTrigger(e.triggers, n)) add("unexpected-trigger", n.name);
	}
	return f;
}
/** Require stable canonical tables before a version-specific additive migration. */
function assertSqliteSchemaTablesPresent(e, t, n, r = {}) {
	const i = new Set(r.allowedMissingTables ?? []);
	const a = getCanonicalSqliteTableNames(n).filter((e) => !i.has(e));
	const o = [];
	const s = 500;
	for (let t = 0; t < a.length; t += s) {
		const n = a.slice(t, t + s);
		const r = n.map((e, t) => `(${t}, ?)`).join(", ");
		const i = e.prepare(`WITH expected(ordinal, name) AS (VALUES ${r})
         SELECT ordinal FROM expected
         WHERE EXISTS (
           SELECT 1 FROM main.sqlite_schema
           WHERE type = 'table' AND name = expected.name LIMIT 1
         )`).all(...n);
		const c = new Set(i.map((e) => e.ordinal));
		for (const [e, t] of n.entries()) if (!c.has(e)) o.push(`missing table ${t}`);
	}
	if (o.length > 0) throwSqliteSchemaMismatches(t, o);
}
/** Return every explicit named index owned by one committed schema. */
function getCanonicalSqliteNamedIndexContracts(e) {
	const t = getSqliteSchemaContract(e);
	const n = [];
	for (const [e, r] of t.tables) for (const t of r.indexes) {
		if (t.name === null || t.sql === null || t.origin !== "c") continue;
		n.push({
			definition: readCanonicalIndexDefinition(t),
			fingerprint: t,
			name: t.name,
			tableName: e,
			unique: t.unique === 1
		});
	}
	return n;
}
/** Return every table owned by one committed schema. */
function getCanonicalSqliteTableNames(e) {
	if (typeof e === "string") {
		const t = readGeneratedSqliteFingerprint(e);
		if (t) return [...t.tableNames];
	}
	return [...getSqliteSchemaContract(e).tables.keys()];
}
/** Read index membership without materializing diagnostic catalog facts. */
function getCanonicalSqliteNamedIndexNames(e) {
	if (typeof e === "string") {
		const t = readGeneratedSqliteFingerprint(e);
		if (t) return [...t.indexNames];
	}
	return getCanonicalSqliteNamedIndexContracts(e).map((e) => e.name);
}
/** A matching native catalog needs neither expected DDL execution nor full diagnostic facts. */
function hasCanonicalSqliteSchemaFingerprint(e, t, n = {}) {
	const r = typeof e === "string" ? readGeneratedSqliteFingerprint(e) : void 0;
	if (!r || !t.readCatalog) return false;
	const i = t.readCatalog(r.viewNames, r.tableNames);
	if (fingerprintSqliteSchemaCatalog(i, r) !== r.fingerprint) return false;
	for (const e of n.optionalCanonicalTriggerGroups ?? []) {
		if (!r.tableNames.includes(e.tableName) || n.excludedTables?.includes(e.tableName)) continue;
		const t = i.tables.find((t) => t.name === e.tableName).triggers;
		if ((!e.optionalWhenTableMissing || !i.tables.some((t) => t.name === e.optionalWhenTableMissing)) && !t.some((t) => e.triggers.some((e) => e.name === t.name))) continue;
		if (!e.triggers.every((e) => containsTrigger(t, {
			name: e.name,
			sql: normalizeOptionalCanonicalTriggerSql(e.sql)
		}))) return false;
	}
	if (!n.excludedIndexes?.length) return true;
	return !i.tables.some((e) => r.tableNames.includes(e.name) && !n.excludedTables?.includes(e.name) && e.indexes.some((e) => e.origin === "c" && e.unique === 1 && n.excludedIndexes?.includes(e.name)));
}
/** Inspect one explicit main-schema index using the canonical schema fingerprint shape. */
function collectSqliteNamedIndexContract(e, t) {
	const n = e.prepare(`
      SELECT tbl_name FROM (
        SELECT name, sql, tbl_name FROM main.sqlite_schema WHERE type = 'index' AND name = ?
      )
    `).get(t);
	if (!n || typeof n.tbl_name !== "string") return;
	const r = e.prepare(`PRAGMA main.index_list(${quoteSqliteIdentifier(n.tbl_name)})`).all().find((e) => e.name === t);
	return r ? collectSqliteIndexContract(e, r) : void 0;
}
function collectOptionalCanonicalTriggerGroups(e, t, n) {
	return (t.optionalCanonicalTriggerGroups ?? []).filter((e) => e.tableName === n).map((t) => ({
		optional: !t.optionalWhenTableMissing || !e.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name = ? LIMIT 1").get(t.optionalWhenTableMissing),
		triggers: t.triggers.map((e) => ({
			name: e.name,
			sql: normalizeOptionalCanonicalTriggerSql(e.sql)
		}))
	}));
}
function normalizeOptionalCanonicalTriggerSql(e) {
	return normalizeSchemaSql(e)?.replace(/^(CREATE TRIGGER) main\./iu, "$1 ") ?? null;
}
const expectedContracts = /* @__PURE__ */ new WeakMap();
const expectedStringContracts = /* @__PURE__ */ new Map();
function getSqliteSchemaContract(e) {
	if (typeof e === "string") {
		const t = expectedStringContracts.get(e);
		if (t) return t;
	}
	const t = typeof e === "string" ? readGeneratedSqliteCatalog(e) : e;
	if (!t) throw new Error("SQLite schema has no generated catalog; run pnpm db:postgres:gen for its declared schema input.");
	let n = expectedContracts.get(t);
	if (!n) {
		n = {
			catalog: t,
			tables: sqliteSchemaContractFromCatalog(t)
		};
		expectedContracts.set(t, n);
	}
	if (typeof e === "string") expectedStringContracts.set(e, n);
	return n;
}
function readCanonicalIndexDefinition(e) {
	if (e.name === null || e.sql === null) throw new Error("Canonical SQLite named index is missing its schema definition.");
	const t = (e.unique === 1 ? /^CREATE\s+UNIQUE\s+INDEX\s+/iu : /^CREATE\s+INDEX\s+/iu).exec(e.sql);
	if (!t) throw new Error(`Canonical SQLite index ${e.name} has an unreadable definition.`);
	const n = readSqlToken(e.sql, t[0].length);
	if (!n || normalizeSqlIdentifier(n.raw) !== e.name.toLowerCase()) throw new Error(`Canonical SQLite index ${e.name} has an unexpected schema name.`);
	const r = e.sql.slice(n.end).trim();
	if (!/^ON\s+/iu.test(r)) throw new Error(`Canonical SQLite index ${e.name} has an unreadable target.`);
	return r;
}
function normalizeColumns(e) {
	return e.map(({ cid: e, name: t, type: n, dflt_value: r, ...i }) => ({
		...i,
		name: normalizeSqlIdentifier(t),
		type: n.toUpperCase(),
		dflt_value: r === null ? null : normalizeSqlWhitespace(r)
	})).toSorted((e, t) => e.name.localeCompare(t.name));
}
function normalizeForeignKeys(e, t) {
	const n = /* @__PURE__ */ new Map();
	for (const { id: t, from: r, table: i, to: a, ...o } of e) {
		const e = n.get(t) ?? [];
		e.push({
			...o,
			from: normalizeSqlIdentifier(r),
			table: normalizeSqlIdentifier(i),
			to: a === null ? null : normalizeSqlIdentifier(a)
		});
		n.set(t, e);
	}
	return [...n.values()].filter((e) => !e.some((e) => t.has(e.from))).map((e) => e.toSorted((e, t) => e.seq - t.seq)).toSorted((e, t) => JSON.stringify(e).localeCompare(JSON.stringify(t)));
}
function compareTablePragmaFacts(e, t, n, r) {
	const i = [];
	const a = new Map(normalizeColumns(t.columns).map((e) => [e.name, e]));
	const o = normalizeColumns(n.columns);
	const s = /* @__PURE__ */ new Set();
	for (const n of o) {
		const o = n.name;
		const c = `${e}.${o}`;
		const l = a.get(o);
		if (!l) {
			if ((r.allowedMissingColumns ?? []).includes(c)) s.add(o);
			else i.push(createSqliteSchemaIssue("missing-column", c));
			continue;
		}
		const u = t.definition?.columns.get(o);
		const d = r.allowedColumnDefinitions?.[c] ?? [];
		if (u !== void 0 && d.some((e) => normalizeSqlWhitespace(e) === u)) {
			s.add(o);
			continue;
		}
		if (JSON.stringify(l) !== JSON.stringify(n)) i.push(createSqliteSchemaIssue("column-definition-drift", c));
	}
	if (n.definition === null) {
		const t = new Set(o.map((e) => e.name));
		for (const n of a.values()) if (!t.has(n.name)) i.push(createSqliteSchemaIssue("unexpected-column", `${e}.${n.name}`));
	}
	if (JSON.stringify(normalizeForeignKeys(t.foreignKeys, s)) !== JSON.stringify(normalizeForeignKeys(n.foreignKeys, s))) i.push(createSqliteSchemaIssue("table-constraint-drift", e));
	return i;
}
function compareTableDefinitions(e, t, n, r, i) {
	const a = [];
	const add = (e, t) => {
		a.push(createSqliteSchemaIssue(e, t));
	};
	if (!t || !n) {
		if (t !== n) add("table-definition-drift", e);
		return a;
	}
	const o = new Set(r.allowedMissingColumns ?? []);
	for (const [a, o] of t.columns) if (!n.columns.has(a)) {
		const t = `${e}.${a}`;
		if ((r.allowedColumnDefinitions?.[t] ?? []).some((e) => normalizeSqlWhitespace(e) === o)) continue;
		if (i && r.allowCompatibleAdditiveColumns && isCompatibleAdditiveColumnDefinition(o)) continue;
		add("unexpected-column", t);
	}
	for (const [i, a] of n.columns) {
		const n = `${e}.${i}`;
		const s = t.columns.get(i);
		if (s === void 0) {
			if (!o.has(n)) add("missing-column", n);
			continue;
		}
		if (s === a) continue;
		if (!(r.allowedColumnDefinitions?.[n] ?? []).some((e) => normalizeSqlWhitespace(e) === s)) add("column-definition-drift", n);
	}
	if (JSON.stringify(t.constraints) !== JSON.stringify(n.constraints)) add("table-constraint-drift", e);
	return a;
}
const SQLITE_STRICT_DATATYPES = /* @__PURE__ */ new Set([
	"ANY",
	"BLOB",
	"INT",
	"INTEGER",
	"REAL",
	"TEXT"
]);
function isCompatibleAdditiveColumnDefinition(e) {
	const t = readSqlToken(e, 0);
	const n = t ? readSqlToken(e, t.end) : null;
	return Boolean(n?.keyword && SQLITE_STRICT_DATATYPES.has(n.keyword) && e.slice(n.end).trim().length === 0);
}
function collectSqliteIndexContract(e, t) {
	const n = executeWithCachedStatement(e, "SELECT sql FROM main.sqlite_schema WHERE type = 'index' AND name = ?", [t.name], (e) => e.get(t.name));
	const r = e.prepare(`PRAGMA main.index_xinfo(${quoteSqliteIdentifier(t.name)})`).all();
	return createSqliteIndexContract(t, typeof n?.sql === "string" ? n.sql : null, r);
}
function containsTrigger(e, t) {
	return e.some((e) => e.name === t.name && e.sql === t.sql);
}
function readSqliteSchemaCookie(e) {
	return e.prepare("PRAGMA schema_version").get()?.schema_version;
}
//#endregion
//#region src/infra/state-lease-process-owner.ts
function parseStateLeaseProcessOwner(e) {
	const t = safeParseJsonRecord(e ?? "")?.owner;
	if (!isRecord(t)) return null;
	const { pid: n, host: r, startedAt: i } = t;
	if (typeof n !== "number" || !Number.isSafeInteger(n) || n <= 0 || typeof r !== "string" || !r || i !== null && (typeof i !== "number" || !Number.isSafeInteger(i) || i < 0)) return null;
	return {
		pid: n,
		host: r,
		startedAt: i,
		...t.machineIdentity === void 0 ? {} : { machineIdentity: MachineIdentitySchema.safeParse(t.machineIdentity).data ?? null },
		...t.processNamespace === void 0 ? {} : { processNamespace: GatewayProcessNamespaceSchema.safeParse(t.processNamespace).data ?? null }
	};
}
function readStateLeaseProcessOwnerStatus(e, t) {
	if (!e) return "unknown";
	const n = classifyGatewayOwnerProcessNamespace(e.processNamespace, {
		ownerHost: e.host,
		machineIdentity: e.machineIdentity
	});
	if (n !== "same") return n;
	return readSameNamespaceProcessOwnerStatus(e);
}
function readSameNamespaceProcessOwnerStatus(e) {
	if (isPidDefinitelyDead(e.pid)) return "dead";
	const t = getFileLockProcessStartTime(e.pid);
	if (e.startedAt === null || t === null) return "unknown";
	return t === e.startedAt ? "live" : "dead";
}
//#endregion
//#region src/shared/state-lease-loss.ts
const milliseconds = number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const StateLeaseLossSchema = discriminatedUnion("reason", [
	object({
		reason: literal$1("expired"),
		expiresAt: milliseconds,
		expiredByMs: milliseconds,
		heartbeatAgeMs: milliseconds,
		renewalTimerLateByMs: milliseconds.optional()
	}),
	object({
		reason: literal$1("replaced"),
		owner: literal$1("[redacted]")
	}),
	object({ reason: literal$1("missing") }),
	object({ reason: literal$1("storage-failed") }),
	object({ reason: literal$1("admission-failed") })
]);
//#endregion
//#region src/state/openclaw-state-lease-store.ts
function readOpenClawStateLease(e, t) {
	return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("state_leases").select([
		"owner",
		"created_at as createdAt",
		"expires_at as expiresAt",
		"heartbeat_at as heartbeatAt",
		"payload_json as payloadJson"
	]).where("scope", "=", t.scope).where("lease_key", "=", t.key));
}
//#endregion
//#region src/infra/gateway-owner-lease.read.ts
const gatewayOwnerKey = {
	scope: "gateway-owner",
	key: "global"
};
function parseSupervisor(e) {
	if (e === null) return null;
	if (!isRecord(e) || e.kind !== "launchd" && e.kind !== "systemd" && e.kind !== "schtasks" && e.kind !== "external" || e.name !== null && (typeof e.name !== "string" || !e.name.trim())) throw new Error("Gateway owner lease supervisor could not be verified");
	return {
		kind: e.kind,
		name: e.name
	};
}
/** Read through the caller's admitted connection when ownership guards a write. */
function readGatewayOwnerLeaseFromDatabase(e, t) {
	if (!tableExists(e, "state_leases")) return;
	return decodeGatewayOwnerLease(readOpenClawStateLease(e, gatewayOwnerKey), t);
}
function decodeGatewayOwnerLease(e, t) {
	if (!e) return;
	const n = parseStateLeaseProcessOwner(e.payloadJson);
	const r = safeParseJsonRecord(e.payloadJson ?? "");
	if (!n || !r || typeof r.port !== "number" || !Number.isInteger(r.port) || r.port <= 0 || r.port > 65535 || r.mode !== "foreground" && r.mode !== "supervised") throw new Error("Gateway owner lease identity could not be verified");
	if (t !== void 0 && r.port !== t) return;
	const i = parseSupervisor(r.supervisor);
	if (r.mode === "foreground" !== (i === null)) throw new Error("Gateway owner lease supervisor does not match its listener mode");
	return {
		...n,
		owner: e.owner,
		heartbeatAt: e.heartbeatAt ?? e.createdAt,
		port: r.port,
		mode: r.mode,
		supervisor: i,
		...typeof r.listeningAt === "number" ? { listeningAt: r.listeningAt } : {},
		...typeof r.stateDatabaseProvenance === "string" ? { stateDatabaseProvenance: r.stateDatabaseProvenance } : {},
		state: readStateLeaseProcessOwnerStatus(n, e.heartbeatAt ?? e.createdAt),
		expired: e.expiresAt === null || e.expiresAt <= Date.now()
	};
}
//#endregion
//#region src/infra/state-legacy-cron-presence.ts
/** Runtime admission needs table presence, without loading the migration's history codecs. */
function hasLegacyCronRunLogs(e) {
	const t = getAdmittedSqliteSchemaFacts(e);
	if (t) return t.tables.has("cron_run_logs");
	return Boolean(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_run_logs' LIMIT 1").get());
}
//#endregion
//#region src/state/openclaw-agent-db-lease-provenance.ts
let boot;
function readAgentDatabaseLeaseProvenance(e) {
	try {
		if (boot === void 0) {
			const e = process.platform === "linux" ? fsSync.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() : "";
			boot = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e) ? [
				hostname(),
				e,
				fsSync.readlinkSync("/proc/self/ns/pid"),
				VERSION
			].join("\0") : null;
		}
		if (!boot) return null;
		const t = fsSync.statSync(e, { bigint: true });
		return t.isFile() ? `process-v1:${createHash("sha256").update(`${boot}\0${t.dev}:${t.ino}`).digest("hex")}` : null;
	} catch {
		return null;
	}
}
//#endregion
//#region src/gateway/worker-environments/environment-recipe.ts
const ProcessString = string().refine((e) => !e.includes("\0"), "Must not contain NUL");
const Command = union([ProcessString, array(ProcessString).min(1).refine((e) => Boolean(e[0]?.length), "Executable must not be empty")]);
const Lifecycle = union([Command, record(string(), Command)]);
const Blob = string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u);
const SecretName = string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
const SecretRequests = record(SecretName, object({
	description: string().optional(),
	documentationUrl: string().optional()
}).passthrough()).refine((e) => Object.keys(e).length <= 16, "At most 16 setup secrets may be requested");
const Environment = record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), ProcessString);
const EnvironmentRecipeSchema = object({
	source: _enum([
		"devcontainer",
		"script",
		"detected",
		"none"
	]),
	identity: Blob.optional(),
	inputs: record(string(), Blob),
	env: record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), ProcessString.nullable()),
	secretNames: array(SecretName).max(16).optional(),
	ignoredPropertiesNote: string().optional(),
	onCreate: Lifecycle.optional(),
	updateContent: Lifecycle.optional(),
	postCreate: Lifecycle.optional(),
	postStart: Lifecycle.optional(),
	detectedInstall: Lifecycle.optional()
}).strict();
const Devcontainer = object({
	onCreateCommand: Lifecycle.optional(),
	updateContentCommand: Lifecycle.optional(),
	postCreateCommand: Lifecycle.optional(),
	postStartCommand: Lifecycle.optional(),
	secrets: SecretRequests.optional(),
	containerEnv: Environment.optional(),
	remoteEnv: record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), ProcessString.nullable()).optional()
}).passthrough();
//#endregion
//#region src/gateway/worker-environments/preparation-identity.schema.ts
const Digest = string().regex(/^[a-f0-9]{64}$/u);
const WorkerPreparationArtifactsSchema = object({
	nodeBootstrapSha256: Digest,
	enabledPluginIds: array(string().min(1).max(256)).max(256),
	workerBundleHash: Digest,
	workerArchiveSha256: Digest,
	openclawVersion: string().min(1).max(128),
	protocolFeatures: array(string().min(1).max(128)).max(64)
}).strict();
const WorkerPreparationTargetSchema = object({
	machineClass: string().min(1).max(256),
	platform: string().min(1).max(64),
	arch: string().min(1).max(64).optional(),
	profileKey: Digest.optional()
}).strict();
const Preparation = object({
	key: Digest,
	cacheKey: Digest,
	contractVersion: union([literal$1(1), literal$1(2)]),
	setupRecipe: string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u).optional(),
	runSetupScript: boolean().optional(),
	recipe: EnvironmentRecipeSchema.optional(),
	target: WorkerPreparationTargetSchema,
	artifacts: WorkerPreparationArtifactsSchema
}).strict();
const EmptyPreparation = Preparation.omit({
	setupRecipe: true,
	runSetupScript: true,
	recipe: true
}).extend({ source: literal$1("empty") });
/** Immutable artifact facts are separate from the reserve's demand/expiry/consumption tuple. */
function readWorkerProjectPreparation(e) {
	if (!isRecord(e) || e.preparation === void 0) return;
	const t = Preparation.safeParse(e.preparation);
	if (!t.success) throw new Error("Worker project preparation identity is invalid");
	return t.data;
}
function readWorkerPreparation(e) {
	if (e.runtimePreparation === void 0) return readWorkerProjectPreparation(e.project);
	const t = EmptyPreparation.safeParse(e.runtimePreparation);
	if (!t.success || e.project !== void 0) throw new Error("Worker runtime preparation identity is invalid");
	return t.data;
}
//#endregion
//#region src/state/openclaw-state-db-image-snapshot-migration.ts
function historicalImageQuery(e) {
	return getNodeSqliteKysely(e).selectFrom("worker_environments").select(["environment_id", "profile_snapshot_json"]).where((t) => t(jsonValid(e, t.ref("profile_snapshot_json")), "=", 1)).where((t) => t(jsonPathValue(e, t.ref("profile_snapshot_json"), t.val("$.project.kind")), "=", "image"));
}
/** Doctor owns this data cutover even when an earlier import already published schema 22. */
function migrateHistoricalImageReserveSnapshots(e) {
	if (!tableExists(e, "worker_environments")) return [];
	const t = executeSqliteQuerySync(e, historicalImageQuery(e)).rows;
	for (const n of t) {
		if (typeof n.profile_snapshot_json !== "string" || typeof n.environment_id !== "string") throw new Error("Historical image reserve row is invalid");
		const t = JSON.parse(n.profile_snapshot_json);
		const r = isRecord(t) ? t.project : void 0;
		if (!isRecord(t) || !isRecord(r) || r.kind !== "image" || typeof r.key !== "string" || !/^[a-f0-9]{64}$/u.test(r.key) || !isRecord(r.preparation) || t.runtimePreparation !== void 0 || t.historicalProfileSnapshotJson !== void 0) throw new Error("Historical image reserve snapshot has conflicting or invalid preparation");
		t.runtimePreparation = {
			...r.preparation,
			source: "empty"
		};
		delete t.project;
		readWorkerPreparation(t);
		t.historicalProfileSnapshotJson = n.profile_snapshot_json;
		executeSqliteQuerySync(e, getNodeSqliteKysely(e).updateTable("worker_environments").set({ profile_snapshot_json: JSON.stringify(t) }).where("environment_id", "=", n.environment_id));
	}
	return t.length > 0 ? ["Migrated historical image reserves with original snapshot evidence retained"] : [];
}
//#endregion
//#region src/infra/client-credential-schema.ts
const CLIENT_CREDENTIAL_SOURCE_TABLES = [
	"device_identities",
	"device_auth_tokens",
	"gateway_origin_device_tokens",
	"exec_approvals_config"
];
const CLIENT_CREDENTIAL_LEGACY_TABLES_SQL = `CREATE TABLE device_identities (
  identity_key TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  public_key_pem TEXT NOT NULL,
  private_key_pem TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;
CREATE INDEX idx_device_identities_device
  ON device_identities(device_id, updated_at_ms DESC);
CREATE TABLE device_auth_tokens (
  device_id TEXT NOT NULL,
  role TEXT NOT NULL,
  token TEXT NOT NULL,
  scopes_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (device_id, role)
) STRICT;
CREATE INDEX idx_device_auth_tokens_updated
  ON device_auth_tokens(updated_at_ms DESC, device_id, role);
CREATE TABLE gateway_origin_device_tokens (
  gateway_scope TEXT NOT NULL,
  device_id TEXT NOT NULL,
  role TEXT NOT NULL,
  token TEXT NOT NULL,
  scopes_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (gateway_scope, device_id, role)
) STRICT;`;
const CLIENT_CREDENTIAL_SCHEMA_SQL = `${CLIENT_CREDENTIAL_LEGACY_TABLES_SQL}
CREATE TABLE native_exec_socket_credentials (
  socket_key TEXT NOT NULL PRIMARY KEY CHECK (socket_key = 'current'),
  socket_path TEXT,
  socket_token TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;
CREATE TABLE client_credential_migration (
  version INTEGER PRIMARY KEY CHECK (version = 1),
  source_store TEXT NOT NULL,
  phase TEXT NOT NULL CHECK (phase IN ('copied', 'complete')),
  updated_at_ms INTEGER NOT NULL
) STRICT;`;
//#endregion
//#region src/state/openclaw-state-db-cron-delivery-migration.ts
/** Absence of old delivery evidence cannot prove that a completion was never sent. */
function migrateCronDeliveryAttemptState(e, t) {
	return t < 20 && tableExists(e, "cron_run_receipts") ? ensureColumn(e, "cron_run_receipts", "delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started'))") : false;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v21-columns.ts
const statePredicateColumnMigration = {
	version: 21,
	tables: [
		"meeting_transcript_sessions",
		"meeting_transcript_summaries",
		"delivery_queue_entries"
	],
	columns: [
		...[
			"source_account_id",
			"source_guild_id",
			"source_channel_id",
			"source_meeting_url",
			"source_thread_ts",
			"source_file_id",
			"metadata_agent_id"
		].map((e) => `meeting_transcript_sessions.${e}`),
		"meeting_transcript_summaries.overview",
		"delivery_queue_entries.retention_id_prefix",
		"delivery_queue_entries.retention_max_age_ms",
		"delivery_queue_entries.retention_max_entries"
	],
	migrate: migratePredicateColumnsV21,
	applied: "Derived meeting transcript selectors and bounded delivery retention columns (v21)"
};
/** Complete the derived projection before any writer or column-only reader runs. */
function migratePredicateColumnsV21(e, t) {
	const n = t === 21 && statePredicateColumnMigration.columns.some((t) => {
		const n = t.indexOf(".");
		const r = t.slice(0, n);
		return tableExists(e, r) && !tableHasColumn(e, r, t.slice(n + 1));
	});
	if (t >= 21 && !n) return false;
	let r = false;
	const text = (e, t) => `CASE WHEN json_valid(${e}) THEN CASE WHEN json_type(${e}, '${t}') = 'text' THEN json_extract(${e}, '${t}') END END`;
	if (tableExists(e, "meeting_transcript_sessions")) {
		const t = [
			"accountId",
			"guildId",
			"channelId",
			"meetingUrl",
			"threadTs",
			"fileId"
		];
		const n = [
			"source_account_id",
			"source_guild_id",
			"source_channel_id",
			"source_meeting_url",
			"source_thread_ts",
			"source_file_id"
		];
		for (const t of [...n, "metadata_agent_id"]) r = ensureColumn(e, "meeting_transcript_sessions", `${t} TEXT`) || r;
		e.exec(`UPDATE meeting_transcript_sessions SET
      ${n.map((e, n) => `${e} = ${text("source_json", `$.${t[n]}`)}`).join(",")},
      metadata_agent_id = ${text("metadata_json", "$.agentId")}`);
	}
	if (tableExists(e, "meeting_transcript_summaries")) {
		r = ensureColumn(e, "meeting_transcript_summaries", "overview TEXT") || r;
		e.exec(`UPDATE meeting_transcript_summaries SET overview = ${text("summary_json", "$.overview")}`);
	}
	if (tableExists(e, "delivery_queue_entries")) {
		r = ensureColumn(e, "delivery_queue_entries", "retention_id_prefix TEXT") || r;
		r = ensureColumn(e, "delivery_queue_entries", "retention_max_age_ms INTEGER") || r;
		r = ensureColumn(e, "delivery_queue_entries", "retention_max_entries INTEGER") || r;
		e.exec(`UPDATE delivery_queue_entries SET
      (retention_id_prefix, retention_max_age_ms, retention_max_entries) = (
        SELECT id_prefix, max_age_ms, max_entries FROM (
          SELECT json_extract(entry_json, '$.completionRetention.idPrefix') id_prefix,
            json_extract(entry_json, '$.completionRetention.maxAgeMs') max_age_ms,
            json_extract(entry_json, '$.completionRetention.maxEntries') max_entries
          WHERE json_valid(entry_json)
            AND json_type(entry_json, '$.completionRetention') = 'object'
        ) WHERE typeof(id_prefix) = 'text' AND id_prefix <> ''
          AND substr(id, 1, length(id_prefix)) = id_prefix
          AND typeof(max_age_ms) = 'integer' AND max_age_ms BETWEEN 1 AND 9007199254740991
          AND typeof(max_entries) = 'integer' AND max_entries BETWEEN 1 AND 9007199254740991
      )`);
	}
	return r;
}
//#endregion
//#region src/state/openclaw-state-db-historical-imports.ts
const table = "worker_session_placements";
const archivalColumn = "repository_preparation TEXT";
/** Only the recognized historical contract may surrender its incomplete-preparation exception. */
function migrateHistoricalRepositoryPreparation(e) {
	if (!tableHasColumn(e, table, "repository_preparation")) return false;
	const t = extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, table).replace("  remote_workspace_dir TEXT,", "  " + archivalColumn + ",\n  remote_workspace_dir TEXT,");
	const n = createSqliteTableContractReader(e)(table);
	const r = parseSqliteTableDefinition(t, table);
	if (n?.strict === 1 && n.withoutRowid === 0 && isDeepStrictEqual(n.definition, r)) return false;
	const i = t.replace(archivalColumn + ",", archivalColumn + " CHECK (repository_preparation IN ('pending', 'ready', 'failed')),").replace("  CHECK (\n    (state IN", "  CHECK (repository_preparation IS NULL OR (repository_preparation = 'ready' AND workspace_base_manifest_ref IS NOT NULL) OR (repository_preparation = 'failed' AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed')) OR (repository_preparation = 'pending' AND workspace_base_manifest_ref IS NULL AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),\n  CHECK (\n    (state IN").replaceAll("AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir", "AND (workspace_base_manifest_ref IS NOT NULL OR repository_preparation IS 'pending' OR repository_preparation IS 'failed') AND remote_workspace_dir");
	if (!n || n.strict !== 1 || n.withoutRowid !== 0 || !isDeepStrictEqual(n.definition, parseSqliteTableDefinition(i, table))) throw new Error("Unrecognized historical worker placement schema; preserve the store for explicit recovery.");
	if (e.prepare("SELECT 1 FROM worker_session_placements WHERE repository_preparation IN ('pending', 'failed') AND turn_claim_owner = 'worker' LIMIT 1").get()) throw new Error("Historical repository preparation retains a worker turn claim; reconcile its owned cleanup before migrating.");
	const a = readSqliteSchemaObjects(e).filter((e) => e.tbl_name === table && (e.type === "index" || e.type === "trigger") && e.sql !== null);
	const o = n.columns.map((e) => e.name);
	const s = o.map((e) => {
		if (e === "state") return "CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'failed' ELSE state END";
		if (e === "recovery_error") return "CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'Historical repository preparation ' || repository_preparation || ' (previous placement ' || state || '); owned cleanup required before recovery.' || CASE WHEN recovery_error IS NULL THEN '' ELSE ' ' || recovery_error END ELSE recovery_error END";
		return quoteSqliteIdentifier(e);
	});
	e.exec(t.replace("CREATE TABLE IF NOT EXISTS " + table, "CREATE TABLE worker_session_placements_historical_migration") + " INSERT INTO worker_session_placements_historical_migration (rowid, " + o.map(quoteSqliteIdentifier).join(", ") + ") SELECT rowid, " + s.join(", ") + " FROM worker_session_placements; DROP TABLE worker_session_placements; ALTER TABLE worker_session_placements_historical_migration RENAME TO worker_session_placements;");
	for (const t of a) {
		if (typeof t.sql !== "string") throw new Error("Historical worker placement schema object is invalid");
		e.exec(t.sql);
	}
	return true;
}
/** Both bounded version publication and full Doctor repair retain the same historical owners. */
function migrateHistoricalStateImports(e, t, n = "version") {
	if (n === "version" && t > 22) return [];
	const r = [];
	const i = t === 21 && migrateHistoricalRepositoryPreparation(e);
	if (i) r.push("Preserved historical worker placement evidence and fenced incomplete repository preparation");
	if ((t === 21 || i) && migratePredicateColumnsV21(e, 21)) r.push(statePredicateColumnMigration.applied);
	if (n === "doctor" || t <= 22) r.push(...migrateHistoricalImageReserveSnapshots(e));
	return r;
}
//#endregion
//#region src/state/openclaw-state-db-index-ordering-migrations.ts
const stateIndexOrderingMigrations = [{
	version: 32,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Aligned PostgreSQL non-null index ordering (v32)"
}, {
	version: 33,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Aligned PostgreSQL partial-index ordering (v33)"
}];
//#endregion
//#region src/state/openclaw-state-db-meeting-chronology-migration.ts
/** The caller owns the schema transaction; legacy local dates freeze its timezone once. */
function migrateMeetingTranscriptStartTime(e, t) {
	if (t >= 23 || !tableExists(e, "meeting_transcript_sessions")) return false;
	let n = ensureColumn(e, "meeting_transcript_sessions", "started_at_ms INTEGER");
	const r = iterateSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("meeting_transcript_sessions").select(["session_id", "started_at"]));
	const i = e.prepare("UPDATE meeting_transcript_sessions SET started_at_ms = ? WHERE session_id = ? AND started_at = ?");
	for (const e of r) {
		i.run(parseDateStringTimestampMs(e.started_at) ?? null, e.session_id, e.started_at);
		n = true;
	}
	return n;
}
//#endregion
//#region src/infra/sqlite-audit-record.kernel.ts
const LEGACY_AUDIT_SEQUENCE_BASE = Number.MIN_SAFE_INTEGER;
function getAuditRecordKysely(e) {
	return getNodeSqliteKysely(e);
}
function parseAuditRecord(e) {
	return {
		key: e.event_key,
		value: JSON.parse(e.payload_json),
		createdAt: e.created_at,
		sequence: e.sequence
	};
}
function readAuditWriteState(e) {
	const t = executeSqliteQueryTakeFirstSync(e.database, getAuditRecordKysely(e.database).selectFrom("diagnostic_events").select((t) => [
		t.fn.max("sequence").filterWhere("sequence", e.legacy ? "<" : ">=", 0).as("sequence"),
		t.fn.countAll().as("count"),
		t.fn.countAll().filterWhere("event_key", "=", e.key ?? "").as("keyCount")
	]).where("scope", "=", e.scope));
	const n = (t?.sequence ?? (e.legacy ? LEGACY_AUDIT_SEQUENCE_BASE : 0)) + 1;
	if (!Number.isSafeInteger(n) || e.legacy && n >= 0) throw new Error(`Audit sequence exhausted for scope ${e.scope}`);
	return {
		nextSequence: n,
		count: coerceRequiredSqliteNumber(t?.count ?? 0),
		keyExists: coerceRequiredSqliteNumber(t?.keyCount ?? 0) > 0
	};
}
function pruneAuditRecords(e) {
	const t = e.count - e.maxEntries;
	if (t <= 0) return;
	const n = e.protectedKey;
	const r = getAuditRecordKysely(e.database).selectFrom("diagnostic_events").select("event_key").where("scope", "=", e.scope);
	const i = (n === void 0 ? r : r.where("event_key", "!=", n)).orderBy("sequence", "asc").limit(t);
	executeSqliteQuerySync(e.database, getAuditRecordKysely(e.database).deleteFrom("diagnostic_events").where("scope", "=", e.scope).where("event_key", "in", i));
}
function prepareSqliteAuditRecord(e, t) {
	const n = JSON.stringify(t.value);
	if (n === void 0) throw new Error(`Audit record ${e}/${t.key} is not JSON-serializable`);
	return {
		event_key: t.key,
		payload_json: n,
		created_at: t.createdAt
	};
}
function createAuditRecordInsert(e) {
	return prepareSqliteQuerySync(e, (t) => getAuditRecordKysely(e).insertInto("diagnostic_events").values({
		scope: t((e) => e.scope),
		event_key: t((e) => e.event_key),
		payload_json: t((e) => e.payload_json),
		created_at: t((e) => e.created_at),
		sequence: t((e) => e.sequence)
	}).onConflict((e) => e.columns(["scope", "event_key"]).doNothing()));
}
const auditRecordInsert = createSqliteQueryCache(createAuditRecordInsert);
/** Connection-bound operations; mutation callers retain the complete transaction. */
function createSqliteAuditRecordKernel(e, t) {
	const n = t.scope;
	const r = t.maxEntries;
	const prune = (t, i) => pruneAuditRecords({
		database: e,
		scope: n,
		maxEntries: r,
		count: t,
		protectedKey: i
	});
	const selectEntries = () => getAuditRecordKysely(e).selectFrom("diagnostic_events").select([
		"event_key",
		"payload_json",
		"created_at",
		"sequence"
	]).where("scope", "=", n);
	function insertRecord(t) {
		return Number(auditRecordInsert(e)({
			...t,
			scope: n
		}).numAffectedRows ?? 0);
	}
	function upsertPreparedRecord(t) {
		const r = readAuditWriteState({
			database: e,
			scope: n,
			legacy: false,
			key: t.event_key
		});
		executeSqliteQuerySync(e, getAuditRecordKysely(e).insertInto("diagnostic_events").values({
			scope: n,
			event_key: t.event_key,
			payload_json: t.payload_json,
			created_at: t.created_at,
			sequence: r.nextSequence
		}).onConflict((e) => e.columns(["scope", "event_key"]).doUpdateSet({
			payload_json: t.payload_json,
			created_at: t.created_at
		})));
		prune(r.count + (r.keyExists ? 0 : 1), t.event_key);
	}
	function deleteRecord(t) {
		executeSqliteQuerySync(e, getAuditRecordKysely(e).deleteFrom("diagnostic_events").where("scope", "=", n).where("event_key", "=", t));
	}
	return {
		register(t) {
			const r = readAuditWriteState({
				database: e,
				scope: n,
				legacy: false
			});
			const i = insertRecord({
				...t,
				sequence: r.nextSequence
			});
			prune(r.count + i, t.event_key);
		},
		upsert: upsertPreparedRecord,
		delete: deleteRecord,
		compareAndSet(t, r, i) {
			if ((executeSqliteQueryTakeFirstSync(e, getAuditRecordKysely(e).selectFrom("diagnostic_events").select("payload_json").where("scope", "=", n).where("event_key", "=", t))?.payload_json ?? null) !== r) return false;
			if (i) upsertPreparedRecord(i);
			else deleteRecord(t);
			return true;
		},
		registerLegacyMany(t) {
			const r = readAuditWriteState({
				database: e,
				scope: n,
				legacy: true
			});
			let i = r.nextSequence;
			let a = r.count;
			for (const e of t) {
				a += insertRecord({
					...e,
					sequence: i
				});
				i += 1;
			}
			prune(a);
		},
		entries() {
			return executeSqliteQuerySync(e, selectEntries().orderBy("sequence", "asc")).rows.map((e) => {
				const { sequence: t, ...n } = parseAuditRecord(e);
				return n;
			});
		},
		latest(t) {
			const n = selectEntries();
			const r = t.beforeSequence === void 0 ? n : n.where("sequence", "<", t.beforeSequence);
			return executeSqliteQuerySync(e, r.orderBy("sequence", "desc").limit(t.limit)).rows.map((e) => parseAuditRecord(e));
		}
	};
}
//#endregion
//#region src/acp/event-ledger-bytes.ts
/** Retained UTF-8 text footprint, including the existing fixed allowance per row. */
function estimateAcpSessionRowBytes(e) {
	return Buffer.byteLength(e.sessionId, "utf8") + Buffer.byteLength(e.sessionKey, "utf8") + Buffer.byteLength(e.cwd, "utf8") + 32;
}
function estimateAcpEventRowBytes(e) {
	return Buffer.byteLength(e.sessionId, "utf8") + Buffer.byteLength(e.sessionKey, "utf8") + Buffer.byteLength(e.runId ?? "", "utf8") + Buffer.byteLength(e.updateJson, "utf8") + 32;
}
//#endregion
//#region src/infra/approval-resolution-ref.ts
/** Build the full SHA-256 base64url locator used only when a transport cannot carry the exact id. */
function buildApprovalResolutionRef(e) {
	return sha256Base64Url(`${e.approvalKind}\0${e.approvalId}`);
}
//#endregion
//#region src/infra/json-object-members.ts
/** Read JSON object members without normalizing number spelling or compound values. */
function readJsonObjectMembers(e) {
	JSON.parse(e);
	const t = [];
	for (let n = 0; n < e.length;) {
		const r = e[n];
		if (/\s/u.test(r)) {
			n++;
			continue;
		}
		const i = n++;
		if (r === "\"") while (n < e.length) {
			const t = e[n++];
			if (t === "\\") n++;
			else if (t === "\"") break;
		}
		else if (!"{}[],:".includes(r)) while (n < e.length && !/[\s{}[\],:]/u.test(e[n])) n++;
		t.push(e.slice(i, n));
	}
	const n = /* @__PURE__ */ new Map();
	if (t[0] !== "{") return n;
	for (let e = 1;;) {
		const r = t[e];
		if (r === void 0 || r === "}") break;
		const i = JSON.parse(r);
		e += 2;
		const a = e;
		let o = 0;
		do {
			const n = t[e++];
			if (n === "{" || n === "[") o++;
			else if (n === "}" || n === "]") o--;
		} while (o > 0);
		if (typeof i === "string" && !n.has(i)) n.set(i, t.slice(a, e).join(""));
		if (t[e] === ",") e++;
	}
	return n;
}
//#endregion
//#region src/infra/delivery-queue-retention-columns.ts
/** Match the historical SQLite policy predicate, including its scalar coercions. */
function deriveDeliveryQueueRetentionColumns(e, t) {
	const n = {
		retention_id_prefix: null,
		retention_max_age_ms: null,
		retention_max_entries: null
	};
	try {
		const r = readJsonObjectMembers(t).get("completionRetention");
		if (!r?.startsWith("{")) return n;
		const i = readJsonObjectMembers(r);
		const a = i.get("idPrefix");
		const o = a?.startsWith("\"") ? JSON.parse(a) : a?.startsWith("[") || a?.startsWith("{") ? a : void 0;
		const s = typeof o === "string" ? o : void 0;
		const integer = (e) => {
			const t = e === "true" ? 1 : e && /^-?\d+$/u.test(e) ? Number(e) : NaN;
			return Number.isSafeInteger(t) && t >= 1 ? t : void 0;
		};
		const c = integer(i.get("maxAgeMs"));
		const l = integer(i.get("maxEntries"));
		return s && !s.includes("\0") && e.startsWith(s) && c !== void 0 && l !== void 0 ? {
			retention_id_prefix: s,
			retention_max_age_ms: c,
			retention_max_entries: l
		} : n;
	} catch {
		return n;
	}
}
//#endregion
//#region src/infra/delivery-queue-cache.ts
const outboundDeliveryNotifications = resolveGlobalSingleton(Symbol.for("openclaw.outboundDeliveryEnqueued"), () => ({ onEnqueued: (e) => {} }));
const failedDeliveryQueueHealthAdmission = {
	name: "state.failed-delivery-queue-health",
	read: (e) => e
};
//#endregion
//#region src/infra/delivery-queue-sqlite-bound.ts
const COMPLETED_TOMBSTONE_RETENTION_MS = 2592e6;
function boundedDeliveryReceipts(e) {
	return getNodeSqliteKysely(e).selectFrom("delivery_queue_entries").select([
		"queue_name",
		"id",
		"enqueued_at",
		"retention_id_prefix as id_prefix",
		"retention_max_age_ms as max_age_ms",
		"retention_max_entries as max_entries"
	]).where("status", "in", ["completed", "failed"]).where("recovery_state", "=", "completed_bounded").where("retention_id_prefix", "is not", null);
}
/** Prunes bounded receipts globally or for one exact producer namespace. */
function pruneDeliveryQueueTombstones(e, t, n) {
	let r = boundedDeliveryReceipts(e);
	if (n) r = r.where("queue_name", "=", n.queueName).where("retention_id_prefix", "=", n.idPrefix);
	const i = getNodeSqliteKysely(e);
	const a = executeSqliteQuerySync(e, i.with("policies", () => r).with("ranked", (e) => e.selectFrom("policies").selectAll().select((e) => e.fn.agg("row_number", []).over((e) => e.partitionBy(["queue_name", "id_prefix"]).orderBy("enqueued_at", "desc").orderBy("id", "desc")).as("retention_rank"))).deleteFrom("delivery_queue_entries").where((e) => e(e.refTuple("queue_name", "id"), "in", e.selectFrom("ranked").select(["queue_name", "id"]).where((e) => e.or([e("enqueued_at", "<", e(e.val(t), "-", e.ref("max_age_ms"))), e("retention_rank", ">", e.ref("max_entries"))])).$asTuple("queue_name", "id"))));
	if ((a.numAffectedRows ?? 0n) > 0n) publishSqliteDatabaseAdmission(e, failedDeliveryQueueHealthAdmission, void 0);
	const o = n ? false : pruneOrdinaryDeliveryReceipts(e, t);
	return (a.numAffectedRows ?? 0n) > 0n || o;
}
function pruneOrdinaryDeliveryReceipts(e, t) {
	return (executeSqliteQuerySync(e, getNodeSqliteKysely(e).deleteFrom("delivery_queue_entries").where("status", "=", "completed").where("enqueued_at", "<", t - COMPLETED_TOMBSTONE_RETENTION_MS).where((e) => e.or([e("recovery_state", "is", null), e("recovery_state", "not in", ["completed_permanent", "completed_bounded"])]))).numAffectedRows ?? 0n) > 0n;
}
const deliveryQueueUpserts = createSqliteQueryCache(() => ({}));
const deliveryQueueReads = createSqliteQueryCache(() => ({}));
//#endregion
//#region src/infra/delivery-queue-sqlite.types.ts
/** Parse only the shipped completion-retention shape for one exact producer ID. */
function parseDeliveryQueueCompletionRetention(e, t) {
	if (e === "permanent") return e;
	const n = asNullableRecord(e);
	if (!n) return;
	const r = typeof n.idPrefix === "string" ? n.idPrefix : "";
	const i = asPositiveSafeInteger(n.maxAgeMs);
	const a = asPositiveSafeInteger(n.maxEntries);
	if (!r || !t.startsWith(r) || i === void 0 || a === void 0) return;
	return {
		idPrefix: r,
		maxAgeMs: i,
		maxEntries: a
	};
}
const finite = (e) => typeof e === "number" && Number.isFinite(e);
/** Recover only authored or shipped producer ownership from a failed entry. */
function inferDeliveryQueueFailureRetention(e, t, n, r = false) {
	const i = parseDeliveryQueueCompletionRetention(e.completionRetention, t) ?? parseDeliveryQueueCompletionRetention(e.failureRetention, t);
	if (i) return i;
	const a = asNullableRecord(asNullableRecord(e.terminalPolicy)?.fence);
	if (a?.kind === "none") return;
	const o = a?.kind === "permanent" ? "permanent" : parseDeliveryQueueCompletionRetention(a, t);
	if (o) return o;
	const s = n === "outbound-preparing-v1" || n === "outbound-legacy-preparing-v1" || n === "outbound-prepared-migration-v1" || e.retainOnFailure === true || asNullableRecord(e.deliveryCompletion) !== null || n === "session" && finite(e.availableAt);
	const c = r && (typeof e.platformSendAttemptId === "string" && e.platformSendAttemptId.length > 0 || finite(e.platformSendStartedAt) || e.recoveryState === "send_attempt_started" || e.recoveryState === "unknown_after_send" || n === "session" && (finite(e.deliveryStartedAt) || typeof e.settlementOutcome === "string" && e.settlementOutcome.length > 0 || finite(e.acknowledgedAt)));
	return s || c ? "permanent" : void 0;
}
/** Strip a terminal queue row to the producer policy needed for admission. */
function projectDeliveryQueueTerminalEntry(e, t, n, r) {
	const i = Number.isSafeInteger(e.retryCount) && e.retryCount >= 0 ? e.retryCount : 0;
	const a = r === "permanent" ? "completed_permanent" : r ? "completed_bounded" : void 0;
	return {
		id: e.id,
		enqueuedAt: t,
		retryCount: i,
		...n === "completed" ? { acknowledgedAt: t } : { failedAt: t },
		...r ? { completionRetention: r } : {},
		...a ? { recoveryState: a } : {}
	};
}
//#endregion
//#region src/state/openclaw-state-db-delivery-queue-backfill.ts
function nonNegativeSafeInteger(e) {
	const t = typeof e === "bigint" ? Number(e) : e;
	return typeof t === "number" && Number.isSafeInteger(t) && t >= 0 ? t : void 0;
}
/** Compact every preexisting failed row without inferring replay or owner policy. */
function compactLegacyDeliveryQueueFailures(e) {
	const t = Date.now();
	const n = e.prepare(`UPDATE delivery_queue_entries SET entry_json = @entryJson,
      retention_id_prefix = @retention_id_prefix, retention_max_age_ms = @retention_max_age_ms,
      retention_max_entries = @retention_max_entries
      WHERE queue_name = @queueName AND id = @id AND status = 'pending' AND entry_json = @previousJson`);
	const r = e.prepare(`SELECT queue_name, id, status, retry_count, entry_json, updated_at, failed_at, recovery_state
       FROM delivery_queue_entries WHERE status IN ('pending', 'failed')`);
	r.setReadBigInts(true);
	const i = r.all();
	const a = e.prepare(`DELETE FROM delivery_queue_entries WHERE queue_name = ? AND id = ? AND status = 'failed'`);
	const o = e.prepare(`UPDATE delivery_queue_entries
        SET entry_kind = NULL, session_key = NULL, channel = NULL, target = NULL,
            account_id = NULL, retry_count = @retryCount, last_attempt_at = NULL,
            last_error = NULL, platform_send_started_at = NULL, entry_json = @entryJson,
            retention_id_prefix = @retention_id_prefix, retention_max_age_ms = @retention_max_age_ms,
            retention_max_entries = @retention_max_entries,
            enqueued_at = @failedAt, failed_at = @failedAt, recovery_state = @recoveryState
      WHERE queue_name = @queueName AND id = @id AND status = 'failed'`);
	for (const e of i) {
		if (e.recovery_state === "settlement_pending") continue;
		const r = safeParseJsonRecord(String(e.entry_json));
		const i = r ?? {};
		const s = String(e.queue_name);
		const c = String(e.id);
		if (e.status === "pending") {
			if (i.retainOnFailure !== true && inferDeliveryQueueFailureRetention(i, c, s, true)) {
				const t = JSON.stringify({
					...i,
					retainOnFailure: true
				});
				n.run({
					entryJson: t,
					queueName: s,
					id: c,
					previousJson: String(e.entry_json),
					...deriveDeliveryQueueRetentionColumns(c, t)
				});
			}
			continue;
		}
		const l = nonNegativeSafeInteger(e.failed_at) ?? nonNegativeSafeInteger(e.updated_at) ?? t;
		const u = Math.max(nonNegativeSafeInteger(e.retry_count) ?? 0, nonNegativeSafeInteger(i.retryCount) ?? 0);
		const d = r ? inferDeliveryQueueFailureRetention(i, c, s, true) : "permanent";
		if (!d) {
			a.run(s, c);
			continue;
		}
		const f = projectDeliveryQueueTerminalEntry({
			id: c,
			retryCount: u
		}, l, "failed", d);
		const p = JSON.stringify(f);
		o.run({
			retryCount: u,
			entryJson: p,
			...deriveDeliveryQueueRetentionColumns(c, p),
			failedAt: l,
			recoveryState: f.recoveryState ?? null,
			queueName: s,
			id: c
		});
	}
	pruneDeliveryQueueTombstones(e, t);
}
//#endregion
//#region src/state/openclaw-state-db-operator-approval-migration.ts
function tableSql$1(e) {
	const t = getAdmittedSqliteSchemaFacts(e);
	if (t) return t.tableSql.get("operator_approvals") ?? void 0;
	const n = e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'operator_approvals'").get();
	return typeof n?.sql === "string" ? n.sql : void 0;
}
function hasCanonicalOperatorApprovalKinds(e) {
	if (!tableExists(e, "operator_approvals")) return true;
	return /kind\s+text\s+not\s+null\s+check\s*\(\s*kind\s+in\s*\(\s*'exec'\s*,\s*'plugin'\s*,\s*'system-agent'\s*\)\s*\)/.test(tableSql$1(e)?.toLowerCase() ?? "");
}
function assertCanonicalOperatorApprovalKinds(e, t) {
	if (!hasCanonicalOperatorApprovalKinds(e)) throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} has a legacy operator approval schema; run openclaw doctor --fix to migrate it.`);
}
function isCanonicalOperatorApprovalKind(e) {
	return e === "exec" || e === "plugin" || e === "system-agent";
}
//#endregion
//#region src/state/openclaw-state-db-legacy-backfills.ts
function ensureOperatorApprovalResolutionRefs(e) {
	if (!tableExists(e, "operator_approvals")) return;
	runSqliteImmediateTransactionSync(e, () => {
		ensureColumn(e, "operator_approvals", "resolution_ref TEXT");
		const t = e.prepare("SELECT approval_id, kind, resolution_ref FROM operator_approvals").all();
		const n = e.prepare("UPDATE operator_approvals SET resolution_ref = ? WHERE approval_id = ?");
		for (const e of t) {
			if (typeof e.approval_id !== "string" || !isCanonicalOperatorApprovalKind(e.kind)) throw new Error("operator approval row cannot be assigned a transport reference");
			const t = buildApprovalResolutionRef({
				approvalId: e.approval_id,
				approvalKind: e.kind
			});
			if (e.resolution_ref !== t) n.run(t, e.approval_id);
		}
		if (e.prepare(`SELECT canonical.approval_id
         FROM operator_approvals AS canonical
         JOIN operator_approvals AS referenced
           ON canonical.approval_id = referenced.resolution_ref
         WHERE canonical.approval_id <> referenced.approval_id
         LIMIT 1`).get()) throw new Error("operator approval ids conflict with durable transport references");
		e.exec(`
      CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref
        ON operator_approvals(resolution_ref);
    `);
	});
}
function nullableTextValue(e, t) {
	if (!e || !Object.hasOwn(e, t)) return;
	const n = e[t];
	return typeof n === "string" || n === null ? n : void 0;
}
/** Promote shipped retained results before runtime hydrates canonical subagent state. */
function repairLegacySubagentRetainedResults(e) {
	if (!tableExists(e, "subagent_runs")) return;
	const repair = () => {
		const t = tableHasColumn(e, "subagent_runs", "pending_final_delivery_payload_json");
		const n = e.prepare(t ? "SELECT run_id, payload_json, pending_final_delivery_payload_json FROM subagent_runs" : "SELECT run_id, payload_json FROM subagent_runs").all();
		const r = e.prepare(`UPDATE subagent_runs
          SET payload_json = ?
        WHERE run_id = ?`);
		for (const e of n) {
			const t = safeParseJsonRecord(e.payload_json) ?? null;
			const n = t ? asNullableRecord(t.parentCompletion) : null;
			const i = n?.completionTarget === "parent" ? n : t;
			const a = i ? asNullableRecord(i.completion) : null;
			if (!i || !a) continue;
			const o = asNullableRecord(i.delivery);
			const s = o ? asNullableRecord(o.payload) : null;
			const c = e.pending_final_delivery_payload_json ? safeParseJsonRecord(e.pending_final_delivery_payload_json) ?? null : null;
			if (!Boolean(s && (Object.hasOwn(s, "frozenResultText") || Object.hasOwn(s, "fallbackFrozenResultText")) || c && (Object.hasOwn(c, "frozenResultText") || Object.hasOwn(c, "fallbackFrozenResultText")))) continue;
			const l = nullableTextValue(s, "frozenResultText") ?? nullableTextValue(c, "frozenResultText");
			const u = nullableTextValue(s, "fallbackFrozenResultText") ?? nullableTextValue(c, "fallbackFrozenResultText");
			if (nullableTextValue(a, "resultText") == null && l !== void 0) a.resultText = l;
			if (nullableTextValue(a, "fallbackResultText") == null && u !== void 0) a.fallbackResultText = u;
			delete s?.frozenResultText;
			delete s?.fallbackFrozenResultText;
			r.run(JSON.stringify(t), e.run_id);
		}
	};
	if (e.isTransaction) {
		repair();
		return;
	}
	runSqliteImmediateTransactionSync(e, repair);
}
/** Canonicalize shipped subagent rows whose pause/kill owner only wrote root terminal fields. */
function repairLegacySubagentExecutionPayloads(e) {
	if (!tableExists(e, "subagent_runs")) return;
	e.exec(`
    UPDATE subagent_runs
    SET payload_json = json_remove(
      CASE
        WHEN json_extract(payload_json, '$.pauseReason') = 'sessions_yield'
          AND json_extract(payload_json, '$.execution.status') <> 'terminal'
          AND json_type(payload_json, '$.endedAt') IN ('integer', 'real')
        THEN json_remove(json_set(
          payload_json,
          '$.execution.status', 'terminal',
          '$.execution.endedAt', json_extract(payload_json, '$.endedAt')
        ), '$.execution.outcome')
        WHEN (json_type(payload_json, '$.killReconciliation') = 'object'
          OR json_extract(payload_json, '$.endedReason') = 'subagent-killed')
          AND json_extract(payload_json, '$.execution.status') <> 'terminal'
          AND json_type(payload_json, '$.endedAt') IN ('integer', 'real')
          AND json_type(payload_json, '$.outcome') = 'object'
        THEN json_set(
          payload_json,
          '$.execution.status', 'terminal',
          '$.execution.endedAt', json_extract(payload_json, '$.endedAt'),
          '$.execution.outcome', json_extract(payload_json, '$.outcome')
        )
        ELSE payload_json
      END,
      '$.startedAt', '$.endedAt', '$.outcome'
    )
    WHERE json_valid(payload_json)
      AND (json_type(payload_json, '$.startedAt') IS NOT NULL
        OR json_type(payload_json, '$.endedAt') IS NOT NULL
        OR json_type(payload_json, '$.outcome') IS NOT NULL);
  `);
}
function backfillAcpReplayEstimatedBytes(e, t = false) {
	if (!tableExists(e, "acp_replay_events") || !tableHasColumn(e, "acp_replay_events", "estimated_bytes")) return;
	const n = "state.repair.acpReplayUtf8Accounting";
	const r = tableExists(e, "config_machine_state") ? getNodeSqliteKysely(e) : void 0;
	if (!t && r && executeSqliteQueryTakeFirstSync(e, r.selectFrom("config_machine_state").select("state_key").where("state_key", "=", n))) return;
	const i = getNodeSqliteKysely(e);
	const a = e.prepare("UPDATE acp_replay_events SET estimated_bytes = ? WHERE session_id = ? AND seq = ?");
	for (const t of iterateSqliteQuerySync(e, i.selectFrom("acp_replay_events").select([
		"session_id",
		"seq",
		"session_key",
		"run_id",
		"update_json",
		"estimated_bytes"
	]))) {
		const e = estimateAcpEventRowBytes({
			sessionId: t.session_id,
			sessionKey: t.session_key,
			runId: t.run_id,
			updateJson: t.update_json
		});
		if (coerceRequiredSqliteNumber(t.estimated_bytes) !== e) a.run(e, t.session_id, t.seq);
	}
	const o = e.prepare("UPDATE acp_replay_sessions SET estimated_bytes = ? WHERE session_id = ?");
	for (const t of iterateSqliteQuerySync(e, i.selectFrom("acp_replay_sessions as s").select([
		"s.session_id",
		"s.session_key",
		"s.cwd",
		"s.estimated_bytes"
	]).select((e) => e.fn.coalesce(e.selectFrom("acp_replay_events as e").select((e) => e.fn.sum("e.estimated_bytes").as("total")).whereRef("e.session_id", "=", "s.session_id"), e.val(0)).as("event_bytes")))) {
		const e = estimateAcpSessionRowBytes({
			sessionId: t.session_id,
			sessionKey: t.session_key,
			cwd: t.cwd
		}) + coerceRequiredSqliteNumber(t.event_bytes);
		if (coerceRequiredSqliteNumber(t.estimated_bytes) !== e) o.run(e, t.session_id);
	}
	if (r) executeSqliteQuerySync(e, r.insertInto("config_machine_state").values({
		state_key: n,
		value_json: "true",
		updated_at_ms: Date.now()
	}).onConflict((e) => e.column("state_key").doNothing()));
}
function backfillCronRunLogEntryJson(e) {
	if (!tableExists(e, "cron_run_logs") || !tableHasColumn(e, "cron_run_logs", "entry_json")) return;
	const t = e.prepare(`SELECT store_key, job_id, seq, ts
         FROM cron_run_logs
        WHERE entry_json = '{}'`).all();
	if (t.length === 0) return;
	const n = e.prepare(`UPDATE cron_run_logs
        SET entry_json = ?
      WHERE store_key = ? AND job_id = ? AND seq = ?`);
	for (const e of t) n.run(JSON.stringify({
		ts: coerceRequiredSqliteNumber(e.ts),
		jobId: e.job_id,
		action: "finished"
	}), e.store_key, e.job_id, e.seq);
}
function textField(e, t) {
	const n = e?.[t];
	return typeof n === "string" && n.trim() ? n : null;
}
function backfillCronJobsFromJobJson(e) {
	if (!tableExists(e, "cron_jobs") || !tableHasColumn(e, "cron_jobs", "job_json") || !tableHasColumn(e, "cron_jobs", "payload_kind")) return;
	const t = e.prepare(`SELECT store_key, job_id, job_json, updated_at
         FROM cron_jobs
        WHERE payload_kind = 'message'
           OR name = ''`).all();
	if (t.length === 0) return;
	const n = e.prepare(`UPDATE cron_jobs
        SET name = ?,
            enabled = ?,
            agent_id = ?,
            payload_kind = ?,
            runtime_updated_at_ms = ?
      WHERE store_key = ?
        AND job_id = ?`);
	for (const e of t) {
		const t = safeParseJsonRecord(e.job_json) ?? null;
		if (!t) continue;
		const r = asNullableRecord(t.schedule);
		const i = asNullableRecord(t.payload);
		const a = textField(r, "kind");
		const o = textField(i, "kind");
		const s = a === "at" && textField(r, "at");
		const c = a === "every" && asFiniteNumber(r?.everyMs) != null;
		const l = a === "cron" && textField(r, "expr");
		const u = o === "systemEvent" && textField(i, "text");
		const d = o === "agentTurn" && textField(i, "message");
		if (!r || !i || !s && !c && !l || !u && !d) continue;
		n.run(textField(t, "name") ?? e.job_id, t.enabled === false ? 0 : 1, textField(t, "agentId"), o, asFiniteNumber(t.updatedAtMs) ?? (coerceRequiredSqliteNumber(e.updated_at) || 0), e.store_key, e.job_id);
	}
}
function backfillDeliveryQueueEntriesFromEntryJson(e) {
	if (!tableExists(e, "delivery_queue_entries") || !tableHasColumn(e, "delivery_queue_entries", "entry_json") || !tableHasColumn(e, "delivery_queue_entries", "retry_count")) return;
	compactLegacyDeliveryQueueFailures(e);
	const t = e.prepare(`SELECT queue_name, id, entry_json
         FROM delivery_queue_entries
        WHERE status = 'pending'
          AND (retry_count = 0
            OR last_attempt_at IS NULL
            OR last_error IS NULL
            OR recovery_state IS NULL
            OR platform_send_started_at IS NULL
            OR entry_kind IS NULL
            OR session_key IS NULL
            OR channel IS NULL
            OR target IS NULL
            OR account_id IS NULL)`).all();
	if (t.length === 0) return;
	const n = e.prepare(`UPDATE delivery_queue_entries
        SET entry_kind = COALESCE(?, entry_kind),
            session_key = COALESCE(?, session_key),
            channel = COALESCE(?, channel),
            target = COALESCE(?, target),
            account_id = COALESCE(?, account_id),
            retry_count = ?,
            last_attempt_at = COALESCE(?, last_attempt_at),
            last_error = COALESCE(?, last_error),
            recovery_state = COALESCE(?, recovery_state),
            platform_send_started_at = COALESCE(?, platform_send_started_at)
      WHERE queue_name = ?
        AND id = ?`);
	for (const e of t) {
		const t = safeParseJsonRecord(e.entry_json) ?? null;
		if (!t) continue;
		const r = asNullableRecord(t.session);
		const i = asNullableRecord(t.route);
		const a = asNullableRecord(t.deliveryContext);
		n.run(textField(t, "kind"), textField(t, "sessionKey") ?? textField(r, "key"), textField(t, "channel") ?? textField(i, "channel") ?? textField(a, "channel"), textField(t, "to") ?? textField(i, "to") ?? textField(a, "to"), textField(t, "accountId") ?? textField(i, "accountId") ?? textField(a, "accountId"), asSafeIntegerInRange(t.retryCount, { min: 0 }) ?? 0, asSafeIntegerInRange(t.lastAttemptAt, { min: 0 }) ?? null, textField(t, "lastError"), textField(t, "recoveryState"), asSafeIntegerInRange(t.platformSendStartedAt, { min: 0 }) ?? null, e.queue_name, e.id);
	}
}
//#endregion
//#region src/state/openclaw-state-db-schema-v13-widerow.ts
const FAILURE_DESTINATION_COLUMNS = [
	["failure_delivery_mode", "mode"],
	["failure_delivery_channel", "channel"],
	["failure_delivery_to", "to"],
	["failure_delivery_account_id", "accountId"]
];
function reprojectLegacyCronJson(e) {
	const t = FAILURE_DESTINATION_COLUMNS.map(([t]) => tableHasColumn(e, "cron_jobs", t) ? quoteSqliteIdentifier(t) : `NULL AS ${quoteSqliteIdentifier(t)}`);
	const n = tableHasColumn(e, "cron_jobs", "last_run_status") ? "last_run_status" : "NULL AS last_run_status";
	const r = e.prepare(`SELECT store_key, job_id, enabled, job_json, state_json, ${n}, ${t.join(", ")}
         FROM cron_jobs`).all();
	const i = e.prepare("UPDATE cron_jobs SET job_json = ?, state_json = ? WHERE store_key = ? AND job_id = ?");
	for (const e of r) {
		if (typeof e.store_key !== "string" || typeof e.job_id !== "string" || typeof e.job_json !== "string" || typeof e.state_json !== "string") throw new Error("OpenClaw v12 cron job row is not canonical");
		const t = asNullableRecord(safeParseJson(e.job_json));
		const n = asNullableRecord(safeParseJson(e.state_json));
		if (!t || !n) continue;
		let r = false;
		const a = asNullableRecord(t.delivery);
		const o = asNullableRecord(a?.failureDestination);
		if ((!Object.hasOwn(t, "delivery") || a !== null) && (!a || !Object.hasOwn(a, "failureDestination") || o !== null)) {
			const n = a ?? {};
			const i = o ?? {};
			for (const [t, n] of FAILURE_DESTINATION_COLUMNS) {
				const a = e[t];
				if (typeof a !== "string" || Object.hasOwn(i, n)) continue;
				i[n] = a === "" ? null : a;
				r = true;
			}
			if (r) {
				n.failureDestination = i;
				t.delivery = n;
			}
		}
		if (typeof t.enabled !== "boolean") {
			t.enabled = e.enabled !== 0;
			r = true;
		}
		const s = Object.hasOwn(n, "lastStatus");
		if (!Object.hasOwn(n, "lastRunStatus") && (s || typeof e.last_run_status === "string")) {
			n.lastRunStatus = s ? n.lastStatus : e.last_run_status;
			r = true;
		}
		if (r) i.run(JSON.stringify(t), JSON.stringify(n), e.store_key, e.job_id);
	}
}
function rebuildJsonCanonicalTable(e, t) {
	const n = `${t}_migration_v13`;
	if (tableExists(e, n)) throw new Error(`OpenClaw v13 migration table already exists: ${n}`);
	const r = extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, t, { errorMessage: `Canonical ${t} schema block is missing` }).replace(`CREATE TABLE IF NOT EXISTS ${t} (`, `CREATE TABLE ${n} (`);
	e.exec(r);
	const i = e.prepare(`PRAGMA table_xinfo(${n})`).all().flatMap((e) => e.hidden === 0 && typeof e.name === "string" ? [e.name] : []);
	const a = i.map((n) => {
		return CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS.some((e) => e.tableName === t && e.columnName === n) && !tableHasColumn(e, t, n) ? "NULL" : quoteSqliteIdentifier(n);
	});
	e.exec(`INSERT INTO ${n} (${i.map(quoteSqliteIdentifier).join(", ")}) SELECT ${a.join(", ")} FROM ${t};`);
	e.exec(`DROP TABLE ${t};`);
	e.exec(`ALTER TABLE ${n} RENAME TO ${t};`);
}
/** Fold obsolete physical projections into canonical JSON before removing their columns. */
function migrateJsonCanonicalWideRowsV13(e, t) {
	if (t >= 13) return false;
	let n = false;
	if (tableExists(e, "cron_jobs") && tableHasColumn(e, "cron_jobs", "schedule_kind")) {
		reprojectLegacyCronJson(e);
		rebuildJsonCanonicalTable(e, "cron_jobs");
		n = true;
	}
	const r = tableExists(e, "workspace_setup_state");
	const i = tableExists(e, "workspace_attestations");
	if (r && !tableHasColumn(e, "workspace_setup_state", "attested_at_ms")) {
		e.exec("ALTER TABLE workspace_setup_state ADD COLUMN attested_at_ms INTEGER;");
		e.exec("ALTER TABLE workspace_setup_state ADD COLUMN attestation_updated_at_ms INTEGER;");
		rebuildJsonCanonicalTable(e, "workspace_setup_state");
		n = true;
	}
	if (i) {
		e.exec(`
      UPDATE workspace_setup_state
         SET attested_at_ms = (
               SELECT attested_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             ),
             attestation_updated_at_ms = (
               SELECT updated_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             )
       WHERE workspace_key IN (SELECT workspace_key FROM workspace_attestations);
    `);
		const t = tableExists(e, "workspace_path_aliases") ? `(SELECT alias.workspace_path FROM workspace_path_aliases alias
           WHERE alias.workspace_key = a.workspace_key LIMIT 1)` : "NULL";
		e.exec(`
      INSERT INTO workspace_setup_state (
        workspace_key, workspace_path, attested_at_ms, attestation_updated_at_ms
      )
      SELECT a.workspace_key,
             ${t},
             a.attested_at_ms,
             a.updated_at_ms
        FROM workspace_attestations a
       WHERE a.workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `);
		e.exec("DROP TABLE workspace_attestations;");
		n = true;
	}
	if ((r || i) && tableExists(e, "workspace_generated_bootstrap_hashes")) {
		rebuildJsonCanonicalTable(e, "workspace_generated_bootstrap_hashes");
		e.exec(`
      DELETE FROM workspace_generated_bootstrap_hashes
       WHERE workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `);
	}
	for (const [t, r, i] of [[
		"auth_profile_stores",
		"store_json",
		"authProfiles.store"
	], [
		"auth_profile_state",
		"state_json",
		"authProfiles.state"
	]]) {
		if (!tableExists(e, t)) continue;
		e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
       SELECT ?, ${r}, updated_at FROM ${t} WHERE store_key = 'shared'
       ON CONFLICT(state_key) DO NOTHING`).run(i);
		e.exec(`DROP TABLE ${t};`);
		n = true;
	}
	if (tableExists(e, "installed_plugin_index")) {
		const t = e.prepare("SELECT * FROM installed_plugin_index WHERE index_key = 'installed-plugin-index'").get();
		if (t) {
			const n = asNullableRecord(safeParseJson(String(t.install_records_json)));
			const r = safeParseJson(String(t.plugins_json));
			const i = safeParseJson(String(t.diagnostics_json));
			if (!n || !Array.isArray(r) || !Array.isArray(i)) {
				const n = "plugins.installedIndex.quarantine";
				const r = `Preserved invalid legacy installed_plugin_index row in diagnostic_events (${n}). Run openclaw doctor --fix or openclaw plugins registry --refresh to repair the plugin index; inspect the preserved row if install records need recovery.`;
				createSqliteAuditRecordKernel(e, {
					scope: n,
					maxEntries: Number.MAX_SAFE_INTEGER
				}).register(prepareSqliteAuditRecord(n, {
					key: createHash("sha256").update(JSON.stringify(t)).digest("hex"),
					value: {
						level: "warn",
						message: r,
						raw: t
					},
					createdAt: Date.now()
				}));
				deferSqlitePostCommitPublication(e, () => createSubsystemLogger("state/db").warn(r));
			}
			const a = {
				version: Number(t.version),
				...typeof t.warning === "string" && t.warning ? { warning: t.warning } : {},
				hostContractVersion: t.host_contract_version,
				compatRegistryVersion: t.compat_registry_version,
				migrationVersion: Number(t.migration_version),
				policyHash: t.policy_hash,
				generatedAtMs: Number(t.generated_at_ms),
				...typeof t.workspace_dir === "string" ? { workspaceDir: t.workspace_dir } : {},
				...typeof t.refresh_reason === "string" && t.refresh_reason ? { refreshReason: t.refresh_reason } : {},
				installRecords: n,
				plugins: r,
				diagnostics: i
			};
			e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
         VALUES (?, ?, ?) ON CONFLICT(state_key) DO NOTHING`).run("plugins.installedIndex", JSON.stringify({
				revision: Number(t.updated_at_ms),
				index: a
			}), Number(t.updated_at_ms));
		}
		e.exec("DROP TABLE installed_plugin_index;");
		n = true;
	}
	if (tableExists(e, "subagent_runs") && tableHasColumn(e, "subagent_runs", "task")) {
		repairLegacySubagentRetainedResults(e);
		rebuildJsonCanonicalTable(e, "subagent_runs");
		n = true;
	}
	return n;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v22-columns.ts
const STATE_CURSOR_TABLES_V22 = [
	"operator_approvals",
	"cron_run_receipts",
	"execution_decision_facts",
	"skill_workshop_changes"
];
/** The schema owner holds the migration transaction with foreign keys disabled. */
function migratePortableIdentityColumnsV22(e, t) {
	if (t >= 22) return false;
	let n = false;
	const r = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e);
	for (const t of STATE_CURSOR_TABLES_V22) {
		if (!tableExists(e, t) || tableHasColumn(e, t, "cursor_id")) continue;
		const i = r.tableSql.get(t);
		if (typeof i !== "string") throw new Error(`Missing v22 cursor migration schema: ${t}`);
		const a = quoteSqliteIdentifier(`${t}_migration_v22`);
		const o = quoteSqliteIdentifier(t);
		const s = [...readTableColumns$1(e, t)].map(quoteSqliteIdentifier).join(", ");
		e.exec(`CREATE TABLE ${a} (cursor_id INTEGER NOT NULL, ${i.slice(i.indexOf("(") + 1)};
      INSERT INTO ${a} (rowid, ${s}, cursor_id) SELECT rowid, ${s}, rowid FROM ${o} ORDER BY rowid;
      DROP TABLE ${o};
      ALTER TABLE ${a} RENAME TO ${o};`);
		for (const n of [...r.indexDefinitions.values(), ...r.triggers.values()]) if (n.table === t && typeof n.sql === "string") e.exec(n.sql);
		n = true;
	}
	if (tableExists(e, "acp_sessions")) {
		n = ensureColumn(e, "acp_sessions", "resume_agent_session_id TEXT") || n;
		n = ensureColumn(e, "acp_sessions", "resume_acpx_session_id TEXT") || n;
		const t = "CASE WHEN json_valid(identity_json) THEN identity_json END";
		const r = "char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279)";
		e.exec(`UPDATE acp_sessions SET
      resume_agent_session_id = CASE WHEN json_type(${t}, '$.agentSessionId') = 'text'
        THEN trim(json_extract(${t}, '$.agentSessionId'), ${r}) END,
      resume_acpx_session_id = CASE WHEN json_type(${t}, '$.acpxSessionId') = 'text'
        THEN trim(json_extract(${t}, '$.acpxSessionId'), ${r}) END;
      DROP INDEX IF EXISTS idx_acp_sessions_resume_agent;
      DROP INDEX IF EXISTS idx_acp_sessions_resume_acpx;`);
	}
	return n;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v24-indexes.ts
const TASK_RUN_INDEX_RETIREMENT_V24_SQL = `
    DROP INDEX IF EXISTS idx_task_runs_run_id;
    DROP INDEX IF EXISTS idx_task_runs_status;
    DROP INDEX IF EXISTS idx_task_runs_runtime_status;
    DROP INDEX IF EXISTS idx_task_runs_cleanup_after;
    DROP INDEX IF EXISTS idx_task_runs_last_event_at;
    DROP INDEX IF EXISTS idx_task_runs_owner_key;
    DROP INDEX IF EXISTS idx_task_runs_parent_flow_id;
    DROP INDEX IF EXISTS idx_task_runs_child_session_key;
    DROP INDEX IF EXISTS idx_task_runs_requester_session_key;
    DROP INDEX IF EXISTS idx_task_runs_runtime_source_ended;
    DROP INDEX IF EXISTS idx_task_runs_runtime_ended;
`;
/** Canonical DDL installs the replacement indexes in the same migration transaction. */
function migrateTaskRunIndexesV24(e, t) {
	if (t >= 24) return false;
	e.exec(TASK_RUN_INDEX_RETIREMENT_V24_SQL);
	return true;
}
//#endregion
//#region src/state/sqlite-table-layout-migration.ts
/** The schema owner holds the migration transaction with foreign keys disabled. */
function migrateSqliteTableWithoutRowid(e, t) {
	const n = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e);
	const r = n.tableSql.get(t);
	if (!r) return false;
	const i = findSqlCharacter(r, "(");
	const a = findSqlClosingParenthesis(r, i);
	const o = r.slice(a + 1).replace(/;\s*$/u, "").trim();
	if (/\bWITHOUT\s+ROWID\b/iu.test(o)) return false;
	const s = quoteSqliteIdentifier(t);
	const c = quoteSqliteIdentifier(`${t}_without_rowid_migration`);
	const l = [...readTableColumns$1(e, t)].map(quoteSqliteIdentifier).join(", ");
	e.exec(`CREATE TABLE ${c} ${r.slice(i, a + 1)}
      ${o ? `${o}, ` : ""}WITHOUT ROWID;
    INSERT INTO ${c} (${l}) SELECT ${l} FROM ${s};
    DROP TABLE ${s};
    ALTER TABLE ${c} RENAME TO ${s};`);
	for (const r of [...n.indexDefinitions.values(), ...n.triggers.values()]) if (r.table === t && typeof r.sql === "string") e.exec(r.sql);
	return true;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v26-layout.ts
/** Historical admission compares the physical layout installed before v26. */
function withLegacyStateHeadLayout(e) {
	return e.replace(/(CREATE TABLE IF NOT EXISTS session_state_heads \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u, "$1;");
}
function migrateSessionStateHeadLayoutV26(e, t) {
	return t < 26 && migrateSqliteTableWithoutRowid(e, "session_state_heads");
}
//#endregion
//#region src/state/openclaw-state-db-schema-v27-indexes.ts
/** Exact historical indexes used by source admission and the PostgreSQL generator. */
function withLegacyStateWriteIndexes(e) {
	return `${e.replace(/ON state_leases\(owner\);/u, "ON state_leases(owner, updated_at DESC);")}
CREATE INDEX IF NOT EXISTS idx_skill_usage_key
  ON skill_usage(skill_key, skill_file);
CREATE INDEX IF NOT EXISTS idx_acp_replay_events_session_seq
  ON acp_replay_events(session_id, seq);
`;
}
const STATE_WRITE_INDEX_RETIREMENT_V27_SQL = `
  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;
  DROP INDEX IF EXISTS idx_skill_usage_key;
  DROP INDEX IF EXISTS idx_state_leases_owner;
`;
function migrateStateWriteIndexesV27(e, t) {
	if (t >= 27) return false;
	e.exec(STATE_WRITE_INDEX_RETIREMENT_V27_SQL);
	return true;
}
//#endregion
//#region src/infra/state-database-maintenance.ts
const StateSchemaMutationConflictError = resolveGlobalSingleton(Symbol.for("openclaw.stateSchemaMutationConflictError"), () => class SchemaMutationConflictError extends Error {
	constructor(e, t) {
		super(`OpenClaw refused shared state schema mutation at ${e} because another Gateway owns that state directory. Stop that Gateway or perform the update through its managed restart path, then retry.`, { cause: t });
		this.name = "StateSchemaMutationConflictError";
	}
});
/** Only a newly acquired lease belongs to this call's cleanup. */
function acquireSchemaMaintenanceLease({ databasePath: e, busyTimeoutMs: t }) {
	if (requestSqliteWorkerSchemaMaintenance(e)) return;
	const n = resolveIdentityPathViaExistingAncestorSync(e);
	const r = getStateDatabaseSchemaLease(n);
	if (r) {
		r.assertCurrent();
		return;
	}
	try {
		return acquireStateDatabaseSchemaLease(n, { busyTimeoutMs: t });
	} catch (e) {
		if (e instanceof GatewayStateOwnerContentionError) throw new StateSchemaMutationConflictError(n, e);
		throw e;
	}
}
/** Ordinary transactions use SQLite; schema changes retain the installation's process owner. */
function withStateDatabaseSchemaMaintenance(e, t) {
	const n = acquireSchemaMaintenanceLease(e);
	if (!n) return t();
	return runWithSqliteCleanup(n, "state schema mutation", () => n.run(t));
}
//#endregion
//#region src/state/openclaw-state-ownership.ts
const STATE_SUPERVISION_KEY = "gateway.supervision";
const MAX_OWNERSHIP_TIMESTAMP_MS = 864e13;
const MANAGER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const ownershipAdmission = {
	name: "state.external-ownership",
	read(e) {
		if (e === null) return null;
		if (isRecord(e) && e.version === 1 && e.mode === "external" && typeof e.managerId === "string" && typeof e.claimedAt === "number") return {
			version: 1,
			mode: "external",
			managerId: e.managerId,
			claimedAt: e.claimedAt
		};
	}
};
function isOpenClawStateWriteContentionError(e) {
	return e instanceof GatewayStateOwnerContentionError || e instanceof StateSchemaMutationConflictError || isSqliteLockError(e);
}
function parseExternalOwnership(e, t) {
	let n;
	try {
		n = JSON.parse(e);
	} catch {
		throw new OpenClawStateOwnershipMetadataError(t, "reserved value is not valid JSON");
	}
	const r = isRecord(n) ? n : void 0;
	const i = r ? Object.keys(r).toSorted().join(",") : "";
	const a = r?.managerId;
	const o = r?.claimedAt;
	if (i !== "claimedAt,managerId,mode,version" || r?.version !== 1 || r?.mode !== "external" || typeof a !== "string" || !MANAGER_ID_PATTERN.test(a) || typeof o !== "number" || !Number.isSafeInteger(o) || o < 0 || o > MAX_OWNERSHIP_TIMESTAMP_MS) throw new OpenClawStateOwnershipMetadataError(t, "reserved value does not match the version 1 external ownership contract");
	return {
		version: 1,
		mode: "external",
		managerId: a,
		claimedAt: o
	};
}
/** Inspect the reserved ownership row without entering the shared-state lifecycle. */
function inspectOpenClawStateOwnershipFromDatabase(e, t, n = false) {
	try {
		if (!n && !tableExists(e, "config_machine_state")) return null;
		const r = n || isPostgresSqlConnection(e) ? "SELECT value_json FROM config_machine_state WHERE state_key = ? LIMIT 1" : "SELECT value_json FROM config_machine_state NOT INDEXED WHERE state_key = ? LIMIT 1";
		const i = e.prepare(r).get(STATE_SUPERVISION_KEY);
		if (!i) return null;
		if (typeof i.value_json !== "string") throw new OpenClawStateOwnershipMetadataError(t, "reserved value is not text");
		return parseExternalOwnership(i.value_json, t);
	} catch (e) {
		throw normalizeOpenClawStateSchemaReadError(e, t);
	}
}
function assertOwnershipAllowsWrite(e, t, n) {
	if (e && !isGatewayExternallySupervised(n)) throw new OpenClawStateExternalOwnershipError(t, e.managerId);
}
/** Fence shared-state writes once an external manager has claimed ownership. */
function assertOpenClawStateWriteAllowed(e) {
	const t = path.resolve(e.databasePath);
	assertStateDatabaseAccessAllowed(t);
	let n = e.inspectOwnership ? void 0 : getSqliteDatabaseAdmission(e.database, ownershipAdmission);
	if (n === void 0) {
		const r = inspectOpenClawStateOwnershipFromDatabase(e.database, t, e.schemaReady);
		n = e.inspectOwnership ? void 0 : getSqliteDatabaseAdmission(e.database, ownershipAdmission);
		if (n === void 0) {
			n = r;
			publishSqliteDatabaseAdmission(e.database, ownershipAdmission, n);
		}
	}
	assertOwnershipAllowsWrite(n, t, e.env ?? process.env);
}
//#endregion
//#region src/state/openclaw-state-schema-runtime.ts
const runtimeSchemaCache = /* @__PURE__ */ new Map();
/** Project canonical SQL to the tables the shared runtime may create during this open. */
function getOpenClawStateRuntimeSchema(e) {
	const { includeVersionLazyAdditiveTables: t, includeAgentDeletionJournal: n = true } = e;
	const r = `${t}:${n}`;
	const i = runtimeSchemaCache.get(r);
	if (i !== void 0) return i;
	let a = OPENCLAW_STATE_SCHEMA_SQL;
	const o = [...t ? FIRST_USE_STATE_TABLES : LAZY_ADDITIVE_STATE_TABLES, ...n ? [] : DOCTOR_OWNED_STATE_TABLES];
	const s = t ? FIRST_USE_STATE_INDEXES : LAZY_ADDITIVE_STATE_INDEXES;
	for (const e of o) a = a.replace(extractSqliteTableSchema(a, e, { errorMessage: `lazy additive state schema block is missing for ${e}` }), "");
	for (const e of s) {
		const t = a.indexOf(`CREATE INDEX IF NOT EXISTS ${e}`);
		const n = a.indexOf(`CREATE UNIQUE INDEX IF NOT EXISTS ${e}`);
		const r = t >= 0 ? t : n;
		const i = r >= 0 ? a.indexOf(";", r) : -1;
		if (r < 0 || i < 0) throw new Error(`lazy additive state schema index is missing for ${e}`);
		a = `${a.slice(0, r)}${a.slice(i + 1)}`;
	}
	runtimeSchemaCache.set(r, a);
	return a;
}
//#endregion
//#region src/state/openclaw-state-schema-compatibility.ts
const STATE_V6_ADDITIVE_TABLES = [
	...LAZY_ADDITIVE_STATE_TABLES,
	"worker_session_tool_operations",
	"worker_turn_tool_authorities"
];
const STATE_V5_ADDITIVE_TABLES = [
	"agent_database_leases",
	"agent_deletion_journal",
	"claw_cron_refs",
	"claw_installs",
	"claw_mcp_server_refs",
	"claw_package_refs",
	"claw_workspace_files",
	"config_machine_state",
	"cron_job_scratch",
	"meeting_transcript_sessions",
	"meeting_transcript_summaries",
	"meeting_transcript_utterances",
	"outbound_media_provenance",
	"worker_environment_credentials",
	"worker_transcript_commit_heads",
	"worker_transcript_commits",
	...STATE_V6_ADDITIVE_TABLES
];
const CLAW_LAZY_ADDITIVE_STATE_COLUMNS = CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`);
const CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS = CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`);
const CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_SET = new Set(CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS);
const CLAW_STARTUP_ADDITIVE_STATE_COLUMN_SET = /* @__PURE__ */ new Set([...CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`), ...Object.values(ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS).flat().map(([e, t]) => `${e}.${t.split(" ", 1)[0]}`)]);
const CLAW_STARTUP_ADDITIVE_STATE_TABLES = ["worker_session_tool_operations", "worker_turn_tool_authorities"];
const CLAW_STARTUP_ADDITIVE_STATE_TABLE_SET = new Set(CLAW_STARTUP_ADDITIVE_STATE_TABLES);
const CLAW_READONLY_OPTIONAL_STATE_INDEXES = [
	"idx_meeting_transcript_utterances_id",
	"idx_operator_approvals_source_run_resolved",
	"idx_worker_session_placements_environment"
];
const RETAINED_STATE_TABLES = ["fleet_cells"];
const STATE_PERSISTENT_SCHEMA_COMPATIBILITY = {
	excludedTables: RETAINED_STATE_TABLES,
	allowCompatibleAdditiveColumns: true,
	allowedMissingTables: DOCTOR_OWNED_STATE_TABLES,
	allowedMissingColumns: CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS,
	allowedColumnDefinitions: {
		"diagnostic_events.sequence": ["sequence INTEGER NOT NULL DEFAULT 0"],
		"template_package_refs.package_integrity": ["package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'"],
		"template_package_refs.updated_at_ms": ["updated_at_ms INTEGER NOT NULL DEFAULT 0"],
		"cron_jobs.enabled": ["enabled INTEGER NOT NULL DEFAULT 1"],
		"cron_jobs.name": ["name TEXT NOT NULL DEFAULT ''"],
		"cron_jobs.payload_kind": ["payload_kind TEXT NOT NULL DEFAULT 'message'"],
		"current_conversation_bindings.conversation_kind": ["conversation_kind TEXT NOT NULL DEFAULT 'channel'"],
		"operator_approvals.resolution_ref": ["resolution_ref TEXT"],
		"worker_environments.desktop_json": ["desktop_json TEXT"],
		"worker_environments.bootstrap_install_kind": ["bootstrap_install_kind TEXT"],
		"worker_environments.shared_host": ["shared_host INTEGER CHECK (shared_host IN (0, 1))"],
		"worker_environments.node_setup_id": ["node_setup_id TEXT"],
		"worker_environments.node_device_id": ["node_device_id TEXT"],
		"worker_session_placements.terminal_reason": ["terminal_reason TEXT"],
		"worker_session_placements.terminal_at_ms": ["terminal_at_ms INTEGER"]
	}
};
const STATE_RUNTIME_SCHEMA_COMPATIBILITY = {
	...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
	excludedTables: [...RETAINED_STATE_TABLES, ...LAZY_ADDITIVE_STATE_TABLES],
	excludedIndexes: LAZY_ADDITIVE_STATE_INDEXES
};
/** Both cold admission and bounded upgrade selection require these present-table columns. */
function findMissingLazyStateStartupColumn(e) {
	for (const { tableName: t, columnName: n } of CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS) {
		if (!STATE_RUNTIME_SCHEMA_COMPATIBILITY.excludedTables?.includes(t)) continue;
		const r = e(t);
		if (r && !r.columns.some((e) => e.name === n)) return {
			tableName: t,
			columnName: n
		};
	}
}
const OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY = {
	...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
	allowedMissingTables: [
		...LAZY_ADDITIVE_STATE_TABLES,
		...CLAW_STARTUP_ADDITIVE_STATE_TABLES,
		...DOCTOR_OWNED_STATE_TABLES
	],
	allowedMissingIndexes: CLAW_READONLY_OPTIONAL_STATE_INDEXES,
	allowedMissingColumns: CLAW_LAZY_ADDITIVE_STATE_COLUMNS
};
//#endregion
//#region src/state/openclaw-update-schema-refusal.ts
/** An unfenced updater needs a manual update when safe publication deferral is unavailable. */
var UpdateSchemaRefusalError = class extends Error {
	constructor(e, t, n) {
		const { targetVersion: r } = n;
		const i = n.recovery?.commands ?? [
			"openclaw gateway stop",
			`npm install -g openclaw@${r} --allow-scripts=openclaw`,
			"openclaw doctor --fix",
			"openclaw gateway start"
		];
		const a = n.cause === void 0 ? "" : ` Deferral failed: ${formatErrorMessage(n.cause).slice(0, 600)}.`;
		const o = `Doctor refused update-time schema repair driven by OpenClaw ${t}: this updater reopens the ledger with old code after migration, and version publication could not be deferred safely.`;
		const s = `${e.map((e) => `${e.kind} database ${e.path}: on-disk schema ${e.foundVersion}, this build's schema ${e.supportedVersion}.`).join(" ")}${a} The blocked schema change was not applied.`;
		super(n.recovery ? `${o} ${s}\n${n.recovery.message}` : [
			o,
			s,
			"Let the updater restore the previous package and exit. Then use an independent shell with the original service account, package prefix, profile, and state/config overrides.",
			`Manual update: ${i.join(" && ")}.`,
			`Use the package manager that owns this install (pnpm: pnpm add -g --allow-build=openclaw openclaw@${r}; Bun: bun add -g --trust openclaw@${r}). On npm 11.15 and earlier, omit --allow-scripts=openclaw.`
		].join("\n"), n);
		this.databases = e;
		this.updaterVersion = t;
		this.code = "update-schema-bump-unfenced";
		this.name = "UpdateSchemaRefusalError";
		this.targetVersion = r;
		this.commands = i;
	}
};
//#endregion
//#region src/state/schema-migration-backup-tables.ts
/** Destination versions, declared only with proof through the complete migration runner. */
const SCHEMA_MIGRATION_BACKUP_TABLES = {
	agent: {
		[30]: [
			"trajectory_runtime_events",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		27: [
			"context_engine_turn_outbox",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		28: [
			"transcript_event_identities",
			"session_windows",
			"memory_entry_origins",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		29: [
			"session_nodes",
			"session_reactions",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		31: ["memory_index_sources", "memory_index_chunks"],
		32: [],
		33: [],
		34: [],
		35: [],
		36: [],
		37: ["session_transcript_cold_archive_chunks"],
		38: []
	},
	state: {
		[29]: [
			...CLIENT_CREDENTIAL_SOURCE_TABLES,
			"sqlite_stat1",
			"sqlite_stat4"
		],
		[23]: ["meeting_transcript_sessions", "worker_environments"],
		26: [
			"session_state_heads",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		27: [
			"acp_replay_events",
			"skill_usage",
			"state_leases",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		28: [
			"github_publication_requests",
			"github_personal_publication_requests",
			"github_repository_publication_requests"
		],
		30: [],
		31: [
			"local_workspace_projections",
			"local_workspace_manifest_nodes",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		32: [],
		33: [],
		34: ["config_machine_state"],
		35: [
			"local_workspace_projections",
			"local_workspace_manifest_nodes",
			"local_workspace_tree_packs",
			"local_workspace_source_path_sets"
		],
		36: [
			"claw_installs",
			"template_installs",
			"claw_workspace_files",
			"template_workspace_files",
			"claw_package_refs",
			"template_package_refs",
			"claw_cron_refs",
			"template_cron_refs",
			"claw_mcp_server_refs",
			"template_mcp_server_refs",
			"agent_provenance",
			"sqlite_stat1",
			"sqlite_stat4"
		]
	}
};
//#endregion
//#region src/state/schema-migration-integrity-tables.ts
const indexStatistics = ["sqlite_stat1", "sqlite_stat4"];
const SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES = {
	agent: [
		"auth_profile_store",
		"auth_profile_state",
		"session_nodes",
		"session_entry_snapshots",
		"session_windows",
		"session_key_contract",
		"session_canonical_validation_pending",
		"memory_index_chunks",
		"memory_index_chunk_recall_metadata",
		"memory_index_chunk_provenance",
		"memory_index_sources",
		"memory_index_paths_fts",
		"memory_index_state",
		...indexStatistics
	],
	state: [
		...CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ tableName: e }) => e),
		...Object.values(ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS).flatMap((e) => e.map(([e]) => e)),
		"audit_events",
		"audit_identity_keys",
		"operator_approvals",
		"session_watch_cursors",
		"subagent_runs",
		"worker_session_placements",
		"meeting_transcript_sessions",
		"meeting_transcript_summaries",
		"delivery_queue_entries",
		"worker_turn_tool_authorities",
		"worker_session_tool_operations",
		"migration_runs",
		"sqlite_sequence",
		...indexStatistics
	]
};
const migrationTables = {
	agent: {
		...SCHEMA_MIGRATION_BACKUP_TABLES.agent,
		10: ["session_transcript_active_events", "session_transcript_index_state"],
		11: [
			"sessions",
			"conversations",
			"session_conversations"
		],
		13: ["transcript_rewrite_watermarks"],
		14: [
			"sessions",
			"session_entries",
			"session_routes",
			"session_nodes",
			"session_windows",
			"session_transcript_generations",
			"transcript_rewrite_watermarks",
			"board_tabs",
			"board_widgets",
			"heartbeat_outcomes",
			"session_members",
			"session_transcript_index_state"
		],
		17: ["state_leases"],
		18: ["session_participants"],
		19: ["session_nodes"],
		21: ["session_key_contract", "session_canonical_validation_pending"],
		22: ["session_transcript_fts_rows"],
		23: [
			"transcript_events",
			"session_transcript_fts",
			"session_transcript_fts_rows",
			"session_transcript_index_state",
			"memory_index_sources",
			"memory_index_chunks",
			"memory_index_chunks_fts",
			"memory_index_chunk_recall_metadata",
			"memory_embedding_cache",
			"memory_index_meta",
			"memory_index_state",
			"cache_entries"
		],
		24: ["session_nodes", "session_entry_snapshots"],
		25: [
			"session_pending_inputs",
			"session_nodes",
			"session_windows",
			"session_key_contract",
			"session_canonical_validation_pending"
		],
		26: [
			"session_nodes",
			"context_engine_turn_outbox",
			"transcript_events"
		]
	},
	state: {
		...SCHEMA_MIGRATION_BACKUP_TABLES.state,
		2: [
			"audit_events",
			"audit_identity_keys",
			"sqlite_sequence"
		],
		4: ["session_watch_cursors"],
		7: ["commitments"],
		8: ["worker_session_placements"],
		9: ["agent_databases"],
		10: [
			"agent_model_catalogs",
			"android_notification_recent_packages",
			"command_log_entries",
			"diagnostic_stability_bundles",
			"media_blobs",
			"model_capability_cache"
		],
		11: ["skill_lifecycle", "skill_workshop_proposal_origin_runs"],
		12: [
			"config_machine_state",
			"skill_curator_state",
			"update_check_state",
			"clawhub_promotions_feed_state",
			"model_catalog_remote",
			"voicewake_triggers",
			"voicewake_routing_routes",
			"voicewake_routing_config",
			"onboarding_recommendations",
			"cron_store_epochs",
			"tui_last_sessions",
			"sidebar_sections",
			"node_host_config",
			"web_push_vapid_keys"
		],
		13: [
			"cron_jobs",
			"subagent_runs",
			"workspace_setup_state",
			"workspace_attestations",
			"workspace_generated_bootstrap_hashes",
			"auth_profile_stores",
			"auth_profile_state",
			"installed_plugin_index",
			"config_machine_state",
			"diagnostic_events"
		],
		14: ["cron_jobs"],
		15: ["current_conversation_bindings"],
		17: ["worker_environments"],
		18: ["github_publication_session_lifecycles", "github_repository_publication_requests"],
		20: ["cron_run_receipts"],
		21: [
			"meeting_transcript_sessions",
			"meeting_transcript_summaries",
			"delivery_queue_entries",
			...indexStatistics
		],
		22: [
			"worker_session_placements",
			"meeting_transcript_sessions",
			"meeting_transcript_summaries",
			"delivery_queue_entries",
			"acp_sessions",
			"operator_approvals",
			"cron_run_receipts",
			"execution_decision_facts",
			"skill_workshop_changes",
			...indexStatistics
		],
		24: ["task_runs", ...indexStatistics],
		25: []
	}
};
/** Cumulative mutation scope; STRICT and index-repair owners check their actual rebuilds. */
function resolveSchemaMigrationIntegrityTables(e) {
	const t = /* @__PURE__ */ new Set(["schema_meta"]);
	if (e.foundVersion === e.supportedVersion) for (const n of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES[e.kind]) t.add(n);
	for (let n = e.foundVersion + 1; n <= e.supportedVersion; n++) for (const r of migrationTables[e.kind][n] ?? []) t.add(r);
	if (e.kind === "agent") {
		for (const { tableName: e } of STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS) t.add(e);
		if (e.foundVersion < 20) {
			t.add("board_widgets");
			t.add("memory_index_sources");
			t.add("memory_index_paths_fts");
		}
		if (e.foundVersion < 25) for (const e of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.agent) t.add(e);
	} else {
		t.add("config_machine_state");
		if (e.foundVersion < 20) for (const e of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.state) t.add(e);
	}
	return [...t].toSorted();
}
//#endregion
//#region src/state/openclaw-state-db-maintenance.ts
function assertMigratedStateTableIntegrity(e, t, n, r = false) {
	const i = resolveSchemaMigrationIntegrityTables({
		kind: "state",
		foundVersion: n,
		supportedVersion: 36
	});
	const a = r ? /* @__PURE__ */ new Set([...i, ...SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.state]) : i;
	for (const n of a) if (tableExists(e, n)) assertSqliteTableIntegrity(e, t, n);
}
const STATE_MIGRATION_VERSIONS = [
	5,
	6,
	7,
	8,
	9,
	10,
	11,
	12,
	13,
	14,
	15,
	16,
	17,
	18,
	19,
	20,
	21,
	22,
	23,
	24,
	25,
	26,
	27,
	28
];
/** Require canonical shared-state ownership without requiring the latest schema. */
function assertOpenClawStateDatabaseOwner(e, t) {
	const n = getStateSchemaVersionAdmission(e);
	if (n && getStateRuntimeSchemaAdmission(e)) return { schema_version: n.userVersion };
	const r = tableExists(e, "schema_meta");
	let i;
	try {
		i = r ? e.prepare("SELECT role, schema_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1").get() : void 0;
	} catch (t) {
		throw classifySqliteTableReadError(e, "schema_meta", [
			"meta_key",
			"role",
			"schema_version"
		], t);
	}
	if (i?.role !== "global") {
		const e = typeof i?.role === "string" ? i.role : "missing";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} has schema role ${e}; expected global. Run openclaw doctor --fix to inspect and repair its ownership.`);
	}
	return i;
}
/** Require the canonical shared-state owner and schema before offline file maintenance. */
function assertOpenClawStateDatabaseForMaintenance(e, t, n) {
	const { pathname: r, schemaVersions: i } = t;
	if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
	const a = assertSupportedStateSchemaVersion(e, r, i);
	if ((i?.contentVersion ?? readStateSchemaContentVersion(e)) !== 36) throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} uses schema version ${a}; run openclaw doctor --fix before compacting it.`);
	const o = assertOpenClawStateDatabaseOwner(e, t);
	if (o?.schema_version !== a && !adoptPeerPublishedStateSchemaVersion(e, o)) {
		const e = typeof o?.schema_version === "number" ? o.schema_version : "invalid";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} metadata schema version ${e} does not match ${a}; run openclaw doctor --fix before compacting it.`);
	}
	assertSqliteSchemaContains(e, r, OPENCLAW_STATE_SCHEMA_SQL, OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY, n);
}
function assertOpenClawStateDatabaseVersionForMigration(e, t) {
	const n = readSqliteUserVersion(e);
	if (readStateSchemaContentVersion(e) !== t.version) throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} uses schema version ${n}; expected ${t.version} before migrating it.`);
	const r = assertOpenClawStateDatabaseOwner(e, t);
	if (r?.schema_version !== n) {
		const e = typeof r?.schema_version === "number" ? r.schema_version : "invalid";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${n}; repair the ownership metadata before migrating it.`);
	}
	assertSqliteSchemaTablesPresent(e, t.pathname, withLegacyTemplateStateSchema(OPENCLAW_STATE_SCHEMA_SQL), { allowedMissingTables: [...t.version === 5 ? STATE_V5_ADDITIVE_TABLES : t.version < 13 ? STATE_V6_ADDITIVE_TABLES : LAZY_ADDITIVE_STATE_TABLES, ...DOCTOR_OWNED_STATE_TABLES] });
}
/** Keep historical migration gates beside their version-specific ownership assertions. */
const openClawStateMigrationAssertions = new Map(STATE_MIGRATION_VERSIONS.map((e) => [e, (t, n) => assertOpenClawStateDatabaseVersionForMigration(t, {
	...n,
	version: e
})]));
function markCurrentStateSchemaVersion(e, t = {}) {
	if (!tableExists(e, "audit_events")) return;
	const n = resolveStateSchemaVersionToPublish(e);
	if (readSqliteUserVersion(e) !== n) e.exec(`PRAGMA user_version = ${n};`);
	publishStateSchemaVersionAdmission(e, {
		userVersion: n,
		contentVersion: 36
	});
	if (tableExists(e, "schema_meta") && [
		"meta_key",
		"schema_version",
		"updated_at"
	].every((t) => tableHasColumn(e, "schema_meta", t))) {
		const r = Date.now();
		if (t.createMetadataIfMissing) {
			e.prepare(`INSERT INTO schema_meta (
           meta_key, role, schema_version, agent_id, app_version, created_at, updated_at
         ) VALUES ('primary', 'global', ?, NULL, NULL, ?, ?)
         ON CONFLICT(meta_key) DO UPDATE SET
           schema_version = excluded.schema_version,
           updated_at = excluded.updated_at
         WHERE schema_meta.schema_version IS NOT excluded.schema_version`).run(n, r, r);
			return;
		}
		e.prepare("UPDATE schema_meta SET schema_version = ?, updated_at = ? WHERE meta_key = 'primary' AND schema_version IS NOT ?").run(n, r, n);
	}
}
/** Historical jobs lost the creator's origin; preserve attribution without guessing authority. */
function migrateCronCreatorNamespaces(e, t) {
	if (t >= 14 || !tableExists(e, "cron_jobs")) return false;
	e.exec(`
    UPDATE cron_jobs
       SET job_json = json_set(job_json, '$.createdActor.source', 'unknown')
     WHERE json_valid(job_json)
       AND json_extract(job_json, '$.createdActor.type') = 'human';
  `);
	return true;
}
/** Keep opaque plugin targets independent of agent identity without rewriting binding records. */
function migrateConversationBindingTargets(e, t) {
	if (t >= 15) return false;
	const n = ["target_agent_id", "target_session_id"].filter((t) => tableHasColumn(e, "current_conversation_bindings", t));
	if (n.length === 0) return false;
	e.exec("DROP INDEX IF EXISTS idx_current_conversation_bindings_target;");
	for (const t of n) e.exec(`ALTER TABLE current_conversation_bindings DROP COLUMN ${t};`);
	return true;
}
/** Add preparation and activation facts without rebuilding the referenced environment table. */
function migratePreparedWorkerOwnership(e, t) {
	if (t >= 17 || !tableExists(e, "worker_environments")) return false;
	const n = OPENCLAW_STATE_SCHEMA_SQL.indexOf("CREATE TABLE IF NOT EXISTS worker_environments (");
	const r = OPENCLAW_STATE_SCHEMA_SQL.indexOf("\n) STRICT;", n);
	if (n < 0 || r < n) throw new Error("OpenClaw worker environment schema marker is missing.");
	const i = splitSqlList(OPENCLAW_STATE_SCHEMA_SQL.slice(n + 48, r)).map((e) => e.trim()).filter((e) => e.startsWith("last_activated_at_ms ") || e.startsWith("preparation_"));
	let a = false;
	for (const t of i) a = ensureColumn(e, "worker_environments", t) || a;
	return a;
}
/** Historical publication rows retain unknown requesters; first use still owns absent tables. */
function migrateGitHubPublicationRequesterAuthority(e, t) {
	if (t >= 18) return false;
	let n = false;
	for (const t of ["github_publication_session_lifecycles", "github_repository_publication_requests"]) n = ensureColumn(e, t, "requester_authority_json TEXT") || n;
	return n;
}
const statePortableIdentityMigration = {
	version: 22,
	tables: ["acp_sessions", ...STATE_CURSOR_TABLES_V22],
	columns: [
		"acp_sessions.resume_agent_session_id",
		"acp_sessions.resume_acpx_session_id",
		...STATE_CURSOR_TABLES_V22.map((e) => `${e}.cursor_id`)
	],
	migrate: migratePortableIdentityColumnsV22,
	applied: "Promoted portable ACP resume keys and cursor identities (v22)"
};
const stateMeetingChronologyMigration = {
	version: 23,
	tables: ["meeting_transcript_sessions"],
	columns: ["meeting_transcript_sessions.started_at_ms"],
	migrate: migrateMeetingTranscriptStartTime,
	applied: "Persisted normalized meeting transcript start times"
};
const stateTaskIndexMigration = {
	version: 24,
	tables: ["task_runs"],
	columns: [],
	migrate: migrateTaskRunIndexesV24,
	applied: "Replaced retained task indexes with ordered cron history indexes (v24)"
};
const stateSubagentOperatorRecoveryMigration = {
	version: 25,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Required original operator authority for subagent recovery (v25)"
};
const stateHeadLayoutMigration = {
	version: 26,
	tables: ["session_state_heads"],
	columns: [],
	migrate: migrateSessionStateHeadLayoutV26,
	applied: "Stored session state heads in their composite primary-key tree (v26)"
};
const stateWriteIndexMigration = {
	version: 27,
	tables: [
		"acp_replay_events",
		"skill_usage",
		"state_leases"
	],
	columns: [],
	migrate: migrateStateWriteIndexesV27,
	applied: "Removed redundant replay and skill indexes and narrowed the lease-owner index (v27)"
};
const stateClientCredentialMigration = {
	version: 29,
	tables: CLIENT_CREDENTIAL_SOURCE_TABLES,
	columns: [],
	migrate: () => false,
	applied: "Moved client credentials and native socket material to the local owner (v29)"
};
const stateAutomationPolicyMigration = {
	version: 30,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Fenced ordinary automation timing and delivery policies from older schedulers (v30)"
};
/** Version-gated column and row migrations, oldest first; each runs inside the caller's schema transaction. */
const versionedStateMigrations = [
	statePortableIdentityMigration,
	stateMeetingChronologyMigration,
	{
		migrate: migrateJsonCanonicalWideRowsV13,
		applied: "Consolidated shared state tables (v13)"
	},
	{
		migrate: migrateCronCreatorNamespaces,
		applied: "Qualified historical cron creator attribution as unknown (v14)"
	},
	{
		migrate: migrateConversationBindingTargets,
		applied: "Removed redundant conversation binding target projections (v15)"
	},
	{
		migrate: migratePreparedWorkerOwnership,
		applied: "Recorded prepared worker ownership and one-use lifecycle (v17)"
	},
	{
		migrate: migrateGitHubPublicationRequesterAuthority,
		applied: "Added original requester authority to GitHub publication receipts (v18)"
	},
	{
		migrate: migrateCronDeliveryAttemptState,
		applied: "Recorded cron completion delivery attempt uncertainty (v20)"
	},
	stateTaskIndexMigration,
	stateHeadLayoutMigration,
	stateWriteIndexMigration,
	statePublicationDraftMigration,
	stateLocalWorkspaceManifestMigration,
	stateCronIdentityMigration,
	stateLocalWorkspaceCasMigration,
	stateTemplateNamesMigration
];
/** Recent version migrations own only their tables; Doctor owns unrelated historical repair. */
function migrateBoundedStateSchema(e, t, n) {
	const r = [
		statePredicateColumnMigration,
		statePortableIdentityMigration,
		stateMeetingChronologyMigration,
		stateTaskIndexMigration,
		stateSubagentOperatorRecoveryMigration,
		stateHeadLayoutMigration,
		stateWriteIndexMigration,
		statePublicationDraftMigration,
		stateClientCredentialMigration,
		stateAutomationPolicyMigration,
		stateLocalWorkspaceManifestMigration,
		...stateIndexOrderingMigrations,
		stateCronIdentityMigration,
		stateLocalWorkspaceCasMigration,
		stateTemplateNamesMigration
	].filter(({ version: e }) => e > t);
	if (t >= 36 || r.length !== 36 - t) return;
	const i = new Set(r.flatMap((e) => e.tables));
	const a = getCanonicalSqliteNamedIndexContracts(OPENCLAW_STATE_SCHEMA_SQL).filter((e) => i.has(e.tableName));
	const o = t < 36 ? withLegacyTemplateStateSchema(OPENCLAW_STATE_SCHEMA_SQL) : OPENCLAW_STATE_SCHEMA_SQL;
	const s = t < 35 ? withLegacyLocalWorkspaceCas(o) : o;
	const c = t < 31 ? withLegacyLocalWorkspaceManifests(s) : s;
	const l = t < 27 ? withLegacyStateWriteIndexes(c) : c;
	const u = t < 26 ? withLegacyStateHeadLayout(l) : l;
	if (!n.versionMigrationOnly && (tableExists(e, "cron_run_logs") || !r.includes(statePublicationDraftMigration) && needsPublicationDraftMigration(e) || findMissingLazyStateStartupColumn(createSqliteTableContractReader(e)) !== void 0 || collectSqliteSchemaIssues(e, u, {
		...withLegacyTemplateStateCompatibility(STATE_RUNTIME_SCHEMA_COMPATIBILITY),
		allowedMissingColumns: [...STATE_RUNTIME_SCHEMA_COMPATIBILITY.allowedMissingColumns ?? [], ...r.flatMap((e) => e.columns)].map(withLegacyTemplateStateSchema),
		allowedMissingIndexes: [
			...STATE_RUNTIME_SCHEMA_COMPATIBILITY.allowedMissingIndexes ?? [],
			...a.map((e) => e.name),
			"idx_acp_replay_events_session_seq",
			"idx_skill_usage_key"
		],
		excludedIndexes: [
			...STATE_RUNTIME_SCHEMA_COMPATIBILITY.excludedIndexes ?? [],
			"idx_acp_sessions_resume_agent",
			"idx_acp_sessions_resume_acpx"
		]
	}).length > 0)) return;
	const d = migrateHistoricalStateImports(e, t);
	for (const i of r) {
		i.migrate(e, t, n);
		d.push(i.applied);
	}
	for (const t of a) if (tableExists(e, t.tableName)) {
		const n = t.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
		e.exec(`${n} IF NOT EXISTS ${t.name} ${t.definition};`);
	}
	return d;
}
function runStateSchemaMigrationTransaction(e, t, n, r, i) {
	return runUpdateSqliteMigration(e, t, () => {
		const a = Number(e.prepare("PRAGMA foreign_keys").get()?.foreign_keys) === 1;
		if (a) e.exec("PRAGMA foreign_keys = OFF;");
		try {
			return runSqliteImmediateTransactionSync(e, () => {
				i?.();
				const r = readSqliteUserVersion(e);
				const a = r < 36 ? readStateSchemaPublicationBlocker(e) : void 0;
				if (!a) return n();
				try {
					if (!tableExists(e, "config_machine_state")) throw new Error("Shared state schema publication requires config_machine_state.");
					return n();
				} catch (e) {
					if (e instanceof OpenClawStateOwnershipError) throw e;
					throw new UpdateSchemaRefusalError([{
						kind: "state",
						path: t,
						foundVersion: r,
						supportedVersion: 36
					}], a.updaterVersion, {
						targetVersion: VERSION,
						cause: e
					});
				}
			}, r);
		} finally {
			if (a && e.isOpen) e.exec("PRAGMA foreign_keys = ON;");
		}
	});
}
function writeCurrentStateSchemaMetadata(e, t) {
	const n = getNodeSqliteKysely(e);
	const r = resolveStateSchemaVersionToPublish(e);
	if (readSqliteUserVersion(e) !== r) e.exec(`PRAGMA user_version = ${r};`);
	publishStateSchemaVersionAdmission(e, {
		userVersion: r,
		contentVersion: 36
	});
	executeSqliteQuerySync(e, n.insertInto("schema_meta").values({
		meta_key: "primary",
		role: "global",
		schema_version: r,
		agent_id: null,
		app_version: VERSION,
		created_at: t,
		updated_at: t
	}).onConflict((e) => e.column("meta_key").doUpdateSet({
		role: "global",
		schema_version: r,
		agent_id: null,
		app_version: VERSION,
		updated_at: t
	}).where((e) => e.or([
		e("schema_meta.schema_version", "!=", r),
		e("schema_meta.app_version", "is not", VERSION),
		e("schema_meta.role", "!=", "global")
	]))));
}
function executeCanonicalStateSchema(e, t) {
	e.exec(getOpenClawStateRuntimeSchema({
		...t,
		includeAgentDeletionJournal: t.includeAgentDeletionJournal ?? tableExists(e, "agent_deletion_journal")
	}));
}
//#endregion
//#region src/state/openclaw-state-db-audit-migration.ts
const AUDIT_EVENT_STATE_SCHEMA_VERSION = 2;
const CANONICAL_AUDIT_TABLES = ["audit_events", "audit_identity_keys"].map((e) => ({
	name: e,
	sql: normalizeSchemaSql(extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, e))
}));
const AUDIT_EVENT_LEGACY_COLUMNS = [
	"sequence",
	"event_id",
	"source_id",
	"source_sequence",
	"occurred_at",
	"kind",
	"action",
	"status",
	"error_code",
	"actor_type",
	"actor_id",
	"agent_id",
	"session_key",
	"session_id",
	"run_id",
	"tool_call_id",
	"tool_name"
];
const AUDIT_EVENT_MIGRATED_COLUMNS = AUDIT_EVENT_LEGACY_COLUMNS.flatMap((e) => e === "source_id" ? [e, "schema_version"] : [e]);
const AUDIT_EVENT_V2_COLUMNS = [
	...AUDIT_EVENT_MIGRATED_COLUMNS,
	"direction",
	"channel",
	"conversation_kind",
	"message_outcome",
	"reason_code",
	"delivery_kind",
	"failure_stage",
	"duration_ms",
	"result_count",
	"account_ref",
	"conversation_ref",
	"message_ref",
	"target_ref"
];
function tableColumnInfo(e, t) {
	return e.prepare(`PRAGMA table_info(${t})`).all();
}
function tableHasExactColumns(e, t, n) {
	const r = tableColumnInfo(e, t).map((e) => e.name);
	return r.length === n.length && r.every((e, t) => e === n[t]);
}
function tableHasRequiredColumns(e, t, n) {
	const r = new Map(tableColumnInfo(e, t).map((e) => [e.name, e]));
	return n.every((e) => Number(r.get(e)?.notnull ?? 0) === 1);
}
function tableSql(e, t) {
	const n = e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);
	return typeof n?.sql === "string" ? n.sql : void 0;
}
function tableHasUniqueColumn(e, t, n) {
	return e.prepare(`PRAGMA index_list(${t})`).all().some((t) => {
		if (Number(t.unique ?? 0) !== 1 || typeof t.name !== "string") return false;
		const r = t.name.replaceAll("'", "''");
		const i = e.prepare(`PRAGMA index_info('${r}')`).all();
		return i.length === 1 && i[0]?.name === n;
	});
}
function hasCanonicalAuditEventTable(e, t, n) {
	const r = tableSql(e, "audit_events")?.toLowerCase();
	return tableHasExactColumns(e, "audit_events", t) && tablePrimaryKeyColumns(e, "audit_events").join(",") === "sequence" && tableHasRequiredColumns(e, "audit_events", n) && typeof r === "string" && /\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(r) && tableHasUniqueColumn(e, "audit_events", "event_id") && tableHasUniqueColumn(e, "audit_events", "source_id");
}
function hasCanonicalAuditIdentityKeyTable(e) {
	if (!tableExists(e, "audit_identity_keys")) return false;
	const t = tableSql(e, "audit_identity_keys")?.toLowerCase();
	return tableHasExactColumns(e, "audit_identity_keys", [
		"id",
		"key_id",
		"key",
		"created_at"
	]) && tablePrimaryKeyColumns(e, "audit_identity_keys").join(",") === "id" && tableHasRequiredColumns(e, "audit_identity_keys", [
		"id",
		"key_id",
		"key",
		"created_at"
	]) && typeof t === "string" && /\bcheck\s*\(\s*id\s*=\s*1\s*\)/.test(t);
}
function hasCanonicalAuditEventsSchema(e) {
	const t = getAdmittedSqliteSchemaFacts(e);
	if (t && CANONICAL_AUDIT_TABLES.every(({ name: e, sql: n }) => normalizeSchemaSql(t.tableSql.get(e) ?? null) === n)) return true;
	if (!tableExists(e, "audit_events")) return readSqliteUserVersion(e) < AUDIT_EVENT_STATE_SCHEMA_VERSION && !tableExists(e, "audit_identity_keys");
	return hasCanonicalAuditEventTable(e, AUDIT_EVENT_V2_COLUMNS, [
		"event_id",
		"source_id",
		"schema_version",
		"source_sequence",
		"occurred_at",
		"kind",
		"action",
		"status",
		"actor_type",
		"actor_id"
	]) && hasCanonicalAuditIdentityKeyTable(e);
}
function canRepairLegacyAuditEventsSchema(e) {
	if (!tableExists(e, "audit_events") || tableExists(e, "audit_events_migration_new") || tableHasColumn(e, "audit_events", "schema_version")) return false;
	return (!tableExists(e, "audit_identity_keys") || hasCanonicalAuditIdentityKeyTable(e)) && hasCanonicalAuditEventTable(e, AUDIT_EVENT_LEGACY_COLUMNS, [
		"event_id",
		"source_id",
		"source_sequence",
		"occurred_at",
		"kind",
		"action",
		"status",
		"actor_type",
		"actor_id",
		"agent_id",
		"run_id"
	]);
}
//#endregion
//#region src/state/openclaw-state-db-schema-v12-foldin.ts
const FOLDED_SINGLETON_STATE_TABLES_V12 = [
	"skill_curator_state",
	"update_check_state",
	"clawhub_promotions_feed_state",
	"model_catalog_remote",
	"voicewake_triggers",
	"voicewake_routing_routes",
	"voicewake_routing_config",
	"onboarding_recommendations",
	"cron_store_epochs",
	"tui_last_sessions",
	"sidebar_sections",
	"node_host_config",
	"web_push_vapid_keys"
];
/** Preserve the table's original catalog SQL for fresh creation and historical migration. */
function createStateConfigMachineTable(e) {
	e.exec(`
    CREATE TABLE IF NOT EXISTS config_machine_state (
      state_key TEXT NOT NULL PRIMARY KEY,
      value_json TEXT NOT NULL,
      updated_at_ms INTEGER NOT NULL
    ) STRICT;
  `);
}
function migrateSingletonStateFoldInV12(e, t) {
	if (t >= 12) return false;
	createStateConfigMachineTable(e);
	const n = e.prepare("INSERT INTO config_machine_state (state_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(state_key) DO NOTHING");
	if (tableExists(e, "update_check_state")) {
		const t = e.prepare("SELECT * FROM update_check_state WHERE state_key = 'default'").get();
		if (t) n.run("update.checkState", JSON.stringify({
			lastCheckedAt: t.last_checked_at ?? void 0,
			lastNotifiedVersion: t.last_notified_version ?? void 0,
			lastNotifiedTag: t.last_notified_tag ?? void 0,
			lastAvailableVersion: t.last_available_version ?? void 0,
			lastAvailableTag: t.last_available_tag ?? void 0,
			autoInstallId: t.auto_install_id ?? void 0,
			autoFirstSeenVersion: t.auto_first_seen_version ?? void 0,
			autoFirstSeenTag: t.auto_first_seen_tag ?? void 0,
			autoFirstSeenAt: t.auto_first_seen_at ?? void 0,
			autoLastAttemptVersion: t.auto_last_attempt_version ?? void 0,
			autoLastAttemptAt: t.auto_last_attempt_at ?? void 0,
			autoLastSuccessVersion: t.auto_last_success_version ?? void 0,
			autoLastSuccessAt: t.auto_last_success_at ?? void 0
		}), Number(t.updated_at_ms));
	}
	if (tableExists(e, "voicewake_triggers")) {
		const t = e.prepare("SELECT trigger, updated_at_ms FROM voicewake_triggers WHERE config_key = 'default' ORDER BY position").all();
		if (t.length > 0) n.run("voicewake.triggers", JSON.stringify(t.map((e) => e.trigger)), Math.max(...t.map((e) => Number(e.updated_at_ms))));
	}
	if (tableExists(e, "voicewake_routing_config")) {
		const t = e.prepare("SELECT * FROM voicewake_routing_config WHERE config_key = 'default'").get();
		if (t) {
			const r = tableExists(e, "voicewake_routing_routes") ? e.prepare("SELECT trigger, target_mode, target_agent_id, target_session_key FROM voicewake_routing_routes WHERE config_key = 'default' ORDER BY position").all() : [];
			const targetFromColumns = (e, t, n) => e === "agent" && typeof t === "string" && t ? { agentId: t } : e === "session" && typeof n === "string" && n ? { sessionKey: n } : { mode: "current" };
			n.run("voicewake.routing", JSON.stringify({
				version: 1,
				defaultTarget: targetFromColumns(t.default_target_mode, t.default_target_agent_id, t.default_target_session_key),
				routes: r.map((e) => ({
					trigger: e.trigger,
					target: targetFromColumns(e.target_mode, e.target_agent_id, e.target_session_key)
				})),
				updatedAtMs: t.updated_at_ms
			}), Number(t.updated_at_ms));
		}
	}
	if (tableExists(e, "onboarding_recommendations")) {
		const t = e.prepare("SELECT * FROM onboarding_recommendations").all();
		for (const e of t) n.run(`onboarding.recommendations.${String(e.config_key)}`, JSON.stringify({
			inventoryHash: e.inventory_hash,
			matches: JSON.parse(String(e.matches_json)),
			offeredAt: e.offered_at_ms,
			acceptedAt: e.accepted_at_ms,
			updatedAt: e.updated_at_ms
		}), Number(e.updated_at_ms));
	}
	if (tableExists(e, "sidebar_sections")) {
		const t = e.prepare("SELECT section_id FROM sidebar_sections ORDER BY position, section_id").all();
		if (t.length > 0) n.run("sidebar.sectionOrder", JSON.stringify(t.map((e) => e.section_id)), Date.now());
	}
	if (tableExists(e, "node_host_config")) {
		const t = e.prepare("SELECT * FROM node_host_config WHERE config_key = 'current'").get();
		if (t) {
			const e = {
				host: t.gateway_host ?? void 0,
				port: t.gateway_port ?? void 0,
				tls: t.gateway_tls == null ? void 0 : t.gateway_tls === 1,
				tlsFingerprint: t.gateway_tls_fingerprint ?? void 0,
				contextPath: t.gateway_context_path ?? void 0,
				cloudflareAccess: t.gateway_cloudflare_access_json == null ? void 0 : JSON.parse(String(t.gateway_cloudflare_access_json))
			};
			n.run("nodeHost.config", JSON.stringify({
				version: t.version,
				nodeId: t.node_id,
				...t.display_name == null ? {} : { displayName: t.display_name },
				gateway: Object.values(e).some((e) => e !== void 0) ? e : void 0,
				installedAppsSharing: t.installed_apps_sharing === 1
			}), Number(t.updated_at_ms));
		}
	}
	if (tableExists(e, "web_push_vapid_keys")) {
		const t = e.prepare("SELECT * FROM web_push_vapid_keys WHERE key_id = 'default'").get();
		if (t) n.run("webPush.vapidKeys", JSON.stringify({
			publicKey: t.public_key,
			privateKey: t.private_key,
			subject: t.subject
		}), Number(t.updated_at_ms));
	}
	let r = false;
	for (const t of FOLDED_SINGLETON_STATE_TABLES_V12) if (tableExists(e, t)) {
		e.exec(`DROP TABLE IF EXISTS ${t};`);
		r = true;
	}
	return r;
}
//#endregion
//#region src/state/session-watch-cursor-provenance.ts
const SESSION_WATCH_PROVENANCE_EXPLICIT = "explicit";
const SESSION_WATCH_PROVENANCE_AMBIENT_GROUP = "ambient-group";
//#endregion
//#region src/state/openclaw-state-db-session-watch-migration.ts
const LEGACY_AMBIENT_GROUP_WATCH_MARKER_PREFIX = "ambient-group-watch:";
const LEGACY_AMBIENT_GROUP_WATCH_MARKER_END = "ambient-group-watch;";
const SESSION_WATCH_PROVENANCE_COLUMN_SQL = `provenance TEXT NOT NULL DEFAULT '${SESSION_WATCH_PROVENANCE_EXPLICIT}' CHECK (provenance IN ('${SESSION_WATCH_PROVENANCE_EXPLICIT}', '${SESSION_WATCH_PROVENANCE_AMBIENT_GROUP}'))`;
function getSessionWatchCursorKysely(e) {
	return getNodeSqliteKysely(e);
}
function decodeLegacyAmbientWatchMarkerKey(e) {
	const t = e.slice(20);
	if (!t || t.length % 2 !== 0 || !/^[0-9a-f]+$/.test(t)) return;
	try {
		return new TextDecoder("utf-8", {
			fatal: true,
			ignoreBOM: true
		}).decode(Buffer.from(t, "hex"));
	} catch {
		return;
	}
}
function migrateSessionWatchCursorProvenance(e) {
	if (!tableExists(e, "session_watch_cursors")) return {
		migratedAmbientWatches: 0,
		removedLegacySentinels: 0
	};
	ensureColumn(e, "session_watch_cursors", SESSION_WATCH_PROVENANCE_COLUMN_SQL);
	const t = getSessionWatchCursorKysely(e);
	const n = executeSqliteQuerySync(e, t.selectFrom("session_watch_cursors").select([
		"watcher_session_key",
		"target_session_key",
		"updated_at"
	]).where("watcher_session_key", ">=", LEGACY_AMBIENT_GROUP_WATCH_MARKER_PREFIX).where("watcher_session_key", "<", LEGACY_AMBIENT_GROUP_WATCH_MARKER_END)).rows;
	let r = 0;
	for (const i of n) {
		const n = decodeLegacyAmbientWatchMarkerKey(i.watcher_session_key);
		if (n) {
			const a = executeSqliteQueryTakeFirstSync(e, t.selectFrom("session_watch_cursors").select("updated_at").where("watcher_session_key", "=", n).where("target_session_key", "=", i.target_session_key));
			if (a) {
				const o = executeSqliteQuerySync(e, t.updateTable("session_watch_cursors").set({
					provenance: SESSION_WATCH_PROVENANCE_AMBIENT_GROUP,
					updated_at: Math.max(a.updated_at, i.updated_at)
				}).where("watcher_session_key", "=", n).where("target_session_key", "=", i.target_session_key));
				r += Number(o.numAffectedRows ?? 0n);
			}
		}
		executeSqliteQuerySync(e, t.deleteFrom("session_watch_cursors").where("watcher_session_key", "=", i.watcher_session_key).where("target_session_key", "=", i.target_session_key));
	}
	return {
		migratedAmbientWatches: r,
		removedLegacySentinels: n.length
	};
}
//#endregion
//#region src/state/openclaw-state-schema-retired.ts
const RETIRED_COMMITMENTS_COLUMNS_SQL = `
  id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT,
  recipient_id TEXT,
  thread_id TEXT,
  sender_id TEXT,
  kind TEXT NOT NULL,
  sensitivity TEXT NOT NULL,
  source TEXT NOT NULL,
  status TEXT NOT NULL,
  reason TEXT NOT NULL,
  suggested_text TEXT NOT NULL,
  dedupe_key TEXT NOT NULL,
  confidence REAL NOT NULL,
  due_earliest_ms INTEGER NOT NULL,
  due_latest_ms INTEGER NOT NULL,
  due_timezone TEXT NOT NULL,
  source_message_id TEXT,
  source_run_id TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  attempts INTEGER NOT NULL,
  last_attempt_at_ms INTEGER,
  sent_at_ms INTEGER,
  dismissed_at_ms INTEGER,
  snoozed_until_ms INTEGER,
  expired_at_ms INTEGER,
  record_json TEXT NOT NULL
`;
const RETIRED_COMMITMENTS_BASE_INDEXES_SQL = `CREATE INDEX idx_commitments_scope_due
  ON commitments(agent_id, session_key, status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_status_due
  ON commitments(status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_scope_dedupe
  ON commitments(agent_id, session_key, channel, dedupe_key, status);`;
const RETIRED_COMMITMENTS_SCHEMA_SQL = `
CREATE TABLE commitments (${RETIRED_COMMITMENTS_COLUMNS_SQL.slice(1, -1)}
) STRICT;
${RETIRED_COMMITMENTS_BASE_INDEXES_SQL}
CREATE INDEX idx_commitments_agent_due
  ON commitments(agent_id, status, due_earliest_ms, due_latest_ms, session_key);
CREATE INDEX idx_commitments_agent_sent
  ON commitments(agent_id, status, sent_at_ms, session_key);
`;
const SHIPPED_RETIRED_COMMITMENTS_SCHEMA_SQL = `
CREATE TABLE commitments (${RETIRED_COMMITMENTS_COLUMNS_SQL.slice(1, -1)}
);
${RETIRED_COMMITMENTS_BASE_INDEXES_SQL}
`;
//#endregion
//#region src/state/openclaw-state-db-table-retirements.ts
const stateDbLog$3 = createSubsystemLogger("state/db");
const logRetiredStateTableMigration = (e) => stateDbLog$3.info(e);
const RETIRED_COMMITMENTS_SCHEMA_VERSION = 7;
const RETIRED_DEAD_STATE_TABLES_V10 = [
	"agent_model_catalogs",
	"android_notification_recent_packages",
	"command_log_entries",
	"diagnostic_stability_bundles",
	"media_blobs",
	"model_capability_cache"
];
const RETIRED_COMMITMENTS_ADDITIVE_COLUMNS = [
	"commitments.account_id",
	"commitments.recipient_id",
	"commitments.thread_id",
	"commitments.sender_id",
	"commitments.kind",
	"commitments.sensitivity",
	"commitments.source",
	"commitments.reason",
	"commitments.suggested_text",
	"commitments.dedupe_key",
	"commitments.confidence",
	"commitments.due_timezone",
	"commitments.source_message_id",
	"commitments.source_run_id",
	"commitments.created_at_ms",
	"commitments.attempts",
	"commitments.last_attempt_at_ms",
	"commitments.sent_at_ms",
	"commitments.dismissed_at_ms",
	"commitments.snoozed_until_ms",
	"commitments.expired_at_ms"
];
function deriveRetiredCommitmentsContract() {
	const e = new Map(getCanonicalSqliteNamedIndexContracts(RETIRED_COMMITMENTS_SCHEMA_SQL).map(({ fingerprint: e, name: t }) => [t, JSON.stringify(e)]));
	return {
		indexFingerprints: e,
		compatibility: {
			allowedColumnDefinitions: {
				"commitments.attempts": ["attempts INTEGER NOT NULL DEFAULT 0"],
				"commitments.confidence": ["confidence REAL NOT NULL DEFAULT 0"],
				"commitments.created_at_ms": ["created_at_ms INTEGER NOT NULL DEFAULT 0"],
				"commitments.dedupe_key": ["dedupe_key TEXT NOT NULL DEFAULT ''"],
				"commitments.due_timezone": ["due_timezone TEXT NOT NULL DEFAULT 'UTC'"],
				"commitments.kind": ["kind TEXT NOT NULL DEFAULT 'followup'"],
				"commitments.reason": ["reason TEXT NOT NULL DEFAULT ''"],
				"commitments.sensitivity": ["sensitivity TEXT NOT NULL DEFAULT 'normal'"],
				"commitments.source": ["source TEXT NOT NULL DEFAULT 'unknown'"],
				"commitments.suggested_text": ["suggested_text TEXT NOT NULL DEFAULT ''"]
			},
			allowedMissingColumns: RETIRED_COMMITMENTS_ADDITIVE_COLUMNS,
			allowedMissingIndexes: [...e.keys()]
		}
	};
}
function hasSupportedRetiredCommitmentsSchema(e, t, { compatibility: n, indexFingerprints: r }) {
	if (collectSqliteSchemaIssues(e, t, n).length > 0) return false;
	return e.prepare(`SELECT type, name
           FROM sqlite_schema
          WHERE type IN ('index', 'trigger')
            AND tbl_name = 'commitments'
            AND sql IS NOT NULL
          ORDER BY type, name`).all().every((t) => t.type === "index" && JSON.stringify(collectSqliteNamedIndexContract(e, t.name)) === r.get(t.name));
}
function assertRecognizedRetiredCommitmentsSchema(e) {
	if (hasRecognizedRetiredCommitmentsSchema(e)) return;
	assertSqliteSchemaContains(e, "retired OpenClaw commitments schema", RETIRED_COMMITMENTS_SCHEMA_SQL, deriveRetiredCommitmentsContract().compatibility);
	throw new Error("Retired OpenClaw commitments schema has unsupported additional indexes; refusing destructive migration.");
}
function hasRecognizedRetiredCommitmentsSchema(e) {
	const t = deriveRetiredCommitmentsContract();
	return hasSupportedRetiredCommitmentsSchema(e, RETIRED_COMMITMENTS_SCHEMA_SQL, t) || hasSupportedRetiredCommitmentsSchema(e, SHIPPED_RETIRED_COMMITMENTS_SCHEMA_SQL, t);
}
function assertNoRetiredCommitmentsForeignKeys(e) {
	const t = e.prepare(`SELECT name
         FROM sqlite_schema
        WHERE type = 'table' AND name <> 'commitments'
        ORDER BY name`).all();
	for (const n of t) if (e.prepare(`PRAGMA foreign_key_list(${quoteSqliteIdentifier(n.name)})`).all().some((e) => typeof e.table === "string" && e.table.toLowerCase() === "commitments")) throw new Error(`Retired OpenClaw commitments schema is referenced by table ${n.name}; refusing destructive migration.`);
}
function collectRetainedSchemaSql(e) {
	return new Map(e.prepare(`SELECT type, name, sql
             FROM sqlite_schema
            WHERE type IN ('trigger', 'view')
              AND tbl_name <> 'commitments'
              AND sql IS NOT NULL
            ORDER BY type, name`).all().map((e) => [`${e.type}:${e.name}`, e.sql]));
}
function assertNoRetiredCommitmentsSchemaDependencies(e) {
	const t = "__openclaw_retired_commitments_probe";
	if (tableExists(e, t)) throw new Error(`OpenClaw state database already contains ${t}; refusing destructive migration.`);
	const n = collectRetainedSchemaSql(e);
	const r = "openclaw_probe_commitments_dependencies";
	e.exec(`SAVEPOINT ${r};`);
	let i;
	try {
		e.exec(`ALTER TABLE commitments RENAME TO ${quoteSqliteIdentifier(t)};`);
		const r = collectRetainedSchemaSql(e);
		i = [...n].find(([e, t]) => r.get(e) !== t)?.[0];
	} catch (t) {
		e.exec(`ROLLBACK TO ${r}; RELEASE ${r};`);
		throw new Error("Could not prove retained SQLite views and triggers independent of commitments; refusing destructive migration.", { cause: t });
	}
	e.exec(`ROLLBACK TO ${r}; RELEASE ${r};`);
	if (i) {
		const [e, t] = i.split(":", 2);
		throw new Error(`Retired OpenClaw commitments schema is referenced by ${e} ${t}; refusing destructive migration.`);
	}
}
function assertVirtualTablesUsable(e, t) {
	const n = e.prepare(`SELECT name
         FROM sqlite_schema
        WHERE type = 'table' AND lower(sql) LIKE 'create virtual table%'
        ORDER BY name`).all();
	for (const r of n) try {
		e.prepare(`SELECT * FROM ${quoteSqliteIdentifier(r.name)} LIMIT 1`).all();
	} catch (e) {
		throw new Error(`SQLite virtual table ${r.name} is unusable ${t} commitments retirement.`, { cause: e });
	}
}
function migrateRetiredCommitmentsSchema(e, t) {
	if (t >= 7) return false;
	if (!tableExists(e, "commitments")) return false;
	assertRecognizedRetiredCommitmentsSchema(e);
	assertNoRetiredCommitmentsForeignKeys(e);
	assertNoRetiredCommitmentsSchemaDependencies(e);
	assertVirtualTablesUsable(e, "before");
	const n = "openclaw_retire_commitments_v7";
	e.exec(`SAVEPOINT ${n};`);
	try {
		e.exec("DROP TABLE commitments;");
		assertVirtualTablesUsable(e, "after");
		e.exec(`RELEASE ${n};`);
		return true;
	} catch (t) {
		e.exec(`ROLLBACK TO ${n}; RELEASE ${n};`);
		throw t;
	}
}
function migrateRetiredDeadStateTablesV10(e, t) {
	if (t >= 10) return false;
	let n = false;
	for (const t of RETIRED_DEAD_STATE_TABLES_V10) if (tableExists(e, t)) {
		e.exec(`DROP TABLE IF EXISTS ${t};`);
		n = true;
	}
	return n;
}
const RETIRED_SKILL_CURATOR_TABLES_V11 = ["skill_lifecycle", "skill_workshop_proposal_origin_runs"];
function migrateRetiredSkillCuratorTablesV11(e, t) {
	if (t >= 11) return false;
	const n = RETIRED_SKILL_CURATOR_TABLES_V11.filter((t) => tableExists(e, t));
	if (n.length === 0) return false;
	if (n.includes("skill_lifecycle")) {
		const t = Number(e.prepare("SELECT COUNT(*) AS archived_count FROM skill_lifecycle WHERE state = 'archived'").get()?.archived_count);
		if (t > 0) stateDbLog$3.info(`${t} previously archived workshop skills are live again; archive any you no longer want`);
	}
	for (const t of n) e.exec(`DROP TABLE IF EXISTS ${t};`);
	return true;
}
/**
* Runs every retired-table migration in schema order and names what it changed.
* Both the repair path and the ordinary open path go through here so the order
* and the operator-visible labels cannot drift apart.
*/
function runRetiredStateTableMigrations(e, t) {
	const n = [];
	if (migrateRetiredCommitmentsSchema(e, t)) n.push("Discarded retired shared-state commitments rows, table, and indexes");
	if (migrateRetiredDeadStateTablesV10(e, t)) n.push("Retired six dead shared-state tables (v10)");
	if (migrateRetiredSkillCuratorTablesV11(e, t)) n.push("Retired legacy skill curator lifecycle and proposal origin-run tables");
	return n;
}
//#endregion
//#region src/state/openclaw-state-db-schema-repair.ts
/** Tables whose existing read contracts can change before this migration completes. */
const STATE_SCHEMA_MIGRATION_READ_TABLES = {
	"agent-databases-composite-primary-key": ["agent_databases"],
	"audit-events-v2": ["audit_events", "audit_identity_keys"],
	"commitments-retirement-v7": ["commitments"],
	"worker-placement-execution-mode-v8": ["worker_session_placements"],
	"agent-databases-relative-paths-v9": ["agent_databases"],
	"state-table-retirement-v10": RETIRED_DEAD_STATE_TABLES_V10,
	"state-table-retirement-v11": RETIRED_SKILL_CURATOR_TABLES_V11,
	"singleton-state-foldin-v12": ["config_machine_state", ...FOLDED_SINGLETON_STATE_TABLES_V12],
	"state-consolidation-v13": [
		"cron_jobs",
		"subagent_runs",
		"workspace_setup_state",
		"workspace_attestations",
		"workspace_generated_bootstrap_hashes",
		"auth_profile_stores",
		"auth_profile_state",
		"installed_plugin_index",
		"config_machine_state",
		"diagnostic_events"
	],
	"creator-namespace-v14": ["cron_jobs"],
	"conversation-binding-targets-v15": ["current_conversation_bindings"],
	"prepared-worker-ownership-v17": ["worker_environments"],
	"github-publication-requester-authority-v18": ["github_publication_session_lifecycles", "github_repository_publication_requests"],
	"meeting-transcript-start-time": ["meeting_transcript_sessions"],
	"portable-identity-columns-v22": ["acp_sessions", ...STATE_CURSOR_TABLES_V22],
	"task-run-indexes-v24": [],
	"subagent-operator-recovery-v25": [],
	"session-state-head-layout-v26": [],
	"state-write-indexes-v27": [],
	"github-publication-draft-v28": [
		"github_publication_requests",
		"github_personal_publication_requests",
		"github_repository_publication_requests"
	],
	"local-client-credentials-v29": [
		"device_identities",
		"device_auth_tokens",
		"gateway_origin_device_tokens",
		"exec_approvals_config"
	],
	"predicate-columns-v21": [
		"meeting_transcript_sessions",
		"meeting_transcript_summaries",
		"delivery_queue_entries"
	],
	"automation-policy-fence-v30": ["cron_jobs"],
	"local-workspace-manifests-v31": ["local_workspace_projections", "local_workspace_manifest_nodes"],
	"local-workspace-cas-v35": [
		"local_workspace_projections",
		"local_workspace_tree_packs",
		"local_workspace_source_path_sets"
	],
	"template-names-v36": [...TEMPLATE_STATE_TABLE_RENAMES.flat(), "agent_provenance"],
	"operator-approvals-system-agent": ["operator_approvals"],
	"session-watch-cursor-provenance-v4": ["session_watch_cursors"],
	"strict-tables-v3": OPENCLAW_STATE_SCHEMA_SQL.split("\n").flatMap((e) => {
		const t = /^CREATE TABLE IF NOT EXISTS (\w+) \(/u.exec(e)?.[1];
		return t ? [t] : [];
	})
};
function dropLegacyStateTables(e) {
	const t = ["database", "verifications"].join("_");
	e.exec(`DROP TABLE IF EXISTS ${t};`);
	e.exec("DROP TABLE IF EXISTS node_pairing_pending; DROP TABLE IF EXISTS node_pairing_paired;");
}
function migrateWorkerPlacementExecutionModeSchema(e, t) {
	if (t >= 8 || !tableExists(e, "worker_session_placements")) return false;
	for (const t of [
		"execution_mode TEXT",
		"terminal_reason TEXT",
		"terminal_at_ms INTEGER"
	]) ensureColumn(e, "worker_session_placements", t);
	const n = extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "worker_session_placements", { errorMessage: "Canonical worker placement schema block is missing" });
	const r = openNodeSqliteDatabase(":memory:");
	let i;
	try {
		r.exec(n);
		i = r.prepare("PRAGMA table_xinfo(worker_session_placements)").all().filter((e) => e.hidden === 0).map((e) => e.name);
	} finally {
		r.close();
	}
	const a = e.prepare("PRAGMA table_xinfo(worker_session_placements)").all().filter((e) => e.hidden === 0).map((e) => e.name);
	const o = new Set(i);
	if (a.length !== i.length || a.some((e) => !o.has(e))) throw new Error("OpenClaw v7 worker placement columns are not canonical");
	if (e.prepare(`SELECT type, name
         FROM sqlite_schema
        WHERE tbl_name = 'worker_session_placements'
          AND type IN ('index', 'trigger')
          AND sql IS NOT NULL
          AND name NOT IN (
            'idx_worker_session_placements_session_key',
            'idx_worker_session_placements_reconcile',
            'idx_worker_session_placements_environment'
          )`).all().length > 0) throw new Error("OpenClaw v7 worker placement schema has unsupported attached objects");
	const s = "worker_session_placements_migration_v8";
	if (tableExists(e, s)) throw new Error(`OpenClaw worker placement migration table already exists: ${s}`);
	const c = n.replace("CREATE TABLE IF NOT EXISTS worker_session_placements", `CREATE TABLE ${s}`);
	const l = i.map(quoteSqliteIdentifier).join(", ");
	e.exec(c);
	e.exec(`INSERT INTO ${s} (${l}) SELECT ${l} FROM worker_session_placements;`);
	e.exec("DROP TABLE worker_session_placements;");
	e.exec(`ALTER TABLE ${s} RENAME TO worker_session_placements;`);
	return true;
}
function isDefaultAgentDatabasePath(e, t) {
	const n = path.dirname(e);
	const r = path.dirname(n);
	return path.basename(e) === "openclaw-agent.sqlite" && path.basename(n) === "agent" && path.basename(r) === t && path.basename(path.dirname(r)) === "agents";
}
function migrateAgentDatabaseRelativePaths(e, t, n) {
	if (t >= 9 || !tableExists(e, "agent_databases")) return {
		relativized: 0,
		reanchored: [],
		deleted: [],
		preserved: 0
	};
	const r = e.prepare("SELECT agent_id, path FROM agent_databases").all();
	const i = e.prepare("UPDATE agent_databases SET path = ? WHERE agent_id = ? AND path = ?");
	const a = e.prepare("DELETE FROM agent_databases WHERE agent_id = ? AND path = ?");
	const o = e.prepare("SELECT 1 FROM agent_databases WHERE agent_id = ? AND path = ? LIMIT 1");
	const s = e.prepare(`
    UPDATE agent_databases AS canonical
       SET schema_version = source.schema_version,
           last_seen_at = source.last_seen_at,
           size_bytes = source.size_bytes
      FROM agent_databases AS source
     WHERE canonical.agent_id = ? AND canonical.path = ?
       AND source.agent_id = canonical.agent_id AND source.path = ?
       AND source.last_seen_at > canonical.last_seen_at
  `);
	let c = 0;
	const l = [];
	const u = [];
	for (const e of r) {
		const t = e.agent_id;
		const r = e.path;
		if (typeof t !== "string" || typeof r !== "string") throw new Error("OpenClaw v8 agent database registry paths are not canonical");
		if (!path.isAbsolute(r)) continue;
		const l = resolveOpenClawAgentDatabaseStoredPath(n, r);
		if (!path.isAbsolute(l)) {
			if (o.get(t, l)) {
				s.run(t, l, r);
				a.run(t, r);
				u.push(r);
			} else {
				i.run(l, t, r);
				c += 1;
			}
		}
	}
	const d = resolveOpenClawStateDirForDatabasePath(n);
	for (const e of r) {
		const t = e.agent_id;
		const r = e.path;
		if (typeof t !== "string" || typeof r !== "string" || !path.isAbsolute(r) || !path.isAbsolute(resolveOpenClawAgentDatabaseStoredPath(n, r))) continue;
		if (isDefaultAgentDatabasePath(path.resolve(r), t)) {
			const e = path.join(d, "agents", t, "agent", "openclaw-agent.sqlite");
			const s = resolveOpenClawAgentDatabaseStoredPath(n, e);
			if (o.get(t, s)) {
				a.run(t, r);
				u.push(r);
			} else if (existsSync(e)) {
				i.run(s, t, r);
				l.push(r);
			}
		}
	}
	return {
		relativized: c,
		reanchored: l,
		deleted: u,
		preserved: r.length - c - l.length - u.length
	};
}
function assertCanonicalAgentDatabasesPrimaryKey(e, t) {
	if (!tableExists(e, "agent_databases")) return;
	const n = tablePrimaryKeyColumns(e, "agent_databases");
	if (n.length !== 2 || n[0] !== "agent_id" || n[1] !== "path") throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} has an unsupported agent database registry schema. Upgrades from pre-July-2026 state are no longer migrated; restore a backup produced by a July 2026 or newer release before retrying.`);
}
function repairLegacyGatewayRestartHandoffsForStrictMigration(e) {
	if (!tableExists(e, "gateway_restart_handoff")) return;
	e.prepare("DELETE FROM gateway_restart_handoff WHERE expires_at <= ?").run(Date.now());
	e.exec(`
    UPDATE gateway_restart_handoff
    SET
      restart_trace_started_at = CASE
        WHEN typeof(restart_trace_started_at) = 'real'
          THEN CAST(restart_trace_started_at AS INTEGER)
        ELSE restart_trace_started_at
      END,
      restart_trace_last_at = CASE
        WHEN typeof(restart_trace_last_at) = 'real'
          THEN CAST(restart_trace_last_at AS INTEGER)
        ELSE restart_trace_last_at
      END
    WHERE typeof(restart_trace_started_at) = 'real'
       OR typeof(restart_trace_last_at) = 'real';
  `);
}
function assertCanonicalStateSchemaShape(e, t) {
	assertCanonicalOperatorApprovalKinds(e, t);
	assertCanonicalAgentDatabasesPrimaryKey(e, t);
	if (!hasCanonicalAuditEventsSchema(e)) {
		if (canRepairLegacyAuditEventsSchema(e)) throw new OpenClawStateDatabaseSchemaMigrationRequiredError("audit-events-v2", t);
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${t} has a noncanonical audit event schema that cannot be repaired automatically; restore the canonical audit_events shape before retrying.`);
	}
}
//#endregion
//#region src/state/openclaw-state-db-fast-path.ts
function assertCurrentStateRuntimeSchema(e, t, n = createSqliteTableContractReader(e)) {
	const r = findMissingLazyStateStartupColumn(n);
	if (r) throwSqliteSchemaMismatches(t, ["missing column " + r.tableName + "." + r.columnName]);
	assertCanonicalStateSchemaShape(e, t);
	assertOpenClawStateDatabaseForMaintenance(e, { pathname: t }, n);
	assertSqliteSchemaContains(e, t, OPENCLAW_STATE_SCHEMA_SQL, STATE_RUNTIME_SCHEMA_COMPATIBILITY, n);
}
/** Catalog presence is enough to refuse retired history without reading or rewriting its rows. */
function assertNoLegacyStateRuntimeRepair(e, t) {
	if (hasLegacyCronRunLogs(e)) throw new OpenClawStateDatabaseSchemaMigrationRequiredError("legacy-cron-run-logs", t);
}
function isOpenClawStateSchemaFastPathEligible(e, t, n) {
	const r = getStateRuntimeSchemaAdmission(e);
	if (r) return r.startupReady;
	let i;
	const a = withSqlitePostCommitPublications(e, () => runSqliteDeferredTransactionSync(e, () => {
		const r = assertSupportedStateSchemaVersion(e, t);
		if (readStateSchemaContentVersion(e) !== 36) return false;
		const a = readSqliteSchemaCookie(e);
		if (typeof a !== "number") throw new Error(`Shared-state database ${t} schema version is unavailable.`);
		assertCurrentStateRuntimeSchema(e, t, createSqliteTableContractReader(e));
		assertNoLegacyStateRuntimeRepair(e, t);
		const o = readGatewayOwnerLeaseFromDatabase(e);
		if (!(o?.state === "live" && o.pid !== process.pid && Boolean(o.stateDatabaseProvenance) && o.stateDatabaseProvenance === readAgentDatabaseLeaseProvenance(t))) i = assertOpenClawStateRuntimeIntegrity(e, t, {
			schemaVersion: a,
			userVersion: r
		}, n);
		return true;
	}, { operationLabel: "state.admission.fast-path" }));
	i?.();
	if (a) publishStateRuntimeSchemaAdmission(e, true);
	return a;
}
//#endregion
//#region src/state/openclaw-state-db-existing-schema.ts
/** Metadata is validated with the physical database's first runtime admission. */
function assertExistingOpenClawStateRuntimeMetadata(e, t, n) {
	if (getStateRuntimeSchemaAdmission(e)) {
		const t = getStateSchemaVersionAdmission(e)?.userVersion;
		if (t !== void 0) return t;
	}
	const r = assertSupportedStateSchemaVersion(e, t, void 0, void 0, n);
	if (readStateSchemaContentVersion(e) !== 36) throw new Error(`Existing shared-state database ${t} requires schema migration by its owning installation; run openclaw doctor --fix there before using it.`);
	let i;
	try {
		i = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("schema_meta").select(["role", "schema_version"]).where("meta_key", "=", "primary").limit(1));
	} catch (t) {
		throw classifySqliteTableReadError(e, "schema_meta", [
			"meta_key",
			"role",
			"schema_version"
		], t);
	}
	if (i?.role !== "global" || i.schema_version !== r) throw new Error(`Existing shared-state database ${t} has inconsistent ownership or schema metadata.`);
	return r;
}
/** Validate an existing runtime schema without applying repairs. */
function assertExistingOpenClawStateRuntimeSchema(e, t, n, r, i = "runtime") {
	const a = getStateRuntimeSchemaAdmission(e) ? getAdmittedSqliteSchemaFacts(e) : void 0;
	if (a) {
		assertOpenClawStateRuntimeIntegrity(e, t, a, n, r)?.();
		return;
	}
	let o;
	runSqliteReadSnapshotSync(e, () => {
		const a = assertExistingOpenClawStateRuntimeMetadata(e, t, i);
		const s = readSqliteSchemaCookie(e);
		if (typeof s !== "number") throw new Error(`Existing shared-state database ${t} schema version is unavailable.`);
		o = assertOpenClawStateRuntimeIntegrity(e, t, {
			schemaVersion: s,
			userVersion: a
		}, n, r);
		const c = createSqliteTableContractReader(e);
		assertCurrentStateRuntimeSchema(e, t, c);
		assertNoLegacyStateRuntimeRepair(e, t);
	}, { operationLabel: "state.admission.existing-schema" });
	o?.();
	publishStateRuntimeSchemaAdmission(e, true);
}
//#endregion
//#region src/state/openclaw-state-db-read-schema.ts
function assertStateReadSchemaForPolicy(e, t, n, r, i, a = "runtime") {
	if (isPostgresSqlConnection(e)) {
		if (r !== void 0) requireNativeDatabaseFile("postgres", "integrity");
		assertSupportedStateSchemaVersion(e, t, void 0, i, a);
		return;
	}
	if (n) assertExistingOpenClawStateRuntimeSchema(e, t, getSqliteWorkerStateIntegrityAdmission(), r, a);
	else assertSupportedStateSchemaVersion(e, t, void 0, i, a);
}
//#endregion
//#region src/state/openclaw-state-postgres-snapshot-context.ts
/** The retained discovery owner selects the same MVCC view for native and worker reads. */
const postgresStateReadSnapshot = resolveGlobalSingleton(Symbol.for("openclaw.postgresStateReadSnapshot"), () => new AsyncLocalStorage());
//#endregion
//#region src/state/openclaw-state-db-read-connection.ts
const retainedReaders = /* @__PURE__ */ new Map();
const corruptedReaders = /* @__PURE__ */ new WeakSet();
let unregisterExitClose;
function retireReader(e) {
	if (retainedReaders.get(e.identity.key) !== e) return;
	clearTimeout(e.idleTimer);
	e.idleTimer = void 0;
	e.retiring = true;
	e.connection.close();
	retainedReaders.delete(e.identity.key);
	if (!retainedReaders.size) {
		unregisterExitClose?.();
		unregisterExitClose = void 0;
	}
}
function scheduleReaderRetirement(e) {
	if (!getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources || retainedReaders.get(e.identity.key) !== e) return;
	e.idleTimer ??= runInDetachedAsyncContext(() => setTimeout(() => {
		try {
			retireReader(e);
		} catch (t) {
			process.emitWarning(`Idle shared-state reader cleanup failed: ${String(t)}`);
			scheduleReaderRetirement(e);
		}
	}, SQLITE_IDLE_HANDLE_TTL_MS).unref());
	e.idleTimer.refresh();
}
/** The host joins this receipt before allowing replacement or deletion of live state. */
function closeRetainedOpenClawStateReadConnections(e) {
	const t = [];
	for (const n of retainedReaders.values()) if (e === void 0 || n.identity.key === e) try {
		retireReader(n);
	} catch (e) {
		t.push(e);
	}
	throwSqliteLifecycleErrors(t, "Retained shared-state reader cleanup failed.");
}
function borrowStateReadConnection(e, t) {
	if (isStatePostgres()) return openStateReadConnectionResult(e, e, t, void 0, true);
	isExistingOpenClawStateSchema(e);
	const n = readDatabasePathIdentitySync(e);
	if (t !== void 0) assertExistingDatabaseIdentity(e, t);
	for (const e of retainedReaders.values()) if (e.identity.canonicalPath === n.canonicalPath && e.identity.key !== n.key) retireReader(e);
	if (!n.key.startsWith("file:")) return openStateReadConnectionResult(e, e, t);
	let r = retainedReaders.get(n.key);
	if (r?.retiring || r && !r.connection.database.db.isOpen) {
		retireReader(r);
		r = void 0;
	}
	if (r?.borrowed) return openStateReadConnectionResult(e, e, n.key);
	if (!r) {
		const t = openStateReadConnectionResult(e, e, n.key);
		if (t.status === "unavailable") return t;
		r = {
			connection: t.value,
			identity: n,
			retiring: false,
			borrowed: false
		};
		retainedReaders.set(n.key, r);
		unregisterExitClose ??= registerSqliteCacheExitClose(closeRetainedOpenClawStateReadConnections);
	}
	const i = r;
	observeOpenClawDatabaseMaintenanceResource(i);
	i.borrowed = true;
	return {
		status: "available",
		value: {
			database: {
				db: i.connection.database.db,
				path: e
			},
			close(e) {
				i.borrowed = false;
				if (e && i.connection.database.db.isOpen && !i.connection.database.db.isTransaction) scheduleReaderRetirement(i);
				else retireReader(i);
				return true;
			}
		}
	};
}
var SnapshotCleanupIncompleteError = class extends Error {};
function assertStateReadSchema(e, t, n, r = "runtime") {
	assertStateReadSchemaForPolicy(e, t, isExistingOpenClawStateSchema(t, e), n, void 0, r);
}
function withOpenClawStateReadOnlyLocation(e, t, n, r, i, a, o = false, s) {
	const c = readOpenClawStateReadOnlyLocation(e, t, n, r, i, a, o, s);
	if (c.status === "unavailable") throw c.error;
	return c.value;
}
/** Return a failed read only after its native reader and admission have settled. */
function readOpenClawStateReadOnlyLocation(e, t, n, r, i, a, o = false, s) {
	const c = o && n === t && !a ? borrowStateReadConnection(t, i) : openStateReadConnectionResult(t, n, i, a, true);
	if (c.status === "unavailable") return c;
	const l = c.value;
	const u = [];
	let d;
	let f;
	try {
		if (r && !isPostgresSqlConnection(l.database.db)) d = r(l.database.db);
		const i = isExistingOpenClawStateSchema(t, l.database.db);
		const a = r ? "doctor-maintenance" : "runtime";
		try {
			let n = false;
			const r = postgresStateReadSnapshot.getStore();
			const read = () => runSqliteReadOperationSync(l.database.db, () => {
				admitStateSchemaFacts(l.database.db, t, a);
				assertStateReadSchemaForPolicy(l.database.db, t, i, void 0, s, a);
				n = true;
				return e(l.database);
			});
			const readTransaction = () => isPostgresSqlConnection(l.database.db) ? l.database.db.runTransaction(() => {
				if (r?.path === t) l.database.db.exec(`SET TRANSACTION SNAPSHOT '${r.snapshot.replaceAll("'", "''")}'`);
				return read();
			}, void 0, true) : read();
			f = {
				status: "available",
				value: withPostgresSchemaAdmissionRetry(l.database.db, readTransaction, () => !n && r?.path !== t)
			};
		} catch (e) {
			if (!isPostgresSqlConnection(l.database.db) && isSqliteCorruptionError(e)) {
				invalidateOpenClawStateRuntimeIntegrity(l.database.db);
				corruptedReaders.add(l.database.db);
			}
			f = {
				status: "unavailable",
				error: e
			};
		}
		const o = typeof n === "string" ? n : n.location;
		if (f.status === "available" && o === t && isPromiseLike(f.value)) throw new SqliteCoordinatorError("SQLite source read must remain synchronous");
		assertTransactionUsable(l.database.db);
	} catch (e) {
		u.push(e);
	}
	try {
		d?.();
	} catch (e) {
		u.push(e);
	}
	try {
		const e = typeof n !== "string" && u.length === 0 && f?.status === "available" && !getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources;
		if (!l.close(u.length === 0 && f?.status === "available" && !corruptedReaders.has(l.database.db)) && !e) throw new SnapshotCleanupIncompleteError("Shared-state snapshot cleanup is incomplete.");
	} catch (e) {
		u.push(e);
	}
	if (u.length) {
		if (f?.status === "unavailable" && !u.includes(f.error)) u.unshift(f.error);
		throwSqliteLifecycleErrors(u, "Shared-state read and reader cleanup failed.");
	}
	return f;
}
function openOpenClawStateReadOnlyLocation(e, t) {
	const n = openOpenClawStateReadConnection(e, t);
	try {
		runSqliteReadOperationSync(n.database.db, () => {
			admitStateSchemaFacts(n.database.db, e);
			assertStateReadSchema(n.database.db, e);
		});
	} catch (e) {
		try {
			n.close();
		} catch (t) {
			throwSqliteLifecycleErrors([e, t], "Shared-state reader admission and cleanup failed.");
		}
		throw e;
	}
	return n;
}
/** Own one native reader; callers retain their runtime or maintenance schema policy. */
function openOpenClawStateReadConnection(e, t, n, r) {
	const i = openStateReadConnectionResult(e, t, n, r);
	if (i.status === "unavailable") throw i.error;
	return i.value;
}
function openStateReadConnectionResult(e, t, n, r, i = false) {
	const a = typeof t === "string" ? void 0 : t;
	const o = typeof t === "string" ? t : t.location;
	const s = resolveSqliteDatabaseFilePath(o);
	const c = {
		readOnly: true,
		timeout: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS
	};
	let l;
	const cleanupFailedOpen = (e) => {
		const t = [e];
		try {
			l?.();
		} catch (e) {
			t.push(e);
		}
		try {
			if (a && !a.cleanup()) t.push(new SnapshotCleanupIncompleteError("Shared-state snapshot cleanup is incomplete."));
		} catch (e) {
			t.push(e);
		}
		if (t.length > 1) throw createSqliteLifecycleAggregateError(t, "Shared-state reader open and cleanup failed.", e);
	};
	let u;
	try {
		if (isStatePostgres()) {
			if (t !== e || r) assertStateFileSnapshotAllowed();
			if (i) isExistingOpenClawStateSchema(e);
			const a = openExistingStatePostgresConnection(e, n);
			if (a) return {
				status: "available",
				value: a
			};
		}
		if (n !== void 0) assertExistingDatabaseIdentity(s, n);
		l = r ? acquireSqliteSnapshotReadToken(r) : void 0;
		if (i) isExistingOpenClawStateSchema(e);
		if (o === e) u = openTrackedStateDatabaseResult(e, c);
		else try {
			u = {
				status: "available",
				database: openNodeSqliteDatabase(o, c)
			};
		} catch (e) {
			u = {
				status: "unavailable",
				error: e
			};
		}
	} catch (e) {
		cleanupFailedOpen(e);
		throw e;
	}
	if (u.status === "unavailable") {
		cleanupFailedOpen(u.error);
		return u;
	}
	const d = u.database;
	let f = false;
	let p = false;
	let m = 0;
	const h = {
		db: d,
		path: e,
		afterClose: () => {
			l?.();
			if (a && m === 0 && !a.cleanup()) throw new SnapshotCleanupIncompleteError("Shared-state snapshot cleanup is incomplete.");
		}
	};
	const g = {
		database: {
			db: d,
			path: e
		},
		snapshotSource: a ? { retain() {
			if (p || f) throw new Error("Shared-state snapshot source is closing or closed");
			const e = retainSnapshotTempDirectory(a.cleanupRoot ?? path.dirname(a.location));
			m++;
			let t = false;
			return {
				location: a.location,
				cleanupRoot: a.cleanupRoot,
				async release() {
					if (!t) {
						t = true;
						e();
						m--;
					}
					if (f && m === 0 && !await a.cleanupAsync()) throw new SnapshotCleanupIncompleteError("Shared-state snapshot cleanup is incomplete.");
				}
			};
		} } : void 0,
		close() {
			if (f) return false;
			p = true;
			const e = openClawStateDatabaseCache.closeOpenClawStateDatabaseHandle(h);
			if (e.length === 1 && e[0] instanceof SnapshotCleanupIncompleteError) return false;
			throwSqliteLifecycleErrors(e, "Shared-state reader cleanup failed.");
			f = true;
			return true;
		}
	};
	try {
		enableNodeSqliteKyselyStatementCache(d);
		if (n !== void 0) assertExistingDatabaseIdentity(s, n);
	} catch (e) {
		try {
			if (!g.close()) throw new SnapshotCleanupIncompleteError("Shared-state snapshot cleanup is incomplete.");
		} catch (t) {
			throw createSqliteLifecycleAggregateError([e, t], "Shared-state reader identity and cleanup failed.", e);
		}
		throw e;
	}
	return {
		status: "available",
		value: g
	};
}
//#endregion
//#region src/state/openclaw-state-db-transaction.ts
const managedStateTransactions = resolveGlobalSingleton(Symbol.for("openclaw.managedStateTransactions"), () => /* @__PURE__ */ new WeakSet());
/** Only the synchronous transaction owner may lend its uncommitted authority rows. */
function isManagedStateTransaction(e) {
	return e.isTransaction && managedStateTransactions.has(e);
}
function runManagedStateTransaction(e, t, n) {
	if (e.isTransaction && !managedStateTransactions.has(e)) throw new Error("Cannot join an unmanaged shared-state transaction; enter through runOpenClawStateWriteTransaction before BEGIN.");
	const transaction = () => withSqlitePostCommitPublications(e, () => {
		const r = !e.isTransaction;
		if (r) managedStateTransactions.add(e);
		try {
			return n.singleStatement ? runSqliteSingleStatementSync(e, t) : runSqliteImmediateTransactionSync(e, t, n);
		} finally {
			if (r) managedStateTransactions.delete(e);
		}
	});
	return n.busyTimeoutMs === void 0 || isPostgresSqlConnection(e) ? transaction() : runWithSqliteBusyTimeout(e, n.busyTimeoutMs, transaction);
}
//#endregion
//#region src/state/openclaw-state-db-readonly-reuse.ts
const maintenanceReaders = /* @__PURE__ */ new WeakMap();
/** Mutable maintenance owns this live reader until drainage; each guard queries current rows. */
function withMaintenanceOpenClawStateDatabaseReadOnly(e, t) {
	const n = getOpenClawDatabaseMaintenanceScope();
	if (!n || !allowsMaintenanceLiveAuthorityReads(n, t)) return { reused: false };
	n.assertReadAdmission();
	let r = maintenanceReaders.get(n);
	if (!r) {
		r = /* @__PURE__ */ new Map();
		maintenanceReaders.set(n, r);
	}
	let i = r.get(t);
	if (!i) {
		const e = captureOpenClawStateDatabaseReadAdmission(t);
		assertExistingDatabaseIdentity(t, e.identity.key, e.identity.birthtime);
		const a = openOpenClawStateReadOnlyLocation(t, t);
		let o = false;
		const close = () => {
			if (o) return;
			if (!a.close()) throw new Error("Maintenance authority reader cleanup is incomplete");
			o = true;
			r.delete(t);
			s();
		};
		const s = registerOpenClawStatePathAsyncResource(e, async () => {
			close();
		});
		n.own(a, "shared-handles", close);
		i = { read(n) {
			e.assertCurrent();
			assertExistingDatabaseIdentity(t, e.identity.key, e.identity.birthtime);
			const r = runSqliteReadOperationSync(a.database.db, () => {
				assertStateReadSchema(a.database.db, t);
				return n(a.database);
			});
			if (isPromiseLike(r)) throw new SqliteCoordinatorError("SQLite maintenance authority read must remain synchronous");
			return r;
		} };
		r.set(t, i);
	}
	return {
		reused: true,
		value: i.read(e)
	};
}
/** Current-authority guards can borrow their writer; discovery sees committed rows. */
function withCachedOpenClawStateDatabaseReadOnly(e, t, n) {
	return openClawStateDatabaseCache.withCachedOpenClawStateDatabase(t, { readOnly: true }, (r) => {
		if (!r.db.isOpen) return { reused: false };
		const i = n && isManagedStateTransaction(r.db);
		if (r.db.isTransaction && !i) return { reused: false };
		try {
			assertStateReadSchema(r.db, t);
			observeOpenClawDatabaseMaintenanceResource(r.db);
			const n = e(r);
			if (i && isPromiseLike(n)) throw new SqliteCoordinatorError("SQLite current-authority read must remain synchronous");
			return {
				reused: true,
				value: n
			};
		} catch (e) {
			openClawStateDatabaseCache.evictOpenClawStateDatabaseAfterCorruption(r, e);
			throw e;
		}
	}) ?? { reused: false };
}
/** A native read borrow can avoid copying only while its original physical path still matches. */
function canReadWarmNativeSourceIndependently(e, t, n) {
	const r = requireOpenClawStateDatabaseIdentity(e);
	if (r.key !== n) return false;
	try {
		assertExistingDatabaseIdentity(t, r.key);
		return true;
	} catch {
		return false;
	}
}
//#endregion
//#region src/infra/sqlite-live-owner.ts
function hasVerifiedLiveSqliteOwner(e) {
	const t = resolveGatewayStateOwnerPath(e);
	let n;
	try {
		n = parseGatewayLockPayload(fsSync.readFileSync(t, "utf8"));
	} catch {
		return false;
	}
	if (!n || n.role && n.role !== "gateway" && n.role !== "agent-embedded") return false;
	const r = readStateLeaseProcessOwnerStatus({
		pid: n.pid,
		host: n.processNamespace?.host ?? hostname(),
		startedAt: n.startTime ?? null,
		processNamespace: n.processNamespace,
		machineIdentity: n.machineIdentity
	});
	if (r === "unknown") throw new GatewayLockNamespaceError(n, t);
	return r === "live";
}
//#endregion
//#region src/state/openclaw-state-read-pool.ts
function stateReadPools(e) {
	return [e.pool, e.awaitedPool].filter((e) => e !== void 0);
}
function createStateReadPool(e, t) {
	ensureSqliteLibrarySelected();
	return createOwnedWorkerTaskPool({
		workerUrl: e,
		workerOptions: { resourceLimits: { maxOldGenerationSizeMb: 512 } },
		maxWorkers: resolveStateReadWorkerCount(),
		idleTimeoutMs: SQLITE_IDLE_HANDLE_TTL_MS,
		burstIdleTimeoutMs: 3e4,
		maxPendingTasks: 128,
		maxPendingBytes: DEFAULT_WORKER_PENDING_BYTES
	}, t ? {
		retainedTransport: true,
		nativeSource: t,
		databaseAccess: "read-only"
	} : { databaseAccess: "read-only" });
}
function closeReadResources(e, t) {
	return getSqliteRuntimeCapabilities().explicitSqliteCloseReleasesNativeResources ? e.closeResources(t) : e.rotate();
}
//#endregion
//#region src/state/openclaw-state-read-request.ts
function stringBytes(e) {
	return e.reduce((e, t) => e + Buffer.byteLength(t ?? "", "utf8"), 0);
}
function commandBytes(e) {
	if (typeof e === "string") return Buffer.byteLength(JSON.stringify(e), "utf8");
	if (typeof e === "number" || typeof e === "bigint") return 8;
	if (typeof e === "boolean") return 1;
	if (e === null || e === void 0) return 0;
	if (Array.isArray(e)) return e.reduce((e, t) => e + 8 + commandBytes(t), 0);
	return Object.entries(e).reduce((e, [t, n]) => e + Buffer.byteLength(t, "utf8") + 8 + commandBytes(n), 0);
}
function requestBytes(e) {
	return commandBytes(e.command) + commandBytes(e.context.databaseEngineSelection) + stringBytes([
		...Object.entries(e.context.environment).flatMap(([e, t]) => [e, t]),
		e.context.existingSchemaPath,
		e.databasePath,
		e.location,
		e.expectedIdentity,
		e.snapshotRoot,
		e.postgresSnapshot
	]);
}
//#endregion
//#region src/state/openclaw-state-read-worker.ts
function decodeOpenClawStateReadReply(e) {
	if (e.ok) return { value: e };
	const t = new Error(e.message);
	retainOpenClawStateWorkerErrorPayload(t, e.error);
	return {
		error: hydrateOpenClawStateWorkerError(t, { includeOrdinary: true }),
		sourceAdmitted: e.sourceAdmitted === true
	};
}
async function closeReadPool(e) {
	if (e.closing) return await e.closing;
	const t = stateReadPools(e);
	if (!t.length) return;
	const n = (async () => {
		const n = await Promise.allSettled(t.map(async (e) => {
			await closeReadResources(e);
			await e.close();
		}));
		throwSqliteLifecycleErrors(n.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader pools cleanup failed");
		e.pool = void 0;
		e.awaitedPool = void 0;
	})();
	e.closing = n;
	try {
		await n;
	} finally {
		e.closing = void 0;
	}
}
function readRuntimes() {
	return resolveGlobalSingleton(Symbol.for("openclaw.stateReadWorkers"), () => {
		const e = /* @__PURE__ */ new Map();
		registerOpenClawStateDatabaseAsyncResource({
			phase: "after-resources",
			async close(t) {
				const n = await Promise.allSettled([...e.values()].map(async (e) => {
					if (t) {
						const n = await Promise.allSettled(stateReadPools(e).map((e) => closeReadResources(e, t.key)));
						throwSqliteLifecycleErrors(n.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader resources cleanup failed");
					} else await closeReadPool(e);
				}));
				throwSqliteLifecycleErrors(n.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader source cleanup failed");
			}
		});
		registerOpenClawStateDatabaseLifecycleListener((t) => {
			if (t.kind !== "opened" && t.identity) {
				const n = t.identity;
				for (const t of e.values()) Promise.allSettled(stateReadPools(t).map((e) => closeReadResources(e, n.key))).then((e) => throwSqliteLifecycleErrors(e.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader invalidation failed")).catch((e) => {
					process.emitWarning(`Shared-state reader invalidation failed: ${String(e)}`);
				});
			}
		});
		return e;
	});
}
function readPool(e, t, n) {
	if (e.sealed && !t || e.closing) throw new WorkerTaskError("Shared-state readers are closing", "unavailable");
	const r = !n || e.pool !== void 0 || getDatabaseProcessRole() === "gateway";
	const i = r ? "pool" : "awaitedPool";
	if (!e[i]) e[i] = createStateReadPool(e.workerUrl, r ? e.nativeSource : void 0);
	return {
		pool: e[i],
		retained: r
	};
}
/** Capture the execution source before snapshot preparation yields. */
function captureOpenClawStateReadSource() {
	const e = captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl("stateRead"));
	const t = captureRetainedNativeWorkerSource({ runtimeGeneration: e.runtimeGeneration });
	const n = readRuntimes();
	let r = n.get(t);
	if (!r) {
		const i = {
			nativeSource: t,
			workerUrl: e.moduleUrl,
			operations: /* @__PURE__ */ new Set(),
			sealed: false
		};
		t.retain(i, () => {
			i.sealed = true;
			if (!i.stopping) i.stopping = Promise.resolve().then(async () => {
				const e = await Promise.allSettled([...i.operations].map((e) => Promise.resolve().then(() => e.close())));
				throwSqliteLifecycleErrors(e.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader source cleanup failed");
				await closeReadPool(i);
				n.delete(t);
			}).finally(() => {
				i.stopping = void 0;
			});
			return i.stopping;
		});
		n.set(t, i);
		r = i;
	}
	return new StateReadSource(r);
}
var StateReadSource = class {
	constructor(e) {
		this.state = e;
		this.admitted = /* @__PURE__ */ new Set();
	}
	createTransport(e, t, n, r = false) {
		return new StateReadTransport(e, this, t, n, r);
	}
	ownsAdmission() {
		return this.admitted.size > 0;
	}
	own(e) {
		const { state: t, admitted: n } = this;
		if (t.sealed || t.closing) throw new WorkerTaskError("Shared-state readers are closing", "unavailable");
		const r = AsyncLocalStorage.snapshot();
		const i = { close: () => r(e) };
		t.operations.add(i);
		n.add(i);
		return () => {
			t.operations.delete(i);
			n.delete(i);
		};
	}
};
var StateReadTransport = class {
	constructor(e, t, n, r, i = false) {
		this.source = t;
		this.onChunk = n;
		this.onChunkAsync = r;
		this.awaitedOnly = i;
		this.tasks = /* @__PURE__ */ new Map();
		this.closed = false;
		this.pendingChunks = 0;
		this.capturedCommand = structuredClone(e);
	}
	async closeTask(e) {
		await e.close(this.tasks.get(e)?.retire ? { retire: true } : void 0);
		this.tasks.delete(e);
	}
	startRun(e, t, n, r, i, a, o, s) {
		const { onChunk: c, onChunkAsync: l } = this;
		let u;
		const d = { retire: true };
		try {
			if (this.closed) throw new WorkerTaskError("Shared-state read transport is closed", "unavailable");
			if (e.databaseEngineSelection && Object.values(e.databaseEngineSelection.effectiveEngines).includes("postgres")) getPostgresPool();
			const f = {
				context: {
					databaseEngineSelection: e.databaseEngineSelection,
					environment: { ...e.environment },
					existingSchemaPath: e.existingSchemaPath,
					stateIntegrity: e.stateIntegrity
				},
				databasePath: e.admission.databasePath,
				location: t,
				checkFreshAdmission: n,
				expectedIdentity: a,
				snapshotRoot: o,
				postgresSnapshot: s,
				command: { ...r }
			};
			const p = readPool(this.source.state, this.source.ownsAdmission(), this.awaitedOnly);
			const m = !p.retained && !e.maintenanceScope && r.type !== "admit";
			const h = p.pool.runTask(() => i.acquire(async () => {
				const e = resolveSqliteDatabaseFilePath(t);
				const n = acquireSqliteDatabaseAdmissionTurn(e, [], void 0, () => i.assertCurrent());
				if (n) u = await n;
				try {
					i.assertCurrent();
					if (a !== void 0) {
						assertDatabaseFileIdentity(await stat(e, { bigint: true }), { key: a });
						i.assertCurrent();
					}
					return f;
				} catch (e) {
					u?.();
					u = void 0;
					throw e;
				}
			}), {
				signal: i.signal,
				inputBytes: requestBytes(f),
				diagnosticOperation: r.type,
				...l ? { onRequest: async (e, { signal: t }) => {
					i.assertCurrent();
					const n = AbortSignal.any([i.signal, t]);
					n.throwIfAborted();
					this.pendingChunks += 1;
					try {
						await l(e, n);
						n.throwIfAborted();
						i.assertCurrent();
						return {
							input: null,
							timeoutMs: 3e5
						};
					} finally {
						this.pendingChunks -= 1;
						if (this.pendingChunks === 0) this.chunksDrained?.();
					}
				} } : c ? { onRequestSync(e) {
					i.assertCurrent();
					c(e);
					return {
						input: null,
						timeoutMs: 3e5
					};
				} } : {}
			});
			this.tasks.set(h, d);
			return {
				task: h,
				result: (async () => {
					let e;
					try {
						const t = await h.result;
						d.retire = m || Boolean(t.nativeCleanupFailure);
						e = decodeOpenClawStateReadReply(t);
					} catch (t) {
						e = { error: t };
					}
					u?.();
					u = void 0;
					d.retire ||= "error" in e;
					return e;
				})()
			};
		} catch (e) {
			u?.();
			u = void 0;
			throw e;
		}
	}
	async startValidateFresh(e, t) {
		const n = this.startRun(e, e.admission.databasePath, true, { type: "admit" }, t);
		const r = await n.result;
		if ("error" in r) throw r.error;
		t.assertCurrent();
		await this.closeTask(n.task);
	}
	async startRead(e, t) {
		return this.startRun(e.context, e.location, e.checkFreshAdmission, this.capturedCommand, t, e.expectedIdentity, e.snapshotRoot, e.postgresSnapshot).result;
	}
	startClose() {
		this.closed = true;
		if (this.closing) return this.closing;
		this.closing = (async () => {
			const e = await Promise.allSettled([...this.tasks.keys()].map((e) => this.closeTask(e)));
			if (this.pendingChunks > 0) await new Promise((e) => {
				this.chunksDrained = e;
			});
			throwSqliteLifecycleErrors(e.flatMap((e) => e.status === "rejected" ? [e.reason] : []), "Shared-state reader task cleanup failed");
		})().finally(() => {
			this.chunksDrained = void 0;
			this.closing = void 0;
		});
		return this.closing;
	}
};
//#endregion
//#region src/state/openclaw-state-read-operation.ts
function isStateReadReply(e, t) {
	return e.ok && e.type === t;
}
/** One async owner joins the query and native cleanup before releasing its snapshot. */
function startOpenClawStateReadOperation(e, t) {
	const { pathname: n, snapshot: r, scopes: i, context: a, preserveArtifacts: o, controller: s, signal: c, receipt: l } = t;
	let u;
	let d;
	let f;
	let p;
	let m;
	let h;
	let g;
	let _;
	let startSnapshotCleanup;
	let v;
	let y;
	let b;
	let x = false;
	let S;
	const isPendingAdmission = (e) => e instanceof StateDatabaseAdmissionPendingError && e.databasePath === n;
	const C = {
		signal: c,
		assertCurrent() {
			c.throwIfAborted();
			a.maintenanceScope?.assertAdmission();
			a.admission.assertCurrent();
			openClawStateDatabaseCache.assertOpenClawStateDatabaseOpenAllowed(n, "cached-read", b);
		},
		async acquire(e) {
			const acquire = () => {
				C.assertCurrent();
				return e();
			};
			try {
				return await acquire();
			} catch (e) {
				if (!isPendingAdmission(e)) throw e;
			}
			S ??= performance.now() + OPENCLAW_SQLITE_BUSY_TIMEOUT_MS;
			return acquireWithWait({
				acquire,
				shouldRetry: isPendingAdmission,
				deadlineMs: S,
				pollIntervalMs: 10,
				sleep: (e) => sleepWithAbort(e, c)
			});
		}
	};
	const closeTransport = async () => {
		if (!u) return;
		h ??= u.startClose();
		try {
			await h;
		} catch (e) {
			h = void 0;
			throw e;
		}
	};
	const cleanup = () => {
		if (x) return Promise.resolve();
		return y ??= (async () => {
			await closeTransport();
			v?.();
			v = void 0;
			if (p) {
				_ = startSnapshotCleanup?.();
				if (!(_ ? await _.result : await p.cleanupAsync())) throw new Error(`Shared-state read snapshot cleanup failed: ${p.cleanupRoot ?? n}`);
				p = void 0;
				_ = void 0;
			}
			if (m) {
				g ??= m.startClose();
				try {
					await g.result;
				} catch (e) {
					g = void 0;
					throw e;
				}
				m = void 0;
				g = void 0;
			}
			f?.release();
			await r?.release?.();
			x = true;
			T();
			d?.();
			for (const e of i) e.resources.delete(w);
		})().finally(() => {
			y = void 0;
		});
	};
	const w = { async close() {
		s.abort(/* @__PURE__ */ new Error("Shared-state read admission closed"));
		if (!p) g ??= m?.startClose();
		await closeTransport();
		await E.catch(() => void 0);
		await cleanup();
	} };
	const T = registerOpenClawStateDatabaseAsyncResource({ async close(e) {
		if (!e || e.key === a.admission.identity.key || e.canonicalPath === a.admission.identity.canonicalPath) await w.close();
	} });
	a.maintenanceScope?.own(w, "shared-resources", () => w.close());
	for (const e of i) e.resources.add(w);
	function consume(e) {
		const t = "error" in e ? e.sourceAdmitted : e.value.type !== "admit" && e.value.sourceAdmitted;
		if (t === true) l.phase = "read";
		else if (t === false && l.phase !== "read") l.phase = "before-read";
		if ("error" in e) throw e.error;
		if (t === true) f?.observe();
		return e.value;
	}
	async function query(t) {
		if (p) v = retainSnapshotTempDirectory(p.cleanupRoot ?? path.dirname(p.location));
		l.phase = e.type === "admit" ? "before-read" : "unobserved";
		return consume(await t.startRead({
			context: a,
			location: r?.cleanClose ? resolveImmutableSqliteFileUri(r.location) : p?.location ?? r?.location ?? n,
			checkFreshAdmission: !f,
			expectedIdentity: !r && !p || r?.cleanClose || r?.postgresSnapshot ? a.admission.identity.key : void 0,
			snapshotRoot: p?.cleanupRoot ?? r?.cleanupRoot,
			postgresSnapshot: r?.postgresSnapshot
		}, C));
	}
	async function run() {
		const i = captureOpenClawStateReadSource();
		const s = i.createTransport(e, t.onChunk, t.onChunkAsync, t.snapshotPreparation === "awaited");
		u = s;
		d = i.own(() => w.close());
		b = await prepareStateDatabaseReadAccess(a.admission);
		c.throwIfAborted();
		a.maintenanceScope?.assertAdmission();
		a.admission.assertCurrent();
		if (e.type === "admit") return query(s);
		const l = !r ? await C.acquire(() => {
			const e = o ? borrowOpenClawStateDatabaseForAsyncRead(n, "cached-read", b) : void 0;
			return {
				native: e,
				borrowed: e ?? (!o ? retainOpenClawStateDatabaseForIndependentRead(n, "cached-read", b) : void 0)
			};
		}) : void 0;
		const h = l?.native;
		f = l?.borrowed;
		const g = h && t.preferIndependentWarmRead && canReadWarmNativeSourceIndependently(h.database, n, a.admission.identity.key);
		if (!r && !f && !existingPathOrUndefined(n)) return;
		if (h && !g) {
			if (isPostgresSqlConnection(h.database.db)) requireNativeDatabaseFile("postgres", "file-snapshot");
			p = await prepareSqliteReadOnlyLocationFromOwnedDatabase(h.database.db, C.assertCurrent, c, "async");
		} else if (!r && o && !g) {
			const r = { key: a.admission.identity.key };
			await s.startValidateFresh(a, C);
			if ((e.type === "plugins.metadata.read" || e.type === "config.health.read") && !a.existingSchemaPath && !a.maintenanceScope && !getStateDatabaseSchemaLease(n) && (hasVerifiedLiveSqliteOwner(n) || readSqliteDatabaseCleanClose(n))) {
				C.assertCurrent();
				const t = await runSqliteReadOnlyOperation(n, {
					type: "startupMetadata.readCurrent",
					input: e
				}, {
					source: "canonical",
					expectedIdentity: a.admission.identity.key,
					env: a.environment,
					signal: c
				});
				C.assertCurrent();
				if (t) {
					const e = t.value;
					if (!e.ok) {
						const t = /* @__PURE__ */ new Error("Startup metadata inspection failed");
						retainOpenClawStateWorkerErrorPayload(t, e.error);
						return consume({
							error: hydrateOpenClawStateWorkerError(t, { includeOrdinary: true }),
							sourceAdmitted: e.sourceAdmitted
						});
					}
					return consume({ value: {
						ok: true,
						sourceAdmitted: true,
						...e.result
					} });
				}
			}
			if (t.snapshotPreparation === "awaited") p = await prepareSqliteReadOnlyLocationAwaited(n, {
				signal: c,
				expectedSourceIdentity: r,
				allowLiveOwner: e.type === "plugins.metadata.read" && a.maintenanceScope?.ownsSchemaMaintenance !== true && !getStateDatabaseSchemaLease(n)
			});
			else {
				m = startSqliteReadOnlyLocationAsync(n, {
					preserveSourceArtifacts: true,
					signal: c,
					expectedSourceIdentity: r
				});
				const e = await m.result;
				p = e;
				startSnapshotCleanup = () => e.startCleanup();
			}
		}
		return query(s);
	}
	const E = run();
	return (async () => {
		let e;
		const n = [];
		try {
			e = await E;
		} catch (e) {
			n.push(e);
		}
		try {
			await cleanup();
		} catch (e) {
			n.push(e);
		}
		throwSqliteLifecycleErrors(n, "Shared-state read and cleanup failed");
		t.callerSignal?.throwIfAborted();
		return e;
	})().catch((e) => {
		throw t.mapError ? t.mapError(e, l.phase) : e;
	});
}
//#endregion
//#region src/state/openclaw-state-read-scope.ts
/** Closing retains custody for accepted readers, but never admits a new reader. */
function assertRetainedReadScopeAdmission(e, t) {
	if (t.some((t) => t?.path === e && (!t.active || t.work.isClosing))) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state read scope is closing or closed; retry the operation in a current scope.");
}
//#endregion
//#region src/state/openclaw-state-read-snapshot-source.ts
const log = createSubsystemLogger("state/db");
//#endregion
//#region src/state/openclaw-state-db-readonly.ts
const disposableStateReads = resolveGlobalSingleton(Symbol.for("openclaw.disposableStateReads"), () => new AsyncLocalStorage());
const stateSnapshotReads = resolveGlobalSingleton(Symbol.for("openclaw.stateSnapshotReads"), () => new AsyncLocalStorage());
function exitStateReadSnapshot(e) {
	return stateSnapshotReads.exit(() => postgresStateReadSnapshot.exit(e));
}
function resolveStateReadCallerSignal() {
	const e = getAsyncWorkSignal();
	const t = stateSnapshotReads.getStore();
	return t && e === t.work.signal ? t.callerSignal : e;
}
/** Stable identity and private bytes for reads within the enclosing snapshot scope. */
function getActiveOpenClawStateDatabaseReadSnapshot(e = {}) {
	const t = stateSnapshotReads.getStore();
	return t?.path === resolveOpenClawStateReadPath(e) ? t.readSource() : void 0;
}
function requiresArtifactPreservingSnapshot(e) {
	if (isStatePostgres()) return false;
	const t = isArtifactPreservingStateRead("shared", e) && !isUpdateRehearsalPrivateDatabase(e, process.env) && !disposableStateReads.getStore()?.some((t) => t.active && t.path === e);
	if (t) assertStateFileSnapshotAllowed();
	return t;
}
const synchronousReadSnapshots = resolveGlobalSingleton(Symbol.for("openclaw.synchronousStateReadSnapshots"), () => ({ current: void 0 }));
function resolveOpenClawStateReadPath(e) {
	const t = resolveDatabasePath(e);
	assertOpenClawStateReadPathCurrent(t);
	return t;
}
/** Prepared paths still honor the invoking reader and schema owner's live admission. */
function assertOpenClawStateReadPathCurrent(e) {
	const t = stateSnapshotReads.getStore();
	const n = disposableStateReads.getStore();
	if (t || n?.length) assertRetainedReadScopeAdmission(e, [t, ...n ?? []]);
	isExistingOpenClawStateSchema(e);
}
function withOpenClawStateDatabaseReadOnlyIfOpen(e, t, n = false) {
	const r = stateSnapshotReads.getStore();
	if (r?.active && r.path === t) {
		openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t, r.env);
		const n = r.readSource();
		if (n) return {
			reused: true,
			value: withOpenClawStateReadOnlyLocation(e, t, n.cleanClose ? resolveImmutableSqliteFileUri(n.location) : n.location)
		};
	}
	if (isArtifactPreservingStateRead("agent", t) && (requiresArtifactPreservingSnapshot(t) || isUpdateRehearsalPrivateDatabase(t, process.env))) return { reused: false };
	if (isStatePostgres() && !n) return { reused: false };
	return withCachedOpenClawStateDatabaseReadOnly(e, t, n || synchronousReadSnapshots.currentAuthorityPath === t);
}
function withFreshOpenClawStateDatabaseReadOnly(e, t, n) {
	const r = t.env ?? process.env;
	openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(n, r);
	if (synchronousReadSnapshots.currentAuthorityPath === n) {
		const t = withMaintenanceOpenClawStateDatabaseReadOnly(e, n);
		if (t.reused) return t.value;
	}
	const i = synchronousReadSnapshots.current;
	if (i && requiresArtifactPreservingSnapshot(n)) {
		let t = i.get(n);
		if (!t) {
			t = openOpenClawStateReadOnlyLocation(n, prepareSqliteReadOnlyLocationSync(n));
			i.set(n, t);
		}
		assertStateReadSchema(t.database.db, n);
		const r = e(t.database);
		if (isPromiseLike(r)) throw new SqliteCoordinatorError("SQLite metadata snapshot read must remain synchronous");
		return r;
	}
	const a = requiresArtifactPreservingSnapshot(n) ? prepareSqliteReadOnlyLocationSync(n) : void 0;
	return withOpenClawStateReadOnlyLocation(e, n, a ?? n, void 0, void 0, void 0, !isMainThread && !getOpenClawDatabaseMaintenanceScope());
}
/** Read existing shared state while preserving non-missing filesystem failures. */
function withExistingOpenClawStateDatabaseReadOnly(e, t = {}) {
	const n = resolveOpenClawStateReadPath(t);
	if (synchronousReadSnapshots.current?.has(n)) return withFreshOpenClawStateDatabaseReadOnly(e, t, n);
	const r = withOpenClawStateDatabaseReadOnlyIfOpen(e, n);
	if (r.reused) return r.value;
	const i = existingPathOrUndefined(n);
	return i === void 0 ? void 0 : withFreshOpenClawStateDatabaseReadOnly(e, t, i);
}
/** Fixed reads observe committed state unless their owner explicitly selected a snapshot. */
function executeExistingOpenClawStateRead(e, t, n = {}) {
	const r = t.type;
	const { context: i, current: a, live: o, mapError: s } = n;
	const c = { phase: "before-read" };
	let l;
	try {
		i?.admission.assertCurrent();
		const execute = () => startRetainedOpenClawStateRead(e, t, c, n);
		const r = o ? () => artifactPreservingReads.run(false, () => exitStateReadSnapshot(execute)) : a ? () => exitStateReadSnapshot(execute) : execute;
		l = runPluginSharedStateWork(() => i?.runInCapturedSchemaScope ? i.runInCapturedSchemaScope(r) : r());
	} catch (e) {
		throw s ? s(e, c.phase) : e;
	}
	return l.then((e) => {
		if (!e || isStateReadReply(e, r)) return e;
		throw new Error(`Unexpected shared-state read reply for ${r}`);
	});
}
function startRetainedOpenClawStateRead(e, t, n, { context: r, signal: i, current: a, live: o, mapError: s, preferIndependentWarmRead: c, snapshotPreparation: l, onChunk: u, onChunkAsync: d }) {
	const f = a || o;
	const p = resolveOpenClawStateReadPath(e);
	const m = stateSnapshotReads.getStore();
	const h = m?.active && m.path === p ? m : void 0;
	const g = [...h ? [h] : [], ...(disposableStateReads.getStore() ?? []).filter((e) => e.active && e.path === p)];
	const _ = h?.env ?? e.env;
	const v = r ?? captureOpenClawStateReadWorkerContext({
		path: p,
		env: _
	});
	if (r) {
		if (v.admission.databasePath !== p) throw new Error("Shared-state read context does not match its selected source");
		v.maintenanceScope?.assertAdmission();
		v.admission.assertCurrent();
	}
	const y = requiresArtifactPreservingSnapshot(p);
	const b = new AbortController();
	const x = i ?? (isArtifactPreservingStateRead() ? resolveStateReadCallerSignal() : h?.callerSignal);
	const S = x ? AbortSignal.any([x, b.signal]) : b.signal;
	const run = () => {
		const e = f ? void 0 : synchronousReadSnapshots.current?.get(p)?.snapshotSource?.retain();
		const start = () => startOpenClawStateReadOperation(t, {
			pathname: p,
			snapshot: e ?? h?.readSource(),
			scopes: g,
			context: v,
			preserveArtifacts: y,
			preferIndependentWarmRead: c,
			snapshotPreparation: l,
			onChunk: u,
			onChunkAsync: d,
			controller: b,
			signal: S,
			callerSignal: x,
			receipt: n,
			mapError: s
		});
		if (h?.prepareSource && !e) {
			S.throwIfAborted();
			return h.prepareSource().then(() => {
				if (S.aborted) throw s ? s(S.reason, n.phase) : S.reason;
				return start();
			}, (e) => {
				throw s ? s(e, n.phase) : e;
			});
		}
		return start();
	};
	const C = g.reduceRight((e, t) => () => t.work.run(() => {
		const n = e();
		t.work.track(() => n).catch(() => void 0);
		return n;
	}), run);
	const w = v.maintenanceScope;
	let T;
	if (w) w.run(() => {
		const e = C();
		T = e;
		return e;
	});
	else T = C();
	if (!T) throw new Error("Shared-state read maintenance scope did not start its operation");
	retainSnapshotWork(T, () => b.abort(/* @__PURE__ */ new Error("Shared-state read admission closed")));
	return T;
}
/** Read existing shared state without creating or updating its SQLite sidecars. */
function withExistingOpenClawStateDatabaseArtifactPreservingReadOnly(e, t = {}, n) {
	if (n) return withExistingOpenClawStateDatabaseCurrentReadOnly(e, t, n);
	return withArtifactPreservingStateReads(() => withExistingOpenClawStateDatabaseReadOnly(e, t));
}
/** Publication guards need current rows, never an inherited discovery snapshot. */
function withExistingOpenClawStateDatabaseCurrentReadOnly(e, t = {}, n) {
	const r = resolveOpenClawStateReadPath(t);
	return exitStateReadSnapshot(() => {
		if (!n) {
			const t = withOpenClawStateDatabaseReadOnlyIfOpen(e, r, true);
			if (t.reused) return t.value;
		}
		if (existingPathOrUndefined(r) === void 0) return;
		openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(r, t.env ?? process.env);
		const i = (isStatePostgres() || t.allowNativeRead) && !isArtifactPreservingStateRead() && (!n || t.allowNativeRead === true);
		if (!i) assertStateFileSnapshotAllowed();
		return withOpenClawStateReadOnlyLocation(e, r, i ? r : prepareSqliteReadOnlyLocationSync(r), n);
	});
}
//#endregion
//#region src/utils/chunk-items.ts
/** Splits items into fixed-size chunks, preserving order and returning one row for non-positive sizes. */
function chunkItems(e, t) {
	if (t <= 0) return [Array.from(e)];
	const n = [];
	for (let r = 0; r < e.length; r += t) n.push(e.slice(r, r + t));
	return n;
}
//#endregion
//#region src/infra/exec-approvals-config.ts
const execSecuritySchema = _enum([
	"allowlist",
	"full",
	"deny"
]);
const execAskSchema = _enum([
	"always",
	"off",
	"on-miss"
]);
const persistedExecApprovalPolicySchema = looseObject({
	security: execSecuritySchema.optional(),
	ask: execAskSchema.optional(),
	askFallback: execSecuritySchema.optional(),
	autoAllowSkills: boolean().optional()
});
function normalizePersistedAllowlistSource(e) {
	return e === "allow-always" ? e : void 0;
}
const persistedExecAllowlistEntrySchema = looseObject({
	pattern: string().refine((e) => e.trim().length > 0),
	id: string().min(1),
	source: literal$1("allow-always").optional(),
	commandText: never().optional(),
	argPattern: string().optional(),
	lastUsedAt: number().finite().optional(),
	lastUsedCommand: string().optional(),
	lastResolvedPath: string().optional()
});
const legacyExecAllowlistEntrySchema = union([string().trim().min(1), persistedExecAllowlistEntrySchema.extend({
	id: string().optional(),
	source: string().transform(normalizePersistedAllowlistSource).optional(),
	commandText: string().optional()
})]).transform((e) => typeof e === "string" ? { pattern: e } : e);
function createExecApprovalsSchema(e, t) {
	const n = persistedExecApprovalPolicySchema.extend({
		allowlist: array(e).optional(),
		mcpTools: array(looseObject({
			server: string().refine((e) => e.trim().length > 0),
			tool: string().refine((e) => e.trim().length > 0),
			source: literal$1("allow-always"),
			addedAt: number().finite().nonnegative(),
			lastUsedAt: number().finite().nonnegative().optional()
		})).optional()
	});
	const r = unknown().refine((e) => !isRecord(e) || !Object.hasOwn(e, "__proto__")).pipe(record(string(), n)).refine((e) => t || !Object.hasOwn(e, "default"));
	return looseObject({
		version: literal$1(1),
		socket: looseObject({
			path: string().optional(),
			token: string().optional()
		}).optional(),
		defaults: persistedExecApprovalPolicySchema.optional(),
		agents: r.optional()
	});
}
const persistedExecApprovalsSchema = createExecApprovalsSchema(persistedExecAllowlistEntrySchema, false);
const legacyExecApprovalsSchema = createExecApprovalsSchema(legacyExecAllowlistEntrySchema, true);
/** Raw repair preserves invalid policy fields while retiring embedded credentials. */
function stripExecApprovalsRawSocketCredentials(e) {
	let t;
	try {
		t = JSON.parse(e);
	} catch {
		return e;
	}
	if (!isRecord(t) || !isRecord(t.socket) || !Object.hasOwn(t.socket, "path") && !Object.hasOwn(t.socket, "token")) return e;
	const { path: n, token: r, ...i } = t.socket;
	if (Object.keys(i).length) t.socket = i;
	else delete t.socket;
	return `${JSON.stringify(t, null, 2)}\n`;
}
//#endregion
//#region src/infra/client-credential-migration-data.ts
/** Canonical predecessors consume legacy inputs even when the retained JSON changes. */
function resolveClientCredentialLegacyImportClaims(e, t) {
	const n = {};
	for (const e of t.identities) if (e.identity_key === "primary" || e.identity_key === "node" || e.identity_key === "shareExtension") {
		n[`identity:${e.identity_key}`] = { sha256: null };
		if (t.authTablePresent) n[`auth:${e.identity_key}`] = { sha256: null };
	}
	if (!t.nativeBootstrap && tableExists(e, "migration_sources") && e.prepare("SELECT 1 FROM migration_sources WHERE migration_kind = 'legacy-device-identity-json' LIMIT 1").get()) n["identity:primary"] = { sha256: null };
	return n;
}
function sourceRows(e, t) {
	const n = getNodeSqliteKysely(e);
	const r = {
		identities: t && !tableExists(e, "device_identities") ? [] : executeSqliteQuerySync(e, n.selectFrom("device_identities").selectAll()).rows,
		tokens: t && !tableExists(e, "device_auth_tokens") ? [] : executeSqliteQuerySync(e, n.selectFrom("device_auth_tokens").selectAll()).rows,
		origins: t && !tableExists(e, "gateway_origin_device_tokens") ? [] : executeSqliteQuerySync(e, n.selectFrom("gateway_origin_device_tokens").selectAll()).rows,
		approvals: t && !tableExists(e, "exec_approvals_config") ? [] : executeSqliteQuerySync(e, n.selectFrom("exec_approvals_config").selectAll()).rows
	};
	const compare = (e, t) => Buffer.compare(Buffer.from(e), Buffer.from(t));
	r.identities.sort((e, t) => compare(e.identity_key, t.identity_key));
	r.tokens.sort((e, t) => compare(e.device_id, t.device_id) || compare(e.role, t.role));
	r.origins.sort((e, t) => compare(e.gateway_scope, t.gateway_scope) || compare(e.device_id, t.device_id) || compare(e.role, t.role));
	r.approvals.sort((e, t) => compare(e.config_key, t.config_key));
	return r;
}
function validateSource(e, t = "require-valid") {
	if (t === "require-valid") for (const t of e.identities) {
		validateStoredDeviceIdentity({
			deviceId: t.device_id,
			publicKeyPem: t.public_key_pem,
			privateKeyPem: t.private_key_pem,
			createdAtMs: t.created_at_ms
		}, t.identity_key);
		if (!Number.isSafeInteger(t.updated_at_ms) || t.updated_at_ms < 0) throw new Error("Client credential migration found an invalid identity timestamp.");
	}
	for (const t of [...e.tokens, ...e.origins]) {
		let e;
		try {
			e = JSON.parse(t.scopes_json);
		} catch {
			throw new Error("Client credential migration found invalid token scopes.");
		}
		if (!Array.isArray(e) || !e.every((e) => typeof e === "string") || !Number.isSafeInteger(t.updated_at_ms) || t.updated_at_ms < 0) throw new Error("Client credential migration found an invalid token record.");
	}
	if (e.approvals.some((e) => e.config_key !== "current") || e.approvals.length > 1) throw new Error("Client credential migration found a noncanonical approval singleton.");
}
function hashClientCredentialRows(e, t) {
	return createHash("sha256").update(stableStringify(t ? {
		authTablePresent: t.authTablePresent,
		identities: e.identities,
		tokens: e.tokens
	} : e)).digest("hex");
}
function extractSocket(e) {
	if (!e) return {
		socket: void 0,
		policy: void 0
	};
	const invalid = () => Object.assign(/* @__PURE__ */ new Error("Client credential migration found invalid socket credentials or projections."), { code: "CLIENT_CREDENTIAL_SOCKET_INVALID" });
	let t;
	try {
		t = JSON.parse(e.raw_json);
	} catch {
		throw new Error("Client credential migration found invalid approval JSON.");
	}
	const n = isRecord(t) ? t.socket : void 0;
	if (n !== void 0 && !isRecord(n)) throw invalid();
	const r = isRecord(n) ? n.path : void 0;
	const i = isRecord(n) ? n.token : void 0;
	if (r !== void 0 && typeof r !== "string" || i !== void 0 && typeof i !== "string") throw invalid();
	if (r === void 0 && i === void 0) return {
		socket: void 0,
		policy: e.raw_json
	};
	return {
		socket: {
			socket_key: "current",
			socket_path: r ?? null,
			socket_token: i ?? null,
			updated_at_ms: e.updated_at_ms
		},
		policy: stripExecApprovalsRawSocketCredentials(e.raw_json)
	};
}
//#endregion
//#region src/infra/client-credential-receipt.ts
const CLIENT_CREDENTIAL_LEGACY_KEYS = [
	"identity:primary",
	"identity:node",
	"identity:shareExtension",
	"auth:primary",
	"auth:node",
	"auth:shareExtension"
];
/** File replacement fences a completed orphan without opening the selected database. */
function readClientCredentialFileIdentity(e) {
	const t = fsSync.statSync(e, {
		bigint: true,
		throwIfNoEntry: false
	});
	if (!t) {
		if (SQLITE_SIDECAR_SUFFIXES.some((t) => fsSync.existsSync(`${e}${t}`))) throw new Error("Client credential source is unavailable; restore the matching main database before using this client.");
		return null;
	}
	if (!t.isFile()) throw new Error("Client credential source is not a regular file.");
	return {
		path: fsSync.realpathSync.native(e),
		dev: String(t.dev),
		ino: String(t.ino)
	};
}
function emptyClientCredentialReceipt(e = null) {
	return {
		format: 1,
		source: null,
		sharedFile: e,
		legacyImports: {}
	};
}
function digest(e) {
	return typeof e === "string" && /^[a-f0-9]{64}$/u.test(e);
}
/** The private receipt is shared with Swift; reject unsupported formats rather than discarding claims. */
function parseClientCredentialReceipt(e, t) {
	const invalid = () => /* @__PURE__ */ new Error("Client credential migration receipt is invalid; run openclaw doctor --fix.");
	let n;
	try {
		n = JSON.parse(e);
	} catch {
		throw invalid();
	}
	if (!isRecord(n) || n.format !== 1 || !isRecord(n.legacyImports)) throw invalid();
	let r = null;
	if (n.source !== null) {
		const e = n.source;
		if (!isRecord(e) || e.kind !== "canonical" && e.kind !== "independent" || e.engine !== "sqlite" && e.engine !== "postgres" && e.engine !== "native-v0" || typeof e.identity !== "string" || e.identity.length === 0 || typeof e.generation !== "string" || e.generation.length === 0 || !digest(e.sha256) || e.destinationVersion !== 1) throw invalid();
		r = {
			kind: e.kind,
			engine: e.engine,
			identity: e.identity,
			generation: e.generation,
			sha256: e.sha256,
			destinationVersion: e.destinationVersion
		};
	}
	let i = null;
	if (n.sharedFile !== null) {
		const e = n.sharedFile;
		if (!isRecord(e) || typeof e.path !== "string" || typeof e.dev !== "string" || !/^\d+$/u.test(e.dev) || typeof e.ino !== "string" || !/^\d+$/u.test(e.ino)) throw invalid();
		i = {
			path: e.path,
			dev: e.dev,
			ino: e.ino
		};
	}
	if (r?.kind === "independent" && (r.engine !== "native-v0" || !i)) throw invalid();
	const a = {};
	for (const [e, t] of Object.entries(n.legacyImports)) {
		const n = CLIENT_CREDENTIAL_LEGACY_KEYS.find((t) => t === e);
		if (!n || !isRecord(t) || t.sha256 !== null && !digest(t.sha256)) throw invalid();
		a[n] = { sha256: t.sha256 };
	}
	return rebaseCanonicalReceipt({
		format: 1,
		source: r,
		sharedFile: i,
		legacyImports: a
	}, t, false);
}
function rebaseCanonicalReceipt(e, t, n) {
	const r = e.sharedFile;
	if (!r || e.source?.kind === "independent") return e;
	const i = !path.isAbsolute(r.path);
	if (i && (!t || !r.path.startsWith("./") || r.path.slice(2).split("/").some((e) => !e || e === "." || e === ".." || e.includes("\\")))) throw new Error("Client credential receipt has an invalid relative shared binding.");
	if (!t) return e;
	const a = resolvePathViaExistingAncestorSync$1(t);
	const o = path.resolve(a, r.path);
	const s = path.relative(a, o);
	const c = s && !path.isAbsolute(s) && s !== ".." && !s.startsWith(`..${path.sep}`);
	const l = n && c ? `./${s.split(path.sep).join("/")}` : o;
	let u = e.source;
	if (u?.engine === "sqlite") {
		const e = `${r.path}:`;
		if (u.identity.startsWith(e)) u = {
			...u,
			identity: `${l}:${u.identity.slice(e.length)}`
		};
		else if (i) throw new Error("Client credential receipt has an invalid relative source identity.");
	}
	return {
		...e,
		source: u,
		sharedFile: {
			...r,
			path: l
		}
	};
}
function serializeClientCredentialReceipt(e, t) {
	return JSON.stringify(rebaseCanonicalReceipt(e, t, true));
}
//#endregion
//#region src/infra/client-credential-native-bootstrap.ts
/** Read-only classification for the native credential bootstrap that predates engine selection. */
function isNativeClientCredentialBootstrap(e) {
	admitSqliteSchema(e);
	const t = getAdmittedSqliteSchemaFacts(e);
	if (t.userVersion !== 0) return false;
	const n = [
		...[...t.tables].map((e) => ({
			type: "table",
			name: e
		})),
		...[...t.indexes].map((e) => ({
			type: "index",
			name: e
		})),
		...[...t.views].map((e) => ({
			type: "view",
			name: e
		})),
		...[...t.triggers.keys()].map((e) => ({
			type: "trigger",
			name: e
		}))
	].filter(({ name: e }) => !e.startsWith("sqlite_"));
	const r = /* @__PURE__ */ new Set([
		"table:device_identities",
		"index:idx_device_identities_device",
		"table:device_auth_tokens",
		"index:idx_device_auth_tokens_updated",
		"table:macos_port_guardian_records",
		"index:idx_macos_port_guardian_records_port"
	]);
	if (!n.length || n.some((e) => !r.has(`${e.type}:${e.name}`))) return false;
	if (t.tables.has("macos_port_guardian_records") || t.indexes.has("idx_macos_port_guardian_records_port")) {
		const t = readGeneratedSqliteCatalog(OPENCLAW_STATE_SCHEMA_SQL)?.tables.filter(({ name: e }) => e === "macos_port_guardian_records");
		if (!t?.length) throw new Error("Native PortGuardian companion has no canonical schema catalog.");
		assertSqliteSchemaContains(e, "Native PortGuardian companion", {
			tables: t,
			views: []
		});
	}
	assertSqliteSchemaContains(e, "Native client credential bootstrap", CLIENT_CREDENTIAL_SCHEMA_SQL, { allowedMissingTables: [
		"device_identities",
		"device_auth_tokens",
		"gateway_origin_device_tokens",
		"native_exec_socket_credentials",
		"client_credential_migration"
	] });
	return true;
}
/** Independent native sources are read-only; journal bytes and timestamps are not content identity. */
function readIndependentClientCredentialSource(e) {
	try {
		var t = _usingCtx();
		const n = readClientCredentialFileIdentity(e);
		if (!n) throw new Error("Independent client credential source is missing; restore its matching backup.");
		const r = fsSync.openSync(e, fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW);
		try {
			const e = Buffer.alloc(100);
			if (fsSync.readSync(r, e, 0, e.length, 0) !== e.length || e.subarray(0, 16).toString("binary") !== "SQLite format 3\0" || e[18] !== 1 || e[19] !== 1) throw new Error("Independent client credentials require DELETE journal mode; stop the old client and restore a compatible source.");
		} finally {
			fsSync.closeSync(r);
		}
		const i = t.u(openNodeSqliteDatabase(e, { readOnly: true }));
		if (!isNativeClientCredentialBootstrap(i)) throw new Error("Independent client credential source is not a native credential-only database.");
		i.exec("BEGIN");
		try {
			const e = getAdmittedSqliteSchemaFacts(i).tables.has("device_auth_tokens");
			const t = sourceRows(i, true);
			validateSource(t);
			const r = hashClientCredentialRows(t, { authTablePresent: e });
			return {
				file: n,
				identity: `${n.dev}:${n.ino}`,
				sha256: r,
				rows: t,
				authTablePresent: e
			};
		} finally {
			i.exec("ROLLBACK");
		}
	} catch (e) {
		t.e = e;
	} finally {
		t.d();
	}
}
//#endregion
//#region src/infra/client-credential-readiness.ts
var ClientCredentialMigrationRequiredError = class extends StartupMaintenanceRequiredError {
	constructor(e = "Client credential migration is incomplete or stale; run openclaw doctor --fix before using this client.") {
		super("state-migrations", e);
		this.name = "ClientCredentialMigrationRequiredError";
	}
};
function notReady() {
	return new ClientCredentialMigrationRequiredError();
}
function assertSupportedVersion(e) {
	if (e !== 1) throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`);
}
/** The receipt is a cross-process migration-phase guard, including in-place copied → complete transitions. */
function readClientCredentialAdmission(e) {
	let t;
	try {
		t = e.prepare(`
    SELECT header.user_version, receipt.source_store, receipt.phase
    FROM pragma_user_version AS header
    LEFT JOIN client_credential_migration AS receipt ON receipt.version = 1
  `).get();
	} catch (t) {
		assertSupportedVersion(readSqliteUserVersion(e));
		throw t;
	}
	if (!t || typeof t.user_version !== "number") throw notReady();
	assertSupportedVersion(t.user_version);
	const n = e.location();
	return { stored: t.source_store === null ? null : {
		phase: t.phase === "complete" ? "complete" : "copied",
		receipt: parseClientCredentialReceipt(String(t.source_store), n ? path.dirname(path.dirname(n)) : void 0)
	} };
}
function readClientCredentialReceipt(e, t) {
	const n = getNodeSqliteKysely(e);
	const r = executeSqliteQueryTakeFirstSync(e, n.selectFrom("client_credential_migration").selectAll().where("version", "=", 1));
	const i = e.location();
	return r ? {
		phase: r.phase,
		receipt: parseClientCredentialReceipt(r.source_store, t ?? (i ? path.dirname(path.dirname(i)) : void 0))
	} : null;
}
function writeClientCredentialReceipt(e, t, n, r = Date.now()) {
	const i = getNodeSqliteKysely(e);
	const a = e.location();
	const o = {
		version: 1,
		source_store: serializeClientCredentialReceipt(t, a ? path.dirname(path.dirname(a)) : void 0),
		phase: n,
		updated_at_ms: r
	};
	executeSqliteQuerySync(e, i.insertInto("client_credential_migration").values(o).onConflict((e) => e.column("version").doUpdateSet(o)));
}
function assertClientCredentialLegacyReady(e, t, n = false, r) {
	let i = false;
	const a = e ? getNodeSqliteKysely(e) : void 0;
	const o = r ?? (e ? readClientCredentialReceipt(e)?.receipt : void 0);
	const s = {
		primary: "device",
		node: "node-device",
		shareExtension: "share-device"
	};
	for (const r of [
		"primary",
		"node",
		"shareExtension"
	]) for (const c of ["identity", "auth"]) {
		if (o?.legacyImports[`${c}:${r}`]) continue;
		const l = `${s[r]}${c === "auth" ? "-auth" : ""}.json`;
		const u = path.join(resolveStateDir(t), "identity", l);
		if ([
			u,
			`${u}.doctor-importing`,
			`${u}.native-importing`
		].some((e) => fsSync.existsSync(e))) {
			if (c === "identity" && e && a && executeSqliteQueryTakeFirstSync(e, a.selectFrom("device_identities").select("identity_key").where("identity_key", "=", r))) continue;
			throw new ClientCredentialMigrationRequiredError("Legacy client credentials require migration; run openclaw doctor --fix before using this client.");
		}
		if (n && o) {
			o.legacyImports[`${c}:${r}`] = { sha256: null };
			i = true;
		}
	}
	if (i && o && e) writeClientCredentialReceipt(e, o, "complete");
}
function assertMissingClientCredentialStoreReady(e) {
	assertClientCredentialLegacyReady(null, e);
	if (readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(e))) throw notReady();
}
function prepareClientCredentialReceipt(e, t, n, r = false, i = readClientCredentialReceipt(e)) {
	let a = i;
	const o = readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(t));
	if (!a && n && !o) {
		assertClientCredentialLegacyReady(null, t);
		const n = emptyClientCredentialReceipt();
		for (const e of CLIENT_CREDENTIAL_LEGACY_KEYS) n.legacyImports[e] = { sha256: null };
		writeClientCredentialReceipt(e, n, "complete");
		a = {
			phase: "complete",
			receipt: n
		};
	}
	if (!a || a.phase !== "complete") throw notReady();
	if (a.receipt.source?.kind === "independent") {
		const t = a.receipt.sharedFile;
		const n = readIndependentClientCredentialSource(t.path);
		if (n.identity !== a.receipt.source.identity || n.file.path !== t.path || n.file.dev !== t.dev || n.file.ino !== t.ino || n.sha256 !== a.receipt.source.sha256) {
			if (r) throw new Error("Independent client credentials changed; open the client or run openclaw doctor --fix before read-only inspection.");
			const t = getNodeSqliteKysely(e);
			executeSqliteQuerySync(e, t.deleteFrom("device_auth_tokens"));
			executeSqliteQuerySync(e, t.deleteFrom("device_identities"));
			executeSqliteQuerySync(e, t.deleteFrom("gateway_origin_device_tokens"));
			for (const r of chunkItems(n.rows.identities, 500)) executeSqliteQuerySync(e, t.insertInto("device_identities").values(r));
			for (const r of chunkItems(n.rows.tokens, 500)) executeSqliteQuerySync(e, t.insertInto("device_auth_tokens").values(r));
			a.receipt.source = {
				kind: "independent",
				engine: "native-v0",
				identity: n.identity,
				generation: "0",
				sha256: n.sha256,
				destinationVersion: 1
			};
			a.receipt.sharedFile = n.file;
			writeClientCredentialReceipt(e, a.receipt, "complete");
		}
	} else {
		const e = a.receipt.sharedFile;
		if (e === null ? o !== null : o === null || e.path !== o.path || e.dev !== o.dev || e.ino !== o.ino) throw notReady();
	}
	return a;
}
/** Admit once under the local owner's existing transaction and native custody. */
function admitClientCredentialStore(e, t, n) {
	const r = prepareClientCredentialReceipt(e, t, n.initialize, n.readOnly, n.stored);
	assertClientCredentialLegacyReady(e, t, !n.readOnly, r.receipt);
	return r.receipt;
}
//#endregion
//#region src/infra/client-credential-operations.ts
function encodeClientNativeTokenRole(e, t) {
	return `v2.${Buffer.from(t).toString("base64url")}.${Buffer.from(e.trim()).toString("base64url")}`;
}
function decodeRole(e) {
	const t = e.split(".");
	if (t.length === 3 && t[0] === "v2" && t[1] !== void 0 && t[2] !== void 0) try {
		const decode = (e) => {
			if (!/^[A-Za-z0-9_-]*$/u.test(e) || e.length % 4 === 1) throw new Error("Invalid component");
			return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(e, "base64url"));
		};
		return {
			gateway: decode(t[1]),
			role: decode(t[2])
		};
	} catch {}
	return {
		role: e,
		gateway: null
	};
}
function clearClientNativeTokens(e, t, n) {
	const r = getNodeSqliteKysely(e);
	if (n.kind === "all") return Number(executeSqliteQuerySync(e, r.deleteFrom("device_auth_tokens").where("device_id", "=", t)).numAffectedRows);
	const i = executeSqliteQuerySync(e, r.selectFrom("device_auth_tokens").select("role").where("device_id", "=", t)).rows.filter(({ role: e }) => {
		const t = decodeRole(e);
		if (n.kind === "role") return t.role === n.role.trim();
		if (n.kind === "gateway") return t.gateway === n.gateway;
		return t.gateway === null;
	}).map(({ role: e }) => e);
	if (i.length === 0) return 0;
	executeSqliteQuerySync(e, r.deleteFrom("device_auth_tokens").where("device_id", "=", t).where("role", "in", i));
	return i.length;
}
/** A scoped winner is retained; the ambiguous legacy token is always consumed. */
function claimClientNativeToken(e, t, n, r) {
	const i = getNodeSqliteKysely(e);
	const a = n.trim();
	const o = executeSqliteQueryTakeFirstSync(e, i.selectFrom("device_auth_tokens").selectAll().where("device_id", "=", t).where("role", "=", a));
	if (!o) return false;
	executeSqliteQuerySync(e, i.insertInto("device_auth_tokens").values({
		...o,
		role: encodeClientNativeTokenRole(n, r)
	}).onConflict((e) => e.columns(["device_id", "role"]).doNothing()));
	executeSqliteQuerySync(e, i.deleteFrom("device_auth_tokens").where("device_id", "=", t).where("role", "=", a));
	return true;
}
function performClientCredentialOperation(e, t, n) {
	const r = getNodeSqliteKysely(e);
	switch (t.kind) {
		case "identity.read":
		case "identity.create":
		case "identity.repair": {
			const n = t.kind === "identity.read" ? t.identity_key : t.identity.identity_key;
			const i = executeSqliteQueryTakeFirstSync(e, r.selectFrom("device_identities").selectAll().where("identity_key", "=", n));
			if (t.kind === "identity.repair") {
				if (i) try {
					storedDeviceIdentityFromRow(i, n);
					return {
						kind: "identityRepair",
						identity: i,
						repaired: false,
						rotated: false
					};
				} catch {}
				const a = i ? salvageStoredIdentityRow(i, n, t.identity.updated_at_ms) : null;
				const o = a ? storedDeviceIdentityToRow(n, a, t.identity.updated_at_ms) : t.identity;
				storedDeviceIdentityFromRow(o, n);
				executeSqliteQuerySync(e, r.insertInto("device_identities").values(o).onConflict((e) => e.column("identity_key").doUpdateSet(o)));
				return {
					kind: "identityRepair",
					identity: o,
					repaired: true,
					rotated: a === null
				};
			}
			if (i) {
				storedDeviceIdentityFromRow(i, n);
				return {
					kind: "identity",
					identity: i
				};
			}
			if (t.kind === "identity.create") {
				storedDeviceIdentityFromRow(t.identity, n);
				executeSqliteQuerySync(e, r.insertInto("device_identities").values(t.identity));
				return {
					kind: "identity",
					identity: t.identity
				};
			}
			return {
				kind: "identity",
				identity: null
			};
		}
		case "native.tokens.clear": return {
			kind: "cleared",
			count: clearClientNativeTokens(e, t.device_id, t.selector)
		};
		case "native.token.claim": return {
			kind: "changed",
			changed: claimClientNativeToken(e, t.device_id, t.role, t.gateway)
		};
		case "token.list": {
			const n = t.gateway_scope === void 0 ? "device_auth_tokens" : "gateway_origin_device_tokens";
			let i = r.selectFrom(n).selectAll().where("device_id", "=", t.device_id);
			if (t.gateway_scope !== void 0) i = i.where("gateway_scope", "=", t.gateway_scope);
			if (t.afterRole !== void 0) i = i.where("role", ">", t.afterRole);
			const a = Math.max(1, Math.min(32, Math.trunc(t.limit ?? 32)));
			const o = executeSqliteQuerySync(e, i.orderBy("role").limit(a + 1)).rows;
			const s = o.slice(0, a).map(({ device_id: e, role: t, token: n, scopes_json: r, updated_at_ms: i }) => ({
				device_id: e,
				role: t,
				token: n,
				scopes_json: r,
				updated_at_ms: i
			}));
			return {
				kind: "tokens",
				tokens: s,
				nextRole: o.length > a ? s.at(-1)?.role ?? null : null
			};
		}
		case "token.read":
		case "token.replace":
		case "token.remove": {
			const { key: n } = t;
			const i = n.gateway_scope === void 0 ? "device_auth_tokens" : "gateway_origin_device_tokens";
			const a = expressionBuilder();
			const o = a.and([
				a("device_id", "=", n.device_id),
				a("role", "=", n.role),
				...n.gateway_scope === void 0 ? [] : [a("gateway_scope", "=", n.gateway_scope)]
			]);
			const s = r.selectFrom(i).selectAll().where(o);
			if (t.kind === "token.read") {
				const t = executeSqliteQueryTakeFirstSync(e, s);
				return {
					kind: "token",
					token: t ? {
						device_id: t.device_id,
						role: t.role,
						token: t.token,
						scopes_json: t.scopes_json,
						updated_at_ms: t.updated_at_ms
					} : null
				};
			}
			const c = executeSqliteQueryTakeFirstSync(e, s);
			const l = t.expectedToken === void 0 ? t.kind !== "token.remove" || t.observedToken === void 0 : (c?.token ?? null) === t.expectedToken;
			const u = t.kind === "token.remove" && t.observedToken !== void 0 && c?.token === t.observedToken && (t.expectedToken === void 0 || typeof t.expectedToken === "string" && t.observedToken.trim() === t.expectedToken);
			if (!(l || u)) return {
				kind: "changed",
				changed: false
			};
			if (t.kind === "token.remove") {
				if (!c) return {
					kind: "changed",
					changed: false
				};
				executeSqliteQuerySync(e, r.deleteFrom(i).where(o));
			} else {
				const i = {
					...t.token,
					device_id: n.device_id,
					role: n.role
				};
				if (n.gateway_scope === void 0) executeSqliteQuerySync(e, r.insertInto("device_auth_tokens").values(i).onConflict((e) => e.columns(["device_id", "role"]).doUpdateSet(i)));
				else executeSqliteQuerySync(e, r.insertInto("gateway_origin_device_tokens").values({
					...i,
					gateway_scope: n.gateway_scope
				}).onConflict((e) => e.columns([
					"gateway_scope",
					"device_id",
					"role"
				]).doUpdateSet(i)));
			}
			return {
				kind: "changed",
				changed: true
			};
		}
		case "socket.read":
		case "socket.ensure": {
			const i = executeSqliteQueryTakeFirstSync(e, r.selectFrom("native_exec_socket_credentials").selectAll().where("socket_key", "=", "current")) ?? null;
			if (t.kind === "socket.read") return {
				kind: "socket",
				socket: i
			};
			const a = t.requested?.path?.trim();
			const o = i?.socket_path;
			const s = !a && o === path.join(n, "exec-approvals.sock") && o !== t.fallback.socket_path;
			const c = {
				socket_key: "current",
				socket_path: a || (s ? t.fallback.socket_path : o) || t.fallback.socket_path,
				socket_token: t.requested?.token?.trim() || i?.socket_token || t.fallback.socket_token,
				updated_at_ms: t.fallback.updated_at_ms
			};
			if (i && i.socket_path === c.socket_path && i.socket_token === c.socket_token) return {
				kind: "socket",
				socket: i
			};
			executeSqliteQuerySync(e, r.insertInto("native_exec_socket_credentials").values(c).onConflict((e) => e.column("socket_key").doUpdateSet(c)));
			return {
				kind: "socket",
				socket: c
			};
		}
		default: throw new Error("Unsupported client credential operation.");
	}
}
//#endregion
//#region src/infra/private-store-file.ts
function createPrivateIfMissing(e) {
	try {
		e();
		return true;
	} catch (e) {
		if (!(e instanceof FsSafeError && e.code === "already-exists")) throw e;
		return false;
	}
}
function createPrivateStoreDirectorySync(e) {
	const t = path.dirname(e);
	const n = process.platform === "linux" ? fsSync.lstatSync(t, { bigint: true }) : void 0;
	try {
		createDirectorySync(e, { private: true });
	} catch (r) {
		const i = r instanceof FsSafeError ? r.details?.publication : void 0;
		if (process.platform !== "linux" || typeof process.getuid !== "function" || !n || !(r instanceof FsSafeError && r.code === "helper-failed") || !(r.cause instanceof FsSafeError && r.cause.code === "insecure-permissions") || r.details?.path !== e || !i || typeof i !== "object" || !("status" in i && i.status === "published")) throw r;
		let a;
		try {
			assertDirectoryIdentitySync(t, n);
			a = fsSync.openSync(e, fsSync.constants.O_RDONLY | fsSync.constants.O_DIRECTORY | fsSync.constants.O_NOFOLLOW);
			const i = fsSync.fstatSync(a, { bigint: true });
			const o = fsSync.lstatSync(e, { bigint: true });
			if (!i.isDirectory() || i.uid !== BigInt(process.getuid()) || (i.mode & 4095n) !== 1472n || i.dev !== o.dev || i.ino !== o.ino) throw r;
			assertDirectoryIdentitySync(t, n);
			fsSync.fchmodSync(a, 448);
			const s = fsSync.fstatSync(a, { bigint: true });
			const c = fsSync.lstatSync(e, { bigint: true });
			if ((s.mode & 4095n) !== 448n || s.dev !== c.dev || s.ino !== c.ino) throw r;
			assertDirectoryIdentitySync(t, n);
		} catch {
			throw r;
		} finally {
			if (a !== void 0) fsSync.closeSync(a);
		}
	}
}
/** The caller admits the existing parent before preparing this store's private file. */
function preparePrivateStoreFileSync(e, t) {
	const n = path.dirname(e);
	if (!t) fsSync.mkdirSync(path.dirname(n), {
		recursive: true,
		mode: 448
	});
	const r = path.join(fsSync.realpathSync.native(path.dirname(n)), path.basename(n));
	if (!t) createPrivateIfMissing(() => createPrivateStoreDirectorySync(r));
	applyPrivateModeSync(n, 448);
	if (!fsSync.existsSync(e)) return createPrivateIfMissing(() => createFileSync(path.join(r, path.basename(e)), { private: true }).close());
	return false;
}
//#endregion
//#region src/infra/client-credential-store.ts
const retainedPaths = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialCustody"), () => /* @__PURE__ */ new Set());
const admittedFiles = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialAdmittedFiles"), () => /* @__PURE__ */ new Map(), (e) => e.clear());
var ClientCredentialBusyError = class extends Error {
	constructor() {
		super("Client credential owner is busy.");
		this.name = "ClientCredentialBusyError";
	}
};
const schemaAdmission = {
	name: "client.credentials.schema-v1",
	schemaDependent: true,
	read: (e) => e === true ? true : void 0
};
function assertPrivateAcl(e) {
	if (process.platform === "darwin" && inspectDarwinAcl(e).kind !== "none") throw new Error("Client credentials require a private directory and file without ACL entries.");
}
/** One admitted handle retains SQLite exclusion across individual commits. */
function openClientCredentialCustody(e, t = {}, n) {
	const r = (t.createIfMissing ?? false) && !t.readOnly;
	const i = resolveClientCredentialStorePath(e);
	const a = path.dirname(i);
	const o = resolveDatabasePathKey(i);
	if (retainedPaths.has(o)) throw new ClientCredentialBusyError();
	if (t.migration) admittedFiles.delete(o);
	if (!t.migration && !fsSync.existsSync(i)) assertMissingClientCredentialStoreReady(e);
	const s = fsSync.lstatSync(a, { throwIfNoEntry: false });
	if (s && (!s.isDirectory() || process.getuid && s.uid !== process.getuid() || process.platform !== "win32" && (s.mode & 63) !== 0)) throw new Error("Client credential directory is unsafe.");
	if (!s && !r) return;
	if (s) assertPrivateAcl(a);
	let c = false;
	if (r) c = preparePrivateStoreFileSync(i, Boolean(s));
	const l = openRootFileSync({
		absolutePath: i,
		rootPath: a,
		boundaryLabel: "client credential store",
		rejectSymlinks: true
	});
	if (!l.ok) {
		if (hasErrnoCode(l.error, "ENOENT") && !r) return;
		throw new Error("Client credential store cannot be safely opened.", { cause: l.error });
	}
	retainedPaths.add(o);
	let u;
	let d = false;
	let physicalClose;
	try {
		const a = fsSync.fstatSync(l.fd, { bigint: true });
		if (process.getuid && a.uid !== BigInt(process.getuid()) || process.platform !== "win32" && (a.mode & 63n) !== 0n) throw new Error("Client credential store owner is unsafe.");
		const s = `${a.dev}:${a.ino}:${readDatabaseIdentityBirthtime(a)}`;
		assertPrivateAcl(i);
		u = openNodeSqliteDatabase(resolveExistingSqliteFileUri(i), { timeout: t.timeoutMs ?? 5e3 });
		const f = u;
		if (u.prepare("PRAGMA journal_mode").get()?.journal_mode !== "delete") throw new Error("Client credentials require DELETE journal mode for exclusive owner custody.");
		physicalClose = () => {
			if (!d) {
				d = true;
				try {
					f.close();
				} finally {
					fsSync.closeSync(l.fd);
					retainedPaths.delete(o);
				}
			}
		};
		const transaction = (e) => {
			if (d) throw new Error("Client credential custody is closed.");
			if (t.readOnly) return runSqliteImmediateTransactionSync(f, e);
			return runUpdateSqliteMigration(f, i, () => runSqliteImmediateTransactionSync(f, e), { retainExclusive: true });
		};
		const p = admittedFiles.get(o);
		let m = false;
		let h = false;
		transaction(() => {
			f.exec("PRAGMA locking_mode=EXCLUSIVE");
			if (t.migration || p?.identity !== s || p.version !== 1) {
				const e = readSqliteUserVersion(f);
				if (e === 0 && !f.prepare("SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").get()) {
					if (!r) throw new Error("Client credential store is empty; run openclaw doctor --fix.");
					f.exec(CLIENT_CREDENTIAL_SCHEMA_SQL);
					m = true;
					writeSqliteUserVersion(f, 1);
				} else {
					if (e !== 1) throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`);
					assertSqliteSchemaContains(f, "Client credentials", CLIENT_CREDENTIAL_SCHEMA_SQL);
					assertSqliteIntegrity(f, "Client credentials");
				}
				publishSqliteDatabaseAdmission(f, schemaAdmission, true);
			}
			if (!t.migration) {
				const n = readClientCredentialAdmission(f);
				const r = admitClientCredentialStore(f, e, {
					initialize: m,
					readOnly: t.readOnly ?? false,
					stored: n.stored
				});
				h = r.sharedFile !== null && r.source === null;
			}
			if (!m) n?.(f);
		});
		if (m && n) transaction(() => n(f));
		if (!t.migration) admittedFiles.set(o, {
			identity: s,
			version: 1
		});
		return {
			database: f,
			path: i,
			created: c,
			needsMetadataUpgrade: h,
			transaction,
			run(n, r) {
				if (d) throw new Error("Client credential custody is closed.");
				if (t.readOnly && isClientCredentialMutation(n)) throw new Error("Client credential custody is read-only.");
				const run = () => {
					const t = performClientCredentialOperation(f, n, resolveStateDir(e));
					r?.();
					return t;
				};
				return transaction(run);
			},
			close: physicalClose,
			[Symbol.dispose]: physicalClose
		};
	} catch (e) {
		admittedFiles.delete(o);
		if (physicalClose) physicalClose();
		else {
			u?.close();
			fsSync.closeSync(l.fd);
			retainedPaths.delete(o);
		}
		throw e;
	}
}
function isClientCredentialMutation(e) {
	return ![
		"identity.read",
		"token.read",
		"token.list",
		"socket.read"
	].includes(e.kind);
}
//#endregion
//#region src/infra/client-credential-migration.ts
function postgresBootstrapProvenance(e) {
	const t = isPostgresSqlConnection(e);
	const n = readEngineAnchor(t ? e.anchor : e, "identity", t);
	if (!n) return;
	const r = n[0];
	if (n.length !== 1 || !r || r.engine !== "postgres" || typeof r.store_id !== "string" || !r.store_id.trim() || typeof r.schema !== "string" || !r.schema.trim()) throw new Error("Invalid PostgreSQL anchor identity during client credential bootstrap.");
	return {
		kind: "canonical",
		engine: "postgres",
		identity: r.store_id,
		generation: `bootstrap:${r.store_id}`,
		sha256: hashClientCredentialRows({
			identities: [],
			tokens: [],
			origins: [],
			approvals: []
		}),
		destinationVersion: 1
	};
}
function readClientCredentialBootstrapSource(e, t) {
	const n = postgresBootstrapProvenance(e);
	if (n) return n;
	const r = e.prepare("SELECT created_at FROM schema_meta WHERE meta_key = 'primary'").get();
	if (!r) throw new Error("Shared credential source identity was not published.");
	return {
		kind: "canonical",
		engine: "sqlite",
		identity: `${t}:${String(r.created_at)}`,
		generation: `bootstrap:${String(r.created_at)}`,
		sha256: hashClientCredentialRows({
			identities: [],
			tokens: [],
			origins: [],
			approvals: []
		}),
		destinationVersion: 1
	};
}
function isPristineSqliteBootstrap(e, t) {
	const n = t?.receipt.source;
	const r = t?.receipt.sharedFile;
	if (t?.phase !== "complete" || n?.kind !== "canonical" || n.engine !== "sqlite" || !r || !n.generation.startsWith("bootstrap:") || n.generation === "bootstrap:" || n.identity !== `${r.path}:${n.generation.slice(10)}` || n.sha256 !== hashClientCredentialRows({
		identities: [],
		tokens: [],
		origins: [],
		approvals: []
	}) || Object.keys(t.receipt.legacyImports).length !== 0) return false;
	const i = getNodeSqliteKysely(e);
	return [
		"device_identities",
		"device_auth_tokens",
		"gateway_origin_device_tokens",
		"native_exec_socket_credentials"
	].every((t) => !executeSqliteQueryTakeFirstSync(e, i.selectFrom(t).selectAll().limit(1)));
}
/** Fresh shared bootstrap binds existing local-only credentials without replacing them. */
function bindFreshClientCredentialStore(e, t) {
	if (!e.isTransaction || !hasSqlitePostCommitScope(e)) throw new Error("Client credential bootstrap has no source commit lifecycle.");
	const n = resolveStateClientCredentialEnvironment(t);
	if (!n) return;
	const r = postgresBootstrapProvenance(e);
	const i = openClientCredentialCustody(n, {
		createIfMissing: true,
		migration: true
	});
	if (!i) throw new Error("Cannot acquire local credentials during shared bootstrap.");
	const close = () => i.close();
	try {
		const n = beginUpdateSqliteCompanion(i.database, i.path, i.created);
		const a = readClientCredentialReceipt(i.database);
		const o = getNodeSqliteKysely(i.database);
		const s = executeSqliteQueryTakeFirstSync(i.database, o.selectFrom("client_credential_migration").selectAll().where("version", "=", 1));
		const c = readClientCredentialFileIdentity(t.path);
		if (!c) throw new Error("Shared credential source is missing during bootstrap.");
		const l = a?.receipt.source;
		const u = a?.receipt.sharedFile;
		const d = u?.path === c.path && u.dev === c.dev && u.ino === c.ino;
		const f = r && l?.kind === r.kind && l.engine === r.engine && l.identity === r.identity && l.generation === r.generation && l.sha256 === r.sha256 && l.destinationVersion === r.destinationVersion && d;
		const p = !r && isPristineSqliteBootstrap(i.database, a);
		if (l && !f && !p || u && !d && !p) throw new Error("Existing client credentials belong to a previous shared database; run openclaw doctor --fix.");
		const m = {
			format: 1,
			source: p && !d ? null : a?.receipt.source ?? null,
			sharedFile: c,
			legacyImports: a?.receipt.legacyImports ?? {}
		};
		runSqliteImmediateTransactionSync(i.database, () => writeClientCredentialReceipt(i.database, m, "copied"));
		if (!stageSqliteTransactionState(e, {
			stage() {},
			commit() {
				try {
					m.source = readClientCredentialBootstrapSource(e, c.path);
					runSqliteImmediateTransactionSync(i.database, () => writeClientCredentialReceipt(i.database, m, "complete"));
					n?.complete();
				} finally {
					close();
				}
			},
			rollback() {
				try {
					runSqliteImmediateTransactionSync(i.database, () => {
						if (s) executeSqliteQuerySync(i.database, o.insertInto("client_credential_migration").values(s).onConflict((e) => e.column("version").doUpdateSet(s)));
						else executeSqliteQuerySync(i.database, o.deleteFrom("client_credential_migration").where("version", "=", 1));
					});
					n?.complete();
				} finally {
					close();
				}
			},
			invalidate: close
		})) throw new Error("Client credential bootstrap has no source commit lifecycle.");
	} catch (e) {
		close();
		throw e;
	}
}
/** Shared schema custody already owns the source transaction; this retains local custody until its outcome. */
function prepareClientCredentialMigration(e, t) {
	if (t.fromVersion >= 29 || isPostgresSqlConnection(e) && t.fromVersion !== 29 - 1) return;
	if (!e.isTransaction) throw new Error("Client credential migration requires the shared owner's transaction.");
	const n = t.fromVersion === 0;
	if (n && !CLIENT_CREDENTIAL_SOURCE_TABLES.some((t) => tableExists(e, t))) {
		bindFreshClientCredentialStore(e, t);
		return;
	}
	const r = resolveStateClientCredentialEnvironment(t);
	const i = getOpenClawDatabaseMaintenanceScope();
	const a = t.capture ?? getUpdateDoctorMigrationSource(t.path) ?? (isPostgresSqlConnection(e) ? void 0 : getDoctorMigrationBackup(e, {
		path: t.path,
		env: r ?? t.env,
		tables: [
			...CLIENT_CREDENTIAL_SOURCE_TABLES,
			"sqlite_stat1",
			"sqlite_stat4"
		]
	})?.capture);
	if (!i?.ownsSchemaMaintenance || !a || a.path !== t.path || !a.generation) throw new Error("Client credentials require backed-up migration custody; stop the app and run openclaw doctor --fix.");
	if (!r) throw new Error("Client credentials in an auxiliary shared database require explicit recovery; preserve the source database.");
	assertStateDatabaseAccessAllowed(t.path);
	i.assertAdmission();
	a.assertCurrent();
	const o = sourceRows(e, n || t.fromVersion < 29 - 1);
	const s = !n || tableExists(e, "device_auth_tokens");
	validateSource(o, n ? "require-valid" : "preserve-for-doctor");
	const c = extractSocket(o.approvals[0]);
	const l = readClientCredentialFileIdentity(t.path);
	if (!l) throw new Error("Client credential source disappeared before migration.");
	const u = tableExists(e, "schema_meta");
	const d = t.fromVersion === 1 && !u;
	const f = (n || d) && !u ? void 0 : e.prepare("SELECT created_at FROM schema_meta WHERE meta_key = 'primary'").get();
	const p = isPostgresSqlConnection(e) ? readEngineAnchor(e.anchor, "identity", true)?.[0] : void 0;
	const m = {
		format: 1,
		source: {
			kind: "canonical",
			engine: isPostgresSqlConnection(e) ? "postgres" : n ? "native-v0" : "sqlite",
			identity: p ? String(p.store_id) : `${l.path}:${String(f?.created_at ?? 0)}`,
			generation: a.generation,
			sha256: hashClientCredentialRows(o, n ? { authTablePresent: s } : void 0),
			destinationVersion: 1
		},
		sharedFile: l,
		legacyImports: resolveClientCredentialLegacyImportClaims(e, {
			identities: o.identities,
			nativeBootstrap: n,
			authTablePresent: s
		})
	};
	const h = openClientCredentialCustody(r, {
		createIfMissing: true,
		migration: true
	});
	if (!h) throw new Error("Client credential migration could not acquire local custody.");
	const close = () => h.close();
	try {
		const t = beginUpdateSqliteCompanion(h.database, h.path, h.created);
		runSqliteImmediateTransactionSync(h.database, () => {
			const e = h.database;
			const t = readClientCredentialReceipt(e);
			if (t) m.legacyImports = {
				...m.legacyImports,
				...t.receipt.legacyImports
			};
			if (t?.phase === "complete" && t.receipt.source?.kind === "independent" && n && t.receipt.source.identity === `${l.dev}:${l.ino}` && t.receipt.source.sha256 === m.source.sha256 && t.receipt.sharedFile?.path === l.path && t.receipt.sharedFile.dev === l.dev && t.receipt.sharedFile.ino === l.ino) {
				writeClientCredentialReceipt(e, m, "copied");
				return;
			}
			const r = getNodeSqliteKysely(e);
			for (const t of [
				"device_identities",
				"device_auth_tokens",
				"gateway_origin_device_tokens",
				"native_exec_socket_credentials",
				"client_credential_migration"
			]) executeSqliteQuerySync(e, r.deleteFrom(t));
			for (const t of chunkItems(o.identities, 500)) executeSqliteQuerySync(e, r.insertInto("device_identities").values(t));
			for (const t of chunkItems(o.tokens, 500)) executeSqliteQuerySync(e, r.insertInto("device_auth_tokens").values(t));
			for (const t of chunkItems(o.origins, 500)) executeSqliteQuerySync(e, r.insertInto("gateway_origin_device_tokens").values(t));
			if (c.socket) executeSqliteQuerySync(e, r.insertInto("native_exec_socket_credentials").values(c.socket));
			executeSqliteQuerySync(e, r.insertInto("client_credential_migration").values({
				version: 1,
				source_store: serializeClientCredentialReceipt(m, path.dirname(path.dirname(h.path))),
				phase: "copied",
				updated_at_ms: Date.now()
			}));
		});
		if (!stageSqliteTransactionState(e, {
			stage() {},
			prepareCommit() {
				if (!d) return;
				const t = e.prepare("SELECT created_at FROM schema_meta WHERE meta_key = 'primary'").get();
				if (!t || !m.source) throw new Error("Historical client credential source identity was not published.");
				m.source.identity = `${l.path}:${String(t.created_at)}`;
				runSqliteImmediateTransactionSync(h.database, () => writeClientCredentialReceipt(h.database, m, "copied"));
			},
			commit() {
				try {
					if (n && !isPostgresSqlConnection(e) && tableExists(e, "schema_meta")) {
						const t = e.prepare("SELECT created_at FROM schema_meta WHERE meta_key = 'primary'").get();
						if (m.source) {
							m.source.engine = "sqlite";
							m.source.identity = `${l.path}:${String(t?.created_at ?? 0)}`;
						}
					}
					runSqliteImmediateTransactionSync(h.database, () => writeClientCredentialReceipt(h.database, m, "complete"));
					t?.complete();
				} finally {
					close();
				}
			},
			rollback: close,
			invalidate: close
		})) throw new Error("Client credential migration has no source commit lifecycle.");
		i.assertAdmission();
		a.assertCurrent();
		if (o.approvals[0] && c.policy !== void 0) executeSqliteQuerySync(e, getNodeSqliteKysely(e).updateTable("exec_approvals_config").set({
			raw_json: c.policy,
			socket_path: null,
			has_socket_token: 0
		}).where("config_key", "=", "current"));
		e.exec("DROP TABLE IF EXISTS device_auth_tokens; DROP TABLE IF EXISTS device_identities; DROP TABLE IF EXISTS gateway_origin_device_tokens;");
	} catch (e) {
		close();
		throw e;
	}
}
//#endregion
//#region src/config/sessions/targets-configured-agents.ts
/** Lists agent ids whose session stores should be considered configured. */
function listConfiguredSessionStoreAgentIds(e) {
	const t = new Set(listAgentIds(e).map((e) => normalizeAgentId(e)));
	const addAcpAgentId = (e) => {
		const n = e?.trim() ?? "";
		if (!n || n === "*") return;
		t.add(normalizeAgentId(n));
	};
	addAcpAgentId(e.acp?.defaultAgent);
	for (const t of e.acp?.allowedAgents ?? []) addAcpAgentId(t);
	for (const t of listAgentEntries(e)) if (t.runtime?.type === "acp") addAcpAgentId(t.runtime.acp?.agent ?? t.id);
	return [...t];
}
//#endregion
//#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 = fsSync.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) => fsSync.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 (fsSync.lstatSync(a, { throwIfNoEntry: false })?.isSymbolicLink()) return { kind: "unavailable" };
		let o = [];
		try {
			o = fsSync.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() || fsSync.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 = fsSync.lstatSync(e, { throwIfNoEntry: false });
			if (n && (!n.isFile() || n.size > 0) || t.slice(1).some((e) => fsSync.lstatSync(e, { throwIfNoEntry: false }))) return { kind: "existing" };
		}
		if (resolveSqliteDatabaseFilePaths(e).some((e) => fsSync.lstatSync(e, { throwIfNoEntry: false }))) return {
			kind: "existing",
			nativeBootstrapEligible: true
		};
		return { kind: "fresh" };
	} catch {
		return { kind: "unavailable" };
	}
}
//#endregion
//#region src/infra/dedupe.ts
/** Creates a bounded in-memory dedupe cache with optional TTL expiry. */
function createDedupeCache(e) {
	const t = resolveNonNegativeIntegerOption(e.ttlMs, 0);
	const n = resolveNonNegativeIntegerOption(e.maxSize, 0);
	const r = /* @__PURE__ */ new Map();
	let i = Number.POSITIVE_INFINITY;
	let a = Number.NEGATIVE_INFINITY;
	let o = true;
	const prune = (e) => {
		const a = t > 0 ? e - t : void 0;
		if (a !== void 0 && a >= i) {
			i = Number.POSITIVE_INFINITY;
			for (const [e, t] of r) if (t.recordedAt <= a) r.delete(e);
			else if (t.recordedAt < i) {
				i = t.recordedAt;
				if (o) break;
			}
		}
		if (n <= 0) {
			r.clear();
			i = Number.POSITIVE_INFINITY;
			return;
		}
		pruneMapToMaxSize(r, n);
	};
	const hasUnexpired = (e, n, i) => {
		const a = r.get(e);
		if (!a) return false;
		if (t > 0 && n - a.recordedAt >= t) {
			r.delete(e);
			return false;
		}
		if (i) {
			a.recordedAt = n;
			r.delete(e);
			r.set(e, a);
		}
		return true;
	};
	return {
		check: (e, n, s) => {
			if (!e) return false;
			const c = n ?? Date.now();
			if (t > 0) {
				if (c < i) i = c;
				if (o) {
					o = c >= a;
					a = c;
				}
			}
			if (hasUnexpired(e, c, true)) return true;
			r.set(e, {
				recordedAt: c,
				...s ? { ownerToken: s } : {}
			});
			prune(c);
			return false;
		},
		peek: (e, t = Date.now()) => {
			if (!e) return false;
			return hasUnexpired(e, t, false);
		},
		delete: (e, t) => {
			if (!e) return;
			if (t && r.get(e)?.ownerToken !== t) return;
			r.delete(e);
		},
		clear: () => {
			r.clear();
			i = Number.POSITIVE_INFINITY;
			a = Number.NEGATIVE_INFINITY;
			o = true;
		},
		size: () => r.size
	};
}
//#endregion
//#region src/state/openclaw-state-db-permissions.ts
const OPENCLAW_STATE_DIR_MODE = 448;
const OPENCLAW_STATE_FILE_MODE = 384;
const stateDbLog$2 = createSubsystemLogger("state/db");
/** Targets already warned about, so chmod-less filesystems warn once per path. */
const chmodWarnedTargets = createDedupeCache({
	ttlMs: 0,
	maxSize: 4096
});
function bestEffortChmodSync(e, t) {
	let n;
	try {
		n = applyPrivateModeSync(e, t);
	} catch (t) {
		if (!hasErrnoCode(t, "EPERM") || !process.getuid || statSync(e).uid === process.getuid()) throw t;
		n = {
			applied: false,
			error: t
		};
	}
	if (n.applied || chmodWarnedTargets.check(e)) return;
	stateDbLog$2.warn(`skipped permission hardening for ${e}: ${String(n.error)}`);
}
/** Private stores this installation owns beside its shared state database. */
const PRIVATE_STATE_STORES = Object.freeze([["client", "credentials.sqlite"], ["control", "services.sqlite"]]);
function ensureOpenClawStatePermissions(e, t, n = {}) {
	const r = path.dirname(e);
	const i = resolveOpenClawStateSqlitePath(t);
	const a = path.dirname(i);
	const o = path.resolve(e) === path.resolve(i);
	if (o && r !== a) throw new Error(`OpenClaw state database path resolved outside its state dir: ${e}`);
	const s = existsSync(r);
	if (n.createDirectory) mkdirSync(r, {
		recursive: true,
		mode: OPENCLAW_STATE_DIR_MODE
	});
	if (o || !s) bestEffortChmodSync(r, OPENCLAW_STATE_DIR_MODE);
	for (const t of resolveSqliteDatabaseFilePaths(e)) if (existsSync(t)) try {
		bestEffortChmodSync(t, OPENCLAW_STATE_FILE_MODE);
	} catch (n) {
		if (t === e || !hasErrnoCode(n, "ENOENT")) throw n;
	}
}
//#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/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;
}
/**
* 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();
}
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-strict.ts
const DEFAULT_STRICT_MIGRATION_BUSY_TIMEOUT_MS = 5e3;
const STRICT_MIGRATION_TABLE_PREFIX = "__openclaw_strict_migration_";
const SQLITE_ROWID_ALIASES = [
	"_rowid_",
	"rowid",
	"oid"
];
function readMainTableList(e, t = {}) {
	return e.prepare("PRAGMA table_list").all().filter((e) => e.schema === "main" && typeof e.name === "string" && (t.includeInternal === true || !e.name.startsWith("sqlite_")));
}
/** Canonical bootstrap needs no legacy rebuild when every ordinary table is already STRICT. */
function hasNonStrictSqliteTables(e) {
	return readMainTableList(e).some((e) => e.type === "table" && Number(e.strict) !== 1);
}
function readTableColumns(e, t) {
	return e.prepare(`PRAGMA table_xinfo(${quoteSqliteIdentifier(t)})`).all();
}
function readVisibleColumns(e, t) {
	return readTableColumns(e, t).filter((e) => Number(e.hidden ?? 0) === 0).map((e) => {
		if (typeof e.name !== "string" || e.name.length === 0) throw new Error(`SQLite table ${t} has an invalid column name`);
		return e.name;
	});
}
function readTableRowidModel(e, t, n) {
	if (Number(n.wr ?? 0) === 1) return {
		alias: null,
		storage: "without-rowid"
	};
	const r = readTableColumns(e, t);
	const i = e.prepare(`SELECT 1 AS found FROM pragma_index_list(?) WHERE origin = 'pk' LIMIT 1`).get(t);
	return resolveTableRowidModel(t, r, Boolean(i));
}
function resolveTableRowidModel(e, t, n) {
	const r = t.filter((e) => Number(e.pk ?? 0) > 0);
	const i = r[0]?.type;
	if (r.length === 1 && typeof i === "string" && i.toUpperCase() === "INTEGER" && !n) return {
		alias: null,
		storage: "integer-primary-key"
	};
	const a = new Set(t.flatMap((e) => typeof e.name === "string" ? [e.name.toLowerCase()] : []));
	const o = SQLITE_ROWID_ALIASES.find((e) => !a.has(e)) ?? null;
	if (!o) throw new Error(`SQLite table ${e} shadows every rowid alias; its implicit rowids cannot be migrated safely`);
	return {
		alias: o,
		storage: "implicit"
	};
}
function canonicalStrictTablesFromCatalog(e) {
	return e.tables.map((e) => {
		if (e.sql === null) throw new Error(`Canonical SQLite table ${e.name} has no CREATE statement`);
		const t = e.withoutRowid === 1 ? {
			alias: null,
			storage: "without-rowid"
		} : resolveTableRowidModel(e.name, e.columns, e.indexes.some((e) => e.origin === "pk"));
		return {
			columns: e.columns.filter((e) => e.hidden === 0).map((e) => e.name),
			createSql: e.sql,
			name: e.name,
			rowidAlias: t.alias,
			rowidStorage: t.storage,
			usesAutoincrement: /\bAUTOINCREMENT\b/iu.test(e.sql)
		};
	}).toSorted((e, t) => e.name.localeCompare(t.name));
}
function readCanonicalStrictTables(e) {
	const t = openNodeSqliteDatabase(":memory:");
	try {
		t.exec(e);
		const n = readMainTableList(t).filter((e) => e.type === "table");
		const r = n.filter((e) => Number(e.strict ?? 0) !== 1).map((e) => e.name);
		if (r.length > 0) throw new Error(`Canonical SQLite schema contains non-STRICT tables: ${r.toSorted().join(", ")}`);
		return n.map((e) => {
			const n = t.prepare("SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?").get(e.name);
			if (typeof n?.sql !== "string") throw new Error(`Canonical SQLite table ${e.name} has no CREATE statement`);
			const r = readTableRowidModel(t, e.name, e);
			return {
				columns: readVisibleColumns(t, e.name),
				createSql: n.sql,
				name: e.name,
				rowidAlias: r.alias,
				rowidStorage: r.storage,
				usesAutoincrement: /\bAUTOINCREMENT\b/iu.test(n.sql)
			};
		}).toSorted((e, t) => e.name.localeCompare(t.name));
	} finally {
		t.close();
	}
}
function rewriteCreateTableName(e, t) {
	const n = e.indexOf("(");
	if (n === -1) throw new Error("Canonical SQLite table CREATE statement has no column list");
	return `CREATE TABLE ${quoteSqliteIdentifier(t)} ${e.slice(n)}`;
}
function readPreservedSchemaObjects(e, t) {
	return e.prepare("SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE type IN ('index', 'trigger', 'view')").all().flatMap((e) => {
		if (e.type !== "index" && e.type !== "trigger" && e.type !== "view" || typeof e.name !== "string" || typeof e.tbl_name !== "string" || typeof e.sql !== "string" || e.type === "index" && !t.has(e.tbl_name)) return [];
		return [{
			name: e.name,
			sql: e.sql,
			type: e.type
		}];
	}).toSorted((e, t) => {
		const n = {
			view: 0,
			index: 1,
			trigger: 2
		};
		return n[e.type] - n[t.type] || e.name.localeCompare(t.name);
	});
}
function readAutoincrementHighWater(e, t) {
	if (!e.prepare("SELECT 1 AS found FROM sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'").get()) return null;
	const n = e.prepare("SELECT CAST(seq AS TEXT) AS seq FROM sqlite_sequence WHERE name = ?").get(t);
	if (n === void 0) return null;
	const r = typeof n.seq === "string" ? /^(\d+)(?:\.0+)?$/u.exec(n.seq)?.[1] : null;
	if (!r) throw new Error(`SQLite table ${t} has an invalid AUTOINCREMENT high-water mark (${typeof n.seq}: ${String(n.seq)})`);
	return r;
}
function restoreAutoincrementHighWater(e, t, n) {
	if (n === null) return;
	const r = readAutoincrementHighWater(e, t);
	const i = r === null || BigInt(n) > BigInt(r) ? n : r;
	e.prepare("DELETE FROM sqlite_sequence WHERE name = ?").run(t);
	e.prepare("INSERT INTO sqlite_sequence (name, seq) VALUES (?, CAST(? AS INTEGER))").run(t, i);
}
function assertMatchingColumns(e, t, n) {
	const r = new Set(t);
	const i = new Set(n);
	const a = n.filter((e) => !r.has(e));
	const o = t.filter((e) => !i.has(e));
	if (a.length === 0 && o.length === 0) return;
	const s = [a.length > 0 ? `missing ${a.join(", ")}` : "", o.length > 0 ? `extra ${o.join(", ")}` : ""].filter(Boolean).join("; ");
	throw new Error(`SQLite table ${e} does not match its canonical columns (${s})`);
}
function readForeignKeysEnabled(e) {
	const t = e.prepare("PRAGMA foreign_keys").get();
	return Number(t?.foreign_keys ?? 0) === 1;
}
/**
* Rebuild canonical non-STRICT tables inside the caller's transaction.
* Foreign-key enforcement must be disabled before BEGIN; integrity is checked
* before this function returns so any bad row or relationship rolls back.
*/
function migrateSqliteSchemaToStrictInTransaction(e, t, n = {}) {
	if (!e.isTransaction) throw new Error("SQLite STRICT schema migration requires an active transaction");
	const r = n.expectedSchema ?? t;
	const i = typeof r === "string" ? readGeneratedSqliteFingerprint(r) : void 0;
	const a = i?.tableNames ?? (typeof r === "string" ? void 0 : r.tables.map((e) => e.name));
	const readCurrentTables = () => new Map(readMainTableList(e).filter((e) => e.type === "table").map((e) => [e.name, e]));
	let o = n.expectedSchema !== void 0 && a ? readCurrentTables() : /* @__PURE__ */ new Map();
	if (n.expectedSchema !== void 0 && a?.every((e) => Number(o.get(e)?.strict ?? 0) === 1)) return { migratedTables: [] };
	const s = typeof r === "string" ? i && readGeneratedSqliteCatalog(r) : r;
	const c = s?.tables.every((e) => e.strict === 1);
	const l = s && c ? canonicalStrictTablesFromCatalog(s) : readCanonicalStrictTables(t);
	if (n.expectedSchema === void 0 || !c || l.some((e) => !o.has(e.name))) {
		e.exec(t);
		o = readCurrentTables();
	}
	const u = l.filter((e) => Number(o.get(e.name)?.strict ?? 0) !== 1);
	if (u.length === 0) return { migratedTables: [] };
	if (readForeignKeysEnabled(e)) throw new Error("SQLite STRICT schema migration requires foreign_keys=OFF before BEGIN");
	const d = readPreservedSchemaObjects(e, new Set(u.map((e) => e.name)));
	for (const t of ["trigger", "view"]) for (const n of d) if (n.type === t) e.exec(`DROP ${t.toUpperCase()} ${quoteSqliteIdentifier(n.name)};`);
	for (const [t, n] of u.entries()) {
		const r = `${STRICT_MIGRATION_TABLE_PREFIX}${t}_${n.name}`;
		if (o.has(r)) throw new Error(`SQLite STRICT migration table already exists: ${r}`);
		const i = readVisibleColumns(e, n.name);
		assertMatchingColumns(n.name, i, n.columns);
		const a = o.get(n.name);
		if (!a) throw new Error(`SQLite table ${n.name} disappeared during STRICT migration`);
		const s = readTableRowidModel(e, n.name, a);
		if (s.storage !== n.rowidStorage) throw new Error(`SQLite table ${n.name} changes rowid storage from ${s.storage} to ${n.rowidStorage}; refusing an identity-changing STRICT migration`);
		const c = n.usesAutoincrement ? readAutoincrementHighWater(e, n.name) : null;
		e.exec(rewriteCreateTableName(n.createSql, r));
		const l = n.columns.map(quoteSqliteIdentifier);
		if (n.rowidAlias) l.unshift(quoteSqliteIdentifier(n.rowidAlias));
		const u = l.join(", ");
		try {
			e.exec(`INSERT INTO ${quoteSqliteIdentifier(r)} (${u}) SELECT ${u} FROM ${quoteSqliteIdentifier(n.name)};`);
		} catch (e) {
			throw new Error(`Failed migrating SQLite table ${n.name} to STRICT`, { cause: e });
		}
		e.exec(`DROP TABLE ${quoteSqliteIdentifier(n.name)};`);
		e.exec(`ALTER TABLE ${quoteSqliteIdentifier(r)} RENAME TO ${quoteSqliteIdentifier(n.name)};`);
		restoreAutoincrementHighWater(e, n.name, c);
	}
	e.exec(t);
	const f = e.prepare("SELECT 1 AS found FROM sqlite_schema WHERE type = ? AND name = ? LIMIT 1");
	for (const t of d) if (!f.get(t.type, t.name)) e.exec(t.sql);
	assertSqliteIntegrity(e, n.databaseLabel ?? "SQLite STRICT schema migration", {
		check: n.integrityCheck ?? "quick",
		tables: u.map((e) => e.name)
	});
	return { migratedTables: u.map((e) => e.name) };
}
/** Atomically upgrade OpenClaw-owned tables described by a canonical STRICT schema. */
function migrateSqliteSchemaToStrict(e, t, n = {}) {
	if (e.isTransaction) throw new Error("SQLite STRICT schema migration cannot start inside a transaction");
	const r = readForeignKeysEnabled(e);
	if (r) e.exec("PRAGMA foreign_keys = OFF;");
	try {
		return runSqliteImmediateTransactionSync(e, () => migrateSqliteSchemaToStrictInTransaction(e, t, n), {
			busyTimeoutMs: n.busyTimeoutMs ?? DEFAULT_STRICT_MIGRATION_BUSY_TIMEOUT_MS,
			databaseLabel: n.databaseLabel,
			operationLabel: "sqlite.strict-schema-migration"
		});
	} finally {
		if (r) e.exec("PRAGMA foreign_keys = ON;");
	}
}
//#endregion
//#region packages/gateway-protocol/src/failover-reasons.ts
const FAILOVER_REASONS = [
	"auth",
	"auth_permanent",
	"format",
	"rate_limit",
	"overloaded",
	"billing",
	"server_error",
	"timeout",
	"tls_certificate",
	"context_overflow",
	"model_not_found",
	"session_expired",
	"empty_response",
	"no_error_details",
	"unclassified",
	"unknown"
];
//#endregion
//#region packages/gateway-protocol/src/schema/closed-object.ts
const identityKey = "~openclawClosedObjectIdentity";
function closedObject(e) {
	const t = Type.Object(e, { additionalProperties: false });
	Object.defineProperty(t, identityKey, { value: Symbol("closedObject") });
	return t;
}
//#endregion
//#region packages/gateway-protocol/src/schema/cron-shared.ts
const MAX_DATE_TIMESTAMP_MS = 864e13;
const CronDateTimestampMsSchema = Type.Integer({
	minimum: 0,
	maximum: MAX_DATE_TIMESTAMP_MS
});
//#endregion
//#region packages/gateway-protocol/src/schema/string-literal-union.ts
/** Preserve the protocol's ordered anyOf shape and TypeBox's tuple-based inference. */
function stringLiteralUnion(e) {
	const t = e.map((e) => Type.Literal(e));
	return Type.Union(t);
}
//#endregion
//#region packages/gateway-protocol/src/schema/cron-automation-result.ts
const AutomationMeaningfulOutcomeSchema = stringLiteralUnion([
	"progress",
	"done",
	"blocked",
	"needs_attention"
]);
const AutomationOutcomeSchema = Type.Union([Type.Literal("no_change"), AutomationMeaningfulOutcomeSchema]);
const AutomationResultSummarySchema = Type.String({
	minLength: 1,
	maxLength: 2e3,
	pattern: "\\S"
});
const AutomationMeaningfulResultSchema = closedObject({
	outcome: AutomationMeaningfulOutcomeSchema,
	summary: AutomationResultSummarySchema
});
/** A quiet check needs no prose; meaningful facts always carry a bounded summary. */
const AutomationResultSchema = Type.Union([closedObject({
	outcome: Type.Literal("no_change"),
	summary: Type.Optional(AutomationResultSummarySchema)
}), AutomationMeaningfulResultSchema]);
const AutomationLastMeaningfulResultSchema = closedObject({
	...AutomationMeaningfulResultSchema.properties,
	atMs: CronDateTimestampMsSchema
});
//#endregion
//#region src/cron/automation-result.ts
/** Normalize once at the model/stored-history boundary against the wire contract. */
function parseAutomationResult(e) {
	if (!isRecord(e)) return;
	const t = typeof e.summary === "string" ? {
		...e,
		summary: e.summary.trim()
	} : { ...e };
	return Value.Check(AutomationResultSchema, t) ? t : void 0;
}
//#endregion
//#region src/cron/completion-status.ts
/** Resolves authored completion from an admitted job, or legacy completion from stored facts. */
function resolveCronCompletionStatus(e) {
	if (e.status === "error" || e.status === "skipped") return "failed";
	if (e.status !== "ok") return "unknown";
	if (e.requiredDelivery === void 0) return e.delivered === true || e.deliveryStatus === "delivered" || e.deliveryStatus === "not-requested" ? "succeeded" : "unknown";
	if (!e.requiredDelivery || e.deliveryStatus === "delivered" || e.deliveryStatus === "not-delivered" && e.deliverySuppressionReason !== void 0) return "succeeded";
	return e.deliveryStatus === "not-delivered" ? "failed" : "unknown";
}
//#endregion
//#region src/cron/execution-error-constants.ts
const CRON_JOB_EXECUTION_TIMEOUT_ERROR = "cron: job execution timed out";
const CRON_SETUP_TIMEOUT_ERROR = "cron: isolated agent setup timed out before runner start";
const CRON_PRE_EXECUTION_TIMEOUT_ERROR = "cron: isolated agent run stalled before execution start";
const CRON_TIMEOUT_ERROR_PREFIXES = [
	CRON_JOB_EXECUTION_TIMEOUT_ERROR,
	CRON_SETUP_TIMEOUT_ERROR,
	CRON_PRE_EXECUTION_TIMEOUT_ERROR
];
/** Recognizes watchdog timeouts without loading agent or execution-phase runtime. */
function isCronTimeoutErrorText(e) {
	return typeof e === "string" && CRON_TIMEOUT_ERROR_PREFIXES.some((t) => e === t || e.startsWith(`${t} `));
}
//#endregion
//#region src/cron/run-diagnostics-normalize.ts
const MAX_ENTRIES = 10;
const MAX_ENTRY_CHARS = 1e3;
const MAX_SUMMARY_CHARS = 2e3;
function normalizeSeverity(e) {
	return e === "info" || e === "warn" || e === "error" ? e : "error";
}
function normalizeSource(e) {
	switch (e) {
		case "cron-preflight":
		case "cron-setup":
		case "model-preflight":
		case "agent-run":
		case "tool":
		case "exec":
		case "delivery": return e;
		default: return "agent-run";
	}
}
function normalizeTimestamp$1(e, t) {
	return typeof e === "number" && Number.isFinite(e) && e >= 0 ? Math.floor(e) : t();
}
function normalizeDiagnosticMessage(e, t) {
	if (typeof e !== "string") return {};
	const n = normalizeOptionalString(e);
	if (!n) return {};
	const r = t(n);
	if (r.length <= MAX_ENTRY_CHARS) return { message: r };
	return {
		message: `${truncateUtf16Safe(r, 999)}…`,
		truncated: true
	};
}
function normalizeCronRunDiagnosticSummary(e) {
	const t = normalizeOptionalString(e);
	if (!t) return;
	if (t.length <= MAX_SUMMARY_CHARS) return t;
	return `${truncateUtf16Safe(t, 1999)}…`;
}
/** Normalizes stored cron diagnostic payloads into bounded entries. */
function normalizeCronRunDiagnosticsCore(e, t) {
	if (!e || typeof e !== "object") return;
	const n = e;
	const r = t?.nowMs ?? Date.now;
	const i = t?.redactText ?? ((e) => e);
	const a = Array.isArray(n.entries) ? n.entries : [];
	const o = [];
	for (const e of a) {
		if (!e || typeof e !== "object") continue;
		const t = e;
		const n = normalizeDiagnosticMessage(t.message, i);
		if (!n.message) continue;
		o.push({
			ts: normalizeTimestamp$1(t.ts, r),
			source: normalizeSource(t.source),
			severity: normalizeSeverity(t.severity),
			message: n.message,
			...typeof t.toolName === "string" && t.toolName.trim() ? { toolName: t.toolName.trim() } : {},
			...typeof t.exitCode === "number" && Number.isFinite(t.exitCode) ? { exitCode: t.exitCode } : t.exitCode === null ? { exitCode: null } : {},
			...t.truncated === true || n.truncated ? { truncated: true } : {}
		});
		if (o.length > MAX_ENTRIES) o.shift();
	}
	const s = normalizeCronRunDiagnosticSummary(typeof n.summary === "string" ? i(n.summary) : void 0);
	if (o.length === 0 && !s) return;
	return {
		...s ? { summary: s } : {},
		entries: o
	};
}
//#endregion
//#region src/cron/run-history-detail.ts
/** Read-side cron codec between cron history detail and the stable run-history wire shape.
* Deliberately free of agent/runtime imports so history reads stay dependency-light;
* the event->entry write codec lives in run-event-codec.ts. */
const CRON_RUN_DETAIL_KIND = "cron-run";
const cronRunStatusSchema = _enum([
	"ok",
	"error",
	"skipped"
]);
const cronCompletionStatusSchema = _enum([
	"succeeded",
	"failed",
	"unknown"
]);
const cronDeliveryStatusSchema = _enum([
	"delivered",
	"not-delivered",
	"unknown",
	"not-requested"
]);
const optionalCronStringSchema = string().optional().catch(void 0);
const optionalNonBlankCronStringSchema = string().refine((e) => e.trim().length > 0).optional().catch(void 0);
const optionalCronTimestampSchema = unknown().optional().transform((e) => normalizeTimestamp(e));
const optionalCronNonnegativeIntegerSchema = unknown().optional().transform((e) => asSafeIntegerInRange(e, { min: 0 }));
const cronUsageSchema = object({
	input_tokens: optionalCronNonnegativeIntegerSchema,
	output_tokens: optionalCronNonnegativeIntegerSchema,
	total_tokens: optionalCronNonnegativeIntegerSchema,
	cache_read_tokens: optionalCronNonnegativeIntegerSchema,
	cache_write_tokens: optionalCronNonnegativeIntegerSchema
}).transform((e) => Object.values(e).some((e) => e !== void 0) ? e : void 0).optional().catch(void 0);
const cronFailureNotificationDeliverySchema = looseObject({
	status: cronDeliveryStatusSchema,
	delivered: boolean().optional().catch(void 0),
	error: optionalCronStringSchema
}).transform(({ status: e, delivered: t, error: n }) => ({
	status: e,
	...t !== void 0 ? { delivered: t } : {},
	...n !== void 0 ? { error: n } : {}
})).optional().catch(void 0);
const cronRunLogEntrySchema = looseObject({
	action: literal$1("finished"),
	jobId: string().refine((e) => e.trim().length > 0),
	ts: unknown().transform((e) => normalizeTimestamp(e)).pipe(number()),
	status: cronRunStatusSchema.optional().catch(void 0),
	completionStatus: cronCompletionStatusSchema.optional().catch(void 0),
	error: optionalCronStringSchema,
	errorReason: _enum(FAILOVER_REASONS).optional().catch(void 0),
	summary: optionalCronStringSchema,
	result: unknown().optional().transform(parseAutomationResult),
	runId: optionalNonBlankCronStringSchema,
	diagnostics: unknown().optional(),
	runAtMs: optionalCronTimestampSchema,
	durationMs: optionalCronNonnegativeIntegerSchema,
	nextRunAtMs: optionalCronTimestampSchema,
	triggerFired: unknown().optional().transform((e) => e === true ? true : void 0),
	model: optionalNonBlankCronStringSchema,
	provider: optionalNonBlankCronStringSchema,
	usage: cronUsageSchema,
	delivered: boolean().optional().catch(void 0),
	deliveryStatus: cronDeliveryStatusSchema.optional().catch(void 0),
	deliveryError: optionalCronStringSchema,
	deliverySuppressionReason: _enum([
		"empty",
		"silent",
		"heartbeat",
		"channel_transform"
	]).optional().catch(void 0),
	failureNotificationDelivery: cronFailureNotificationDeliverySchema,
	delivery: custom(isJsonObject).optional().catch(void 0),
	sessionId: optionalNonBlankCronStringSchema,
	sessionKey: optionalNonBlankCronStringSchema
});
/** Native JSON parsing keeps released scalar/null and numeric-overflow semantics. */
function parseCronRunDetailJson(e) {
	return safeParseJson(e);
}
function toJsonValue(e) {
	const t = JSON.stringify(e);
	return t === void 0 ? void 0 : parseCronRunDetailJson(t);
}
function isJsonObject(e) {
	return isRecord(e);
}
function normalizeTimestamp(e) {
	return asSafeIntegerInRange(e, {
		min: 0,
		max: MAX_DATE_TIMESTAMP_MS$1
	});
}
/** Parses stored or migrated cron history while preserving the stable wire shape. */
function parseCronRunLogEntryObject(e, t) {
	const n = normalizeOptionalString(t?.jobId);
	const r = cronRunLogEntrySchema.safeParse(e);
	if (!r.success) return null;
	const i = r.data;
	if (n && i.jobId !== n) return null;
	return {
		ts: i.ts,
		jobId: i.jobId,
		action: "finished",
		status: i.status,
		completionStatus: i.completionStatus ?? resolveCronCompletionStatus({
			status: i.status,
			delivered: i.delivered,
			deliveryStatus: i.deliveryStatus
		}),
		error: i.error,
		errorReason: i.errorReason,
		summary: i.summary,
		result: i.result,
		runId: i.runId,
		diagnostics: normalizeCronRunDiagnosticsCore(i.diagnostics),
		runAtMs: i.runAtMs,
		durationMs: i.durationMs,
		nextRunAtMs: i.nextRunAtMs,
		triggerFired: i.triggerFired,
		model: i.model,
		provider: i.provider,
		usage: i.usage,
		delivered: i.delivered,
		deliveryStatus: i.deliveryStatus,
		deliveryError: i.deliveryError,
		deliverySuppressionReason: i.deliverySuppressionReason,
		failureNotificationDelivery: i.failureNotificationDelivery,
		delivery: i.delivery,
		sessionId: i.sessionId,
		sessionKey: i.sessionKey
	};
}
/** Encodes Cron-owned outcome fields for retained history. */
function cronRunLogEntryToDetail(e, t) {
	return toJsonValue({
		kind: CRON_RUN_DETAIL_KIND,
		status: e.status,
		completionStatus: e.completionStatus,
		error: e.error ?? null,
		summary: e.summary ?? null,
		result: e.result,
		storeKey: t.storeKey,
		errorReason: e.errorReason,
		diagnostics: e.diagnostics,
		delivered: e.delivered,
		deliveryStatus: e.deliveryStatus,
		deliveryError: e.deliveryError,
		deliverySuppressionReason: e.deliverySuppressionReason,
		failureNotificationDelivery: e.failureNotificationDelivery,
		delivery: e.delivery,
		sessionId: e.sessionId,
		runId: e.runId,
		runAtMs: e.runAtMs,
		durationMs: e.durationMs,
		nextRunAtMs: e.nextRunAtMs,
		triggerFired: e.triggerFired,
		triggerStateChanged: t.triggerEval?.fired === true ? t.triggerEval.stateChanged : void 0,
		triggerState: t.triggerEval?.fired === true && t.triggerEval.stateChanged ? t.triggerEval.state : void 0,
		scriptStateChanged: t.scriptResult?.scriptStateChanged === true ? true : void 0,
		scriptState: t.scriptResult?.scriptStateChanged === true ? t.scriptResult.scriptState : void 0,
		model: e.model,
		provider: e.provider,
		usage: e.usage
	}) ?? { kind: CRON_RUN_DETAIL_KIND };
}
/** Preserves the released history row status vocabulary. */
function cronRunStorageStatus(e) {
	if (e.status === "ok") return (e.completionStatus ?? resolveCronCompletionStatus({
		status: e.status,
		delivered: e.delivered,
		deliveryStatus: e.deliveryStatus
	})) === "succeeded" ? "succeeded" : "failed";
	return e.status === "error" && isCronTimeoutErrorText(e.error) ? "timed_out" : "failed";
}
//#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/infra/sqlite-schema-ensure.ts
/** Install missing additive objects using the connection's admitted schema lifecycle. */
function createSqliteSchemaEnsurer(e, t) {
	const present = (e) => {
		const n = getAdmittedSqliteSchemaFacts(e);
		return n !== void 0 && t.tables.every((e) => n.tables.has(e)) && (t.indexes?.every((e) => n.indexes.has(e)) ?? true);
	};
	return (t, n) => {
		if (isPostgresSqlConnection(t)) requireNativeDatabaseFile("postgres", "repair");
		runSqliteReadOperationSync(t, () => {
			if (present(t)) return;
			const install = (t) => t.exec(e());
			if (n) n(install);
			else if (t.isTransaction) install(t);
			else runSqliteImmediateTransactionSync(t, () => install(t));
		});
	};
}
//#endregion
//#region src/state/openclaw-state-feature-schema.ts
const featureLocalSql = {
	local_workspace_projections: [
		extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "local_workspace_projections"),
		extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "local_workspace_manifest_nodes"),
		extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "local_workspace_tree_packs"),
		extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "local_workspace_source_path_sets")
	].join("\n"),
	user_profiles: `
CREATE TABLE IF NOT EXISTS user_profiles (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT,
  primary_github_account_id INTEGER,
  avatar BLOB,
  avatar_mime TEXT,
  avatar_sha256 TEXT,
  merged_into TEXT,
  role TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_emails (
  email TEXT NOT NULL PRIMARY KEY,
  profile_id TEXT NOT NULL,
  binding_id TEXT,
  created_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_user_profile_emails_profile_id
  ON user_profile_emails(profile_id);

${extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, "user_profile_identities")}
`,
	operator_approval_standing_grants: `
CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
  minted_by_approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
  revoked_at_ms INTEGER,
  revoked_by TEXT,
  last_used_at_ms INTEGER,
  use_count INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;
`,
	worker_environment_session_attachments: `
CREATE TABLE IF NOT EXISTS worker_environment_session_attachments (
  session_id TEXT PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  environment_id TEXT NOT NULL UNIQUE,
  generation INTEGER NOT NULL CHECK (generation >= 1),
  created_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  closed_at_ms INTEGER,
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS worker_environment_session_attachments_session_key
ON worker_environment_session_attachments(agent_id, session_key);
`
};
function getOpenClawStateFeatureSchemaSql(e, t) {
	if (t === void 0 && featureLocalSql[e]) return featureLocalSql[e];
	if (e === "skill_library_entries" && t === void 0) return extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, e, {
		endMarker: "-- End profile-owned skill library.",
		includeEndMarker: false,
		errorMessage: "Canonical skill library schema missing."
	});
	return extractSqliteTableSchema(e === "user_profile_emails" ? featureLocalSql.user_profiles : OPENCLAW_STATE_SCHEMA_SQL, e, t);
}
//#endregion
//#region src/state/openclaw-state-db-schema-additive.ts
const tableEnsurers = /* @__PURE__ */ new Map();
function ensureTable(e, t, n) {
	if (isPostgresSqlConnection(e)) return ensureStatePostgresFragment(e, t);
	let r = tableEnsurers.get(t);
	if (!r) {
		const e = getOpenClawStateFeatureSchemaSql(t, n);
		r = createSqliteSchemaEnsurer(() => e, {
			tables: getCanonicalSqliteTableNames(e),
			indexes: getCanonicalSqliteNamedIndexNames(e)
		});
		tableEnsurers.set(t, r);
	}
	r(e);
}
function ensureWorkerSessionToolStateSchema(e) {
	ensureTable(e, "worker_turn_tool_authorities");
	ensureTable(e, "worker_session_tool_operations");
}
/**
* Complete first-use columns before a STRICT rebuild or in a private port copy.
* Both require canonical layouts; ordinary admission leaves these columns lazy.
*/
function ensureFirstUseAdditiveStateColumnsForStrictMigration(e) {
	for (const { columnName: t, dataType: n, tableName: r } of CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS) ensureColumn(e, r, `${t} ${n}`);
}
function ensureColumns(e, t) {
	const n = [];
	for (const [r, i] of t) {
		const t = i.trim().split(/\s+/, 1)[0];
		if (t && ensureColumn(e, r, i)) n.push({
			tableName: r,
			columnName: t
		});
	}
	return n;
}
/** Runtime pairs new columns with their transforms; full historical repair stays explicit. */
function ensureAdditiveStateColumns(e, t) {
	const n = t === "repair";
	ensureWorkerSessionToolStateSchema(e);
	for (const { columnName: t, dataType: n, tableName: r } of CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS) ensureColumn(e, r, `${t} ${n}`);
	if (ensureColumn(e, ...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageUpdatedAt[0])) e.exec("UPDATE template_package_refs SET updated_at_ms = installed_at_ms;");
	ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.packageIntegrity);
	const r = ensureColumn(e, ...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.diagnosticSequence[0]);
	if (r) e.exec(`
      WITH ranked AS (
        SELECT
          rowid AS event_rowid,
          ROW_NUMBER() OVER (
            PARTITION BY scope
            ORDER BY created_at ASC, rowid ASC
          ) AS sequence
        FROM diagnostic_events
      )
      UPDATE diagnostic_events
      SET sequence = (
        SELECT ranked.sequence
        FROM ranked
        WHERE ranked.event_rowid = diagnostic_events.rowid
      );
    `);
	if (r || n) e.exec("DROP INDEX IF EXISTS idx_diagnostic_events_scope_created;");
	const i = ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.cronRunLogs);
	if (n || i.some(({ tableName: e }) => e === "cron_run_logs")) backfillCronRunLogEntryJson(e);
	const a = ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.acpReplay).length > 0;
	if (a || n) backfillAcpReplayEstimatedBytes(e, a);
	const o = ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.cronJobs);
	if (n || o.some(({ columnName: e }) => [
		"name",
		"enabled",
		"agent_id",
		"payload_kind",
		"runtime_updated_at_ms"
	].includes(e))) backfillCronJobsFromJobJson(e);
	const s = ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.deliveryQueue);
	if (n || s.some(({ tableName: e }) => e === "delivery_queue_entries")) backfillDeliveryQueueEntriesFromEntryJson(e);
	ensureColumn(e, ...ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.originalMediaRoot[0]);
	ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.beforeTaskAttribution);
	ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.taskRequester);
	ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.taskRunDetails);
	if (n) {
		repairLegacySubagentExecutionPayloads(e);
		repairLegacySubagentRetainedResults(e);
	}
	ensureColumns(e, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS.workerEnvironments);
	if (n || !tableHasColumn(e, "operator_approvals", "resolution_ref")) ensureOperatorApprovalResolutionRefs(e);
}
//#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 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());
}
//#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
/** 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.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 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 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 { safeParseJson as A, copyConfigResolutionFactsExcept as C, resolveConfigSecretRef as D, hasUnresolvedConfigPath as E, setConfigResolutionFacts as O, cloneConfigWithResolutionFacts as S, getConfigResolutionFacts as T, resolveClientCredentialStorePath as _, migrateSqliteSchemaToStrict as a, isDeeplyFrozenPlainData as b, withExistingOpenClawStateDatabaseArtifactPreservingReadOnly as c, listAgentIds as d, DeviceIdentityStorageError as f, storedDeviceIdentityToRow as g, normalizeIdentityKey as h, closedObject as i, safeParseJsonRecord as j, stableStringify as k, withExistingOpenClawStateDatabaseReadOnly as l, identityFromCredentialResult as m, runOpenClawStateWriteTransaction as n, executeExistingOpenClawStateRead as o, generateStoredDeviceIdentity as p, stringLiteralUnion as r, getActiveOpenClawStateDatabaseReadSnapshot as s, openOpenClawStateDatabase as t, resolveAgentWorkspaceDir as u, runtimeConfigPublication as v, getAuthoredConfigSecretRef as w, resolveConfigForRead as x, freezeJsonSnapshot as y };