UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

998 lines (997 loc) • 48.1 kB
import { p as isRecord } from "./utils-BclMknzT.mjs"; import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs"; import { c as sqliteErrorCode, l as sqliteExtendedResultCode } from "./sqlite-error-diagnostics-DXQCgyiD.mjs"; import { n as isPostgresSqlConnection } from "./sql-connection-VmV9pnJI.mjs"; import { c as registerNodeSqliteDisposeCallback, i as executeWithCachedStatement } from "./kysely-sync-cache-state-D75yJYFp.mjs"; import { C as releaseSqliteDatabaseAdmission, F as observeSqliteNativeOperations, I as canPreserveTransactionSnapshot, J as normalizeSchemaSql, M as observeSqliteTransactionState, N as sqliteSchemaOwners, O as settleSqliteDatabaseAdmissionPublication, P as observeSqliteNativeClose, Z as quoteSqliteIdentifier, _ as publishSqliteDatabaseAdmission, b as readSqliteDatabaseWriteRevision, c as getSqliteDatabaseSchemaRevision, d as invalidateLocalSqliteSchemaAdmissions, i as finishSqliteDatabaseWrite, j as finishSqliteReadScope, k as suspendSqliteDatabaseAdmission, o as getSqliteDatabaseAdmission, r as discardSqliteDatabaseTransactionAdmissions, t as beginSqliteDatabaseWrite, tt as beginSqliteDatabaseAdmissionOperation, v as publishSqliteDatabaseSchemaChange } from "./sqlite-database-admission-DMm34jqt.mjs"; import { isDeepStrictEqual } from "node:util"; import { createHash, randomUUID } from "node:crypto"; import { isMainThread } from "node:worker_threads"; //#region src/infra/database-engine/physical-facts-contract.ts const postgresPhysicalFactsKey = { name: "database.engine.schema", schemaDependent: true }; //#endregion //#region src/infra/database-engine/postgres-catalog.ts function canonical(e) { return JSON.stringify(e, (e, t) => t !== null && typeof t === "object" && !Array.isArray(t) ? Object.fromEntries(Object.entries(t).toSorted(([e], [t]) => e.localeCompare(t, "en"))) : t); } function assertPostgresCatalog(e, t) { if (!isDeepStrictEqual(e.map(canonical).toSorted(), t.map(canonical).toSorted())) throw new Error("PostgreSQL catalog differs from its generated contract; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor."); } function readPostgresCatalog(e) { if (!Array.isArray(e) || !e.every((e) => e !== null && typeof e === "object" && typeof e.table === "string" && typeof e.kind === "string" && "value" in e)) throw new Error("PostgreSQL did not return catalog facts"); return e; } /** One statement gives every catalog fact the same PostgreSQL MVCC snapshot. */ function postgresCatalogQuery(e, t = false) { const n = `'${e.replaceAll("'", "''")}'`; const columns = (e, t) => `(SELECT jsonb_agg(a.attname ORDER BY k.ordinality) FROM unnest(${t}) WITH ORDINALITY k(num, ordinality) JOIN pg_catalog.pg_attribute a ON a.attrelid = ${e} AND a.attnum = k.num)`; const action = (e) => `CASE ${e} WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END`; return `WITH relations AS ( SELECT c.oid, c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${n} AND c.relkind IN ('r', 'p') ), attributes AS ( SELECT r.relname, a.attname, a.atttypid, a.atttypmod, a.attnotnull, a.attidentity, a.attnum, a.attgenerated, a.attcollation, pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default_expression FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum WHERE a.attnum > 0 AND NOT a.attisdropped ), facts AS ( SELECT r.relname AS "table", 'table' AS kind, 'null'::jsonb AS value FROM relations r UNION ALL SELECT a.relname, 'column', jsonb_build_object( 'name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod), 'nullable', NOT a.attnotnull, 'identity', a.attidentity = 'd', 'position', a.attnum, 'default', regexp_replace(a.default_expression, '::(text|bigint|double precision)$', '')) FROM attributes a UNION ALL SELECT r.relname, CASE c.contype WHEN 'p' THEN 'primaryKey' ELSE 'unique' END, ${columns("r.oid", "c.conkey")} FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid WHERE c.contype IN ('p', 'u') UNION ALL SELECT r.relname, 'foreignKey', jsonb_build_object( 'columns', ${columns("r.oid", "c.conkey")}, 'target', target.relname, 'targetColumns', ${columns("c.confrelid", "c.confkey")}, 'onUpdate', ${action("c.confupdtype")}, 'onDelete', ${action("c.confdeltype")}, 'deferrable', c.condeferrable, 'deferred', c.condeferred) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid JOIN pg_catalog.pg_class target ON target.oid = c.confrelid WHERE c.contype = 'f' UNION ALL SELECT r.relname, 'indexes', to_jsonb((SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = r.oid)) FROM relations r UNION ALL SELECT r.relname, 'checks', to_jsonb((SELECT count(*) FROM pg_catalog.pg_constraint c WHERE c.conrelid = r.oid AND c.contype = 'c')) FROM relations r ${t ? `UNION ALL SELECT r.relname, 'constraintDefinition', jsonb_build_object('name', c.conname, 'definition', pg_catalog.pg_get_constraintdef(c.oid)) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid UNION ALL SELECT a.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', a.default_expression, 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM attributes a UNION ALL SELECT r.relname, 'triggerDefinition', jsonb_build_object('name', t.tgname, 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled, 'function', pg_catalog.pg_get_functiondef(t.tgfoid)) FROM relations r JOIN pg_catalog.pg_trigger t ON t.tgrelid = r.oid WHERE NOT t.tgisinternal UNION ALL SELECT c.relname, 'viewDefinition', to_jsonb(pg_catalog.pg_get_viewdef(c.oid)) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${n} AND c.relkind IN ('v', 'm') UNION ALL SELECT c.cfgname, 'textSearchDefinition', jsonb_build_object('token', m.maptokentype, 'order', m.mapseqno, 'dictionary', d.dictname, 'namespace', dn.nspname) FROM pg_catalog.pg_ts_config c JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace JOIN pg_catalog.pg_ts_config_map m ON m.mapcfg = c.oid JOIN pg_catalog.pg_ts_dict d ON d.oid = m.mapdict JOIN pg_catalog.pg_namespace dn ON dn.oid = d.dictnamespace WHERE n.nspname = ${n} AND c.cfgname = 'openclaw_simple_unaccent' UNION ALL SELECT p.proname, 'functionDefinition', to_jsonb(pg_catalog.pg_get_functiondef(p.oid)) FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${n} AND p.proname = 'openclaw_vector' AND p.prokind = 'f'` : ""} ) SELECT coalesce(jsonb_agg(facts), '[]'::jsonb) AS catalog FROM facts`; } //#endregion //#region src/infra/database-engine/capability-unavailable.ts var DatabaseSearchCapabilityUnavailableError = class extends Error { constructor(e, t) { super(t ?? `Database ${e} search capability is unavailable.`); this.capability = e; this.code = "DATABASE_SEARCH_CAPABILITY_UNAVAILABLE"; this.name = "DatabaseSearchCapabilityUnavailableError"; } }; //#endregion //#region src/infra/database-engine/postgres-search-schema.ts const pgSearchName = (e) => `"${e.replaceAll("\"", "\"\"")}"`; const searchConfig = "openclaw_simple_unaccent"; /** * PostgreSQL's parser keeps dates, paths, file names and `a/b` as single lexemes * (`-08`, `server.py`, `/v1/models`); SQLite FTS5 unicode61 splits on every * non-alphanumeric character. Replacing punctuation runs before parsing gives * both engines the same words; the ASCII class keeps the expression locale-stable. */ const postgresSearchTokenSeparators = "[[:punct:]]+"; /** The stored vector expression; `config` and `field` are already-rendered SQL. */ function postgresSearchVectorSql(e, t, n = 1) { const r = `coalesce(${t}, '')`; return `to_tsvector(${e}::regconfig, ${n === 2 ? `regexp_replace(${r}, '${postgresSearchTokenSeparators}', ' ', 'g')` : r})`; } /** * Version 2 maintains the vector from a trigger instead of a generated column: * PostgreSQL 16 cannot change a generated expression in place, and dropping the * column would move its position out of the sealed catalog. The body resolves * the configuration from the trigger's own schema so it carries no namespace. */ function postgresSearchTextTriggerSql(e) { const { table: t, field: n, sync: r } = e; return `CREATE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN NEW.openclaw_search := ${postgresSearchVectorSql(`format('%I.%I', TG_TABLE_SCHEMA, '${searchConfig}')`, `NEW.${n}`, 2)}; RETURN NEW; END $$; CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE OF ${n} ON ${t} FOR EACH ROW EXECUTE FUNCTION ${r}();`; } const key = { name: "database.postgres.search", schemaDependent: true }; /** Called only by store admission; query paths consume these retained facts. */ function admitPostgresSearch(e, t, n, r = 1) { const i = JSON.stringify(t); if (getSqliteDatabaseAdmission(e, key)?.some((e) => e.signature === i && e.vectorSearchVersion >= r)) return; const a = /* @__PURE__ */ new Set(); if (Object.keys(t.text ?? {}).length) a.add("unaccent"); if (Object.values(t.text ?? {}).some((e) => e.postgres?.mode === "trigram")) a.add("pg_trgm"); if (t.mode !== "keyword-only" && Object.keys(t.vector ?? {}).length) a.add("vector"); for (const e of t.mode === "keyword-only" ? [] : Object.values(t.vector ?? {})) { const t = e.postgres?.dimensions; if (!Number.isInteger(t) || t < 1 || t > 16e3) throw new Error("PostgreSQL vector capability unavailable: dimensions must be 1–16000; choose a supported embedding dimension and rebuild the derived index."); } const o = t.extensionSchema ?? "public"; const s = e.prepare(`SELECT a.name, e.extname, e.extversion, n.nspname FROM pg_catalog.pg_available_extensions a LEFT JOIN pg_catalog.pg_extension e ON e.extname = a.name LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE a.name IN ('unaccent', 'pg_trgm', 'vector')`).all(); for (const e of a) { const t = s.find((t) => t.name === e); if (!t?.extname || t.nspname !== o) { const n = !t ? `Install the server extension package for ${e}, then have a database administrator run` : t.extname ? `Configure the store's extensionSchema as ${String(t.nspname)}, or have a database administrator relocate the extension; installation SQL is` : "Have a database administrator run"; throw new DatabaseSearchCapabilityUnavailableError(e === "vector" ? "vector" : "fullText", `PostgreSQL ${e} capability unavailable. ${n}: CREATE EXTENSION IF NOT EXISTS ${pgSearchName(e)} WITH SCHEMA ${pgSearchName(o)};${e === "vector" ? " For keyword-only memory explicitly set memory.search.provider to \"none\"." : ""}`); } if (e === "vector" && r === 2) { const e = /^(\d+)\.(\d+)/.exec(String(t.extversion)); if (!e || Number(e[1]) === 0 && Number(e[2]) < 7) throw new DatabaseSearchCapabilityUnavailableError("vector", "PostgreSQL binary vector search requires pgvector 0.7 or newer. Upgrade the server extension package, then have a database administrator run ALTER EXTENSION vector UPDATE before reopening the store."); } } if (e.prepare("SELECT coalesce(has_schema_privilege(to_regnamespace(?), 'CREATE'), has_database_privilege(current_database(), 'CREATE'))::int AS allowed").get(n)?.allowed !== 1) throw new Error(`PostgreSQL search capability unavailable: insufficient CREATE privilege. Have the database owner grant CREATE on schema ${pgSearchName(n)} (or on the database before initial admission).`); return () => publishPostgresSearch(e, t, r); } function publishPostgresSearch(e, t, n = 1) { const r = JSON.stringify(t); const i = getSqliteDatabaseAdmission(e, key) ?? []; const a = i.find((e) => e.signature === r); publishSqliteDatabaseAdmission(e, key, [...i.filter((e) => e.signature !== r), { signature: r, vectorSearchVersion: a?.vectorSearchVersion === 2 ? 2 : n }]); } /** Canonical bytes remain binary64; the derived vector rounds once to float32. */ function postgresVectorDecoderSql(e, t = 1, n = false) { const r = pgSearchName(e); if (t === 1) return `CREATE ${n ? "OR REPLACE " : ""}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector LANGUAGE plpgsql IMMUTABLE STRICT AS $$ DECLARE vals real[] := '{}'; bits bigint; exponent integer; fraction double precision; value double precision; BEGIN IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF; FOR i IN 0..dimensions-1 LOOP bits := 0; FOR j IN 0..7 LOOP bits := bits | (get_byte(bytes, i*8+j)::bigint << (j*8)); END LOOP; exponent := ((bits >> 52) & 2047)::integer; IF exponent = 2047 THEN RAISE EXCEPTION 'embedding must be finite'; END IF; fraction := (bits & 4503599627370495)::double precision / 4503599627370496; IF exponent < 873 OR (exponent = 873 AND fraction = 0) THEN value := 0; ELSE value := (1 + fraction) * power(2::double precision, exponent - 1023); END IF; IF bits < 0 THEN value := -value; END IF; vals := array_append(vals, value::real); END LOOP; RETURN vals::${r}.vector; END $$;`; return `CREATE ${n ? "OR REPLACE " : ""}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector LANGUAGE plpgsql IMMUTABLE STRICT AS $$ DECLARE vals double precision[]; first_nonfinite integer; BEGIN IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF; -- Flatten TOAST once: repeated get_byte calls otherwise detoast the entire embedding. bytes := bytes || '\\x'::bytea; WITH bits AS MATERIALIZED ( SELECT i, get_byte(bytes, i*8)::bigint | (get_byte(bytes, i*8+1)::bigint << 8) | (get_byte(bytes, i*8+2)::bigint << 16) | (get_byte(bytes, i*8+3)::bigint << 24) | (get_byte(bytes, i*8+4)::bigint << 32) | (get_byte(bytes, i*8+5)::bigint << 40) | (get_byte(bytes, i*8+6)::bigint << 48) | (get_byte(bytes, i*8+7)::bigint << 56) AS b FROM generate_series(0, dimensions-1) AS i ), parts AS ( SELECT i, b, ((b >> 52) & 2047)::integer AS exponent, (b & 4503599627370495)::double precision / 4503599627370496 AS fraction FROM bits ) SELECT coalesce(array_agg( CASE WHEN b < 0 THEN -1::double precision ELSE 1::double precision END * CASE WHEN exponent = 2047 OR exponent < 873 OR (exponent = 873 AND fraction = 0) THEN 0::double precision ELSE (1 + fraction) * power(2::double precision, exponent - 1023) END ORDER BY i ), ARRAY[]::double precision[]), min(i) FILTER (WHERE exponent = 2047) INTO vals, first_nonfinite FROM parts; IF first_nonfinite IS NOT NULL THEN -- Preserve the old left-to-right overflow versus nonfinite error precedence. PERFORM vals[1:first_nonfinite]::real[]; RAISE EXCEPTION 'embedding must be finite'; END IF; RETURN vals::real[]::${r}.vector; END $$;`; } /** Deterministic derived DDL joins the store's generated DDL hash and exact catalog seal. */ function postgresSearchSql(e, t, n = {}, r = 1, i = 1, a = 1) { const o = pgSearchName(e.extensionSchema ?? "public"); const s = `${pgSearchName(t)}.${pgSearchName(searchConfig)}`; const c = `'${s.replaceAll("'", "''")}'`; const l = []; if (Object.keys(e.text ?? {}).length && !n.text) l.push(`CREATE TEXT SEARCH CONFIGURATION ${s} (COPY = pg_catalog.simple); ALTER TEXT SEARCH CONFIGURATION ${s} ALTER MAPPING FOR hword, hword_part, word, numword, numhword, hword_numpart WITH ${o}.unaccent, pg_catalog.simple;`); for (const t of Object.values(e.text ?? {})) { if (!t.postgres || t.fields.length !== 1) throw new Error("PostgreSQL text index requires one field and a declared source identity"); const e = pgSearchName(t.table), n = pgSearchName(t.fields[0]); l.push(a === 2 ? `ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector; ${postgresSearchTextTriggerSql({ table: e, field: n, sync: pgSearchName(`${t.table}_search_sync`) })} UPDATE ${e} SET openclaw_search = ${postgresSearchVectorSql(c, n, 2)};` : `ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector GENERATED ALWAYS AS (${postgresSearchVectorSql(c, n)}) STORED;`); l.push(`CREATE INDEX ${pgSearchName(`${t.table}_search_gin`)} ON ${e} USING gin(openclaw_search);`); if (t.postgres.mode === "trigram") l.push(`CREATE INDEX ${pgSearchName(`${t.table}_trgm_gin`)} ON ${e} USING gin(${n} ${o}.gin_trgm_ops);`); } if (e.mode === "keyword-only") return l.join("\n"); if (Object.keys(e.vector ?? {}).length && !n.vector) l.push(postgresVectorDecoderSql(e.extensionSchema ?? "public", r)); for (const t of Object.values(e.vector ?? {})) { const e = t.postgres; if (!e) throw new Error("PostgreSQL vector index requires a canonical embedding source"); const n = pgSearchName(t.table), r = pgSearchName(e.source), a = pgSearchName(e.key), s = pgSearchName(e.embedding); const c = `INSERT INTO ${n}(id, embedding) SELECT ${a}, openclaw_vector(${s}, ${e.dimensions}) FROM ${r} WHERE octet_length(${s}) > 0`; const u = i === 2 ? `, embedding_bits bit(${e.dimensions}) GENERATED ALWAYS AS (CASE WHEN ${o}.vector_norm(embedding) > 0 THEN ${o}.binary_quantize(embedding)::bit(${e.dimensions}) ELSE NULL END) STORED` : ""; l.push(`CREATE TABLE ${n} (id TEXT PRIMARY KEY REFERENCES ${r}(${a}) ON UPDATE CASCADE ON DELETE CASCADE, embedding ${o}.vector(${e.dimensions}) NOT NULL${u}); CREATE FUNCTION ${pgSearchName(`${t.table}_sync`)}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF TG_OP = 'UPDATE' AND OLD.${s} IS NOT DISTINCT FROM NEW.${s} THEN RETURN NEW; END IF; IF octet_length(NEW.${s}) > 0 THEN INSERT INTO ${n}(id, embedding) VALUES (NEW.${a}, openclaw_vector(NEW.${s}, ${e.dimensions})) ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding; ELSE DELETE FROM ${n} WHERE id = NEW.${a}; END IF; RETURN NEW; END $$; CREATE TRIGGER ${pgSearchName(`${t.table}_sync`)} AFTER INSERT OR UPDATE OF ${s} ON ${r} FOR EACH ROW EXECUTE FUNCTION ${pgSearchName(`${t.table}_sync`)}(); ${c};`); } return l.join("\n"); } //#endregion //#region src/infra/database-engine/postgres-schema.ts function postgresStoreNamespace(e, t, n) { return `${e}_${t}_${n.replaceAll("-", "").slice(0, 16)}`; } const postgresSchemaMetadataSql = `CREATE TABLE openclaw_schema_meta ( store TEXT PRIMARY KEY, version BIGINT NOT NULL, store_id TEXT NOT NULL, fingerprint TEXT, ddl_hash TEXT, server_major BIGINT)`; const recovery$1 = "Use a compatible OpenClaw binary or restore the matching PostgreSQL schema and anchor; do not edit schema metadata."; const canonicalNamespace = "openclaw_schema"; const quote = (e) => `"${e.replaceAll("\"", "\"\"")}"`; const hash$1 = (e) => createHash("sha256").update(e).digest("hex"); const capabilities = /* @__PURE__ */ new WeakMap(); const admittedSchemaKey = { name: "database.postgres.schema", schemaDependent: true }; const getAdmittedPostgresSchema = (e) => getSqliteDatabaseAdmission(e, admittedSchemaKey); const retainPostgresSchema = (e, t) => { const { postgresMigrations: n, ...r } = t; publishSqliteDatabaseAdmission(e, admittedSchemaKey, r); }; function admitPostgresCapabilities(e) { const t = capabilities.get(e); if (t) return t; const n = e.prepare("SELECT current_setting('server_version_num')::int AS version, current_setting('server_encoding') AS server_encoding, current_setting('client_encoding') AS client_encoding").get(); if (!n || typeof n.version !== "number" || n.version < 16e4 || n.server_encoding !== "UTF8" || n.client_encoding !== "UTF8") throw new Error("PostgreSQL requires version 16 or newer and UTF8 server/client encoding; upgrade the server or port to a UTF8 database and set client_encoding=UTF8."); const r = { serverMajor: Math.floor(n.version / 1e4), serverEncoding: "UTF8", clientEncoding: "UTF8" }; capabilities.set(e, r); return r; } function readPostgresSchema(e, t, n) { const r = e.query(`WITH captured AS (${postgresCatalogQuery(t, true)}) SELECT catalog::text, to_jsonb(meta)::text AS metadata FROM captured CROSS JOIN ${quote(t)}.openclaw_schema_meta meta WHERE meta.store = ?`, [n]).rows[0]; if (!r || typeof r.catalog !== "string" || typeof r.metadata !== "string") throw new Error(`Missing PostgreSQL catalog or metadata. ${recovery$1}`); const i = JSON.parse(r.metadata); return { catalog: readPostgresCatalog(JSON.parse(r.catalog)), metadata: i }; } function withPostgresSearchExtensions(e, t) { return { ...e, searchExtensions: JSON.parse(t.metadata.search_extensions ?? "{}") }; } function postgresSchemaFingerprint(e, t) { const n = e.filter((e) => e.table !== "openclaw_schema_meta").map((e) => JSON.stringify(e)).toSorted().join("\n"); if (!t) return hash$1(n); const r = JSON.stringify(t.from).slice(1, -1); const i = JSON.stringify(quote(t.from)).slice(1, -1); const a = JSON.stringify(t.to).slice(1, -1); return hash$1(n.replaceAll(`${i}.`, `${r}.`).replaceAll(r, a)); } function postgresSchemaSql(e, t, n) { const r = new Set(n?.filter((e) => e.kind === "table").map((e) => e.table)); const i = e.postgresFragments?.filter((e) => n ? e.tables.some((e) => r.has(e)) : e.activation === "version-additive") ?? []; const a = /* @__PURE__ */ new Map(); const add = (t) => { if (a.has(t.id)) return; for (const n of t.dependencies) { const t = e.postgresFragments?.find((e) => e.id === n); if (!t) throw new Error(`Missing PostgreSQL fragment dependency ${n}`); add(t); } a.set(t.id, t.sql); }; i.forEach(add); const o = [e.search, ...Object.values(e.searchExtensions ?? {})].filter((e) => e !== void 0); const s = { text: false, vector: false }; const c = o.map((n) => { const r = postgresSearchSql(n, t, s, e.postgresVectorDecoderVersion, e.postgresVectorSearchVersion, e.postgresTextSearchVersion); s.text ||= Object.keys(n.text ?? {}).length > 0; s.vector ||= n.mode !== "keyword-only" && Object.keys(n.vector ?? {}).length > 0; return `;\n${r}`; }); return [ e.postgres ?? "", ...a.values(), ...c ].join("\n"); } function recordPostgresSchema(e, t, n, r) { if (!e.isTransaction) throw new Error("PostgreSQL schema publication requires the owner's writer transaction"); const i = r ?? readPostgresSchema(e, t, n.id); e.prepare("UPDATE openclaw_schema_meta SET fingerprint = ?, ddl_hash = ?, server_major = ? WHERE store = ?").run(postgresSchemaFingerprint(i.catalog), hash$1(postgresSchemaSql(n, canonicalNamespace, i.catalog)), admitPostgresCapabilities(e).serverMajor, n.id); } /** Rare upgrade/unsealed-pilot path: PostgreSQL deparses both sides on this server. */ function verifyPostgresSchema(e, t, n, r, i = false) { const a = postgresSchemaFingerprint(r.catalog); const o = postgresSchemaSql(n, canonicalNamespace, r.catalog); const { metadata: s } = r; const c = admitPostgresCapabilities(e).serverMajor; if (s.server_major === c && s.fingerprint && s.fingerprint !== a) throw new Error(`PostgreSQL schema drift detected. ${recovery$1}`); if (s.server_major === c && s.fingerprint && s.ddl_hash === hash$1(o)) return; if (i) e.runTransaction(() => verifyPostgresSchemaDefinition(e, t, n, r)); else verifyAndRecordPostgresSchema(e, t, n, r); } function verifyPostgresSchemaDefinition(e, t, n, r) { const i = postgresSchemaFingerprint(r.catalog, { from: t, to: t }); const a = `openclaw_check_${randomUUID().replaceAll("-", "")}`; e.exec(`CREATE SCHEMA ${quote(a)}`); try { e.exec(`SET LOCAL search_path TO ${quote(a)}`); e.exec(postgresSchemaSql(n, a, r.catalog)); const o = e.query(`SELECT catalog::text FROM (${postgresCatalogQuery(a, true)}) captured`).rows[0]; if (postgresSchemaFingerprint(readPostgresCatalog(JSON.parse(String(o?.catalog))), { from: a, to: t }) !== i) throw new Error(`PostgreSQL schema drift detected against generated DDL. ${recovery$1}`); } finally { e.exec(`SET LOCAL search_path TO ${quote(t)}`); e.exec(`DROP SCHEMA ${quote(a)} CASCADE`); } } /** Migrations and major upgrades validate the destination before publishing its seal. */ function verifyAndRecordPostgresSchema(e, t, n, r = readPostgresSchema(e, t, n.id)) { e.runTransaction(() => { verifyPostgresSchemaDefinition(e, t, n, r); if (!r.metadata.ddl_hash) e.exec("ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS fingerprint TEXT, ADD COLUMN IF NOT EXISTS ddl_hash TEXT, ADD COLUMN IF NOT EXISTS server_major BIGINT"); recordPostgresSchema(e, t, n, r); }); return r; } //#endregion //#region src/infra/database-engine/physical-facts.ts const recovery = "Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor."; function getPostgresPhysicalFacts(e, t) { return getSqliteDatabaseAdmission(e, postgresPhysicalFactsKey, t); } /** Retain PostgreSQL admission facts on its admitted connection. */ function admitPostgresPhysicalFacts(e) { const t = getPostgresPhysicalFacts(e.db); if (t) return t; const n = admitPostgresCapabilities(e.db); let r; try { r = readPostgresSchema(e.db, e.namespace, e.store); } catch (e) { throw new Error(`Cannot read PostgreSQL catalog or metadata. ${recovery}`, { cause: e }); } const { metadata: i, catalog: a } = r; if (i.version !== e.version || i.store_id !== e.storeId) throw new Error(`PostgreSQL metadata identity or version mismatch. ${recovery}`); if (e.schema) { const t = withPostgresSearchExtensions(e.schema, r); if (e.recordSchema) recordPostgresSchema(e.db, e.namespace, t, r); else verifyPostgresSchema(e.db, e.namespace, t, r, e.preserveSchemaSeal); retainPostgresSchema(e.db, t); } const o = { engine: "postgres", admissionId: randomUUID(), store: e.store, namespace: e.namespace, storeId: i.store_id, version: i.version, capabilities: n, catalog: a }; publishSqliteDatabaseAdmission(e.db, postgresPhysicalFactsKey, o); return o; } function requireNativeDatabaseFile(e, t) { if (e === "postgres") throw new Error(`PostgreSQL cannot use SQLite ${t}; stop the Gateway and back up/restore the PostgreSQL schema with its matching anchor (P3-6 export support pending).`); } //#endregion //#region src/infra/sqlite-pinned-read-snapshot.ts const snapshots = resolveGlobalSingleton(Symbol.for("openclaw.sqlitePinnedReadSnapshots"), () => /* @__PURE__ */ new WeakMap()); function getSqlitePinnedReadSnapshot(e) { return snapshots.get(e); } /** First schema admission consumes the same cookie that pins its catalog capture. */ function runSqliteSchemaReadSnapshotSync(e, t) { const n = snapshots.get(e); for (let r = 0;; r += 1) { snapshots.set(e, n ?? {}); try { const n = executeWithCachedStatement(e, "PRAGMA schema_version", [], (e) => { let n; try { let i; try { n = e.iterate(); i = n.next(); } catch (e) { if (!isMainThread && r < 4 && (sqliteExtendedResultCode(e) === 261 || sqliteErrorCode(e) === "SQLITE_BUSY_RECOVERY")) return { retry: true }; throw e; } if (i.done) throw new Error("SQLite schema_version query returned no row"); return { retry: false, value: t(Number(i.value.schema_version)) }; } finally { n?.return?.(); } }); if (!n.retry) return n.value; } finally { if (!n) snapshots.delete(e); } } } //#endregion //#region src/infra/sqlite-schema-admission.ts const schemaAdmission = { name: "sqlite-schema", writer: "connection", lifetime: "process", schemaDependent: true, read: (e) => { return isRecord(e) ? e : void 0; } }; const textEncodingAdmission = { name: "sqlite-text-encoding", writer: "connection", lifetime: "process", read: (e) => typeof e === "string" ? e : void 0 }; /** Native metadata read shared by admission and pre-admission migrations. */ function readSqliteTextEncoding(e) { const t = getSqliteDatabaseAdmission(e, textEncodingAdmission); if (t !== void 0) return t; const n = executeWithCachedStatement(e, "PRAGMA encoding", [], (e) => e.get()); if (typeof n?.encoding !== "string") throw new Error("SQLite did not report its text encoding"); return n.encoding; } /** Native catalog projection shared by admission and maintenance. */ function readSqliteSchemaObjects(e) { return executeWithCachedStatement(e, "SELECT type, name, tbl_name, sql FROM main.sqlite_schema WHERE type IN ('table', 'view', 'index', 'trigger')", [], (e) => e.all()); } /** Capture the physical catalog for admission or pre-admission schema maintenance. */ function captureSqliteSchemaFacts(e, t = 0, n) { const r = getSqliteDatabaseAdmission(e, textEncodingAdmission); const i = runSqliteSchemaReadSnapshotSync(e, (i) => { const a = executeWithCachedStatement(e, "PRAGMA user_version", [], (e) => e.get()); const o = Number(a?.user_version ?? 0); n?.(o); const s = r ?? readSqliteTextEncoding(e); const c = readSqliteSchemaObjects(e); const l = { admissionId: randomUUID(), revision: t, userVersion: o, textEncoding: s, schemaVersion: i, tables: /* @__PURE__ */ new Set(), views: /* @__PURE__ */ new Set(), tableSql: /* @__PURE__ */ new Map(), indexes: /* @__PURE__ */ new Set(), indexDefinitions: /* @__PURE__ */ new Map(), triggers: /* @__PURE__ */ new Map() }; for (const e of c) { if (typeof e.name !== "string") continue; const t = typeof e.sql === "string" ? e.sql : null; switch (e.type) { case "table": l.tables.add(e.name); l.tableSql.set(e.name, t); break; case "view": l.views.add(e.name); break; case "index": l.indexes.add(e.name); if (typeof e.tbl_name === "string") l.indexDefinitions.set(e.name, { table: e.tbl_name, sql: t }); break; case "trigger": if (typeof e.tbl_name === "string") l.triggers.set(e.name, { table: e.tbl_name, sql: t }); } } return l; }); if (r === void 0 && (i.tables.size > 0 || i.views.size > 0)) publishSqliteDatabaseAdmission(e, textEncodingAdmission, i.textEncoding); return i; } function captureTrackedSqliteSchemaFacts(e, t, n) { t.capturing = true; try { return captureSqliteSchemaFacts(e, t.revision, n); } finally { t.capturing = false; } } function invalidateTrackedSqliteSchemaFacts(e) { e.revision += 1; e.facts = void 0; } //#endregion //#region src/infra/sqlite-schema-lifetime.ts function observeSchemaLifetime(e, t, n) { if (t.snapshot && t.snapshot !== n) { if (!e.isTransaction || !t.transactionCatalogBound) invalidateTrackedSqliteSchemaFacts(t); t.snapshot = void 0; t.qualifiedSnapshot = void 0; } const r = getSqliteDatabaseSchemaRevision(e); const i = t.processRevision !== void 0 && t.processRevision !== r; if (i && !t.transactionalSchema && (e.isTransaction && t.transactionCatalogBound || t.facts && n && t.qualifiedSnapshot === n)) { t.transactionalFacts ||= e.isTransaction; t.snapshot = n; return false; } t.processRevision = r; if (i) invalidateTrackedSqliteSchemaFacts(t); if ((t.transactionalSchema || t.transactionalTempSchema || t.transactionalFacts) && !e.isTransaction) { if (t.transactionalSchema) publishSqliteDatabaseSchemaChange(e); invalidateTrackedSqliteSchemaFacts(t); t.transactionalSchema = false; t.transactionalTempSchema = false; t.transactionalFacts = false; } return i; } //#endregion //#region src/infra/sqlite-temp-generation-schema.ts function prepareSqliteTempTrackingSchema(e, t) { const { createSql: n, objects: r } = prepareTranscriptIndexSchema(t); const i = new Map(r.map((e) => [e.name.toLowerCase(), e])); const a = r.map((e) => e.name); const o = r.filter((e) => e.type === "table").map((e) => e.name); const s = [...a, ...o]; const c = executeWithCachedStatement(e, `SELECT type, name, tbl_name, sql FROM temp.sqlite_schema WHERE name COLLATE NOCASE IN (${a.map(() => "?").join(",")}) OR (type = 'trigger' AND tbl_name COLLATE NOCASE IN (${o.map(() => "?").join(",")}))`, s, (e) => e.all(...s)); const l = c.some((e) => { const t = typeof e.name === "string" ? i.get(e.name.toLowerCase()) : void 0; return !t || e.type !== t.type || e.tbl_name !== t.table || typeof e.sql !== "string" || normalizeSchemaSql(e.sql) !== normalizeSchemaSql(t.sql); }); return { sql: n(new Set(c.flatMap((e) => e.type === "trigger" && typeof e.name === "string" ? [e.name.toLowerCase()] : []))), unexpected: l }; } function prepareTranscriptIndexSchema(e) { const t = quoteSqliteIdentifier(e.statusTable); const n = quoteSqliteIdentifier(e.pendingTable); const r = quoteSqliteIdentifier(e.pendingIndex); const i = `${t} ( id INTEGER PRIMARY KEY CHECK (id = 1), sibling_write_revision INTEGER NOT NULL, schema_version INTEGER NOT NULL, complete INTEGER NOT NULL, after_session TEXT, completed_traversals INTEGER NOT NULL ) STRICT`; const a = `${n} (session_id TEXT PRIMARY KEY, state INTEGER NOT NULL) STRICT`; const o = `${r} ON ${n}(state, session_id)`; const s = e.observedTables.flatMap((e) => [ "INSERT", "UPDATE", "DELETE" ].map((t) => { const r = `openclaw_${e}_projection_${t.toLowerCase()}`; const i = t === "UPDATE" ? ["OLD", "NEW"] : [t === "DELETE" ? "OLD" : "NEW"]; return { name: r, table: e, definition: `TRIGGER ${quoteSqliteIdentifier(r)} AFTER ${t} ON main.${quoteSqliteIdentifier(e)} WHEN ${i.map((e) => `NOT EXISTS ( SELECT 1 FROM ${n} WHERE session_id = ${e}.session_id AND state = 0 )`).join(" OR ")} BEGIN ${i.map((e) => ` UPDATE ${n} SET state = 0 WHERE session_id = ${e}.session_id; INSERT INTO ${n} SELECT ${e}.session_id, 0 WHERE NOT EXISTS ( SELECT 1 FROM ${n} WHERE session_id = ${e}.session_id );`).join("\n")} END` }; })); const createSql = (e) => ` CREATE TEMP TABLE IF NOT EXISTS ${i}; INSERT INTO temp.${t} VALUES (1, -1, -1, 0, NULL, 0) ON CONFLICT(id) DO UPDATE SET sibling_write_revision = -1; CREATE TEMP TABLE IF NOT EXISTS ${a}; CREATE INDEX IF NOT EXISTS temp.${o}; ${s.map(({ name: t, definition: n }) => { return `${e.has(t.toLowerCase()) ? `DROP TRIGGER IF EXISTS temp.${quoteSqliteIdentifier(t)};` : ""}CREATE TEMP ${n};`; }).join("\n")} `; return { createSql, objects: [ { name: e.statusTable, type: "table", table: e.statusTable, sql: `CREATE TABLE ${i}` }, { name: e.pendingTable, type: "table", table: e.pendingTable, sql: `CREATE TABLE ${a}` }, { name: e.pendingIndex, type: "index", table: e.pendingTable, sql: `CREATE INDEX ${o}` }, ...s.map((e) => ({ name: e.name, type: "trigger", table: e.table, sql: `CREATE ${e.definition}` })) ] }; } //#endregion //#region src/infra/sqlite-schema-facts.ts const postgresReadSnapshots = resolveGlobalSingleton(Symbol.for("openclaw.postgresReadSnapshots"), () => /* @__PURE__ */ new WeakMap()); /** The transaction owner supplies one admitted lifetime immediately after read-only BEGIN. */ function beginPostgresReadSnapshotScope(e) { const t = getPostgresPhysicalFacts(e); const n = readSqliteDatabaseWriteRevision(e); if (t && n !== void 0) postgresReadSnapshots.set(e, { schema: t, writeRevision: n, mutationRevision: e.mutationRevision, snapshot: {} }); return () => postgresReadSnapshots.delete(e); } /** Schema publications outside DDL (such as a deferred version marker) share this revision. */ function invalidateSqliteSchemaFacts(e) { getSqliteDatabaseSchemaRevision(e); invalidateSchemaFacts(e, true); } function invalidateSchemaFacts(e, t, n = "main", r = n !== "temp") { const i = sqliteSchemaOwners.get(e); if (i) { const a = n === "main"; i.isolatedTempTables.clear(); if (e.isTransaction) i.transactionMutationRevision = void 0; if (a) invalidateLocalSqliteSchemaAdmissions(e); if (a && e.isTransaction && !i.transactionalSchema) i.transactionBaseFacts = i.facts; if (r) for (const e of i.mutationListeners ?? []) e(void 0); invalidateTrackedSqliteSchemaFacts(i); i.transactionalSchema ||= a && e.isTransaction; i.transactionalTempSchema ||= n === "temp" && e.isTransaction; i.pendingSchema ||= a && i.nativeDepth > 0; if (t && a && !e.isTransaction && i.nativeDepth === 0) publishSqliteDatabaseSchemaChange(e); } } /** MAIN mutations and rollback revoke before execution; TEMP DDL only revokes local facts. */ function registerSqliteSchemaMutationListener(e, t) { const n = sqliteSchemaOwners.get(e); if (!n) throw new Error("SQLite schema observation requires a tracked connection"); const r = n.mutationListeners ??= /* @__PURE__ */ new Set(); r.add(t); return () => r.delete(t); } function trackSchemaChanges(e, t, n, r) { const settle = (n = false, r = false) => { if (r) { const n = getSqlitePinnedReadSnapshot(e); const r = n && (t.transactionalSchema ? t.transactionBaseFacts : t.facts); discardSqliteDatabaseTransactionAdmissions(e); invalidateTrackedSqliteSchemaFacts(t); t.transactionalSchema = false; t.transactionalTempSchema = false; t.transactionalFacts = false; if (n && t.admitted && !t.authorizerActive) { t.facts = r ? { ...r, revision: t.revision } : captureTrackedSqliteSchemaFacts(e, t); t.snapshot = n; t.qualifiedSnapshot = n; } t.transactionBaseFacts = void 0; return; } if ((n || !e.isTransaction) && (t.transactionalSchema || t.transactionalTempSchema || t.transactionalFacts)) { if (t.transactionalSchema) publishSqliteDatabaseSchemaChange(e); invalidateTrackedSqliteSchemaFacts(t); t.transactionalSchema &&= e.isTransaction; t.transactionalTempSchema &&= e.isTransaction; t.transactionalFacts = false; } }; const i = observeSqliteNativeOperations(e, n, (n, i) => { if (t.settling) return { finish: () => {} }; const { control: a, dataChange: o } = n; const s = a?.outerRollback === true ? false : n.schemaChange; const c = n.mainSchemaChange && a?.outerRollback !== true; observeSqliteTransactionState(e, t); const l = i === "bind" ? void 0 : getSqlitePinnedReadSnapshot(e); const u = i !== "bind" && !l && !t.capturing ? {} : void 0; if (l && l !== t.snapshot && !t.capturing) { if (e.isTransaction && (t.transactionRead || t.transactionCatalogBound) && t.processRevision !== getSqliteDatabaseSchemaRevision(e)) { if (!t.transactionCatalogBound) invalidateTrackedSqliteSchemaFacts(t); t.transactionalFacts = true; } else { observeSchemaLifetime(e, t, void 0); if (!t.facts && !t.transactionalSchema) { const n = getSqliteDatabaseAdmission(e, schemaAdmission); if (n) t.facts = { ...n, revision: t.revision }; } } t.snapshot = l; t.qualifiedSnapshot = l; } if (t.nativeDepth === 0) settle(); const d = e.isTransaction; if ((r || t.processRevision === void 0) && !d && (a?.kind === "BEGIN" || a?.kind === "SAVEPOINT")) { const n = getSqliteDatabaseSchemaRevision(e); t.processRevision ??= n; } const f = !d && a?.kind === "BEGIN" && a.single ? t.mutationRevision : void 0; if (!d && a?.kind === "BEGIN" && t.admitted) getAdmittedSqliteSchemaFacts(e); const p = Boolean(a) && !canPreserveTransactionSnapshot(a, d); const m = a?.kind === "ROLLBACK"; const h = m && t.transactionalSchema && !a.outerRollback; const g = s && !n.temporaryTableSchemaChange || m && t.transactionalSchema; const _ = c || h ? "main" : m ? t.transactionalTempSchema && !t.transactionalSchema ? "temp" : "rollback" : n.temporaryTableSchemaChange ? "temp" : "local"; if (m) discardSqliteDatabaseTransactionAdmissions(e); if (s || m) invalidateSchemaFacts(e, false, _, g); if (o || n.temporaryTableSchemaChange || a?.kind === "ROLLBACK") t.mutationRevision += 1; if (i !== "bind" && d && !a && !t.transactionCatalogBound) t.transactionRead = true; const v = s || o || a !== void 0; const y = n.temporaryWriteTables?.every((e) => t.isolatedTempTables.has(e)); if (o && !y || c) beginSqliteDatabaseWrite(e, c || t.nativeDepth > 0); if (v) t.mutationDepth += 1; t.nativeDepth += 1; const b = beginSqliteDatabaseAdmissionOperation(e); const x = t.schemaMutationRevision; if (c) t.schemaMutationRevision += 1; t.pendingSchema ||= c; if (u) t.unmanagedSnapshots.add(u); return { stepped: () => { if (l && t.facts && e.isTransaction) t.transactionCatalogBound = true; }, finish: (n, r, i) => { if (u && t.unmanagedSnapshots.delete(u) && t.iteratorFacts) { invalidateTrackedSqliteSchemaFacts(t); t.iteratorFacts = false; } b(); t.nativeDepth -= 1; if (v) t.mutationDepth -= 1; if (!e.isOpen) return; if (s || m) { if (m) discardSqliteDatabaseTransactionAdmissions(e); invalidateSchemaFacts(e, false, _, g); } const o = n && d && a?.outerRollback === true && !e.isTransaction && !c && t.schemaMutationRevision === x; if (o) { settle(false, true); t.pendingSchema = false; } if (t.nativeDepth === 0) { t.settling = true; try { const i = t.pendingSchema || t.transactionalSchema; if (!o && t.pendingSchema && !e.isTransaction && !t.transactionalSchema) publishSqliteDatabaseSchemaChange(e); if (!o) settle(p); if (i && !e.isTransaction && !o) { invalidateTrackedSqliteSchemaFacts(t); if (!n) discardSqliteDatabaseTransactionAdmissions(e); if (t.admitted && !t.authorizerActive && !r) { getAdmittedSqliteSchemaFacts(e); t.transactionBaseFacts = void 0; } } t.pendingSchema = false; } finally { t.settling = false; } } finishSqliteReadScope(e, t, d, p, n, f); if (t.mutationDepth === 0 && !e.isTransaction) finishSqliteDatabaseWrite(e, i); t.transactionRead ||= e.isTransaction && Boolean(a && !a.single); } }; }); observeSqliteNativeClose(e, () => { finishSqliteDatabaseWrite(e); releaseSqliteDatabaseAdmission(e); }); t.installTempTrackingSchema = (r) => { const { sql: a, unexpected: o } = prepareSqliteTempTrackingSchema(e, r); try { i(() => n.DatabaseSync.prototype.exec.call(e, a), { schemaChange: o, mainSchemaChange: o, temporaryTableSchemaChange: false, dataChange: true, temporaryWriteTables: [], control: void 0 }); if (!o) for (const e of [r.statusTable, r.pendingTable]) t.isolatedTempTables.add(e.toLowerCase()); } catch (t) { invalidateSqliteSchemaFacts(e); throw t; } }; if (typeof e.setAuthorizer === "function") e.setAuthorizer = (r) => { n.DatabaseSync.prototype.setAuthorizer.call(e, r); t.authorizerActive = r !== null; suspendSqliteDatabaseAdmission(e, t.authorizerActive); invalidateTrackedSqliteSchemaFacts(t); }; registerNodeSqliteDisposeCallback(e, () => { invalidateTrackedSqliteSchemaFacts(t); t.readRevision = void 0; t.transactionSnapshot = void 0; }); } /** Local mutation witness; committed sibling writes use the physical admission revision. */ function readSqliteNativeMutationRevision(e) { return isPostgresSqlConnection(e) ? e.mutationRevision : sqliteSchemaOwners.get(e)?.mutationRevision; } /** Reuse row facts only inside an admitted synchronous operation. */ function runSqliteReadOperationSync(e, t) { if (isPostgresSqlConnection(e)) return t(); const n = sqliteSchemaOwners.get(e); if (!n || n.authorizerActive) return t(); n.readDepth += 1; try { if (n.admitted) getAdmittedSqliteSchemaFacts(e); return t(); } finally { n.readDepth -= 1; } } /** Install at native open, before callers can retain statements or install an authorizer. */ function trackSqliteSchema(e, t, n = true) { if (!sqliteSchemaOwners.has(e)) { const r = { admitted: false, publicationReady: false, revision: 0, readDepth: 0, mutationRevision: 0, mutationDepth: 0, transactionOpen: e.isOpen && e.isTransaction, transactionRead: false, transactionCatalogBound: false, nativeDepth: 0, pendingSchema: false, schemaMutationRevision: 0, settling: false, capturing: false, transactionalSchema: false, transactionalTempSchema: false, transactionalFacts: false, authorizerActive: false, unmanagedSnapshots: /* @__PURE__ */ new Set(), isolatedTempTables: /* @__PURE__ */ new Set(), iteratorFacts: false }; sqliteSchemaOwners.set(e, r); trackSchemaChanges(e, r, t, n); const i = getSqliteDatabaseSchemaRevision(e, { existingOnly: true }); const a = getSqliteDatabaseAdmission(e, schemaAdmission, { existingOnly: true }); if (a) { r.admitted = true; r.facts = { ...a, revision: r.revision }; r.processRevision = i; } } } /** Select first ordinary admission without querying or authorizing a connection. */ function isSqliteSchemaAdmissionCold(e) { const t = sqliteSchemaOwners.get(e); return Boolean(t && !t.admitted && !t.authorizerActive); } /** Admission retains schema facts; its header validator must stay synchronous and read-free. */ function admitSqliteSchema(e, t) { const n = sqliteSchemaOwners.get(e); if (!n) throw new Error("SQLite schema admission requires a connection tracked from native open"); n.admitted = true; const r = getAdmittedSqliteSchemaFacts(e, t); if (!n.publicationReady && r && n.unmanagedSnapshots.size === 0 && !getSqlitePinnedReadSnapshot(e)) n.publicationReady = settleSqliteDatabaseAdmissionPublication(e); } /** Consume the physical database's admitted facts and owner-published schema changes. */ function getAdmittedSqliteSchemaFacts(e, t) { if (isPostgresSqlConnection(e)) return; const n = sqliteSchemaOwners.get(e); if (!n?.admitted || n.authorizerActive) return; const r = getSqlitePinnedReadSnapshot(e); const i = e.isTransaction && (n.transactionRead || n.transactionCatalogBound) && n.processRevision !== getSqliteDatabaseSchemaRevision(e) || n.unmanagedSnapshots.size > 0; const a = observeSchemaLifetime(e, n, r); if (!n.facts) { n.snapshot = r; n.transactionalFacts ||= e.isTransaction && (n.readDepth === 0 || a); const o = i || Boolean(r) || n.transactionalSchema; const s = n.transactionalSchema || o ? void 0 : getSqliteDatabaseAdmission(e, schemaAdmission); if (s) { t?.(s.userVersion); n.facts = { ...s, revision: n.revision }; return n.facts; } const c = getSqliteDatabaseSchemaRevision(e); n.facts = captureTrackedSqliteSchemaFacts(e, n, t); n.iteratorFacts ||= n.unmanagedSnapshots.size > 0; n.qualifiedSnapshot = r; n.transactionCatalogBound ||= e.isTransaction; if (!o) publishSqliteDatabaseAdmission(e, schemaAdmission, n.facts, { schemaRevision: c }); } else t?.(n.facts.userVersion); return n.facts; } //#endregion export { readPostgresSchema as C, admitPostgresSearch as D, withPostgresSearchExtensions as E, assertPostgresCatalog as O, postgresStoreNamespace as S, verifyPostgresSchema as T, requireNativeDatabaseFile as _, isSqliteSchemaAdmissionCold as a, postgresSchemaMetadataSql as b, runSqliteReadOperationSync as c, readSqliteSchemaObjects as d, schemaAdmission as f, getPostgresPhysicalFacts as g, admitPostgresPhysicalFacts as h, invalidateSqliteSchemaFacts as i, trackSqliteSchema as l, runSqliteSchemaReadSnapshotSync as m, beginPostgresReadSnapshotScope as n, readSqliteNativeMutationRevision as o, getSqlitePinnedReadSnapshot as p, getAdmittedSqliteSchemaFacts as r, registerSqliteSchemaMutationListener as s, admitSqliteSchema as t, captureSqliteSchemaFacts as u, admitPostgresCapabilities as v, verifyAndRecordPostgresSchema as w, postgresSchemaSql as x, getAdmittedPostgresSchema as y };