UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,166 lines • 256 kB
import { c as hasErrnoCode } from "./paths-0xDagtub.mjs";
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { a as wrapSqliteWorkerError } from "./sqlite-worker-error-Q7g0aE9t.mjs";
import { n as isSqliteLockError, u as sqlitePrimaryResultCode } from "./sqlite-error-diagnostics-DXQCgyiD.mjs";
import { h as AsyncContext, m as parseDiagnosticEnvFlags, t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { a as runtimeProcessScriptEntrypoints } from "./runtime-process-manifest-BxvHhnYN.mjs";
import { a as registerListener, i as notifyListeners, n as isPostgresSqlConnection, r as sqlPublicationAnchor } from "./sql-connection-VmV9pnJI.mjs";
import { a as inspectDatabasePathIdentity, c as normalizeDatabasePath, s as isSoleDatabaseFileDescriptor, t as assertDatabaseFileIdentity, u as readDatabaseIdentityBirthtime } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { c as createSqliteLifecycleAggregateError } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { n as resolveRuntimeScriptEnv, r as resolveStandaloneSidecarRoot } from "./cli-invocation-CSfpG5sl.mjs";
import { t as PROCESS_MACHINE_IDENTITY_KEY } from "./current-machine-identity-DFuZQ9km.mjs";
import { n as compareValidSemver } from "./semver-DUtldgR6.mjs";
import { createRequire } from "node:module";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual, toUSVString } from "node:util";
import { spawnSync } from "node:child_process";
import fsSync, { existsSync } from "node:fs";
import path, { posix } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createHash, randomUUID } from "node:crypto";
import { normalizeWindowsPathForComparison } from "@openclaw/fs-safe/path";
import fsPromises from "node:fs/promises";
import os from "node:os";
import { getEnvironmentData, isMainThread, setEnvironmentData, threadId } from "node:worker_threads";
//#region src/infra/sqlite-post-commit.ts
const log = createSubsystemLogger("sqlite/publication");
/**
* Installation is synchronous, including failure fencing. Observers cannot turn a
* committed write into a failed transaction or prevent another owner's receipt.
*/
function installCommittedState(e, t) {
	const n = /* @__PURE__ */ new Map();
	const install = (e, t) => {
		try {
			t?.();
		} catch (t) {
			n.set(e, t);
		}
	};
	for (const t of e) install(t, t.commit);
	const invalidate = () => {
		let e = true;
		for (const [t, r] of n) try {
			if (t.invalidate) t.invalidate(r);
			else e = false;
		} catch {
			e = false;
		}
		return e;
	};
	invalidate();
	for (const t of e) if (!n.has(t)) install(t, t.prepareObservers);
	const r = invalidate();
	if (n.size > 0) try {
		log.error("Committed SQLite facts could not be installed", {
			count: n.size,
			fenced: r
		});
	} catch {}
	if (!r) return;
	for (const e of t) try {
		e();
	} catch {
		try {
			log.error("SQLite post-commit notification failed");
		} catch {}
	}
}
const pendingPublications = resolveGlobalSingleton(Symbol.for("openclaw.sqlitePostCommitPublications"), () => /* @__PURE__ */ new WeakMap());
const pendingTransactionState = resolveGlobalSingleton(Symbol.for("openclaw.sqliteTransactionState"), () => /* @__PURE__ */ new WeakMap());
/** Snapshots read within this managed transaction can still roll back. */
function hasSqlitePostCommitScope(e) {
	return pendingPublications.has(sqlPublicationAnchor(e));
}
/** Publications are non-throwing observers, never part of a durable transaction's result. */
function deferSqlitePostCommitPublication(e, t) {
	const n = pendingPublications.get(sqlPublicationAnchor(e));
	if (!n) return false;
	n.push(t);
	return true;
}
/**
* Stage private transaction-local state that publishes before fallible observers.
* Observer preparation follows every committed state update. All callbacks must not throw.
*/
function stageSqliteTransactionState(e, t) {
	const n = pendingTransactionState.get(sqlPublicationAnchor(e));
	if (!n) return false;
	t.stage?.();
	n.push({
		prepareCommit: t.prepareCommit,
		commit: t.commit,
		prepareObservers: t.prepareObservers,
		invalidate: t.invalidate,
		rollback: t.rollback
	});
	return true;
}
/** Tentative native writes stay private until their owner's final commit guard succeeds. */
function prepareSqliteTransactionCommit(e) {
	for (const t of pendingTransactionState.get(sqlPublicationAnchor(e)) ?? []) t.prepareCommit?.();
}
function rollbackTransactionState(e, t, n = "rolled-back") {
	const r = [];
	for (const i of e.toReversed()) try {
		if (n === "unknown" && i.invalidate) i.invalidate(t);
		else i.rollback?.(t);
	} catch (e) {
		r.push(e);
	}
	if (r.length > 0) throw createSqliteLifecycleAggregateError([t, ...r], "SQLite transaction and rollback observers failed", t);
}
/** A lost transaction invalidates every savepoint's staged state and observers. */
function discardSqliteTransactionState(e, t, n = "unknown") {
	const r = sqlPublicationAnchor(e);
	pendingPublications.get(r)?.splice(0);
	const i = pendingTransactionState.get(r)?.splice(0) ?? [];
	pendingPublications.delete(r);
	pendingTransactionState.delete(r);
	rollbackTransactionState(i, t, n);
}
/** Nested rollback restores staged state and discards observers; savepoints wait for outer commit. */
function withSqlitePostCommitPublications(e, t) {
	const n = sqlPublicationAnchor(e);
	const r = e.isTransaction || pendingPublications.has(n);
	const i = r ? pendingPublications.get(n) : [];
	const a = r ? pendingTransactionState.get(n) : [];
	const o = i?.length ?? 0;
	const s = a?.length ?? 0;
	if (!r && i && a) {
		pendingPublications.set(n, i);
		pendingTransactionState.set(n, a);
	}
	let c;
	try {
		c = t();
	} catch (e) {
		i?.splice(o);
		rollbackTransactionState(a?.splice(s) ?? [], e);
		throw e;
	} finally {
		if (!r) {
			pendingPublications.delete(n);
			pendingTransactionState.delete(n);
		}
	}
	if (!r) installCommittedState(a ?? [], i ?? []);
	return c;
}
//#endregion
//#region src/infra/sqlite-reader-lifecycle.ts
const readerOwners = new AsyncContext(Symbol.for("openclaw.sqliteReaderOwners"));
const connections = resolveGlobalSingleton(Symbol.for("openclaw.sqliteReaderConnections"), () => ({
	nextId: 0,
	byDatabase: /* @__PURE__ */ new WeakMap(),
	byPath: /* @__PURE__ */ new Map(),
	finalizer: new FinalizationRegistry((e) => forgetConnection(e))
}));
/** The same Windows file can arrive with a namespaced or differently cased path. */
function sqliteReaderDatabasePathKey(e) {
	const t = path.resolve(e);
	return process.platform === "win32" ? normalizeWindowsPathForComparison(t) : t;
}
function boundedOperation(e) {
	return (e.trim() || "sqlite reader").slice(0, 120);
}
function captureSqliteReaderOwner() {
	const e = readerOwners.getStore();
	if (!e) return;
	const { timing: t, ...n } = e;
	return n;
}
/** Mutable diagnostic counters only; never source or write authority. */
function currentSqliteOperationTiming() {
	return readerOwners.getStore()?.timing;
}
function currentOwner(e, t) {
	const n = t ?? readerOwners.getStore();
	return {
		operation: boundedOperation(n?.operation ?? e),
		ownerKind: n?.ownerKind ?? (isMainThread ? "main" : "worker"),
		...n?.actorId !== void 0 ? { actorId: n.actorId } : {}
	};
}
function connectionFor(e) {
	let t = connections.byDatabase.get(e);
	if (!t) {
		const n = Date.now();
		const r = e.location();
		t = {
			id: ++connections.nextId,
			path: r ? sqliteReaderDatabasePathKey(r) : void 0,
			database: new WeakRef(e),
			owner: currentOwner("sqlite connection"),
			openedAtMs: n,
			readers: /* @__PURE__ */ new Map()
		};
		connections.byDatabase.set(e, t);
		connections.finalizer.register(e, t, t);
	}
	if (t.path) {
		const e = connections.byPath.get(t.path) ?? /* @__PURE__ */ new Map();
		e.set(t.id, t);
		connections.byPath.set(t.path, e);
	}
	return t;
}
/** Forget observations only; explicit reader custody belongs to its caller. */
function forgetConnection(e) {
	if (e.path) {
		const t = connections.byPath.get(e.path);
		t?.delete(e.id);
		if (t?.size === 0) connections.byPath.delete(e.path);
	}
}
/** Register weak metadata without replacing native methods or acquiring lifecycle custody. */
function registerSqliteReaderConnection(e) {
	if (e.isOpen) connectionFor(e);
}
function retainSqliteReader(e, t, n) {
	const r = connectionFor(e);
	const i = Date.now();
	const a = {
		...currentOwner(t, n),
		kind: "iterator",
		connectionId: r.id,
		threadId,
		startedAtMs: i,
		lastProgressAtMs: i
	};
	const o = Symbol(a.operation);
	const s = r.readers;
	s.set(o, a);
	return {
		progress() {
			if (s.has(o)) a.lastProgressAtMs = Date.now();
		},
		release() {
			s.delete(o);
		}
	};
}
function diagnostics(e) {
	const t = Date.now();
	return [...e].map(({ startedAtMs: e, lastProgressAtMs: n, ...r }) => Object.assign(r, {
		ageMs: Math.max(0, t - e),
		idleMs: Math.max(0, t - n)
	})).toSorted((e, t) => t.ageMs - e.ageMs).slice(0, 8);
}
/** Observed local activity is diagnostic evidence, not proof of which connection owns a WAL lock. */
function readSqliteReaderDiagnosticsForPath(e) {
	const t = sqliteReaderDatabasePathKey(e);
	const n = connections.byPath.get(t);
	const r = [];
	const i = [];
	const a = Date.now();
	for (const e of n?.values() ?? []) {
		const t = e.database.deref();
		if (!t?.isOpen) {
			forgetConnection(e);
			continue;
		}
		i.push(...e.readers.values());
		r.push({
			...e.owner,
			connectionId: e.id,
			threadId,
			ageMs: Math.max(0, a - e.openedAtMs),
			transactionOpen: t.isTransaction,
			trackedReaders: e.readers.size
		});
	}
	return {
		scope: "current-thread",
		blockingOwner: "unknown",
		nativeStatements: "unobserved",
		threadId,
		observedAtMs: a,
		connectionCount: r.length,
		readerCount: i.length,
		connections: r.toSorted((e, t) => t.trackedReaders - e.trackedReaders || Number(t.transactionOpen) - Number(e.transactionOpen)).slice(0, 8),
		activeReaders: diagnostics(i)
	};
}
//#endregion
//#region src/infra/bun-sqlite-library-probe.generated.ts
const BUN_SQLITE_LIBRARY_PROBE_SOURCE = "import{createRequire}from\"node:module\";try{const candidate=process.argv[2];if(!candidate||process.argv.length!==3){throw new Error(\"Expected one SQLite library path\")}const require2=createRequire(import.meta.url);const{Database}=require2(\"bun:sqlite\");Database.setCustomSQLite(candidate);const database=new Database(\":memory:\");let facts;try{facts=database.query(\"SELECT sqlite_version() AS version, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted\").get()}finally{database.close()}process.stdout.write(JSON.stringify({protocol:1,version:facts.version,extensionLoadingSupported:facts.omitted===0}))}catch(error){process.stdout.write(JSON.stringify({protocol:1,error:(error instanceof Error?error.message:String(error)).slice(0,512)}));process.exitCode=1}\n";
//#endregion
//#region src/infra/runtime-process-script-file.ts
/** The generated bootstrap binds this operation to declared, built program sources. */
function materializeRuntimeProcessScriptFile(e, t = {}) {
	const n = fsSync.mkdtempSync(path.join(t.parentDirectory ?? os.tmpdir(), "openclaw-script-"));
	const r = path.join(n, e.fileName);
	let i = false;
	const dispose = () => {
		if (i) return;
		try {
			fsSync.rmSync(n, {
				recursive: true,
				force: true
			});
			i = true;
		} catch (e) {
			process.emitWarning(`Runtime script cleanup failed at ${n}: ${e instanceof Error ? e.message : String(e)}`);
		}
	};
	try {
		fsSync.writeFileSync(r, e.source, {
			mode: 384,
			flag: "wx"
		});
		return {
			url: pathToFileURL(r),
			dispose
		};
	} catch (e) {
		dispose();
		throw e;
	}
}
//#endregion
//#region src/infra/bun-sqlite-library-probe.ts
/** Each candidate gets a fresh process because Bun's SQLite selection is one-shot. */
function probeBunSqliteLibrary(e) {
	const t = materializeRuntimeProcessScriptFile({
		fileName: runtimeProcessScriptEntrypoints.bunSqliteLibraryProbe.fileName,
		source: BUN_SQLITE_LIBRARY_PROBE_SOURCE
	});
	try {
		const n = fileURLToPath(t.url);
		const r = path.dirname(n);
		const i = path.join(r, "bunfig.toml");
		fsSync.writeFileSync(i, "", {
			mode: 384,
			flag: "wx"
		});
		const a = {};
		for (const e of [
			"SystemRoot",
			"SYSTEMROOT",
			"WINDIR",
			"TEMP",
			"TMP",
			"TMPDIR"
		]) if (process.env[e]) a[e] = process.env[e];
		const o = spawnSync(process.execPath, [
			"--no-install",
			"--no-env-file",
			`--config=${i}`,
			n,
			path.resolve(e)
		], {
			cwd: r,
			env: resolveRuntimeScriptEnv(a),
			encoding: "utf8",
			stdio: [
				"ignore",
				"pipe",
				"pipe"
			],
			timeout: 5e3,
			killSignal: "SIGKILL",
			maxBuffer: 4096
		});
		if (o.error) throw o.error;
		let s;
		try {
			s = JSON.parse(o.stdout);
		} catch {
			throw new Error("SQLite library probe returned invalid output");
		}
		if (typeof s !== "object" || s === null || Array.isArray(s) || !("protocol" in s) || s.protocol !== 1) throw new Error("SQLite library probe returned invalid output");
		if (o.status !== 0) throw new Error("error" in s && typeof s.error === "string" ? s.error.slice(0, 512) : `SQLite library probe failed (${o.signal ?? o.status})`);
		if (!("version" in s) || typeof s.version !== "string" || s.version.length > 64 || !("extensionLoadingSupported" in s) || typeof s.extensionLoadingSupported !== "boolean") throw new Error("SQLite library probe returned invalid output");
		return {
			version: s.version,
			extensionLoadingSupported: s.extensionLoadingSupported
		};
	} finally {
		t.dispose();
	}
}
//#endregion
//#region src/infra/sqlite-database-admission-key.ts
const SQLITE_DATABASE_ADMISSIONS_KEY = "openclaw.sqliteDatabaseAdmissions.v1";
//#endregion
//#region node-sqlite-capabilities.mjs
/** @param {string} value */
function isSqliteWalResetSafeVersion(e) {
	const t = /^(\d+)\.(\d+)\.(\d+)$/u.exec(e.trim());
	if (!t) return false;
	const [n, r, i] = t.slice(1).map(Number);
	if (![
		n,
		r,
		i
	].every(Number.isSafeInteger)) return false;
	return n > 3 || n === 3 && (r > 51 || r === 51 && i >= 3 || r === 50 && i >= 7 || r === 44 && i >= 6);
}
//#endregion
//#region src/infra/bun-sqlite-library.ts
const WORKER_SELECTION_KEY = "openclaw.bunSqliteLibrarySelection";
const WORKER_CAPABILITIES_KEY = "openclaw.sqliteRuntimeCapabilities";
const SQLITE_NATIVE_RUNTIME_ADMISSION_KEY = "openclaw.sqliteNativeRuntimeAdmission";
function createCapabilities(e) {
	let t;
	let n;
	let r = 0;
	const i = Object.freeze({
		explicitSqliteCloseReleasesNativeResources: false,
		decided: false,
		reason: "SQLite close capability has not been decided"
	});
	function decide(e) {
		if (!t) {
			t = Object.freeze(e);
			setEnvironmentData(WORKER_CAPABILITIES_KEY, t);
			if (t.explicitSqliteCloseReleasesNativeResources && r > 0) process.emitWarning(`SQLite close became capable after ${r} topology owners were created; those owners remain conservative`, { code: "SQLITE_EARLY_TOPOLOGY" });
		}
		return t;
	}
	function conservative(e) {
		return {
			explicitSqliteCloseReleasesNativeResources: false,
			decided: true,
			reason: e
		};
	}
	function settled() {
		if (t) return t;
		if (!process.versions.bun) return decide({
			explicitSqliteCloseReleasesNativeResources: true,
			decided: true,
			reason: "Node runtime"
		});
		if (process.platform === "win32") return decide(conservative("Bun Windows native-close conformance is not qualified"));
		if (!isMainThread) return decide({
			...i,
			reason: "Parent did not complete SQLite close admission",
			...getEnvironmentData(WORKER_CAPABILITIES_KEY)
		});
	}
	return {
		get() {
			return settled() ?? i;
		},
		capture() {
			const e = settled() ?? i;
			if (!e.decided) r += 1;
			return e.explicitSqliteCloseReleasesNativeResources;
		},
		initialize() {
			n ??= (async () => {
				e();
				const t = settled();
				if (t) return t;
				try {
					if (parseDiagnosticEnvFlags(process.env.OPENCLAW_DIAGNOSTICS).flags.some((e) => e.toLowerCase() === "sqlite.close.conservative")) return decide(conservative("SQLite close optimization disabled by internal diagnostic flag"));
					const { probeSqliteNativeClose: e } = await import("./bun-sqlite-close-probe-ByAfx4CH.mjs");
					return decide({
						...await e(),
						decided: true
					});
				} catch (e) {
					return decide(conservative(`SQLite close check failed: ${String(e)}`));
				}
			})();
			return n;
		}
	};
}
function selectLibrary(e) {
	const { Database: t } = createRequire(import.meta.url)("bun:sqlite");
	t.setCustomSQLite(e);
}
function createSelector() {
	let e;
	let t;
	return (n = {}) => {
		if (t) throw t;
		if (e) return e;
		const r = n.explicitPath ?? (process.env.OPENCLAW_SQLITE_LIBRARY?.trim() || void 0);
		if (!process.versions.bun || process.platform !== "darwin") {
			e = r ? {
				source: "runtime",
				ignoredOverride: "OPENCLAW_SQLITE_LIBRARY requires Bun on macOS"
			} : { source: "runtime" };
			return e;
		}
		const i = n.standaloneRoot ?? resolveStandaloneSidecarRoot();
		const a = r === void 0 && i !== void 0 ? posix.join(i, "lib/libsqlite3.dylib") : void 0;
		const o = process.env.HOMEBREW_PREFIX?.trim();
		const s = r !== void 0 ? [r] : [.../* @__PURE__ */ new Set([
			...a ? [a] : [],
			...o ? [posix.join(o, "opt/sqlite/lib/libsqlite3.dylib")] : [],
			"/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib",
			"/usr/local/opt/sqlite/lib/libsqlite3.dylib",
			"/opt/local/lib/libsqlite3.dylib"
		])];
		const c = [];
		for (const n of s) {
			const i = r !== void 0 ? "env" : n === a ? "bundled" : "discovered";
			let o;
			let s = true;
			try {
				try {
					o = probeBunSqliteLibrary(n);
				} catch (e) {
					s = existsSync(n);
					throw s ? e : new Error("missing file", { cause: e });
				}
				if (!isSqliteWalResetSafeVersion(o.version)) throw new Error(`SQLite version ${o.version} below the WAL safety floor`);
				if (!o.extensionLoadingSupported) throw new Error("built with SQLITE_OMIT_LOAD_EXTENSION");
			} catch (e) {
				if (r === void 0) {
					if (s || n === a) c.push(`${n} (${e instanceof Error ? e.message : String(e)})`);
					continue;
				}
				t = selectionError(n, e, i === "bundled");
				throw t;
			}
			try {
				selectLibrary(n);
			} catch (e) {
				t = selectionError(n, e, i === "bundled");
				throw t;
			}
			e = {
				source: i,
				path: n,
				version: o.version,
				extensionLoadingSupported: true
			};
			return e;
		}
		t = /* @__PURE__ */ new Error(`No supported SQLite library for Bun on macOS (${process.arch})` + (c.length > 0 ? `; unusable: ${c.join(", ")}` : "") + ". Apple's system SQLite fails OpenClaw's read-only database connections. " + (a ? "Rebuild or replace the complete standalone artifact to restore its bundled SQLite library. " : "") + `Install one with brew install sqlite, or set OPENCLAW_SQLITE_LIBRARY to a libsqlite3.dylib built for ${process.arch}.`);
		throw t;
	};
}
function selectionError(e, t, n = false) {
	const r = n ? "Rebuild or replace the complete standalone artifact (openclaw and runtime/), or set OPENCLAW_SQLITE_LIBRARY to a supported library." : "Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.";
	return new Error(`Cannot use ${n ? "bundled " : ""}SQLite library ${e}: ${t instanceof Error ? t.message : String(t)}. ${r}`, { cause: t });
}
function createRuntimeSelector() {
	const e = Boolean(process.versions.bun) && process.platform === "darwin";
	let t;
	if (e && !isMainThread) t = getEnvironmentData(WORKER_SELECTION_KEY);
	const n = createSelector();
	let r = false;
	return (i) => {
		const a = t ?? n(i);
		if (e && isMainThread && !r) {
			setEnvironmentData(WORKER_SELECTION_KEY, Object.freeze({ ...a }));
			r = true;
		}
		return a;
	};
}
function runtimeSelector() {
	return resolveGlobalSingleton(Symbol.for("openclaw.bunSqliteLibrarySelection"), createRuntimeSelector);
}
function capabilities() {
	const e = runtimeSelector();
	return e.capabilities ??= createCapabilities(e);
}
function getSqliteRuntimeCapabilities() {
	return capabilities().get();
}
/** A topology owner keeps this snapshot for placement and paired native retirement. */
function captureSqliteWorkerClosePolicy() {
	return capabilities().capture();
}
/** Retained supervisors forward the caller's current facts when creating each descendant. */
function captureSqliteWorkerEnvironmentData(e = getEnvironmentData(SQLITE_DATABASE_ADMISSIONS_KEY)) {
	return [
		[WORKER_SELECTION_KEY, ensureSqliteLibrarySelected()],
		[WORKER_CAPABILITIES_KEY, getSqliteRuntimeCapabilities()],
		[SQLITE_NATIVE_RUNTIME_ADMISSION_KEY, getEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY)],
		[SQLITE_DATABASE_ADMISSIONS_KEY, e],
		[PROCESS_MACHINE_IDENTITY_KEY, getEnvironmentData(PROCESS_MACHINE_IDENTITY_KEY)]
	];
}
/** Select once, before any SQLite open; shared across CLI and bundled SDK module graphs. */
function ensureSqliteLibrarySelected(e) {
	return runtimeSelector()(e);
}
//#endregion
//#region src/infra/sqlite-database-admission-delta.ts
function changedAdmissionEntries(e, t) {
	const n = /* @__PURE__ */ new Map();
	for (const [r, i] of e) if (t.get(r) !== i) n.set(r, i);
	return n;
}
function changedAdmissionWriteScopes(e, t) {
	const n = /* @__PURE__ */ new Map();
	e.forEach((e, r) => {
		if (e !== t[r]) e.forEach((e, i) => {
			if (t[r].get(i) !== e) n.set(i, e);
		});
	});
	return n;
}
//#endregion
//#region src/infra/sqlite-database-admission-record.ts
function readSqliteDatabaseAdmissionIdentity(e) {
	return `${e.dev}:${e.ino}:${readDatabaseIdentityBirthtime(e)}`;
}
const SqliteDatabaseGenerationSlot = {
	schemaRevision: 0,
	factRevision: 1,
	publicationRevision: 2,
	retired: 3,
	writeRevision: 4,
	hostRevision: 5,
	unscopedWriteRevision: 6,
	writeScopeRevision: 7,
	sealPresent: 8
};
const SQLITE_DATABASE_GENERATION_LENGTH = Object.keys(SqliteDatabaseGenerationSlot).length;
const decodedValue = Symbol.for("openclaw.sqliteDatabaseAdmission.decodedValue");
function readSqliteDatabaseAdmissionFact(e, t) {
	e[decodedValue] ??= { value: t.read ? t.read(e.value) : e.value };
	return e[decodedValue].value;
}
function admitSqliteDatabaseFactValue(e, t) {
	const n = { value: t };
	readSqliteDatabaseAdmissionFact(n, e);
	return n;
}
const MAX_WRITE_SCOPE_BYTES = 1048576;
const scopeRetention = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseWriteScopeRetention"), () => /* @__PURE__ */ new WeakMap());
const writeScopeBytes = (e) => e.length * 2 + 256;
/** Idle receipts cache freshness; active effect guards retain their exact shared cells. */
function retainSqliteDatabaseWriteScope(e, t, n) {
	const r = e.writeScopes;
	let i = scopeRetention.get(r);
	if (!i) {
		i = {
			bytes: [...r.keys()].reduce((e, t) => e + writeScopeBytes(t), 0),
			retired: /* @__PURE__ */ new Set()
		};
		scopeRetention.set(r, i);
	}
	if (!r.delete(t)) i.bytes += writeScopeBytes(t);
	r.set(t, n);
	pruneSqliteDatabaseWriteScopes(e);
}
/** Active effect scopes may exceed the idle budget until their final release. */
function pruneSqliteDatabaseWriteScopes(e) {
	const t = scopeRetention.get(e.writeScopes);
	if (t.bytes <= MAX_WRITE_SCOPE_BYTES) return false;
	let n = false;
	for (const [r, i] of e.writeScopes) {
		if (Atomics.compareExchange(i.state, 2, 0, -1) > 0 && Atomics.load(i.state, 1) === 0) continue;
		Atomics.store(i.state, 1, 1);
		advanceSqliteDatabaseGeneration(e, "writeScopeRevision");
		e.writeScopes.delete(r);
		t.bytes -= writeScopeBytes(r);
		t.retired.add(r);
		n = true;
		if (t.bytes <= MAX_WRITE_SCOPE_BYTES) break;
	}
	return n;
}
function readSqliteDatabaseAdmissions(e) {
	return Array.isArray(e) ? e : void 0;
}
function isSqliteDatabaseAdmissionRetired(e) {
	return readSqliteDatabaseGeneration(e, "retired") !== 0;
}
function isSqliteDatabaseAdmissionFactCurrent(e, t) {
	return !isSqliteDatabaseAdmissionRetired(e) && Atomics.load(new Int32Array(t.current), 0) === 1 && t.revision === readSqliteDatabaseFactRevision(e, t.schemaDependent);
}
function hasSqliteDatabaseSchemaAdmission(e) {
	const t = e?.facts.get("sqlite-schema");
	return Boolean(e && t && isSqliteDatabaseAdmissionFactCurrent(e, t));
}
function readSqliteDatabaseFactRevision(e, t) {
	return readSqliteDatabaseGeneration(e, t ? "schemaRevision" : "factRevision");
}
function readSqliteDatabaseGeneration(e, t) {
	return Atomics.load(new Int32Array(e.generation), SqliteDatabaseGenerationSlot[t]);
}
function advanceSqliteDatabaseGeneration(e, t) {
	return Atomics.add(new Int32Array(e.generation), SqliteDatabaseGenerationSlot[t], 1);
}
function publishSqliteDatabaseFact(e, t, n, r, i) {
	if (isSqliteDatabaseAdmissionRetired(e) || r !== readSqliteDatabaseFactRevision(e, t.schemaDependent)) return false;
	if (t.writer === "host") advanceSqliteDatabaseGeneration(e, "hostRevision");
	const a = e.facts.get(t.name);
	if (a) Atomics.store(new Int32Array(a.current), 0, 0);
	const o = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
	Atomics.store(new Int32Array(o), 0, 1);
	e.facts.set(t.name, {
		...n,
		revision: r,
		schemaDependent: t.schemaDependent === true,
		lifetime: t.lifetime,
		publication: i,
		current: o
	});
	advanceSqliteDatabaseGeneration(e, "publicationRevision");
	return true;
}
function revokeSqliteDatabaseAdmissionFacts(e) {
	if (!e) return;
	for (const t of e.facts.values()) Atomics.store(new Int32Array(t.current), 0, 0);
	advanceSqliteDatabaseGeneration(e, "schemaRevision");
	advanceSqliteDatabaseGeneration(e, "factRevision");
}
const EMPTY_WRITE_SCOPE_BUCKETS = Array.from({ length: 128 }, () => /* @__PURE__ */ new Map());
function snapshotWriteScopes(e, t = EMPTY_WRITE_SCOPE_BUCKETS, n) {
	let r = t;
	const i = scopeRetention.get(e);
	const visit = (n, a) => {
		let o = 0;
		for (let e = 0; e < a.length; e++) o = o * 31 + a.charCodeAt(e) | 0;
		const s = o & EMPTY_WRITE_SCOPE_BUCKETS.length - 1;
		const c = !n || Atomics.load(n.state, 1) !== 0;
		if (c) {
			if (e.delete(a) && i) i.bytes -= writeScopeBytes(a);
		}
		if (c ? !t[s].has(a) : t[s].get(a) === n) return;
		if (r === t) r = t.slice();
		if (r[s] === t[s]) r[s] = new Map(t[s]);
		if (c) r[s].delete(a);
		else r[s].set(a, n);
	};
	if (n) for (const t of n) visit(e.get(t), t);
	else e.forEach(visit);
	for (const t of i?.retired ?? []) visit(e.get(t), t);
	i?.retired.clear();
	return r;
}
function createSqliteDatabaseAdmissionCursor() {
	return {
		revision: -1,
		records: /* @__PURE__ */ new WeakMap()
	};
}
var SqliteDatabaseAdmissionRegistry = class {
	constructor() {
		this.records = /* @__PURE__ */ new Map();
		this.exchangeCursor = createSqliteDatabaseAdmissionCursor();
		this.locations = /* @__PURE__ */ new Map();
		this.published = /* @__PURE__ */ new Map();
		this.scopeSweeps = /* @__PURE__ */ new WeakMap();
		this.descriptors = /* @__PURE__ */ new Map();
		this.revision = 0;
		this.retainProcessFacts = true;
	}
	useConnectionScopedFacts() {
		this.retainProcessFacts = false;
	}
	changeReferences(e, t) {
		let n = e.references.get(threadId);
		if (!n) {
			n = new SharedArrayBuffer(2 * Int32Array.BYTES_PER_ELEMENT);
			e.references.set(threadId, n);
		}
		if (Atomics.add(new Int32Array(n), 0, t) + t !== (t === 1 ? 1 : 0)) return false;
		if (t === -1) this.retireUnreferenced(e);
		this.publish(e);
		return true;
	}
	retireUnreferenced(e) {
		if (threadId !== 0 || isSqliteDatabaseAdmissionRetired(e) || [...e.references.values()].some((e) => Atomics.load(new Int32Array(e), 0) > 0)) return;
		for (const [t, n] of e.facts) if (!this.retainProcessFacts || n.lifetime !== "process" || !isSqliteDatabaseAdmissionFactCurrent(e, n)) e.facts.delete(t);
		const t = this.descriptors.get(e.identity);
		if (t) t.facts = e.facts;
		Atomics.compareExchange(new Int32Array(e.generation), SqliteDatabaseGenerationSlot.retired, 0, 2);
		e.writeScopes.clear();
	}
	releaseWorker(e) {
		const t = /* @__PURE__ */ new Map();
		for (const n of this.records.values()) {
			const r = e > 0 ? n.references.get(e) : void 0;
			if (!r) continue;
			Atomics.store(new Int32Array(r), 0, -1);
			this.retireUnreferenced(n);
			t.set(n, void 0);
		}
		if (t.size > 0) this.publish(t);
	}
	observeLocation(e, t) {
		const n = normalizeDatabasePath(path.resolve(e));
		if (t === void 0) this.locations.delete(n);
		else this.locations.set(n, t);
	}
	forLocation(e) {
		const t = this.locations.get(normalizeDatabasePath(path.resolve(e)));
		const n = t === void 0 ? void 0 : this.records.get(t);
		return n && !isSqliteDatabaseAdmissionRetired(n) ? n : void 0;
	}
	hasSchemaAdmissionForIdentity(e) {
		if (!e.key.startsWith("file:") || e.birthtime === void 0) return false;
		const t = `${e.key.slice(5)}:${e.birthtime}`;
		return hasSqliteDatabaseSchemaAdmission(this.records.get(t));
	}
	forget(e) {
		this.records.delete(e);
		this.published.delete(e);
		for (const [t, n] of this.locations) if (n === e) this.locations.delete(t);
	}
	/** Physical custody survives a cancelled caller without publishing native authority. */
	retainDescriptorCustody(e, t) {
		const n = readSqliteDatabaseAdmissionIdentity(t);
		const r = this.descriptors.get(n);
		if (r && r.descriptor !== e) (r.additionalDescriptors ??= /* @__PURE__ */ new Set()).add(e);
		if (!r) this.descriptors.set(n, {
			descriptor: e,
			file: t,
			facts: /* @__PURE__ */ new Map()
		});
	}
	retainDescriptor(e, t, n) {
		const r = this.descriptors.get(readSqliteDatabaseAdmissionIdentity(n));
		const i = {
			identity: readSqliteDatabaseAdmissionIdentity(n),
			physicalIdentity: {
				key: `file:${n.dev}:${n.ino}`,
				birthtime: readDatabaseIdentityBirthtime(n)
			},
			location: e,
			descriptor: t,
			descriptorOwner: 0,
			generationId: randomUUID(),
			generation: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * SQLITE_DATABASE_GENERATION_LENGTH),
			writeScopes: /* @__PURE__ */ new Map(),
			writeScopeRevision: 0,
			references: /* @__PURE__ */ new Map(),
			facts: new Map([...r?.facts ?? []].filter(([, e]) => Atomics.load(new Int32Array(e.current), 0) === 1).map(([e, t]) => [e, {
				...t,
				revision: 0
			}]))
		};
		this.records.set(i.identity, i);
		const a = r?.descriptor === t ? r : {
			descriptor: t,
			file: n,
			facts: /* @__PURE__ */ new Map()
		};
		a.file = n;
		a.facts = /* @__PURE__ */ new Map();
		this.descriptors.set(i.identity, a);
		this.observeLocation(e, i.identity);
		this.publish(i);
		return i;
	}
	/** Only the joined lifecycle owner may release a retained descriptor. */
	retireDescriptor(e, t) {
		const n = this.records.get(e);
		const r = this.descriptors.get(e);
		const i = r?.descriptor ?? n?.descriptor;
		if (i === void 0) return false;
		const a = fsSync.fstatSync(i, { bigint: true });
		if (a.nlink > 1n || t.requireSoleDescriptor && !isSoleDatabaseFileDescriptor(i, a, r?.additionalDescriptors)) return false;
		if (n) Atomics.store(new Int32Array(n.generation), SqliteDatabaseGenerationSlot.retired, 1);
		fsSync.closeSync(i);
		r?.additionalDescriptors?.forEach((e) => fsSync.closeSync(e));
		this.descriptors.delete(e);
		this.forget(e);
		this.publish();
		return true;
	}
	publish(e, t) {
		const n = e instanceof Map;
		if (e && !n && this.records.get(e.identity) !== e) return;
		for (const r of this.records.values()) {
			if (isSqliteDatabaseAdmissionRetired(r)) {
				if (readSqliteDatabaseGeneration(r, "retired") === 1) {
					this.descriptors.get(r.identity)?.additionalDescriptors?.forEach(fsSync.closeSync);
					this.descriptors.delete(r.identity);
				}
				this.forget(r.identity);
				continue;
			}
			if (e && e !== r && !(n && e.has(r))) continue;
			let i = e === r || n;
			for (const [e, t] of r.references) if (Atomics.load(new Int32Array(t), 0) < 0) {
				r.references.delete(e);
				i = true;
			}
			const a = this.published.get(r.identity);
			const o = readSqliteDatabaseGeneration(r, "writeScopeRevision");
			const s = a && e ? n ? e.get(r) : t : void 0;
			const c = s === void 0 && this.scopeSweeps.get(r) !== o;
			const l = snapshotWriteScopes(r.writeScopes, a?.writeScopes, s ?? (c ? void 0 : []));
			if (c) this.scopeSweeps.set(r, o);
			i ||= l !== a?.writeScopes;
			if (!i) continue;
			if (threadId === 0) r.writeScopeRevision = readSqliteDatabaseGeneration(r, "writeScopeRevision");
			const { writeScopes: u, ...d } = r;
			const f = {
				...d,
				facts: new Map(r.facts),
				references: new Map(r.references),
				hostRevision: threadId === 0 ? readSqliteDatabaseGeneration(r, "hostRevision") : r.hostRevision
			};
			const p = {
				...f,
				writeScopes: l.filter((e) => e.size > 0)
			};
			this.published.set(r.identity, {
				metadata: f,
				writeScopes: l,
				snapshot: p
			});
		}
		this.revision++;
		setEnvironmentData(SQLITE_DATABASE_ADMISSIONS_KEY, [...this.published.values()].map((e) => e.snapshot));
	}
	capture(e, t) {
		const n = t ? /* @__PURE__ */ new Set([...t.admissions?.map((e) => e.identity) ?? [], ...t.location === void 0 ? [] : [this.forLocation(t.location)?.identity].filter((e) => e !== void 0)]) : void 0;
		if (!n && !e) this.publish();
		if (!n && e?.revision === this.revision) return [];
		const r = n ? [...n].flatMap((e) => {
			const t = this.published.get(e);
			return t && !isSqliteDatabaseAdmissionRetired(t.snapshot) ? [t] : [];
		}) : [...this.published.values()];
		if (!e) return r.map((e) => e.snapshot);
		if (!n) e.revision = this.revision;
		return r.flatMap((t) => {
			const n = e.records.get(t.metadata.generation);
			if (n === t) return [];
			e.records.set(t.metadata.generation, t);
			return [n ? {
				...t.metadata,
				facts: changedAdmissionEntries(t.metadata.facts, n.metadata.facts),
				writeScopes: [changedAdmissionWriteScopes(t.writeScopes, n.writeScopes)],
				references: changedAdmissionEntries(t.metadata.references, n.metadata.references)
			} : t.snapshot];
		});
	}
	captureExchange(e, t) {
		return t && typeof t !== "string" && isSqliteDatabaseAdmissionRetired(t) ? [{
			...t,
			facts: /* @__PURE__ */ new Map(),
			writeScopes: [],
			references: /* @__PURE__ */ new Map()
		}] : this.capture(this.exchangeCursor, e);
	}
	resetExchangeCursor() {
		this.exchangeCursor = createSqliteDatabaseAdmissionCursor();
	}
	install(e) {
		const t = /* @__PURE__ */ new Map();
		for (const n of e) {
			let e = this.records.get(n.identity);
			if (n.descriptorOwner !== 0 || isSqliteDatabaseAdmissionRetired(n)) {
				if (e && isSqliteDatabaseAdmissionRetired(e)) t.set(e, void 0);
				continue;
			}
			let r = false;
			if (e && isSqliteDatabaseAdmissionRetired(e)) e = void 0;
			if (!e) {
				e = {
					...n,
					facts: new Map(n.facts),
					writeScopes: /* @__PURE__ */ new Map(),
					references: new Map(n.references),
					hostRevision: void 0
				};
				this.records.set(n.identity, e);
				this.observeLocation(n.location, n.identity);
				r = true;
			} else if (e.generationId !== n.generationId) continue;
			if (!e.cleanCloseRefusal && n.cleanCloseRefusal) {
				e.cleanCloseRefusal = n.cleanCloseRefusal;
				r = true;
			}
			for (const [t, i] of n.facts) if (isSqliteDatabaseAdmissionFactCurrent(n, i) && e.facts.get(t)?.publication !== i.publication) {
				e.facts.set(t, i);
				r = true;
			}
			const i = t.get(e) ?? [];
			for (const t of n.writeScopes) for (const [n, a] of t) {
				if (Atomics.load(a.state, 1) !== 0) continue;
				const t = e.writeScopes.get(n);
				if (t?.identity === a.identity || threadId === 0 && t && Atomics.load(t.state, 1) === 0) continue;
				if (threadId === 0) {
					const t = advanceSqliteDatabaseGeneration(e, "writeScopeRevision");
					if (this.scopeSweeps.get(e) === t) this.scopeSweeps.set(e, t + 1 | 0);
				}
				retainSqliteDatabaseWriteScope(e, n, a);
				i.push(n);
				r = true;
			}
			const a = readSqliteDatabaseGeneration(e, "writeScopeRevision");
			if (threadId === 0 || n.writeScopeRevision === a) {
				r ||= e.writeScopeRevision !== a;
				e.writeScopeRevision = a;
			}
			for (const [t, i] of n.references) if (!e.references.has(t) && Atomics.load(new Int32Array(i), 0) >= 0) {
				e.references.set(t, i);
				r = true;
			}
			if (threadId !== 0 && n.hostRevision !== void 0 && n.hostRevision !== e.hostRevision && n.hostRevision === readSqliteDatabaseGeneration(e, "hostRevision")) {
				e.hostRevision = n.hostRevision;
				r = true;
			}
			this.retireUnreferenced(e);
			if (r || isSqliteDatabaseAdmissionRetired(e)) t.set(e, i.length > 0 ? i : void 0);
		}
		if (t.size > 0) this.publish(t);
		return t.size > 0;
	}
};
//#endregion
//#region src/infra/sqlite-database-admission-context.ts
const state$2 = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseAdmissions"), () => ({
	registry: new SqliteDatabaseAdmissionRegistry(),
	descriptorPreparation: Promise.resolve(),
	connections: /* @__PURE__ */ new WeakMap(),
	openedIdentities: /* @__PURE__ */ new WeakMap(),
	unproven: /* @__PURE__ */ new WeakSet(),
	suspended: /* @__PURE__ */ new WeakSet(),
	local: /* @__PURE__ */ new WeakMap(),
	rolledBack: /* @__PURE__ */ new WeakSet(),
	dataWriters: /* @__PURE__ */ new WeakMap(),
	localWriteRevisions: /* @__PURE__ */ new WeakMap(),
	writeListeners: /* @__PURE__ */ new WeakMap(),
	ddlRevisions: /* @__PURE__ */ new WeakMap(),
	schemaDirty: /* @__PURE__ */ new WeakSet(),
	localSchemaRevisions: /* @__PURE__ */ new Map(),
	misses: /* @__PURE__ */ new WeakMap(),
	exchange: new AsyncLocalStorage(),
	exchanging: false,
	publication: 0
}));
function captureSqliteDatabaseAdmissions(e, t) {
	return state$2.registry.capture(e, t);
}
function installSqliteDatabaseAdmissions(e) {
	state$2.registry.install(e);
}
function exchangeSqliteDatabaseAdmission(e, t, n = false, r) {
	const i = state$2.exchange.getStore();
	if (!i || state$2.exchanging) return;
	state$2.exchanging = true;
	try {
		const a = typeof e === "string" ? { location: e } : { admissions: [e] };
		const o = state$2.registry.captureExchange(a, e);
		if (n && o.length === 0) return;
		installSqliteDatabaseAdmissions(i(o, typeof e === "string" ? e : void 0, t, r));
	} catch (e) {
		state$2.registry.resetExchangeCursor();
		throw e;
	} finally {
		state$2.exchanging = false;
	}
}
function withSqliteDatabaseAdmissionExchange(e, t) {
	return state$2.exchange.run(e, t);
}
/** Unsupported worker hosts retain native validation instead of waiting for unpublished facts. */
function canShareSqliteDatabaseAdmissions() {
	return threadId === 0 || state$2.exchange.getStore() !== void 0;
}
const inherited = readSqliteDatabaseAdmissions(getEnvironmentData(SQLITE_DATABASE_ADMISSIONS_KEY));
if (inherited) {
	installSqliteDatabaseAdmissions(inherited);
	state$2.registry.captureExchange();
}
//#endregion
//#region src/infra/sqlite-clean-close-seal.ts
const fullVerificationIntervalMs = 6048e5;
function fileFields(e) {
	return {
		dev: e.dev.toString(),
		ino: e.ino.toString(),
		birthtime: readDatabaseIdentityBirthtime(e),
		size: e.size.toString(),
		mtimeNs: e.mtimeNs.toString()
	};
}
function checksum(e) {
	return createHash("sha256").update(e).digest("hex").slice(0, 16);
}
function hasNoJournal(e) {
	return ["-wal", "-journal"].every((t) => {
		try {
			const n = fsSync.statSync(`${e}${t}`, { bigint: true });
			return n.isFile() && n.size === 0n;
		} catch (e) {
			if (hasErrnoCode(e, "ENOENT")) return true;
			throw e;
		}
	});
}
/** The caller supplies fstat from its retained descriptor; closing a new one can release SQLite locks. */
function readSqliteCleanCloseSeal(e, t, n) {
	const refuse = (e) => {
		n?.(e);
	};
	try {
		const n = `${e}.seal`;
		if (!fsSync.lstatSync(n).isFile()) return refuse("malformed-proof");
		return decodeSqliteCleanCloseSeal(fsSync.readFileSync(n, "utf8"), t, hasNoJournal(e), refuse);
	} catch (e) {
		return refuse(hasErrnoCode(e, "ENOENT") ? "no-proof" : "malformed-proof");
	}
}
function decodeSqliteCleanCloseSeal(e, t, n, r) {
	const i = JSON.parse(e);
	if (!isRecord(i) || typeof i.payload !== "string" || i.checksum !== checksum(i.payload)) return r("malformed-proof");
	const a = JSON.parse(i.payload);
	if (!isRecord(a) || a.version !== 1 || typeof a.schemaIdentity !== "string" || typeof a.verifiedAt !== "number" || !Number.isSafeInteger(a.verifiedAt) || !("facts" in a) || !t.isFile()) return r("malformed-proof");
	const o = Date.now() - a.verifiedAt;
	if (o < 0 || o > fullVerificationIntervalMs) return r("expired-proof");
	if (!Object.entries(fileFields(t)).every(([e, t]) => a[e] === t)) return r("file-mismatch");
	if (!n) return r("journal-present");
	return {
		schemaIdentity: a.schemaIdentity,
		verifiedAt: a.verifiedAt,
		facts: a.facts,
		...a.identity === void 0 ? {} : { identity: a.identity }
	};
}
async function readSqliteCleanCloseSealAsync(e, t, n) {
	const refuse = (e) => {
		n?.(e);
	};
	try {
		const n = e + ".seal";
		if (!(await fsSync.promises.lstat(n)).isFile()) return refuse("malformed-proof");
		return decodeSqliteCleanCloseSeal(await fsSync.promises.readFile(n, "utf8"), t, (await Promise.all(["-wal", "-journal"].map(async (t) => {
			try {
				const n = await fsSync.promises.stat(e + t, { bigint: true });
				return n.isFile() && n.size === 0n;
			} catch (e) {
				if (hasErrnoCode(e, "ENOENT")) return true;
				throw e;
			}
		}))).every(Boolean), refuse);
	} catch (e) {
		return refuse(hasErrnoCode(e, "ENOENT") ? "no-proof" : "malformed-proof");
	}
}
function invalidateSqliteCleanCloseSeal(e) {
	try {
		fsSync.unlinkSync(`${e}.seal`);
	} catch (e) {
		if (!hasErrnoCode(e, "ENOENT")) throw e;
	}
}
function writeSqliteCleanCloseSeal(e, t, n, r) {
	try {
		const i = `${e}.seal`;
		const a = fsSync.lstatSync(i, { throwIfNoEntry: false });
		if (!n.isFile() || a && !a.isFile() || !hasNoJournal(e)) {
			invalidateSqliteCleanCloseSeal(e);
			return false;
		}
		const o = JSON.stringify({
			version: 1,
			schemaIdentity: t,
			...fileFields(n),
			verifiedAt: r.verifiedAt,
			facts: r.facts,
			identity: r.identity
		});
		fsSync.writeFileSync(i, JSON.stringify({
			payload: o,
			checksum: checksum(o)
		}));
		return true;
	} catch {
		try {
			invalidateSqliteCleanCloseSeal(e);
		} catch {}
		return false;
	}
}
//#endregion
//#region src/infra/sqlite-database-admission-descriptor.ts
/** Resolve SQLite's absolute URLs and encoded filename form at filesystem boundaries. */
function resolveSqliteDatabaseFilePath(e) {
	if (!e.startsWith("file:")) return e;
	const [t = ""] = e.slice(5).split(/[?#]/u, 1);
	return t.startsWith("/") ? fileURLToPath(e) : decodeURIComponent(t);
}
/** Physical admission uses the existing host registry and its single restart-proof owner. */
function createSqliteDatabaseDescriptorOwner(e) {
	/** The caller owns permission to create; ordinary turn preparation observes absence only. */
	function prepareSqliteDatabaseAdmissionAsync(t) {
		const n = resolveAdmissionTarget(t.location, t.create !== void 0);
		if (!n) return Promise.resolve(void 0);
		const { filename: r, create: i } = n;
		let a = t.identity;
		const prepare = async () => {
			t.assertCurrent();
			const n = a ?? await inspectDatabasePathIdentity(r);
			a = void 0;
			t.assertCurrent();
			if (!n) return;
			if (t.expectedIdentity && (n.key !== t.expectedIdentity.key || t.expectedIdentity.birthtime !== void 0 && n.birthtime !== t.expectedIdentity.birthtime)) throw new Error("SQLite Worker path no longer matches its borrowed native owner");
			const o = n.key.startsWith("file:");
			const s = !o && i ? t.create : void 0;
			if (!o && !s) return n;
			const c = `${n.key.slice(5)}:${n.birthtime}`;
			if (t.observedLocation && t.observedLocation.identity !== c) throw new Error("SQLite database changed while retaining its admission identity");
			if (threadId !== 0) {
				if (s) throw new Error("SQLite descriptor creation belongs to the host");
				pathAdmission(r, c);
				t.assertCurrent();
				return n;
			}
			const l = o ? state$2.registry.descriptors.get(c) : void 0;
			if (l) {
				assertDatabaseFileIdentity(l.file, n);
				if (retainPreparedSqliteDatabaseAdmissionLocation(r, void 0, {
					identity: c,
					canonicalPath: n.canonicalPath
				})) return n;
			}
			let u;
			let d;
			if (l) {
				u = l.descriptor;
				d = l.file;
			} else {
				if (s) await s.authorize(n.canonicalPath);
				t.assertCurrent();
				const e = s ? createDeferredCore() : void 0;
				if (e) s?.retain(e.promise);
				let i;
				try {
					i = await new Promise((e, t) => {
						fsSync.open(r, s ? "wx" : "r", 420, (n, r) => n ? t(n) : e(r));
					});
					u = i;
					d = await new Promise((e, t) => {
						fsSync.fstat(u, { bigint: true }, (n, r) => n ? t(n) : e(r));
					});
					if (o) assertDatabaseFileIdentity(d, n);
					state$2.registry.retainDescriptorCustody(u, d);
					e?.resolve();
				} catch (t) {
					if (i === void 0) {
						e?.resolve();
						if (s && hasErrnoCode(t, "EEXIST")) return prepare();
					} else e?.reject(t);
					throw t;
				}
			}
			const f = o ? n : {
				key: `file:${d.dev}:${d.ino}`,
				canonicalPath: n.canonicalPath,
				birthtime: readDatabaseIdentityBirthtime(d)
			};
			let p;
			const m = o ? await readSqliteCleanCloseSealAsync(n.canonicalPath, d, (e) => {
				p = e;
			}) : void 0;
			const h = await inspectDatabasePathIdentity(r);
			if (!h || h.key !== f.key || h.birthtime !== f.birthtime || h.canonicalPath !== f.canonicalPath) throw new Error("SQLite database changed identity during admission");
			t.assertCurrent();
			const g = state$2.registry.records.get(readSqliteDatabaseAdmissionIdentity(d));
			const _ = g && !isSqliteDatabaseAdmissionRetired(g) ? g : state$2.registry.retainDescriptor(f.canonicalPath, state$2.registry.descriptors.get(readSqliteDatabaseAdmissionIdentity(d))?.descriptor ?? u, d);
			state$2.registry.observeLocation(r, _.identity);
			if (o) e.load(_, {
				seal: m,
				refusal: p
			});
			else e.markLoaded(_);
			return f;
		};
		const o = state$2.descriptorPreparation.then(prepare);
		state$2.descriptorPreparation = o.then(() => {}, () => {});
		return o;
	}
	/** Consume already prepared physical custody without beginning another filesystem operation. */
	function retainPreparedSqliteDatabaseAdmissionLocation(t, n, r) {
		const i = !r && state$2.registry.forLocation(t);
		const a = i && state$2.registry.descriptors.get(i.identity);
		if (i && n?.birthtime !== void 0 && i.physicalIdentity.key === n.key && i.physicalIdentity.birthtime === n.birthtime && a && a.descriptor === i.descriptor && e.isLoaded(a)) {
			e.load(i);
			return true;
		}
		const o = r && state$2.registry.descriptors.get(r.identity);
		if (r && o && e.isLoaded(o)) {
			if (n) assertDatabaseFileIdentity(o.file, n);
			const i = state$2.registry.records.get(r.identity);
			const a = i && !isSqliteDatabaseAdmissionRetired(i) ? i : state$2.registry.retainDescriptor(r.canonicalPath, o.descriptor, o.file);
			state$2.registry.observeLocation(t, a.identity);
			e.markLoaded(a);
			return true;
		}
		return false;
	}
	/** Identity descriptors stay open for the process: closing one can release SQLite's POSIX locks. */
	function retainSqliteDatabaseAdmissionLocation(t, n, r) {
		if (retainPreparedSqliteDatabaseAdmissionLocation(t, n, r)) return;
		const i = fsSync.statSync(t, { bigint: true });
		if (!i.isFile()) return;
		const a = readSqliteDatabaseAdmissionIdentity(i);
		const o = state$2.registry.records.get(a);
		if (o && !isSqliteDatabaseAdmissionRetired(o)) {
			state$2.registry.observeLocation(t, a);
			e.load(o);
			return;
		}
		if (threadId !== 0) return;
		const s = state$2.registry.descriptors.get(a)?.descriptor ?? fsSync.openSync(t, "r");
		const c = fsSync.fstatSync(s, { bigint: true });
		if (!c.isFile() || readSqliteDatabaseAdmissionIdentity(c) !== a) throw new Error("SQLite database changed while retaining its admission identity");
		const l = state$2.registry.retainDescriptor(fsSync.realpathSync.native(t), s, c);
		state$2.registry.observeLocation(t, l.identity);
		e.load(l);
	}
	function pathAdmission(t, n) {
		try {
			let r = state$2.registry.forLocation(t);
			if (!r) {
				let e = n;
				if (e === void 0 && threadId !== 0) {
					const n = fsSync.statSync(t, { bigint: true });
					if (!n.isFile()) return;
					e = readSqliteDatabaseAdmissionIdentity(n);
				}
				exchangeSqliteDatabaseAdmission(t, void 0, false, e !== void 0 && threadId !== 0 ? {
					identity: e,
					canonicalPath: fsSync.realpathSync.native(t)
				} : void 0);
				r = state$2.registry.forLocation(t);
			}
			if (r) {
				e.load(r);
				return r;
			}
			retainSqliteDatabaseAdmissionLocation(t);
			return state$2.registry.forLocation(t);
		} catch (e) {
			if (hasErrnoCode(e, "ENOENT")) return;
			throw e;
		}
	}
	function resolveAdmissionTarget(e, t) {
		let n = e;
		let r = t;
		if (!n || n === ":memory:") return;
		if (n.startsWith("file:")) {
			const e = new URL(n);
			if (e.searchParams.get("mode") === "memory") return;
			if (["ro", "rw"].includes(e.searchParams.get("mode") ?? "")) r = false;
			n = resolveSqliteDatabaseFilePath(n);
			if (!n || n === ":memory:") return;
		}
		return {
			filename: n,
			create: r
		};
	}
	/** Bracket native open so a pathname swap cannot lend the replacement file's admission. */
	function prepareSqliteDatabaseAdmission(t, n = {}) {
		const r = resolveAdmissionTarget(t, n.create);
		if (!r) return;
		const { filename: i, create: a } = r;
		try {
			const e = fsSync.statSync(i, { bigint: true });
			if (!e.isFile()) {
				state$2.registry.observeLocation(i, void 0);
				return;
			}
			const t = readSqliteDatabaseAdmissionIdentity(e);
			state$2.registry.observeLocation(i, t);
			return t;
		} catch (t) {
			if (hasErrnoCode(t, "ENOENT")) {
				state$2.registry.observeLocation(i, void 0);
				if (!a) return;
				if (threadId !== 0) {
					const e = state$2.exchange.getStore() !== void 0;
					exchangeSqliteDatabaseAdmission(i, true);
					const n = prepareSqliteDatabaseAdmission(i);
					if (e && n === void 0) throw new Error(`SQLite worker file creation requires host authority: ${i}`, { cause: t });
					return n;
				}
				let n;
				try {
					n = fsSync.openSync(i, "wx", 420);
				} catch (e) {
					if (hasErrnoCode(e, "EEXIST")) return prepareSqliteDatabaseAdmission(i);
					throw e;
				}
				const r = fsSync.fstatSync(n, { bigint: true });
				const o = state$2.registry.retainDescriptor(fsSync.realpathSync.native(i), n, r);
				e.markLoaded(o);
				if (prepareSqliteDatabaseAdmission(i) !== o.identity) throw new Error("SQLite database changed identity during file creation", { cause: t });
				return o.identity;
			}
			throw t;
		}
	}
	return {
		prepareSqliteDatabaseAdmissionAsync,
		retainSqliteDatabaseAdmissionLocation,
		prepareSqliteDatabaseAdmission,
		pathAdmission
	};
}
//#endregion
//#region src/infra/sqlite-native-admission.ts
const state$1 = resolveGlobalSingleton(Symbol.for("openclaw.sqliteNativeAdmissions"), () => ({ operations: /* @__PURE__ */ new WeakMap() }));
function getSqliteNativeAdmissionFacts(e) {
	return state$1.operations.get(e)?.facts;
}
/** Callback-local facts may describe an implicit statement transaction that can still abort. */
function beginSqliteDatabaseAdmissionOperation(e) {
	const t = state$1.operations.get(e) ?? {
		depth: 0,
		facts: /* @__PURE__ */ new Map()
	};
	t.depth += 1;
	state$1.operations.set(e, t);
	return () => {
		t.depth -= 1;
		if (t.depth === 0) state$1.operations.delete(e);
	};
}
//#endregion
//#region src/infra/sqlite-database-admission-read.ts
/** Admission lookups consume the owning registry and transaction-local state. */
function createSqliteDatabaseAdmissionReader(e) {
	const { state: t, admission: n, pathAdmission: r, exchange: i, retain: a, release: o, publishFact: s } = e;
	function withPathAdmission(e, t) {
		const n = r(e);
		if (!n) return t(void 0);
		try {
			a(n);
			return t(n);
		} finally {
			o(n);
		}
	}
	function getSqliteDatabaseAdmission(e, r, a = {}) {
		const o = sqlPublicationAnchor(e);
		if (!o.isOpen || t.suspended.has(o)) return;
		const s = n(o, a.existingOnly !== true && !e.isTransaction);
		if (!s) return;
		const c = (isPostgresSqlConnection(e) ? void 0 : getSqliteNativeAdmissionFacts(e))?.get(r.name) ?? t.local.get(o)?.get(r.name);
		if (c && c.revision === readSqliteDatabaseFactRevision(s, c.schemaDependent) && (!c.schemaDependent || c.ddlRevision === (t.ddlRevisions.get(o) ?? 0))) return readSqliteDatabaseAdmissionFact(c, r);
		if (r.schemaDependent && t.schemaDirty.has(o)) return;
		if (t.rolledBack.has(o)) {
			if (e.isTransaction) return;
			t.rolledBack.delete(o);
		}
		let l = s.facts.get(r.name);
		if (!l || !isSqliteDatabaseAdmissionFactCurrent(s, l) || a.refresh && r.writer !== "host") {
			if (r.writer === "host") {
				if (e.isTransaction || threadId === 0 || s.hostRevision === readSqliteDatabaseGeneration(s, "hostRevision")) return;
				i(s);
				l = s.facts.get(r.name);
				return l && isSqliteDatabaseAdmissionFactCurrent(s, l) ? readSqliteDatabaseAdmissionFact(l, r) : void 0;
			}
			const n = readSqliteDatabaseGeneration(s, "publicationRevision");
			const o = t.misses.get(s) ?? /* @__PURE__ */ new Map();
			t.misses.set(s, o);
			if (r.writer !== "connection" && !e.isTransaction && (a.refresh || o.get(r.name) !== n)) {
				i(s);
				l = s.facts.get(r.name);
				o.set(r.name, readSqliteDatabaseGeneration(s, "publicationRevision"));
			}
		}
		return l && isSqliteDatabaseAdmissionFactCurrent(s, l) ? readSqliteDatabaseAdmissionFact(l, r) : void 0;
	}
	function getOrLoadSqliteDatabaseAdmissionForPath(e, t, n) {
		const read = (e) => {
			if (!e) return n();
			const r = e.facts.get(t.name);
			const i = r && isSqliteDatabaseAdmissionFactCurrent(e, r) ? readSqliteDatabaseAdmissionFact(r, t) : void 0;
			if (i !== void 0) return i;
			const a = readSqliteDatabaseFactRevision(e, t.schemaDependent);
			const o = n();
			if (o !== void 0) s(e, t, admitSqliteDatabaseFactValue(t, o), a);
			return o;
		};
		return t.lifetime === "process" ? withPathAdmission(e, read) : read(r(e));
	}
	/** Optional preparation consumes only facts already delivered to this isolate. */
	function peekSqliteDatabaseAdmissionForPath(e, n) {
		const r = t.registry.forLocation(e);
		const i = r?.facts.get(n.name);
		return r && i && isSqliteDatabaseAdmissionFactCurrent(r, i) ? readSqliteDatabaseAdmissionFact(i, n) : void 0;
	}
	/** Retain revision cells while following the owner's current publication. */
	function prepareSqliteDatabaseAdmissionForPath(e, t) {
		const n = r(e);
		if (!n) return () => void 0;
		const i = new Int32Array(n.generation);
		const a = t.schemaDependent ? SqliteDatabaseGenerationSlot.schemaRevision : SqliteDatabaseGenerationSlot.factRevision;
		let o = n.facts.get(t.name);
		let s = o && new Int32Array(o.current);
		return () => {
			if (Atomics.load(i, SqliteDatabaseGenerationSlot.retired) !== 0) return;
			const e = n.facts.get(t.name);
			if (e !== o) {
				o = e;
				s = o && new Int32Array(o.current);
			}
			return o && s && Atomics.load(s, 0) === 1 && o.revision === Atomics.load(i, a) ? readSqliteDatabaseAdmissionFact(o, t) : void 0;
		};
	}
	function getSqliteDatabaseSchemaRevision(e, r = {}) {
		const i = sqlPublicationAnchor(e);
		const a = n(i, r.existingOnly !== true);
		if (a) return readSqliteDatabaseGeneration(a, "schemaRevision");
		const o = t.openedIdentities.get(i);
		return o ? t.localSchemaRevisions.get(o) ?? 0 : void 0;
	}
	function hasSqliteDatabaseSchemaAdmissionForPath(e) {
		return hasSqliteDatabaseSchemaAdmission(r(e));
	}
	/** Admission owns the descriptor's immutable identity; callers do not re-stat its pathname. */
	function getSqliteDatabaseAdmissionIdentityForPath(e) {
		return t.registry.forLocation(e)?.physicalIdentity;
	}
	/** Consume the already captured physical identity without another filesystem lookup. */
	function hasSqliteDatabaseSchemaAdmissionForIdentity(e) {
		return t.registry.hasSchemaAdmissionForIdentity(e);
	}
	return {
		getSqliteDatabaseAdmission,
		getSqliteDatabaseSchemaRevision,
		getOrLoadSqliteDatabaseAdmissionForPath,
		peekSqliteDatabaseAdmissionForPath,
		prepareSqliteDatabaseAdmissionForPath,
		hasSqliteDatabaseSchemaAdmissionForPath,
		getSqliteDatabaseAdmissionIdentityForPath,
		hasSqliteDatabaseSchemaAdmissionForIdentity
	};
}
//#endregion
//#region src/infra/sqlite-schema-sql.ts
const TABLE_CONSTRAINT_KEYWORDS = /* @__PURE__ */ new Set([
	"CHECK",
	"FOREIGN",
	"PRIMARY",
	"UNIQUE"
]);
/** Select canonical DDL without opening a database or changing its installation lifecycle. */
function extractSqliteTableSchema(e, t, n = {}) {
	const r = e.indexOf(`CREATE TABLE IF NOT EXISTS ${t} (`);
	const i = n.endMarker ?? e.slice(r).match(/\n\) STRICT(?:, WITHOUT ROWID)?;/u)?.[0];
	const a = i ? e.indexOf(i, r) : -1;
	if (r < 0 || !i || a < r) throw new Error(n.errorMessage ?? `Canonical schema markers are missing for ${t}`);
	return e.slice(r, a + (n.includeEndMarker === false ? 0 : i.length));
}
function readTableConstraintKeyword(e, t) {
	let n = t;
	if (n.keyword === "CONSTRAINT") {
		const t = readSqlToken(e, n.end);
		n = t ? readSqlToken(e, t.end) : null;
	}
	return n?.keyword && TABLE_CONSTRAINT_KEYWORDS.has(n.keyword) ? n.keyword : null;
}
function readSqlToken(e, t) {
	let n = t;
	while (n < e.length && /\s/u.test(e[n] ?? "")) n += 1;
	const r = e[n];
	if (!r) return null;
	if (r === "\"" || r === "`" || r === "[") {
		const t = skipSqlQuoted(e, n, r);
		return {
			end: t,
			keyword: null,
			raw: e.slice(n, t)
		};
	}
	let i = n;
	while (i < e.length && !/[\s(,]/u.test(e[i] ?? "")) i += 1;
	const a = e.slice(n, i);
	return {
		end: i,
		keyword: a.toUpperCase(),
		raw: a
	};
}
function normalizeSqlIdentifier(e) {
	if (e.startsWith("\"") && e.endsWith("\"")) return e.slice(1, -1).replaceAll("\"\"", "\"").toLowerCase();
	if (e.startsWith("`") && e.endsWith("`")) return e.slice(1, -1).replaceAll("``", "`").toLowerCase();
	if (e.startsWith("[") && e.endsWith("]")) return e.slice(1, -1).toLowerCase();
	return e.toLowerCase();
}
function normalizeSchemaSql(e) {
	if (e === null) return null;
	return normalizeSqlWhitespace(e).replace(/;\s*$/u, "").trim().replace(/^(CREATE (?:TABLE|VIRTUAL TABLE|UNIQUE INDEX|INDEX|TRIGGER)) IF NOT EXISTS /iu, "$1 ");
}
function splitSqlList(e) {
	const t = [];
	let n = 0;
	let r = 0;
	for (const i of unquotedSqlIndexes(e, 0)) {
		const a = e[i];
		if (a === "(") n += 1;
		else if (a === ")") n -= 1;
		else if (a === "," && n === 0) {
			t.push(e.slice(r, i));
			r = i + 1;
		}
	}
	t.push(e.slice(r));
	return t;
}
function findSqlCharacter(e, t) {
	for (const n of unquotedSqlIndexes(e, 0)) if (e[n] === t) return n;
	return -1;
}
/** Match SQL keywords without treating quoted payloads, identifiers or comments as code. */
function hasUnquotedSqlKeyword(e, t) {
	const n = /* @__PURE__ */ new Set();
	for (const r of e.matchAll(t)) n.add(r.index);
	if (n.size === 0) return false;
	for (const t of unquotedSqlIndexes(e, 0)) if (n.has(t)) return true;
	return false;
}
function findSqlClosingParenthesis(e, t) {
	let n = 0;
	for (const r of unquotedSqlIndexes(e, t)) {
		const t = e[r];
		if (t === "(") n += 1;
		else if (t === ")") {
			n -= 1;
			if (n === 0) return r;
		}
	}
	throw new Error("SQLite schema contains an unterminated table definition.");
}
function normalizeSqlWhitespace(e) {
	let t = "";
	let n = false;
	const r = /[^\s'"`[/-]+|\s+|./gsu;
	let i;
	while (i = r.exec(e)) {
		const a = i.index;
		const o = i[0][0] ?? "";
		const s = skipSqlQuoted(e, a, o);
		let c = i[0];
		if (s !== a) {
			c = e.slice(a, s);
			r.lastIndex = s;
		} else {
			const t = skipSqlComment(e, a);
			if (t !== a) {
				n = true;
				r.lastIndex = t;
				continue;
			}
			if (/\s/u.test(o)) {
				n = true;
				continue;
			}
		}
		if (n && t.length > 0) t += " ";
		t += c;
		n = false;
	}
	return t.trim();
}
function quoteSqliteIdentifier(e) {
	return `"${e.replaceAll("\"", "\"\"")}"`;
}
function* unquotedSqlIndexes(e, t) {
	let n = t;
	while (n < e.length) {
		const t = skipSqlQuoted(e, n, e[n] ?? "");
		const r = t !== n ? t : skipSqlComment(e, n);
		if (r !== n) n = r;
		else {
			yield n;
			n += 1;
		}
	}
}
function skipSqlQuoted(e, t, n) {
	if (n !== "'" && n !== "\"" && n !== "`" && n !== "[") return t;
	const r = n === "[" ? "]" : n;
	let i = t + 1;
	while (i < e.length) {
		if (e[i] !== r) {
			i += 1;
			continue;
		}
		if (n !== "[" && e[i + 1] === r) {
			i += 2;
			continue;
		}
		return i + 1;
	}
	return e.length;
}
function skipSqlComment(e, t) {
	if (e.startsWith("--", t)) {
		const n = e.indexOf("\n", t + 2);
		return n === -1 ? e.length : n + 1;
	}
	if (e.startsWith("/*", t)) {
		const n = e.indexOf("*/", t + 2);
		return n === -1 ? e.length : n + 2;
	}
	return t;
}
//#endregion
//#region src/infra/sqlite-schema-contract-assembly.ts
function createSqliteTableContract(e, t, n, r, i, a, o) {
	const s = i.map((e) => ({
		name: e.name,
		sql: normalizeSchemaSql(e.sql)
	}));
	const c = t.sql?.startsWith("CREATE TABLE ") ? null : normalizeSchemaSql(t.sql);
	const l = c !== null && /^CREATE VIRTUAL TABLE /iu.test(c);
	return {
		definition: l ? null : parseSqliteTableDefinition(t.sql, e),
		indexes: r,
		columns: a,
		foreignKeys: o,
		strict: n.strict,
		triggers: s,
		virtualTableSql: l ? c : null,
		withoutRowid: n.wr
	};
}
function createSqliteIndexContract(e, t, n) {
	const r = n.map(({ cid: e, coll: t, desc: n, key: r, name: i, seqno: a }) => ({
		coll: t,
		desc: n,
		key: r,
		kind: e === -2 ? "expression" : e === -1 ? "rowid" : "column",
		name: i,
		seqno: a
	}));
	return {
		name: e.name.startsWith("sqlite_autoindex_") ? null : e.name,
		origin: e.origin,
		partial: e.partial,
		sql: normalizeSchemaSql(t),
		terms: r,
		unique: e.unique
	};
}
function parseSqliteTableDefinition(e, t) {
	if (e === null) throw new Error(`Could not inspect SQLite table definition for ${t}.`);
	const n = findSqlCharacter(e, "(");
	if (n === -1) throw new Error(`SQLite table ${t} has no column definition.`);
	const r = findSqlClosingParenthesis(e, n);
	const i = /* @__PURE__ */ new Map();
	const a = [];
	for (const o of splitSqlList(e.slice(n + 1, r))) {
		const e = normalizeSqlWhitespace(o);
		if (!e) continue;
		const n = readSqlToken(e, 0);
		if (!n) throw new Error(`SQLite table ${t} contains an unreadable definition.`);
		if (readTableConstraintKeyword(e, n)) {
			a.push(e);
			continue;
		}
		const r = normalizeSqlIdentifier(n.raw);
		if (i.has(r)) throw new Error(`SQLite table ${t} contains duplicate column ${r}.`);
		i.set(r, e);
	}
	return {
		columns: new Map([...i].toSorted(([e], [t]) => e.localeCompare(t))),
		constraints: a.toSorted()
	};
}
//#endregion
//#region src/state/openclaw-agent-db-additive-columns.ts
const SESSION_OWNER_COLUMN_DEFINITIONS = [
	{
		columnName: "owner_actor_type",
		dataType: "TEXT",
		tableName: "session_nodes"
	},
	{
		columnName: "owner_actor_id",
		dataType: "TEXT",
		tableName: "session_nodes"
	},
	{
		columnName: "owner_assigned_by_type",
		dataType: "TEXT",
		tableName: "session_nodes"
	},
	{
		columnName: "owner_assigned_by_id",
		dataType: "TEXT",
		tableName: "session_nodes"
	},
	{
		columnName: "owner_assigned_at",
		dataType: "INTEGER",
		tableName: "session_nodes"
	}
];
const LEGACY_ACP_MIGRATION_COLUMN_DEFINITION = {
	columnName: "legacy_acp_migration_json",
	dataType: "TEXT",
	tableName: "session_nodes"
};
const CANONICAL_READY_COLUMN_DEFINITION = {
	columnName: "canonical_ready",
	dataType: "TEXT",
	tableName: "session_key_contract"
};
const FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS = [
	...SESSION_OWNER_COLUMN_DEFINITIONS,
	LEGACY_ACP_MIGRATION_COLUMN_DEFINITION,
	CANONICAL_READY_COLUMN_DEFINITION
];
const STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS = [
	{
		tableName: "session_pending_inputs",
		columnName: "consumed_event_id",
		dataType: "TEXT"
	},
	{
		tableName: "session_transcript_active_events",
		columnName: "context_eligible",
		dataType: "INTEGER"
	},
	{
		tableName: "session_nodes",
		columnName: "project_id",
		dataType: "TEXT"
	},
	{
		tableName: "session_windows",
		columnName: "row_transcript_json",
		dataType: "TEXT"
	},
	{
		tableName: "session_windows",
		columnName: "row_transcript_updated_at",
		dataType: "INTEGER"
	},
	{
		tableName: "session_conversations",
		columnName: "route_context_json",
		dataType: "TEXT"
	}
];
/** Missing feature-local tables stay absent; existing tables must satisfy this build's readers. */
function hasPendingAgentStartupColumns(e) {
	const t = /* @__PURE__ */ new Map();
	return STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS.some(({ tableName: n, columnName: r }) => {
		if (!e.has(n)) return false;
		const i = e.get(n);
		if (!i) return true;
		let a = t.get(n);
		if (!a) {
			a = parseSqliteTableDefinition(i, n).columns;
			t.set(n, a);
		}
		return !a.has(r);
	});
}
//#endregion
//#region src/infra/warning-filter.ts
const warningFilterKey = Symbol.for("openclaw.warning-filter");
function shouldIgnoreWarning(e) {
	return Boolean(e.code === "DEP0040" && e.message?.includes("punycode") || e.code === "DEP0060" && e.message?.includes("util._extend") || e.name === "ExperimentalWarning" && e.message?.includes("SQLite is an experimental feature"));
}
function normalizeWarningArgs(e) {
	const t = e[0];
	const n = e[1];
	const r = e[2];
	let i;
	let a;
	let o;
	if (t instanceof Error) {
		i = t.name;
		o = t.message;
		a = t.code;
	} else if (typeof t === "string") o = t;
	if (isRecord(n)) {
		if (typeof n.type === "string") i = n.type;
		if (typeof n.code === "string") a = n.code;
	} else {
		if (typeof n === "string") i = n;
		if (typeof r === "string") a = r;
	}
	return {
		name: i,
		code: a,
		message: o
	};
}
/** Installs the global process warning filter once for the current JS realm. */
function installProcessWarningFilter() {
	const e = resolveGlobalSingleton(warningFilterKey, () => ({ installed: false }));
	if (e.installed) return;
	const t = process.emitWarning.bind(process);
	const wrappedEmitWarning = ((...e) => {
		if (shouldIgnoreWarning(normalizeWarningArgs(e))) return;
		if (e[0] instanceof Error && isRecord(e[1])) {
			const t = e[0];
			const n = Object.assign(new Error(t.message), {
				name: t.name,
				code: t.code
			});
			process.emit("warning", n);
			return;
		}
		Reflect.apply(t, process, e);
	});
	process.emitWarning = wrappedEmitWarning;
	e.installed = true;
}
//#endregion
//#region src/infra/sqlite-native-runtime.ts
const require = createRequire(import.meta.url);
let validatedSqliteModule;
let extensionLoadingSupported = false;
let jsonbSupported = false;
function assertSqliteWalResetSafeVersion(e, t) {
	if (isSqliteWalResetSafeVersion(e)) return;
	const n = process.config.variables;
	const r = n.node_shared_sqlite === true || n.node_shared_sqlite === "true";
	throw new Error(`OpenClaw requires SQLite 3.51.3+, 3.50.7+ within 3.50.x, or 3.44.6+ within 3.44.x for WAL safety; Node ${t} ${r ? "uses shared system" : "embeds"} SQLite ${e}, which is affected by the upstream WAL-reset database corruption bug. ${r ? "Upgrade the system SQLite library to one of those safe versions, or use a Node build embedding a safe version." : "Upgrade to Node 24.22.1+ or 26.12.1+ before retrying."}`);
}
function sqliteNativeRuntimeIdentity() {
	return {
		pid: process.pid,
		executable: process.execPath,
		nodeVersion: process.versions.node,
		bunVersion: process.versions.bun,
		library: ensureSqliteLibrarySelected()
	};
}
function parseSqliteNativeRuntimeAdmission(e) {
	if (!isRecord(e) || e.format !== 1 || typeof e.version !== "string" || typeof e.extensionLoadingSupported !== "boolean") return;
	const t = sqliteNativeRuntimeIdentity();
	if (!isDeepStrictEqual(e.runtime, t)) return;
	return {
		format: 1,
		runtime: t,
		version: e.version,
		storageIdentity: isRecord(e.storageIdentity) && typeof e.storageIdentity.sourceId === "string" && typeof e.storageIdentity.compileOptions === "string" ? {
			sourceId: e.storageIdentity.sourceId,
			compileOptions: e.storageIdentity.compileOptions
		} : void 0,
		extensionLoadingSupported: e.extensionLoadingSupported
	};
}
function safeSqliteNativeRuntimeAdmission(e) {
	try {
		const t = parseSqliteNativeRuntimeAdmission(e);
		return t && isSqliteWalResetSafeVersion(t.version) ? t : void 0;
	} catch {
		return;
	}
}
/** Reuse a validated isolate fact without opening SQLite or probing the native library. */
function captureSqliteNativeRuntimeAdmission() {
	return safeSqliteNativeRuntimeAdmission(getEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY));
}
/** Publish to later sibling workers; database authority remains with its existing owners. */
function installSqliteNativeRuntimeAdmission(e) {
	const t = safeSqliteNativeRuntimeAdmission(e);
	if (t) setEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY, t);
}
function assertSafeSqliteRuntime(e) {
	if (validatedSqliteModule === e) return;
	const t = parseSqliteNativeRuntimeAdmission(getEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY));
	if (t) {
		assertSqliteWalResetSafeVersion(t.version, process.versions.node);
		jsonbSupported = (compareValidSemver(t.version, "3.45.0") ?? -1) >= 0;
		extensionLoadingSupported = t.extensionLoadingSupported;
		validatedSqliteModule = e;
		return;
	}
	const n = new e.DatabaseSync(":memory:");
	let r;
	let i;
	let a;
	try {
		const e = n.prepare("SELECT sqlite_version() AS version, sqlite_source_id() AS sourceId, (SELECT group_concat(compile_options, ',') FROM (SELECT compile_options FROM pragma_compile_options ORDER BY compile_options)) AS compileOptions, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted").get();
		r = typeof e?.version === "string" ? e.version : "unknown";
		assertSqliteWalResetSafeVersion(r, process.versions.node);
		if (typeof e?.sourceId === "string" && e.sourceId && typeof e.compileOptions === "string") i = {
			sourceId: e.sourceId,
			compileOptions: e.compileOptions
		};
		a = e?.omitted === 0;
	} finally {
		n.close();
	}
	jsonbSupported = (compareValidSemver(r, "3.45.0") ?? -1) >= 0;
	extensionLoadingSupported = a;
	validatedSqliteModule = e;
	setEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY, {
		format: 1,
		runtime: sqliteNativeRuntimeIdentity(),
		version: r,
		storageIdentity: i,
		extensionLoadingSupported: a
	});
}
/** Load node:sqlite after installing the process warning filter. */
function requireNodeSqlite() {
	installProcessWarningFilter();
	try {
		ensureSqliteLibrarySelected();
		const e = require("node:sqlite");
		assertSafeSqliteRuntime(e);
		return e;
	} catch (e) {
		const t = formatErrorMessage(e);
		throw new Error(`SQLite support is unavailable or unsafe in this Node runtime. ${t}`, { cause: e });
	}
}
//#endregion
//#region src/state/openclaw-agent-schema.ts
const OPENCLAW_AGENT_SCHEMA_SQL = "-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;\n-- session_entry_snapshots owns keyed cold values. Promoted node columns are query\n-- indexes; session_windows and their children own transcript generations.\n-- Legacy ACP provenance is private import evidence carried with its logical session.\n\nCREATE TABLE IF NOT EXISTS schema_meta (\n  meta_key TEXT NOT NULL PRIMARY KEY,\n  role TEXT NOT NULL,\n  schema_version INTEGER NOT NULL,\n  agent_id TEXT,\n  app_version TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_nodes (\n  session_key TEXT NOT NULL PRIMARY KEY,\n  current_session_id TEXT NOT NULL,\n  entry_json TEXT NOT NULL,\n  session_started_at INTEGER,\n  has_optional_references INTEGER NOT NULL DEFAULT 0,\n  snapshot_revision INTEGER NOT NULL DEFAULT 0,\n  legacy_acp_migration_json TEXT,\n  entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),\n  updated_at INTEGER NOT NULL,\n  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),\n  created_at INTEGER,\n  created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),\n  created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),\n  created_actor_id TEXT,\n  owner_actor_type TEXT,\n  owner_actor_id TEXT,\n  owner_assigned_by_type TEXT,\n  owner_assigned_by_id TEXT,\n  owner_assigned_at INTEGER,\n  project_id TEXT,\n  parent_session_key TEXT,\n  spawned_by TEXT,\n  fork_source_session_key TEXT,\n  fork_source_session_id TEXT,\n  fork_source_entry_id TEXT,\n  label TEXT,\n  display_name TEXT,\n  category TEXT,\n  icon TEXT,\n  pinned_at INTEGER,\n  archived_at INTEGER,\n  last_read_at INTEGER,\n  last_interaction_at INTEGER,\n  last_activity_at INTEGER\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_entry_snapshots (\n  session_key TEXT NOT NULL,\n  field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),\n  value_json TEXT NOT NULL,\n  PRIMARY KEY (session_key, field),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT, WITHOUT ROWID;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert\nAFTER INSERT ON session_entry_snapshots\nBEGIN\n  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n  WHERE session_key = NEW.session_key;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update\nAFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots\nWHEN NEW.session_key IS NOT OLD.session_key\n  OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json\nBEGIN\n  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n  WHERE session_key IN (OLD.session_key, NEW.session_key);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete\nAFTER DELETE ON session_entry_snapshots\nBEGIN\n  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n  WHERE session_key = OLD.session_key;\nEND;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at\n  ON session_nodes(updated_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label\n  ON session_nodes(label, session_key)\n  WHERE label IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key\n  ON session_nodes(parent_session_key, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by\n  ON session_nodes(spawned_by, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status\n  ON session_nodes(status, session_key)\n  WHERE status IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at\n  ON session_nodes(archived_at, session_key)\n  WHERE archived_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active\n  ON session_nodes(session_key)\n  WHERE archived_at IS NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id\n  ON session_nodes(current_session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending\n  ON session_nodes(session_key)\n  WHERE entry_valid = 0;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid\n  ON session_nodes(session_key)\n  WHERE entry_valid != 1;\n\nCREATE TABLE IF NOT EXISTS session_participants (\n  session_key TEXT NOT NULL,\n  identity_namespace TEXT NOT NULL,\n  actor_id TEXT NOT NULL,\n  contribution_count INTEGER NOT NULL,\n  first_prompted_at INTEGER,\n  last_prompted_at INTEGER,\n  PRIMARY KEY (session_key, identity_namespace, actor_id),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_key_contract (\n  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n  main_key TEXT NOT NULL,\n  canonical_ready TEXT,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nINSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);\n\nCREATE TABLE IF NOT EXISTS session_windows (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  session_key TEXT NOT NULL,\n  previous_session_id TEXT,\n  reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),\n  session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  transcript_updated_at INTEGER DEFAULT NULL,\n  row_transcript_json TEXT,\n  row_transcript_updated_at INTEGER,\n  transcript_observed_at INTEGER DEFAULT NULL,\n  session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),\n  acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),\n  plugin_owner_id TEXT,\n  hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),\n  started_at INTEGER,\n  ended_at INTEGER,\n  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),\n  chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),\n  channel TEXT,\n  account_id TEXT,\n  primary_conversation_id TEXT,\n  model_provider TEXT,\n  model TEXT,\n  agent_harness_id TEXT,\n  parent_session_key TEXT,\n  spawned_by TEXT,\n  display_name TEXT,\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n  FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at\n  ON session_windows(updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key\n  ON session_windows(session_key, updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at\n  ON session_windows(created_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation\n  ON session_windows(primary_conversation_id)\n  WHERE primary_conversation_id IS NOT NULL;\n\n-- Offline imports and repairs queue explicit work; admission also settles keys\n-- removed during repair, so the queue deliberately has no node foreign key.\nCREATE TABLE IF NOT EXISTS session_canonical_validation_pending (\n  session_key TEXT NOT NULL PRIMARY KEY\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS conversations (\n  conversation_id TEXT NOT NULL PRIMARY KEY,\n  channel TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),\n  peer_id TEXT NOT NULL,\n  delivery_target TEXT NOT NULL,\n  parent_conversation_id TEXT,\n  thread_id TEXT,\n  native_channel_id TEXT,\n  native_direct_user_id TEXT,\n  label TEXT,\n  metadata_json TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup\n  ON conversations(channel, account_id, kind, peer_id, thread_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity\n  ON conversations(\n    channel,\n    account_id,\n    kind,\n    peer_id,\n    IFNULL(parent_conversation_id, ''),\n    IFNULL(thread_id, '')\n  );\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversations_updated\n  ON conversations(updated_at DESC, conversation_id);\n\nCREATE TABLE IF NOT EXISTS conversation_deliveries (\n  operation_id TEXT NOT NULL PRIMARY KEY,\n  operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),\n  conversation_id TEXT NOT NULL,\n  source_session_key TEXT,\n  message_hash TEXT NOT NULL,\n  status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),\n  prepared_message_id TEXT,\n  platform_message_id TEXT,\n  queue_id TEXT,\n  rejection_error TEXT,\n  reply_message_id TEXT,\n  reply_to_id TEXT,\n  reply_thread_id TEXT,\n  reply_text TEXT,\n  reply_timestamp INTEGER,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  CHECK (\n    (status = 'rejected' AND rejection_error IS NOT NULL) OR\n    (status != 'rejected' AND rejection_error IS NULL)\n  ),\n  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply\n  ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)\n  WHERE status IN ('queued', 'sent', 'replied');\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated\n  ON conversation_deliveries(updated_at DESC, operation_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_source_session\n  ON conversation_deliveries(source_session_key, operation_id);\n\nCREATE TABLE IF NOT EXISTS session_conversations (\n  session_id TEXT NOT NULL,\n  conversation_id TEXT NOT NULL,\n  role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),\n  route_context_json TEXT,\n  first_seen_at INTEGER NOT NULL,\n  last_seen_at INTEGER NOT NULL,\n  PRIMARY KEY (session_id, conversation_id, role),\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE\n) STRICT;\n\n-- Older same-version writers preserve the envelope while updating the association.\nCREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update\nAFTER UPDATE OF role, last_seen_at ON session_conversations\nWHEN NEW.route_context_json IS OLD.route_context_json\nBEGIN\n  UPDATE session_conversations\n  SET route_context_json = NULL\n  WHERE session_id = NEW.session_id\n    AND conversation_id = NEW.conversation_id\n    AND role = NEW.role;\nEND;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation\n  ON session_conversations(conversation_id, last_seen_at DESC, session_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary\n  ON session_conversations(session_id)\n  WHERE role = 'primary';\n\nCREATE TABLE IF NOT EXISTS session_members (\n  session_key TEXT NOT NULL,\n  identity_id TEXT NOT NULL,\n  added_by TEXT NOT NULL,\n  added_at INTEGER NOT NULL,\n  PRIMARY KEY (session_key, identity_id),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_members_identity\n  ON session_members(identity_id, session_key);\n\nCREATE TABLE IF NOT EXISTS session_suggestions (\n  id TEXT PRIMARY KEY,\n  session_key TEXT NOT NULL,\n  author_id TEXT NOT NULL,\n  author_label TEXT,\n  text TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),\n  dispatch_token TEXT,\n  dispatch_started_at INTEGER,\n  dispatch_resolution TEXT CHECK (dispatch_resolution IN ('send', 'queue', 'edit', 'dismiss')),\n  CHECK (\n    (dispatch_token IS NULL AND dispatch_started_at IS NULL AND dispatch_resolution IS NULL)\n    OR (dispatch_token IS NOT NULL AND dispatch_started_at IS NOT NULL AND dispatch_resolution IS NOT NULL)\n  ),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created\n  ON session_suggestions(session_key, state, created_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created\n  ON session_suggestions(author_id, created_at, id);\n\nCREATE TABLE IF NOT EXISTS session_reactions (\n  session_key TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  message_id TEXT NOT NULL,\n  emoji TEXT NOT NULL,\n  identity_id TEXT NOT NULL,\n  identity_label TEXT,\n  created_at INTEGER NOT NULL,\n  PRIMARY KEY (session_key, session_id, message_id, emoji, identity_id),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS board_tabs (\n  session_key TEXT NOT NULL,\n  tab_id TEXT NOT NULL,\n  title TEXT NOT NULL,\n  position INTEGER NOT NULL CHECK (position >= 0),\n  chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),\n  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),\n  revision INTEGER NOT NULL CHECK (revision >= 0),\n  PRIMARY KEY (session_key, tab_id),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS board_widgets (\n  session_key TEXT NOT NULL,\n  name TEXT NOT NULL,\n  tab_id TEXT NOT NULL,\n  title TEXT,\n  content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),\n  html BLOB,\n  descriptor_json TEXT,\n  sha256 TEXT NOT NULL,\n  view_generation TEXT,\n  revision INTEGER NOT NULL CHECK (revision >= 1),\n  size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),\n  size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),\n  position INTEGER NOT NULL CHECK (position >= 0),\n  manifest TEXT NOT NULL DEFAULT '{}',\n  grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),\n  granted_sha TEXT,\n  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (session_key, name),\n  FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,\n  CHECK (\n    (content_kind = 'html' AND html IS NOT NULL AND descriptor_json IS NULL AND view_generation IS NOT NULL) OR\n    (content_kind = 'mcp-app' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL) OR\n    (content_kind = 'plugin' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL)\n  )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position\n  ON board_widgets(session_key, tab_id, position);\n\nCREATE TABLE IF NOT EXISTS session_progress_cards (\n  session_key TEXT NOT NULL PRIMARY KEY,\n  markdown TEXT,\n  steps_json TEXT,\n  revision INTEGER NOT NULL,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS heartbeat_outcomes (\n  session_key TEXT NOT NULL PRIMARY KEY,\n  run_session_key TEXT NOT NULL,\n  outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),\n  summary TEXT NOT NULL,\n  response_reason TEXT,\n  priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),\n  next_check TEXT,\n  task_names_json TEXT,\n  wake_source TEXT,\n  wake_reason TEXT,\n  occurred_at INTEGER NOT NULL,\n  context_run_id TEXT,\n  context_claimed_at INTEGER,\n  updated_at INTEGER NOT NULL,\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS message_tool_run_outcomes (\n  id INTEGER PRIMARY KEY,\n  run_id TEXT NOT NULL,\n  session_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  provider TEXT NOT NULL,\n  model TEXT NOT NULL,\n  outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),\n  run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),\n  occurred_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred\n  ON message_tool_run_outcomes(occurred_at DESC, id DESC);\n\n-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.\n-- They intentionally have no session FK; bounded retention belongs to the operation owner.\nCREATE TABLE IF NOT EXISTS session_goal_operations (\n  session_key TEXT NOT NULL,\n  operation_id TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  request_fingerprint TEXT NOT NULL,\n  result_json TEXT NOT NULL,\n  expires_at INTEGER NOT NULL,\n  PRIMARY KEY (session_key, operation_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry\n  ON session_goal_operations(expires_at);\n\nCREATE TABLE IF NOT EXISTS transcript_events (\n  session_id TEXT NOT NULL,\n  seq INTEGER NOT NULL,\n  event_json TEXT,\n  created_at INTEGER NOT NULL,\n  event_zstd BLOB,\n  event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),\n  navigation_json TEXT,\n  navigation_type TEXT,\n  navigation_custom_type TEXT,\n  navigation_display INTEGER NOT NULL DEFAULT 0,\n  message_role TEXT,\n  navigation_last_type TEXT,\n  navigation_last_custom_type TEXT,\n  navigation_valid INTEGER NOT NULL DEFAULT 1,\n  PRIMARY KEY (session_id, seq),\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n  CHECK (\n    (event_json IS NOT NULL AND event_zstd IS NULL)\n    OR (\n      event_json IS NULL AND event_zstd IS NOT NULL\n      AND event_utf8_bytes IS NOT NULL\n      AND event_utf8_bytes BETWEEN 1 AND 4194304\n      AND length(event_zstd) BETWEEN 1 AND 4194304\n      AND navigation_json IS NOT NULL\n    )\n  ),\n  CHECK (\n    navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(\n      octet_length(navigation_json) <= 16384\n      AND json_type(navigation_json, '$.version') = 'integer'\n      AND json_extract(navigation_json, '$.version') = 1\n      AND json_type(navigation_json, '$.report') = 'object'\n      AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')\n      AND json_type(navigation_json, '$.navigation') = 'object'\n      AND json_type(navigation_json, '$.reset') = 'object'\n      AND json_type(navigation_json, '$.model') = 'object'\n      AND json_type(navigation_json, '$.modelBytes') = 'integer'\n      AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304\n      AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'\n      AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304\n      AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'\n      AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,\n      0) ELSE 0 END\n  )\n) STRICT;\n\n-- Canonical cold-tier owner for reclaimed transcript generations. The derived\n-- .deleted/.reset file may be recreated from this row after a crash.\nCREATE TABLE IF NOT EXISTS session_transcript_archives (\n  session_id TEXT NOT NULL,\n  generation TEXT NOT NULL,\n  session_key TEXT NOT NULL,\n  reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),\n  encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),\n  archive_blob BLOB NOT NULL,\n  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),\n  archive_name TEXT NOT NULL UNIQUE,\n  created_at INTEGER NOT NULL,\n  published_at INTEGER,\n  publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),\n  last_publish_attempt_at INTEGER,\n  last_publish_error TEXT,\n  PRIMARY KEY (session_id, generation),\n  CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending\n  ON session_transcript_archives(created_at, session_id, generation)\n  WHERE published_at IS NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention\n  ON session_transcript_archives(created_at, session_id, generation);\n\nCREATE TABLE IF NOT EXISTS session_transcript_cold_archives (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  generation TEXT NOT NULL,\n  archive_name TEXT NOT NULL UNIQUE,\n  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),\n  event_count INTEGER NOT NULL CHECK (event_count >= 1),\n  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),\n  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),\n  last_seq INTEGER NOT NULL,\n  archived_at INTEGER NOT NULL,\n  storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),\n  archive_blob BLOB,\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),\n  CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_transcript_cold_archive_chunks (\n  session_id TEXT NOT NULL,\n  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),\n  archive_name TEXT NOT NULL UNIQUE,\n  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),\n  first_seq INTEGER NOT NULL,\n  last_seq INTEGER NOT NULL CHECK (last_seq >= first_seq),\n  event_count INTEGER NOT NULL CHECK (event_count >= 1),\n  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),\n  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),\n  archive_blob BLOB,\n  PRIMARY KEY (session_id, chunk_index),\n  FOREIGN KEY (session_id) REFERENCES session_transcript_cold_archives(session_id) ON DELETE CASCADE,\n  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  generation TEXT NOT NULL,\n  updated_at INTEGER NOT NULL,\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS trajectory_runtime_events (\n  session_id TEXT NOT NULL,\n  seq INTEGER NOT NULL,\n  run_id TEXT,\n  event_json TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  event_utf8_bytes INTEGER,\n  event_payload BLOB,\n  event_codec TEXT,\n  PRIMARY KEY (session_id, seq),\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run\n  ON trajectory_runtime_events(session_id, run_id, created_at, COALESCE(event_utf8_bytes, octet_length(event_json)));\n\nCREATE TABLE IF NOT EXISTS acp_parent_stream_events (\n  session_id TEXT NOT NULL,\n  run_id TEXT NOT NULL,\n  seq INTEGER NOT NULL,\n  event_json TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  PRIMARY KEY (session_id, run_id, seq),\n  FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run\n  ON acp_parent_stream_events(run_id, seq);\n\nCREATE TABLE IF NOT EXISTS transcript_event_identities (\n  session_id TEXT NOT NULL,\n  event_id TEXT NOT NULL,\n  seq INTEGER NOT NULL,\n  event_type TEXT,\n  parent_id TEXT,\n  message_idempotency_key TEXT,\n  created_at INTEGER NOT NULL,\n  PRIMARY KEY (session_id, event_id),\n  FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency\n  ON transcript_event_identities(session_id, message_idempotency_key)\n  WHERE message_idempotency_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence\n  ON transcript_event_identities(session_id, seq);\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence\n  ON transcript_event_identities(session_id, event_type, seq DESC);\n\nCREATE TABLE IF NOT EXISTS context_engine_turn_outbox (\n  enqueue_sequence INTEGER PRIMARY KEY,\n  advancement_key TEXT NOT NULL UNIQUE,\n  engine_id TEXT NOT NULL,\n  owner_plugin_id TEXT,\n  session_id TEXT NOT NULL,\n  payload_json TEXT NOT NULL,\n  payload_state TEXT,\n  attempt_count INTEGER NOT NULL DEFAULT 0,\n  last_attempt_at INTEGER,\n  last_error TEXT,\n  created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine\n  ON context_engine_turn_outbox(engine_id, created_at);\n\nCREATE TABLE IF NOT EXISTS cache_entries (\n  scope TEXT NOT NULL,\n  key TEXT NOT NULL,\n  value_json TEXT,\n  blob BLOB,\n  expires_at INTEGER,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (scope, key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_cache_expiry\n  ON cache_entries(scope, expires_at, key)\n  WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_cache_updated\n  ON cache_entries(scope, updated_at DESC, key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_scope\n  ON cache_entries(CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.agentId') END,\n    CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.sessionKey') END, CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.origin') END)\n  WHERE scope = 'talk-client-voice-sessions'\n    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';\n\nCREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_updated\n  ON cache_entries(scope, updated_at)\n  WHERE scope = 'talk-client-voice-sessions'\n    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';\n\nCREATE TABLE IF NOT EXISTS auth_profile_store (\n  store_key TEXT NOT NULL PRIMARY KEY,\n  store_json TEXT NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS auth_profile_state (\n  state_key TEXT NOT NULL PRIMARY KEY,\n  state_json TEXT NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_meta (\n  key TEXT PRIMARY KEY,\n  value TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_sources (\n  id INTEGER PRIMARY KEY,\n  path TEXT NOT NULL,\n  source TEXT NOT NULL DEFAULT 'memory',\n  hash TEXT NOT NULL,\n  mtime REAL NOT NULL,\n  size INTEGER NOT NULL,\n  UNIQUE (path, source)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunks (\n  chunk_rowid INTEGER PRIMARY KEY,\n  id TEXT NOT NULL UNIQUE,\n  path TEXT NOT NULL,\n  source TEXT NOT NULL DEFAULT 'memory',\n  start_line INTEGER NOT NULL,\n  end_line INTEGER NOT NULL,\n  hash TEXT NOT NULL,\n  model TEXT NOT NULL,\n  text TEXT NOT NULL,\n  embedding BLOB NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (\n  chunk_id TEXT PRIMARY KEY,\n  importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),\n  triggers TEXT,\n  project_key TEXT,\n  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (\n  chunk_id TEXT PRIMARY KEY,\n  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),\n  session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),\n  observed_at INTEGER NOT NULL,\n  supersedes_key TEXT,\n  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_entry_origins (\n  entry_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  session_key TEXT,\n  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),\n  observed_at INTEGER NOT NULL,\n  PRIMARY KEY (entry_key, agent_id, session_id)\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS memory_session_tombstones (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  agent_id TEXT NOT NULL,\n  reason TEXT NOT NULL,\n  created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_embedding_cache (\n  provider TEXT NOT NULL,\n  model TEXT NOT NULL,\n  provider_key TEXT NOT NULL,\n  hash TEXT NOT NULL,\n  embedding BLOB NOT NULL,\n  dims INTEGER,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (provider, model, provider_key, hash)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_state (\n  id INTEGER PRIMARY KEY CHECK (id = 1),\n  revision INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS standing_intents (\n  intent_key INTEGER PRIMARY KEY,\n  id TEXT NOT NULL UNIQUE,\n  description TEXT NOT NULL,\n  trigger_keywords TEXT NOT NULL,\n  trigger_embedding TEXT,\n  channel_scope TEXT,\n  sender_scope TEXT,\n  creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),\n  status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),\n  expires_at INTEGER NOT NULL,\n  max_fires INTEGER NOT NULL CHECK (max_fires > 0),\n  fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),\n  cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),\n  last_fired_at INTEGER,\n  created_at INTEGER NOT NULL,\n  source_session_id TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle\n  ON standing_intents(status, expires_at, last_fired_at);\n\nCREATE INDEX IF NOT EXISTS idx_standing_intents_scope\n  ON standing_intents(status, channel_scope, sender_scope);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(\n  trigger_keywords,\n  content = 'standing_intents',\n  content_rowid = 'intent_key',\n  tokenize = 'unicode61 remove_diacritics 2'\n);\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert\nAFTER INSERT ON standing_intents\nBEGIN\n  INSERT INTO standing_intents_fts(rowid, trigger_keywords)\n  VALUES (new.intent_key, new.trigger_keywords);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete\nAFTER DELETE ON standing_intents\nBEGIN\n  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)\n  VALUES ('delete', old.intent_key, old.trigger_keywords);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update\nAFTER UPDATE OF trigger_keywords ON standing_intents\nBEGIN\n  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)\n  VALUES ('delete', old.intent_key, old.trigger_keywords);\n  INSERT INTO standing_intents_fts(rowid, trigger_keywords)\n  VALUES (new.intent_key, new.trigger_keywords);\nEND;\n\nCREATE TABLE IF NOT EXISTS session_transcript_index_state (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  indexed_seq INTEGER NOT NULL,\n  leaf_event_id TEXT,\n  needs_rebuild INTEGER NOT NULL DEFAULT 0,\n  active_event_count INTEGER NOT NULL DEFAULT 0,\n  active_message_count INTEGER NOT NULL DEFAULT 0,\n  updated_at INTEGER NOT NULL,\n  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_transcript_active_events (\n  session_id TEXT NOT NULL,\n  active_position INTEGER NOT NULL CHECK (active_position >= 0),\n  event_seq INTEGER NOT NULL,\n  message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),\n  context_eligible INTEGER,\n  PRIMARY KEY (session_id, active_position),\n  FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq\n  ON session_transcript_active_events(session_id, event_seq);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages\n  ON session_transcript_active_events(session_id, message_position)\n  WHERE message_position IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending\n  ON session_transcript_active_events(session_id)\n  WHERE context_eligible IS NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(\n  text,\n  session_id UNINDEXED,\n  message_id UNINDEXED,\n  role UNINDEXED,\n  timestamp UNINDEXED,\n  tokenize = 'unicode61 remove_diacritics 2'\n);\n\nCREATE TABLE IF NOT EXISTS session_transcript_fts_rows (\n  id INTEGER PRIMARY KEY,\n  session_id TEXT NOT NULL,\n  message_id TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message\n  ON session_transcript_fts_rows(session_id, message_id);\n\nCREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete\nAFTER DELETE ON session_transcript_fts_rows\nBEGIN\n  DELETE FROM session_transcript_fts WHERE rowid = OLD.id;\nEND;\n\nINSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);\n\nCREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at\n  ON memory_embedding_cache(updated_at);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_sources_source\n  ON memory_index_sources(source);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source\n  ON memory_index_chunks(path, source);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source\n  ON memory_index_chunks(source);\n\n-- Accepted input stays outside the active transcript until its exact turn owns execution.\nCREATE TABLE IF NOT EXISTS session_pending_inputs (\n  seq INTEGER PRIMARY KEY AUTOINCREMENT,\n  input_id TEXT NOT NULL UNIQUE,\n  session_key TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  idempotency_key TEXT NOT NULL,\n  run_id TEXT NOT NULL,\n  request_hash TEXT NOT NULL,\n  message_json TEXT NOT NULL,\n  lifecycle_generation TEXT NOT NULL,\n  state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),\n  accepted_at INTEGER NOT NULL,\n  consumed_event_id TEXT,\n  UNIQUE (session_id, idempotency_key),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session\n  ON session_pending_inputs(session_key, session_id, seq DESC);\n\n-- Processing completion is separate from input consumption; neither schedules replay.\nCREATE TABLE IF NOT EXISTS session_input_completions (\n  session_key TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  idempotency_key TEXT NOT NULL,\n  run_id TEXT NOT NULL,\n  request_hash TEXT NOT NULL,\n  outcome_json TEXT NOT NULL,\n  succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),\n  completed_at INTEGER NOT NULL,\n  PRIMARY KEY (session_id, idempotency_key),\n  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key\n  ON session_input_completions(session_key);\n";
//#endregion
//#region src/state/openclaw-state-schema.ts
const OPENCLAW_STATE_SCHEMA_SQL = "\n\nCREATE TABLE IF NOT EXISTS mcp_oauth_stores (\n  store_key TEXT NOT NULL PRIMARY KEY,\n  format_version INTEGER NOT NULL CHECK (format_version = 1),\n  store_json TEXT NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS mcp_oauth_pending_authorizations (\n  state TEXT NOT NULL PRIMARY KEY,\n  store_key TEXT NOT NULL,\n  create_time INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS diagnostic_events (\n  scope TEXT NOT NULL,\n  event_key TEXT NOT NULL,\n  payload_json TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  sequence INTEGER NOT NULL DEFAULT 0,\n  PRIMARY KEY (scope, event_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_diagnostic_events_scope_sequence\n  ON diagnostic_events(scope, sequence, event_key);\n\nCREATE TABLE IF NOT EXISTS skill_usage (\n  skill_file TEXT NOT NULL PRIMARY KEY,\n  skill_key TEXT NOT NULL,\n  skill_name TEXT NOT NULL,\n  skill_source TEXT NOT NULL,\n  first_used_at_ms INTEGER NOT NULL,\n  last_used_at_ms INTEGER NOT NULL,\n  use_count INTEGER NOT NULL,\n  last_agent_id TEXT\n) STRICT;\n\n-- Profile-owned skill library: additive, absent until first publication/import.\nCREATE TABLE IF NOT EXISTS skill_library_entries (\n  skill_id TEXT NOT NULL PRIMARY KEY,\n  owner_profile_id TEXT,\n  author_profile_id TEXT NOT NULL,\n  slug TEXT NOT NULL,\n  current_revision TEXT NOT NULL,\n  shared INT NOT NULL,\n  enabled INT NOT NULL,\n  removed INT NOT NULL,\n  created_at INT NOT NULL,\n  updated_at INT NOT NULL\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_revisions (\n  skill_id TEXT NOT NULL,\n  revision TEXT NOT NULL,\n  description TEXT NOT NULL,\n  files_json TEXT NOT NULL,\n  created_at INT NOT NULL,\n  PRIMARY KEY (skill_id, revision)\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_events (\n  event_id TEXT NOT NULL PRIMARY KEY,\n  skill_id TEXT NOT NULL,\n  revision TEXT NOT NULL,\n  action TEXT NOT NULL,\n  actor_profile_id TEXT NOT NULL,\n  created_at INT NOT NULL\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_uploads (\n  upload_id TEXT NOT NULL PRIMARY KEY,\n  owner_profile_id TEXT NOT NULL,\n  slug TEXT NOT NULL,\n  size_bytes INT NOT NULL,\n  sha256 TEXT NOT NULL,\n  archive_blob BLOB NOT NULL,\n  expires_at INT NOT NULL,\n  published_skill_id TEXT\n) STRICT;\n-- End profile-owned skill library.\n\nCREATE TABLE IF NOT EXISTS skill_workshop_changes (\n  cursor_id INTEGER NOT NULL,\n  change_id TEXT NOT NULL PRIMARY KEY,\n  agent_id TEXT NOT NULL,\n  skill_name TEXT NOT NULL,\n  action TEXT NOT NULL CHECK (action IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore')),\n  actor TEXT NOT NULL CHECK (actor IN ('agent', 'review', 'curator', 'user')),\n  summary TEXT NOT NULL,\n  version_id TEXT,\n  session_key TEXT,\n  run_id TEXT,\n  created_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS skill_workshop_changes_cursor_id_idx\n  ON skill_workshop_changes(cursor_id);\n\nCREATE INDEX IF NOT EXISTS idx_skill_workshop_changes_agent_time\n  ON skill_workshop_changes(agent_id, created_at_ms);\n\nCREATE TABLE IF NOT EXISTS audit_events (\n  sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n  event_id TEXT NOT NULL UNIQUE,\n  source_id TEXT NOT NULL UNIQUE,\n  schema_version INTEGER NOT NULL DEFAULT 1,\n  source_sequence INTEGER NOT NULL,\n  occurred_at INTEGER NOT NULL,\n  kind TEXT NOT NULL,\n  action TEXT NOT NULL,\n  status TEXT NOT NULL,\n  error_code TEXT,\n  actor_type TEXT NOT NULL,\n  actor_id TEXT NOT NULL,\n  agent_id TEXT,\n  session_key TEXT,\n  session_id TEXT,\n  run_id TEXT,\n  tool_call_id TEXT,\n  tool_name TEXT,\n  direction TEXT,\n  channel TEXT,\n  conversation_kind TEXT,\n  message_outcome TEXT,\n  reason_code TEXT,\n  delivery_kind TEXT,\n  failure_stage TEXT,\n  duration_ms INTEGER,\n  result_count INTEGER,\n  account_ref TEXT,\n  conversation_ref TEXT,\n  message_ref TEXT,\n  target_ref TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_time\n  ON audit_events(occurred_at DESC, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_agent_sequence\n  ON audit_events(agent_id, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_session_sequence\n  ON audit_events(session_key, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_run_sequence\n  ON audit_events(run_id, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_kind_sequence\n  ON audit_events(kind, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_status_sequence\n  ON audit_events(status, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_channel_sequence\n  ON audit_events(channel, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_direction_sequence\n  ON audit_events(direction, sequence DESC);\n\nCREATE TABLE IF NOT EXISTS outbound_message_execution_bindings (\n  event_id TEXT NOT NULL PRIMARY KEY,\n  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),\n  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),\n  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n  FOREIGN KEY (event_id) REFERENCES audit_events(event_id) ON DELETE CASCADE\n) STRICT;\nCREATE INDEX IF NOT EXISTS outbound_message_execution_bindings_execution_event_idx\n  ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);\n\nCREATE TABLE IF NOT EXISTS outbound_message_progress (\n  sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n  progress_id TEXT NOT NULL UNIQUE CHECK (length(progress_id) BETWEEN 1 AND 256),\n  source_id TEXT NOT NULL UNIQUE CHECK (length(source_id) BETWEEN 1 AND 512),\n  source_sequence INTEGER NOT NULL CHECK (source_sequence >= 1),\n  schema_version INTEGER NOT NULL CHECK (schema_version = 1),\n  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),\n  action TEXT NOT NULL CHECK (\n    action IN ('message.outbound.queued', 'message.outbound.platform-started')\n  ),\n  outcome TEXT NOT NULL CHECK (outcome IN ('queued', 'platform_started')),\n  actor_type TEXT NOT NULL CHECK (actor_type IN ('agent', 'system')),\n  actor_id TEXT NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),\n  agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) BETWEEN 1 AND 256),\n  run_id TEXT CHECK (run_id IS NULL OR length(run_id) BETWEEN 1 AND 256),\n  context_id TEXT,\n  execution_id TEXT,\n  channel TEXT NOT NULL CHECK (length(channel) BETWEEN 1 AND 256),\n  conversation_kind TEXT NOT NULL CHECK (\n    conversation_kind IN ('direct', 'group', 'channel', 'unknown')\n  ),\n  duration_ms INTEGER CHECK (duration_ms IS NULL OR duration_ms >= 0),\n  account_ref TEXT,\n  conversation_ref TEXT,\n  target_ref TEXT,\n  UNIQUE (occurred_at, progress_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS outbound_message_progress_occurred_idx\n  ON outbound_message_progress (occurred_at, sequence);\nCREATE INDEX IF NOT EXISTS outbound_message_progress_run_occurred_idx\n  ON outbound_message_progress (run_id, occurred_at, sequence);\n\nCREATE TABLE IF NOT EXISTS audit_identity_keys (\n  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n  key_id TEXT NOT NULL,\n  key BLOB NOT NULL,\n  created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS config_revision_keys (\n  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n  hmac_key BLOB NOT NULL CHECK (length(hmac_key) = 32)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS execution_identity_contexts (\n  context_id TEXT NOT NULL PRIMARY KEY CHECK (length(context_id) BETWEEN 1 AND 256),\n  execution_id TEXT NOT NULL UNIQUE CHECK (length(execution_id) BETWEEN 1 AND 256),\n  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n  created_at INTEGER NOT NULL CHECK (created_at >= 0),\n  coverage_state TEXT NOT NULL CHECK (\n    coverage_state IN ('attribution-only', 'unattributed', 'unknown', 'unsupported')\n  ),\n  context_bytes INTEGER NOT NULL CHECK (context_bytes BETWEEN 1 AND 16384),\n  context_json TEXT NOT NULL CHECK (length(context_json) > 0),\n  UNIQUE (created_at, context_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS execution_identity_contexts_run_created_idx\n  ON execution_identity_contexts (run_id, created_at, execution_id);\n\nCREATE TABLE IF NOT EXISTS execution_decision_facts (\n  cursor_id INTEGER NOT NULL,\n  receipt_id TEXT NOT NULL PRIMARY KEY CHECK (length(receipt_id) BETWEEN 1 AND 256),\n  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),\n  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),\n  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n  action_id TEXT CHECK (action_id IS NULL OR length(action_id) BETWEEN 1 AND 256),\n  action_family TEXT NOT NULL CHECK (length(action_family) BETWEEN 1 AND 256),\n  decision_outcome TEXT NOT NULL CHECK (\n    decision_outcome IN ('allowed', 'denied', 'not-applicable', 'unknown')\n  ),\n  coverage_state TEXT NOT NULL CHECK (\n    coverage_state IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported')\n  ),\n  reason_code TEXT NOT NULL CHECK (length(reason_code) BETWEEN 1 AND 256),\n  owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 256),\n  source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 256),\n  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),\n  receipt_bytes INTEGER NOT NULL CHECK (receipt_bytes BETWEEN 1 AND 16384),\n  receipt_json TEXT NOT NULL CHECK (length(receipt_json) > 0),\n  UNIQUE (occurred_at, receipt_id)\n) STRICT;\nCREATE UNIQUE INDEX IF NOT EXISTS execution_decision_facts_cursor_id_idx\n  ON execution_decision_facts(cursor_id);\n\nCREATE INDEX IF NOT EXISTS execution_decision_facts_context_occurred_idx\n  ON execution_decision_facts (context_id, occurred_at, receipt_id);\nCREATE INDEX IF NOT EXISTS execution_decision_facts_run_occurred_idx\n  ON execution_decision_facts (run_id, occurred_at, receipt_id);\n\n-- Exact admission identity stays separate from owner-native lifecycle rows so\n-- older readers retain byte-compatible cron/task/flow table definitions.\nCREATE TABLE IF NOT EXISTS execution_owner_lifecycle_bindings (\n  owner_kind TEXT NOT NULL,\n  owner_id TEXT NOT NULL,\n  context_id TEXT NOT NULL,\n  execution_id TEXT NOT NULL,\n  PRIMARY KEY (owner_kind, owner_id)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_state_events (\n  sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n  dedupe_key TEXT UNIQUE,\n  session_key TEXT NOT NULL,\n  session_id TEXT,\n  agent_id TEXT NOT NULL,\n  kind TEXT NOT NULL,\n  actor_type TEXT NOT NULL,\n  actor_id TEXT,\n  run_id TEXT,\n  occurred_at INTEGER NOT NULL,\n  summary TEXT NOT NULL,\n  payload_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_state_events_session_sequence\n  ON session_state_events(session_key, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_session_state_events_time\n  ON session_state_events(occurred_at DESC, sequence DESC);\n\nCREATE TABLE IF NOT EXISTS session_state_heads (\n  session_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  last_sequence INTEGER NOT NULL,\n  pruned_max_sequence INTEGER NOT NULL DEFAULT 0,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (session_key, agent_id)\n) STRICT, WITHOUT ROWID;\n\n-- Notifiable watcher identity is the bare session key, matching the process-local\n-- system-event queue it feeds. Provenance distinguishes explicit immediate-wake\n-- watches from ambient queue-only group watches. Other bare keys\n-- (session.scope=\"global\") are ambiguous across agents and excluded until watcher\n-- identity is agent-scoped end-to-end.\nCREATE TABLE IF NOT EXISTS session_watch_cursors (\n  watcher_session_key TEXT NOT NULL,\n  watcher_store_path TEXT,\n  target_session_key TEXT NOT NULL,\n  last_seen_sequence INTEGER NOT NULL DEFAULT 0,\n  notified_sequence INTEGER NOT NULL DEFAULT 0,\n  material_sequence INTEGER NOT NULL DEFAULT 0,\n  provenance TEXT NOT NULL DEFAULT 'explicit' CHECK (provenance IN ('explicit', 'ambient-group')),\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (watcher_session_key, target_session_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_watch_cursors_target\n  ON session_watch_cursors(target_session_key);\n\nCREATE TABLE IF NOT EXISTS session_upstream_links (\n  session_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  catalog_id TEXT NOT NULL,\n  host_id TEXT NOT NULL,\n  thread_id TEXT NOT NULL,\n  upstream_kind TEXT NOT NULL,\n  upstream_ref_json TEXT,\n  last_marker_json TEXT,\n  last_scanned_at INTEGER,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  -- (session_key, agent_id) composite identity: under session.scope=\"global\" agents\n  -- share bare keys; a key-only row would let one agent overwrite another's upstream.\n  PRIMARY KEY (session_key, agent_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_upstream_links_catalog_id\n  ON session_upstream_links(catalog_id);\n\nCREATE TABLE IF NOT EXISTS state_leases (\n  scope TEXT NOT NULL,\n  lease_key TEXT NOT NULL,\n  owner TEXT NOT NULL,\n  expires_at INTEGER,\n  heartbeat_at INTEGER,\n  payload_json TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (scope, lease_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_state_leases_expiry\n  ON state_leases(expires_at, scope, lease_key)\n  WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_state_leases_owner\n  ON state_leases(owner);\n\nCREATE TABLE IF NOT EXISTS exec_approvals_config (\n  config_key TEXT NOT NULL PRIMARY KEY,\n  raw_json TEXT NOT NULL,\n  socket_path TEXT,\n  has_socket_token INTEGER NOT NULL,\n  default_security TEXT,\n  default_ask TEXT,\n  default_ask_fallback TEXT,\n  auto_allow_skills INTEGER,\n  agent_count INTEGER NOT NULL,\n  allowlist_count INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS operator_approvals (\n  cursor_id INTEGER NOT NULL,\n  approval_id TEXT NOT NULL PRIMARY KEY CHECK (\n    length(approval_id) > 0 AND approval_id NOT IN ('.', '..')\n  ),\n  resolution_ref TEXT NOT NULL CHECK (\n    length(resolution_ref) = 43 AND resolution_ref NOT GLOB '*[^A-Za-z0-9_-]*'\n  ),\n  kind TEXT NOT NULL CHECK (kind IN ('exec', 'plugin', 'system-agent')),\n  status TEXT NOT NULL CHECK (status IN ('pending', 'allowed', 'denied', 'expired', 'cancelled')),\n  presentation_json TEXT NOT NULL,\n  requested_by_device_id TEXT,\n  requested_by_client_id TEXT,\n  requested_by_device_token_auth INTEGER NOT NULL DEFAULT 0,\n  reviewer_device_ids_json TEXT NOT NULL,\n  source_agent_id TEXT,\n  source_session_key TEXT,\n  source_session_id TEXT,\n  source_run_id TEXT,\n  source_tool_call_id TEXT,\n  source_tool_name TEXT,\n  audience_session_keys_json TEXT NOT NULL,\n  runtime_epoch TEXT NOT NULL,\n  created_at_ms INTEGER NOT NULL,\n  expires_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  decision TEXT CHECK (decision IN ('allow-once', 'allow-always', 'deny')),\n  terminal_reason TEXT CHECK (\n    terminal_reason IN (\n      'user',\n      'timeout',\n      'malformed-verdict',\n      'no-route',\n      'run-aborted',\n      'gateway-restart',\n      'storage-corrupt'\n    )\n  ),\n  resolved_at_ms INTEGER,\n  resolver_kind TEXT CHECK (resolver_kind IN ('device', 'channel', 'runtime', 'system')),\n  resolver_id TEXT,\n  consumed_at_ms INTEGER,\n  consumed_by TEXT,\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 (\n    (\n      status = 'pending'\n      AND decision IS NULL\n      AND terminal_reason IS NULL\n      AND resolved_at_ms IS NULL\n      AND resolver_kind IS NULL\n      AND resolver_id IS NULL\n      AND consumed_at_ms IS NULL\n      AND consumed_by IS NULL\n    )\n    OR (\n      status = 'allowed'\n      AND decision IN ('allow-once', 'allow-always')\n      AND terminal_reason = 'user'\n      AND resolved_at_ms IS NOT NULL\n      AND resolver_kind IS NOT NULL\n    )\n    OR (\n      status = 'denied'\n      AND decision = 'deny'\n      AND terminal_reason IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')\n      AND resolved_at_ms IS NOT NULL\n      AND resolver_kind IS NOT NULL\n      AND consumed_at_ms IS NULL\n      AND consumed_by IS NULL\n    )\n    OR (\n      status = 'expired'\n      AND decision = 'deny'\n      AND terminal_reason = 'timeout'\n      AND resolved_at_ms IS NOT NULL\n      AND resolver_kind IS NOT NULL\n      AND consumed_at_ms IS NULL\n      AND consumed_by IS NULL\n    )\n    OR (\n      status = 'cancelled'\n      AND decision = 'deny'\n      AND terminal_reason IN ('run-aborted', 'gateway-restart')\n      AND resolved_at_ms IS NOT NULL\n      AND resolver_kind IS NOT NULL\n      AND consumed_at_ms IS NULL\n      AND consumed_by IS NULL\n    )\n  ),\n  CHECK (\n    (consumed_at_ms IS NULL AND consumed_by IS NULL)\n    OR (\n      status = 'allowed'\n      AND decision = 'allow-once'\n      AND consumed_at_ms IS NOT NULL\n      AND consumed_by IS NOT NULL\n    )\n  )\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_cursor_id\n  ON operator_approvals(cursor_id);\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_status_expiry\n  ON operator_approvals(status, expires_at_ms, approval_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref\n  ON operator_approvals(resolution_ref);\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_source_session_created\n  ON operator_approvals(source_session_key, created_at_ms DESC, approval_id);\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_source_run_resolved\n  ON operator_approvals(source_run_id, resolved_at_ms, approval_id)\n  WHERE source_run_id IS NOT NULL AND resolved_at_ms IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_resolved\n  ON operator_approvals(resolved_at_ms, approval_id)\n  WHERE resolved_at_ms IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_runtime_pending\n  ON operator_approvals(runtime_epoch, approval_id)\n  WHERE status = 'pending';\n\nCREATE TABLE IF NOT EXISTS operator_approval_execution_identities (\n  approval_id TEXT NOT NULL PRIMARY KEY\n    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n  source_context_id TEXT NOT NULL CHECK (\n    length(source_context_id) BETWEEN 1 AND 256 AND source_context_id = trim(source_context_id)\n  ),\n  source_execution_id TEXT NOT NULL CHECK (\n    length(source_execution_id) BETWEEN 1 AND 256 AND source_execution_id = trim(source_execution_id)\n  )\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS operator_approval_standing_grants (\n  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),\n  minted_by_approval_id TEXT NOT NULL\n    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),\n  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),\n  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),\n  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),\n  created_at_ms INTEGER NOT NULL,\n  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),\n  revoked_at_ms INTEGER,\n  revoked_by TEXT,\n  last_used_at_ms INTEGER,\n  use_count INTEGER NOT NULL DEFAULT 0\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding\n  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);\n\nCREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (\n  grant_id TEXT NOT NULL PRIMARY KEY\n    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,\n  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS schema_meta (\n  meta_key TEXT NOT NULL PRIMARY KEY,\n  role TEXT NOT NULL,\n  schema_version INTEGER NOT NULL,\n  agent_id TEXT,\n  app_version TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS config_machine_state (\n  state_key TEXT NOT NULL PRIMARY KEY,\n  value_json TEXT NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS device_pairing_pending (\n  request_id TEXT NOT NULL PRIMARY KEY,\n  device_id TEXT NOT NULL,\n  public_key TEXT NOT NULL,\n  display_name TEXT,\n  platform TEXT,\n  device_family TEXT,\n  client_id TEXT,\n  client_mode TEXT,\n  browser_origin TEXT,\n  role TEXT,\n  roles_json TEXT,\n  scopes_json TEXT,\n  remote_ip TEXT,\n  silent INTEGER,\n  is_repair INTEGER,\n  ts INTEGER NOT NULL,\n  refreshed_at_ms INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_pairing_pending_device\n  ON device_pairing_pending(device_id, ts DESC);\n\nCREATE TABLE IF NOT EXISTS device_pairing_paired (\n  device_id TEXT NOT NULL PRIMARY KEY,\n  public_key TEXT NOT NULL,\n  display_name TEXT,\n  operator_label TEXT,\n  platform TEXT,\n  device_family TEXT,\n  client_id TEXT,\n  client_mode TEXT,\n  browser_origin TEXT,\n  role TEXT,\n  roles_json TEXT,\n  scopes_json TEXT,\n  approved_scopes_json TEXT,\n  remote_ip TEXT,\n  tokens_json TEXT,\n  approved_via TEXT,\n  node_surface_json TEXT,\n  pending_node_surface_json TEXT,\n  created_at_ms INTEGER NOT NULL,\n  approved_at_ms INTEGER NOT NULL,\n  last_seen_at_ms INTEGER,\n  last_seen_reason TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_pairing_paired_approved\n  ON device_pairing_paired(approved_at_ms DESC, device_id);\n\nCREATE TABLE IF NOT EXISTS device_bootstrap_tokens (\n  token_key TEXT NOT NULL PRIMARY KEY,\n  token TEXT NOT NULL,\n  setup_id TEXT,\n  ts INTEGER NOT NULL,\n  device_id TEXT,\n  public_key TEXT,\n  profile_json TEXT,\n  redeemed_profile_json TEXT,\n  pending_profile_json TEXT,\n  issued_at_ms INTEGER NOT NULL,\n  last_used_at_ms INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_bootstrap_tokens_ts\n  ON device_bootstrap_tokens(ts);\n\n-- Terminal outcome of a redeemed setup credential. The bootstrap row is deleted\n-- on redemption, so this is the only durable proof a setup code succeeded; the\n-- presenting client reconciles it when the completion broadcast is missed.\n-- Non-secret only: never the bootstrap token or anything derived from it.\n-- Bounded by retention to a handful of live rows, so the primary key is the\n-- only access path worth having.\nCREATE TABLE IF NOT EXISTS device_pair_setup_completions (\n  setup_id TEXT NOT NULL PRIMARY KEY,\n  device_id TEXT NOT NULL,\n  device_name TEXT,\n  access TEXT NOT NULL,\n  completed_at_ms INTEGER NOT NULL,\n  delivery_state TEXT NOT NULL CHECK (delivery_state IN ('uncertain', 'confirmed')),\n  retain_until_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS device_pairing_join_codes (\n  shortcode TEXT,\n  payload_json TEXT,\n  created_at_ms INTEGER,\n  expires_at_ms INTEGER\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS macos_port_guardian_records (\n  pid INTEGER NOT NULL PRIMARY KEY,\n  port INTEGER NOT NULL,\n  command TEXT NOT NULL,\n  mode TEXT NOT NULL,\n  timestamp REAL NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_macos_port_guardian_records_port\n  ON macos_port_guardian_records(port, timestamp DESC);\n\nCREATE TABLE IF NOT EXISTS workspace_setup_state (\n  workspace_key TEXT NOT NULL PRIMARY KEY,\n  -- NULL only for attestation-only rows whose legacy source never recorded a\n  -- path (orphan hashed-key attestations); setup rows always carry one.\n  workspace_path TEXT,\n  -- NULL setup columns mean an attestation-only row: replaceWorkspaceAttestation\n  -- may record hashes before any setup milestone exists for the workspace.\n  version INTEGER,\n  bootstrap_seeded_at TEXT,\n  setup_completed_at TEXT,\n  updated_at INTEGER,\n  attested_at_ms INTEGER,\n  attestation_updated_at_ms INTEGER,\n  CHECK (version IS NULL OR workspace_path IS NOT NULL)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_workspace_setup_state_path\n  ON workspace_setup_state(workspace_path);\n\nCREATE TABLE IF NOT EXISTS workspace_path_aliases (\n  alias_key TEXT NOT NULL PRIMARY KEY,\n  alias_path TEXT NOT NULL,\n  workspace_key TEXT NOT NULL,\n  workspace_path TEXT NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_workspace_path_aliases_workspace\n  ON workspace_path_aliases(workspace_key);\n\n\n\nCREATE TABLE IF NOT EXISTS workspace_generated_bootstrap_hashes (\n  workspace_key TEXT NOT NULL,\n  filename TEXT NOT NULL,\n  sha256 TEXT NOT NULL,\n  PRIMARY KEY (workspace_key, filename),\n  FOREIGN KEY (workspace_key) REFERENCES workspace_setup_state(workspace_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS native_hook_relay_bridges (\n  relay_id TEXT NOT NULL PRIMARY KEY,\n  pid INTEGER NOT NULL,\n  hostname TEXT NOT NULL,\n  port INTEGER NOT NULL,\n  token TEXT NOT NULL,\n  expires_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_native_hook_relay_bridges_expires\n  ON native_hook_relay_bridges(expires_at_ms, relay_id);\n\nCREATE TABLE IF NOT EXISTS managed_outgoing_image_records (\n  attachment_id TEXT NOT NULL PRIMARY KEY,\n  session_key TEXT NOT NULL,\n  agent_id TEXT,\n  message_id TEXT,\n  created_at TEXT NOT NULL,\n  updated_at TEXT,\n  retention_class TEXT,\n  alt TEXT NOT NULL,\n  original_media_root TEXT NOT NULL,\n  original_media_id TEXT NOT NULL,\n  original_media_subdir TEXT NOT NULL,\n  original_content_type TEXT NOT NULL,\n  original_width INTEGER,\n  original_height INTEGER,\n  original_size_bytes INTEGER,\n  original_filename TEXT,\n  record_json TEXT NOT NULL,\n  cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_session\n  ON managed_outgoing_image_records(session_key, created_at DESC, attachment_id);\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_message\n  ON managed_outgoing_image_records(session_key, message_id, attachment_id)\n  WHERE message_id IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_session\n  ON managed_outgoing_image_records(session_key, agent_id, created_at DESC, attachment_id);\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_message\n  ON managed_outgoing_image_records(session_key, agent_id, message_id, attachment_id)\n  WHERE message_id IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS channel_pairing_requests (\n  channel_key TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  request_id TEXT NOT NULL,\n  code TEXT NOT NULL,\n  created_at TEXT NOT NULL,\n  last_seen_at TEXT NOT NULL,\n  meta_json TEXT,\n  PRIMARY KEY (channel_key, account_id, request_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_code\n  ON channel_pairing_requests(channel_key, code);\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_created\n  ON channel_pairing_requests(channel_key, created_at, request_id);\n\nCREATE TABLE IF NOT EXISTS channel_pairing_allow_entries (\n  channel_key TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  entry TEXT NOT NULL,\n  sort_order INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (channel_key, account_id, entry)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_allow_account\n  ON channel_pairing_allow_entries(channel_key, account_id, sort_order, entry);\n\nCREATE TABLE IF NOT EXISTS web_push_subscriptions (\n  endpoint_hash TEXT NOT NULL PRIMARY KEY,\n  subscription_id TEXT NOT NULL UNIQUE,\n  endpoint TEXT NOT NULL,\n  p256dh TEXT NOT NULL,\n  auth TEXT NOT NULL,\n  device_id TEXT,\n  user_profile_id TEXT,\n  preferences_json TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_updated\n  ON web_push_subscriptions(updated_at_ms DESC, subscription_id);\n\nCREATE TABLE IF NOT EXISTS web_push_approval_deliveries (\n  approval_id TEXT NOT NULL\n    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n  subscription_id TEXT NOT NULL\n    REFERENCES web_push_subscriptions(subscription_id) ON DELETE CASCADE,\n  device_id TEXT NOT NULL,\n  user_profile_id TEXT,\n  prepared_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (approval_id, subscription_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_web_push_approval_deliveries_subscription\n  ON web_push_approval_deliveries(subscription_id, approval_id);\n\nCREATE TABLE IF NOT EXISTS apns_registrations (\n  node_id TEXT NOT NULL PRIMARY KEY,\n  transport TEXT NOT NULL,\n  token TEXT,\n  relay_handle TEXT,\n  send_grant TEXT,\n  installation_id TEXT,\n  relay_origin TEXT,\n  topic TEXT NOT NULL,\n  environment TEXT NOT NULL,\n  distribution TEXT,\n  token_debug_suffix TEXT,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_apns_registrations_updated\n  ON apns_registrations(updated_at_ms DESC, node_id);\n\nCREATE TABLE IF NOT EXISTS apns_registration_tombstones (\n  node_id TEXT NOT NULL PRIMARY KEY,\n  deleted_at_ms INTEGER NOT NULL\n) STRICT;\n\n-- Node-host-owned launch journal. The descriptor and its credential remain\n-- process memory only; this table records bounded supervision facts.\nCREATE TABLE IF NOT EXISTS node_worker_launches (\n  launch_id TEXT NOT NULL PRIMARY KEY\n    CHECK (length(launch_id) BETWEEN 1 AND 256 AND instr(launch_id, char(0)) = 0),\n  plan_hash TEXT NOT NULL\n    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),\n  gateway_namespace TEXT NOT NULL\n    CHECK (\n      length(gateway_namespace) BETWEEN 1 AND 128\n      AND gateway_namespace NOT GLOB '*[^A-Za-z0-9._-]*'\n      AND gateway_namespace GLOB '[A-Za-z0-9]*'\n    ),\n  environment_id TEXT NOT NULL\n    CHECK (length(environment_id) BETWEEN 1 AND 256 AND instr(environment_id, char(0)) = 0),\n  session_id TEXT NOT NULL\n    CHECK (length(session_id) BETWEEN 1 AND 256 AND instr(session_id, char(0)) = 0),\n  owner_epoch INTEGER NOT NULL CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),\n  placement_generation INTEGER NOT NULL\n    CHECK (placement_generation BETWEEN 0 AND 9007199254740991),\n  run_id TEXT NOT NULL\n    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),\n  state TEXT NOT NULL\n    CHECK (state IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled')),\n  supervisor_pid INTEGER NOT NULL CHECK (supervisor_pid BETWEEN 1 AND 2147483647),\n  supervisor_start_time INTEGER NOT NULL\n    CHECK (supervisor_start_time BETWEEN 0 AND 9007199254740991),\n  worker_pid INTEGER CHECK (worker_pid IS NULL OR worker_pid BETWEEN 1 AND 2147483647),\n  worker_start_time INTEGER CHECK (\n    worker_start_time IS NULL OR worker_start_time BETWEEN 0 AND 9007199254740991\n  ),\n  result_json TEXT CHECK (\n    result_json IS NULL\n    OR (\n      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536\n      AND instr(result_json, char(0)) = 0\n      AND json_valid(result_json)\n    )\n  ),\n  error_text TEXT CHECK (\n    error_text IS NULL\n    OR (\n      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096\n      AND instr(error_text, char(0)) = 0\n      AND instr(error_text, char(10)) = 0\n      AND instr(error_text, char(13)) = 0\n    )\n  ),\n  completed_at_ms INTEGER CHECK (\n    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991\n  ),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n  updated_at_ms INTEGER NOT NULL CHECK (\n    updated_at_ms BETWEEN created_at_ms AND 9007199254740991\n  ),\n  CHECK ((worker_pid IS NULL) = (worker_start_time IS NULL)),\n  CHECK (\n    (state = 'pending'\n      AND worker_pid IS NULL AND result_json IS NULL AND error_text IS NULL\n      AND completed_at_ms IS NULL)\n    OR\n    (state = 'running'\n      AND worker_pid IS NOT NULL AND result_json IS NULL AND error_text IS NULL\n      AND completed_at_ms IS NULL)\n    OR\n    (state = 'completed'\n      AND result_json IS NOT NULL AND error_text IS NULL\n      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n    OR\n    (state IN ('failed', 'interrupted', 'cancelled')\n      AND result_json IS NULL AND error_text IS NOT NULL\n      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n  )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_node_worker_launches_terminal_completed\n  ON node_worker_launches(completed_at_ms, launch_id)\n  WHERE completed_at_ms IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS node_worker_launch_boots (\n  launch_id TEXT NOT NULL PRIMARY KEY\n    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n  boot_id TEXT CHECK (boot_id IS NULL OR length(boot_id) BETWEEN 1 AND 128)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS node_worker_launch_containers (\n  launch_id TEXT PRIMARY KEY,\n  container_json TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS node_worker_launch_cleanup (\n  launch_id TEXT NOT NULL PRIMARY KEY\n    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n  cleanup_mode TEXT NOT NULL CHECK (cleanup_mode IN ('process-group', 'owned-anchor')),\n  lineage_settled INTEGER CHECK (lineage_settled IS NULL OR lineage_settled = 1)\n) STRICT;\n\n-- Older readers retain owned-anchor custody: lineage EOF is not this certificate.\nCREATE TABLE IF NOT EXISTS node_worker_launch_process_scopes (\n  launch_id TEXT NOT NULL PRIMARY KEY\n    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n  scope_kind TEXT NOT NULL CHECK (scope_kind = 'linux-subreaper'),\n  descendants_reaped INTEGER CHECK (descendants_reaped IS NULL OR descendants_reaped = 1)\n) STRICT;\n\n-- Turn receipts have a shorter lifetime than their physical worker owner.\n-- Keeping the launch running preserves capacity and predecessor cleanup semantics.\nCREATE TABLE IF NOT EXISTS node_worker_turns (\n  turn_id TEXT NOT NULL PRIMARY KEY\n    CHECK (length(turn_id) BETWEEN 1 AND 256 AND instr(turn_id, char(0)) = 0),\n  owner_launch_id TEXT NOT NULL\n    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n  plan_hash TEXT NOT NULL\n    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),\n  run_id TEXT NOT NULL\n    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),\n  state TEXT NOT NULL\n    CHECK (state IN ('running', 'completed', 'failed', 'interrupted', 'cancelled')),\n  result_json TEXT CHECK (\n    result_json IS NULL\n    OR (\n      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536\n      AND instr(result_json, char(0)) = 0\n      AND json_valid(result_json)\n    )\n  ),\n  error_text TEXT CHECK (\n    error_text IS NULL\n    OR (\n      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096\n      AND instr(error_text, char(0)) = 0\n      AND instr(error_text, char(10)) = 0\n      AND instr(error_text, char(13)) = 0\n    )\n  ),\n  completed_at_ms INTEGER CHECK (\n    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991\n  ),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n  updated_at_ms INTEGER NOT NULL CHECK (\n    updated_at_ms BETWEEN created_at_ms AND 9007199254740991\n  ),\n  CHECK (\n    (state = 'running'\n      AND result_json IS NULL AND error_text IS NULL AND completed_at_ms IS NULL)\n    OR\n    (state = 'completed'\n      AND result_json IS NOT NULL AND error_text IS NULL\n      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n    OR\n    (state IN ('failed', 'interrupted', 'cancelled')\n      AND result_json IS NULL AND error_text IS NOT NULL\n      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n  )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_node_worker_turns_terminal_completed\n  ON node_worker_turns(completed_at_ms, turn_id)\n  WHERE completed_at_ms IS NOT NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_node_worker_turns_active_owner\n  ON node_worker_turns(owner_launch_id)\n  WHERE state = 'running';\n\nCREATE TABLE IF NOT EXISTS config_health_entries (\n  config_path TEXT NOT NULL PRIMARY KEY,\n  last_known_good_json TEXT,\n  last_promoted_good_json TEXT,\n  last_observed_suspicious_signature TEXT,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS clawhub_promotion_claims (\n  slug TEXT NOT NULL PRIMARY KEY,\n  provider TEXT,\n  model_keys_json TEXT NOT NULL,\n  ends_at_ms INTEGER NOT NULL,\n  claimed_at_ms INTEGER NOT NULL\n) STRICT;\n\n\n\nCREATE TABLE IF NOT EXISTS official_external_plugin_catalog_snapshots (\n  feed_url TEXT NOT NULL PRIMARY KEY,\n  body TEXT NOT NULL,\n  status INTEGER NOT NULL,\n  etag TEXT,\n  last_modified TEXT,\n  checksum TEXT NOT NULL,\n  saved_at TEXT NOT NULL,\n  trust_mode TEXT,\n  trust_key_id TEXT,\n  trust_signature_count INTEGER,\n  trust_threshold INTEGER,\n  trust_verified_at TEXT,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_official_external_plugin_catalog_snapshots_updated\n  ON official_external_plugin_catalog_snapshots(updated_at_ms DESC, feed_url);\n\nCREATE TABLE IF NOT EXISTS update_runs (\n  run_id TEXT PRIMARY KEY NOT NULL,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  trigger TEXT NOT NULL CHECK (trigger IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api')),\n  phase TEXT NOT NULL CHECK (phase IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished')),\n  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped')),\n  reason TEXT,\n  origin_json TEXT NOT NULL CHECK (length(CAST(origin_json AS BLOB)) <= 16384),\n  target_json TEXT NOT NULL CHECK (length(CAST(target_json AS BLOB)) <= 16384),\n  before_json TEXT NOT NULL CHECK (length(CAST(before_json AS BLOB)) <= 16384),\n  after_json TEXT NOT NULL CHECK (length(CAST(after_json AS BLOB)) <= 16384),\n  steps_json TEXT NOT NULL CHECK (length(CAST(steps_json AS BLOB)) <= 16384),\n  verification_json TEXT NOT NULL CHECK (length(CAST(verification_json AS BLOB)) <= 16384),\n  repair_json TEXT NOT NULL CHECK (length(CAST(repair_json AS BLOB)) <= 16384),\n  confirmed_at_ms INTEGER,\n  finished_at_ms INTEGER,\n  downtime_ms INTEGER,\n  CHECK ((status = 'running' AND phase != 'finished' AND finished_at_ms IS NULL) OR\n    (status != 'running' AND phase = 'finished' AND finished_at_ms IS NOT NULL))\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_update_runs_created\n  ON update_runs(created_at_ms DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_update_runs_active\n  ON update_runs(status, created_at_ms DESC, run_id);\n\nCREATE TABLE IF NOT EXISTS gateway_restart_sentinel (\n  sentinel_key TEXT NOT NULL PRIMARY KEY,\n  version INTEGER NOT NULL,\n  kind TEXT NOT NULL,\n  status TEXT NOT NULL,\n  ts INTEGER NOT NULL,\n  session_key TEXT,\n  thread_id TEXT,\n  delivery_channel TEXT,\n  delivery_to TEXT,\n  delivery_account_id TEXT,\n  message TEXT,\n  continuation_json TEXT,\n  doctor_hint TEXT,\n  stats_json TEXT,\n  payload_json TEXT NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_restart_sentinel_ts\n  ON gateway_restart_sentinel(ts DESC, sentinel_key);\n\nCREATE TABLE IF NOT EXISTS gateway_restart_intent (\n  intent_key TEXT NOT NULL PRIMARY KEY,\n  kind TEXT NOT NULL,\n  pid INTEGER NOT NULL,\n  created_at INTEGER NOT NULL,\n  reason TEXT,\n  force INTEGER,\n  wait_ms INTEGER,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS gateway_restart_handoff (\n  handoff_key TEXT NOT NULL PRIMARY KEY,\n  kind TEXT NOT NULL,\n  version INTEGER NOT NULL,\n  intent_id TEXT NOT NULL,\n  pid INTEGER NOT NULL,\n  process_instance_id TEXT,\n  created_at INTEGER NOT NULL,\n  expires_at INTEGER NOT NULL,\n  reason TEXT,\n  restart_trace_started_at INTEGER,\n  restart_trace_last_at INTEGER,\n  source TEXT NOT NULL,\n  restart_kind TEXT NOT NULL,\n  supervisor_mode TEXT NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_restart_handoff_expiry\n  ON gateway_restart_handoff(expires_at, pid);\n\nCREATE TABLE IF NOT EXISTS gateway_boot_lifecycle (\n  boot_id TEXT NOT NULL PRIMARY KEY,\n  pid INTEGER NOT NULL,\n  started_at_ms INTEGER NOT NULL,\n  completed_at_ms INTEGER,\n  outcome TEXT,\n  startup_reason TEXT,\n  reason TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_boot_lifecycle_started\n  ON gateway_boot_lifecycle(started_at_ms);\n\nCREATE TABLE IF NOT EXISTS acp_sessions (\n  session_key TEXT NOT NULL PRIMARY KEY,\n  session_id TEXT,\n  backend TEXT NOT NULL,\n  agent TEXT NOT NULL,\n  runtime_session_name TEXT NOT NULL,\n  identity_json TEXT,\n  resume_agent_session_id TEXT,\n  resume_acpx_session_id TEXT,\n  mode TEXT NOT NULL,\n  runtime_options_json TEXT,\n  cwd TEXT,\n  state TEXT NOT NULL,\n  last_activity_at INTEGER NOT NULL,\n  last_error TEXT,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_state_activity\n  ON acp_sessions(state, last_activity_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_agent_activity\n  ON acp_sessions(agent, last_activity_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_agent\n  ON acp_sessions(resume_agent_session_id);\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_acpx\n  ON acp_sessions(resume_acpx_session_id);\n\nCREATE TABLE IF NOT EXISTS acp_replay_sessions (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  session_key TEXT NOT NULL,\n  cwd TEXT NOT NULL,\n  complete INTEGER NOT NULL,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  next_seq INTEGER NOT NULL,\n  -- Running estimate of this session's ledger footprint (row overhead plus\n  -- all event rows), maintained at insert/trim so budget checks never scan\n  -- acp_replay_events (#100622).\n  estimated_bytes INTEGER NOT NULL DEFAULT 0\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_key_updated\n  ON acp_replay_sessions(session_key, complete, updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_updated\n  ON acp_replay_sessions(updated_at DESC, session_id);\n\nCREATE TABLE IF NOT EXISTS acp_replay_events (\n  session_id TEXT NOT NULL,\n  seq INTEGER NOT NULL,\n  at INTEGER NOT NULL,\n  session_key TEXT NOT NULL,\n  run_id TEXT,\n  update_json TEXT NOT NULL,\n  estimated_bytes INTEGER NOT NULL DEFAULT 0,\n  PRIMARY KEY (session_id, seq),\n  FOREIGN KEY (session_id) REFERENCES acp_replay_sessions(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_databases (\n  agent_id TEXT NOT NULL,\n  path TEXT NOT NULL,\n  schema_version INTEGER NOT NULL,\n  last_seen_at INTEGER NOT NULL,\n  size_bytes INTEGER,\n  PRIMARY KEY (agent_id, path)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_deletion_journal (\n  agent_id TEXT PRIMARY KEY,\n  operation_id TEXT NOT NULL DEFAULT '',\n  phase TEXT,\n  agent_dir TEXT NOT NULL,\n  workspace_dir TEXT NOT NULL,\n  sessions_dir TEXT NOT NULL,\n  database_paths_json TEXT NOT NULL DEFAULT '[]',\n  cleanup_paths_json TEXT NOT NULL DEFAULT '[]',\n  created_at INTEGER NOT NULL,\n  cleanup_completed INTEGER NOT NULL DEFAULT 0,\n  delete_files INTEGER NOT NULL DEFAULT 1\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_provenance (\n  agent_id TEXT PRIMARY KEY,\n  created_via TEXT NOT NULL CHECK (created_via IN ('operator', 'agent', 'template')),\n  creator_agent_id TEXT,\n  created_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_database_leases (\n  lease_id TEXT PRIMARY KEY,\n  agent_id TEXT NOT NULL,\n  path TEXT NOT NULL,\n  owner_pid INTEGER NOT NULL,\n  owner_start_time INTEGER,\n  opened_at INTEGER NOT NULL,\n  provenance TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS plugin_state_entries (\n  plugin_id TEXT NOT NULL,\n  namespace TEXT NOT NULL,\n  entry_key TEXT NOT NULL,\n  value_json TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  expires_at INTEGER,\n  PRIMARY KEY (plugin_id, namespace, entry_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_state_expiry\n  ON plugin_state_entries(expires_at)\n  WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_state_listing\n  ON plugin_state_entries(plugin_id, namespace, created_at, entry_key, expires_at);\n\nCREATE TABLE IF NOT EXISTS channel_ingress_events (\n  queue_name TEXT NOT NULL,\n  event_id TEXT NOT NULL,\n  channel_id TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  status TEXT NOT NULL,\n  lane_key TEXT,\n  payload_json TEXT NOT NULL,\n  metadata_json TEXT,\n  received_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  claim_token TEXT,\n  claim_owner TEXT,\n  claimed_at INTEGER,\n  attempts INTEGER NOT NULL DEFAULT 0,\n  last_attempt_at INTEGER,\n  last_error TEXT,\n  failed_reason TEXT,\n  failed_at INTEGER,\n  completed_at INTEGER,\n  completed_metadata_json TEXT,\n  PRIMARY KEY (queue_name, event_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_pending\n  ON channel_ingress_events(queue_name, status, received_at, event_id);\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_claims\n  ON channel_ingress_events(queue_name, status, claimed_at);\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_lane\n  ON channel_ingress_events(queue_name, status, lane_key);\n\nCREATE TABLE IF NOT EXISTS plugin_blob_entries (\n  plugin_id TEXT NOT NULL,\n  namespace TEXT NOT NULL,\n  entry_key TEXT NOT NULL,\n  metadata_json TEXT NOT NULL,\n  blob BLOB NOT NULL,\n  created_at INTEGER NOT NULL,\n  expires_at INTEGER,\n  PRIMARY KEY (plugin_id, namespace, entry_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_blob_expiry\n  ON plugin_blob_entries(expires_at)\n  WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_blob_listing\n  ON plugin_blob_entries(plugin_id, namespace, created_at, entry_key);\n\nCREATE TABLE IF NOT EXISTS skill_uploads (\n  upload_id TEXT NOT NULL PRIMARY KEY,\n  kind TEXT NOT NULL,\n  slug TEXT NOT NULL,\n  force INTEGER NOT NULL,\n  size_bytes INTEGER NOT NULL,\n  sha256 TEXT,\n  actual_sha256 TEXT,\n  received_bytes INTEGER NOT NULL,\n  archive_blob BLOB NOT NULL,\n  created_at INTEGER NOT NULL,\n  expires_at INTEGER NOT NULL,\n  committed INTEGER NOT NULL,\n  committed_at INTEGER,\n  idempotency_key_hash TEXT UNIQUE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_skill_uploads_expiry\n  ON skill_uploads(expires_at);\n\nCREATE INDEX IF NOT EXISTS idx_skill_uploads_idempotency\n  ON skill_uploads(idempotency_key_hash)\n  WHERE idempotency_key_hash IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS skill_upload_chunks (\n  upload_id TEXT NOT NULL,\n  byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0),\n  size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),\n  chunk_blob BLOB NOT NULL,\n  PRIMARY KEY (upload_id, byte_offset),\n  FOREIGN KEY (upload_id) REFERENCES skill_uploads(upload_id) ON DELETE CASCADE,\n  CHECK (length(chunk_blob) = size_bytes)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_sessions (\n  id TEXT NOT NULL PRIMARY KEY,\n  started_at INTEGER NOT NULL,\n  ended_at INTEGER,\n  mode TEXT NOT NULL,\n  source_scope TEXT NOT NULL,\n  source_process TEXT NOT NULL,\n  proxy_url TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_blobs (\n  blob_id TEXT NOT NULL PRIMARY KEY,\n  content_type TEXT,\n  encoding TEXT NOT NULL,\n  size_bytes INTEGER NOT NULL,\n  sha256 TEXT NOT NULL,\n  data BLOB NOT NULL,\n  created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_events (\n  id INTEGER NOT NULL PRIMARY KEY,\n  session_id TEXT NOT NULL,\n  ts INTEGER NOT NULL,\n  source_scope TEXT NOT NULL,\n  source_process TEXT NOT NULL,\n  protocol TEXT NOT NULL,\n  direction TEXT NOT NULL,\n  kind TEXT NOT NULL,\n  flow_id TEXT NOT NULL,\n  method TEXT,\n  host TEXT,\n  path TEXT,\n  status INTEGER,\n  close_code INTEGER,\n  content_type TEXT,\n  headers_json TEXT,\n  data_text TEXT,\n  data_blob_id TEXT,\n  data_sha256 TEXT,\n  error_text TEXT,\n  meta_json TEXT,\n  FOREIGN KEY (session_id) REFERENCES capture_sessions(id) ON DELETE CASCADE,\n  FOREIGN KEY (data_blob_id) REFERENCES capture_blobs(blob_id) ON DELETE SET NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS capture_events_session_ts_idx\n  ON capture_events(session_id, ts);\n\nCREATE INDEX IF NOT EXISTS capture_events_flow_idx\n  ON capture_events(flow_id, ts);\n\nCREATE TABLE IF NOT EXISTS sandbox_registry_entries (\n  registry_kind TEXT NOT NULL,\n  container_name TEXT NOT NULL,\n  session_key TEXT,\n  backend_id TEXT,\n  runtime_label TEXT,\n  image TEXT,\n  created_at_ms INTEGER,\n  last_used_at_ms INTEGER,\n  config_label_kind TEXT,\n  config_hash TEXT,\n  cdp_port INTEGER,\n  no_vnc_port INTEGER,\n  entry_json TEXT NOT NULL,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (registry_kind, container_name)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_updated\n  ON sandbox_registry_entries(registry_kind, updated_at DESC, container_name);\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_session\n  ON sandbox_registry_entries(registry_kind, session_key, last_used_at_ms DESC, container_name)\n  WHERE session_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_last_used\n  ON sandbox_registry_entries(registry_kind, last_used_at_ms DESC, container_name)\n  WHERE last_used_at_ms IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS sandbox_persistent_execs (\n  owner_key TEXT NOT NULL PRIMARY KEY,\n  source_identity TEXT NOT NULL,\n  attempt_id TEXT NOT NULL UNIQUE,\n  owner_json TEXT NOT NULL,\n  backend_id TEXT NOT NULL CHECK (backend_id = 'docker'),\n  backend_target_json TEXT NOT NULL,\n  workspace_binding_json TEXT NOT NULL,\n  container_id TEXT NOT NULL,\n  container_name TEXT NOT NULL,\n  container_started_at TEXT NOT NULL,\n  revision INTEGER NOT NULL CHECK (revision > 0),\n  phase TEXT NOT NULL CHECK (phase IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped')),\n  receipt_json TEXT,\n  error TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  CHECK (phase NOT IN ('prepared', 'running') OR receipt_json IS NOT NULL)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container\n  ON sandbox_persistent_execs(container_id, owner_key);\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container_name\n  ON sandbox_persistent_execs(container_name, owner_key);\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_source\n  ON sandbox_persistent_execs(source_identity, owner_key);\n\nCREATE TABLE IF NOT EXISTS cron_jobs (\n  store_key TEXT NOT NULL,\n  job_id TEXT NOT NULL,\n  declaration_key TEXT,\n  owner_agent_id TEXT,\n  name TEXT NOT NULL,\n  description TEXT,\n  enabled INTEGER NOT NULL,\n  agent_id TEXT,\n  payload_kind TEXT NOT NULL,\n  job_json TEXT NOT NULL,\n  grant_definition_revision TEXT,\n  grant_definition_generation INTEGER,\n  grant_definition_updated_at INTEGER,\n  state_json TEXT NOT NULL DEFAULT '{}',\n  runtime_updated_at_ms INTEGER,\n  schedule_identity TEXT,\n  sort_order INTEGER NOT NULL DEFAULT 0,\n  updated_at INTEGER NOT NULL,\n  PRIMARY KEY (store_key, job_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_cron_jobs_store_order\n  ON cron_jobs(store_key, sort_order ASC, updated_at ASC, job_id);\n\n-- One owner-native receipt is also the durable execution fence. Receipts\n-- survive job deletion so operators can distinguish a run from log inference.\nCREATE TABLE IF NOT EXISTS cron_run_receipts (\n  cursor_id INTEGER NOT NULL,\n  receipt_id TEXT PRIMARY KEY,\n  store_key TEXT NOT NULL,\n  job_id TEXT NOT NULL,\n  config_revision TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  request_run_id TEXT,\n  delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started')),\n  status TEXT NOT NULL,\n  owner_pid INTEGER NOT NULL,\n  owner_start_time INTEGER,\n  started_at_ms INTEGER NOT NULL,\n  finished_at_ms INTEGER,\n  error_text TEXT,\n  CHECK (status IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded')),\n  CHECK (\n    (status = 'running' AND finished_at_ms IS NULL)\n    OR\n    (status != 'running' AND finished_at_ms IS NOT NULL)\n  )\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS cron_run_receipts_cursor_id_idx\n  ON cron_run_receipts(cursor_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_cron_run_receipts_active_job\n  ON cron_run_receipts(store_key, job_id)\n  WHERE status = 'running';\n\nCREATE INDEX IF NOT EXISTS idx_cron_run_receipts_job_history\n  ON cron_run_receipts(store_key, job_id, started_at_ms DESC, receipt_id DESC);\n\n-- Retirement follows the receipt's retention without changing its released shape.\nCREATE TABLE IF NOT EXISTS cron_run_trigger_state_retirements (\n  receipt_id TEXT PRIMARY KEY\n    REFERENCES cron_run_receipts(receipt_id) ON DELETE CASCADE\n) STRICT;\n\n-- Runtime-private authority is independent of job_json so downgraded writers\n-- can rewrite recognized job config without erasing or silently widening it.\nCREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (\n  store_key TEXT NOT NULL,\n  job_id TEXT NOT NULL,\n  authority_json TEXT,\n  authority_input_fingerprint TEXT,\n  recovery_required INTEGER NOT NULL,\n  PRIMARY KEY (store_key, job_id),\n  FOREIGN KEY (store_key, job_id)\n    REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,\n  CHECK (recovery_required IN (0, 1)),\n  CHECK (\n    (recovery_required = 0 AND authority_json IS NOT NULL AND authority_input_fingerprint IS NOT NULL)\n    OR\n    (recovery_required = 1 AND authority_json IS NULL AND authority_input_fingerprint IS NULL)\n  )\n) STRICT;\n\n-- Scratch is separate from cron_jobs so scheduler state writes and downgraded\n-- full-row replacement preserve it. New builds prune rows explicitly on job removal.\n-- content NULL is a tombstone: it keeps the revision lineage monotonic across\n-- unset/recreate so stale compare-and-swap writes cannot resurrect old content.\nCREATE TABLE IF NOT EXISTS cron_job_scratch (\n  store_key TEXT NOT NULL,\n  job_id TEXT NOT NULL,\n  content TEXT,\n  revision INTEGER NOT NULL,\n  source_sha256 TEXT,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (store_key, job_id),\n  CHECK (revision >= 1),\n  CHECK (content IS NULL OR length(CAST(content AS BLOB)) <= 262144)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_cron_job_scratch_store_updated\n  ON cron_job_scratch(store_key, updated_at_ms DESC, job_id);\n\nCREATE TABLE IF NOT EXISTS delivery_queue_entries (\n  queue_name TEXT NOT NULL,\n  id TEXT NOT NULL,\n  status TEXT NOT NULL,\n  entry_kind TEXT,\n  session_key TEXT,\n  channel TEXT,\n  target TEXT,\n  account_id TEXT,\n  retry_count INTEGER NOT NULL DEFAULT 0,\n  last_attempt_at INTEGER,\n  last_error TEXT,\n  recovery_state TEXT,\n  platform_send_started_at INTEGER,\n  entry_json TEXT NOT NULL,\n  retention_id_prefix TEXT,\n  retention_max_age_ms INTEGER,\n  retention_max_entries INTEGER,\n  enqueued_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  failed_at INTEGER,\n  PRIMARY KEY (queue_name, id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_pending\n  ON delivery_queue_entries(queue_name, status, enqueued_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_failed\n  ON delivery_queue_entries(status, queue_name, failed_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_session\n  ON delivery_queue_entries(queue_name, status, session_key, enqueued_at, id)\n  WHERE session_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_target\n  ON delivery_queue_entries(queue_name, status, channel, target, enqueued_at, id)\n  WHERE channel IS NOT NULL AND target IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_bounded_retention\n  ON delivery_queue_entries(queue_name, retention_id_prefix, enqueued_at DESC, id DESC)\n  WHERE status IN ('completed', 'failed') AND recovery_state = 'completed_bounded'\n    AND retention_id_prefix IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS task_runs (\n  task_id TEXT NOT NULL PRIMARY KEY,\n  runtime TEXT NOT NULL,\n  task_kind TEXT,\n  source_id TEXT,\n  requester_session_key TEXT,\n  owner_key TEXT NOT NULL,\n  scope_kind TEXT NOT NULL,\n  child_session_key TEXT,\n  parent_flow_id TEXT,\n  parent_task_id TEXT,\n  agent_id TEXT,\n  requester_agent_id TEXT,\n  run_id TEXT,\n  execution_owner_host TEXT,\n  execution_owner_pid INTEGER,\n  execution_owner_start_identity INTEGER,\n  label TEXT,\n  task TEXT NOT NULL,\n  status TEXT NOT NULL,\n  delivery_status TEXT NOT NULL,\n  notify_policy TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  started_at INTEGER,\n  ended_at INTEGER,\n  last_event_at INTEGER,\n  cleanup_after INTEGER,\n  tool_use_count INTEGER,\n  last_tool_name TEXT,\n  error TEXT,\n  progress_summary TEXT,\n  terminal_summary TEXT,\n  terminal_outcome TEXT,\n  detail_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_task_runs_runtime_run\n  ON task_runs(runtime, run_id, source_id, created_at, task_id);\nCREATE INDEX IF NOT EXISTS idx_task_runs_cron_runtime_order\n  ON task_runs(runtime, created_at, task_id) WHERE runtime = 'cron';\nCREATE INDEX IF NOT EXISTS idx_task_runs_cron_source_order\n  ON task_runs(source_id, created_at, task_id) WHERE runtime = 'cron';\n\nCREATE TABLE IF NOT EXISTS subagent_runs (\n  run_id TEXT NOT NULL PRIMARY KEY,\n  child_session_key TEXT NOT NULL,\n  controller_session_key TEXT,\n  controller_store_path TEXT,\n  requester_session_key TEXT NOT NULL,\n  requester_store_path TEXT,\n  created_at INTEGER NOT NULL,\n  payload_json TEXT NOT NULL DEFAULT '{}'\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_child_session_key\n  ON subagent_runs(child_session_key, created_at DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_requester_session_key\n  ON subagent_runs(requester_session_key, created_at DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_controller_session_key\n  ON subagent_runs(controller_session_key, created_at DESC, run_id);\n\nCREATE TABLE IF NOT EXISTS current_conversation_bindings (\n  binding_key TEXT NOT NULL PRIMARY KEY,\n  binding_id TEXT NOT NULL,\n  target_session_key TEXT NOT NULL,\n  channel TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  conversation_kind TEXT NOT NULL,\n  parent_conversation_id TEXT,\n  conversation_id TEXT NOT NULL,\n  target_kind TEXT NOT NULL,\n  status TEXT NOT NULL,\n  bound_at INTEGER NOT NULL,\n  expires_at INTEGER,\n  metadata_json TEXT,\n  record_json TEXT NOT NULL,\n  updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_target\n  ON current_conversation_bindings(target_session_key, updated_at DESC, binding_key);\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_conversation\n  ON current_conversation_bindings(channel, account_id, conversation_kind, conversation_id);\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_expires\n  ON current_conversation_bindings(expires_at, binding_key);\n\nCREATE TABLE IF NOT EXISTS plugin_binding_approvals (\n  plugin_root TEXT NOT NULL,\n  channel TEXT NOT NULL,\n  account_id TEXT NOT NULL,\n  plugin_id TEXT NOT NULL,\n  plugin_name TEXT,\n  approved_at INTEGER NOT NULL,\n  PRIMARY KEY (plugin_root, channel, account_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_binding_approvals_plugin\n  ON plugin_binding_approvals(plugin_id, approved_at DESC);\n\nCREATE TABLE IF NOT EXISTS task_delivery_state (\n  task_id TEXT NOT NULL PRIMARY KEY,\n  requester_origin_json TEXT,\n  last_notified_event_at INTEGER,\n  FOREIGN KEY (task_id) REFERENCES task_runs(task_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS flow_runs (\n  flow_id TEXT NOT NULL PRIMARY KEY,\n  shape TEXT,\n  sync_mode TEXT NOT NULL DEFAULT 'managed',\n  owner_key TEXT NOT NULL,\n  requester_origin_json TEXT,\n  controller_id TEXT,\n  revision INTEGER NOT NULL DEFAULT 0,\n  status TEXT NOT NULL,\n  notify_policy TEXT NOT NULL,\n  goal TEXT NOT NULL,\n  current_step TEXT,\n  blocked_task_id TEXT,\n  blocked_summary TEXT,\n  state_json TEXT,\n  wait_json TEXT,\n  cancel_requested_at INTEGER,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL,\n  ended_at INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_flow_runs_status ON flow_runs(status);\nCREATE INDEX IF NOT EXISTS idx_flow_runs_owner_key ON flow_runs(owner_key);\nCREATE INDEX IF NOT EXISTS idx_flow_runs_updated_at ON flow_runs(updated_at);\n\n-- Durable meeting-capture sessions are gateway-global rather than agent-session\n-- transcripts. JSON/JSONL files are doctor import inputs or explicit CLI exports.\nCREATE TABLE IF NOT EXISTS meeting_transcript_sessions (\n  started_at_ms INTEGER,\n  session_id TEXT NOT NULL,\n  started_at TEXT NOT NULL,\n  selector TEXT NOT NULL UNIQUE,\n  export_key TEXT NOT NULL,\n  session_slug TEXT NOT NULL,\n  provider_id TEXT NOT NULL,\n  title TEXT,\n  source_json TEXT NOT NULL,\n  source_account_id TEXT,\n  source_guild_id TEXT,\n  source_channel_id TEXT,\n  source_meeting_url TEXT,\n  source_thread_ts TEXT,\n  source_file_id TEXT,\n  stopped_at TEXT,\n  metadata_json TEXT,\n  metadata_agent_id TEXT,\n  export_manifest_json TEXT NOT NULL DEFAULT '{}',\n  export_pending_json TEXT NOT NULL DEFAULT '[]',\n  next_utterance_seq INTEGER NOT NULL DEFAULT 0 CHECK (next_utterance_seq >= 0),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n  PRIMARY KEY (session_id, started_at)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_started\n  ON meeting_transcript_sessions(started_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_chronology\n  ON meeting_transcript_sessions(started_at_ms DESC, session_id ASC, started_at ASC);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_id\n  ON meeting_transcript_sessions(session_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_slug\n  ON meeting_transcript_sessions(session_slug, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_export_key\n  ON meeting_transcript_sessions(export_key);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_source\n  ON meeting_transcript_sessions(provider_id, source_account_id, source_guild_id,\n    source_channel_id, source_meeting_url, source_thread_ts, source_file_id,\n    stopped_at DESC, started_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_account\n  ON meeting_transcript_sessions(source_account_id);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_agent\n  ON meeting_transcript_sessions(metadata_agent_id);\n\nCREATE TABLE IF NOT EXISTS meeting_transcript_utterances (\n  session_id TEXT NOT NULL,\n  session_started_at TEXT NOT NULL,\n  sequence INTEGER NOT NULL CHECK (sequence >= 0),\n  utterance_id TEXT,\n  started_at TEXT,\n  ended_at TEXT,\n  speaker_id TEXT,\n  speaker_label TEXT,\n  text TEXT NOT NULL,\n  final INTEGER CHECK (final IN (0, 1)),\n  metadata_json TEXT,\n  PRIMARY KEY (session_id, session_started_at, sequence),\n  FOREIGN KEY (session_id, session_started_at)\n    REFERENCES meeting_transcript_sessions(session_id, started_at)\n    ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_utterances_id\n  ON meeting_transcript_utterances(session_id, session_started_at, utterance_id)\n  WHERE utterance_id IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS meeting_transcript_summaries (\n  session_id TEXT NOT NULL,\n  session_started_at TEXT NOT NULL,\n  generated_at TEXT,\n  summary_json TEXT,\n  overview TEXT,\n  markdown TEXT,\n  utterance_count INTEGER NOT NULL CHECK (utterance_count >= 0),\n  PRIMARY KEY (session_id, session_started_at),\n  FOREIGN KEY (session_id, session_started_at)\n    REFERENCES meeting_transcript_sessions(session_id, started_at)\n    ON DELETE CASCADE,\n  CHECK (summary_json IS NOT NULL OR markdown IS NOT NULL)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS migration_runs (\n  id TEXT NOT NULL PRIMARY KEY,\n  started_at INTEGER NOT NULL,\n  finished_at INTEGER,\n  status TEXT NOT NULL,\n  report_json TEXT NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_migration_runs_started\n  ON migration_runs(started_at DESC, id);\n\nCREATE TABLE IF NOT EXISTS migration_sources (\n  source_key TEXT NOT NULL PRIMARY KEY,\n  migration_kind TEXT NOT NULL,\n  source_path TEXT NOT NULL,\n  target_table TEXT NOT NULL,\n  source_sha256 TEXT,\n  source_size_bytes INTEGER,\n  source_record_count INTEGER,\n  last_run_id TEXT NOT NULL,\n  status TEXT NOT NULL,\n  imported_at INTEGER NOT NULL,\n  removed_source INTEGER NOT NULL DEFAULT 0,\n  report_json TEXT NOT NULL,\n  FOREIGN KEY (last_run_id) REFERENCES migration_runs(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_migration_sources_path\n  ON migration_sources(source_path, migration_kind, target_table);\n\nCREATE INDEX IF NOT EXISTS idx_migration_sources_run\n  ON migration_sources(last_run_id, source_path);\n\nCREATE TABLE IF NOT EXISTS backup_runs (\n  id TEXT NOT NULL PRIMARY KEY,\n  created_at INTEGER NOT NULL,\n  archive_path TEXT NOT NULL,\n  status TEXT NOT NULL,\n  manifest_json TEXT NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_backup_runs_created\n  ON backup_runs(created_at DESC, id);\n\nCREATE TABLE IF NOT EXISTS worktrees (\n  id TEXT NOT NULL PRIMARY KEY,\n  repo_fingerprint TEXT NOT NULL,\n  repo_root TEXT NOT NULL,\n  path TEXT NOT NULL,\n  branch TEXT NOT NULL,\n  base_ref TEXT NOT NULL,\n  owner_kind TEXT NOT NULL CHECK (owner_kind IN ('manual', 'workboard', 'session')),\n  owner_id TEXT,\n  snapshot_ref TEXT,\n  provisioned_paths_json TEXT,\n  created_at INTEGER NOT NULL,\n  last_active_at INTEGER NOT NULL,\n  removed_at INTEGER,\n  run_end_cleanup_json TEXT,\n  gc_protection_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_worktrees_repo_fingerprint\n  ON worktrees(repo_fingerprint);\n\nCREATE INDEX IF NOT EXISTS idx_worktrees_removed_at\n  ON worktrees(removed_at);\n\nCREATE TABLE IF NOT EXISTS worktree_provisioned_file_chunks (\n  worktree_id TEXT NOT NULL,\n  path TEXT NOT NULL,\n  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),\n  data BLOB NOT NULL,\n  PRIMARY KEY (worktree_id, path, chunk_index)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS worktree_templates (\n  cache_key TEXT NOT NULL PRIMARY KEY,\n  id TEXT NOT NULL UNIQUE,\n  repo_root TEXT NOT NULL,\n  common_dir TEXT NOT NULL,\n  worktree_root TEXT NOT NULL,\n  path TEXT NOT NULL,\n  backend TEXT NOT NULL,\n  source_commit TEXT NOT NULL,\n  content_key TEXT NOT NULL,\n  status TEXT NOT NULL CHECK (status IN ('preparing', 'ready')),\n  created_at INTEGER NOT NULL,\n  last_used_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS projects (\n  id TEXT NOT NULL PRIMARY KEY,\n  display_name TEXT NOT NULL,\n  repo_root TEXT NOT NULL,\n  origin_url TEXT,\n  source TEXT NOT NULL CHECK (source IN ('registered', 'cloned')),\n  created_at_ms INT NOT NULL,\n  updated_at_ms INT NOT NULL\n) STRICT;\n\n-- One explicitly retained, normalized private background per durable profile.\nCREATE TABLE IF NOT EXISTS user_background_images (\n  profile_id TEXT NOT NULL PRIMARY KEY REFERENCES user_profiles(id) ON DELETE CASCADE,\n  asset_id TEXT NOT NULL UNIQUE,\n  image BLOB NOT NULL CHECK (length(image) BETWEEN 1 AND 2097152),\n  width INTEGER NOT NULL CHECK (width BETWEEN 1 AND 2560),\n  height INTEGER NOT NULL CHECK (height BETWEEN 1 AND 2560)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS user_preferences (\n  profile_id TEXT NOT NULL,\n  pref_key TEXT NOT NULL,\n  value_json TEXT NOT NULL,\n  updated_at_ms INT NOT NULL,\n  PRIMARY KEY (profile_id, pref_key)\n) STRICT;\n\n-- Gateway-owned custom session group catalog (names + display order).\n-- Membership stays on each session entry's category field; this table only\n-- owns which groups exist and how operator UIs order them.\nCREATE TABLE IF NOT EXISTS session_groups (\n  name TEXT NOT NULL PRIMARY KEY,\n  position INTEGER NOT NULL,\n  created_at INTEGER NOT NULL,\n  cwd TEXT,\n  worktree INTEGER\n) STRICT;\n\n-- Gateway-owned durable cloud worker lifecycle. Provider-specific execution\n-- stays in plugins; this table records only core reconciliation facts.\nCREATE TABLE IF NOT EXISTS worker_environments (\n  environment_id TEXT NOT NULL PRIMARY KEY,\n  provider_id TEXT NOT NULL,\n  profile_id TEXT NOT NULL,\n  profile_snapshot_json TEXT NOT NULL,\n  last_activated_at_ms INTEGER,\n  preparation_key TEXT,\n  preparation_purpose TEXT,\n  preparation_demand_at_ms INTEGER,\n  preparation_expires_at_ms INTEGER,\n  preparation_consumed_at_ms INTEGER CHECK (\n    (preparation_key IS NULL AND preparation_demand_at_ms IS NULL\n      AND preparation_expires_at_ms IS NULL AND preparation_consumed_at_ms IS NULL)\n    OR\n    (preparation_key IS NOT NULL AND length(preparation_key) = 64\n      AND preparation_key NOT GLOB '*[^0-9a-f]*'\n      AND preparation_demand_at_ms IS NOT NULL\n      AND preparation_demand_at_ms BETWEEN 0 AND 9007199254740991\n      AND preparation_expires_at_ms IS NOT NULL\n      AND preparation_expires_at_ms > preparation_demand_at_ms\n      AND preparation_expires_at_ms <= 9007199254740991\n      AND (preparation_consumed_at_ms IS NULL\n        OR (preparation_consumed_at_ms >= preparation_demand_at_ms\n          AND preparation_consumed_at_ms < preparation_expires_at_ms)))\n  ),\n  provision_operation_id TEXT NOT NULL UNIQUE,\n  lease_id TEXT,\n  node_setup_id TEXT,\n  node_device_id TEXT,\n  ssh_host TEXT,\n  ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)),\n  ssh_user TEXT,\n  ssh_host_key TEXT,\n  ssh_key_ref_json TEXT,\n  desktop_json TEXT,\n  state TEXT NOT NULL CHECK (\n    state IN (\n      'requested',\n      'provisioning',\n      'bootstrapping',\n      'ready',\n      'attached',\n      'idle',\n      'draining',\n      'destroying',\n      'destroyed',\n      'failed',\n      'orphaned'\n    )\n  ),\n  bootstrap_bundle_hash TEXT,\n  bootstrap_openclaw_version TEXT,\n  bootstrap_protocol_features_json TEXT,\n  bootstrap_install_kind TEXT,\n  owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0),\n  teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed')),\n  attached_session_ids_json TEXT NOT NULL DEFAULT '[]',\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  state_changed_at_ms INTEGER NOT NULL,\n  idle_since_at_ms INTEGER,\n  destroy_requested_at_ms INTEGER,\n  last_error TEXT,\n  shared_host INTEGER\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_worker_environments_provider_lease\n  ON worker_environments(provider_id, lease_id)\n  WHERE lease_id IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_worker_environments_terminal_changed\n  ON worker_environments(state_changed_at_ms, environment_id);\n\n-- A dedicated node registers its fixed build paths before ready, then binds\n-- them once. The environment belongs to the Gateway's separate database.\nCREATE TABLE IF NOT EXISTS node_worker_prepared_workspaces (\n  preparation_key TEXT NOT NULL PRIMARY KEY CHECK (\n    length(preparation_key) = 64 AND preparation_key NOT GLOB '*[^0-9a-f]*'\n  ),\n  cache_key TEXT NOT NULL CHECK (\n    length(cache_key) = 64 AND cache_key NOT GLOB '*[^0-9a-f]*'\n  ),\n  gateway_namespace TEXT NOT NULL CHECK (length(gateway_namespace) > 0),\n  workspace_dir TEXT NOT NULL UNIQUE CHECK (length(workspace_dir) > 0),\n  home_dir TEXT NOT NULL CHECK (length(home_dir) > 0),\n  source_manifest_ref TEXT NOT NULL CHECK (\n    length(source_manifest_ref) = 71 AND substr(source_manifest_ref, 1, 7) = 'sha256:'\n      AND substr(source_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'\n  ),\n  prepared_manifest_ref TEXT NOT NULL CHECK (\n    length(prepared_manifest_ref) = 71 AND substr(prepared_manifest_ref, 1, 7) = 'sha256:'\n      AND substr(prepared_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'\n  ),\n  state TEXT NOT NULL CHECK (state IN ('available', 'bound', 'retiring', 'retired')),\n  environment_id TEXT NOT NULL CHECK (length(environment_id) > 0),\n  session_id TEXT,\n  session_key TEXT,\n  owner_epoch INTEGER CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n  bound_at_ms INTEGER CHECK (bound_at_ms BETWEEN created_at_ms AND 9007199254740991),\n  retired_at_ms INTEGER CHECK (\n    retired_at_ms BETWEEN coalesce(bound_at_ms, created_at_ms) AND 9007199254740991\n  ),\n  CHECK (\n    (session_id IS NULL AND session_key IS NULL AND owner_epoch IS NULL AND bound_at_ms IS NULL)\n    OR\n    (session_id IS NOT NULL AND length(session_id) > 0\n      AND session_key IS NOT NULL AND length(session_key) > 0\n      AND owner_epoch IS NOT NULL AND bound_at_ms IS NOT NULL)\n  ),\n  CHECK (\n    (state = 'available' AND bound_at_ms IS NULL AND retired_at_ms IS NULL)\n    OR (state = 'bound' AND bound_at_ms IS NOT NULL AND retired_at_ms IS NULL)\n    OR (state = 'retiring' AND retired_at_ms IS NULL)\n    OR (state = 'retired' AND retired_at_ms IS NOT NULL)\n  )\n) STRICT;\n\n-- Provider-advertised fallback ports preserve stable retry order separately\n-- from the downgrade-sensitive canonical worker environment row.\nCREATE TABLE IF NOT EXISTS worker_environment_ssh_fallback_ports (\n  environment_id TEXT NOT NULL,\n  position INTEGER NOT NULL CHECK (position >= 0 AND position <= 9),\n  port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),\n  PRIMARY KEY (environment_id, position),\n  UNIQUE (environment_id, port),\n  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE\n) STRICT;\n\n-- Logical sessions own repository intent and accepted artifact references,\n-- independently of the worker or rotating transcript session id.\nCREATE TABLE IF NOT EXISTS session_repository_workspaces (\n  workspace_id TEXT NOT NULL PRIMARY KEY CHECK (length(workspace_id) = 36),\n  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),\n  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),\n  url TEXT NOT NULL CHECK (length(url) BETWEEN 1 AND 4096),\n  requested_ref TEXT CHECK (requested_ref IS NULL OR length(requested_ref) BETWEEN 1 AND 1024),\n  run_setup_script INTEGER NOT NULL DEFAULT 0 CHECK (run_setup_script IN (0, 1)),\n  base_commit TEXT CHECK (base_commit IS NULL OR length(base_commit) IN (40, 64)),\n  base_manifest_hash TEXT,\n  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),\n  checkpoint_ref TEXT,\n  manifest_hash TEXT,\n  revision INTEGER NOT NULL CHECK (revision >= 0),\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  UNIQUE (agent_id, session_key),\n  CHECK (base_manifest_hash IS NULL OR base_commit IS NOT NULL),\n  CHECK ((checkpoint_ref IS NULL AND manifest_hash IS NULL)\n    OR (checkpoint_ref IS NOT NULL AND manifest_hash IS NOT NULL AND base_manifest_hash IS NOT NULL))\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS github_repository_publication_requests (\n  request_id TEXT NOT NULL PRIMARY KEY,\n  owner_profile_id TEXT,\n  connection_generation TEXT,\n  idempotency_key TEXT NOT NULL,\n  request_digest TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  session_lifecycle_revision TEXT,\n  requester_authority_json TEXT,\n  session_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  workspace_id TEXT NOT NULL,\n  checkpoint_ref TEXT,\n  checkpoint_digest TEXT,\n  claim_id TEXT,\n  run_id TEXT,\n  environment_id TEXT,\n  owner_epoch INTEGER,\n  placement_generation INTEGER,\n  identity_source TEXT NOT NULL CHECK (identity_source IN ('system-detected', 'system-configured', 'agent-override', 'personal')),\n  identity_profile_id TEXT,\n  identity_account_id INTEGER NOT NULL,\n  identity_login TEXT NOT NULL,\n  title TEXT,\n  body TEXT,\n  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),\n  gateway_instance_id TEXT,\n  execution_id TEXT,\n  last_effect TEXT CHECK (last_effect IN ('push', 'pull_request')),\n  effect_state TEXT CHECK (effect_state IN ('dispatched', 'observed')),\n  push_repository TEXT,\n  repository TEXT,\n  branch TEXT NOT NULL,\n  base_branch TEXT,\n  source_head_commit TEXT,\n  source_index_tree TEXT,\n  workspace_tree TEXT,\n  previous_head_commit TEXT,\n  pushed_head_commit TEXT,\n  head_commit TEXT,\n  pull_request_url TEXT,\n  error_code TEXT,\n  next_action TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  reported_at_ms INTEGER,\n  draft INTEGER,\n  CHECK ((identity_source = 'personal' AND owner_profile_id IS NOT NULL AND connection_generation IS NOT NULL)\n    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) STRICT;\nCREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_shared_request\n  ON github_repository_publication_requests(session_id, idempotency_key) WHERE owner_profile_id IS NULL;\nCREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_personal_request\n  ON github_repository_publication_requests(owner_profile_id, session_id, idempotency_key) WHERE owner_profile_id IS NOT NULL;\n\n-- Session placement lives in the shared state database so local admission,\n-- worker admission, and environment attachment use one durable authority.\nCREATE TABLE IF NOT EXISTS worker_session_placements (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  agent_id TEXT NOT NULL,\n  session_key TEXT NOT NULL,\n  execution_mode TEXT CHECK (execution_mode IN ('worker-turn', 'remote-exec')),\n  state TEXT NOT NULL CHECK (\n    state IN (\n      'local',\n      'requested',\n      'provisioning',\n      'syncing',\n      'starting',\n      'active',\n      'draining',\n      'reconciling',\n      'reclaimed',\n      'failed'\n    )\n  ),\n  environment_id TEXT,\n  transition_generation INTEGER NOT NULL DEFAULT 0 CHECK (transition_generation >= 0),\n  active_owner_epoch INTEGER CHECK (active_owner_epoch IS NULL OR active_owner_epoch >= 1),\n  workspace_base_manifest_ref TEXT,\n  remote_workspace_dir TEXT,\n  worker_bundle_hash TEXT,\n  last_transcript_ack_cursor INTEGER CHECK (\n    last_transcript_ack_cursor IS NULL OR last_transcript_ack_cursor >= 0\n  ),\n  last_live_event_ack_cursor INTEGER CHECK (\n    last_live_event_ack_cursor IS NULL OR last_live_event_ack_cursor >= 0\n  ),\n  recovery_error TEXT,\n  turn_claim_owner TEXT CHECK (turn_claim_owner IN ('local', 'worker')),\n  turn_claim_id TEXT,\n  turn_claim_run_id TEXT,\n  turn_claim_generation INTEGER CHECK (\n    turn_claim_generation IS NULL OR turn_claim_generation >= 0\n  ),\n  turn_claim_owner_epoch INTEGER CHECK (\n    turn_claim_owner_epoch IS NULL OR turn_claim_owner_epoch >= 1\n  ),\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  state_changed_at_ms INTEGER NOT NULL,\n  terminal_reason TEXT,\n  terminal_at_ms INTEGER,\n  CHECK (\n    (state IN ('local', 'requested')\n      AND environment_id IS NULL AND active_owner_epoch IS NULL\n      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n      AND worker_bundle_hash IS NULL\n      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n      AND recovery_error IS NULL)\n    OR\n    (state IS 'provisioning'\n      AND active_owner_epoch IS NULL\n      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n      AND worker_bundle_hash IS NULL\n      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n      AND recovery_error IS NULL)\n    OR\n    (state IS 'syncing'\n      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL\n      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n      AND worker_bundle_hash IS NOT NULL\n      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n      AND recovery_error IS NULL)\n    OR\n    (state IS 'starting'\n      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL\n      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n      AND worker_bundle_hash IS NOT NULL\n      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n      AND recovery_error IS NULL)\n    OR\n    (state IN ('active', 'draining', 'reconciling')\n      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL\n      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL)\n    OR\n    (state IS 'reclaimed'\n      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL\n      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL\n      AND turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL\n      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)\n    OR\n    (state IS 'failed' AND recovery_error IS NOT NULL)\n  ),\n  CHECK (\n    (turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL\n      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)\n    OR\n    (turn_claim_owner IS 'local' AND turn_claim_id IS NOT NULL\n      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL\n      AND turn_claim_owner_epoch IS NULL)\n    OR\n    (turn_claim_owner IS 'worker' AND turn_claim_id IS NOT NULL\n      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL\n      AND turn_claim_owner_epoch IS NOT NULL)\n  ),\n  CHECK (\n    turn_claim_owner IS NULL\n    OR\n    (turn_claim_owner IS 'local' AND (\n      state IN ('local', 'requested', 'failed')\n      OR (state IN ('active', 'draining') AND execution_mode IS 'remote-exec')\n    ))\n    OR\n    (turn_claim_owner IS 'worker' AND state IN ('active', 'draining')\n      AND (execution_mode IS NULL OR execution_mode IS 'worker-turn')\n      AND turn_claim_owner_epoch IS active_owner_epoch)\n  )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_session_key\n  ON worker_session_placements(agent_id, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_reconcile\n  ON worker_session_placements(updated_at_ms, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_environment\n  ON worker_session_placements(environment_id)\n  WHERE environment_id IS NOT NULL;\n\n-- Planned placement moves retain their exact source CAS and bounded target\n-- without widening the stable placement-state vocabulary. The opaque operation\n-- id fences stale asynchronous completion; it is correlation, never authority.\nCREATE TABLE IF NOT EXISTS worker_session_placement_moves (\n  operation_id TEXT NOT NULL PRIMARY KEY,\n  session_id TEXT NOT NULL UNIQUE\n    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE,\n  source_generation INTEGER NOT NULL CHECK (source_generation >= 0),\n  source_environment_id TEXT NOT NULL CHECK (\n    length(source_environment_id) BETWEEN 1 AND 256\n    AND source_environment_id = trim(source_environment_id)\n  ),\n  source_owner_epoch INTEGER NOT NULL CHECK (source_owner_epoch >= 1),\n  target_kind TEXT NOT NULL CHECK (target_kind IN ('gateway', 'profile', 'device')),\n  target_id TEXT,\n  -- Keep these nullable columns constraint-free so lazy ALTER TABLE produces the\n  -- same shape as fresh databases; placement-move code validates their values.\n  target_machine_class TEXT,\n  target_os TEXT,\n  -- Explicit source abandonment is a durable operator decision. Keep the bit\n  -- bare and nullable so same-version older readers can safely omit it.\n  abandon_source INTEGER,\n  last_error TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  CHECK (\n    (target_kind IS 'gateway' AND target_id IS NULL)\n    OR\n    (target_kind IN ('profile', 'device')\n      AND target_id IS NOT NULL\n      AND length(target_id) BETWEEN 1 AND 256\n      AND target_id = trim(target_id))\n  )\n) STRICT;\n\n-- Worker-visible session RPC authority is persisted against the exact turn\n-- claim. The launch descriptor is informative only; Gateway dispatch always\n-- revalidates this record and the live placement claim before executing.\nCREATE TABLE IF NOT EXISTS worker_turn_tool_authorities (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  environment_id TEXT NOT NULL,\n  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n  claim_id TEXT NOT NULL,\n  run_id TEXT NOT NULL,\n  tool_names_json TEXT NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- Tool-call ids are idempotency keys only within one exact source turn claim.\n-- A running operation from another Gateway instance is ambiguous and is never\n-- replayed. A persisted random seed separates durable downstream identities\n-- from Gateway authentication keys and survives ordinary process restarts.\nCREATE TABLE IF NOT EXISTS worker_session_tool_operations (\n  source_session_id TEXT NOT NULL,\n  source_claim_id TEXT NOT NULL,\n  tool_call_id TEXT NOT NULL,\n  tool_name TEXT NOT NULL CHECK (tool_name IN ('sessions_spawn', 'sessions_send')),\n  request_digest TEXT NOT NULL,\n  operation_seed TEXT NOT NULL,\n  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'unknown')),\n  child_session_key TEXT,\n  result_json TEXT,\n  gateway_instance_id TEXT NOT NULL,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (source_session_id, source_claim_id, tool_call_id),\n  FOREIGN KEY (source_session_id)\n    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- Local sandbox execution is a projection of a session-owned managed worktree.\n-- No cascade: an older binary must not discard pending edits with a session row.\nCREATE TABLE IF NOT EXISTS local_workspace_projections (\n  worktree_id TEXT NOT NULL PRIMARY KEY,\n  agent_id TEXT NOT NULL,\n  session_key TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  lifecycle_revision TEXT,\n  projection_path TEXT NOT NULL UNIQUE,\n  base_commit TEXT NOT NULL,\n  source_paths_json TEXT NOT NULL,\n  baseline_json TEXT,\n  baseline_ref TEXT,\n  pending_ref TEXT,\n  pending_target TEXT CHECK (pending_target IN ('canonical', 'projection')),\n  paused_runtimes_json TEXT,\n  journal_json TEXT,\n  journal_pack BLOB CHECK (journal_pack IS NULL OR length(journal_pack) <= 268435456),\n  revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),\n  created_at_ms INTEGER NOT NULL,\n  checkpoint_json TEXT,\n  tree_root_digest BLOB,\n  source_paths_digest BLOB,\n  canonical_fingerprints BLOB,\n  projection_fingerprints BLOB,\n  CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL),\n  CHECK ((journal_json IS NULL) = (journal_pack IS NULL))\n) STRICT;\n\n-- The projection owner advances changed nodes and its root in one acceptance.\n-- Legacy baseline_json remains only until that owner's resumable conversion.\nCREATE TABLE IF NOT EXISTS local_workspace_manifest_nodes (\n  worktree_id TEXT NOT NULL,\n  path TEXT NOT NULL,\n  node_json TEXT NOT NULL,\n  PRIMARY KEY (worktree_id, path),\n  FOREIGN KEY (worktree_id)\n    REFERENCES local_workspace_projections(worktree_id) ON DELETE CASCADE\n) STRICT;\n\n-- Immutable subtrees and source inventories are shared across projections and revisions.\n-- Large JSON packs measured 410k VFS reads/load WITHOUT ROWID versus 10k with rowid.\nCREATE TABLE IF NOT EXISTS local_workspace_tree_packs (\n  tree_digest BLOB NOT NULL PRIMARY KEY CHECK (length(tree_digest) = 32),\n  records_json TEXT NOT NULL,\n  children_json TEXT NOT NULL,\n  sweep_epoch INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS local_workspace_source_path_sets (\n  path_digest BLOB NOT NULL PRIMARY KEY CHECK (length(path_digest) = 32),\n  paths_zstd BLOB NOT NULL,\n  sweep_epoch INTEGER NOT NULL\n) STRICT, WITHOUT ROWID;\n\n-- A reconciliation journal is written before managed-worktree mutation. The\n-- bounded Git base snapshot repairs any subset left by an interrupted apply.\nCREATE TABLE IF NOT EXISTS worker_workspace_reconciliations (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  environment_id TEXT NOT NULL,\n  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n  base_manifest_ref TEXT NOT NULL,\n  current_manifest_ref TEXT NOT NULL,\n  plan_json TEXT NOT NULL,\n  base_pack BLOB NOT NULL CHECK (length(base_pack) <= 268435456),\n  created_at_ms INTEGER NOT NULL,\n  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- A completed remote turn is fenced from stale-claim teardown until its\n-- workspace result is durably reconciled into the managed worktree.\nCREATE TABLE IF NOT EXISTS worker_workspace_pending_results (\n  session_id TEXT NOT NULL PRIMARY KEY,\n  environment_id TEXT NOT NULL,\n  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n  claim_id TEXT NOT NULL,\n  run_id TEXT NOT NULL,\n  gateway_instance_id TEXT NOT NULL,\n  recovery_requested_at_ms INTEGER,\n  workspace_accepted_at_ms INTEGER,\n  staged_result_ref TEXT,\n  repository_workspace_id TEXT,\n  created_at_ms INTEGER NOT NULL,\n  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- GitHub publication intent records the authoritative session worktree. Cloud\n-- requests execute only after the exact turn claim's result is accepted locally.\n-- Secrets stay in the effective Gateway-owned GitHub profile and never enter\n-- this row or the worker protocol.\nCREATE TABLE IF NOT EXISTS github_publication_requests (\n  request_id TEXT NOT NULL PRIMARY KEY,\n  idempotency_key TEXT NOT NULL,\n  request_digest TEXT NOT NULL,\n  session_id TEXT NOT NULL,\n  session_key TEXT NOT NULL,\n  agent_id TEXT NOT NULL,\n  worktree_id TEXT NOT NULL,\n  repository_fingerprint TEXT NOT NULL,\n  claim_id TEXT,\n  run_id TEXT,\n  environment_id TEXT,\n  owner_epoch INTEGER CHECK (owner_epoch IS NULL OR owner_epoch >= 1),\n  placement_generation INTEGER CHECK (\n    placement_generation IS NULL OR placement_generation >= 0\n  ),\n  identity_source TEXT NOT NULL CHECK (\n    identity_source IN ('system-detected', 'system-configured', 'agent-override')\n  ),\n  identity_profile_id TEXT,\n  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),\n  identity_login TEXT NOT NULL,\n  title TEXT,\n  body TEXT,\n  status TEXT NOT NULL CHECK (\n    status IN ('requested', 'publishing', 'published', 'failed')\n  ),\n  gateway_instance_id TEXT,\n  repository TEXT,\n  branch TEXT NOT NULL,\n  base_branch TEXT,\n  source_head_commit TEXT,\n  source_index_tree TEXT,\n  workspace_tree TEXT,\n  head_commit TEXT,\n  pull_request_url TEXT,\n  error_code TEXT,\n  next_action TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  reported_at_ms INTEGER,\n  draft INTEGER,\n  UNIQUE (session_id, idempotency_key),\n  CHECK (\n    (claim_id IS NULL AND run_id IS NULL AND environment_id IS NULL\n      AND owner_epoch IS NULL AND placement_generation IS NULL)\n    OR\n    (claim_id IS NOT NULL AND run_id IS NOT NULL AND placement_generation IS NOT NULL\n      AND ((environment_id IS NULL AND owner_epoch IS NULL)\n        OR (environment_id IS NOT NULL AND owner_epoch IS NOT NULL)))\n  ),\n  CHECK (\n    (identity_source IS 'system-detected' AND identity_profile_id IS NULL)\n    OR\n    (identity_source IN ('system-configured', 'agent-override')\n      AND identity_profile_id IS NOT NULL)\n  ),\n  CHECK (\n    (source_head_commit IS NULL AND source_index_tree IS NULL AND workspace_tree IS NULL)\n    OR\n    (source_head_commit IS NOT NULL AND workspace_tree IS NOT NULL)\n  ),\n  CHECK (\n    (status IS 'published' AND pull_request_url IS NOT NULL AND error_code IS NULL\n      AND next_action IS NULL)\n    OR\n    (status IS 'failed' AND pull_request_url IS NULL AND error_code IS NOT NULL\n      AND next_action IS NOT NULL)\n    OR\n    (status IN ('requested', 'publishing') AND pull_request_url IS NULL\n      AND error_code IS NULL AND next_action IS NULL)\n  )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_github_publication_requests_pending\n  ON github_publication_requests(status, updated_at_ms, request_id);\n\n-- Personal requests cannot be interpreted or resumed by older shared publishers.\nCREATE TABLE IF NOT EXISTS github_personal_publication_requests (\n  request_id TEXT NOT NULL PRIMARY KEY CHECK (length(request_id) = 36),\n  owner_profile_id TEXT NOT NULL CHECK (length(owner_profile_id) BETWEEN 1 AND 128),\n  connection_generation TEXT NOT NULL CHECK (length(connection_generation) = 36),\n  idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 128),\n  request_digest TEXT NOT NULL CHECK (length(request_digest) = 64),\n  session_id TEXT NOT NULL CHECK (length(session_id) BETWEEN 1 AND 128),\n  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),\n  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),\n  worktree_id TEXT NOT NULL CHECK (length(worktree_id) BETWEEN 1 AND 128),\n  repository_fingerprint TEXT NOT NULL CHECK (length(repository_fingerprint) BETWEEN 1 AND 256),\n  identity_source TEXT NOT NULL CHECK (identity_source = 'personal'),\n  identity_profile_id TEXT NOT NULL CHECK (length(identity_profile_id) = 36),\n  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),\n  identity_login TEXT NOT NULL CHECK (length(identity_login) BETWEEN 1 AND 39),\n  title TEXT CHECK (title IS NULL OR length(title) BETWEEN 1 AND 256),\n  body TEXT CHECK (body IS NULL OR length(body) BETWEEN 1 AND 8192),\n  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),\n  gateway_instance_id TEXT CHECK (gateway_instance_id IS NULL OR length(gateway_instance_id) BETWEEN 1 AND 128),\n  execution_id TEXT CHECK (execution_id IS NULL OR length(execution_id) = 36),\n  last_effect TEXT CHECK (last_effect IS NULL OR last_effect IN ('push', 'pull_request')),\n  effect_state TEXT CHECK (effect_state IS NULL OR effect_state IN ('dispatched', 'observed')),\n  push_repository TEXT NOT NULL CHECK (length(push_repository) BETWEEN 3 AND 256),\n  repository TEXT NOT NULL CHECK (length(repository) BETWEEN 3 AND 256),\n  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),\n  base_branch TEXT NOT NULL CHECK (length(base_branch) BETWEEN 1 AND 256),\n  source_head_commit TEXT NOT NULL CHECK (length(source_head_commit) IN (40, 64)),\n  source_index_tree TEXT NOT NULL CHECK (length(source_index_tree) IN (40, 64)),\n  workspace_tree TEXT NOT NULL CHECK (length(workspace_tree) IN (40, 64)),\n  head_commit TEXT CHECK (head_commit IS NULL OR length(head_commit) IN (40, 64)),\n  pull_request_url TEXT CHECK (pull_request_url IS NULL OR length(pull_request_url) BETWEEN 1 AND 2048),\n  error_code TEXT CHECK (error_code IS NULL OR length(error_code) BETWEEN 1 AND 64),\n  next_action TEXT CHECK (next_action IS NULL OR length(next_action) BETWEEN 1 AND 1024),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms),\n  reported_at_ms INTEGER,\n  draft INTEGER,\n  UNIQUE (owner_profile_id, session_id, idempotency_key),\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)\n    OR (status = 'failed' AND error_code IS NOT NULL AND next_action IS NOT NULL)\n    OR (status IN ('requested', 'publishing', 'needs_confirmation') AND error_code IS NULL AND next_action IS NULL))\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_github_personal_publication_owner_session\n  ON github_personal_publication_requests(owner_profile_id, session_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_github_personal_publication_pending\n  ON github_personal_publication_requests(status, updated_at_ms, request_id);\n\n-- Older readers validate both local receipt tables exactly. Their immutable\n-- lifecycle binding stays in a first-use companion so those schemas remain readable.\nCREATE TABLE IF NOT EXISTS github_publication_session_lifecycles (\n  publication_kind TEXT NOT NULL CHECK (publication_kind IN ('shared', 'personal')),\n  request_id TEXT NOT NULL,\n  lifecycle_revision TEXT,\n  requester_authority_json TEXT,\n  PRIMARY KEY (publication_kind, request_id)\n) STRICT;\n\n-- One active, opaque admission credential per worker environment. Plaintext\n-- may be retried until delivery acknowledgement but never enters durable state.\nCREATE TABLE IF NOT EXISTS worker_environment_credentials (\n  environment_id TEXT NOT NULL PRIMARY KEY,\n  credential_hash TEXT NOT NULL UNIQUE,\n  bundle_hash TEXT NOT NULL,\n  session_id TEXT,\n  rpc_set_version INTEGER NOT NULL CHECK (rpc_set_version >= 1),\n  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 0),\n  expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms >= 0),\n  delivered_at_ms INTEGER CHECK (delivered_at_ms >= 0),\n  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE\n) STRICT;\n\n-- One durable sequence cursor per attached session owner epoch. The environment\n-- binding prevents independent workers with coincident epochs from sharing replay state.\nCREATE TABLE IF NOT EXISTS worker_transcript_commit_heads (\n  session_id TEXT NOT NULL,\n  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n  environment_id TEXT NOT NULL,\n  next_seq INTEGER NOT NULL CHECK (next_seq >= 1),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n  PRIMARY KEY (session_id, run_epoch)\n) STRICT;\n\n-- Pending rows preserve a claimed request across gateway restarts. Terminal rows\n-- cache the exact result returned for deterministic at-least-once replay.\nCREATE TABLE IF NOT EXISTS worker_transcript_commits (\n  session_id TEXT NOT NULL,\n  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n  seq INTEGER NOT NULL CHECK (seq >= 1),\n  request_hash TEXT NOT NULL,\n  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),\n  result_json TEXT,\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n  PRIMARY KEY (session_id, run_epoch, seq),\n  FOREIGN KEY (session_id, run_epoch)\n    REFERENCES worker_transcript_commit_heads(session_id, run_epoch)\n    ON DELETE CASCADE,\n  CHECK (\n    (state = 'pending' AND result_json IS NULL) OR\n    (state = 'terminal' AND result_json IS NOT NULL)\n  )\n) STRICT;\n\n-- Pending rows preserve a claimed inference turn across gateway restarts.\n-- Terminal rows cache the exact outcome returned for deterministic replay.\nCREATE TABLE IF NOT EXISTS worker_inference_turns (\n  session_id TEXT NOT NULL,\n  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n  run_id TEXT NOT NULL,\n  turn_id TEXT NOT NULL,\n  environment_id TEXT NOT NULL,\n  request_hash TEXT NOT NULL,\n  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),\n  terminal_json TEXT,\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n  PRIMARY KEY (session_id, run_epoch, run_id, turn_id),\n  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE,\n  CHECK (\n    (state = 'pending' AND terminal_json IS NULL) OR\n    (state = 'terminal' AND terminal_json IS NOT NULL)\n  )\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_worker_inference_turns_pending_run\n  ON worker_inference_turns(session_id, run_epoch, run_id)\n  WHERE state = 'pending';\n\nCREATE TABLE IF NOT EXISTS template_installs (\n  agent_id TEXT NOT NULL PRIMARY KEY,\n  schema_version TEXT NOT NULL,\n  source_kind TEXT NOT NULL,\n  template_name TEXT NOT NULL,\n  template_version TEXT NOT NULL,\n  package_root TEXT NOT NULL,\n  manifest_path TEXT NOT NULL,\n  integrity_kind TEXT NOT NULL,\n  integrity TEXT NOT NULL,\n  source_byte_length INTEGER NOT NULL,\n  manifest_schema_version INTEGER NOT NULL,\n  plan_integrity TEXT NOT NULL,\n  workspace TEXT NOT NULL UNIQUE,\n  agent_config_digest TEXT NOT NULL,\n  agent_owned_paths_json TEXT NOT NULL,\n  bootstrap_source_path TEXT,\n  bootstrap_content_digest TEXT,\n  status TEXT NOT NULL CHECK (\n    status IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial')\n  ),\n  added_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS template_workspace_files (\n  agent_id TEXT NOT NULL,\n  target_path TEXT NOT NULL,\n  schema_version TEXT NOT NULL,\n  workspace TEXT NOT NULL,\n  source_path TEXT NOT NULL,\n  content_digest TEXT NOT NULL,\n  status TEXT NOT NULL,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (agent_id, target_path)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS template_package_refs (\n  agent_id TEXT NOT NULL,\n  package_kind TEXT NOT NULL,\n  package_source TEXT NOT NULL,\n  package_ref TEXT NOT NULL,\n  package_version TEXT NOT NULL,\n  package_integrity TEXT NOT NULL,\n  schema_version TEXT NOT NULL,\n  template_name TEXT NOT NULL,\n  package_status TEXT NOT NULL,\n  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),\n  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),\n  independent_owner INTEGER NOT NULL CHECK (independent_owner IN (0, 1)),\n  extension_id TEXT,\n  extension_format TEXT,\n  extension_detected_format TEXT,\n  extension_mapped_json TEXT,\n  extension_unavailable_json TEXT,\n  extension_adapter_identity TEXT,\n  installed_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (agent_id, package_kind, package_source, package_ref, package_version)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS template_cron_refs (\n  agent_id TEXT NOT NULL,\n  manifest_id TEXT NOT NULL,\n  schema_version TEXT NOT NULL,\n  declaration_key TEXT NOT NULL UNIQUE,\n  scheduler_job_id TEXT UNIQUE,\n  status TEXT NOT NULL,\n  job_json TEXT NOT NULL,\n  error TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (agent_id, manifest_id)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS template_mcp_server_refs (\n  agent_id TEXT NOT NULL,\n  name TEXT NOT NULL,\n  schema_version TEXT NOT NULL,\n  config_digest TEXT NOT NULL,\n  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),\n  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),\n  independent_owner INTEGER NOT NULL DEFAULT 0 CHECK (independent_owner IN (0, 1)),\n  status TEXT NOT NULL,\n  error TEXT,\n  created_at_ms INTEGER NOT NULL,\n  updated_at_ms INTEGER NOT NULL,\n  PRIMARY KEY (agent_id, name)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS user_profile_identities (\n  provider TEXT NOT NULL,\n  subject TEXT NOT NULL,\n  profile_id TEXT NOT NULL,\n  canonical_login TEXT,\n  -- Host-scoped verified credit evidence; current profile bindings govern attribution.\n  verified_email_json TEXT,\n  created_at INTEGER NOT NULL,\n  authorization_id TEXT,\n  authorization_basis_json TEXT,\n  PRIMARY KEY (provider, subject)\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_user_profile_identities_profile_id\n  ON user_profile_identities(profile_id);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_user_profile_identities_authorization\n  ON user_profile_identities(authorization_id);\n\nCREATE TABLE IF NOT EXISTS outbound_media_provenance (\n  realpath TEXT NOT NULL PRIMARY KEY,\n  kind TEXT NOT NULL,\n  version INTEGER NOT NULL,\n  sha256 TEXT NOT NULL,\n  size_bytes INTEGER NOT NULL,\n  created_at_ms INTEGER NOT NULL\n) STRICT;\n\n-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,\n-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.\nCREATE TABLE IF NOT EXISTS secret_store_entries (\n  scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),\n  scope_id TEXT NOT NULL,\n  name TEXT NOT NULL,\n  value TEXT NOT NULL,\n  kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),\n  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n  updated_by TEXT,\n  deleted_at_ms INTEGER,\n  allowed_hosts TEXT,\n  CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),\n  PRIMARY KEY (scope_kind, scope_id, name)\n) STRICT;\nCREATE INDEX IF NOT EXISTS secret_store_entries_live_idx\n  ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;\n";
//#endregion
//#region src/state/openclaw-database-seal-schema.ts
const integrityPolicyRevision = 3;
function sqliteDatabaseSealSchemaFor(e) {
	requireNodeSqlite();
	const t = captureSqliteNativeRuntimeAdmission();
	const n = t?.storageIdentity;
	if (!t || !n) return;
	const r = [t.runtime.nodeVersion, t.runtime.bunVersion ?? null];
	const i = JSON.stringify([
		t.version,
		n.sourceId,
		n.compileOptions,
		...r
	]);
	const a = createHash("sha256").update(JSON.stringify([
		integrityPolicyRevision,
		i,
		e
	]));
	const o = createHash("sha256").update(e);
	if (e !== "state") {
		a.update(String(38));
		a.update(OPENCLAW_AGENT_SCHEMA_SQL);
		o.update(String(38));
		o.update(OPENCLAW_AGENT_SCHEMA_SQL);
	}
	if (e !== "agent") {
		a.update(String(36));
		a.update(OPENCLAW_STATE_SCHEMA_SQL);
		o.update(String(36));
		o.update(OPENCLAW_STATE_SCHEMA_SQL);
	}
	return {
		schemaIdentity: a.digest("hex"),
		identity: {
			runtime: JSON.stringify(r),
			sqlite: {
				version: t.version,
				sourceId: n.sourceId,
				compileOptions: n.compileOptions.split(",").filter((e) => !e.startsWith("COMPILER=")).join(",")
			},
			schema: o.digest("hex"),
			policy: integrityPolicyRevision
		}
	};
}
//#endregion
//#region src/infra/sqlite-database-admission-seal.ts
const sealSchemas = {};
function sealSchema(e) {
	const t = e.includes("agent.schema-metadata");
	const n = t === e.includes("state.schema-version") ? "other" : t ? "agent" : "state";
	return sealSchemas[n] ??= sqliteDatabaseSealSchemaFor(n);
}
const integrityVerificationKey = {
	name: "sqlite.full-verification",
	lifetime: "process",
	read: (e) => typeof e === "number" && Number.isSafeInteger(e) ? e : void 0
};
const quickIntegrityVerificationKey = {
	...integrityVerificationKey,
	name: "sqlite.quick-verification"
};
const sealedKeys = /* @__PURE__ */ new Set([
	"sqlite-schema",
	"sqlite.full-verification",
	"sqlite.quick-verification",
	"state.schema-version",
	"state.runtime-schema",
	"state.integrity",
	"agent.completed-validation",
	"agent.canonical-validation-receipt",
	"agent.schema-metadata"
]);
function isSealedKey(e) {
	return sealedKeys.has(e) || e.startsWith("memory.index-schema:");
}
function encodeSealValue(e, t) {
	if (t instanceof Map) return {
		sealType: "map",
		entries: [...t]
	};
	if (t instanceof Set) return {
		sealType: "set",
		entries: [...t]
	};
	if (t instanceof SharedArrayBuffer) return {
		sealType: "shared",
		entries: [...new Int32Array(t)]
	};
	return t;
}
function decodeSealValue(e, t) {
	if (!isRecord(t) || !Array.isArray(t.entries)) return t;
	if (t.sealType === "map") return new Map(t.entries);
	if (t.sealType === "set") return new Set(t.entries);
	if (t.sealType === "shared") {
		const e = new SharedArrayBuffer(t.entries.length * Int32Array.BYTES_PER_ELEMENT);
		new Int32Array(e).set(t.entries);
		return e;
	}
	return t;
}
var SqliteDatabaseCleanCloseSeals = class {
	constructor(e, t) {
		this.publishFact = e;
		this.references = t;
		this.loaded = /* @__PURE__ */ new WeakMap();
	}
	isLoaded(e) {
		return this.loaded.has(e);
	}
	markLoaded(e) {
		const t = this.references.descriptor(e) ?? e;
		const n = this.loaded.get(t);
		if (n && n !== e.generation) Atomics.store(new Int32Array(e.generation), SqliteDatabaseGenerationSlot.sealPresent, Atomics.load(new Int32Array(n), SqliteDatabaseGenerationSlot.sealPresent));
		this.loaded.set(t, e.generation);
	}
	load(e, t) {
		if (threadId !== 0) return;
		const n = this.references.descriptor(e) ?? e;
		if (this.loaded.has(n)) {
			this.markLoaded(e);
			return;
		}
		this.markLoaded(e);
		e.cleanCloseRefusal = "malformed-proof";
		try {
			if (t?.refusal) e.cleanCloseRefusal = t.refusal;
			const n = t ? t.seal : readSqliteCleanCloseSeal(e.location, fsSync.fstatSync(e.descriptor, { bigint: true }), (t) => {
				e.cleanCloseRefusal = t;
			});
			if (!n || typeof n.facts !== "string") return;
			const r = JSON.parse(n.facts, decodeSealValue);
			if (!Array.isArray(r) || !r.every((e) => Array.isArray(e) && e.length === 3 && typeof e[0] === "string" && isSealedKey(e[0]) && typeof e[1] === "boolean") || !r.some(([e, , t]) => (e === integrityVerificationKey.name || e === quickIntegrityVerificationKey.name) && t === n.verifiedAt) || !r.some(([e, , t]) => e === "sqlite-schema" && isRecord(t))) return;
			const i = sealSchema(r.map(([e]) => e));
			if (!i) {
				e.cleanCloseRefusal = "identity-mismatch";
				return;
			}
			const a = n.identity;
			if (a !== void 0 && (!isRecord(a) || typeof a.runtime !== "string" || typeof a.schema !== "string" || typeof a.policy !== "number")) return;
			if (isRecord(a) && typeof a.sqlite !== "string") {
				if (!isRecord(a.sqlite) || typeof a.sqlite.version !== "string" || typeof a.sqlite.sourceId !== "string" || typeof a.sqlite.compileOptions !== "string") return;
				const t = a.schema !== i.identity.schema;
				const n = a.policy !== i.identity.policy;
				const r = a.sqlite.compileOptions !== i.identity.sqlite.compileOptions;
				if (t || n || r) {
					e.cleanCloseRefusal = t ? "schema-mismatch" : n ? "policy-mismatch" : "feature-mismatch";
					return;
				}
			} else if (n.schemaIdentity !== i.schemaIdentity) {
				e.cleanCloseRefusal = "identity-mismatch";
				return;
			}
			const o = r.find(([e]) => e === "sqlite-schema")?.[2];
			if (!(o.tableSql instanceof Map)) return;
			if (hasPendingAgentStartupColumns(o.tableSql)) {
				e.cleanCloseRefusal = "schema-mismatch";
				return;
			}
			delete e.cleanCloseRefusal;
			for (const [t, n, i] of r) this.publishFact(e, {
				name: t,
				schemaDependent: n,
				lifetime: "process"
			}, { value: i }, readSqliteDatabaseFactRevision(e, n));
			Atomics.store(new Int32Array(e.generation), SqliteDatabaseGenerationSlot.sealPresent, 1);
		} catch {} finally {
			this.references.publish(e);
		}
	}
	invalidate(e, t) {
		invalidateSqliteCleanCloseSeal(t?.location ?? e);
		if (t) Atomics.store(new Int32Array(t.generation), SqliteDatabaseGenerationSlot.sealPresent, 0);
	}
	prepare(e, t, n) {
		const r = this.preparePublication(e, t, n);
		if (t) this.references.retain(t);
		let i = t;
		return {
			publish: () => i !== void 0 && r(),
			[Symbol.dispose]: () => {
				const e = i;
				i = void 0;
				if (e) this.references.release(e);
			}
		};
	}
	preparePublication(e, t, n) {
		if (!t || e.isTransaction) return () => false;
		if (n === void 0) return () => false;
		const r = [...t.facts].filter(([e, n]) => isSealedKey(e) && isSqliteDatabaseAdmissionFactCurrent(t, n));
		if (!r.some(([e]) => e === "sqlite-schema")) return () => false;
		const i = JSON.stringify(r.map(([e, t]) => [
			e,
			t.schemaDependent,
			t.value
		]), encodeSealValue);
		const a = sealSchema(r.map(([e]) => e));
		if (!a) return () => false;
		return () => {
			if (e.isOpen || readSqliteDatabaseGeneration(t, "retired") !== 0 || r.some(([, e]) => Atomics.load(new Int32Array(e.current), 0) !== 1 || e.revision !== readSqliteDatabaseFactRevision(t, e.schemaDependent))) return false;
			try {
				const e = fsSync.fstatSync(t.descriptor, { bigint: true });
				if (readSqliteDatabaseAdmissionIdentity(fsSync.statSync(t.location, { bigint: true })) !== t.identity) return false;
				const r = writeSqliteCleanCloseSeal(t.location, a.schemaIdentity, e, {
					verifiedAt: n,
					facts: i,
					identity: a.identity
				});
				Atomics.store(new Int32Array(t.generation), SqliteDatabaseGenerationSlot.sealPresent, r ? 1 : 0);
				return r;
			} catch {
				return false;
			}
		};
	}
};
//#endregion
//#region src/infra/sqlite-schema-mutation.ts
function schemaStatement(e) {
	if (/^(?:CREATE|ALTER|DROP|REINDEX|VACUUM)\b/iu.test(e)) return true;
	const t = /^(?:INSERT(?: OR \w+)? INTO|UPDATE(?: OR \w+)?|DELETE FROM|REPLACE INTO)\s+/iu.exec(e);
	if (t) {
		const n = readSqlToken(e, t[0].length)?.raw ?? "";
		const r = n.slice(findSqlCharacter(n, ".") + 1);
		return ["sqlite_schema", "sqlite_master"].includes(normalizeSqlIdentifier(r));
	}
	if (!/^PRAGMA\b/iu.test(e)) return false;
	const n = [findSqlCharacter(e, "="), findSqlCharacter(e, "(")].filter((e) => e >= 0);
	if (n.length === 0) return false;
	const r = e.slice(6, Math.min(...n)).trim();
	const i = r.slice(findSqlCharacter(r, ".") + 1).trim();
	const a = i.startsWith("'") && i.endsWith("'") ? i.slice(1, -1).toLowerCase() : normalizeSqlIdentifier(i);
	return ["user_version", "schema_version"].includes(a);
}
function changesSchema(e) {
	if (!/\b(?:CREATE|ALTER|DROP|REINDEX|VACUUM|PRAGMA|INSERT|UPDATE|DELETE|REPLACE)\b/iu.test(e)) return false;
	let t = normalizeSqlWhitespace(e);
	while (t) {
		t = t.replace(/^[\s;]+/u, "");
		const e = findSqlCharacter(t, ";");
		if (schemaStatement(e < 0 ? t : t.slice(0, e))) return true;
		t = e < 0 ? "" : t.slice(e + 1);
	}
	return false;
}
function createsOnlyTemporaryObject(e) {
	let t = normalizeSqlWhitespace(e);
	const n = /^\s*CREATE\s+(?:TEMP|TEMPORARY)\s+(TABLE|TRIGGER)\b/iu.exec(t)?.[1]?.toUpperCase();
	if (!n) return false;
	let r = findSqlCharacter(t, ";");
	if (n === "TABLE") return r < 0 || t.slice(r + 1).trim() === "";
	while (r >= 0) {
		t = t.slice(r + 1).trim();
		r = findSqlCharacter(t, ";");
		const e = (r < 0 ? t : t.slice(0, r)).trim();
		if (/^END$/iu.test(e)) return r < 0 || t.slice(r + 1).trim() === "";
	}
	return false;
}
function changesOnlyTemporaryTable(e) {
	const t = normalizeSqlWhitespace(e);
	const n = findSqlCharacter(t, ";");
	if (n >= 0 && t.slice(n + 1).trim() !== "") return false;
	return /^CREATE\s+(?:TEMP|TEMPORARY)\s+TABLE\b/iu.test(t) || /^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:temp|"temp"|`temp`|\[temp\])\s*\./iu.test(t);
}
function changesData(e) {
	return hasUnquotedSqlKeyword(e, /\b(?:INSERT|UPDATE|DELETE|REPLACE)\b/giu);
}
function temporaryWriteTables(e) {
	const t = [];
	let n = normalizeSqlWhitespace(e);
	while (n) {
		n = n.replace(/^[\s;]+/u, "");
		const e = findSqlCharacter(n, ";");
		const r = e < 0 ? n : n.slice(0, e);
		if (changesData(r)) {
			const e = /^(?:INSERT(?: OR \w+)? INTO|REPLACE INTO|UPDATE(?: OR \w+)?|DELETE FROM)\s+(?:temp|"temp"|`temp`|\[temp\])\s*\.\s*("(?:[^"]|"")+"|`(?:[^`]|``)+`|\[[^\]]+\]|[a-z_]\w*)(?=\s|\(|$)/iu.exec(r)?.[1];
			if (e === void 0) return;
			t.push(normalizeSqlIdentifier(e));
		}
		n = e < 0 ? "" : n.slice(e + 1);
	}
	return t;
}
const sqlLeadingTrivia = /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/u;
const transactionControlPrefix = /^(BEGIN|SAVEPOINT|COMMIT|END|RELEASE|ROLLBACK)\b/i;
function readTransactionControl(e, t) {
	let n;
	let r = false;
	let i = false;
	let a = 0;
	let o = e;
	while (o) {
		o = o.replace(sqlLeadingTrivia, "");
		if (!o) break;
		a += 1;
		const e = o.includes(";") ? findSqlCharacter(o, ";") : -1;
		const s = e < 0 ? o : o.slice(0, e);
		const c = transactionControlPrefix.exec(s)?.[1]?.toUpperCase();
		if (c === "ROLLBACK") {
			n = c;
			i ||= r;
			r = !/^ROLLBACK(?: TRANSACTION)? TO\b/iu.test(normalizeSqlWhitespace(s));
			i ||= !r;
		} else if (c || !/^SELECT\b/iu.test(s) && (changesSchema(s) || changesData(s))) i = true;
		n ||= c;
		if (e < 0 || t === "statement") break;
		o = o.slice(e + 1);
	}
	return n ? {
		kind: n,
		single: a === 1,
		outerRollback: r && !i
	} : void 0;
}
function canPreserveTransactionSnapshot(e, t) {
	return Boolean(t && e?.single && (e.kind === "SAVEPOINT" || e.kind === "RELEASE" || e.kind === "ROLLBACK"));
}
function classifySqliteMutation(e, t) {
	const n = changesSchema(e);
	const r = changesData(e);
	const i = n && changesOnlyTemporaryTable(e);
	return {
		schemaChange: n,
		mainSchemaChange: n && !i && !createsOnlyTemporaryObject(e),
		temporaryTableSchemaChange: i,
		dataChange: r,
		temporaryWriteTables: r ? temporaryWriteTables(e) : void 0,
		control: readTransactionControl(e, t)
	};
}
//#endregion
//#region src/infra/sqlite-native-observer.ts
const pending = resolveGlobalSingleton(Symbol.for("openclaw.sqliteNativeExecution"), () => /* @__PURE__ */ new WeakMap());
const preparedMutations = resolveGlobalSingleton(Symbol.for("openclaw.sqlitePreparedNativeMutation"), () => /* @__PURE__ */ new WeakMap());
/** Only the native begin callback may consume the pending autocommit receipt. */
function isPreparingSqliteNativeMutation(e) {
	return preparedMutations.get(e)?.phase === "preparing";
}
const iteratorFinalizer = new FinalizationRegistry((e) => {
	for (const t of e) t.finish(false, true);
});
function createIteratorLifetime(e, t) {
	const n = {
		finished: false,
		invalidated: false,
		pause: () => n.stopObservation(),
		invalidate: () => {
			n.invalidated = true;
			n.finish();
		},
		stopObservation: (e = false, r = false) => {
			const i = n.observed;
			n.observed = void 0;
			t.delete(n);
			i?.finish(e, r);
		},
		finish: (t = false, r = false) => {
			if (!n.finished) {
				n.finished = true;
				e.delete(n);
				n.stopObservation(t, r);
			}
		}
	};
	e.add(n);
	return n;
}
const bindingMutation = {
	schemaChange: false,
	mainSchemaChange: false,
	temporaryTableSchemaChange: false,
	dataChange: false,
	temporaryWriteTables: void 0,
	control: void 0
};
/** Dispose callbacks may refuse close; native custody expires only after SQLite has closed. */
function observeSqliteNativeClose(e, t) {
	for (const n of ["close", Symbol.dispose]) {
		if (typeof e[n] !== "function") continue;
		const r = e[n].bind(e);
		e[n] = () => {
			try {
				r();
			} finally {
				if (!e.isOpen) t();
			}
		};
	}
}
function callStatement(e, t) {
	return Reflect.apply(e, void 0, t);
}
/** Native callbacks can mutate from any SQL, including SELECT and retained prepared statements. */
function observeSqliteNativeOperations(e, t, n) {
	const begin = (t, r) => {
		const i = preparedMutations.get(e);
		if (i) {
			if (i.phase !== "armed" || r !== "execute" || !t.dataChange || t.schemaChange || t.control) throw new Error("Prepared SQLite mutations must execute exactly one data statement");
			i.phase = "observing";
		}
		const a = n(t, r);
		pending.set(e, (pending.get(e) ?? 0) + 1);
		return {
			...a,
			finish(t, n, r) {
				try {
					a.finish(t, n, r);
				} finally {
					const t = (pending.get(e) ?? 1) - 1;
					if (t === 0) pending.delete(e);
					else pending.set(e, t);
				}
			}
		};
	};
	const r = /* @__PURE__ */ new Set();
	const execute = (t, n, r = "execute") => {
		const i = preparedMutations.get(e);
		const a = begin(n, r);
		let o = false;
		let s = false;
		let c = false;
		try {
			if (i) {
				i.phase = "preparing";
				i.prepare();
				i.phase = "executing";
			}
			const e = t();
			s = true;
			if (r !== "bind") a.stepped?.();
			o = true;
			return e;
		} catch (t) {
			c = Boolean(i && (i.phase === "preparing" || !s && (isSqliteLockError(t) || sqlitePrimaryResultCode(t) === 19)));
			if (i && !c) {
				const n = wrapSqliteWorkerError("Prepared SQLite mutation outcome is unknown", "outcome-unknown", t);
				discardSqliteTransactionState(e, n);
				throw n;
			}
			throw t;
		} finally {
			if (i) i.phase = "finished";
			a.finish(o, false, c);
		}
	};
	e.exec = (n) => execute(() => t.DatabaseSync.prototype.exec.call(e, n), classifySqliteMutation(n, "batch"), "exec");
	e.prepare = (...n) => {
		const i = t.DatabaseSync.prototype.prepare.call(e, ...n);
		const a = classifySqliteMutation(n[0], "statement");
		const o = Object.hasOwn(i, "run") ? i.run.bind(i) : void 0;
		const s = Object.hasOwn(i, "get") ? i.get.bind(i) : void 0;
		const c = Object.hasOwn(i, "all") ? i.all.bind(i) : void 0;
		const l = Object.hasOwn(i, "iterate") ? i.iterate.bind(i) : void 0;
		const u = /* @__PURE__ */ new Set();
		let d = false;
		const reset = (e, t = "reuse") => {
			if (u.size === 0) return e();
			const n = [...u];
			const r = e();
			for (const e of n) if (t === "return") e.pause();
			else e.invalidate();
			return r;
		};
		const wrap = (e) => (...t) => execute(() => reset(() => callStatement(e(), t)), a);
		i.run = wrap(() => o ?? t.StatementSync.prototype.run.bind(i));
		i.get = wrap(() => s ?? t.StatementSync.prototype.get.bind(i));
		i.all = wrap(() => c ?? t.StatementSync.prototype.all.bind(i));
		i.iterate = (...n) => {
			if (!d) {
				iteratorFinalizer.register(i, u);
				d = true;
			}
			const o = execute(() => reset(() => callStatement(l ?? t.StatementSync.prototype.iterate.bind(i), n)), bindingMutation, "bind");
			const s = new WeakRef(o);
			const c = createIteratorLifetime(u, r);
			const f = o.next;
			const p = o.return;
			let m;
			o.next = function(...t) {
				if (m && this === s.deref() && e.isOpen) return { ...m };
				if (this !== s.deref() || c.invalidated || !e.isOpen) return f.apply(this, t);
				if (c.finished) {
					c.finished = false;
					u.add(c);
				}
				c.observed ??= begin(a, "iterate");
				r.add(c);
				const n = f.apply(this, t);
				if (n.done) {
					p?.call(this);
					m = { ...n };
					c.finish(true);
				} else c.observed?.stepped?.();
				return n;
			};
			if (p) o.return = function(...t) {
				if (m && this === s.deref() && e.isOpen) return { ...m };
				if (this !== s.deref() || !e.isOpen) return p.apply(this, t);
				const n = execute(() => c.finished || c.invalidated ? p.apply(this, t) : reset(() => p.apply(this, t), "return"), bindingMutation, "bind");
				if (n.done) m = { ...n };
				c.finish();
				return n;
			};
			return o;
		};
		for (const e of ["close", Symbol.dispose]) {
			const t = i[e]?.bind(i);
			if (t) i[e] = () => reset(t, "finalize");
		}
		return i;
	};
	observeSqliteNativeClose(e, () => {
		for (const e of r) e.invalidate();
	});
	return execute;
}
//#endregion
//#region src/infra/sqlite-database-write-receipts.ts
const state = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseWriteScopes"), () => ({
	writeScopes: /* @__PURE__ */ new WeakMap(),
	pendingWriteScopes: /* @__PURE__ */ new WeakMap(),
	localScopeRevisions: /* @__PURE__ */ new WeakMap(),
	localUnscopedRevisions: /* @__PURE__ */ new WeakMap()
}));
/** Scoped revisions borrow physical admission and publication from their existing owner. */
function createSqliteDatabaseWriteReceipts(e) {
	/** Local sibling writers notify maintenance after publishing their shared write revision. */
	function onSqliteDatabaseWriteSettled(t, n) {
		const r = sqlPublicationAnchor(t);
		const i = e.admission(r);
		if (!i) return;
		let a = e.writeListeners.get(i);
		if (!a) {
			a = /* @__PURE__ */ new Set();
			e.writeListeners.set(i, a);
		}
		return registerListener(a, n);
	}
	/** An interrupted native write may have committed before its receipt was published. */
	function settleWorker(t, n) {
		const r = n > 0 ? t.references.get(n) : void 0;
		if (r && Atomics.exchange(new Int32Array(r), 1, 0) > 0) {
			advanceSqliteDatabaseGeneration(t, "writeRevision");
			advanceSqliteDatabaseGeneration(t, "unscopedWriteRevision");
			const n = e.writeListeners.get(t);
			if (n) notifyListeners(n, void 0);
		}
	}
	/** A typed owner certifies all session keys affected by this synchronous kernel. */
	function withSqliteDatabaseWriteScope(t, n, r) {
		const i = sqlPublicationAnchor(t);
		const a = e.admission(i);
		if (!(a ? readSqliteDatabaseGeneration(a, "writeScopeRevision") > 0 : state.localScopeRevisions.has(i))) {
			const e = r();
			if (e instanceof Promise) throw new Error("SQLite write scopes cannot await work");
			return e;
		}
		const o = normalizedWriteScopes(n);
		const s = state.writeScopes.get(i);
		state.writeScopes.set(i, o);
		try {
			const e = r();
			if (e instanceof Promise) throw new Error("SQLite write scopes cannot await work");
			return e;
		} finally {
			if (s) state.writeScopes.set(i, s);
			else state.writeScopes.delete(i);
		}
	}
	/** Authority and user callbacks cannot borrow their caller's certified mutation scope. */
	function withoutSqliteDatabaseWriteScope(e, t) {
		const n = sqlPublicationAnchor(e);
		const r = state.writeScopes.get(n);
		state.writeScopes.delete(n);
		try {
			return t();
		} finally {
			if (r) state.writeScopes.set(n, r);
		}
	}
	function ensureWriteScopes(t, n, r) {
		let i = false;
		for (const e of n) {
			let n = t.writeScopes.get(e);
			if (!n || Atomics.load(n.state, 1) !== 0 || r && !pinWriteScope(n)) {
				n = createScopeRevision();
				if (r) Atomics.store(n.state, 2, 1);
				if (threadId === 0) advanceSqliteDatabaseGeneration(t, "writeScopeRevision");
				i = true;
			}
			if (r) r.push(n);
			retainSqliteDatabaseWriteScope(t, e, n);
		}
		if (i) {
			advanceSqliteDatabaseGeneration(t, "publicationRevision");
			e.publish(t, n);
		}
	}
	function pinWriteScope(e) {
		let t = Atomics.load(e.state, 2);
		while (t >= 0) {
			const n = Atomics.compareExchange(e.state, 2, t, t + 1);
			if (n === t) return true;
			t = n;
		}
		return false;
	}
	function createScopeRevision() {
		return {
			identity: randomUUID(),
			state: new Int32Array(new SharedArrayBuffer(3 * Int32Array.BYTES_PER_ELEMENT))
		};
	}
	/** Keep exact receipts through asynchronous source preparation and its final effect. */
	function retainSqliteDatabaseWriteScopesForPath(t, n) {
		const r = e.pathAdmission(t);
		if (!r || isSqliteDatabaseAdmissionRetired(r)) return;
		const i = [];
		let a = false;
		const release = () => {
			if (a) return;
			a = true;
			try {
				for (const e of i) Atomics.sub(e.state, 2, 1);
				if (i.length > 0 && !isSqliteDatabaseAdmissionRetired(r) && pruneSqliteDatabaseWriteScopes(r)) {
					advanceSqliteDatabaseGeneration(r, "publicationRevision");
					e.publish(r, []);
				}
			} finally {
				e.release(r);
			}
		};
		try {
			e.retain(r);
			ensureWriteScopes(r, normalizedWriteScopes(n), i);
			return release;
		} catch (e) {
			release();
			throw e;
		}
	}
	/** Deletion owners retire only scopes whose stored identity has actually been removed. */
	function retireSqliteDatabaseWriteScopes(t, n) {
		const r = sqlPublicationAnchor(t);
		const i = normalizedWriteScopes(n);
		const a = e.admission(r);
		const retire = () => {
			const t = a?.writeScopes ?? state.localScopeRevisions.get(r);
			const o = n.flatMap((e) => typeof e !== "string" && e.partition === void 0 ? [normalizedWriteScopes([e])[0].slice(0, -1) + ","] : []);
			for (const e of t?.keys() ?? []) if (o.some((t) => e.startsWith(t))) i.push(e);
			if (!a) {
				const e = state.localScopeRevisions.get(r);
				for (const t of i) e?.delete(t);
				return;
			}
			if (isSqliteDatabaseAdmissionRetired(a)) return;
			let s = false;
			for (const e of i) {
				const t = a.writeScopes.get(e);
				if (t && Atomics.exchange(t.state, 1, 1) === 0) s = true;
			}
			if (s) {
				advanceSqliteDatabaseGeneration(a, "writeScopeRevision");
				advanceSqliteDatabaseGeneration(a, "publicationRevision");
				e.publish(a, i);
			}
		};
		if (!stageSqliteTransactionState(r, { commit: retire }) && !t.isTransaction) retire();
	}
	function scopedWriteToken(e, t, n, r = 0) {
		const i = readSqliteDatabaseGeneration(e, "schemaRevision") + r | 0;
		const a = [];
		for (const r of t) {
			const o = e.writeScopes.get(r);
			if (!o || Atomics.load(o.state, 1) !== 0) return JSON.stringify([
				e.identity,
				e.generationId,
				i,
				"database",
				readSqliteDatabaseGeneration(e, "writeRevision") + (n !== void 0 ? 1 : 0) | 0,
				t
			]);
			a.push([
				r,
				o.identity,
				Atomics.load(o.state, 0) + (n?.has(r) ? 1 : 0) | 0
			]);
		}
		return JSON.stringify([
			e.identity,
			e.generationId,
			i,
			readSqliteDatabaseGeneration(e, "unscopedWriteRevision") + (n === null ? 1 : 0) | 0,
			a
		]);
	}
	function localScopedWriteToken(e, t, n) {
		return JSON.stringify([
			"memory",
			(state.localUnscopedRevisions.get(e) ?? 0) + (n === null ? 1 : 0),
			t.map((t) => [
				t,
				state.localScopeRevisions.get(e).get(t).identity,
				Atomics.load(state.localScopeRevisions.get(e).get(t).state, 0) + (n?.has(t) ? 1 : 0) | 0
			])
		]);
	}
	function normalizedWriteScopes(e) {
		return [...new Set((typeof e === "string" ? [e] : e).map((e) => typeof e === "string" ? JSON.stringify(["key", toUSVString(e)]) : JSON.stringify([
			"session-id",
			toUSVString(e.sessionId),
			...e.partition === void 0 ? [] : [toUSVString(e.partition)]
		])))].toSorted();
	}
	function ensureLocalWriteScopes(e, t) {
		const n = state.localScopeRevisions.get(e) ?? /* @__PURE__ */ new Map();
		for (const e of t) if (!n.has(e)) n.set(e, createScopeRevision());
		state.localScopeRevisions.set(e, n);
	}
	function readScopedWriteToken(t, n, r, i = 0) {
		const a = normalizedWriteScopes(n);
		const o = e.admission(t);
		if (o) ensureWriteScopes(o, a);
		else ensureLocalWriteScopes(t, a);
		if (e.readRevision(t) === void 0) return;
		return o ? scopedWriteToken(o, a, r, i) : localScopedWriteToken(t, a, r);
	}
	/** Per-key receipts survive unrelated committed writes. */
	function readSqliteDatabaseScopedWriteToken(e, t) {
		return readScopedWriteToken(sqlPublicationAnchor(e), t);
	}
	function readSqliteDatabaseScopedWriteTokenForPath(t, n) {
		const r = normalizedWriteScopes(n);
		const i = e.pathAdmission(t);
		if (!i || isSqliteDatabaseAdmissionRetired(i)) return;
		ensureWriteScopes(i, r);
		return scopedWriteToken(i, r);
	}
	/** A cohort discovers all dependency scopes in one admission publication. */
	function readSqliteDatabaseScopedWriteTokensForPath(t, n) {
		const r = e.pathAdmission(t);
		if (!r || isSqliteDatabaseAdmissionRetired(r)) return;
		const i = n.map(normalizedWriteScopes);
		ensureWriteScopes(r, i.flat());
		return i.map((e) => scopedWriteToken(r, e));
	}
	/** Capture the exact post-commit token before any fallible publication executes. */
	function readSqliteDatabasePendingScopedWriteToken(t, n) {
		const r = sqlPublicationAnchor(t);
		return readScopedWriteToken(r, n, state.pendingWriteScopes.get(r), e.hasPendingSchemaMutation(r) ? 1 : 0);
	}
	/** Host row caches retain a physical identity and receipt without opening SQLite. */
	function readSqliteDatabaseWriteTokenForPath(t) {
		const n = e.pathAdmission(t);
		if (!n || isSqliteDatabaseAdmissionRetired(n)) return;
		return `${n.identity}:${n.generationId}:${readSqliteDatabaseGeneration(n, "writeRevision")}`;
	}
	/** Predict the token published when the current native mutation settles. */
	function readSqliteDatabasePendingWriteToken(t) {
		const n = sqlPublicationAnchor(t);
		if (!t.isOpen || !t.isTransaction && !isPreparingSqliteNativeMutation(n) || !hasSqlitePostCommitScope(n) || e.suspended(n)) return;
		const r = e.writer(n);
		if (!r || isSqliteDatabaseAdmissionRetired(r)) return;
		return `${r.identity}:${r.generationId}:${readSqliteDatabaseGeneration(r, "writeRevision") + 1 | 0}`;
	}
	return {
		cancel(e) {
			state.pendingWriteScopes.delete(e);
		},
		begin(e, t) {
			const n = t ? void 0 : state.writeScopes.get(e);
			const r = state.pendingWriteScopes.get(e);
			if (!n || r === null) state.pendingWriteScopes.set(e, null);
			else {
				const t = r ?? /* @__PURE__ */ new Set();
				for (const e of n) t.add(e);
				state.pendingWriteScopes.set(e, t);
			}
		},
		finish(e, t) {
			const n = state.pendingWriteScopes.get(e);
			state.pendingWriteScopes.delete(e);
			let r = !n;
			if (n) {
				const i = state.localScopeRevisions.get(e);
				for (const e of n) {
					const n = i?.get(e);
					if (n) Atomics.add(n.state, 0, 1);
					const a = t?.writeScopes.get(e);
					if (a && Atomics.load(a.state, 1) === 0) Atomics.add(a.state, 0, 1);
					else if (t && (a || t.writeScopeRevision !== readSqliteDatabaseGeneration(t, "writeScopeRevision"))) r = true;
				}
			}
			if (r) {
				state.localUnscopedRevisions.set(e, (state.localUnscopedRevisions.get(e) ?? 0) + 1);
				if (t) advanceSqliteDatabaseGeneration(t, "unscopedWriteRevision");
			}
		},
		settleWorker,
		onSqliteDatabaseWriteSettled,
		retireSqliteDatabaseWriteScopes,
		retainSqliteDatabaseWriteScopesForPath,
		withSqliteDatabaseWriteScope,
		withoutSqliteDatabaseWriteScope,
		readSqliteDatabaseScopedWriteToken,
		readSqliteDatabaseScopedWriteTokenForPath,
		readSqliteDatabaseScopedWriteTokensForPath,
		readSqliteDatabasePendingScopedWriteToken,
		readSqliteDatabaseWriteTokenForPath,
		readSqliteDatabasePendingWriteToken
	};
}
//#endregion
//#region src/infra/sqlite-schema-scope.ts
const sqliteSchemaOwners = resolveGlobalSingleton(Symbol.for("openclaw.sqliteSchemaFacts"), () => /* @__PURE__ */ new WeakMap());
function observeSqliteTransactionState(e, t) {
	const n = e.isTransaction;
	if (t.transactionOpen !== n) {
		if (t.transactionOpen) t.mutationRevision += 1;
		t.transactionOpen = n;
		t.transactionMutationRevision = void 0;
		t.transactionSnapshot = void 0;
		t.transactionRead = false;
		t.transactionCatalogBound = false;
	}
}
function finishSqliteReadScope(e, t, n, r, i, a) {
	const o = e.isTransaction;
	if (!i && n && !o) t.mutationRevision += 1;
	t.transactionOpen = o;
	if (!n || !o) t.transactionMutationRevision = o ? a : void 0;
	if (n !== o || r) {
		t.transactionSnapshot = void 0;
		t.transactionRead = false;
		t.transactionCatalogBound = false;
	}
}
//#endregion
//#region src/infra/sqlite-database-admission.ts
const seals = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseCleanCloseSeals"), () => new SqliteDatabaseCleanCloseSeals(publishFact, {
	retain: (e) => state$2.registry.changeReferences(e, 1),
	release: releaseReference,
	publish: (e) => state$2.registry.publish(e),
	descriptor: (e) => state$2.registry.descriptors.get(e.identity)
}));
const descriptors = createSqliteDatabaseDescriptorOwner(seals);
const { prepareSqliteDatabaseAdmissionAsync, prepareSqliteDatabaseAdmission, retainSqliteDatabaseAdmissionLocation } = descriptors;
const { pathAdmission } = descriptors;
function readSqliteDatabaseCleanClose(e) {
	const t = prepareSqliteDatabaseAdmission(e);
	const n = pathAdmission(e);
	return n !== void 0 && n.identity === t && Atomics.load(new Int32Array(n.generation), SqliteDatabaseGenerationSlot.sealPresent) === 1;
}
function recordSqliteDatabaseIntegrity(e, t = Date.now()) {
	publishSqliteDatabaseAdmission(e, integrityVerificationKey, t);
}
/** Capture admitted facts before close; publish only after successful TRUNCATE and native close. */
function prepareSqliteDatabaseCleanClose(e) {
	return seals.prepare(e, admission(e), getSqliteDatabaseAdmission(e, integrityVerificationKey) ?? getSqliteDatabaseAdmission(e, quickIntegrityVerificationKey));
}
const reader = createSqliteDatabaseAdmissionReader({
	state: state$2,
	admission,
	pathAdmission,
	exchange: exchangeSqliteDatabaseAdmission,
	publishFact,
	retain: retainReference,
	release: releaseReference
});
const { getSqliteDatabaseAdmission, getSqliteDatabaseSchemaRevision, getOrLoadSqliteDatabaseAdmissionForPath, peekSqliteDatabaseAdmissionForPath, prepareSqliteDatabaseAdmissionForPath, hasSqliteDatabaseSchemaAdmissionForPath, getSqliteDatabaseAdmissionIdentityForPath, hasSqliteDatabaseSchemaAdmissionForIdentity } = reader;
const scopedWrites = createSqliteDatabaseWriteReceipts({
	admission,
	pathAdmission,
	retain: retainReference,
	release: releaseReference,
	writeListeners: state$2.writeListeners,
	readRevision: readSqliteDatabaseWriteRevision,
	writer: (e) => state$2.dataWriters.get(e),
	suspended: (e) => state$2.suspended.has(e),
	hasPendingSchemaMutation: (e) => e.isTransaction && sqliteSchemaOwners.get(e)?.transactionalSchema === true,
	publish(e, t) {
		state$2.registry.publish(e, t);
		exchangeSqliteDatabaseAdmission(e);
	}
});
const { onSqliteDatabaseWriteSettled, retireSqliteDatabaseWriteScopes, retainSqliteDatabaseWriteScopesForPath, withSqliteDatabaseWriteScope, withoutSqliteDatabaseWriteScope, readSqliteDatabaseScopedWriteToken, readSqliteDatabaseScopedWriteTokenForPath, readSqliteDatabaseScopedWriteTokensForPath, readSqliteDatabasePendingScopedWriteToken, readSqliteDatabaseWriteTokenForPath, readSqliteDatabasePendingWriteToken } = scopedWrites;
/** Explicit readiness/readmission shares committed facts before handing off the connection. */
function settleSqliteDatabaseAdmissionPublication(e) {
	if (e.isTransaction || getSqliteNativeAdmissionFacts(e) || hasSqlitePostCommitScope(e) || state$2.exchanging) return false;
	const t = admission(e);
	if (t) exchangeSqliteDatabaseAdmission(t, void 0, true);
	return true;
}
function bindSqliteDatabaseAdmission(e, t) {
	state$2.connections.delete(e);
	state$2.openedIdentities.delete(e);
	state$2.unproven.delete(e);
	const n = e.location();
	if (!n || n === ":memory:") return;
	const r = prepareSqliteDatabaseAdmission(n);
	if (t !== void 0 && r !== t) throw new Error("SQLite database changed identity during native open");
	if (!r) return;
	state$2.openedIdentities.set(e, r);
	if (t === void 0) {
		state$2.unproven.add(e);
		return;
	}
	const i = state$2.registry.records.get(r);
	if (i && !isSqliteDatabaseAdmissionRetired(i) || state$2.registry.descriptors.get(r)?.facts.size) admission(e);
}
function admission(e, t = true) {
	const n = state$2.openedIdentities.get(e);
	if (!e.isOpen || n === void 0 || state$2.unproven.has(e)) return;
	const r = state$2.connections.get(e);
	if (r) return isSqliteDatabaseAdmissionRetired(r) ? void 0 : r;
	const i = e.location();
	if (!i || i === ":memory:") return;
	const a = t && !e.isTransaction ? pathAdmission(i) : state$2.registry.records.get(n);
	if (a && a.identity !== n) throw new Error("SQLite database changed identity before admission");
	return a && !isSqliteDatabaseAdmissionRetired(a) ? retainConnection(e, a) : void 0;
}
function retainConnection(e, t) {
	const n = t.identity;
	let r = t;
	try {
		for (;;) {
			if (r.identity !== n) throw new Error("SQLite database changed identity during native open");
			const t = state$2.registry.changeReferences(r, 1);
			let i = false;
			try {
				if (t) exchangeSqliteDatabaseAdmission(r);
				const n = readSqliteDatabaseGeneration(r, "retired");
				if (n === 0) {
					state$2.connections.set(e, r);
					i = true;
					return r;
				}
				if (n !== 2) throw new Error("SQLite database admission retired during native open");
			} finally {
				if (!i) state$2.registry.changeReferences(r, -1);
			}
			const a = e.location();
			const o = e.isTransaction ? state$2.registry.records.get(n) : a ? pathAdmission(a) : void 0;
			if (!o || isSqliteDatabaseAdmissionRetired(o)) throw new Error("SQLite database admission unavailable during native open");
			r = o;
		}
	} catch (t) {
		state$2.openedIdentities.delete(e);
		throw t;
	}
}
/** Native close retires row receipts while descriptor custody retains opted-in physical facts. */
function releaseSqliteDatabaseAdmission(e) {
	const t = state$2.connections.get(e);
	if (state$2.openedIdentities.delete(e) && t) {
		state$2.local.delete(e);
		releaseReference(t);
	}
}
function retainReference(e) {
	if (state$2.registry.changeReferences(e, 1)) exchangeSqliteDatabaseAdmission(e);
}
function releaseReference(e) {
	if (state$2.registry.changeReferences(e, -1)) {
		state$2.localSchemaRevisions.delete(e.identity);
		exchangeSqliteDatabaseAdmission(e);
	}
}
function publishFact(e, t, n, r) {
	if (t.writer === "host" && threadId !== 0) throw new Error("SQLite host-owned admission facts require the host publisher");
	if (!publishSqliteDatabaseFact(e, t, n, r, `${threadId}:${++state$2.publication}`)) return;
	state$2.registry.publish(e);
	if (t.writer !== "connection") exchangeSqliteDatabaseAdmission(e);
}
/** Publish one row-cache revision when a local native write settles. */
function beginSqliteDatabaseWrite(e, t = false) {
	const n = admission(e);
	if (n && Atomics.load(new Int32Array(n.generation), SqliteDatabaseGenerationSlot.sealPresent) === 1) seals.invalidate(n.location, n);
	scopedWrites.begin(e, t);
	if (state$2.dataWriters.has(e)) return;
	state$2.dataWriters.set(e, n);
	if (n) Atomics.add(new Int32Array(n.references.get(threadId)), 1, 1);
}
/** Failed writes invalidate too, unless the prepared native owner certifies no effect. */
function finishSqliteDatabaseWrite(e, t = false) {
	if (!state$2.dataWriters.has(e)) return;
	const n = state$2.dataWriters.get(e);
	state$2.dataWriters.delete(e);
	if (t) {
		scopedWrites.cancel(e);
		if (n) Atomics.sub(new Int32Array(n.references.get(threadId)), 1, 1);
		return;
	}
	state$2.localWriteRevisions.set(e, (state$2.localWriteRevisions.get(e) ?? 0) + 1);
	scopedWrites.finish(e, n);
	if (n) {
		advanceSqliteDatabaseGeneration(n, "writeRevision");
		Atomics.sub(new Int32Array(n.references.get(threadId)), 1, 1);
		const e = state$2.writeListeners.get(n);
		if (e) notifyListeners(e, void 0);
	}
}
/** Ordinary reads consume the last committed writer revision without a writer census. */
function readSqliteDatabaseWriteRevision(e) {
	const t = sqlPublicationAnchor(e);
	if (!t.isOpen || state$2.suspended.has(t)) return;
	const n = admission(t);
	if (!n) {
		const e = t.location();
		return !e || e === ":memory:" ? state$2.localWriteRevisions.get(t) ?? 0 : void 0;
	}
	return readSqliteDatabaseGeneration(n, "writeRevision");
}
/** Settle interrupted native writes before releasing the departed worker's handles. */
function trackSqliteDatabaseAdmissionWorker(e) {
	const t = e.threadId;
	e.once("exit", () => {
		for (const e of state$2.registry.records.values()) scopedWrites.settleWorker(e, t);
		state$2.registry.releaseWorker(t);
	});
}
function hasPendingSqliteDatabaseSchemaMutation(e) {
	const t = sqlPublicationAnchor(e);
	return e.isTransaction && state$2.schemaDirty.has(t);
}
function publishSqliteDatabaseAdmission(e, t, n, r = {}) {
	const i = sqlPublicationAnchor(e);
	const a = admission(i, !e.isTransaction);
	if (!a || isSqliteDatabaseAdmissionRetired(a) || state$2.suspended.has(i)) return;
	if (t.writer === "host" && threadId !== 0) throw new Error("SQLite host-owned admission facts require the host publisher");
	const o = (t.schemaDependent ? r.schemaRevision : void 0) ?? readSqliteDatabaseFactRevision(a, t.schemaDependent);
	const s = isPostgresSqlConnection(e) ? void 0 : getSqliteNativeAdmissionFacts(e);
	const c = admitSqliteDatabaseFactValue(t, n);
	if (!s && !e.isTransaction && !hasSqlitePostCommitScope(e)) {
		publishFact(a, t, c, o);
		return;
	}
	const l = {
		...c,
		revision: o,
		schemaDependent: t.schemaDependent === true,
		ddlRevision: state$2.ddlRevisions.get(i) ?? 0
	};
	if (s) {
		s.set(t.name, l);
		return;
	}
	const u = state$2.local.get(i) ?? /* @__PURE__ */ new Map();
	state$2.local.set(i, u);
	const d = u.get(t.name);
	const restore = () => {
		if (state$2.local.get(i) !== u) return;
		if (d === void 0) u.delete(t.name);
		else u.set(t.name, d);
	};
	stageSqliteTransactionState(i, {
		stage: () => u.set(t.name, l),
		rollback: restore,
		commit: () => {
			if (state$2.local.get(i) === u && u.get(t.name) === l) {
				u.delete(t.name);
				if (l.revision === readSqliteDatabaseFactRevision(a, l.schemaDependent) && (!l.schemaDependent || l.ddlRevision === (state$2.ddlRevisions.get(i) ?? 0))) publishFact(a, t, l, l.revision);
			}
		}
	});
}
/** Track uncommitted DDL separately so it cannot revive a receipt validated before a later change. */
function invalidateLocalSqliteSchemaAdmissions(e) {
	const t = sqlPublicationAnchor(e);
	const n = state$2.ddlRevisions.get(t) ?? 0;
	const r = state$2.schemaDirty.has(t);
	const stage = () => {
		state$2.ddlRevisions.set(t, n + 1);
		state$2.schemaDirty.add(t);
	};
	if (!stageSqliteTransactionState(t, {
		stage,
		commit: () => {},
		rollback: () => {
			state$2.ddlRevisions.set(t, n);
			if (!r) state$2.schemaDirty.delete(t);
		}
	})) stage();
}
/** Raw rollback cannot restore staging boundaries; require new facts in any remaining transaction. */
function discardSqliteDatabaseTransactionAdmissions(e) {
	const t = sqlPublicationAnchor(e);
	const n = admission(t, false);
	for (const r of [isPostgresSqlConnection(e) ? void 0 : getSqliteNativeAdmissionFacts(e), state$2.local.get(t)]) {
		for (const e of r?.keys() ?? []) {
			const t = n?.facts.get(e);
			if (t) Atomics.store(new Int32Array(t.current), 0, 0);
		}
		r?.clear();
	}
	state$2.local.delete(t);
	state$2.rolledBack.add(t);
	if (!e.isTransaction) state$2.schemaDirty.delete(t);
}
/** The DDL owner advances committed format and acknowledges only its final validated receipts. */
function publishSqliteDatabaseSchemaChange(e) {
	const t = sqlPublicationAnchor(e);
	const n = admission(t, false);
	if (n) {
		const e = advanceSqliteDatabaseGeneration(n, "schemaRevision");
		const r = state$2.ddlRevisions.get(t) ?? 0;
		for (const n of state$2.local.get(t)?.values() ?? []) if (n.schemaDependent && n.revision === e && n.ddlRevision === r) n.revision = e + 1;
	} else {
		const e = state$2.openedIdentities.get(t);
		if (e) state$2.localSchemaRevisions.set(e, (state$2.localSchemaRevisions.get(e) ?? 0) + 1);
	}
	if (!e.isTransaction) state$2.schemaDirty.delete(t);
}
function revoke(e, t = e?.location) {
	if (t) seals.invalidate(t, e);
	revokeSqliteDatabaseAdmissionFacts(e);
}
function revokeSqliteDatabaseAdmissions(e) {
	revoke(state$2.connections.get(e) ?? admission(e));
	state$2.local.delete(e);
}
function revokeSqliteDatabaseAdmissionsForPath(e) {
	revoke(pathAdmission(e), e);
}
/** Explicit removal or maintenance calls this only after its owner has joined native consumers. */
function retireSqliteDatabaseAdmissionForPath(e, t = {}) {
	const n = prepareSqliteDatabaseAdmission(e);
	if (!n) return;
	state$2.localSchemaRevisions.delete(n);
	const r = threadId === 0 ? state$2.registry.records.get(n) : pathAdmission(e);
	if (state$2.registry.retireDescriptor(n, t) && r) exchangeSqliteDatabaseAdmission(r);
}
function suspendSqliteDatabaseAdmission(e, t) {
	if (t) state$2.suspended.add(e);
	else state$2.suspended.delete(e);
}
//#endregion
export { readTableConstraintKeyword as $, trackSqliteDatabaseAdmissionWorker as A, STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS as B, releaseSqliteDatabaseAdmission as C, stageSqliteTransactionState as Ct, revokeSqliteDatabaseAdmissionsForPath as D, revokeSqliteDatabaseAdmissions as E, observeSqliteNativeOperations as F, findSqlCharacter as G, createSqliteTableContract as H, canPreserveTransactionSnapshot as I, normalizeSchemaSql as J, findSqlClosingParenthesis as K, OPENCLAW_STATE_SCHEMA_SQL as L, observeSqliteTransactionState as M, sqliteSchemaOwners as N, settleSqliteDatabaseAdmissionPublication as O, observeSqliteNativeClose as P, readSqlToken as Q, installSqliteNativeRuntimeAdmission as R, recordSqliteDatabaseIntegrity as S, prepareSqliteTransactionCommit as St, retireSqliteDatabaseAdmissionForPath as T, parseSqliteTableDefinition as U, createSqliteIndexContract as V, extractSqliteTableSchema as W, normalizeSqlWhitespace as X, normalizeSqlIdentifier as Y, quoteSqliteIdentifier as Z, publishSqliteDatabaseAdmission as _, retainSqliteReader as _t, getOrLoadSqliteDatabaseAdmissionForPath as a, installSqliteDatabaseAdmissions as at, readSqliteDatabaseWriteRevision as b, discardSqliteTransactionState as bt, getSqliteDatabaseSchemaRevision as c, readSqliteDatabaseAdmissions as ct, invalidateLocalSqliteSchemaAdmissions as d, ensureSqliteLibrarySelected as dt, splitSqlList as et, onSqliteDatabaseWriteSettled as f, getSqliteRuntimeCapabilities as ft, prepareSqliteDatabaseCleanClose as g, registerSqliteReaderConnection as gt, prepareSqliteDatabaseAdmissionAsync as h, readSqliteReaderDiagnosticsForPath as ht, finishSqliteDatabaseWrite as i, captureSqliteDatabaseAdmissions as it, finishSqliteReadScope as j, suspendSqliteDatabaseAdmission as k, hasPendingSqliteDatabaseSchemaMutation as l, captureSqliteWorkerClosePolicy as lt, prepareSqliteDatabaseAdmission as m, currentSqliteOperationTiming as mt, bindSqliteDatabaseAdmission as n, resolveSqliteDatabaseFilePath as nt, getSqliteDatabaseAdmission as o, withSqliteDatabaseAdmissionExchange as ot, peekSqliteDatabaseAdmissionForPath as p, captureSqliteReaderOwner as pt, hasUnquotedSqlKeyword as q, discardSqliteDatabaseTransactionAdmissions as r, canShareSqliteDatabaseAdmissions as rt, getSqliteDatabaseAdmissionIdentityForPath as s, createSqliteDatabaseAdmissionCursor as st, beginSqliteDatabaseWrite as t, beginSqliteDatabaseAdmissionOperation as tt, hasSqliteDatabaseSchemaAdmissionForIdentity as u, captureSqliteWorkerEnvironmentData as ut, publishSqliteDatabaseSchemaChange as v, sqliteReaderDatabasePathKey as vt, retainSqliteDatabaseAdmissionLocation as w, withSqlitePostCommitPublications as wt, readSqliteDatabaseWriteTokenForPath as x, hasSqlitePostCommitScope as xt, readSqliteDatabaseCleanClose as y, deferSqlitePostCommitPublication as yt, requireNodeSqlite as z };