{"version":3,"sources":["../src/backend/types.ts","../src/query/compiler/schema.ts","../src/utils/sql-errors.ts","../src/backend/capabilities/bundle-registry.ts","../src/backend/capabilities/bind.ts","../src/backend/capabilities/recursive-traversal.ts","../src/backend/capabilities/write-fence.ts","../src/backend/command-contract.ts","../src/backend/capabilities/execution.ts","../src/backend/capabilities/schema-fenced-insert.ts","../src/backend/graph-backend-keys.ts","../src/backend/transaction-resource.ts","../src/backend/derive-backend.ts"],"names":["typeGraphGlobalSymbol","ConfigurationError","MAX_PG_IDENTIFIER_LENGTH","isSqlFragment","sql","CompilerInvariantError","parseRecordedInstant","createDataKeyedBag","requiredAdvisoryLockExpression","requireDefined","requiredIsolationFactExpression","accepted","descriptor"],"mappings":";;;;;;;;;AAigBO,SAAS,oCACd,YAAA,EACqB;AACrB,EAAA,IACE,YAAA,CAAa,cAAA,EAAgB,SAAA,KAAc,IAAA,IAC1C,YAAA,CAAa,SAAA,CAAU,uBAAA,IACtB,YAAA,CAAa,eAAA,IACb,YAAA,CAAa,SAAA,KAAc,KAAA,EAC7B;AACA,IAAA,OAAO,YAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,GAAG,YAAA;AAAA,IACH,gBAAgB,EAAE,GAAG,YAAA,CAAa,cAAA,EAAgB,WAAW,KAAA;AAAM,GACrE;AACF;AAMO,SAAS,gCACd,qBAAA,EAES;AACT,EAAA,OAAO,kBAAkB,qBAAA,GACrB,qBAAA,CAAsB,aAAa,SAAA,CAAU,uBAAA,GAC7C,sBAAsB,SAAA,CAAU,uBAAA;AACtC;AAGO,SAAS,wBACd,qBAAA,EAES;AACT,EAAA,MAAM,YAAA,GACJ,cAAA,IAAkB,qBAAA,GAChB,qBAAA,CAAsB,YAAA,GACtB,qBAAA;AACJ,EAAA,OAAO,YAAA,CAAa,UAAU,WAAA,KAAgB,MAAA;AAChD;AAGO,SAAS,oBACd,qBAAA,EAES;AACT,EAAA,MAAM,YAAA,GACJ,cAAA,IAAkB,qBAAA,GAChB,q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AS,YAAY,CAAA;AAC5C","file":"chunk-6JRVV2SS.cjs","sourcesContent":["/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport {\n  type Cardinality,\n  type IndexEntity,\n  type JsonScalar,\n  type JsonValue,\n  type KindEntity,\n  type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport {\n  type VectorSlot,\n  type VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\nimport { type SqlFragment } from \"../query/sql-fragment\";\nimport {\n  type CompiledRowsSql,\n  type CompiledSelectSql,\n  type CompiledStatementSql,\n  type CompiledTemporaryStatementSql,\n} from \"../query/sql-intent\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * The mechanism a strategy uses to combine a row filter with an *approximate*\n * (ANN) vector search.\n *\n * Every approximate search TypeGraph issues carries at least one filter: the\n * liveness predicate that excludes soft-deleted and out-of-validity rows. Add\n * a `.where(...)` predicate and it narrows further. Engines differ in where\n * they apply it relative to the index traversal:\n *\n * - `\"filter-pushdown\"` — the filter constrains the ANN candidate set itself.\n *   sqlite-vec's `vec0` KNN accepts primary-key `IN (SELECT …)` pushdown.\n * - `\"iterative-scan\"` — the engine re-enters the index, gathering more\n *   candidates until `LIMIT` rows survive the filter *or* it hits its own scan\n *   bound. pgvector >= 0.8 (`hnsw.iterative_scan` / `ivfflat.iterative_scan`,\n *   applied automatically by the backend).\n * - `\"post-filter\"` — the engine retrieves a fixed multiple of the page from\n *   the ANN index and applies the filter afterwards. libSQL's DiskANN\n *   `vector_top_k` is a table function with no filter pushdown, so this is the\n *   only shape available to it.\n *\n * This names what the strategy *asks the engine to do*. Whether the engine can\n * honor it — and whether honoring it is enough to fill a page — is\n * {@link FilteredApproximateSearch.guaranteesFullPage}.\n */\nexport type FilteredApproximateSearchMode =\n  \"filter-pushdown\" | \"iterative-scan\" | \"post-filter\";\n\n/**\n * How a filtered approximate (ANN) vector search behaves, and whether it can\n * silently return fewer rows than `limit` while more matches exist.\n *\n * Read `guaranteesFullPage` — not `mode` — to decide whether a short page is\n * possible. Only `\"filter-pushdown\"` guarantees a full page:\n *\n * - **sqlite-vec** pushes the filter into the KNN. Exact.\n * - **pgvector** re-enters the index, but the iterative scan stops at\n *   `hnsw.max_scan_tuples` / `ivfflat.max_probes`, and on **pgvector < 0.8**\n *   there is no iterative scan at all — the backend detects that at runtime,\n *   warns once, and the search stays `ef_search`-bounded, behaving like\n *   `\"post-filter\"`. Neither case is visible in a statically-declared `mode`,\n *   which is exactly why the guarantee is a separate field.\n * - **libSQL** over-fetches a fixed multiple of the page and filters\n *   afterwards, so it under-fills once more than that headroom is filtered out.\n *\n * A store with heavy tombstone drift — routine in a temporal store — is what\n * turns a short page from a theoretical caveat into an observed one. Exact\n * (`approximate: false`) searches are unaffected on every engine: they scan, so\n * the filter reaches every row.\n */\nexport type FilteredApproximateSearch = Readonly<{\n  mode: FilteredApproximateSearchMode;\n  /**\n   * `true` only when a filtered approximate search is guaranteed to return\n   * `limit` rows whenever `limit` matching rows exist — no engine-side scan\n   * bound, no version dependence, no over-fetch headroom to exhaust.\n   */\n  guaranteesFullPage: boolean;\n}>;\n\n/**\n * Whether an engine exposes a PER-SEARCH knob for the ANN candidate frontier —\n * the parameter {@link VectorSearchParams.efSearch} maps onto.\n *\n * Declared, never inferred: `efSearch` is an accepted option, so a backend that\n * cannot apply it must refuse it rather than ignore it (AGENTS.md contract\n * discipline). This capability is what the shared refusal predicate reads, and\n * what a caller reads to know whether passing `efSearch` will be honored.\n *\n * - **pgvector**: `hnsw.ef_search`, applied per search with `SET LOCAL` inside\n *   the search's own transaction — hence `requiresTransactionScope`, since a\n *   session-wide `SET` would leak the override into concurrent searches.\n * - **sqlite-vec**: `tunable: false`. A vec0 KNN takes `k` and nothing else;\n *   there is no frontier to widen.\n * - **libSQL DiskANN**: `tunable: false`. `vector_top_k(idx, q, k)` is a table\n *   function with no per-query parameters; DiskANN's `search_l` is fixed at\n *   index-creation time.\n */\nexport type VectorSearchFrontierTuning =\n  | Readonly<{\n      tunable: true;\n      /** Engine-native parameter `efSearch` maps to (`\"hnsw.ef_search\"`). */\n      parameter: string;\n      /**\n       * The one index type whose search honors the parameter. `efSearch` on a\n       * slot of any other index type is refused, not ignored: an IVFFlat or\n       * brute-force slot would silently discard it.\n       */\n      indexType: VectorIndexType;\n      /**\n       * `true` when applying the parameter needs a transaction to scope it to\n       * the one search. A backend without interactive transactions refuses\n       * `efSearch` rather than leaking a session-wide setting.\n       */\n      requiresTransactionScope: boolean;\n    }>\n  | Readonly<{\n      tunable: false;\n      /**\n       * Why this engine has no per-search frontier knob — surfaced in the\n       * refusal's details so the state is named rather than implied.\n       */\n      reason: string;\n    }>;\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n  /** Whether the backend supports vector operations */\n  supported: boolean;\n  /** Supported similarity metrics */\n  metrics: readonly VectorMetric[];\n  /** Supported index types */\n  indexTypes: readonly VectorIndexType[];\n  /** Maximum dimensions supported */\n  maxDimensions: number;\n  /**\n   * How a filtered approximate search bounds recall — and whether it can\n   * silently return a short page. See {@link FilteredApproximateSearch}.\n   *\n   * Required, so a new vector strategy cannot omit the declaration and inherit\n   * an engine promise it does not keep.\n   */\n  filteredApproximateSearch: FilteredApproximateSearch;\n  /**\n   * Whether a per-search ANN frontier override (`efSearch`) can be applied.\n   * See {@link VectorSearchFrontierTuning}.\n   *\n   * Required, so a new vector strategy must state whether it honors the\n   * option instead of inheriting silence — the exact defect this closes.\n   */\n  searchFrontierTuning: VectorSearchFrontierTuning;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n *    Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n *    Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n *    Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n  /** Whether the backend supports fulltext operations */\n  supported: boolean;\n  /**\n   * Language / tokenizer names understood by this backend.\n   * Postgres: installed regconfigs (english, simple, ...).\n   * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n   */\n  languages: readonly string[];\n  /** Whether phrase queries are supported. */\n  phraseQueries: boolean;\n  /** Whether prefix (`foo*`) queries are supported. */\n  prefixQueries: boolean;\n  /** Whether highlighting / snippets are supported. */\n  highlighting: boolean;\n}>;\n\n/**\n * Whole-graph analytics capabilities declared by a backend.\n *\n * `supported` means the backend can pin one transactional connection while\n * an algorithm creates, updates, and drops session-local temporary state.\n * `mathFunctions` records whether transcendental SQL functions needed by\n * deferred algorithms such as MCL/spectral are available; exact WCC does not\n * require them.\n */\nexport type GraphAnalyticsCapabilities = Readonly<{\n  supported: boolean;\n  mathFunctions: boolean;\n}>;\n\n/**\n * How much of the contribution health lifecycle a backend can serve.\n *\n * The three rungs escalate — probe (read-only) → repair\n * (non-destructive) → rebuild (destructive) — and each is declared\n * separately because a backend can genuinely stop at any of them. A\n * backend that provisions contributions but cannot probe its own catalog\n * is a real gap, and the honest answer to `store.probeContributions()`\n * there is a refusal, not `ready`: \"assessed and healthy\" and \"never\n * looked\" must never share a return value.\n */\nexport type ContributionCapabilities = Readonly<{\n  /**\n   * Whether strategy-owned contribution tables are provisioned and\n   * attested by durable markers on this backend at all. `false` means\n   * there is nothing to assess, and the probe reports no entries rather\n   * than refusing.\n   */\n  supported: boolean;\n  /**\n   * Whether the backend can cross its durable markers against the live\n   * catalog — `store.probeContributions()` and\n   * `store.verifyContributions()`. False with `supported: true` is the\n   * declared gap: both refuse with `ConfigurationError`.\n   */\n  probe: boolean;\n  /**\n   * Whether the backend can run the destructive drop → recreate →\n   * repopulate → stamp rebuild (`store.rebuildContribution()`). Requires\n   * both a strategy that declares `dropDdl` and a transactional schema\n   * fence to run it under; false means `rebuildContribution` refuses.\n   *\n   * Describes the fulltext projection only. `rebuildContribution(\"vector\")`\n   * refuses on every backend regardless of this flag — embeddings exist\n   * only in the storage a rebuild would drop, so there is nothing to\n   * reconstruct them from — and `reembedVectorField` is the sanctioned\n   * destructive path there.\n   */\n  rebuild: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\nimport { type RecursiveTraversalCapability } from \"./capabilities/recursive-traversal\";\n\nexport type { RecursiveTraversalCapability } from \"./capabilities/recursive-traversal\";\n\nimport {\n  type FenceSql,\n  type WriteFenceDeclaration,\n} from \"./capabilities/write-fence\";\n\nexport type {\n  FenceSql,\n  WriteFenceDeclaration,\n} from \"./capabilities/write-fence\";\n\nimport { type BackendCatalogProbes } from \"./capabilities/catalog\";\nimport { type LineageMembers } from \"./capabilities/lineage\";\nimport { type EngineRecordedTimeMembers } from \"./capabilities/recorded-time\";\n\nexport type {\n  BackendCatalogProbes,\n  CatalogColumn,\n  CatalogIndexBehavior,\n  IndexState,\n  NormalizedColumnKind,\n  TableState,\n} from \"./capabilities/catalog\";\nexport type {\n  EngineRevision,\n  EntityKey,\n  LineageDelta,\n  LineageMembers,\n  LineageSession,\n} from \"./capabilities/lineage\";\nexport type {\n  EngineRecordedRevision,\n  EngineRecordedTimeMembers,\n  RecordedSourceTable,\n  RecordedTimeSession,\n} from \"./capabilities/recorded-time\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n  /** How this backend executes work and establishes atomicity. */\n  execution: Readonly<{\n    /** Whether the backend can hold an interactive callback/session transaction. */\n    interactiveTransactions: boolean;\n    /**\n     * Where this exact backend object can execute a conformance-earned atomic\n     * batch. `root` owns the transaction boundary; `session` is already bound\n     * to the transaction that makes a closed statement sequence atomic.\n     */\n    atomicBatch: \"none\" | \"root\" | \"session\";\n    /**\n     * How this backend groups a multi-statement write into one unit: an\n     * `\"interactive\"` callback/session transaction that can hold a fenced\n     * conversation across several round trips; `\"optimistic-retry\"`, the\n     * same interactive transaction on an engine whose write fence resolves\n     * `mechanism: \"row\"` with `conflict: \"commit-time\"` — two acquirers of\n     * one fence row both proceed and the loser's COMMIT fails, so every\n     * store-owned unit of work must be prepared to replay from the top; a\n     * `\"batch\"` atomic program with no such transaction; or `\"none\"` when it\n     * offers neither and a managed write can only run its statements one at\n     * a time with no atomicity across them.\n     *\n     * Derived, never hand-declared, on every bundled backend through\n     * `deriveUnitOfWork` (`backend/capabilities/execution.ts`) —\n     * `\"optimistic-retry\"` when `interactiveTransactions` is true AND the\n     * caller supplied the resolved write-fence plan's `conflict` fact as\n     * `\"commit-time\"`, else `\"interactive\"` when `interactiveTransactions`\n     * is true, else `\"batch\"` when `atomicBatch` is not `\"none\"`, else\n     * `\"none\"` — overwriting whatever a profile's own `declaredCapabilities`\n     * set. `finalizeEngineCapabilities` is the one place that resolves this\n     * fact fresh, from the root profile's own `row`-mechanism plan; every\n     * later derivation boundary (`downgradeAtomicBatch`,\n     * `scopeAtomicBatchToSession`) carries it forward instead of\n     * re-resolving it, by reading whether its own source object was already\n     * `\"optimistic-retry\"` — so the tier survives a derived or\n     * session-scoped backend for as long as `interactiveTransactions` stays\n     * `true`. Optional so a custom `GraphBackend` implementation, which\n     * nothing derives this for, is not forced to declare it.\n     *\n     * `src/store/operations/write-transaction.ts`'s retry-routing helpers\n     * are the store-owned `\"optimistic-retry\"` consumers: every\n     * `runWritePlan`/`runHookedWritePlan`/\n     * `runAutocommitSingleStatementWritePlan` call, `runIdentityMutation`,\n     * `rebuildIdentityClosureWithSchemaFence`, `rebuildContribution`, and the\n     * index-materialization claim/record calls each wrap their write in\n     * `runRetriedUnit` when this reads `\"optimistic-retry\"` (and, for the\n     * transaction-opening ones, the write opens its own transaction rather\n     * than joining an existing one). Two backend-owned transactions consult\n     * the SAME tier directly, outside the store's write path entirely:\n     * PostgreSQL's graph-template instantiation row branch and\n     * `runSchemaWriteTransaction` (behind `commitSchemaVersion` and its\n     * three siblings), both in `src/backend/drizzle/postgres.ts` — each\n     * acquires the schema-commit fence row in a `db.transaction(...)` it\n     * opens directly, so each wraps that whole transaction in\n     * `runRetriedUnit` itself rather than routing through the store's\n     * helpers. Two further readers key off the\n     * `\"batch\"` value: the batch-tier write verdict\n     * (`resolveBatchWriteVerdict` in\n     * `backend/capabilities/batch-write-verdict.ts`) and the autocommit\n     * single-statement eligibility gate (`canFuseSchemaFenceInFirstWrite`).\n     * Absent is treated as anything but `\"batch\"`: `resolveBatchWriteVerdict`\n     * answers `program` (its \"not a batch-tier limitation\" verdict) for it,\n     * so a backend that declares neither an interactive transaction nor an\n     * atomic batch still fails closed on a write that needs one — through\n     * that write's own capability check, not through a batch-tier refusal it\n     * never earned.\n     */\n    unitOfWork?: \"interactive\" | \"optimistic-retry\" | \"batch\" | \"none\";\n  }>;\n  /** Whether the backend supports SQL window functions such as ROW_NUMBER() */\n  windowFunctions: boolean;\n  /**\n   * Whether aggregate calls may contain their own `ORDER BY` clause, as used\n   * by ordered scalar and record collection. Absent is `false`: custom and remote\n   * backends must opt in only when their active engine accepts that syntax.\n   */\n  orderedAggregates?: boolean;\n  /**\n   * Whether `updateNode` / `updateEdge` honor `clearValidTo: true` by storing\n   * SQL NULL in `valid_to`. Absent is `false`: custom backends must opt in so\n   * the store refuses every explicit clear-bearing call before lookup,\n   * coalescing, or write instead of making support depend on row state.\n   */\n  clearValidTo?: boolean;\n  /**\n   * Whether the backend's `execute()` supports `UPDATE … RETURNING`. Absent or\n   * `true` means supported (every engine TypeGraph ships — SQLite ≥ 3.35,\n   * PostgreSQL ≥ 8.2 — supports it). A custom backend whose engine cannot run\n   * `RETURNING` must set this to `false` so recorded-time history capture\n   * (`history: true`), which relies on `UPDATE … RETURNING` on its hot path,\n   * is refused up front instead of failing mid-flush.\n   */\n  returning?: boolean;\n  /**\n   * Maximum number of bound parameters the engine accepts in one statement.\n   * SQLite defaults to 999 (raisable at compile time via\n   * `SQLITE_MAX_VARIABLE_NUMBER`), while hosted SQLite runtimes may impose a\n   * lower platform ceiling. PostgreSQL's wire protocol encodes a 65535-count,\n   * but postgres.js accepts at most 65533 bound values, so the bundled\n   * PostgreSQL capability advertises that lower shared-driver ceiling.\n   * Recorded-time capture and recorded point reads size their multi-row\n   * statements to this ceiling — the same budget the backend's own batched\n   * inserts use — instead of a conservative dialect-blind constant. Custom\n   * runtimes can override a detected or probed limit here, but hosted platform\n   * hard ceilings may only be lowered. Absent means the recorded-time fallback\n   * budget applies.\n   */\n  maxBindParameters?: number;\n  /**\n   * Whether this backend supplies the claim relations that fence declared\n   * constraints (`uniques`, re-keyed onto claim axes, plus\n   * `typegraph_edge_claims`) AND implements the claim members.\n   *\n   * Absent means `false`: the backend predates the claim relations, keeps every\n   * fence it has today, and is listed as such in the parity matrix. Never\n   * INFERRED from member presence — a projection that forwarded `capabilities`\n   * while dropping a method would otherwise yield a verdict read from a\n   * different object than the write goes to. `claimSupport`\n   * (`store/claims/backing.ts`) is the one reader, and it refuses a backend\n   * whose declaration and surface disagree in either direction.\n   */\n  readonly constraintClaims?: boolean;\n  /**\n   * Whether the command port can atomically apply the claim portion of\n   * a node create. Absent means projection-only: method presence alone is not\n   * evidence that a custom backend understands the newer plan field, so the\n   * store retains the standalone claim fallback.\n   */\n  readonly atomicNodeInsertClaims?: boolean;\n  /** Whether edge writes atomically persist and arbitrate `matchIdentity`. */\n  readonly durableEdgeMatchIdentity?: boolean;\n  /** Vector search capabilities (undefined if not configured) */\n  vector?: VectorCapabilities | undefined;\n  /** Fulltext search capabilities (undefined if not configured) */\n  fulltext?: FulltextCapabilities | undefined;\n  /** Whole-graph analytics capabilities (undefined when unavailable). */\n  graphAnalytics?: GraphAnalyticsCapabilities | undefined;\n  /**\n   * How far up the contribution health ladder this backend goes\n   * (undefined on a backend with no contribution machinery at all,\n   * equivalent to every member `false`).\n   */\n  contributions?: ContributionCapabilities | undefined;\n  /**\n   * Whether this engine can compute a bounded transitive closure of a\n   * relation in one round trip (a recursive CTE, or a graph-native\n   * expansion operator).\n   *\n   * Absent means SUPPORTED. Every engine TypeGraph ships supports it, and\n   * every custom backend on this release already has every recursion site\n   * run against it unconditionally: making absence mean `false` would\n   * refuse traversals that work today. See\n   * {@link RecursiveTraversalCapability} for the full contract.\n   */\n  recursiveTraversal?: RecursiveTraversalCapability | undefined;\n  /**\n   * How this backend excludes concurrent writers: a keyed advisory lock, a\n   * single writer slot the engine serializes by construction, or a\n   * deployment-level promise that this process serializes its own writes and\n   * no other client writes to the database — see\n   * {@link WriteFenceDeclaration} for the full `mechanism`/`drain` contract.\n   *\n   * Absent means `unfenced` for any backend the first-party factories did\n   * not build (`resolveWriteFencePlan`, `src/backend/capabilities/write-fence.ts`):\n   * an undeclared custom backend is refused at construction for Operational\n   * Identity and for TypeGraph-owned recorded-clock allocation (`history` /\n   * `revisionTracking`) rather than silently emitting locks the engine may\n   * not honor.\n   */\n  writeFence?: WriteFenceDeclaration | undefined;\n}>;\n\nexport type BackendExecutionCapabilities = BackendCapabilities[\"execution\"];\n\n/**\n * Capability overrides accepted by bundled backend factories.\n *\n * Root atomic-batch support is deliberately absent: bundled factories derive\n * it from the transport they actually discover and register. Callers may\n * override interactive transaction availability for an otherwise unknown\n * driver, but cannot advertise an executor the factory did not find.\n */\nexport type BundledBackendCapabilityOverrides = Readonly<\n  Omit<Partial<BackendCapabilities>, \"execution\"> & {\n    execution?: Readonly<{\n      interactiveTransactions?: boolean;\n    }>;\n  }\n>;\n\n/** Keeps session-scoped analytics honest when a required SQL feature is absent. */\nexport function normalizeGraphAnalyticsCapabilities(\n  capabilities: BackendCapabilities,\n): BackendCapabilities {\n  if (\n    capabilities.graphAnalytics?.supported !== true ||\n    (capabilities.execution.interactiveTransactions &&\n      capabilities.windowFunctions &&\n      capabilities.returning !== false)\n  ) {\n    return capabilities;\n  }\n  return {\n    ...capabilities,\n    graphAnalytics: { ...capabilities.graphAnalytics, supported: false },\n  };\n}\n\n/**\n * Returns whether the supplied backend or capability declaration can keep an\n * interactive transaction open across awaited statements.\n */\nexport function supportsInteractiveTransactions(\n  backendOrCapabilities:\n    BackendCapabilities | Readonly<{ capabilities: BackendCapabilities }>,\n): boolean {\n  return \"capabilities\" in backendOrCapabilities ?\n      backendOrCapabilities.capabilities.execution.interactiveTransactions\n    : backendOrCapabilities.execution.interactiveTransactions;\n}\n\n/** Returns whether this exact root declares certified atomic batch support. */\nexport function supportsRootAtomicBatch(\n  backendOrCapabilities:\n    BackendCapabilities | Readonly<{ capabilities: BackendCapabilities }>,\n): boolean {\n  const capabilities =\n    \"capabilities\" in backendOrCapabilities ?\n      backendOrCapabilities.capabilities\n    : backendOrCapabilities;\n  return capabilities.execution.atomicBatch === \"root\";\n}\n\n/** Returns whether this exact object owns any certified atomic batch session. */\nexport function supportsAtomicBatch(\n  backendOrCapabilities:\n    BackendCapabilities | Readonly<{ capabilities: BackendCapabilities }>,\n): boolean {\n  const capabilities =\n    \"capabilities\" in backendOrCapabilities ?\n      backendOrCapabilities.capabilities\n    : backendOrCapabilities;\n  return capabilities.execution.atomicBatch !== \"none\";\n}\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A node/edge row's `props` column as the driver returned it: SQLite always\n * yields the JSON text; PostgreSQL drivers yield the jsonb value already\n * parsed. Keeping the driver's shape avoids a per-row\n * parse→stringify→re-parse round trip on the PostgreSQL read path —\n * consumers normalize through {@link rowPropsToObject} /\n * {@link rowPropsToJsonText} at the point of use.\n */\nexport type RowProps = string | Readonly<Record<string, unknown>>;\n\n/** The row's props as an object, parsing only when the driver gave text. */\nexport function rowPropsToObject(props: RowProps): Record<string, unknown> {\n  return typeof props === \"string\" ?\n      (JSON.parse(props) as Record<string, unknown>)\n    : props;\n}\n\n/** The row's props as JSON text, serializing only when the driver gave an object. */\nexport function rowPropsToJsonText(props: RowProps): string {\n  return typeof props === \"string\" ? props : JSON.stringify(props);\n}\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n  graph_id: string;\n  kind: string;\n  id: string;\n  props: RowProps;\n  version: number;\n  valid_from: string | undefined;\n  valid_to: string | undefined;\n  created_at: string;\n  updated_at: string;\n  deleted_at: string | undefined;\n}>;\n\n/**\n * A {@link NodeRow} proven live (not soft-deleted). Functions that must only\n * ever touch live rows — the live-row update pipeline, soft delete — take\n * this type so a caller holding a possibly-tombstoned row is forced through\n * {@link isLiveNodeRow} first, instead of silently running live-row side\n * effects (uniqueness reservations, embedding/fulltext sync) for a row that\n * stays invisible.\n */\nexport type LiveNodeRow = NodeRow & Readonly<{ deleted_at: undefined }>;\n\n/**\n * A {@link NodeRow} proven soft-deleted. A resurrect targets exactly this\n * shape; see {@link isTombstonedNodeRow}.\n */\nexport type TombstonedNodeRow = NodeRow & Readonly<{ deleted_at: string }>;\n\nexport function isLiveNodeRow(row: NodeRow): row is LiveNodeRow {\n  return row.deleted_at === undefined;\n}\n\nexport function isTombstonedNodeRow(row: NodeRow): row is TombstonedNodeRow {\n  return row.deleted_at !== undefined;\n}\n\n/**\n * The read-only slice of a backend. Give this type to code that is\n * semantically a read — probes, gates, support-graph loads — so a read path\n * structurally CANNOT open a write transaction, mutate rows, or execute raw\n * SQL: those members do not exist on the type. Extend the pick as read paths\n * need more of the read surface.\n */\nexport type GraphReadBackend = Pick<\n  GraphBackend,\n  | \"dialect\"\n  | \"getNode\"\n  | \"getEdge\"\n  | \"findNodesByKind\"\n  | \"findEdgesByKind\"\n  | \"findEdgesByHeterogeneousEndpointSet\"\n  | \"findEdgesConnectedTo\"\n>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n  graph_id: string;\n  id: string;\n  kind: string;\n  from_kind: string;\n  from_id: string;\n  to_kind: string;\n  to_id: string;\n  props: RowProps;\n  match_identity_name?: string;\n  match_identity_key?: string;\n  valid_from: string | undefined;\n  valid_to: string | undefined;\n  created_at: string;\n  updated_at: string;\n  deleted_at: string | undefined;\n}>;\n\n/** The schema-declared identity persisted with an edge row. */\nexport type EdgeMatchIdentityStorage = Readonly<{\n  name: string;\n  key: string;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n  graph_id: string;\n  node_kind: string;\n  constraint_name: string;\n  key: string;\n  node_id: string;\n  concrete_kind: string;\n  deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n  graph_id: string;\n  version: number;\n  schema_hash: string;\n  schema_doc: string; // JSON string\n  created_at: string;\n  is_active: boolean;\n}>;\n\n/** A durable, server-resident materialized schema template. */\nexport type GraphTemplateRow = Readonly<{\n  template_id: string;\n  schema_hash: string;\n  schema_doc: string;\n  created_at: string;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n  graphId: string;\n  kind: string;\n  id: string;\n  props: Readonly<Record<string, unknown>>;\n  /**\n   * Omitted (`undefined`): the insert stamps its own creation timestamp —\n   * UNLESS a stated `validTo` at or before that instant would make the stored\n   * window readable at no coordinate, in which case the row is stored with no\n   * lower bound (\"ended at T, start unknown\"). See\n   * `resolveStampedValidityLowerBound`, which every insert builder decides\n   * through. Custom backend implementations can import that owner from\n   * `@nicia-ai/typegraph/backend` rather than reimplementing the rule.\n   * `null`: preserves an explicit open-left validity window (no lower\n   * bound) — used by interchange import to round-trip a row that was\n   * already NULL, instead of re-stamping it to the import's own timestamp.\n   */\n  validFrom?: string | null;\n  validTo?: string;\n}>;\n\n/** One validated plain caller-ID member of the heterogeneous node upsert CTE. */\nexport type HeterogeneousNodeUpsertEntry = Readonly<{\n  kind: string;\n  id: string;\n  /** Complete create-parsed document used for inserts and resurrections. */\n  props: Readonly<Record<string, unknown>>;\n  /** Caller patch used only when the target row is already live. */\n  updateProps: Readonly<Record<string, unknown>>;\n}>;\n\n/** Exact-session input for the PostgreSQL heterogeneous node upsert lowering. */\nexport type HeterogeneousNodeUpsertParams = Readonly<{\n  entries: readonly HeterogeneousNodeUpsertEntry[];\n  schemaFence: SchemaWriteFenceParams;\n}>;\n\n/**\n * A backend validity-end mutation. Omission preserves the stored end,\n * `validTo` sets it, and `clearValidTo` reopens the window. The union keeps the\n * two write actions mutually exclusive without exposing SQL `NULL`.\n */\nexport type BackendValidityEndMutation =\n  | Readonly<{ validTo?: string; clearValidTo?: never }>\n  | Readonly<{ validTo?: never; clearValidTo: true }>;\n\n/** Parameters for updating a node. */\nexport type UpdateNodeParams = Readonly<{\n  graphId: string;\n  kind: string;\n  id: string;\n  props: Readonly<Record<string, unknown>>;\n  /**\n   * Applied when resurrecting a tombstone, which RESETS the window. Omitted\n   * means the resurrection instant — unless a stated `validTo` at or before it\n   * would leave the row readable at no coordinate, in which case the\n   * resurrection stores no lower bound. Same rule, same owner, as an insert:\n   * `resolveStampedValidityLowerBound`.\n   *\n   * The store's own resurrection paths never omit it. Their window guard has to\n   * judge the bound the write will STORE, so they resolve it through that owner\n   * against the instant they sampled and pass the result — `null` included,\n   * which is how \"store no lower bound\" is spelled here. Omission is for callers\n   * with no such verdict to honor; it lets this builder decide against its own,\n   * strictly later sample.\n   */\n  validFrom?: string | null;\n  /**\n   * The effective `valid_from` this write ASSERTS the target row already\n   * carries, stated only by a caller whose decision DEPENDED on it.\n   *\n   * `(graph_id, kind, id)` does not pin a row across time. A caller that\n   * validated the document's window against the bound it probed — interchange\n   * import's `onConflict: \"update\"` is the case — decided what to write from a\n   * value a concurrent `hardDelete` + recreate can replace between the probe\n   * and the write, so a predicate on identity alone lets that decision land on\n   * a row it was never computed for: the document's stated `validFrom` is\n   * ignored, or a `valid_to` is persisted below the new row's `valid_from`.\n   * Stating the bound here puts it in the UPDATE's own `WHERE`, which is the\n   * only placement the race cannot slip past.\n   *\n   * NULL-SAFE: `null` asserts the row has NO lower bound (`IS NULL`), a string\n   * asserts equality, and omitting it asserts nothing. `null` and `undefined`\n   * are therefore NOT interchangeable here — see `expectedValidFromPredicate`.\n   *\n   * A backend MUST apply the predicate when it is present, on the same terms as\n   * {@link UpdateEdgeParams.kind}: silently ignoring it re-opens the window the\n   * caller stated it to close. A write whose stated bound does not match affects\n   * zero rows and surfaces as a `no_row_returned` `DatabaseOperationError`.\n   */\n  expectedValidFrom?: string | null;\n  incrementVersion?: boolean;\n  /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n  clearDeleted?: boolean;\n}> &\n  BackendValidityEndMutation;\n\n/**\n * Parameters for updating a set of live nodes selected by a compiled\n * TypeGraph query.\n *\n * The candidate query must expose the named node-id column from the same graph\n * and kind. The backend independently fences the rows it writes to\n * `graphId` and `kind`; constructing the matching candidate query remains the\n * caller's responsibility.\n * Property values replace top-level keys, including preserving an explicit\n * JSON `null` value.\n *\n * This is a storage primitive: callers that expose it as a graph mutation are\n * responsible for schema validation and for synchronizing uniqueness,\n * fulltext, and vector sidecars. The result contains after-images only; callers\n * that need previous property values must freeze the candidate set and retain\n * its before-images in the same transaction before invoking this method.\n */\nexport type UpdateNodeSetParams = Readonly<{\n  operation: \"updateWhere\";\n  graphId: string;\n  kind: string;\n  patch: Readonly<Record<string, JsonValue>>;\n  /** Top-level properties to remove (the storage form of an `undefined` patch value). */\n  unsetProperties?: readonly string[];\n  candidateIds: CompiledSelectSql;\n  /** Projected SQL column holding the candidate node id (for example `n_id`). */\n  candidateIdColumn: string;\n}>;\n\n/**\n * A guarded set update whose exact current-value predicates are applied by the\n * same outer UPDATE that writes the row. Kept as a distinct backend port so an\n * older/custom `updateNodeSet` implementation can never silently ignore the\n * compare-and-set fence.\n */\nexport type NodePropertyExpectation =\n  Readonly<{ kind: \"value\"; value: JsonScalar }> | Readonly<{ kind: \"absent\" }>;\n\nexport type CompareAndSetNodeParams = Readonly<{\n  operation: \"compareAndSet\";\n  graphId: string;\n  kind: string;\n  patch: Readonly<Record<string, JsonValue>>;\n  unsetProperties?: readonly string[];\n  candidateIds: CompiledSelectSql;\n  candidateIdColumn: string;\n  /**\n   * Exact scalar-or-absence predicates re-checked by the outer UPDATE. This\n   * discriminated map cannot be assigned to an ordinary set update.\n   */\n  expected: Readonly<Record<string, NodePropertyExpectation>>;\n}>;\n\n/** The after-images changed by {@link GraphBackend.updateNodeSet}. */\nexport type UpdateNodeSetResult = Readonly<{\n  affectedCount: number;\n  rows: readonly NodeRow[];\n}>;\n\n/** One resolved, whole-row replacement in a guarded node batch. */\nexport type ResolvedNodeUpdateBatchEntry = Readonly<{\n  graphId: string;\n  kind: string;\n  id: string;\n  props: Readonly<Record<string, unknown>>;\n  /** The preimage version the batch must still observe for every member. */\n  expectedVersion: number;\n}>;\n\n/**\n * Replaces several distinct live rows in one statement and returns their\n * after-images. The all-or-nothing version gate makes this safe to use before\n * rebuilding shared sidecars in a portable transaction.\n */\nexport type ResolvedNodeUpdateBatchParams = Readonly<{\n  entries: readonly ResolvedNodeUpdateBatchEntry[];\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n  graphId: string;\n  kind: string;\n  id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n  graphId: string;\n  id: string;\n  kind: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n  props: Readonly<Record<string, unknown>>;\n  /**\n   * Durable schema-declared match identity. Both values are written with the\n   * edge row and arbitrated by the database's edge-identity unique key.\n   */\n  matchIdentity?: EdgeMatchIdentityStorage;\n  /**\n   * Omitted (`undefined`): the insert stamps its own creation timestamp —\n   * UNLESS a stated `validTo` at or before that instant would make the stored\n   * window readable at no coordinate, in which case the row is stored with no\n   * lower bound (\"ended at T, start unknown\"). See\n   * `resolveStampedValidityLowerBound`, which every insert builder decides\n   * through. Custom backend implementations can import that owner from\n   * `@nicia-ai/typegraph/backend` rather than reimplementing the rule.\n   * `null`: preserves an explicit open-left validity window (no lower\n   * bound) — used by interchange import to round-trip a row that was\n   * already NULL, instead of re-stamping it to the import's own timestamp.\n   */\n  validFrom?: string | null;\n  validTo?: string;\n}>;\n\n/**\n * Write-only session exposed inside {@link GraphBackend.trustedImport}.\n *\n * The caller has accepted the trusted-import contract: properties, endpoint\n * references, uniqueness, and cardinality are not validated. Backends may\n * therefore use engine-native ingestion primitives that bypass the normal\n * store write pipeline.\n */\nexport type TrustedImportSession = Readonly<{\n  insertNodes: (params: readonly InsertNodeParams[]) => Promise<void>;\n  insertEdges: (params: readonly InsertEdgeParams[]) => Promise<void>;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n  graphId: string;\n  id: string;\n  /**\n   * The kind this write ASSERTS the target row already carries.\n   *\n   * Edge ids are graph-global while public collections are kind-scoped, so a\n   * kind-scoped write has an expected kind and must not land on a row carrying\n   * a different one. Stating it here puts the predicate in the write\n   * statement's own `WHERE`, which is the only placement a concurrent\n   * `hardDelete` + recreate cannot slip past: a read-then-write pair keyed on\n   * `(graph_id, id)` alone re-resolves that id between the read and the write\n   * under PostgreSQL READ COMMITTED. A write whose stated kind does not match\n   * affects zero rows.\n   *\n   * A backend MUST apply the predicate when it is present — silently ignoring\n   * it re-opens the window the caller stated it to close, and the ignoring\n   * backend looks correct until it is raced.\n   * `tests/edge-write-self-verification.test.ts` asserts the behavior against\n   * the built-in backends.\n   *\n   * Omitted where the operation legitimately spans kinds: the node delete\n   * cascade removes every connected edge whatever its kind, so it states none.\n   * {@link DeleteEdgeParams} and {@link HardDeleteEdgeParams} carry the same\n   * field with the same contract.\n   */\n  kind?: string;\n  /**\n   * The ENDPOINTS this write asserts the target row already carries, stated\n   * only by a write that actually checked them.\n   *\n   * Kind alone does not pin a row's identity. An edge's endpoints are immutable\n   * for a given row, but the ID is not: a concurrent `hardDelete` + recreate\n   * under the SAME kind with DIFFERENT endpoints satisfies a kind-only\n   * predicate, so an upsert that resolved this id BY endpoints could otherwise\n   * write to an edge pointing somewhere it never looked. Carrying them here\n   * closes that, on the same terms and in the same `WHERE` as `kind`.\n   *\n   * All four move together or not at all — they are one assertion. A plain\n   * `update` on a kind-scoped collection states none of them, because it\n   * resolved the edge by id and kind and made no claim about where it points;\n   * predicating on endpoints it never checked would refuse legitimate writes.\n   * The same MUST-apply contract as `kind` binds a backend that receives them.\n   */\n  fromKind?: string;\n  fromId?: string;\n  toKind?: string;\n  toId?: string;\n  props: Readonly<Record<string, unknown>>;\n  /**\n   * Applied when resurrecting a tombstone, where it asserts a COMPLETE window:\n   * `validTo` is rewritten alongside it (omitted `validTo` reopens the window).\n   * Omitting `validFrom` on a resurrection leaves the stored window in place.\n   */\n  validFrom?: string | null;\n  /**\n   * The effective `valid_from` this write asserts the target row already\n   * carries. Same three states, same NULL-safety, and the same MUST-apply\n   * contract as {@link UpdateNodeParams.expectedValidFrom}; stated by the same\n   * kind of caller, one whose verdict READ that bound.\n   *\n   * Separate from the immutable-identity components above because it is not\n   * immutable: a resurrection rewrites `valid_from`. It is asserted for the\n   * opposite reason — precisely because it can change, a decision computed from\n   * it must be fenced against it having changed.\n   */\n  expectedValidFrom?: string | null;\n  /**\n   * The `valid_to` state a constraint decision read. NULL-safe and MUST apply\n   * when present, like `expectedValidFrom`; used to fence ended-to-open edges.\n   */\n  expectedValidTo?: string | null;\n  clearDeleted?: boolean;\n}> &\n  BackendValidityEndMutation;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n  graphId: string;\n  id: string;\n  /** See {@link UpdateEdgeParams.kind}. */\n  kind?: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n  graphId: string;\n  kind: string;\n  id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n  graphId: string;\n  id: string;\n  /** See {@link UpdateEdgeParams.kind}. */\n  kind?: string;\n}>;\n\n/** Parameters for a batched edge delete (soft or hard). */\nexport type DeleteEdgesBatchParams = Readonly<{\n  graphId: string;\n  ids: readonly string[];\n  /** See {@link UpdateEdgeParams.kind}. */\n  kind?: string;\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeId: string;\n  fieldPath: string;\n  embedding: readonly number[];\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n}>;\n\n/**\n * A projection written from the node row's `RETURNING` source by a fused\n * generated-id insert. Identity is deliberately absent: the backend derives\n * graph, kind, and id from the inserted-row CTE, so a sidecar cannot disagree\n * with the node row it accompanies.\n */\nexport type NodeInsertProjection =\n  | Readonly<{\n      kind: \"embedding\";\n      fieldPath: string;\n      embedding: readonly number[];\n      dimensions: number;\n      metric: VectorMetric;\n      indexType: VectorIndexType;\n    }>\n  | Readonly<{\n      kind: \"fulltext\";\n      action: \"upsert\";\n      content: string;\n      language: string;\n    }>\n  | Readonly<{\n      kind: \"fulltext\";\n      action: \"delete\";\n    }>;\n\n/**\n * A uniqueness-relation claim carried by an atomic node-insert plan.\n *\n * Node identity is deliberately absent: the backend derives the owner pair\n * from the node insert parameters, so the claim cannot name a different row.\n * Placement is decided by the store's claim-site owner and preserved by the\n * SQL compiler as an explicit dependency around the node insert.\n */\nexport type NodeInsertClaimVerdict =\n  | Readonly<{\n      kind: \"uniqueness\";\n      probeAxes: readonly string[];\n      fields: readonly string[];\n    }>\n  | Readonly<{\n      kind: \"disjointness\";\n      conflictingKinds: readonly string[];\n    }>;\n\nexport type NodeInsertClaim = Readonly<{\n  axis: string;\n  constraintName: string;\n  key: string;\n  placement: \"pre-insert\" | \"post-insert\";\n  /**\n   * The complete read set for this claim. A canonical claim upsert only sees\n   * the folded axis; the additional uniqueness axes preserve compatibility\n   * with rows written before that fold. Disjoint claims name their live-node\n   * fallback population instead, because old databases can have no claim row\n   * for an existing disjoint overlap.\n   */\n  verdict: NodeInsertClaimVerdict;\n}>;\n\n/** The two atomic node-insert shapes supported by a planned-write backend. */\nexport type ManagedNodeCreateMode =\n  | Readonly<{ kind: \"ordinary\" }>\n  | Readonly<{\n      kind: \"schema-fenced\";\n      schemaFence: SchemaWriteFenceParams;\n    }>;\n\n/** A complete managed node create, including its row and atomic write plan. */\nexport type ManagedNodeCreatePlan = Readonly<{\n  entity: \"node\";\n  params: InsertNodeParams;\n  /** Whether the node id was generated by the store rather than supplied. */\n  idGenerated: boolean;\n  mode: ManagedNodeCreateMode;\n  claims: readonly NodeInsertClaim[];\n  projections: readonly NodeInsertProjection[];\n}>;\n\n/** A complete managed edge create, including its row and atomic write plan. */\nexport type ManagedEdgeCreatePlan = Readonly<{\n  entity: \"edge\";\n  params: InsertEdgeParams;\n  schemaFence?: SchemaWriteFenceParams;\n  cardinalityClaim?: ClaimEdgeCardinalityParams;\n}>;\n\n/** A node create command accepted by the authoritative command port. */\nexport type NodeCreateCommand = Readonly<{\n  kind: \"node.create\";\n  plan: ManagedNodeCreatePlan;\n}>;\n\n/** An edge create command accepted by the authoritative command port. */\nexport type EdgeCreateCommand = Readonly<{\n  kind: \"edge.create\";\n  plan: ManagedEdgeCreatePlan;\n}>;\n\n/** The authoritative match-key read paired with a convergent edge create. */\nexport type EdgeConvergenceMatch =\n  | Readonly<{\n      kind: \"dynamic\";\n      matchOn: readonly string[];\n      props: Record<string, unknown>;\n    }>\n  | Readonly<{\n      kind: \"durable\";\n      identity: EdgeMatchIdentityStorage;\n    }>;\n\n/** An edge create command that atomically returns an existing match or inserts. */\nexport type EdgeConvergeCreateCommand = Readonly<{\n  kind: \"edge.converge-create\";\n  plan: ManagedEdgeCreatePlan;\n  match: EdgeConvergenceMatch;\n}>;\n\n/** The semantic commands currently supported by the authoritative port. */\nexport type GraphCommand =\n  NodeCreateCommand | EdgeCreateCommand | EdgeConvergeCreateCommand;\n\nexport type NodeCreateCommandResult =\n  | Readonly<{ outcome: \"created\"; entity: \"node\"; row: NodeRow }>\n  | Readonly<{ outcome: \"rejected\"; entity: \"node\"; reason: \"unknown\" }>\n  | Readonly<{\n      outcome: \"unsupported\";\n      entity: \"node\";\n      dimensions: readonly [\n        \"schemaFence\" | \"claims\" | \"projections\",\n        ...(readonly (\"schemaFence\" | \"claims\" | \"projections\")[]),\n      ];\n    }>;\n\nexport type EdgeCreateCommandResult =\n  | Readonly<{ outcome: \"created\"; entity: \"edge\"; row: EdgeRow }>\n  | Readonly<{ outcome: \"rejected\"; entity: \"edge\"; reason: \"unknown\" }>\n  | Readonly<{\n      outcome: \"unsupported\";\n      entity: \"edge\";\n      dimensions: readonly [\n        \"schemaFence\" | \"cardinalityClaim\" | \"endpointPredicate\",\n        ...(readonly (\n          \"schemaFence\" | \"cardinalityClaim\" | \"endpointPredicate\"\n        )[]),\n      ];\n    }>;\n\nexport type EdgeConvergeCreateCommandResult =\n  | Readonly<{ outcome: \"created\"; entity: \"edge\"; row: EdgeRow }>\n  | Readonly<{ outcome: \"found\"; entity: \"edge\"; row: EdgeRow }>\n  | Readonly<{ outcome: \"rejected\"; entity: \"edge\"; reason: \"unknown\" }>\n  | Readonly<{\n      outcome: \"unsupported\";\n      entity: \"edge\";\n      dimensions: readonly [\n        \"convergence\" | \"endpointPredicate\",\n        ...(readonly (\"convergence\" | \"endpointPredicate\")[]),\n      ];\n    }>;\n\n/** The session boundary on which an authoritative command executes. */\nexport type GraphCommandSession = \"root\" | \"transaction\";\n\n/** Effective transaction isolation observed on the command's physical session. */\nexport type GraphCommandIsolation =\n  \"read_committed\" | \"repeatable_read\" | \"serializable\" | \"unknown\";\n\ndeclare const GRAPH_COMMAND_COORDINATION_BRAND: unique symbol;\n\n/** Compile-time evidence that graph-write coordination is already established. */\nexport type GraphCommandCoordination = Readonly<{\n  [GRAPH_COMMAND_COORDINATION_BRAND]: true;\n}>;\n\nexport type GraphCommandExecutionContext =\n  | Readonly<{\n      session: \"root\";\n      coordination: \"none\";\n    }>\n  | Readonly<{\n      session: \"transaction\";\n      coordination: \"none\" | GraphCommandCoordination;\n    }>;\n\n/** The result union returned by the authoritative command port. */\nexport type GraphCommandResult =\n  | NodeCreateCommandResult\n  | EdgeCreateCommandResult\n  | EdgeConvergeCreateCommandResult;\n\n/** The single extensible authority boundary for semantic backend commands. */\nexport type GraphCommandPort = Readonly<{\n  /** The database session this port is structurally bound to. */\n  session: GraphCommandSession;\n  /**\n   * Execute an authoritative command. First-party Store paths pass an\n   * explicit execution context through\n   * `executeAuthoritativeGraphCommand`.\n   */\n  execute: (\n    this: void,\n    command: GraphCommand,\n    context: GraphCommandExecutionContext,\n  ) => Promise<GraphCommandResult>;\n}>;\n\n/**\n * One row of a batched embedding upsert.\n */\nexport type UpsertEmbeddingBatchRow = Readonly<{\n  nodeId: string;\n  embedding: readonly number[];\n}>;\n\n/**\n * Parameters for a batched embedding upsert. Homogeneous per vector slot:\n * one graph, one node kind, one field, many nodes. Duplicate `nodeId`\n * values within a batch are deduplicated last-write-wins by the backend\n * (a multi-row upsert cannot affect one row twice).\n */\nexport type UpsertEmbeddingBatchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  fieldPath: string;\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n  rows: readonly UpsertEmbeddingBatchRow[];\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeId: string;\n  fieldPath: string;\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  fieldPath: string;\n  queryEmbedding: readonly number[];\n  metric: VectorMetric;\n  /**\n   * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n   * slot. The store populates it from the schema's `embedding()`\n   * declaration via `getEmbeddingDimensions()`; the backend uses it to\n   * construct the `VectorSlot` whose typed storage the strategy scans.\n   */\n  dimensions: number;\n  /**\n   * Index type materialized for this slot. `\"none\"` means brute-force\n   * only; otherwise the strategy may route through its ANN structure.\n   * The store populates it from `getEmbeddingIndex()`.\n   */\n  indexType: VectorIndexType;\n  limit: number;\n  minScore?: number;\n  /**\n   * Subquery of eligible node ids (single column, exposed as `node_id`).\n   * When present, the search statement computes top-k over this candidate\n   * set — the store passes its compiled current-read query here so\n   * `where` predicates push down into the search SQL. Exact on engines\n   * whose search form takes the filter inside retrieval (pgvector,\n   * sqlite-vec, tsvector, FTS5); libSQL's DiskANN cannot pre-filter, so\n   * it post-filters an over-fetched ANN set and recall against the\n   * candidate set is bounded by that headroom. When absent, the backend\n   * restricts to CURRENT nodes of the kind — non-tombstoned AND inside\n   * their validity window — matching a `current` read.\n   */\n  candidates?: SqlFragment;\n  /**\n   * Rows to skip AFTER ranking (pagination). The engine fetches\n   * `limit + offset` ranked candidates and discards the first `offset`.\n   */\n  offset?: number;\n  /**\n   * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n   * Sizes the dynamic candidate list the index scan maintains: higher\n   * trades latency for recall. The floor for the over-fetch to fill its\n   * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n   * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n   * HNSW path only.\n   *\n   * APPLIED OR REFUSED, never ignored. Read\n   * `capabilities.vector.searchFrontierTuning` to know which you get:\n   *\n   * - `tunable: false` (sqlite-vec, libSQL DiskANN — no per-search frontier\n   *   knob exists): `UnsupportedBackendCapabilityError`.\n   * - a slot whose index type is not the tunable one (pgvector IVFFlat or\n   *   brute-force): `ConfigurationError`.\n   * - `requiresTransactionScope` on a backend reporting\n   *   `execution.interactiveTransactions: false` (for example `drizzle-orm/neon-http`):\n   *   `UnsupportedBackendCapabilityError`, because `SET LOCAL` has no frame\n   *   to be local to.\n   */\n  efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n  nodeId: string;\n  /**\n   * Cosine metric returns similarity score (higher is better).\n   * L2 and inner_product return raw distance (lower is better).\n   */\n  score: number;\n}>;\n\n/**\n * Parameters for a single-statement hybrid (vector + fulltext, RRF-fused)\n * search. The store facade resolves every default before calling — the\n * per-source candidate depths (`k`), the fusion constants, and the shared\n * `candidates` subquery — so the backend composes `SqlFragment` values without policy.\n */\nexport type HybridSearchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  vector: Readonly<{\n    fieldPath: string;\n    queryEmbedding: readonly number[];\n    metric: VectorMetric;\n    dimensions: number;\n    indexType: VectorIndexType;\n    /** Candidate depth of the vector source (rows entering fusion). */\n    k: number;\n    minScore?: number;\n    efSearch?: number;\n  }>;\n  fulltext: Readonly<{\n    query: string;\n    mode?: FulltextQueryMode;\n    language?: string;\n    /** Candidate depth of the fulltext source (rows entering fusion). */\n    k: number;\n    minScore?: number;\n    includeSnippets?: boolean;\n  }>;\n  fusion: Readonly<{\n    /** RRF rank constant (`1 / (k + rank)`). */\n    k: number;\n    vectorWeight: number;\n    fulltextWeight: number;\n  }>;\n  /** Fused rows to return after `offset`. */\n  limit: number;\n  /** Fused rows to skip (rank-relative pagination). */\n  offset?: number;\n  /** See {@link VectorSearchParams.candidates}; applies to both sources. */\n  candidates?: SqlFragment;\n}>;\n\n/**\n * One fused hybrid hit, hydrated in the same statement: the node row\n * rides along so the caller needs no follow-up id fetch.\n */\nexport type HybridSearchRow = Readonly<{\n  node: NodeRow;\n  fusedScore: number;\n  vectorRank?: number;\n  vectorScore?: number;\n  fulltextRank?: number;\n  fulltextScore?: number;\n  snippet?: string;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  fieldPath: string;\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n  /** Index-specific parameters */\n  indexParams?: Readonly<{\n    /** HNSW: max connections per layer */\n    m?: number;\n    /** HNSW: construction search depth */\n    efConstruction?: number;\n    /** IVFFlat: number of lists */\n    lists?: number;\n  }>;\n  /**\n   * Build the index without taking an `AccessExclusiveLock` on live\n   * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n   * `concurrent` flag the relational DDL path uses inside\n   * `materializeIndexes()`. Cannot be set inside a transaction —\n   * callers (`materializeIndexes()`) run at top level. Backends that\n   * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n   */\n  concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeId: string;\n  content: string;\n  language: string;\n}>;\n\n/** Parameters for the ordinary post-insert fulltext synchronization path. */\nexport type NodeFulltextSync =\n  | Readonly<{\n      graphId: string;\n      nodeKind: string;\n      nodeId: string;\n      action: \"upsert\";\n      content: string;\n      language: string;\n    }>\n  | Readonly<{\n      graphId: string;\n      nodeKind: string;\n      nodeId: string;\n      action: \"delete\";\n    }>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n  nodeId: string;\n  content: string;\n  language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  /** The user-supplied query string. */\n  query: string;\n  /** How to parse `query`. Default: \"websearch\". */\n  mode?: FulltextQueryMode;\n  /**\n   * Language for query parsing. The store facade resolves the kind's\n   * declared language and passes it here, so the tsquery is a plan-time\n   * constant (GIN-servable); when absent the backend falls back to the\n   * per-row language column.\n   * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n   * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n   */\n  language?: string;\n  /** Max rows to return. */\n  limit: number;\n  /** Minimum rank to include (backend-dependent units). */\n  minScore?: number;\n  /** Whether to return a highlighted snippet per match. */\n  includeSnippets?: boolean;\n  /**\n   * Subquery of eligible node ids (single column). When present, the\n   * search statement computes top-k over this candidate set — the store\n   * passes its compiled current-read query here so `where` predicates,\n   * subclass expansion, and valid-time currency all push down into the\n   * search SQL. Exact on engines whose search form takes the filter\n   * inside retrieval (pgvector, sqlite-vec, tsvector, FTS5); libSQL's\n   * DiskANN cannot pre-filter, so it post-filters an over-fetched ANN\n   * set and recall against the candidate set is bounded by that\n   * headroom. When absent, the backend restricts to CURRENT nodes of\n   * the kind — non-tombstoned AND inside their validity window —\n   * matching a `current` read.\n   */\n  candidates?: SqlFragment;\n  /**\n   * Rows to skip AFTER ranking (pagination). The engine fetches\n   * `limit + offset` ranked candidates and discards the first `offset`.\n   */\n  offset?: number;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n  nodeId: string;\n  /**\n   * Backend-native relevance score.\n   * Postgres: `ts_rank_cd` (higher is better).\n   * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n   */\n  score: number;\n  /** 1-based rank within the result set, suitable for RRF. */\n  rank: number;\n  /** Highlighted snippet of the content (if `includeSnippets` was set). */\n  snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\n/**\n * Parameters for atomically claiming an index build (see\n * `claimIndexMaterialization`). The declaration fields ride along so a\n * fresh claim row is honest while the build is in flight.\n */\nexport type ClaimIndexMaterializationParams = Readonly<{\n  indexName: string;\n  graphId: string;\n  entity: IndexEntity;\n  kind: string;\n  signature: string;\n  schemaVersion: number;\n  /** Opaque claim identity; release is token-guarded. */\n  token: string;\n  /** A claim older than this is stale and may be taken over. */\n  leaseMs: number;\n}>;\n\n/** Parameters for releasing a build claim (token-guarded). */\nexport type ReleaseIndexMaterializationClaimParams = Readonly<{\n  indexName: string;\n  token: string;\n}>;\n\nexport type IndexMaterializationRow = Readonly<{\n  indexName: string;\n  graphId: string;\n  entity: IndexEntity;\n  kind: string;\n  signature: string;\n  schemaVersion: number;\n  materializedAt: string | undefined;\n  lastAttemptedAt: string;\n  lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n  indexName: string;\n  graphId: string;\n  entity: IndexEntity;\n  kind: string;\n  signature: string;\n  schemaVersion: number;\n  attemptedAt: string;\n  /** ISO timestamp on success; undefined on failure (preserves existing). */\n  materializedAt: string | undefined;\n  /** Error message on failure; undefined on success (clears existing). */\n  error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n  graphId: string;\n  logicalName: string;\n  owner: string;\n  tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n  graphId: string;\n  logicalName: string;\n  owner: string;\n  tableName: string;\n  signature: string;\n  materializedAt: string | undefined;\n  lastAttemptedAt: string;\n  lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n  graphId: string;\n  logicalName: string;\n  owner: string;\n  tableName: string;\n  signature: string;\n  attemptedAt: string;\n  /** ISO timestamp on success; undefined on failure (preserves existing). */\n  materializedAt: string | undefined;\n  /** Error message on failure; undefined on success (clears existing). */\n  error: string | undefined;\n}>;\n\n/**\n * Why a contribution is not usable. Most members are a disagreement\n * between the durable marker and the physical catalog; one\n * (`failed-materialization`) is a state the two agree on and that is\n * broken anyway. A contribution that is genuinely healthy — or that was\n * simply never attempted — is not reported at all.\n *\n * - `orphaned-marker` — the marker records a successful materialization\n *   but the physical table is gone (a partial restore, an out-of-band\n *   `DROP`, a schema-scoped restore that missed the contribution\n *   tables). The state {@link GraphBackend.verifyContributions} exists\n *   to surface: nothing on the open path probes the catalog, so this\n *   database opens clean and fails at the first dependent read or write.\n * - `missing-marker` — the physical table exists but no marker attests\n *   it as initialized (no row, no recorded success, or a recorded\n *   failure). Reads and writes are refused with\n *   `StoreNotInitializedError` even though storage is present. These\n *   three causes share one state because they share one repair; check\n *   {@link ContributionDiagnostic.lastError} to tell them apart.\n * - `failed-materialization` — the marker records a *failed* attempt\n *   and no table was produced. Marker and catalog agree here, so this\n *   is not a disagreement — but it is where a contribution lands when\n *   provisioning genuinely broke (the `fts5` module is absent, the role\n *   lacks `CREATE`, the extension was never loaded), and calling it\n *   healthy on the grounds that both sides agree would be the one\n *   answer this method must never give. Distinguished from a\n *   contribution that was never attempted, which has no marker row and\n *   is correctly silent. {@link ContributionDiagnostic.lastError}\n *   carries the reason it failed.\n * - `stale` — the table exists and the marker records a prior success\n *   at a different signature (a strategy swap, or a declared embedding\n *   dimension that has moved ahead of the provisioned table).\n *\n * **Do not re-frame this union as \"how the marker disagrees with the\n * catalog.\"** It was described that way once, and the description was\n * load-bearing in the wrong direction: under it, a marker recording a\n * failed attempt with no table looks like agreement, therefore not a\n * disagreement, therefore correctly silent — and a contribution that\n * had genuinely broken was reported as healthy. The gap read as\n * principled rather than as an oversight precisely because the framing\n * endorsed it. \"Why the contribution is unusable\" is the question that\n * makes `failed-materialization` obviously belong, and any future\n * tidy-up that narrows the framing back will re-open the same hole.\n */\nexport type ContributionDiagnosticState =\n  \"orphaned-marker\" | \"missing-marker\" | \"failed-materialization\" | \"stale\";\n\n/**\n * One contribution that is not usable, reported by\n * {@link GraphBackend.verifyContributions}.\n *\n * The identity fields come from the active contribution declaration and\n * match the durable-marker identity contract, so a caller can route an entry\n * to its repair without reconstructing any internal naming contract. A\n * `missing-marker` entry may have no marker row at all.\n *\n * **Route on {@link ContributionDiagnosticState}, not on whether the\n * entry is a vector slot.** The repair differs per state and the wrong\n * choice destroys data: `store.reembedVectorField` drops and recreates\n * storage, so applying it to a `missing-marker` — where the table is\n * intact and only the bookkeeping is wrong — discards every embedding\n * to fix a marker, and without an `embed` callback it leaves the field\n * empty. Prefer `store.repairContributions()` for `missing-marker` and\n * `failed-materialization`; it resolves the current strategy declarations\n * internally and keeps the normal signature-drift guard enabled. It reports\n * `stale` and `orphaned-marker` as `requires-rebuild`. See the per-state\n * repair table in the troubleshooting guide.\n */\nexport type ContributionDiagnostic = Readonly<{\n  /** Producing strategy, e.g. `\"fts5\"` / `\"tsvector\"` / `\"pgvector\"`. */\n  owner: string;\n  /** Stable logical slot, e.g. `\"fulltext\"`. Never the SQL name. */\n  logicalName: string;\n  /** Resolved physical table name that was probed. */\n  physicalName: string;\n  /** Node kind — vector slots only. */\n  kind?: string;\n  /** Embedding field path — vector slots only. */\n  fieldPath?: string;\n  state: ContributionDiagnosticState;\n  /**\n   * The error the marker recorded against its last attempt, when it\n   * recorded one. Absent otherwise.\n   *\n   * This is the part of the picture the catalog cannot supply. `state`\n   * says what to do — the states are chosen so that each maps to one\n   * repair — while this says *why it broke*, which is a different\n   * question and often a different investigation. A failed attempt with no\n   * table surfaces as `failed-materialization`; when the table exists but\n   * the marker does not attest a successful materialization, it surfaces as\n   * `missing-marker`. This field distinguishes only failures whose marker\n   * recorded a reason; a missing row has no `lastError`. Present on any state\n   * whose marker row carries an error, not just those two states.\n   */\n  lastError?: string;\n}>;\n\n/**\n * Outcome of one contribution considered by\n * {@link GraphBackend.repairContributions}.\n *\n * Repair targets are always resolved from the backend's current strategy\n * declarations. The diagnostic is returned for operator context only; callers\n * never pass diagnostics or physical DDL back into the repair API.\n */\nexport type ContributionRepairEntry =\n  | Readonly<{\n      diagnostic: ContributionDiagnostic;\n      status: \"repaired\";\n    }>\n  | Readonly<{\n      diagnostic: ContributionDiagnostic;\n      status: \"requires-rebuild\";\n    }>\n  | Readonly<{\n      diagnostic: ContributionDiagnostic;\n      status: \"failed\";\n      error: string;\n    }>;\n\n/** Result of a contribution repair pass followed by a fresh verification. */\nexport type ContributionRepairResult = Readonly<{\n  results: readonly ContributionRepairEntry[];\n  remaining: readonly ContributionDiagnostic[];\n}>;\n\n// ============================================================\n// Contribution readiness probe (#377)\n// ============================================================\n\n/**\n * The search projection a probe entry summarizes. Deliberately the\n * logical *class* rather than one physical table: a caller asking \"is\n * search ready?\" is deciding whether to issue a fulltext or a vector\n * query, and a per-`(kind, field)` breakdown of pgvector tables answers\n * a question they did not ask. The physical detail an operator needs to\n * act is one `verifyContributions()` call away, and\n * {@link ContributionProbeEntry.detail} names the affected slots.\n */\nexport type ContributionProbeContribution = \"fulltext\" | \"vector\";\n\n/**\n * Readiness of one search projection.\n *\n * - `ready` — every contribution backing this projection is attested by\n *   its durable marker and present in the catalog. Not a promise about\n *   future coherence: a write that lands after the probe returns is\n *   outside what any assessment can cover.\n * - `degraded` — at least one contribution is unusable. Dependent operations\n *   may be refused with a typed contribution error, fail at the engine boundary\n *   when compiled SQL directly references missing storage, or observe\n *   incomplete storage.\n *   {@link ContributionProbeEntry.detail} says which and why.\n * - `building` — **reserved.** No shipped path publishes it. Recording\n *   an in-flight marker would need a fifth\n *   {@link ContributionDiagnosticState} and would widen the hot-path\n *   gate's verdict set; the destructive rebuild instead runs inside one\n *   transaction, so a concurrent probe observes the state before or\n *   after it and never a partial one. Reserved rather than removed so a\n *   future streaming/async materializer can populate it without a\n *   breaking change — treat it as \"not `ready`\" today.\n */\nexport type ContributionProbeState = \"ready\" | \"degraded\" | \"building\";\n\n/**\n * One search projection's readiness, from\n * {@link GraphBackend.probeContributions}.\n */\nexport type ContributionProbeEntry = Readonly<{\n  contribution: ContributionProbeContribution;\n  state: ContributionProbeState;\n  /**\n   * Operator-facing summary of why the projection is not `ready` —\n   * e.g. `\"fulltext table \\\"typegraph_node_fulltext\\\" is missing\n   * (orphaned-marker)\"`. Absent on a `ready` entry.\n   *\n   * Human-readable and not a stable format: route on `state`, and call\n   * `store.verifyContributions()` for the structured per-table\n   * diagnostics this string is derived from.\n   */\n  detail?: string;\n}>;\n\n/**\n * Result of {@link GraphBackend.probeContributions}.\n *\n * A projection with no declared contributions is omitted rather than\n * reported `ready`, so an empty `entries` array means \"nothing to\n * assess\" — a graph with no `searchable()` or `embedding()` fields, or a\n * backend with no contribution support — never \"assessed and healthy\".\n */\nexport type ContributionProbeResult = Readonly<{\n  /**\n   * The durable graph revision the assessment was taken at, so a caller\n   * can place this probe in the graph's committed history.\n   *\n   * Graph-global, like the clock it reads: it advances on every committed\n   * capture from any writer, so an advance between two probes means\n   * \"something committed in between\", never \"the write this caller just\n   * made landed\". Confirm a specific write by observing the write itself.\n   *\n   * Absent unless the Store is revision-tracked (`revisionTracking:\n   * true` or `history: true`) — the same condition under which\n   * `store.revisionNow()` returns a value. This is the one honest shape:\n   * a store with no durable revision clock has no revision to stamp, and\n   * substituting a wall-clock timestamp or the schema version would be a\n   * materially weaker guarantee wearing the name of a stronger one. The\n   * schema version in particular does not advance on data writes, so it\n   * could not order a probe against a caller's write at all.\n   */\n  graphRevision?: string;\n  entries: readonly ContributionProbeEntry[];\n}>;\n\n// ============================================================\n// Destructive contribution rebuild (#337)\n// ============================================================\n\n/**\n * Which search projection {@link GraphBackend.rebuildContribution}\n * targets. Scoped explicitly at the call site rather than inferred from\n * a diagnostic: the operation destroys storage, so which storage is the\n * caller's decision to state, not TypeGraph's to guess.\n */\nexport type ContributionRebuildScope = ContributionProbeContribution;\n\n/**\n * What a rebuild's `repopulate` callback reconstructed. Reported back so\n * the rebuild result can distinguish \"recreated empty storage\" from\n * \"recreated and refilled\", which is the difference between a finished\n * repair and half of one.\n */\nexport type ContributionRepopulationStats = Readonly<{\n  /** Nodes scanned. */\n  processed: number;\n  /** Content rows written. */\n  repopulated: number;\n  /** Nodes whose stored `props` could not be read as an object. */\n  skipped: number;\n}>;\n\n/** Outcome of one destructive contribution rebuild. */\nexport type ContributionRebuildResult = Readonly<{\n  /** Physical tables dropped and recreated, in the order rebuilt. */\n  rebuilt: readonly string[];\n  /** Nodes scanned while reconstructing content from stored rows. */\n  processed: number;\n  /** Content rows written into the recreated storage. */\n  repopulated: number;\n  /**\n   * Nodes whose stored `props` could not be read as an object, so no\n   * content row could be reconstructed for them. Non-zero means the\n   * rebuilt index is missing those nodes; the IDs come back from\n   * `store.search.rebuildFulltext()`, which reports them individually.\n   */\n  skipped: number;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n  graphId: string;\n  kindName: string;\n  entity: KindEntity;\n  schemaVersion: number;\n  /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n  removedAt: string | undefined;\n  lastAttemptedAt: string;\n  lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n  graphId: string;\n  kindName: string;\n  entity: KindEntity;\n  schemaVersion: number;\n  attemptedAt: string;\n  /** ISO timestamp on success; undefined while pending or on failure. */\n  removedAt: string | undefined;\n  /** Error message on failure; undefined on success or while pending. */\n  error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/** @internal Capability token for connection-local temporary writes. */\nexport const INTERNAL_TEMPORARY_WRITES: unique symbol = typeGraphGlobalSymbol(\n  \"internal-temporary-writes-v1\",\n);\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n  /** Transaction isolation level (if supported) */\n  isolationLevel?:\n    \"read_uncommitted\" | \"read_committed\" | \"repeatable_read\" | \"serializable\";\n  /**\n   * Transaction access mode (if supported). `read_only` is intended for\n   * multi-statement reads that need one snapshot and must not perform writes.\n   */\n  accessMode?: \"read_only\" | \"read_write\";\n}>;\n\n/** @internal Transaction options available only to TypeGraph-owned execution. */\nexport type InternalTransactionOptions = TransactionOptions &\n  Readonly<{\n    /**\n     * Permit writes only to connection-local temporary state. The iterative\n     * operation primitive uses this when an engine rejects temporary DDL in a\n     * read-only transaction.\n     */\n    temporaryWrites?: typeof INTERNAL_TEMPORARY_WRITES;\n  }>;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * The physical names of the four Operational Identity relations: the current\n * assertion ledger, its recorded-time twin, and the two DERIVED relations\n * (closure, separation) rebuilt from the ledger.\n *\n * Named once so the two ports that speak about them —\n * {@link GraphBackend.ensureIdentityTables} and\n * {@link GraphBackend.identityTableDdl} — cannot drift apart.\n */\nexport type IdentityTableNames = Readonly<{\n  identityAssertions: string;\n  recordedIdentityAssertions: string;\n  identityClosure: string;\n  identitySeparation: string;\n}>;\n\n/**\n * The physical names of the three recorded relations. Named once so the\n * ports that speak about them cannot drift apart — the {@link IdentityTableNames}\n * precedent.\n */\nexport type RecordedTableNames = Readonly<{\n  recordedClock: string;\n  recordedEdges: string;\n  recordedNodes: string;\n}>;\n\n/**\n * One recorded relation's provisioning DDL, with the roles the caller needs\n * SEPARATED rather than positional.\n */\nexport type RecordedRelationDdl = Readonly<{\n  /** The single `CREATE TABLE` statement. */\n  createTable: string;\n  /** Its index/constraint statements, in application order. */\n  indexes: readonly string[];\n  /**\n   * The name the ENGINE will have given this relation's PRIMARY KEY constraint\n   * once `createTable` has executed, or `undefined` on an engine that does not\n   * name PK constraints separately (SQLite).\n   *\n   * NOT \"the name the DDL text declares\": both bundled emitters push an unnamed\n   * inline `PRIMARY KEY (…)` (`ddl.ts:114-118`, `:441-445`), so on PostgreSQL the\n   * server derives `<table>_pkey`. The point of the field is that the derivation\n   * is an ENGINE convention, and the only honest source of it is whoever authored\n   * the DDL for that engine — a migration that reconstructs it bakes one adapter's\n   * convention in.\n   *\n   * The name is returned UNREDUCED. Reducing an over-long identifier is a\n   * separate decision with a separate owner (`shortenedIdentifier`), and it\n   * applies only to the RENAME's target. The source name is the *temporary*\n   * table's PK name, and temp table names are hash-derived and short BY\n   * CONSTRUCTION (`` `__tg_${role}_${shortHash(tableName)}` ``, an 8-char\n   * hash, so `<temp>_pkey` is at most ~21 bytes for any configured table\n   * name) — nowhere near the 63-byte ceiling. So the split is a structural\n   * fact about the temp-name shape, not a claim about PostgreSQL's\n   * truncation semantics: `shortenedIdentifier` is the identity on the\n   * source for every reachable input, and its effect is observable only on\n   * the target.\n   *\n   * A backend must apply this option consistently across name sets: return a\n   * name for both the temporary and final relation, or `undefined` for both.\n   * The migration refuses a mixed pair because silently dropping either name\n   * would leave the swapped relation with a backend-inconsistent constraint.\n   */\n  primaryKeyConstraintName?: string | undefined;\n}>;\n\n/**\n * The database-global extensions TypeGraph installs on a caller's behalf.\n *\n * The extent is closed on purpose: {@link GraphBackend.ensureExtension}\n * interpolates the name into DDL, so the allowlist — not the caller — is what\n * decides the identifier can be trusted. `pg_trgm` backs `method: \"trigram\"`\n * index materialization; `vector` backs pgvector storage.\n */\nexport const DATABASE_EXTENSION_NAMES = [\"pg_trgm\", \"vector\"] as const;\n\n/** A name {@link GraphBackend.ensureExtension} accepts. */\nexport type DatabaseExtensionName = (typeof DATABASE_EXTENSION_NAMES)[number];\n\n/**\n * Optional durable-identity batch write seam. Every input must carry\n * `matchIdentity`; identity conflicts are omitted from the returned rows.\n */\nexport type DurableEdgeBatchMembers = Readonly<{\n  insertEdgesDurableBatchReturning?: (\n    this: void,\n    params: readonly InsertEdgeParams[],\n  ) => Promise<readonly EdgeRow[]>;\n}>;\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n *\n * Every function is receiver-free (`this: void`). Implementations must close\n * over their state instead of reading `this`, which makes saved optional\n * capabilities and other detached port calls safe by construction.\n */\nexport type GraphBackend = Readonly<{\n  /** The SQL dialect */\n  dialect: SqlDialect;\n  /** Backend capabilities */\n  capabilities: BackendCapabilities;\n  /** Table names used by this backend (for query schema auto-derivation) */\n  tableNames?: SqlTableNames | undefined;\n  /**\n   * Optional fulltext strategy override. When present, both the compiler\n   * (for `$fulltext.matches()` in query builder) and backend-direct\n   * search paths use this instead of the dialect's default strategy —\n   * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n   * When absent, the dialect's default strategy is used.\n   */\n  fulltextStrategy?: FulltextStrategy | undefined;\n  /**\n   * Optional vector strategy this backend is wired with. The query\n   * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n   * field)` relevance scans for `field.similarTo(...)` predicates, and\n   * the index-materialization / removal paths read its deterministic\n   * `tableName(...)` to address the right physical per-field storage.\n   * `undefined` when the backend has no vector support (e.g. a generic\n   * SQLite backend without sqlite-vec).\n   */\n  vectorStrategy?: VectorStrategy | undefined;\n  /**\n   * The lock-statement spelling this backend's `capabilities.writeFence`\n   * declaration requires when `mechanism` is `\"advisory\"` — resolved through\n   * {@link resolveWriteFencePlan} rather than read directly by a lock site.\n   * Absent on a backend that serializes writers instead (SQLite's writer\n   * slot needs no lock statement at all) or that declares no usable fence.\n   */\n  fenceSql?: FenceSql | undefined;\n\n  // === Node Operations ===\n  insertNode: (this: void, params: InsertNodeParams) => Promise<NodeRow>;\n  /**\n   * Inserts a node only when its primary-key slot is empty. `undefined` means\n   * the slot was already occupied; unlike `insertNode`, that outcome is not a\n   * database error and leaves the surrounding transaction usable.\n   *\n   * First-party SQL backends expose this for the caller-supplied-id create\n   * fast path. Custom backends may omit it and retain the probe-then-insert\n   * path.\n   */\n  insertNodeIfAbsent?: (\n    this: void,\n    params: InsertNodeParams,\n  ) => Promise<NodeRow | undefined>;\n  /**\n   * First-party transactional fast path: the INSERT takes the active-schema\n   * shared fence in its source query. A missing row is deliberately ambiguous\n   * (stale schema versus an occupied id) and must be diagnosed by the caller.\n   */\n  insertNodeIfAbsentWithSchemaFence?: (\n    this: void,\n    params: InsertNodeParams,\n    schemaFence: SchemaWriteFenceParams,\n  ) => Promise<NodeRow | undefined>;\n  /** Like `insertNode`, but acquires the schema fence in that INSERT. */\n  insertNodeWithSchemaFence?: (\n    this: void,\n    params: InsertNodeParams,\n    schemaFence: SchemaWriteFenceParams,\n  ) => Promise<NodeRow | undefined>;\n  insertNodeNoReturn?: (this: void, params: InsertNodeParams) => Promise<void>;\n  insertNodesBatch?: (\n    this: void,\n    params: readonly InsertNodeParams[],\n  ) => Promise<void>;\n  insertNodesBatchReturning?: (\n    this: void,\n    params: readonly InsertNodeParams[],\n  ) => Promise<readonly NodeRow[]>;\n  updateNode: (this: void, params: UpdateNodeParams) => Promise<NodeRow>;\n  /** One data-modifying CTE for plain caller-ID node upserts across kinds. */\n  upsertHeterogeneousNodes?: (\n    this: void,\n    params: HeterogeneousNodeUpsertParams,\n  ) => Promise<readonly NodeRow[]>;\n  updateNodeSet?: (\n    this: void,\n    params: UpdateNodeSetParams,\n  ) => Promise<UpdateNodeSetResult>;\n  updateResolvedNodesBatch?: (\n    this: void,\n    params: ResolvedNodeUpdateBatchParams,\n  ) => Promise<readonly NodeRow[]>;\n  compareAndSetNode?: (\n    this: void,\n    params: CompareAndSetNodeParams,\n  ) => Promise<UpdateNodeSetResult>;\n  deleteNode: (this: void, params: DeleteNodeParams) => Promise<void>;\n  hardDeleteNode: (this: void, params: HardDeleteNodeParams) => Promise<void>;\n  getNode: (\n    this: void,\n    graphId: string,\n    kind: string,\n    id: string,\n  ) => Promise<NodeRow | undefined>;\n  getNodes?: (\n    this: void,\n    graphId: string,\n    kind: string,\n    ids: readonly string[],\n  ) => Promise<readonly NodeRow[]>;\n\n  // === Edge Operations ===\n  insertEdge: (this: void, params: InsertEdgeParams) => Promise<EdgeRow>;\n  /** Executes semantic authoritative graph commands. */\n  commands: GraphCommandPort;\n  insertEdgeNoReturn?: (this: void, params: InsertEdgeParams) => Promise<void>;\n  insertEdgesBatch?: (\n    this: void,\n    params: readonly InsertEdgeParams[],\n  ) => Promise<void>;\n  insertEdgesBatchReturning?: (\n    this: void,\n    params: readonly InsertEdgeParams[],\n  ) => Promise<readonly EdgeRow[]>;\n  updateEdge: (this: void, params: UpdateEdgeParams) => Promise<EdgeRow>;\n  deleteEdge: (this: void, params: DeleteEdgeParams) => Promise<void>;\n  hardDeleteEdge: (this: void, params: HardDeleteEdgeParams) => Promise<void>;\n  /**\n   * Batched {@link deleteEdge}: one soft-delete statement per bind-budget\n   * chunk instead of one per edge. Optional — cascade deletes fall back to\n   * the per-edge form when unset. Same per-row semantics, including an\n   * optional asserted kind and idempotence on already-tombstoned rows.\n   */\n  deleteEdgesBatch?: (\n    this: void,\n    params: DeleteEdgesBatchParams,\n  ) => Promise<void>;\n  /** Batched {@link hardDeleteEdge}; see {@link deleteEdgesBatch}. */\n  hardDeleteEdgesBatch?: (\n    this: void,\n    params: DeleteEdgesBatchParams,\n  ) => Promise<void>;\n  getEdge: (\n    this: void,\n    graphId: string,\n    id: string,\n  ) => Promise<EdgeRow | undefined>;\n  getEdges?: (\n    this: void,\n    graphId: string,\n    ids: readonly string[],\n  ) => Promise<readonly EdgeRow[]>;\n\n  // === Edge Cardinality Operations ===\n  countEdgesFrom: (this: void, params: CountEdgesFromParams) => Promise<number>;\n  edgeExistsBetween: (\n    this: void,\n    params: EdgeExistsBetweenParams,\n  ) => Promise<boolean>;\n\n  // === Edge Query Operations ===\n  findEdgesConnectedTo: (\n    this: void,\n    params: FindEdgesConnectedToParams,\n  ) => Promise<readonly EdgeRow[]>;\n\n  // === Collection Query Operations ===\n  findNodesByKind: (\n    this: void,\n    params: FindNodesByKindParams,\n  ) => Promise<readonly NodeRow[]>;\n  countNodesByKind: (\n    this: void,\n    params: CountNodesByKindParams,\n  ) => Promise<number>;\n  findEdgesByKind: (\n    this: void,\n    params: FindEdgesByKindParams,\n  ) => Promise<readonly EdgeRow[]>;\n  /**\n   * Reads the edges of a SET of endpoints in one statement per bind-budget\n   * chunk — see {@link FindEdgesByEndpointSetParams}.\n   *\n   * **Optional, and its absence is the capability signal.** `store.edges.<kind>\n   * .bulkFindFrom` / `.bulkFindTo` check for this method before issuing any\n   * read and refuse with a typed `ConfigurationError` when it is missing,\n   * rather than degrading to a per-endpoint loop. A caller reaching for a bulk\n   * endpoint read is asking for set-oriented statements; quietly giving them N\n   * singleton statements is the surprise the method exists to prevent.\n   *\n   * Both bundled Drizzle backends implement it. A custom backend that does not\n   * simply omits it and the bulk reads refuse; the singleton `findEdgesByKind`\n   * path is unaffected.\n   */\n  findEdgesByEndpointSet?: (\n    this: void,\n    params: FindEdgesByEndpointSetParams,\n  ) => Promise<readonly EdgeRow[]>;\n  /**\n   * Reads several edge kinds from a heterogeneous set of endpoints without\n   * issuing one statement per licensed `(edge kind, endpoint kind)` pair.\n   *\n   * Optional for custom backends. Store-level heterogeneous bulk reads refuse\n   * when it is absent rather than hiding a per-kind/per-endpoint fallback.\n   */\n  findEdgesByHeterogeneousEndpointSet?: (\n    this: void,\n    params: FindEdgesByHeterogeneousEndpointSetParams,\n  ) => Promise<readonly EdgeRow[]>;\n  countEdgesByKind: (\n    this: void,\n    params: CountEdgesByKindParams,\n  ) => Promise<number>;\n\n  // === Unique Constraint Operations ===\n  insertUnique: (this: void, params: InsertUniqueParams) => Promise<void>;\n  /**\n   * Batched variant of `insertUnique`: one multi-row statement per chunk\n   * with the same per-entry conflict semantics (throws `UniquenessError`\n   * for the first entry whose key a different live node holds). Optional —\n   * callers fall back to per-entry `insertUnique` when unset.\n   */\n  insertUniqueBatch?: (\n    this: void,\n    entries: readonly InsertUniqueParams[],\n  ) => Promise<void>;\n  deleteUnique: (this: void, params: DeleteUniqueParams) => Promise<void>;\n  /**\n   * Permanently removes every uniqueness sidecar owned by the specified\n   * concrete nodes. Optional capability used by set-based updates before they\n   * rebuild reservations from the returned node after-images.\n   */\n  hardDeleteUniquesByNodeIds?: (\n    this: void,\n    params: HardDeleteUniquesByNodeIdsParams,\n  ) => Promise<void>;\n  /**\n   * Permanently removes every uniqueness claim owned by nodes of one concrete\n   * kind, at whatever axis each claim sits on. THE definition of \"the claims\n   * this kind owns\" — kind removal reaps through it so it can neither leak a\n   * claim whose axis is a sibling kind nor delete a surviving sibling's claim.\n   * Optional capability.\n   */\n  hardDeleteUniquesByConcreteKind?: (\n    this: void,\n    params: HardDeleteUniquesByConcreteKindParams,\n  ) => Promise<void>;\n  checkUnique: (\n    this: void,\n    params: CheckUniqueParams,\n  ) => Promise<UniqueRow | undefined>;\n  checkUniqueBatch?: (\n    this: void,\n    params: CheckUniqueBatchParams,\n  ) => Promise<readonly UniqueRow[]>;\n\n  // === Edge Cardinality Claim Operations ===\n  /**\n   * Takes the claim on one edge cardinality axis, in two statements: a\n   * decision-free create-or-lock that reports the committed holder, and — only\n   * when that holder is a different edge — a conditional takeover that succeeds\n   * exactly when the incumbent is no longer an edge the axis and key describe.\n   *\n   * The claim is the FENCE for a declared cardinality: `(kind, from)` and\n   * `(kind, from, to)` are predicates the edges primary key `(graph_id, id)`\n   * cannot enforce, so without this relation two concurrent writers can both\n   * pass the probe and both commit. Read through the `constraintClaims`\n   * capability, never through member presence — see `claimSupport`\n   * (`store/claims/backing.ts`).\n   */\n  claimEdgeCardinality?: (\n    this: void,\n    params: ClaimEdgeCardinalityParams,\n  ) => Promise<EdgeClaimOutcome>;\n  /**\n   * Strong single-claim variant which, while holding the claim row, also\n   * refuses any claimless live edge that already matches the declared axis.\n   *\n   * Member presence is an explicit optimization contract: callers may omit\n   * the separate entity-relation cardinality probe only when the exact write\n   * target exposes this operation. Custom and legacy backends that implement\n   * only `claimEdgeCardinality` retain the probe-first path unchanged.\n   */\n  claimEdgeCardinalityGuarded?: (\n    this: void,\n    params: ClaimEdgeCardinalityParams,\n  ) => Promise<EdgeClaimOutcome>;\n  /**\n   * Batched variant of `claimEdgeCardinality`: one multi-row create-or-lock\n   * statement, then a takeover statement only for the entries a different edge\n   * holds. Outcomes are returned positionally, one per entry.\n   *\n   * Callers must not pass two entries with the same conflict target\n   * (`axis`, `key`): a multi-row upsert cannot affect one row twice.\n   */\n  claimEdgeCardinalityBatch?: (\n    this: void,\n    entries: readonly ClaimEdgeCardinalityParams[],\n  ) => Promise<readonly EdgeClaimOutcome[]>;\n  /**\n   * Housekeeping only: drops the claim rows named edges hold, so hard deletes,\n   * kind removal and `clearGraph` do not grow the relation without bound. The\n   * FENCE never depends on it having run — a claim whose holder is no longer\n   * live (or, for `oneActive`, no longer active) is taken over in place.\n   */\n  purgeEdgeClaims?: (\n    this: void,\n    params: PurgeEdgeClaimsParams,\n  ) => Promise<void>;\n\n  /**\n   * Read-only diagnostic: the rows that make a declared constraint currently\n   * violated, for a caller (`store.verifyConstraintFences()`) that folds them\n   * onto the claim axes they contend for.\n   *\n   * It reads the ENTITY relations for the two families whose pre-upgrade\n   * violations no claim row records — a database written before the claim\n   * relations existed holds no edge claims at all — and the `uniques` relation\n   * for uniqueness, where a pre-upgrade duplicate is exactly two live rows\n   * sitting at two different `node_kind`s. A scan of a claim relation's primary\n   * key can find neither, which is why this is not one.\n   *\n   * Returns the contending ROWS, not the verdict: the axis a `uniques` row\n   * belongs to is a fold over the graph's subclass component, and the key an\n   * edge's claim sits on is `EDGE_CARDINALITY_SPECS`' — both of which live\n   * above the backend, so a backend that decided either would be a second\n   * spelling of a decision the fence already owns.\n   *\n   * Writes nothing: no DDL, no claim writes. Safe on a replica and under a\n   * least-privilege role. Present only on backends that can run the audit;\n   * `store.verifyConstraintFences()` refuses with a typed error when absent\n   * rather than reporting an empty (and therefore reassuring) result.\n   */\n  readConstraintFenceViolations?: (\n    this: void,\n    params: ReadConstraintFenceViolationsParams,\n  ) => Promise<ConstraintFenceViolationRows>;\n\n  // === Schema Operations ===\n  getActiveSchema: (\n    this: void,\n    graphId: string,\n  ) => Promise<SchemaVersionRow | undefined>;\n  getSchemaVersion: (\n    this: void,\n    graphId: string,\n    version: number,\n  ) => Promise<SchemaVersionRow | undefined>;\n  /**\n   * Atomically inserts a new schema version and activates it as a single\n   * transactional unit, with optimistic compare-and-swap on the currently\n   * active version.\n   *\n   * - If `expected.kind === \"active\"` and the actual active version\n   *   differs, throws `StaleVersionError` (caller should refetch and\n   *   retry).\n   * - If a row already exists at `params.version` with the same\n   *   `schemaHash`, returns it idempotently — reactivating it if it was\n   *   left inactive by an earlier crashed commit.\n   * - If a row already exists at `params.version` with a different\n   *   `schemaHash`, throws `SchemaContentConflictError`.\n   *\n   * Requires `capabilities.execution.interactiveTransactions === true`. On non-transactional\n   * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n   * throws `ConfigurationError` rather than running with degraded\n   * atomicity that would silently re-introduce the orphan-row crash\n   * window the primitive exists to eliminate.\n   */\n  commitSchemaVersion: (\n    this: void,\n    params: CommitSchemaVersionParams,\n  ) => Promise<SchemaVersionRow>;\n  /**\n   * Commit a schema version only if every requested kind is empty. The probes\n   * and schema CAS run under one backend-owned write fence, preventing a\n   * participating schema-managed Store write from landing between the final\n   * count and commit. Raw Stores and direct backend writes are not fenced.\n   */\n  commitSchemaVersionIfKindsEmpty?: (\n    this: void,\n    params: CommitSchemaVersionParams,\n    probes: readonly SchemaKindEmptinessProbe[],\n  ) => Promise<CommitSchemaVersionIfKindsEmptyResult>;\n  /**\n   * Acquire the transaction-scoped shared fence for a schema-managed graph\n   * write, then verify that the active schema still matches the Store that is\n   * issuing it. Official transactional backends provide this method; custom\n   * backends may omit it, in which case schema-managed Store writes fail\n   * closed rather than racing a schema change. This method must be called on a\n   * transaction-scoped backend. PostgreSQL locks the active schema row, so a\n   * concurrent change either becomes visible at read committed or raises the\n   * database's native serialization failure at stronger isolation.\n   *\n   * On rejection the thrown `StaleVersionError` reports the active\n   * version this transaction can observe after the conflict resolves, so\n   * `details.actual` names the version that won rather than the absence the\n   * blocked read momentarily saw.\n   */\n  lockSchemaVersionForWrite?: (\n    this: void,\n    params: Readonly<{ graphId: string; expectedVersion: number }>,\n  ) => Promise<void>;\n  /**\n   * PostgreSQL/PGlite transaction-scoped fast path that takes the active\n   * schema `FOR SHARE` fence and the recorded graph advisory lock in one SQL\n   * statement, in that order. The graph-lock CTE is reachable only through a\n   * matching schema row, so a stale Store never acquires the later lock.\n   *\n   * Bundled PostgreSQL/PGlite transaction targets expose this member; their\n   * root backends omit it so it cannot be used outside an already-open\n   * transaction. SQLite/custom transaction backends omit it too. A zero-row\n   * fence runs the same honest active-version diagnostic as\n   * {@link GraphBackend.lockSchemaVersionForWrite} and throws its\n   * `StaleVersionError`.\n   */\n  lockSchemaVersionAndGraphWrite?: (\n    this: void,\n    params: SchemaWriteFenceParams,\n  ) => Promise<GraphCommandIsolation>;\n  /**\n   * Internal schema-lifecycle seam for features whose data preflight must\n   * commit atomically with the schema CAS. The callback runs in the same\n   * write transaction after the schema write fence is acquired and before the\n   * version write; it receives no schema-version write methods, so callers\n   * cannot bypass the CAS.\n   *\n   * The preflight target is a {@link SchemaCommitPreflightBackend}: the\n   * transaction backend plus the schema-write DDL primitive, because a\n   * transition may have to CREATE the storage its own preflight then fills —\n   * and creating it outside this transaction would publish it empty whenever\n   * the commit is refused.\n   *\n   * @internal\n   */\n  commitSchemaVersionWithPreflight?: (\n    this: void,\n    params: CommitSchemaVersionParams,\n    preflight: (target: SchemaCommitPreflightBackend) => Promise<void>,\n  ) => Promise<SchemaVersionRow>;\n  /**\n   * Atomically flips the active schema pointer to an existing version,\n   * with optimistic compare-and-swap on the currently active version.\n   * Used by `rollbackSchema` and any other \"promote/demote existing\n   * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n   * `MigrationError` if the target version row does not exist.\n   *\n   * Same transactional requirements as `commitSchemaVersion`.\n   */\n  setActiveVersion: (\n    this: void,\n    params: SetActiveVersionParams,\n  ) => Promise<void>;\n\n  /** Register an immutable materialized schema template. */\n  registerGraphTemplate?: (\n    this: void,\n    params: Readonly<{\n      templateId: string;\n      schemaHash: string;\n      schemaDoc: SerializedSchema;\n    }>,\n  ) => Promise<GraphTemplateRow>;\n  /**\n   * Instantiate a v1 schema from a registered template in one database\n   * statement. The caller supplies the hash of the graph-id-rebound document;\n   * the large schema document remains server-side.\n   */\n  instantiateGraphTemplate?: (\n    this: void,\n    params: Readonly<{\n      templateId: string;\n      templateSchemaHash: string;\n      graphId: string;\n      schemaHash: string;\n    }>,\n  ) => Promise<\n    | Readonly<{ status: \"ready\"; row: SchemaVersionRow }>\n    | Readonly<{ status: \"refused\" }>\n  >;\n\n  /**\n   * Run an administrative callback while holding the same per-graph lock as\n   * schema commits. The callback receives the transaction-scoped backend, so\n   * its reads, DML, and DDL are committed atomically before another schema\n   * writer can proceed.\n   *\n   * This is intentionally absent from {@link TransactionBackend}: nesting a\n   * schema-write lock from an already-open transaction can deadlock. It is an\n   * optional backend capability so custom backends can decline operations\n   * that require a schema fence rather than silently running them unsafely.\n   */\n  schemaWriteTransaction?: <T>(\n    this: void,\n    graphId: string,\n    fn: (\n      tx: TransactionBackend &\n        Readonly<{\n          executeStatement: NonNullable<TransactionBackend[\"executeStatement\"]>;\n          tableExists: (this: void, tableName: string) => Promise<boolean>;\n          executeSchemaDdl: (this: void, ddl: string) => Promise<void>;\n          deleteSchemaVectorSlotContribution: (\n            this: void,\n            slot: VectorSlot,\n          ) => Promise<void>;\n        }>,\n    ) => Promise<T>,\n  ) => Promise<T>;\n\n  // === Embedding Operations (optional - depends on vector capabilities) ===\n  upsertEmbedding?: (\n    this: void,\n    params: UpsertEmbeddingParams,\n  ) => Promise<void>;\n  /**\n   * Batched variant of `upsertEmbedding` for one vector slot. Optional —\n   * callers fall back to per-row `upsertEmbedding` when unset.\n   */\n  upsertEmbeddingBatch?: (\n    this: void,\n    params: UpsertEmbeddingBatchParams,\n  ) => Promise<void>;\n  deleteEmbedding?: (\n    this: void,\n    params: DeleteEmbeddingParams,\n  ) => Promise<void>;\n  deleteEmbeddingBatch?: (\n    this: void,\n    params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n      Readonly<{ nodeIds: readonly string[] }>,\n  ) => Promise<void>;\n  /**\n   * KNN search over one `(nodeKind, fieldPath)` slot. Top-k is computed\n   * over CURRENT nodes only — non-tombstoned AND inside their validity\n   * window, matching a `current` read — so index drift (embedding rows\n   * whose node was deleted or expired outside the store pipeline) can\n   * neither surface nor crowd current rows out of the top-k. Custom\n   * backends implementing this member must honor the same contract. Exact on pgvector >= 0.8 (HNSW via\n   * `hnsw.iterative_scan = strict_order`; IVFFlat via\n   * `ivfflat.iterative_scan = relaxed_order` plus a re-sort of the\n   * bounded set; probe-bounded below 0.8) and sqlite-vec;\n   * libSQL's DiskANN over-fetches 4x and post-filters (recall bounded by\n   * that headroom).\n   */\n  vectorSearch?: (\n    this: void,\n    params: VectorSearchParams,\n  ) => Promise<readonly VectorSearchResult[]>;\n  createVectorIndex?: (\n    this: void,\n    params: CreateVectorIndexParams,\n  ) => Promise<void>;\n  dropVectorIndex?: (\n    this: void,\n    params: DropVectorIndexParams,\n  ) => Promise<void>;\n  /**\n   * Single-statement hybrid search: both sources, RRF fusion, liveness\n   * join, and node hydration composed into ONE statement — replacing the\n   * facade's two search round trips plus id-hydration fetch. Optional;\n   * the store falls back to the multi-statement path when unset (custom\n   * backends, engines without window functions). Same liveness contract\n   * as `vectorSearch` / `fulltextSearch`.\n   */\n  hybridSearch?: (\n    this: void,\n    params: HybridSearchParams,\n  ) => Promise<readonly HybridSearchRow[]>;\n\n  // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n  upsertFulltext?: (this: void, params: UpsertFulltextParams) => Promise<void>;\n  deleteFulltext?: (this: void, params: DeleteFulltextParams) => Promise<void>;\n  /**\n   * Batched variant of `upsertFulltext`. Optional — callers fall back to\n   * per-row `upsertFulltext` when unset.\n   */\n  upsertFulltextBatch?: (\n    this: void,\n    params: UpsertFulltextBatchParams,\n  ) => Promise<void>;\n  /**\n   * Batched variant of `deleteFulltext`. Optional — callers fall back to\n   * per-row `deleteFulltext` when unset.\n   */\n  deleteFulltextBatch?: (\n    this: void,\n    params: DeleteFulltextBatchParams,\n  ) => Promise<void>;\n  /**\n   * Ranked fulltext search over one node kind. Like `vectorSearch`, top-k\n   * is computed over CURRENT nodes only — non-tombstoned AND inside their\n   * validity window (exact on both engines — plain WHERE, no top-k table\n   * function involved). Custom backends implementing this member must\n   * honor the same contract.\n   */\n  fulltextSearch?: (\n    this: void,\n    params: FulltextSearchParams,\n  ) => Promise<readonly FulltextSearchResult[]>;\n\n  // === Index Materialization (used by store.materializeIndexes) ===\n  /**\n   * Idempotently ensure ONLY the `typegraph_index_materializations`\n   * table exists — separate from `bootstrapTables` so that\n   * `materializeIndexes` doesn't pull in the full base-table DDL set\n   * just to access the status table.\n   *\n   * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n   * INDEX IF NOT EXISTS` statements covering every base table. Two\n   * concurrent calls (e.g. two replicas of the same `schema_doc` both\n   * starting up and calling `materializeIndexes`) race on\n   * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n   * the single status table eliminates the cross-table race entirely\n   * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n   * is well-behaved on Postgres.\n   */\n  ensureIndexMaterializationsTable?: (this: void) => Promise<void>;\n\n  /**\n   * Install the PostgreSQL `pg_trgm` extension under a database-global\n   * concurrency fence. Relational trigram index materialization calls this\n   * before emitting its index DDL; non-PostgreSQL backends omit it.\n   *\n   * @deprecated The `pg_trgm`-only spelling of {@link GraphBackend.ensureExtension},\n   *   which says the same thing for every extension the library installs. It is\n   *   retained — and still consulted, after `ensureExtension` — so a backend\n   *   written against 0.47 keeps its fence; the bundled PostgreSQL backend\n   *   implements it by delegating. Implement `ensureExtension` in new backends.\n   */\n  ensureTrigramExtension?: (this: void) => Promise<void>;\n\n  /**\n   * Idempotently ensure ONLY the `typegraph_revision_origins` table exists.\n   *\n   * Revision-tracked stores use this per-graph, durable random origin together\n   * with the recorded clock to prevent two independent stores with coincident\n   * timestamps from sharing a merge base anchor. It is focused rather than\n   * using `bootstrapTables` so existing deployments can adopt revision anchors\n   * without replaying all base-table DDL during a merge read.\n   */\n  ensureRevisionOriginsTable?: (this: void) => Promise<void>;\n\n  /**\n   * Idempotently add the durable edge-match identity columns, pair constraint,\n   * and unique index to the configured edge relation.\n   *\n   * Every edge write names these nullable columns, even when its graph does\n   * not declare `matchIdentity`. Privileged schema preparation therefore calls\n   * this focused hook on every open so pre-provisioned base tables adopt newer\n   * physical storage without replaying the complete base-table DDL set.\n   * Ordinary runtime store construction never performs DDL.\n   *\n   * @internal\n   */\n  ensureEdgeMatchIdentityStorage?: (this: void) => Promise<void>;\n\n  /**\n   * Idempotently ensure ONLY the three Operational Identity relations exist —\n   * the current-assertions table, the recorded-time assertions table, and the\n   * derived closure and separation tables — with their indexes and CHECK\n   * constraints (CREATE TABLE / CREATE INDEX IF NOT EXISTS).\n   *\n   * First enablement of identity on an existing populated deployment attaches\n   * via `createStore` / `createSqliteBackend` / `createPostgresBackend`, none\n   * of which run DDL, so the enablement preflight would otherwise\n   * SELECT/DELETE/INSERT tables that do not exist yet. The store calls this\n   * before the enablement locks and closure rebuild. Focused rather than\n   * `bootstrapTables` for the same concurrency rationale as\n   * {@link ensureRevisionOriginsTable}. Stores call it before opening the\n   * schema-commit transaction so DDL does not re-enter its per-graph lock.\n   * Returns the logical names that were absent before this call. Callers set\n   * `provisionMissing` only for safe first enablement; on an already-enabled\n   * graph, missing ledger tables are deliberately left absent so a failed open\n   * cannot make its next retry silently accept empty replacement storage.\n   *\n   * @internal\n   */\n  ensureIdentityTables?: (\n    this: void,\n    tableNames: IdentityTableNames,\n    options: Readonly<{ provisionMissing: boolean }>,\n  ) => Promise<readonly string[]>;\n\n  /**\n   * The idempotent CREATE statements for exactly the identity relations —\n   * the same DDL {@link ensureIdentityTables} issues, handed back as data\n   * instead of executed.\n   *\n   * Pure and synchronous: it executes nothing and probes no catalog, so it is\n   * safe to call from inside an already-open transaction, where invoking a\n   * top-level backend method would re-enter the backend's serialized statement\n   * queue and deadlock. That is the whole point. Provisioning a missing DERIVED\n   * relation (closure, separation) on an already-enabled graph has to CREATE it\n   * and FILL it in one transaction, because a created-but-empty derived\n   * relation is readable and answers every question with \"nothing\" — for the\n   * separation relation, \"nothing\" means \"not separated\", which is exactly the\n   * answer that lets a contradictory merge commit.\n   *\n   * A backend that omits this cannot offer that atomicity. Callers do not fall\n   * back: when a fill is owed, the upgrade is REFUSED with the typed\n   * `IDENTITY_UPGRADE_REQUIRES_ATOMIC_DDL` error naming this port — creating\n   * and filling back-to-back would publish the readable-empty state the\n   * paragraph above forbids.\n   *\n   * @internal\n   */\n  identityTableDdl?: (\n    this: void,\n    tableNames: IdentityTableNames,\n  ) => readonly string[];\n\n  /**\n   * The provisioning DDL for the three recorded relations under the given\n   * physical names, keyed by logical relation. Used only by the offline legacy\n   * preview-schema migration, which builds temp tables, copies, and swaps —\n   * so it is called TWICE per migration, once per name set, and the migration\n   * (not the backend) composes the temp `createTable` with the final `indexes`.\n   *\n   * A backend that omits this cannot be migrated FROM the timestamp-only\n   * preview schema — a schema only the bundled Drizzle backends ever created.\n   * `migrateLegacyRecordedTime` REFUSES with `UnsupportedBackendCapabilityError`\n   * naming this port rather than emitting DDL it cannot author.\n   *\n   * @internal\n   */\n  recordedTableDdl?: (\n    this: void,\n    tableNames: RecordedTableNames,\n  ) => Readonly<Record<keyof RecordedTableNames, RecordedRelationDdl>>;\n\n  /**\n   * Look up a recorded materialization for a declared index by its\n   * physical SQL index name. Returns `undefined` if no row exists.\n   */\n  getIndexMaterialization?: (\n    this: void,\n    indexName: string,\n  ) => Promise<IndexMaterializationRow | undefined>;\n  /**\n   * Bulk variant of `getIndexMaterialization`: load every recorded\n   * materialization whose `indexName` (status key) is in `statusKeys`,\n   * in a single round-trip. Returned rows are unordered — callers index\n   * by `indexName`. Optional; consumers fall back to per-key\n   * `getIndexMaterialization` when unset.\n   */\n  getIndexMaterializations?: (\n    this: void,\n    statusKeys: readonly string[],\n  ) => Promise<readonly IndexMaterializationRow[]>;\n  /**\n   * Upsert a materialization attempt — success or failure. Failure rows\n   * preserve any prior `materializedAt` so the historical successful\n   * timestamp survives across error windows.\n   */\n  recordIndexMaterialization?: (\n    this: void,\n    params: RecordIndexMaterializationParams,\n  ) => Promise<void>;\n  /**\n   * Atomically claims the build of one index across every materializer\n   * (process- and pool-safe: the status row's own atomicity is the mutex).\n   * Returns true when this caller now holds the claim. Backends whose\n   * index builds cannot deadlock across callers (SQLite: engine-level\n   * write serialization, no CONCURRENTLY) omit it; `materializeIndexes`\n   * then builds without a claim, exactly as before.\n   */\n  claimIndexMaterialization?: (\n    this: void,\n    params: ClaimIndexMaterializationParams,\n  ) => Promise<boolean>;\n  /** Releases a claim taken by `claimIndexMaterialization` (token-guarded). */\n  releaseIndexMaterializationClaim?: (\n    this: void,\n    params: ReleaseIndexMaterializationClaimParams,\n  ) => Promise<void>;\n\n  /**\n   * Physical-schema introspection: table/index presence, PostgreSQL's\n   * invalid-index leftover state, and normalized column types. Present on\n   * both bundled Drizzle backends; a custom backend that omits it loses the\n   * store paths that consult it directly: index materialization\n   * (`store.materializeIndexes()` refuses only once its empty-candidate\n   * short circuit and the status-table ensure step have already run;\n   * `store.materializeSystemIndexes()`, which has no candidate short\n   * circuit, refuses only once that same status-table ensure step has\n   * run), the recorded-time schema check, and the recorded-time\n   * migration's column read.\n   */\n  catalog?: BackendCatalogProbes | undefined;\n\n  /**\n   * The engine's whole-database revision and the per-graph change delta\n   * since an earlier one. Present only when a backend's engine declares it\n   * (`EngineProvisioning.lineage`) — absent by default on a custom backend\n   * that supplies none, and absent on both bundled Drizzle profiles\n   * regardless of `history`. A history-enabled store never populates this\n   * member itself: it always resolves its lineage from its own recorded\n   * relations instead (`resolveLineage` in\n   * `store/recorded-capture/lineage.ts`), never from this member. Every\n   * consumer falls back to a full comparison when this is absent — see\n   * `requireLineage` in `backend/capabilities/lineage.ts`.\n   */\n  lineage?: LineageMembers | undefined;\n\n  /**\n   * The engine's own recorded (system-time) read source and revision clock.\n   * Present only when a backend's engine declares it\n   * (`EngineProvisioning.recordedTime`) — absent by default on a custom\n   * backend that supplies none, and absent on both bundled Drizzle profiles,\n   * which always allocate TypeGraph's own recorded clock and relations\n   * instead. Declaring this member is what makes a backend engine-native for\n   * recorded time — see `resolveRecordedTimeOwnership` in\n   * `backend/capabilities/recorded-time-ownership.ts`, the one reader of\n   * that distinction. A backend that supplies `recordedTime` must also\n   * supply `lineage`: engine-native history keeps no recorded relations of\n   * its own to derive a change delta from, so `createSqlBackend` refuses a\n   * profile that declares one without the other.\n   */\n  recordedTime?: EngineRecordedTimeMembers | undefined;\n\n  // === Contribution Materialization (#135 — durable strategy-owned\n  // storage marker, sibling of the index status table) ===\n\n  /**\n   * Idempotently ensure ONLY the\n   * `typegraph_contribution_materializations` table exists. Same\n   * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n   * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n   * replica startup, where the full `bootstrapTables` set risks a\n   * Postgres SHARE-lock deadlock.\n   */\n  ensureContributionMaterializationsTable?: (this: void) => Promise<void>;\n\n  /**\n   * Look up the durable materialization marker for one strategy-owned\n   * contribution identity. Returns `undefined` when no row exists\n   * (\"never initialized\").\n   */\n  getContributionMaterialization?: (\n    this: void,\n    identity: ContributionMaterializationIdentity,\n  ) => Promise<ContributionMaterializationRow | undefined>;\n\n  /**\n   * Upsert a contribution-materialization attempt — success or failure.\n   * Failure rows preserve any prior `materializedAt` via COALESCE so a\n   * later failed re-attempt doesn't erase the historical success.\n   */\n  recordContributionMaterialization?: (\n    this: void,\n    params: RecordContributionMaterializationParams,\n  ) => Promise<void>;\n\n  /**\n   * Resolve (once per backend instance, cached) and assert the durable\n   * materialization markers for every `runtimeEnsure` contribution this\n   * backend's strategy declares, for `graphId`. Throws\n   * `StoreNotInitializedError` when a marker is missing, stale\n   * (signature drift), or recorded a failed last attempt.\n   *\n   * This is the single read-side gate the fulltext hot-path wrappers\n   * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n   * marker writes — initialization is the exclusive job of the async\n   * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n   */\n  assertRuntimeContributionsInitialized?: (\n    this: void,\n    graphId: string,\n  ) => Promise<void>;\n\n  // === Kind Removal Status ===\n\n  /**\n   * Bootstraps the per-deployment `typegraph_kind_removals` table so\n   * `store.evolve()` can check pending removals and the removal verbs can\n   * persist and materialize removal status. Mirrors the focused-bootstrap\n   * rationale documented on `ensureIndexMaterializationsTable` — the full\n   * `bootstrapTables` touches every base table and risks Postgres SHARE-lock\n   * deadlock under concurrent replica startup.\n   */\n  ensureKindRemovalsTable?: (this: void) => Promise<void>;\n\n  /**\n   * List graph-extension kind removals whose data-cleanup pass has not yet\n   * succeeded for this `graphId`. Returns rows with\n   * `removedAt: undefined`. Order is unspecified; callers materialize\n   * one-at-a-time and don't depend on it.\n   */\n  getPendingKindRemovals?: (\n    this: void,\n    graphId: string,\n  ) => Promise<readonly KindRemovalRow[]>;\n\n  /**\n   * List ALL kind-removal rows for a `graphId` — pending and completed.\n   * Used by `materializeRemovals()` reconciliation to detect rows that\n   * are missing entirely (the `removeKinds()` crash window) versus\n   * already completed. Without this distinction the reconciler would\n   * have to upsert every expected historical removal on every call,\n   * churning `last_attempted_at` on rows that long since succeeded.\n   * Order is unspecified.\n   */\n  getAllKindRemovals?: (\n    this: void,\n    graphId: string,\n  ) => Promise<readonly KindRemovalRow[]>;\n\n  /**\n   * Upsert a kind-removal status row. `removedAt: undefined` records\n   * the pending state at schema-commit time; `removedAt: <iso>`\n   * marks the data cleanup successful. The COALESCE rule on `removedAt`\n   * mirrors `recordIndexMaterialization` so a later failure doesn't\n   * clobber the historical successful timestamp from another replica.\n   */\n  recordKindRemoval?: (\n    this: void,\n    params: RecordKindRemovalParams,\n  ) => Promise<void>;\n\n  // === Reconciliation Watermark ===\n\n  /**\n   * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n   * table so `materializeRemovals()` can persist reconciliation\n   * progress. Same focused-bootstrap rationale as the other status\n   * tables — full `bootstrapTables` risks Postgres SHARE-lock\n   * deadlock under concurrent replica startup.\n   */\n  ensureReconciliationMarkersTable?: (this: void) => Promise<void>;\n\n  // === Table Contributions (#129) ===\n\n  /**\n   * Materializes every contribution flagged `runtimeEnsure` — the\n   * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n   * managed setups don't create. Called once after a successful schema\n   * load. Deliberately scoped: base/drizzle-visible tables are\n   * `runtimeEnsure: false`, so this does not regress startup into\n   * broad DDL/probing across every table.\n   *\n   * The canonical durable-marker writer (#135): for each runtime\n   * contribution it short-circuits when the marker already records a\n   * matching signature, otherwise runs the idempotent `createDdl` and\n   * records the marker (success or failure) keyed by `graphId`.\n   */\n  ensureRuntimeContributions?: (this: void, graphId: string) => Promise<void>;\n\n  /**\n   * Privileged materializer for one embedding `(kind, field)` slot's\n   * `ownedTables` contribution(s): creates the per-field vector table and\n   * records its durable marker, idempotently. The vector counterpart of\n   * `ensureRuntimeContributions` — vectors are per-`(kind, field)` and\n   * graph-derived, so the store enumerates slots (via\n   * `resolveEmbeddingFields`) and uses the batch counterpart at boot under\n   * the privileged role. Pass `{ force: true }` to overwrite the marker\n   * at the current signature, bypassing the drift-guard — the sanctioned\n   * path `store.reembedVectorField()` uses after recreating storage at a\n   * new dimension. Pass `{ onDrift: \"skip\" }` to leave an\n   * already-provisioned slot whose shape has since changed untouched\n   * (warn + no-op) instead of refusing — the boot/evolve path, so a\n   * declared dimension change never blocks startup before the operator\n   * can run `reembedVectorField`. Present only on backends wired with a\n   * vector strategy.\n   */\n  ensureVectorSlotContribution?: (\n    this: void,\n    slot: VectorSlot,\n    options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n  ) => Promise<void>;\n\n  /**\n   * Batch form of `ensureVectorSlotContribution`, used by privileged boot to\n   * resolve every slot's durable markers with one graph-scoped query. The\n   * singular method remains available for re-embedding and compatibility.\n   */\n  ensureVectorSlotContributions?: (\n    this: void,\n    slots: readonly VectorSlot[],\n    options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n  ) => Promise<void>;\n\n  /**\n   * SELECT-only gate for one embedding `(kind, field)` slot: asserts the\n   * durable marker(s) for the slot's `ownedTables` contribution(s),\n   * cached per backend instance. Throws `StoreNotInitializedError` when\n   * the slot is missing, stale (signature drift), or recorded a failed\n   * last attempt. The vector counterpart of\n   * `assertRuntimeContributionsInitialized`, consulted by the verified\n   * runtime attach. Performs ZERO DDL and ZERO writes. Present only on\n   * backends wired with a vector strategy.\n   */\n  assertVectorSlotInitialized?: (this: void, slot: VectorSlot) => Promise<void>;\n\n  /**\n   * Batch form of `assertVectorSlotInitialized`, used by verified attach to\n   * resolve every slot's durable markers with one graph-scoped query.\n   */\n  assertVectorSlotsInitialized?: (\n    this: void,\n    slots: readonly VectorSlot[],\n  ) => Promise<void>;\n\n  /**\n   * Forget one embedding `(kind, field)` slot's durable contribution\n   * marker(s). Called after the slot's per-field table is dropped\n   * (vector-field reclaim) so a later `ensureVectorSlotContribution`\n   * re-creates the table instead of trusting an orphaned \"initialized\"\n   * marker. Does NOT drop the table itself (the caller already did).\n   * Present only on backends wired with a vector strategy.\n   */\n  deleteVectorSlotContribution?: (\n    this: void,\n    slot: VectorSlot,\n  ) => Promise<void>;\n\n  /**\n   * Diagnostic: compare each contribution currently expected for `graphId`\n   * against its durable marker and the physical catalog.\n   *\n   * Covers the strategy-owned `runtimeEnsure` contributions (fulltext)\n   * plus the `ownedTables` contribution(s) of each supplied vector slot.\n   * Returns one {@link ContributionDiagnostic} per detected unusable\n   * contribution. A recorded failed materialization is unusable even when\n   * marker and catalog agree that no table was produced. A contribution with\n   * neither a marker nor a table is treated as never attempted and omitted;\n   * marker rows outside the current declaration set are not audited. An empty\n   * array therefore is not proof that storage was initialized.\n   *\n   * Deliberately NOT part of the open path. `ensureRuntimeContributions`\n   * and `assertRuntimeContributionsInitialized` short-circuit on a\n   * per-instance signature cache and then on the marker row alone, which\n   * is the right default for a hot path but leaves a database whose\n   * contribution tables were dropped out of band opening clean and\n   * failing at the first dependent read or write. This method is the explicit,\n   * operator-invoked catalog probe that fills that gap: it issues one uncached\n   * existence query per distinct physical table and performs ZERO DDL\n   * and ZERO writes, so it is safe under a least-privilege runtime role.\n   *\n   * Present only on backends that can probe their own catalog.\n   */\n  verifyContributions?: (\n    this: void,\n    graphId: string,\n    vectorSlots: readonly VectorSlot[],\n  ) => Promise<readonly ContributionDiagnostic[]>;\n\n  /**\n   * Re-audit current contribution declarations and non-destructively repair\n   * `missing-marker` and `failed-materialization` findings. The backend must\n   * resolve every target itself; it must not accept caller-provided physical\n   * identities or DDL. `stale` and `orphaned-marker` findings are returned as\n   * `requires-rebuild` because repairing either can require destructive data\n   * reconstruction.\n   *\n   * Present only on backends that can both probe their catalog and run the\n   * strategy-owned contribution DDL.\n   */\n  repairContributions?: (\n    this: void,\n    graphId: string,\n    vectorSlots: readonly VectorSlot[],\n  ) => Promise<ContributionRepairResult>;\n\n  /**\n   * Read-only readiness probe: the same marker-versus-catalog audit\n   * `verifyContributions` performs, projected onto one entry per search\n   * projection. Shares that method's detection logic exactly — a second\n   * implementation would be free to disagree with the one the hot-path\n   * gate actually consults, and a health check that disagrees with the\n   * gate is worse than none.\n   *\n   * Writes nothing: no DDL, no marker writes, no effect on the\n   * per-instance caches the hot path relies on. Safe on a read path, on\n   * a replica, and under a least-privilege role.\n   *\n   * Present only on backends that can probe their catalog; a backend\n   * that provisions contributions without this method declares the gap\n   * as `capabilities.contributions.probe === false`.\n   */\n  probeContributions?: (\n    this: void,\n    graphId: string,\n    vectorSlots: readonly VectorSlot[],\n  ) => Promise<readonly ContributionProbeEntry[]>;\n\n  /**\n   * Destructively rebuild one search projection for one graph: clear that\n   * graph's rows from the projection's storage, ensure the storage matches\n   * the current `createDdl`, reconstruct the graph's content, and stamp the\n   * durable marker at the current signature.\n   *\n   * This is the repair `repairContributions` deliberately refuses to\n   * perform, and it must never be reachable from it. A `stale`\n   * contribution's table exists at the *old* physical shape, so the\n   * idempotent `CREATE ... IF NOT EXISTS` in the ordinary ensure path\n   * no-ops; re-stamping the marker there would leave it blessing a table\n   * whose shape is wrong, which is exactly what the drift guard exists\n   * to prevent. Only a drop makes the recreate meaningful, and destroying\n   * content is a decision the caller states rather than one a flag named\n   * `force` implies.\n   *\n   * The fulltext projection's storage is one physical table shared by every\n   * graph in the database, while this call is fenced per graph.\n   * Implementations must therefore scope the teardown to `graphId` and may\n   * drop the storage only when doing so destroys no other graph's rows;\n   * when the recorded shape is stale and the drop that would repair it is\n   * not available, they refuse (`shared-storage-in-use`) rather than\n   * re-stamp a shape nothing verified.\n   *\n   * Runs the whole sequence inside one transaction under the same\n   * per-graph fence as a schema commit, so an interrupted rebuild leaves\n   * the contribution exactly as it was rather than attested-but-empty.\n   *\n   * `repopulate` receives that transaction and reconstructs content from\n   * rows TypeGraph already stores. The inversion exists because deciding\n   * *what* content a node contributes needs the schema registry, which\n   * is a Store-layer concern the backend must not reach into.\n   *\n   * @param scope which projection to rebuild. Implementations must\n   *   refuse `\"vector\"`: embeddings live only in the storage this would\n   *   drop, so there is nothing to reconstruct them from.\n   */\n  rebuildContribution?: (\n    this: void,\n    graphId: string,\n    scope: ContributionRebuildScope,\n    repopulate: (\n      target: TransactionBackend,\n    ) => Promise<ContributionRepopulationStats>,\n  ) => Promise<ContributionRebuildResult>;\n\n  /**\n   * Bootstraps the fulltext storage table the active `FulltextStrategy`\n   * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n   * methods: idempotent and concurrency-safe under replica startup.\n   *\n   * Superseded by `ensureRuntimeContributions()` (#129); retained as\n   * a thin back-compat wrapper for backends/callers predating #129. Not\n   * machine-`@deprecated` because the manager still calls it as the\n   * pre-#129 fallback. #135 removed the remaining hot-path callers and\n   * routed this through the durable-marker writer.\n   */\n  ensureFulltextTable?: (this: void, graphId: string) => Promise<void>;\n\n  /**\n   * Read the high-water mark schema version for which\n   * `materializeRemovals` reconciliation has already verified history\n   * for `graphId`. Returns `undefined` when no marker has been\n   * recorded yet. Used to skip already-checked transitions in the\n   * recovery walk.\n   */\n  getReconciliationMarker?: (\n    this: void,\n    graphId: string,\n  ) => Promise<number | undefined>;\n\n  /**\n   * Persist the reconciliation high-water mark for `graphId`. Called\n   * after `materializeRemovals` completes a clean walk; subsequent\n   * calls walk only versions newer than this marker. Idempotent\n   * upsert by `graphId`.\n   */\n  setReconciliationMarker?: (\n    this: void,\n    graphId: string,\n    version: number,\n  ) => Promise<void>;\n\n  // === Graph Lifecycle ===\n  /**\n   * Adopts deployment-wide base relations to the physical schema required by\n   * this library version and stamps the singleton installation marker.\n   * Privileged schema-management entry points call this; ordinary raw Store\n   * construction never does.\n   *\n   * @internal\n   */\n  adoptBaseSchema?: (this: void) => Promise<void>;\n\n  /**\n   * SELECT-only sibling of {@link GraphBackend.adoptBaseSchema}. Throws a\n   * typed base-schema migration error when privileged adoption has not run.\n   * Least-privilege verified/template entry points call this before DML.\n   *\n   * @internal\n   */\n  assertBaseSchemaCurrent?: (this: void) => Promise<void>;\n\n  /**\n   * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n   * Intended for import-replacement workflows. No hooks, no per-row logic.\n   */\n  clearGraph: (this: void, graphId: string) => Promise<void>;\n\n  /**\n   * Creates the base TypeGraph tables if they don't already exist.\n   *\n   * Called automatically by `createStoreWithSchema()` when a fresh database\n   * is detected. Users who manage DDL themselves via `createStore()` never\n   * hit this path.\n   */\n  bootstrapTables?: (this: void) => Promise<void>;\n\n  /**\n   * Refreshes the backend's query-planner statistics.\n   *\n   * Call this once after a large initial import or bulk backfill. Without\n   * up-to-date statistics, the planner can pick suboptimal execution plans\n   * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n   * forward traversal; on SQLite it's the difference between 0.9ms and\n   * 23ms fulltext search. Autovacuum / background statistics collection\n   * will catch up eventually, but calling this explicitly after a bulk\n   * load gives you correct latencies immediately.\n   *\n   * Implementations:\n   * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n   * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n   *\n   * Safe to call at any time; costs a few tens of milliseconds on the\n   * sizes this library is designed for.\n   */\n  refreshStatistics: (this: void) => Promise<void>;\n\n  /**\n   * Runs an intentionally trusted, all-or-nothing initial import.\n   *\n   * Optional because only backends that can pin one transaction and use a\n   * native high-throughput write path expose it. Implementations must reject\n   * a database whose TypeGraph node or edge tables already contain rows. They\n   * may temporarily remove rebuildable secondary indexes, but must restore\n   * them before committing. Any callback, insert, or rebuild failure rolls the\n   * entire operation back.\n   *\n   * This is a top-level-only lifecycle operation and is deliberately absent\n   * from {@link TransactionBackend}. When `schemaWrite` is supplied, the\n   * import acquires and validates that Store version's managed-write fence\n   * before checking emptiness or writing. Omitting it retains the raw,\n   * unversioned import behavior.\n   */\n  trustedImport?: <T>(\n    this: void,\n    fn: (session: TrustedImportSession) => Promise<T>,\n    options?: Readonly<{\n      schemaWrite?: Readonly<{ graphId: string; expectedVersion: number }>;\n    }>,\n  ) => Promise<T>;\n\n  // === Query Execution ===\n  execute: <T>(this: void, query: CompiledRowsSql) => Promise<readonly T[]>;\n\n  /**\n   * Execute a non-row-returning SQL statement bound to this backend or\n   * transaction. Optional because custom backends may only expose the public\n   * row-returning query path; features that need statement execution must\n   * capability-check and fail loudly.\n   */\n  executeStatement?: (this: void, query: CompiledStatementSql) => Promise<void>;\n\n  /**\n   * Execute an internally compiled statement against connection-local\n   * temporary state. History wrappers preserve this path because it cannot\n   * mutate graph or history tables; callers cannot construct its branded\n   * input through the public API.\n   */\n  executeTemporaryStatement?: (\n    this: void,\n    query: CompiledTemporaryStatementSql,\n  ) => Promise<void>;\n\n  /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n  executeRaw?: <T>(\n    this: void,\n    sqlText: string,\n    params: readonly unknown[],\n  ) => Promise<readonly T[]>;\n\n  /** Compile a TypeGraph `SqlFragment` to `{ sql, params }` without executing. */\n  compileSql?: (\n    this: void,\n    query: SqlFragment,\n  ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n  /**\n   * Execute a DDL statement that returns no rows (CREATE INDEX,\n   * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n   * because some drivers (better-sqlite3) require `.run()` for DDL\n   * and `.all()` for queries — the ambiguity can't be resolved by\n   * inspecting the SQL string portably.\n   *\n   * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n   * cannot run inside a transaction. Implementations must execute the\n   * statement outside `transaction(...)`.\n   */\n  executeDdl?: (this: void, ddl: string) => Promise<void>;\n\n  /**\n   * Installs a database-global extension idempotently, tolerating the\n   * concurrent-install race.\n   *\n   * `CREATE EXTENSION IF NOT EXISTS` is not a concurrency primitive on\n   * PostgreSQL: the existence check cannot see another session's uncommitted\n   * `pg_extension` row, so the loser of a race waits for the winner and is\n   * then handed SQLSTATE 23505 instead of the harmless \"already exists\"\n   * notice (#446). A backend implementing this member owns that retry, and\n   * may additionally serialize same-extension installers behind a fence of its\n   * own (the bundled PostgreSQL backend takes a transaction advisory lock\n   * keyed on the extension, #475).\n   *\n   * This is the one member the library asks for an extension install; it\n   * supersedes {@link GraphBackend.ensureTrigramExtension}, which said the same\n   * thing for one extension.\n   *\n   * Like `executeDdl`, implementations MUST run the statement at the\n   * top-level backend, never inside `transaction(...)`: the 23505 aborts the\n   * enclosing transaction, so a retry issued inside one would only collect\n   * `25P02` on the way out. That is why this member is absent from\n   * {@link TransactionBackend}.\n   */\n  ensureExtension?: (this: void, name: DatabaseExtensionName) => Promise<void>;\n\n  // === Transaction ===\n  /** Runs TypeGraph operations inside a backend-owned transaction. */\n  transaction: <T>(\n    this: void,\n    fn: (tx: TransactionBackend) => Promise<T>,\n    options?: TransactionOptions,\n  ) => Promise<T>;\n\n  // === Lifecycle ===\n  close: (this: void) => Promise<void>;\n}> &\n  DurableEdgeBatchMembers;\n\n/** Policy for provisioning physical schema inside a caller-owned transaction. */\nexport type SchemaProvisioning = \"dml-only\" | \"transactional\";\n\n/**\n * Adapter-native transaction interoperability layered on top of the portable\n * TypeGraph backend. Only adapter entrypoints expose this capability.\n */\nexport type AdapterBackend<TNativeTransaction> = GraphBackend &\n  Readonly<{\n    /** Whether caller-owned schema transactions may provision physical storage. */\n    schemaProvisioning: SchemaProvisioning;\n    /**\n     * Runs TypeGraph operations and exposes the exact adapter-native handle\n     * bound to the same transaction.\n     */\n    transactionWithNative: <T>(\n      this: void,\n      fn: (\n        tx: TransactionBackend,\n        nativeTransaction: TNativeTransaction,\n      ) => Promise<T>,\n      options?: TransactionOptions,\n    ) => Promise<T>;\n    /** Adopts a caller-owned, already-open adapter transaction. */\n    adoptTransaction: (\n      this: void,\n      externalTransaction: TNativeTransaction,\n    ) => TransactionBackend;\n    /**\n     * Adopt a caller-owned native transaction for a schema change. The adapter\n     * proves the transaction is active and acquires its schema-write fence on\n     * that literal session before returning the privileged CAS target. It\n     * never opens, commits, retries, or rolls back the caller's transaction.\n     * Optional because drivers without active-session evidence must refuse.\n     */\n    adoptSchemaWriteTransaction?: (\n      this: void,\n      externalTransaction: TNativeTransaction,\n      graphId: string,\n      options: Readonly<{ waitBudgetMs: number }>,\n    ) => Promise<AdoptedSchemaWriteTransaction>;\n  }>;\n\n/**\n * The schema-write facet available only after adoption earned its fence.\n * The caller owns the native transaction and remains responsible for its commit\n * or rollback.\n */\nexport type AdoptedSchemaWriteTransaction = Readonly<{\n  backend: SchemaWriteTransactionBackend &\n    Readonly<{\n      commitSchemaVersion: GraphBackend[\"commitSchemaVersion\"];\n      ensureVectorSlotContributions?: (\n        this: void,\n        slots: readonly VectorSlot[],\n        options?: Readonly<{ onDrift?: \"throw\" | \"skip\" }>,\n      ) => Promise<void>;\n    }>;\n  activeSchema: SchemaVersionRow | undefined;\n}>;\n\nexport type BackendIdentity = Pick<\n  GraphBackend,\n  | \"dialect\"\n  | \"capabilities\"\n  | \"tableNames\"\n  | \"fulltextStrategy\"\n  | \"vectorStrategy\"\n  | \"fenceSql\"\n>;\n\nexport type NodeEntityReadBackend = Pick<\n  GraphBackend,\n  \"getNode\" | \"getNodes\" | \"findNodesByKind\" | \"countNodesByKind\"\n>;\n\nexport type NodeEntityWriteBackend = Pick<\n  GraphBackend,\n  | \"insertNode\"\n  | \"insertNodeIfAbsent\"\n  | \"insertNodeIfAbsentWithSchemaFence\"\n  | \"insertNodeWithSchemaFence\"\n  | \"commands\"\n  | \"insertNodeNoReturn\"\n  | \"insertNodesBatch\"\n  | \"insertNodesBatchReturning\"\n  | \"updateNode\"\n  | \"upsertHeterogeneousNodes\"\n  | \"updateResolvedNodesBatch\"\n  | \"compareAndSetNode\"\n  | \"updateNodeSet\"\n  | \"deleteNode\"\n  | \"hardDeleteNode\"\n>;\n\nexport type EdgeEntityReadBackend = Pick<\n  GraphBackend,\n  | \"getEdge\"\n  | \"getEdges\"\n  | \"countEdgesFrom\"\n  | \"edgeExistsBetween\"\n  | \"findEdgesConnectedTo\"\n  | \"findEdgesByKind\"\n  | \"findEdgesByEndpointSet\"\n  | \"findEdgesByHeterogeneousEndpointSet\"\n  | \"countEdgesByKind\"\n>;\n\nexport type EdgeEntityWriteBackend = Pick<\n  GraphBackend,\n  | \"insertEdge\"\n  | \"commands\"\n  | \"insertEdgeNoReturn\"\n  | \"insertEdgesBatch\"\n  | \"insertEdgesBatchReturning\"\n  | \"insertEdgesDurableBatchReturning\"\n  | \"updateEdge\"\n  | \"deleteEdge\"\n  | \"deleteEdgesBatch\"\n  | \"hardDeleteEdge\"\n  | \"hardDeleteEdgesBatch\"\n>;\n\nexport type GraphEntityReadBackend = NodeEntityReadBackend &\n  EdgeEntityReadBackend;\n\nexport type GraphEntityWriteBackend = NodeEntityWriteBackend &\n  EdgeEntityWriteBackend;\n\nexport type UniqueConstraintBackend = Pick<\n  GraphBackend,\n  | \"insertUnique\"\n  | \"insertUniqueBatch\"\n  | \"deleteUnique\"\n  | \"hardDeleteUniquesByNodeIds\"\n  | \"hardDeleteUniquesByConcreteKind\"\n  | \"checkUnique\"\n  | \"checkUniqueBatch\"\n>;\n\nexport type SchemaReadBackend = Pick<\n  GraphBackend,\n  \"getActiveSchema\" | \"getSchemaVersion\"\n>;\n\nexport type SchemaCommitBackend = Pick<\n  GraphBackend,\n  \"commitSchemaVersion\" | \"commitSchemaVersionIfKindsEmpty\" | \"setActiveVersion\"\n>;\n\nexport type SchemaWriteFenceBackend = Pick<\n  GraphBackend,\n  \"lockSchemaVersionForWrite\" | \"lockSchemaVersionAndGraphWrite\"\n>;\n\nexport type VectorOperationBackend = Pick<\n  GraphBackend,\n  | \"upsertEmbedding\"\n  | \"upsertEmbeddingBatch\"\n  | \"deleteEmbedding\"\n  | \"deleteEmbeddingBatch\"\n  | \"vectorSearch\"\n  | \"createVectorIndex\"\n  | \"dropVectorIndex\"\n>;\n\nexport type FulltextOperationBackend = Pick<\n  GraphBackend,\n  | \"upsertFulltext\"\n  | \"deleteFulltext\"\n  | \"upsertFulltextBatch\"\n  | \"deleteFulltextBatch\"\n  | \"fulltextSearch\"\n>;\n\nexport type IndexMaterializationBackend = Pick<\n  GraphBackend,\n  | \"ensureIndexMaterializationsTable\"\n  | \"getIndexMaterialization\"\n  | \"getIndexMaterializations\"\n  | \"recordIndexMaterialization\"\n>;\n\n/** The optional catalog-introspection surface. See {@link BackendCatalogProbes}. */\nexport type CatalogBackend = Pick<GraphBackend, \"catalog\">;\n\n/** The optional engine-lineage surface. See {@link LineageMembers}. */\nexport type LineageBackend = Pick<GraphBackend, \"lineage\">;\n\n/** The optional engine-native recorded-time surface. See {@link EngineRecordedTimeMembers}. */\nexport type RecordedTimeBackend = Pick<GraphBackend, \"recordedTime\">;\n\nexport type ContributionMaterializationBackend = Pick<\n  GraphBackend,\n  | \"ensureContributionMaterializationsTable\"\n  | \"getContributionMaterialization\"\n  | \"recordContributionMaterialization\"\n  | \"assertRuntimeContributionsInitialized\"\n  | \"ensureRuntimeContributions\"\n  | \"ensureFulltextTable\"\n>;\n\nexport type RemovalMaterializationBackend = Pick<\n  GraphBackend,\n  | \"ensureKindRemovalsTable\"\n  | \"getPendingKindRemovals\"\n  | \"getAllKindRemovals\"\n  | \"recordKindRemoval\"\n  | \"ensureReconciliationMarkersTable\"\n  | \"getReconciliationMarker\"\n  | \"setReconciliationMarker\"\n>;\n\nexport type GraphLifecycleBackend = Pick<\n  GraphBackend,\n  \"clearGraph\" | \"bootstrapTables\"\n>;\n\nexport type QueryExecutionBackend = Pick<GraphBackend, \"execute\">;\n\nexport type RawQueryExecutionBackend = Pick<\n  GraphBackend,\n  \"executeRaw\" | \"compileSql\"\n>;\n\nexport type SqlCompilationBackend = Pick<GraphBackend, \"compileSql\">;\n\nexport type RawStatementExecutionBackend = Pick<\n  GraphBackend,\n  \"executeStatement\" | \"executeTemporaryStatement\" | \"executeDdl\"\n>;\n\nexport type BackendMaintenance = Pick<GraphBackend, \"refreshStatistics\">;\n\nexport type BackendTransactions = Pick<GraphBackend, \"transaction\">;\n\nexport type AdapterBackendTransactions<TNativeTransaction> = Pick<\n  AdapterBackend<TNativeTransaction>,\n  \"transactionWithNative\" | \"adoptTransaction\"\n>;\n\nexport type BackendLifecycle = Pick<GraphBackend, \"close\">;\n\n/**\n * Read-oriented transaction projection exposed by portable transaction\n * contexts. It preserves snapshot-aware graph reads and TypeGraph-compiled\n * row queries while excluding graph writes, arbitrary raw SQL, DDL,\n * transaction adoption, and lifecycle control.\n */\nexport type TransactionReadBackend = Readonly<\n  BackendIdentity &\n    GraphEntityReadBackend &\n    SchemaReadBackend &\n    QueryExecutionBackend &\n    SqlCompilationBackend\n>;\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * This is an explicit facet composition, not `Omit<GraphBackend, ...>`.\n * New top-level-only backend methods therefore do not silently appear on\n * transaction-scoped backends. `commitSchemaVersion`, `setActiveVersion`,\n * `refreshStatistics`, `transaction`, `adoptTransaction`, and `close` stay\n * deliberately absent: their guarantees depend on the top-level backend or\n * lifecycle owner rather than an already-open transaction.\n */\nexport type TransactionBackend = Readonly<\n  BackendIdentity &\n    GraphEntityReadBackend &\n    GraphEntityWriteBackend &\n    UniqueConstraintBackend &\n    // The edge cardinality claim relation's surface. Inline rather than a named\n    // member type: it is a different relation from `uniques` with a different\n    // key, and naming it would add a type the public surface references but no\n    // entrypoint exports.\n    Pick<\n      GraphBackend,\n      | \"claimEdgeCardinality\"\n      | \"claimEdgeCardinalityGuarded\"\n      | \"claimEdgeCardinalityBatch\"\n      | \"purgeEdgeClaims\"\n    > &\n    SchemaReadBackend &\n    SchemaWriteFenceBackend &\n    VectorOperationBackend &\n    FulltextOperationBackend &\n    IndexMaterializationBackend &\n    CatalogBackend &\n    LineageBackend &\n    RecordedTimeBackend &\n    ContributionMaterializationBackend &\n    RemovalMaterializationBackend &\n    GraphLifecycleBackend &\n    QueryExecutionBackend &\n    RawQueryExecutionBackend &\n    RawStatementExecutionBackend\n>;\n\n/**\n * Transaction backend exposed only while the backend's schema-write lock is\n * held. Unlike the ordinary top-level `executeDdl` port, this DDL primitive is\n * explicitly transaction-scoped and must use the callback's transaction.\n *\n * @internal\n */\nexport type SchemaWriteTransactionBackend = TransactionBackend &\n  Readonly<{\n    executeStatement: NonNullable<TransactionBackend[\"executeStatement\"]>;\n    tableExists: (this: void, tableName: string) => Promise<boolean>;\n    executeSchemaDdl: (this: void, ddl: string) => Promise<void>;\n    deleteSchemaVectorSlotContribution: (\n      this: void,\n      slot: VectorSlot,\n    ) => Promise<void>;\n  }>;\n\n/**\n * The target a schema-commit preflight runs against: a transaction backend\n * that MAY also carry the schema-write DDL primitive.\n *\n * Optional, deliberately. Both bundled backends pass the same\n * {@link SchemaWriteTransactionBackend} their `schemaWriteTransaction` exposes,\n * so DDL is available there; a custom backend may implement\n * {@link GraphBackend.commitSchemaVersionWithPreflight} over a transaction that\n * cannot run DDL. Declaring the port as present-or-absent lets a preflight that\n * needs it refuse with a typed error naming the capability, instead of calling\n * `undefined` — or, far worse, skipping the DDL and continuing.\n *\n * @internal\n */\nexport type SchemaCommitPreflightBackend = TransactionBackend &\n  Readonly<{\n    executeSchemaDdl?: (this: void, ddl: string) => Promise<void>;\n  }>;\n\n/**\n * Builds the actual runtime projection exposed as `TransactionContext.backend`.\n * This is an explicit object rather than a type-only narrowing so portable\n * callers cannot discover write or arbitrary-SQL methods on the underlying\n * transaction backend at runtime.\n *\n * @internal\n */\nexport function createTransactionReadBackend(\n  backend: TransactionBackend,\n): TransactionReadBackend {\n  const getNodes = backend.getNodes;\n  const getEdges = backend.getEdges;\n  const compileSql = backend.compileSql;\n\n  return Object.freeze({\n    dialect: backend.dialect,\n    capabilities: backend.capabilities,\n    ...(backend.tableNames === undefined ?\n      {}\n    : { tableNames: backend.tableNames }),\n    ...(backend.fulltextStrategy === undefined ?\n      {}\n    : { fulltextStrategy: backend.fulltextStrategy }),\n    ...(backend.vectorStrategy === undefined ?\n      {}\n    : { vectorStrategy: backend.vectorStrategy }),\n    getNode: (graphId, kind, id) => backend.getNode(graphId, kind, id),\n    ...(getNodes === undefined ?\n      {}\n    : {\n        getNodes: (graphId: string, kind: string, ids: readonly string[]) =>\n          getNodes(graphId, kind, ids),\n      }),\n    getEdge: (graphId, id) => backend.getEdge(graphId, id),\n    ...(getEdges === undefined ?\n      {}\n    : {\n        getEdges: (graphId: string, ids: readonly string[]) =>\n          getEdges(graphId, ids),\n      }),\n    countEdgesFrom: (params) => backend.countEdgesFrom(params),\n    edgeExistsBetween: (params) => backend.edgeExistsBetween(params),\n    findEdgesConnectedTo: (params) => backend.findEdgesConnectedTo(params),\n    findNodesByKind: (params) => backend.findNodesByKind(params),\n    countNodesByKind: (params) => backend.countNodesByKind(params),\n    findEdgesByKind: (params) => backend.findEdgesByKind(params),\n    countEdgesByKind: (params) => backend.countEdgesByKind(params),\n    getActiveSchema: (graphId) => backend.getActiveSchema(graphId),\n    getSchemaVersion: (graphId, version) =>\n      backend.getSchemaVersion(graphId, version),\n    execute: <T>(query: CompiledRowsSql) => backend.execute<T>(query),\n    ...(compileSql === undefined ?\n      {}\n    : { compileSql: (query: SqlFragment) => compileSql(query) }),\n  });\n}\n\n/**\n * Closes an owned resource after provisioning fails without replacing the\n * original domain error with a secondary cleanup failure.\n */\nexport async function closeAfterFailure(\n  resource: Readonly<{ close: () => void | Promise<void> }>,\n  provisioningError: unknown,\n): Promise<never> {\n  try {\n    await resource.close();\n  } catch {\n    // The provisioning failure remains the actionable error. Managed close is\n    // retryable when the resource is returned, but a failed factory has no\n    // handle it can safely expose for a second attempt.\n  }\n  throw provisioningError;\n}\n\n/** Options for {@link runOptionallyInTransaction}. */\nexport type RunOptionallyInTransactionOptions = Readonly<{\n  /**\n   * Pass only when the toplevel backend method would recurse — pass the\n   * operation-level backend so the no-transaction path doesn't loop back\n   * through the same toplevel method.\n   */\n  fallback?: GraphBackend | TransactionBackend;\n  /**\n   * Options for the transaction this opens — most usefully\n   * `accessMode: \"read_only\"`, which lets a multi-statement READ declare itself\n   * to the engine instead of only promising it (SQLite issues `BEGIN` rather\n   * than reserving the single writer slot with `BEGIN IMMEDIATE`; PostgreSQL\n   * issues `BEGIN … READ ONLY`).\n   *\n   * Scopes the transaction and nothing else, so it is not honored on the\n   * fallthrough path: a backend without interactive transactions opens no\n   * transaction to configure. The callback receives an explicit execution\n   * mode (`interactive-transaction` or `sequential`), so callers never infer\n   * the execution boundary from backend object identity.\n   */\n  transaction?: TransactionOptions;\n}>;\n\n/** What {@link runOptionallyInTransaction} actually did for this invocation. */\nexport type OptionalTransactionExecution =\n  | Readonly<{\n      /** The callback runs on a transaction-scoped interactive session. */\n      mode: \"interactive-transaction\";\n    }>\n  | Readonly<{\n      /** The callback runs sequentially without an encompassing transaction. */\n      mode: \"sequential\";\n    }>;\n\n/**\n * Runs `fn` inside a transaction when given a top-level backend that supports\n * one, falling through to a direct invocation otherwise. Lets call sites benefit\n * from atomicity on backends that have transactions while staying functional on\n * backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over HTTP), and\n * avoids opening nested transactions when the caller already holds a\n * transaction-scoped backend. The single-statement race window is already\n * implicit on any backend without interactive transactions; callers that\n * cannot tolerate it must branch on the capability themselves.\n */\nexport async function runOptionallyInTransaction<T>(\n  backend: GraphBackend | TransactionBackend,\n  fn: (\n    target: GraphBackend | TransactionBackend,\n    execution: OptionalTransactionExecution,\n  ) => Promise<T>,\n  options?: RunOptionallyInTransactionOptions,\n): Promise<T> {\n  if (\n    \"transaction\" in backend &&\n    backend.capabilities.execution.interactiveTransactions\n  ) {\n    return backend.transaction(\n      (tx) => fn(tx, { mode: \"interactive-transaction\" }),\n      options?.transaction,\n    );\n  }\n  return fn(options?.fallback ?? backend, { mode: \"sequential\" });\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  constraintName: string;\n  key: string;\n  nodeId: string;\n  concreteKind: string;\n}>;\n\n/**\n * Parameters for releasing a unique constraint entry.\n *\n * Every release is scoped to the claim's OWNER — the pair\n * `(concreteKind, nodeId)`, because a node id is unique only within its kind.\n * The two shapes differ only in whether the claim AXIS participates:\n *\n *  - **Lifecycle release** (`nodeKind` absent) — \"give up every claim this node\n *    holds for this constraint and key, whatever axis it sits on\". Soft delete,\n *    an update's key-change release and the resurrect diff use it, so a claim\n *    written under an older axis is still released by newer code.\n *  - **Compensating release** (`nodeKind` present) — \"undo exactly the row I\n *    just claimed, at the axis I claimed it on\". A failed write's rollback uses\n *    it, so it touches neither a row that predates the write nor one another\n *    node holds.\n */\nexport type DeleteUniqueParams = Readonly<{\n  graphId: string;\n  /**\n   * The claim axis (`uniques.node_kind`) the release is restricted to. Absent\n   * releases the owner's claims at every axis — see the two shapes above.\n   */\n  nodeKind?: string;\n  constraintName: string;\n  key: string;\n  /** The claim owner's concrete kind (`uniques.concrete_kind`). */\n  concreteKind: string;\n  /** The claim owner's node id (`uniques.node_id`). */\n  nodeId: string;\n}>;\n\n/** Parameters for permanently clearing uniqueness sidecars by node identity. */\nexport type HardDeleteUniquesByNodeIdsParams = Readonly<{\n  graphId: string;\n  concreteKind: string;\n  nodeIds: readonly string[];\n}>;\n\n/** Parameters for permanently clearing every uniqueness claim a kind owns. */\nexport type HardDeleteUniquesByConcreteKindParams = Readonly<{\n  graphId: string;\n  concreteKind: string;\n}>;\n\n/**\n * One edge cardinality claim, named by the components its axis, its key and its\n * holder-liveness predicate are all built from.\n *\n * The components are passed RAW rather than pre-rendered: `EDGE_CARDINALITY_SPECS`\n * (`store/claims/edge-claims.ts`) is the one table that decides which endpoints\n * the key covers and what a holder must still be, and both the TypeScript probe\n * and the SQL builder read it. A caller that rendered the axis and key itself\n * would be a second spelling of that decision.\n */\nexport type ClaimEdgeCardinalityParams = Readonly<{\n  graphId: string;\n  /** The declared cardinality; `many` declares nothing and never claims. */\n  cardinality: Exclude<Cardinality, \"many\">;\n  edgeKind: string;\n  /** The edge that will hold the axis if this claim lands. */\n  edgeId: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n}>;\n\n/**\n * What a claim statement decided.\n *\n * `refused` carries the incumbent so the caller can say which edge holds the\n * axis; the typed refusal itself is the store's, built from the same\n * `checkCardinality` / `checkUniqueEdge` owners the probe uses, so a caller\n * cannot tell which layer refused.\n */\nexport type EdgeClaimOutcome =\n  | Readonly<{ status: \"claimed\" }>\n  | Readonly<{ status: \"refused\"; holderEdgeId: string }>;\n\n/** Parameters for the housekeeping purge of claims held by named edges. */\nexport type PurgeEdgeClaimsParams = Readonly<{\n  graphId: string;\n  edgeIds: readonly string[];\n}>;\n\n/** One edge kind's declared cardinality, as the fence audit reads it. */\nexport type EdgeCardinalityDeclaration = Readonly<{\n  edgeKind: string;\n  /** `many` declares nothing, so it is unrepresentable here. */\n  cardinality: Exclude<Cardinality, \"many\">;\n}>;\n\n/**\n * What a constraint-fence audit asks the database about: the declarations the\n * graph carries, one list per family.\n *\n * The declarations are passed rather than discovered because the backend holds\n * no schema — and because the `uniqueConstraintNames` restriction is\n * load-bearing rather than an optimization: the `uniques` relation also holds\n * disjointness claims, whose `node_kind` is a pair label rather than a kind and\n * for which no uniqueness axis can be computed. Those rows are covered by\n * `disjointKindPairs`, from the nodes relation.\n */\nexport type ReadConstraintFenceViolationsParams = Readonly<{\n  graphId: string;\n  /** Every unique constraint name the graph declares, in any scope. */\n  uniqueConstraintNames: readonly string[];\n  /** Every declared `disjointWith` pair, each read as one intersection. */\n  disjointKindPairs: readonly (readonly [string, string])[];\n  /** Every edge kind declaring a cardinality other than `many`. */\n  edgeCardinalities: readonly EdgeCardinalityDeclaration[];\n}>;\n\n/**\n * One live `uniques` row that shares its `(constraint_name, key)` with at least\n * one other live row — a candidate, not a verdict: two rows contend only when\n * their `node_kind`s fold onto ONE claim axis, which the caller decides.\n */\nexport type ContendedUniqueRow = Readonly<{\n  nodeKind: string;\n  constraintName: string;\n  key: string;\n  concreteKind: string;\n  nodeId: string;\n}>;\n\n/**\n * One live edge that shares its declared cardinality's population with at least\n * one other live edge. The endpoints are returned whole so the caller can name\n * the claim key through the one builder that renders it.\n */\nexport type ContendedEdgeRow = Readonly<{\n  edgeKind: string;\n  cardinality: Exclude<Cardinality, \"many\">;\n  edgeId: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n}>;\n\n/** One node id live under BOTH kinds of a declared disjoint pair. */\nexport type DisjointOverlapRow = Readonly<{\n  kinds: readonly [string, string];\n  nodeId: string;\n}>;\n\n/** Everything one constraint-fence audit read, per family. */\nexport type ConstraintFenceViolationRows = Readonly<{\n  contendedUniqueRows: readonly ContendedUniqueRow[];\n  contendedEdgeRows: readonly ContendedEdgeRow[];\n  disjointOverlaps: readonly DisjointOverlapRow[];\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  constraintName: string;\n  key: string;\n  /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n  includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  constraintName: string;\n  keys: readonly string[];\n  /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n  includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n  graphId: string;\n  version: number;\n  schemaHash: string;\n  schemaDoc: SerializedSchema;\n  isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n *   for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n *   active and is committing version N+1 against that baseline. The\n *   commit fails with `StaleVersionError` if some other writer has\n *   advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n  Readonly<{ kind: \"initial\" }> | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n  graphId: string;\n  /** CAS guard — see `CommitSchemaVersionExpected`. */\n  expected: CommitSchemaVersionExpected;\n  /** The new version to insert and activate. */\n  version: number;\n  schemaHash: string;\n  schemaDoc: SerializedSchema;\n}>;\n\nexport type SchemaKindEmptinessProbe = Readonly<{\n  entity: \"node\" | \"edge\";\n  kind: string;\n  /** Which rows make this schema transition unsafe. Must be chosen explicitly. */\n  rows: \"nonDeleted\" | \"all\";\n}>;\n\nexport type PopulatedSchemaKind = SchemaKindEmptinessProbe &\n  Readonly<{ count: number }>;\n\nexport type CommitSchemaVersionIfKindsEmptyResult =\n  | Readonly<{ status: \"committed\"; row: SchemaVersionRow }>\n  | Readonly<{\n      status: \"populated\";\n      kinds: readonly PopulatedSchemaKind[];\n    }>;\n\nexport type LockSchemaVersionForWriteParams = Readonly<{\n  graphId: string;\n  expectedVersion: number;\n}>;\n\n/** Parameters shared by the ordinary and fused schema-write fences. */\nexport type SchemaWriteFenceParams = LockSchemaVersionForWriteParams;\n\n/**\n * Optional schema-managed write identity for a trusted import. Supplying it\n * acquires and validates the Store version's transaction-scoped schema fence;\n * omitting it leaves the import outside the versioned guarantee.\n */\nexport type TrustedImportOptions = Readonly<{\n  schemaWrite?: Readonly<{ graphId: string; expectedVersion: number }>;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n  graphId: string;\n  /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n  expected: CommitSchemaVersionExpected;\n  /** The version to mark active. Must already exist. */\n  version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n  graphId: string;\n  edgeKind: string;\n  fromKind: string;\n  fromId: string;\n  /** If true, only count edges where valid_to IS NULL */\n  activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n  graphId: string;\n  edgeKind: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n  graphId: string;\n  nodeKind: string;\n  nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n  graphId: string;\n  kind: string;\n  /** Max rows to return. */\n  limit?: number;\n  /** Offset. Present for backward compat; rebuild uses `after` instead. */\n  offset?: number;\n  /** If true, exclude deleted nodes. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n  /**\n   * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n   * behavior). Rebuild should use \"id\" for iteration that is stable under\n   * concurrent writes and shared timestamps.\n   */\n  orderBy?: \"id\" | \"created_at\";\n  /**\n   * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n   * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n   * exclusive with `offset` — callers pick one.\n   */\n  after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n  graphId: string;\n  kind: string;\n  /** If true, exclude deleted nodes. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n  graphId: string;\n  kind: string;\n  fromKind?: string;\n  fromId?: string;\n  toKind?: string;\n  toId?: string;\n  limit?: number;\n  offset?: number;\n  /** If true, exclude deleted edges. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n  /**\n   * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n   * behavior). Use \"id\" for iteration that is stable under shared `created_at`\n   * timestamps — the offset path orders by the NON-unique `created_at`, so a\n   * full enumeration must page by the unique `id` to avoid skipping a row at a\n   * page boundary. Mirrors {@link FindNodesByKindParams.orderBy}.\n   */\n  orderBy?: \"id\" | \"created_at\";\n  /**\n   * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this value.\n   * When `orderBy: \"id\"`, compared lexicographically. Mutually exclusive with\n   * `offset` — callers pick one. Mirrors {@link FindNodesByKindParams.after}.\n   */\n  after?: string;\n}>;\n\n/**\n * The endpoint side a {@link FindEdgesByEndpointSetParams} read fans out over.\n */\nexport type EdgeEndpointSide = \"from\" | \"to\";\n\n/**\n * Parameters for reading the edges of a SET of endpoints in one statement per\n * bind-budget chunk — the widened form of {@link FindEdgesByKindParams}'s\n * scalar `fromId` / `toId`.\n *\n * Deliberately a SEPARATE parameter type on a separate operation rather than\n * optional fields on `FindEdgesByKindParams`. A backend that did not implement\n * set membership would still type-check while ignoring the id list, and would\n * then return every edge of the kind — which the caller would rebucket into a\n * correct-looking answer at unbounded cost. Splitting the operation makes that\n * failure unreachable: support is detected by the method's presence, before any\n * read is issued.\n *\n * The shape also makes the previously-validated illegal states\n * unrepresentable. One `side` instead of two independent id lists means both\n * endpoints can never fan out at once; no scalar `fromId` / `toId` field means\n * a scalar and a set can never disagree; no `limit` / `offset` / `after` means\n * a global slice can never be requested across a read the backend splits into\n * bind-budget chunks.\n */\nexport type FindEdgesByEndpointSetParams = Readonly<{\n  graphId: string;\n  kind: string;\n  /** Which endpoint column the id set constrains. */\n  side: EdgeEndpointSide;\n  /**\n   * Kind of the fanned-out endpoint. Required: it is the index prefix that\n   * makes the set a seek rather than a scan, so a set is always scoped to one\n   * endpoint kind and a heterogeneous page costs one read per distinct kind.\n   */\n  endpointKind: string;\n  /**\n   * Endpoint NODE ids to match — deliberately not named `ids`, which in the\n   * backend params vocabulary means edge ids (see\n   * {@link DeleteEdgesBatchParams}); the write-surface assertion in\n   * `recorded-capture/write-surface.ts` classifies params structurally and a\n   * `{ graphId, ids }` read would be misread as a write.\n   *\n   * The backend deduplicates before splitting the list across bind-budget\n   * chunks — a repeated id spanning two chunks would return its edges twice.\n   * An empty list reads nothing and yields no rows.\n   */\n  endpointIds: readonly string[];\n  /**\n   * Maximum rows per distinct endpoint id, applied inside the statement (via\n   * `ROW_NUMBER()` over the read's own ordering) rather than by the caller.\n   * Only meaningful on a backend whose `capabilities.windowFunctions` is true;\n   * callers must still cap client-side, so a backend that ignores this returns\n   * a superset rather than a wrong answer. Unlike a global `limit`, a\n   * per-endpoint cap composes with chunking: each endpoint's rows fall\n   * entirely within one chunk.\n   */\n  limitPerEndpoint?: number;\n  /** If true, exclude deleted edges. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n}>;\n\n/**\n * Parameters for reading several edge kinds from several endpoint kinds.\n *\n * The endpoint pairs are joined as a relation, so round trips are independent\n * of the number of licensed edge-kind/endpoint-kind combinations. Large source\n * sets may still be split to respect the backend's bind-parameter budget.\n */\nexport type FindEdgesByHeterogeneousEndpointSetParams = Readonly<{\n  graphId: string;\n  side: EdgeEndpointSide;\n  endpoints: readonly Readonly<{\n    kind: string;\n    id: string;\n    /**\n     * Optional endpoint on the opposite side of the edge. When present, the\n     * set read performs an exact directed-pair seek instead of materializing\n     * every edge incident to `kind` / `id` and leaving the caller to filter.\n     * This is particularly important for hub nodes.\n     */\n    opposite?: Readonly<{ kind: string; id: string }>;\n  }>[];\n  edgeKinds: readonly string[];\n  limitPerEndpoint?: number;\n  /** If true, exclude deleted edges. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n  graphId: string;\n  kind: string;\n  fromKind?: string;\n  fromId?: string;\n  toKind?: string;\n  toId?: string;\n  /** If true, exclude deleted edges. Default true. */\n  excludeDeleted?: boolean;\n  /** Temporal mode for filtering by validity period. */\n  temporalMode?: TemporalMode;\n  /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n  asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Conservative per-statement bound-parameter floor for SQLite. The\n * compiled-in `SQLITE_MAX_VARIABLE_NUMBER` defaulted to 999 before SQLite\n * 3.32.0; drivers whose real ceiling cannot be probed (async/remote\n * connections) keep this floor. Single source of truth for\n * {@link SQLITE_CAPABILITIES} and the SQLite backend's batch math fallback.\n */\nexport const SQLITE_MAX_BIND_PARAMETERS = 999;\n\n/**\n * `SQLITE_MAX_VARIABLE_NUMBER` default since SQLite 3.32.0 (better-sqlite3\n * also compiles it in explicitly). Used when a synchronous driver's probe\n * confirms a modern build.\n */\nexport const MODERN_SQLITE_MAX_BIND_PARAMETERS = 32_766;\n\n/**\n * Cloudflare D1's documented per-statement bound-parameter ceiling. Far\n * below the classic SQLite floor, so D1 detection must cap the budget or\n * batched writes fail at runtime.\n */\nexport const D1_MAX_BIND_PARAMETERS = 100;\n\n/**\n * Cloudflare SQLite-backed Durable Objects' documented per-statement\n * bound-parameter ceiling. The resolved `do-sqlite` execution profile must\n * advertise this limit so every capability-driven batch path stays below it.\n */\nexport const DURABLE_OBJECT_MAX_BIND_PARAMETERS = 100;\n\n/**\n * Safe bound-parameter ceiling shared by every bundled PostgreSQL driver.\n * The protocol count can represent 65535, but postgres.js rejects a statement\n * with 65534 bound values, so backend batch math uses the lower portable limit.\n */\nexport const POSTGRES_MAX_BIND_PARAMETERS = 65_533;\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = Object.freeze({\n  execution: Object.freeze({\n    interactiveTransactions: true,\n    atomicBatch: \"none\",\n    unitOfWork: \"interactive\",\n  }),\n  windowFunctions: true, // SQLite has supported window functions since 3.25.0\n  clearValidTo: true,\n  returning: true, // SQLite has supported RETURNING since 3.35.0\n  // The bundled schema ships both claim relations and the shared operation\n  // backend implements every claim member.\n  constraintClaims: true,\n  durableEdgeMatchIdentity: true,\n  maxBindParameters: SQLITE_MAX_BIND_PARAMETERS,\n  // Generic SQLite builds do not guarantee ENABLE_MATH_FUNCTIONS. The local\n  // better-sqlite3 factory overrides this flag for its bundled build contract.\n  graphAnalytics: Object.freeze({ supported: true, mathFunctions: false }),\n  recursiveTraversal: Object.freeze({ supported: true }),\n  writeFence: Object.freeze({\n    mechanism: \"engine-serialized\",\n  }),\n});\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = Object.freeze({\n  execution: Object.freeze({\n    interactiveTransactions: true,\n    atomicBatch: \"none\",\n    unitOfWork: \"interactive\",\n  }),\n  windowFunctions: true, // PostgreSQL supports ROW_NUMBER() and related windows\n  orderedAggregates: true,\n  clearValidTo: true,\n  returning: true, // PostgreSQL has supported RETURNING since 8.2\n  // The bundled schema ships both claim relations and the shared operation\n  // backend implements every claim member.\n  constraintClaims: true,\n  durableEdgeMatchIdentity: true,\n  atomicNodeInsertClaims: true,\n  maxBindParameters: POSTGRES_MAX_BIND_PARAMETERS,\n  graphAnalytics: Object.freeze({ supported: true, mathFunctions: true }),\n  recursiveTraversal: Object.freeze({ supported: true }),\n  writeFence: Object.freeze({\n    mechanism: \"advisory\",\n    drain: \"table-lock\",\n  }),\n});\n","/**\n * SQL Schema Configuration for Query Compilation\n *\n * Provides table and column identifiers that the query compiler uses.\n * This allows the compiler to work with custom table names instead of\n * hard-coded defaults.\n */\nimport {\n  type EngineRecordedRevision,\n  type EngineRecordedTimeMembers,\n} from \"../../backend/capabilities/recorded-time\";\nimport { type VectorIndexType, type VectorMetric } from \"../../backend/types\";\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../../constants\";\nimport {\n  parseRecordedInstant,\n  type RecordedInstantParts,\n} from \"../../core/temporal\";\nimport { CompilerInvariantError, ConfigurationError } from \"../../errors\";\nimport { typeGraphGlobalSymbol } from \"../../utils/global-symbol\";\nimport { isSqlFragment, sql, type SqlFragment } from \"../sql-fragment\";\n\nconst SQL_SCHEMA_BRAND: unique symbol = typeGraphGlobalSymbol(\"sql-schema-v1\");\n\n/**\n * Table names for TypeGraph SQL schema.\n *\n * Carries every customizable physical-table name the backend exposes,\n * including the secondary tables (`uniques`, `edgeClaims`, `fences`) that\n * the query compiler itself doesn't reference but `materializeRemovals` and\n * other cleanup paths (or, for `fences`, `resolveFenceStatements`'s\n * `row`-mechanism derivation) need to address by name. Backends without a\n * `uniques` table (custom embeddings-only stores) leave it as the\n * default — the cleanup path is a no-op for kinds with no unique\n * rows.\n */\nexport type SqlTableNames = Readonly<{\n  /** Active schema version relation; absent on backends without checked reads. */\n  schemaVersions?: string | undefined;\n  /** Nodes table name (default: \"typegraph_nodes\") */\n  nodes: string;\n  /** Edges table name (default: \"typegraph_edges\") */\n  edges: string;\n  /** Recorded node relation table name (default: \"typegraph_recorded_nodes\") */\n  recordedNodes?: string | undefined;\n  /** Recorded edge relation table name (default: \"typegraph_recorded_edges\") */\n  recordedEdges?: string | undefined;\n  /** Recorded-time commit clock table name (default: \"typegraph_recorded_clock\") */\n  recordedClock?: string | undefined;\n  /** Durable per-graph revision-origin table name (default: \"typegraph_revision_origins\") */\n  revisionOrigins?: string | undefined;\n  /** Identity assertion ledger (default: \"typegraph_identity_assertions\") */\n  identityAssertions?: string | undefined;\n  /** Recorded identity assertion relation */\n  recordedIdentityAssertions?: string | undefined;\n  /** Derived current identity closure */\n  identityClosure?: string | undefined;\n  /** Derived separation relation over identity classes */\n  identitySeparation?: string | undefined;\n  /** Node fulltext table name (default: \"typegraph_node_fulltext\") */\n  fulltext: string;\n  /** Node uniques table name (default: \"typegraph_node_uniques\") */\n  uniques: string;\n  /** Edge cardinality claim table name (default: \"typegraph_edge_claims\") */\n  edgeClaims?: string | undefined;\n  /**\n   * Write-fence rows table name (default: \"typegraph_fences\") — the\n   * never-dropped relation a `row`-mechanism write fence acquires a keyed\n   * exclusion against. Part of the base schema on every backend, whether or\n   * not any target ever declares `writeFence.mechanism: \"row\"`.\n   */\n  fences?: string | undefined;\n}>;\n\nexport type ResolvedSqlTableNames = Readonly<{\n  /** Active schema version relation; absent on backends without checked reads. */\n  schemaVersions?: string;\n  /** Nodes table name */\n  nodes: string;\n  /** Edges table name */\n  edges: string;\n  /** Recorded node relation table name */\n  recordedNodes: string;\n  /** Recorded edge relation table name */\n  recordedEdges: string;\n  /** Recorded-time commit clock table name */\n  recordedClock: string;\n  /** Durable per-graph revision-origin table name */\n  revisionOrigins: string;\n  identityAssertions: string;\n  recordedIdentityAssertions: string;\n  identityClosure: string;\n  identitySeparation: string;\n  /** Node fulltext table name */\n  fulltext: string;\n  /** Node uniques table name */\n  uniques: string;\n  /** Edge cardinality claim table name */\n  edgeClaims: string;\n  /** Write-fence rows table name */\n  fences: string;\n}>;\n\ntype SqlSchemaFields = Readonly<{\n  /** Table names */\n  tables: ResolvedSqlTableNames;\n  /** Get a `SqlFragment` reference to the nodes table. */\n  nodesTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the edges table. */\n  edgesTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the recorded node relation. */\n  recordedNodesTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the recorded edge relation. */\n  recordedEdgesTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the recorded-time commit clock. */\n  recordedClockTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the durable per-graph revision origins. */\n  revisionOriginsTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the identity assertion ledger. */\n  identityAssertionsTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the recorded identity assertion relation. */\n  recordedIdentityAssertionsTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the derived identity closure. */\n  identityClosureTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the derived identity separation relation. */\n  identitySeparationTable: SqlFragment;\n  /** Get a `SqlFragment` reference to the fulltext table. */\n  fulltextTable: SqlFragment;\n}>;\n\n/**\n * SQL schema configuration for query compilation.\n * Contains table identifiers and utility methods for generating `SqlFragment` references.\n *\n * Branded and frozen by {@link createSqlSchema}; callers should not construct\n * schema-shaped objects by hand.\n */\nexport abstract class SqlSchema implements SqlSchemaFields {\n  declare private readonly typeGraphSqlSchemaBrand: true;\n  abstract readonly tables: ResolvedSqlTableNames;\n  abstract readonly nodesTable: SqlFragment;\n  abstract readonly edgesTable: SqlFragment;\n  abstract readonly recordedNodesTable: SqlFragment;\n  abstract readonly recordedEdgesTable: SqlFragment;\n  abstract readonly recordedClockTable: SqlFragment;\n  abstract readonly revisionOriginsTable: SqlFragment;\n  abstract readonly identityAssertionsTable: SqlFragment;\n  abstract readonly recordedIdentityAssertionsTable: SqlFragment;\n  abstract readonly identityClosureTable: SqlFragment;\n  abstract readonly identitySeparationTable: SqlFragment;\n  abstract readonly fulltextTable: SqlFragment;\n}\n\nclass SqlSchemaDescriptor extends SqlSchema {\n  declare readonly [SQL_SCHEMA_BRAND]: true;\n  readonly tables: ResolvedSqlTableNames;\n  readonly nodesTable: SqlFragment;\n  readonly edgesTable: SqlFragment;\n  readonly recordedNodesTable: SqlFragment;\n  readonly recordedEdgesTable: SqlFragment;\n  readonly recordedClockTable: SqlFragment;\n  readonly revisionOriginsTable: SqlFragment;\n  readonly identityAssertionsTable: SqlFragment;\n  readonly recordedIdentityAssertionsTable: SqlFragment;\n  readonly identityClosureTable: SqlFragment;\n  readonly identitySeparationTable: SqlFragment;\n  readonly fulltextTable: SqlFragment;\n\n  constructor(fields: SqlSchemaFields) {\n    super();\n    Object.defineProperty(this, SQL_SCHEMA_BRAND, {\n      configurable: false,\n      enumerable: false,\n      value: true,\n      writable: false,\n    });\n    this.tables = fields.tables;\n    this.nodesTable = fields.nodesTable;\n    this.edgesTable = fields.edgesTable;\n    this.recordedNodesTable = fields.recordedNodesTable;\n    this.recordedEdgesTable = fields.recordedEdgesTable;\n    this.recordedClockTable = fields.recordedClockTable;\n    this.revisionOriginsTable = fields.revisionOriginsTable;\n    this.identityAssertionsTable = fields.identityAssertionsTable;\n    this.recordedIdentityAssertionsTable =\n      fields.recordedIdentityAssertionsTable;\n    this.identityClosureTable = fields.identityClosureTable;\n    this.identitySeparationTable = fields.identitySeparationTable;\n    this.fulltextTable = fields.fulltextTable;\n    Object.freeze(this);\n  }\n}\n\n/**\n * Default table names matching the standard TypeGraph schema.\n */\nconst DEFAULT_TABLE_NAMES = {\n  schemaVersions: \"typegraph_schema_versions\",\n  nodes: \"typegraph_nodes\",\n  edges: \"typegraph_edges\",\n  recordedNodes: \"typegraph_recorded_nodes\",\n  recordedEdges: \"typegraph_recorded_edges\",\n  recordedClock: \"typegraph_recorded_clock\",\n  revisionOrigins: \"typegraph_revision_origins\",\n  identityAssertions: \"typegraph_identity_assertions\",\n  recordedIdentityAssertions: \"typegraph_recorded_identity_assertions\",\n  identityClosure: \"typegraph_identity_closure\",\n  identitySeparation: \"typegraph_identity_separation\",\n  fulltext: \"typegraph_node_fulltext\",\n  uniques: \"typegraph_node_uniques\",\n  edgeClaims: \"typegraph_edge_claims\",\n  fences: \"typegraph_fences\",\n} satisfies ResolvedSqlTableNames;\n\nfunction resolveTableNames(\n  names: Partial<SqlTableNames>,\n): ResolvedSqlTableNames {\n  return {\n    nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,\n    edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,\n    recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,\n    recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,\n    recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,\n    revisionOrigins:\n      names.revisionOrigins ?? DEFAULT_TABLE_NAMES.revisionOrigins,\n    identityAssertions:\n      names.identityAssertions ?? DEFAULT_TABLE_NAMES.identityAssertions,\n    recordedIdentityAssertions:\n      names.recordedIdentityAssertions ??\n      DEFAULT_TABLE_NAMES.recordedIdentityAssertions,\n    identityClosure:\n      names.identityClosure ?? DEFAULT_TABLE_NAMES.identityClosure,\n    identitySeparation:\n      names.identitySeparation ?? DEFAULT_TABLE_NAMES.identitySeparation,\n    fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,\n    uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques,\n    edgeClaims: names.edgeClaims ?? DEFAULT_TABLE_NAMES.edgeClaims,\n    fences: names.fences ?? DEFAULT_TABLE_NAMES.fences,\n    schemaVersions: names.schemaVersions ?? DEFAULT_TABLE_NAMES.schemaVersions,\n  };\n}\n\n/**\n * Regex for valid SQL identifiers.\n * Must start with a letter or underscore.\n * Can contain letters, digits, underscores, and dollar signs.\n * Dollar signs are a PostgreSQL extension but commonly supported.\n */\nconst VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;\n\n/**\n * Validates that a table name is a valid SQL identifier.\n *\n * @throws Error if the table name is invalid\n */\nfunction validateTableName(name: string, label: string): void {\n  if (!name || name.length === 0) {\n    throw new ConfigurationError(`${label} table name cannot be empty`);\n  }\n  if (name.length > MAX_PG_IDENTIFIER_LENGTH) {\n    throw new ConfigurationError(\n      `${label} table name exceeds maximum length of ${MAX_PG_IDENTIFIER_LENGTH} characters`,\n    );\n  }\n  if (!VALID_IDENTIFIER_PATTERN.test(name)) {\n    throw new ConfigurationError(\n      `${label} table name \"${name}\" is not a valid SQL identifier. ` +\n        `Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`,\n    );\n  }\n}\n\nfunction freezeSqlSchema(fields: SqlSchemaFields): SqlSchema {\n  return new SqlSchemaDescriptor(fields);\n}\n\nfunction isSqlSchema(schema: unknown): schema is SqlSchema {\n  if (typeof schema !== \"object\" || schema === null) return false;\n  const candidate = schema as Record<PropertyKey, unknown>;\n  return (\n    candidate[SQL_SCHEMA_BRAND] === true &&\n    typeof candidate[\"tables\"] === \"object\" &&\n    candidate[\"tables\"] !== null &&\n    Object.isFrozen(candidate[\"tables\"]) &&\n    isSqlFragment(candidate[\"nodesTable\"]) &&\n    isSqlFragment(candidate[\"edgesTable\"]) &&\n    isSqlFragment(candidate[\"recordedNodesTable\"]) &&\n    isSqlFragment(candidate[\"recordedEdgesTable\"]) &&\n    isSqlFragment(candidate[\"recordedClockTable\"]) &&\n    isSqlFragment(candidate[\"revisionOriginsTable\"]) &&\n    isSqlFragment(candidate[\"fulltextTable\"]) &&\n    Object.isFrozen(candidate)\n  );\n}\n\nexport function requireSqlSchema(\n  schema: unknown,\n  surface = \"SqlSchema\",\n): SqlSchema {\n  if (isSqlSchema(schema)) return schema;\n  throw new ConfigurationError(\n    `${surface} must be created with createSqlSchema(...).`,\n    { code: \"INVALID_SQL_SCHEMA\", surface },\n    {\n      suggestion:\n        \"Pass the result of createSqlSchema(...) instead of a plain schema-shaped object.\",\n    },\n  );\n}\n\n/**\n * Creates a SqlSchema configuration from table names.\n *\n * Table names are validated to ensure they are valid SQL identifiers.\n * This prevents SQL injection and ensures compatibility across databases.\n *\n * @param names - Optional custom table names (defaults to standard names)\n * @returns SqlSchema configuration for query compilation\n * @throws Error if any table name is invalid\n *\n * @example\n * ```typescript\n * // Use default table names\n * const schema = createSqlSchema();\n *\n * // Use custom table names\n * const schema = createSqlSchema({\n *   nodes: \"myapp_nodes\",\n *   edges: \"myapp_edges\",\n *   fulltext: \"myapp_fulltext\",\n * });\n * ```\n */\nexport function createSqlSchema(names: Partial<SqlTableNames> = {}): SqlSchema {\n  const tables = resolveTableNames(names);\n\n  // Validate all table names\n  validateTableName(tables.nodes, \"nodes\");\n  validateTableName(tables.edges, \"edges\");\n  validateTableName(tables.recordedNodes, \"recordedNodes\");\n  validateTableName(tables.recordedEdges, \"recordedEdges\");\n  validateTableName(tables.recordedClock, \"recordedClock\");\n  validateTableName(tables.revisionOrigins, \"revisionOrigins\");\n  validateTableName(tables.identityAssertions, \"identityAssertions\");\n  validateTableName(\n    tables.recordedIdentityAssertions,\n    \"recordedIdentityAssertions\",\n  );\n  validateTableName(tables.identityClosure, \"identityClosure\");\n  validateTableName(tables.identitySeparation, \"identitySeparation\");\n  validateTableName(tables.fulltext, \"fulltext\");\n  validateTableName(tables.uniques, \"uniques\");\n  validateTableName(tables.edgeClaims, \"edgeClaims\");\n  validateTableName(tables.fences, \"fences\");\n\n  return freezeSqlSchema({\n    tables: Object.freeze(tables),\n    nodesTable: sql.identifier(tables.nodes),\n    edgesTable: sql.identifier(tables.edges),\n    recordedNodesTable: sql.identifier(tables.recordedNodes),\n    recordedEdgesTable: sql.identifier(tables.recordedEdges),\n    recordedClockTable: sql.identifier(tables.recordedClock),\n    revisionOriginsTable: sql.identifier(tables.revisionOrigins),\n    identityAssertionsTable: sql.identifier(tables.identityAssertions),\n    recordedIdentityAssertionsTable: sql.identifier(\n      tables.recordedIdentityAssertions,\n    ),\n    identityClosureTable: sql.identifier(tables.identityClosure),\n    identitySeparationTable: sql.identifier(tables.identitySeparation),\n    fulltextTable: sql.identifier(tables.fulltext),\n  });\n}\n\n/**\n * The recorded/system-time relation a read coordinate may reconstruct from.\n *\n * TypeGraph's built-in capture relation is bound by `createStore(..., {\n * history: true })`. Hosts can also bind externally populated row-compatible\n * recorded relations through `recordedRelation({ schema })`. Keeping both as\n * explicit values separates the read contract from the write-capture mechanism\n * so future external/TMS-owned recorded relations can feed the same query\n * machinery without changing StoreView or ReadCoordinate.\n */\nconst EXTERNAL_RECORDED_READ_SOURCE: unique symbol = typeGraphGlobalSymbol(\n  \"external-recorded-read-source-v1\",\n);\n\n/**\n * The relation a {@link RecordedReadSource} sources rows from: the two entity\n * tables the query compiler swaps to for a recorded read, and the identity\n * assertion ledger the identity reconstruction path consults.\n */\nexport type RecordedSourceTable = \"nodes\" | \"edges\" | \"identityAssertions\";\n\n/**\n * The one seam every recorded read consults instead of spelling the relation\n * swap and the recorded-time interval itself.\n *\n * `source` names the relation (or table expression) holding `table`'s\n * recorded rows for `revision`. TypeGraph's own capture and external\n * bindings both return the matching recorded relation regardless of\n * `revision` — the relation carries every revision, and `predicate` narrows\n * it afterward. A binding whose `source` already scopes its rows to exactly\n * one revision (an engine-native temporal table expression, say) returns\n * `undefined` from `predicate` instead of re-spelling a redundant filter.\n *\n * `carriesInterval` names the other fact every binding-shape-aware reader\n * needs: whether `source`'s rows carry the `recorded_from`/`recorded_to`\n * columns a TypeGraph-relation-backed source's every revision has. A reader\n * that needs to order or filter on that interval (`recorded-read-service.ts`'s\n * point-read and scan `ORDER BY`) consults this instead of re-deriving the\n * fact from `binding.kind` itself, so a fourth binding kind cannot leave one\n * site still assuming a column the new binding's source does not have.\n */\nexport type RecordedReadSource = Readonly<{\n  source: (\n    table: RecordedSourceTable,\n    revision: RecordedInstantParts,\n  ) => SqlFragment;\n  predicate: (\n    prefix: SqlFragment,\n    revision: RecordedInstantParts,\n  ) => SqlFragment | undefined;\n  carriesInterval: boolean;\n}>;\n\n/**\n * `source`/`predicate` shared by every TypeGraph-relation-backed binding: the\n * recorded relation named by `schema`, narrowed by the `recorded_from <= r\n * AND r < recorded_to` interval every recorded row carries. `recordedRelation`\n * and the built-in capture binding both build their seam this way, so the\n * relation swap and the interval cannot drift apart between the two kinds.\n */\nfunction typeGraphRelationRecordedReadSource(\n  schema: SqlSchema,\n): RecordedReadSource {\n  return {\n    source(\n      table: RecordedSourceTable,\n      _revision: RecordedInstantParts,\n    ): SqlFragment {\n      switch (table) {\n        case \"nodes\": {\n          return schema.recordedNodesTable;\n        }\n        case \"edges\": {\n          return schema.recordedEdgesTable;\n        }\n        case \"identityAssertions\": {\n          return schema.recordedIdentityAssertionsTable;\n        }\n      }\n    },\n    predicate(\n      prefix: SqlFragment,\n      revision: RecordedInstantParts,\n    ): SqlFragment {\n      if (revision.kind !== \"typegraph\") {\n        // Every caller resolves `revision` by parsing the SAME coordinate this\n        // binding was bound to source rows from — reaching here with an\n        // engine-native (`e1`) revision would mean a coordinate minted for one\n        // ownership form reached the read binding of the other, which the\n        // construction-time and asOfRecorded ownership checks both refuse\n        // before a read is ever compiled.\n        throw new CompilerInvariantError(\n          \"A TypeGraph-relation recorded read binding received an engine-native revision.\",\n          { revisionKind: revision.kind },\n        );\n      }\n      const recordedFrom = sql`${prefix}recorded_from`;\n      const recordedTo = sql`${prefix}recorded_to`;\n      const { revision: revisionNumber } = revision;\n      return sql`${recordedFrom} <= ${revisionNumber} AND ${revisionNumber} < ${recordedTo}`;\n    },\n    carriesInterval: true,\n  };\n}\n\nexport type ExternalRecordedReadSource = Readonly<{\n  kind: \"external\";\n  schema: SqlSchema;\n  [EXTERNAL_RECORDED_READ_SOURCE]: true;\n}> &\n  RecordedReadSource;\n\ntype ExternalRecordedReadSourceCandidate = Readonly<{\n  kind?: unknown;\n  schema?: unknown;\n  [EXTERNAL_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nconst TYPEGRAPH_RECORDED_READ_SOURCE: unique symbol = typeGraphGlobalSymbol(\n  \"typegraph-recorded-read-source-v1\",\n);\n\nexport type TypeGraphRecordedReadSource = Readonly<{\n  kind: \"typegraph-capture\";\n  schema: SqlSchema;\n  [TYPEGRAPH_RECORDED_READ_SOURCE]: true;\n}> &\n  RecordedReadSource;\n\nconst ENGINE_RECORDED_READ_SOURCE: unique symbol = typeGraphGlobalSymbol(\n  \"engine-recorded-read-source-v1\",\n);\n\n/**\n * The recorded read binding for a backend that owns recorded time itself\n * (`GraphBackend.recordedTime`, `backend/capabilities/recorded-time.ts`).\n * `source` defers to `recordedTime.source`, converting the parsed\n * engine-native revision into the `EngineRecordedRevision` shape that member\n * expects; `predicate` always returns `undefined` — the engine's own source\n * expression already scopes every row to exactly one revision, so there is no\n * separate interval to layer on top the way the TypeGraph-relation source\n * needs one.\n */\nexport type EngineRecordedReadSource = Readonly<{\n  kind: \"engine-native\";\n  schema: SqlSchema;\n  [ENGINE_RECORDED_READ_SOURCE]: true;\n}> &\n  RecordedReadSource;\n\nexport type RecordedReadBinding =\n  | ExternalRecordedReadSource\n  | TypeGraphRecordedReadSource\n  | EngineRecordedReadSource;\n\n/**\n * Narrows a parsed recorded revision to the engine-native shape\n * `EngineRecordedTimeMembers.source`/`revisionNow` traffic in. Symmetric with\n * `typeGraphRelationRecordedReadSource`'s own guard: a TypeGraph-owned (`r1`)\n * revision reaching an engine-native binding means a coordinate minted for\n * the other ownership form got here, which construction and `asOfRecorded`\n * both refuse ahead of any read.\n */\nfunction requireEngineRecordedRevision(\n  revision: RecordedInstantParts,\n): EngineRecordedRevision {\n  if (revision.kind !== \"engine\") {\n    throw new CompilerInvariantError(\n      \"An engine-native recorded read binding received a TypeGraph-owned revision.\",\n      { revisionKind: revision.kind },\n    );\n  }\n  return { revision: revision.revision, recordedAt: revision.recordedAt };\n}\n\n/**\n * Builds the recorded read binding for an engine-native backend, wrapping its\n * `recordedTime` member as the {@link RecordedReadSource} seam every recorded\n * read consults. `schema` is carried only for shape parity with the other two\n * binding kinds (`recordedReadSqlSchema` still needs a live schema to copy the\n * non-swapped table references from) — the engine's own `source` never reads\n * from it.\n */\nexport function createEngineRecordedReadBinding(\n  recordedTime: EngineRecordedTimeMembers,\n  schema: SqlSchema,\n): EngineRecordedReadSource {\n  const readSchema = requireSqlSchema(\n    schema,\n    \"engine recorded read binding schema\",\n  );\n  return Object.freeze({\n    kind: \"engine-native\",\n    schema: readSchema,\n    [ENGINE_RECORDED_READ_SOURCE]: true as const,\n    source(table: RecordedSourceTable, revision: RecordedInstantParts) {\n      return recordedTime.source(\n        table,\n        requireEngineRecordedRevision(revision),\n      );\n    },\n    predicate(): undefined {\n      return;\n    },\n    carriesInterval: false,\n  });\n}\n\nexport type RecordedRelationOptions = Readonly<{\n  schema: SqlSchema;\n}>;\n\nexport function recordedRelation(\n  options: RecordedRelationOptions,\n): ExternalRecordedReadSource {\n  const schema = requireSqlSchema(options.schema, \"recordedRelation schema\");\n  return Object.freeze({\n    kind: \"external\",\n    schema,\n    [EXTERNAL_RECORDED_READ_SOURCE]: true as const,\n    ...typeGraphRelationRecordedReadSource(schema),\n  });\n}\n\nexport function requireExternalRecordedReadSource(\n  source: unknown,\n): ExternalRecordedReadSource | undefined {\n  if (source === undefined) return undefined;\n  if (isExternalRecordedReadSource(source)) return source;\n  throw new ConfigurationError(\n    \"recordedRead must be created with recordedRelation({ schema }).\",\n    { code: \"INVALID_RECORDED_READ_SOURCE\" },\n    {\n      suggestion:\n        \"Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes.\",\n    },\n  );\n}\n\nfunction isExternalRecordedReadSource(\n  source: unknown,\n): source is ExternalRecordedReadSource {\n  if (typeof source !== \"object\" || source === null) return false;\n  const candidate = source as ExternalRecordedReadSourceCandidate;\n  return (\n    candidate.kind === \"external\" &&\n    candidate[EXTERNAL_RECORDED_READ_SOURCE] === true &&\n    isSqlSchema(candidate.schema) &&\n    Object.isFrozen(candidate)\n  );\n}\n\nexport function createRecordedReadBinding(\n  schema: SqlSchema,\n): TypeGraphRecordedReadSource {\n  const readSchema = requireSqlSchema(schema, \"recorded read binding schema\");\n  return Object.freeze({\n    kind: \"typegraph-capture\",\n    schema: readSchema,\n    [TYPEGRAPH_RECORDED_READ_SOURCE]: true as const,\n    ...typeGraphRelationRecordedReadSource(readSchema),\n  });\n}\n\nexport function requireRecordedReadBinding(\n  binding: unknown,\n  surface: string,\n): RecordedReadBinding {\n  if (isRecordedReadBinding(binding)) return binding;\n  if (binding !== undefined) {\n    throw new ConfigurationError(\n      \"Recorded-time reads require a recorded read relation created by TypeGraph.\",\n      { code: \"INVALID_RECORDED_READ_BINDING\", surface },\n      {\n        suggestion:\n          \"Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object.\",\n      },\n    );\n  }\n  throw new ConfigurationError(\n    \"Recorded-time reads require a recorded read relation.\",\n    { code: \"RECORDED_READ_REQUIRES_BINDING\", surface },\n    {\n      suggestion:\n        \"Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n    },\n  );\n}\n\ntype TypeGraphRecordedReadSourceCandidate = Readonly<{\n  kind?: unknown;\n  schema?: unknown;\n  [TYPEGRAPH_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nfunction isTypeGraphRecordedReadSource(\n  source: unknown,\n): source is TypeGraphRecordedReadSource {\n  if (typeof source !== \"object\" || source === null) return false;\n  const candidate = source as TypeGraphRecordedReadSourceCandidate;\n  return (\n    candidate.kind === \"typegraph-capture\" &&\n    candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true &&\n    isSqlSchema(candidate.schema) &&\n    Object.isFrozen(candidate)\n  );\n}\n\ntype EngineRecordedReadSourceCandidate = Readonly<{\n  kind?: unknown;\n  schema?: unknown;\n  [ENGINE_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nfunction isEngineRecordedReadSource(\n  source: unknown,\n): source is EngineRecordedReadSource {\n  if (typeof source !== \"object\" || source === null) return false;\n  const candidate = source as EngineRecordedReadSourceCandidate;\n  return (\n    candidate.kind === \"engine-native\" &&\n    candidate[ENGINE_RECORDED_READ_SOURCE] === true &&\n    isSqlSchema(candidate.schema) &&\n    Object.isFrozen(candidate)\n  );\n}\n\nfunction isRecordedReadBinding(\n  binding: unknown,\n): binding is RecordedReadBinding {\n  return (\n    isExternalRecordedReadSource(binding) ||\n    isTypeGraphRecordedReadSource(binding) ||\n    isEngineRecordedReadSource(binding)\n  );\n}\n\n/**\n * Returns a schema view whose primary node/edge sources are the recorded-time\n * relations for `revision`, resolved through `binding.source` — the single\n * place the relation swap and the recorded-time predicate ({@link\n * recordedReadSchemaFor}'s caller, via `compileTemporalFilter`) both consult\n * the same seam. The recorded relations are row-compatible with the live\n * tables for every column the query compiler, subgraph extractor, and\n * algorithms already read.\n */\nexport function recordedReadSqlSchema(\n  binding: RecordedReadBinding,\n  revision: RecordedInstantParts,\n): SqlSchema {\n  const validated = requireRecordedReadBinding(binding, \"recorded-read-schema\");\n  const { schema } = validated;\n  return freezeSqlSchema({\n    tables: schema.tables,\n    nodesTable: validated.source(\"nodes\", revision),\n    edgesTable: validated.source(\"edges\", revision),\n    recordedNodesTable: schema.recordedNodesTable,\n    recordedEdgesTable: schema.recordedEdgesTable,\n    recordedClockTable: schema.recordedClockTable,\n    revisionOriginsTable: schema.revisionOriginsTable,\n    identityAssertionsTable: schema.identityAssertionsTable,\n    recordedIdentityAssertionsTable: schema.recordedIdentityAssertionsTable,\n    identityClosureTable: schema.identityClosureTable,\n    identitySeparationTable: schema.identitySeparationTable,\n    fulltextTable: schema.fulltextTable,\n  });\n}\n\n/**\n * Resolves the read schema for a coordinate: the live schema when no recorded\n * pin is set, or the recorded-relation view when `recordedAsOf` is present. The\n * single place every read path decides whether to source the recorded tables.\n */\nexport function recordedReadSchemaFor(\n  schema: SqlSchema,\n  recordedAsOf: string | undefined,\n  binding: RecordedReadBinding | undefined,\n  surface: string,\n): SqlSchema {\n  const baseSchema = requireSqlSchema(schema, `${surface} schema`);\n  if (recordedAsOf === undefined) return baseSchema;\n  const revision = parseRecordedInstant(recordedAsOf, \"recordedAsOf\");\n  return recordedReadSqlSchema(\n    requireRecordedReadBinding(binding, surface),\n    revision,\n  );\n}\n\n/**\n * Default SqlSchema using standard TypeGraph table names.\n */\nexport const DEFAULT_SQL_SCHEMA: SqlSchema = createSqlSchema();\n\n/**\n * The compiler's resolved view of one declared embedding field — the\n * `(dimensions, metric, indexType)` a {@link VectorStrategy} needs to\n * name and scan the field's typed per-`(kind, field)` storage. Sourced\n * from the registered node schema's `embedding()` declaration when the\n * store builds its compile options.\n */\nexport type VectorSlotDescriptor = Readonly<{\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n}>;\n\n/**\n * Map of declared embedding slots keyed by {@link vectorSlotKey} -\n * `\"<nodeKind>\\0<fieldPath>\"` (NUL-separated). Carries every `(concrete kind,\n * fieldPath)` that declares an embedding field, so the compiler's\n * `field.similarTo(...)` CTE can UNION ALL the per-field tables for the\n * kinds in an alias that actually declare the field (only\n * `includeSubClasses` yields more than one).\n */\nexport type VectorSlotMap = ReadonlyMap<string, VectorSlotDescriptor>;\n\n/** NUL-delimited composite key for {@link VectorSlotMap}. */\nexport function vectorSlotKey(nodeKind: string, fieldPath: string): string {\n  return `${nodeKind}\\u0000${fieldPath}`;\n}\n\n/**\n * CTE aliases used by the standard query emitter. Joining on these names\n * across multiple builder files is fragile when typed as raw strings —\n * import these constants instead.\n */\nexport const ALIAS_CTE_PREFIX = \"cte_\" as const;\nexport const EMBEDDINGS_CTE_ALIAS = \"cte_embeddings\" as const;\nexport const FULLTEXT_CTE_ALIAS = \"cte_fulltext\" as const;\nexport const HYBRID_CANDIDATES_CTE_ALIAS = \"cte_relevance_candidates\" as const;\n","/**\n * Cross-dialect detection of \"this relation does not exist yet\" errors.\n *\n * Shared so the schema bootstrap (`loadActiveSchemaWithBootstrap`) and\n * the durable contribution-materialization gate (#135) agree on what a\n * missing-table failure looks like, and — critically — so neither one\n * swallows a genuine system fault (connection/permission/driver error)\n * as a benign \"not bootstrapped yet\".\n *\n * Detection walks the error's `cause` chain because Drizzle (>= the\n * `DrizzleQueryError` era, drizzle-orm ≥ 0.36) wraps every failure from a\n * query-builder call (`db.select()`, `db.insert()`, …): the wrapper's\n * `.message` becomes the failed query text and the real driver error —\n * which carries both the missing-relation text and the SQLSTATE — is\n * preserved on `.cause`. node-postgres / postgres-js nest the pg error\n * one link deep; better-sqlite3 throws it unwrapped; raw `client.query()`\n * fast paths surface it directly. Walking the chain makes the check\n * wrapper- and driver-agnostic instead of only matching the outermost\n * `.message`, which on Postgres is just the SQL string.\n */\n\nimport { ConfigurationError } from \"../errors\";\n\nconst SQLITE_MISSING_TABLE_PATTERN = \"no such table\";\nconst SQLITE_GENERIC_ERROR_CODE = \"SQLITE_ERROR\";\nconst SQLITE_NOT_AUTHORIZED_CODE = \"SQLITE_AUTH\";\n\n/**\n * SQLite's EXTENDED result code for \"this read transaction cannot become a\n * write transaction\": the connection began a DEFERRED transaction, took a read\n * snapshot, and another connection has committed since. SQLite refuses the\n * upgrade because honoring it would let the writer act on a stale view; the\n * only recovery is `ROLLBACK` and a fresh transaction (SQLite's own rule — the\n * failure is not retryable in place).\n *\n * It is the one code that names the DEFERRED frame itself. A transaction opened\n * `BEGIN IMMEDIATE` holds the writer slot from the start and can never produce\n * it, and plain `SQLITE_BUSY` says something else entirely (\"another writer\n * holds the slot right now\"), so this code alone can be attributed to how the\n * transaction was begun. The numeric spelling is accepted for libSQL, which\n * surfaces only `rawCode`/`extendedCode` over a remote connection.\n */\nconst SQLITE_STALE_SNAPSHOT_CODE = \"SQLITE_BUSY_SNAPSHOT\";\nconst SQLITE_STALE_SNAPSHOT_EXTENDED_CODE = 517;\n\n/** A SQLite writer-slot wait failure, excluding stale DEFERRED snapshots. */\nexport function isSqliteWriterSlotBusy(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    const code: unknown = Reflect.get(link, \"code\");\n    if (code === SQLITE_STALE_SNAPSHOT_CODE) return false;\n    if (code === \"SQLITE_BUSY\" || code === \"SQLITE_LOCKED\") return true;\n  }\n  return false;\n}\nconst DRIZZLE_QUERY_ERROR_PREFIX = \"Failed query:\";\nconst POSTGRES_UNDEFINED_RELATION_PATTERN =\n  /\\b(?:relation|table)\\s+\"[^\"]+\"\\s+does not exist\\b/i;\n\n/**\n * SQLSTATE for PostgreSQL `undefined_table`. Preferred over the\n * human-readable message: it is locale-independent (the \"... does not\n * exist\" text is translated under a non-English `lc_messages`) and is\n * preserved on the underlying driver error even when Drizzle overwrites\n * `.message` with the query text.\n */\nconst POSTGRES_UNDEFINED_TABLE_CODE = \"42P01\";\nconst POSTGRES_UNIQUE_VIOLATION_CODE = \"23505\";\nconst POSTGRES_NOT_NULL_VIOLATION_CODE = \"23502\";\n\n/**\n * SQLSTATEs a racing IDEMPOTENT DDL statement loses with — the ones that mean\n * \"another session is committing the very thing this statement asks for\", not\n * \"this statement is wrong\".\n *\n * PostgreSQL's `IF NOT EXISTS` is not a concurrency primitive: the existence\n * check cannot see another session's uncommitted catalog rows, so the loser\n * waits for the winner and is then handed the conflict the winner's commit\n * produced — `unique_violation` (23505) from `pg_type`/`pg_class` for a racing\n * CREATE, `duplicate_column` (42701) for a racing `ALTER TABLE ... ADD COLUMN\n * IF NOT EXISTS`, and `duplicate_object` (42710) for a racing named constraint.\n * Retrying once after that wait observes the committed object and succeeds; a\n * failure the retry cannot clear stays loud.\n */\nconst POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES = [\n  POSTGRES_UNIQUE_VIOLATION_CODE,\n  \"42701\",\n  \"42710\",\n] as const;\n\n/**\n * The one concurrent-DDL race PostgreSQL reports with no SQLSTATE of its own:\n * `heap_update` losing a catalog row to a concurrent updater raises\n * `elog(ERROR, \"tuple concurrently updated\")`, which carries the catch-all\n * `internal_error` (XX000).\n *\n * XX000 alone is far too broad to retry on — it covers genuine server faults —\n * so this shape is identified by SQLSTATE AND message together. Matching the\n * message is sound here specifically because `elog` emits it through\n * `errmsg_internal`, which is NOT run through gettext: unlike an `ereport`\n * message, it reads identically under every `lc_messages`.\n */\nconst POSTGRES_INTERNAL_ERROR_CODE = \"XX000\";\nconst POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE = \"tuple concurrently updated\";\n\n/**\n * PostgreSQL failures that mean a temporary table cannot be created here:\n * `read_only_sql_transaction` (a replica or otherwise read-only execution\n * context) and `insufficient_privilege` (a role without the database `TEMP`\n * privilege).\n */\nconst POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES = [\n  \"25006\",\n  \"42501\",\n] as const;\n\n/**\n * PostgreSQL failures that mean the read-write transaction hosting temporary\n * tables cannot even start. A standby rejects the read-write access mode in\n * the `BEGIN` itself with `feature_not_supported` (\"cannot set transaction\n * read-write mode during recovery\"), so the failure never reaches a\n * `CREATE TEMP TABLE`; a session pinned read-only by a proxy or by\n * `default_transaction_read_only` reports `read_only_sql_transaction`.\n */\nconst POSTGRES_READ_WRITE_REFUSED_SQL_STATES = [\"0A000\", \"25006\"] as const;\n\nexport type PostgresTemporaryTableUnavailableSqlState =\n  (typeof POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES)[number];\n\nexport type PostgresReadWriteRefusedSqlState =\n  (typeof POSTGRES_READ_WRITE_REFUSED_SQL_STATES)[number];\n\n/**\n * Yields an error and each error reachable by following `.cause`,\n * outermost first. `seen` guards the pathological cyclic-cause case so a\n * self-referential chain can't spin forever.\n *\n * The walk intentionally follows `.cause` through *non-`Error`* links, not just\n * `Error` instances: postgres-js surfaces its driver error as a plain object\n * (message + SQLSTATE `code`) on a Drizzle wrapper's `.cause`, so stopping at\n * the first non-`Error` link would miss it (see the postgres-js test). A plain\n * object is classified by its locale-independent SQLSTATE alone\n * ({@link isPostgresUndefinedTable}); the looser SQLite message substring is\n * consulted only for `Error` instances and raw strings\n * ({@link missingTableMessage}), so an unrelated object in a cause chain that\n * merely mentions one of those phrases is not mistaken for a missing table.\n */\nexport function* errorChain(error: unknown): Generator<unknown, void, void> {\n  const seen = new Set<unknown>();\n  let current: unknown = error;\n  while (current !== undefined && current !== null && !seen.has(current)) {\n    seen.add(current);\n    yield current;\n    current =\n      canReadProperty(current) ? Reflect.get(current, \"cause\") : undefined;\n  }\n}\n\nfunction canReadProperty(value: unknown): value is object {\n  return (\n    (typeof value === \"object\" && value !== null) || typeof value === \"function\"\n  );\n}\n\n/**\n * Whether a single chain link is a PostgreSQL `undefined_table` failure,\n * identified by its SQLSTATE rather than a message substring.\n */\nfunction isPostgresUndefinedTable(link: unknown): boolean {\n  return (\n    canReadProperty(link) &&\n    Reflect.get(link, \"code\") === POSTGRES_UNDEFINED_TABLE_CODE\n  );\n}\n\nfunction messageProperty(link: unknown): string | undefined {\n  if (typeof link === \"string\") return link;\n  if (link instanceof Error) return link.message;\n  const message =\n    canReadProperty(link) ?\n      (Reflect.get(link, \"message\") as unknown)\n    : undefined;\n  return typeof message === \"string\" ? message : undefined;\n}\n\nfunction errorMessage(link: unknown): string {\n  return messageProperty(link) ?? String(link);\n}\n\n/**\n * The message a SQLite missing-table substring match may be tested against — but\n * only for `Error` instances and raw `string` links, never an arbitrary plain\n * object.\n *\n * Generic \"does not exist\" is deliberately not substring-matched: PostgreSQL uses\n * that phrase for undefined columns, functions, types, and relations. PostgreSQL\n * missing tables are classified by SQLSTATE 42P01 when available, or by the\n * narrower driver-message shape `relation/table \"...\" does not exist` when a\n * bring-your-own driver omits SQLSTATE. SQLite does not expose a portable\n * SQLSTATE here, so the narrow \"no such table\" engine message is still accepted.\n */\nfunction missingTableMessage(link: unknown): string | undefined {\n  return typeof link === \"string\" || link instanceof Error ?\n      messageProperty(link)\n    : undefined;\n}\n\nfunction sqliteErrorCode(link: unknown): unknown {\n  if (!canReadProperty(link)) return undefined;\n  return Reflect.get(link, \"code\");\n}\n\n/**\n * SQLite driver messages normalized independently of transport decoration.\n * Native SQLite usually returns the engine text alone, while libSQL prefixes\n * that same text with its symbolic result code. Classifiers compare the\n * canonical engine message so every SQLite error shape has one owner.\n */\nfunction sqliteErrorMessage(link: unknown): string | undefined {\n  const message = messageProperty(link);\n  const code = sqliteErrorCode(link);\n  if (\n    typeof message === \"string\" &&\n    typeof code === \"string\" &&\n    code.startsWith(\"SQLITE_\") &&\n    message.startsWith(`${code}: `)\n  ) {\n    return message.slice(code.length + 2);\n  }\n  return message;\n}\n\n/**\n * Cloudflare D1 / Durable Objects may surface a missing-table failure as the\n * generic SQLite code with no detail. Accept the bare marker, but do not\n * substring-match detailed `SQLITE_ERROR: ...` failures: those include syntax\n * errors and bind-limit faults that must stay loud.\n */\nfunction isBareSqliteErrorMarker(link: unknown): boolean {\n  const message = sqliteErrorMessage(link);\n  if (message === SQLITE_GENERIC_ERROR_CODE) return true;\n  if (sqliteErrorCode(link) !== SQLITE_GENERIC_ERROR_CODE) return false;\n  return (\n    message === undefined ||\n    message === SQLITE_GENERIC_ERROR_CODE ||\n    message.includes(SQLITE_MISSING_TABLE_PATTERN)\n  );\n}\n\nfunction isPostgresUndefinedRelationMessage(link: unknown): boolean {\n  const message = errorMessage(link);\n  if (message.startsWith(DRIZZLE_QUERY_ERROR_PREFIX)) return false;\n  return POSTGRES_UNDEFINED_RELATION_PATTERN.test(message);\n}\n\n/**\n * Whether any link in the cause chain is a PostgreSQL \"insufficient\n * resources\" failure (SQLSTATE class 53: disk_full, out_of_memory,\n * configuration_limit_exceeded, ...). Parallel index builds surface\n * shared-memory exhaustion this way (53100 from dsm_impl_posix on hosts\n * with a small /dev/shm); callers retry such work with parallelism\n * disabled. Identified by the locale-independent 5-character SQLSTATE\n * prefix only — never by message text.\n */\nexport function isInsufficientResourcesError(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    const code: unknown = Reflect.get(link, \"code\");\n    if (typeof code === \"string\" && code.length === 5 && code.startsWith(\"53\"))\n      return true;\n  }\n  return false;\n}\n\nexport function isMissingTableError(error: unknown): boolean {\n  // SQLSTATE 42P01 is locale-independent and structural, so it is honored on\n  // *every* link — including a plain driver-error object reached only by walking\n  // through a non-`Error` `.cause` (postgres-js).\n  //\n  // The SQLite message substring is honored only while every prior link in the\n  // chain was an `Error` (or the top-level string) — the reach of the\n  // pre-broadening walk, which stopped at the first non-`Error` `.cause`.\n  let everyPriorLinkWasError = true;\n  for (const link of errorChain(error)) {\n    if (isPostgresUndefinedTable(link)) return true;\n    if (isPostgresUndefinedRelationMessage(link)) return true;\n    if (isBareSqliteErrorMarker(link)) return true;\n    if (everyPriorLinkWasError) {\n      const message = missingTableMessage(link);\n      if (message?.includes(SQLITE_MISSING_TABLE_PATTERN) === true) {\n        return true;\n      }\n    }\n    if (!(link instanceof Error)) everyPriorLinkWasError = false;\n  }\n  return false;\n}\n\n/** Whether one chain link is the un-coded `tuple concurrently updated` race. */\nfunction isPostgresConcurrentTupleUpdate(link: unknown): boolean {\n  if (!canReadProperty(link)) return false;\n  if (Reflect.get(link, \"code\") !== POSTGRES_INTERNAL_ERROR_CODE) return false;\n  return (\n    messageProperty(link)?.includes(\n      POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE,\n    ) === true\n  );\n}\n\n/**\n * Whether PostgreSQL refused an IDEMPOTENT DDL statement because another\n * session was concurrently committing the same catalog change — the single\n * owner of \"this DDL lost a race and is worth one retry\".\n *\n * Every idempotent-DDL site in the codebase classifies through this one\n * function: the Postgres backend's `executeConcurrentCreateDdl` (bootstrap\n * tables, contribution materialization, identity relations, the index\n * materialization table and its additive columns) and the identity\n * schema-transition retry. A second copy of the predicate would drift the\n * moment one site learned about a new race SQLSTATE — as `ALTER TABLE ... ADD\n * COLUMN IF NOT EXISTS` (42701) did (#445).\n *\n * Callers MUST use it only around DDL that is a no-op when the object already\n * exists. On any other statement 23505/42701 are real defects, and retrying\n * them would hide a duplicate write.\n */\nexport function isPostgresConcurrentDdlRaceError(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    if (\n      isSqlStateIn(\n        Reflect.get(link, \"code\"),\n        POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES,\n      )\n    ) {\n      return true;\n    }\n    if (isPostgresConcurrentTupleUpdate(link)) return true;\n  }\n  return false;\n}\n\n/**\n * The PostgreSQL error fields naming the violated constraint and its relation.\n * Both spellings are read because the drivers disagree: node-postgres and\n * PGlite expose the protocol fields as `constraint` / `table`, while\n * postgres-js exposes them as `constraint_name` / `table_name`. Reading only\n * one spelling would silently classify nothing on the other driver.\n */\nconst POSTGRES_CONSTRAINT_FIELDS = [\"constraint\", \"constraint_name\"] as const;\nconst POSTGRES_RELATION_FIELDS = [\"table\", \"table_name\"] as const;\nconst POSTGRES_COLUMN_FIELDS = [\"column\", \"column_name\"] as const;\n\n/**\n * SQLite's EXTENDED result code for a primary-key duplicate, in both spellings a\n * driver reports it: the symbolic name (better-sqlite3 `code`, and the\n * `SqliteError` the libSQL client nests on its own error's `.cause`) and the\n * numeric value (libSQL `rawCode` / `extendedCode`, the only form a remote\n * connection surfaces).\n *\n * The extended code — not the base `SQLITE_CONSTRAINT` — is what makes the\n * classification possible at all: SQLite distinguishes a PRIMARY KEY duplicate\n * (1555) from any other unique-index duplicate (`SQLITE_CONSTRAINT_UNIQUE`,\n * 2067) in the code itself, so nothing has to read the message, which names the\n * columns rather than the constraint.\n */\nconst SQLITE_PRIMARY_KEY_VIOLATION_CODE = \"SQLITE_CONSTRAINT_PRIMARYKEY\";\nconst SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE = 1555;\nconst SQLITE_UNIQUE_VIOLATION_CODE = \"SQLITE_CONSTRAINT_UNIQUE\";\nconst SQLITE_UNIQUE_VIOLATION_EXTENDED_CODE = 2067;\nconst SQLITE_NOT_NULL_VIOLATION_CODE = \"SQLITE_CONSTRAINT_NOTNULL\";\nconst SQLITE_NOT_NULL_VIOLATION_EXTENDED_CODE = 1299;\nconst SQLITE_EXTENDED_CODE_FIELDS = [\"rawCode\", \"extendedCode\"] as const;\n\n/**\n * A relation plus the names its PRIMARY KEY constraint can carry — how far a\n * duplicate-key classification is allowed to reach on an engine that reports the\n * violated constraint by name. See {@link isDuplicatePrimaryKeyError}.\n */\nexport type PrimaryKeyRelation = Readonly<{\n  table: string;\n  constraintNames: readonly string[];\n  /** SQLite/libSQL's remote protocol reports the violated key by columns. */\n  sqliteColumns: readonly string[];\n}>;\n\nfunction firstStringField(\n  link: object,\n  fields: readonly string[],\n): string | undefined {\n  for (const field of fields) {\n    const value: unknown = Reflect.get(link, field);\n    if (typeof value === \"string\") return value;\n  }\n  return undefined;\n}\n\n/**\n * Whether PostgreSQL reported this link as a duplicate of `relation`'s PRIMARY\n * KEY: SQLSTATE, relation, and constraint name must all agree on the SAME link\n * (the driver error), so a 23505 raised by an unrelated statement deeper in the\n * chain cannot be attributed to this relation.\n */\nfunction isPostgresPrimaryKeyViolation(\n  link: object,\n  relation: PrimaryKeyRelation,\n): boolean {\n  if (Reflect.get(link, \"code\") !== POSTGRES_UNIQUE_VIOLATION_CODE)\n    return false;\n  if (firstStringField(link, POSTGRES_RELATION_FIELDS) !== relation.table) {\n    return false;\n  }\n  const constraint = firstStringField(link, POSTGRES_CONSTRAINT_FIELDS);\n  return (\n    constraint !== undefined && relation.constraintNames.includes(constraint)\n  );\n}\n\n/**\n * Whether SQLite reported this link as a PRIMARY KEY duplicate. Native SQLite\n * reports an extended code; remote libSQL reports only the generic constraint\n * code and the complete violated-column message, so the relation's columns\n * are also checked for that transport shape.\n */\nfunction isSqlitePrimaryKeyViolation(\n  link: object,\n  relation: PrimaryKeyRelation,\n): boolean {\n  if (Reflect.get(link, \"code\") === SQLITE_PRIMARY_KEY_VIOLATION_CODE) {\n    return true;\n  }\n  for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n    const value: unknown = Reflect.get(link, field);\n    if (\n      typeof value === \"number\" &&\n      value === SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE\n    ) {\n      return true;\n    }\n  }\n  if (Reflect.get(link, \"code\") !== \"SQLITE_CONSTRAINT\") return false;\n  const message = sqliteErrorMessage(link);\n  const expectedColumns = relation.sqliteColumns\n    .map((column) => `${relation.table}.${column}`)\n    .join(\", \");\n  return message === `UNIQUE constraint failed: ${expectedColumns}`;\n}\n\n/**\n * Whether the engine refused a statement because it duplicated a PRIMARY KEY —\n * on PostgreSQL, `relation`'s specifically.\n *\n * Classification is structural: SQLSTATE and SQLite extended result codes, plus\n * the PostgreSQL protocol's own constraint and relation fields. Never message\n * text, which is translated under a non-English `lc_messages`, is overwritten\n * with the query string by Drizzle's wrapper, and on SQLite names the key's\n * COLUMNS rather than the constraint. The `.cause` chain is walked because every\n * driver here nests the real error under at least one wrapper.\n *\n * Narrowing to the primary key is the whole point. A `unique: true` index\n * declaration materializes a UNIQUE INDEX on the same relation, and violating\n * THAT is a declared-uniqueness failure about the row's VALUES, not a duplicate\n * identity. PostgreSQL reports it under the index's own name and SQLite under a\n * different extended code, so it never matches here and keeps surfacing as it\n * did before.\n *\n * `relation` scopes the PostgreSQL arm, which is the one that can see a\n * constraint name. SQLite reports no relation at all, so its scope comes from\n * the CALL SITE instead: callers must invoke this only for a statement that\n * writes exactly one relation — the node or edge insert — where a primary-key\n * duplicate can only be that relation's. Applying it to a multi-relation\n * statement would attribute the wrong table's collision.\n */\nexport function isDuplicatePrimaryKeyError(\n  error: unknown,\n  relation: PrimaryKeyRelation,\n): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    if (isPostgresPrimaryKeyViolation(link, relation)) return true;\n    if (isSqlitePrimaryKeyViolation(link, relation)) return true;\n  }\n  return false;\n}\n\n/**\n * Whether the engine refused a known NOT NULL sentinel emitted by a write\n * program. PostgreSQL supplies relation and column protocol fields; SQLite\n * supplies a NOT NULL extended code and identifies the column in its stable\n * constraint report. No other failure is allowed to trigger a specialized\n * write diagnostic.\n */\nexport function isNotNullColumnViolation(\n  error: unknown,\n  relation: Readonly<{ table: string; column: string }>,\n): boolean {\n  const expectedSqliteMessage = `NOT NULL constraint failed: ${relation.table}.${relation.column}`;\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    if (\n      Reflect.get(link, \"code\") === POSTGRES_NOT_NULL_VIOLATION_CODE &&\n      firstStringField(link, POSTGRES_RELATION_FIELDS) === relation.table &&\n      firstStringField(link, POSTGRES_COLUMN_FIELDS) === relation.column\n    ) {\n      return true;\n    }\n    const code: unknown = Reflect.get(link, \"code\");\n    const isSqliteNotNullViolation =\n      code === SQLITE_NOT_NULL_VIOLATION_CODE ||\n      code === \"SQLITE_CONSTRAINT\" ||\n      SQLITE_EXTENDED_CODE_FIELDS.some(\n        (field) =>\n          Reflect.get(link, field) === SQLITE_NOT_NULL_VIOLATION_EXTENDED_CODE,\n      );\n    if (\n      sqliteErrorMessage(link) === expectedSqliteMessage &&\n      (isSqliteNotNullViolation || code === undefined)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Whether the engine reported a duplicate of one unique index.\n *\n * PostgreSQL identifies the index directly. SQLite exposes only its extended\n * result code and ordered column list, so both must match; the result code by\n * itself would misclassify every other unique index on the relation.\n */\nexport function isDuplicateUniqueIndexError(\n  error: unknown,\n  relation: Readonly<{\n    table: string;\n    indexName: string;\n    sqliteColumns: readonly string[];\n  }>,\n): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    if (\n      Reflect.get(link, \"code\") === POSTGRES_UNIQUE_VIOLATION_CODE &&\n      firstStringField(link, POSTGRES_RELATION_FIELDS) === relation.table &&\n      firstStringField(link, POSTGRES_CONSTRAINT_FIELDS) === relation.indexName\n    ) {\n      return true;\n    }\n    const isSqliteUniqueViolation =\n      Reflect.get(link, \"code\") === SQLITE_UNIQUE_VIOLATION_CODE ||\n      Reflect.get(link, \"code\") === \"SQLITE_CONSTRAINT\" ||\n      SQLITE_EXTENDED_CODE_FIELDS.some(\n        (field) =>\n          Reflect.get(link, field) === SQLITE_UNIQUE_VIOLATION_EXTENDED_CODE,\n      );\n    const message = sqliteErrorMessage(link);\n    const expectedColumns = relation.sqliteColumns\n      .map((column) => `${relation.table}.${column}`)\n      .join(\", \");\n    if (\n      isSqliteUniqueViolation &&\n      message === `UNIQUE constraint failed: ${expectedColumns}`\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/** Whether SQLite DDL named one of the two absent match-identity columns. */\nexport function isSqliteMissingEdgeMatchIdentityColumnError(\n  error: unknown,\n): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    const code: unknown = Reflect.get(link, \"code\");\n    const message = sqliteErrorMessage(link);\n    if (\n      code === \"SQLITE_ERROR\" &&\n      typeof message === \"string\" &&\n      /^(?:no such column: (?:[^.]+\\.)?|table .+ has no column named |no column named )\"?match_identity_(?:name|key)\"?(?: - should this be a string literal in single-quotes\\?)?$/.test(\n        message,\n      )\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/** Whether a concurrent SQLite adopter already added the column we planned. */\nexport function isSqliteDuplicateEdgeMatchIdentityColumnError(\n  error: unknown,\n): boolean {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    if (Reflect.get(link, \"code\") !== \"SQLITE_ERROR\") continue;\n    const message = sqliteErrorMessage(link);\n    if (\n      message === \"duplicate column name: match_identity_name\" ||\n      message === \"duplicate column name: match_identity_key\"\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Whether a durable convergence statement proved that the adapter's static\n * capability declaration has not been provisioned in this database yet.\n *\n * This runtime-DML classifier deliberately includes missing conflict arbiters\n * as well as missing columns. Provisioning code must instead use the narrower\n * SQLite column predicate above before it performs any DDL.\n */\nexport function isEdgeMatchIdentityStorageUnavailableError(\n  error: unknown,\n): boolean {\n  if (isSqliteMissingEdgeMatchIdentityColumnError(error)) return true;\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    const code: unknown = Reflect.get(link, \"code\");\n    if (code === \"42P10\") return true;\n    const message = sqliteErrorMessage(link);\n    if (code === \"42703\") {\n      const column = firstStringField(link, [\"column\"]);\n      if (column === \"match_identity_name\" || column === \"match_identity_key\") {\n        return true;\n      }\n      if (\n        typeof message === \"string\" &&\n        /\\bmatch_identity_(?:name|key)\\b/i.test(message)\n      ) {\n        return true;\n      }\n    }\n    if (\n      code === \"SQLITE_ERROR\" &&\n      message ===\n        \"ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint\"\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isSqlStateIn<SqlState extends string>(\n  code: unknown,\n  states: readonly SqlState[],\n): code is SqlState {\n  const known: readonly string[] = states;\n  return typeof code === \"string\" && known.includes(code);\n}\n\n/**\n * The first SQLSTATE in the error's cause chain that belongs to `states`. The\n * walk handles both direct driver errors and wrappers such as\n * DrizzleQueryError, which keeps the SQLSTATE-bearing error on `.cause`.\n */\nfunction matchSqlState<SqlState extends string>(\n  error: unknown,\n  states: readonly SqlState[],\n): SqlState | undefined {\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) continue;\n    const code: unknown = Reflect.get(link, \"code\");\n    if (isSqlStateIn(code, states)) return code;\n  }\n  return undefined;\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE that prevented temporary-table creation.\n *\n * Callers must use this only at a `CREATE TEMP TABLE` execution seam: 42501\n * is otherwise a generic permission failure, and translating it elsewhere\n * would hide a different authorization problem.\n */\nexport function postgresTemporaryTableUnavailableSqlState(\n  error: unknown,\n): PostgresTemporaryTableUnavailableSqlState | undefined {\n  return matchSqlState(error, POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES);\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE with which the server refused to open a\n * read-write transaction.\n *\n * Callers must use this only for a failure raised while opening such a\n * transaction — 0A000 is otherwise a generic \"unsupported feature\" report\n * that any statement can raise.\n */\nexport function postgresReadWriteRefusedSqlState(\n  error: unknown,\n): PostgresReadWriteRefusedSqlState | undefined {\n  return matchSqlState(error, POSTGRES_READ_WRITE_REFUSED_SQL_STATES);\n}\n\n/**\n * Whether SQLite rejected a statement through its authorizer. Cloudflare D1\n * and Durable Objects surface this as `not authorized: SQLITE_AUTH`, usually on\n * a Drizzle wrapper's `.cause`; native drivers may instead expose\n * `code: \"SQLITE_AUTH\"`. Both shapes are structural enough to distinguish from\n * an unrelated permission or connection failure.\n */\nexport function isSqliteNotAuthorizedError(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;\n    const message = messageProperty(link);\n    if (\n      message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true &&\n      message.toLowerCase().includes(\"not authorized\")\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Whether SQLite refused a write because the enclosing DEFERRED transaction's\n * read snapshot went stale before it could take the writer slot\n * ({@link SQLITE_STALE_SNAPSHOT_CODE}).\n *\n * Classified structurally — the extended result code in either spelling a\n * driver reports it (better-sqlite3's symbolic `code`, libSQL's numeric\n * `rawCode`/`extendedCode`) — and never by message: SQLite renders this as the\n * bare, indistinguishable \"database is locked\".\n */\nexport function isSqliteStaleSnapshotError(error: unknown): boolean {\n  for (const link of errorChain(error)) {\n    if (sqliteErrorCode(link) === SQLITE_STALE_SNAPSHOT_CODE) return true;\n    if (!canReadProperty(link)) continue;\n    for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n      if (Reflect.get(link, field) === SQLITE_STALE_SNAPSHOT_EXTENDED_CODE) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * PostgreSQL SQLSTATEs for a transaction that did not commit and whose\n * documented recovery is to re-run it, verbatim, from the top:\n * `serialization_failure` (40001, raised under `SERIALIZABLE`/`REPEATABLE\n * READ` when a concurrent transaction's writes conflict with this one's\n * reads) and `deadlock_detected` (40P01, raised when the lock manager breaks\n * a cycle by aborting one participant). Neither means the statement itself\n * was wrong.\n */\nconst SERIALIZATION_FAILURE_SQL_STATES = [\"40001\", \"40P01\"] as const;\n\n/**\n * The shape of a SQLSTATE: five upper-case alphanumerics. Distinguishes an\n * engine verdict (`23505`) from a code some other layer minted (a\n * `TypeGraphError`'s `GRAPH_MERGE_ERROR`, a socket's `ECONNRESET`), which\n * says nothing about how the engine classified the failure.\n */\nconst SQL_STATE_SHAPE = /^[0-9A-Z]{5}$/;\n\n/**\n * Driver-message fallback for a serialization failure whose SQLSTATE was\n * dropped by a wrapper. Matches the fixed PostgreSQL texts for the two\n * SQLSTATEs above.\n *\n * Never consulted when any link carries a SQLSTATE other than the two\n * above: the engine has already classified that failure. Otherwise\n * consulted per link, not chain-wide: a link is a candidate for the message\n * match only when that same link's own `code` is not a string — a link that\n * carries some other coded failure (a unique violation, say) has already\n * been classified by the engine, so its message is never consulted even\n * though a sibling link elsewhere in the chain is coded too. This matters\n * because every {@link TypeGraphError} carries a string `code`: a driver\n * error with no SQLSTATE that gets wrapped in one (graph-merge's commit\n * retry sees exactly this shape) must still have ITS OWN message checked.\n * Raw string links are never candidates either — a bare string cannot carry\n * a `code` of its own, so treating it as message evidence would recognize\n * strings the SQLSTATE pass could never corroborate.\n */\nconst SERIALIZATION_FAILURE_MESSAGE_PATTERN =\n  /could not serialize access|deadlock detected/i;\n\n/**\n * Per-backend serialization-failure classifiers a profile registers through\n * {@link registerSerializationFailureClassifier} — one entry per built\n * backend object, keyed by identity so a classifier this module never saw\n * cannot be forged onto an unrelated target.\n *\n * A `SqlEngineProfile.execution.serializationFailure` exists for an engine\n * whose commit-conflict SQLSTATE is not PostgreSQL's `40001`/`40P01`: this\n * map is what lets {@link isSerializationFailure} consult that engine's own\n * classifier before falling back to the SQLSTATE/message rules below, while\n * staying the one predicate every retry owner calls.\n */\nconst SERIALIZATION_FAILURE_CLASSIFIERS = new WeakMap<\n  object,\n  (error: unknown) => boolean\n>();\n\n/**\n * Registers `classifier` as `target`'s serialization-failure classifier.\n * `createSqlBackend` is the one caller, on the exact backend object it is\n * about to return, for a profile that declares\n * `execution.serializationFailure`.\n *\n * @internal\n */\nexport function registerSerializationFailureClassifier(\n  target: object,\n  classifier: (error: unknown) => boolean,\n): void {\n  SERIALIZATION_FAILURE_CLASSIFIERS.set(target, classifier);\n}\n\n/**\n * Carries a registered classifier from `base` onto `derived` — the same\n * \"carry, never copy\" contract every other backend-identity mark follows.\n * `src/backend/derive-backend.ts` is the only module allowed to call this,\n * alongside its calls to the other carry functions.\n *\n * @internal\n */\nexport function carrySerializationFailureClassifier(\n  derived: object,\n  base: object,\n): void {\n  const classifier = SERIALIZATION_FAILURE_CLASSIFIERS.get(base);\n  if (classifier !== undefined) {\n    SERIALIZATION_FAILURE_CLASSIFIERS.set(derived, classifier);\n  }\n}\n\n/**\n * Whether `error` (or anything in its `.cause` chain) is a PostgreSQL\n * transaction-conflict failure that the documented protocol says to retry by\n * re-running the whole transaction: a serialization failure or a deadlock.\n *\n * `target` — when supplied — is consulted FIRST against\n * {@link SERIALIZATION_FAILURE_CLASSIFIERS}: a profile-declared classifier\n * for an engine whose commit-conflict shape is not PostgreSQL's own ADDS to\n * the standard rules rather than replacing them — recognizing `error` as a\n * conflict wins outright, but the classifier declining is not the final\n * word, and this function's own SQLSTATE/message rules still run for that\n * call. Classification otherwise prefers the locale-independent SQLSTATE and\n * falls back to the fixed driver message on a per-link basis for links with\n * no `code` of their own (see {@link SERIALIZATION_FAILURE_MESSAGE_PATTERN}).\n * This is the one predicate every retry owner in the codebase consults; a\n * second, inline reimplementation of this decision is a defect even while it\n * agrees with this one, because the two WILL drift.\n */\nexport function isSerializationFailure(\n  error: unknown,\n  target?: object,\n): boolean {\n  if (target !== undefined) {\n    const classifier = SERIALIZATION_FAILURE_CLASSIFIERS.get(target);\n    if (classifier?.(error)) return true;\n  }\n  const uncodedLinks: unknown[] = [];\n  let sawOtherSqlState = false;\n  for (const link of errorChain(error)) {\n    if (!canReadProperty(link)) {\n      uncodedLinks.push(link);\n      continue;\n    }\n    const code: unknown = Reflect.get(link, \"code\");\n    if (isSqlStateIn(code, SERIALIZATION_FAILURE_SQL_STATES)) return true;\n    if (typeof code !== \"string\") {\n      uncodedLinks.push(link);\n    } else if (SQL_STATE_SHAPE.test(code)) {\n      sawOtherSqlState = true;\n    }\n  }\n  // The engine already classified this failure as something else: a wrapper\n  // whose message merely quotes conflict text (a parameter literal, a\n  // statement's own error string) must not turn a unique violation into a\n  // retried conflict.\n  if (sawOtherSqlState) return false;\n  for (const link of uncodedLinks) {\n    if (typeof link === \"string\") continue;\n    const message = messageProperty(link);\n    if (\n      typeof message === \"string\" &&\n      SERIALIZATION_FAILURE_MESSAGE_PATTERN.test(message)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction historyMissingRecordedRelationsError(\n  details: Record<string, unknown>,\n  cause: unknown,\n): ConfigurationError {\n  return new ConfigurationError(\n    \"history: true requires the recorded-time relations to exist, but a recorded relation is missing.\",\n    details,\n    {\n      cause,\n      suggestion:\n        \"Create the recorded-time relations (typegraph_recorded_nodes, typegraph_recorded_edges, typegraph_recorded_clock) — e.g. re-run the generated migration SQL — on this database before enabling history capture.\",\n    },\n  );\n}\n\n/**\n * Converts missing recorded-relation failures into the actionable precondition\n * error used by construction-time history checks. Capture paths use this after\n * the live write has already succeeded inside the same transaction; recorded\n * read paths use it when query/schema swapping reaches a recorded table that\n * has not been materialized yet.\n */\nexport async function withRecordedRelationsPrecondition<T>(\n  promise: Promise<T>,\n  details: Record<string, unknown>,\n): Promise<T> {\n  try {\n    return await promise;\n  } catch (error) {\n    if (!isMissingTableError(error)) throw error;\n    throw historyMissingRecordedRelationsError(\n      { ...details, code: \"RECORDED_RELATIONS_MISSING\" },\n      error,\n    );\n  }\n}\n\n/**\n * Engine \"vector dimension mismatch\" message shapes. pgvector:\n * `expected 384 dimensions, not 512`; libSQL / sqlite-vec surface a similar\n * `expected N … got/not M`. The first capture is the dimension the *stored*\n * column expects; the optional second is the dimension that was *attempted*.\n */\nconst DIMENSION_MISMATCH_PATTERN =\n  /expected (\\d+) dimensions(?:[,\\s]+(?:not|got|but got|but)\\s*(\\d+))?/i;\n\n/**\n * Parses an engine vector-dimension-mismatch error into `{ expected, actual }`\n * by walking the `.cause` chain (drivers wrap the real error). `expected` is\n * the stored column's dimension; `actual` (when the message includes it) is the\n * attempted vector's dimension. Returns `undefined` for unrelated errors.\n */\nexport function parseDimensionMismatch(\n  error: unknown,\n): { expected: number; actual: number | undefined } | undefined {\n  for (const link of errorChain(error)) {\n    const message = errorMessage(link);\n    const match = DIMENSION_MISMATCH_PATTERN.exec(message);\n    if (match) {\n      return {\n        expected: Number(match[1]),\n        actual: match[2] === undefined ? undefined : Number(match[2]),\n      };\n    }\n  }\n  return undefined;\n}\n","/**\n * The PILOT capability-bundle registry — DATA ONLY, sibling in spirit to\n * `backend/member-classes.ts`.\n *\n * A bundle is a named set of {@link GraphBackend} member names split into a\n * required core and a set of graduated extras, with a dialect scope, an\n * optional declaration source and cross-check mode, a port-surface refusal\n * code, a per-operation disposition table naming the sites and the extras\n * each operation requires, and one verdict resolver (`resolve.ts`) plus one\n * member accessor (`bind.ts`). It is not a re-shaping of `GraphBackend`.\n *\n * Two definition kinds, because the measurement has two shapes:\n *\n * - A GATED bundle has a non-empty required core (every member required).\n *   Its resolver returns supported-with-core-member-names or\n *   unsupported-with-`missing`. Pilot: `claims`, `statementExecution`,\n *   `recordedRevisionOrigins`.\n * - A GRADUATED bundle has no required core: every member is an extra with\n *   its own measured disposition. Its resolver returns the per-extra verdict\n *   map and no `supported` field at all. Pilot: `uniqueSidecarBatch`,\n *   `batchPointRead`, `contributionHealth`.\n *\n * Deliberately absent, by round-5 ruling (no pilot consumer for either):\n * `arity` on core members, `requiresBundles` edges, `AnyOfSelection`,\n * `CapabilityCoreMember`, `AllOfMembers`, `AnyOfMembers`. Both are designed\n * and seeded for WS5b in the design document's appendix, beside their first\n * real consumers.\n *\n * This is the PILOT of a larger sweep (WS5b): 16 of the 98 optional\n * `GraphBackend` members are bundled here; the other 82 are classified in\n * {@link UNBUNDLED_OPTIONAL_MEMBERS} as either `reasoned` (no bundle should\n * ever own them) or `deferred` (WS5b's seed, with a measured ceiling).\n */\nimport { type SqlDialect } from \"../../query/dialect/types\";\nimport { type Assert, type Equal } from \"../../utils/type-assert\";\nimport { type BackendCapabilities, type GraphBackend } from \"../types\";\n\n/**\n * The keys of `T` that are optional — i.e. `undefined` may stand in for the\n * member without violating the type. `object extends Pick<T, K>` is true\n * exactly when `Pick<T, K>` accepts `{}`, which is true exactly when `K` is\n * optional on `T`.\n */\nexport type OptionalKeys<T> = {\n  [K in keyof T]-?: object extends Pick<T, K> ? K : never;\n}[keyof T];\n\n/**\n * Every optional `GraphBackend` member — 98 of them, verified equal to the\n * names parsed from `etc/typegraph-backend.api.md` (§Baselines). Derived,\n * never hand-written: a member added or removed from `GraphBackend` changes\n * this type automatically, and the totality proof below fails loudly if the\n * registry has not kept up.\n */\nexport type OptionalGraphBackendMember = OptionalKeys<GraphBackend>;\n\n/** How an operation degrades — or refuses — when a member it needs is absent. */\nexport type CapabilityBundleDisposition =\n  /** Absence refuses, with ONE typed error per operation. */\n  | Readonly<{ kind: \"refuse\"; code: string }>\n  /** Absence degrades along a named, tested path. Never refuses. */\n  | Readonly<{ kind: \"fallback\"; fallback: string }>;\n\n/**\n * A graduated extra: present ⇒ a better path, absent ⇒ this exact\n * disposition. `members` is a list because an extra MAY be an all-or-nothing\n * group; every pilot extra is single-membered (the measured group,\n * `indexMaterialization`'s build-claim protocol, is deferred).\n */\nexport type CapabilityBundleExtra<\n  Id extends string,\n  M extends OptionalGraphBackendMember,\n> = Readonly<{\n  id: Id;\n  members: readonly M[];\n  /** REQUIRED, and typed — never a bare `fallback: string`. */\n  disposition: CapabilityBundleDisposition;\n}>;\n\nexport type CapabilityCrossCheck =\n  /** Presence alone. The default, and 5 of the 6 pilot bundles. */\n  | \"none\"\n  /**\n   * Declared-but-missing refuses; implements-without-declaring resolves\n   * supported. One-directional. No bundle uses this today — it exists so a\n   * future cross-check has a shape to grow into, one that must carry its own\n   * justification row when adopted.\n   */\n  | \"declared-implies-members\"\n  /**\n   * Disagreement in EITHER direction refuses. `claims` only — the existing\n   * `CONSTRAINT_CLAIM_SURFACE_MISMATCH`, whose bidirectionality carries a\n   * fence-specific justification (\"a silent fallback would unfence exactly\n   * the writes the capability exists to fence\") that no other family has.\n   */\n  | \"bidirectional\";\n\n/** One inventory key an operation row owns. */\nexport type CapabilityBundleOperationSite = Readonly<{\n  file: string;\n  member: OptionalGraphBackendMember;\n  /**\n   * Disambiguator, required only where one `(file, member)` pair is split\n   * across two or more operation rows. Three pairs need it in the pilot:\n   * `node-operations.ts#checkUniqueBatch`, `guards.ts#executeStatement` and\n   * `migrate-recorded-time.ts#executeStatement`.\n   */\n  lines?: readonly number[];\n  /**\n   * Set when B7's rewiring pass reclassified this site AWAY from `pilot`\n   * instead of rewiring it — additive, optional, and read by nothing but the\n   * inventory/report tooling. `\"deferred\"` names a site whose receiver family\n   * needs plumbing this batch must not force (WS5b's input); `\"reasoned\"`\n   * names one this batch decided a verdict must never gate at all. The\n   * `code`/`disposition` above stay the classification data they always were;\n   * this is a SEPARATE fact about the site, not a replacement for either.\n   */\n  rewiring?: Readonly<{ class: \"deferred\" | \"reasoned\"; reason: string }>;\n}>;\n\n/** Every caller-visible operation that consumes a bundle. */\nexport type CapabilityBundleOperation = Readonly<{\n  /** The caller-visible name that lands in `details.operation`. */\n  operation: string;\n  disposition: CapabilityBundleDisposition;\n  /** The extras this operation needs, by id. */\n  requires?: readonly string[];\n  /** Every inventory key this row owns, as `(file, member)` pairs. */\n  sites: readonly CapabilityBundleOperationSite[];\n  /**\n   * Set only where the site itself reads the declaration to decide between\n   * refusing and degrading. One measured instance in the pilot:\n   * `probeContributions` (`store.ts:4406`).\n   */\n  declarationGate?: true;\n}>;\n\ntype CapabilityBundleCommon = Readonly<{\n  /**\n   * The registry's own id namespace is derived from `CAPABILITY_BUNDLES`\n   * below (never hand-written) — but the derivation cannot be fed back into\n   * THIS type: `CapabilityBundleId` is `(typeof CAPABILITY_BUNDLES)[number]\n   * [\"id\"]`, and `CAPABILITY_BUNDLES` is built from values (`CLAIMS`, …)\n   * whose own type is checked against `CapabilityBundleDefinition` — which\n   * embeds this type. Typing this field `CapabilityBundleId` therefore makes\n   * every bundle constant's type depend on its own initializer\n   * (`TS2502`/`TS2456`, confirmed by compiling the literal design text).\n   * `string` here is the minimal break: each bundle constant still infers\n   * its literal id via `as const`, and `CapabilityBundleId` below is still\n   * wholly derived from `CAPABILITY_BUNDLES`, never hand-written.\n   */\n  id: string;\n  /** Dialects whose first-party factory implements this bundle's core. Default: both. */\n  dialects?: readonly SqlDialect[];\n  /** The `BackendCapabilities` field that DECLARES the bundle, when one exists. */\n  declaration?: keyof BackendCapabilities;\n  /** Read only when not `\"none\"` (ruling F2). */\n  crossCheck: CapabilityCrossCheck;\n  /** The code the MEMBER ACCESSOR throws when the port disagrees with the verdict (I20). */\n  portSurfaceCode: string;\n  operations: readonly CapabilityBundleOperation[];\n}>;\n\n/** A bundle with a required core. */\nexport type GatedBundleDefinition<\n  MCore extends OptionalGraphBackendMember,\n  XId extends string = never,\n  MExtra extends OptionalGraphBackendMember = never,\n> = CapabilityBundleCommon &\n  Readonly<{\n    kind: \"gated\";\n    /** Every name required. No arity wrapper — no pilot bundle has an `any-of` core. */\n    core: readonly MCore[];\n    extras?: readonly CapabilityBundleExtra<XId, MExtra>[];\n    /** The bundle-wide disposition when the CORE is unsatisfied. */\n    disposition: CapabilityBundleDisposition;\n  }>;\n\n/** A bundle with no required core: every member is a graduated extra. */\nexport type GraduatedBundleDefinition<\n  XId extends string,\n  MExtra extends OptionalGraphBackendMember,\n> = CapabilityBundleCommon &\n  Readonly<{\n    kind: \"graduated\";\n    extras: readonly CapabilityBundleExtra<XId, MExtra>[];\n    /** No `disposition`: there is no bundle-level verdict to dispose of. */\n  }>;\n\nexport type CapabilityBundleDefinition =\n  | GatedBundleDefinition<\n      OptionalGraphBackendMember,\n      string,\n      OptionalGraphBackendMember\n    >\n  | GraduatedBundleDefinition<string, OptionalGraphBackendMember>;\n\n// ---------------------------------------------------------------------------\n// The seven pilot bundles — measured, per §Baselines, against this tree.\n// ---------------------------------------------------------------------------\n\n/**\n * `claimSupport` (`store/claims/backing.ts`) is the ONE bidirectional\n * cross-check consumer in the tree. Since B7 it delegates to\n * `resolveBundle`, which runs `resolve.ts`'s `assertClaimsBidirectionalAgreement`\n * — the check's only remaining owner; there is no second copy left in\n * `backing.ts` to keep byte-for-byte in sync with.\n */\nexport const CLAIMS = {\n  id: \"claims\",\n  kind: \"gated\",\n  core: [\n    \"claimEdgeCardinality\",\n    \"claimEdgeCardinalityBatch\",\n    \"purgeEdgeClaims\",\n    \"hardDeleteUniquesByConcreteKind\",\n  ],\n  declaration: \"constraintClaims\",\n  crossCheck: \"bidirectional\",\n  portSurfaceCode: \"CONSTRAINT_CLAIM_SURFACE_MISMATCH\",\n  disposition: {\n    kind: \"fallback\",\n    fallback: \"unclaimed writes; the caller's own supported:false branch\",\n  },\n  operations: [\n    {\n      operation: \"edge claim write\",\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"unclaimed writes; the caller's own supported:false branch\",\n      },\n      sites: [\n        { file: \"store/claims/backing.ts\", member: \"claimEdgeCardinality\" },\n        {\n          file: \"store/claims/backing.ts\",\n          member: \"claimEdgeCardinalityBatch\",\n        },\n        { file: \"store/claims/backing.ts\", member: \"purgeEdgeClaims\" },\n        {\n          file: \"store/claims/backing.ts\",\n          member: \"hardDeleteUniquesByConcreteKind\",\n        },\n      ],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/**\n * Three independently-guarded extras. Measured, `hardDeleteUniquesByNodeIds`'\n * only standalone site (`node-claims.ts:732`) reaches the member through\n * `requireDefined` rather than a degrading guard, so — the round-5\n * enumeration's correction to the round-4 table — its disposition is\n * `refuse`, not the fallback round 4 assumed from the bundle's name.\n */\nexport const UNIQUE_SIDECAR_BATCH = {\n  id: \"uniqueSidecarBatch\",\n  kind: \"graduated\",\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  extras: [\n    {\n      id: \"insertUniqueBatch\",\n      members: [\"insertUniqueBatch\"],\n      disposition: { kind: \"fallback\", fallback: \"issueClaimsIndividually\" },\n    },\n    {\n      id: \"checkUniqueBatch\",\n      members: [\"checkUniqueBatch\"],\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"per-key checkUnique loop\",\n      },\n    },\n    {\n      id: \"hardDeleteUniquesByNodeIds\",\n      members: [\"hardDeleteUniquesByNodeIds\"],\n      disposition: {\n        kind: \"refuse\",\n        // Registry-assigned: the real throw is `requireDefined`'s generic\n        // `TypeError`, which carries no domain code of its own.\n        code: \"UNIQUE_REAP_BY_NODE_IDS_UNSUPPORTED\",\n      },\n    },\n  ],\n  operations: [\n    {\n      operation: \"unique batch probe\",\n      disposition: { kind: \"fallback\", fallback: \"per-key checkUnique loop\" },\n      requires: [\"checkUniqueBatch\"],\n      sites: [\n        {\n          file: \"store/operations/node-operations.ts\",\n          member: \"checkUniqueBatch\",\n          lines: [1275, 1320],\n        },\n        {\n          file: \"store/operations/node-operations.ts\",\n          member: \"checkUniqueBatch\",\n          lines: [1575, 1593],\n        },\n      ],\n    },\n    {\n      operation: \"unique claim issue\",\n      disposition: { kind: \"fallback\", fallback: \"issueClaimsIndividually\" },\n      requires: [\"insertUniqueBatch\"],\n      sites: [\n        { file: \"store/claims/node-claims.ts\", member: \"insertUniqueBatch\" },\n      ],\n    },\n    {\n      operation: \"unique reap by node ids\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"UNIQUE_REAP_BY_NODE_IDS_UNSUPPORTED\",\n      },\n      requires: [\"hardDeleteUniquesByNodeIds\"],\n      sites: [\n        {\n          file: \"store/claims/node-claims.ts\",\n          member: \"hardDeleteUniquesByNodeIds\",\n        },\n      ],\n    },\n    {\n      operation: \"set-based node update\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"SET_UPDATE_UNIQUENESS_UNSUPPORTED\",\n      },\n      requires: [\n        \"hardDeleteUniquesByNodeIds\",\n        \"insertUniqueBatch\",\n        \"checkUniqueBatch\",\n      ],\n      sites: [\n        {\n          file: \"store/operations/node-write-pipeline.ts\",\n          member: \"hardDeleteUniquesByNodeIds\",\n        },\n        {\n          file: \"store/operations/node-write-pipeline.ts\",\n          member: \"insertUniqueBatch\",\n        },\n        {\n          file: \"store/operations/node-write-pipeline.ts\",\n          member: \"checkUniqueBatch\",\n        },\n        {\n          file: \"store/operations/node-operations.ts\",\n          member: \"hardDeleteUniquesByNodeIds\",\n        },\n        {\n          file: \"store/operations/node-operations.ts\",\n          member: \"insertUniqueBatch\",\n        },\n        {\n          file: \"store/operations/node-operations.ts\",\n          member: \"checkUniqueBatch\",\n          lines: [1993],\n        },\n      ],\n    },\n    {\n      operation: \"resolved node write\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"RESOLVED_NODE_UNIQUENESS_UNSUPPORTED\",\n      },\n      requires: [\n        \"hardDeleteUniquesByNodeIds\",\n        \"insertUniqueBatch\",\n        \"checkUniqueBatch\",\n      ],\n      sites: [\n        {\n          file: \"store/claims/resolved-node-claims.ts\",\n          member: \"checkUniqueBatch\",\n          lines: [211],\n        },\n        {\n          file: \"store/claims/resolved-node-claims.ts\",\n          member: \"checkUniqueBatch\",\n          lines: [292],\n        },\n        {\n          file: \"store/claims/resolved-node-claims.ts\",\n          member: \"hardDeleteUniquesByNodeIds\",\n        },\n        {\n          file: \"store/claims/resolved-node-claims.ts\",\n          member: \"insertUniqueBatch\",\n        },\n      ],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/** Two independently-guarded extras, both fallback. */\nexport const BATCH_POINT_READ = {\n  id: \"batchPointRead\",\n  kind: \"graduated\",\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  extras: [\n    {\n      id: \"getNodes\",\n      members: [\"getNodes\"],\n      disposition: { kind: \"fallback\", fallback: \"per-id getNode\" },\n    },\n    {\n      id: \"getEdges\",\n      members: [\"getEdges\"],\n      disposition: { kind: \"fallback\", fallback: \"per-id getEdge\" },\n    },\n  ],\n  operations: [\n    {\n      operation: \"search hydration\",\n      disposition: { kind: \"fallback\", fallback: \"per-id getNode\" },\n      requires: [\"getNodes\"],\n      sites: [{ file: \"store/search.ts\", member: \"getNodes\" }],\n    },\n    {\n      operation: \"import reference validation\",\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"per-row getNode in the routing loop\",\n      },\n      requires: [\"getNodes\"],\n      sites: [{ file: \"interchange/import.ts\", member: \"getNodes\" }],\n    },\n    {\n      operation: \"import edge endpoint hydration\",\n      disposition: { kind: \"fallback\", fallback: \"per-row getEdge\" },\n      requires: [\"getEdges\"],\n      sites: [{ file: \"interchange/import.ts\", member: \"getEdges\" }],\n    },\n    {\n      operation: \"edge batch endpoint priming\",\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"skip the priming pass; endpoint validation reads per-row\",\n      },\n      requires: [\"getNodes\"],\n      sites: [\n        { file: \"store/operations/edge-operations.ts\", member: \"getNodes\" },\n      ],\n    },\n    {\n      operation: \"node create batch priming\",\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"skip priming; per-row probes\",\n      },\n      requires: [\"getNodes\"],\n      sites: [\n        { file: \"store/operations/node-operations.ts\", member: \"getNodes\" },\n      ],\n    },\n    {\n      operation: \"node collection batch load\",\n      disposition: { kind: \"fallback\", fallback: \"per-id getNode\" },\n      requires: [\"getNodes\"],\n      sites: [\n        { file: \"store/collections/node-collection.ts\", member: \"getNodes\" },\n      ],\n    },\n    {\n      operation: \"node batch fetch\",\n      disposition: { kind: \"fallback\", fallback: \"per-id getNode\" },\n      requires: [\"getNodes\"],\n      sites: [{ file: \"store/node-fetch.ts\", member: \"getNodes\" }],\n    },\n    {\n      operation: \"edge batch fetch\",\n      disposition: { kind: \"fallback\", fallback: \"per-id getEdge\" },\n      requires: [\"getEdges\"],\n      sites: [{ file: \"store/edge-fetch.ts\", member: \"getEdges\" }],\n    },\n    {\n      operation: \"identity member hydration\",\n      disposition: { kind: \"fallback\", fallback: \"per-id getNode\" },\n      requires: [\"getNodes\"],\n      sites: [{ file: \"store/store.ts\", member: \"getNodes\" }],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/**\n * Set-oriented endpoint reads are a separate family from point hydration.\n * A backend may implement `getNodes`/`getEdges` while deliberately omitting\n * this operation: the collection API promises one set-oriented read per\n * bind-budget chunk and therefore refuses instead of silently issuing an\n * unbounded singleton loop.\n */\nexport const ENDPOINT_SET_READ = {\n  id: \"endpointSetRead\",\n  kind: \"graduated\",\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  extras: [\n    {\n      id: \"findEdgesByEndpointSet\",\n      members: [\"findEdgesByEndpointSet\"],\n      disposition: {\n        kind: \"refuse\",\n        code: \"ENDPOINT_SET_READ_UNSUPPORTED\",\n      },\n    },\n  ],\n  operations: [\n    {\n      operation: \"bulk endpoint read\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"ENDPOINT_SET_READ_UNSUPPORTED\",\n      },\n      requires: [\"findEdgesByEndpointSet\"],\n      sites: [\n        {\n          file: \"store/collections/edge-collection.ts\",\n          member: \"findEdgesByEndpointSet\",\n        },\n      ],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/**\n * Core `executeStatement`. `IDENTITY_REQUIRES_STATEMENT_EXECUTION` and\n * `IDENTITY_REQUIRES_ATOMIC_BACKEND` are the existing `details.code` values\n * at `identity/sql-target.ts:101` and `store/store.ts:921`; the remaining\n * rows' underlying throws carry no domain code of their own today, so their\n * `code` here is registry-assigned classification (documented per row).\n */\nexport const STATEMENT_EXECUTION = {\n  id: \"statementExecution\",\n  kind: \"gated\",\n  core: [\"executeStatement\"],\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  disposition: {\n    kind: \"refuse\",\n    code: \"IDENTITY_REQUIRES_STATEMENT_EXECUTION\",\n  },\n  operations: [\n    {\n      operation: \"identity statement execution\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"IDENTITY_REQUIRES_STATEMENT_EXECUTION\",\n      },\n      sites: [\n        {\n          file: \"identity/sql-target.ts\",\n          member: \"executeStatement\",\n          rewiring: {\n            class: \"deferred\",\n            reason:\n              \"requires verdict threading through IdentityServiceContext / the capture session — WS5b input, measured at ~13 files/~35 signatures\",\n          },\n        },\n      ],\n    },\n    {\n      operation: \"recorded capture statement\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"RECORDED_CAPTURE_STATEMENT_UNSUPPORTED\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/guards.ts\",\n          member: \"executeStatement\",\n          lines: [62, 79],\n          // DUAL-CLASS (file, member) pair: this same \"guards.ts#executeStatement\"\n          // key also carries the \"reasoned\" rewiring below (the port-surface\n          // fallback site). The live scanner (scripts/bundle-member-access-scan.ts)\n          // matches rewiring annotations on (file, member) only — it cannot read\n          // `lines` to split the pair — so every live executeStatement access in\n          // this file classifies as `annotated-residue` once either sibling\n          // annotation exists.\n          rewiring: {\n            class: \"deferred\",\n            reason:\n              \"requires verdict threading through IdentityServiceContext / the capture session — WS5b input, measured at ~13 files/~35 signatures\",\n          },\n        },\n      ],\n    },\n    {\n      operation: \"history construction gate\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"HISTORY_REQUIRES_STATEMENT_EXECUTION\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/guards.ts\",\n          member: \"executeStatement\",\n          lines: [251],\n        },\n      ],\n    },\n    {\n      operation: \"revision tracking construction gate\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"REVISION_TRACKING_REQUIRES_STATEMENT_EXECUTION\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/guards.ts\",\n          member: \"executeStatement\",\n          lines: [299],\n        },\n      ],\n    },\n    {\n      operation: \"history-unsafe raw write overlay\",\n      disposition: {\n        kind: \"fallback\",\n        fallback: \"omit the overriding member; the port's own absence stands\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/guards.ts\",\n          member: \"executeStatement\",\n          lines: [219],\n          // DUAL-CLASS (file, member) pair: this same \"guards.ts#executeStatement\"\n          // key also carries the \"deferred\" rewiring above (the recorded-capture\n          // statement site). The live scanner (scripts/bundle-member-access-scan.ts)\n          // matches rewiring annotations on (file, member) only — it cannot read\n          // `lines` to split the pair — so every live executeStatement access in\n          // this file classifies as `annotated-residue` once either sibling\n          // annotation exists.\n          rewiring: {\n            class: \"reasoned\",\n            reason:\n              \"genuinely a port-surface presence test; re-keying it on a verdict changes behavior in both directions (a phantom-rejecting stub one way, a raw-write escape on a history-enabled store the other — a safety regression), and adding a non-throwing gated accessor to the frozen binder surface for ONE site is the over-generalization anti-pattern\",\n          },\n        },\n      ],\n    },\n    {\n      operation: \"identity construction gate\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"IDENTITY_REQUIRES_ATOMIC_BACKEND\",\n      },\n      sites: [\n        { file: \"store/store.ts\", member: \"executeStatement\", lines: [921] },\n        { file: \"store/store.ts\", member: \"executeStatement\", lines: [928] },\n      ],\n    },\n    {\n      operation: \"validity window repair\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"VALIDITY_WINDOW_REPAIR_REQUIRES_STATEMENT_EXECUTION\",\n      },\n      sites: [\n        {\n          file: \"backend/repair-validity-windows.ts\",\n          member: \"executeStatement\",\n        },\n      ],\n    },\n    {\n      operation: \"recorded-time migration\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"RECORDED_TIME_MIGRATION_REQUIRES_STATEMENT_EXECUTION\",\n      },\n      sites: [\n        {\n          file: \"backend/migrate-recorded-time.ts\",\n          member: \"executeStatement\",\n          lines: [154, 161, 801],\n          rewiring: {\n            class: \"deferred\",\n            reason:\n              \"the delete path's public Pick-typed backend cannot reach resolveBundle, and the shared module-private helpers make a single-path rewire two owners\",\n          },\n        },\n      ],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/**\n * Four extras, one per public `Store` method, each read alone. Three refuse\n * with their own existing error; `probeContributions` is the pilot's one\n * `declarationGate` row — fallback to `{ entries: [] }` when\n * `capabilities.contributions` is undeclared, refuse when it is declared.\n */\nexport const CONTRIBUTION_HEALTH = {\n  id: \"contributionHealth\",\n  kind: \"graduated\",\n  declaration: \"contributions\",\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  extras: [\n    {\n      id: \"verifyContributions\",\n      members: [\"verifyContributions\"],\n      disposition: { kind: \"refuse\", code: \"CONTRIBUTION_VERIFY_UNSUPPORTED\" },\n    },\n    {\n      id: \"repairContributions\",\n      members: [\"repairContributions\"],\n      disposition: { kind: \"refuse\", code: \"CONTRIBUTION_REPAIR_UNSUPPORTED\" },\n    },\n    {\n      id: \"rebuildContribution\",\n      members: [\"rebuildContribution\"],\n      disposition: {\n        kind: \"refuse\",\n        code: \"CONTRIBUTION_REBUILD_UNSUPPORTED\",\n      },\n    },\n    {\n      id: \"probeContributions\",\n      members: [\"probeContributions\"],\n      disposition: { kind: \"fallback\", fallback: \"{entries: []}\" },\n    },\n  ],\n  operations: [\n    {\n      operation: \"contribution verify\",\n      disposition: { kind: \"refuse\", code: \"CONTRIBUTION_VERIFY_UNSUPPORTED\" },\n      requires: [\"verifyContributions\"],\n      sites: [{ file: \"store/store.ts\", member: \"verifyContributions\" }],\n    },\n    {\n      operation: \"contribution repair\",\n      disposition: { kind: \"refuse\", code: \"CONTRIBUTION_REPAIR_UNSUPPORTED\" },\n      requires: [\"repairContributions\"],\n      sites: [{ file: \"store/store.ts\", member: \"repairContributions\" }],\n    },\n    {\n      operation: \"contribution rebuild\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"CONTRIBUTION_REBUILD_UNSUPPORTED\",\n      },\n      requires: [\"rebuildContribution\"],\n      sites: [{ file: \"store/store.ts\", member: \"rebuildContribution\" }],\n    },\n    {\n      operation: \"contribution probe\",\n      disposition: { kind: \"fallback\", fallback: \"{entries: []}\" },\n      requires: [\"probeContributions\"],\n      sites: [{ file: \"store/store.ts\", member: \"probeContributions\" }],\n      declarationGate: true,\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/**\n * Core `ensureRevisionOriginsTable`, both refusals existing typed throws\n * (registry-assigned codes; neither underlying throw carries a domain code\n * of its own today).\n */\nexport const RECORDED_REVISION_ORIGINS = {\n  id: \"recordedRevisionOrigins\",\n  kind: \"gated\",\n  core: [\"ensureRevisionOriginsTable\"],\n  crossCheck: \"none\",\n  portSurfaceCode: \"BUNDLE_PORT_SURFACE_MISMATCH\",\n  disposition: {\n    kind: \"refuse\",\n    code: \"REVISION_TRACKING_REQUIRES_REVISION_ORIGINS\",\n  },\n  operations: [\n    {\n      operation: \"revision tracking construction gate\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"REVISION_TRACKING_REQUIRES_REVISION_ORIGINS\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/guards.ts\",\n          member: \"ensureRevisionOriginsTable\",\n        },\n      ],\n    },\n    {\n      operation: \"revision origin bootstrap\",\n      disposition: {\n        kind: \"refuse\",\n        code: \"REVISION_ORIGIN_BOOTSTRAP_UNSUPPORTED\",\n      },\n      sites: [\n        {\n          file: \"store/recorded-capture/clock.ts\",\n          member: \"ensureRevisionOriginsTable\",\n        },\n      ],\n    },\n  ],\n} as const satisfies CapabilityBundleDefinition;\n\n/** The pilot registry: seven bundles, 16 members, 31 operation rows. */\nexport const CAPABILITY_BUNDLES = [\n  CLAIMS,\n  UNIQUE_SIDECAR_BATCH,\n  BATCH_POINT_READ,\n  STATEMENT_EXECUTION,\n  CONTRIBUTION_HEALTH,\n  RECORDED_REVISION_ORIGINS,\n  ENDPOINT_SET_READ,\n] as const;\n\nexport type CapabilityBundleId = (typeof CAPABILITY_BUNDLES)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// UNBUNDLED_OPTIONAL_MEMBERS — the other 82, both kinds classified (I5, I6).\n// ---------------------------------------------------------------------------\n\n/** No bundle should ever own this member; the reason is the fact to preserve. */\nexport type ReasonedUnbundledMember = Readonly<{\n  kind: \"reasoned\";\n  reason: string;\n  /** Measured receiver-scoped access count (§Baselines). May be 0. */\n  accesses: number;\n}>;\n\n/** The 14 remaining WS5b bundle ids, retained from the round-4 sweep table. */\nexport type Ws5bBundleId =\n  | \"batchEntityWrite\"\n  | \"heterogeneousEndpointSetRead\"\n  | \"vectorOperations\"\n  | \"hybridSearch\"\n  | \"vectorSlotContributions\"\n  | \"fulltextOperations\"\n  | \"fulltextProvisioning\"\n  | \"databaseExtensions\"\n  | \"contributionProvisioning\"\n  | \"indexMaterialization\"\n  | \"ddlExecution\"\n  | \"temporaryStatements\"\n  | \"rawStatementReuse\"\n  | \"trustedImport\";\n\n/** WS5b's residue: this bundle owns it, and the access count may not grow. */\nexport type DeferredUnbundledMember = Readonly<{\n  kind: \"deferred\";\n  workstream: \"WS5b\";\n  bundle: Ws5bBundleId;\n  /** Measured receiver-scoped access count (§Baselines) — the ceiling. */\n  ceiling: number;\n}>;\n\nexport type UnbundledOptionalMember =\n  ReasonedUnbundledMember | DeferredUnbundledMember;\n\n/**\n * The 32 `reasoned` + 49 `deferred` members\n * (B9's scanner corrected two `reasoned` counts: `tableNames` 22→23,\n * `ensureIdentityTables` 3→4; #520 then added `recordedTableDdl` with one\n * access; resolving the write-fence spelling through the fence plan then\n * added `fenceSql` with two accesses; the catalog-introspection bag then\n * added `catalog`, a reasoned member with zero measured accesses — its own\n * absence refusal lives in this directory, which the live scanner excludes\n * wholesale; the forked working-copy strategy then reads the connected\n * backend's `tableNames` to fence them against the base store's resolved\n * schema — 90 → 91; the lineage capability then added `lineage`, a\n * reasoned member with two live accesses (`resolveLineage`'s two reads of\n * the backend's own member) — 91 → 93. A later fix briefly grew this to 95\n * by re-deriving `resolveLineage(target)`'s resolution and comparing it\n * against the transaction handle's own `lineage` by identity inside\n * `assertTargetUnchanged` — a dead read, since `LineageMembers` took no\n * session argument and the comparison never actually pinned anything to\n * the transaction. Giving `revision`/`changesSince` a real `session`\n * parameter made that comparison unnecessary — `assertTargetUnchanged` now\n * reaches `lineage` through `requireLineage(txBackend, …)`, a call the\n * live scanner does not see (it reads `.lineage` inside\n * `backend/capabilities/`, outside the scanned scope) — back to 93. The\n * engine-native recorded-time capability then added `recordedTime`, a\n * reasoned member with zero measured accesses: its own absence refusal\n * (`requireRecordedTime`) lives in the excluded `backend/capabilities/`\n * directory, and every other current read\n * (`profile.provisioning.recordedTime` in `create-sql-backend.ts` and both\n * dialects' transaction-scoped threading) is off `EngineProvisioning`, a\n * type the receiver test's arm (b) does not recognize by name — still 93,\n * 16 + 84 = 100 members total.\n */\nexport const UNBUNDLED_OPTIONAL_MEMBERS = {\n  upsertHeterogeneousNodes: {\n    kind: \"reasoned\",\n    reason: \"Exact-session PostgreSQL heterogeneous node upsert program.\",\n    accesses: 6,\n  },\n  adoptBaseSchema: {\n    kind: \"reasoned\",\n    reason:\n      \"Privileged deployment-wide physical-schema adoption. Bundled backends implement the versioned marker lifecycle; custom backends may omit it when they provision their own base relations.\",\n    accesses: 2,\n  },\n  assertBaseSchemaCurrent: {\n    kind: \"reasoned\",\n    reason:\n      \"SELECT-only sibling of base adoption, consulted by verified and graph-template entry points plus the managed libSQL installation postcondition so incompatible storage fails before use. Custom backends may omit it only when they own base-schema compatibility themselves; omission intentionally preserves the legacy no-gate contract.\",\n    accesses: 4,\n  },\n  ensureEdgeMatchIdentityStorage: {\n    kind: \"reasoned\",\n    reason:\n      \"Focused privileged base-schema adoption hook. The versioned base-schema lifecycle calls it only while adopting an unstamped release because all edge writes name the nullable columns; runtime stores never consult it. Custom backends may omit it only when their durableEdgeMatchIdentity declaration promises independently provisioned storage.\",\n    accesses: 1,\n  },\n  claimEdgeCardinalityGuarded: {\n    kind: \"reasoned\",\n    reason:\n      \"A stronger first-party single-claim operation whose member presence explicitly permits the store to fold the legacy entity probe into the claim; custom and legacy claim backends keep probe-then-claim, so it is not part of the claims bundle's required portable surface.\",\n    accesses: 1,\n  },\n  insertNodeIfAbsentWithSchemaFence: {\n    kind: \"reasoned\",\n    reason:\n      \"First-party schema-managed insert fast path selected only by the node create session; a missing member retains the ordinary fence then insert path.\",\n    accesses: 6,\n  },\n  insertNodeWithSchemaFence: {\n    kind: \"reasoned\",\n    reason:\n      \"Same first-party schema-fenced node insert family; generated ids use it only when no earlier lock-bearing work is required.\",\n    accesses: 7,\n  },\n  bootstrapTables: {\n    kind: \"reasoned\",\n    reason:\n      \"One-shot provisioning hook consulted by createStore and the managed libSQL legacy fallback before any capability question exists; it has no operation that could refuse or degrade.\",\n    accesses: 4,\n  },\n  tableNames: {\n    kind: \"reasoned\",\n    reason:\n      \"Physical names read by the compiler and schema-checked reads. The optional schema-version binding is required only by checked reads; its absence refuses that operation.\",\n    // 25, including the schema-checked read binding. Previously 24, not the grep tier's 23: store/store.ts holds two `backend.tableNames`\n    // accesses on one physical line, which a line-keyed grep counts once but\n    // the type-aware scanner counts as two access nodes (§Baselines). The\n    // forked working-copy strategy reads the connected backend's names to\n    // fence them against the base store's resolved schema.\n    accesses: 25,\n  },\n  fenceSql: {\n    kind: \"reasoned\",\n    reason:\n      \"The write-fence lock spelling a backend's `writeFence: { mechanism: \\\"advisory\\\" }` declaration requires. Every lock site reads it exclusively through the resolved `WriteFencePlan`'s `sql` field (`resolveWriteFencePlan`/`requireWriteFence` in `backend/capabilities/write-fence.ts`). The one exception is `assertRecordedCaptureTransactionIsolation` (`store/recorded-capture/guards.ts`), which reads `target.fenceSql` directly: it is gated purely on `dialect`, not on a resolved fence plan, so there is no plan to read the spelling through.\",\n    accesses: 2,\n  },\n  commitSchemaVersionIfKindsEmpty: {\n    kind: \"reasoned\",\n    reason:\n      \"Schema-version write fence, a SchemaCommitBackend role member. Its absence is dispositioned by the schema manager's own gate, which is a write-pipeline decision, not a feature-family one.\",\n    accesses: 2,\n  },\n  commitSchemaVersionWithPreflight: {\n    kind: \"reasoned\",\n    reason:\n      \"Same schema-version write-fence family as commitSchemaVersionIfKindsEmpty.\",\n    accesses: 3,\n  },\n  lockSchemaVersionForWrite: {\n    kind: \"reasoned\",\n    reason:\n      \"Same family; also the one schema member on TransactionBackend, so bundling it would re-open the accessor's B-1 port-typing question for no pilot consumer.\",\n    accesses: 1,\n  },\n  lockSchemaVersionAndGraphWrite: {\n    kind: \"reasoned\",\n    reason:\n      \"PostgreSQL/PGlite transaction-only latency seam which preserves the existing schema-then-graph lock order in one dependent-CTE statement; SQLite and custom backends retain the two portable lock operations.\",\n    accesses: 1,\n  },\n  schemaWriteTransaction: {\n    kind: \"reasoned\",\n    reason:\n      \"Same family — and it returns a narrowed transaction backend, so it is a port constructor rather than an operation.\",\n    accesses: 4,\n  },\n  registerGraphTemplate: {\n    kind: \"reasoned\",\n    reason:\n      \"Administrative template registration is gated by the graph-template facade, which refuses absent backends rather than treating a missing registry as an empty template set.\",\n    accesses: 1,\n  },\n  instantiateGraphTemplate: {\n    kind: \"reasoned\",\n    reason:\n      \"Administrative schema bootstrap operation, gated by the graph-template facade; it is not a runtime feature family because absence is a typed refusal before any graph write.\",\n    accesses: 1,\n  },\n  ensureIdentityTables: {\n    kind: \"reasoned\",\n    reason:\n      \"Identity DDL, gated by the identity construction gate (store.ts:918-935), which is the write-fence design's decision and must stay one owner there.\",\n    // 4, not the grep tier's 3: identity/schema-transition.ts:228 accesses\n    // `input.ensureIdentityTables` through a derived (arm-b) receiver whose\n    // property name never matches the grep receiver-name filter\n    // (backend|Backend|target|Target|tx|port|source). The type-aware scanner\n    // resolves it via the receiver's declared type node, which textually\n    // references `GraphBackend[\"ensureIdentityTables\"]` (§Baselines).\n    accesses: 4,\n  },\n  identityTableDdl: {\n    kind: \"reasoned\",\n    reason:\n      \"Same identity-DDL family as ensureIdentityTables. Adopted evolution adds one Store handoff of the DDL factory and one same-session catalog inspection before the fenced schema commit; both refuse absent DDL rather than skipping required storage.\",\n    accesses: 4,\n  },\n  recordedTableDdl: {\n    kind: \"reasoned\",\n    reason:\n      \"Recorded-time migration DDL factory; its only consumer has its own typed capability refusal, so it is a provisioning port rather than a feature-family operation.\",\n    accesses: 1,\n  },\n  ensureKindRemovalsTable: {\n    kind: \"reasoned\",\n    reason:\n      \"Kind-removal provisioning; the removal path's own gate is a schema-lifecycle decision with a single consumer (materialize-removals.ts) and no second theory to consolidate.\",\n    accesses: 3,\n  },\n  getAllKindRemovals: {\n    kind: \"reasoned\",\n    reason: \"Same kind-removal family as ensureKindRemovalsTable.\",\n    accesses: 2,\n  },\n  getPendingKindRemovals: {\n    kind: \"reasoned\",\n    reason: \"Same kind-removal family as ensureKindRemovalsTable.\",\n    accesses: 4,\n  },\n  recordKindRemoval: {\n    kind: \"reasoned\",\n    reason: \"Same kind-removal family as ensureKindRemovalsTable.\",\n    accesses: 4,\n  },\n  ensureReconciliationMarkersTable: {\n    kind: \"reasoned\",\n    reason:\n      \"Reconciliation-marker family; single consumer, single gate, same reasoning.\",\n    accesses: 2,\n  },\n  getReconciliationMarker: {\n    kind: \"reasoned\",\n    reason: \"Same reconciliation-marker family.\",\n    accesses: 2,\n  },\n  setReconciliationMarker: {\n    kind: \"reasoned\",\n    reason: \"Same reconciliation-marker family.\",\n    accesses: 2,\n  },\n  readConstraintFenceViolations: {\n    kind: \"reasoned\",\n    reason:\n      'Read-only fence audit with exactly one caller and a documented \"absent ⇒ the report is unavailable\" contract (history-store-backend.ts:105-108); no operation degrades or refuses on it.',\n    accesses: 1,\n  },\n  ensureContributionMaterializationsTable: {\n    kind: \"reasoned\",\n    reason:\n      \"Zero consumers in src/** outside the backend implementations — measured, not inferred. A member no code path consults has no measurable arity or disposition.\",\n    accesses: 0,\n  },\n  getContributionMaterialization: {\n    kind: \"reasoned\",\n    reason:\n      \"Same zero-consumer family as ensureContributionMaterializationsTable.\",\n    accesses: 0,\n  },\n  recordContributionMaterialization: {\n    kind: \"reasoned\",\n    reason:\n      \"Zero consumers outside the backend implementations; its only in-tree use is a backend implementation calling its own member (backend/drizzle/contribution-materializations.ts:1588), which the scanner excludes by scope.\",\n    accesses: 0,\n  },\n\n  assertRuntimeContributionsInitialized: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"contributionProvisioning\",\n    ceiling: 1,\n  },\n  assertVectorSlotInitialized: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorSlotContributions\",\n    ceiling: 1,\n  },\n  assertVectorSlotsInitialized: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorSlotContributions\",\n    ceiling: 1,\n  },\n  catalog: {\n    kind: \"reasoned\",\n    reason:\n      \"Physical-schema introspection (table/index presence, PostgreSQL's invalid-index leftover state, normalized column types) a store path consults directly rather than through a bundle disposition; its own absence has one typed refusal naming it, not a per-operation fallback. That refusal lives in backend/capabilities/, which the live access scanner excludes wholesale (it is the registry's own directory), so its access count is measured as zero even though the refusal reads the member.\",\n    accesses: 0,\n  },\n  lineage: {\n    kind: \"reasoned\",\n    reason:\n      \"Whole-database revision and per-graph change delta, consulted directly by a caller that wants to skip a full comparison rather than through a bundle disposition; every such caller already knows how to fall back to the full comparison when this is absent, so there is no per-operation degradation table to own. Its absence refusal lives in backend/capabilities/, which the live access scanner excludes wholesale (it is the registry's own directory). The store's own recorded-relations derivation (`resolveLineage`, store/recorded-capture/lineage.ts) selects the backend's own `lineage` over the derived one: two reads on the same line. Every OTHER consumer — `assertTargetUnchanged`'s commit-time engine-anchor check among them — reaches `lineage` through `resolveLineage`/`requireLineage` rather than a raw `.lineage` read of its own, so none of them add to this count.\",\n    accesses: 2,\n  },\n  recordedTime: {\n    kind: \"reasoned\",\n    reason:\n      \"The engine's own recorded (system-time) read source and revision clock. Present only when a backend's engine declares it, and consulted only through resolveRecordedTimeOwnership/requireRecordedTime, both of which live in backend/capabilities/, which the live access scanner excludes wholesale (it is the registry's own directory). createSqlBackend's co-requirement check against `lineage` and both dialects' transaction-scoped threading all read `.recordedTime` off `EngineProvisioning`, not off a `GraphBackend`/`TransactionBackend`-typed receiver, so none of them add to this count either.\",\n    accesses: 0,\n  },\n  claimIndexMaterialization: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 2,\n  },\n  compileSql: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"rawStatementReuse\",\n    ceiling: 9,\n  },\n  createVectorIndex: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 4,\n  },\n  deleteEdgesBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 6,\n  },\n  deleteEmbedding: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 8,\n  },\n  deleteEmbeddingBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 4,\n  },\n  deleteFulltext: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 12,\n  },\n  deleteFulltextBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 6,\n  },\n  deleteVectorSlotContribution: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorSlotContributions\",\n    ceiling: 0,\n  },\n  dropVectorIndex: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 0,\n  },\n  ensureExtension: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"databaseExtensions\",\n    ceiling: 2,\n  },\n  ensureFulltextTable: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextProvisioning\",\n    ceiling: 1,\n  },\n  ensureIndexMaterializationsTable: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 2,\n  },\n  ensureRuntimeContributions: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"contributionProvisioning\",\n    ceiling: 2,\n  },\n  ensureTrigramExtension: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"databaseExtensions\",\n    ceiling: 2,\n  },\n  ensureVectorSlotContribution: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorSlotContributions\",\n    ceiling: 4,\n  },\n  ensureVectorSlotContributions: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorSlotContributions\",\n    // Adopted evolution adds a pre-fence capability refusal and a same-session\n    // provision invocation. The existing boot consumer remains the third read.\n    ceiling: 3,\n  },\n  executeDdl: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"ddlExecution\",\n    ceiling: 13,\n  },\n  executeRaw: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"rawStatementReuse\",\n    // Query projections and derived relations now share the compiled-SQL\n    // template path for row and scalar terminals.\n    ceiling: 11,\n  },\n  executeTemporaryStatement: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"temporaryStatements\",\n    ceiling: 3,\n  },\n  findEdgesByHeterogeneousEndpointSet: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"heterogeneousEndpointSetRead\",\n    // Import prefetches existing endpoint pairs through the same bulk-read\n    // capability rather than issuing one probe per incoming edge.\n    ceiling: 5,\n  },\n  fulltextSearch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 4,\n  },\n  fulltextStrategy: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 2,\n  },\n  getIndexMaterialization: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 3,\n  },\n  getIndexMaterializations: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 2,\n  },\n  hardDeleteEdgesBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 5,\n  },\n  hybridSearch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"hybridSearch\",\n    ceiling: 2,\n  },\n  insertEdgeNoReturn: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  insertEdgesBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  insertEdgesBatchReturning: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  insertEdgesDurableBatchReturning: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 8,\n  },\n  insertNodeNoReturn: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  insertNodeIfAbsent: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 7,\n  },\n  insertNodesBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  insertNodesBatchReturning: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 4,\n  },\n  recordIndexMaterialization: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 6,\n  },\n  releaseIndexMaterializationClaim: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"indexMaterialization\",\n    ceiling: 2,\n  },\n  trustedImport: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"trustedImport\",\n    ceiling: 1,\n  },\n  compareAndSetNode: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 6,\n  },\n  updateNodeSet: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 6,\n  },\n  updateResolvedNodesBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"batchEntityWrite\",\n    ceiling: 6,\n  },\n  upsertEmbedding: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 10,\n  },\n  upsertEmbeddingBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 4,\n  },\n  upsertFulltext: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 10,\n  },\n  upsertFulltextBatch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"fulltextOperations\",\n    ceiling: 6,\n  },\n  vectorSearch: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 4,\n  },\n  vectorStrategy: {\n    kind: \"deferred\",\n    workstream: \"WS5b\",\n    bundle: \"vectorOperations\",\n    ceiling: 9,\n  },\n} as const satisfies Record<string, UnbundledOptionalMember>;\n\n/**\n * The appendix's 14 remaining WS5b bundles, as (bundle id → member names) — written\n * INDEPENDENTLY of `UNBUNDLED_OPTIONAL_MEMBERS`'s `deferred` entries, so the\n * totality proof below is not a tautology: grouping the `deferred` entries\n * by `bundle` must reproduce this table exactly.\n */\nexport const WS5B_SEED_BUNDLES = {\n  batchEntityWrite: [\n    \"insertNodesBatch\",\n    \"insertNodesBatchReturning\",\n    \"insertEdgesBatch\",\n    \"insertEdgesBatchReturning\",\n    \"insertEdgesDurableBatchReturning\",\n    \"deleteEdgesBatch\",\n    \"hardDeleteEdgesBatch\",\n    \"insertNodeNoReturn\",\n    \"insertNodeIfAbsent\",\n    \"insertEdgeNoReturn\",\n    \"compareAndSetNode\",\n    \"updateNodeSet\",\n    \"updateResolvedNodesBatch\",\n  ],\n  heterogeneousEndpointSetRead: [\"findEdgesByHeterogeneousEndpointSet\"],\n  vectorOperations: [\n    \"upsertEmbedding\",\n    \"deleteEmbedding\",\n    \"upsertEmbeddingBatch\",\n    \"deleteEmbeddingBatch\",\n    \"vectorSearch\",\n    \"vectorStrategy\",\n    \"createVectorIndex\",\n    \"dropVectorIndex\",\n  ],\n  hybridSearch: [\"hybridSearch\"],\n  vectorSlotContributions: [\n    \"assertVectorSlotsInitialized\",\n    \"assertVectorSlotInitialized\",\n    \"ensureVectorSlotContributions\",\n    \"ensureVectorSlotContribution\",\n    \"deleteVectorSlotContribution\",\n  ],\n  fulltextOperations: [\n    \"upsertFulltext\",\n    \"deleteFulltext\",\n    \"upsertFulltextBatch\",\n    \"deleteFulltextBatch\",\n    \"fulltextSearch\",\n    \"fulltextStrategy\",\n  ],\n  fulltextProvisioning: [\"ensureFulltextTable\"],\n  databaseExtensions: [\"ensureExtension\", \"ensureTrigramExtension\"],\n  contributionProvisioning: [\n    \"ensureRuntimeContributions\",\n    \"assertRuntimeContributionsInitialized\",\n  ],\n  indexMaterialization: [\n    \"getIndexMaterialization\",\n    \"recordIndexMaterialization\",\n    \"getIndexMaterializations\",\n    \"ensureIndexMaterializationsTable\",\n    \"claimIndexMaterialization\",\n    \"releaseIndexMaterializationClaim\",\n  ],\n  ddlExecution: [\"executeDdl\"],\n  temporaryStatements: [\"executeTemporaryStatement\"],\n  rawStatementReuse: [\"executeRaw\", \"compileSql\"],\n  trustedImport: [\"trustedImport\"],\n} as const satisfies Record<\n  Ws5bBundleId,\n  readonly OptionalGraphBackendMember[]\n>;\n\n// ---------------------------------------------------------------------------\n// Compile-time proofs — written exactly as member-classes.ts:288,306-376.\n// ---------------------------------------------------------------------------\n\n// Structural, not nominal: reads `core`/`extras` off each bundle directly\n// rather than matching against `GatedBundleDefinition`/`GraduatedBundleDefinition`.\n// Measured against the compiler: matching the named definition types instead\n// (`D extends GatedBundleDefinition<infer MCore, string, infer MExtra> ? …`)\n// infers `MCore` correctly but, for a gated bundle with no `extras` field\n// (`CLAIMS`), leaves `MExtra` with NO inference candidate — and TypeScript's\n// fallback for an unmatched `infer` is the type parameter's CONSTRAINT\n// (`OptionalGraphBackendMember`, the full 98), not `never`, silently widening\n// `MCore | MExtra` to every optional member. The structural form below has no\n// such unmatched parameter: `extras` is read only when the field is actually\n// present, so a bundle without one contributes no `ExtrasMembersOf` members\n// at all.\ntype CoreMembersOf<D> = D extends { core: readonly (infer M)[] } ? M : never;\ntype ExtrasMembersOf<D> =\n  D extends { extras: readonly (infer E)[] } ?\n    E extends { members: readonly (infer M)[] } ?\n      M\n    : never\n  : never;\ntype BundleMembers<D> = CoreMembersOf<D> | ExtrasMembersOf<D>;\n\ntype BundledMember = BundleMembers<(typeof CAPABILITY_BUNDLES)[number]>;\n\ntype ReasonedMember = {\n  [\n    K in keyof typeof UNBUNDLED_OPTIONAL_MEMBERS\n  ]: (typeof UNBUNDLED_OPTIONAL_MEMBERS)[K] extends { kind: \"reasoned\" } ? K\n  : never;\n}[keyof typeof UNBUNDLED_OPTIONAL_MEMBERS];\n\ntype DeferredMember = {\n  [\n    K in keyof typeof UNBUNDLED_OPTIONAL_MEMBERS\n  ]: (typeof UNBUNDLED_OPTIONAL_MEMBERS)[K] extends { kind: \"deferred\" } ? K\n  : never;\n}[keyof typeof UNBUNDLED_OPTIONAL_MEMBERS];\n\ntype Ws5bSeedMember = (typeof WS5B_SEED_BUNDLES)[Ws5bBundleId][number];\n\n/**\n * DISJOINTNESS, written to REPORT the offender — `Assert<Equal<Extract<A,\n * B>, never>>` looks like the obvious spelling and is useless here: inside a\n * generic alias `Equal` defers to `boolean`, which satisfies neither `true`\n * nor `false`, so the assertion passes whatever it is given.\n */\ntype Disjoint<A, B> =\n  [Extract<A, B>] extends [never] ? true\n  : [\"MEMBER CLASSIFIED TWICE\", Extract<A, B>];\n\n/* eslint-disable @typescript-eslint/no-unused-vars -- compile-time assertions */\n\n// (i) Totality: the three-way partition covers exactly the 98 optional members.\ntype _totality = Assert<\n  Equal<\n    BundledMember | ReasonedMember | DeferredMember,\n    OptionalGraphBackendMember\n  >\n>;\n\n// (ii) Pairwise disjointness, across the partition and across the seven bundles.\ntype _partitionDisjoint1 = Assert<\n  Disjoint<BundledMember, ReasonedMember | DeferredMember>\n>;\ntype _partitionDisjoint2 = Assert<Disjoint<ReasonedMember, DeferredMember>>;\n\ntype _bundleDisjoint1 = Assert<\n  Disjoint<\n    (typeof CLAIMS)[\"core\"][number],\n    | (typeof UNIQUE_SIDECAR_BATCH)[\"extras\"][number][\"members\"][number]\n    | (typeof BATCH_POINT_READ)[\"extras\"][number][\"members\"][number]\n    | (typeof STATEMENT_EXECUTION)[\"core\"][number]\n    | (typeof CONTRIBUTION_HEALTH)[\"extras\"][number][\"members\"][number]\n    | (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]\n    | (typeof ENDPOINT_SET_READ)[\"extras\"][number][\"members\"][number]\n  >\n>;\ntype _bundleDisjoint2 = Assert<\n  Disjoint<\n    (typeof UNIQUE_SIDECAR_BATCH)[\"extras\"][number][\"members\"][number],\n    | (typeof BATCH_POINT_READ)[\"extras\"][number][\"members\"][number]\n    | (typeof STATEMENT_EXECUTION)[\"core\"][number]\n    | (typeof CONTRIBUTION_HEALTH)[\"extras\"][number][\"members\"][number]\n    | (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]\n    | (typeof ENDPOINT_SET_READ)[\"extras\"][number][\"members\"][number]\n  >\n>;\ntype _bundleDisjoint3 = Assert<\n  Disjoint<\n    (typeof BATCH_POINT_READ)[\"extras\"][number][\"members\"][number],\n    | (typeof STATEMENT_EXECUTION)[\"core\"][number]\n    | (typeof CONTRIBUTION_HEALTH)[\"extras\"][number][\"members\"][number]\n    | (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]\n    | (typeof ENDPOINT_SET_READ)[\"extras\"][number][\"members\"][number]\n  >\n>;\ntype _bundleDisjoint4 = Assert<\n  Disjoint<\n    (typeof STATEMENT_EXECUTION)[\"core\"][number],\n    | (typeof CONTRIBUTION_HEALTH)[\"extras\"][number][\"members\"][number]\n    | (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]\n    | (typeof ENDPOINT_SET_READ)[\"extras\"][number][\"members\"][number]\n  >\n>;\ntype _bundleDisjoint5 = Assert<\n  Disjoint<\n    (typeof CONTRIBUTION_HEALTH)[\"extras\"][number][\"members\"][number],\n    | (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]\n    | (typeof ENDPOINT_SET_READ)[\"extras\"][number][\"members\"][number]\n  >\n>;\n\n// (iii) The deferred set and the appendix's seed list name the same members.\ntype _ws5bSeedEqualsDeferred = Assert<Equal<DeferredMember, Ws5bSeedMember>>;\n\n/* eslint-enable @typescript-eslint/no-unused-vars */\n","/**\n * The bundle BINDING half (ruling B1): the actual member functions, bound at\n * the call site off whichever port the site holds. The accessor is the\n * SINGLE owner of binding — it never re-derives presence, only reads the\n * verdict's `present`/`missing` fields to decide which names to bind, then\n * binds them off the port passed to it. It throws the bundle's\n * `portSurfaceCode` when the verdict says present and the port disagrees\n * (I20) — the generalization of the check `store/claims/backing.ts:157-169`\n * performs today.\n */\nimport { ConfigurationError } from \"../../errors\";\nimport { createDataKeyedBag } from \"../../utils/object\";\nimport { type GraphBackend } from \"../types\";\nimport {\n  BATCH_POINT_READ,\n  CAPABILITY_BUNDLES,\n  type CapabilityBundleId,\n  CLAIMS,\n  CONTRIBUTION_HEALTH,\n  ENDPOINT_SET_READ,\n  type GatedBundleDefinition,\n  type OptionalGraphBackendMember,\n  RECORDED_REVISION_ORIGINS,\n  STATEMENT_EXECUTION,\n  UNIQUE_SIDECAR_BATCH,\n} from \"./bundle-registry\";\nimport {\n  type BundleVerdictOf,\n  type ExtraMember,\n  type ExtrasOf,\n  type ExtraVerdict,\n} from \"./resolve\";\n\n/**\n * I21. The brand is what makes a BOUND member type-distinguishable from a\n * PORT member: without it, `binding.getNodes` at a rewired site still has a\n * receiver assignable to `Pick<GraphBackend, …>`, and a syntactic scanner\n * could never tell a bound value from an unbound one.\n */\ndeclare const BUNDLE_BINDING: unique symbol;\n\n/** Every named member, guaranteed present — bound off the port, never a port member itself. */\nexport type BundleBinding<M extends OptionalGraphBackendMember> = Required<\n  Pick<GraphBackend, M>\n> &\n  Readonly<{ [BUNDLE_BINDING]: true }>;\n\n/**\n * The graduated twin of {@link BundleBinding}: a bundle with no required\n * core cannot promise every member is present, so its bundle-wide \"members\"\n * accessor (`uniqueSidecarBatchMembers`, `batchPointReadMembers`,\n * `contributionHealthMembers`) reports whichever extras the verdict marks\n * present — never all of them by construction, and never a cast that claims\n * otherwise.\n */\nexport type PartialBundleBinding<M extends OptionalGraphBackendMember> =\n  Readonly<Partial<Pick<GraphBackend, M>>> &\n    Readonly<{ [BUNDLE_BINDING]: true }>;\n\nfunction portSurfaceCodeFor(bundle: CapabilityBundleId): string {\n  const definition = CAPABILITY_BUNDLES.find(\n    (candidate) => candidate.id === bundle,\n  );\n  return definition?.portSurfaceCode ?? \"BUNDLE_PORT_SURFACE_MISMATCH\";\n}\n\n/**\n * The one owner of \"does this port have every one of these names\" — used both\n * by {@link bindNames}'s REFUSE arm (`bindCore`/`bindExtra`, which keep the\n * throw) and by {@link bindExtraIfReachable}'s FALLBACK arm (which turns the\n * same answer into `undefined`). Returns the first missing name, or\n * `undefined` when the port has them all.\n */\nfunction findMissingPortMember<M extends OptionalGraphBackendMember>(\n  port: Readonly<Partial<Pick<GraphBackend, M>>>,\n  names: readonly M[],\n): M | undefined {\n  const portRecord = port as Readonly<Record<string, unknown>>;\n  return names.find((name) => portRecord[name] === undefined);\n}\n\nfunction bindNames<const M extends OptionalGraphBackendMember>(\n  port: Readonly<Partial<Pick<GraphBackend, M>>>,\n  names: readonly M[],\n  bundle: CapabilityBundleId,\n): Record<string, unknown> {\n  const missing = findMissingPortMember(port, names);\n  if (missing !== undefined) {\n    throw new ConfigurationError(\n      `The port passed to capability bundle \"${bundle}\" is missing \"${missing}\", which the resolved verdict says is present.`,\n      {\n        code: portSurfaceCodeFor(bundle),\n        bundle,\n        member: missing,\n      },\n    );\n  }\n  const bound = createDataKeyedBag<unknown>();\n  const portRecord = port as Readonly<Record<string, unknown>>;\n  for (const name of names) {\n    bound[name] = portRecord[name];\n  }\n  return bound;\n}\n\n/**\n * Bind a gated bundle's core off the port the calls execute on. The port\n * parameter is the STRUCTURAL MINIMUM over the members (ruling B-1), so\n * every one of the pilot's receiver shapes is accepted:\n * `GraphBackend`, `TransactionBackend`, `WriteTarget`, `IdentityTarget`,\n * `Pick<GraphBackend, \"dialect\" | \"executeStatement\">` and the\n * `RevisionOriginBackend`-shaped `Pick<GraphBackend, \"dialect\" |\n * \"ensureRevisionOriginsTable\" | \"execute\" | \"executeStatement\">`.\n *\n * @throws {ConfigurationError} with the bundle's `portSurfaceCode` when the\n *   verdict says a core member is present and the port lacks it (I20).\n */\nexport function bindCore<\n  const D extends GatedBundleDefinition<\n    OptionalGraphBackendMember,\n    string,\n    OptionalGraphBackendMember\n  >,\n  M extends D[\"core\"][number],\n>(\n  port: Readonly<Partial<Pick<GraphBackend, M>>>,\n  verdict: Extract<BundleVerdictOf<D>, { supported: true }>,\n  definition: D,\n): BundleBinding<M> {\n  const bound = bindNames(\n    port,\n    verdict.members as readonly M[],\n    definition.id as CapabilityBundleId,\n  );\n  return bound as BundleBinding<M>;\n}\n\n/**\n * Bind one graduated extra. Takes the EXTRA's own verdict, not the bundle's:\n * `requireExtras` (`resolve.ts`) narrows `verdict.extras.someExtra` at an\n * `if`/assertion, not `verdict` as a whole, so a signature demanding the\n * whole narrowed verdict would compile only after that call — the common\n * case is the fallback branch, which never calls `requireExtras` at all.\n *\n * @throws {ConfigurationError} with the bundle's `portSurfaceCode` when the\n *   extra verdict says present and the port lacks the member (I20).\n */\nexport function bindExtra<const M extends OptionalGraphBackendMember>(\n  port: Readonly<Partial<Pick<GraphBackend, M>>>,\n  extraVerdict: Extract<ExtraVerdict<M>, { present: true }>,\n  bundle: CapabilityBundleId,\n): BundleBinding<M> {\n  const bound = bindNames(port, extraVerdict.members, bundle);\n  return bound as BundleBinding<M>;\n}\n\n/**\n * The FALLBACK arm of I20's disposition-keyed port-mismatch split (ruling,\n * B8 blocker): binds an extra when the verdict says it is present AND the\n * port can reach it, otherwise returns `undefined` — collapsing \"the verdict\n * says absent\" and \"the port cannot reach it\" into the site's single declared\n * fallback, which is exactly the shape a `fallback`-dispositioned row already\n * has. Used ONLY at call sites whose registry operation row disposes\n * `fallback`; a `refuse` row keeps calling {@link bindExtra} (or\n * {@link bindCore}) so its port mismatch still throws (I20's REFUSE arm).\n *\n * Deliberately does NOT consult the row's disposition itself: an extra's own\n * disposition and its operation row's disposition can differ (`\n * checkUniqueBatch` is a `fallback` extra owned by both a `fallback` row and\n * two `refuse` rows), so only the call site — which knows which row it is —\n * can choose the arm.\n */\nexport function bindExtraIfReachable<\n  const M extends OptionalGraphBackendMember,\n>(\n  port: Readonly<Partial<Pick<GraphBackend, M>>>,\n  extraVerdict: ExtraVerdict<M>,\n  bundle: CapabilityBundleId,\n): BundleBinding<M> | undefined {\n  if (!extraVerdict.present) return undefined;\n  if (findMissingPortMember(port, extraVerdict.members) !== undefined) {\n    return undefined;\n  }\n  return bindExtra(port, extraVerdict, bundle);\n}\n\n/**\n * The one owner of \"bind every extra the verdict marks present\" — the three\n * graduated bundle-wide \"members\" accessors below each call this with their\n * own bundle id rather than re-spelling the present/absent fold.\n */\nfunction bindPresentExtraVerdicts(\n  port: Readonly<Partial<Pick<GraphBackend, OptionalGraphBackendMember>>>,\n  extras: Readonly<Record<string, ExtraVerdict<OptionalGraphBackendMember>>>,\n  bundle: CapabilityBundleId,\n): Record<string, unknown> {\n  const bound = createDataKeyedBag<unknown>();\n  for (const extraVerdict of Object.values(extras)) {\n    if (!extraVerdict.present) continue;\n    Object.assign(bound, bindExtra(port, extraVerdict, bundle));\n  }\n  return bound;\n}\n\nexport function claimsMembers(\n  port: Readonly<Partial<Pick<GraphBackend, (typeof CLAIMS)[\"core\"][number]>>>,\n  verdict: Extract<BundleVerdictOf<typeof CLAIMS>, { supported: true }>,\n): BundleBinding<(typeof CLAIMS)[\"core\"][number]> {\n  return bindCore(port, verdict, CLAIMS);\n}\n\nexport function statementExecutionMembers(\n  port: Readonly<\n    Partial<Pick<GraphBackend, (typeof STATEMENT_EXECUTION)[\"core\"][number]>>\n  >,\n  verdict: Extract<\n    BundleVerdictOf<typeof STATEMENT_EXECUTION>,\n    { supported: true }\n  >,\n): BundleBinding<(typeof STATEMENT_EXECUTION)[\"core\"][number]> {\n  return bindCore(port, verdict, STATEMENT_EXECUTION);\n}\n\nexport function recordedRevisionOriginsMembers(\n  port: Readonly<\n    Partial<\n      Pick<GraphBackend, (typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]>\n    >\n  >,\n  verdict: Extract<\n    BundleVerdictOf<typeof RECORDED_REVISION_ORIGINS>,\n    { supported: true }\n  >,\n): BundleBinding<(typeof RECORDED_REVISION_ORIGINS)[\"core\"][number]> {\n  return bindCore(port, verdict, RECORDED_REVISION_ORIGINS);\n}\n\ntype UniqueSidecarBatchExtraMember = ExtraMember<\n  typeof UNIQUE_SIDECAR_BATCH,\n  keyof ExtrasOf<typeof UNIQUE_SIDECAR_BATCH>\n>;\n\nexport function uniqueSidecarBatchMembers(\n  port: Readonly<Partial<Pick<GraphBackend, UniqueSidecarBatchExtraMember>>>,\n  verdict: BundleVerdictOf<typeof UNIQUE_SIDECAR_BATCH>,\n): PartialBundleBinding<UniqueSidecarBatchExtraMember> {\n  const bound = bindPresentExtraVerdicts(\n    port,\n    verdict.extras,\n    UNIQUE_SIDECAR_BATCH.id,\n  );\n  return bound as unknown as PartialBundleBinding<UniqueSidecarBatchExtraMember>;\n}\n\ntype BatchPointReadExtraMember = ExtraMember<\n  typeof BATCH_POINT_READ,\n  keyof ExtrasOf<typeof BATCH_POINT_READ>\n>;\n\nexport function batchPointReadMembers(\n  port: Readonly<Partial<Pick<GraphBackend, BatchPointReadExtraMember>>>,\n  verdict: BundleVerdictOf<typeof BATCH_POINT_READ>,\n): PartialBundleBinding<BatchPointReadExtraMember> {\n  const bound = bindPresentExtraVerdicts(\n    port,\n    verdict.extras,\n    BATCH_POINT_READ.id,\n  );\n  return bound as unknown as PartialBundleBinding<BatchPointReadExtraMember>;\n}\n\ntype EndpointSetReadExtraMember = ExtraMember<\n  typeof ENDPOINT_SET_READ,\n  keyof ExtrasOf<typeof ENDPOINT_SET_READ>\n>;\n\nexport function endpointSetReadMembers(\n  port: Readonly<Partial<Pick<GraphBackend, EndpointSetReadExtraMember>>>,\n  verdict: BundleVerdictOf<typeof ENDPOINT_SET_READ>,\n): PartialBundleBinding<EndpointSetReadExtraMember> {\n  const bound = bindPresentExtraVerdicts(\n    port,\n    verdict.extras,\n    ENDPOINT_SET_READ.id,\n  );\n  return bound as unknown as PartialBundleBinding<EndpointSetReadExtraMember>;\n}\n\ntype ContributionHealthExtraMember = ExtraMember<\n  typeof CONTRIBUTION_HEALTH,\n  keyof ExtrasOf<typeof CONTRIBUTION_HEALTH>\n>;\n\nexport function contributionHealthMembers(\n  port: Readonly<Partial<Pick<GraphBackend, ContributionHealthExtraMember>>>,\n  verdict: BundleVerdictOf<typeof CONTRIBUTION_HEALTH>,\n): PartialBundleBinding<ContributionHealthExtraMember> {\n  const bound = bindPresentExtraVerdicts(\n    port,\n    verdict.extras,\n    CONTRIBUTION_HEALTH.id,\n  );\n  return bound as unknown as PartialBundleBinding<ContributionHealthExtraMember>;\n}\n","/**\n * The `recursiveTraversal` capability: whether this engine can compute a\n * BOUNDED TRANSITIVE CLOSURE of a relation in one round trip — the traversal\n * primitive, not the SQL syntax.\n */\nimport { ConfigurationError } from \"../../errors\";\nimport { type BackendCapabilities } from \"../types\";\n\n/**\n * Whether this engine can compute a BOUNDED TRANSITIVE CLOSURE of a relation\n * in one round trip — the traversal primitive, not the SQL syntax. A SQL\n * engine satisfies it with `WITH RECURSIVE`; a graph-native engine satisfies\n * it with a native expansion operator. What the capability promises is the\n * SEMANTICS: given a seed set, a step relation, and a hop bound, the engine\n * returns the reachable set (optionally with depth and path) without the\n * client issuing one statement per hop.\n *\n * Absent means SUPPORTED. Every engine TypeGraph ships supports it, and every\n * custom backend already has the six emission sites run against it\n * unconditionally: making absence mean `false` would refuse traversals that\n * work today. This mirrors `returning`, not `constraintClaims` — absence is\n * only allowed to mean \"false\" where absence is SAFE, and here it is not. A\n * backend that genuinely lacks the primitive must say so.\n */\nexport type RecursiveTraversalCapability = Readonly<{\n  supported: boolean;\n  /**\n   * Why the engine lacks it — surfaced in every refusal's details so the\n   * state is named rather than implied. Required when `supported: false` and\n   * forbidden when `true`, so the union cannot carry a dangling reason.\n   */\n  reason?: string;\n}>;\n\n/**\n * The brand. Declared but never exported, and never assigned at runtime — it\n * exists only so that an object literal outside this module is not assignable\n * to {@link RecursiveTraversalVerdict}. Compare `VectorSlot`'s construction\n * discipline: the type is public, the constructor is the seam.\n */\ndeclare const RECURSIVE_TRAVERSAL_VERDICT: unique symbol;\n\n/**\n * The decision, branded so it can only originate from this module's\n * constructors. Round 1 made the verdict a required *field*, which forces a\n * token, not a verdict: any caller could satisfy it by writing\n * `{ supported: true }` inline, and nothing tied the value to the resolver.\n * The brand closes that at the type level.\n */\nexport type RecursiveTraversalVerdict = Readonly<\n  { [RECURSIVE_TRAVERSAL_VERDICT]: true } & (\n    { supported: true } | { supported: false; reason: string }\n  )\n>;\n\n/** THE one reader of `capabilities.recursiveTraversal`, and THE one constructor. */\nexport function resolveRecursiveTraversal(\n  capabilities: BackendCapabilities,\n): RecursiveTraversalVerdict {\n  const declared = capabilities.recursiveTraversal;\n  if (declared === undefined) {\n    return { supported: true } as RecursiveTraversalVerdict;\n  }\n  if (declared.supported) {\n    return { supported: true } as RecursiveTraversalVerdict;\n  }\n  // A raw custom-backend object may never have passed the §4 assert\n  // (`assertBundledCapabilityDeclarations`), so `reason` is not guaranteed to\n  // be present even though the type says it is. Naming the state explicitly\n  // beats a default that would hide a contradictory declaration.\n  return {\n    supported: false,\n    reason:\n      declared.reason ??\n      \"backend declares recursiveTraversal: { supported: false }\",\n  } as RecursiveTraversalVerdict;\n}\n\n/**\n * The ONE sanctioned way to obtain a verdict without a backend: the query\n * compiler's public entry point `compileQuery(ast, graphId, \"postgres\")`\n * takes no backend at all, so it has no capabilities to resolve from. The\n * reason string is required and is echoed in nothing — it exists so the call\n * site states why it is allowed to assume.\n */\nexport function assumeRecursiveTraversalSupported(\n  reason: string,\n): RecursiveTraversalVerdict {\n  // `reason` is intentionally unused in the returned verdict: it documents\n  // the assumption at the call site rather than becoming part of the value.\n  void reason;\n  return { supported: true } as RecursiveTraversalVerdict;\n}\n\n/** THE one refusal builder. */\nexport function recursiveTraversalUnsupportedError(\n  verdict: Extract<RecursiveTraversalVerdict, { supported: false }>,\n  operation: string,\n): ConfigurationError {\n  return new ConfigurationError(\n    `${operation} requires recursive traversal, but this backend declares recursiveTraversal: { supported: false }.`,\n    {\n      code: \"RECURSIVE_TRAVERSAL_UNSUPPORTED\",\n      capability: \"recursiveTraversal\",\n      operation,\n      reason: verdict.reason,\n    },\n    {\n      suggestion:\n        \"Use a backend that supports recursive traversal, or avoid this query shape.\",\n    },\n  );\n}\n\n/** THE one assertion: refuses when the verdict says the engine cannot. */\nexport function assertRecursiveTraversal(\n  verdict: RecursiveTraversalVerdict,\n  operation: string,\n): asserts verdict is Extract<RecursiveTraversalVerdict, { supported: true }> {\n  if (verdict.supported) return;\n  throw recursiveTraversalUnsupportedError(verdict, operation);\n}\n","/**\n * The write-fence capability: how this engine excludes concurrent writers,\n * declared as `capabilities.writeFence`.\n *\n * `resolveWriteFencePlan` is THE one owner of the write-fence decision every\n * lock site used to re-derive from `dialect` inline. A lock site never\n * spells the dialect itself; it resolves a plan and consumes it.\n */\nimport { ConfigurationError } from \"../../errors\";\nimport { type SqlTableNames } from \"../../query/compiler/schema\";\nimport { type SqlDialect } from \"../../query/dialect/types\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { type BackendCapabilities } from \"../types\";\n\n/**\n * The lock-statement spelling a backend supplies alongside its\n * `writeFence` declaration.\n *\n * `advisory` needs `advisoryLockExpression` and `isolationFactExpression`\n * (required by that mechanism's own construction-time check below); `row`\n * needs neither — TypeGraph spells its acquire statement itself from the\n * fences relation — but MAY supply `isolationFactExpression` so recorded\n * capture and match-key convergence can still read the session fact off the\n * same acquisition (absent, they fail closed on an unknown fact, as they do\n * today). `lockTables` is needed by either mechanism only when its\n * declaration's `drain` is `\"table-lock\"`. Every member therefore stays\n * optional in the type; {@link planFromWriteFenceDeclaration} is what\n * refuses construction when the RESOLVED mechanism/drain combination needed\n * a member this object does not supply.\n *\n * This is deliberately the ONLY spelling a backend author writes.\n * {@link resolveFenceStatements} derives the standalone-statement forms\n * (`acquireKeyed`, `acquireKeyedWithIsolation`, `isolationFact`) from these\n * expressions — a backend never spells both a statement and the expression\n * it wraps separately, so the fused embedding and the standalone statement\n * can never disagree about what they lock or read.\n *\n * `advisoryLockExpression`'s `key` accepts a `number` for the\n * database-scoped locks that key on a constant second argument (`0`) rather\n * than a hashed value — the two-argument `pg_advisory_xact_lock(int4, int4)`\n * overload takes that second argument as a plain integer, never as\n * `hashtext(...)` of one.\n */\nexport type FenceSql = Readonly<{\n  /** A relation lock, e.g. `LOCK TABLE ... IN ... MODE`. */\n  lockTables?: (\n    tables: readonly string[],\n    mode: \"share\" | \"share-row-exclusive\" | \"access-exclusive\",\n  ) => SqlFragment;\n  /**\n   * The bare lock expression, with no `SELECT` around it. A statement that\n   * must take the lock INSIDE a larger query it composes itself embeds this\n   * directly — PostgreSQL's fused schema + graph-write fence\n   * (`postgres-schema-write-fence.ts`) is the one site that needs this: it\n   * reaches the schema table, so it cannot be built from a standalone\n   * statement. Every other lock site consumes\n   * {@link resolveFenceStatements}'s derived `acquireKeyed`, which wraps\n   * this in a standalone `SELECT`. Absent for a `row`-mechanism target,\n   * which has no lock expression to embed.\n   */\n  advisoryLockExpression?: (\n    namespace: string,\n    key: string | number,\n  ) => SqlFragment;\n  /**\n   * The bare session isolation-level read, with no `SELECT`/alias around\n   * it — embedded the same way `advisoryLockExpression` is, and wrapped by\n   * {@link resolveFenceStatements}'s derived `isolationFact` /\n   * `acquireKeyedWithIsolation` for every other site.\n   */\n  isolationFactExpression?: () => SqlFragment;\n}>;\n\n/**\n * `FenceSql`'s author-supplied expressions plus the three\n * mechanism-neutral standalone-statement forms {@link resolveFenceStatements}\n * derives from them — what a `lock` or `row` plan's `sql` field actually\n * carries, and what every ordinary lock site consumes. A site never asks\n * which mechanism produced its `sql`; it calls `acquireKeyed`,\n * `acquireKeyedWithIsolation`, or `isolationFact` exactly the same way\n * either way.\n */\nexport type FenceStatements = FenceSql &\n  Readonly<{\n    /**\n     * A keyed exclusion, scoped to the transaction: `pg_advisory_xact_lock`\n     * under `advisory`, an `INSERT ... ON CONFLICT ... DO UPDATE ...\n     * RETURNING` against the fences relation under `row`.\n     */\n    acquireKeyed: (namespace: string, key: string | number) => SqlFragment;\n    /**\n     * The same acquisition plus the session's isolation-level fact, in ONE\n     * statement — the \"session facts come from the session that enforces\n     * them\" contract: the fact is read on the exact connection the\n     * acquisition was just taken on. Under `row` with no\n     * `isolationFactExpression` supplied, the acquisition still runs and\n     * returns its generation; the isolation fact is simply absent from the\n     * row, which the consumers already read as \"unknown\" and fail closed on.\n     */\n    acquireKeyedWithIsolation: (\n      namespace: string,\n      key: string | number,\n    ) => SqlFragment;\n    /**\n     * The bare session isolation-level read, with no acquisition. Yields no\n     * row when the target supplies no `isolationFactExpression` — the same\n     * \"unknown fact\" shape a real read produces for a value this fence\n     * cannot classify.\n     */\n    isolationFact: () => SqlFragment;\n  }>;\n\nfunction advisoryAcquireKeyedStatement(\n  advisoryLockExpression: NonNullable<FenceSql[\"advisoryLockExpression\"]>,\n  namespace: string,\n  key: string | number,\n): SqlFragment {\n  return sql`SELECT ${advisoryLockExpression(namespace, key)}`;\n}\n\nfunction advisoryAcquireKeyedWithIsolationStatement(\n  advisoryLockExpression: NonNullable<FenceSql[\"advisoryLockExpression\"]>,\n  isolationFactExpression: NonNullable<FenceSql[\"isolationFactExpression\"]>,\n  namespace: string,\n  key: string | number,\n): SqlFragment {\n  return sql`\n    SELECT\n      ${advisoryLockExpression(namespace, key)},\n      ${isolationFactExpression()} AS transaction_isolation\n  `;\n}\n\n/**\n * The composite key every `row`-mechanism acquisition writes: the existing\n * advisory namespace and key, joined verbatim, so the lock-order and\n * namespace-per-position invariants every keyed site already relies on\n * carry over unchanged to the fences relation.\n */\nfunction fenceRowKey(namespace: string, key: string | number): string {\n  return `${namespace}:${key}`;\n}\n\n/**\n * The portable acquisition statement every `row`-mechanism keyed site\n * shares: an UPSERT that always advances the row's own stored generation\n * (never the literal `1` this statement inserts), so two acquirers of the\n * same key always observe a strictly increasing sequence regardless of\n * which one the engine admits first. `isolationFactExpression`, when\n * supplied, rides the same `RETURNING` clause the generation does, so the\n * fact is read on the exact statement that took the row.\n */\nfunction fenceRowAcquireStatement(\n  fencesTable: SqlFragment,\n  namespace: string,\n  key: string | number,\n  isolationFactExpression?: FenceSql[\"isolationFactExpression\"],\n): SqlFragment {\n  const isolationColumn =\n    isolationFactExpression === undefined ?\n      sql``\n    : sql`, ${isolationFactExpression()} AS transaction_isolation`;\n  return sql`\n    INSERT INTO ${fencesTable} (key, generation)\n    VALUES (${fenceRowKey(namespace, key)}, 1)\n    ON CONFLICT (key) DO UPDATE SET generation = ${fencesTable}.generation + 1\n    RETURNING generation${isolationColumn}\n  `;\n}\n\n/**\n * The bare session isolation-level read shared by both mechanisms: wraps\n * `isolationFactExpression` in a standalone `SELECT` when the target\n * supplies one, and otherwise a statement that yields no row — the same\n * \"unknown fact\" shape {@link normalizeGraphCommandIsolation}-style readers\n * already treat a missing column as, so a target with no expression fails\n * closed exactly as it does today rather than needing a new case.\n */\nfunction isolationFactStatement(\n  isolationFactExpression?: FenceSql[\"isolationFactExpression\"],\n): SqlFragment {\n  return isolationFactExpression === undefined ?\n      sql`SELECT NULL AS transaction_isolation WHERE 1 = 0`\n    : sql`SELECT ${isolationFactExpression()} AS transaction_isolation`;\n}\n\n/**\n * Which derivation {@link resolveFenceStatements} applies — an explicit\n * discriminant, never inferred from what `fenceSql` happens to contain: the\n * BUNDLED PostgreSQL factory always supplies the full `postgresFenceSql`\n * (including `advisoryLockExpression`) as its profile's `fenceSql`\n * REGARDLESS of which mechanism a derived profile declares (a test deriving\n * `writeFence.mechanism: \"row\"` from the bundled factory does not thereby\n * swap out `fenceSql`), so the SHAPE of `fenceSql` alone cannot say which\n * mechanism resolved. Defaults to `\"advisory\"` when omitted: both external\n * callers of {@link resolveFenceStatements} outside `planFromWriteFenceDeclaration`\n * (`clock.ts`'s bundled-spelling renderers, `guards.ts`'s dialect-gated\n * isolation read, gated on `dialect` alone, never on a resolved mechanism)\n * only ever want the advisory derivation or call `isolationFact()` — which\n * renders identically under either derivation — so the default costs them\n * nothing.\n */\ntype FenceStatementsStyle =\n  | Readonly<{ mechanism: \"advisory\" }>\n  | Readonly<{ mechanism: \"row\"; fencesTableName?: string | undefined }>;\n\nconst ADVISORY_FENCE_STATEMENTS_STYLE: FenceStatementsStyle = {\n  mechanism: \"advisory\",\n};\n\n/**\n * THE one owner of \"wrap a fence's acquire/isolation expressions in their\n * standalone statement forms\": derives `acquireKeyed`,\n * `acquireKeyedWithIsolation`, and `isolationFact` — the only way to reach\n * those three forms, so a fused embedding and a portable lock site can\n * never spell the lock or the isolation read differently. Called by\n * `planFromWriteFenceDeclaration` once per resolved `lock` or `row` plan\n * (passing its own resolved {@link FenceStatementsStyle} explicitly), and\n * directly by the two callers described on that type for a target's own\n * standalone statements without resolving a full plan.\n */\nexport function resolveFenceStatements(\n  fenceSql: FenceSql,\n  style: FenceStatementsStyle = ADVISORY_FENCE_STATEMENTS_STYLE,\n): FenceStatements {\n  const { isolationFactExpression } = fenceSql;\n  if (style.mechanism === \"advisory\") {\n    // Resolved lazily, inside the two acquisition closures below, rather\n    // than eagerly here: `guards.ts`'s session-fact read calls this with the\n    // default (`\"advisory\"`) style regardless of which mechanism the target\n    // actually declared, wanting only `isolationFact()` — a `row` target\n    // that supplies `isolationFactExpression` but no `advisoryLockExpression`\n    // must still get a rendered fact read from that call, not a `TypeError`\n    // for a member `isolationFact()` never needed. `isolationFact()` itself\n    // never requires either expression: it renders identically to the `row`\n    // derivation's own `isolationFactStatement` call, the \"costs them\n    // nothing\" default the module doc above promises.\n    function requiredAdvisoryLockExpression(): NonNullable<\n      FenceSql[\"advisoryLockExpression\"]\n    > {\n      return requireDefined(\n        fenceSql.advisoryLockExpression,\n        \"resolveFenceStatements: an advisory fenceSql's advisoryLockExpression was validated present above\",\n      );\n    }\n    function requiredIsolationFactExpression(): NonNullable<\n      FenceSql[\"isolationFactExpression\"]\n    > {\n      return requireDefined(\n        isolationFactExpression,\n        \"resolveFenceStatements: an advisory fenceSql's isolationFactExpression was validated present above\",\n      );\n    }\n    return {\n      ...fenceSql,\n      acquireKeyed: (namespace: string, key: string | number) =>\n        advisoryAcquireKeyedStatement(\n          requiredAdvisoryLockExpression(),\n          namespace,\n          key,\n        ),\n      acquireKeyedWithIsolation: (namespace: string, key: string | number) =>\n        advisoryAcquireKeyedWithIsolationStatement(\n          requiredAdvisoryLockExpression(),\n          requiredIsolationFactExpression(),\n          namespace,\n          key,\n        ),\n      isolationFact: () => isolationFactStatement(isolationFactExpression),\n    };\n  }\n  // Resolved lazily, inside the two closures below, rather than eagerly\n  // here: a `row` plan is shaped for EVERY resolved declaration, including\n  // one a purely drain-side site (J4, J6, J18) resolves without ever\n  // calling `acquireKeyed`/`acquireKeyedWithIsolation` — such a site must\n  // not refuse over a fences table name it never needed. The refusal below\n  // therefore fires the first time one of those two is actually CALLED, not\n  // when this function returns — `WriteFenceTarget.tableNames`' own doc\n  // names this same deferral.\n  const { fencesTableName } = style;\n  function requiredFencesTable(): SqlFragment {\n    if (fencesTableName === undefined) {\n      throw new ConfigurationError(\n        \"This row-mechanism write fence has no fences table name \" +\n          \"(`tableNames.fences`), so TypeGraph cannot spell the fence-row \" +\n          \"acquisition.\",\n        { code: \"WRITE_FENCE_SQL_UNAVAILABLE\" },\n        {\n          suggestion:\n            \"Supply `tableNames.fences` on this backend (the bundled SQLite/PostgreSQL backends default it to `typegraph_fences`).\",\n        },\n      );\n    }\n    return sql.identifier(fencesTableName);\n  }\n  return {\n    ...fenceSql,\n    acquireKeyed: (namespace: string, key: string | number) =>\n      fenceRowAcquireStatement(requiredFencesTable(), namespace, key),\n    acquireKeyedWithIsolation: (namespace: string, key: string | number) =>\n      fenceRowAcquireStatement(\n        requiredFencesTable(),\n        namespace,\n        key,\n        isolationFactExpression,\n      ),\n    isolationFact: () => isolationFactStatement(isolationFactExpression),\n  };\n}\n\n/**\n * How a backend excludes concurrent writers, and how far a caller that took\n * the lock can drain the resource it protects.\n *\n * `mechanism` is the exclusion primitive: `\"advisory\"` is a keyed\n * `pg_advisory_xact_lock`-style lock a caller takes explicitly (and needs\n * `fenceSql` to spell); `\"row\"` is a keyed exclusion spelled by TypeGraph\n * itself against a never-dropped relation of fence rows, for an engine with\n * no advisory-lock primitive; `\"engine-serialized\"` is the engine's own\n * single writer slot (SQLite); `\"caller-serialized\"` is a promise the\n * DEPLOYMENT makes rather than the engine or a lock — the backend's own\n * process serializes every write unit it issues (see the in-process queue\n * this mechanism requires) AND no other client writes to the same database\n * while this backend is open.\n *\n * `drain` is a separate fact, and applies ONLY to `mechanism: \"advisory\"` or\n * `\"row\"`: whether a caller that already took the keyed exclusion can\n * additionally take a relation-wide lock on the resource a table-lock site\n * protects. `\"table-lock\"` means yes (a `LOCK TABLE`-style statement is\n * available and appropriate); `\"quiescent\"` means the resource is already\n * exclusive for another reason (e.g. a `caller-serialized` in-process queue\n * layered alongside an advisory lock) so a table-lock site takes NO\n * statement rather than one it does not need; `\"none\"` means neither — a\n * table-lock site refuses, naming this drain. `\"engine-serialized\"` and\n * `\"caller-serialized\"` carry no `drain`: an engine's single writer slot and\n * an in-process serialization promise are each already a stronger exclusion\n * than any `drain` value could add, so there is nothing for the field to say\n * — declaring one alongside either mechanism is refused\n * (`WRITE_FENCE_DECLARATION_INVALID`, `validateWriteFenceDeclaration` below).\n *\n * `conflict` applies ONLY to `mechanism: \"row\"`: the engine fact for two\n * writers of one fence row. `\"wait\"` is a lock-based engine — the second\n * acquirer's statement blocks until the first commits, exactly like an\n * advisory lock. `\"commit-time\"` is an optimistic-concurrency engine — both\n * acquirers proceed and the loser's COMMIT fails, so correctness comes from\n * the unit owner retrying it, never from waiting; the retry can only run\n * inside an interactive transaction it replays, so `\"commit-time\"` requires\n * `capabilities.execution.interactiveTransactions: true` and is refused on a\n * backend that declares it `false` — the tier `commit-time` needs would\n * silently never derive otherwise (`WRITE_FENCE_DECLARATION_INVALID`,\n * `validateWriteFenceDeclaration` below). Declaring `conflict` on any other\n * mechanism is refused the same way an out-of-place `drain` is.\n */\nexport type WriteFenceDeclaration =\n  | Readonly<{\n      mechanism: \"advisory\";\n      drain: \"table-lock\" | \"quiescent\" | \"none\";\n    }>\n  | Readonly<{\n      mechanism: \"row\";\n      drain: \"table-lock\" | \"quiescent\" | \"none\";\n      conflict: \"wait\" | \"commit-time\";\n    }>\n  | Readonly<{ mechanism: \"engine-serialized\" }>\n  | Readonly<{ mechanism: \"caller-serialized\" }>;\n\n/**\n * The two members of {@link WriteFenceDeclaration} that carry `drain` —\n * named so a function that runs for either a resolved `\"advisory\"` or\n * `\"row\"` declaration (the fence-SQL refusal below) can say so in its own\n * parameter type instead of accepting the full union and re-widening\n * `drain` into \"possibly absent\".\n */\ntype DrainCarryingWriteFenceDeclaration = Extract<\n  WriteFenceDeclaration,\n  { mechanism: \"advisory\" | \"row\" }\n>;\n\n/**\n * The decision every lock site consumes, rather than a flag a caller would\n * have to re-derive.\n */\nexport type WriteFencePlan =\n  /**\n   * Take the keyed advisory lock, spelled by `sql` — the target's OWN\n   * declared spelling: a lock site never hand-writes the statement, it\n   * resolves a plan and consumes `sql.<builder>(…)`.\n   */\n  | Readonly<{\n      kind: \"lock\";\n      drain: \"table-lock\" | \"quiescent\" | \"none\";\n      sql: FenceStatements;\n    }>\n  /**\n   * Take the keyed exclusion against the fences relation, spelled by `sql` —\n   * mechanism-neutral: a keyed site calls the exact same `sql.acquireKeyed`/\n   * `sql.acquireKeyedWithIsolation` a `lock` plan's site calls. `conflict`\n   * is the one fact a `row` site (and the tier deriving `optimistic-retry`)\n   * reads that a `lock` site never needs, because an advisory engine only\n   * ever waits.\n   */\n  | Readonly<{\n      kind: \"row\";\n      drain: \"table-lock\" | \"quiescent\" | \"none\";\n      conflict: \"wait\" | \"commit-time\";\n      sql: FenceStatements;\n    }>\n  /** No lock needed: the engine serializes writers. */\n  | Readonly<{ kind: \"engine-serialized\" }>\n  /**\n   * No lock needed: the deployment itself promises no concurrent writer\n   * exists — this backend's own process serializes every write unit it\n   * issues, and no other client writes to the database while it is open.\n   */\n  | Readonly<{ kind: \"caller-serialized\" }>\n  /** Neither. Every non-degradable fence refuses: `capabilities.writeFence` is absent. */\n  | Readonly<{ kind: \"unfenced\" }>;\n\n/**\n * What `resolveWriteFencePlan` needs: the dialect (for the first-party\n * dialect-derivation arm and for the refusal message), the declared\n * capabilities, the lock-statement spelling a resolved `\"advisory\"` or\n * `\"row\"` mechanism requires, and — for `\"row\"` — the resolved table names\n * carrying the physical name of the fences relation\n * `resolveFenceStatements` spells its acquisition against. Structural on\n * purpose — see the module-private first-party mark below, which is\n * carried out-of-band rather than as a type member. `GraphBackend`'s own\n * `tableNames` field already satisfies this structurally, so every lock\n * site that calls `resolveWriteFencePlan(target)` with the backend itself —\n * narrowed to whatever `Pick<GraphBackend, ...>` that site declares — reads\n * the SAME resolved fences table name a `row`-mechanism backend was built\n * with, with no separate field to keep in sync.\n */\nexport type WriteFenceTarget = Readonly<{\n  dialect: SqlDialect;\n  capabilities: BackendCapabilities;\n  fenceSql?: FenceSql | undefined;\n  /**\n   * Read only when the resolved mechanism is `\"row\"` — specifically\n   * `tableNames.fences`. Typed as the same optional-field `SqlTableNames`\n   * `GraphBackend.tableNames` declares (rather than the fully resolved\n   * `ResolvedSqlTableNames`) so every existing lock site that passes the\n   * backend itself as this target — narrowed to whatever `Pick<GraphBackend,\n   * ...>` that site declares — stays structurally assignable with no\n   * changes; a target whose `tableNames.fences` is genuinely absent refuses\n   * the first time a keyed site actually acquires the fence row instead\n   * (`resolveFenceStatements`'s `requiredFencesTable`, called lazily so a\n   * purely drain-side site that never acquires never refuses over a name it\n   * never needed).\n   */\n  tableNames?: SqlTableNames | undefined;\n}>;\n\n/**\n * Marks a backend (or a small fence-target object built alongside one) as\n * produced by `createSqliteBackend` / `createPostgresBackend`, so\n * `resolveWriteFencePlan`'s dialect-derivation arm — correct only for a\n * factory backend, unsound for anything else (M-5) — is reachable only from\n * them.\n *\n * A `WeakSet<object>` keyed by object identity, not a `unique symbol`\n * property: `deriveBackend` returns a `Proxy` whose `set` trap writes\n * through to a possibly-frozen base, so a symbol property written at\n * construction is not guaranteed to survive every derivation the same way a\n * side-table entry does, and a `WeakSet` is unforgeable by a custom\n * backend in a way a plain property is not. Module-private and NOT\n * barrelled: nothing outside this module and `derive-backend.ts` may mark or\n * carry the mark.\n */\nconst FIRST_PARTY_FACTORY_BACKENDS = new WeakSet<object>();\n\n/**\n * The two first-party factories call this on the backend object they are\n * about to return (or on a small fence-target object built alongside one),\n * before it escapes the factory body.\n *\n * @internal\n */\nexport function markFirstPartyFactory<T extends object>(target: T): T {\n  FIRST_PARTY_FACTORY_BACKENDS.add(target);\n  return target;\n}\n\n/**\n * Whether `target` came from one of TypeGraph's bundled backend factories.\n *\n * This stays an out-of-band, unforgeable fact for the same reason as\n * {@link markFirstPartyFactory}: an arbitrary backend that happens to report\n * the same dialect cannot thereby opt into an optimization whose transaction\n * lifetime TypeGraph has not audited.\n *\n * @internal\n */\nexport function isFirstPartyFactory(target: object): boolean {\n  return FIRST_PARTY_FACTORY_BACKENDS.has(target);\n}\n\n/**\n * Carries the first-party mark from a source object onto one derived from\n * it, so a factory backend projected or decorated for a transaction still\n * resolves the SAME plan its source would — a lost mark would otherwise\n * answer \"dialect-derived\" at one call site and \"unfenced\" at another for\n * the same underlying backend.\n *\n * `src/backend/derive-backend.ts` is the only module allowed to call this,\n * alongside its call to `carryBackendResourceAudit`.\n *\n * @internal\n */\nexport function carryFirstPartyFactoryMark(\n  derived: object,\n  base: object,\n): void {\n  if (FIRST_PARTY_FACTORY_BACKENDS.has(base)) {\n    FIRST_PARTY_FACTORY_BACKENDS.add(derived);\n  }\n}\n\n/**\n * The bundled-profile objects `buildSqliteEngineProfile` and\n * `buildPostgresEngineProfile` returned, keyed by object identity rather\n * than a field. Module-private for the same reason\n * `FIRST_PARTY_FACTORY_BACKENDS` is: `registerFirstPartyProfile` grants\n * standing to the ONE object each builder returns, so a copy, spread, or\n * otherwise derived profile is a new object this set has never seen and is\n * never first-party — no field on it could carry the standing forward the\n * way a spread carries every other key.\n */\nconst FIRST_PARTY_PROFILES = new WeakSet<object>();\n\n/**\n * The `SqlEngineProfile` fields `registerFirstPartyProfile` freezes beyond\n * the profile object itself — read through this narrow structural shape\n * rather than `SqlEngineProfile` itself, so this module (below\n * `create-sql-backend.ts` and `./profile` in the dependency order) need not\n * import the profile type to reach them.\n */\ntype ProfileTrustBearingBags = Readonly<{\n  declaredCapabilities?: object;\n  resourceAudit?: object;\n  autocommit?: object;\n  tableNames?: object;\n  fenceSql?: object;\n}>;\n\n/**\n * Registers `profile` as first-party and returns the SAME object, frozen —\n * a builder writes `const profile: SqlEngineProfile<...> = {...}; return\n * registerFirstPartyProfile(profile);` and hands its caller back exactly the\n * object this set now recognizes. Called once each by\n * `buildSqliteEngineProfile` and `buildPostgresEngineProfile` on the exact\n * object they return. Not exported from `src/backend/index.ts` or the\n * `adapters/drizzle/engine` entrypoint, so nothing outside this module can\n * grant a profile first-party standing — a profile assembled anywhere else,\n * including one built by spreading a bundled profile's fields into a new\n * object literal, is a different object and is never registered.\n *\n * The `Object.freeze` on `profile` itself binds its own fields — a caller\n * cannot replace `profile.resourceAudit` with a different object — but that\n * alone leaves every sub-object still mutable in place. That matters because\n * `deriveEngineProfile` builds a derived profile as `{...base, ...overrides}`:\n * any field `overrides` does not name is the SAME sub-object `base` holds,\n * not a copy, so `derived.resourceAudit.kind = \"serialized\"` would otherwise\n * mutate `base.resourceAudit` directly, behind the override validation that\n * only ever sees `overrides`. So this also freezes the bags a derived\n * profile shares with `base` by reference: `resourceAudit`, `autocommit`,\n * `tableNames`, `fenceSql`, and `declaredCapabilities` — their OWN fields,\n * not what those fields point to. `declaredCapabilities` arrives already\n * sealed: each builder passes its declaration through\n * `sealCapabilityDeclaration` (`./declarations`), the one owner of \"clone,\n * then deep-freeze\", so the bag is immutable all the way down and never\n * aliases an object the caller supplied as an override. `resourceAudit\n * .resource` and `identityLeaseResource` stay reachable and mutable: those\n * are the driver's own connection handles, not data TypeGraph owns, and\n * freezing the `resourceAudit` object itself already blocks swapping which\n * handle it names. `fenceSql`'s own functions stay reachable and mutable\n * too — this freeze binds only the CONTAINER, so a derived profile can\n * still be constructed with a fresh `fenceSql` override, but it blocks a\n * caller from reassigning `derived.fenceSql.advisoryLockExpression` (or any\n * other member) in place, which would otherwise silently rewrite the\n * spelling `base.fenceSql` hands back too. Every other profile field is a\n * closure this module has no business freezing (`execution`, `provisioning`,\n * the six `*Runtime` bags, `assembly`).\n *\n * `deriveEngineProfile` itself is unaffected beyond this: it reads `base`'s\n * fields and spreads them into a NEW object literal, which spreading a\n * frozen source object does not freeze — a caller who overrides\n * `declaredCapabilities` with a fresh literal gets back a profile whose\n * `declaredCapabilities` is that fresh, unfrozen object, exactly as before.\n *\n * @internal\n */\nexport function registerFirstPartyProfile<T extends object>(profile: T): T {\n  FIRST_PARTY_PROFILES.add(profile);\n  const bags = profile as ProfileTrustBearingBags;\n  if (bags.declaredCapabilities !== undefined) {\n    Object.freeze(bags.declaredCapabilities);\n  }\n  if (bags.resourceAudit !== undefined) Object.freeze(bags.resourceAudit);\n  if (bags.autocommit !== undefined) Object.freeze(bags.autocommit);\n  if (bags.tableNames !== undefined) Object.freeze(bags.tableNames);\n  if (bags.fenceSql !== undefined) Object.freeze(bags.fenceSql);\n  return Object.freeze(profile);\n}\n\n/**\n * Whether `profile` is an object {@link registerFirstPartyProfile} has\n * actually registered.\n *\n * `createSqlBackend` calls this once per assembly and uses the result to\n * gate every `markFirstPartyFactory` call it makes — on the backend it\n * returns and on the one fence target it builds. A profile this module\n * never registered leaves both unmarked, which in turn keeps two things\n * closed to it: `resolveWriteFencePlan`'s dialect-derivation fallback\n * (sound only for the two bundled dialects) and the lazy schema-fence\n * lease `src/store/operations/write-transaction.ts` takes out under\n * `isFirstPartyFactory`.\n *\n * @internal\n */\nexport function isFirstPartyProfile(profile: object): boolean {\n  return FIRST_PARTY_PROFILES.has(profile);\n}\n\n/**\n * The write-fence declaration a first-party (bundled-factory) target derives\n * when its `capabilities` name no `writeFence` — exactly what every lock\n * site used to compute inline from `dialect` before this capability\n * existed. `writeFenceDeclarationLine` formats this same derivation as the\n * migration-guide literal a refusal prints, so the derivation and the\n * printed suggestion can never disagree.\n */\nfunction deriveFromDialect(dialect: SqlDialect): WriteFenceDeclaration {\n  switch (dialect) {\n    case \"postgres\": {\n      return { mechanism: \"advisory\", drain: \"table-lock\" };\n    }\n    case \"sqlite\": {\n      return { mechanism: \"engine-serialized\" };\n    }\n    default: {\n      return dialect satisfies never;\n    }\n  }\n}\n\n/**\n * Which declaration style {@link planFromWriteFenceDeclaration} resolved its\n * `WriteFenceDeclaration` from — carried only so\n * {@link refuseWriteFenceSqlUnavailable} can name the declaration the target\n * ACTUALLY made, rather than assuming a shape unconditionally.\n *\n * - `\"writeFence\"` — the target declared `capabilities.writeFence` directly.\n * - `\"dialect\"` — `writeFence` is absent; a first-party factory target's\n *   `mechanism` came from {@link deriveFromDialect}.\n */\ntype WriteFenceDeclarationSource = \"writeFence\" | \"dialect\";\n\n/**\n * Names the declaration {@link refuseWriteFenceSqlUnavailable} blames for\n * promising a keyed exclusion this target cannot spell — the phrase each of\n * its two provenances (a direct `writeFence`, or the first-party dialect\n * derivation) fills in differently, so the refusal never states a\n * declaration the target did not actually make. The first-party dialect\n * derivation never resolves `mechanism: \"row\"` (only a bundled factory's\n * OWN `advisory`/`engine-serialized` split, {@link deriveFromDialect}), so\n * its phrase always describes an advisory lock; a directly declared `row`\n * still reads correctly through `formatWriteFenceDeclaration`.\n */\nfunction describeResolvedDrainCarryingDeclaration(\n  declaration: DrainCarryingWriteFenceDeclaration,\n  source: WriteFenceDeclarationSource,\n  dialect: SqlDialect,\n): string {\n  switch (source) {\n    case \"writeFence\": {\n      return `declares \\`capabilities.${formatWriteFenceDeclaration(declaration)}\\``;\n    }\n    case \"dialect\": {\n      return `resolves an advisory-lock write fence from its \\`${dialect}\\` dialect`;\n    }\n    default: {\n      return source satisfies never;\n    }\n  }\n}\n\n/**\n * Whether `fenceSql` actually supplies `member` as a callable — the runtime\n * check behind {@link refuseWriteFenceSqlUnavailable}'s per-member refusal.\n * `FenceSql`'s members are each optional on the type (a `row`-mechanism\n * target genuinely need not supply `advisoryLockExpression`, for one), so\n * this is the one place that turns \"does this resolved mechanism/drain\n * combination actually have what it needs?\" into a yes/no a caller can\n * refuse on — for BOTH a hand-built `fenceSql` missing a member its\n * declaration promised, and a mechanism that simply never needed the member\n * in the first place.\n */\nfunction fenceSqlMemberPresent(\n  fenceSql: FenceSql | undefined,\n  member: keyof FenceSql,\n): boolean {\n  return typeof fenceSql?.[member] === \"function\";\n}\n\n/**\n * What TypeGraph cannot spell without `member` — the phrase\n * {@link refuseWriteFenceSqlUnavailable} interpolates into its message so a\n * caller reads which statement is missing, not just that \"something\" is.\n */\nfunction fenceSqlMemberPurpose(member: keyof FenceSql): string {\n  switch (member) {\n    case \"advisoryLockExpression\": {\n      return \"advisory-lock statement this fence needs to take\";\n    }\n    case \"isolationFactExpression\": {\n      return \"session isolation-level read this fence needs to take\";\n    }\n    case \"lockTables\": {\n      return 'table-lock statement its drain: \"table-lock\" declaration needs to take';\n    }\n    default: {\n      return member satisfies never;\n    }\n  }\n}\n\n/**\n * THE refusal for a `lock` or `row` decision whose target supplies no\n * spelling — or an incomplete one — to take it with: never defaulted, never\n * silently degraded to `unfenced`. The declaration already promised a real\n * keyed exclusion exists, so the only honest response to a missing spelling\n * is to say so, naming the exact `fenceSql` member the resolved\n * mechanism/drain combination needed and could not find.\n *\n * The one call site is `planFromWriteFenceDeclaration`, shared by every\n * `resolveWriteFencePlan` arm that can resolve `mechanism: \"advisory\"` or\n * `\"row\"` — a declared `writeFence` and the first-party dialect derivation\n * both resolve through it, and each passes its own\n * {@link WriteFenceDeclarationSource} so the message names the declaration\n * the target actually made.\n *\n * @throws {ConfigurationError} always.\n */\nfunction refuseWriteFenceSqlUnavailable(\n  dialect: SqlDialect,\n  declaration: DrainCarryingWriteFenceDeclaration,\n  source: WriteFenceDeclarationSource,\n  member: keyof FenceSql,\n): never {\n  throw new ConfigurationError(\n    `This backend ${describeResolvedDrainCarryingDeclaration(declaration, source, dialect)} ` +\n      `but its \\`fenceSql\\` is missing \\`${member}\\`, so TypeGraph cannot ` +\n      `spell the ${fenceSqlMemberPurpose(member)}.`,\n    {\n      code: \"WRITE_FENCE_SQL_UNAVAILABLE\",\n      dialect,\n      member,\n      drain: declaration.drain,\n    },\n    {\n      suggestion:\n        dialect === \"postgres\" ?\n          \"Supply `fenceSql: postgresFenceSql` (exported from `@nicia-ai/typegraph/adapters/drizzle/postgres`) — the bundled PostgreSQL backend does this automatically — or provide a custom FenceSql matching this engine's lock syntax.\"\n        : 'Provide a custom `fenceSql: FenceSql` matching this engine\\'s lock syntax, or declare `writeFence.mechanism: \"engine-serialized\"` instead.',\n    },\n  );\n}\n\n/**\n * THE refusal for a session-fact read (no lock plan involved) whose target\n * supplies no `fenceSql` to spell it with. Distinct from\n * {@link refuseWriteFenceSqlUnavailable}: that refusal fires only under a\n * resolved `lock` plan, so it can name the declaration that actually\n * resolved to `mechanism: \"advisory\"` — a claim that makes no sense for a\n * target with no lock plan in play at all (e.g. one declaring `mechanism:\n * \"engine-serialized\"`). A session-fact read is gated on `dialect` alone,\n * not on a resolved plan, so it needs its own refusal naming what it\n * actually needs.\n *\n * @throws {ConfigurationError} always.\n */\nexport function refuseFenceSqlSessionFactUnavailable(\n  dialect: SqlDialect,\n): never {\n  throw new ConfigurationError(\n    `This ${dialect}-dialect backend supplies no \\`fenceSql\\`, so TypeGraph ` +\n      \"cannot spell the session isolation-level read recorded capture requires.\",\n    { code: \"WRITE_FENCE_SQL_UNAVAILABLE\", dialect },\n    {\n      suggestion:\n        dialect === \"postgres\" ?\n          \"Supply `fenceSql: postgresFenceSql` (exported from `@nicia-ai/typegraph/adapters/drizzle/postgres`) — the bundled PostgreSQL backend does this automatically — or provide a custom FenceSql matching this engine's lock syntax.\"\n        : \"Provide a custom `fenceSql: FenceSql` matching this engine's lock syntax.\",\n    },\n  );\n}\n\n/** {@link validateWriteFenceDeclaration}'s accepted `mechanism` values. */\nconst VALID_WRITE_FENCE_MECHANISMS = [\n  \"advisory\",\n  \"row\",\n  \"engine-serialized\",\n  \"caller-serialized\",\n] as const;\n\n/** {@link validateWriteFenceDeclaration}'s accepted `drain` values. */\nconst VALID_WRITE_FENCE_DRAINS = [\"table-lock\", \"quiescent\", \"none\"] as const;\n\n/**\n * {@link validateWriteFenceDeclaration}'s accepted `conflict` values —\n * `mechanism: \"row\"` only.\n */\nconst VALID_WRITE_FENCE_CONFLICTS = [\"wait\", \"commit-time\"] as const;\n\n/**\n * THE refusal for a `WriteFenceDeclaration` field TypeScript's discriminated\n * union cannot police at runtime — see {@link validateWriteFenceDeclaration}.\n *\n * @throws {ConfigurationError} always.\n */\nfunction refuseInvalidWriteFenceDeclaration(\n  field: \"mechanism\" | \"drain\" | \"conflict\",\n  value: unknown,\n  accepted: readonly string[],\n): never {\n  throw new ConfigurationError(\n    `capabilities.writeFence.${field} is invalid: ${JSON.stringify(value)}. ` +\n      `Accepted values are ${accepted.map((accepted) => `\"${accepted}\"`).join(\", \")}.`,\n    { code: \"WRITE_FENCE_DECLARATION_INVALID\", field, value, accepted },\n    {\n      suggestion: `Declare capabilities.writeFence.${field} as one of the accepted values.`,\n    },\n  );\n}\n\n/**\n * THE one validator of a raw `WriteFenceDeclaration` value, run before\n * {@link planFromWriteFenceDeclaration} shapes a plan from it.\n *\n * TypeScript's discriminated union only holds a caller who goes through the\n * type checker — a plain-JavaScript backend author, or a value round-tripped\n * through JSON/config, can supply any string for `mechanism` or `drain`, or\n * attach a `drain` to a serialized mechanism that accepts none. Every one of\n * those is refused HERE, before a plan is shaped, for two reasons a\n * downstream `default` arm cannot provide on its own: an invalid `drain`\n * must never fall through to behaving like `\"quiescent\"` (a table-lock site\n * would then silently take no lock instead of refusing), and an invalid\n * `mechanism` must never reach a switch's `default` arm, which — unlike this\n * validator — has no reason to believe the value it was handed is one of the\n * cases it already exhausted, and `x satisfies never` is a compile-time\n * assertion only: at runtime it would return the invalid string as though it\n * were a resolved plan.\n *\n * `interactiveTransactions` is the target's OWN `capabilities.execution`\n * fact (never re-derived here), checked only against `conflict:\n * \"commit-time\"`: that value is honored solely by the `optimistic-retry`\n * execution tier replaying a unit inside an interactive transaction, and\n * `finalizeEngineCapabilities` derives that tier only when\n * `interactiveTransactions` is `true` — declaring `\"commit-time\"` on a\n * backend that reports `false` would otherwise be accepted here and then\n * silently dropped downstream (the loser would fail with no retry). An\n * accepted declaration is applied or refused; it is never ignored.\n */\nfunction validateWriteFenceDeclaration(\n  declaration: WriteFenceDeclaration,\n  interactiveTransactions: boolean,\n): void {\n  const mechanism: string = declaration.mechanism;\n  if (\n    !(VALID_WRITE_FENCE_MECHANISMS as readonly string[]).includes(mechanism)\n  ) {\n    refuseInvalidWriteFenceDeclaration(\n      \"mechanism\",\n      mechanism,\n      VALID_WRITE_FENCE_MECHANISMS,\n    );\n  }\n  if (mechanism === \"advisory\" || mechanism === \"row\") {\n    const drain: string = (declaration as DrainCarryingWriteFenceDeclaration)\n      .drain;\n    if (!(VALID_WRITE_FENCE_DRAINS as readonly string[]).includes(drain)) {\n      refuseInvalidWriteFenceDeclaration(\n        \"drain\",\n        drain,\n        VALID_WRITE_FENCE_DRAINS,\n      );\n    }\n    if (mechanism === \"row\") {\n      const conflict: string = (\n        declaration as Extract<WriteFenceDeclaration, { mechanism: \"row\" }>\n      ).conflict;\n      if (\n        !(VALID_WRITE_FENCE_CONFLICTS as readonly string[]).includes(conflict)\n      ) {\n        refuseInvalidWriteFenceDeclaration(\n          \"conflict\",\n          conflict,\n          VALID_WRITE_FENCE_CONFLICTS,\n        );\n      }\n      if (conflict === \"commit-time\" && !interactiveTransactions) {\n        throw new ConfigurationError(\n          'capabilities.writeFence.conflict: \"commit-time\" requires ' +\n            \"capabilities.execution.interactiveTransactions: true — the \" +\n            '\"optimistic-retry\" execution tier that replays a commit-time ' +\n            \"loser only derives on an interactive backend; on a \" +\n            \"non-interactive one the declaration would be accepted and then \" +\n            \"silently dropped, leaving the loser's write fail with no retry.\",\n          {\n            code: \"WRITE_FENCE_DECLARATION_INVALID\",\n            field: \"conflict\",\n            mechanism,\n            conflict,\n          },\n          {\n            suggestion:\n              'Declare capabilities.execution.interactiveTransactions: true, or declare conflict: \"wait\" instead.',\n          },\n        );\n      }\n      return;\n    }\n    // mechanism === \"advisory\": `conflict` is a `row`-only fact (the engine\n    // behavior of two writers of ONE fence row), which an advisory lock\n    // never has — a caller declaring it here is refused the same way a\n    // stray `drain` on a serialized mechanism is, below.\n    if (\"conflict\" in declaration) {\n      throw new ConfigurationError(\n        'capabilities.writeFence.conflict applies only to mechanism: \"row\"; ' +\n          '\"advisory\" must not declare a conflict.',\n        {\n          code: \"WRITE_FENCE_DECLARATION_INVALID\",\n          field: \"conflict\",\n          mechanism,\n        },\n        {\n          suggestion:\n            'Remove conflict from this writeFence declaration — mechanism: \"advisory\" needs none.',\n        },\n      );\n    }\n    return;\n  }\n  if (\"drain\" in declaration) {\n    throw new ConfigurationError(\n      \"capabilities.writeFence.drain applies only to \" +\n        `mechanism: \"advisory\" or \"row\"; \"${mechanism}\" must not declare a drain.`,\n      {\n        code: \"WRITE_FENCE_DECLARATION_INVALID\",\n        field: \"drain\",\n        mechanism,\n      },\n      {\n        suggestion: `Remove drain from this writeFence declaration — mechanism: \"${mechanism}\" needs none.`,\n      },\n    );\n  }\n  if (\"conflict\" in declaration) {\n    throw new ConfigurationError(\n      \"capabilities.writeFence.conflict applies only to \" +\n        `mechanism: \"row\"; \"${mechanism}\" must not declare a conflict.`,\n      {\n        code: \"WRITE_FENCE_DECLARATION_INVALID\",\n        field: \"conflict\",\n        mechanism,\n      },\n      {\n        suggestion: `Remove conflict from this writeFence declaration — mechanism: \"${mechanism}\" needs none.`,\n      },\n    );\n  }\n}\n\n/**\n * THE one constructor of a {@link WriteFencePlan} from an already-resolved\n * {@link WriteFenceDeclaration}, regardless of which declaration style\n * produced it (`capabilities.writeFence` directly, or the first-party\n * dialect derivation). One owner means both provenances resolve to the\n * identical plan shape.\n *\n * `source` names which of those two provenances `declaration` came from —\n * threaded only to {@link refuseWriteFenceSqlUnavailable}, so a missing\n * `fenceSql` is blamed on the declaration the target actually made.\n */\nfunction planFromWriteFenceDeclaration(\n  target: WriteFenceTarget,\n  declaration: WriteFenceDeclaration,\n  source: WriteFenceDeclarationSource,\n): WriteFencePlan {\n  validateWriteFenceDeclaration(\n    declaration,\n    target.capabilities.execution.interactiveTransactions,\n  );\n  switch (declaration.mechanism) {\n    case \"advisory\": {\n      if (!fenceSqlMemberPresent(target.fenceSql, \"advisoryLockExpression\")) {\n        refuseWriteFenceSqlUnavailable(\n          target.dialect,\n          declaration,\n          source,\n          \"advisoryLockExpression\",\n        );\n      }\n      if (!fenceSqlMemberPresent(target.fenceSql, \"isolationFactExpression\")) {\n        refuseWriteFenceSqlUnavailable(\n          target.dialect,\n          declaration,\n          source,\n          \"isolationFactExpression\",\n        );\n      }\n      if (\n        declaration.drain === \"table-lock\" &&\n        !fenceSqlMemberPresent(target.fenceSql, \"lockTables\")\n      ) {\n        refuseWriteFenceSqlUnavailable(\n          target.dialect,\n          declaration,\n          source,\n          \"lockTables\",\n        );\n      }\n      return {\n        kind: \"lock\",\n        drain: declaration.drain,\n        sql: resolveFenceStatements(\n          requireDefined(\n            target.fenceSql,\n            \"resolveWriteFencePlan: fenceSql was validated present above\",\n          ),\n        ),\n      };\n    }\n    case \"row\": {\n      if (\n        declaration.drain === \"table-lock\" &&\n        !fenceSqlMemberPresent(target.fenceSql, \"lockTables\")\n      ) {\n        refuseWriteFenceSqlUnavailable(\n          target.dialect,\n          declaration,\n          source,\n          \"lockTables\",\n        );\n      }\n      return {\n        kind: \"row\",\n        drain: declaration.drain,\n        conflict: declaration.conflict,\n        // `target.fenceSql` may be entirely absent for a `row` target that\n        // declares no isolation read and no table-lock drain — `FenceSql`'s\n        // members are all optional, so `{}` is itself a valid (empty) one.\n        // `mechanism: \"row\"` is passed explicitly, never inferred from\n        // `fenceSql`'s shape: the bundled PostgreSQL factory's `fenceSql` is\n        // the same `postgresFenceSql` object (advisoryLockExpression\n        // included) regardless of which mechanism this declaration names.\n        sql: resolveFenceStatements(target.fenceSql ?? {}, {\n          mechanism: \"row\",\n          fencesTableName: target.tableNames?.fences,\n        }),\n      };\n    }\n    case \"engine-serialized\": {\n      return { kind: \"engine-serialized\" };\n    }\n    case \"caller-serialized\": {\n      return { kind: \"caller-serialized\" };\n    }\n    default: {\n      // Unreachable for a TypeScript-typed caller (exhaustive above) and for\n      // any runtime value too: `validateWriteFenceDeclaration` already\n      // refused an unrecognized `mechanism` before this switch ran. Refuses\n      // rather than returning `declaration.mechanism satisfies never` —\n      // which, for an actual invalid string reaching here, would hand that\n      // string back as though it were a resolved `WriteFencePlan`.\n      return refuseInvalidWriteFenceDeclaration(\n        \"mechanism\",\n        (declaration as WriteFenceDeclaration).mechanism,\n        VALID_WRITE_FENCE_MECHANISMS,\n      );\n    }\n  }\n}\n\n/**\n * THE one reader of `capabilities.writeFence`, and THE one constructor of a\n * {@link WriteFencePlan}.\n *\n * Resolution order:\n *\n * 1. **`writeFence` declared** — resolve it directly through\n *    {@link planFromWriteFenceDeclaration}.\n * 2. **Undeclared, first-party factory** — derive from `dialect`\n *    ({@link deriveFromDialect}), which is exactly what every lock site used\n *    to compute inline. Both bundled factories declare `writeFence`\n *    unconditionally, so nothing in-tree reaches this arm; it is reachable\n *    only from tests that build a backend object bypassing the factories'\n *    declared capabilities while still carrying the first-party mark.\n * 3. **Undeclared, anything else** — `unfenced`. Conservative: an\n *    undeclared custom backend is by definition uncertified, and inferring\n *    lock support from `dialect` alone is the unsound inference this\n *    capability replaces (a PostgreSQL-wire backend reporting `dialect:\n *    \"postgres\"` need not honor `pg_advisory_xact_lock`).\n */\nexport function resolveWriteFencePlan(\n  target: WriteFenceTarget,\n): WriteFencePlan {\n  const { writeFence } = target.capabilities;\n  if (writeFence !== undefined) {\n    return planFromWriteFenceDeclaration(target, writeFence, \"writeFence\");\n  }\n  if (FIRST_PARTY_FACTORY_BACKENDS.has(target)) {\n    return planFromWriteFenceDeclaration(\n      target,\n      deriveFromDialect(target.dialect),\n      \"dialect\",\n    );\n  }\n  return { kind: \"unfenced\" };\n}\n\n/**\n * Formats a {@link WriteFenceDeclaration} exactly as a caller would write it\n * under `capabilities.writeFence`.\n */\nfunction formatWriteFenceDeclaration(\n  declaration: WriteFenceDeclaration,\n): string {\n  switch (declaration.mechanism) {\n    case \"advisory\": {\n      return `writeFence: { mechanism: \"advisory\", drain: \"${declaration.drain}\" }`;\n    }\n    case \"row\": {\n      return (\n        `writeFence: { mechanism: \"row\", drain: \"${declaration.drain}\", ` +\n        `conflict: \"${declaration.conflict}\" }`\n      );\n    }\n    case \"engine-serialized\": {\n      return 'writeFence: { mechanism: \"engine-serialized\" }';\n    }\n    case \"caller-serialized\": {\n      return 'writeFence: { mechanism: \"caller-serialized\" }';\n    }\n    default: {\n      return refuseInvalidWriteFenceDeclaration(\n        \"mechanism\",\n        (declaration as WriteFenceDeclaration).mechanism,\n        VALID_WRITE_FENCE_MECHANISMS,\n      );\n    }\n  }\n}\n\n/**\n * THE one owner of the literal declaration line a refusal recommends —\n * printed verbatim by both unfenced refusals below and by\n * `createSqlBackend`'s own construction-time gate, so the migration guide\n * cannot rot into a pointer (ruling OQ-B).\n */\nexport function writeFenceDeclarationLine(\n  dialect: SqlDialect,\n  indent = \"\",\n): string {\n  const line = formatWriteFenceDeclaration(deriveFromDialect(dialect));\n  return `${indent}${line}`;\n}\n\n/**\n * The shared body of both unfenced-construction refusals below: `undeclared`\n * is the only way `resolveWriteFencePlan` ever reaches `unfenced` now that\n * `writeFence` is the sole declaration, so this states that fact plainly and\n * prints the fix, keyed to the dialect the backend reports.\n */\nfunction unfencedRefusalMessage(dialect: SqlDialect, resource: string): string {\n  return (\n    \"This backend declares no usable write fence: `capabilities.writeFence` \" +\n    `is absent, so TypeGraph cannot know whether it fences concurrent ` +\n    `writers, and ${resource} cannot run unfenced. Declare it:\\n\\n` +\n    `${writeFenceDeclarationLine(dialect, \"  \")}\\n`\n  );\n}\n\n/**\n * THE refusal for Operational Identity constructed against an `unfenced`\n * backend. §5.3.1 (J9b).\n *\n * @throws {ConfigurationError} always.\n */\nexport function refuseUnfencedOperationalIdentity(dialect: SqlDialect): never {\n  throw new ConfigurationError(\n    unfencedRefusalMessage(dialect, \"Operational Identity\"),\n    { code: \"IDENTITY_REQUIRES_WRITE_FENCE\", dialect },\n    {\n      suggestion:\n        \"Declare `capabilities.writeFence` on this backend, or construct the store without `identity`.\",\n    },\n  );\n}\n\n/**\n * THE refusal for TypeGraph-owned recorded-clock allocation (`history` /\n * `revisionTracking`) constructed against an `unfenced` backend that owns\n * its own recorded-time relations. §5.3.1 (J9a).\n *\n * @throws {ConfigurationError} always.\n */\nexport function refuseUnfencedClockAllocation(dialect: SqlDialect): never {\n  throw new ConfigurationError(\n    unfencedRefusalMessage(\n      dialect,\n      \"TypeGraph's recorded-time clock allocation\",\n    ),\n    { code: \"RECORDED_CLOCK_REQUIRES_WRITE_FENCE\", dialect },\n    {\n      suggestion:\n        \"Declare `capabilities.writeFence` on this backend, or construct the store without `history`/`revisionTracking`.\",\n    },\n  );\n}\n\n/**\n * THE refusal for a fence that cannot degrade: `unfenced` always refuses,\n * and a `lock` or `row` plan whose `drain` cannot back the table lock an\n * operation requires refuses too — the declared-advisory-only (or\n * declared-row-only) posture (`drain: \"none\"`), which T15 exercises as its\n * own matrix row.\n *\n * `engine-serialized` and `caller-serialized` satisfy both `requires`\n * values without consulting `drain`: a writer slot and an in-process,\n * out-of-band serialization promise are each a stronger exclusion than\n * either lock shape, so there is nothing for either `requires` to add.\n *\n * @throws {ConfigurationError} under `unfenced`, and under\n * `(kind: \"lock\" | \"row\") && drain === \"none\"` when `requires === \"drain\"`.\n */\nexport function requireWriteFence(\n  plan: WriteFencePlan,\n  operation: string,\n  requires: \"keyed\" | \"drain\",\n): Extract<\n  WriteFencePlan,\n  { kind: \"lock\" | \"row\" | \"engine-serialized\" | \"caller-serialized\" }\n> {\n  switch (plan.kind) {\n    case \"lock\":\n    case \"row\": {\n      if (requires === \"drain\" && plan.drain === \"none\") {\n        throw new ConfigurationError(\n          `${operation} requires a table lock, but this backend's write-fence ` +\n            'declaration reports drain: \"none\".',\n          {\n            code: \"WRITE_FENCE_UNAVAILABLE\",\n            operation,\n            requires,\n            plan,\n          },\n          {\n            suggestion:\n              'Declare `writeFence.drain: \"table-lock\"` on this backend, or avoid this operation.',\n          },\n        );\n      }\n      return plan;\n    }\n    case \"engine-serialized\": {\n      return plan;\n    }\n    case \"caller-serialized\": {\n      return plan;\n    }\n    case \"unfenced\": {\n      throw new ConfigurationError(\n        `${operation} requires a write fence, but this backend declares no ` +\n          \"usable write fence (`capabilities.writeFence` is absent).\",\n        {\n          code: \"WRITE_FENCE_UNAVAILABLE\",\n          operation,\n          requires,\n        },\n        {\n          suggestion:\n            \"Declare `capabilities.writeFence` on this backend, matching the engine's real locking support.\",\n        },\n      );\n    }\n    default: {\n      plan satisfies never;\n      throw new ConfigurationError(\n        `${operation} could not resolve a write-fence plan.`,\n        { code: \"WRITE_FENCE_UNAVAILABLE\", operation, requires },\n      );\n    }\n  }\n}\n\n/**\n * THE one accessor for `fence.sql.lockTables` at a drain site — never\n * re-spelled per site. Call only after checking `fence.drain ===\n * \"table-lock\"` (TypeScript cannot narrow a resolved `lock`/`row` fence's\n * type on that check alone, since `drain` is not `WriteFencePlan`'s\n * discriminant): `lockTables` is guaranteed present at that point,\n * regardless of which mechanism resolved — `planFromWriteFenceDeclaration`\n * already refused construction of a `table-lock` declaration whose target\n * supplies no `lockTables` ({@link refuseWriteFenceSqlUnavailable}). This\n * `requireDefined` only turns that already-established runtime guarantee\n * into the type narrowing TypeScript cannot infer on its own —\n * `FenceStatements` inherits `lockTables?` from `FenceSql`, since an\n * `advisory`/`row` target with `drain !== \"table-lock\"` genuinely need not\n * supply one.\n */\nexport function requireFenceLockTables(\n  fence: Extract<WriteFencePlan, { kind: \"lock\" | \"row\" }>,\n  operation: string,\n): NonNullable<FenceSql[\"lockTables\"]> {\n  return requireDefined(\n    fence.sql.lockTables,\n    `${operation}: lockTables was validated present by the resolved drain: \"table-lock\" plan`,\n  );\n}\n","import { CompilerInvariantError, ConfigurationError } from \"../errors\";\nimport type {\n  EdgeConvergeCreateCommand,\n  EdgeConvergeCreateCommandResult,\n  EdgeCreateCommand,\n  EdgeCreateCommandResult,\n  GraphCommand,\n  GraphCommandCoordination,\n  GraphCommandExecutionContext,\n  GraphCommandIsolation,\n  GraphCommandPort,\n  GraphCommandResult,\n  GraphCommandSession,\n  NodeCreateCommand,\n  NodeCreateCommandResult,\n} from \"./types\";\n\nconst graphCommandCoordinationBindings = new WeakMap<\n  object,\n  Readonly<{\n    graphId: string;\n    isolation: GraphCommandIsolation;\n    sessionIdentity: object;\n  }>\n>();\nconst graphCommandPortSessionIdentities = new WeakMap<object, object>();\n\nexport type {\n  GraphCommandCoordination,\n  GraphCommandExecutionContext,\n  GraphCommandIsolation,\n  GraphCommandSession,\n} from \"./types\";\n\n/**\n * Retains a transaction command session's identity across a transparent port\n * wrapper. Coordination attaches to the session identity, not the wrapper\n * object, so an observing/decorating backend cannot make a proven\n * advisory lock look like it belongs to another connection.\n */\nexport function carryGraphCommandPortSessionMetadata(\n  base: GraphCommandPort,\n  derived: GraphCommandPort,\n): void {\n  if (base.session !== derived.session) {\n    throw new CompilerInvariantError(\n      \"A derived graph command port must retain its base command session.\",\n      { baseSession: base.session, derivedSession: derived.session },\n    );\n  }\n  graphCommandPortSessionIdentities.set(\n    derived,\n    graphCommandPortSessionIdentity(base),\n  );\n}\n\nfunction graphCommandPortSessionIdentity(port: GraphCommandPort): object {\n  return graphCommandPortSessionIdentities.get(port) ?? port;\n}\n\n/**\n * Internal evidence mint used only after a graph's advisory lock has been\n * acquired on the command port's transaction. The binding prevents a real\n * lock from transaction A (or graph A) authorizing a command on B.\n */\nexport function mintGraphCommandCoordination(\n  port: GraphCommandPort,\n  graphId: string,\n  isolation: GraphCommandIsolation,\n): GraphCommandCoordination {\n  const coordination = Object.freeze({}) as GraphCommandCoordination;\n  graphCommandCoordinationBindings.set(coordination, {\n    graphId,\n    isolation,\n    sessionIdentity: graphCommandPortSessionIdentity(port),\n  });\n  return coordination;\n}\n\nfunction isGraphCommandCoordination(\n  value: unknown,\n): value is GraphCommandCoordination {\n  if (typeof value !== \"object\" || value === null) return false;\n  return graphCommandCoordinationBindings.has(value);\n}\n\n/** Normalize a database isolation setting into command-contract vocabulary. */\nexport function normalizeGraphCommandIsolation(\n  value: unknown,\n): GraphCommandIsolation {\n  if (typeof value !== \"string\") return \"unknown\";\n  switch (value.replaceAll(\" \", \"_\").toLowerCase()) {\n    case \"read_committed\":\n    case \"read_uncommitted\": {\n      return \"read_committed\";\n    }\n    case \"repeatable_read\": {\n      return \"repeatable_read\";\n    }\n    case \"serializable\": {\n      return \"serializable\";\n    }\n    default: {\n      return \"unknown\";\n    }\n  }\n}\n\nfunction boundGraphCommandCoordination(\n  port: GraphCommandPort,\n  coordination: GraphCommandCoordination,\n  graphId?: string,\n) {\n  const binding = graphCommandCoordinationBindings.get(coordination);\n  return (\n      binding?.sessionIdentity === graphCommandPortSessionIdentity(port) &&\n        (graphId === undefined || binding.graphId === graphId)\n    ) ?\n      binding\n    : undefined;\n}\n\n/** Effective isolation of coordination earned by this graph and transaction. */\nexport function graphCommandCoordinationIsolation(\n  port: GraphCommandPort,\n  graphId: string,\n  coordination: GraphCommandCoordination,\n): GraphCommandIsolation {\n  return (\n    boundGraphCommandCoordination(port, coordination, graphId)?.isolation ??\n    \"unknown\"\n  );\n}\n\n/**\n * A match-key convergence must observe the winner after waiting for its graph\n * lock. Repeatable-read snapshots cannot do that; serializable can instead\n * force a database serialization retry. Adopted/custom transaction ports\n * without an audited isolation level fail closed for the same reason.\n */\nexport function assertGraphCommandConvergenceIsolation(\n  port: GraphCommandPort,\n  coordination: GraphCommandCoordination,\n): void {\n  const isolation =\n    boundGraphCommandCoordination(port, coordination)?.isolation ?? \"unknown\";\n  if (isolation === \"read_committed\" || isolation === \"serializable\") return;\n  throw new ConfigurationError(\n    \"Match-key convergence requires read-committed or serializable transaction isolation.\",\n    {\n      code: \"MATCH_KEY_CONVERGENCE_REQUIRES_FRESH_SNAPSHOT\",\n      isolation,\n    },\n    {\n      suggestion:\n        \"Use read_committed, retry a serializable transaction as a whole, or configure a custom PostgreSQL graph-write fence to report the effective transaction isolation.\",\n    },\n  );\n}\n\n/** Assert that a coordination token belongs to this port and command graph. */\nexport function assertGraphCommandCoordination(\n  port: GraphCommandPort,\n  command: GraphCommand,\n  coordination: GraphCommandCoordination,\n): void {\n  if (\n    boundGraphCommandCoordination(\n      port,\n      coordination,\n      command.plan.params.graphId,\n    ) !== undefined\n  ) {\n    return;\n  }\n  throw new CompilerInvariantError(\n    \"Graph command coordination does not belong to this transaction port and graph.\",\n    { graphId: command.plan.params.graphId },\n  );\n}\n\n/** Build the non-negotiable context for one command session. */\nexport function graphCommandExecutionContext(\n  session: GraphCommandSession,\n  coordination: \"none\" | GraphCommandCoordination = \"none\",\n): GraphCommandExecutionContext {\n  if (session === \"root\") {\n    if (coordination !== \"none\") {\n      throw new CompilerInvariantError(\n        \"A root command cannot inherit a transaction-scoped graph write lock.\",\n        { coordination, session },\n      );\n    }\n    return { session, coordination: \"none\" };\n  }\n  return { session, coordination };\n}\n\n/**\n * Validate a context before it reaches a first-party executor. The helper\n * below always creates a valid value, while direct port callers use this same\n * assertion to keep session/coordination shape single-owned.\n */\nexport function assertGraphCommandExecutionContext(\n  context: unknown,\n): asserts context is GraphCommandExecutionContext {\n  const facts =\n    typeof context === \"object\" && context !== null ?\n      (context as Readonly<Record<string, unknown>>)\n    : undefined;\n  if (\n    facts === undefined ||\n    (facts[\"coordination\"] !== \"none\" &&\n      !isGraphCommandCoordination(facts[\"coordination\"])) ||\n    !(\n      (facts[\"session\"] === \"root\" && facts[\"coordination\"] === \"none\") ||\n      facts[\"session\"] === \"transaction\"\n    )\n  ) {\n    throw new CompilerInvariantError(\n      \"A graph command received an invalid execution context.\",\n      { context: facts },\n    );\n  }\n}\n\n/** Refuse a backend result that does not describe the submitted command. */\nexport function assertCommandResultMatchesCommand(\n  command: NodeCreateCommand,\n  result: GraphCommandResult,\n): asserts result is NodeCreateCommandResult;\nexport function assertCommandResultMatchesCommand(\n  command: EdgeCreateCommand,\n  result: GraphCommandResult,\n): asserts result is EdgeCreateCommandResult;\nexport function assertCommandResultMatchesCommand(\n  command: EdgeConvergeCreateCommand,\n  result: GraphCommandResult,\n): asserts result is EdgeConvergeCreateCommandResult;\nexport function assertCommandResultMatchesCommand(\n  command: GraphCommand,\n  result: GraphCommandResult,\n): void;\nexport function assertCommandResultMatchesCommand(\n  command: GraphCommand,\n  result: GraphCommandResult,\n): void {\n  const planEntity = command.plan.entity;\n  const graphId = command.plan.params.graphId;\n  const commandId = command.plan.params.id;\n  const resultEntity = result.entity;\n  if (resultEntity !== planEntity) {\n    throw new CompilerInvariantError(\n      \"A command result must describe the submitted command entity.\",\n      {\n        planEntity,\n        resultEntity,\n        graphId,\n        id: commandId,\n      },\n    );\n  }\n  if (result.outcome === \"found\") {\n    if (command.kind !== \"edge.converge-create\") {\n      throw new CompilerInvariantError(\n        \"Only an edge convergence command may return a found result.\",\n        { commandKind: command.kind, graphId, id: commandId },\n      );\n    }\n    const row = result.row;\n    const params = command.plan.params;\n    const matchIdentityMatches =\n      command.match.kind === \"dynamic\" ||\n      (row.match_identity_name === command.match.identity.name &&\n        row.match_identity_key === command.match.identity.key);\n    if (\n      row.graph_id === params.graphId &&\n      row.kind === params.kind &&\n      row.from_kind === params.fromKind &&\n      row.from_id === params.fromId &&\n      row.to_kind === params.toKind &&\n      row.to_id === params.toId &&\n      matchIdentityMatches\n    ) {\n      return;\n    }\n    throw new CompilerInvariantError(\n      \"A convergent edge result row must match the submitted edge identity.\",\n      {\n        command: {\n          graphId: params.graphId,\n          kind: params.kind,\n          fromKind: params.fromKind,\n          fromId: params.fromId,\n          toKind: params.toKind,\n          toId: params.toId,\n        },\n        result: {\n          graphId: row.graph_id,\n          kind: row.kind,\n          fromKind: row.from_kind,\n          fromId: row.from_id,\n          toKind: row.to_kind,\n          toId: row.to_id,\n        },\n      },\n    );\n  }\n  const plan = command.plan;\n  if (result.outcome !== \"created\") return;\n  const durableIdentityMatches =\n    plan.entity === \"node\" ||\n    plan.params.matchIdentity === undefined ||\n    (result.entity === \"edge\" &&\n      result.row.match_identity_name === plan.params.matchIdentity.name &&\n      result.row.match_identity_key === plan.params.matchIdentity.key);\n  if (\n    result.row.graph_id === plan.params.graphId &&\n    result.row.kind === plan.params.kind &&\n    result.row.id === plan.params.id &&\n    durableIdentityMatches\n  ) {\n    return;\n  }\n  throw new CompilerInvariantError(\n    \"A command result row must match the submitted command identity.\",\n    {\n      command: {\n        graphId: plan.params.graphId,\n        kind: plan.params.kind,\n        id: plan.params.id,\n      },\n      result: {\n        graphId: result.row.graph_id,\n        kind: result.row.kind,\n        id: result.row.id,\n      },\n    },\n  );\n}\n\n/**\n * Execute a command through the explicit authoritative seam.\n *\n * Store write paths must use this helper so session and coordination evidence\n * are explicit at every first-party call site.\n */\nexport function executeAuthoritativeGraphCommand(\n  port: GraphCommandPort,\n  command: NodeCreateCommand,\n  coordination?: \"none\" | GraphCommandCoordination,\n): Promise<NodeCreateCommandResult>;\n/** Execute an authoritative edge-create command and return its typed result. */\nexport function executeAuthoritativeGraphCommand(\n  port: GraphCommandPort,\n  command: EdgeCreateCommand,\n  coordination?: \"none\" | GraphCommandCoordination,\n): Promise<EdgeCreateCommandResult>;\n/** Execute an authoritative convergent edge-create command and return its typed result. */\nexport function executeAuthoritativeGraphCommand(\n  port: GraphCommandPort,\n  command: EdgeConvergeCreateCommand,\n  coordination?: \"none\" | GraphCommandCoordination,\n): Promise<EdgeConvergeCreateCommandResult>;\n/** Execute any graph command when its concrete kind is not statically known. */\nexport function executeAuthoritativeGraphCommand(\n  port: GraphCommandPort,\n  command: GraphCommand,\n  coordination?: \"none\" | GraphCommandCoordination,\n): Promise<GraphCommandResult>;\nexport function executeAuthoritativeGraphCommand(\n  port: GraphCommandPort,\n  command: GraphCommand,\n  coordination: \"none\" | GraphCommandCoordination = \"none\",\n): Promise<GraphCommandResult> {\n  const context = graphCommandExecutionContext(port.session, coordination);\n  assertGraphCommandExecutionContext(context);\n  if (coordination !== \"none\") {\n    assertGraphCommandCoordination(port, command, coordination);\n    if (command.kind === \"edge.converge-create\") {\n      // Store and public helper callers are checked here before a custom port\n      // can execute the convergence command.\n      assertGraphCommandConvergenceIsolation(port, coordination);\n    }\n  }\n  return port.execute(command, context).then((result) => {\n    assertCommandResultMatchesCommand(command, result);\n    return result;\n  });\n}\n","import type {\n  BackendCapabilities,\n  BackendExecutionCapabilities,\n} from \"../types\";\n\n/**\n * THE one derivation of `execution.unitOfWork` from the two execution facts\n * plus one optional root-backend fact. An engine that can hold an open\n * callback transaction groups a write that way regardless of whether it also\n * exposes an atomic batch primitive — unless `fenceConflict` is\n * `\"commit-time\"`, meaning the caller resolved this backend's write-fence\n * plan to mechanism `row` with an engine that lets two acquirers of one fence\n * row both proceed and fails the loser's COMMIT: the interactive transaction\n * alone is not enough on that fence, and the tier becomes `\"optimistic-retry\"`\n * instead. With no interactive transaction, a closed atomic program is the\n * unit when one exists, and there is none at all when neither does. Every\n * place that changes `atomicBatch` — the capability tail and the two\n * boundaries below — re-derives through this function, so the facts can\n * never disagree on one object.\n *\n * `fenceConflict` is resolved once, in `createSqlBackend`, from the root\n * profile's declared write-fence capability — it is a root-backend fact, not\n * something a derived or session-scoped capabilities object can re-resolve\n * for itself. `downgradeAtomicBatch` and `scopeAtomicBatchToSession` below\n * never have it to hand, but they are not blind to it either: the source\n * object they derive from already carries the ROOT's answer in its own\n * `execution.unitOfWork`, so they read `\"optimistic-retry\"` back off that\n * field as their `fenceConflict` input rather than rediscovering it.\n * Omitting `fenceConflict` altogether — a capabilities object with no\n * established `unitOfWork` yet — always answers `\"interactive\"` or\n * `\"batch\"`/`\"none\"`, never `\"optimistic-retry\"`.\n */\nexport function deriveUnitOfWork(\n  execution: Pick<\n    BackendExecutionCapabilities,\n    \"interactiveTransactions\" | \"atomicBatch\"\n  > &\n    Readonly<{\n      /**\n       * The resolved write-fence plan's `conflict` fact when that plan's\n       * `kind` is `\"row\"`, `undefined` otherwise or when the caller has no\n       * way to know it. Only `finalizeEngineCapabilities` — the sole caller\n       * that resolves a root profile's write-fence plan — ever supplies\n       * this; every other caller omits it and so can never derive\n       * `\"optimistic-retry\"`.\n       */\n      fenceConflict?: \"wait\" | \"commit-time\" | undefined;\n    }>,\n): NonNullable<BackendExecutionCapabilities[\"unitOfWork\"]> {\n  if (execution.interactiveTransactions) {\n    return execution.fenceConflict === \"commit-time\" ?\n        \"optimistic-retry\"\n      : \"interactive\";\n  }\n  return execution.atomicBatch === \"none\" ? \"none\" : \"batch\";\n}\n\n/**\n * Removes exact atomic execution evidence at a backend derivation or session\n * boundary, and re-derives `unitOfWork` with it: a derived object with no\n * atomic batch is not a batch-tier backend, whatever its source was.\n *\n * Retry ownership under `\"optimistic-retry\"` is a root-backend fact: it\n * comes from the write-fence plan `createSqlBackend` resolves once for the\n * profile's own connection, not from anything this function computes fresh.\n * `withUnitOfWork` below carries it forward instead of rediscovering it: it\n * reads `capabilities.execution.unitOfWork` — the source's own, already\n * resolved answer — and passes `\"commit-time\"` through as `fenceConflict`\n * exactly when that source was `\"optimistic-retry\"`, so a derived object\n * built through this function keeps the tier for as long as\n * `interactiveTransactions` stays `true`, and falls back to `\"interactive\"`\n * only where the source never carried the tier to begin with.\n *\n * Derived/projection constructors and transaction factories share this owner\n * so a new backend construction seam cannot accidentally retain execution\n * authority earned by another exact object.\n */\nexport function downgradeAtomicBatch(\n  capabilities: BackendCapabilities,\n): BackendCapabilities {\n  return {\n    ...capabilities,\n    execution: withUnitOfWork({\n      ...capabilities.execution,\n      atomicBatch: \"none\",\n    }),\n  };\n}\n\nfunction withUnitOfWork(\n  execution: BackendExecutionCapabilities,\n): BackendExecutionCapabilities {\n  return {\n    ...execution,\n    unitOfWork: deriveUnitOfWork({\n      ...execution,\n      fenceConflict:\n        execution.unitOfWork === \"optimistic-retry\" ? \"commit-time\" : undefined,\n    }),\n  };\n}\n\n/**\n * Declares atomic authority for one already-open transaction session.\n *\n * Session authority is earned independently of the root verdict: a root may\n * be unable to own a multi-statement atomic boundary while its transaction\n * factory can still prove one pinned open session. The session must register\n * its own exact-resource transport and semantic profile; this declaration\n * alone never authorizes execution.\n *\n * Like `downgradeAtomicBatch` above, `withUnitOfWork` carries retry\n * ownership forward rather than re-resolving it: `\"optimistic-retry\"` is a\n * root-backend fact this session-scoped capabilities object has no way to\n * re-resolve for itself, but it reads the source's own `unitOfWork` for the\n * answer and keeps the tier for as long as `interactiveTransactions` stays\n * `true`.\n */\nexport function scopeAtomicBatchToSession(\n  capabilities: BackendCapabilities,\n  available: boolean,\n): BackendCapabilities {\n  return {\n    ...capabilities,\n    execution: withUnitOfWork({\n      ...capabilities.execution,\n      atomicBatch: available ? \"session\" : \"none\",\n    }),\n  };\n}\n","/**\n * Origin evidence for the schema-fenced INSERT fast path.\n *\n * The fused statements are not merely an optional structural convenience:\n * their PostgreSQL `FOR SHARE` and SQLite transaction-fence contract is owned\n * by the bundled factories. A custom backend can expose methods with the same\n * names, and an adopted transaction is bound to a caller-owned boundary, so\n * neither is eligible by inference. Factory-owned root backends and the\n * transaction handles those factories open carry this out-of-band evidence.\n */\nimport type { WriteFencePlan } from \"./write-fence\";\n\nconst ELIGIBLE_SCHEMA_FENCED_INSERT_BACKENDS = new WeakSet<object>();\n\n/**\n * Every caller that could mark a backend or transaction handle eligible goes\n * through {@link markSchemaFencedInsertEligibleUnderFence} instead of this\n * primitive directly, so eligibility can never be granted without a resolved\n * fence plan backing it.\n */\nfunction markSchemaFencedInsertEligible<T extends object>(target: T): T {\n  ELIGIBLE_SCHEMA_FENCED_INSERT_BACKENDS.add(target);\n  return target;\n}\n\n/**\n * Marks `target` schema-fenced-insert eligible only when `fencePlan` fences\n * concurrent writers with a mechanism the fused insert can actually compose\n * itself into — `kind !== \"unfenced\"` AND `kind !== \"row\"`. A `row` plan's\n * keyed exclusion is a full standalone statement against the fences relation\n * (`FenceStatements.acquireKeyed`, an `INSERT ... RETURNING`), not a bare\n * expression like `row`'s `lock` sibling supplies: there is no fragment to\n * embed inside the fused INSERT the way `FOR SHARE`/an advisory-lock\n * subquery embeds today. A `row` target's managed write therefore always\n * runs the portable two-statement path (`lockSchemaVersionForStoreWrite`,\n * the one place the fence-row acquisition actually happens for a write),\n * exactly like the no-spelling case this function already excluded.\n *\n * @internal Called only by bundled factories for their root/owned-tx handles.\n */\nexport function markSchemaFencedInsertEligibleUnderFence<T extends object>(\n  target: T,\n  fencePlan: WriteFencePlan,\n): T {\n  if (fencePlan.kind !== \"unfenced\" && fencePlan.kind !== \"row\") {\n    markSchemaFencedInsertEligible(target);\n  }\n  return target;\n}\n\n/** @internal `deriveBackend` carries origin evidence across wrappers/projections. */\nexport function carrySchemaFencedInsertEligibility(\n  derived: object,\n  base: object,\n): void {\n  if (ELIGIBLE_SCHEMA_FENCED_INSERT_BACKENDS.has(base)) {\n    ELIGIBLE_SCHEMA_FENCED_INSERT_BACKENDS.add(derived);\n  }\n}\n\n/** Whether this backend originated in a bundled root or factory-owned transaction. */\nexport function isSchemaFencedInsertEligible(target: object): boolean {\n  return ELIGIBLE_SCHEMA_FENCED_INSERT_BACKENDS.has(target);\n}\n","import { type Assert, type ContainsAll } from \"../utils/type-assert\";\nimport type { CLAIMS } from \"./capabilities/bundle-registry\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * Runtime allowlist for the portable GraphBackend port.\n *\n * Data only: the projection constructors that consume this allowlist live in\n * `derive-backend.ts`, the one seam that carries a backend's\n * serialized-resource audit.\n *\n * `satisfies` rejects misspelled/non-port keys. The coverage record below\n * rejects every newly added GraphBackend key until it is deliberately added\n * here, so a port expansion can neither leak through structural forwarding nor\n * silently disappear from a narrowed backend.\n *\n * @internal\n */\nexport const GRAPH_BACKEND_PROJECTION_KEYS = [\n  \"dialect\",\n  \"capabilities\",\n  \"tableNames\",\n  \"fulltextStrategy\",\n  \"vectorStrategy\",\n  \"fenceSql\",\n  \"insertNode\",\n  \"insertNodeIfAbsent\",\n  \"commands\",\n  \"insertNodeNoReturn\",\n  \"insertNodesBatch\",\n  \"insertNodesBatchReturning\",\n  \"updateNode\",\n  \"upsertHeterogeneousNodes\",\n  \"updateResolvedNodesBatch\",\n  \"compareAndSetNode\",\n  \"updateNodeSet\",\n  \"deleteNode\",\n  \"hardDeleteNode\",\n  \"getNode\",\n  \"getNodes\",\n  \"insertEdge\",\n  \"insertEdgeNoReturn\",\n  \"insertEdgesBatch\",\n  \"insertEdgesBatchReturning\",\n  \"insertEdgesDurableBatchReturning\",\n  \"updateEdge\",\n  \"deleteEdge\",\n  \"hardDeleteEdge\",\n  \"deleteEdgesBatch\",\n  \"hardDeleteEdgesBatch\",\n  \"getEdge\",\n  \"getEdges\",\n  \"countEdgesFrom\",\n  \"edgeExistsBetween\",\n  \"findEdgesConnectedTo\",\n  \"findNodesByKind\",\n  \"countNodesByKind\",\n  \"findEdgesByKind\",\n  \"findEdgesByEndpointSet\",\n  \"findEdgesByHeterogeneousEndpointSet\",\n  \"countEdgesByKind\",\n  \"adoptBaseSchema\",\n  \"assertBaseSchemaCurrent\",\n  \"insertUnique\",\n  \"insertUniqueBatch\",\n  \"deleteUnique\",\n  \"hardDeleteUniquesByNodeIds\",\n  \"hardDeleteUniquesByConcreteKind\",\n  \"checkUnique\",\n  \"checkUniqueBatch\",\n  \"claimEdgeCardinality\",\n  \"claimEdgeCardinalityGuarded\",\n  \"claimEdgeCardinalityBatch\",\n  \"purgeEdgeClaims\",\n  \"readConstraintFenceViolations\",\n  \"getActiveSchema\",\n  \"getSchemaVersion\",\n  \"registerGraphTemplate\",\n  \"instantiateGraphTemplate\",\n  \"commitSchemaVersion\",\n  \"commitSchemaVersionIfKindsEmpty\",\n  \"lockSchemaVersionForWrite\",\n  \"lockSchemaVersionAndGraphWrite\",\n  \"commitSchemaVersionWithPreflight\",\n  \"setActiveVersion\",\n  \"schemaWriteTransaction\",\n  \"upsertEmbedding\",\n  \"upsertEmbeddingBatch\",\n  \"deleteEmbedding\",\n  \"deleteEmbeddingBatch\",\n  \"vectorSearch\",\n  \"createVectorIndex\",\n  \"dropVectorIndex\",\n  \"hybridSearch\",\n  \"upsertFulltext\",\n  \"deleteFulltext\",\n  \"upsertFulltextBatch\",\n  \"deleteFulltextBatch\",\n  \"fulltextSearch\",\n  \"ensureIndexMaterializationsTable\",\n  \"ensureTrigramExtension\",\n  \"ensureRevisionOriginsTable\",\n  \"ensureEdgeMatchIdentityStorage\",\n  \"getIndexMaterialization\",\n  \"getIndexMaterializations\",\n  \"recordIndexMaterialization\",\n  \"claimIndexMaterialization\",\n  \"releaseIndexMaterializationClaim\",\n  \"ensureContributionMaterializationsTable\",\n  \"getContributionMaterialization\",\n  \"recordContributionMaterialization\",\n  \"assertRuntimeContributionsInitialized\",\n  \"ensureKindRemovalsTable\",\n  \"getPendingKindRemovals\",\n  \"getAllKindRemovals\",\n  \"recordKindRemoval\",\n  \"ensureReconciliationMarkersTable\",\n  \"ensureRuntimeContributions\",\n  \"ensureVectorSlotContribution\",\n  \"ensureVectorSlotContributions\",\n  \"assertVectorSlotInitialized\",\n  \"assertVectorSlotsInitialized\",\n  \"deleteVectorSlotContribution\",\n  \"verifyContributions\",\n  \"repairContributions\",\n  \"probeContributions\",\n  \"rebuildContribution\",\n  \"ensureFulltextTable\",\n  \"ensureIdentityTables\",\n  \"identityTableDdl\",\n  \"recordedTableDdl\",\n  \"getReconciliationMarker\",\n  \"setReconciliationMarker\",\n  \"insertNodeIfAbsentWithSchemaFence\",\n  \"insertNodeWithSchemaFence\",\n  \"clearGraph\",\n  \"bootstrapTables\",\n  \"refreshStatistics\",\n  \"trustedImport\",\n  \"execute\",\n  \"executeStatement\",\n  \"executeTemporaryStatement\",\n  \"executeRaw\",\n  \"compileSql\",\n  \"executeDdl\",\n  \"ensureExtension\",\n  \"catalog\",\n  \"lineage\",\n  \"recordedTime\",\n  \"transaction\",\n  \"close\",\n] as const satisfies readonly (keyof GraphBackend)[];\n\n/** @internal */\nexport type ProjectedGraphBackendKey =\n  (typeof GRAPH_BACKEND_PROJECTION_KEYS)[number];\n\nconst MISSING_GRAPH_BACKEND_PROJECTION_KEYS: Record<\n  Exclude<keyof GraphBackend, ProjectedGraphBackendKey>,\n  never\n> = {};\nvoid MISSING_GRAPH_BACKEND_PROJECTION_KEYS;\n\n// I13: the projection carries every `claims` core member, or a projected\n// backend could forward the declaration while silently dropping one of the\n// four members `claimSupport` binds.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _projectionContainsClaimsCore = Assert<\n  ContainsAll<\n    typeof GRAPH_BACKEND_PROJECTION_KEYS,\n    (typeof CLAIMS)[\"core\"][number]\n  >\n>;\n","/**\n * Ownership tracking for backends that serialize every statement onto ONE\n * database connection.\n *\n * Two facts are recorded here, and only these two:\n *\n * 1. **Which serialized resource a backend wrapper belongs to.** Distinct\n *    `GraphBackend` objects (a second `createPostgresBackend(...)` over the same\n *    client, a projection, an overlay, a managed-close wrapper) are not `===`,\n *    yet their statements land on the same connection. Marking a backend with\n *    the underlying client object — and inheriting that mark through every\n *    decorator — makes \"these two wrappers cannot run a read transaction and a\n *    write transaction at the same time\" answerable.\n *\n *    Only backends whose driver is known to be single-connection are marked;\n *    everything else is deliberately left unmarked, because a pooled connection\n *    hands out an independent connection per checkout and refusing concurrent\n *    work there would refuse legitimate work. The complete classification —\n *    marked, deliberately unmarked, and known gaps — is the inventory at the\n *    bottom of this doc.\n *\n * 2. **Which long-lived interchange stream currently holds that resource.** A\n *    streaming export holds a read-only transaction on its connection for the\n *    whole stream; a streaming import opens a write transaction per chunk on\n *    that same connection for the whole stream. Any second long-lived stream on\n *    the resource therefore either nests a transaction inside the first one\n *    (`cannot start a transaction within a transaction`) or waits for a\n *    connection that is never released — and that is true of ALL FOUR pairings,\n *    not only the two cross-kind ones:\n *\n *    | holder          | second stream    | outcome without the lease          |\n *    | --------------- | ---------------- | ---------------------------------- |\n *    | export snapshot | import stream    | import's chunk waits on the reader |\n *    | import stream   | export snapshot  | export's read strands the import   |\n *    | import stream   | import stream    | nested BEGIN                       |\n *    | export snapshot | export snapshot  | nested BEGIN                       |\n *\n *    So the lease is EXCLUSIVE, not refcounted: at most one stream of any kind\n *    holds a given serialized resource, and at most one holds a transactional\n *    SQLite backend object even when its resource is declared independent. The\n *    second stream is refused with the holder's kind named (see\n *    {@link acquireSerializedStreamLease}). Refcounting admitted the two\n *    same-kind rows above, which then failed on the driver after chunks had\n *    already committed.\n *\n *    `\"import-stream\"` is the kind of EVERY long-lived import, not only the\n *    chunk-streaming one: an in-memory `importGraph` and a `trustedImport`\n *    session write through the same one connection over the same kind of window,\n *    so they claim the same lease and are refused by the same holders.\n *\n * The check and the registration happen in ONE synchronous section inside\n * {@link acquireSerializedStreamLease} — there is no way for a caller to check\n * without claiming, so there is no window to get wrong. On a single-threaded\n * event loop a check with no `await` before its registration is atomic: two\n * long-lived streams cannot both observe a free resource, so no interleaving is\n * left where each waits for the other.\n *\n * Neither fact is a general concurrency model:\n *\n * - No attempt is made to detect shared connections we cannot see (two `pg`\n *   Clients dialed at the same server, two better-sqlite3 handles on one file).\n *   Those are genuinely independent connections and are correctly not refused.\n * - RESIDUAL GAP: the lease is keyed by serialized resource, so an UNMARKED\n *   backend registers nothing and can hold nothing. A driver we cannot\n *   positively identify as single-connection therefore keeps exactly today's\n *   protection — the identity-based pre-flight in `importGraphStream`, which\n *   only sees a stream that still names its own source backend — and an\n *   export/import pair interleaved on such a connection can still wedge. Closing\n *   that requires recognizing the driver, not more bookkeeping here.\n * - RESIDUAL GAP: an export without interactive transactions abstains entirely — it opens no\n *   snapshot transaction, so `exportGraphStream` neither claims the lease nor\n *   consults it: such an export is never refused and never refuses anyone.\n *   A streaming import claims the lease whatever its backend reports,\n *   because its writes still have to land somewhere an open snapshot is not.\n *   The visible cost of that asymmetry is one conservative refusal: two\n *   streaming imports through a MARKED but deliberately `transactionMode:\n *   \"none\"` connection frame nothing and would in fact interleave harmlessly,\n *   yet the second is refused. That is the deliberate trade — the alternative\n *   (gating the import's claim on `capabilities.execution.interactiveTransactions` too) would stop a\n *   real snapshot export from being refused mid-import on a mixed-profile\n *   connection, which is the far likelier pairing.\n * - RESIDUAL GAP: the lease's population is INTERCHANGE STREAMS. Ordinary\n *   long-lived frames on the same serialized connection — a `store.transaction`\n *   held across awaits by application code, `schemaWriteTransaction` (the\n *   provenance claim, the identity DDL fence), `store.evolve()` — neither hold\n *   nor consult it, so one of those opening while an export snapshot is live\n *   on the same connection blocks or wedges without a typed error, exactly as\n *   any two of them always have. Representing every long-lived frame here is a\n *   different, larger contract (a connection-wide frame lease); the streams\n *   are covered because they are the pairing users actually compose.\n *\n * ## Inventory of serialized resources\n *\n * Every `GraphBackend` in this package is built by `createSqliteBackend` or\n * `createPostgresBackend` (the batteries-included factories — local\n * better-sqlite3, libSQL, PGlite — and every decorator go through one of them).\n * Both resolve the verdict and hand it to `createSqlBackend`\n * (`drizzle/engine/create-sql-backend.ts`), which applies the mark once\n * before the backend object escapes — so that is the only place a mark is\n * applied, and this list is the whole population. Predicates are named\n * rather than line-cited so the inventory stays greppable as the files move.\n *\n * MARKED — the factory resolves the resource before the backend object exists,\n * so no wrapper can observe it unmarked:\n *\n * - better-sqlite3 `Database` (`prepare` + `pragma`) — `createSqliteBackend` via\n *   `getSerializedSqliteConnection`, which asks one named predicate per driver.\n * - bun:sqlite `Database` (`prepare` + `query` + `run`/`exec` + `serialize` +\n *   a `filename` string) — same site, via `isBunSqliteClient`. One synchronous\n *   connection, like better-sqlite3; `query` and `filename` are what separate\n *   it structurally from better-sqlite3 (`pragma`, `name`), so the mark never\n *   rests on a session's constructor name, which bundlers rename.\n * - sql.js `Database` (`prepare` + `exec` + `run` + `export` +\n *   `getRowsModified`) — same site, via `isSqlJsClient`. One in-WASM handle\n *   executed in-process; `export` and `getRowsModified` are sql.js's own API\n *   and exist on no other SQLite client.\n * - Local `@libsql/client` (`protocol === \"file\"`: `file:` paths, `:memory:`,\n *   an embedded replica's local file) — same site, via `isLocalLibsqlClient`.\n * - PGlite — `createPostgresBackend` via `getPgliteClient` (`query` +\n *   `dumpDataDir`).\n * - Bare `pg` / `@neondatabase/serverless` `Client`, including a checked-out\n *   `PoolClient` — same site, via `isBarePgClient`.\n * - `pg` / neon-serverless `Pool` capped at one connection — same site, via\n *   `isSingleConnectionPgPool`, which asks `isSingleConnectionPgPoolCap` what a\n *   cap of one looks like. pg-pool normalizes `max` (and the legacy `poolSize`)\n *   into `options` without coercing either, so `{ max: 1 }`, `{ max: \"1\" }` and\n *   `{ poolSize: \"1\" }` are one and the same one-connection pool, and all three\n *   are marked.\n * - postgres-js capped at one connection — same site, via\n *   `isSingleConnectionCallablePgClient`, which asks\n *   `isSingleConnectionPostgresJsCap`. The client is CALLABLE, so it needed a\n *   resolver arm of its own; `begin` reserves the sole connection, making an\n *   export snapshot hold the connection every other wrapper writes through.\n *   postgres-js resolves `max` from the options object, the URL query string and\n *   `PGMAX` and coerces none of them, so `{ max: 1 }`, `?max=1` and `PGMAX=1`\n *   are all marked. Requires postgres-js identity (`isPostgresJsClient`) as well\n *   as the cap: a cap on a callable we cannot attribute to a known driver is not\n *   evidence.\n * - Cloudflare Durable Object storage (`drizzle(ctx.storage)`) —\n *   `createSqliteBackend` via `getDurableObjectStorageClient`, the same\n *   full-shape evidence `transactionMode: \"do-sqlite\"` requires to run a\n *   transaction. The storage transaction frame is AMBIENT on the storage object\n *   (no tx handle exists on DO), so a second wrapper's writes land inside the\n *   first wrapper's export snapshot; nothing else abstains, since the DO backend\n *   reports `capabilities.execution.interactiveTransactions: true`.\n *\n * DELIBERATELY UNMARKED, by class — marking these would refuse work that\n * succeeds:\n *\n * - Pooled connections: a default-size `pg` / neon-serverless / `@vercel/postgres`\n *   pool, postgres-js or Bun `SQL` at default size. Each checkout is an\n *   independent connection.\n * - Session-less HTTP drivers: `neon-http`, Cloudflare D1, RDS Data API. Nothing\n *   is held between statements, and the two that report\n *   `capabilities.execution.interactiveTransactions: false` are additionally short-circuited by\n *   {@link snapshotExportContention} before marking is consulted.\n * - Remote `@libsql/client` (`http` / `ws`): an independent stream per\n *   transaction.\n * - Separate handles on one database (two `pg` Clients at one server, two\n *   better-sqlite3 handles on one file): genuinely concurrent connections.\n * - Transaction-scoped backends (`transaction()`, `adoptTransaction`): the\n *   caller's transaction already owns the connection and opens no second frame,\n *   and the guards run on the root backend a Store holds. Decorators over a root\n *   backend DO carry the verdict, via\n *   {@link carryBackendResourceAudit}.\n *\n * KNOWN GAPS — serialized in fact, unmarked, so they keep only the\n * identity-based pre-flight in `importGraphStream` (which a `history: true`\n * store's overlay already defeats). Each is a coverage extension needing\n * positive evidence of the client shape, never a silent no-op. Every one of\n * them has the SAME sanctioned workaround until its shape is recognized: the\n * caller declares the connection with\n * `{ serializedResource: { mode: \"shared\", resource: client } }` (see\n * {@link SerializedResourceDeclaration}), which is a claim the caller can make\n * and this package cannot.\n *\n * - React Native / Expo SQLite drivers — `expo-sqlite` and `op-sqlite`. One\n *   connection each, and both are genuinely serialized, but neither exposes a\n *   plain `prepare` (`prepareAsync` / `prepareSync`, `prepareStatement`), so\n *   none of the predicates above can see them and neither driver is installable\n *   here to derive the shape from rather than guess it. Remaining #434 scope:\n *   each needs its own positive shape, taken from the driver's own typings.\n * - `node:sqlite` `DatabaseSync`: UNREACHABLE through Drizzle today —\n *   drizzle-orm 0.45.2 ships `bun-sqlite`, `sql-js`, `durable-sqlite`,\n *   `expo-sqlite`, `op-sqlite`, `sqlite-proxy` and `better-sqlite3`, and no\n *   `node-sqlite` entrypoint, so no `createSqliteBackend` call can be handed\n *   one. Re-check when the Drizzle floor moves; nothing to mark until then.\n * - postgres-js given a NON-NUMERIC string cap other than one, e.g.\n *   `postgres(url + \"?max=5\")`: `[...Array(options.max)]` (postgres@3.4.9\n *   `src/index.js:65`) yields length 1 for any such string, so that client\n *   really does open exactly one connection today and really can wedge a stream\n *   pair. Unmarked on purpose — marking it would be marking on an upstream bug,\n *   and the day postgres-js coerces `max` the same configuration becomes a\n *   five-connection pool whose concurrent work we would then refuse. A caller on\n *   that shape materializes the export or imports into an independent backend,\n *   exactly as before this guard existed.\n * - Bun `SQL` (Postgres) built with `{ max: 1 }`: genuinely serialized, but\n *   nothing in this package positively identifies that driver — there is no\n *   Postgres equivalent of the SQLite driver shapes above — so `options.max`\n *   there cannot be attributed to a driver whose dispatch we know. Marking it\n *   needs a Bun-`SQL` discriminator first. Remaining #434 scope.\n * - Drivers we cannot identify at all (`sqlite-proxy`, `pg-proxy`, a bespoke\n *   adapter): whether the far side serializes is unknowable from here, so they\n *   fall under the residual gap above.\n */\nimport { ConfigurationError } from \"../errors\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * What we know about the connection a backend's statements land on.\n *\n * `independent` is a POSITIVE verdict — a factory looked and found statements\n * that can run on independent connections. It is not the same runtime state as\n * a backend nobody audited, which carries no record at all.\n */\nexport type BackendResourceAudit =\n  | Readonly<{ kind: \"serialized\"; resource: object }>\n  | Readonly<{\n      kind: \"independent\";\n      /** Stable key for the SQLite identity arm of an explicit declaration. */\n      identityLeaseResource?: object;\n    }>;\n\n/**\n * Declare the connection this backend serializes on, when TypeGraph cannot\n * detect it (Bun `SQL`, `expo-sqlite`, `op-sqlite`, `sqlite-proxy`, `pg-proxy`,\n * a postgres-js pool capped through a string the driver does not coerce — the\n * KNOWN GAPS in this module's inventory). Two wrappers that pass the same\n * object are treated as one serialized resource, exactly as two wrappers over a\n * detected client are.\n *\n * - `\"detect\"` (the default, and the same behavior as omitting the option):\n *   whatever the factory's driver predicates find, and nothing else.\n * - `\"shared\"`: the given object IS the serialized resource. Refused with a\n *   {@link ConfigurationError} when the factory detected a DIFFERENT resource —\n *   silently overriding would let two wrappers over one handle be given two\n *   different sentinels and quietly de-serialize a pair that really does share.\n * - `\"independent\"`: statements can run on independent connections. The\n *   documented escape hatch for a mis-detection, so a user surprised by a\n *   refusal is never stuck.\n *\n * SCOPE — read this before using `\"independent\"`: this option controls the\n * SHARED-RESOURCE arm of {@link snapshotExportContention} only. It cannot lift\n * the object-identity arm, under which ONE SQLite backend object exporting into\n * ITSELF is refused with `same-sqlite-backend`. That arm is a driver fact (one\n * handle, one open snapshot transaction), not a claim about connection\n * topology, so no declaration can make it false.\n *\n * That surviving arm is SQLITE-ONLY, deliberately: it is gated on\n * `dialect === \"sqlite\"`, so on Postgres a backend declared `\"independent\"`\n * exporting into ITSELF is not refused either — a Postgres client that hands\n * out independent connections is exactly what the declaration claims, and the\n * snapshot and the writes it contends with land on different ones.\n */\nexport type SerializedResourceDeclaration =\n  | Readonly<{ mode: \"detect\" }>\n  | Readonly<{ mode: \"shared\"; resource: object }>\n  | Readonly<{ mode: \"independent\" }>;\n\nconst BACKEND_RESOURCE_AUDITS = new WeakMap<object, BackendResourceAudit>();\n\n/**\n * The kinds of long-lived interchange stream that hold a serialized connection\n * across many statements — the population the lease is exclusive over.\n */\nexport type SerializedStreamKind = \"export-snapshot\" | \"import-stream\";\n\n/**\n * The outcome of claiming a serialized resource for a long-lived stream: the\n * (idempotent) release and the resource the claim was registered under when it\n * succeeded, or the kind of stream already holding it when it did not.\n *\n * `resource` is the decision itself rather than a flag a caller re-derives\n * from the backend: `undefined` means nothing was registered, because the\n * backend runs on no known serialized resource.\n */\nexport type SerializedStreamLease =\n  | Readonly<{\n      acquired: true;\n      resource: object | undefined;\n      release: () => void;\n    }>\n  | Readonly<{ acquired: false; heldBy: SerializedStreamKind }>;\n\n/**\n * The one long-lived stream holding each serialized resource. An entry exists\n * only while that stream is in flight; its release deletes the key, so a\n * finished stream retains nothing and refuses nobody.\n */\nconst ACTIVE_SERIALIZED_STREAMS = new Map<object, SerializedStreamKind>();\n\n/** Whether two audits are the same verdict about the same connection. */\nfunction auditsAgree(\n  left: BackendResourceAudit,\n  right: BackendResourceAudit,\n): boolean {\n  if (left.kind === \"serialized\") {\n    return right.kind === \"serialized\" && left.resource === right.resource;\n  }\n  return (\n    right.kind === \"independent\" &&\n    left.identityLeaseResource === right.identityLeaseResource\n  );\n}\n\n/** Names a verdict for the write-once refusal below. */\nfunction formatAudit(audit: BackendResourceAudit): string {\n  return audit.kind === \"serialized\" ? \"serialized\" : \"independent\";\n}\n\n/**\n * The two objects a refused `\"shared\"` declaration could not reconcile: the one\n * the caller named and the one this package detected.\n */\nexport type SerializedResourceConflict = Readonly<{\n  declared: object;\n  detected: object;\n}>;\n\n/**\n * The handles behind each refusal, held OFF the error object on purpose.\n *\n * `TypeGraphError.toLogString()` `JSON.stringify`s `details`, and the\n * documented handler pattern is `console.error(error.toLogString())` — so a\n * driver handle in `details` writes whatever that driver stores into the\n * caller's logs, and a `pg.Pool` stores its `connectionString`, password\n * included. The refusal therefore carries only a DESCRIPTION of each side\n * (`declaredKind` / `detectedKind`), while the identities live here, reachable\n * by asking for them and by nothing that walks an error's own properties.\n */\nconst SERIALIZED_RESOURCE_CONFLICTS = new WeakMap<\n  Error,\n  SerializedResourceConflict\n>();\n\n/**\n * The two objects a serialized-resource refusal could not reconcile, or\n * `undefined` for any other error.\n *\n * @internal\n */\nexport function serializedResourceConflict(\n  error: unknown,\n): SerializedResourceConflict | undefined {\n  return error instanceof ConfigurationError ?\n      SERIALIZED_RESOURCE_CONFLICTS.get(error)\n    : undefined;\n}\n\n/**\n * How a refusal names one side of a conflict without publishing the handle:\n * the constructor name (`\"Database\"`, `\"BoundPool\"`, `\"Object\"`), which says\n * what KIND of thing each side is and carries no connection string.\n */\nfunction describeSerializedResource(resource: object): string {\n  const constructorName = (\n    resource as Readonly<{ constructor?: Readonly<{ name?: unknown }> }>\n  ).constructor?.name;\n  return typeof constructorName === \"string\" && constructorName !== \"\" ?\n      constructorName\n    : \"Object\";\n}\n\n/**\n * The verdict a backend factory records, from what its driver predicates\n * detected and what the caller declared.\n *\n * The single owner of \"what a {@link SerializedResourceDeclaration} means\":\n * both drizzle factories call it, so the two cannot drift about whether a\n * declaration wins, loses, or is refused.\n *\n * Applied or refused, never ignored:\n *\n * - `\"shared\"` naming the resource detection already found, or naming one on a\n *   backend detection could not classify → recorded as that resource.\n * - `\"shared\"` naming a DIFFERENT resource than detection found → refused, so\n *   two wrappers over one handle cannot be handed two different sentinels and\n *   silently de-serialized.\n * - `\"independent\"` → recorded, whatever detection found. This is the escape\n *   hatch, not a conflict: detection is a duck-type over driver internals and\n *   the caller knows their topology.\n * - `\"detect\"` or absent → exactly what detection found.\n *\n * Called INSIDE the factory body before the backend object exists, so a\n * refusal happens before any object is published (CTA-3) and a caller can never\n * hold a backend whose declaration was rejected.\n *\n * @throws {ConfigurationError} `details.reason: \"serialized-resource-conflict\"`\n * when a `\"shared\"` declaration names a resource detection disagrees with. Its\n * `details` describe the two sides (`declaredKind` / `detectedKind`) rather\n * than carrying them, because `details` is logged verbatim; the handles\n * themselves come from {@link serializedResourceConflict}.\n * @internal\n */\nexport function resolveDeclaredBackendResource(\n  detected: object | undefined,\n  declaration: SerializedResourceDeclaration | undefined,\n): BackendResourceAudit {\n  switch (declaration?.mode) {\n    case \"shared\": {\n      if (detected !== undefined && detected !== declaration.resource) {\n        const refusal = new ConfigurationError(\n          `serializedResource declared { mode: \"shared\" } naming an object ` +\n            `that is not the connection this backend was detected to run on. ` +\n            `Two wrappers over one connection must name the SAME object, or ` +\n            `the guards that refuse a concurrent export/import pair on it stop ` +\n            `seeing them as one resource.`,\n          {\n            reason: \"serialized-resource-conflict\",\n            declaredKind: describeSerializedResource(declaration.resource),\n            detectedKind: describeSerializedResource(detected),\n          },\n          {\n            suggestion:\n              `Declare the client TypeGraph already detected (or drop the ` +\n              `declaration and let detection stand). Use ` +\n              `{ mode: \"independent\" } if the detection is wrong and this ` +\n              `backend really does run on its own connection.`,\n          },\n        );\n        SERIALIZED_RESOURCE_CONFLICTS.set(refusal, {\n          declared: declaration.resource,\n          detected,\n        });\n        throw refusal;\n      }\n      return { kind: \"serialized\", resource: declaration.resource };\n    }\n    case \"independent\": {\n      return { kind: \"independent\", identityLeaseResource: {} };\n    }\n    case \"detect\":\n    case undefined: {\n      return detected === undefined ?\n          { kind: \"independent\" }\n        : { kind: \"serialized\", resource: detected };\n    }\n  }\n}\n\n/**\n * Records what a backend factory found about the connection its backend runs\n * on.\n *\n * INVARIANT: recorded ONCE per backend, by the factory that built it, BEFORE\n * the backend object escapes the factory body. Derived backends (deriveBackend,\n * projectBackend, projectBackendWithout, projectGraphBackend,\n * wrapWithManagedClose) carry the verdict at construction time, so a wrapper\n * built before the audit lands is silently unaudited and evades the\n * import/clone guards.\n *\n * A second call with an equal verdict is a no-op. A second call with a\n * DIFFERENT verdict throws: the stream lease reads this value and closes over\n * the resource it claimed, so a verdict that changes under a live lease\n * de-serializes a pair that really does share a connection.\n *\n * The throw is an INTERNAL invariant assertion — no library path re-audits and\n * a user cannot reach this function — so it is a plain `TypeError` naming both\n * verdicts, matching the repo's internal-assertion spelling (`requireDefined`,\n * src/utils/presence.ts). Deliberately not a `ConfigurationError`: that type is\n * user-category and would route a library bug into user-facing handling.\n *\n * @internal\n */\nexport function auditBackendResource(\n  backend: GraphBackend,\n  audit: BackendResourceAudit,\n): void {\n  const recorded = BACKEND_RESOURCE_AUDITS.get(backend);\n  if (recorded !== undefined) {\n    if (auditsAgree(recorded, audit)) return;\n    throw new TypeError(\n      `A backend's serialized-resource audit is written once: this backend ` +\n        `was audited \"${formatAudit(recorded)}\" and a conflicting audit ` +\n        `\"${formatAudit(audit)}\"${\n          recorded.kind === \"serialized\" && audit.kind === \"serialized\" ?\n            \" naming a different connection\"\n          : \"\"\n        } was attempted. The stream lease closes over the resource it claimed, ` +\n        `so a verdict that changes under a live lease de-serializes a pair ` +\n        `that really does share a connection.`,\n    );\n  }\n  BACKEND_RESOURCE_AUDITS.set(backend, audit);\n}\n\n/**\n * Copies a base backend's verdict onto a backend derived from it, or nothing\n * when the base carries none.\n *\n * @internal The construction seam's carry. `src/backend/derive-backend.ts` is\n * the only module allowed to import it.\n */\nexport function carryBackendResourceAudit(derived: object, base: object): void {\n  const audit = BACKEND_RESOURCE_AUDITS.get(base);\n  if (audit !== undefined) BACKEND_RESOURCE_AUDITS.set(derived, audit);\n}\n\n/**\n * The verdict recorded for `backend`, or `undefined` when nobody audited it.\n *\n * A pure map read: the value is written once at construction, so two reads can\n * never disagree and a lease cannot have its premise changed under it.\n *\n * @internal\n */\nexport function resolveBackendAudit(\n  backend: object,\n): BackendResourceAudit | undefined {\n  return BACKEND_RESOURCE_AUDITS.get(backend);\n}\n\n/**\n * How a backend's connection was classified, as a single value.\n *\n * `\"unaudited\"` is NOT a verdict about the connection: it says nobody looked.\n * Two populations are legitimately unaudited and always will be —\n * transaction-scoped backends (`transaction()`, `adoptTransaction`), which are\n * built from an operations fragment rather than derived from a root backend,\n * and `GraphBackend`s users implement themselves. So `\"unaudited\"` on an\n * arbitrary object proves nothing; on a backend one of this package's factories\n * built, or on one derived from such a backend through `derive-backend.ts`, it\n * proves the construction bypassed the seam.\n */\nexport type BackendResourceProvenance =\n  \"serialized\" | \"independent\" | \"unaudited\";\n\n/**\n * The classification of `backend`'s connection — the decision itself rather\n * than a flag every caller re-derives from {@link resolveBackendAudit}.\n *\n * @internal\n */\nexport function backendResourceProvenance(\n  backend: object,\n): BackendResourceProvenance {\n  return resolveBackendAudit(backend)?.kind ?? \"unaudited\";\n}\n\n/** Whether two backend wrappers cannot make snapshot reads and writes concurrently. */\nexport function sharesSerializedTransactionResource(\n  left: GraphBackend,\n  right: GraphBackend,\n): boolean {\n  const leftAudit = resolveBackendAudit(left);\n  if (leftAudit?.kind !== \"serialized\") return false;\n  const rightAudit = resolveBackendAudit(right);\n  // Resource identity, not audit-record identity: two audits naming the same\n  // client object are the same connection however they were recorded.\n  return (\n    rightAudit?.kind === \"serialized\" &&\n    leftAudit.resource === rightAudit.resource\n  );\n}\n\n/** How a snapshot export on one backend contends with a write on another. */\nexport type SnapshotExportContention =\n  \"same-sqlite-backend\" | \"shared-resource\";\n\n/**\n * Whether a snapshot export on `source` would hold the one connection `target`\n * writes through, and via which detector. `undefined` means no contention.\n *\n * The single owner of \"a snapshot export blocks this write\": the streaming\n * import guard, and the working-copy cloner that exists to pre-empt it, both\n * ask here rather than re-deriving the arms.\n *\n * - A source without interactive transactions (SQLite `transactionMode: \"none\"`, HTTP-only\n *   Postgres drivers) exports statement by statement with nothing held open, so\n *   sharing its connection is merely interleaving and is never contention.\n * - Object identity on a SQLite backend is checked FIRST, so a marked\n *   better-sqlite3 backend exporting into itself reports the more specific\n *   detector even though the shared-resource arm would also match.\n */\nexport function snapshotExportContention(\n  source: GraphBackend,\n  target: GraphBackend,\n): SnapshotExportContention | undefined {\n  if (!source.capabilities.execution.interactiveTransactions) return undefined;\n  if (source === target && source.dialect === \"sqlite\") {\n    return \"same-sqlite-backend\";\n  }\n  if (sharesSerializedTransactionResource(source, target)) {\n    return \"shared-resource\";\n  }\n  return undefined;\n}\n\n/**\n * Claims the serialized resource `backend` runs on for a long-lived stream of\n * `kind`, or reports which kind of stream already holds it.\n *\n * EXCLUSIVE: one stream per serialized resource, whatever its kind. Two exports\n * nest their snapshot transactions on the one connection exactly as an export\n * and an import do, so \"is a stream already running here\" — not \"is a stream of\n * the OTHER kind already running here\" — is the question the holder registry\n * answers.\n *\n * ONE SYNCHRONOUS SECTION, by construction: the lookup and the registration are\n * in this function's body with no `await` between them, and there is no separate\n * \"is it free?\" query a caller could read and then act on later. On a\n * single-threaded event loop that makes \"no other stream held this connection\n * when this one claimed it\" true for the whole stream, in whichever order two\n * streams start — the second one always finds the first's registration.\n *\n * A known serialized resource is the normal lease key. A transactional SQLite\n * backend audited `independent` instead uses its own identity: the declaration\n * can separate distinct wrappers, but cannot make two streams on ONE backend\n * object use different handles. An unaudited backend, and an independent\n * Postgres backend, registers nothing (see the residual gap in the module doc).\n *\n * The acquired arm reports the resource it registered under, so a caller reads\n * the decision instead of re-deriving it from the backend; `undefined` is the\n * no-op arm. The returned release is idempotent and deletes only its own\n * registration, so an already-released stream can never evict the next\n * stream's lease.\n */\nfunction streamLeaseResource(backend: GraphBackend): object | undefined {\n  const audit = resolveBackendAudit(backend);\n  if (audit?.kind === \"serialized\") return audit.resource;\n  if (\n    audit?.kind === \"independent\" &&\n    audit.identityLeaseResource !== undefined &&\n    backend.dialect === \"sqlite\" &&\n    backend.capabilities.execution.interactiveTransactions\n  ) {\n    return audit.identityLeaseResource;\n  }\n  return undefined;\n}\n\nexport function acquireSerializedStreamLease(\n  backend: GraphBackend,\n  kind: SerializedStreamKind,\n): SerializedStreamLease {\n  const resource = streamLeaseResource(backend);\n  if (resource === undefined) {\n    return {\n      acquired: true,\n      resource: undefined,\n      release: () => {\n        // Nothing was registered: this backend has no known serialized\n        // resource, so there is nothing to give back.\n      },\n    };\n  }\n  const holder = ACTIVE_SERIALIZED_STREAMS.get(resource);\n  if (holder !== undefined) return { acquired: false, heldBy: holder };\n  ACTIVE_SERIALIZED_STREAMS.set(resource, kind);\n  let released = false;\n  return {\n    acquired: true,\n    resource,\n    release: () => {\n      if (released) return;\n      released = true;\n      ACTIVE_SERIALIZED_STREAMS.delete(resource);\n    },\n  };\n}\n","/**\n * The one construction seam for derived backends.\n *\n * Every backend the library builds FROM another backend — an overlay, an\n * allowlist projection, a narrowing-by-omission, a managed-close wrapper — is\n * built here, and every constructor in this module carries the source's\n * serialized-resource audit, its first-party-factory write-fence mark, and\n * its schema-fenced-insert origin evidence onto the object it returns. Raw\n * `{ ...backend }`, `Object.assign` and rest-omission construction build a\n * NEW object none of those proofs follow, which\n * is the defect this module exists to make unreachable: a derived backend\n * that lost its resource-audit mark reads as unowned, and the import/clone\n * guards then let a read-and-write-through-one-connection stream proceed into\n * a deadlock; one that lost its write-fence mark would resolve\n * `resolveWriteFencePlan`'s dialect-derivation arm at one call site and\n * `unfenced` at another for the same underlying backend.\n *\n * This is the only module that imports {@link carryBackendResourceAudit},\n * {@link carryFirstPartyFactoryMark}, {@link carrySchemaFencedInsertEligibility},\n * and {@link carrySerializationFailureClassifier}.\n *\n * Naming convention this module's ratchet depends on: an identifier ending in\n * `Backend` denotes a whole backend object; a members fragment is named\n * `*Members`.\n */\nimport { carrySerializationFailureClassifier } from \"../utils/sql-errors\";\nimport { downgradeAtomicBatch } from \"./capabilities/execution\";\nimport { carrySchemaFencedInsertEligibility } from \"./capabilities/schema-fenced-insert\";\nimport { carryFirstPartyFactoryMark } from \"./capabilities/write-fence\";\nimport { carryGraphCommandPortSessionMetadata } from \"./command-contract\";\nimport {\n  GRAPH_BACKEND_PROJECTION_KEYS,\n  type ProjectedGraphBackendKey,\n} from \"./graph-backend-keys\";\nimport { carryBackendResourceAudit } from \"./transaction-resource\";\nimport {\n  type AdapterBackend,\n  type BackendCapabilities,\n  type GraphBackend,\n  type GraphCommandPort,\n  type TransactionBackend,\n} from \"./types\";\n\nconst BACKEND_DERIVATION_SOURCES = new WeakMap<object, object>();\n\nfunction recordBackendDerivation(derived: object, source: object): void {\n  BACKEND_DERIVATION_SOURCES.set(derived, source);\n}\n\n/** Returns whether `candidate` was built from `source` through this seam. */\nexport function isBackendDerivedFrom(\n  candidate: object,\n  source: object,\n): boolean {\n  const visited = new Set<object>();\n  let current: object | undefined = candidate;\n  while (current !== undefined && !visited.has(current)) {\n    if (current === source) return candidate !== source;\n    visited.add(current);\n    current = BACKEND_DERIVATION_SOURCES.get(current);\n  }\n  return false;\n}\n\n/** Returns the original backend at the root of a `deriveBackend` chain. */\nexport function backendDerivationRoot(backend: object): object {\n  const visited = new Set<object>();\n  let current = backend;\n  while (!visited.has(current)) {\n    visited.add(current);\n    const source = BACKEND_DERIVATION_SOURCES.get(current);\n    if (source === undefined) return current;\n    current = source;\n  }\n  return current;\n}\n\n/**\n * Rejects overlay members that are not members of the decorated backend, so a\n * misspelled override cannot silently add a property nothing forwards to.\n *\n * Public so custom backend wrappers can use the same audited decoration seam\n * whose lineage the conformance runners verify.\n */\nexport type ExactBackendOverlay<T extends object, O extends Partial<T>> = O &\n  Readonly<Record<Exclude<keyof O, keyof T>, never>>;\n\nfunction isGraphCommandPort(value: unknown): value is GraphCommandPort {\n  if (typeof value !== \"object\" || value === null) return false;\n  const candidate = value as Readonly<Record<string, unknown>>;\n  return (\n    (candidate[\"session\"] === \"root\" ||\n      candidate[\"session\"] === \"transaction\") &&\n    typeof candidate[\"execute\"] === \"function\"\n  );\n}\n\nfunction resolveDerivedCapabilities(\n  capabilities: unknown,\n  preserveAtomicSession: boolean,\n): unknown {\n  if (typeof capabilities !== \"object\" || capabilities === null) return;\n  const capabilityMembers = capabilities as Readonly<\n    Record<PropertyKey, unknown>\n  >;\n  const execution = capabilityMembers[\"execution\"];\n  if (typeof execution !== \"object\" || execution === null) return;\n  const executionMembers = execution as Readonly<Record<PropertyKey, unknown>>;\n  if (!(\"atomicBatch\" in executionMembers)) return;\n  const typed = capabilityMembers as BackendCapabilities;\n  return preserveAtomicSession && typed.execution.atomicBatch === \"session\" ?\n      typed\n    : downgradeAtomicBatch(typed);\n}\n\nfunction deriveExecutionCapabilities(\n  base: object,\n  overrides: object,\n  preserveAtomicSession: boolean,\n): unknown {\n  const overridesCapabilities = Object.hasOwn(overrides, \"capabilities\");\n  const capabilities =\n    overridesCapabilities ?\n      (Reflect.get(overrides, \"capabilities\", overrides) as unknown)\n    : (Reflect.get(base, \"capabilities\", base) as unknown);\n  return resolveDerivedCapabilities(\n    capabilities,\n    preserveAtomicSession && !overridesCapabilities,\n  );\n}\n\n/**\n * A same-session command-port wrapper preserves the underlying transaction's\n * coordination and isolation evidence. A root-to-transaction override is a\n * deliberate session boundary (recorded capture opens that transaction), so\n * it starts with fresh evidence that the transaction factory must bind.\n */\nfunction carryDerivedCommandPortMetadata(\n  base: object,\n  overrides: object,\n): void {\n  if (!Object.hasOwn(overrides, \"commands\")) return;\n  const baseCommands: unknown = Reflect.get(base, \"commands\");\n  const overrideCommands: unknown = Reflect.get(overrides, \"commands\");\n  if (\n    isGraphCommandPort(baseCommands) &&\n    isGraphCommandPort(overrideCommands) &&\n    baseCommands.session === overrideCommands.session\n  ) {\n    carryGraphCommandPortSessionMetadata(baseCommands, overrideCommands);\n  }\n}\n\n/**\n * Decorates a backend with overlay members without copying it.\n *\n * This is a decoration primitive: every non-overridden target property remains\n * reachable. Never use it to narrow a capability surface; construct an\n * explicit allowlist projection first, then decorate that projection.\n *\n * Backend wrappers use this instead of object spread so proxy backends keep\n * getters and non-enumerable members, and so the derived object carries the\n * source's serialized-resource audit. GraphBackend functions are receiver-free\n * by contract, so delegated methods are returned unchanged.\n *\n * `T` is bounded by `object`, not by the backend union — the same bound\n * {@link projectBackend} carries — so a PROJECTION is decorable too: the write\n * pipeline's read-only row-work target is what a batch's pending-aware\n * validation overlays. `ExactBackendOverlay` still rejects any key `T` does not\n * declare, so the looser bound cannot smuggle a member onto a surface that\n * withholds it.\n */\nfunction deriveBackendInternal<\n  T extends object,\n  const O extends Partial<T> = Partial<T>,\n>(\n  base: T,\n  overrides: ExactBackendOverlay<T, O>,\n  preserveAtomicSession: boolean,\n): T {\n  const derivedCapabilities = deriveExecutionCapabilities(\n    base,\n    overrides,\n    preserveAtomicSession,\n  );\n  // A Proxy may not report a different value for a non-writable,\n  // non-configurable data property on its target. Bundled backends are often\n  // frozen at public boundaries, so proxying `base` directly makes a valid\n  // overlay throw before it can forward anything. The extensible shell owns\n  // no backend members; every operation below still delegates to `base` or\n  // `overrides`, preserving getters and the no-copy decoration contract.\n  const decorationShell = Object.create(Reflect.getPrototypeOf(base)) as T;\n\n  function hasOverlayProperty(property: PropertyKey): boolean {\n    return Object.hasOwn(overrides, property);\n  }\n\n  const decoratedBackend = new Proxy(decorationShell, {\n    get(_targetObject, property) {\n      if (property === \"capabilities\" && derivedCapabilities !== undefined) {\n        return derivedCapabilities;\n      }\n      if (hasOverlayProperty(property)) {\n        return Reflect.get(overrides, property, overrides);\n      }\n      return Reflect.get(base, property, base);\n    },\n\n    has(_targetObject, property) {\n      return hasOverlayProperty(property) || Reflect.has(base, property);\n    },\n\n    ownKeys() {\n      return [\n        ...new Set([...Reflect.ownKeys(base), ...Reflect.ownKeys(overrides)]),\n      ];\n    },\n\n    getOwnPropertyDescriptor(_targetObject, property) {\n      if (property === \"capabilities\" && derivedCapabilities !== undefined) {\n        const source = hasOverlayProperty(property) ? overrides : base;\n        const descriptor = Reflect.getOwnPropertyDescriptor(source, property);\n        return descriptor === undefined ? undefined : (\n            {\n              configurable: true,\n              enumerable: descriptor.enumerable ?? false,\n              value: derivedCapabilities,\n              writable: \"writable\" in descriptor ? descriptor.writable : false,\n            }\n          );\n      }\n      if (hasOverlayProperty(property)) {\n        const descriptor = Reflect.getOwnPropertyDescriptor(\n          overrides,\n          property,\n        );\n        if (descriptor === undefined) return;\n        return { ...descriptor, configurable: true };\n      }\n      const descriptor = Reflect.getOwnPropertyDescriptor(base, property);\n      return descriptor === undefined ? undefined : (\n          { ...descriptor, configurable: true }\n        );\n    },\n\n    set(_targetObject, property, value) {\n      if (hasOverlayProperty(property)) {\n        return Reflect.set(overrides, property, value, overrides);\n      }\n      return Reflect.set(base, property, value, base);\n    },\n\n    defineProperty(_targetObject, property, attributes) {\n      if (hasOverlayProperty(property)) {\n        return Reflect.defineProperty(overrides, property, attributes);\n      }\n      return Reflect.defineProperty(base, property, attributes);\n    },\n\n    deleteProperty(_targetObject, property) {\n      if (hasOverlayProperty(property)) {\n        return Reflect.deleteProperty(overrides, property);\n      }\n      return Reflect.deleteProperty(base, property);\n    },\n  });\n  carryBackendResourceAudit(decoratedBackend, base);\n  carryFirstPartyFactoryMark(decoratedBackend, base);\n  carrySchemaFencedInsertEligibility(decoratedBackend, base);\n  carrySerializationFailureClassifier(decoratedBackend, base);\n  carryDerivedCommandPortMetadata(base, overrides);\n  recordBackendDerivation(decoratedBackend, base);\n  return decoratedBackend;\n}\n\nexport function deriveBackend<\n  T extends object,\n  const O extends Partial<T> = Partial<T>,\n>(base: T, overrides: ExactBackendOverlay<T, O>): T {\n  return deriveBackendInternal(base, overrides, false);\n}\n\n/**\n * Decorates one already-open transaction without discarding its session\n * declaration. The caller must separately bind exact transport and semantic\n * registrations to the returned object before exposing it to Store code. A\n * capabilities override still downgrades the declaration: this seam preserves\n * evidence from the base session; it never accepts replacement evidence.\n *\n * @internal\n */\nexport function deriveTransactionSessionBackend<\n  T extends TransactionBackend,\n  const O extends Partial<T> = Partial<T>,\n>(base: T, overrides: ExactBackendOverlay<T, O>): T {\n  return deriveBackendInternal(base, overrides, true);\n}\n\n/** Public name for the audited, decoration-only backend derivation seam. */\nexport function decorateBackend<\n  T extends object,\n  const O extends Partial<T> = Partial<T>,\n>(base: T, overrides: ExactBackendOverlay<T, O>): T {\n  return deriveBackend(base, overrides);\n}\n\n/**\n * Copies exactly `keys` off `base` into a fresh object.\n *\n * Generic over the SOURCE's own type, so a structurally wider input keeps the\n * declared types of the members it does provide. Keys the source does not\n * carry stay absent rather than becoming `undefined` members.\n *\n * @internal\n */\nexport function projectBackend<\n  TBackend extends object,\n  const TKey extends keyof TBackend,\n>(base: TBackend, keys: readonly TKey[]): Readonly<Pick<TBackend, TKey>> {\n  const entries = keys.flatMap((key) => {\n    if (!Reflect.has(base, key)) return [];\n    const value = Reflect.get(base, key) as unknown;\n    const projectedValue =\n      key === \"capabilities\" ?\n        (resolveDerivedCapabilities(value, false) ?? value)\n      : value;\n    return [[key, projectedValue] as const];\n  });\n\n  // Keys are constrained to TBackend and values are copied from that same\n  // object without reshaping. Optional members remain absent.\n  const projection = Object.fromEntries(entries) as Readonly<\n    Pick<TBackend, TKey>\n  >;\n  // A projection forwards every statement to the SAME connection as its source,\n  // so it owns the same serialized transaction resource. Carrying here rather\n  // than at each call site keeps the verdict attached through the projections\n  // built deep inside the store (recorded-time capture, hooked query backends),\n  // where an import guard would otherwise see an unaudited backend and let a\n  // read-and-write-through-one-connection stream proceed into a deadlock.\n  carryBackendResourceAudit(projection, base);\n  carryFirstPartyFactoryMark(projection, base);\n  carrySchemaFencedInsertEligibility(projection, base);\n  carrySerializationFailureClassifier(projection, base);\n  recordBackendDerivation(projection, base);\n  return projection;\n}\n\n/**\n * Every key a derived backend must retain: the source's own keys — enumerable\n * or not, string or symbol — plus every key on its prototype chain up to, but\n * not including, `Object.prototype`.\n *\n * A class-implemented GraphBackend is a supported shape and keeps its methods\n * on the prototype, so `Reflect.ownKeys` alone would silently drop them.\n */\nfunction backendKeys<TBackend extends object>(\n  base: TBackend,\n): readonly (keyof TBackend)[] {\n  const keys = new Set<PropertyKey>();\n  let current: object | undefined = base;\n  while (current !== undefined && current !== Object.prototype) {\n    for (const key of Reflect.ownKeys(current)) keys.add(key);\n    current = Reflect.getPrototypeOf(current) ?? undefined;\n  }\n  // Every key was enumerated off `base` itself, so each one is a key of\n  // TBackend at runtime; the compiler cannot narrow `PropertyKey` against an\n  // unresolved type parameter.\n  return [...keys] as unknown as readonly (keyof TBackend)[];\n}\n\n/**\n * Narrows a backend by omission — the seam replacement for\n * `const { omitted, ...rest } = backend`.\n *\n * Omits from the SOURCE's keys, so a structurally wider input (an\n * `AdapterBackend` with `transactionWithNative` / `adoptTransaction`) keeps\n * every member it had except the named ones.\n *\n * KEY RULE, deliberately NOT the rest destructure's rule: the retained set is\n * every own key (enumerable or not, string or symbol) PLUS every key on the\n * prototype chain up to — not including — `Object.prototype`, minus `omitted`.\n * A rest destructure copies only own ENUMERABLE keys and drops prototype\n * members; the declared `Omit<TBackend, TKey>` promises they survive, and\n * enumerating the prototype chain is what makes that promise true. Retaining\n * non-enumerable own keys is the other deliberate difference: a member hidden\n * behind a non-enumerable descriptor is still a member the wrapper forwards.\n *\n * @internal\n */\nexport function projectBackendWithout<\n  TBackend extends object,\n  const TKey extends keyof TBackend,\n>(base: TBackend, omitted: readonly TKey[]): Omit<TBackend, TKey> {\n  const excluded = new Set<PropertyKey>(omitted);\n  const retained = backendKeys(base).filter((key) => !excluded.has(key));\n  return projectBackend(base, retained);\n}\n\n/**\n * Creates a runtime GraphBackend projection.\n *\n * Structurally wider inputs (for example AdapterBackend) lose every property\n * not named by the portable GraphBackend allowlist. Optional port members stay\n * absent when the source does not provide them.\n *\n * @internal\n */\nexport function projectGraphBackend(base: GraphBackend): GraphBackend {\n  return projectBackend<GraphBackend, ProjectedGraphBackendKey>(\n    base,\n    GRAPH_BACKEND_PROJECTION_KEYS,\n  );\n}\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose<TNativeTransaction>(\n  backend: AdapterBackend<TNativeTransaction>,\n  teardown: () => void | Promise<void>,\n): AdapterBackend<TNativeTransaction>;\nexport function wrapWithManagedClose(\n  backend: GraphBackend,\n  teardown: () => void | Promise<void>,\n): GraphBackend;\nexport function wrapWithManagedClose(\n  backend: GraphBackend,\n  teardown: () => void | Promise<void>,\n): GraphBackend {\n  let backendClosed = false;\n  let teardownComplete = false;\n  let closeInFlight: Promise<void> | undefined;\n\n  async function closeManagedResources(): Promise<void> {\n    const errors: unknown[] = [];\n    if (!backendClosed) {\n      try {\n        await backend.close();\n        backendClosed = true;\n      } catch (error) {\n        errors.push(error);\n      }\n    }\n    if (!teardownComplete) {\n      try {\n        await teardown();\n        teardownComplete = true;\n      } catch (error) {\n        errors.push(error);\n      }\n    }\n\n    if (errors.length === 1) throw errors[0];\n    if (errors.length > 1) {\n      throw new AggregateError(\n        errors,\n        \"The backend and its managed resource both failed to close.\",\n      );\n    }\n  }\n\n  const closeOverlay: Pick<GraphBackend, \"close\"> = {\n    async close(): Promise<void> {\n      if (backendClosed && teardownComplete) return;\n      closeInFlight ??= closeManagedResources().finally(() => {\n        closeInFlight = undefined;\n      });\n      await closeInFlight;\n    },\n  };\n  return deriveBackend(backend, closeOverlay);\n}\n"]}