@dbsp/core 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/model-ir.ts","../src/intent-ast.ts","../src/model-impl.ts","../src/dx/logger.ts","../src/dx/symbols.ts","../src/dx/table-ref.ts","../src/dx/table-ref-factory.ts","../src/dx/schema.ts","../src/conventions.ts","../src/planner.ts","../src/dx/errors.ts","../src/transition/applier.ts","../src/transition/context-match.ts","../src/transition/context-compat.ts","../src/transition/execution-contract.ts","../src/transition/ids.ts","../src/transition/plan-digest.ts","../src/transition/validation.ts","../src/transition/registry.ts","../src/transition/resource-scope.ts","../src/transition/resume.ts","../src/transition/run-metadata.ts","../src/transition/check-delta.ts","../src/transition/enum-delta.ts","../src/transition/index-delta.ts","../src/transition/comparator.ts","../src/transition/evidence-match.ts","../src/transition/evidence-access.ts","../src/transition/prover.ts","../src/transition/composer.ts","../src/transition/staging.ts","../src/transition/staged-orchestrator.ts","../src/adapter.ts","../src/dx/batch-values.ts","../src/dx/column-utils.ts","../src/dx/window-functions.ts","../src/dx/filters.ts","../src/dx/expressions.ts","../src/dx/case-when-builder.ts","../src/dx/builder-utils.ts","../src/dx/cte-builder.ts","../src/dx/feature-checkers.ts","../src/dx/full-text-search.ts","../src/dx/hook-utils.ts","../src/dx/hooks.ts","../src/dx/include-hints.ts","../src/dx/subquery-builder.ts","../src/dx/object-filter.ts","../src/dx/types.ts","../src/dx/intent-builder.ts","../src/dx/lightweight-model.ts","../src/dx/mutation-builders.ts","../src/dx/negotiate-features.ts","../src/dx/nql.ts","../src/dx/hydration-utils.ts","../src/dx/orm-instance.ts","../src/dx/hierarchy-helpers.ts","../src/dx/exists-intent.ts","../src/dx/pagination-impl.ts","../src/dx/result-hydrator.ts","../src/dx/relation-paths.ts","../src/dx/set-operation-builder.ts","../src/dx/stream-impl.ts","../src/dx/query-builder.ts","../src/dx/raw-cte-builder.ts","../src/dx/orm.ts","../src/dx/range.ts","../src/dialects/index.ts","../src/sql-utils.ts","../src/assert/assertion-functions.ts","../src/assert/assertion-parser.ts","../src/assert/assertion-runner.ts","../src/assert/types.ts"],"sourcesContent":["/**\n * @module model-ir\n * ModelIR (Model Intermediate Representation) - Schema definition format for db-semantic-planner.\n * Represents database tables, columns, and relations with planning metadata.\n *\n * Type definitions live in @dbsp/types. This module re-exports them\n * and provides runtime functions.\n */\n\n// Re-export all types from @dbsp/types for backward compatibility\nexport type {\n\tAmbiguityCheckResult,\n\tCardinality,\n\tCheckConstraintIR,\n\tColumnIR,\n\tColumnJsReadType,\n\tColumnType,\n\tEnumIR,\n\tFilterStrategy,\n\tForeignKeyIR,\n\tIncludeStrategy,\n\tIndexIR,\n\tJoinDefault,\n\tLogicalIdentity,\n\tLogicalIdentityCarrier,\n\tModelIR,\n\tOnDeleteAction,\n\tOptionality,\n\tPartitionIR,\n\tPseudoColumnMetadata,\n\tRecursiveMetadata,\n\tRelationIR,\n\tRelationKind,\n\tRelationType,\n\tRequiredEnumLabelIR,\n\tSequenceIR,\n\tTableIR,\n\tTableReaddressAddress,\n\tTableReaddressDeclaration,\n} from '@dbsp/types';\n\nimport type {\n\tPseudoColumnMetadata,\n\tRecursiveMetadata,\n\tRelationIR,\n\tRelationKind,\n} from '@dbsp/types';\n\n// ============================================================================\n// Runtime Functions (stay in @dbsp/core)\n// ============================================================================\n\n/**\n * Creates pseudo-column metadata from a self-referential FK.\n */\nexport function createPseudoColumnMetadata(\n\ttable: string,\n\tforeignKeyColumn: string,\n\ttargetColumn: string,\n\tparentRole: string,\n\tchildRole: string,\n): PseudoColumnMetadata {\n\t// For single self-ref FK: ascendant/descendant are direct keywords\n\t// For multi-FK: they become scoped (e.g., manager.ascendant)\n\treturn {\n\t\ttable,\n\t\tforeignKeyColumn,\n\t\ttargetColumn,\n\t\tparentRole,\n\t\tchildRole,\n\t\tascendantKeyword: 'ascendant',\n\t\tdescendantKeyword: 'descendant',\n\t};\n}\n\n/**\n * CLI-NQL: Convert ORM-style RelationType to database-style RelationKind.\n * Handles recursive relations when recursive metadata is present.\n */\nexport function getRelationKind(relation: RelationIR): RelationKind {\n\t// Check for recursive relation first\n\tif (relation.recursive) {\n\t\treturn relation.recursive.direction === 'up'\n\t\t\t? 'recursive-up'\n\t\t\t: 'recursive-down';\n\t}\n\n\t// Map ORM types to database perspective\n\tswitch (relation.type) {\n\t\tcase 'belongsTo':\n\t\tcase 'hasOne':\n\t\t\treturn 'many-to-one';\n\t\tcase 'hasMany':\n\t\t\treturn 'one-to-many';\n\t\tcase 'belongsToMany':\n\t\t\treturn 'many-to-many';\n\t}\n}\n\n/**\n * CLI-NQL: Type guard to check if a relation has recursive metadata.\n */\nexport function isRecursiveRelation(\n\trelation: RelationIR,\n): relation is RelationIR & { recursive: RecursiveMetadata } {\n\treturn relation.recursive !== undefined;\n}\n\n/**\n * CLI-NQL: Check if a relation is self-referential (source === target).\n * Self-referential relations are candidates for recursive traversal.\n */\nexport function isSelfReferential(relation: RelationIR): boolean {\n\treturn relation.source === relation.target;\n}\n\n/**\n * CLI-NQL: Create default recursive metadata for a self-referential relation.\n * Used when schema doesn't explicitly define recursive metadata.\n */\nexport function createRecursiveMetadata(\n\tdirection: 'up' | 'down',\n\tthroughRelation: string,\n\tmaxDepth = 10,\n): RecursiveMetadata {\n\treturn {\n\t\tdirection,\n\t\tmaxDepth,\n\t\tthrough: throughRelation,\n\t};\n}\n","/**\n * @module intent-ast\n * IntentAST (Intent Abstract Syntax Tree) - Query intent representation for db-semantic-planner.\n *\n * This module re-exports all IntentAST types and type guards from @dbsp/types.\n * The canonical source is @dbsp/types/intent-ast.\n *\n * @since ARCH-007: Types centralized in @dbsp/types to avoid circular dependencies.\n */\n\n// Re-export everything from @dbsp/types (types + type guards + helpers)\nexport * from '@dbsp/types';\n","/**\n * @module model-impl\n * ModelIR implementation with Map-based storage and helper methods.\n */\n\nimport type {\n\tAmbiguityCheckResult,\n\tEnumIR,\n\tLogicalIdentity,\n\tLogicalIdentityCarrier,\n\tModelIR,\n\tRelationIR,\n\tSequenceIR,\n\tTableIR,\n} from './model-ir.js';\n\nfunction hasExternalSchema(schemaName: string | null | undefined): boolean {\n\treturn schemaName != null && schemaName.trim().length > 0;\n}\n\nfunction logicalIdentityId(\n\tidentity: LogicalIdentity | undefined,\n): string | undefined {\n\tconst id = identity?.id;\n\treturn typeof id === 'string' ? id.trim() : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction logicalIdentityCarrierIsWellFormed(\n\tcarrier: LogicalIdentityCarrier | undefined,\n): boolean {\n\treturn (\n\t\tisRecord(carrier) &&\n\t\ttypeof carrier.kind === 'string' &&\n\t\tcarrier.kind.trim().length > 0 &&\n\t\tcarrier.authenticated === false\n\t);\n}\n\n/**\n * Immutable ModelIR implementation\n */\nexport class ModelIRImpl implements ModelIR {\n\treadonly tables: ReadonlyMap<string, TableIR>;\n\treadonly externalTables: ReadonlySet<string>;\n\treadonly relations: ReadonlyMap<string, RelationIR>;\n\treadonly enums?: ReadonlyMap<string, EnumIR>;\n\treadonly extensions?: readonly string[];\n\treadonly sequences?: ReadonlyMap<string, SequenceIR>;\n\n\t// Pre-computed indexes for efficient lookups\n\tprivate readonly relationsBySource: ReadonlyMap<\n\t\tstring,\n\t\treadonly RelationIR[]\n\t>;\n\tprivate readonly relationsByTarget: ReadonlyMap<\n\t\tstring,\n\t\treadonly RelationIR[]\n\t>;\n\n\tconstructor(\n\t\ttables: Map<string, TableIR>,\n\t\trelations: Map<string, RelationIR>,\n\t\tenums?: Map<string, EnumIR>,\n\t\textensions?: readonly string[],\n\t\tsequences?: Map<string, SequenceIR>,\n\t\texternalTables?: Iterable<string>,\n\t) {\n\t\t// Freeze the maps to ensure immutability\n\t\tthis.tables = Object.freeze(new Map(tables)) as ReadonlyMap<\n\t\t\tstring,\n\t\t\tTableIR\n\t\t>;\n\t\tthis.externalTables = Object.freeze(\n\t\t\tnew Set(externalTables),\n\t\t) as ReadonlySet<string>;\n\t\tthis.relations = Object.freeze(new Map(relations)) as ReadonlyMap<\n\t\t\tstring,\n\t\t\tRelationIR\n\t\t>;\n\t\tif (enums) {\n\t\t\tthis.enums = Object.freeze(new Map(enums)) as ReadonlyMap<string, EnumIR>;\n\t\t}\n\t\tif (extensions && extensions.length > 0) {\n\t\t\tthis.extensions = Object.freeze([...extensions]) as readonly string[];\n\t\t}\n\t\tif (sequences) {\n\t\t\tthis.sequences = Object.freeze(new Map(sequences)) as ReadonlyMap<\n\t\t\t\tstring,\n\t\t\t\tSequenceIR\n\t\t\t>;\n\t\t}\n\n\t\t// Build indexes\n\t\tthis.relationsBySource = this.buildRelationsBySourceIndex(relations);\n\t\tthis.relationsByTarget = this.buildRelationsByTargetIndex(relations);\n\n\t\t// Validate the schema\n\t\tthis.validate();\n\t}\n\n\t/**\n\t * Get table by name\n\t */\n\tgetTable(name: string): TableIR | undefined {\n\t\treturn this.tables.get(name);\n\t}\n\n\t/**\n\t * Get relation by qualified name \"source.relationName\"\n\t */\n\tgetRelation(qualifiedName: string): RelationIR | undefined {\n\t\treturn this.relations.get(qualifiedName);\n\t}\n\n\t/**\n\t * Get all relations from a source table\n\t */\n\tgetRelationsFrom(sourceTable: string): readonly RelationIR[] {\n\t\treturn this.relationsBySource.get(sourceTable) ?? [];\n\t}\n\n\t/**\n\t * Get all relations to a target table\n\t */\n\tgetRelationsTo(targetTable: string): readonly RelationIR[] {\n\t\treturn this.relationsByTarget.get(targetTable) ?? [];\n\t}\n\n\t/**\n\t * Check if relation path is ambiguous (multiple relations to same target)\n\t */\n\tisAmbiguous(sourceTable: string, targetTable: string): AmbiguityCheckResult {\n\t\tconst relationsFromSource = this.getRelationsFrom(sourceTable);\n\t\tconst matchingRelations = relationsFromSource.filter(\n\t\t\t(r) => r.target === targetTable,\n\t\t);\n\n\t\tif (matchingRelations.length <= 1) {\n\t\t\treturn {\n\t\t\t\tambiguous: false,\n\t\t\t\toptions: matchingRelations.map((r) => r.name),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tambiguous: true,\n\t\t\toptions: matchingRelations.map((r) => r.name),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Private Methods\n\t// =========================================================================\n\n\tprivate buildRelationsBySourceIndex(\n\t\trelations: Map<string, RelationIR>,\n\t): ReadonlyMap<string, readonly RelationIR[]> {\n\t\tconst index = new Map<string, RelationIR[]>();\n\n\t\tfor (const relation of relations.values()) {\n\t\t\tconst existing = index.get(relation.source) ?? [];\n\t\t\tindex.set(relation.source, [...existing, relation]);\n\t\t}\n\n\t\t// Create frozen index with readonly arrays\n\t\tconst frozenIndex = new Map<string, readonly RelationIR[]>();\n\t\tfor (const [key, value] of index) {\n\t\t\tfrozenIndex.set(key, Object.freeze(value));\n\t\t}\n\n\t\treturn Object.freeze(frozenIndex) as ReadonlyMap<\n\t\t\tstring,\n\t\t\treadonly RelationIR[]\n\t\t>;\n\t}\n\n\tprivate buildRelationsByTargetIndex(\n\t\trelations: Map<string, RelationIR>,\n\t): ReadonlyMap<string, readonly RelationIR[]> {\n\t\tconst index = new Map<string, RelationIR[]>();\n\n\t\tfor (const relation of relations.values()) {\n\t\t\tconst existing = index.get(relation.target) ?? [];\n\t\t\tindex.set(relation.target, [...existing, relation]);\n\t\t}\n\n\t\t// Create frozen index with readonly arrays\n\t\tconst frozenIndex = new Map<string, readonly RelationIR[]>();\n\t\tfor (const [key, value] of index) {\n\t\t\tfrozenIndex.set(key, Object.freeze(value));\n\t\t}\n\n\t\treturn Object.freeze(frozenIndex) as ReadonlyMap<\n\t\t\tstring,\n\t\t\treadonly RelationIR[]\n\t\t>;\n\t}\n\n\tprivate validate(): void {\n\t\tconst errors: string[] = [];\n\t\tconst logicalIdentityOwners = new Map<string, string>();\n\n\t\tconst recordLogicalIdentity = (\n\t\t\tidentity: LogicalIdentity | undefined,\n\t\t\towner: string,\n\t\t): void => {\n\t\t\tif (identity === undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isRecord(identity)) {\n\t\t\t\terrors.push(`${owner} has a malformed logical identity`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = logicalIdentityId(identity);\n\t\t\tif (id === undefined) {\n\t\t\t\terrors.push(`${owner} has a malformed logical identity id`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (id.length === 0) {\n\t\t\t\terrors.push(`${owner} has an empty logical identity id`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!logicalIdentityCarrierIsWellFormed(identity.carrier)) {\n\t\t\t\terrors.push(`${owner} has a malformed logical identity carrier`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst priorOwner = logicalIdentityOwners.get(id);\n\t\t\tif (priorOwner) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Logical identity \"${id}\" is attached to multiple objects: ${priorOwner}, ${owner}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogicalIdentityOwners.set(id, owner);\n\t\t};\n\n\t\t// Validate PK columns exist when PK is defined\n\t\tfor (const table of this.tables.values()) {\n\t\t\trecordLogicalIdentity(table.logicalIdentity, `table \"${table.name}\"`);\n\t\t\tfor (const column of table.columns) {\n\t\t\t\trecordLogicalIdentity(\n\t\t\t\t\tcolumn.logicalIdentity,\n\t\t\t\t\t`column \"${table.name}.${column.name}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (this.externalTables.has(table.name)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Table \"${table.name}\" cannot be both managed and external`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (table.primaryKey) {\n\t\t\t\tconst pkCols = Array.isArray(table.primaryKey)\n\t\t\t\t\t? table.primaryKey\n\t\t\t\t\t: [table.primaryKey];\n\t\t\t\tfor (const pk of pkCols) {\n\t\t\t\t\tif (!table.columns.some((c) => c.name === pk)) {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t`Table \"${table.name}\" primary key column \"${pk}\" not found in columns`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate all FK references point to existing tables\n\t\tfor (const table of this.tables.values()) {\n\t\t\tfor (const fk of table.foreignKeys) {\n\t\t\t\tif (\n\t\t\t\t\t!hasExternalSchema(fk.references.schema) &&\n\t\t\t\t\t!this.tables.has(fk.references.table) &&\n\t\t\t\t\t!this.externalTables.has(fk.references.table)\n\t\t\t\t) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Table \"${table.name}\" has FK referencing non-existent table \"${fk.references.table}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate all relation targets exist\n\t\tfor (const relation of this.relations.values()) {\n\t\t\tif (!this.tables.has(relation.source)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Relation \"${relation.name}\" has non-existent source table \"${relation.source}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!this.tables.has(relation.target)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Relation \"${relation.name}\" has non-existent target table \"${relation.target}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (relation.through && !this.tables.has(relation.through)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Relation \"${relation.name}\" has non-existent through table \"${relation.through}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Detect circular relations (informational only, not an error)\n\t\t// Detection logic is retained but logging removed to avoid test pollution\n\t\tthis.detectCircularRelations();\n\n\t\tif (errors.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`ModelIR validation failed:\\n${errors.map((e) => ` - ${e}`).join('\\n')}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate detectCircularRelations(): string[] {\n\t\tconst circular: string[] = [];\n\t\tconst visited = new Set<string>();\n\t\tconst recursionStack = new Set<string>();\n\n\t\tconst dfs = (table: string, path: string[]): void => {\n\t\t\tif (recursionStack.has(table)) {\n\t\t\t\tconst cycleStart = path.indexOf(table);\n\t\t\t\tconst cycle = [...path.slice(cycleStart), table].join(' -> ');\n\t\t\t\tcircular.push(cycle);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (visited.has(table)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvisited.add(table);\n\t\t\trecursionStack.add(table);\n\n\t\t\tconst relations = this.getRelationsFrom(table);\n\t\t\tfor (const relation of relations) {\n\t\t\t\tdfs(relation.target, [...path, table]);\n\t\t\t}\n\n\t\t\trecursionStack.delete(table);\n\t\t};\n\n\t\tfor (const tableName of this.tables.keys()) {\n\t\t\tdfs(tableName, []);\n\t\t}\n\n\t\treturn circular;\n\t}\n}\n","/**\n * E10: Injectable Logger\n *\n * Provides a pluggable logging interface for library code.\n * Default implementation uses console, but can be replaced for:\n * - Silent mode (testing, production)\n * - Custom logging frameworks (pino, winston, etc.)\n * - Structured logging\n */\n\nimport { resetWarnedReservedWords } from './table-ref-factory.js';\n\n/**\n * Category of a DX warning, used internally by {@link emitWarning} to decide\n * env/per-instance suppression (#159). The category is NEVER passed to the\n * logger sink (see {@link Logger.warn}) — it only drives the suppression\n * decision inside `emitWarning`.\n *\n * - `'dx'`: developer-experience warnings (e.g. reserved word column access).\n * Suppressible via `DBSP_SUPPRESS_DX_WARNINGS` and per-instance `suppressDxWarnings`.\n * - `'runtime'`: operational warnings (e.g. raw SQL usage). Suppressible via\n * its own gate (e.g. `NODE_ENV`) plus the global logger, but NOT via\n * `DBSP_SUPPRESS_DX_WARNINGS` or per-instance `suppressDxWarnings`.\n */\nexport type WarningCategory = 'dx' | 'runtime';\n\n/**\n * Logger interface for dbsp library code.\n *\n * Only includes methods actually used by the library.\n * Extend as needed when new log levels are required.\n */\nexport interface Logger {\n\t/**\n\t * Log a warning message.\n\t * Used for: reserved word usage, raw SQL warnings, deprecation notices.\n\t *\n\t * @param message - The warning message text (stable across versions —\n\t * downstream consumers may parse it). This is the ONLY argument the\n\t * sink ever receives — {@link WarningCategory} is internal to\n\t * {@link emitWarning}'s suppression decision and is never forwarded\n\t * here, so a `{ warn: console.warn }` or rest-arg/pino-style wrapper\n\t * never sees an unexpected extra token.\n\t */\n\twarn(message: string): void;\n}\n\n/**\n * Default logger that writes to console.\n * Used when no custom logger is provided.\n */\nexport const defaultLogger: Logger = {\n\twarn: (message: string) => console.warn(message),\n};\n\n/**\n * Silent logger that discards all messages.\n * Useful for testing or when warnings should be suppressed.\n */\nexport const silentLogger: Logger = {\n\twarn: () => {},\n};\n\n/**\n * Global logger instance.\n * Can be replaced via setLogger() for application-wide configuration.\n */\nlet globalLogger: Logger = defaultLogger;\n\n/**\n * Set the global logger instance.\n *\n * @param logger - Logger implementation to use globally\n *\n * @example\n * ```typescript\n * import { setLogger, silentLogger } from '@dbsp/core';\n *\n * // Silence all warnings in tests\n * setLogger(silentLogger);\n *\n * // Use custom logger\n * setLogger({\n * warn: (msg) => myLogger.warning('[dbsp]', msg),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n\tglobalLogger = logger;\n}\n\n/**\n * Get the current global logger.\n * Internal use - prefer using getLogger() in library code.\n */\nexport function getLogger(): Logger {\n\treturn globalLogger;\n}\n\n/**\n * Reset logger to default (for testing).\n *\n * Also clears the module-level reserved-word warning dedup (#159) so tests\n * that install a spy logger and assert on warn call counts stay isolated\n * from each other.\n */\nexport function resetLogger(): void {\n\tglobalLogger = defaultLogger;\n\tresetWarnedReservedWords();\n}\n\n/**\n * Options for {@link emitWarning}.\n */\nexport interface EmitWarningOptions {\n\t/**\n\t * Categories to suppress for this call site — e.g. an ORM instance's\n\t * `suppressDxWarnings` option (passing `['dx']`). Union'd with the env gate: a warning is\n\t * suppressed if EITHER applies.\n\t */\n\treadonly suppress?: readonly WarningCategory[];\n}\n\n/**\n * Parse a boolean-ish environment variable value.\n *\n * `undefined`, `''`, `'0'`, and `'false'` (case-insensitive) are treated as\n * disabled; every other value (including `'1'`, `'true'`, `'yes'`, or any\n * other non-empty string) is treated as enabled. This avoids the common\n * `if (process.env.FLAG)` bug where `FLAG=0` or `FLAG=false` are truthy\n * strings and therefore incorrectly enable the flag.\n */\nfunction isEnvFlagEnabled(value: string | undefined): boolean {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst normalized = value.trim().toLowerCase();\n\treturn normalized !== '' && normalized !== '0' && normalized !== 'false';\n}\n\n/**\n * Central warning emission helper (#159).\n *\n * Suppression precedence (a warning is suppressed if ANY of the following hold):\n * 1. `category === 'dx'` AND `DBSP_SUPPRESS_DX_WARNINGS` is enabled per\n * {@link isEnvFlagEnabled} (read per-call, matching this repo's `NODE_ENV`\n * gate convention; `'0'`/`'false'` do NOT enable it).\n * 2. `options.suppress` includes `category`.\n * 3. The global logger is the exported `silentLogger` singleton (an explicit\n * global silence — checked by reference, not behavior, so a custom no-op\n * logger does NOT trigger this branch).\n *\n * Default (no env var, no `suppress` option, non-silent logger) → nothing is\n * suppressed; the message reaches `getLogger().warn(...)`.\n *\n * The category is used ONLY for this suppression decision — it is NEVER\n * passed to `getLogger().warn(...)`, which receives just the message (see\n * {@link Logger.warn}).\n *\n * @returns `true` when the warning was actually emitted, `false` when\n * suppressed. Callers that dedup (e.g. the reserved-word warning) MUST\n * only record the dedup key when this returns `true` — recording it\n * unconditionally would let a suppressed call permanently \"poison\" the\n * dedup slot for every later, non-suppressed caller in the same process.\n */\nexport function emitWarning(\n\tmessage: string,\n\tcategory: WarningCategory,\n\toptions?: EmitWarningOptions,\n): boolean {\n\tif (\n\t\tcategory === 'dx' &&\n\t\tisEnvFlagEnabled(process.env.DBSP_SUPPRESS_DX_WARNINGS)\n\t) {\n\t\treturn false;\n\t}\n\tif (options?.suppress?.includes(category)) {\n\t\treturn false;\n\t}\n\tconst logger = getLogger();\n\tif (logger === silentLogger) {\n\t\treturn false;\n\t}\n\tlogger.warn(message);\n\treturn true;\n}\n","/**\n * @fileoverview ES6 Symbols for type-safe query API metadata.\n *\n * These symbols are used as property keys in TableRef, ColumnRef, and RelationRef\n * to store metadata without colliding with user-defined column names.\n *\n * @example\n * ```typescript\n * import { TABLE_META, COLUMN_META } from './symbols';\n *\n * // Access table name from TableRef\n * const tableName = users[TABLE_META]; // 'users'\n *\n * // Access column name from ColumnRef\n * const columnName = users.id[COLUMN_META]; // 'id'\n * ```\n *\n * @module symbols\n * @since DX-040\n */\n\n/**\n * Symbol for accessing table name metadata from a TableRef.\n *\n * @description\n * Used internally to retrieve the table name from a TableRef object.\n * Uses `Symbol.for()` to create a global symbol that survives serialization\n * and can be accessed across module boundaries.\n *\n * @example\n * ```typescript\n * const { users } = schema.tables;\n * const tableName = users[TABLE_META]; // 'users'\n * ```\n */\nexport const TABLE_META: unique symbol = Symbol.for('dbsp:table');\n\n/**\n * Symbol for accessing column name metadata from a ColumnRef.\n *\n * @description\n * Used internally to retrieve the column name from a ColumnRef object.\n * Uses `Symbol.for()` for cross-module accessibility.\n *\n * @example\n * ```typescript\n * const { users } = schema.tables;\n * const columnName = users.id[COLUMN_META]; // 'id'\n * ```\n */\nexport const COLUMN_META: unique symbol = Symbol.for('dbsp:column');\n\n/**\n * Symbol for accessing relation metadata from a RelationRef.\n *\n * @description\n * Used internally to retrieve relation information (target table, relation type)\n * from a RelationRef object. Uses `Symbol.for()` for cross-module accessibility.\n *\n * @example\n * ```typescript\n * const { users } = schema.tables;\n * const relInfo = users.posts[RELATION_META];\n * // { target: 'posts', type: 'hasMany' }\n * ```\n */\nexport const RELATION_META: unique symbol = Symbol.for('dbsp:relation');\n\n/**\n * Symbol for type branding (internal use).\n *\n * @description\n * Used internally to distinguish between TableRef, ColumnRef, and RelationRef\n * at runtime. This enables type guards and runtime validation.\n * Uses `Symbol.for()` for cross-module accessibility.\n *\n * @example\n * ```typescript\n * function isTableRef(value: unknown): value is TableRef<any, any> {\n * return typeof value === 'object' && value !== null && BRAND in value\n * && (value as any)[BRAND] === 'TableRef';\n * }\n * ```\n */\nexport const BRAND: unique symbol = Symbol.for('dbsp:brand');\n\n/**\n * Symbol for tracking the relation path through which a column was accessed.\n *\n * @description\n * Used to enable cross-table queries. When a column is accessed through a relation\n * (e.g., `users.posts.published`), this symbol stores the relation path.\n * This allows the query builder to generate EXISTS subqueries automatically.\n * Uses `Symbol.for()` for cross-module accessibility.\n *\n * @example\n * ```typescript\n * const { users } = schema.tables;\n * const col = users.posts.published;\n * const path = col[RELATION_PATH]; // ['posts']\n * // Multiple hops: users.posts.comments.author\n * // path would be ['posts', 'comments']\n * ```\n */\nexport const RELATION_PATH: unique symbol = Symbol.for('dbsp:relationPath');\n\n/**\n * Type declarations for Symbol keys to enable TypeScript inference.\n *\n * These types allow TypeScript to understand the shape of objects\n * that use these symbols as keys.\n */\nexport type TableMetaKey = typeof TABLE_META;\nexport type ColumnMetaKey = typeof COLUMN_META;\nexport type RelationMetaKey = typeof RELATION_META;\nexport type BrandKey = typeof BRAND;\n\n// ============================================================================\n// Type Guards for Symbol-keyed Properties\n// ============================================================================\n\n/**\n * Type-safe check for the presence of a symbol-keyed property on an unknown value.\n *\n * Replaces `SYMBOL in (value as unknown as object)` casts throughout the DX layer.\n *\n * @param value - The value to check (any type)\n * @param sym - The symbol key to look for\n * @returns `true` if `value` is a non-null object containing `sym`\n *\n * @example\n * ```typescript\n * if (hasSymbolMeta(value, COLUMN_META)) {\n * // value is narrowed to Record<typeof COLUMN_META, unknown>\n * }\n * ```\n */\nexport function hasSymbolMeta<S extends symbol>(\n\tvalue: unknown,\n\tsym: S,\n): value is Record<S, unknown> {\n\treturn typeof value === 'object' && value !== null && sym in value;\n}\n","/**\n * @fileoverview Type-safe table and column reference types for the query API.\n *\n * This module defines the core reference types used in the type-safe query builder:\n * - `TableRef`: Reference to a table with typed columns and relations\n * - `ColumnRef`: Reference to a column with table, name, and TypeScript type\n * - `RelationRef`: Reference to a relation (FK-based join path)\n * - `AliasedColumn`: Column with an alias for result type inference\n * - `AllColumns`: Wildcard type for SELECT *\n *\n * These types use ES6 Symbols for internal metadata to avoid collision\n * with user-defined column names (see symbols.ts).\n *\n * @example\n * ```typescript\n * const { users } = schema.tables;\n *\n * // TableRef with columns\n * users.id // ColumnRef<'users', 'id', number>\n * users.name // ColumnRef<'users', 'name', string>\n * users['*'] // AllColumns<'users', {...}>\n *\n * // RelationRef for cross-table queries\n * users.posts // RelationRef<'posts', Post[], 'hasMany'>\n * users.posts.title // ColumnRef<'posts', 'title', string>\n * ```\n *\n * @module table-ref\n * @since DX-040\n */\n\nimport {\n\tBRAND,\n\tCOLUMN_META,\n\thasSymbolMeta,\n\tRELATION_META,\n\tRELATION_PATH,\n\tTABLE_META,\n} from './symbols.js';\n\n// Re-export symbols for convenience\nexport {\n\tBRAND,\n\tCOLUMN_META,\n\thasSymbolMeta,\n\tRELATION_META,\n\tRELATION_PATH,\n\tTABLE_META,\n};\n\n/**\n * Relation types supported by the ORM.\n */\nexport type RelationType = 'belongsTo' | 'hasMany' | 'hasOne';\n\n/**\n * Base interface for ColumnRef metadata (using Symbols).\n * @internal\n */\ninterface ColumnRefBase<TTable extends string, TColumn extends string, TType> {\n\t/** @internal Table name metadata (via Symbol) */\n\treadonly [TABLE_META]: TTable;\n\n\t/** @internal Column name metadata (via Symbol) */\n\treadonly [COLUMN_META]: TColumn;\n\n\t/** @internal Type brand for runtime identification */\n\treadonly [BRAND]: 'ColumnRef';\n\n\t/**\n\t * Phantom type for TypeScript inference.\n\t * @internal Not used at runtime - only for type inference.\n\t */\n\treadonly _type: TType;\n}\n\n/**\n * Reference to a column in a table.\n *\n * @typeParam TTable - The table name as a string literal type (e.g., 'users')\n * @typeParam TColumn - The column name as a string literal type (e.g., 'id')\n * @typeParam TType - The TypeScript type of the column value (e.g., number, string)\n *\n * @description\n * ColumnRef carries type information for compile-time inference while also\n * containing runtime metadata accessible via Symbols. The `_type` property\n * is a phantom type (never instantiated at runtime) used for inference.\n *\n * @example\n * ```typescript\n * // users.id is ColumnRef<'users', 'id', number>\n * const id: ColumnRef<'users', 'id', number>;\n *\n * // Access metadata (rarely needed by users)\n * id[TABLE_META] // 'users'\n * id[COLUMN_META] // 'id'\n *\n * // Create alias for result type\n * id.as('userId') // AliasedColumn<'users', 'id', number, 'userId'>\n * ```\n */\nexport type ColumnRef<\n\tTTable extends string,\n\tTColumn extends string,\n\tTType,\n> = ColumnRefBase<TTable, TColumn, TType> & {\n\t/**\n\t * Create an aliased version of this column for result type inference.\n\t *\n\t * @typeParam TAlias - The alias name as a string literal type\n\t * @param alias - Must match `/^[a-zA-Z_][a-zA-Z0-9_]*$/` (validated at runtime)\n\t * @returns AliasedColumn with the specified alias\n\t * @throws Error if alias doesn't match the valid identifier pattern\n\t *\n\t * @example\n\t * ```typescript\n\t * users.id.as('userId')\n\t * // Result type will use 'userId' instead of 'id'\n\t * ```\n\t */\n\tas<TAlias extends string>(\n\t\talias: TAlias,\n\t): AliasedColumn<TTable, TColumn, TType, TAlias>;\n};\n\n/**\n * Column with an alias for result type inference.\n *\n * @typeParam TTable - The source table name\n * @typeParam TColumn - The source column name\n * @typeParam TType - The TypeScript type of the column value\n * @typeParam TAlias - The alias name that will appear in query results\n *\n * @description\n * Extends ColumnRef with an `_alias` property. When used in a query,\n * the result type will use the alias instead of the original column name.\n *\n * @example\n * ```typescript\n * const query = orm.from(users)\n * .select(users.id.as('userId'))\n * .all();\n * // Result type: { userId: number }[]\n * ```\n */\nexport type AliasedColumn<\n\tTTable extends string,\n\tTColumn extends string,\n\tTType,\n\tTAlias extends string,\n> = ColumnRef<TTable, TColumn, TType> & {\n\t/**\n\t * The alias name for this column.\n\t * Used to determine the property name in query results.\n\t */\n\treadonly _alias: TAlias;\n};\n\n/**\n * Represents all columns from a table for SELECT * operations.\n *\n * @typeParam TTable - The table name\n * @typeParam TColumns - Record mapping column names to their TypeScript types\n *\n * @description\n * Used when accessing the wildcard property `table['*']`.\n * When used in a query, selects all columns from the table.\n *\n * @example\n * ```typescript\n * orm.from(users).select(users['*']).all()\n * // SQL: SELECT * FROM users\n * // Result type: User[]\n * ```\n */\nexport interface AllColumns<\n\tTTable extends string,\n\tTColumns extends Record<string, unknown>,\n> {\n\t/** @internal Type brand for runtime identification */\n\treadonly [BRAND]: 'AllColumns';\n\n\t/** @internal Table name metadata */\n\treadonly [TABLE_META]: TTable;\n\n\t/**\n\t * Phantom type containing all column types.\n\t * @internal Used for result type inference.\n\t */\n\treadonly _columns: TColumns;\n}\n\n/**\n * Base interface for RelationRef metadata (using Symbols).\n * @internal\n */\ninterface RelationRefBase<\n\tTTarget extends string,\n\tTTargetType,\n\tTRelationType extends RelationType,\n> {\n\t/** @internal Relation metadata containing target and type */\n\treadonly [RELATION_META]: { target: TTarget; type: TRelationType };\n\n\t/** @internal Type brand for runtime identification */\n\treadonly [BRAND]: 'RelationRef';\n\n\t/**\n\t * Phantom type for the related records.\n\t * @internal Used for result type inference with include().\n\t */\n\treadonly _type: TTargetType;\n}\n\n/**\n * Reference to a relation (FK-based join path).\n *\n * @typeParam TTarget - The target table name (e.g., 'posts')\n * @typeParam TTargetType - The TypeScript type of related records (e.g., Post[])\n * @typeParam TRelationType - The relation type: 'belongsTo' | 'hasMany' | 'hasOne'\n * @typeParam TTargetColumns - Record mapping target column names to their types\n *\n * @description\n * RelationRef enables cross-table queries by allowing access to columns\n * from related tables. It also supports the wildcard `'*'` for selecting\n * all columns from the related table.\n *\n * @example\n * ```typescript\n * // users.posts is RelationRef<'posts', Post[], 'hasMany'>\n *\n * // Access related table's columns\n * users.posts.title // ColumnRef<'posts', 'title', string>\n * users.posts['*'] // AllColumns<'posts', {...}>\n *\n * // Use in cross-table queries\n * orm.from(users).where(eq(users.posts.published, true))\n * // Generates EXISTS subquery\n * ```\n */\nexport type RelationRef<\n\tTTarget extends string,\n\tTTargetType,\n\tTRelationType extends RelationType,\n\tTTargetColumns extends Record<string, unknown> = Record<string, unknown>,\n> = RelationRefBase<TTarget, TTargetType, TRelationType> & {\n\t/**\n\t * Access columns through relation (for cross-table queries).\n\t */\n\treadonly [K in keyof TTargetColumns]: ColumnRef<\n\t\tTTarget,\n\t\tK & string,\n\t\tTTargetColumns[K]\n\t>;\n} & {\n\t/**\n\t * Wildcard for selecting all columns from the related table.\n\t *\n\t * @example\n\t * ```typescript\n\t * users.posts['*'] // AllColumns<'posts', {...}>\n\t * ```\n\t */\n\treadonly '*': AllColumns<TTarget, TTargetColumns>;\n};\n\n/**\n * Base interface for TableRef metadata (using Symbols).\n * @internal\n */\ninterface TableRefBase<TName extends string> {\n\t/** @internal Table name metadata (via Symbol) */\n\treadonly [TABLE_META]: TName;\n\n\t/** @internal Type brand for runtime identification */\n\treadonly [BRAND]: 'TableRef';\n}\n\n/**\n * Reference to a table in the schema.\n *\n * @typeParam TName - The table name as a string literal type (e.g., 'users')\n * @typeParam TColumns - Record mapping column names to ColumnRef types\n * @typeParam TRelations - Record mapping relation names to RelationRef types\n *\n * @description\n * TableRef is the primary type for type-safe queries. It provides:\n * - Access to all columns as ColumnRef properties\n * - Access to all relations as RelationRef properties\n * - A `'*'` wildcard for SELECT * operations\n * - Internal metadata via Symbols (no collision with user columns)\n *\n * TableRef objects are created by the schema builder and accessed via\n * `schema.tables.tableName`.\n *\n * @example\n * ```typescript\n * const { users, posts } = schema.tables;\n *\n * // Access columns\n * users.id // ColumnRef<'users', 'id', number>\n * users.name // ColumnRef<'users', 'name', string>\n *\n * // Access relations\n * users.posts // RelationRef<'posts', Post[], 'hasMany'>\n *\n * // Wildcard\n * users['*'] // AllColumns<'users', {...}>\n *\n * // Internal metadata (rarely needed)\n * users[TABLE_META] // 'users'\n * ```\n */\nexport type TableRef<\n\tTName extends string,\n\tTColumns extends Record<string, ColumnRef<TName, string, unknown>>,\n\tTRelations extends Record<\n\t\tstring,\n\t\tRelationRef<string, unknown, RelationType>\n\t> = Record<never, never>,\n> = TableRefBase<TName> & {\n\t/**\n\t * All columns as ColumnRef properties.\n\t */\n\treadonly [K in keyof TColumns]: TColumns[K];\n} & {\n\t/**\n\t * All relations as RelationRef properties (excluding column name conflicts).\n\t */\n\treadonly [K in keyof TRelations as K extends keyof TColumns\n\t\t? never\n\t\t: K]: TRelations[K];\n} & {\n\t/**\n\t * Wildcard for SELECT * operations.\n\t * The `'*'` character is never a valid SQL identifier, preventing collisions.\n\t *\n\t * @example\n\t * ```typescript\n\t * orm.from(users).select(users['*']).all()\n\t * // SQL: SELECT * FROM users\n\t * ```\n\t */\n\treadonly '*': AllColumns<TName, InferColumnTypes<TColumns>>;\n};\n\n/**\n * Helper type to extract column types from a TColumns record.\n *\n * @typeParam TColumns - Record of column names to ColumnRef types\n * @returns Record mapping column names to their TypeScript types\n *\n * @internal\n */\nexport type InferColumnTypes<\n\tTColumns extends Record<string, ColumnRef<string, string, unknown>>,\n> = {\n\t[K in keyof TColumns]: TColumns[K] extends ColumnRef<string, string, infer T>\n\t\t? T\n\t\t: never;\n};\n\n/**\n * Helper type to infer the row type from a TableRef.\n *\n * @typeParam T - A TableRef type\n * @returns The TypeScript type representing a single row from the table\n *\n * @example\n * ```typescript\n * type UserRow = InferTableRow<typeof users>;\n * // { id: number; name: string; email: string }\n * ```\n */\nexport type InferTableRow<T> =\n\tT extends TableRef<infer _TName, infer TColumns>\n\t\t? InferColumnTypes<TColumns>\n\t\t: never;\n\n/**\n * Type guard to check if a value is a TableRef.\n *\n * @param value - The value to check\n * @returns True if the value is a TableRef\n *\n * @example\n * ```typescript\n * if (isTableRef(value)) {\n * const tableName = value[TABLE_META];\n * }\n * ```\n */\nexport function isTableRef(\n\tvalue: unknown,\n): value is TableRef<\n\tstring,\n\tRecord<string, ColumnRef<string, string, unknown>>\n> {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tBRAND in value &&\n\t\t(value as Record<symbol, unknown>)[BRAND] === 'TableRef'\n\t);\n}\n\n/**\n * Type guard to check if a value is a ColumnRef.\n *\n * @param value - The value to check\n * @returns True if the value is a ColumnRef\n *\n * @example\n * ```typescript\n * if (isColumnRef(value)) {\n * const columnName = value[COLUMN_META];\n * }\n * ```\n */\nexport function isColumnRef(\n\tvalue: unknown,\n): value is ColumnRef<string, string, unknown> {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tBRAND in value &&\n\t\t(value as Record<symbol, unknown>)[BRAND] === 'ColumnRef'\n\t);\n}\n\n/**\n * Type guard to check if a value is a RelationRef.\n *\n * @param value - The value to check\n * @returns True if the value is a RelationRef\n *\n * @example\n * ```typescript\n * if (isRelationRef(value)) {\n * const relInfo = value[RELATION_META];\n * }\n * ```\n */\nexport function isRelationRef(\n\tvalue: unknown,\n): value is RelationRef<string, unknown, RelationType> {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tBRAND in value &&\n\t\t(value as Record<symbol, unknown>)[BRAND] === 'RelationRef'\n\t);\n}\n\n/**\n * Type guard to check if a value is an AllColumns.\n *\n * @param value - The value to check\n * @returns True if the value is an AllColumns\n *\n * @example\n * ```typescript\n * if (isAllColumns(value)) {\n * const tableName = value[TABLE_META];\n * }\n * ```\n */\nexport function isAllColumns(\n\tvalue: unknown,\n): value is AllColumns<string, Record<string, unknown>> {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tBRAND in value &&\n\t\t(value as Record<symbol, unknown>)[BRAND] === 'AllColumns'\n\t);\n}\n\n/**\n * Type guard to check if a value is an AliasedColumn.\n *\n * @param value - The value to check\n * @returns True if the value is an AliasedColumn\n */\nexport function isAliasedColumn(\n\tvalue: unknown,\n): value is AliasedColumn<string, string, unknown, string> {\n\treturn isColumnRef(value) && '_alias' in value;\n}\n","/**\n * @fileoverview Runtime factory for creating TableRef, ColumnRef, and RelationRef objects.\n *\n * This module creates the runtime representations of the type-safe table references.\n * It uses ES6 Symbols for metadata and Proxies for lazy property access.\n *\n * @module table-ref-factory\n * @since DX-040\n */\n\nimport type { ModelIR } from '../model-ir.js';\nimport { emitWarning, type WarningCategory } from './logger.js';\nimport {\n\tBRAND,\n\tCOLUMN_META,\n\tRELATION_META,\n\tRELATION_PATH,\n\ttype RelationType,\n\tTABLE_META,\n} from './table-ref.js';\n\n// ============================================================================\n// JS Reserved Words (H-03)\n// ============================================================================\n\n/**\n * JavaScript reserved words and built-in properties that might conflict\n * with column names. When accessed, these are intercepted by the Proxy\n * and a warning is logged.\n */\nconst JS_RESERVED_WORDS = new Set([\n\t// Object built-ins\n\t'constructor',\n\t'prototype',\n\t'__proto__',\n\t'hasOwnProperty',\n\t'isPrototypeOf',\n\t'propertyIsEnumerable',\n\t'toLocaleString',\n\t'toString',\n\t'valueOf',\n\t// Function built-ins\n\t'arguments',\n\t'caller',\n\t'callee',\n\t'length',\n\t'name',\n\t// Common JS keywords used as identifiers\n\t'class',\n\t'default',\n\t'delete',\n\t'export',\n\t'extends',\n\t'import',\n\t'new',\n\t'return',\n\t'super',\n\t'switch',\n\t'this',\n\t'throw',\n\t'typeof',\n]);\n\n/**\n * Module-level dedup for reserved-word warnings (#159), keyed\n * `${tableName}.${columnName}`. Warns once PER PROCESS rather than once per\n * `createTableRef()` call — a fresh ORM instance no longer re-triggers the\n * warning for a table/column it already warned about. Cleared by\n * {@link resetWarnedReservedWords} (wired into `resetLogger()`) for test\n * isolation.\n */\nconst warnedReservedWords = new Set<string>();\n\n/**\n * Clear the module-level reserved-word warning dedup (#159).\n * Called by `resetLogger()`; exported directly for callers that need to\n * reset dedup without touching the global logger.\n */\nexport function resetWarnedReservedWords(): void {\n\twarnedReservedWords.clear();\n}\n\n/**\n * Log a warning when a reserved word is used as a column name.\n * This is ERR-05 from the spec.\n *\n * The dedup key is recorded ONLY when emitWarning() actually emits (#159) —\n * a suppressed access (per-instance suppress, the env gate, or a global\n * silentLogger) must NOT consume the dedup slot, or a later non-suppressed\n * caller in the same process would never see the warning.\n */\nfunction warnReservedWord(\n\ttableName: string,\n\tcolumnName: string,\n\tsuppress?: readonly WarningCategory[],\n): void {\n\tconst dedupKey = `${tableName}.${columnName}`;\n\tif (warnedReservedWords.has(dedupKey)) {\n\t\treturn;\n\t}\n\tconst emitted = emitWarning(\n\t\t`[dbsp] Warning: Column \"${columnName}\" in table \"${tableName}\" is a JavaScript reserved word. ` +\n\t\t\t`Access it via bracket notation: table['${columnName}']`,\n\t\t'dx',\n\t\tsuppress ? { suppress } : undefined,\n\t);\n\tif (emitted) {\n\t\twarnedReservedWords.add(dedupKey);\n\t}\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a ColumnRef object with Symbol metadata.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param relationPath - Optional relation path for cross-table queries (DX-040 Block 7)\n * @returns A ColumnRef-like object with Symbol properties\n */\nexport function createColumnRef(\n\ttableName: string,\n\tcolumnName: string,\n\trelationPath?: readonly string[],\n): object {\n\tconst columnRef: Record<symbol | string, unknown> = {\n\t\t[TABLE_META]: tableName,\n\t\t[COLUMN_META]: columnName,\n\t\t[BRAND]: 'ColumnRef' as const,\n\t\t_type: undefined as unknown, // Phantom type placeholder\n\t\tas(alias: string) {\n\t\t\t// Validate alias (ERR-04)\n\t\t\tif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(alias)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid alias \"${alias}\": must match /^[a-zA-Z_][a-zA-Z0-9_]*$/`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...this,\n\t\t\t\t_alias: alias,\n\t\t\t};\n\t\t},\n\t};\n\n\t// Add relation path if provided (for cross-table queries)\n\tif (relationPath && relationPath.length > 0) {\n\t\tcolumnRef[RELATION_PATH] = relationPath;\n\t}\n\n\treturn columnRef;\n}\n\n/**\n * Create an AllColumns object for SELECT * operations.\n *\n * @param tableName - The table name\n * @returns An AllColumns-like object\n */\nexport function createAllColumns(tableName: string): object {\n\treturn {\n\t\t[TABLE_META]: tableName,\n\t\t[BRAND]: 'AllColumns' as const,\n\t\t_columns: {}, // Phantom type placeholder\n\t};\n}\n\n/**\n * Map ModelIR RelationType to table-ref RelationType.\n */\nfunction mapRelationType(modelRelationType: string): RelationType {\n\tswitch (modelRelationType) {\n\t\tcase 'belongsTo':\n\t\t\treturn 'belongsTo';\n\t\tcase 'hasMany':\n\t\tcase 'belongsToMany':\n\t\t\treturn 'hasMany';\n\t\tcase 'hasOne':\n\t\t\treturn 'hasOne';\n\t\tdefault:\n\t\t\treturn 'hasMany'; // Default fallback\n\t}\n}\n\n/**\n * Helper to check if a column exists in a table.\n */\nfunction hasColumn(\n\tcolumns: readonly { name: string }[],\n\tcolumnName: string,\n): boolean {\n\treturn columns.some((col) => col.name === columnName);\n}\n\n/**\n * Helper to get column names from a table.\n */\nfunction getColumnNames(columns: readonly { name: string }[]): string[] {\n\treturn columns.map((col) => col.name);\n}\n\n/**\n * Create a RelationRef object with column access via Proxy.\n *\n * @param targetTable - The target table name\n * @param relationType - The relation type (belongsTo, hasMany, hasOne)\n * @param model - The ModelIR for looking up target table columns\n * @param relationName - The name of the relation (for building relation path)\n * @param parentPath - The parent relation path (for chained relations like users.posts.comments)\n * @returns A RelationRef-like object with Proxy for column access\n */\nexport function createRelationRef(\n\ttargetTable: string,\n\trelationType: RelationType,\n\tmodel: ModelIR,\n\trelationName?: string,\n\tparentPath?: readonly string[],\n): object {\n\t// Build the current relation path\n\tconst currentPath: readonly string[] =\n\t\trelationName !== undefined\n\t\t\t? [...(parentPath ?? []), relationName]\n\t\t\t: (parentPath ?? []);\n\n\tconst base = {\n\t\t[RELATION_META]: { target: targetTable, type: relationType },\n\t\t[BRAND]: 'RelationRef' as const,\n\t\t[RELATION_PATH]: currentPath, // Store path on RelationRef too\n\t\t_type: undefined as unknown, // Phantom type placeholder\n\t};\n\n\t// Use Proxy for lazy column access on the relation\n\treturn new Proxy(base, {\n\t\tget(target, prop, receiver) {\n\t\t\t// Handle Symbol properties\n\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\t// Handle '*' wildcard\n\t\t\tif (prop === '*') {\n\t\t\t\treturn createAllColumns(targetTable);\n\t\t\t}\n\n\t\t\t// Handle built-in properties\n\t\t\tif (prop in target) {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\t// Check if this is a column in the target table\n\t\t\tconst targetTableIR = model.getTable(targetTable);\n\t\t\tif (targetTableIR && hasColumn(targetTableIR.columns, prop as string)) {\n\t\t\t\t// Pass the relation path for cross-table query support\n\t\t\t\treturn createColumnRef(targetTable, prop as string, currentPath);\n\t\t\t}\n\n\t\t\t// Check if this is a relation from the target table (chained relations)\n\t\t\tfor (const rel of model.getRelationsFrom(targetTable)) {\n\t\t\t\tif (rel.name === prop) {\n\t\t\t\t\treturn createRelationRef(\n\t\t\t\t\t\trel.target,\n\t\t\t\t\t\tmapRelationType(rel.type),\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tprop as string,\n\t\t\t\t\t\tcurrentPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check inverse relations\n\t\t\tfor (const rel of model.getRelationsTo(targetTable)) {\n\t\t\t\tif (rel.source === prop) {\n\t\t\t\t\treturn createRelationRef(\n\t\t\t\t\t\trel.source,\n\t\t\t\t\t\t'hasMany',\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tprop as string,\n\t\t\t\t\t\tcurrentPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Return undefined for non-existent properties\n\t\t\treturn undefined;\n\t\t},\n\t\thas(target, prop) {\n\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\treturn prop in target;\n\t\t\t}\n\t\t\tif (prop === '*') {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst targetTableIR = model.getTable(targetTable);\n\t\t\treturn (\n\t\t\t\tprop in target ||\n\t\t\t\t(targetTableIR !== undefined &&\n\t\t\t\t\thasColumn(targetTableIR.columns, prop as string))\n\t\t\t);\n\t\t},\n\t\townKeys(target) {\n\t\t\tconst targetTableIR = model.getTable(targetTable);\n\t\t\tconst columnNames = targetTableIR\n\t\t\t\t? getColumnNames(targetTableIR.columns)\n\t\t\t\t: [];\n\t\t\treturn [...Reflect.ownKeys(target), '*', ...columnNames];\n\t\t},\n\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\tconst self = this as ProxyHandler<typeof base>;\n\t\t\tif (\n\t\t\t\tprop === '*' ||\n\t\t\t\t(typeof prop === 'string' && self.has?.(target, prop))\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tvalue: self.get?.(target, prop, target),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn Reflect.getOwnPropertyDescriptor(target, prop);\n\t\t},\n\t});\n}\n\n/**\n * Create a TableRef object with columns and relations via Proxy.\n *\n * @param tableName - The table name\n * @param model - The ModelIR containing table and relation information\n * @param suppress - Warning categories to suppress for this instance (#159).\n * The public entry point is `createOrm({ suppressDxWarnings: true })`,\n * which derives this general `WarningCategory[]` shape internally.\n * @returns A TableRef-like object with Proxy for lazy property access\n */\nexport function createTableRef(\n\ttableName: string,\n\tmodel: ModelIR,\n\tsuppress?: readonly WarningCategory[],\n): object {\n\tconst tableIR = model.getTable(tableName);\n\tif (!tableIR) {\n\t\tthrow new Error(`Table \"${tableName}\" not found in model`);\n\t}\n\n\tconst base = {\n\t\t[TABLE_META]: tableName,\n\t\t[BRAND]: 'TableRef' as const,\n\t};\n\n\t// Build relations map: relation name -> { targetTable, relationType }\n\t// Include both direct relations (from this table) and inverse relations (to this table)\n\tconst relations = new Map<string, { target: string; type: RelationType }>();\n\n\t// Direct relations (belongsTo) - where this table is the source\n\tfor (const relation of model.getRelationsFrom(tableName)) {\n\t\tconst relationType = mapRelationType(relation.type);\n\t\trelations.set(relation.name, {\n\t\t\ttarget: relation.target,\n\t\t\ttype: relationType,\n\t\t});\n\t}\n\n\t// Inverse relations (hasMany/hasOne) - where this table is the target\n\tfor (const relation of model.getRelationsTo(tableName)) {\n\t\t// Skip if the relation is from this table to itself (would be handled above)\n\t\tif (relation.source === tableName) continue;\n\n\t\t// Derive inverse relation name: use explicit inverse option or default to source table name\n\t\t// The inverse name should be on the relation itself if specified\n\t\tconst inverseName = relation.source; // Default: source table name (e.g., 'posts')\n\n\t\t// Only add if not already present (direct relations take precedence)\n\t\tif (!relations.has(inverseName)) {\n\t\t\t// Inverse of belongsTo is hasMany (or hasOne if the FK is unique, but we default to hasMany)\n\t\t\trelations.set(inverseName, { target: relation.source, type: 'hasMany' });\n\t\t}\n\t}\n\n\treturn new Proxy(base, {\n\t\tget(target, prop, receiver) {\n\t\t\t// Handle Symbol properties\n\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\t// Handle '*' wildcard (H-02)\n\t\t\tif (prop === '*') {\n\t\t\t\treturn createAllColumns(tableName);\n\t\t\t}\n\n\t\t\t// Handle built-in properties\n\t\t\tif (prop in target) {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tconst propStr = prop as string;\n\n\t\t\t// Check for JS reserved words (H-03, ERR-05)\n\t\t\tif (JS_RESERVED_WORDS.has(propStr)) {\n\t\t\t\t// Check if it's actually a column\n\t\t\t\tif (hasColumn(tableIR.columns, propStr)) {\n\t\t\t\t\twarnReservedWord(tableName, propStr, suppress);\n\t\t\t\t\treturn createColumnRef(tableName, propStr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if this is a column\n\t\t\tif (hasColumn(tableIR.columns, propStr)) {\n\t\t\t\treturn createColumnRef(tableName, propStr);\n\t\t\t}\n\n\t\t\t// Check if this is a relation\n\t\t\tconst relation = relations.get(propStr);\n\t\t\tif (relation) {\n\t\t\t\t// Pass relation name for building relation path (DX-040 Block 7)\n\t\t\t\treturn createRelationRef(\n\t\t\t\t\trelation.target,\n\t\t\t\t\trelation.type,\n\t\t\t\t\tmodel,\n\t\t\t\t\tpropStr,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Return undefined for non-existent properties\n\t\t\treturn undefined;\n\t\t},\n\t\thas(target, prop) {\n\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\treturn prop in target;\n\t\t\t}\n\t\t\tif (prop === '*') {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst propStr = prop as string;\n\t\t\treturn (\n\t\t\t\tprop in target ||\n\t\t\t\thasColumn(tableIR.columns, propStr) ||\n\t\t\t\trelations.has(propStr)\n\t\t\t);\n\t\t},\n\t\townKeys(target) {\n\t\t\tconst columnNames = getColumnNames(tableIR.columns);\n\t\t\tconst relationNames = Array.from(relations.keys());\n\t\t\treturn [\n\t\t\t\t...Reflect.ownKeys(target),\n\t\t\t\t'*',\n\t\t\t\t...columnNames,\n\t\t\t\t...relationNames,\n\t\t\t];\n\t\t},\n\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\tconst self = this as ProxyHandler<typeof base>;\n\t\t\tif (\n\t\t\t\tprop === '*' ||\n\t\t\t\t(typeof prop === 'string' && self.has?.(target, prop))\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tvalue: self.get?.(target, prop, target),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn Reflect.getOwnPropertyDescriptor(target, prop);\n\t\t},\n\t});\n}\n\n/**\n * Options for {@link createTablesProxy}.\n */\nexport interface CreateTablesProxyOptions {\n\t/** Warning categories to suppress for every TableRef built by this proxy (#159). */\n\treadonly suppressWarnings?: readonly WarningCategory[];\n}\n\n/**\n * Create the tables Proxy for a schema.\n *\n * This is the main entry point that creates a Proxy which lazily\n * instantiates TableRef objects when tables are accessed.\n *\n * @param model - The ModelIR containing all table and relation information\n * @param tableNames - List of table names in the schema\n * @param options - Optional per-instance warning suppression (#159)\n * @returns A Proxy that returns TableRef objects for each table\n */\nexport function createTablesProxy(\n\tmodel: ModelIR,\n\ttableNames: string[],\n\toptions?: CreateTablesProxyOptions,\n): object {\n\tconst tableSet = new Set(tableNames);\n\tconst cache = new Map<string, object>();\n\tconst suppress = options?.suppressWarnings;\n\n\treturn new Proxy(\n\t\t{},\n\t\t{\n\t\t\tget(_target, prop) {\n\t\t\t\t// Handle Symbol properties\n\t\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst propStr = prop as string;\n\n\t\t\t\t// Return cached TableRef if exists\n\t\t\t\tif (cache.has(propStr)) {\n\t\t\t\t\treturn cache.get(propStr);\n\t\t\t\t}\n\n\t\t\t\t// Create TableRef if this is a valid table\n\t\t\t\tif (tableSet.has(propStr)) {\n\t\t\t\t\tconst tableRef = createTableRef(propStr, model, suppress);\n\t\t\t\t\tcache.set(propStr, tableRef);\n\t\t\t\t\treturn tableRef;\n\t\t\t\t}\n\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\thas(_target, prop) {\n\t\t\t\tif (typeof prop === 'symbol') {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn tableSet.has(prop as string);\n\t\t\t},\n\t\t\townKeys() {\n\t\t\t\treturn tableNames;\n\t\t\t},\n\t\t\tgetOwnPropertyDescriptor(_target, prop) {\n\t\t\t\tif (typeof prop === 'string' && tableSet.has(prop)) {\n\t\t\t\t\t// Get or create the TableRef\n\t\t\t\t\tlet tableRef = cache.get(prop);\n\t\t\t\t\tif (!tableRef) {\n\t\t\t\t\t\ttableRef = createTableRef(prop, model, suppress);\n\t\t\t\t\t\tcache.set(prop, tableRef);\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tvalue: tableRef,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t},\n\t);\n}\n","/**\n * ARCH-005: Unified Schema API\n *\n * Provides the schema() + ref() API. Relations are auto-inferred from FK\n * declarations.\n *\n * @example\n * ```typescript\n * import { schema, ref } from '@dbsp/core';\n *\n * const db = schema({\n * users: { id: 'uuid', email: { type: 'text', unique: true } },\n * posts: { id: 'uuid', authorId: ref('users') },\n * });\n * ```\n */\n\nimport type { WhereIntent } from '@dbsp/types';\nimport type { Mutable } from '@dbsp/types/internal';\nimport type { DbCasing } from '../adapter.js';\nimport { ModelIRImpl } from '../model-impl.js';\nimport type {\n\tCheckConstraintIR,\n\tColumnIR,\n\tColumnJsReadType,\n\tColumnType,\n\tForeignKeyIR,\n\tIndexIR,\n\tModelIR,\n\tOnDeleteAction,\n\tPseudoColumnMetadata,\n\tRelationIR,\n\tRelationType,\n\tTableIR,\n\tTableReaddressDeclaration,\n} from '../model-ir.js';\nimport { createPseudoColumnMetadata } from '../model-ir.js';\nimport type { InferTables } from './schema-tables-types.js';\nimport { createTablesProxy } from './table-ref-factory.js';\n\nexport type { ColumnJsReadType } from '../model-ir.js';\n\n// ============================================================================\n// Public Types\n// ============================================================================\n\n/**\n * Supported column types in schema definitions.\n * Maps to ColumnType from ModelIR.\n */\nexport type SchemaColumnType = ColumnType;\n\n/**\n * Column definition - short form (just type) or long form (with options).\n */\nexport type ColumnDef =\n\t| SchemaColumnType\n\t| {\n\t\t\ttype: SchemaColumnType;\n\t\t\tjs?: ColumnJsReadType;\n\t\t\tdbType?: string;\n\t\t\tnullable?: boolean;\n\t\t\tunique?: boolean;\n\t\t\tprimaryKey?: boolean;\n\t\t\tautoIncrement?: boolean;\n\t\t\tdefault?: unknown;\n\t\t\tindex?: boolean;\n\t };\n\n/**\n * Self-referential relation role names.\n * Required when declaring a ref() to the same table.\n */\nexport interface SelfRefRoles {\n\t/** Name for the direct parent relation (e.g., 'parent', 'manager') */\n\tparent: string;\n\t/** Name for the direct children relation (e.g., 'children', 'directReports') */\n\tchildren: string;\n\t/** Name for recursive ancestors (default: 'ancestors') */\n\tancestors?: string;\n\t/** Name for recursive descendants (default: 'descendants') */\n\tdescendants?: string;\n}\n\n/**\n * Options for ref() foreign key declarations.\n */\nexport interface RefOptions {\n\t/** Target schema name (omit for same-schema references) */\n\tschema?: string;\n\n\t// FK column constraints\n\t/** Is this FK nullable? → optional relation */\n\tnullable?: boolean;\n\t/** Is this FK unique? → 1:1 instead of 1:N */\n\tunique?: boolean;\n\t/** Optional read-side JavaScript representation for bigint/int8 FK columns */\n\tjs?: ColumnJsReadType;\n\n\t// FK behavior\n\t/** ON DELETE action */\n\tonDelete?: OnDeleteAction;\n\t/** ON UPDATE action */\n\tonUpdate?: OnDeleteAction;\n\n\t// Relation naming\n\t/** Local relation name (e.g., 'createdBy' for createdById column) */\n\tas?: string;\n\t/** Inverse relation name on target table (e.g., 'writings' instead of 'author_posts') */\n\tinverse?: string;\n\n\t// Self-ref only (MANDATORY when source === target)\n\t/** Role names for self-referential relations */\n\troles?: SelfRefRoles;\n\n\t/**\n\t * Source columns forming a composite FK (table-level `foreignKeys` only).\n\t */\n\tcolumns?: readonly string[];\n\n\t/**\n\t * Target columns the FK references.\n\t * - For column-level `ref()`: the target column on the referenced\n\t * table. Defaults to `['id']` by convention; the actual target\n\t * PK column is not auto-resolved. Length must be exactly 1.\n\t * - For table-level composite FKs: the list of target columns.\n\t */\n\treferences?: readonly string[];\n}\n\n/**\n * Marker type for ref() declarations in schema.\n * Generic over target and options to preserve literal types for inference.\n * @internal\n */\nexport interface RefDefinition<\n\tTTarget extends string = string,\n\tTOptions extends RefOptions = RefOptions,\n> {\n\treadonly __brand: 'ref';\n\treadonly target: TTarget;\n\treadonly options: TOptions;\n}\n\n/**\n * Table definition - a record of column names to column or ref definitions.\n */\nexport type TableDef = Record<string, ColumnDef | RefDefinition>;\n\n/**\n * Schema definition - a record of table names to table definitions.\n */\nexport type SchemaDefinition = Record<string, TableDef>;\n\n/**\n * Table-level constraints for composite indexes and foreign keys.\n * Used as the 2nd argument to schema() for constraints that span multiple columns.\n *\n * @example\n * ```typescript\n * schema({\n * orderItems: {\n * orderId: 'uuid',\n * productId: 'uuid',\n * quantity: 'integer',\n * },\n * }, {\n * orderItems: {\n * indexes: [\n * { columns: ['orderId', 'productId'], unique: true },\n * ],\n * foreignKeys: [\n * ref('orders', { columns: ['orderId', 'productId'], references: ['orderId', 'productId'] }),\n * ],\n * },\n * });\n * ```\n */\nexport interface SchemaIndexOptions {\n\t/** Columns included in the index */\n\tcolumns: string[];\n\t/** Whether this is a unique index */\n\tunique?: boolean;\n\t/**\n\t * PG15+ — for a UNIQUE index, treat NULLs as not distinct\n\t * (`NULLS NOT DISTINCT`); true is rejected for non-unique indexes. Emitted\n\t * as declared; coherent server-version capability gating for all index\n\t * features is tracked together in #245.\n\t */\n\tnullsNotDistinct?: boolean;\n\t/** Custom index name (auto-generated if not provided) */\n\tname?: string;\n\t/** Index access method (default: btree). E.g. 'gin', 'gist', 'hnsw', 'bm25' */\n\tmethod?: string;\n\t/** Partial index predicate (WHERE clause) */\n\twhere?: string;\n\t/**\n\t * Non-key columns to include (INCLUDE clause, PG11+).\n\t * Emitted as declared; coherent server-version capability gating for all\n\t * index features is tracked together in #245.\n\t */\n\tinclude?: string[];\n\t/** Per-column operator class overrides. Key = column name, value = opclass name */\n\topclass?: Record<string, string>;\n\t/** Index storage parameters (WITH clause). Key = param name, value = param value */\n\twith?: Record<string, string>;\n}\n\nexport interface SchemaIndexValidationInput {\n\treadonly columns: readonly string[];\n\treadonly unique?: boolean;\n\treadonly nullsNotDistinct?: boolean;\n\treadonly name?: string;\n}\n\nexport interface SchemaTableOptions {\n\t/** Indexes for this table (simple, composite, partial, GIN, HNSW, BM25, etc.) */\n\tindexes?: SchemaIndexOptions[];\n\t/** CHECK constraints for this table */\n\tcheckConstraints?: Array<{\n\t\tname: string;\n\t\texpression: string;\n\t}>;\n\t/** Composite foreign keys for this table (use ref() with columns/references) */\n\tforeignKeys?: RefDefinition[];\n\t/** Explicit rename or schema move for this desired table. */\n\treaddress?: TableReaddressDeclaration;\n\t/** Explicitly bring this existing table under managed state. */\n\tadopt?: true;\n\t/** Request a reviewed retire-and-create replacement of this table. */\n\treplace?: true;\n}\n\n/**\n * Per-table constraint options, keyed by table name.\n */\nexport type SchemaConstraints = Record<string, SchemaTableOptions>;\n\n/**\n * Top-level schema-wide DDL objects: extensions, sequences.\n */\nexport interface SchemaExtras {\n\t/** PostgreSQL extensions to ensure (CREATE EXTENSION IF NOT EXISTS \"name\") */\n\textensions?: string[];\n\t/**\n\t * Sequences to create (CREATE SEQUENCE), or, with `adopt: true`, an existing standalone\n\t * sequence for `convergePg` to take into management. Key = sequence name\n\t */\n\tsequences?: Record<\n\t\tstring,\n\t\t{\n\t\t\tstartWith?: number | string;\n\t\t\tincrementBy?: number | string;\n\t\t\tminValue?: number | string;\n\t\t\tmaxValue?: number | string;\n\t\t\tcycle?: boolean;\n\t\t\t/** Explicitly bring an existing standalone sequence under managed state. */\n\t\t\tadopt?: true;\n\t\t}\n\t>;\n}\n\n/**\n * Result of schema() function with strongly-typed table/column info.\n */\n/**\n * Per-table default filters applied to all queries.\n * Commonly used for soft delete filtering.\n *\n * @example\n * ```typescript\n * import { isNull } from '@dbsp/core';\n *\n * const db = schema(tables, undefined, {\n * defaultFilters: {\n * products: isNull('deletedAt'),\n * users: isNull('deletedAt'),\n * },\n * });\n * ```\n */\nexport type DefaultFilters = Record<string, WhereIntent>;\n\n/**\n * Options for schema() function.\n */\nexport interface SchemaOptions {\n\t/**\n\t * Default filters applied automatically to all queries per table.\n\t * Override with `.withoutDefaultFilters()` on the query builder.\n\t */\n\tdefaultFilters?: DefaultFilters;\n\t/**\n\t * Column name treated as the implicit primary key for short-form column\n\t * declarations. When set (default `'id'`), `inferPrimaryKey` resolves the\n\t * implicit PK BEFORE falling back to FK columns: a column matching this name\n\t * is treated as the PK whenever no explicit `primaryKey: true` flag is present\n\t * on any column — regardless of whether the table also has FK columns.\n\t *\n\t * Default: `'id'` (matches existing codebase convention).\n\t *\n\t * Set to `null` to disable the implicit-PK convention entirely. Primary\n\t * keys must then be declared explicitly with `primaryKey: true` (or are\n\t * inferred from FK columns for junction tables). Empty string (`''`) and\n\t * whitespace-only strings are rejected eagerly at `schema()` time\n\t * (before any per-table processing) with a `SchemaValidationError`.\n\t *\n\t * Match the adapter's `defaultPkColumnName` if your project uses a\n\t * different naming scheme (e.g. `'pk_uuid'`).\n\t *\n\t * @remarks\n\t * `inferPrimaryKey` resolves PKs in this order:\n\t * 1. Explicit `primaryKey: true` on column(s)\n\t * 2. Column matching `defaultPkColumnName` (this option) — skipped when set to `null`\n\t * 3. FK columns (composite, for junction tables — applies regardless of this option)\n\t * 4. No primary key\n\t *\n\t * @example\n\t * // Default — 'id' is implicit PK\n\t * schema({ users: { id: 'uuid' } });\n\t *\n\t * // Custom convention\n\t * schema({ users: { pk_uuid: 'uuid' } }, undefined, { defaultPkColumnName: 'pk_uuid' });\n\t *\n\t * // Strict — no implicit PK convention\n\t * schema({ users: { id: 'uuid' } }, undefined, { defaultPkColumnName: null });\n\t * // ↑ no PK declared — FKs targeting users.id will fail validation.\n\t */\n\tdefaultPkColumnName?: string | null;\n}\n\nexport interface Schema<T extends SchemaDefinition> {\n\t/** The raw schema definition */\n\treadonly definition: T;\n\t/** Table-level constraints supplied to schema() or reconstructed from introspection */\n\treadonly constraints?: SchemaConstraints;\n\t/** Schema-wide objects supplied to schema(); retained for durable declarations. */\n\treadonly extras?: SchemaExtras;\n\t/** Planning inputs supplied to schema(); retained without changing model semantics. */\n\treadonly options?: SchemaOptions;\n\t/** Converted ModelIR for use with ORM */\n\treadonly model: ModelIR;\n\t/** Table names */\n\treadonly tableNames: (keyof T)[];\n\t/**\n\t * Type-safe table references for query building.\n\t *\n\t * Provides typed access to tables, columns, and relations:\n\t * - `schema.tables.users` returns a TableRef with typed columns\n\t * - `schema.tables.users.id` returns a ColumnRef\n\t * - `schema.tables.users.posts` returns a RelationRef (if relation exists)\n\t * - `schema.tables.users['*']` returns AllColumns for SELECT *\n\t *\n\t * @example\n\t * ```typescript\n\t * const { users, posts } = schema.tables;\n\t *\n\t * // Type-safe column access\n\t * users.id // ColumnRef<'users', 'id', string>\n\t * users.name // ColumnRef<'users', 'name', string>\n\t *\n\t * // Type-safe relation access\n\t * users.posts // RelationRef<'posts', Post[], 'hasMany'>\n\t *\n\t * // Wildcard for SELECT *\n\t * users['*'] // AllColumns<'users', {...}>\n\t * ```\n\t *\n\t * @since DX-040\n\t */\n\treadonly tables: InferTables<T>;\n\t/**\n\t * DB column casing — describes what casing the database uses.\n\t * @see DbCasing\n\t */\n\treadonly dbCasing?: DbCasing;\n\t/**\n\t * Timestamp when this schema was introspected from the database.\n\t * Only present for schemas created via getSchemaFromDb().\n\t * Useful for detecting schema drift.\n\t */\n\treadonly introspectedAt?: Date;\n\t/**\n\t * Default filters per table (e.g., soft delete filtering).\n\t * Applied automatically to all queries unless `.withoutDefaultFilters()` is called.\n\t */\n\treadonly defaultFilters?: DefaultFilters;\n}\n\n// ============================================================================\n// Type Inference Helpers\n// ============================================================================\n\n/**\n * JSON-compatible value type for json/jsonb columns.\n */\nexport type JsonValue =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| JsonValue[]\n\t| { [key: string]: JsonValue };\n\n/**\n * Range value type for PostgreSQL range types.\n */\nexport interface InferredRangeValue<T> {\n\treadonly start: T | null;\n\treadonly end: T | null;\n\treadonly startInclusive?: boolean;\n\treadonly endInclusive?: boolean;\n}\n\n/**\n * Maps a ColumnType string to its TypeScript type.\n */\nexport type InferColumnType<T extends SchemaColumnType> =\n\t// String types\n\tT extends 'string' | 'text' | 'uuid'\n\t\t? string\n\t\t: // Numeric types\n\t\t\tT extends 'number' | 'integer' | 'decimal'\n\t\t\t? number\n\t\t\t: // BigInt\n\t\t\t\tT extends 'bigint'\n\t\t\t\t? bigint\n\t\t\t\t: // Boolean\n\t\t\t\t\tT extends 'boolean'\n\t\t\t\t\t? boolean\n\t\t\t\t\t: // Date/time types\n\t\t\t\t\t\tT extends 'date' | 'time' | 'datetime' | 'timestamp'\n\t\t\t\t\t\t? Date\n\t\t\t\t\t\t: // JSON types\n\t\t\t\t\t\t\tT extends 'json' | 'jsonb'\n\t\t\t\t\t\t\t? JsonValue\n\t\t\t\t\t\t\t: // PostgreSQL range types\n\t\t\t\t\t\t\t\tT extends 'daterange'\n\t\t\t\t\t\t\t\t? InferredRangeValue<Date>\n\t\t\t\t\t\t\t\t: T extends 'tsrange' | 'tstzrange'\n\t\t\t\t\t\t\t\t\t? InferredRangeValue<Date>\n\t\t\t\t\t\t\t\t\t: T extends 'int4range' | 'int8range'\n\t\t\t\t\t\t\t\t\t\t? InferredRangeValue<number>\n\t\t\t\t\t\t\t\t\t\t: T extends 'numrange'\n\t\t\t\t\t\t\t\t\t\t\t? InferredRangeValue<number>\n\t\t\t\t\t\t\t\t\t\t\t: // Fallback\n\t\t\t\t\t\t\t\t\t\t\t\tunknown;\n\n/**\n * Extracts the type string from a ColumnDef (handles short and long forms).\n */\ntype ExtractColumnType<C extends ColumnDef> = C extends SchemaColumnType\n\t? C\n\t: C extends { readonly type: infer T extends SchemaColumnType }\n\t\t? T\n\t\t: never;\n\n/**\n * Checks if a ColumnDef is nullable.\n */\ntype IsNullable<C extends ColumnDef> = C extends { readonly nullable: true }\n\t? true\n\t: false;\n\n/**\n * Infers the non-null TypeScript type for a single column definition.\n * Bigint keeps its existing default type unless an explicit read-side js type is set.\n */\nexport type InferColumnNonNull<C extends ColumnDef> =\n\tExtractColumnType<C> extends 'bigint'\n\t\t? C extends { readonly js: 'number' }\n\t\t\t? number\n\t\t\t: C extends { readonly js: 'bigint' }\n\t\t\t\t? bigint\n\t\t\t\t: C extends { readonly js: 'string' }\n\t\t\t\t\t? string\n\t\t\t\t\t: InferColumnType<ExtractColumnType<C>>\n\t\t: InferColumnType<ExtractColumnType<C>>;\n\n/**\n * Infers the TypeScript type for a single column definition.\n * Handles both short form ('string') and long form ({ type: 'string', nullable: true }).\n */\nexport type InferColumn<C extends ColumnDef> =\n\tIsNullable<C> extends true\n\t\t? InferColumnNonNull<C> | null\n\t\t: InferColumnNonNull<C>;\n\n/**\n * Infers the FK column type from a RefDefinition.\n *\n * ⚠️ **Limitation:** FK columns are typed as `number | string` because inferring\n * the target PK type at compile time would require resolving cross-table references,\n * which creates circular type dependencies in TypeScript.\n *\n * **Why not infer from target table?**\n * Given `ref('users')`, we'd need to:\n * 1. Find `users` table in the schema\n * 2. Find column with `primaryKey: true`\n * 3. Get its type\n *\n * This creates circular refs when tables reference each other (A→B→A).\n *\n * **Pragmatic trade-off:** `number | string` covers 99% of PKs (auto-increment int or UUID).\n *\n * @example\n * authorId: ref('users') // Type: number | string\n * editorId: ref('users', { nullable: true }) // Type: number | string | null\n */\ntype InferRefColumnNonNull<R extends RefDefinition> = R extends {\n\treadonly options: { readonly js: 'number' };\n}\n\t? number\n\t: R extends { readonly options: { readonly js: 'bigint' } }\n\t\t? bigint\n\t\t: R extends { readonly options: { readonly js: 'string' } }\n\t\t\t? string\n\t\t\t: number | string;\n\nexport type InferRefColumn<R extends RefDefinition> = R extends {\n\treadonly options: { readonly nullable: true };\n}\n\t? InferRefColumnNonNull<R> | null\n\t: InferRefColumnNonNull<R>;\n\n/**\n * Infers the row type for a single table definition.\n * Maps each column to its TypeScript type.\n */\nexport type InferRow<T extends TableDef> = {\n\t[K in keyof T]: T[K] extends RefDefinition\n\t\t? InferRefColumn<T[K]>\n\t\t: T[K] extends ColumnDef\n\t\t\t? InferColumn<T[K]>\n\t\t\t: unknown;\n};\n\n/**\n * Infers the complete database type from a schema definition.\n * Maps each table name to its row type.\n *\n * @example\n * ```typescript\n * const mySchema = schema({\n * users: { id: 'integer', email: 'string', bio: { type: 'text', nullable: true } },\n * posts: { id: 'integer', title: 'string', authorId: ref('users') },\n * });\n *\n * type DB = InferDB<typeof mySchema.definition>;\n * // DB = {\n * // users: { id: number; email: string; bio: string | null };\n * // posts: { id: number; title: string; authorId: number | string };\n * // }\n * ```\n */\nexport type InferDB<S extends SchemaDefinition> = {\n\t[TableName in keyof S]: InferRow<S[TableName]>;\n};\n\n/**\n * Helper type to extract the inferred DB type from a Schema instance.\n */\nexport type InferSchemaDB<S extends Schema<SchemaDefinition>> =\n\tS extends Schema<infer T> ? InferDB<T> : never;\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nfunction normalizeReferenceSchema(\n\tschemaName: string | null | undefined,\n): string | undefined {\n\tif (schemaName == null) return undefined;\n\tconst t = schemaName.trim();\n\treturn t.length > 0 ? t : undefined;\n}\n\nfunction hasExternalSchema(schemaName: string | null | undefined): boolean {\n\treturn normalizeReferenceSchema(schemaName) !== undefined;\n}\n\nfunction normalizeRefOptions<TOptions extends RefOptions>(\n\toptions: TOptions,\n): TOptions {\n\tconst schemaName = normalizeReferenceSchema(options.schema);\n\tif (schemaName === options.schema) return options;\n\n\tconst { schema: _schema, ...rest } = options;\n\treturn (\n\t\tschemaName === undefined ? rest : { ...rest, schema: schemaName }\n\t) as TOptions;\n}\n\n/**\n * Declares a foreign key reference to another table.\n *\n * @param target - Target table name (must exist in schema)\n * @param options - Optional FK constraints and relation naming\n * @returns RefDefinition for use in table definitions\n *\n * @example\n * ```typescript\n * // Simple FK (1:N)\n * authorId: ref('users')\n *\n * // Optional FK\n * editorId: ref('users', { nullable: true })\n *\n * // 1:1 relation (unique FK)\n * userId: ref('users', { unique: true })\n *\n * // Custom naming\n * createdById: ref('users', { as: 'createdBy', inverse: 'createdDocuments' })\n *\n * // Self-ref (requires roles)\n * parentId: ref('categories', { roles: { parent: 'parent', children: 'children' } })\n * ```\n */\nexport function ref<\n\tconst TTarget extends string,\n\tconst TOptions extends RefOptions = Record<string, never>,\n>(target: TTarget, options?: TOptions): RefDefinition<TTarget, TOptions> {\n\treturn {\n\t\t__brand: 'ref',\n\t\ttarget,\n\t\toptions: options ? normalizeRefOptions(options) : ({} as TOptions),\n\t};\n}\n\n/**\n * Type guard for RefDefinition.\n */\nexport function isRef(\n\tvalue: ColumnDef | RefDefinition,\n): value is RefDefinition {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'__brand' in value &&\n\t\tvalue.__brand === 'ref'\n\t);\n}\n\n/**\n * Creates a type-safe schema definition and converts it to ModelIR.\n *\n * @param definition - Schema definition with tables and columns\n * @returns Schema object with definition, model, and table names\n *\n * @example\n * ```typescript\n * const db = schema({\n * users: {\n * id: 'uuid',\n * email: { type: 'text', unique: true },\n * },\n * posts: {\n * id: 'uuid',\n * title: 'text',\n * authorId: ref('users'),\n * },\n * });\n *\n * // Use with ORM\n * const orm = createOrm({ model: db.model, adapter });\n * ```\n */\nexport function schema<const T extends SchemaDefinition>(\n\tdefinition: T,\n\tconstraints?: SchemaConstraints,\n\toptions?: SchemaOptions,\n\textras?: SchemaExtras,\n): Schema<T> {\n\t// Validate and convert to ModelIR\n\tconst model = schemaToModelIR(definition, constraints, extras, options);\n\tconst tableNames = Object.keys(definition) as (keyof T)[];\n\n\t// Validate default filters reference existing tables\n\tconst defaultFilters = options?.defaultFilters;\n\tif (defaultFilters) {\n\t\tconst tableNameSet = new Set(tableNames as string[]);\n\t\tfor (const tableName of Object.keys(defaultFilters)) {\n\t\t\tif (!tableNameSet.has(tableName)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Default filter for non-existent table '${tableName}'. ` +\n\t\t\t\t\t\t`Available: ${[...tableNameSet].join(', ')}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create type-safe tables proxy (DX-040)\n\tconst tables = createTablesProxy(\n\t\tmodel,\n\t\ttableNames as string[],\n\t) as InferTables<T>;\n\n\treturn {\n\t\tdefinition,\n\t\t...(constraints !== undefined ? { constraints } : {}),\n\t\t...(extras !== undefined ? { extras } : {}),\n\t\t...(options !== undefined ? { options } : {}),\n\t\tmodel,\n\t\ttableNames,\n\t\ttables,\n\t\t...(defaultFilters ? { defaultFilters } : {}),\n\t};\n}\n\n// ============================================================================\n// Conversion to ModelIR\n// ============================================================================\n\n/**\n * Validation error during schema conversion.\n */\nexport class SchemaValidationError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly table?: string,\n\t\tpublic readonly column?: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'SchemaValidationError';\n\t}\n}\n\nexport function validateSchemaIndexOptions(\n\ttableName: string,\n\tidx: SchemaIndexValidationInput,\n): void {\n\tif (idx.nullsNotDistinct === true && idx.unique !== true) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Index \"${idx.name ?? `idx_${tableName}_${idx.columns.join('_')}`}\" on \"${tableName}\" cannot use nullsNotDistinct unless unique is true`,\n\t\t);\n\t}\n}\n\n/**\n * Converts a schema definition to ModelIR.\n *\n * @internal\n */\nexport function schemaToModelIR(\n\tdefinition: SchemaDefinition,\n\tconstraints?: SchemaConstraints,\n\textras?: SchemaExtras,\n\toptions?: SchemaOptions,\n): ModelIR {\n\t// R6-L1: fail-fast before any per-table work. Empty / whitespace-only\n\t// defaultPkColumnName is rejected here (once) rather than per-table in\n\t// inferPrimaryKey, because the error is a schema-level misconfiguration\n\t// and should be reported at the earliest possible point.\n\tif (\n\t\ttypeof options?.defaultPkColumnName === 'string' &&\n\t\toptions.defaultPkColumnName.trim().length === 0\n\t) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`defaultPkColumnName cannot be an empty or whitespace-only string. Pass null to disable the implicit-PK convention or omit the option for the default 'id'.`,\n\t\t);\n\t}\n\n\tconst tableNames = Object.keys(definition);\n\n\t// Phase 1: Validate refs point to existing tables (existence + roles only)\n\tvalidateRefs(definition, tableNames);\n\n\t// Phase 2: Collect all refs and validate constraints\n\tconst refsByTable = collectRefs(definition);\n\n\t// Phase 3: Build tables (columns, PKs, FKs, indexes) — inferPrimaryKey runs here\n\tconst tables = buildTables(\n\t\tdefinition,\n\t\trefsByTable,\n\t\ttableNames,\n\t\tconstraints,\n\t\toptions,\n\t);\n\n\t// Phase 3.5: Validate FK targets exist and are referenceable (post-build, uses resolved PKs)\n\tvalidateFkTargets(tables);\n\n\t// Phase 4: Build relations from refs and table-level composite FK constraints\n\tconst relations = buildRelations(\n\t\tdefinition,\n\t\trefsByTable,\n\t\ttableNames,\n\t\tconstraints,\n\t);\n\n\t// Phase 5: Build ModelIR\n\tconst tableMap = new Map<string, TableIR>();\n\tfor (const table of tables) {\n\t\ttableMap.set(table.name, table);\n\t}\n\n\tconst relationMap = new Map<string, RelationIR>();\n\tfor (const relation of relations) {\n\t\tconst qualifiedName = `${relation.source}.${relation.name}`;\n\t\trelationMap.set(qualifiedName, relation);\n\t}\n\n\t// Phase 6: Build extras (extensions, sequences)\n\tconst extensions = extras?.extensions;\n\tconst sequenceMap = extras?.sequences\n\t\t? new Map(\n\t\t\t\tObject.entries(extras.sequences).map(([name, seq]) => {\n\t\t\t\t\tconst { adopt, ...shape } = seq;\n\t\t\t\t\treturn [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t...shape,\n\t\t\t\t\t\t\t...(adopt === true ? { adopt: true as const } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t];\n\t\t\t\t}),\n\t\t\t)\n\t\t: undefined;\n\n\treturn new ModelIRImpl(\n\t\ttableMap,\n\t\trelationMap,\n\t\tundefined,\n\t\textensions,\n\t\tsequenceMap,\n\t);\n}\n\n// ============================================================================\n// Validation\n// ============================================================================\n\nfunction validateRefs(\n\tdefinition: SchemaDefinition,\n\ttableNames: string[],\n): void {\n\tconst tableSet = new Set(tableNames);\n\n\tfor (const [tableName, tableDef] of Object.entries(definition)) {\n\t\tfor (const [columnName, columnDef] of Object.entries(tableDef)) {\n\t\t\tif (isRef(columnDef)) {\n\t\t\t\t// Check target exists\n\t\t\t\tif (\n\t\t\t\t\t!hasExternalSchema(columnDef.options.schema) &&\n\t\t\t\t\t!tableSet.has(columnDef.target)\n\t\t\t\t) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Foreign key '${columnName}' references non-existent table '${columnDef.target}'`,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tcolumnName,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Self-ref requires roles\n\t\t\t\tif (\n\t\t\t\t\t!hasExternalSchema(columnDef.options.schema) &&\n\t\t\t\t\tcolumnDef.target === tableName &&\n\t\t\t\t\t!columnDef.options.roles\n\t\t\t\t) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Self-referential FK '${columnName}' must have 'roles' option with parent/children names`,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tcolumnName,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Roles only valid for self-ref\n\t\t\t\tif (\n\t\t\t\t\t(hasExternalSchema(columnDef.options.schema) ||\n\t\t\t\t\t\tcolumnDef.target !== tableName) &&\n\t\t\t\t\tcolumnDef.options.roles\n\t\t\t\t) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`'roles' option is only valid for self-referential FKs, but '${columnName}' references '${columnDef.target}'`,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tcolumnName,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * PostgreSQL UNIQUE constraints only support btree and hash index methods.\n * Other methods (gin, gist, brin, spgist, hnsw, bm25, etc.) cannot enforce\n * uniqueness and therefore cannot back a foreign key target column.\n * Treat undefined as 'btree' (the PostgreSQL default).\n */\nconst UNIQUE_CAPABLE_INDEX_METHODS = new Set(['btree', 'hash']);\n\n/**\n * Validates FK target columns exist and are referenceable.\n *\n * For ALL FKs (single-column and composite):\n * - Source and target column counts must match.\n *\n * For local-target FKs:\n * - Every referenced column must exist on the target table.\n *\n * For single-column FKs only (the case `buildRefColumn` produces where both\n * `fk.columns.length === 1` AND `fk.references.columns.length === 1`):\n * - Referenced column must be referenceable: singleton primary key,\n * column-level `unique: true`, or a single-column UNIQUE index declared\n * via SchemaConstraints covering exactly the referenced column with no\n * partial-index `WHERE` clause, no expression columns, and using a\n * uniqueness-capable index method (btree or hash).\n * - Mirrors PostgreSQL error 42830 (\"there is no unique constraint matching\n * given keys for referenced table\") at schema()-time instead of at DDL\n * apply time.\n *\n * Composite PK members alone do not qualify as referenceable (matches PG strict\n * semantics): a column that is part of a composite PK still needs an explicit\n * UNIQUE constraint to be the target of an FK.\n */\nfunction validateFkTargets(tables: readonly TableIR[]): void {\n\tconst tableMap = new Map(tables.map((t) => [t.name, t]));\n\n\tfor (const table of tables) {\n\t\tfor (const fk of table.foreignKeys) {\n\t\t\t// R4-1: Source-column existence — guard against constraint-level FKs that\n\t\t\t// declare `columns: [...]` referencing local columns that don't exist on\n\t\t\t// the source table. Column-level FKs (via buildRefColumn) can't trigger\n\t\t\t// this because the source column IS the column being declared, but\n\t\t\t// SchemaConstraints.foreignKeys does not validate this elsewhere.\n\t\t\tfor (const srcCol of fk.columns) {\n\t\t\t\tif (!table.columns.some((c) => c.name === srcCol)) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Foreign key in '${table.name}' uses non-existent source column '${srcCol}'`,\n\t\t\t\t\t\ttable.name,\n\t\t\t\t\t\tsrcCol,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Validate column counts. Zero-length arrays on either side are malformed\n\t\t\t// and should be flagged here rather than silently passed to PG.\n\t\t\tif (fk.columns.length === 0 || fk.references.columns.length === 0) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Foreign key in '${table.name}' has zero-length \\`columns\\` or \\`references\\` array`,\n\t\t\t\t\ttable.name,\n\t\t\t\t\tfk.columns[0],\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// R6-3a: source and target column counts must match for ALL FKs (composite included).\n\t\t\t// PostgreSQL requires a 1-to-1 mapping between source and referenced columns.\n\t\t\tif (fk.columns.length !== fk.references.columns.length) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Foreign key in '${table.name}' has mismatched column counts: ` +\n\t\t\t\t\t\t`${fk.columns.length} source column(s) but ${fk.references.columns.length} referenced column(s)`,\n\t\t\t\t\ttable.name,\n\t\t\t\t\tfk.columns[0],\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (hasExternalSchema(fk.references.schema)) continue;\n\n\t\t\tconst target = tableMap.get(fk.references.table);\n\t\t\t// Defensive: column-level FKs are pre-validated by validateRefs (Phase 1),\n\t\t\t// but table-level constraints.foreignKeys bypass that — so this gate is\n\t\t\t// the only barrier against constraint-based FKs to non-existent tables.\n\t\t\t// Throw rather than skip silently.\n\t\t\tif (!target) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Foreign key in '${table.name}' references non-existent table '${fk.references.table}'`,\n\t\t\t\t\ttable.name,\n\t\t\t\t\tfk.columns[0],\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// R6-3b: every referenced column must exist on local target tables.\n\t\t\tfor (const refCol of fk.references.columns) {\n\t\t\t\tif (!target.columns.some((c) => c.name === refCol)) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Foreign key in '${table.name}' references non-existent column '${target.name}.${refCol}'`,\n\t\t\t\t\t\ttable.name,\n\t\t\t\t\t\tfk.columns[0],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Uniqueness check is single-column-only — composites left to PostgreSQL.\n\t\t\tif (fk.columns.length !== 1 || fk.references.columns.length !== 1)\n\t\t\t\tcontinue;\n\n\t\t\tfor (const refCol of fk.references.columns) {\n\t\t\t\t// Existence already validated by R6-3b above for all FKs — targetCol is guaranteed defined here.\n\t\t\t\tconst targetCol = target.columns.find((c) => c.name === refCol);\n\t\t\t\tif (!targetCol) continue; // defensive\n\t\t\t\t// Uniqueness — a column is referenceable when any of the following holds:\n\t\t\t\t// 1. It is the table's singleton resolved primaryKey (covers explicit column-level PK,\n\t\t\t\t// table-level singleton PK, and the implicit-id convention resolved by inferPrimaryKey).\n\t\t\t\t// 2. It has explicit `unique: true`.\n\t\t\t\t// 3. It is the sole column of a non-partial, non-expression single-column UNIQUE index\n\t\t\t\t// declared via SchemaConstraints (partial indexes with a WHERE clause, or expression\n\t\t\t\t// indexes, do NOT make a column referenceable — PG error 42830).\n\t\t\t\t// Members of a composite PK alone do not qualify (matches PG strict semantics).\n\t\t\t\tconst isSingletonPk =\n\t\t\t\t\ttypeof target.primaryKey === 'string' && target.primaryKey === refCol;\n\t\t\t\tconst isUnique = targetCol.unique === true;\n\t\t\t\t// R2-F2: PG only allows UNIQUE constraints on btree/hash indexes —\n\t\t\t\t// gin/gist/brin/spgist/hnsw/bm25 cannot enforce uniqueness even when\n\t\t\t\t// `unique: true` is declared. Fail at schema() time instead of DDL apply.\n\t\t\t\tconst isUniqueIndex =\n\t\t\t\t\ttarget.indexes?.some((idx) => {\n\t\t\t\t\t\tconst method = idx.method ?? 'btree';\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tidx.unique === true &&\n\t\t\t\t\t\t\tidx.columns.length === 1 &&\n\t\t\t\t\t\t\tidx.columns[0] === refCol &&\n\t\t\t\t\t\t\tidx.where === undefined &&\n\t\t\t\t\t\t\t(idx.expressions === undefined || idx.expressions.length === 0) &&\n\t\t\t\t\t\t\tUNIQUE_CAPABLE_INDEX_METHODS.has(method)\n\t\t\t\t\t\t);\n\t\t\t\t\t}) ?? false;\n\t\t\t\tif (!isSingletonPk && !isUnique && !isUniqueIndex) {\n\t\t\t\t\t// R2-F1: tailor the remediation hint based on the target's PK shape.\n\t\t\t\t\t// - composite PK (string[]): no single PK column to target; suggest\n\t\t\t\t\t// marking unique or using a table-level composite FK.\n\t\t\t\t\t// - resolved single PK (string): point at the existing PK column.\n\t\t\t\t\t// - no PK at all: suggest the defaultPkColumnName convention.\n\t\t\t\t\tconst isCompositePk = Array.isArray(target.primaryKey);\n\t\t\t\t\tconst hasSingleResolvedPk = typeof target.primaryKey === 'string';\n\t\t\t\t\tconst suggestion = isCompositePk\n\t\t\t\t\t\t? `Either mark '${target.name}.${refCol}' with \\`unique: true\\` or add a single-column unique index via SchemaConstraints — '${target.name}' has a composite primary key, so a single-column FK cannot target the PK directly (use a table-level composite FK referencing all PK columns if that is the intent).`\n\t\t\t\t\t\t: hasSingleResolvedPk\n\t\t\t\t\t\t\t? `Either mark the target column with \\`unique: true\\`, add a single-column unique index via SchemaConstraints, or change the FK to target the existing primary key column '${target.primaryKey as string}'.`\n\t\t\t\t\t\t\t: `Either mark the target column with \\`unique: true\\`, add a single-column unique index via SchemaConstraints, or — if '${refCol}' is your primary-key column convention — pass \\`{ defaultPkColumnName: '${refCol}' }\\` as the third argument to \\`schema()\\` (or omit the option entirely if '${refCol}' is 'id').`;\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Foreign key in '${table.name}' targets '${target.name}.${refCol}' which is neither primary key nor unique. ${suggestion}`,\n\t\t\t\t\t\ttable.name,\n\t\t\t\t\t\tfk.columns[0],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Collected ref info for a table.\n */\ninterface CollectedRef {\n\tcolumnName: string;\n\ttarget: string;\n\toptions: RefOptions;\n\tlocalRelation: string; // Derived relation name\n\tinverseRelation: string; // Derived inverse relation name\n}\n\n/**\n * Collects refs per table and validates multi-FK constraints.\n */\nfunction collectRefs(\n\tdefinition: SchemaDefinition,\n): Map<string, CollectedRef[]> {\n\tconst refsByTable = new Map<string, CollectedRef[]>();\n\n\tfor (const [tableName, tableDef] of Object.entries(definition)) {\n\t\tconst refs: CollectedRef[] = [];\n\t\tconst refsByTarget = new Map<string, string[]>(); // target -> column names\n\n\t\tfor (const [columnName, columnDef] of Object.entries(tableDef)) {\n\t\t\tif (isRef(columnDef)) {\n\t\t\t\t// Track refs by target for multi-FK validation\n\t\t\t\tconst existing = refsByTarget.get(columnDef.target) || [];\n\t\t\t\texisting.push(columnName);\n\t\t\t\trefsByTarget.set(columnDef.target, existing);\n\n\t\t\t\t// Derive relation names\n\t\t\t\tconst localRelation = deriveLocalRelation(\n\t\t\t\t\tcolumnName,\n\t\t\t\t\tcolumnDef.options,\n\t\t\t\t);\n\t\t\t\tconst inverseRelation = deriveInverseRelation(\n\t\t\t\t\tlocalRelation,\n\t\t\t\t\ttableName,\n\t\t\t\t\tcolumnDef.options,\n\t\t\t\t\tcolumnDef.target === tableName,\n\t\t\t\t);\n\n\t\t\t\trefs.push({\n\t\t\t\t\tcolumnName,\n\t\t\t\t\ttarget: columnDef.target,\n\t\t\t\t\toptions: columnDef.options,\n\t\t\t\t\tlocalRelation,\n\t\t\t\t\tinverseRelation,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Validate multi-FK to same table requires explicit naming\n\t\tfor (const [target, columns] of refsByTarget) {\n\t\t\tif (columns.length > 1 && target !== tableName) {\n\t\t\t\t// Multiple FKs to same non-self table - all must have 'as'\n\t\t\t\tfor (const columnName of columns) {\n\t\t\t\t\tconst ref = refs.find((r) => r.columnName === columnName);\n\t\t\t\t\tif (ref && !ref.options.as) {\n\t\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t\t`Multiple FKs to '${target}' require explicit 'as' naming. Column '${columnName}' has no 'as' option.`,\n\t\t\t\t\t\t\ttableName,\n\t\t\t\t\t\t\tcolumnName,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check for duplicate relation names within this table\n\t\tconst seenRelations = new Set<string>();\n\t\tfor (const ref of refs) {\n\t\t\tif (ref.options.roles) {\n\t\t\t\t// Self-ref - check all role names\n\t\t\t\tconst roles = ref.options.roles;\n\t\t\t\tconst allNames = [\n\t\t\t\t\troles.parent,\n\t\t\t\t\troles.children,\n\t\t\t\t\troles.ancestors || 'ancestors',\n\t\t\t\t\troles.descendants || 'descendants',\n\t\t\t\t];\n\t\t\t\tfor (const name of allNames) {\n\t\t\t\t\tif (seenRelations.has(name)) {\n\t\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t\t`Duplicate relation name '${name}'`,\n\t\t\t\t\t\t\ttableName,\n\t\t\t\t\t\t\tref.columnName,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tseenRelations.add(name);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (seenRelations.has(ref.localRelation)) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Duplicate relation name '${ref.localRelation}'`,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tref.columnName,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tseenRelations.add(ref.localRelation);\n\t\t\t}\n\t\t}\n\n\t\trefsByTable.set(tableName, refs);\n\t}\n\n\treturn refsByTable;\n}\n\n// ============================================================================\n// Naming Derivation\n// ============================================================================\n\n/**\n * Derives local relation name from column name.\n * authorId -> author, user_id -> user\n */\nfunction deriveLocalRelation(columnName: string, options: RefOptions): string {\n\tif (options.as) {\n\t\treturn options.as;\n\t}\n\n\t// Remove 'Id' suffix (camelCase)\n\tif (columnName.endsWith('Id')) {\n\t\treturn columnName.slice(0, -2);\n\t}\n\n\t// Remove '_id' suffix (snake_case - shouldn't happen but handle it)\n\tif (columnName.endsWith('_id')) {\n\t\treturn columnName.slice(0, -3);\n\t}\n\n\t// Fallback: use column name as-is\n\treturn columnName;\n}\n\n/**\n * Derives inverse relation name.\n * Default pattern: {localRelation}_{tableName}\n */\nfunction deriveInverseRelation(\n\tlocalRelation: string,\n\tsourceTable: string,\n\toptions: RefOptions,\n\tisSelfRef: boolean,\n): string {\n\t// Self-ref doesn't use standard inverse naming\n\tif (isSelfRef) {\n\t\treturn ''; // Handled via roles\n\t}\n\n\tif (options.inverse) {\n\t\treturn options.inverse;\n\t}\n\n\t// Pattern: author -> author_posts (for source table 'posts')\n\treturn `${localRelation}_${sourceTable}`;\n}\n\n// ============================================================================\n// Table Building\n// ============================================================================\n\n/**\n * Returns the ColumnType of the primary key in the target table definition.\n * Falls back to 'uuid' if the target is not found or has no explicit PK.\n */\nfunction getTargetPkType(\n\tdefinition: SchemaDefinition,\n\ttarget: string,\n): ColumnType {\n\tconst targetDef = definition[target];\n\tif (!targetDef) return 'uuid';\n\n\tfor (const [, colDef] of Object.entries(targetDef)) {\n\t\tif (isRef(colDef)) continue;\n\t\tconst def = normalizeColumnDef(colDef);\n\t\tif (def.primaryKey) return def.type;\n\t}\n\n\tif ('id' in targetDef) {\n\t\tconst idDef = targetDef.id;\n\t\tif (idDef && !isRef(idDef)) return normalizeColumnDef(idDef).type;\n\t}\n\treturn 'uuid';\n}\n\n/**\n * Returns the ColumnType for a specific named column in a target table definition.\n * Used by buildRefColumn to derive the source column type when `references` points\n * to a non-PK unique column. Falls back to `undefined` when the column is not found\n * or is itself a ref (chain case handled by getTargetPkType).\n */\nfunction getReferencedColumnType(\n\ttargetDef: TableDef,\n\treferencedCol: string,\n\tdefinition?: SchemaDefinition,\n\tvisited?: Set<string>,\n): ColumnType | undefined {\n\tconst colDef = targetDef[referencedCol];\n\tif (!colDef) return undefined;\n\tif (isRef(colDef)) {\n\t\t// R6-5 (chained ref): follow the chain to resolve the final concrete type.\n\t\t// Guard against cycles and runaway chains with a visited-key accumulator.\n\t\tif (!definition) return undefined;\n\t\tconst chainedTableName = colDef.target;\n\t\tconst chainedTargetDef = definition[chainedTableName];\n\t\tif (!chainedTargetDef) return undefined;\n\t\t// The chained ref's referenced column: options.references[0] ?? 'id'\n\t\tconst chainedRefCols = colDef.options.references;\n\t\tconst firstChainedRefCol =\n\t\t\tchainedRefCols && chainedRefCols.length === 1\n\t\t\t\t? chainedRefCols[0]\n\t\t\t\t: undefined;\n\t\tconst chainedRefCol: string = firstChainedRefCol ?? 'id';\n\t\t// Visited key uniquely identifies the (tableDef, column) pair in the chain.\n\t\tconst visitedKey = `${chainedTableName}.${chainedRefCol}`;\n\t\tconst seen = visited ?? new Set<string>();\n\t\tif (seen.has(visitedKey)) return undefined; // cycle detected\n\t\tseen.add(visitedKey);\n\t\treturn getReferencedColumnType(\n\t\t\tchainedTargetDef,\n\t\t\tchainedRefCol,\n\t\t\tdefinition,\n\t\t\tseen,\n\t\t);\n\t}\n\treturn normalizeColumnDef(colDef).type;\n}\n\n/**\n * Builds a FK column + ForeignKeyIR pair from a ref definition.\n */\nfunction buildRefColumn(\n\tcolumnName: string,\n\tcolumnDef: RefDefinition,\n\tdefinition: SchemaDefinition,\n): { col: ColumnIR; fk: ForeignKeyIR } {\n\t// R5-1: When options.references specifies a single target column, derive the\n\t// source column type from THAT column's type rather than the target's PK type.\n\t// This prevents a type mismatch when the FK points at a unique non-PK column\n\t// that has a different type than the table's PK (e.g. email:string vs id:uuid).\n\tconst targetDef = definition[columnDef.target];\n\tconst externalSchema = normalizeReferenceSchema(columnDef.options.schema);\n\tif (externalSchema !== undefined) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Cannot infer column type for foreign key column '${columnName}' to external table '${externalSchema}.${columnDef.target}'. Declare the source column with an explicit type and add the external foreign key at the table level with SchemaConstraints.foreignKeys.`,\n\t\t\tundefined,\n\t\t\tcolumnName,\n\t\t);\n\t}\n\tconst targetCol =\n\t\tcolumnDef.options.references?.length === 1\n\t\t\t? columnDef.options.references[0]\n\t\t\t: undefined;\n\tconst inferredType =\n\t\ttargetCol && targetDef\n\t\t\t? (getReferencedColumnType(targetDef, targetCol, definition) ??\n\t\t\t\tgetTargetPkType(definition, columnDef.target))\n\t\t\t: getTargetPkType(definition, columnDef.target);\n\tconst col: Mutable<ColumnIR> = {\n\t\tname: columnName,\n\t\ttype: inferredType,\n\t\tnullable: columnDef.options.nullable ?? false,\n\t};\n\tif (columnDef.options.js !== undefined) {\n\t\tvalidateColumnJsReadType(columnName, inferredType, columnDef.options.js);\n\t\tcol.js = columnDef.options.js;\n\t}\n\tif (columnDef.options.unique) col.unique = true;\n\n\tif (\n\t\tcolumnDef.options.references &&\n\t\tcolumnDef.options.references.length !== 1\n\t) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`FK column '${columnName}' got 'references' with ${columnDef.options.references.length} columns; column-level FK requires exactly one target column (use table-level foreignKeys for composite FKs).`,\n\t\t);\n\t}\n\tconst fk: Mutable<ForeignKeyIR> = {\n\t\tcolumns: [columnName],\n\t\treferences: {\n\t\t\ttable: columnDef.target,\n\t\t\tcolumns: columnDef.options.references ?? ['id'],\n\t\t\t...(externalSchema !== undefined ? { schema: externalSchema } : {}),\n\t\t},\n\t};\n\tif (columnDef.options.onDelete) fk.onDelete = columnDef.options.onDelete;\n\tif (columnDef.options.onUpdate) fk.onUpdate = columnDef.options.onUpdate;\n\n\treturn { col: col as ColumnIR, fk: fk as ForeignKeyIR };\n}\n\n/**\n * Builds a regular ColumnIR from a normalized column definition.\n */\nfunction buildRegularColumn(\n\tcolumnName: string,\n\tcolumnDef: ColumnDef,\n): { col: ColumnIR; isPk: boolean } {\n\tconst def = normalizeColumnDef(columnDef);\n\tconst col: Mutable<ColumnIR> = {\n\t\tname: columnName,\n\t\ttype: def.type,\n\t\tnullable: def.nullable ?? false,\n\t};\n\tif (def.js !== undefined) {\n\t\tvalidateColumnJsReadType(columnName, def.type, def.js);\n\t\tcol.js = def.js;\n\t}\n\tif (def.dbType?.trim()) col.originalDbType = def.dbType.trim();\n\tif (def.unique) col.unique = def.unique;\n\tif (def.autoIncrement) col.autoIncrement = def.autoIncrement;\n\tif (def.default !== undefined) col.default = def.default;\n\treturn { col: col as ColumnIR, isPk: def.primaryKey ?? false };\n}\n\n/**\n * Builds columns, foreign keys, and explicit primary key list for a table.\n */\nfunction buildColumnsForTable(\n\t_tableName: string,\n\ttableDef: TableDef,\n\tdefinition: SchemaDefinition,\n): { columns: ColumnIR[]; foreignKeys: ForeignKeyIR[]; primaryKey: string[] } {\n\tconst columns: ColumnIR[] = [];\n\tconst foreignKeys: ForeignKeyIR[] = [];\n\tconst primaryKey: string[] = [];\n\n\tfor (const [columnName, columnDef] of Object.entries(tableDef)) {\n\t\tif (isRef(columnDef)) {\n\t\t\tconst { col, fk } = buildRefColumn(columnName, columnDef, definition);\n\t\t\tcolumns.push(col);\n\t\t\tforeignKeys.push(fk);\n\t\t} else {\n\t\t\tconst { col, isPk } = buildRegularColumn(columnName, columnDef);\n\t\t\tcolumns.push(col);\n\t\t\tif (isPk) primaryKey.push(columnName);\n\t\t}\n\t}\n\treturn { columns, foreignKeys, primaryKey };\n}\n\n/**\n * Infers the final primary key from explicit declarations, the implicit-PK name\n * convention, or FK columns (for junction tables).\n *\n * Resolution order:\n * 1. Explicit `primaryKey: true` on column(s)\n * 2. Column matching `defaultPkColumnName` (options.defaultPkColumnName) — skipped\n * when set to `null` (strict mode)\n * 3. FK columns (composite PK for junction tables — applies regardless of option)\n * 4. No primary key\n */\nfunction inferPrimaryKey(\n\tprimaryKey: string[],\n\tforeignKeys: ForeignKeyIR[],\n\tcolumns: ColumnIR[],\n\toptions?: { defaultPkColumnName?: string | null },\n): string | readonly string[] | undefined {\n\tif (primaryKey.length > 0) {\n\t\treturn primaryKey.length === 1 ? (primaryKey[0] as string) : primaryKey;\n\t}\n\t// Implicit PK convention BEFORE FK fallback. Honoured unless explicitly\n\t// disabled with `defaultPkColumnName: null`. Empty/whitespace-only strings\n\t// are rejected at schemaToModelIR() time (R6-L1 guard fires before this runs).\n\tconst pkColName =\n\t\toptions?.defaultPkColumnName === undefined\n\t\t\t? 'id'\n\t\t\t: options.defaultPkColumnName;\n\tif (pkColName !== null && columns.some((c) => c.name === pkColName)) {\n\t\treturn pkColName;\n\t}\n\t// FK fallback for junction tables (applies regardless of the option above).\n\tconst fkColumns = foreignKeys.flatMap((fk) => fk.columns);\n\tif (fkColumns.length > 0) {\n\t\treturn fkColumns.length === 1 ? fkColumns[0] : fkColumns;\n\t}\n\treturn undefined;\n}\n\n/**\n * Builds pseudo-columns for self-referential FKs with roles.\n */\nfunction buildPseudoColumns(\n\ttableName: string,\n\trefsByTable: Map<string, CollectedRef[]>,\n\tfinalPk: string | readonly string[] | undefined,\n): PseudoColumnMetadata[] {\n\tconst pseudoColumns: PseudoColumnMetadata[] = [];\n\tconst refs = refsByTable.get(tableName) ?? [];\n\tconst pkColumn =\n\t\ttypeof finalPk === 'string' ? finalPk : (finalPk?.[0] ?? 'id');\n\n\tfor (const ref of refs) {\n\t\tif (\n\t\t\t!hasExternalSchema(ref.options.schema) &&\n\t\t\tref.options.roles &&\n\t\t\tref.target === tableName\n\t\t) {\n\t\t\tpseudoColumns.push(\n\t\t\t\tcreatePseudoColumnMetadata(\n\t\t\t\t\ttableName,\n\t\t\t\t\tref.columnName,\n\t\t\t\t\tpkColumn,\n\t\t\t\t\tref.options.roles.parent,\n\t\t\t\t\tref.options.roles.children,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn pseudoColumns;\n}\n\n/**\n * Builds IndexIR entries from column-level `index: true` declarations.\n */\nfunction buildColumnIndexes(tableName: string, tableDef: TableDef): IndexIR[] {\n\tconst indexes: IndexIR[] = [];\n\tfor (const [columnName, columnDef] of Object.entries(tableDef)) {\n\t\tif (isRef(columnDef)) continue;\n\t\tconst def = normalizeColumnDef(columnDef);\n\t\tif (def.index) {\n\t\t\tindexes.push({\n\t\t\t\tname: `idx_${tableName}_${columnName}`,\n\t\t\t\tcolumns: [columnName],\n\t\t\t\tunique: false,\n\t\t\t});\n\t\t}\n\t}\n\treturn indexes;\n}\n\n/**\n * Processes table-level constraints (indexes, CHECK constraints, composite FKs).\n */\nfunction buildTableConstraints(\n\ttableName: string,\n\tconstraints: SchemaConstraints | undefined,\n): {\n\textraIndexes: IndexIR[];\n\tcheckConstraints: CheckConstraintIR[];\n\textraForeignKeys: ForeignKeyIR[];\n} {\n\tconst extraIndexes: IndexIR[] = [];\n\tconst checkConstraints: CheckConstraintIR[] = [];\n\tconst extraForeignKeys: ForeignKeyIR[] = [];\n\n\tconst tableConstraints = constraints?.[tableName];\n\tif (!tableConstraints) {\n\t\treturn { extraIndexes, checkConstraints, extraForeignKeys };\n\t}\n\n\tif (tableConstraints.indexes) {\n\t\tfor (const idx of tableConstraints.indexes) {\n\t\t\tvalidateSchemaIndexOptions(tableName, idx);\n\t\t\tconst indexIR: Mutable<IndexIR> = {\n\t\t\t\tname: idx.name ?? `idx_${tableName}_${idx.columns.join('_')}`,\n\t\t\t\tcolumns: idx.columns,\n\t\t\t\tunique: idx.unique ?? false,\n\t\t\t};\n\t\t\tif (idx.nullsNotDistinct !== undefined) {\n\t\t\t\tindexIR.nullsNotDistinct = idx.nullsNotDistinct;\n\t\t\t}\n\t\t\tif (idx.method) indexIR.method = idx.method;\n\t\t\tif (idx.where) indexIR.where = idx.where;\n\t\t\tif (idx.include !== undefined) indexIR.include = idx.include;\n\t\t\tif (idx.opclass) indexIR.opclass = idx.opclass;\n\t\t\tif (idx.with) indexIR.with = idx.with;\n\t\t\textraIndexes.push(indexIR as IndexIR);\n\t\t}\n\t}\n\n\tif (tableConstraints.checkConstraints) {\n\t\tfor (const chk of tableConstraints.checkConstraints) {\n\t\t\tcheckConstraints.push({\n\t\t\t\tname: chk.name,\n\t\t\t\texpression: `CHECK (${chk.expression})`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (tableConstraints.foreignKeys) {\n\t\tfor (const fkRef of tableConstraints.foreignKeys) {\n\t\t\tif (fkRef.options.js !== undefined) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Table-level foreignKeys cannot use 'js'; declare js on a column-level ref() instead.`,\n\t\t\t\t\ttableName,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!fkRef.options.columns?.length) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Composite FK on \"${tableName}\" → \"${fkRef.target}\" requires 'columns' option`,\n\t\t\t\t\ttableName,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst externalSchema = normalizeReferenceSchema(fkRef.options.schema);\n\t\t\tconst fk: Mutable<ForeignKeyIR> = {\n\t\t\t\tcolumns: [...fkRef.options.columns],\n\t\t\t\treferences: {\n\t\t\t\t\ttable: fkRef.target,\n\t\t\t\t\tcolumns: fkRef.options.references\n\t\t\t\t\t\t? [...fkRef.options.references]\n\t\t\t\t\t\t: ['id'],\n\t\t\t\t\t...(externalSchema !== undefined ? { schema: externalSchema } : {}),\n\t\t\t\t},\n\t\t\t};\n\t\t\tif (fkRef.options.onDelete) fk.onDelete = fkRef.options.onDelete;\n\t\t\tif (fkRef.options.onUpdate) fk.onUpdate = fkRef.options.onUpdate;\n\t\t\textraForeignKeys.push(fk as ForeignKeyIR);\n\t\t}\n\t}\n\n\treturn { extraIndexes, checkConstraints, extraForeignKeys };\n}\n\n/**\n * Builds TableIR objects from schema definition.\n */\nfunction buildTables(\n\tdefinition: SchemaDefinition,\n\trefsByTable: Map<string, CollectedRef[]>,\n\ttableNames: string[],\n\tconstraints?: SchemaConstraints,\n\toptions?: SchemaOptions,\n): TableIR[] {\n\tconst tables: TableIR[] = [];\n\n\tfor (const tableName of tableNames) {\n\t\tconst tableDef = definition[tableName];\n\t\tif (!tableDef) continue;\n\t\tconst lifecycleDirectives = [\n\t\t\tconstraints?.[tableName]?.adopt === true ? 'adopt' : undefined,\n\t\t\tconstraints?.[tableName]?.replace === true ? 'replace' : undefined,\n\t\t\tconstraints?.[tableName]?.readdress === undefined\n\t\t\t\t? undefined\n\t\t\t\t: 'readdress',\n\t\t].filter((directive): directive is string => directive !== undefined);\n\t\tif (lifecycleDirectives.length > 1)\n\t\t\tthrow new Error(\n\t\t\t\t`schema table ${tableName} cannot set more than one lifecycle directive (${lifecycleDirectives.join(', ')})`,\n\t\t\t);\n\n\t\tconst { columns, foreignKeys, primaryKey } = buildColumnsForTable(\n\t\t\ttableName,\n\t\t\ttableDef,\n\t\t\tdefinition,\n\t\t);\n\t\tconst finalPk = inferPrimaryKey(primaryKey, foreignKeys, columns, options);\n\t\tconst pseudoColumns = buildPseudoColumns(tableName, refsByTable, finalPk);\n\t\tconst columnIndexes = buildColumnIndexes(tableName, tableDef);\n\t\tconst { extraIndexes, checkConstraints, extraForeignKeys } =\n\t\t\tbuildTableConstraints(tableName, constraints);\n\n\t\tconst table: TableIR = {\n\t\t\tname: tableName,\n\t\t\t...(constraints?.[tableName]?.adopt === true\n\t\t\t\t? { adopt: true as const }\n\t\t\t\t: {}),\n\t\t\t...(constraints?.[tableName]?.replace === true\n\t\t\t\t? { replace: true as const }\n\t\t\t\t: {}),\n\t\t\t...(constraints?.[tableName]?.readdress\n\t\t\t\t? { readdress: constraints[tableName].readdress }\n\t\t\t\t: {}),\n\t\t\tcolumns,\n\t\t\t...(finalPk !== undefined ? { primaryKey: finalPk } : {}),\n\t\t\tforeignKeys: [...foreignKeys, ...extraForeignKeys],\n\t\t\tindexes: [...columnIndexes, ...extraIndexes],\n\t\t\t...(checkConstraints.length > 0 ? { checkConstraints } : {}),\n\t\t\t...(pseudoColumns.length > 0 ? { pseudoColumns } : {}),\n\t\t};\n\t\ttables.push(table);\n\t}\n\n\treturn tables;\n}\n\n/**\n * Normalizes column definition to object form.\n */\nfunction normalizeColumnDef(def: ColumnDef): {\n\ttype: SchemaColumnType;\n\tjs?: ColumnJsReadType;\n\tdbType?: string;\n\tnullable?: boolean;\n\tunique?: boolean;\n\tprimaryKey?: boolean;\n\tautoIncrement?: boolean;\n\tdefault?: unknown;\n\tindex?: boolean;\n} {\n\tif (typeof def === 'string') {\n\t\treturn { type: def };\n\t}\n\treturn def;\n}\n\nfunction formatJsReadType(js: unknown): string {\n\treturn typeof js === 'string' ? js : String(js);\n}\n\nfunction validateColumnJsReadType(\n\tcolumnName: string,\n\tcolumnType: ColumnType,\n\tjs: unknown,\n): asserts js is ColumnJsReadType {\n\tif (js !== 'bigint' && js !== 'number' && js !== 'string') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`column '${columnName}': invalid \\`js\\` value '${formatJsReadType(js)}'; expected 'bigint' | 'number' | 'string'`,\n\t\t\tundefined,\n\t\t\tcolumnName,\n\t\t);\n\t}\n\tif (columnType !== 'bigint') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`column '${columnName}': \\`js\\` read type is only valid on \\`type: 'bigint'\\` columns (got type '${columnType}')`,\n\t\t\tundefined,\n\t\t\tcolumnName,\n\t\t);\n\t}\n}\n\n// ============================================================================\n// Relation Building\n// ============================================================================\n\n/**\n * Builds RelationIR objects from collected refs.\n */\nfunction buildRelations(\n\t_definition: SchemaDefinition,\n\trefsByTable: Map<string, CollectedRef[]>,\n\ttableNames: string[],\n\tconstraints?: SchemaConstraints,\n): RelationIR[] {\n\tconst relations: RelationIR[] = [];\n\n\tfor (const tableName of tableNames) {\n\t\tconst refs = refsByTable.get(tableName) || [];\n\n\t\tfor (const ref of refs) {\n\t\t\t// RelationIR has no schema field; schema-qualified refs are DDL FKs only.\n\t\t\tif (hasExternalSchema(ref.options.schema)) continue;\n\n\t\t\tif (ref.options.roles) {\n\t\t\t\t// Self-referential - generate 4 relations\n\t\t\t\tconst roles = ref.options.roles;\n\n\t\t\t\t// 1. Direct parent (belongsTo)\n\t\t\t\trelations.push({\n\t\t\t\t\tname: roles.parent,\n\t\t\t\t\ttype: 'belongsTo',\n\t\t\t\t\tsource: tableName,\n\t\t\t\t\ttarget: tableName,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: 'one',\n\t\t\t\t\toptionality: ref.options.nullable ? 'optional' : 'required',\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t});\n\n\t\t\t\t// 2. Direct children (hasMany)\n\t\t\t\trelations.push({\n\t\t\t\t\tname: roles.children,\n\t\t\t\t\ttype: 'hasMany',\n\t\t\t\t\tsource: tableName,\n\t\t\t\t\ttarget: tableName,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: 'many',\n\t\t\t\t\toptionality: 'optional', // Children are always optional\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t});\n\n\t\t\t\t// 3. Recursive ancestors (hasMany with recursive metadata)\n\t\t\t\tconst ancestorsName = roles.ancestors || 'ancestors';\n\t\t\t\trelations.push({\n\t\t\t\t\tname: ancestorsName,\n\t\t\t\t\ttype: 'hasMany',\n\t\t\t\t\tsource: tableName,\n\t\t\t\t\ttarget: tableName,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: 'many',\n\t\t\t\t\toptionality: 'optional',\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t\trecursive: {\n\t\t\t\t\t\tdirection: 'up',\n\t\t\t\t\t\tmaxDepth: 10,\n\t\t\t\t\t\tthrough: roles.parent,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// 4. Recursive descendants (hasMany with recursive metadata)\n\t\t\t\tconst descendantsName = roles.descendants || 'descendants';\n\t\t\t\trelations.push({\n\t\t\t\t\tname: descendantsName,\n\t\t\t\t\ttype: 'hasMany',\n\t\t\t\t\tsource: tableName,\n\t\t\t\t\ttarget: tableName,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: 'many',\n\t\t\t\t\toptionality: 'optional',\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t\trecursive: {\n\t\t\t\t\t\tdirection: 'down',\n\t\t\t\t\t\tmaxDepth: 10,\n\t\t\t\t\t\tthrough: roles.children,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Standard relation - generate belongsTo and inverse hasMany/hasOne\n\t\t\t\tconst isUnique = ref.options.unique ?? false;\n\n\t\t\t\t// 1. belongsTo from source to target\n\t\t\t\trelations.push({\n\t\t\t\t\tname: ref.localRelation,\n\t\t\t\t\ttype: 'belongsTo',\n\t\t\t\t\tsource: tableName,\n\t\t\t\t\ttarget: ref.target,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: 'one',\n\t\t\t\t\toptionality: ref.options.nullable ? 'optional' : 'required',\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t});\n\n\t\t\t\t// 2. Inverse relation from target to source\n\t\t\t\tconst inverseType: RelationType = isUnique ? 'hasOne' : 'hasMany';\n\t\t\t\tconst inverseCardinality = isUnique ? 'one' : 'many';\n\n\t\t\t\trelations.push({\n\t\t\t\t\tname: ref.inverseRelation,\n\t\t\t\t\ttype: inverseType,\n\t\t\t\t\tsource: ref.target,\n\t\t\t\t\ttarget: tableName,\n\t\t\t\t\tforeignKey: ref.columnName,\n\t\t\t\t\tcardinality: inverseCardinality,\n\t\t\t\t\toptionality: 'optional', // Inverse is always optional\n\t\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\t\tjoinDefault: 'auto',\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\taddCompositeConstraintRelations(relations, tableNames, constraints);\n\n\treturn relations;\n}\n\nfunction relationKey(source: string, name: string): string {\n\treturn `${source}.${name}`;\n}\n\nfunction pushRelationIfAbsent(\n\trelations: RelationIR[],\n\trelationKeys: Set<string>,\n\trelation: RelationIR,\n): void {\n\tconst key = relationKey(relation.source, relation.name);\n\tif (relationKeys.has(key)) return;\n\trelationKeys.add(key);\n\trelations.push(relation);\n}\n\nfunction deriveCompositeConstraintRelationName(\n\tfkColumn: string,\n\toptions: RefOptions,\n): string {\n\treturn deriveLocalRelation(fkColumn, options);\n}\n\nfunction addCompositeConstraintRelations(\n\trelations: RelationIR[],\n\ttableNames: readonly string[],\n\tconstraints?: SchemaConstraints,\n): void {\n\tif (!constraints) return;\n\n\tconst tableSet = new Set(tableNames);\n\tconst relationKeys = new Set(\n\t\trelations.map((relation) => relationKey(relation.source, relation.name)),\n\t);\n\n\tfor (const tableName of tableNames) {\n\t\tconst foreignKeys = constraints[tableName]?.foreignKeys;\n\t\tif (!foreignKeys) continue;\n\n\t\tfor (const fkRef of foreignKeys) {\n\t\t\tif (hasExternalSchema(fkRef.options.schema)) continue;\n\t\t\tif (!tableSet.has(fkRef.target)) continue;\n\n\t\t\tconst columns = fkRef.options.columns;\n\t\t\tif (!columns?.length) continue;\n\t\t\tconst references = fkRef.options.references ?? ['id'];\n\n\t\t\t// Column-level ref() already derives navigable single-column relations.\n\t\t\tif (columns.length === 1 && references.length === 1) continue;\n\n\t\t\tconst foreignKey = [...columns];\n\t\t\tconst referencedKey = [...references];\n\t\t\tconst belongsToName = deriveCompositeConstraintRelationName(\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: foreignKey copies columns whose length is guaranteed >= 1 by the \"if (!columns?.length) continue;\" guard above\n\t\t\t\tforeignKey[0]!,\n\t\t\t\tfkRef.options,\n\t\t\t);\n\t\t\tconst inverseName = fkRef.options.inverse ?? tableName;\n\t\t\tconst isUnique = fkRef.options.unique ?? false;\n\t\t\tconst inverseType: RelationType = isUnique ? 'hasOne' : 'hasMany';\n\t\t\tconst inverseCardinality = isUnique ? 'one' : 'many';\n\n\t\t\tpushRelationIfAbsent(relations, relationKeys, {\n\t\t\t\tname: belongsToName,\n\t\t\t\ttype: 'belongsTo',\n\t\t\t\tsource: tableName,\n\t\t\t\ttarget: fkRef.target,\n\t\t\t\tforeignKey,\n\t\t\t\ttargetKey: referencedKey,\n\t\t\t\tcardinality: 'one',\n\t\t\t\toptionality: fkRef.options.nullable ? 'optional' : 'required',\n\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\tjoinDefault: 'auto',\n\t\t\t});\n\n\t\t\tpushRelationIfAbsent(relations, relationKeys, {\n\t\t\t\tname: inverseName,\n\t\t\t\ttype: inverseType,\n\t\t\t\tsource: fkRef.target,\n\t\t\t\ttarget: tableName,\n\t\t\t\tforeignKey,\n\t\t\t\tsourceKey: referencedKey,\n\t\t\t\tcardinality: inverseCardinality,\n\t\t\t\toptionality: 'optional',\n\t\t\t\tincludeStrategy: 'auto',\n\t\t\t\tfilterStrategy: 'auto',\n\t\t\t\tjoinDefault: 'auto',\n\t\t\t});\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Database Introspection → Schema\n// ============================================================================\n\n/**\n * Options for getSchemaFromDb.\n */\nexport interface GetSchemaFromDbOptions {\n\t/** Schema name to introspect (default: 'public' for PostgreSQL) */\n\treadonly schema?: string;\n\t/** Tables to include (default: all). */\n\treadonly tables?: readonly string[];\n\t/** Tables to exclude (glob patterns supported). */\n\treadonly exclude?: readonly string[];\n}\n\n/**\n * Map ColumnType from ModelIR to JS-friendly runtime type strings.\n * Used by getSchemaFromDb to create user-friendly schema definitions.\n *\n * Tests expect: 'serial/integer' → 'number', 'varchar/text' → 'string'\n */\nfunction columnTypeToJsType(type: ColumnType): SchemaColumnType {\n\tswitch (type) {\n\t\t// Numeric types → 'number' (includes integer, bigint, decimal)\n\t\tcase 'integer':\n\t\tcase 'bigint':\n\t\tcase 'decimal':\n\t\t\treturn 'number';\n\t\t// String types → 'string' (includes text, uuid)\n\t\tcase 'text':\n\t\tcase 'uuid':\n\t\t\treturn 'string';\n\t\t// All other types pass through as-is (they're valid SchemaColumnType)\n\t\tdefault:\n\t\t\treturn type;\n\t}\n}\n\n/**\n * Adapter interface for introspection.\n * Must have introspect() method and optionally dbCasing.\n */\ninterface IntrospectableAdapter {\n\treadonly dbCasing?: DbCasing;\n\tintrospect(options?: {\n\t\tschema?: string;\n\t\tinclude?: readonly string[];\n\t\texclude?: readonly string[];\n\t}): Promise<ModelIR & { introspectedAt?: Date }>;\n}\n\n/**\n * Create a Schema from database introspection.\n *\n * This function introspects the database schema and returns a Schema<T>\n * that can be used with createOrm().\n *\n * @example\n * ```typescript\n * const adapter = createPgsqlAdapter(pool);\n * const schema = await getSchemaFromDb(adapter, { schema: 'public' });\n * const orm = createOrm({ schema, adapter });\n * ```\n *\n * @param adapter - An adapter that implements introspect()\n * @param options - Introspection options (schema name, table filters)\n * @returns A Schema<T> with definition, model, and type-safe tables\n */\nexport async function getSchemaFromDb<\n\tT extends SchemaDefinition = SchemaDefinition,\n>(\n\tadapter: IntrospectableAdapter,\n\toptions?: GetSchemaFromDbOptions,\n): Promise<Schema<T>> {\n\t// Build introspection options, only including defined values\n\tconst introspectOptions: {\n\t\tschema?: string;\n\t\tinclude?: readonly string[];\n\t\texclude?: readonly string[];\n\t} = {};\n\tif (options?.schema !== undefined) introspectOptions.schema = options.schema;\n\tif (options?.tables !== undefined) introspectOptions.include = options.tables;\n\tif (options?.exclude !== undefined)\n\t\tintrospectOptions.exclude = options.exclude;\n\n\t// Call adapter introspection\n\tconst introspectionResult = await adapter.introspect(introspectOptions);\n\n\tconst model = introspectionResult;\n\tconst introspectedAt = introspectionResult.introspectedAt;\n\n\t// Build FK lookup: column name → target table\n\t// ForeignKeyIR uses columns[] array and references.table\n\tconst fkLookup = new Map<\n\t\tstring,\n\t\tMap<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\ttarget: string;\n\t\t\t\trefs: readonly string[];\n\t\t\t\tschema?: string;\n\t\t\t\tnullable: boolean;\n\t\t\t\tunique: boolean;\n\t\t\t\tonDelete?: OnDeleteAction;\n\t\t\t\tonUpdate?: RefOptions['onUpdate'];\n\t\t\t}\n\t\t>\n\t>();\n\tconst compositeExternalFkLookup = new Map<string, ForeignKeyIR[]>();\n\tfor (const table of model.tables.values()) {\n\t\tconst tableFks = new Map<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\ttarget: string;\n\t\t\t\trefs: readonly string[];\n\t\t\t\tschema?: string;\n\t\t\t\tnullable: boolean;\n\t\t\t\tunique: boolean;\n\t\t\t\tonDelete?: OnDeleteAction;\n\t\t\t\tonUpdate?: RefOptions['onUpdate'];\n\t\t\t}\n\t\t>();\n\t\tfor (const fk of table.foreignKeys) {\n\t\t\tconst externalSchema = normalizeReferenceSchema(fk.references.schema);\n\t\t\tif (externalSchema !== undefined && fk.columns.length > 1) {\n\t\t\t\tconst tableCompositeFks =\n\t\t\t\t\tcompositeExternalFkLookup.get(table.name) ?? [];\n\t\t\t\ttableCompositeFks.push({\n\t\t\t\t\t...fk,\n\t\t\t\t\treferences: {\n\t\t\t\t\t\t...fk.references,\n\t\t\t\t\t\tschema: externalSchema,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tcompositeExternalFkLookup.set(table.name, tableCompositeFks);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Existing per-column emission path for same-schema FKs and single-column external FKs.\n\t\t\tconst fkColumn = fk.columns[0];\n\t\t\tif (!fkColumn) continue;\n\n\t\t\t// Find the column to check nullable/unique\n\t\t\tconst column = table.columns.find((c) => c.name === fkColumn);\n\t\t\ttableFks.set(fkColumn, {\n\t\t\t\ttarget: fk.references.table,\n\t\t\t\trefs: fk.references.columns,\n\t\t\t\t...(externalSchema !== undefined ? { schema: externalSchema } : {}),\n\t\t\t\tnullable: column?.nullable ?? true,\n\t\t\t\tunique: column?.unique ?? false,\n\t\t\t\t...(fk.onDelete !== undefined ? { onDelete: fk.onDelete } : {}),\n\t\t\t\t...(fk.onUpdate !== undefined ? { onUpdate: fk.onUpdate } : {}),\n\t\t\t});\n\t\t}\n\t\tfkLookup.set(table.name, tableFks);\n\t}\n\n\t// Convert ModelIR to SchemaDefinition\n\tconst definition: Record<string, TableDef> = {};\n\tconst constraints: SchemaConstraints = {};\n\n\tfor (const table of model.tables.values()) {\n\t\tconst tableDef: TableDef = {};\n\t\tconst tableFks = fkLookup.get(table.name) ?? new Map();\n\t\tconst compositeExternalFks =\n\t\t\tcompositeExternalFkLookup.get(table.name) ?? [];\n\n\t\tfor (const column of table.columns) {\n\t\t\tconst fk = tableFks.get(column.name);\n\n\t\t\tif (fk) {\n\t\t\t\tif (fk.schema !== undefined) {\n\t\t\t\t\tconst sourceColumn: Mutable<Exclude<ColumnDef, SchemaColumnType>> = {\n\t\t\t\t\t\ttype: columnTypeToJsType(column.type),\n\t\t\t\t\t\tnullable: fk.nullable,\n\t\t\t\t\t};\n\t\t\t\t\tif (fk.unique) sourceColumn.unique = true;\n\t\t\t\t\ttableDef[column.name] = sourceColumn;\n\t\t\t\t\tconstraints[table.name] ??= {};\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: constraints entry is initialized above\n\t\t\t\t\tconst tableConstraints = constraints[table.name]!;\n\t\t\t\t\ttableConstraints.foreignKeys ??= [];\n\t\t\t\t\tconst foreignKeys = tableConstraints.foreignKeys;\n\t\t\t\t\tforeignKeys.push(\n\t\t\t\t\t\tref(fk.target, {\n\t\t\t\t\t\t\tschema: fk.schema,\n\t\t\t\t\t\t\tcolumns: [column.name],\n\t\t\t\t\t\t\treferences: fk.refs,\n\t\t\t\t\t\t\t...(fk.onDelete !== undefined ? { onDelete: fk.onDelete } : {}),\n\t\t\t\t\t\t\t...(fk.onUpdate !== undefined ? { onUpdate: fk.onUpdate } : {}),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// FK column → ref() definition\n\t\t\t\tconst usesDefaultReferences =\n\t\t\t\t\tfk.refs.length === 1 && fk.refs[0] === 'id';\n\t\t\t\ttableDef[column.name] = ref(fk.target, {\n\t\t\t\t\tnullable: fk.nullable,\n\t\t\t\t\tunique: fk.unique,\n\t\t\t\t\t...(!usesDefaultReferences ? { references: fk.refs } : {}),\n\t\t\t\t\t...(fk.onDelete !== undefined && fk.onDelete !== 'NO ACTION'\n\t\t\t\t\t\t? { onDelete: fk.onDelete }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(fk.onUpdate !== undefined && fk.onUpdate !== 'NO ACTION'\n\t\t\t\t\t\t? { onUpdate: fk.onUpdate }\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Regular column → JS type\n\t\t\t\ttableDef[column.name] = columnTypeToJsType(column.type);\n\t\t\t}\n\t\t}\n\n\t\tfor (const fk of compositeExternalFks) {\n\t\t\tconst externalSchema = fk.references.schema;\n\t\t\tif (externalSchema === undefined) continue;\n\t\t\tconstraints[table.name] ??= {};\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: constraints entry is initialized above\n\t\t\tconst tableConstraints = constraints[table.name]!;\n\t\t\ttableConstraints.foreignKeys ??= [];\n\t\t\tconst foreignKeys = tableConstraints.foreignKeys;\n\t\t\tforeignKeys.push(\n\t\t\t\tref(fk.references.table, {\n\t\t\t\t\tschema: externalSchema,\n\t\t\t\t\tcolumns: fk.columns,\n\t\t\t\t\treferences: fk.references.columns,\n\t\t\t\t\t...(fk.onDelete !== undefined ? { onDelete: fk.onDelete } : {}),\n\t\t\t\t\t...(fk.onUpdate !== undefined ? { onUpdate: fk.onUpdate } : {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tdefinition[table.name] = tableDef;\n\t}\n\n\tconst tableNames = Object.keys(definition) as (keyof T)[];\n\tconst generatedConstraints =\n\t\tObject.keys(constraints).length > 0 ? constraints : undefined;\n\n\t// Create type-safe tables proxy\n\tconst tables = createTablesProxy(\n\t\tmodel,\n\t\ttableNames as string[],\n\t) as InferTables<T>;\n\n\t// Build result with optional properties only if defined\n\tconst result: Mutable<Schema<T>> = {\n\t\tdefinition: definition as T,\n\t\tmodel,\n\t\ttableNames,\n\t\ttables,\n\t};\n\n\t// Add optional properties only if they have values\n\tif (generatedConstraints !== undefined) {\n\t\tresult.constraints = generatedConstraints;\n\t}\n\tif (adapter.dbCasing !== undefined) {\n\t\tresult.dbCasing = adapter.dbCasing;\n\t}\n\tif (introspectedAt !== undefined) {\n\t\tresult.introspectedAt = introspectedAt;\n\t}\n\n\treturn result;\n}\n","/**\n * Naming and self-reference convention helpers.\n */\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Convert table name to singular form.\n * Simple heuristic: remove trailing 's' if present.\n */\n/**\n * Built-in mapping of irregular plural forms to their singular equivalents.\n * Import and extend this to handle domain-specific irregular plurals:\n *\n * ```ts\n * import { IRREGULAR_PLURALS, singularize } from '@dbsp/core';\n * const custom = { ...IRREGULAR_PLURALS, matrices: 'matrix', indices: 'index' };\n * singularize('matrices', custom); // 'matrix'\n * ```\n */\nexport const IRREGULAR_PLURALS: Record<string, string> = {\n\tpeople: 'person',\n\tchildren: 'child',\n\tmen: 'man',\n\twomen: 'woman',\n\tteeth: 'tooth',\n\tfeet: 'foot',\n\tgeese: 'goose',\n\tmice: 'mouse',\n\tdata: 'datum',\n\tmedia: 'medium',\n\tcriteria: 'criterion',\n\tphenomena: 'phenomenon',\n};\n\nexport function singularize(\n\tname: string,\n\toverrides?: Record<string, string>,\n): string {\n\tconst lower = name.toLowerCase();\n\n\t// Check user-provided overrides first\n\tif (overrides) {\n\t\tconst override = overrides[lower];\n\t\tif (override !== undefined) {\n\t\t\tif (name[0]?.toUpperCase() === name[0]) {\n\t\t\t\treturn override.charAt(0).toUpperCase() + override.slice(1);\n\t\t\t}\n\t\t\treturn override;\n\t\t}\n\t}\n\n\t// Check built-in irregular plurals\n\tconst irregular = IRREGULAR_PLURALS[lower];\n\tif (irregular !== undefined) {\n\t\t// Preserve original case pattern\n\t\tif (name[0]?.toUpperCase() === name[0]) {\n\t\t\treturn irregular.charAt(0).toUpperCase() + irregular.slice(1);\n\t\t}\n\t\treturn irregular;\n\t}\n\n\t// Handle 'ies' → 'y' (categories → category)\n\tif (lower.endsWith('ies') && name.length > 3) {\n\t\treturn `${name.slice(0, -3)}y`;\n\t}\n\n\t// Handle 'es' for words ending in -shes, -ches, -xes, -zes, -ses (boxes → box)\n\t// But NOT for -les, -res, -tes, etc. (profiles → profile, not profil)\n\tif (\n\t\tlower.endsWith('es') &&\n\t\tname.length > 2 &&\n\t\t(lower.endsWith('shes') ||\n\t\t\tlower.endsWith('ches') ||\n\t\t\tlower.endsWith('xes') ||\n\t\t\tlower.endsWith('zes') ||\n\t\t\t(lower.endsWith('ses') &&\n\t\t\t\t!lower.endsWith('ases') &&\n\t\t\t\t!lower.endsWith('uses')))\n\t) {\n\t\treturn name.slice(0, -2);\n\t}\n\n\t// Handle regular plurals ending in 's' (but not 'ss')\n\tif (lower.endsWith('s') && !lower.endsWith('ss') && name.length > 1) {\n\t\treturn name.slice(0, -1);\n\t}\n\n\t// Already singular or unknown pattern\n\treturn name;\n}\n\n/**\n * Convert table name to plural form.\n * Simple heuristic: add 's' or 'es' or 'ies'.\n */\nexport function pluralize(name: string): string {\n\tif (\n\t\tname.endsWith('y') &&\n\t\t!['ay', 'ey', 'oy', 'uy'].some((s) => name.endsWith(s))\n\t) {\n\t\treturn `${name.slice(0, -1)}ies`;\n\t}\n\tif (\n\t\tname.endsWith('s') ||\n\t\tname.endsWith('x') ||\n\t\tname.endsWith('ch') ||\n\t\tname.endsWith('sh')\n\t) {\n\t\treturn `${name}es`;\n\t}\n\treturn `${name}s`;\n}\n\n/**\n * Capitalize first letter.\n */\nexport function capitalize(name: string): string {\n\treturn name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/**\n * Decapitalize first letter.\n */\nexport function decapitalize(name: string): string {\n\treturn name.charAt(0).toLowerCase() + name.slice(1);\n}\n\n/**\n * Get the inverse relation name for a self-referential FK.\n * Special case: parent → children (most common hierarchy pattern).\n * Otherwise: pluralize the belongsTo name (manager → managers).\n */\nexport function getSelfRefInverseName(belongsToName: string): string {\n\t// The most common self-ref pattern\n\tif (belongsToName === 'parent') return 'children';\n\n\t// For other cases, just pluralize (manager → managers)\n\treturn pluralize(belongsToName);\n}\n\n/**\n * Pseudo-column metadata for a self-referential FK.\n * Exported for use by schema builder.\n */\ninterface SelfRefPseudoColumn {\n\t/** FK column name (e.g., 'parentId', 'managerId') */\n\tforeignKeyColumn: string;\n\t/** Target column (usually 'id') */\n\ttargetColumn: string;\n\t/** Parent role name (e.g., 'parent', 'manager') */\n\tparentRole: string;\n\t/** Child role name (e.g., 'children', 'subordinates') */\n\tchildRole: string;\n}\n\ninterface DetectedFK {\n\t/** Column name in source table */\n\tcolumn: string;\n\t/** Target table name */\n\ttargetTable: string;\n\t/** Inferred relation name (e.g., 'author' from 'authorId') */\n\tinferredName: string;\n\t/** Target column (from references.column or default 'id') */\n\ttargetColumn: string;\n\t/** Custom parent role for self-ref FKs (from parentRole or inferred) */\n\tparentRole?: string;\n\t/** Custom child role for self-ref FKs (from childRole or inferred) */\n\tchildRole?: string;\n}\n\n/**\n * Extract pseudo-column metadata from detected FKs.\n * Only self-referential FKs produce pseudo-columns.\n */\nexport function extractSelfRefPseudoColumns(\n\ttableName: string,\n\tfks: DetectedFK[],\n): SelfRefPseudoColumn[] {\n\tconst selfRefFKs = fks.filter((fk) => fk.targetTable === tableName);\n\tif (selfRefFKs.length === 0) return [];\n\n\t// Single self-ref FK: use default parent/child keywords\n\t// Multiple self-ref FKs: require explicit roles (validated elsewhere)\n\treturn selfRefFKs.map((fk) => ({\n\t\tforeignKeyColumn: fk.column,\n\t\ttargetColumn: fk.targetColumn,\n\t\tparentRole: fk.parentRole ?? fk.inferredName,\n\t\tchildRole: fk.childRole ?? getSelfRefInverseName(fk.inferredName),\n\t}));\n}\n\n/**\n * Validate self-referential FK roles for a table.\n * Returns error messages if validation fails.\n */\nexport function validateSelfRefRoles(\n\ttableName: string,\n\tpseudoColumns: SelfRefPseudoColumn[],\n\treservedNames: Set<string> = new Set([\n\t\t'parent',\n\t\t'child',\n\t\t'ascendant',\n\t\t'descendant',\n\t]),\n): string[] {\n\tconst errors: string[] = [];\n\n\tif (pseudoColumns.length === 0) return errors;\n\n\t// Collect all role names for collision detection\n\tconst allRoles = new Set<string>();\n\n\tfor (const pc of pseudoColumns) {\n\t\t// Check reserved name collision (only for multi-FK tables)\n\t\tif (pseudoColumns.length > 1) {\n\t\t\tif (reservedNames.has(pc.parentRole)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Table '${tableName}': parentRole '${pc.parentRole}' conflicts with reserved keyword. Use a custom role name.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (reservedNames.has(pc.childRole)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Table '${tableName}': childRole '${pc.childRole}' conflicts with reserved keyword. Use a custom role name.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check cross-collision between different FKs\n\t\tif (allRoles.has(pc.parentRole)) {\n\t\t\terrors.push(\n\t\t\t\t`Table '${tableName}': duplicate parentRole '${pc.parentRole}'. Each self-ref FK needs unique roles.`,\n\t\t\t);\n\t\t}\n\t\tif (allRoles.has(pc.childRole)) {\n\t\t\terrors.push(\n\t\t\t\t`Table '${tableName}': duplicate childRole '${pc.childRole}'. Each self-ref FK needs unique roles.`,\n\t\t\t);\n\t\t}\n\n\t\tallRoles.add(pc.parentRole);\n\t\tallRoles.add(pc.childRole);\n\t}\n\n\treturn errors;\n}\n","/**\n * @module planner\n * Semantic Planner - Decision engine for query planning.\n * Transforms QueryIntent + ModelIR into PlanReport with strategic decisions.\n *\n * Type definitions live in @dbsp/types. This module re-exports them\n * and provides runtime functions.\n */\n\nimport type {\n\tCTEDefinition,\n\tDecisionType,\n\tDialectCapabilities,\n\tIncludeStrategy,\n\tPlanDecision,\n\tPlanOptions,\n\tPlanReport,\n\tPlanWarning,\n\tRecursivePlanOptions,\n\tRecursivePlanReport,\n\tResolvedIncludeStrategy,\n} from '@dbsp/types';\nimport { resolveJsonAggOrderKey, toColumnList } from '@dbsp/types';\nimport { InvalidOperationError } from './dx/errors.js';\nimport {\n\tgetNodeIdAlias,\n\ttype IncludeIntent,\n\tisRawExpression,\n\ttype QueryIntent,\n\ttype RecursiveIntent,\n\ttype WhereAndIntent,\n\ttype WhereInIntent,\n\ttype WhereIntent,\n\ttype WhereNotIntent,\n\ttype WhereOrIntent,\n} from './intent-ast.js';\nimport type { ModelIR, RelationIR } from './model-ir.js';\n\n// Re-export all planner types from @dbsp/types for backward compatibility\nexport type {\n\tCTEDefinition,\n\tDecisionType,\n\tPlanDecision,\n\tPlanOptions,\n\tPlanReport,\n\tPlanWarning,\n\tPlanWarningCode,\n\tRecursivePlanOptions,\n\tRecursivePlanReport,\n\tResolvedIncludeStrategy,\n} from '@dbsp/types';\n\n// ============================================================================\n// Warning Types\n// ============================================================================\n\n/**\n * Warning codes for planning issues\n */\n\n/**\n * A warning about the query plan\n */\n\n// ============================================================================\n// CTE Types\n// ============================================================================\n\n/**\n * CTE definition for extracted subqueries\n */\n\n// ============================================================================\n// Plan Report\n// ============================================================================\n\n/**\n * Complete plan report\n */\n\n// ============================================================================\n// Plan Options\n// ============================================================================\n\n/**\n * Planning options for customization\n */\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error thrown when plan cannot be created due to ambiguity\n */\nexport class AmbiguousPlanError extends Error {\n\treadonly sourceTable: string;\n\treadonly targetTable: string;\n\treadonly options: readonly string[];\n\n\tconstructor(\n\t\tsourceTable: string,\n\t\ttargetTable: string,\n\t\toptions: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`Ambiguous relation from \"${sourceTable}\" to \"${targetTable}\". ` +\n\t\t\t\t`Use \"via\" to specify one of: ${options.join(', ')}`,\n\t\t);\n\t\tthis.name = 'AmbiguousPlanError';\n\t\tthis.sourceTable = sourceTable;\n\t\tthis.targetTable = targetTable;\n\t\tthis.options = options;\n\t}\n}\n\n/**\n * Error thrown when recursive CTE base/recursive cases have incompatible shapes.\n * Per RFC-001: columns must match in count, order, and be type-compatible.\n */\nexport class RecursiveShapeMismatchError extends Error {\n\treadonly cteName: string;\n\treadonly baseColumns: readonly string[];\n\treadonly recursiveColumns: readonly string[];\n\treadonly mismatchDetails: string;\n\n\tconstructor(\n\t\tcteName: string,\n\t\tbaseColumns: readonly string[],\n\t\trecursiveColumns: readonly string[],\n\t\tmismatchDetails: string,\n\t) {\n\t\tsuper(\n\t\t\t`Recursive CTE \"${cteName}\" shape mismatch: ${mismatchDetails}. ` +\n\t\t\t\t`Base columns: [${baseColumns.join(', ')}], ` +\n\t\t\t\t`Recursive columns: [${recursiveColumns.join(', ')}]`,\n\t\t);\n\t\tthis.name = 'RecursiveShapeMismatchError';\n\t\tthis.cteName = cteName;\n\t\tthis.baseColumns = baseColumns;\n\t\tthis.recursiveColumns = recursiveColumns;\n\t\tthis.mismatchDetails = mismatchDetails;\n\t}\n}\n\n// ============================================================================\n// Recursive CTE Shape Validation Helpers\n// ============================================================================\n\n/**\n * Computes expected base case columns from RecursiveIntent.\n * Order: [node_id_alias, ...select_fields, depth (if track.depth), path (if track.path)]\n */\nfunction computeBaseColumns(intent: RecursiveIntent): readonly string[] {\n\tconst columns: string[] = [];\n\n\t// node_id is always first\n\tcolumns.push(getNodeIdAlias(intent.start.nodeIdExpr));\n\n\t// select fields (if specified)\n\tif (intent.start.select) {\n\t\tcolumns.push(...intent.start.select);\n\t}\n\n\t// tracked columns\n\tif (intent.track?.depth) {\n\t\tcolumns.push('depth');\n\t}\n\tif (intent.track?.path) {\n\t\tcolumns.push('path');\n\t}\n\n\treturn Object.freeze(columns);\n}\n\n/**\n * Computes expected recursive step columns from RecursiveIntent.\n * Must match base columns in count and order.\n */\nfunction computeRecursiveColumns(intent: RecursiveIntent): readonly string[] {\n\tconst columns: string[] = [];\n\n\t// node_id is always first (from traversal)\n\tcolumns.push(getNodeIdAlias(intent.start.nodeIdExpr));\n\n\t// select fields must match base\n\tif (intent.start.select) {\n\t\tcolumns.push(...intent.start.select);\n\t}\n\n\t// tracked columns with expressions\n\tif (intent.track?.depth) {\n\t\tcolumns.push('depth'); // Will be `prev.depth + 1`\n\t}\n\tif (intent.track?.path) {\n\t\tcolumns.push('path'); // Will be `prev.path || id`\n\t}\n\n\treturn Object.freeze(columns);\n}\n\n/**\n * Validates that base and recursive columns are shape-compatible.\n * Throws RecursiveShapeMismatchError if validation fails.\n */\nexport function validateRecursiveShape(intent: RecursiveIntent): void {\n\tconst baseColumns = computeBaseColumns(intent);\n\tconst recursiveColumns = computeRecursiveColumns(intent);\n\n\t// Check column count\n\tif (baseColumns.length !== recursiveColumns.length) {\n\t\tthrow new RecursiveShapeMismatchError(\n\t\t\tintent.cteName,\n\t\t\tbaseColumns,\n\t\t\trecursiveColumns,\n\t\t\t`column count mismatch: base has ${baseColumns.length}, recursive has ${recursiveColumns.length}`,\n\t\t);\n\t}\n\n\t// Check column order (names must match at each position)\n\tfor (let i = 0; i < baseColumns.length; i++) {\n\t\tif (baseColumns[i] !== recursiveColumns[i]) {\n\t\t\tthrow new RecursiveShapeMismatchError(\n\t\t\t\tintent.cteName,\n\t\t\t\tbaseColumns,\n\t\t\t\trecursiveColumns,\n\t\t\t\t`column ${i} name mismatch: base has \"${baseColumns[i]}\", recursive has \"${recursiveColumns[i]}\"`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Planner State (Internal)\n// ============================================================================\n\ninterface PlannerState {\n\tdecisions: PlanDecision[];\n\twarnings: PlanWarning[];\n\tctes: CTEDefinition[];\n\trelationsAnalyzed: number;\n\tdecisionCounters: Record<DecisionType, number>;\n\trelationAccessCounts: Map<string, string[]>; // relation path -> intent paths\n\tvisitedIncludes: Set<string>; // For circular detection\n}\n\n// ============================================================================\n// Planner Implementation\n// ============================================================================\n\n/**\n * Create a query plan from an intent and model\n */\nexport function plan(\n\tintent: QueryIntent,\n\tmodel: ModelIR,\n\toptions: PlanOptions = {},\n): PlanReport {\n\tconst startTime = performance.now();\n\n\tconst state: PlannerState = {\n\t\tdecisions: [],\n\t\twarnings: [],\n\t\tctes: [],\n\t\trelationsAnalyzed: 0,\n\t\tdecisionCounters: {\n\t\t\t'filter-strategy': 0,\n\t\t\t'join-type': 0,\n\t\t\t'include-strategy': 0,\n\t\t\t'cte-extraction': 0,\n\t\t\tambiguity: 0,\n\t\t\t'recursive-cte': 0,\n\t\t\t'bidirectional-edges': 0,\n\t\t},\n\t\trelationAccessCounts: new Map(),\n\t\tvisitedIncludes: new Set(),\n\t};\n\n\tconst opts: Required<PlanOptions> = {\n\t\tforceFilterStrategy: options.forceFilterStrategy as 'exists' | 'join',\n\t\tforceJoinType: options.forceJoinType as 'left' | 'inner',\n\t\tenableCTEs: options.enableCTEs ?? true,\n\t\tcteThreshold: options.cteThreshold ?? 2,\n\t\tmaxIncludeDepth: options.maxIncludeDepth ?? 5,\n\t\tdisambiguate: options.disambiguate ?? {},\n\t\tdefaultIncludeStrategy: options.defaultIncludeStrategy ?? 'auto',\n\t\tdialectCapabilities: options.dialectCapabilities as DialectCapabilities,\n\t};\n\n\t// Validate root table — skip when the FROM is a BatchValues unnest() source\n\t// (the alias is not a real table; schema validation would incorrectly fail)\n\tconst rootTable = intent.batchValuesSource\n\t\t? null\n\t\t: model.getTable(intent.from);\n\tif (!intent.batchValuesSource && !rootTable) {\n\t\tthrow new Error(`Unknown table: ${intent.from}`);\n\t}\n\n\t// Optimize IN-subquery → EXISTS when the relation is known in schema.\n\t// The optimized WHERE goes into `executableIntent` (adapter compiles from it),\n\t// while `intent` stays as the original submitted intent (observable via dump()).\n\t// `plannedIntent` is only used locally to decide whether to emit executableIntent.\n\tconst optimizedWhere = intent.where\n\t\t? optimizeInToExists(intent.where, intent.from, model)\n\t\t: undefined;\n\n\t// Build the post-optimization intent (used as executableIntent when optimization ran)\n\tconst plannedIntent: QueryIntent =\n\t\toptimizedWhere !== undefined && optimizedWhere !== intent.where\n\t\t\t? { ...intent, where: optimizedWhere }\n\t\t\t: intent;\n\n\t// Process where clause\n\tif (optimizedWhere) {\n\t\tprocessWhere(optimizedWhere, intent.from, model, state, opts, 'where');\n\t}\n\n\t// Process includes\n\tif (intent.include) {\n\t\tfor (let i = 0; i < intent.include.length; i++) {\n\t\t\tconst inc = intent.include[i];\n\t\t\tif (inc) {\n\t\t\t\tprocessInclude(\n\t\t\t\t\tinc,\n\t\t\t\t\tintent.from,\n\t\t\t\t\tmodel,\n\t\t\t\t\tstate,\n\t\t\t\t\topts,\n\t\t\t\t\t`include[${i}]`,\n\t\t\t\t\t0,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract CTEs if enabled\n\tif (opts.enableCTEs) {\n\t\textractCTEs(state, opts.cteThreshold);\n\t}\n\n\t// Detect raw SQL usage and add security warnings\n\tdetectRawSqlUsage(intent, state);\n\n\tconst planningTimeMs = performance.now() - startTime;\n\n\t// PERF (FIND-051): use .slice() instead of spread ([...arr]) — avoids the extra\n\t// iterable-protocol overhead; semantically identical for plain arrays.\n\tconst ambiguousDecision = state.decisions.find(\n\t\t(d) => d.type === 'ambiguity' && d.choice === 'unresolved',\n\t);\n\n\tconst metadata: PlanReport['metadata'] = ambiguousDecision\n\t\t? Object.freeze({\n\t\t\t\tplanningTimeMs,\n\t\t\t\trelationsAnalyzed: state.relationsAnalyzed,\n\t\t\t\tisAmbiguous: true,\n\t\t\t\tambiguousOptions: ambiguousDecision.alternatives as readonly string[],\n\t\t\t})\n\t\t: Object.freeze({\n\t\t\t\tplanningTimeMs,\n\t\t\t\trelationsAnalyzed: state.relationsAnalyzed,\n\t\t\t\tisAmbiguous: false,\n\t\t\t});\n\n\tconst report: PlanReport = {\n\t\trootTable: intent.from,\n\t\tdecisions: Object.freeze(state.decisions.slice()),\n\t\twarnings: Object.freeze(state.warnings.slice()),\n\t\tctes: Object.freeze(state.ctes.slice()),\n\t\t// intent is ALWAYS the original submitted intent (contract: observable via dump()).\n\t\t// executableIntent carries the optimized WHERE (e.g. IN→EXISTS) when the\n\t\t// optimizer rewrote it, so the adapter compiles the correct SQL from that field.\n\t\t// When no optimization applies, executableIntent is left undefined and the\n\t\t// adapter falls back to intent.\n\t\tintent,\n\t\t...(plannedIntent !== intent && { executableIntent: plannedIntent }),\n\t\tmetadata,\n\t};\n\n\treturn Object.freeze(report);\n}\n\n// ============================================================================\n// Recursive Intent Planning\n// ============================================================================\n\n/**\n * RecursivePlanReport extends PlanReport with recursive-specific metadata.\n */\n\n/**\n * Options specific to recursive CTE planning.\n */\n\n/**\n * Create a plan for a recursive CTE intent.\n * Per RFC-001: validates shape, generates decisions for traversal strategy.\n */\nexport function planRecursive(\n\tintent: RecursiveIntent,\n\tmodel: ModelIR,\n\toptions: RecursivePlanOptions = {},\n): RecursivePlanReport {\n\tconst startTime = performance.now();\n\n\t// Step 1: Validate shape compatibility\n\tvalidateRecursiveShape(intent);\n\n\tconst state: PlannerState = {\n\t\tdecisions: [],\n\t\twarnings: [],\n\t\tctes: [],\n\t\trelationsAnalyzed: 0,\n\t\tdecisionCounters: {\n\t\t\t'filter-strategy': 0,\n\t\t\t'join-type': 0,\n\t\t\t'include-strategy': 0,\n\t\t\t'cte-extraction': 0,\n\t\t\tambiguity: 0,\n\t\t\t'recursive-cte': 0,\n\t\t\t'bidirectional-edges': 0,\n\t\t},\n\t\trelationAccessCounts: new Map(),\n\t\tvisitedIncludes: new Set(),\n\t};\n\n\t// Validate that start table exists\n\tconst startTable = model.getTable(intent.start.from);\n\tif (!startTable) {\n\t\tthrow new Error(`Unknown table: ${intent.start.from}`);\n\t}\n\n\t// Step 2: Generate recursive-cte decision\n\tconst traversalKind = intent.traversal.kind;\n\n\tconst recursiveCteDecision: PlanDecision = {\n\t\tid: generateDecisionId(state, 'recursive-cte'),\n\t\ttype: 'recursive-cte',\n\t\tcontext: {\n\t\t\tsourceTable: intent.start.from,\n\t\t\tintentPath: `recursive:${intent.cteName}`,\n\t\t},\n\t\tchoice: 'with-recursive',\n\t\treasoning: generateRecursiveReasoning(intent),\n\t\talternatives: ['with-recursive', 'iterative'],\n\t};\n\tstate.decisions.push(recursiveCteDecision);\n\n\t// Step 3: Handle bidirectional edges (for edge-table traversal)\n\tlet usesBidirectional = false;\n\tif (\n\t\ttraversalKind === 'edge-table' &&\n\t\tintent.traversal.kind === 'edge-table'\n\t) {\n\t\tconst edgeTraversal = intent.traversal;\n\t\tif (edgeTraversal.direction === 'both') {\n\t\t\tusesBidirectional = true;\n\n\t\t\tconst storageHint = edgeTraversal.edgeStorageHint ?? 'unknown';\n\t\t\tconst strategy =\n\t\t\t\toptions.forceBidirectionalStrategy ??\n\t\t\t\t(storageHint === 'directed-only' ? 'union-all' : 'union');\n\n\t\t\tconst bidirectionalDecision: PlanDecision = {\n\t\t\t\tid: generateDecisionId(state, 'bidirectional-edges'),\n\t\t\t\ttype: 'bidirectional-edges',\n\t\t\t\tcontext: {\n\t\t\t\t\tsourceTable: intent.start.from,\n\t\t\t\t\ttarget: edgeTraversal.edgeTable,\n\t\t\t\t\tintentPath: `recursive:${intent.cteName}:edges`,\n\t\t\t\t},\n\t\t\t\tchoice: strategy,\n\t\t\t\treasoning: generateBidirectionalReasoning(storageHint, strategy),\n\t\t\t\talternatives: ['union', 'union-all'],\n\t\t\t};\n\t\t\tstate.decisions.push(bidirectionalDecision);\n\n\t\t\t// Add warning if using union-all with unknown storage\n\t\t\tif (strategy === 'union-all' && storageHint === 'unknown') {\n\t\t\t\tstate.warnings.push({\n\t\t\t\t\tcode: 'POTENTIAL_ROW_EXPLOSION',\n\t\t\t\t\tmessage: `Bidirectional edge traversal with UNION ALL on unknown storage hint may produce duplicates`,\n\t\t\t\t\tsuggestion: `Set edgeStorageHint: 'directed-only' if edges are guaranteed uni-directional, or use dedupe: 'final'`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Step 4: Validate maxDepth\n\tif (intent.maxDepth < 1) {\n\t\tthrow new Error(`maxDepth must be >= 1, got ${intent.maxDepth}`);\n\t}\n\n\tif (intent.maxDepth > 100) {\n\t\tstate.warnings.push({\n\t\t\tcode: 'DEEP_NESTING',\n\t\t\tmessage: `maxDepth of ${intent.maxDepth} is unusually high`,\n\t\t\tsuggestion: `Consider if you really need traversal depth > 100. Large values may cause performance issues.`,\n\t\t});\n\t}\n\n\tconst planningTimeMs = performance.now() - startTime;\n\n\tconst dedupeStrategy = intent.dedupe ?? 'none';\n\n\t// PERF (FIND-051): use .slice() instead of spread — avoids iterable-protocol overhead.\n\tconst report: RecursivePlanReport = {\n\t\trootTable: intent.start.from,\n\t\tdecisions: Object.freeze(state.decisions.slice()),\n\t\twarnings: Object.freeze(state.warnings.slice()),\n\t\tctes: Object.freeze(state.ctes.slice()),\n\t\tintent,\n\t\tmetadata: Object.freeze({\n\t\t\tplanningTimeMs,\n\t\t\trelationsAnalyzed: state.relationsAnalyzed,\n\t\t\tisAmbiguous: false,\n\t\t\tisRecursive: true as const,\n\t\t\ttraversalKind,\n\t\t\tusesBidirectional,\n\t\t\tdedupeStrategy,\n\t\t}),\n\t};\n\n\treturn Object.freeze(report) as RecursivePlanReport;\n}\n\n/**\n * Generate reasoning for recursive CTE decision.\n */\nfunction generateRecursiveReasoning(intent: RecursiveIntent): string {\n\tconst parts: string[] = [];\n\n\tparts.push(\n\t\t`Recursive CTE \"${intent.cteName}\" using ${intent.traversal.kind} traversal`,\n\t);\n\n\tif (intent.traversal.kind === 'adjacency') {\n\t\tparts.push(\n\t\t\t`direction=${intent.traversal.direction}, parentId=${intent.traversal.parentId}`,\n\t\t);\n\t} else if (intent.traversal.kind === 'edge-table') {\n\t\tparts.push(\n\t\t\t`edgeTable=${intent.traversal.edgeTable}, direction=${intent.traversal.direction}`,\n\t\t);\n\t}\n\n\tparts.push(`maxDepth=${intent.maxDepth}`);\n\n\tif (intent.dedupe && intent.dedupe !== 'none') {\n\t\tparts.push(`dedupe=${intent.dedupe}`);\n\t}\n\n\treturn parts.join(', ');\n}\n\n/**\n * Generate reasoning for bidirectional edge decision.\n */\nfunction generateBidirectionalReasoning(\n\tstorageHint: 'unknown' | 'directed-only',\n\tstrategy: 'union' | 'union-all',\n): string {\n\tif (storageHint === 'directed-only') {\n\t\treturn strategy === 'union-all'\n\t\t\t? 'edgeStorageHint=directed-only guarantees no reverse duplicates, UNION ALL is safe'\n\t\t\t: 'UNION used despite directed-only hint (forced or conservative)';\n\t}\n\treturn strategy === 'union'\n\t\t? 'edgeStorageHint=unknown, using UNION to eliminate potential duplicates'\n\t\t: 'UNION ALL used despite unknown storage hint (may produce duplicates)';\n}\n\n// ============================================================================\n// IN → EXISTS Optimization\n// ============================================================================\n\n/**\n * Optimize IN (subquery) → EXISTS when the subquery targets a known relation.\n *\n * Pattern detected:\n * WHERE id IN (SELECT customer_id FROM orders WHERE ...)\n * Rewritten to:\n * WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = outer.id AND ...)\n *\n * This is a standard SQL optimization: EXISTS short-circuits on first match,\n * while IN materializes the full set. The rewrite is valid when the subquery\n * selects a FK column that references the outer table's PK.\n */\n\n/**\n * Check whether the FK column resolved by a WHERE EXISTS rewrite is provably\n * non-nullable in the ModelIR.\n *\n * Used to guard NOT(IN-subquery) → NOT EXISTS rewrites: SQL's three-valued logic\n * means `x NOT IN (SELECT y ...)` returns UNKNOWN (not TRUE) when y can be NULL,\n * so it excludes the row. NOT EXISTS does not have this behavior — it returns\n * TRUE when the subquery is empty. The rewrite is only semantically equivalent\n * when the FK column is NOT NULL.\n *\n * Returns `false` (conservative) when the relation or column cannot be resolved.\n */\nfunction isSubquerySelectedColumnNonNullable(\n\texistsIntent: { relation: string },\n\tsourceTable: string,\n\tmodel: ModelIR,\n): boolean {\n\tconst rel = model.getRelation(`${sourceTable}.${existsIntent.relation}`);\n\tif (!rel) return false;\n\n\tconst fkColumns = toColumnList(rel.foreignKey);\n\tif (fkColumns.length !== 1) return false;\n\t// biome-ignore lint/style/noNonNullAssertion: fkColumns.length === 1 guaranteed by the return-false guard above\n\tconst fk = fkColumns[0]!;\n\n\tconst targetTableIR = model.getTable(rel.target);\n\tif (!targetTableIR) return false;\n\n\tconst column = targetTableIR.columns.find((c) => c.name === fk);\n\tif (!column) return false;\n\n\treturn !column.nullable;\n}\n\nfunction optimizeInToExists(\n\twhere: WhereIntent,\n\tsourceTable: string,\n\tmodel: ModelIR,\n\t// negated tracks whether this node is under an odd number of NOT wrappers.\n\t// It is used ONLY for the NULL-safety guard — it never determines the rewrite\n\t// form (exists vs notExists).\n\t//\n\t// The rewrite form is determined solely by the in-intent's OWN `not` flag:\n\t// • inWhere.not === false → rewrite to { kind: 'exists' }\n\t// • inWhere.not === true → rewrite to { kind: 'notExists' }\n\t//\n\t// The outer boolean structure (not/and/or wrappers) is PRESERVED by recursion,\n\t// so the form must mirror only the in-intent's own polarity. The `negated`\n\t// parity is XOR'd with `inWhere.not` to compute whether the rewrite would\n\t// occur in a negated context — used ONLY to block rewrites where the FK is\n\t// nullable (NULL-unsafe under effective negation).\n\t//\n\t// Examples at the 'in' leaf:\n\t// • inSubquery(...) at negated=false → effectiveNeg=false, form=exists → exists\n\t// • inSubquery(...) at negated=true → effectiveNeg=true, nullable?keep:form=exists → exists (outer not preserved)\n\t// • {not:true} at negated=false → effectiveNeg=true, nullable?keep:form=notExists\n\t// • {not:true} at negated=true → effectiveNeg=false, form=exists (double-neg, outer not preserved)\n\tnegated = false,\n): WhereIntent {\n\tswitch (where.kind) {\n\t\tcase 'in': {\n\t\t\tconst inWhere = where as WhereInIntent;\n\t\t\tif (!inWhere.subquery) return where;\n\n\t\t\t// Only rewrite when the subquery is SIMPLE: single source table, one\n\t\t\t// selected column (the FK), and NO modifiers that change the result set.\n\t\t\t// Any of the following make the subquery non-simple — keep IN unchanged:\n\t\t\t// limit / orderBy — LIMIT n restricts which rows satisfy IN, can't be\n\t\t\t// expressed in EXISTS form\n\t\t\t// offset — similar row-restriction semantics\n\t\t\t// groupBy / having — HAVING count(*)>1 restricts to duplicates etc.;\n\t\t\t// EXISTS (SELECT 1 ... GROUP BY x HAVING ...) drops\n\t\t\t// the HAVING restriction and matches MORE rows\n\t\t\t// distinct / distinctOn — deduplicate semantics lost in EXISTS\n\t\t\t// joins / include — extra tables in the subquery aren't propagated\n\t\t\t// batchValuesSource — unnest() source, not a real table\n\t\t\t// aggregate select — SELECT max(price) is not a simple FK projection\n\t\t\tconst sq = inWhere.subquery;\n\t\t\tif (\n\t\t\t\tsq.limit != null ||\n\t\t\t\tsq.orderBy?.length ||\n\t\t\t\tsq.offset != null ||\n\t\t\t\tsq.groupBy?.length ||\n\t\t\t\tsq.having != null ||\n\t\t\t\tsq.distinct ||\n\t\t\t\tsq.distinctOn?.length ||\n\t\t\t\tsq.joins?.length ||\n\t\t\t\tsq.include?.length ||\n\t\t\t\tsq.batchValuesSource != null ||\n\t\t\t\tsq.existsWrap ||\n\t\t\t\tsq.lock != null ||\n\t\t\t\t(sq.select != null && sq.select.type !== 'fields')\n\t\t\t) {\n\t\t\t\treturn where;\n\t\t\t}\n\n\t\t\t// Extract the single column from the subquery's select\n\t\t\tconst subSelect = inWhere.subquery.select;\n\t\t\tif (subSelect?.type !== 'fields') return where;\n\t\t\tconst fields = 'fields' in subSelect ? subSelect.fields : undefined;\n\t\t\tif (fields?.length !== 1) return where;\n\t\t\tconst subColumn = fields[0];\n\t\t\tif (!subColumn) return where;\n\n\t\t\t// Look for a relation from sourceTable to subquery's table\n\t\t\t// where the FK column matches the subquery's selected column\n\t\t\tconst relationsFrom = model.getRelationsFrom(sourceTable);\n\t\t\tconst sourceTableIR = model.getTable(sourceTable);\n\t\t\tconst sourcePkColumns = toColumnList(sourceTableIR?.primaryKey);\n\t\t\tif (sourcePkColumns.length > 1) return where;\n\t\t\tconst sourcePk = sourcePkColumns[0] ?? 'id';\n\n\t\t\tlet matchedRelation: string | undefined;\n\n\t\t\tfor (const rel of relationsFrom) {\n\t\t\t\tif (rel.target !== inWhere.subquery.from) continue;\n\t\t\t\tconst fkColumns = toColumnList(rel.foreignKey);\n\t\t\t\tif (fkColumns.length !== 1) continue;\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: fkColumns.length === 1 guaranteed by the continue guard above\n\t\t\t\tconst fk = fkColumns[0]!;\n\n\t\t\t\t// hasMany: outer.pk IN (SELECT fk FROM target WHERE ...)\n\t\t\t\t// The subquery selects the FK column, outer field is PK\n\t\t\t\tif (\n\t\t\t\t\trel.type === 'hasMany' &&\n\t\t\t\t\tfk === subColumn &&\n\t\t\t\t\tinWhere.field === sourcePk\n\t\t\t\t) {\n\t\t\t\t\tmatchedRelation = rel.name;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!matchedRelation) return where;\n\n\t\t\t// NULL-safety guard: compute effective negation (XOR of outer context parity\n\t\t\t// and the in-intent's own `not` flag) to determine whether this rewrite\n\t\t\t// occurs under effective negation. Under effective negation with a nullable\n\t\t\t// FK, `x NOT IN (SELECT y ...)` returns UNKNOWN (row excluded) when y is NULL,\n\t\t\t// whereas `NOT EXISTS` always returns TRUE — so the rewrite would BROADEN the\n\t\t\t// filter. Block the rewrite in that case.\n\t\t\tconst effectiveNegated = negated !== Boolean(inWhere.not);\n\t\t\tif (effectiveNegated) {\n\t\t\t\tconst existsIntent = { relation: matchedRelation };\n\t\t\t\tif (\n\t\t\t\t\t!isSubquerySelectedColumnNonNullable(existsIntent, sourceTable, model)\n\t\t\t\t) {\n\t\t\t\t\t// Nullable FK under effective negation — keep original IN (correct SQL semantics)\n\t\t\t\t\treturn where;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rewrite form is determined SOLELY by the in-intent's own `not` flag,\n\t\t\t// NOT by `effectiveNegated`. The outer boolean structure (not/and/or\n\t\t\t// wrappers) is preserved by the recursion, so the form must mirror only\n\t\t\t// the in-intent's own polarity:\n\t\t\t// • inWhere.not === false → { kind: 'exists' } — outer NOT wraps it if present\n\t\t\t// • inWhere.not === true → { kind: 'notExists' } — outer NOT wraps it if present\n\t\t\tconst targetKind = inWhere.not ? 'notExists' : 'exists';\n\t\t\treturn {\n\t\t\t\tkind: targetKind,\n\t\t\t\trelation: matchedRelation,\n\t\t\t\t...(inWhere.subquery.where && { where: inWhere.subquery.where }),\n\t\t\t} as unknown as WhereIntent;\n\t\t}\n\n\t\tcase 'and': {\n\t\t\tconst andWhere = where as WhereAndIntent;\n\t\t\tconst optimized = andWhere.conditions.map((c) =>\n\t\t\t\toptimizeInToExists(c, sourceTable, model, negated),\n\t\t\t);\n\t\t\tif (optimized.every((c, i) => c === andWhere.conditions[i])) return where;\n\t\t\treturn { kind: 'and', conditions: optimized } as WhereAndIntent;\n\t\t}\n\n\t\tcase 'or': {\n\t\t\t// The adapter now compiles EXISTS inline at its boolean tree position\n\t\t\t// (enrichExistsDecisionsInPlace replaces stubs in-place rather than hoisting\n\t\t\t// to top-level AND). Recursing here is safe: an exists inside an OR\n\t\t\t// becomes a whereOr stub that is enriched in-place, preserving OR semantics.\n\t\t\tconst orWhere = where as WhereOrIntent;\n\t\t\tconst optimized = orWhere.conditions.map((c) =>\n\t\t\t\toptimizeInToExists(c, sourceTable, model, negated),\n\t\t\t);\n\t\t\tif (optimized.every((c, i) => c === orWhere.conditions[i])) return where;\n\t\t\treturn { kind: 'or', conditions: optimized } as WhereOrIntent;\n\t\t}\n\n\t\tcase 'not': {\n\t\t\tconst notWhere = where as WhereNotIntent;\n\t\t\t// Flip negation parity for the child (used only for the null-safety guard\n\t\t\t// inside 'case in'). The outer 'not' wrapper is ALWAYS preserved: after\n\t\t\t// the child rewrites its 'in' leaf to 'exists' or 'notExists', the outer\n\t\t\t// not() remains to produce the correct SQL structure:\n\t\t\t// not(in_not=false) → child becomes exists → not(exists) = NOT EXISTS ✓\n\t\t\t// not(in_not=true) → child becomes notExists → not(notExists) = NOT NOT EXISTS = EXISTS (adapter compiles correctly)\n\t\t\tconst optimized = optimizeInToExists(\n\t\t\t\tnotWhere.condition,\n\t\t\t\tsourceTable,\n\t\t\t\tmodel,\n\t\t\t\t!negated,\n\t\t\t);\n\t\t\tif (optimized === notWhere.condition) return where;\n\t\t\treturn { kind: 'not', condition: optimized } as WhereNotIntent;\n\t\t}\n\n\t\tdefault:\n\t\t\treturn where;\n\t}\n}\n\n// ============================================================================\n// Where Processing\n// ============================================================================\n\nfunction processWhere(\n\twhere: WhereIntent,\n\tsourceTable: string,\n\tmodel: ModelIR,\n\tstate: PlannerState,\n\topts: Required<PlanOptions>,\n\tintentPath: string,\n): void {\n\tswitch (where.kind) {\n\t\tcase 'exists':\n\t\tcase 'notExists':\n\t\t\tprocessRelationFilter(\n\t\t\t\twhere.relation,\n\t\t\t\tsourceTable,\n\t\t\t\tmodel,\n\t\t\t\tstate,\n\t\t\t\topts,\n\t\t\t\t`${intentPath}.${where.kind}`,\n\t\t\t\twhere.where,\n\t\t\t);\n\t\t\tbreak;\n\n\t\tcase 'relationFilter':\n\t\t\tprocessRelationFilter(\n\t\t\t\twhere.relation,\n\t\t\t\tsourceTable,\n\t\t\t\tmodel,\n\t\t\t\tstate,\n\t\t\t\topts,\n\t\t\t\t`${intentPath}.relationFilter`,\n\t\t\t\twhere.where,\n\t\t\t\twhere.mode,\n\t\t\t);\n\t\t\tbreak;\n\n\t\tcase 'and':\n\t\t\tfor (let i = 0; i < where.conditions.length; i++) {\n\t\t\t\tconst cond = where.conditions[i];\n\t\t\t\tif (cond) {\n\t\t\t\t\tprocessWhere(\n\t\t\t\t\t\tcond,\n\t\t\t\t\t\tsourceTable,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t`${intentPath}.and[${i}]`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'or':\n\t\t\tfor (let i = 0; i < where.conditions.length; i++) {\n\t\t\t\tconst cond = where.conditions[i];\n\t\t\t\tif (cond) {\n\t\t\t\t\tprocessWhere(\n\t\t\t\t\t\tcond,\n\t\t\t\t\t\tsourceTable,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t`${intentPath}.or[${i}]`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'not':\n\t\t\tprocessWhere(\n\t\t\t\twhere.condition,\n\t\t\t\tsourceTable,\n\t\t\t\tmodel,\n\t\t\t\tstate,\n\t\t\t\topts,\n\t\t\t\t`${intentPath}.not`,\n\t\t\t);\n\t\t\tbreak;\n\n\t\t// Scalar conditions don't need relation analysis\n\t\tcase 'comparison':\n\t\tcase 'like':\n\t\tcase 'in':\n\t\tcase 'any':\n\t\tcase 'null':\n\t\t\t// No relation analysis needed\n\t\t\tbreak;\n\n\t\tcase 'expression':\n\t\t\tbreak; // Custom expression — no relation analysis, pass through\n\n\t\t// Adapter-only kinds: planner records no decisions; the adapter compiles\n\t\t// them directly from the intent. Explicit cases here prevent silent\n\t\t// fallthrough and keep the switch exhaustive.\n\n\t\tcase 'rawExists':\n\t\tcase 'rawNotExists':\n\t\t\t// The subquery is an arbitrary QueryIntent — no FK-based relation\n\t\t\t// resolution to perform at plan time. The adapter handles compilation.\n\t\t\tbreak;\n\n\t\tcase 'subquery':\n\t\t\t// Scalar subquery comparison — the adapter resolves the inner\n\t\t\t// QueryIntent directly; no planner-level relation analysis needed.\n\t\t\tbreak;\n\n\t\tcase 'range':\n\t\t\t// PostgreSQL range operator — scalar field check, no relation\n\t\t\t// analysis required; adapter emits the range SQL.\n\t\t\tbreak;\n\n\t\tcase 'jsonContains':\n\t\tcase 'jsonExists':\n\t\t\t// JSON containment / key-existence operators — scalar field checks\n\t\t\t// compiled entirely by the adapter.\n\t\t\tbreak;\n\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: if a new WhereIntent kind is added to the\n\t\t\t// union without a matching case here, TypeScript will flag this as\n\t\t\t// a type error at compile time, preventing silent no-ops.\n\t\t\tconst _exhaustive: never = where;\n\t\t\tthrow new Error(\n\t\t\t\t`processWhere: unhandled WhereIntent kind '${(_exhaustive as { kind: string }).kind}'`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction processRelationFilter(\n\trelationPath: string | readonly string[],\n\tsourceTable: string,\n\tmodel: ModelIR,\n\tstate: PlannerState,\n\topts: Required<PlanOptions>,\n\tintentPath: string,\n\tnestedWhere?: WhereIntent,\n\tmode?: 'some' | 'every' | 'none',\n): void {\n\tstate.relationsAnalyzed++;\n\n\t// Normalize relation path to array (SPEC-002: multi-hop support)\n\tconst relations = Array.isArray(relationPath) ? relationPath : [relationPath];\n\n\t// Process each relation in the chain\n\tlet currentSource = sourceTable;\n\tfor (let i = 0; i < relations.length; i++) {\n\t\tconst relationName = relations[i];\n\t\tif (!relationName) continue;\n\n\t\tconst isLastInChain = i === relations.length - 1;\n\t\tconst chainPath = `${intentPath}[${i}]`;\n\n\t\t// Find the relation\n\t\tconst relation = disambiguateRelation(\n\t\t\trelationName,\n\t\t\tcurrentSource,\n\t\t\tmodel,\n\t\t\tstate,\n\t\t\topts,\n\t\t\tchainPath,\n\t\t);\n\n\t\tif (!relation) {\n\t\t\treturn; // Error already added to warnings or exception thrown\n\t\t}\n\n\t\t// Track relation access for CTE extraction\n\t\tconst relPath = `${currentSource}.${relation.name}`;\n\t\tconst paths = state.relationAccessCounts.get(relPath) ?? [];\n\t\tpaths.push(chainPath);\n\t\tstate.relationAccessCounts.set(relPath, paths);\n\n\t\t// Determine filter strategy (only for last relation in chain)\n\t\tif (isLastInChain) {\n\t\t\tconst filterStrategy = determineFilterStrategy(\n\t\t\t\trelation,\n\t\t\t\topts,\n\t\t\t\tmode ?? 'some',\n\t\t\t);\n\n\t\t\tconst decisionId = generateDecisionId(state, 'filter-strategy');\n\t\t\t// Detect self-referential relation (source === target)\n\t\t\tconst isSelfRef = relation.source === relation.target;\n\t\t\t// SPEC-002: Include full path in context for multi-hop\n\t\t\tconst context: PlanDecision['context'] = {\n\t\t\t\tsourceTable: currentSource,\n\t\t\t\ttarget: relation.target,\n\t\t\t\trelation: relation.name,\n\t\t\t\tintentPath: chainPath,\n\t\t\t\t...(relations.length > 1 && { relationPath: relations.join('.') }),\n\t\t\t\t...(isSelfRef && { isSelfRef }),\n\t\t\t};\n\t\t\tstate.decisions.push({\n\t\t\t\tid: decisionId,\n\t\t\t\ttype: 'filter-strategy',\n\t\t\t\tcontext,\n\t\t\t\tchoice: filterStrategy,\n\t\t\t\treasoning: generateFilterReasoning(\n\t\t\t\t\trelation,\n\t\t\t\t\tfilterStrategy,\n\t\t\t\t\tmode,\n\t\t\t\t\tisSelfRef,\n\t\t\t\t),\n\t\t\t\talternatives: filterStrategy === 'exists' ? ['join'] : ['exists'],\n\t\t\t});\n\n\t\t\t// Check for potential row explosion warning\n\t\t\tif (filterStrategy === 'join' && relation.cardinality === 'many') {\n\t\t\t\tstate.warnings.push({\n\t\t\t\t\tcode: 'POTENTIAL_ROW_EXPLOSION',\n\t\t\t\t\tmessage: `Using JOIN on to-many relation \"${relation.name}\" may cause row multiplication`,\n\t\t\t\t\tsuggestion: `Consider using EXISTS strategy for relation \"${relation.name}\"`,\n\t\t\t\t\trelatedDecision: decisionId,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Process nested where on the final target\n\t\t\tif (nestedWhere) {\n\t\t\t\tprocessWhere(\n\t\t\t\t\tnestedWhere,\n\t\t\t\t\trelation.target,\n\t\t\t\t\tmodel,\n\t\t\t\t\tstate,\n\t\t\t\t\topts,\n\t\t\t\t\t`${intentPath}.where`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Move to next table in chain\n\t\tcurrentSource = relation.target;\n\t}\n}\n\n// ============================================================================\n// Include Processing\n// ============================================================================\n\nfunction processInclude(\n\tinclude: IncludeIntent,\n\tsourceTable: string,\n\tmodel: ModelIR,\n\tstate: PlannerState,\n\topts: Required<PlanOptions>,\n\tintentPath: string,\n\tdepth: number,\n\tancestorIsLeftJoin = false,\n): void {\n\tstate.relationsAnalyzed++;\n\n\t// Check depth\n\tif (depth > opts.maxIncludeDepth) {\n\t\tstate.warnings.push({\n\t\t\tcode: 'DEEP_NESTING',\n\t\t\tmessage: `Include depth ${depth} exceeds maximum ${opts.maxIncludeDepth}`,\n\t\t\tsuggestion: 'Consider flattening the query or increasing maxIncludeDepth',\n\t\t});\n\t}\n\n\t// Use via hint if provided, otherwise use relation name\n\tconst relationName = include.via ?? include.relation;\n\n\t// Resolve the relation\n\tconst relation = disambiguateRelation(\n\t\trelationName,\n\t\tsourceTable,\n\t\tmodel,\n\t\tstate,\n\t\topts,\n\t\tintentPath,\n\t\tinclude.via,\n\t);\n\n\tif (!relation) {\n\t\treturn;\n\t}\n\n\t// Check for circular includes\n\tconst includePath = `${sourceTable}.${relation.name}`;\n\tconst isSelfReferentialRelation = relation.source === relation.target;\n\tif (!isSelfReferentialRelation && state.visitedIncludes.has(includePath)) {\n\t\tstate.warnings.push({\n\t\t\tcode: 'CIRCULAR_INCLUDE',\n\t\t\tmessage: `Circular include detected: ${includePath}`,\n\t\t\tsuggestion: 'Remove circular include to prevent infinite recursion',\n\t\t});\n\t\treturn;\n\t}\n\tif (!isSelfReferentialRelation) state.visitedIncludes.add(includePath);\n\n\t// Track relation access for CTE extraction\n\tconst relationPath = `${sourceTable}.${relation.name}`;\n\tconst paths = state.relationAccessCounts.get(relationPath) ?? [];\n\tpaths.push(intentPath);\n\tstate.relationAccessCounts.set(relationPath, paths);\n\n\t// CLI-012c: Check for recursive include on self-referential relations\n\tconst isRecursiveInclude =\n\t\t(!!include.recursive || !!relation.recursive) && isSelfReferentialRelation;\n\n\t// Determine include strategy\n\t// Priority: 1) recursive → cte (if dialect supports it), 2) include.join → forces join strategy, 3) include.strategy override, 4) auto-detect\n\tlet includeStrategy: ResolvedIncludeStrategy;\n\tif (isRecursiveInclude) {\n\t\t// FIND-013: Guard recursive → cte against dialect capability.\n\t\t// selectSmartStrategy handles the general case, but processInclude has\n\t\t// an early-exit path that forces 'cte' before reaching it. A dialect\n\t\t// that declared supportsRecursiveCTE=false must not silently receive an\n\t\t// invalid plan.\n\t\tif (opts.dialectCapabilities?.supportsRecursiveCTE === false) {\n\t\t\tthrow new UnsupportedStrategyError(\n\t\t\t\t`Recursive includes require a dialect with supportsRecursiveCTE; ` +\n\t\t\t\t\t`current dialect (${opts.dialectCapabilities.name}) declared it unsupported.`,\n\t\t\t);\n\t\t}\n\t\tincludeStrategy = 'cte';\n\t} else if (include.join !== undefined) {\n\t\t// Explicit join type forces the 'join' strategy (inner or left JOIN)\n\t\tif (include.limit != null) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'include',\n\t\t\t\t`include.limit cannot be applied with the 'join' strategy because join ` +\n\t\t\t\t\t`cannot enforce per-parent-row limits. ` +\n\t\t\t\t\t`Use strategy: 'flat' (→ LATERAL) or strategy: 'cte' explicitly.`,\n\t\t\t);\n\t\t}\n\t\tincludeStrategy = 'join';\n\t} else if (include.strategy === 'flat') {\n\t\t// NQL v2.1: flat = exclude nested output (json_agg), planner picks best flat strategy\n\t\t// lateral only when per-row LIMIT is needed; otherwise join is simpler\n\t\t// Also use lateral when any nested child has a limit (LATERAL cascade required)\n\t\tconst needsLateral = include.limit != null || hasNestedLimit(include);\n\t\tincludeStrategy = selectSmartStrategy(\n\t\t\trelation,\n\t\t\topts.dialectCapabilities,\n\t\t\tfalse,\n\t\t\t/* excludeNested */ true,\n\t\t\t/* hasLimit */ needsLateral,\n\t\t);\n\t} else {\n\t\tincludeStrategy = determineIncludeStrategy(relation, opts);\n\t\t// FIND-014: include.limit cannot be enforced by the join strategy (which\n\t\t// performs a flat JOIN without per-parent-row limiting). Silently\n\t\t// dropping the limit produces unlimited children — incorrect behaviour.\n\t\t// Callers must explicitly request 'flat' (→ lateral) or 'cte' to get\n\t\t// per-parent limiting.\n\t\tif (include.limit != null && includeStrategy === 'join') {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'include',\n\t\t\t\t`include.limit cannot be applied with the 'join' strategy because join ` +\n\t\t\t\t\t`cannot enforce per-parent-row limits. ` +\n\t\t\t\t\t`Use strategy: 'flat' (→ LATERAL) or strategy: 'cte' explicitly.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Pre-compute join type for include-strategy decision embedding\n\t// (only relevant when strategy is 'join')\n\t// When an ancestor used LEFT JOIN (optional relation), cascade LEFT to preserve\n\t// parent rows — even for relations that would normally be INNER (required).\n\t// An explicit join: 'inner' override on THIS hop resets the cascade for children.\n\tconst autoJoinType = determineJoinType(relation, opts, !!include.where);\n\tconst cascadedJoinType: 'inner' | 'left' =\n\t\tancestorIsLeftJoin && include.join === undefined ? 'left' : autoJoinType;\n\tconst explicitJoinType: 'inner' | 'left' | undefined =\n\t\tincludeStrategy === 'join' ? (include.join ?? cascadedJoinType) : undefined;\n\n\tconst includeDecisionId = generateDecisionId(state, 'include-strategy');\n\tconst parentKey =\n\t\trelation.type === 'belongsTo' ? relation.targetKey : relation.sourceKey;\n\tconst targetTable = model.getTable(relation.target);\n\tconst targetOrder = targetTable\n\t\t? resolveJsonAggOrderKey(targetTable)\n\t\t: undefined;\n\n\tstate.decisions.push({\n\t\tid: includeDecisionId,\n\t\ttype: 'include-strategy',\n\t\tcontext: {\n\t\t\tsourceTable,\n\t\t\ttarget: relation.target,\n\t\t\trelation: relation.name,\n\t\t\trelationType: relation.type,\n\t\t\tincludeAlias: include.relation,\n\t\t\tintentPath,\n\t\t\t// Foreign key info for json_agg compilation (Phase 3)\n\t\t\t...(relation.foreignKey !== undefined && {\n\t\t\t\tforeignKey: relation.foreignKey,\n\t\t\t}),\n\t\t\t...(parentKey !== undefined && { parentKey }),\n\t\t\t...(targetOrder &&\n\t\t\t\ttargetOrder.columns.length > 0 && {\n\t\t\t\t\ttargetOrderKey: targetOrder.columns,\n\t\t\t\t}),\n\t\t\t...(targetOrder?.fallback && { orderByFallback: true }),\n\t\t},\n\t\tchoice: includeStrategy,\n\t\t// Embed joinType so the adapter's join handler can use it directly\n\t\t...(explicitJoinType !== undefined && { joinType: explicitJoinType }),\n\t\treasoning: isRecursiveInclude\n\t\t\t? `Recursive include on self-referential relation \"${relation.name}\" → forced CTE strategy`\n\t\t\t: generateIncludeReasoning(relation, includeStrategy),\n\t\talternatives: getAlternativeStrategies(\n\t\t\tincludeStrategy,\n\t\t\topts.dialectCapabilities,\n\t\t),\n\t});\n\n\t// CLI-012c: Warn if recursive is set but relation is not self-referential\n\tif (include.recursive && !isRecursiveInclude) {\n\t\tstate.warnings.push({\n\t\t\tcode: 'INVALID_RECURSIVE_INCLUDE',\n\t\t\tmessage: `recursive option on \"${relation.name}\" ignored: relation is not self-referential (source=${relation.source}, target=${relation.target})`,\n\t\t\tsuggestion: `Remove recursive option or use RecursiveIntent for cross-table recursion`,\n\t\t});\n\t}\n\n\t// CLI-012/CLI-012c: Create CTE when strategy is 'cte' (recursive or not)\n\tif (includeStrategy === 'cte') {\n\t\tconst cteName = `cte_${sourceTable}_${relation.name}`;\n\t\t// Check if CTE already exists (avoid duplicates from nested includes)\n\t\tconst existingCte = state.ctes.find((c) => c.name === cteName);\n\t\tif (!existingCte) {\n\t\t\tstate.ctes.push({\n\t\t\t\tname: cteName,\n\t\t\t\tpurpose: isRecursiveInclude\n\t\t\t\t\t? `Recursive include for self-referential \"${relation.name}\"`\n\t\t\t\t\t: `CTE for \"${relation.name}\" include`,\n\t\t\t\treferencedBy: [intentPath],\n\t\t\t\tsourceIntent: `${sourceTable}.${relation.name}`,\n\t\t\t\trecursive: isRecursiveInclude,\n\t\t\t});\n\t\t} else {\n\t\t\t// Add intentPath to existing CTE's referencedBy\n\t\t\t(existingCte.referencedBy as string[]).push(intentPath);\n\t\t}\n\t}\n\n\t// Emit join-type decision (only if using join strategy)\n\tif (includeStrategy === 'join' && explicitJoinType !== undefined) {\n\t\tconst joinDecisionId = generateDecisionId(state, 'join-type');\n\n\t\tstate.decisions.push({\n\t\t\tid: joinDecisionId,\n\t\t\ttype: 'join-type',\n\t\t\tcontext: {\n\t\t\t\tsourceTable,\n\t\t\t\ttarget: relation.target,\n\t\t\t\trelation: relation.name,\n\t\t\t\tintentPath,\n\t\t\t},\n\t\t\tchoice: explicitJoinType,\n\t\t\treasoning: generateJoinReasoning(\n\t\t\t\trelation,\n\t\t\t\texplicitJoinType,\n\t\t\t\t!!include.where,\n\t\t\t),\n\t\t\talternatives: explicitJoinType === 'left' ? ['inner'] : ['left'],\n\t\t});\n\t}\n\n\t// Process nested where\n\tif (include.where) {\n\t\tprocessWhere(\n\t\t\tinclude.where,\n\t\t\trelation.target,\n\t\t\tmodel,\n\t\t\tstate,\n\t\t\topts,\n\t\t\t`${intentPath}.where`,\n\t\t);\n\t}\n\n\t// Process nested includes\n\tif (include.include) {\n\t\t// Propagate LEFT JOIN cascade to children based on THIS hop's actual join type.\n\t\t// - If this hop emits LEFT JOIN → children inherit the cascade\n\t\t// - If this hop emits INNER JOIN (explicit or auto) → cascade resets\n\t\t// When strategy is not 'join' (json_agg, lateral, cte), explicitJoinType is\n\t\t// undefined → false → no cascade (non-join strategies don't affect the chain).\n\t\tconst nextAncestorIsLeftJoin = explicitJoinType === 'left';\n\t\tfor (let i = 0; i < include.include.length; i++) {\n\t\t\tconst nestedInc = include.include[i];\n\t\t\tif (nestedInc) {\n\t\t\t\tprocessInclude(\n\t\t\t\t\tnestedInc,\n\t\t\t\t\trelation.target,\n\t\t\t\t\tmodel,\n\t\t\t\t\tstate,\n\t\t\t\t\topts,\n\t\t\t\t\t`${intentPath}.include[${i}]`,\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\tnextAncestorIsLeftJoin,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove from visited after processing (allow same relation at different depths)\n\tif (!isSelfReferentialRelation) state.visitedIncludes.delete(includePath);\n}\n\n// ============================================================================\n// Relation Resolution\n// ============================================================================\n\nfunction disambiguateRelation(\n\trelationName: string,\n\tsourceTable: string,\n\tmodel: ModelIR,\n\tstate: PlannerState,\n\topts: Required<PlanOptions>,\n\t_intentPath: string,\n\tviaHint?: string,\n): RelationIR | undefined {\n\t// Try direct lookup first\n\tconst directRelation = model.getRelation(`${sourceTable}.${relationName}`);\n\tif (directRelation) {\n\t\treturn directRelation;\n\t}\n\n\t// Check if this might be a target table name (ambiguous case)\n\tconst relationsToTarget = model\n\t\t.getRelationsFrom(sourceTable)\n\t\t.filter((r) => r.target === relationName);\n\n\tif (relationsToTarget.length === 0) {\n\t\t// Check for virtual recursive relations (ancestors/descendants)\n\t\t// These are auto-inferred from self-referential relations and handled by the compiler\n\t\tif (relationName === 'ancestors' || relationName === 'descendants') {\n\t\t\tconst selfReferentialRelations = model\n\t\t\t\t.getRelationsFrom(sourceTable)\n\t\t\t\t.filter((r) => r.source === r.target);\n\t\t\tif (selfReferentialRelations.length > 0) {\n\t\t\t\t// Virtual recursive relation - return the underlying self-referential relation\n\t\t\t\t// The compiler will handle the actual recursive CTE generation\n\t\t\t\treturn selfReferentialRelations[0];\n\t\t\t}\n\t\t}\n\n\t\t// No relation found\n\t\tstate.warnings.push({\n\t\t\tcode: 'AMBIGUOUS_RELATION',\n\t\t\tmessage: `Unknown relation \"${relationName}\" from table \"${sourceTable}\"`,\n\t\t\tsuggestion: `Check that the relation exists in the schema`,\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tif (relationsToTarget.length === 1) {\n\t\t// Unambiguous - only one relation to target\n\t\treturn relationsToTarget[0];\n\t}\n\n\t// Multiple relations - need disambiguation\n\tconst options = relationsToTarget.map((r) => r.name);\n\n\t// Check for via hint\n\tif (viaHint) {\n\t\tconst resolved = relationsToTarget.find((r) => r.name === viaHint);\n\t\tif (resolved) {\n\t\t\treturn resolved;\n\t\t}\n\t}\n\n\t// Check disambiguate option\n\tconst disambiguateKey = `${sourceTable}.${relationName}`;\n\tconst disambiguated = opts.disambiguate[disambiguateKey];\n\tif (disambiguated) {\n\t\tconst resolved = relationsToTarget.find((r) => r.name === disambiguated);\n\t\tif (resolved) {\n\t\t\treturn resolved;\n\t\t}\n\t}\n\n\t// Ambiguous - throw error\n\tthrow new AmbiguousPlanError(sourceTable, relationName, options);\n}\n\n// ============================================================================\n// Strategy Determination\n// ============================================================================\n\nfunction determineFilterStrategy(\n\trelation: RelationIR,\n\topts: Required<PlanOptions>,\n\t_mode: 'some' | 'every' | 'none',\n): 'exists' | 'join' {\n\t// Forced strategy takes precedence\n\tif (opts.forceFilterStrategy) {\n\t\treturn opts.forceFilterStrategy;\n\t}\n\n\t// Use relation hint if not auto\n\tif (relation.filterStrategy !== 'auto') {\n\t\treturn relation.filterStrategy;\n\t}\n\n\t// Auto-determine based on cardinality and mode\n\tif (relation.cardinality === 'one') {\n\t\treturn 'join';\n\t}\n\n\t// For cardinality 'many', EXISTS is generally better\n\t// (avoids row explosion)\n\treturn 'exists';\n}\n\n/**\n * Resolved include strategy - the actual strategy to use (never 'auto').\n * This is what the compiler receives after planner decision.\n */\n\n/**\n * Determine the include strategy for a relation.\n *\n * Strategy selection logic (CORE-006):\n * 1. If relation has explicit strategy (not 'auto'), use it (after validation)\n * 2. If planner option has explicit strategy (not 'auto'), use it\n * 3. Smart auto selection based on:\n * - Relation type (hasOne/belongsTo → join, hasMany/belongsToMany → depends)\n * - Dialect capabilities (lateral, json_agg support)\n * - Recursive relations → cte\n *\n * @throws {UnsupportedStrategyError} if requested strategy not supported by dialect\n */\nfunction determineIncludeStrategy(\n\trelation: RelationIR,\n\topts: Required<PlanOptions>,\n\tisRecursive = false,\n): ResolvedIncludeStrategy {\n\tconst capabilities = opts.dialectCapabilities;\n\n\t// Helper to validate strategy against dialect capabilities\n\tconst validateStrategy = (\n\t\tstrategy: IncludeStrategy,\n\t): ResolvedIncludeStrategy => {\n\t\tif (strategy === 'auto') {\n\t\t\t// Should not happen, but fallback to join\n\t\t\treturn 'join';\n\t\t}\n\n\t\t// Validate against dialect capabilities if available\n\t\tif (capabilities) {\n\t\t\tif (strategy === 'lateral' && !capabilities.supportsLateralJoin) {\n\t\t\t\tthrow new UnsupportedStrategyError(\n\t\t\t\t\t`Strategy 'lateral' is not supported by ${capabilities.name}. ` +\n\t\t\t\t\t\t`Use 'join', 'subquery', or 'json_agg' instead.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (strategy === 'json_agg' && !capabilities.supportsJsonAgg) {\n\t\t\t\tthrow new UnsupportedStrategyError(\n\t\t\t\t\t`Strategy 'json_agg' is not supported by ${capabilities.name}. ` +\n\t\t\t\t\t\t`Use 'join', 'subquery', or 'lateral' instead.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (strategy === 'cte' && !capabilities.supportsRecursiveCTE) {\n\t\t\t\tthrow new UnsupportedStrategyError(\n\t\t\t\t\t`Strategy 'cte' is not supported by ${capabilities.name}. ` +\n\t\t\t\t\t\t`Use 'join' or 'subquery' instead.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn strategy;\n\t};\n\n\t// 1. Use relation hint if not auto (explicit override)\n\tif (relation.includeStrategy !== 'auto') {\n\t\treturn validateStrategy(relation.includeStrategy);\n\t}\n\n\t// 2. Use planner option if specified (CLI-010: runtime override)\n\tif (opts.defaultIncludeStrategy && opts.defaultIncludeStrategy !== 'auto') {\n\t\treturn validateStrategy(opts.defaultIncludeStrategy);\n\t}\n\n\t// 3. Smart auto selection based on relation type + dialect\n\treturn selectSmartStrategy(relation, capabilities, isRecursive);\n}\n\n/**\n * Check if any nested include (recursively) has a limit set.\n * Used to determine if an intermediate ancestor needs LATERAL for cascade.\n */\nfunction hasNestedLimit(include: IncludeIntent): boolean {\n\tif (!include.include || include.include.length === 0) return false;\n\tfor (const child of include.include) {\n\t\tif (child.limit != null) return true;\n\t\tif (hasNestedLimit(child)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Smart strategy selection based on relation characteristics and dialect.\n *\n * Selection algorithm:\n * - Recursive relations → 'cte' (if supported) or 'subquery'\n * - hasOne/belongsTo (to-one) → 'join' (always safe, single row)\n * - hasMany/belongsToMany (to-many):\n * - If dialect supports json_agg → 'json_agg' (single row per parent, no explosion)\n * - Else if dialect supports lateral → 'lateral' (good with LIMIT)\n * - Else → 'join' (let DB optimize, user can override to 'subquery' if needed)\n */\nfunction selectSmartStrategy(\n\t_relation: RelationIR,\n\tcapabilities: DialectCapabilities | undefined,\n\tisRecursive: boolean,\n\texcludeNested = false,\n\thasLimit = false,\n): ResolvedIncludeStrategy {\n\t// Recursive relations should use CTE\n\tif (isRecursive) {\n\t\tif (capabilities?.supportsRecursiveCTE !== false) {\n\t\t\treturn 'cte';\n\t\t}\n\t\t// Fallback for dialects without CTE support (rare)\n\t\treturn 'subquery';\n\t}\n\n\t// Default strategy for ALL relation types: json_agg\n\t// Rationale:\n\t// - json_agg: aggregates children into single JSON array, no row explosion\n\t// - Works for both to-one (hasOne, belongsTo) and to-many (hasMany)\n\t// - User can force JOIN via | flat modifier if data is too large for JSON\n\t// - lateral: only when per-row LIMIT is needed (top N children pattern)\n\t// - join: simple flat strategy, well-optimized by the database\n\n\tif (capabilities?.supportsJsonAgg && !excludeNested) {\n\t\treturn 'json_agg';\n\t}\n\n\t// LATERAL only when per-row LIMIT is needed — otherwise join is simpler and faster\n\tif (hasLimit && capabilities?.supportsLateralJoin) {\n\t\treturn 'lateral';\n\t}\n\n\t// Fallback: use join (database optimizer handles it)\n\t// User can explicitly request 'subquery' if row explosion is a concern\n\treturn 'join';\n}\n\n/**\n * Error thrown when requested include strategy is not supported by dialect.\n */\nexport class UnsupportedStrategyError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'UnsupportedStrategyError';\n\t}\n}\n\n/**\n * Get alternative strategies for a given strategy based on dialect capabilities.\n */\nfunction getAlternativeStrategies(\n\tstrategy: ResolvedIncludeStrategy,\n\tcapabilities: DialectCapabilities | undefined,\n): string[] {\n\tconst allStrategies: ResolvedIncludeStrategy[] = [\n\t\t'join',\n\t\t'subquery',\n\t\t'cte',\n\t\t'lateral',\n\t\t'json_agg',\n\t];\n\n\t// Filter out current strategy and unsupported ones\n\treturn allStrategies.filter((s) => {\n\t\tif (s === strategy) return false;\n\t\tif (!capabilities) return s === 'join' || s === 'subquery'; // No capabilities = only basic strategies\n\t\tif (s === 'lateral' && !capabilities.supportsLateralJoin) return false;\n\t\tif (s === 'json_agg' && !capabilities.supportsJsonAgg) return false;\n\t\tif (s === 'cte' && !capabilities.supportsRecursiveCTE) return false;\n\t\treturn true;\n\t});\n}\n\nfunction determineJoinType(\n\trelation: RelationIR,\n\topts: Required<PlanOptions>,\n\thasFilter: boolean,\n): 'left' | 'inner' {\n\t// Forced join type takes precedence\n\tif (opts.forceJoinType) {\n\t\treturn opts.forceJoinType;\n\t}\n\n\t// Use relation hint if not auto\n\tif (relation.joinDefault !== 'auto') {\n\t\treturn relation.joinDefault;\n\t}\n\n\t// Auto-determine based on optionality and filter presence\n\tif (relation.optionality === 'required') {\n\t\treturn 'inner';\n\t}\n\n\t// Optional relation with filter implies existence\n\tif (hasFilter) {\n\t\treturn 'inner';\n\t}\n\n\t// Optional without filter -> LEFT to preserve parent rows\n\treturn 'left';\n}\n\n// ============================================================================\n// Raw SQL Detection (Security Observability)\n// ============================================================================\n\n/**\n * Detects raw SQL expressions in the query intent and adds security warnings.\n * This provides observability for potentially unsafe SQL usage.\n */\nfunction detectRawSqlUsage(intent: QueryIntent, state: PlannerState): void {\n\t// Check SELECT expressions for raw SQL\n\tif (\n\t\tintent.select &&\n\t\t'type' in intent.select &&\n\t\tintent.select.type === 'expressions'\n\t) {\n\t\tfor (const col of intent.select.columns) {\n\t\t\t// Direct ExpressionIntent format - check if it's a raw expression\n\t\t\tif (isRawExpression(col)) {\n\t\t\t\tstate.warnings.push({\n\t\t\t\t\tcode: 'RAW_SQL_USAGE',\n\t\t\t\t\tmessage: `Raw SQL expression detected: \"${col.sql}\" (alias: ${col.as})`,\n\t\t\t\t\tsuggestion:\n\t\t\t\t\t\t'Raw SQL bypasses type safety and SQL injection protection. ' +\n\t\t\t\t\t\t'Ensure the SQL is safe and consider using built-in expression helpers instead.',\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ============================================================================\n// CTE Extraction\n// ============================================================================\n\nfunction extractCTEs(state: PlannerState, threshold: number): void {\n\t// PERF (FIND-053): build O(1) lookup structures once before the R-relation loop,\n\t// replacing O(R×D) linear scans (decisions.find + ctes.some) inside the loop.\n\tconst decisionByTableRelation = new Map<string, PlanDecision>();\n\tfor (const d of state.decisions) {\n\t\tif (d.type === 'include-strategy') {\n\t\t\tconst k = `${d.context?.sourceTable ?? ''}:${d.context?.relation ?? ''}`;\n\t\t\t// Keep first match (earliest decision wins)\n\t\t\tif (!decisionByTableRelation.has(k)) {\n\t\t\t\tdecisionByTableRelation.set(k, d);\n\t\t\t}\n\t\t}\n\t}\n\tconst cteNameSet = new Set(state.ctes.map((c) => c.name));\n\n\tfor (const [relationPath, intentPaths] of state.relationAccessCounts) {\n\t\tif (intentPaths.length >= threshold) {\n\t\t\tconst parts = relationPath.split('.');\n\t\t\tconst table = parts[0] ?? 'unknown';\n\t\t\tconst relation = parts[1] ?? 'unknown';\n\t\t\tconst cteName = `cte_${table}_${relation}`;\n\n\t\t\t// SPEC-002: Skip CTE extraction if the include strategy is 'json_agg'.\n\t\t\t// json_agg uses a subquery that doesn't benefit from CTEs and would conflict.\n\t\t\t// Other strategies (join, cte, separate) can still use CTE extraction.\n\t\t\tconst includeStrategyDecision = decisionByTableRelation.get(\n\t\t\t\t`${table}:${relation}`,\n\t\t\t);\n\t\t\tif (includeStrategyDecision?.choice === 'json_agg') {\n\t\t\t\t// json_agg strategy uses its own subquery - CTE extraction not needed\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip if CTE already exists (from include processing)\n\t\t\tif (cteNameSet.has(cteName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstate.ctes.push({\n\t\t\t\tname: cteName,\n\t\t\t\tpurpose: `${relation} relation accessed ${intentPaths.length} times`,\n\t\t\t\treferencedBy: Object.freeze(intentPaths.slice()),\n\t\t\t\tsourceIntent: relationPath,\n\t\t\t});\n\n\t\t\tconst decisionId = generateDecisionId(state, 'cte-extraction');\n\t\t\tstate.decisions.push({\n\t\t\t\tid: decisionId,\n\t\t\t\ttype: 'cte-extraction',\n\t\t\t\tcontext: {\n\t\t\t\t\tsourceTable: table,\n\t\t\t\t\trelation,\n\t\t\t\t},\n\t\t\t\tchoice: cteName,\n\t\t\t\treasoning: `Extracting ${relationPath} to CTE \"${cteName}\" because it is accessed ${intentPaths.length} times (threshold: ${threshold})`,\n\t\t\t\talternatives: ['inline'],\n\t\t\t});\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\nfunction generateDecisionId(state: PlannerState, type: DecisionType): string {\n\tstate.decisionCounters[type]++;\n\tconst counter = state.decisionCounters[type].toString().padStart(3, '0');\n\treturn `${type.replace('-', '')}-${counter}`;\n}\n\nfunction generateFilterReasoning(\n\trelation: RelationIR,\n\tstrategy: 'exists' | 'join',\n\tmode?: 'some' | 'every' | 'none',\n\tisSelfRef?: boolean,\n): string {\n\tconst modeText = mode ? ` (mode: ${mode})` : '';\n\tconst selfRefText = isSelfRef ? ' [self-referential]' : '';\n\n\tif (strategy === 'exists') {\n\t\treturn (\n\t\t\t`Relation ${relation.source}.${relation.name} has cardinality \"${relation.cardinality}\"${modeText}${selfRefText} - ` +\n\t\t\t`using EXISTS to avoid row explosion`\n\t\t);\n\t}\n\n\treturn (\n\t\t`Relation ${relation.source}.${relation.name} has cardinality \"${relation.cardinality}\"${modeText}${selfRefText} - ` +\n\t\t`using JOIN for efficient single-row access`\n\t);\n}\n\nfunction generateIncludeReasoning(\n\trelation: RelationIR,\n\tstrategy: ResolvedIncludeStrategy,\n): string {\n\tconst prefix = `Relation ${relation.source}.${relation.name} (${relation.type}, cardinality: ${relation.cardinality})`;\n\n\tswitch (strategy) {\n\t\tcase 'join':\n\t\t\treturn `${prefix} - using JOIN for efficient single-query fetch`;\n\t\tcase 'subquery':\n\t\t\treturn `${prefix} - using subquery query to avoid row multiplication`;\n\t\tcase 'cte':\n\t\t\treturn `${prefix} - using CTE for recursive/hierarchical traversal`;\n\t\tcase 'lateral':\n\t\t\treturn `${prefix} - using LATERAL JOIN for per-row correlated subquery (LIMIT per parent)`;\n\t\tcase 'json_agg':\n\t\t\treturn `${prefix} - using JSON aggregation to avoid row explosion`;\n\t}\n}\n\nfunction generateJoinReasoning(\n\trelation: RelationIR,\n\tjoinType: 'left' | 'inner',\n\t_hasFilter: boolean,\n): string {\n\tif (joinType === 'inner') {\n\t\tif (relation.optionality === 'required') {\n\t\t\treturn (\n\t\t\t\t`Relation ${relation.source}.${relation.name} is required - ` +\n\t\t\t\t`using INNER JOIN`\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\t`Relation ${relation.source}.${relation.name} has filter - ` +\n\t\t\t`using INNER JOIN (filter implies existence)`\n\t\t);\n\t}\n\n\treturn (\n\t\t`Relation ${relation.source}.${relation.name} is optional without filter - ` +\n\t\t`using LEFT JOIN to preserve parent rows without matches`\n\t);\n}\n","/**\n * Error thrown when attempting to execute a query without a database configured.\n *\n * @example\n * ```typescript\n * const orm = createOrm({ model: schema, adapter: mockAdapter }); // Mock adapter\n * await orm.select('users').findMany(); // Throws ExecutionError (mock can't execute)\n * ```\n */\nexport class ExecutionError extends Error {\n\toverride readonly name = 'ExecutionError' as const;\n\n\t/**\n\t * The operation that was attempted.\n\t */\n\treadonly operation: string;\n\n\t/**\n\t * The reason the operation failed.\n\t */\n\treadonly reason: string;\n\n\t/**\n\t * How to fix the issue.\n\t */\n\treadonly fix: string;\n\n\tconstructor(opts: { operation: string; reason: string; fix: string }) {\n\t\tconst message =\n\t\t\t`Cannot execute ${opts.operation}: ${opts.reason}\\n\\n` +\n\t\t\t`To fix: ${opts.fix}`;\n\n\t\tsuper(message);\n\n\t\tthis.operation = opts.operation;\n\t\tthis.reason = opts.reason;\n\t\tthis.fix = opts.fix;\n\n\t\tObject.setPrototypeOf(this, ExecutionError.prototype);\n\t}\n}\n\n/**\n * Error thrown when firstOrThrow() finds no results.\n *\n * @example\n * ```typescript\n * await orm.select('users').where(eq('id', 999)).firstOrThrow();\n * // Throws NotFoundError: No record found for 'users'\n * ```\n */\nexport class NotFoundError extends Error {\n\toverride readonly name = 'NotFoundError' as const;\n\n\t/**\n\t * The table that was queried.\n\t */\n\treadonly table: string;\n\n\t/**\n\t * Optional: hint about the query that returned no results.\n\t */\n\treadonly hint?: string;\n\n\tconstructor(table: string, hint?: string) {\n\t\tconst message = hint\n\t\t\t? `No record found for '${table}'. ${hint}`\n\t\t\t: `No record found for '${table}'`;\n\n\t\tsuper(message);\n\t\tthis.table = table;\n\t\tif (hint !== undefined) {\n\t\t\tthis.hint = hint;\n\t\t}\n\t\tObject.setPrototypeOf(this, NotFoundError.prototype);\n\t}\n}\n\n/**\n * Error thrown when strict mode is enabled and an ambiguous relation is detected.\n *\n * This error provides detailed information about the ambiguity and available options\n * for disambiguation.\n *\n * @example\n * ```typescript\n * try {\n * orm.select('users').include('posts').plan();\n * } catch (error) {\n * if (error instanceof AmbiguousRelationError) {\n * console.log(error.options); // ['authoredPosts', 'reviewedPosts']\n * }\n * }\n * ```\n */\nexport class AmbiguousRelationError extends Error {\n\toverride readonly name = 'AmbiguousRelationError' as const;\n\n\t/**\n\t * The source table where the ambiguous relation originates.\n\t */\n\treadonly sourceTable: string;\n\n\t/**\n\t * The target table that has multiple possible relations.\n\t */\n\treadonly targetTable: string;\n\n\t/**\n\t * Available relation names that can be used to disambiguate.\n\t * Use one of these values with `{ via: 'relationName' }` to resolve the ambiguity.\n\t */\n\treadonly options: readonly string[];\n\n\t/**\n\t * Public-safe message (no schema enumeration).\n\t * Matches the pattern of RelationNotFoundError, TableNotFoundError, ColumnNotFoundError.\n\t */\n\treadonly publicMessage: string;\n\n\tconstructor(\n\t\tsourceTable: string,\n\t\ttargetTable: string,\n\t\toptions: readonly string[],\n\t) {\n\t\t// Generic message for .message — does NOT embed schema details to avoid info leakage.\n\t\t// Detailed developer guidance is available via .sourceTable, .targetTable, .options.\n\t\tconst genericMessage = 'Ambiguous relation';\n\n\t\tsuper(genericMessage);\n\n\t\tthis.sourceTable = sourceTable;\n\t\tthis.targetTable = targetTable;\n\t\tthis.options = options;\n\t\tthis.publicMessage = genericMessage;\n\n\t\t// Required for proper instanceof checks when extending built-in classes\n\t\t// See: https://github.com/microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n\t\tObject.setPrototypeOf(this, AmbiguousRelationError.prototype);\n\t}\n}\n\n/**\n * Finds the closest match to a target string from a list of candidates.\n * Uses Levenshtein distance for fuzzy matching.\n *\n * @example\n * ```typescript\n * findClosestMatch('usrs', ['users', 'posts', 'comments']); // 'users'\n * findClosestMatch('xyz', ['users', 'posts']); // undefined (no close match)\n * ```\n */\nexport function findClosestMatch(\n\ttarget: string,\n\tcandidates: readonly string[],\n): string | undefined {\n\tif (candidates.length === 0) return undefined;\n\n\tconst targetLower = target.toLowerCase();\n\tlet bestMatch: string | undefined;\n\tlet bestScore = Number.POSITIVE_INFINITY;\n\n\tfor (const candidate of candidates) {\n\t\tconst candidateLower = candidate.toLowerCase();\n\n\t\t// Exact prefix match is best\n\t\tif (candidateLower.startsWith(targetLower)) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Calculate simple distance (Levenshtein approximation for small strings)\n\t\tconst distance = levenshteinDistance(targetLower, candidateLower);\n\t\tif (distance < bestScore && distance <= Math.max(target.length, 3)) {\n\t\t\tbestScore = distance;\n\t\t\tbestMatch = candidate;\n\t\t}\n\t}\n\n\treturn bestMatch;\n}\n\n/**\n * Simple Levenshtein distance implementation.\n */\nfunction levenshteinDistance(a: string, b: string): number {\n\t// Pre-initialize matrix with zeros\n\tconst rows = b.length + 1;\n\tconst cols = a.length + 1;\n\tconst matrix: number[][] = [];\n\n\tfor (let i = 0; i < rows; i++) {\n\t\tmatrix[i] = new Array<number>(cols).fill(0);\n\t}\n\n\t// Initialize first column\n\tfor (let i = 0; i < rows; i++) {\n\t\tconst row = matrix[i];\n\t\tif (row) row[0] = i;\n\t}\n\t// Initialize first row\n\tconst firstRow = matrix[0];\n\tif (firstRow) {\n\t\tfor (let j = 0; j < cols; j++) {\n\t\t\tfirstRow[j] = j;\n\t\t}\n\t}\n\n\tfor (let i = 1; i < rows; i++) {\n\t\tconst currentRow = matrix[i];\n\t\tconst prevRow = matrix[i - 1];\n\t\tif (!currentRow || !prevRow) continue;\n\n\t\tfor (let j = 1; j < cols; j++) {\n\t\t\tconst prevDiag = prevRow[j - 1] ?? 0;\n\t\t\tconst prevUp = prevRow[j] ?? 0;\n\t\t\tconst prevLeft = currentRow[j - 1] ?? 0;\n\n\t\t\tif (b.charAt(i - 1) === a.charAt(j - 1)) {\n\t\t\t\tcurrentRow[j] = prevDiag;\n\t\t\t} else {\n\t\t\t\tcurrentRow[j] = Math.min(\n\t\t\t\t\tprevDiag + 1, // substitution\n\t\t\t\t\tprevLeft + 1, // insertion\n\t\t\t\t\tprevUp + 1, // deletion\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst lastRow = matrix[b.length];\n\treturn lastRow ? (lastRow[a.length] ?? 0) : 0;\n}\n\ntype TableScopedErrorOptions = {\n\ttable: string;\n\trequested: string;\n\tavailable: readonly string[];\n};\n\nabstract class TableScopedError extends Error {\n\treadonly table: string;\n\treadonly requested: string;\n\treadonly available: readonly string[];\n\treadonly suggestion?: string;\n\treadonly publicMessage: string;\n\n\tprotected constructor(opts: TableScopedErrorOptions, genericMessage: string) {\n\t\tconst suggestion = findClosestMatch(opts.requested, opts.available);\n\n\t\t// Generic message — does NOT embed available list to avoid info leakage\n\t\tsuper(genericMessage);\n\n\t\tthis.table = opts.table;\n\t\tthis.requested = opts.requested;\n\t\tthis.available = opts.available;\n\t\tthis.publicMessage = genericMessage;\n\t\tif (suggestion !== undefined) {\n\t\t\tthis.suggestion = suggestion;\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when a requested relation does not exist.\n *\n * Provides helpful suggestions including available relations and fuzzy-matched\n * \"Did you mean?\" hints.\n *\n * @example\n * ```typescript\n * const err = new RelationNotFoundError({\n * table: 'users',\n * requested: 'comment',\n * available: ['posts', 'profile', 'comments'],\n * });\n * // err.message === 'Relation not found'\n * // err.available === ['posts', 'profile', 'comments']\n * // err.suggestion === 'comments'\n * ```\n */\nexport class RelationNotFoundError extends TableScopedError {\n\toverride readonly name = 'RelationNotFoundError' as const;\n\n\t/**\n\t * The table where the relation was requested.\n\t */\n\tdeclare readonly table: string;\n\n\t/**\n\t * The relation name that was requested but not found.\n\t */\n\tdeclare readonly requested: string;\n\n\t/**\n\t * Available relations on this table.\n\t */\n\tdeclare readonly available: readonly string[];\n\n\t/**\n\t * Suggested relation name (fuzzy match), if any.\n\t */\n\tdeclare readonly suggestion?: string;\n\n\t/**\n\t * Public-safe message (no schema enumeration).\n\t */\n\tdeclare readonly publicMessage: string;\n\n\tconstructor(opts: {\n\t\ttable: string;\n\t\trequested: string;\n\t\tavailable: readonly string[];\n\t}) {\n\t\tsuper(opts, 'Relation not found');\n\t\tObject.setPrototypeOf(this, RelationNotFoundError.prototype);\n\t}\n}\n\n/**\n * Error thrown when an operation is invalid or malformed.\n *\n * @example\n * ```typescript\n * orm.insert('users').values([]).execute();\n * // Throws InvalidOperationError: No values provided for insert\n * ```\n */\nexport class InvalidOperationError extends Error {\n\toverride readonly name = 'InvalidOperationError' as const;\n\n\t/**\n\t * The operation that was attempted.\n\t */\n\treadonly operation: string;\n\n\t/**\n\t * The reason the operation is invalid.\n\t */\n\treadonly reason: string;\n\n\tconstructor(operation: string, reason: string) {\n\t\tconst message = `Invalid ${operation}: ${reason}`;\n\t\tsuper(message);\n\t\tthis.operation = operation;\n\t\tthis.reason = reason;\n\t\tObject.setPrototypeOf(this, InvalidOperationError.prototype);\n\t}\n}\n\n/**\n * Error thrown when an operation is potentially unsafe and requires explicit confirmation.\n *\n * @example\n * ```typescript\n * orm.update('users').set({ active: false }).execute();\n * // Throws UnsafeOperationError: WHERE clause required\n * ```\n */\n\n/**\n * Validate that a string is a safe SQL identifier (table, column, schema, alias).\n *\n * Rules:\n * 1. Must not be empty\n * 2. Must not exceed 63 characters (PostgreSQL limit)\n * 3. Must start with a letter or underscore\n * 4. Must contain only alphanumeric, underscore, or dollar sign\n *\n * @param value - The identifier to validate\n * @param type - Type label for error messages (e.g. 'schema', 'table', 'column')\n * @throws InvalidOperationError if validation fails\n */\nexport function validateIdentifier(value: string, type: string): void {\n\tif (!value || value.length === 0) {\n\t\tthrow new InvalidOperationError(type, `${type} name must not be empty`);\n\t}\n\tif (value.length > 63) {\n\t\tthrow new InvalidOperationError(\n\t\t\ttype,\n\t\t\t`${type} name must not exceed 63 characters`,\n\t\t);\n\t}\n\tif (!/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/.test(value)) {\n\t\tthrow new InvalidOperationError(\n\t\t\ttype,\n\t\t\t`${type} name contains invalid characters`,\n\t\t);\n\t}\n}\n\nexport class UnsafeOperationError extends Error {\n\toverride readonly name = 'UnsafeOperationError' as const;\n\n\t/**\n\t * The operation that was attempted.\n\t */\n\treadonly operation: string;\n\n\t/**\n\t * How to make the operation safe or explicit.\n\t */\n\treadonly fix: string;\n\n\tconstructor(operation: string, fix: string) {\n\t\tconst message = `Unsafe ${operation}: ${fix}`;\n\t\tsuper(message);\n\t\tthis.operation = operation;\n\t\tthis.fix = fix;\n\t\tObject.setPrototypeOf(this, UnsafeOperationError.prototype);\n\t}\n}\n\n/**\n * Error thrown when a requested table does not exist in the schema.\n *\n * Provides helpful suggestions including available tables and fuzzy-matched\n * \"Did you mean?\" hints.\n *\n * @example\n * ```typescript\n * const err = new TableNotFoundError({\n * requested: 'usrs',\n * available: ['users', 'posts', 'comments'],\n * });\n * // err.message === 'Table not found'\n * // err.available === ['users', 'posts', 'comments']\n * // err.suggestion === 'users'\n * ```\n */\nexport class TableNotFoundError extends Error {\n\toverride readonly name = 'TableNotFoundError' as const;\n\n\t/**\n\t * The table name that was requested but not found.\n\t */\n\treadonly requested: string;\n\n\t/**\n\t * Available tables in the schema.\n\t */\n\treadonly available: readonly string[];\n\n\t/**\n\t * Suggested table name (fuzzy match), if any.\n\t */\n\treadonly suggestion?: string;\n\n\t/**\n\t * Public-safe message (no schema enumeration).\n\t */\n\treadonly publicMessage: string;\n\n\tconstructor(opts: { requested: string; available: readonly string[] }) {\n\t\tconst suggestion = findClosestMatch(opts.requested, opts.available);\n\n\t\t// Generic message — does NOT embed available list to avoid info leakage\n\t\tconst genericMessage = 'Table not found';\n\n\t\tsuper(genericMessage);\n\n\t\tthis.requested = opts.requested;\n\t\tthis.available = opts.available;\n\t\tthis.publicMessage = genericMessage;\n\t\tif (suggestion !== undefined) {\n\t\t\tthis.suggestion = suggestion;\n\t\t}\n\n\t\tObject.setPrototypeOf(this, TableNotFoundError.prototype);\n\t}\n}\n\n/**\n * Error thrown when a requested column does not exist on a table.\n *\n * Provides helpful suggestions including available columns and fuzzy-matched\n * \"Did you mean?\" hints.\n *\n * @example\n * ```typescript\n * const err = new ColumnNotFoundError({\n * table: 'users',\n * requested: 'emial',\n * available: ['id', 'email', 'name', 'createdAt'],\n * });\n * // err.message === 'Column not found'\n * // err.available === ['id', 'email', 'name', 'createdAt']\n * // err.suggestion === 'email'\n * ```\n */\nexport class ColumnNotFoundError extends TableScopedError {\n\toverride readonly name = 'ColumnNotFoundError' as const;\n\n\t/**\n\t * The table where the column was requested.\n\t */\n\tdeclare readonly table: string;\n\n\t/**\n\t * The column name that was requested but not found.\n\t */\n\tdeclare readonly requested: string;\n\n\t/**\n\t * Available columns on this table.\n\t */\n\tdeclare readonly available: readonly string[];\n\n\t/**\n\t * Suggested column name (fuzzy match), if any.\n\t */\n\tdeclare readonly suggestion?: string;\n\n\t/**\n\t * Public-safe message (no schema enumeration).\n\t */\n\tdeclare readonly publicMessage: string;\n\n\tconstructor(opts: {\n\t\ttable: string;\n\t\trequested: string;\n\t\tavailable: readonly string[];\n\t}) {\n\t\tsuper(opts, 'Column not found');\n\t\tObject.setPrototypeOf(this, ColumnNotFoundError.prototype);\n\t}\n}\n\n/**\n * Error thrown when schema's naming convention doesn't match adapter's naming convention.\n *\n * This validation prevents subtle bugs where column names in queries don't match\n * the expected database column names due to naming convention mismatch.\n *\n * @example\n * ```typescript\n * const schema = await getSchemaFromDb(adapter); // dbCasing: 'snake_case'\n * const orm = createOrm({\n * schema,\n * adapter: createPgsqlAdapter(pool, { dbCasing: 'preserve' }),\n * });\n * // Throws NamingConventionMismatchError\n * ```\n *\n * @since ARCH-006\n */\nexport class NamingConventionMismatchError extends Error {\n\toverride readonly name = 'NamingConventionMismatchError' as const;\n\n\t/**\n\t * The DB casing used by the schema.\n\t */\n\treadonly schemaCasing: string;\n\n\t/**\n\t * The DB casing used by the adapter.\n\t */\n\treadonly adapterCasing: string;\n\n\tconstructor(opts: { schemaCasing: string; adapterCasing: string }) {\n\t\tconst message =\n\t\t\t`DB casing mismatch: Schema uses '${opts.schemaCasing}' but adapter uses '${opts.adapterCasing}'.\\n` +\n\t\t\t`Either align them or recreate the schema with the same dbCasing as the adapter.`;\n\n\t\tsuper(message);\n\n\t\tthis.schemaCasing = opts.schemaCasing;\n\t\tthis.adapterCasing = opts.adapterCasing;\n\n\t\tObject.setPrototypeOf(this, NamingConventionMismatchError.prototype);\n\t}\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * Error codes for programmatic error handling.\n *\n * Use these codes to identify error types without relying on `instanceof` checks,\n * which is useful for serialization and cross-boundary error handling.\n *\n * @example\n * ```typescript\n * try {\n * await orm.select('users').all();\n * } catch (error) {\n * if (error.code === ErrorCode.EXECUTION_ERROR) {\n * // Handle execution error\n * }\n * }\n * ```\n */\nexport const ErrorCode = {\n\t/** Query execution failed (no adapter configured) */\n\tEXECUTION_ERROR: 'DBSP_E001',\n\t/** No record found (firstOrThrow) */\n\tNOT_FOUND: 'DBSP_E002',\n\t/** Ambiguous relation detected in strict mode */\n\tAMBIGUOUS_RELATION: 'DBSP_E003',\n\t/** Relation not found in schema */\n\tRELATION_NOT_FOUND: 'DBSP_E004',\n\t/** Invalid operation in current context */\n\tINVALID_OPERATION: 'DBSP_E005',\n\t/** Unsafe operation blocked */\n\tUNSAFE_OPERATION: 'DBSP_E006',\n\t/** Table not found in schema */\n\tTABLE_NOT_FOUND: 'DBSP_E007',\n\t/** Column not found on table */\n\tCOLUMN_NOT_FOUND: 'DBSP_E008',\n\t/** Schema naming convention doesn't match adapter naming convention */\n\tNAMING_CONVENTION_MISMATCH: 'DBSP_E009',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n// ============================================================================\n// Error Factory\n// ============================================================================\n\n/**\n * Factory functions for creating DBSP errors with consistent structure.\n *\n * Using the factory provides several benefits:\n * - Consistent error creation across the codebase\n * - Error codes are automatically attached\n * - Type-safe error construction\n * - Centralized error message formatting\n *\n * @example\n * ```typescript\n * import { Errors } from '@dbsp/core';\n *\n * // Create errors with factory\n * throw Errors.tableNotFound({\n * requested: 'userz',\n * available: ['users', 'posts', 'comments'],\n * });\n *\n * // Check error type\n * if (Errors.isTableNotFound(error)) {\n * console.log(error.suggestion); // 'users'\n * }\n * ```\n */\nexport const Errors = {\n\t// -------------------------------------------------------------------------\n\t// Factory functions\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Create an execution error (no adapter configured).\n\t */\n\texecution(opts: {\n\t\toperation: string;\n\t\treason: string;\n\t\tfix: string;\n\t}): ExecutionError & { code: typeof ErrorCode.EXECUTION_ERROR } {\n\t\tconst error = new ExecutionError(opts);\n\t\treturn Object.assign(error, { code: ErrorCode.EXECUTION_ERROR });\n\t},\n\n\t/**\n\t * Create a not found error (firstOrThrow returned no results).\n\t */\n\tnotFound(\n\t\ttable: string,\n\t\thint?: string,\n\t): NotFoundError & { code: typeof ErrorCode.NOT_FOUND } {\n\t\tconst error = new NotFoundError(table, hint);\n\t\treturn Object.assign(error, { code: ErrorCode.NOT_FOUND });\n\t},\n\n\t/**\n\t * Create an ambiguous relation error.\n\t */\n\tambiguousRelation(\n\t\tsourceTable: string,\n\t\ttargetTable: string,\n\t\toptions: readonly string[],\n\t): AmbiguousRelationError & { code: typeof ErrorCode.AMBIGUOUS_RELATION } {\n\t\tconst error = new AmbiguousRelationError(sourceTable, targetTable, options);\n\t\treturn Object.assign(error, { code: ErrorCode.AMBIGUOUS_RELATION });\n\t},\n\n\t/**\n\t * Create a relation not found error.\n\t */\n\trelationNotFound(opts: {\n\t\ttable: string;\n\t\trequested: string;\n\t\tavailable: readonly string[];\n\t}): RelationNotFoundError & { code: typeof ErrorCode.RELATION_NOT_FOUND } {\n\t\tconst error = new RelationNotFoundError(opts);\n\t\treturn Object.assign(error, { code: ErrorCode.RELATION_NOT_FOUND });\n\t},\n\n\t/**\n\t * Create an invalid operation error.\n\t */\n\tinvalidOperation(\n\t\toperation: string,\n\t\treason: string,\n\t): InvalidOperationError & { code: typeof ErrorCode.INVALID_OPERATION } {\n\t\tconst error = new InvalidOperationError(operation, reason);\n\t\treturn Object.assign(error, { code: ErrorCode.INVALID_OPERATION });\n\t},\n\n\t/**\n\t * Create an unsafe operation error.\n\t */\n\tunsafeOperation(\n\t\toperation: string,\n\t\tfix: string,\n\t): UnsafeOperationError & { code: typeof ErrorCode.UNSAFE_OPERATION } {\n\t\tconst error = new UnsafeOperationError(operation, fix);\n\t\treturn Object.assign(error, { code: ErrorCode.UNSAFE_OPERATION });\n\t},\n\n\t/**\n\t * Create a table not found error.\n\t */\n\ttableNotFound(opts: {\n\t\trequested: string;\n\t\tavailable: readonly string[];\n\t}): TableNotFoundError & { code: typeof ErrorCode.TABLE_NOT_FOUND } {\n\t\tconst error = new TableNotFoundError(opts);\n\t\treturn Object.assign(error, { code: ErrorCode.TABLE_NOT_FOUND });\n\t},\n\n\t/**\n\t * Create a column not found error.\n\t */\n\tcolumnNotFound(opts: {\n\t\ttable: string;\n\t\trequested: string;\n\t\tavailable: readonly string[];\n\t}): ColumnNotFoundError & { code: typeof ErrorCode.COLUMN_NOT_FOUND } {\n\t\tconst error = new ColumnNotFoundError(opts);\n\t\treturn Object.assign(error, { code: ErrorCode.COLUMN_NOT_FOUND });\n\t},\n\n\t// -------------------------------------------------------------------------\n\t// Type guards\n\t// -------------------------------------------------------------------------\n\n\t/** Check if error is an ExecutionError */\n\tisExecution(error: unknown): error is ExecutionError {\n\t\treturn error instanceof ExecutionError;\n\t},\n\n\t/** Check if error is a NotFoundError */\n\tisNotFound(error: unknown): error is NotFoundError {\n\t\treturn error instanceof NotFoundError;\n\t},\n\n\t/** Check if error is an AmbiguousRelationError */\n\tisAmbiguousRelation(error: unknown): error is AmbiguousRelationError {\n\t\treturn error instanceof AmbiguousRelationError;\n\t},\n\n\t/** Check if error is a RelationNotFoundError */\n\tisRelationNotFound(error: unknown): error is RelationNotFoundError {\n\t\treturn error instanceof RelationNotFoundError;\n\t},\n\n\t/** Check if error is an InvalidOperationError */\n\tisInvalidOperation(error: unknown): error is InvalidOperationError {\n\t\treturn error instanceof InvalidOperationError;\n\t},\n\n\t/** Check if error is an UnsafeOperationError */\n\tisUnsafeOperation(error: unknown): error is UnsafeOperationError {\n\t\treturn error instanceof UnsafeOperationError;\n\t},\n\n\t/** Check if error is a TableNotFoundError */\n\tisTableNotFound(error: unknown): error is TableNotFoundError {\n\t\treturn error instanceof TableNotFoundError;\n\t},\n\n\t/** Check if error is a ColumnNotFoundError */\n\tisColumnNotFound(error: unknown): error is ColumnNotFoundError {\n\t\treturn error instanceof ColumnNotFoundError;\n\t},\n\n\t/** Check if error is a NamingConventionMismatchError */\n\tisNamingConventionMismatch(\n\t\terror: unknown,\n\t): error is NamingConventionMismatchError {\n\t\treturn error instanceof NamingConventionMismatchError;\n\t},\n\n\t/** Check if error is any DBSP error */\n\tisDbspError(\n\t\terror: unknown,\n\t): error is\n\t\t| ExecutionError\n\t\t| NotFoundError\n\t\t| AmbiguousRelationError\n\t\t| RelationNotFoundError\n\t\t| InvalidOperationError\n\t\t| UnsafeOperationError\n\t\t| TableNotFoundError\n\t\t| ColumnNotFoundError\n\t\t| NamingConventionMismatchError {\n\t\treturn (\n\t\t\terror instanceof ExecutionError ||\n\t\t\terror instanceof NotFoundError ||\n\t\t\terror instanceof AmbiguousRelationError ||\n\t\t\terror instanceof RelationNotFoundError ||\n\t\t\terror instanceof InvalidOperationError ||\n\t\t\terror instanceof UnsafeOperationError ||\n\t\t\terror instanceof TableNotFoundError ||\n\t\t\terror instanceof ColumnNotFoundError ||\n\t\t\terror instanceof NamingConventionMismatchError\n\t\t);\n\t},\n\n\t/** Check if error has a DBSP error code */\n\thasCode(error: unknown): error is Error & { code: ErrorCode } {\n\t\treturn (\n\t\t\terror instanceof Error &&\n\t\t\t'code' in error &&\n\t\t\ttypeof (error as Error & { code: unknown }).code === 'string' &&\n\t\t\t(error as Error & { code: string }).code.startsWith('DBSP_E')\n\t\t);\n\t},\n} as const;\n","import { randomUUID } from 'node:crypto';\nimport type {\n\tApplicableAssessment,\n\tApplyGuard,\n\tApplyPolicy,\n\tApplyResult,\n\tAssumption,\n\tClaimId,\n\tDurableApplyOutcome,\n\tDurableIntentRecord,\n\tEvidenceId,\n\tEvidenceObservation,\n\tFingerprintManifest,\n\tIssuedObservation,\n\tLedgerPayload,\n\tObservationContext,\n\tOperationEffectAssessment,\n\tOutcomeReason,\n\tPlanAssessment,\n\tProvenPlanShape,\n\tProvenPlanStep,\n\tRecoveryArtefact,\n\tRecoveryOutcome,\n\tStepJournal,\n\tTransactionalCompletionRecord,\n\tTransitionLessor,\n\tTransitionRunJournal,\n\tTransitionRunMetadata,\n} from '@dbsp/types';\nimport { canonicalJsonDigest } from './canonical-json.js';\nimport { matchLiveObservationContext } from './context-match.js';\nimport { mintDurablyLoadedRun } from './durably-loaded-run.js';\nimport { validateExecutionContract } from './execution-contract.js';\nimport { claimId, semanticArtifactId } from './ids.js';\nimport type {\n\tApplier,\n\tDurableApplyInput,\n\tDurableApplyResult,\n\tInProcessProvenPlan,\n\tTransitionRunPersister,\n} from './index.js';\nimport { isMintedInProcessPlan, mintInProcessPlan } from './minting.js';\nimport { transitionPlanDigest } from './plan-digest.js';\nimport {\n\ttype ExecutionCoordinator,\n\tisOperationRuntime,\n\ttype OperationRuntime,\n\ttype PackRegistry,\n\ttype TransitionExecutionClient,\n} from './registry.js';\nimport { assumptionAccepted } from './resource-scope.js';\nimport { resumeTransitionRun } from './resume.js';\nimport { createTransitionRunMetadata } from './run-metadata.js';\nimport {\n\tacquireExclusiveTransitionLease,\n\tacquireTransitionLease,\n\tisTransitionLessor,\n\tmarkTransitionClientCompromised,\n\tplanOperationSession,\n\tremintTransitionLessorFromSession,\n\ttype TransitionLease,\n\ttype TransitionLeaseFailure,\n\ttransitionLessorRejectionAssessment,\n\ttransitionLessorRejectionDetail,\n} from './transition-lessor.js';\nimport { validateTransitionRelationalInvariants } from './validation.js';\n\nconst APPLIER_ARTIFACT = {\n\tid: semanticArtifactId('dbsp.core.transition.applier'),\n\tversion: '0.1.0',\n};\n\nconst UNMINTED_PLAN_DETAIL =\n\t'plan was not minted by prove() in this process; applying a serialized plan is a separate, not-yet-available API (roadmap: identity & adoption)';\n\n/**\n * An execution path is strict at exactly one of these boundaries. Public\n * `apply()` has no durable preflight input, so it defaults to the in-process\n * boundary. Only `applyDurable()` can construct the durable-contract branch\n * after it has loaded and verified the persisted contract.\n */\ntype ExecutionContextBoundary =\n\t| {\n\t\t\treadonly kind: 'in-process';\n\t\t\treadonly expectedContext: ObservationContext;\n\t }\n\t| {\n\t\t\treadonly kind: 'durable-contract';\n\t\t\treadonly context: ObservationContext;\n\t };\n\ntype DurableExecutionCarrier = {\n\treadonly plan: InProcessProvenPlan;\n\treadonly assessment: ApplicableAssessment;\n\treadonly __durableRun?: TransitionRunMetadata;\n\treadonly __durablyLoadedRun?: import('./durably-loaded-run.js').DurablyLoadedRun;\n\t/**\n\t * The first delivery attempt remains run-scoped for durable journal and\n\t * recovery compatibility. A replay receives a fresh attempt identity.\n\t */\n\treadonly __executionId?: string;\n\treadonly __executionBoundary?: Extract<\n\t\tExecutionContextBoundary,\n\t\t{ readonly kind: 'durable-contract' }\n\t>;\n};\n\nfunction contextMatchAtExecutionBoundary(\n\tboundary: ExecutionContextBoundary,\n\tactual: ObservationContext,\n) {\n\tif (boundary.kind === 'durable-contract') return { ok: true } as const;\n\treturn matchLiveObservationContext({\n\t\texpected: boundary.expectedContext,\n\t\tactual,\n\t});\n}\n\nfunction snapshotDurablePlan(plan: ProvenPlanShape): InProcessProvenPlan {\n\tconst text = JSON.stringify(plan);\n\tif (text === undefined)\n\t\tthrow new Error('durable plan is not JSON serializable');\n\treturn mintInProcessPlan(JSON.parse(text) as ProvenPlanShape);\n}\n\n/**\n * Stable durable-apply refusal names. The assessment remains a\n * `context-mismatch`: no target operation has begun. The fact value gives\n * the CLI a lossless, public result contract without teaching core execution\n * a second result type.\n */\nexport type DurableApplyRefusalCode =\n\t| 'load-failed'\n\t| 'run-id-mismatch'\n\t| 'compatibility-refusal'\n\t| 'plan-digest-mismatch'\n\t| 'digest-mismatch'\n\t| 'plan-validation-failed'\n\t| 'execution-contract-refused'\n\t| 'execution-preflight-failed'\n\t| 'execution-failed'\n\t| 'context-mismatch'\n\t| 'prior-step-events-refusal'\n\t| 'transactional-only-refusal'\n\t| 'operation-unavailable'\n\t| 'assumption-not-accepted'\n\t| 'authorization-write-failed'\n\t| 'database-read-only';\n\nfunction isDatabaseReadOnlyError(error: unknown): boolean {\n\treturn (\n\t\terror !== null &&\n\t\ttypeof error === 'object' &&\n\t\t'code' in error &&\n\t\t(error as { readonly code?: unknown }).code === 'database-read-only'\n\t);\n}\n\nfunction durableRefusal(\n\tcode: DurableApplyRefusalCode,\n\tdetail: string,\n): DurableApplyResult {\n\treturn {\n\t\tdurableOutcome: code,\n\t\tassessment: assessment({\n\t\t\tcode: 'context-mismatch',\n\t\t\tartifact: APPLIER_ARTIFACT,\n\t\t\tfact: { key: 'durable-apply-outcome', value: code },\n\t\t\tdetail,\n\t\t\tscope: [],\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction durableResolvedExecutionOutcome(\n\tresult: Omit<ApplyResult, 'unresolvedOutcome'>,\n): Exclude<DurableApplyOutcome, 'recovery-required' | 'transport-ambiguous'> {\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'partially-applied';\n\tswitch (result.assessment.reasons[0]?.code) {\n\t\tcase 'unknown-step-result':\n\t\t\treturn 'unknown-step-result';\n\t\tcase 'operation-failed-not-applied':\n\t\t\treturn 'operation-failed-not-applied';\n\t\tcase 'guard-failed':\n\t\t\treturn 'guard-failed';\n\t\tcase 'guard-timeout':\n\t\t\treturn 'guard-timeout';\n\t\tdefault:\n\t\t\treturn result.assessment.lifecycle === 'outcome-unknown'\n\t\t\t\t? 'outcome-unknown'\n\t\t\t\t: 'context-mismatch';\n\t}\n}\n\nfunction durableExecutionResult(result: ApplyResult): DurableApplyResult {\n\tconst unresolvedOutcome = result.unresolvedOutcome;\n\tif (unresolvedOutcome?.kind === 'recovery-required')\n\t\treturn {\n\t\t\t...result,\n\t\t\tunresolvedOutcome,\n\t\t\tdurableOutcome: 'recovery-required',\n\t\t};\n\tif (unresolvedOutcome?.kind === 'transport-ambiguous')\n\t\treturn {\n\t\t\t...result,\n\t\t\tunresolvedOutcome,\n\t\t\tdurableOutcome: 'transport-ambiguous',\n\t\t};\n\tconst { unresolvedOutcome: _unresolvedOutcome, ...resolvedResult } = result;\n\treturn {\n\t\t...resolvedResult,\n\t\tdurableOutcome: durableResolvedExecutionOutcome(resolvedResult),\n\t};\n}\n\nfunction recoveryOutcome(result: ApplyResult): RecoveryOutcome {\n\tif (result.recoveryOutcome) return result.recoveryOutcome;\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'recovery-partially-applied';\n\tswitch (result.assessment.reasons[0]?.code) {\n\t\tcase 'resume-required':\n\t\t\treturn 'recovery-resume-required';\n\t\tcase 'unknown-step-result':\n\t\t\treturn 'recovery-unknown-step-result';\n\t\tcase 'guard-failed':\n\t\t\treturn 'recovery-guard-failed';\n\t\tcase 'guard-timeout':\n\t\t\treturn 'recovery-guard-timeout';\n\t\tcase 'operation-failed-not-applied':\n\t\t\treturn 'recovery-operation-failed-not-applied';\n\t\tdefault:\n\t\t\treturn 'recovery-context-mismatch';\n\t}\n}\n\nfunction assessment(\n\treason: OutcomeReason,\n\tlifecycle: PlanAssessment['lifecycle'] = 'planned',\n\tcontinuation: PlanAssessment['continuation'] = 'replan-required',\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle,\n\t\tcontinuation,\n\t\treasons: [reason],\n\t};\n}\n\nfunction completedAssessment(\n\tproven: ApplicableAssessment,\n): ApplicableAssessment {\n\treturn {\n\t\t...proven,\n\t\tlifecycle: 'completed',\n\t\tcontinuation: 'none',\n\t};\n}\n\nfunction transitionLessorRejectionResult(detail?: string): ApplyResult {\n\treturn {\n\t\tassessment: transitionLessorRejectionAssessment(\n\t\t\tAPPLIER_ARTIFACT,\n\t\t\t'planned',\n\t\t\tdetail,\n\t\t),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction primaryClaimFromPlan(plan: InProcessProvenPlan): ClaimId {\n\treturn (\n\t\tplan.claims[0]?.id ??\n\t\tplan.steps.flatMap((step) => [...step.requiredClaims])[0] ??\n\t\tclaimId('dbsp.transition.claim.plan')\n\t);\n}\n\nfunction derivedApplicableAssessment(\n\tplan: InProcessProvenPlan,\n): ApplicableAssessment {\n\tconst established =\n\t\tplan.assumptions.length === 0 &&\n\t\tplan.claims.every(\n\t\t\t(item) =>\n\t\t\t\titem.derivedBy.conclusion === 'established' &&\n\t\t\t\titem.assumes.length === 0,\n\t\t);\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance: established ? 'established' : 'accepted-under-assumptions',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'none',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'proven-applicable',\n\t\t\t\tclaim: primaryClaimFromPlan(plan),\n\t\t\t\tscope: [],\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction evidenceIds(\n\tobservations: readonly IssuedObservation[],\n): readonly EvidenceId[] {\n\treturn observations\n\t\t.filter((observation) => observation.role === 'evidence')\n\t\t.map((observation) => observation.id);\n}\n\nfunction managedOutcomeReadBack(\n\tobservations: readonly IssuedObservation[],\n): LedgerPayload {\n\tconst value = {\n\t\t// PostgreSQL jsonb omits undefined object members. Request and result are\n\t\t// the only optional members introduced here, so omit each before canonical\n\t\t// hashing rather than minting a digest for the literal token \"undefined\".\n\t\tobservations: observations.map((observation) => ({\n\t\t\t...(observation.request === undefined\n\t\t\t\t? {}\n\t\t\t\t: { request: observation.request }),\n\t\t\t...(observation.result === undefined\n\t\t\t\t? {}\n\t\t\t\t: { result: observation.result }),\n\t\t})),\n\t} as unknown as LedgerPayload['value'];\n\treturn {\n\t\tvalue,\n\t\tdigest: canonicalJsonDigest(value),\n\t};\n}\n\nfunction recordedAt(): string {\n\treturn new Date().toISOString();\n}\n\nfunction lockTimeoutMs(\n\truntime: OperationRuntime,\n\tstep: ProvenPlanStep,\n\tcontext: ObservationContext,\n): number {\n\tconst effects = runtime.effectsOf(step.operation, context);\n\tconst waits = effects.effects.locks.flatMap((lock) =>\n\t\ttypeof lock.maxWaitMs === 'number' ? [lock.maxWaitMs] : [],\n\t);\n\treturn waits.length > 0 ? Math.max(...waits) : 5000;\n}\n\nfunction fingerprintMatches(\n\texpected: FingerprintManifest,\n\tactual: FingerprintManifest,\n): boolean {\n\treturn expected.digest === actual.digest;\n}\n\nfunction intentRecord(\n\tstep: ProvenPlanStep,\n\trun: TransitionRunMetadata,\n\texecutionId: string,\n): DurableIntentRecord {\n\treturn {\n\t\trunId: run.runId,\n\t\trun,\n\t\texecutionId,\n\t\tstepId: step.stepId,\n\t\toperation: step.operation,\n\t\trecordedAt: recordedAt(),\n\t};\n}\n\nfunction completionRecord(\n\tstep: ProvenPlanStep,\n\trun: TransitionRunMetadata,\n\tcommittedWithDdl = true,\n): TransactionalCompletionRecord {\n\treturn {\n\t\trunId: run.runId,\n\t\tstepId: step.stepId,\n\t\tcommittedWithDdl,\n\t\trecordedAt: recordedAt(),\n\t};\n}\n\nfunction contextMismatchReason(\n\tstep: ProvenPlanStep,\n\tdetail: string,\n): OutcomeReason {\n\treturn {\n\t\tcode: 'context-mismatch',\n\t\tartifact: step.operation.operationKind.artifact,\n\t\tfact: { key: 'fingerprint', value: detail },\n\t\tscope: [],\n\t};\n}\n\nfunction journalWithObserved(\n\tintent: DurableIntentRecord,\n\toutcome:\n\t\t| 'guard-failed'\n\t\t| 'guard-timeout'\n\t\t| 'operation-failed-not-applied'\n\t\t| 'partially-applied',\n\tobservations: readonly IssuedObservation[],\n\trecovery: readonly RecoveryArtefact[] = [],\n): StepJournal {\n\tconst base = {\n\t\tintent,\n\t\toutcome,\n\t\tobservedOutcome: {\n\t\t\tstepId: intent.stepId,\n\t\t\tobservations: evidenceIds(observations),\n\t\t\trecordedAt: recordedAt(),\n\t\t},\n\t};\n\tif (outcome === 'guard-timeout') {\n\t\treturn base;\n\t}\n\treturn { ...base, recovery };\n}\n\nfunction unacceptedAssumptionResult(\n\tplan: InProcessProvenPlan,\n\tassumption: Assumption,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment({\n\t\t\tcode: 'uncomposable',\n\t\t\tfragments: plan.steps.map((step) => step.selectionRationale.chosen),\n\t\t\tassumption: assumption.id,\n\t\t\tscope: assumption.scope,\n\t\t\tdetail: 'apply policy did not accept required assumption',\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction unacceptedStepAssumptionResult(\n\t_plan: InProcessProvenPlan,\n\tstep: ProvenPlanStep,\n\tassumption: Assumption,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment({\n\t\t\tcode: 'uncomposable',\n\t\t\tfragments: [step.selectionRationale.chosen],\n\t\t\tassumption: assumption.id,\n\t\t\tscope: assumption.scope,\n\t\t\tdetail: `apply policy did not accept assumption ${assumption.id} required by step ${step.stepId}`,\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction uncomposablePlanResult(\n\tplan: InProcessProvenPlan,\n\tdetail: string,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment({\n\t\t\tcode: 'uncomposable',\n\t\t\tfragments: plan.steps.map((step) => step.selectionRationale.chosen),\n\t\t\tscope: [],\n\t\t\tdetail,\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction unresolvedRuntimeResult(step: ProvenPlanStep): ApplyResult {\n\treturn {\n\t\tassessment: assessment(\n\t\t\tcontextMismatchReason(step, 'operation runtime missing'),\n\t\t),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction unresolvedOperationResult(\n\tstep: ProvenPlanStep,\n\tdetail: string,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment(contextMismatchReason(step, detail)),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction invalidPlanResult(detail: string): ApplyResult {\n\treturn {\n\t\tassessment: assessment({\n\t\t\tcode: 'context-mismatch',\n\t\t\tartifact: APPLIER_ARTIFACT,\n\t\t\tfact: { key: 'proven-plan', value: detail },\n\t\t\tscope: [],\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction persistenceFailureResult(\n\trun: TransitionRunMetadata,\n\terror: unknown,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment({\n\t\t\tcode: 'persistence-failed',\n\t\t\tartifact: APPLIER_ARTIFACT,\n\t\t\tfact: {\n\t\t\t\tkey: 'transition-run-id',\n\t\t\t\tvalue: run.runId,\n\t\t\t},\n\t\t\tdetail: `transition-run persistence is indeterminate; load run ${run.runId} before retrying: ${errorDetail(error)}`,\n\t\t\tscope: [],\n\t\t}),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction unknownJournal(intent: DurableIntentRecord): StepJournal {\n\treturn {\n\t\tintent,\n\t\toutcome: 'unknown-step-result',\n\t};\n}\n\nfunction partiallyAppliedReason(\n\tstep: ProvenPlanStep,\n\tdetail: string,\n\trecovery: readonly RecoveryArtefact[] = [],\n): OutcomeReason {\n\treturn {\n\t\tcode: 'partially-applied',\n\t\tstepId: step.stepId,\n\t\toperationKind: step.operation.operationKind,\n\t\toperationRef: step.operation.ref,\n\t\tscope: [],\n\t\tdetail,\n\t\t...(recovery.length > 0 ? { recovery } : {}),\n\t};\n}\n\nfunction guardFailedReason(\n\tstep: ProvenPlanStep,\n\tguard: ApplyGuard,\n\trecovery: readonly RecoveryArtefact[],\n): OutcomeReason {\n\treturn {\n\t\tcode: 'guard-failed',\n\t\tstepId: step.stepId,\n\t\toperationKind: step.operation.operationKind,\n\t\toperationRef: step.operation.ref,\n\t\trecovery,\n\t\tscope: guard.predicate.scope,\n\t};\n}\n\nfunction operationFailedNotAppliedReason(\n\tstep: ProvenPlanStep,\n\tdetail: string,\n): OutcomeReason {\n\treturn {\n\t\tcode: 'operation-failed-not-applied',\n\t\tstepId: step.stepId,\n\t\toperationKind: step.operation.operationKind,\n\t\toperationRef: step.operation.ref,\n\t\tscope: [],\n\t\tdetail,\n\t};\n}\n\nfunction stoppedAssessment(\n\treason: OutcomeReason,\n\thasCommittedSteps: boolean,\n): PlanAssessment {\n\treturn assessment(\n\t\treason,\n\t\thasCommittedSteps ? 'partially-applied' : 'planned',\n\t\thasCommittedSteps ? 'resume-possible' : 'replan-required',\n\t);\n}\n\nclass CommitOutcomeUncertainError extends Error {\n\treadonly originalError: unknown;\n\n\tconstructor(error: unknown) {\n\t\tsuper(\n\t\t\terror instanceof Error\n\t\t\t\t? error.message\n\t\t\t\t: 'transaction commit outcome is uncertain',\n\t\t);\n\t\tthis.name = 'CommitOutcomeUncertainError';\n\t\tthis.originalError = error;\n\t}\n}\n\nfunction errorDetail(error: unknown): string {\n\tif (error instanceof AggregateError) {\n\t\tconst details = error.errors\n\t\t\t.map(errorDetail)\n\t\t\t.filter((detail) => detail !== 'unknown error');\n\t\treturn details.length > 0\n\t\t\t? `${error.message}: ${details.join('; ')}`\n\t\t\t: error.message;\n\t}\n\treturn error instanceof Error ? error.message : 'unknown error';\n}\n\n/** Keep the failed work and the rollback that failed to clean it up together. */\nfunction applyAndRollbackFailure(\n\toriginalError: unknown,\n\tcleanupError: unknown,\n): AggregateError {\n\tconst failure = new AggregateError(\n\t\t[originalError, cleanupError],\n\t\t'transition apply failed and its rollback also failed',\n\t);\n\tObject.defineProperties(failure, {\n\t\toriginalError: { value: originalError, configurable: true },\n\t\tcleanupError: { value: cleanupError, configurable: true },\n\t});\n\treturn failure;\n}\n\nconst postRollbackObservedJournalWrites = new WeakMap<\n\tTransitionExecutionClient,\n\t{\n\t\treadonly coordinator: ExecutionCoordinator | OperationRuntime;\n\t\treadonly maxWaitMs: number;\n\t}\n>();\n\nasync function rollbackAndPrepareObservedJournalWrite(\n\tcoordinator: ExecutionCoordinator | OperationRuntime,\n\tclient: TransitionExecutionClient,\n\tmaxWaitMs: number,\n): Promise<void> {\n\tawait coordinator.rollback(client);\n\t// ROLLBACK clears PostgreSQL's SET LOCAL lock_timeout. An observed event\n\t// appends through SELECT ... FOR UPDATE, so give the standalone append a new,\n\t// bounded transaction.\n\tpostRollbackObservedJournalWrites.set(client, { coordinator, maxWaitMs });\n}\n\nfunction withJournalWriteWarning<T extends PlanAssessment>(\n\tassessmentValue: T,\n\terror: unknown,\n): T {\n\tconst detail = `observed journal write failed after outcome was decided: ${errorDetail(error)}`;\n\treturn {\n\t\t...assessmentValue,\n\t\treasons: assessmentValue.reasons.map((reason, index) =>\n\t\t\tindex === 0\n\t\t\t\t? {\n\t\t\t\t\t\t...reason,\n\t\t\t\t\t\tdetail: reason.detail ? `${reason.detail}; ${detail}` : detail,\n\t\t\t\t\t}\n\t\t\t\t: reason,\n\t\t),\n\t};\n}\n\nasync function writeObservedJournalOutcome(params: {\n\treadonly semantics: OperationRuntime;\n\treadonly client: TransitionExecutionClient;\n\treadonly journal: StepJournal;\n}): Promise<\n\t{ readonly ok: true } | { readonly ok: false; readonly error: unknown }\n> {\n\ttry {\n\t\tconst postRollback = postRollbackObservedJournalWrites.get(params.client);\n\t\tif (postRollback) {\n\t\t\tpostRollbackObservedJournalWrites.delete(params.client);\n\t\t\tawait postRollback.coordinator.begin(params.client);\n\t\t\ttry {\n\t\t\t\tawait postRollback.coordinator.setLockTimeout(\n\t\t\t\t\tparams.client,\n\t\t\t\t\tpostRollback.maxWaitMs,\n\t\t\t\t);\n\t\t\t\tawait params.semantics.writeObservedJournal(\n\t\t\t\t\tparams.client,\n\t\t\t\t\tparams.journal,\n\t\t\t\t);\n\t\t\t\tawait postRollback.coordinator.commit(params.client);\n\t\t\t} catch (error) {\n\t\t\t\tawait postRollback.coordinator\n\t\t\t\t\t.rollback(params.client)\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else {\n\t\t\tawait params.semantics.writeObservedJournal(\n\t\t\t\tparams.client,\n\t\t\t\tparams.journal,\n\t\t\t);\n\t\t}\n\t\treturn { ok: true };\n\t} catch (error) {\n\t\treturn { ok: false, error };\n\t}\n}\n\nasync function writeObservedJournalOrResult(params: {\n\treadonly semantics: OperationRuntime;\n\treadonly client: TransitionExecutionClient;\n\treadonly journal: StepJournal;\n\treadonly result: ApplyResult;\n\treadonly outcomeDurable: boolean;\n\treadonly onDurableWriteWarning?: (error: unknown) => void;\n}): Promise<ApplyResult | undefined> {\n\tconst write = await writeObservedJournalOutcome(params);\n\tif (write.ok) {\n\t\treturn undefined;\n\t}\n\tif (!params.outcomeDurable) {\n\t\tthrow write.error;\n\t}\n\tif (params.onDurableWriteWarning) {\n\t\tparams.onDurableWriteWarning(write.error);\n\t\treturn params.result;\n\t}\n\treturn {\n\t\t...params.result,\n\t\tassessment: withJournalWriteWarning(params.result.assessment, write.error),\n\t};\n}\n\nfunction durableEvidence(\n\tobservations: readonly IssuedObservation[],\n): readonly EvidenceObservation[] {\n\treturn observations.filter(\n\t\t(observation): observation is EvidenceObservation =>\n\t\t\tobservation.role === 'evidence',\n\t);\n}\n\nexport function createApplier(\n\tregistry: PackRegistry,\n\tpersister: TransitionRunPersister,\n): Applier {\n\treturn {\n\t\tartifact: APPLIER_ARTIFACT,\n\t\tasync apply(\n\t\t\tproven: {\n\t\t\t\treadonly plan: InProcessProvenPlan;\n\t\t\t\treadonly assessment: ApplicableAssessment;\n\t\t\t},\n\t\t\tpolicy: ApplyPolicy,\n\t\t\ttarget: TransitionLessor,\n\t\t): Promise<ApplyResult> {\n\t\t\tconst carrier = proven as DurableExecutionCarrier;\n\t\t\tconst plan =\n\t\t\t\ttypeof proven === 'object' && proven !== null\n\t\t\t\t\t? (proven as { readonly plan?: unknown }).plan\n\t\t\t\t\t: undefined;\n\t\t\tif (!isMintedInProcessPlan(plan)) {\n\t\t\t\treturn invalidPlanResult(UNMINTED_PLAN_DETAIL);\n\t\t\t}\n\t\t\tif (plan.segments.length === 0) {\n\t\t\t\tif (!isTransitionLessor(target)) {\n\t\t\t\t\treturn transitionLessorRejectionResult();\n\t\t\t\t}\n\t\t\t\treturn uncomposablePlanResult(\n\t\t\t\t\tplan,\n\t\t\t\t\t'plan contains no executable steps',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (plan.steps.length === 0) {\n\t\t\t\treturn uncomposablePlanResult(\n\t\t\t\t\tplan,\n\t\t\t\t\t'plan contains no executable steps',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst diagnostic = validateTransitionRelationalInvariants({\n\t\t\t\tkind: 'plan',\n\t\t\t\tplan,\n\t\t\t});\n\t\t\tif (!diagnostic.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`internal error: minted proven plan violated relational invariants: ${diagnostic.detail}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst reportedAssessment = derivedApplicableAssessment(plan);\n\n\t\t\tconst proofContext = plan.observations.find(\n\t\t\t\t(observation) => observation.role === 'evidence',\n\t\t\t)?.context;\n\t\t\tif (!proofContext) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'internal error: minted proven plan has no evidence observation context',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst executionBoundary: ExecutionContextBoundary =\n\t\t\t\tcarrier.__executionBoundary ?? {\n\t\t\t\t\tkind: 'in-process',\n\t\t\t\t\texpectedContext: proofContext,\n\t\t\t\t};\n\t\t\tconst assumptionById = new Map(\n\t\t\t\tplan.assumptions.map((assumption) => [assumption.id, assumption]),\n\t\t\t);\n\t\t\tconst stepAssumptionIds = new Set<string>();\n\t\t\tfor (const step of plan.steps) {\n\t\t\t\tfor (const assumptionId of step.restsOnAssumptions) {\n\t\t\t\t\tstepAssumptionIds.add(assumptionId);\n\t\t\t\t\tconst assumption = assumptionById.get(assumptionId);\n\t\t\t\t\tif (assumption && !assumptionAccepted(assumption, policy)) {\n\t\t\t\t\t\treturn unacceptedStepAssumptionResult(plan, step, assumption);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const assumption of plan.assumptions) {\n\t\t\t\tif (\n\t\t\t\t\t!stepAssumptionIds.has(assumption.id) &&\n\t\t\t\t\t!assumptionAccepted(assumption, policy)\n\t\t\t\t) {\n\t\t\t\t\treturn unacceptedAssumptionResult(plan, assumption);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst run = carrier.__durableRun ?? createTransitionRunMetadata(plan);\n\t\t\t// A regular apply can only receive a plan minted by prove() in this\n\t\t\t// process. Durable apply supplies the stricter load-path witness below.\n\t\t\tconst durablyLoadedRun =\n\t\t\t\tcarrier.__durablyLoadedRun ?? mintDurablyLoadedRun(run);\n\t\t\t// A durable run is the reviewed plan, not one of its execution attempts.\n\t\t\t// Every admitted attempt gets an opaque fresh identity; a prior committed\n\t\t\t// step fact is refused by applyDurable before this path is reached.\n\t\t\tconst executionId =\n\t\t\t\tcarrier.__executionId ?? `dbsp.transition.execution.${randomUUID()}`;\n\t\t\tconst operationEffectsByRef = new Map<\n\t\t\t\tstring,\n\t\t\t\tOperationEffectAssessment\n\t\t\t>();\n\t\t\tfor (const step of plan.steps) {\n\t\t\t\tconst operationResolution = registry.resolveOperation(step.operation);\n\t\t\t\tif (!operationResolution.ok) {\n\t\t\t\t\treturn unresolvedOperationResult(step, operationResolution.detail);\n\t\t\t\t}\n\t\t\t\toperationEffectsByRef.set(\n\t\t\t\t\tstep.operation.ref,\n\t\t\t\t\toperationResolution.semantics.effectsOf(step.operation, proofContext),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst semanticDiagnostic = validateTransitionRelationalInvariants({\n\t\t\t\tkind: 'plan',\n\t\t\t\tplan,\n\t\t\t\toperationEffectsByRef,\n\t\t\t});\n\t\t\tif (!semanticDiagnostic.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`internal error: minted proven plan violated relational invariants: ${semanticDiagnostic.detail}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst observations: IssuedObservation[] = [];\n\t\t\tconst journals: StepJournal[] = [];\n\t\t\tconst journalWriteWarnings: unknown[] = [];\n\t\t\tconst recordJournalWriteWarning = (error: unknown): void => {\n\t\t\t\tjournalWriteWarnings.push(error);\n\t\t\t};\n\t\t\tconst assessmentWithJournalWriteWarnings = <T extends PlanAssessment>(\n\t\t\t\tassessmentValue: T,\n\t\t\t): T => {\n\t\t\t\tlet warned = assessmentValue;\n\t\t\t\tfor (const error of journalWriteWarnings) {\n\t\t\t\t\twarned = withJournalWriteWarning(warned, error);\n\t\t\t\t}\n\t\t\t\treturn warned;\n\t\t\t};\n\t\t\tconst resultWithJournalWriteWarnings = (\n\t\t\t\tresult: ApplyResult,\n\t\t\t): ApplyResult =>\n\t\t\t\tjournalWriteWarnings.length === 0\n\t\t\t\t\t? result\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\tassessment: {\n\t\t\t\t\t\t\t\t...assessmentWithJournalWriteWarnings(result.assessment),\n\t\t\t\t\t\t\t\t// At the durable boundary, effects may be committed without an\n\t\t\t\t\t\t\t\t// observed journal. Its durable proof is incomplete, so never\n\t\t\t\t\t\t\t\t// report that as a completed run.\n\t\t\t\t\t\t\t\t...(executionBoundary.kind === 'durable-contract' &&\n\t\t\t\t\t\t\t\tresult.assessment.lifecycle === 'completed'\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tlifecycle: 'outcome-unknown' as const,\n\t\t\t\t\t\t\t\t\t\t\tcontinuation: 'human-intervention-required' as const,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\tconst resultWithCommittedJournals = (\n\t\t\t\tresult: ApplyResult,\n\t\t\t): ApplyResult => {\n\t\t\t\tif (journals.length === 0) {\n\t\t\t\t\treturn resultWithJournalWriteWarnings(result);\n\t\t\t\t}\n\t\t\t\tconst assessmentValue =\n\t\t\t\t\tresult.assessment.lifecycle === 'partially-applied' ||\n\t\t\t\t\tresult.assessment.lifecycle === 'outcome-unknown'\n\t\t\t\t\t\t? result.assessment\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...result.assessment,\n\t\t\t\t\t\t\t\tlifecycle: 'partially-applied' as const,\n\t\t\t\t\t\t\t\tcontinuation:\n\t\t\t\t\t\t\t\t\tresult.assessment.continuation === 'none'\n\t\t\t\t\t\t\t\t\t\t? ('resume-possible' as const)\n\t\t\t\t\t\t\t\t\t\t: result.assessment.continuation,\n\t\t\t\t\t\t\t};\n\t\t\t\treturn resultWithJournalWriteWarnings({\n\t\t\t\t\t...result,\n\t\t\t\t\tassessment: assessmentValue,\n\t\t\t\t\tjournals: [...journals, ...result.journals],\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst resultWithObservedJournal = async (params: {\n\t\t\t\treadonly semantics: OperationRuntime;\n\t\t\t\treadonly client: TransitionExecutionClient | undefined;\n\t\t\t\treadonly journal: StepJournal;\n\t\t\t\treadonly result: ApplyResult;\n\t\t\t\treadonly outcomeDurable: boolean;\n\t\t\t}): Promise<ApplyResult> => {\n\t\t\t\tif (!params.client) {\n\t\t\t\t\treturn resultWithJournalWriteWarnings(params.result);\n\t\t\t\t}\n\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\tsemantics: params.semantics,\n\t\t\t\t\tclient: params.client,\n\t\t\t\t\tjournal: params.journal,\n\t\t\t\t\tresult: params.result,\n\t\t\t\t\toutcomeDurable: params.outcomeDurable,\n\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t});\n\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\tjournalWriteFailure ?? params.result,\n\t\t\t\t);\n\t\t\t};\n\t\t\t// Locking and observing precede the durable step boundary. The\n\t\t\t// OperationRuntime contract makes that safe: if this refusal is reached,\n\t\t\t// no DDL or external effect has occurred, so there is no step attempt to\n\t\t\t// reconcile. Previously committed steps remain in `journals`, however,\n\t\t\t// and keep the run recoverable.\n\t\t\tconst preIntentRefusal = (reason: OutcomeReason): ApplyResult =>\n\t\t\t\tresultWithCommittedJournals({\n\t\t\t\t\tassessment: stoppedAssessment(reason, journals.length > 0),\n\t\t\t\t\tjournals: [],\n\t\t\t\t\tobservations,\n\t\t\t\t});\n\t\t\tconst stepById = new Map(plan.steps.map((step) => [step.stepId, step]));\n\t\t\ttype ResolvedStep = {\n\t\t\t\treadonly step: ProvenPlanStep;\n\t\t\t\treadonly semantics: OperationRuntime;\n\t\t\t\treadonly operationIssuer: NonNullable<\n\t\t\t\t\tReturnType<PackRegistry['resolveIssuer']>\n\t\t\t\t>;\n\t\t\t\treadonly intent: DurableIntentRecord;\n\t\t\t\treadonly coordinatorBinding: ReturnType<\n\t\t\t\t\tPackRegistry['transactionCoordinatorFor']\n\t\t\t\t>;\n\t\t\t};\n\t\t\tconst preflightSegments: {\n\t\t\t\treadonly segment: InProcessProvenPlan['segments'][number];\n\t\t\t\treadonly resolvedSteps: readonly ResolvedStep[];\n\t\t\t\treadonly first: ResolvedStep;\n\t\t\t\treadonly transactional: boolean;\n\t\t\t\treadonly segmentCoordinator: ExecutionCoordinator | OperationRuntime;\n\t\t\t}[] = [];\n\t\t\tfor (const segment of plan.segments) {\n\t\t\t\tconst segmentSteps = segment.stepIds.map((stepId) =>\n\t\t\t\t\tstepById.get(stepId),\n\t\t\t\t);\n\t\t\t\tif (segmentSteps.some((step) => !step)) {\n\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t`segment ${segment.segmentId} references a missing step`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst resolvedSteps: ResolvedStep[] = [];\n\t\t\t\tfor (const step of segmentSteps as ProvenPlanStep[]) {\n\t\t\t\t\tconst operationResolution = registry.resolveOperation(step.operation);\n\t\t\t\t\tif (!operationResolution.ok) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tunresolvedOperationResult(step, operationResolution.detail),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst semantics = operationResolution.semantics;\n\t\t\t\t\tif (!isOperationRuntime(semantics)) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(unresolvedRuntimeResult(step));\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tsemantics.artifact.id !==\n\t\t\t\t\t\t\tstep.operation.operationKind.artifact.id ||\n\t\t\t\t\t\tsemantics.artifact.version !==\n\t\t\t\t\t\t\tstep.operation.operationKind.artifact.version\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(unresolvedRuntimeResult(step));\n\t\t\t\t\t}\n\t\t\t\t\tconst operationIssuer = registry.resolveIssuer(\n\t\t\t\t\t\tstep.operation.operationKind.artifact,\n\t\t\t\t\t);\n\t\t\t\t\tif (!operationIssuer) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tunresolvedOperationResult(\n\t\t\t\t\t\t\t\tstep,\n\t\t\t\t\t\t\t\t'operation observation issuer missing',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst execution = operationEffectsByRef.get(step.operation.ref)\n\t\t\t\t\t\t?.effects.execution;\n\t\t\t\t\tif (!execution) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tunresolvedOperationResult(step, 'operation effects missing'),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tsegment.transaction === 'joins-current' &&\n\t\t\t\t\t\texecution.transaction !== 'joins-current'\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t`step ${step.stepId} execution semantics do not match segment ${segment.segmentId}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tsegment.transaction === 'forbids-transaction' &&\n\t\t\t\t\t\texecution.transaction !== 'forbids-transaction'\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t`step ${step.stepId} execution semantics do not match segment ${segment.segmentId}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tsegment.transaction !== 'forbids-transaction' &&\n\t\t\t\t\t\texecution.transaction === 'forbids-transaction'\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t`step ${step.stepId} forbids the transaction used by segment ${segment.segmentId}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tresolvedSteps.push({\n\t\t\t\t\t\tstep,\n\t\t\t\t\t\tsemantics,\n\t\t\t\t\t\toperationIssuer,\n\t\t\t\t\t\tintent: intentRecord(step, run, executionId),\n\t\t\t\t\t\tcoordinatorBinding: registry.transactionCoordinatorFor(semantics),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst first = resolvedSteps[0];\n\t\t\t\tif (!first) {\n\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t`segment ${segment.segmentId} contains no steps`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst transactional = segment.transaction !== 'forbids-transaction';\n\t\t\t\tconst runtimeSet = new Set(\n\t\t\t\t\tresolvedSteps.map((entry) => entry.semantics),\n\t\t\t\t);\n\t\t\t\tlet segmentCoordinator: ExecutionCoordinator | OperationRuntime =\n\t\t\t\t\tfirst.semantics;\n\t\t\t\tif (transactional && runtimeSet.size > 1) {\n\t\t\t\t\tconst firstBinding = first.coordinatorBinding;\n\t\t\t\t\tif (!firstBinding) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t`segment ${segment.segmentId} spans multiple operation runtimes without an explicit shared transaction coordinator`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tresolvedSteps.some((entry) => {\n\t\t\t\t\t\t\tconst binding = entry.coordinatorBinding;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t!binding ||\n\t\t\t\t\t\t\t\tbinding.coordinator !== firstBinding.coordinator ||\n\t\t\t\t\t\t\t\tbinding.transactionDomain !== firstBinding.transactionDomain\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t`segment ${segment.segmentId} spans operation runtimes with different transaction coordinators`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tsegmentCoordinator = firstBinding.coordinator;\n\t\t\t\t} else if (\n\t\t\t\t\ttransactional &&\n\t\t\t\t\tfirst.coordinatorBinding &&\n\t\t\t\t\tresolvedSteps.every((entry) => {\n\t\t\t\t\t\tconst binding = entry.coordinatorBinding;\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tbinding?.coordinator === first.coordinatorBinding?.coordinator &&\n\t\t\t\t\t\t\tbinding?.transactionDomain ===\n\t\t\t\t\t\t\t\tfirst.coordinatorBinding?.transactionDomain\n\t\t\t\t\t\t);\n\t\t\t\t\t})\n\t\t\t\t) {\n\t\t\t\t\tsegmentCoordinator = first.coordinatorBinding.coordinator;\n\t\t\t\t} else if (!transactional && runtimeSet.size > 1) {\n\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t`segment ${segment.segmentId} spans multiple operation runtimes without a transaction`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tpreflightSegments.push({\n\t\t\t\t\tsegment,\n\t\t\t\t\tresolvedSteps,\n\t\t\t\t\tfirst,\n\t\t\t\t\ttransactional,\n\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!isTransitionLessor(target)) {\n\t\t\t\treturn resultWithCommittedJournals(transitionLessorRejectionResult());\n\t\t\t}\n\t\t\t// Once, and here: every check above is pure and in-memory, and nothing\n\t\t\t// below this line is unobservable — the first segment takes a lease,\n\t\t\t// opens a transaction and runs DDL. Persisting inside the loop instead\n\t\t\t// would re-persist per segment and, on a later segment, discard the\n\t\t\t// journals the earlier ones already committed.\n\t\t\ttry {\n\t\t\t\tawait persister.persist(run, plan);\n\t\t\t} catch (error) {\n\t\t\t\treturn persistenceFailureResult(run, error);\n\t\t\t}\n\t\t\tlet runtimeContext =\n\t\t\t\texecutionBoundary.kind === 'durable-contract'\n\t\t\t\t\t? executionBoundary.context\n\t\t\t\t\t: proofContext;\n\t\t\tfor (const {\n\t\t\t\tresolvedSteps,\n\t\t\t\tfirst,\n\t\t\t\ttransactional,\n\t\t\t\tsegmentCoordinator,\n\t\t\t} of preflightSegments) {\n\t\t\t\tlet client: TransitionExecutionClient | undefined;\n\t\t\t\tlet lease: TransitionLease | undefined;\n\t\t\t\tlet committed = false;\n\t\t\t\tlet transactionStarted = false;\n\t\t\t\tlet releaseFailure: TransitionLeaseFailure | undefined;\n\t\t\t\tlet active = first;\n\t\t\t\tlet activeContext = runtimeContext;\n\t\t\t\tlet activeIntentWritten = false;\n\t\t\t\tlet activeOperationAttempted = false;\n\t\t\t\tlet activeNonRollbackableOperationExecuted = false;\n\t\t\t\tconst completedInSegment: {\n\t\t\t\t\treadonly step: ProvenPlanStep;\n\t\t\t\t\treadonly semantics: OperationRuntime;\n\t\t\t\t\treadonly operationIssuer: NonNullable<\n\t\t\t\t\t\tReturnType<PackRegistry['resolveIssuer']>\n\t\t\t\t\t>;\n\t\t\t\t\treadonly intent: DurableIntentRecord;\n\t\t\t\t\treadonly stepContext: ObservationContext;\n\t\t\t\t\treadonly completion: TransactionalCompletionRecord;\n\t\t\t\t\treadonly journal?: StepJournal;\n\t\t\t\t}[] = [];\n\t\t\t\ttry {\n\t\t\t\t\tlease = await acquireTransitionLease(target);\n\t\t\t\t\tconst leasedSession = lease.session;\n\t\t\t\t\tclient = {\n\t\t\t\t\t\topaqueClient: leasedSession,\n\t\t\t\t\t\tmarkClientCompromised: () => {\n\t\t\t\t\t\t\tmarkTransitionClientCompromised(leasedSession);\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tconst executionClient = client;\n\t\t\t\t\tif (executionBoundary.kind === 'durable-contract')\n\t\t\t\t\t\tactiveContext = executionBoundary.context;\n\t\t\t\t\tif (transactional) {\n\t\t\t\t\t\tawait segmentCoordinator.begin(executionClient);\n\t\t\t\t\t\ttransactionStarted = true;\n\t\t\t\t\t\t// The reservation takes a PostgreSQL row lock. Set the plan-derived\n\t\t\t\t\t\t// bound first, so this wait and later application locks report the\n\t\t\t\t\t\t// timeout that actually applied.\n\t\t\t\t\t\tawait segmentCoordinator.setLockTimeout(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tlockTimeoutMs(first.semantics, first.step, runtimeContext),\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// PostgreSQL reservations hold the proven run row before any\n\t\t\t\t\t\t// application lock. The subsequent intent append runs on this\n\t\t\t\t\t\t// session and therefore reuses that journal lock. Coordinators\n\t\t\t\t\t\t// without this optional protocol (including the generic\n\t\t\t\t\t\t// non-transactional path) retain the old exposure: a row lock\n\t\t\t\t\t\t// cannot be held across application locking without a transaction.\n\t\t\t\t\t\tawait segmentCoordinator.reserveJournalRun?.(executionClient, run);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const entry of resolvedSteps) {\n\t\t\t\t\t\tactive = entry;\n\t\t\t\t\t\tactiveContext = runtimeContext;\n\t\t\t\t\t\tactiveIntentWritten = false;\n\t\t\t\t\t\tactiveOperationAttempted = false;\n\t\t\t\t\t\tactiveNonRollbackableOperationExecuted = false;\n\t\t\t\t\t\tawait segmentCoordinator.setLockTimeout(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, runtimeContext),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait entry.semantics.acquireLocks(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\tentry.semantics.effectsOf(entry.step.operation, runtimeContext),\n\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t\truntimeContext = await entry.semantics.observeContext(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t\truntimeContext =\n\t\t\t\t\t\t\tregistry.contextWithDerivedCapabilities(runtimeContext);\n\t\t\t\t\t\tconst stepContext = runtimeContext;\n\t\t\t\t\t\tactiveContext = stepContext;\n\t\t\t\t\t\tconst liveContextMatch = contextMatchAtExecutionBoundary(\n\t\t\t\t\t\t\texecutionBoundary,\n\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!liveContextMatch.ok) {\n\t\t\t\t\t\t\tconst mismatchDetail = liveContextMatch.detail;\n\t\t\t\t\t\t\tconst mismatch = contextMismatchReason(\n\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\tmismatchDetail,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\t\t\t\tcontextMismatchReason(\n\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\terrorDetail(\n\t\t\t\t\t\t\t\t\t\t\t\tapplyAndRollbackFailure(\n\t\t\t\t\t\t\t\t\t\t\t\t\tnew Error(mismatchDetail),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcleanupError,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn preIntentRefusal(mismatch);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst before = await entry.semantics.observeOperation(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t'before',\n\t\t\t\t\t\t\tentry.operationIssuer,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tobservations.push(...before.observations);\n\t\t\t\t\t\tlet currentFingerprints: ReturnType<\n\t\t\t\t\t\t\tOperationRuntime['buildFingerprints']\n\t\t\t\t\t\t>;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcurrentFingerprints = entry.semantics.buildFingerprints(\n\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\tdurableEvidence(before.observations),\n\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tlet reportedError = error;\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\t\t\t\treportedError = applyAndRollbackFailure(error, cleanupError);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// A builder failure cannot establish drift. Preserve an\n\t\t\t\t\t\t\t// observed unknown outcome, including the original cause, so\n\t\t\t\t\t\t\t// admission will not turn an evidence failure into a pristine\n\t\t\t\t\t\t\t// re-planning loop.\n\t\t\t\t\t\t\tconst journal = unknownJournal(entry.intent);\n\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\t\t\tstepId: entry.step.stepId,\n\t\t\t\t\t\t\t\t\t\toperationKind: entry.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\t\toperationRef: entry.step.operation.ref,\n\t\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t\t\tdetail: `expectedBefore fingerprint construction failed: ${errorDetail(reportedError)}`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!fingerprintMatches(\n\t\t\t\t\t\t\t\tentry.step.expectedBefore,\n\t\t\t\t\t\t\t\tcurrentFingerprints.expectedBefore,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst mismatchDetail = 'expectedBefore mismatch';\n\t\t\t\t\t\t\tconst mismatch = contextMismatchReason(\n\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\tmismatchDetail,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\t\t\t\tcontextMismatchReason(\n\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\terrorDetail(\n\t\t\t\t\t\t\t\t\t\t\t\tapplyAndRollbackFailure(\n\t\t\t\t\t\t\t\t\t\t\t\t\tnew Error(mismatchDetail),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcleanupError,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn preIntentRefusal(mismatch);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst managedClaim =\n\t\t\t\t\t\t\texecutionBoundary.kind === 'durable-contract'\n\t\t\t\t\t\t\t\t? entry.step.managedClaim\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\texecutionBoundary.kind === 'durable-contract' &&\n\t\t\t\t\t\t\tentry.semantics.executionContractEligibility?.eligible === true &&\n\t\t\t\t\t\t\t!managedClaim\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(\n\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t'managed-eligible step has no immutable managed claim material',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (managedClaim) {\n\t\t\t\t\t\t\tconst preflightManagedOutcome =\n\t\t\t\t\t\t\t\tentry.semantics.preflightManagedOutcome;\n\t\t\t\t\t\t\tif (preflightManagedOutcome) {\n\t\t\t\t\t\t\t\tconst detail = await preflightManagedOutcome(executionClient, {\n\t\t\t\t\t\t\t\t\tclaim: managedClaim,\n\t\t\t\t\t\t\t\t\trun,\n\t\t\t\t\t\t\t\t\ttransactional,\n\t\t\t\t\t\t\t\t\tlockTimeoutMs: lockTimeoutMs(\n\t\t\t\t\t\t\t\t\t\tentry.semantics,\n\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (detail) {\n\t\t\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\t\t\tlockTimeoutMs(\n\t\t\t\t\t\t\t\t\t\t\t\t\tentry.semantics,\n\t\t\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t\t\tactiveContext,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(\n\t\t\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t\t\terrorDetail(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tapplyAndRollbackFailure(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew Error(detail),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcleanupError,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(entry.step, detail),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Mark before awaiting: a write error can still mean the intent\n\t\t\t\t\t\t// reached durable storage, so downstream recovery must remain\n\t\t\t\t\t\t// conservative.\n\t\t\t\t\t\tactiveIntentWritten = true;\n\t\t\t\t\t\tawait entry.semantics.writeIntentJournal(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst runGuardPhase = async (\n\t\t\t\t\t\t\tphase: ProvenPlanStep['guards'][number]['phase'],\n\t\t\t\t\t\t\tnonRollbackableOperationExecuted = false,\n\t\t\t\t\t\t): Promise<ApplyResult | undefined> => {\n\t\t\t\t\t\t\tfor (const guard of entry.step.guards.filter(\n\t\t\t\t\t\t\t\t(candidate) => candidate.phase === phase,\n\t\t\t\t\t\t\t)) {\n\t\t\t\t\t\t\t\tconst guardResult = await entry.semantics.checkGuard(\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\t\tguard,\n\t\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tobservations.push(...guardResult.observations);\n\t\t\t\t\t\t\t\tif (!guardResult.passed) {\n\t\t\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst hasAppliedWork =\n\t\t\t\t\t\t\t\t\t\tjournals.length > 0 || nonRollbackableOperationExecuted;\n\t\t\t\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t\t\t\t\tnonRollbackableOperationExecuted\n\t\t\t\t\t\t\t\t\t\t\t? 'partially-applied'\n\t\t\t\t\t\t\t\t\t\t\t: 'guard-failed',\n\t\t\t\t\t\t\t\t\t\tguardResult.observations,\n\t\t\t\t\t\t\t\t\t\tguardResult.recovery,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tconst guardFailureReason = guardFailedReason(\n\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\tguard,\n\t\t\t\t\t\t\t\t\t\tguardResult.recovery,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\t\t\tassessment: hasAppliedWork\n\t\t\t\t\t\t\t\t\t\t\t? assessment(\n\t\t\t\t\t\t\t\t\t\t\t\t\tguardFailureReason,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'resume-possible',\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t: stoppedAssessment(guardFailureReason, false),\n\t\t\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tconst journalWriteFailure =\n\t\t\t\t\t\t\t\t\t\tawait writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\t\t\toutcomeDurable: nonRollbackableOperationExecuted,\n\t\t\t\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treturn journalWriteFailure ?? result;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst beforeGuardFailure = await runGuardPhase('before-operation');\n\t\t\t\t\t\tif (beforeGuardFailure) {\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(beforeGuardFailure);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tactiveOperationAttempted = true;\n\t\t\t\t\t\tconst nonRollbackableExecutionTracker = {\n\t\t\t\t\t\t\tmarkNonRollbackableOperationExecuted: () => {\n\t\t\t\t\t\t\t\tactiveNonRollbackableOperationExecuted = true;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst executionOutcome = managedClaim\n\t\t\t\t\t\t\t? await (() => {\n\t\t\t\t\t\t\t\t\tconst executeManagedOutcome =\n\t\t\t\t\t\t\t\t\t\tentry.semantics.executeManagedOutcome;\n\t\t\t\t\t\t\t\t\tif (!executeManagedOutcome)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t`managed claim ${managedClaim.plannedClaimKey} has no outcome execution adapter`,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\treturn executeManagedOutcome(executionClient, {\n\t\t\t\t\t\t\t\t\t\tclaim: managedClaim,\n\t\t\t\t\t\t\t\t\t\trun,\n\t\t\t\t\t\t\t\t\t\tdurablyLoadedRun,\n\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t\ttransactional,\n\t\t\t\t\t\t\t\t\t\tlockTimeoutMs: lockTimeoutMs(\n\t\t\t\t\t\t\t\t\t\t\tentry.semantics,\n\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\treadBack: async () => {\n\t\t\t\t\t\t\t\t\t\t\tconst observed = await entry.semantics.observeOperation(\n\t\t\t\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t\t\t\t\t'after',\n\t\t\t\t\t\t\t\t\t\t\t\tentry.operationIssuer,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\treturn managedOutcomeReadBack(observed.observations);\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t\t: await entry.semantics.executeOperation(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\topaqueClient: planOperationSession(\n\t\t\t\t\t\t\t\t\t\t\texecutionClient.opaqueClient,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\tmarkClientCompromised:\n\t\t\t\t\t\t\t\t\t\t\texecutionClient.markClientCompromised,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t\tentry.step.guards.filter(\n\t\t\t\t\t\t\t\t\t\t(guard) => guard.phase === 'during-operation',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tnonRollbackableExecutionTracker,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\tif (executionOutcome.kind === 'recovery-required') {\n\t\t\t\t\t\t\texecutionClient.markClientCompromised();\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings({\n\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t`claim ${executionOutcome.claimId} remains open and requires recovery: ${executionOutcome.detail}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals,\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\tunresolvedOutcome: executionOutcome,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (executionOutcome.kind === 'transport-ambiguous') {\n\t\t\t\t\t\t\texecutionClient.markClientCompromised();\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings({\n\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t`managed outcome transport is ambiguous: ${executionOutcome.detail}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals,\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\tunresolvedOutcome: executionOutcome,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (executionOutcome.kind === 'guard-failed') {\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst nonRollbackableFootprint =\n\t\t\t\t\t\t\t\texecutionOutcome.nonRollbackableFootprint ??\n\t\t\t\t\t\t\t\t'unknown-or-present';\n\t\t\t\t\t\t\tconst currentStepHasDurableFootprint =\n\t\t\t\t\t\t\t\tactiveNonRollbackableOperationExecuted &&\n\t\t\t\t\t\t\t\tnonRollbackableFootprint === 'unknown-or-present';\n\t\t\t\t\t\t\tconst hasCommittedSteps = journals.length > 0;\n\t\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t\t\thasCommittedSteps || currentStepHasDurableFootprint\n\t\t\t\t\t\t\t\t\t? 'partially-applied'\n\t\t\t\t\t\t\t\t\t: 'guard-failed',\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t\texecutionOutcome.recovery,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst reason = guardFailedReason(\n\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\texecutionOutcome.guard,\n\t\t\t\t\t\t\t\texecutionOutcome.recovery,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst hasAppliedWork =\n\t\t\t\t\t\t\t\thasCommittedSteps || currentStepHasDurableFootprint;\n\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\tassessment: hasAppliedWork\n\t\t\t\t\t\t\t\t\t? assessment(reason, 'partially-applied', 'resume-possible')\n\t\t\t\t\t\t\t\t\t: stoppedAssessment(reason, false),\n\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\toutcomeDurable: currentStepHasDurableFootprint,\n\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\t\t\t\tjournalWriteFailure ?? result,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (executionOutcome.kind === 'partially-applied') {\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (transactional) {\n\t\t\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\t\t\texecutionOutcome.detail ??\n\t\t\t\t\t\t\t\t\t'operation reported a partial outcome before commit; transaction rolled back';\n\t\t\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t\t\t\t'operation-failed-not-applied',\n\t\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t\t\texecutionOutcome.recovery,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\t\tassessment: stoppedAssessment(\n\t\t\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(entry.step, detail),\n\t\t\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\toutcomeDurable: journals.length > 0,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t\texecutionOutcome.recovery,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\texecutionOutcome.detail ??\n\t\t\t\t\t\t\t\t\t\t\t'operation partially applied and requires recovery',\n\t\t\t\t\t\t\t\t\t\texecutionOutcome.recovery,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t\t'resume-possible',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\t\t\t\tjournalWriteFailure ?? result,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst afterGuardFailure = await runGuardPhase(\n\t\t\t\t\t\t\t'after-operation',\n\t\t\t\t\t\t\tactiveNonRollbackableOperationExecuted,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (afterGuardFailure) {\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(afterGuardFailure);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst postconditionAfterCommit =\n\t\t\t\t\t\t\toperationEffectsByRef.get(entry.step.operation.ref)?.effects\n\t\t\t\t\t\t\t\t.execution.postconditionVisibility === 'after-commit';\n\t\t\t\t\t\tif (postconditionAfterCommit) {\n\t\t\t\t\t\t\tif (!transactional || resolvedSteps.length !== 1) {\n\t\t\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\t\t\tuncomposablePlanResult(\n\t\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\t\t`step ${entry.step.stepId} postcondition is only visible after commit and must execute in its own transactional segment`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst completion = completionRecord(\n\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\trun,\n\t\t\t\t\t\t\t\ttransactional,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait entry.semantics.writeCompletionJournal(\n\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\tcompletion,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcompletedInSegment.push({\n\t\t\t\t\t\t\t\tstep: entry.step,\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\toperationIssuer: entry.operationIssuer,\n\t\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\tcompletion,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet after: Awaited<\n\t\t\t\t\t\t\tReturnType<OperationRuntime['observeOperation']>\n\t\t\t\t\t\t>;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tafter = await entry.semantics.observeOperation(\n\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\t'after',\n\t\t\t\t\t\t\t\tentry.operationIssuer,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\t\tentry.intent,\n\t\t\t\t\t\t\t\ttransactional\n\t\t\t\t\t\t\t\t\t? 'operation-failed-not-applied'\n\t\t\t\t\t\t\t\t\t: 'partially-applied',\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t\t: 'after observation failed';\n\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\tassessment: transactional\n\t\t\t\t\t\t\t\t\t? stoppedAssessment(\n\t\t\t\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(\n\t\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t\t`expectedAfter observation failed before commit: ${detail}`,\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t: assessment(\n\t\t\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(entry.step, detail),\n\t\t\t\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\toutcomeDurable: !transactional,\n\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\t\t\t\tjournalWriteFailure ?? result,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tobservations.push(...after.observations);\n\t\t\t\t\t\tconst observedOutcome = {\n\t\t\t\t\t\t\tstepId: entry.step.stepId,\n\t\t\t\t\t\t\tobservations: evidenceIds(after.observations),\n\t\t\t\t\t\t\trecordedAt: recordedAt(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!fingerprintMatches(entry.step.expectedAfter, after.fingerprint)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tif (transactionStarted && !committed) {\n\t\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tlockTimeoutMs(entry.semantics, entry.step, activeContext),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst journal: StepJournal = {\n\t\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\t\toutcome: transactional\n\t\t\t\t\t\t\t\t\t? 'operation-failed-not-applied'\n\t\t\t\t\t\t\t\t\t: 'partially-applied',\n\t\t\t\t\t\t\t\tobservedOutcome,\n\t\t\t\t\t\t\t\trecovery: [],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\tassessment: transactional\n\t\t\t\t\t\t\t\t\t? stoppedAssessment(\n\t\t\t\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(\n\t\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t\t'expectedAfter mismatch before commit',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t: assessment(\n\t\t\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t\t'expectedAfter mismatch',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\toutcomeDurable: !transactional,\n\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\t\t\t\tjournalWriteFailure ?? result,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completion = completionRecord(entry.step, run, transactional);\n\t\t\t\t\t\tawait entry.semantics.writeCompletionJournal(\n\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\tcompletion,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst journal: StepJournal = {\n\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\toutcome: 'completed',\n\t\t\t\t\t\t\ttransactionalCompletion: completion,\n\t\t\t\t\t\t\tobservedOutcome,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (transactional) {\n\t\t\t\t\t\t\tcompletedInSegment.push({\n\t\t\t\t\t\t\t\tstep: entry.step,\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\toperationIssuer: entry.operationIssuer,\n\t\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\t\tstepContext,\n\t\t\t\t\t\t\t\tcompletion,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst journalWrite = await writeObservedJournalOutcome({\n\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (!journalWrite.ok) {\n\t\t\t\t\t\t\t\trecordJournalWriteWarning(journalWrite.error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjournals.push(journal);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (transactional) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait segmentCoordinator.commit(executionClient);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new CommitOutcomeUncertainError(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommitted = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const entry of completedInSegment) {\n\t\t\t\t\t\tlet journal = entry.journal;\n\t\t\t\t\t\tif (!journal) {\n\t\t\t\t\t\t\tlet after: Awaited<\n\t\t\t\t\t\t\t\tReturnType<OperationRuntime['observeOperation']>\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tafter = await entry.semantics.observeOperation(\n\t\t\t\t\t\t\t\t\texecutionClient,\n\t\t\t\t\t\t\t\t\tentry.step.operation,\n\t\t\t\t\t\t\t\t\tentry.stepContext,\n\t\t\t\t\t\t\t\t\t'after',\n\t\t\t\t\t\t\t\t\tentry.operationIssuer,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tconst unknown = unknownJournal(entry.intent);\n\t\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\t\t\t\tstepId: entry.step.stepId,\n\t\t\t\t\t\t\t\t\t\t\toperationKind: entry.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\t\t\toperationRef: entry.step.operation.ref,\n\t\t\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t\t\t\tdetail: `after-commit expectedAfter observation failed after commit: ${errorDetail(error)}`,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tjournals: [...journals, unknown],\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\treturn await resultWithObservedJournal({\n\t\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\t\tjournal: unknown,\n\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tobservations.push(...after.observations);\n\t\t\t\t\t\t\tconst observedOutcome = {\n\t\t\t\t\t\t\t\tstepId: entry.step.stepId,\n\t\t\t\t\t\t\t\tobservations: evidenceIds(after.observations),\n\t\t\t\t\t\t\t\trecordedAt: recordedAt(),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!fingerprintMatches(entry.step.expectedAfter, after.fingerprint)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst journalWithMismatch: StepJournal = {\n\t\t\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\t\t\toutcome: 'partially-applied',\n\t\t\t\t\t\t\t\t\tobservedOutcome,\n\t\t\t\t\t\t\t\t\trecovery: [],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\t\t\tentry.step,\n\t\t\t\t\t\t\t\t\t\t\t'expectedAfter mismatch after commit',\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tjournals: [...journals, journalWithMismatch],\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst journalWriteFailure = await writeObservedJournalOrResult({\n\t\t\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\t\t\tjournal: journalWithMismatch,\n\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t\t\t\tonDurableWriteWarning: recordJournalWriteWarning,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\treturn resultWithJournalWriteWarnings(\n\t\t\t\t\t\t\t\t\tjournalWriteFailure ?? result,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjournal = {\n\t\t\t\t\t\t\t\tintent: entry.intent,\n\t\t\t\t\t\t\t\toutcome: 'completed',\n\t\t\t\t\t\t\t\ttransactionalCompletion: entry.completion,\n\t\t\t\t\t\t\t\tobservedOutcome,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst journalWrite = await writeObservedJournalOutcome({\n\t\t\t\t\t\t\tsemantics: entry.semantics,\n\t\t\t\t\t\t\tclient: executionClient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!journalWrite.ok) {\n\t\t\t\t\t\t\trecordJournalWriteWarning(journalWrite.error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjournals.push(journal);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst lessorRejectionDetail = transitionLessorRejectionDetail(error);\n\t\t\t\t\tif (lessorRejectionDetail) {\n\t\t\t\t\t\treturn resultWithCommittedJournals(\n\t\t\t\t\t\t\ttransitionLessorRejectionResult(lessorRejectionDetail),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treleaseFailure = { error };\n\t\t\t\t\tif (error instanceof CommitOutcomeUncertainError) {\n\t\t\t\t\t\t// COMMIT may have reached PostgreSQL even though its acknowledgement\n\t\t\t\t\t\t// was lost. This lease must never return to the pool, and no observed\n\t\t\t\t\t\t// journal append may turn transport ambiguity into a claimed fact.\n\t\t\t\t\t\tclient?.markClientCompromised();\n\t\t\t\t\t\tconst journal = unknownJournal(active.intent);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\t\tstepId: active.step.stepId,\n\t\t\t\t\t\t\t\t\toperationKind: active.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\toperationRef: active.step.operation.ref,\n\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t\tdetail: `commit outcome uncertain after commit failure: ${errorDetail(error.originalError)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\tlet rollbackAttempted = false;\n\t\t\t\t\tlet rollbackSucceeded = false;\n\t\t\t\t\tif (client && transactionStarted && !committed) {\n\t\t\t\t\t\trollbackAttempted = true;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait rollbackAndPrepareObservedJournalWrite(\n\t\t\t\t\t\t\t\tsegmentCoordinator,\n\t\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\t\tlockTimeoutMs(active.semantics, active.step, activeContext),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\trollbackSucceeded = true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// The outcome below reports uncertainty; resume must re-introspect.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\trollbackAttempted &&\n\t\t\t\t\t\t!rollbackSucceeded &&\n\t\t\t\t\t\t(activeOperationAttempted || completedInSegment.length > 0)\n\t\t\t\t\t) {\n\t\t\t\t\t\t// Attribute uncertainty to the earliest operation that ran in this\n\t\t\t\t\t\t// segment. The durable record cannot yet express reconcilable\n\t\t\t\t\t\t// segment uncertainty, so an unconfirmed rollback after executed\n\t\t\t\t\t\t// work requires human intervention.\n\t\t\t\t\t\tconst uncertain = completedInSegment[0] ?? active;\n\t\t\t\t\t\tconst journal = unknownJournal(uncertain.intent);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\t\tstepId: uncertain.step.stepId,\n\t\t\t\t\t\t\t\t\toperationKind: uncertain.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\toperationRef: uncertain.step.operation.ref,\n\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t\t\t? `rollback outcome uncertain after failure: ${error.message}; human intervention is required because the durable record cannot yet express reconcilable segment uncertainty`\n\t\t\t\t\t\t\t\t\t\t\t: 'rollback outcome uncertain after apply failure; human intervention is required because the durable record cannot yet express reconcilable segment uncertainty',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: uncertain.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (!activeIntentWritten) {\n\t\t\t\t\t\tif (segmentCoordinator.isLockTimeout(error)) {\n\t\t\t\t\t\t\treturn preIntentRefusal({\n\t\t\t\t\t\t\t\tcode: 'guard-timeout',\n\t\t\t\t\t\t\t\tstepId: active.step.stepId,\n\t\t\t\t\t\t\t\toperationKind: active.step.operation.operationKind,\n\t\t\t\t\t\t\t\toperationRef: active.step.operation.ref,\n\t\t\t\t\t\t\t\tmaxWaitMs: lockTimeoutMs(\n\t\t\t\t\t\t\t\t\tactive.semantics,\n\t\t\t\t\t\t\t\t\tactive.step,\n\t\t\t\t\t\t\t\t\tactiveContext,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn preIntentRefusal(\n\t\t\t\t\t\t\toperationFailedNotAppliedReason(\n\t\t\t\t\t\t\t\tactive.step,\n\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t\t: 'operation setup failed before intent',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (segmentCoordinator.isLockTimeout(error)) {\n\t\t\t\t\t\tconst hasAppliedWork =\n\t\t\t\t\t\t\tjournals.length > 0 || activeNonRollbackableOperationExecuted;\n\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\tactive.intent,\n\t\t\t\t\t\t\tactiveNonRollbackableOperationExecuted\n\t\t\t\t\t\t\t\t? 'partially-applied'\n\t\t\t\t\t\t\t\t: 'guard-timeout',\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: stoppedAssessment(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'guard-timeout',\n\t\t\t\t\t\t\t\t\tstepId: active.step.stepId,\n\t\t\t\t\t\t\t\t\toperationKind: active.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\toperationRef: active.step.operation.ref,\n\t\t\t\t\t\t\t\t\tmaxWaitMs: lockTimeoutMs(\n\t\t\t\t\t\t\t\t\t\tactive.semantics,\n\t\t\t\t\t\t\t\t\t\tactive.step,\n\t\t\t\t\t\t\t\t\t\tactiveContext,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\thasAppliedWork,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: hasAppliedWork,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (!activeOperationAttempted) {\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'operation setup failed before executeOperation';\n\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\tactive.intent,\n\t\t\t\t\t\t\t'operation-failed-not-applied',\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: stoppedAssessment(\n\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(active.step, detail),\n\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: journals.length > 0,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\ttransactional &&\n\t\t\t\t\t\trollbackAttempted &&\n\t\t\t\t\t\trollbackSucceeded &&\n\t\t\t\t\t\t!activeNonRollbackableOperationExecuted\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'operation failed before commit';\n\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\tactive.intent,\n\t\t\t\t\t\t\t'operation-failed-not-applied',\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: stoppedAssessment(\n\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(active.step, detail),\n\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: journals.length > 0,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (!committed && !activeNonRollbackableOperationExecuted) {\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'operation failed before non-rollbackable DDL was reached';\n\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\tactive.intent,\n\t\t\t\t\t\t\t'operation-failed-not-applied',\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: stoppedAssessment(\n\t\t\t\t\t\t\t\toperationFailedNotAppliedReason(active.step, detail),\n\t\t\t\t\t\t\t\tjournals.length > 0,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: journals.length > 0,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (committed || activeNonRollbackableOperationExecuted) {\n\t\t\t\t\t\tconst journal = journalWithObserved(\n\t\t\t\t\t\t\tactive.intent,\n\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\tpartiallyAppliedReason(\n\t\t\t\t\t\t\t\t\tactive.step,\n\t\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t\t\t: 'segment failed after an earlier commit',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t'partially-applied',\n\t\t\t\t\t\t\t\t'resume-possible',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (journals.length > 0) {\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'segment failed after an earlier commit without a confirmed rollback';\n\t\t\t\t\t\tconst journal = unknownJournal(active.intent);\n\t\t\t\t\t\tconst result = {\n\t\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\t\tstepId: active.step.stepId,\n\t\t\t\t\t\t\t\t\toperationKind: active.step.operation.operationKind,\n\t\t\t\t\t\t\t\t\toperationRef: active.step.operation.ref,\n\t\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\t\tdetail,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst journal = unknownJournal(active.intent);\n\t\t\t\t\tconst result = {\n\t\t\t\t\t\tassessment: assessment(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\t\t\t\t\tstepId: active.step.stepId,\n\t\t\t\t\t\t\t\toperationKind: active.step.operation.operationKind,\n\t\t\t\t\t\t\t\toperationRef: active.step.operation.ref,\n\t\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t\t\t: 'unknown apply error',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t'outcome-unknown',\n\t\t\t\t\t\t\t'human-intervention-required',\n\t\t\t\t\t\t),\n\t\t\t\t\t\tjournals: [...journals, journal],\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t};\n\t\t\t\t\treturn resultWithObservedJournal({\n\t\t\t\t\t\tsemantics: active.semantics,\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\tjournal,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\toutcomeDurable: true,\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tif (lease) {\n\t\t\t\t\t\tawait lease.release(releaseFailure);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn resultWithJournalWriteWarnings({\n\t\t\t\tassessment: completedAssessment(reportedAssessment),\n\t\t\t\tjournals,\n\t\t\t\tobservations,\n\t\t\t});\n\t\t},\n\t\tasync applyDurable(input: DurableApplyInput): Promise<DurableApplyResult> {\n\t\t\tlet loaded: TransitionRunJournal & { readonly plan: ProvenPlanShape };\n\t\t\ttry {\n\t\t\t\tconst supplied = await input.loadCurrent(input.runId);\n\t\t\t\tloaded = JSON.parse(JSON.stringify(supplied)) as typeof supplied;\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'load-failed',\n\t\t\t\t\t`run could not be loaded: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (loaded.run.runId !== input.runId) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'run-id-mismatch',\n\t\t\t\t\t'loaded run id does not match requested run id',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (loaded.run.coreVersion !== '0.3.0') {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'compatibility-refusal',\n\t\t\t\t\t`run is execution-ineligible; re-plan (execution compatibility epoch ${loaded.run.coreVersion} is not supported; expected 0.3.0)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet plan: InProcessProvenPlan;\n\t\t\ttry {\n\t\t\t\t// The durable evidence is immutable before any adapter extension can\n\t\t\t\t// inspect it. Callbacks receive this same verified snapshot.\n\t\t\t\tplan = snapshotDurablePlan(loaded.plan);\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t`loaded plan could not be snapshotted safely: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet observedPlanDigest: string;\n\t\t\ttry {\n\t\t\t\tobservedPlanDigest = transitionPlanDigest(plan);\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t`loaded plan could not be digested: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.expectedPlanDigest !== observedPlanDigest) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-digest-mismatch',\n\t\t\t\t\t`reviewed plan digest does not match the stored plan: expected ${input.expectedPlanDigest}; observed ${observedPlanDigest}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (loaded.run.planDigest !== observedPlanDigest) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'digest-mismatch',\n\t\t\t\t\t'loaded plan digest does not match run metadata',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst contract = validateExecutionContract(plan.executionContract);\n\t\t\tif (!contract.ok)\n\t\t\t\treturn durableRefusal('execution-contract-refused', contract.detail);\n\t\t\tlet structural: ReturnType<typeof validateTransitionRelationalInvariants>;\n\t\t\ttry {\n\t\t\t\tstructural = validateTransitionRelationalInvariants({\n\t\t\t\t\tkind: 'plan',\n\t\t\t\t\tplan,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t`loaded plan could not be structurally validated: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!structural.ok)\n\t\t\t\treturn durableRefusal('plan-validation-failed', structural.detail);\n\t\t\tif (loaded.events.length > 0) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'prior-step-events-refusal',\n\t\t\t\t\t'run has prior step-attempt events; run dbsp reconcile --db <database> <run-id>',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst nonTransactionalAssumptions = plan.assumptions.filter(\n\t\t\t\t(assumption) => assumption.class === 'non-transactional-segment',\n\t\t\t);\n\t\t\tif (\n\t\t\t\tplan.segments.some(\n\t\t\t\t\t(segment) => segment.transaction === 'forbids-transaction',\n\t\t\t\t) &&\n\t\t\t\t(nonTransactionalAssumptions.length === 0 ||\n\t\t\t\t\t!nonTransactionalAssumptions.every((assumption) =>\n\t\t\t\t\t\tassumptionAccepted(assumption, input.policy),\n\t\t\t\t\t))\n\t\t\t) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'transactional-only-refusal',\n\t\t\t\t\t\"durable apply executes segments that forbid a transaction block only when the plan's non-transactional-segment assumption is accepted; run was not attempted\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst context = plan.observations.find(\n\t\t\t\t(observation) => observation.role === 'evidence',\n\t\t\t)?.context;\n\t\t\tif (!context)\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t'loaded plan has no evidence observation context',\n\t\t\t\t);\n\t\t\tconst effects = new Map<string, OperationEffectAssessment>();\n\t\t\tfor (const step of plan.steps) {\n\t\t\t\tlet resolution: ReturnType<typeof registry.resolveOperation>;\n\t\t\t\ttry {\n\t\t\t\t\tresolution = registry.resolveOperation(step.operation);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t\t`operation ${step.operation.ref} could not be resolved: ${errorDetail(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!resolution.ok ||\n\t\t\t\t\tresolution.semantics.artifact.id !==\n\t\t\t\t\t\tstep.operation.operationKind.artifact.id ||\n\t\t\t\t\tresolution.semantics.artifact.version !==\n\t\t\t\t\t\tstep.operation.operationKind.artifact.version\n\t\t\t\t) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'operation-unavailable',\n\t\t\t\t\t\t`required operation artifact ${step.operation.operationKind.artifact.id}@${step.operation.operationKind.artifact.version} is unavailable`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\teffects.set(\n\t\t\t\t\t\tstep.operation.ref,\n\t\t\t\t\t\tresolution.semantics.effectsOf(step.operation, context),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t\t`operation ${step.operation.ref} could not be validated: ${errorDetail(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet semantic: ReturnType<typeof validateTransitionRelationalInvariants>;\n\t\t\ttry {\n\t\t\t\tsemantic = validateTransitionRelationalInvariants({\n\t\t\t\t\tkind: 'plan',\n\t\t\t\t\tplan,\n\t\t\t\t\toperationEffectsByRef: effects,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'plan-validation-failed',\n\t\t\t\t\t`loaded plan could not be semantically validated: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!semantic.ok)\n\t\t\t\treturn durableRefusal('plan-validation-failed', semantic.detail);\n\t\t\tconst durablyLoadedRun = mintDurablyLoadedRun(loaded.run);\n\t\t\tfor (const assumption of plan.assumptions) {\n\t\t\t\tif (!assumptionAccepted(assumption, input.policy)) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'assumption-not-accepted',\n\t\t\t\t\t\t`assumption ${assumption.id} (${assumption.class}) is not accepted for its trust root and scope`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet lease: TransitionLease | undefined;\n\t\t\tlet leaseReleaseFailure: TransitionLeaseFailure | undefined;\n\t\t\ttry {\n\t\t\t\tlease = await acquireExclusiveTransitionLease(input.target);\n\t\t\t} catch (error) {\n\t\t\t\treturn durableRefusal(\n\t\t\t\t\t'execution-preflight-failed',\n\t\t\t\t\t`execution preflight lease could not be acquired: ${errorDetail(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst preflightLease = lease;\n\t\t\t\tlet prepared: Awaited<ReturnType<typeof input.prepareExecutionSession>>;\n\t\t\t\ttry {\n\t\t\t\t\tprepared = await input.prepareExecutionSession(\n\t\t\t\t\t\tpreflightLease.session,\n\t\t\t\t\t\tcontract.contract,\n\t\t\t\t\t\tplan,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'execution-preflight-failed',\n\t\t\t\t\t\t`execution preflight query failed: ${errorDetail(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!prepared.ok)\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\tprepared.kind === 'read-only'\n\t\t\t\t\t\t\t? 'database-read-only'\n\t\t\t\t\t\t\t: prepared.kind === 'failed'\n\t\t\t\t\t\t\t\t? 'execution-preflight-failed'\n\t\t\t\t\t\t\t\t: 'execution-contract-refused',\n\t\t\t\t\t\tprepared.detail,\n\t\t\t\t\t);\n\t\t\t\ttry {\n\t\t\t\t\tawait input.authorize(loaded.run, plan, preflightLease.session);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\t'authorization-write-failed',\n\t\t\t\t\t\t`authorization could not be committed: ${errorDetail(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst pinnedTarget = remintTransitionLessorFromSession(\n\t\t\t\t\tpreflightLease.session,\n\t\t\t\t\tasync () => ({\n\t\t\t\t\t\tquery: (sql: string, params?: unknown) =>\n\t\t\t\t\t\t\tpreflightLease.session.query(sql, params),\n\t\t\t\t\t\t// Re-minting the logical lease retains the preflight revocation capability.\n\t\t\t\t\t\t// The ordinary channel remains available to durable infrastructure.\n\t\t\t\t\t\tqueryPlanOperation: (sql: string, params?: unknown) =>\n\t\t\t\t\t\t\tplanOperationSession(preflightLease.session).query(sql, params),\n\t\t\t\t\t\t// apply() owns logical segment leases, but this outer durable\n\t\t\t\t\t\t// boundary owns the physical connection until apply() has settled:\n\t\t\t\t\t\t// post-step observed-journal writes still use this session.\n\t\t\t\t\t\trelease: (error?: unknown) => {\n\t\t\t\t\t\t\tif (error) leaseReleaseFailure ??= { error };\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Await before this try's finally returns the physical lease. A bare\n\t\t\t\t// return would run finally while apply() still owns its logical leases\n\t\t\t\t// and can still owe an observed-journal write.\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await this.apply(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\tassessment: derivedApplicableAssessment(plan),\n\t\t\t\t\t\t\t__durableRun: loaded.run,\n\t\t\t\t\t\t\t__durablyLoadedRun: durablyLoadedRun,\n\t\t\t\t\t\t\t__executionId: `dbsp.transition.execution.${randomUUID()}`,\n\t\t\t\t\t\t\t__executionBoundary: {\n\t\t\t\t\t\t\t\tkind: 'durable-contract',\n\t\t\t\t\t\t\t\tcontext: prepared.context,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} as DurableExecutionCarrier,\n\t\t\t\t\t\tinput.policy,\n\t\t\t\t\t\tpinnedTarget,\n\t\t\t\t\t);\n\t\t\t\t\treturn durableExecutionResult(result);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn durableRefusal(\n\t\t\t\t\t\tisDatabaseReadOnlyError(error)\n\t\t\t\t\t\t\t? 'database-read-only'\n\t\t\t\t\t\t\t: 'execution-failed',\n\t\t\t\t\t\t`execution phase failed: ${errorDetail(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tif (lease) await lease.release(leaseReleaseFailure);\n\t\t\t}\n\t\t},\n\t\tasync resume(journal, readContext, policy, target, admitRecovery) {\n\t\t\tconst result = await resumeTransitionRun(registry, {\n\t\t\t\tjournal,\n\t\t\t\treadContext,\n\t\t\t\ttarget,\n\t\t\t\t...(policy ? { policy } : {}),\n\t\t\t\t...(admitRecovery ? { admitRecovery } : {}),\n\t\t\t});\n\t\t\treturn { ...result, recoveryOutcome: recoveryOutcome(result) };\n\t\t},\n\t};\n}\n","import { createHash } from 'node:crypto';\nimport type { ObservationContext, TransitionRunMetadata } from '@dbsp/types';\nimport {\n\tfirstObservationContextIdentityMismatch,\n\tfirstObservationContextNucleusMismatch,\n} from './context-compat.js';\nimport { stableJson } from './stable-json.js';\n\nexport type ObservationContextMatchResult =\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly detail: string };\n\nexport function observationContextDigest(context: ObservationContext): string {\n\treturn createHash('sha256').update(stableJson(context)).digest('hex');\n}\n\nexport function matchLiveObservationContext(params: {\n\treadonly expected: ObservationContext;\n\treadonly actual: ObservationContext;\n\treadonly label?: string;\n}): ObservationContextMatchResult {\n\tconst label = params.label ?? 'live observation context';\n\tif (params.actual.databaseId !== params.expected.databaseId) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `${label} databaseId ${params.actual.databaseId} does not match proof databaseId ${params.expected.databaseId}`,\n\t\t};\n\t}\n\tconst mismatchedField = firstObservationContextNucleusMismatch(\n\t\tparams.expected,\n\t\tparams.actual,\n\t);\n\tif (mismatchedField) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `${label} nucleus differs from proof context at ${mismatchedField}`,\n\t\t};\n\t}\n\treturn { ok: true };\n}\n\nexport function matchObservationContextIdentity(params: {\n\treadonly expected: ObservationContext;\n\treadonly actual: ObservationContext;\n\treadonly label?: string;\n}): ObservationContextMatchResult {\n\tconst label = params.label ?? 'observation context';\n\tconst mismatchedField = firstObservationContextIdentityMismatch(\n\t\tparams.expected,\n\t\tparams.actual,\n\t);\n\tif (mismatchedField) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `${label} identity differs from proof context at ${mismatchedField}`,\n\t\t};\n\t}\n\treturn { ok: true };\n}\n\nexport function matchRunObservationContext(params: {\n\treadonly run: TransitionRunMetadata;\n\treadonly actual: ObservationContext;\n}): ObservationContextMatchResult {\n\tif (params.actual.databaseId !== params.run.databaseId) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `readContext databaseId ${params.actual.databaseId} does not match run databaseId ${params.run.databaseId}`,\n\t\t};\n\t}\n\tconst actualDigest = observationContextDigest(params.actual);\n\tif (actualDigest !== params.run.targetContextDigest) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: 'readContext digest does not match run targetContextDigest',\n\t\t};\n\t}\n\treturn { ok: true };\n}\n","import type {\n\tObservationContext,\n\tObservationPrivilegeMergeResult,\n} from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport type ObservationContextMergeResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly context: ObservationContext;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly detail: string;\n\t };\n\nexport type ObservationPrivilegeMerger = (\n\tleft: readonly string[],\n\tright: readonly string[],\n) => ObservationPrivilegeMergeResult;\n\nconst ADDITIVE_CONTEXT_FIELDS = new Set(['capabilities', 'privileges']);\nconst IDENTITY_CONTEXT_FIELDS = [\n\t'databaseId',\n\t'engine',\n\t'engineVersion',\n\t'targetSchema',\n] as const;\n\nfunction sortedUnique(values: readonly string[]): readonly string[] {\n\treturn [...new Set(values)].sort();\n}\n\nfunction nucleusKeys(\n\tleft: ObservationContext,\n\tright: ObservationContext,\n): readonly string[] {\n\treturn [...new Set([...Object.keys(left), ...Object.keys(right)])]\n\t\t.filter((key) => !ADDITIVE_CONTEXT_FIELDS.has(key))\n\t\t.sort();\n}\n\nfunction contextValue(context: ObservationContext, key: string): unknown {\n\treturn (context as unknown as Readonly<Record<string, unknown>>)[key];\n}\n\nexport function firstObservationContextNucleusMismatch(\n\tleft: ObservationContext,\n\tright: ObservationContext,\n): string | undefined {\n\tfor (const key of nucleusKeys(left, right)) {\n\t\tif (\n\t\t\tstableJson(contextValue(left, key)) !==\n\t\t\tstableJson(contextValue(right, key))\n\t\t) {\n\t\t\treturn key;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function firstObservationContextIdentityMismatch(\n\tleft: ObservationContext,\n\tright: ObservationContext,\n): string | undefined {\n\tfor (const key of IDENTITY_CONTEXT_FIELDS) {\n\t\tif (\n\t\t\tstableJson(contextValue(left, key)) !==\n\t\t\tstableJson(contextValue(right, key))\n\t\t) {\n\t\t\treturn key;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction privilegesMatchAsSet(\n\tleft: readonly string[],\n\tright: readonly string[],\n): boolean {\n\treturn stableJson(sortedUnique(left)) === stableJson(sortedUnique(right));\n}\n\nfunction mergePrivileges(\n\tleft: readonly string[],\n\tright: readonly string[],\n\tmerger?: ObservationPrivilegeMerger,\n):\n\t| { readonly ok: true; readonly privileges: readonly string[] }\n\t| { readonly ok: false; readonly detail: string } {\n\tif (privilegesMatchAsSet(left, right)) {\n\t\treturn { ok: true, privileges: sortedUnique(left) };\n\t}\n\tif (!merger) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail:\n\t\t\t\t'candidate proof contexts differ in privileges and no issuer privilege merger is registered',\n\t\t};\n\t}\n\tconst result = merger(sortedUnique(left), sortedUnique(right));\n\tif ('conflict' in result) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: result.conflict,\n\t\t};\n\t}\n\treturn { ok: true, privileges: sortedUnique(result.merged) };\n}\n\nexport function mergeCompatibleObservationContexts(\n\tleft: ObservationContext,\n\tright: ObservationContext,\n\tmerger?: ObservationPrivilegeMerger,\n): ObservationContextMergeResult {\n\tconst mismatchedField = firstObservationContextNucleusMismatch(left, right);\n\tif (mismatchedField) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `candidate proof contexts differ at ${mismatchedField}`,\n\t\t};\n\t}\n\tconst privileges = mergePrivileges(left.privileges, right.privileges, merger);\n\tif (!privileges.ok) {\n\t\treturn privileges;\n\t}\n\treturn {\n\t\tok: true,\n\t\tcontext: {\n\t\t\t...left,\n\t\t\tcapabilities: sortedUnique([...left.capabilities, ...right.capabilities]),\n\t\t\tprivileges: privileges.privileges,\n\t\t},\n\t};\n}\n","import type {\n\tExecutionContract,\n\tExecutionRequirement,\n\tProvenPlanShape,\n} from '@dbsp/types';\nimport { EXECUTION_CONTRACT_VERSION } from '@dbsp/types';\nimport type { InProcessProvenPlan } from './index.js';\nimport { mintInProcessPlan } from './minting.js';\nimport { stableJson } from './stable-json.js';\n\nexport type ExecutionContractValidation =\n\t| { readonly ok: true; readonly contract: ExecutionContract }\n\t| { readonly ok: false; readonly detail: string };\n\n/**\n * The one ordering rule for execution-contract requirements. Construction uses\n * it to make fresh contracts canonical; validation uses it to verify durable\n * input has not been reordered.\n */\nfunction canonicalRequirements(\n\trequirements: readonly ExecutionRequirement[],\n): readonly ExecutionRequirement[] {\n\tconst ordered = [...requirements].sort((left, right) => {\n\t\tconst leftJson = stableJson(left);\n\t\tconst rightJson = stableJson(right);\n\t\treturn leftJson < rightJson ? -1 : leftJson > rightJson ? 1 : 0;\n\t});\n\treturn ordered.filter(\n\t\t(requirement, index) =>\n\t\t\tindex === 0 || stableJson(requirement) !== stableJson(ordered[index - 1]),\n\t);\n}\n\nfunction compareNamespaceIdentity(\n\tleft: { readonly name: string; readonly oid: string },\n\tright: { readonly name: string; readonly oid: string },\n): number {\n\treturn left.name < right.name\n\t\t? -1\n\t\t: left.name > right.name\n\t\t\t? 1\n\t\t\t: left.oid < right.oid\n\t\t\t\t? -1\n\t\t\t\t: left.oid > right.oid\n\t\t\t\t\t? 1\n\t\t\t\t\t: 0;\n}\n\nfunction canonicalNamespaces(\n\tnamespaces: readonly { readonly name: string; readonly oid: string }[],\n): readonly { readonly name: string; readonly oid: string }[] {\n\tconst ordered = [...namespaces].sort(compareNamespaceIdentity);\n\treturn ordered.filter(\n\t\t(namespace, index) =>\n\t\t\tindex === 0 ||\n\t\t\tcompareNamespaceIdentity(namespace, ordered[index - 1] ?? namespace) !==\n\t\t\t\t0,\n\t);\n}\n\n/** Construct a fresh versioned contract whose requirements are canonical. */\nexport function createExecutionContract(\n\trequirements: readonly ExecutionRequirement[],\n): ExecutionContract {\n\treturn {\n\t\tversion: EXECUTION_CONTRACT_VERSION,\n\t\trequirements: canonicalRequirements(requirements),\n\t};\n}\n\nfunction nonEmpty(value: unknown): value is string {\n\treturn typeof value === 'string' && value.length > 0;\n}\n\nfunction validRequirement(\n\trequirement: unknown,\n): requirement is ExecutionRequirement {\n\tif (\n\t\trequirement === null ||\n\t\ttypeof requirement !== 'object' ||\n\t\tArray.isArray(requirement)\n\t)\n\t\treturn false;\n\tconst value = requirement as Record<string, unknown>;\n\tif (\n\t\t!nonEmpty(value.kind) ||\n\t\t!['must-match', 'set-and-verify', 'must-satisfy', 'provenance'].includes(\n\t\t\tvalue.mode as string,\n\t\t)\n\t)\n\t\treturn false;\n\tswitch (value.kind) {\n\t\tcase 'postgresql.physical-target': {\n\t\t\tif (\n\t\t\t\t!(\n\t\t\t\t\tvalue.mode === 'must-match' &&\n\t\t\t\t\tnonEmpty(value.systemIdentifier) &&\n\t\t\t\t\tnonEmpty(value.databaseOid) &&\n\t\t\t\t\tArray.isArray(value.namespaces) &&\n\t\t\t\t\tvalue.namespaces.length > 0 &&\n\t\t\t\t\tvalue.namespaces.every(\n\t\t\t\t\t\t(item) =>\n\t\t\t\t\t\t\titem !== null &&\n\t\t\t\t\t\t\ttypeof item === 'object' &&\n\t\t\t\t\t\t\tnonEmpty((item as Record<string, unknown>).name) &&\n\t\t\t\t\t\t\tnonEmpty((item as Record<string, unknown>).oid),\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn false;\n\t\t\tconst namespaces = value.namespaces as readonly {\n\t\t\t\treadonly name: string;\n\t\t\t\treadonly oid: string;\n\t\t\t}[];\n\t\t\treturn (\n\t\t\t\tstableJson(namespaces) ===\n\t\t\t\t\tstableJson(canonicalNamespaces(namespaces)) &&\n\t\t\t\tnew Set(namespaces.map((namespace) => namespace.name)).size ===\n\t\t\t\t\tnamespaces.length\n\t\t\t);\n\t\t}\n\t\tcase 'postgresql.engine-version':\n\t\t\treturn (\n\t\t\t\tvalue.mode === 'must-satisfy' &&\n\t\t\t\tnonEmpty(value.stepId) &&\n\t\t\t\t(value.minServerVersionNum === undefined ||\n\t\t\t\t\tNumber.isInteger(value.minServerVersionNum)) &&\n\t\t\t\t(value.maxServerVersionNum === undefined ||\n\t\t\t\t\tNumber.isInteger(value.maxServerVersionNum))\n\t\t\t);\n\t\tcase 'postgresql.authority':\n\t\t\treturn (\n\t\t\t\tvalue.mode === 'must-satisfy' &&\n\t\t\t\t['schema-usage', 'table-alter', 'type-alter'].includes(\n\t\t\t\t\tvalue.action as string,\n\t\t\t\t) &&\n\t\t\t\tnonEmpty(value.schema) &&\n\t\t\t\t(value.action === 'schema-usage' || nonEmpty(value.object))\n\t\t\t);\n\t\tcase 'postgresql.session-setting':\n\t\t\treturn (\n\t\t\t\t(value.mode === 'set-and-verify' || value.mode === 'provenance') &&\n\t\t\t\t[\n\t\t\t\t\t'standard_conforming_strings',\n\t\t\t\t\t'search_path',\n\t\t\t\t\t'client_encoding',\n\t\t\t\t\t'TimeZone',\n\t\t\t\t].includes(value.setting as string) &&\n\t\t\t\tnonEmpty(value.value) &&\n\t\t\t\t(value.mode !== 'set-and-verify' ||\n\t\t\t\t\t(value.setting === 'standard_conforming_strings' &&\n\t\t\t\t\t\tvalue.value === 'on') ||\n\t\t\t\t\t(value.setting === 'client_encoding' && value.value === 'UTF8'))\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Fail closed for malformed, future, or non-canonical persisted contracts. */\nexport function validateExecutionContract(\n\tvalue: unknown,\n): ExecutionContractValidation {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value))\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: 'plan is missing an execution contract; re-plan before execution',\n\t\t};\n\tconst contract = value as ExecutionContract;\n\tif (contract.version !== EXECUTION_CONTRACT_VERSION)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `execution contract version ${String(contract.version)} is unsupported`,\n\t\t};\n\tif (\n\t\t!Array.isArray(contract.requirements) ||\n\t\tcontract.requirements.length === 0\n\t)\n\t\treturn { ok: false, detail: 'execution contract has no requirements' };\n\tif (!contract.requirements.every(validRequirement))\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: 'execution contract contains an unknown requirement kind or mode',\n\t\t};\n\tconst canonical = canonicalRequirements(contract.requirements);\n\tif (stableJson(canonical) !== stableJson(contract.requirements))\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: 'execution contract requirements are not canonically ordered',\n\t\t};\n\treturn { ok: true, contract };\n}\n\n/** Attach a planning-time-only contract to a fresh immutable durable plan. */\nexport function bindExecutionContract(\n\tplan: InProcessProvenPlan,\n\tcontract: ExecutionContract,\n): InProcessProvenPlan {\n\tconst validation = validateExecutionContract(contract);\n\tif (!validation.ok) throw new Error(validation.detail);\n\t// Do not JSON-clone here. Minting accepts explicit plain-data values such as\n\t// undefined, NaN, Infinity, and -0; JSON would silently alter them before the\n\t// digest is calculated. Persistence performs its own lossless JSONB gate.\n\treturn mintInProcessPlan({\n\t\t...plan,\n\t\texecutionContract: validation.contract,\n\t} as ProvenPlanShape);\n}\n","import type {\n\tAdvisoryObservationId,\n\tAssumptionId,\n\tClaimId,\n\tEvidenceId,\n\tSemanticArtifactId,\n} from '@dbsp/types';\n\nexport function semanticArtifactId(value: string): SemanticArtifactId {\n\treturn value as SemanticArtifactId;\n}\n\nexport function assumptionId(value: string): AssumptionId {\n\treturn value as AssumptionId;\n}\n\nexport function claimId(value: string): ClaimId {\n\treturn value as ClaimId;\n}\n\nexport function evidenceId(value: string): EvidenceId {\n\treturn value as EvidenceId;\n}\n\nexport function advisoryObservationId(value: string): AdvisoryObservationId {\n\treturn value as AdvisoryObservationId;\n}\n","import { createHash } from 'node:crypto';\nimport type { ProvenPlanShape } from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\nimport { validateNormalizedManagedStepManifest } from './validation.js';\n\nfunction hasManagedStepShape(steps: unknown): boolean {\n\treturn (\n\t\tArray.isArray(steps) &&\n\t\tsteps.length > 0 &&\n\t\tsteps.every((step) => {\n\t\t\tconst candidate = step as unknown as Record<string, unknown>;\n\t\t\treturn (\n\t\t\t\ttypeof candidate.stepKey === 'string' &&\n\t\t\t\ttypeof candidate.order === 'number' &&\n\t\t\t\t'statementBundle' in candidate\n\t\t\t);\n\t\t})\n\t);\n}\n\n/**\n * Canonical digest used to bind a durable transition run to its proven plan.\n */\nexport function transitionPlanDigest(plan: ProvenPlanShape): string {\n\tconst normalized = hasManagedStepShape(plan.steps)\n\t\t? (() => {\n\t\t\t\tconst validation = validateNormalizedManagedStepManifest(\n\t\t\t\t\tplan.steps as unknown as readonly import('@dbsp/types').NormalizedManagedStep[],\n\t\t\t\t);\n\t\t\t\tif (!validation.ok)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`cannot digest invalid managed-step manifest: ${validation.detail}`,\n\t\t\t\t\t);\n\t\t\t\treturn { ...plan, steps: validation.manifest.steps };\n\t\t\t})()\n\t\t: plan;\n\treturn createHash('sha256').update(stableJson(normalized)).digest('hex');\n}\n","import type {\n\tAssumption,\n\tCatalogueIdentity,\n\tDeclarableResourceAddress,\n\tGuardedPlanStep,\n\tJsonObject,\n\tJsonValue,\n\tLedgerPayload,\n\tManagedStepLifecycle,\n\tManagedStepSelectionRequirement,\n\tNormalizedManagedStep,\n\tObservationContext,\n\tOperationEffectAssessment,\n\tPhysicalOperation,\n\tProofClaim,\n\tProvenPlanShape,\n\tResourceAddress,\n\tSequenceIR,\n\tTableIR,\n\tTableReaddressAddress,\n\tTransitionFragment,\n} from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport type TransitionRelationalValidationInput =\n\t| {\n\t\t\treadonly kind: 'fragment';\n\t\t\treadonly fragment: TransitionFragment;\n\t\t\treadonly claims: readonly ProofClaim[];\n\t\t\treadonly assumptions: readonly Assumption[];\n\t }\n\t| {\n\t\t\treadonly kind: 'plan';\n\t\t\treadonly plan: ProvenPlanShape;\n\t\t\treadonly operationEffectsByRef?: ReadonlyMap<\n\t\t\t\tstring,\n\t\t\t\tOperationEffectAssessment\n\t\t\t>;\n\t };\n\nexport type TransitionRelationalValidationResult =\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly detail: string };\n\ndeclare const validatedManagedStepManifestBrand: unique symbol;\n\n/** A manifest normalized and accepted by the managed lifecycle boundary. */\nexport interface ValidatedManagedStepManifest {\n\treadonly steps: readonly NormalizedManagedStep[];\n\treadonly [validatedManagedStepManifestBrand]: 'dbsp-validated-managed-step-manifest';\n}\n\nexport type ValidatedManagedStepManifestResult =\n\t| { readonly ok: true; readonly manifest: ValidatedManagedStepManifest }\n\t| { readonly ok: false; readonly detail: string };\n\nconst DECLARABLE_KINDS = new Set([\n\t'table',\n\t'column',\n\t'index',\n\t'constraint',\n\t'enum',\n\t'sequence',\n\t'extension',\n]);\n\nconst CLASSIFICATIONS = new Set([\n\t'non-destructive',\n\t'removal',\n\t'data-destructive',\n\t'paired-readdress',\n]);\n\nconst CLAIM_KINDS = new Set([\n\t'adopt-intent',\n\t'intent',\n\t'retire-intent',\n\t'readdress-intent',\n]);\n\nclass ManifestParseError extends Error {}\n\nfunction parseError(detail: string): never {\n\tthrow new ManifestParseError(detail);\n}\n\nfunction record(value: unknown, detail: string): Record<string, unknown> {\n\tif (!value || typeof value !== 'object' || Array.isArray(value))\n\t\treturn parseError(detail);\n\treturn value as Record<string, unknown>;\n}\n\nfunction nonEmptyString(value: unknown, detail: string): string {\n\tif (typeof value !== 'string' || value.length === 0)\n\t\treturn parseError(detail);\n\treturn value;\n}\n\nfunction strings(value: unknown, detail: string): readonly string[] {\n\tif (!Array.isArray(value)) return parseError(detail);\n\treturn value.map((item) => nonEmptyString(item, detail));\n}\n\nfunction canonicalJson(value: unknown, detail: string): JsonValue {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean')\n\t\treturn value;\n\tif (typeof value === 'number') {\n\t\tif (!Number.isFinite(value)) return parseError(detail);\n\t\treturn value;\n\t}\n\tif (!value || typeof value !== 'object') return parseError(detail);\n\tif (Array.isArray(value))\n\t\treturn value.map((item) => canonicalJson(item, detail));\n\tif (Object.getPrototypeOf(value) !== Object.prototype)\n\t\treturn parseError(detail);\n\tconst result: Record<string, JsonValue> = {};\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tif (item === undefined) return parseError(detail);\n\t\tresult[key] = canonicalJson(item, detail);\n\t}\n\treturn result;\n}\n\nfunction catalogueIdentity(value: unknown, detail: string): CatalogueIdentity {\n\tconst source = record(value, detail);\n\tif (typeof source.format !== 'number' || !Number.isInteger(source.format))\n\t\treturn parseError(detail);\n\tconst identityValue = canonicalJson(source.value, detail);\n\tif (\n\t\t!identityValue ||\n\t\tArray.isArray(identityValue) ||\n\t\ttypeof identityValue !== 'object'\n\t)\n\t\treturn parseError(detail);\n\treturn {\n\t\tengine: nonEmptyString(source.engine, detail),\n\t\tformat: source.format,\n\t\tvalue: identityValue as JsonObject,\n\t};\n}\n\n/** Parse parent containment while deliberately dropping scope and observed identity. */\nfunction resourceParent(value: unknown, detail: string): ResourceAddress {\n\tconst source = record(value, detail);\n\tconst parent = source.parent;\n\treturn {\n\t\tengine: nonEmptyString(source.engine, detail),\n\t\tdatabase: nonEmptyString(source.database, detail),\n\t\t...(source.schema === undefined\n\t\t\t? {}\n\t\t\t: { schema: nonEmptyString(source.schema, detail) }),\n\t\t...(parent === undefined ? {} : { parent: resourceParent(parent, detail) }),\n\t\tkind: nonEmptyString(source.kind, detail),\n\t\tname: nonEmptyString(source.name, detail),\n\t};\n}\n\ntype ManagedLedgerAddress = DeclarableResourceAddress & {\n\treadonly scope: 'schema' | 'database';\n};\n\nfunction ledgerAddress(value: unknown, detail: string): ManagedLedgerAddress {\n\tconst source = record(value, detail);\n\tif (source.scope !== 'schema' && source.scope !== 'database')\n\t\treturn parseError(detail);\n\tconst kind = nonEmptyString(source.kind, detail);\n\tif (!DECLARABLE_KINDS.has(kind)) return parseError(detail);\n\tconst identity =\n\t\tsource.catalogueIdentity === undefined\n\t\t\t? undefined\n\t\t\t: catalogueIdentity(source.catalogueIdentity, detail);\n\tconst qualifiedBy =\n\t\tsource.qualifiedBy === undefined\n\t\t\t? undefined\n\t\t\t: strings(source.qualifiedBy, detail);\n\treturn {\n\t\tscope: source.scope,\n\t\tengine: nonEmptyString(source.engine, detail),\n\t\tdatabase: nonEmptyString(source.database, detail),\n\t\t...(source.schema === undefined\n\t\t\t? {}\n\t\t\t: { schema: nonEmptyString(source.schema, detail) }),\n\t\t...(source.parent === undefined\n\t\t\t? {}\n\t\t\t: { parent: resourceParent(source.parent, detail) }),\n\t\tkind: kind as DeclarableResourceAddress['kind'],\n\t\tname: nonEmptyString(source.name, detail),\n\t\t...(identity === undefined ? {} : { catalogueIdentity: identity }),\n\t\t...(qualifiedBy === undefined ? {} : { qualifiedBy }),\n\t};\n}\n\nfunction payload(value: unknown, detail: string): LedgerPayload {\n\tconst source = record(value, detail);\n\treturn {\n\t\tvalue: canonicalJson(source.value, detail),\n\t\tdigest: nonEmptyString(source.digest, detail),\n\t};\n}\n\nfunction selection(\n\tvalue: unknown,\n\tdetail: string,\n): ManagedStepSelectionRequirement {\n\tconst source = record(value, detail);\n\tif (\n\t\tsource.kind !== 'replacement' &&\n\t\tsource.kind !== 'adoption' &&\n\t\tsource.kind !== 'readdress' &&\n\t\tsource.kind !== 'optional-action'\n\t)\n\t\treturn parseError(detail);\n\treturn {\n\t\tkind: source.kind,\n\t\tselector: nonEmptyString(source.selector, detail),\n\t};\n}\n\nfunction readdressEndpoint(\n\tvalue: unknown,\n\tdetail: string,\n): TableReaddressAddress {\n\tconst source = record(value, detail);\n\treturn {\n\t\tname: nonEmptyString(source.name, detail),\n\t\t...(source.schema === undefined\n\t\t\t? {}\n\t\t\t: { schema: nonEmptyString(source.schema, detail) }),\n\t\t...(source.kind === undefined\n\t\t\t? {}\n\t\t\t: { kind: nonEmptyString(source.kind, detail) }),\n\t\t...(source.database === undefined\n\t\t\t? {}\n\t\t\t: { database: nonEmptyString(source.database, detail) }),\n\t};\n}\n\nfunction lifecycle(value: unknown, detail: string): ManagedStepLifecycle {\n\tconst source = record(value, detail);\n\tif (source.kind === 'adoption')\n\t\treturn {\n\t\t\tkind: 'adoption',\n\t\t\tshape: canonicalJson(source.shape, detail) as unknown as TableIR,\n\t\t};\n\tif (source.kind === 'sequence-adoption')\n\t\treturn {\n\t\t\tkind: 'sequence-adoption',\n\t\t\tshape: sequenceShape(source.shape, detail),\n\t\t};\n\tif (source.kind === 'adoption-refused') return { kind: 'adoption-refused' };\n\tif (source.kind === 'readdress') {\n\t\tconst declaration = record(source.declaration, detail);\n\t\treturn {\n\t\t\tkind: 'readdress',\n\t\t\tdeclaration: {\n\t\t\t\tfrom: readdressEndpoint(declaration.from, detail),\n\t\t\t\tto: readdressEndpoint(declaration.to, detail),\n\t\t\t},\n\t\t};\n\t}\n\treturn parseError(detail);\n}\n\nfunction sequenceShape(value: unknown, detail: string): SequenceIR {\n\tconst source = record(value, detail);\n\tconst sequenceInteger = (item: unknown): number | string => {\n\t\tif (typeof item === 'string') return item;\n\t\tif (typeof item === 'number' && Number.isFinite(item)) return item;\n\t\treturn parseError(detail);\n\t};\n\tconst sequenceBoolean = (item: unknown): boolean => {\n\t\tif (typeof item === 'boolean') return item;\n\t\treturn parseError(detail);\n\t};\n\treturn {\n\t\tname: nonEmptyString(source.name, detail),\n\t\t...(source.startWith === undefined\n\t\t\t? {}\n\t\t\t: { startWith: sequenceInteger(source.startWith) }),\n\t\t...(source.incrementBy === undefined\n\t\t\t? {}\n\t\t\t: { incrementBy: sequenceInteger(source.incrementBy) }),\n\t\t...(source.minValue === undefined\n\t\t\t? {}\n\t\t\t: { minValue: sequenceInteger(source.minValue) }),\n\t\t...(source.maxValue === undefined\n\t\t\t? {}\n\t\t\t: { maxValue: sequenceInteger(source.maxValue) }),\n\t\t...(source.cycle === undefined\n\t\t\t? {}\n\t\t\t: { cycle: sequenceBoolean(source.cycle) }),\n\t\t...(source.schema === undefined\n\t\t\t? {}\n\t\t\t: { schema: nonEmptyString(source.schema, detail) }),\n\t};\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (value !== null && typeof value === 'object') {\n\t\tfor (const child of Object.values(value)) deepFreeze(child);\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\nfunction parseStep(value: unknown, index: number): NormalizedManagedStep {\n\tconst source = record(value, `managed step ${index} is not an object`);\n\tconst stepKey = nonEmptyString(\n\t\tsource.stepKey,\n\t\t`managed step ${index} has invalid step key`,\n\t);\n\tconst prefix = `managed step ${stepKey}`;\n\tconst order = source.order;\n\tif (typeof order !== 'number' || !Number.isInteger(order) || order < 0)\n\t\treturn parseError(`${prefix} has invalid order`);\n\tif (typeof source.requiresVacancy !== 'boolean')\n\t\treturn parseError(`${prefix} has invalid vacancy flag`);\n\tif (!CLASSIFICATIONS.has(source.classification as string))\n\t\treturn parseError(`${prefix} has invalid classification`);\n\tif (!CLAIM_KINDS.has(source.claimKind as string))\n\t\treturn parseError(`${prefix} has invalid lifecycle claim kind`);\n\tif (\n\t\tsource.replayPolicy !== 'recorded' &&\n\t\tsource.replayPolicy !== 'fresh-live-only'\n\t)\n\t\treturn parseError(`${prefix} has invalid replay policy`);\n\tconst address =\n\t\tsource.address === undefined\n\t\t\t? undefined\n\t\t\t: ledgerAddress(source.address, `${prefix} has invalid address`);\n\tconst closureSource =\n\t\tsource.closure === undefined\n\t\t\t? undefined\n\t\t\t: record(source.closure, `${prefix} has invalid closure`);\n\tconst closure =\n\t\tclosureSource === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\troot: ledgerAddress(\n\t\t\t\t\t\tclosureSource.root,\n\t\t\t\t\t\t`${prefix} has invalid closure root`,\n\t\t\t\t\t),\n\t\t\t\t\tmembers: (() => {\n\t\t\t\t\t\tif (!Array.isArray(closureSource.members))\n\t\t\t\t\t\t\treturn parseError(`${prefix} has invalid closure members`);\n\t\t\t\t\t\treturn closureSource.members.map((member) => {\n\t\t\t\t\t\t\tconst parsed = record(\n\t\t\t\t\t\t\t\tmember,\n\t\t\t\t\t\t\t\t`${prefix} has invalid closure member`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tplannedClaimKey: nonEmptyString(\n\t\t\t\t\t\t\t\t\tparsed.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t`${prefix} has invalid closure member`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\taddress: ledgerAddress(\n\t\t\t\t\t\t\t\t\tparsed.address,\n\t\t\t\t\t\t\t\t\t`${prefix} has invalid closure member`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t});\n\t\t\t\t\t})(),\n\t\t\t\t};\n\tif ((address === undefined) === (closure === undefined))\n\t\treturn parseError(\n\t\t\t`${prefix} must have exactly one address or closure root`,\n\t\t);\n\tconst statementBundle = record(\n\t\tsource.statementBundle,\n\t\t`${prefix} has invalid statement bundle`,\n\t);\n\tif (!Array.isArray(statementBundle.statements))\n\t\treturn parseError(`${prefix} has invalid statement bundle`);\n\tconst expectedDeclaration =\n\t\tsource.expectedDeclaration === undefined\n\t\t\t? undefined\n\t\t\t: payload(\n\t\t\t\t\tsource.expectedDeclaration,\n\t\t\t\t\t`${prefix} has invalid expected declaration`,\n\t\t\t\t);\n\tconst expectedCatalogueIdentity =\n\t\tsource.expectedCatalogueIdentity === undefined\n\t\t\t? undefined\n\t\t\t: catalogueIdentity(\n\t\t\t\t\tsource.expectedCatalogueIdentity,\n\t\t\t\t\t`${prefix} has invalid expected catalogue identity`,\n\t\t\t\t);\n\tconst parsed: NormalizedManagedStep = {\n\t\tstepKey,\n\t\torder,\n\t\tsegmentId: nonEmptyString(\n\t\t\tsource.segmentId,\n\t\t\t`${prefix} has invalid segment id`,\n\t\t),\n\t\tdependencyOrder: strings(\n\t\t\tsource.dependencyOrder,\n\t\t\t`${prefix} has invalid dependencies`,\n\t\t),\n\t\t...(address === undefined ? {} : { address }),\n\t\t...(closure === undefined ? {} : { closure }),\n\t\tclaimKind: source.claimKind as NormalizedManagedStep['claimKind'],\n\t\tplannedClaimKeys: strings(\n\t\t\tsource.plannedClaimKeys,\n\t\t\t`${prefix} has invalid planned claim keys`,\n\t\t),\n\t\tstatementBundle: {\n\t\t\tstatements: statementBundle.statements.map((statement, ordinal) => {\n\t\t\t\tconst parsedStatement = record(\n\t\t\t\t\tstatement,\n\t\t\t\t\t`${prefix} has an invalid statement bundle`,\n\t\t\t\t);\n\t\t\t\tif (parsedStatement.ordinal !== ordinal)\n\t\t\t\t\treturn parseError(`${prefix} has an invalid statement bundle`);\n\t\t\t\treturn {\n\t\t\t\t\tordinal,\n\t\t\t\t\tsql: nonEmptyString(\n\t\t\t\t\t\tparsedStatement.sql,\n\t\t\t\t\t\t`${prefix} has an invalid statement bundle`,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}),\n\t\t},\n\t\tclassification:\n\t\t\tsource.classification as NormalizedManagedStep['classification'],\n\t\trequiresVacancy: source.requiresVacancy,\n\t\t...(expectedDeclaration === undefined ? {} : { expectedDeclaration }),\n\t\t...(expectedCatalogueIdentity === undefined\n\t\t\t? {}\n\t\t\t: { expectedCatalogueIdentity }),\n\t\t...(source.selection === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tselection: selection(\n\t\t\t\t\t\tsource.selection,\n\t\t\t\t\t\t`${prefix} has invalid selection`,\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t...(source.lifecycle === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlifecycle: lifecycle(\n\t\t\t\t\t\tsource.lifecycle,\n\t\t\t\t\t\t`${prefix} has invalid lifecycle`,\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treplayPolicy: source.replayPolicy,\n\t};\n\treturn parsed;\n}\n\nfunction validateLifecycleCoupling(\n\tstep: NormalizedManagedStep,\n): string | undefined {\n\tconst lifecycle = step.lifecycle;\n\tif (\n\t\tstep.selection?.kind === 'adoption' &&\n\t\t(!lifecycle ||\n\t\t\t(step.address?.kind === 'table' && lifecycle.kind !== 'adoption') ||\n\t\t\t(step.address?.kind === 'sequence' &&\n\t\t\t\tlifecycle.kind !== 'sequence-adoption') ||\n\t\t\t(step.address?.kind !== 'table' && step.address?.kind !== 'sequence'))\n\t)\n\t\treturn `adoption step ${step.stepKey} has invalid lifecycle coupling`;\n\tif (step.selection?.kind === 'replacement') {\n\t\tif (lifecycle)\n\t\t\treturn `replacement step ${step.stepKey} has invalid lifecycle coupling`;\n\t\tif (\n\t\t\t(step.classification === 'removal' &&\n\t\t\t\tstep.claimKind === 'retire-intent' &&\n\t\t\t\t!step.requiresVacancy) ||\n\t\t\t(step.classification === 'non-destructive' &&\n\t\t\t\tstep.claimKind === 'intent' &&\n\t\t\t\tstep.requiresVacancy)\n\t\t)\n\t\t\treturn undefined;\n\t\treturn `replacement step ${step.stepKey} has invalid lifecycle coupling`;\n\t}\n\tif (\n\t\tstep.classification === 'removal' &&\n\t\t(step.claimKind !== 'retire-intent' || step.requiresVacancy)\n\t)\n\t\treturn `removal step ${step.stepKey} has an invalid lifecycle claim`;\n\tif (step.classification !== 'removal' && step.claimKind === 'retire-intent')\n\t\treturn `non-removal step ${step.stepKey} cannot retire a managed address`;\n\tif (\n\t\tstep.classification === 'paired-readdress' &&\n\t\tlifecycle?.kind !== 'readdress'\n\t)\n\t\treturn `readdress step ${step.stepKey} has invalid lifecycle coupling`;\n\tif (!lifecycle) return undefined;\n\tif (lifecycle.kind === 'adoption') {\n\t\tif (\n\t\t\tstep.claimKind !== 'adopt-intent' ||\n\t\t\tstep.classification !== 'non-destructive' ||\n\t\t\tstep.requiresVacancy ||\n\t\t\tstep.selection?.kind !== 'adoption' ||\n\t\t\t!step.address ||\n\t\t\tstep.address.kind !== 'table' ||\n\t\t\t!step.expectedDeclaration ||\n\t\t\t!step.expectedCatalogueIdentity ||\n\t\t\tstep.statementBundle.statements.length !== 0\n\t\t)\n\t\t\treturn `adoption step ${step.stepKey} has invalid lifecycle coupling`;\n\t\treturn undefined;\n\t}\n\tif (lifecycle.kind === 'sequence-adoption') {\n\t\tif (\n\t\t\tstep.claimKind !== 'adopt-intent' ||\n\t\t\tstep.classification !== 'non-destructive' ||\n\t\t\tstep.requiresVacancy ||\n\t\t\tstep.selection?.kind !== 'adoption' ||\n\t\t\t!step.address ||\n\t\t\tstep.address.kind !== 'sequence' ||\n\t\t\tstep.selection.selector !== `sequence:${step.address.name}` ||\n\t\t\tlifecycle.shape.name !== step.address.name ||\n\t\t\t(lifecycle.shape.schema !== undefined &&\n\t\t\t\tlifecycle.shape.schema !== step.address.schema) ||\n\t\t\t!step.expectedDeclaration ||\n\t\t\t!step.expectedCatalogueIdentity ||\n\t\t\tstep.statementBundle.statements.length !== 0\n\t\t)\n\t\t\treturn `sequence adoption step ${step.stepKey} has invalid lifecycle coupling`;\n\t\treturn undefined;\n\t}\n\tif (lifecycle.kind === 'readdress') {\n\t\tif (\n\t\t\tstep.claimKind !== 'readdress-intent' ||\n\t\t\tstep.classification !== 'paired-readdress' ||\n\t\t\tstep.requiresVacancy ||\n\t\t\tstep.selection?.kind !== 'readdress' ||\n\t\t\t!step.address ||\n\t\t\tstep.address.kind !== 'table'\n\t\t)\n\t\t\treturn `readdress step ${step.stepKey} has invalid lifecycle coupling`;\n\t\treturn undefined;\n\t}\n\tif (\n\t\tstep.classification !== 'non-destructive' ||\n\t\tstep.claimKind !== 'intent' ||\n\t\tstep.requiresVacancy ||\n\t\t!step.address ||\n\t\tstep.statementBundle.statements.length !== 0\n\t)\n\t\treturn `adoption-refused step ${step.stepKey} has invalid lifecycle coupling`;\n\treturn undefined;\n}\n\nfunction validatedManifest(\n\tsteps: readonly NormalizedManagedStep[],\n): ValidatedManagedStepManifest {\n\treturn deepFreeze({ steps }) as ValidatedManagedStepManifest;\n}\n\n/**\n * Generic lifecycle invariants for adapter-produced normalized managed steps.\n * Mapping a concrete DDL kind remains adapter work; core only validates the\n * durable protocol shape before it becomes digest-covered plan material.\n */\nexport function validateNormalizedManagedStepManifest(\n\tsteps: readonly NormalizedManagedStep[],\n): ValidatedManagedStepManifestResult {\n\tlet parsedSteps: readonly NormalizedManagedStep[];\n\ttry {\n\t\tparsedSteps = steps.map((step, index) => parseStep(step, index));\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail:\n\t\t\t\terror instanceof ManifestParseError\n\t\t\t\t\t? error.message\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: String(error),\n\t\t};\n\t}\n\tconst keys = new Set<string>();\n\tconst stepsByKey = new Map<string, NormalizedManagedStep>();\n\tconst plannedClaimKeys = new Set<string>();\n\tfor (const [index, step] of parsedSteps.entries()) {\n\t\tif (step.order !== index)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `managed step ${step.stepKey} has non-contiguous order`,\n\t\t\t};\n\t\tif (keys.has(step.stepKey))\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate managed step key ${step.stepKey}`,\n\t\t\t};\n\t\tkeys.add(step.stepKey);\n\t\tstepsByKey.set(step.stepKey, step);\n\t\tif (step.plannedClaimKeys.length === 0)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `managed step ${step.stepKey} has no planned claim key`,\n\t\t\t};\n\t\tfor (const plannedClaimKey of step.plannedClaimKeys) {\n\t\t\tif (plannedClaimKeys.has(plannedClaimKey))\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `duplicate planned claim key ${plannedClaimKey}`,\n\t\t\t\t};\n\t\t\tplannedClaimKeys.add(plannedClaimKey);\n\t\t}\n\t\tif (\n\t\t\tstep.statementBundle.statements.some(\n\t\t\t\t(statement, ordinal) =>\n\t\t\t\t\tstatement.ordinal !== ordinal || statement.sql.length === 0,\n\t\t\t)\n\t\t)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `managed step ${step.stepKey} has an invalid statement bundle`,\n\t\t\t};\n\t\tif (\n\t\t\tstep.classification === 'removal' &&\n\t\t\tstep.replayPolicy !== 'fresh-live-only'\n\t\t)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `removal step ${step.stepKey} is not fresh-live-only`,\n\t\t\t};\n\t\tif (step.classification !== 'removal' && step.replayPolicy !== 'recorded')\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `non-removal step ${step.stepKey} is not recorded-replayable`,\n\t\t\t};\n\t\tconst lifecycleError = validateLifecycleCoupling(step);\n\t\tif (lifecycleError)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: lifecycleError,\n\t\t\t};\n\t}\n\tfor (const step of parsedSteps) {\n\t\tfor (const dependency of step.dependencyOrder) {\n\t\t\tif (!keys.has(dependency))\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `managed step ${step.stepKey} references missing dependency ${dependency}`,\n\t\t\t\t};\n\t\t\tif (dependency === step.stepKey)\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `managed step ${step.stepKey} depends on itself`,\n\t\t\t\t};\n\t\t\tconst dependencyStep = stepsByKey.get(dependency);\n\t\t\tif (dependencyStep && dependencyStep.order >= step.order)\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `managed step ${step.stepKey} depends on a non-preceding step ${dependency}`,\n\t\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true, manifest: validatedManifest(parsedSteps) };\n}\n\nfunction sameTrustRoot(\n\tleft: Assumption['asserter'],\n\tright: Assumption['asserter'],\n): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nfunction sameArtifact(\n\tleft: Assumption['asserter'],\n\tright: Assumption['asserter'],\n): boolean {\n\treturn sameTrustRoot(left, right);\n}\n\nfunction sameResource(left: ResourceAddress, right: ResourceAddress): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nfunction resourceCovers(\n\tcovering: readonly ResourceAddress[],\n\ttarget: readonly ResourceAddress[],\n): boolean {\n\treturn target.every((resource) =>\n\t\tcovering.some((candidate) => sameResource(candidate, resource)),\n\t);\n}\n\nfunction refCounts(\n\toperations: readonly PhysicalOperation[],\n): ReadonlyMap<string, number> {\n\tconst counts = new Map<string, number>();\n\tfor (const operation of operations) {\n\t\tcounts.set(operation.ref, (counts.get(operation.ref) ?? 0) + 1);\n\t}\n\treturn counts;\n}\n\nfunction duplicateOperationRef(\n\tcounts: ReadonlyMap<string, number>,\n): string | undefined {\n\tfor (const [ref, count] of counts) {\n\t\tif (count > 1) {\n\t\t\treturn ref;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction validatesExactlyOneRef(\n\tref: string | undefined,\n\tcounts: ReadonlyMap<string, number>,\n): boolean {\n\treturn typeof ref === 'string' && ref.length > 0 && counts.get(ref) === 1;\n}\n\nfunction validateAssumptionIds(\n\tassumptions: readonly Assumption[],\n): TransitionRelationalValidationResult {\n\tconst seen = new Set<string>();\n\tfor (const assumption of assumptions) {\n\t\tif (seen.has(assumption.id)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate assumption id ${assumption.id}`,\n\t\t\t};\n\t\t}\n\t\tseen.add(assumption.id);\n\t}\n\treturn { ok: true };\n}\n\nfunction validateClaimIdsAndEvidence(\n\tplan: ProvenPlanShape,\n): TransitionRelationalValidationResult {\n\tconst claimIds = new Set<string>();\n\tconst observationIds = new Set<string>();\n\tfor (const observation of plan.observations) {\n\t\tif (observation.role !== 'evidence') {\n\t\t\tcontinue;\n\t\t}\n\t\tif (observationIds.has(observation.id)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate observation id ${observation.id}`,\n\t\t\t};\n\t\t}\n\t\tobservationIds.add(observation.id);\n\t}\n\tfor (const claim of plan.claims) {\n\t\tif (claimIds.has(claim.id)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate claim id ${claim.id}`,\n\t\t\t};\n\t\t}\n\t\tclaimIds.add(claim.id);\n\t\tconst conclusionShape = validateClaimConclusionShape(claim);\n\t\tif (!conclusionShape.ok) {\n\t\t\treturn conclusionShape;\n\t\t}\n\t\tfor (const evidenceId of claim.supportedBy) {\n\t\t\tif (!observationIds.has(evidenceId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `claim ${claim.id} supportedBy references missing observation ${evidenceId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tfor (const evidenceId of claim.derivedBy.inputs) {\n\t\t\tif (!observationIds.has(evidenceId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `claim ${claim.id} derivedBy.inputs references missing observation ${evidenceId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction assumptionExists(\n\tassumptions: readonly Assumption[],\n\tassumptionId: string,\n): boolean {\n\treturn assumptions.some((assumption) => assumption.id === assumptionId);\n}\n\nfunction validateClaimConclusionShape(\n\tclaim: ProofClaim,\n): TransitionRelationalValidationResult {\n\tif (\n\t\tclaim.derivedBy.conclusion === 'established' &&\n\t\tclaim.assumes.length > 0\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `established claim ${claim.id} must not assume ${claim.assumes.join(', ')}`,\n\t\t};\n\t}\n\tif (\n\t\tclaim.derivedBy.conclusion === 'established-under-assumptions' &&\n\t\tclaim.assumes.length === 0\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `established-under-assumptions claim ${claim.id} must list at least one assumption`,\n\t\t};\n\t}\n\treturn { ok: true };\n}\n\nfunction validateEstablishedClaim(params: {\n\treadonly claimId: string;\n\treadonly claims: readonly ProofClaim[];\n\treadonly assumptions: readonly Assumption[];\n\treadonly requiredAssumptionIds?: readonly string[] | undefined;\n\treadonly missingDetail: string;\n\treadonly rejectedDetail: (\n\t\tconclusion: ProofClaim['derivedBy']['conclusion'],\n\t) => string;\n\treadonly missingAssumptionDetail: (assumptionId: string) => string;\n\treadonly missingClosureDetail: (assumptionId: string) => string;\n}): TransitionRelationalValidationResult {\n\tconst {\n\t\tclaimId,\n\t\tclaims,\n\t\tassumptions,\n\t\trequiredAssumptionIds,\n\t\tmissingDetail,\n\t\trejectedDetail,\n\t\tmissingAssumptionDetail,\n\t\tmissingClosureDetail,\n\t} = params;\n\tconst claim = claims.find((candidate) => candidate.id === claimId);\n\tif (!claim) {\n\t\treturn { ok: false, detail: missingDetail };\n\t}\n\tconst conclusionShape = validateClaimConclusionShape(claim);\n\tif (!conclusionShape.ok) {\n\t\treturn conclusionShape;\n\t}\n\tif (claim.derivedBy.conclusion === 'established') {\n\t\treturn { ok: true };\n\t}\n\tif (claim.derivedBy.conclusion !== 'established-under-assumptions') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: rejectedDetail(claim.derivedBy.conclusion),\n\t\t};\n\t}\n\tfor (const assumptionId of claim.assumes) {\n\t\tif (!assumptionExists(assumptions, assumptionId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: missingAssumptionDetail(assumptionId),\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\trequiredAssumptionIds &&\n\t\t\t!requiredAssumptionIds.includes(assumptionId)\n\t\t) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: missingClosureDetail(assumptionId),\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction expectedOperationPackTrustRoot(\n\toperation: PhysicalOperation,\n): Assumption['asserter'] {\n\treturn { kind: 'pack', artifact: operation.operationKind.artifact };\n}\n\nfunction operationPackSemanticsAssumption(\n\tassumptions: readonly Assumption[],\n\toperation: PhysicalOperation,\n): Assumption | undefined {\n\tconst expectedAsserter = expectedOperationPackTrustRoot(operation);\n\treturn assumptions.find(\n\t\t(assumption) =>\n\t\t\tassumption.class === 'operation-pack-semantics' &&\n\t\t\tsameArtifact(assumption.asserter, expectedAsserter),\n\t);\n}\n\nfunction operationPackSemanticsAssumptionsFromEffects(params: {\n\treadonly operation: PhysicalOperation;\n\treadonly effects: OperationEffectAssessment;\n}): readonly Assumption[] {\n\tconst expectedAsserter = expectedOperationPackTrustRoot(params.operation);\n\treturn params.effects.restsOn.filter(\n\t\t(assumption) =>\n\t\t\tassumption.class === 'operation-pack-semantics' &&\n\t\t\tsameArtifact(assumption.asserter, expectedAsserter),\n\t);\n}\n\nfunction validateOperationPackSemanticsAssumption(params: {\n\treadonly operation: PhysicalOperation;\n\treadonly assumptions: readonly Assumption[];\n\treadonly stepId?: string;\n\treadonly requiredAssumptionIds?: readonly string[] | undefined;\n\treadonly operationEffects?: OperationEffectAssessment | undefined;\n}): TransitionRelationalValidationResult {\n\tconst {\n\t\toperation,\n\t\tassumptions,\n\t\tstepId,\n\t\trequiredAssumptionIds,\n\t\toperationEffects,\n\t} = params;\n\tif (operationEffects) {\n\t\tconst requiredOperationPackAssumptions =\n\t\t\toperationPackSemanticsAssumptionsFromEffects({\n\t\t\t\toperation,\n\t\t\t\teffects: operationEffects,\n\t\t\t});\n\t\tif (requiredOperationPackAssumptions.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `operation ${operation.ref} is missing an operation-pack-semantics assumption for ${operation.operationKind.artifact.id}@${operation.operationKind.artifact.version}`,\n\t\t\t};\n\t\t}\n\t\tfor (const required of requiredOperationPackAssumptions) {\n\t\t\tconst actual = assumptions.find(\n\t\t\t\t(assumption) => assumption.id === required.id,\n\t\t\t);\n\t\t\tif (!actual) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `operation ${operation.ref} is missing operation-pack-semantics assumption ${required.id} in plan assumptions`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (stableJson(actual) !== stableJson(required)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `operation ${operation.ref} operation-pack-semantics assumption ${required.id} does not match its operation effects`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequiredAssumptionIds &&\n\t\t\t\t!requiredAssumptionIds.includes(required.id)\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${stepId ?? operation.ref} is missing operation-pack-semantics assumption ${required.id} from the step assumption closure`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn { ok: true };\n\t}\n\tif (requiredAssumptionIds) {\n\t\treturn { ok: true };\n\t}\n\tconst assumption = operationPackSemanticsAssumption(assumptions, operation);\n\tif (!assumption) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `operation ${operation.ref} is missing an operation-pack-semantics assumption for ${operation.operationKind.artifact.id}@${operation.operationKind.artifact.version}`,\n\t\t};\n\t}\n\treturn { ok: true };\n}\n\nfunction validateBinding(params: {\n\treadonly guard: GuardedPlanStep['guards'][number];\n\treadonly claims: readonly ProofClaim[];\n\treadonly assumptions: readonly Assumption[];\n\treadonly requiredAssumptionIds?: readonly string[];\n\treadonly expectedAsserter: Assumption['asserter'];\n}): TransitionRelationalValidationResult {\n\tconst {\n\t\tguard,\n\t\tclaims,\n\t\tassumptions,\n\t\trequiredAssumptionIds,\n\t\texpectedAsserter,\n\t} = params;\n\tif (guard.protocol.kind === 'impossible' || !guard.protocol.binding) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `guard ${guard.predicate.kind} has an impossible protocol`,\n\t\t};\n\t}\n\tconst binding = guard.protocol.binding;\n\tif (binding.kind === 'stable-identity') {\n\t\treturn validateEstablishedClaim({\n\t\t\tclaimId: binding.identityClaim,\n\t\t\tclaims,\n\t\t\tassumptions,\n\t\t\trequiredAssumptionIds,\n\t\t\tmissingDetail: `stable-identity binding references missing or unestablished claim ${binding.identityClaim}`,\n\t\t\trejectedDetail: (conclusion) =>\n\t\t\t\t`stable-identity binding references ${conclusion} claim ${binding.identityClaim}`,\n\t\t\tmissingAssumptionDetail: (assumptionId) =>\n\t\t\t\t`stable-identity binding claim ${binding.identityClaim} assumes missing assumption ${assumptionId}`,\n\t\t\tmissingClosureDetail: (assumptionId) =>\n\t\t\t\t`stable-identity binding claim ${binding.identityClaim} assumes ${assumptionId}, which is missing from the step assumption closure`,\n\t\t});\n\t}\n\tif (binding.kind !== 'external-ddl-exclusion') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `guard ${guard.predicate.kind} has unbindable target protocol`,\n\t\t};\n\t}\n\n\tconst assumption = assumptions.find(\n\t\t(candidate) => candidate.id === binding.assumption,\n\t);\n\tif (!assumption) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion binding references missing assumption ${binding.assumption}`,\n\t\t};\n\t}\n\tif (assumption.class !== 'external-ddl-exclusion') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion binding ${binding.assumption} references assumption class ${assumption.class}`,\n\t\t};\n\t}\n\tif (!sameTrustRoot(assumption.asserter, expectedAsserter)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion assumption ${binding.assumption} has the wrong trust root`,\n\t\t};\n\t}\n\tif (!resourceCovers(assumption.scope, binding.scope)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion assumption ${binding.assumption} does not cover its binding scope`,\n\t\t};\n\t}\n\tif (!resourceCovers(assumption.scope, guard.predicate.scope)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion assumption ${binding.assumption} does not cover its guard scope`,\n\t\t};\n\t}\n\tif (\n\t\trequiredAssumptionIds &&\n\t\t!requiredAssumptionIds.includes(binding.assumption)\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `external-ddl-exclusion assumption ${binding.assumption} is missing from the step assumption closure`,\n\t\t};\n\t}\n\treturn { ok: true };\n}\n\nfunction validateObservationContexts(\n\tcontexts: readonly ObservationContext[],\n): TransitionRelationalValidationResult {\n\tif (contexts.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: 'plan contains no durable evidence context',\n\t\t};\n\t}\n\tconst expected = stableJson(contexts[0]);\n\tfor (const context of contexts.slice(1)) {\n\t\tif (stableJson(context) !== expected) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: 'plan evidence observations do not share one context',\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction executionCommitBoundaryBefore(\n\texecution: OperationEffectAssessment['effects']['execution'],\n): boolean {\n\treturn (\n\t\texecution.commitBoundary === 'before' ||\n\t\texecution.commitBoundary === 'before-and-after'\n\t);\n}\n\nfunction executionCommitBoundaryAfter(\n\texecution: OperationEffectAssessment['effects']['execution'],\n): boolean {\n\treturn (\n\t\texecution.commitBoundary === 'after' ||\n\t\texecution.commitBoundary === 'before-and-after'\n\t);\n}\n\nfunction executionPostconditionVisibleOnlyAfterCommit(\n\texecution: OperationEffectAssessment['effects']['execution'],\n): boolean {\n\treturn execution.postconditionVisibility === 'after-commit';\n}\n\nfunction validateSegmentExecutionSemantics(\n\tplan: ProvenPlanShape,\n\toperationEffectsByRef: ReadonlyMap<string, OperationEffectAssessment>,\n): TransitionRelationalValidationResult {\n\tconst stepById = new Map(plan.steps.map((step) => [step.stepId, step]));\n\tconst executableStepIds = plan.segments.flatMap((segment) => [\n\t\t...segment.stepIds,\n\t]);\n\tconst globalStepIndex = new Map(\n\t\texecutableStepIds.map((stepId, index) => [stepId, index]),\n\t);\n\tfor (const segment of plan.segments) {\n\t\tfor (const [segmentIndex, stepId] of segment.stepIds.entries()) {\n\t\t\tconst step = stepById.get(stepId);\n\t\t\tif (!step) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst effects = operationEffectsByRef.get(step.operation.ref);\n\t\t\tif (!effects) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} is missing operation effects for segment validation`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst execution = effects.effects.execution;\n\t\t\tif (\n\t\t\t\tsegment.transaction === 'joins-current' &&\n\t\t\t\texecution.transaction !== 'joins-current'\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} execution semantics do not match segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\tsegment.transaction === 'forbids-transaction' &&\n\t\t\t\texecution.transaction !== 'forbids-transaction'\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} execution semantics do not match segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\tsegment.transaction !== 'forbids-transaction' &&\n\t\t\t\texecution.transaction === 'forbids-transaction'\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} forbids the transaction used by segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\texecution.transaction === 'requires-new' &&\n\t\t\t\tsegment.transaction !== 'requires-new'\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a new transaction outside segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (execution.transaction === 'requires-new' && segmentIndex > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a new segment before execution`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\texecution.transaction === 'forbids-transaction' &&\n\t\t\t\tsegment.stepIds.length !== 1\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} forbids coalescing with other segment steps`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst currentGlobalIndex = globalStepIndex.get(stepId) ?? 0;\n\t\t\tconst hasPriorExecutableStep = currentGlobalIndex > 0;\n\t\t\tif (\n\t\t\t\texecutionCommitBoundaryBefore(execution) &&\n\t\t\t\thasPriorExecutableStep &&\n\t\t\t\t!segment.commitBoundaryBefore\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a commit boundary before segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (executionCommitBoundaryBefore(execution) && segmentIndex > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a commit boundary before operation but is coalesced in segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst hasLaterSegmentStep = segmentIndex < segment.stepIds.length - 1;\n\t\t\tif (\n\t\t\t\texecutionCommitBoundaryAfter(execution) &&\n\t\t\t\t!segment.commitBoundaryAfter\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a commit boundary after segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (executionCommitBoundaryAfter(execution) && hasLaterSegmentStep) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires a commit boundary after operation but is coalesced in segment ${segment.segmentId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (executionPostconditionVisibleOnlyAfterCommit(execution)) {\n\t\t\t\tif (segment.stepIds.length !== 1) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tdetail: `step ${step.stepId} postcondition is only visible after commit and cannot be coalesced in segment ${segment.segmentId}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (hasPriorExecutableStep && !segment.commitBoundaryBefore) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tdetail: `step ${step.stepId} postcondition is only visible after commit and requires a commit boundary before segment ${segment.segmentId}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!segment.commitBoundaryAfter) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tdetail: `step ${step.stepId} postcondition is only visible after commit and requires a commit boundary after segment ${segment.segmentId}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction validateFragment(\n\tfragment: TransitionFragment,\n\tclaims: readonly ProofClaim[],\n\tassumptions: readonly Assumption[],\n): TransitionRelationalValidationResult {\n\tconst assumptionIds = validateAssumptionIds(assumptions);\n\tif (!assumptionIds.ok) {\n\t\treturn assumptionIds;\n\t}\n\tconst counts = refCounts(fragment.operations);\n\tconst duplicate = duplicateOperationRef(counts);\n\tif (duplicate) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `duplicate operation ref ${duplicate}`,\n\t\t};\n\t}\n\tfor (const obligation of fragment.obligations) {\n\t\tif (!validatesExactlyOneRef(obligation.appliesTo, counts)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `proof obligation ${obligation.proposition.kind} has missing or dangling appliesTo`,\n\t\t\t};\n\t\t}\n\t}\n\tfor (const operation of fragment.operations) {\n\t\tconst operationPackAssumption = validateOperationPackSemanticsAssumption({\n\t\t\toperation,\n\t\t\tassumptions,\n\t\t});\n\t\tif (!operationPackAssumption.ok) {\n\t\t\treturn operationPackAssumption;\n\t\t}\n\t}\n\tfor (const guard of fragment.guards) {\n\t\tif (!validatesExactlyOneRef(guard.appliesTo, counts)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `guard ${guard.predicate.kind} has missing or dangling appliesTo`,\n\t\t\t};\n\t\t}\n\t\tif (guard.protocol.kind === 'impossible') {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `guard ${guard.predicate.kind} has an impossible protocol`,\n\t\t\t};\n\t\t}\n\t\tconst binding = validateBinding({\n\t\t\tguard,\n\t\t\tclaims,\n\t\t\tassumptions,\n\t\t\texpectedAsserter: { kind: 'pack', artifact: fragment.generatedBy.pack },\n\t\t});\n\t\tif (!binding.ok) {\n\t\t\treturn binding;\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction validatePlan(\n\tplan: ProvenPlanShape,\n\toperationEffectsByRef?: ReadonlyMap<string, OperationEffectAssessment>,\n): TransitionRelationalValidationResult {\n\tconst assumptionIds = validateAssumptionIds(plan.assumptions);\n\tif (!assumptionIds.ok) {\n\t\treturn assumptionIds;\n\t}\n\tconst claimEvidence = validateClaimIdsAndEvidence(plan);\n\tif (!claimEvidence.ok) {\n\t\treturn claimEvidence;\n\t}\n\tconst operations = plan.steps.map((step) => step.operation);\n\tconst counts = refCounts(operations);\n\tconst duplicate = duplicateOperationRef(counts);\n\tif (duplicate) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `duplicate operation ref ${duplicate}`,\n\t\t};\n\t}\n\tconst claimIds = new Set(plan.claims.map((claim) => claim.id));\n\tconst assumptionIdSet = new Set(\n\t\tplan.assumptions.map((assumption) => assumption.id),\n\t);\n\tconst stepIds = new Set(plan.steps.map((step) => step.stepId));\n\tconst segmentIds = new Set<string>();\n\tconst segmentStepIds = new Set<string>();\n\tconst segmentByStepId = new Map<string, string>();\n\tfor (const segment of plan.segments) {\n\t\tif (segmentIds.has(segment.segmentId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate segment id ${segment.segmentId}`,\n\t\t\t};\n\t\t}\n\t\tsegmentIds.add(segment.segmentId);\n\t\tif (segment.stepIds.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `segment ${segment.segmentId} contains no steps`,\n\t\t\t};\n\t\t}\n\t\tfor (const stepId of segment.stepIds) {\n\t\t\tif (!stepIds.has(stepId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `segment ${segment.segmentId} references missing step ${stepId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (segmentStepIds.has(stepId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${stepId} is assigned to multiple segments`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tsegmentStepIds.add(stepId);\n\t\t\tsegmentByStepId.set(stepId, segment.segmentId);\n\t\t}\n\t}\n\tconst flattenedSegmentStepIds = plan.segments.flatMap((segment) => [\n\t\t...segment.stepIds,\n\t]);\n\tconst planStepIds = plan.steps.map((step) => step.stepId);\n\tif (stableJson(planStepIds) !== stableJson(flattenedSegmentStepIds)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail:\n\t\t\t\t'plan step order does not match flattened segment execution order',\n\t\t};\n\t}\n\tfor (const step of plan.steps) {\n\t\tif (!segmentIds.has(step.segmentId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `step ${step.stepId} references missing segment ${step.segmentId}`,\n\t\t\t};\n\t\t}\n\t\tif (!segmentStepIds.has(step.stepId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `step ${step.stepId} is missing from its segment`,\n\t\t\t};\n\t\t}\n\t\tif (segmentByStepId.get(step.stepId) !== step.segmentId) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `step ${step.stepId} segment ${step.segmentId} does not match its segment membership`,\n\t\t\t};\n\t\t}\n\t\tconst operationPackAssumption = validateOperationPackSemanticsAssumption({\n\t\t\toperation: step.operation,\n\t\t\tassumptions: plan.assumptions,\n\t\t\trequiredAssumptionIds: step.restsOnAssumptions,\n\t\t\tstepId: step.stepId,\n\t\t\toperationEffects: operationEffectsByRef?.get(step.operation.ref),\n\t\t});\n\t\tif (!operationPackAssumption.ok) {\n\t\t\treturn operationPackAssumption;\n\t\t}\n\t\tfor (const claimId of step.requiredClaims) {\n\t\t\tif (!claimIds.has(claimId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} requires missing claim ${claimId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requiredClaim = validateEstablishedClaim({\n\t\t\t\tclaimId,\n\t\t\t\tclaims: plan.claims,\n\t\t\t\tassumptions: plan.assumptions,\n\t\t\t\trequiredAssumptionIds: step.restsOnAssumptions,\n\t\t\t\tmissingDetail: `step ${step.stepId} requires missing claim ${claimId}`,\n\t\t\t\trejectedDetail: (conclusion) =>\n\t\t\t\t\t`step ${step.stepId} requires ${conclusion} claim ${claimId}`,\n\t\t\t\tmissingAssumptionDetail: (assumptionId) =>\n\t\t\t\t\t`step ${step.stepId} required claim ${claimId} assumes missing assumption ${assumptionId}`,\n\t\t\t\tmissingClosureDetail: (assumptionId) =>\n\t\t\t\t\t`step ${step.stepId} required claim ${claimId} assumes ${assumptionId}, which is missing from the step assumption closure`,\n\t\t\t});\n\t\t\tif (!requiredClaim.ok) {\n\t\t\t\treturn requiredClaim;\n\t\t\t}\n\t\t}\n\t\tfor (const assumptionId of step.restsOnAssumptions) {\n\t\t\tif (!assumptionIdSet.has(assumptionId)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `step ${step.stepId} references missing assumption ${assumptionId}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tfor (const guard of step.guards) {\n\t\t\tif (guard.appliesTo !== step.operation.ref) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `guard ${guard.predicate.kind} applies to ${guard.appliesTo}, not step operation ${step.operation.ref}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!validatesExactlyOneRef(guard.appliesTo, counts)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `guard ${guard.predicate.kind} has missing or dangling appliesTo`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst binding = validateBinding({\n\t\t\t\tguard,\n\t\t\t\tclaims: plan.claims,\n\t\t\t\tassumptions: plan.assumptions,\n\t\t\t\trequiredAssumptionIds: step.restsOnAssumptions,\n\t\t\t\texpectedAsserter: {\n\t\t\t\t\tkind: 'pack',\n\t\t\t\t\tartifact: step.selectionRationale.chosen.pack,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!binding.ok) {\n\t\t\t\treturn binding;\n\t\t\t}\n\t\t}\n\t}\n\tconst contexts = plan.observations\n\t\t.filter((observation) => observation.role === 'evidence')\n\t\t.map((observation) => observation.context);\n\tconst observationContexts = validateObservationContexts(contexts);\n\tif (!observationContexts.ok) {\n\t\treturn observationContexts;\n\t}\n\tif (operationEffectsByRef) {\n\t\tconst segmentExecution = validateSegmentExecutionSemantics(\n\t\t\tplan,\n\t\t\toperationEffectsByRef,\n\t\t);\n\t\tif (!segmentExecution.ok) {\n\t\t\treturn segmentExecution;\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\n/**\n * Diagnostic consistency check for transition fragments and already-trusted,\n * in-process plans. For plan inputs this is not an untrusted serialized-plan\n * validator; apply() first requires the module-private minting capability, and\n * any later plan failure is a prover bug.\n */\nexport function validateTransitionRelationalInvariants(\n\tinput: TransitionRelationalValidationInput,\n): TransitionRelationalValidationResult {\n\treturn input.kind === 'fragment'\n\t\t? validateFragment(input.fragment, input.claims, input.assumptions)\n\t\t: validatePlan(input.plan, input.operationEffectsByRef);\n}\n","import type {\n\tApplyGuard,\n\tCapabilityDescriptor,\n\tDurableIntentRecord,\n\tEquivalenceCapability,\n\tEvidenceObservation,\n\tFingerprintManifest,\n\tIssuedObservation,\n\tLedgerPayload,\n\tManagedStepClaimMaterial,\n\tModelIR,\n\tObservationContext,\n\tObservationIssuer,\n\tOperationEffectAssessment,\n\tOperationExecutionOutcome,\n\tOperationKindRef,\n\tOperationSemantics,\n\tPhysicalOperation,\n\tRecoveryArtefact,\n\tRuleRef,\n\tSemanticArtifactRef,\n\tStepJournal,\n\tTransactionalCompletionRecord,\n\tTransitionCompositionFact,\n\tTransitionRule,\n\tTransitionRunMetadata,\n\tTransitionSessionClient,\n} from '@dbsp/types';\nimport {\n\tmergeCompatibleObservationContexts,\n\ttype ObservationContextMergeResult,\n} from './context-compat.js';\nimport type { DurablyLoadedRun } from './durably-loaded-run.js';\n\nexport interface OperationFingerprints {\n\treadonly expectedBefore: FingerprintManifest;\n\treadonly expectedAfter: FingerprintManifest;\n}\n\nexport interface RegisteredOperationSemantics extends OperationSemantics {\n\treadonly operationKind?: OperationKindRef;\n\t/**\n\t * Execution-contract-aware packs declare whether reviewed requirements can be\n\t * derived for this operation. Contract-construction consumers may use the\n\t * declaration; proving remains available to callers that do not require a\n\t * contract.\n\t */\n\treadonly executionContractEligibility?:\n\t\t| { readonly eligible: true }\n\t\t| { readonly eligible: false; readonly detail: string };\n\t/**\n\t * Session settings that this operation's SQL renderer requires. Execution\n\t * contract construction reads these from the resolved operation runtime, so\n\t * the durable contract cannot drift from renderer prerequisites.\n\t */\n\treadonly rendererSessionRequirements?: readonly {\n\t\treadonly setting: 'standard_conforming_strings';\n\t\treadonly value: 'on';\n\t}[];\n\tsupportsOperation?(operation: PhysicalOperation): boolean;\n\t/**\n\t * Optional non-executable SQL view for a proven operation. Packs opt in per\n\t * operation; consumers must refuse to render operations without this view.\n\t */\n\trenderPlanSql?(\n\t\toperation: PhysicalOperation,\n\t\tcontext: ObservationContext,\n\t): string;\n\tbuildFingerprints(\n\t\toperation: PhysicalOperation,\n\t\tevidence: readonly EvidenceObservation[],\n\t\tcontext: ObservationContext,\n\t): OperationFingerprints;\n}\n\nexport interface OperationObservation {\n\treadonly observations: readonly IssuedObservation[];\n\treadonly fingerprint: FingerprintManifest;\n}\n\nexport interface ComparatorNameNormalizer {\n\t/**\n\t * Normalize identifiers from the observed/current model into the namespace\n\t * used by authored desired models before comparator matching runs. Enum\n\t * names are not normalized: a declared enum name is the physical catalog type\n\t * name that columns reference in `originalDbType` (#825).\n\t */\n\tnormalizeCurrentIdentifier(identifier: string): string;\n}\n\ninterface CompositionFactSatisfactionOwner {\n\treadonly compositionFactKinds: readonly string[];\n\tsatisfiesCompositionFact(\n\t\tfact: TransitionCompositionFact,\n\t\tcurrent: ModelIR,\n\t\tcontext: ObservationContext,\n\t): boolean;\n}\n\nexport type RulePrecedenceFact = {\n\treadonly higher: RuleRef;\n\treadonly lower: RuleRef;\n\treadonly reason: string;\n};\n\nexport interface GuardExecutionResult {\n\treadonly passed: boolean;\n\treadonly observations: readonly IssuedObservation[];\n\treadonly recovery: readonly RecoveryArtefact[];\n}\n\nexport interface TransitionExecutionClient {\n\treadonly opaqueClient: TransitionSessionClient;\n\t/** Mark the checked-out client unsafe to return to its pool. */\n\tmarkClientCompromised(): void;\n}\n\nexport interface NonRollbackableExecutionTracker {\n\tmarkNonRollbackableOperationExecuted(): void;\n}\n\n/**\n * Adapter boundary for a plan-carried managed statement bundle. Core owns the\n * immutable material and the run link; the adapter owns claim admission,\n * token-gated SQL, and the INV-07 transaction composition.\n */\nexport interface ManagedOutcomeExecutionRequest {\n\treadonly claim: ManagedStepClaimMaterial;\n\treadonly run: TransitionRunMetadata;\n\t/** Core-minted proof that this run crossed a verified execution boundary. */\n\treadonly durablyLoadedRun: DurablyLoadedRun;\n\t/** Minted once by apply(), never reused when a recorded run is applied again. */\n\treadonly executionId: string;\n\treadonly transactional: boolean;\n\treadonly lockTimeoutMs: number;\n\t/** The operation's own live postcondition observation, never a generic identity probe. */\n\treadBack(): Promise<LedgerPayload>;\n}\n\n/** The plan and session facts an adapter may inspect before the step intent. */\nexport type ManagedOutcomePreflightRequest = Pick<\n\tManagedOutcomeExecutionRequest,\n\t'claim' | 'run' | 'transactional' | 'lockTimeoutMs'\n>;\n\nexport interface ExecutionCoordinator {\n\treadonly transactionDomain: string;\n\t/**\n\t * When supplied, core calls this after `begin` and before application locks\n\t * for transactional segments. It may reserve the durable run journal on the\n\t * same session so later intent writes keep journal-then-application lock\n\t * order. Generic runtimes without an operation/journal reservation protocol\n\t * leave this absent; in particular a non-transactional segment cannot retain\n\t * a transaction-scoped journal row lock across application locking.\n\t *\n\t * Before an intent exists, core can invoke `begin`, `setLockTimeout`, this\n\t * optional reservation, `rollback`, and `isLockTimeout`. They must\n\t * not perform operation DDL or any external effect. `executeOperation` is\n\t * the first callback allowed to do so.\n\t */\n\treserveJournalRun?(\n\t\tclient: TransitionExecutionClient,\n\t\trun: TransitionRunMetadata,\n\t): Promise<void>;\n\tbegin(client: TransitionExecutionClient): Promise<void>;\n\tsetLockTimeout(\n\t\tclient: TransitionExecutionClient,\n\t\tmaxWaitMs: number,\n\t): Promise<void>;\n\tcommit(client: TransitionExecutionClient): Promise<void>;\n\trollback(client: TransitionExecutionClient): Promise<void>;\n\tisLockTimeout(error: unknown): boolean;\n}\n\nexport interface TransactionCoordinatorBinding {\n\treadonly coordinator: ExecutionCoordinator;\n\treadonly transactionDomain: string;\n}\n\nexport interface OperationRuntime extends RegisteredOperationSemantics {\n\t/**\n\t * Before `writeIntentJournal`, core can invoke `effectsOf`, `begin`,\n\t * `setLockTimeout`, optional `reserveJournalRun`, `acquireLocks`,\n\t * `observeContext`,\n\t * `observeOperation`, `buildFingerprints`, `rollback`, and `isLockTimeout`.\n\t * All must perform no operation DDL or external effect. The only\n\t * pre-intent diagnostic exception is `writeObservedJournal` after a\n\t * fingerprint-construction failure: it may append that immutable failure\n\t * event, but may not perform operation DDL or an external effect. This lets a\n\t * refusal before the intent leave the run pristine; `executeOperation` is the\n\t * first callback allowed to perform the operation's DDL or external effect.\n\t */\n\treserveJournalRun?(\n\t\tclient: TransitionExecutionClient,\n\t\trun: TransitionRunMetadata,\n\t): Promise<void>;\n\twriteIntentJournal(\n\t\tclient: TransitionExecutionClient,\n\t\trecord: DurableIntentRecord,\n\t): Promise<void>;\n\tbegin(client: TransitionExecutionClient): Promise<void>;\n\tsetLockTimeout(\n\t\tclient: TransitionExecutionClient,\n\t\tmaxWaitMs: number,\n\t): Promise<void>;\n\tacquireLocks(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\teffects: OperationEffectAssessment,\n\t\tcontext: ObservationContext,\n\t): Promise<void>;\n\tobserveContext(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\tproofContext: ObservationContext,\n\t): Promise<ObservationContext>;\n\tobserveOperation(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\tcontext: ObservationContext,\n\t\tphase: 'before' | 'after',\n\t\tissuer: ObservationIssuer,\n\t): Promise<OperationObservation>;\n\tcheckGuard(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\tguard: ApplyGuard,\n\t\tcontext: ObservationContext,\n\t): Promise<GuardExecutionResult>;\n\texecuteOperation(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\tcontext: ObservationContext,\n\t\tduringGuards?: readonly ApplyGuard[],\n\t\texecutionTracker?: NonRollbackableExecutionTracker,\n\t): Promise<OperationExecutionOutcome>;\n\t/**\n\t * Required when a plan step carries managed claim material. The applier\n\t * never falls back to `executeOperation` for such a step.\n\t */\n\texecuteManagedOutcome?(\n\t\tclient: TransitionExecutionClient,\n\t\trequest: ManagedOutcomeExecutionRequest,\n\t): Promise<OperationExecutionOutcome>;\n\t/**\n\t * Refuses a managed outcome before its durable step intent is recorded.\n\t * This boundary is for adapter-owned prerequisites such as an incompatible\n\t * ledger marker; it must not execute DDL or append ledger members.\n\t */\n\tpreflightManagedOutcome?(\n\t\tclient: TransitionExecutionClient,\n\t\trequest: ManagedOutcomePreflightRequest,\n\t): Promise<string | undefined>;\n\twriteCompletionJournal(\n\t\tclient: TransitionExecutionClient,\n\t\toperation: PhysicalOperation,\n\t\trecord: TransactionalCompletionRecord,\n\t): Promise<void>;\n\tcommit(client: TransitionExecutionClient): Promise<void>;\n\trollback(client: TransitionExecutionClient): Promise<void>;\n\twriteObservedJournal(\n\t\tclient: TransitionExecutionClient,\n\t\tjournal: StepJournal,\n\t): Promise<void>;\n\tisLockTimeout(error: unknown): boolean;\n}\n\nexport interface TransitionPack {\n\treadonly rules: readonly TransitionRule[];\n\treadonly operationSemantics: readonly RegisteredOperationSemantics[];\n\treadonly issuer: ObservationIssuer;\n\treadonly executionCoordinator?: ExecutionCoordinator;\n\treadonly transactionDomain?: string;\n\treadonly equivalence?: EquivalenceCapability;\n\treadonly capabilityDescriptors?: readonly CapabilityDescriptor[];\n\treadonly comparatorNameNormalizer?: ComparatorNameNormalizer;\n\treadonly compositionFactKinds?: CompositionFactSatisfactionOwner['compositionFactKinds'];\n\treadonly satisfiesCompositionFact?: CompositionFactSatisfactionOwner['satisfiesCompositionFact'];\n\treadonly rulePrecedence?: readonly RulePrecedenceFact[];\n}\n\nexport type OperationResolution =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly semantics: RegisteredOperationSemantics;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly detail: string;\n\t };\n\nfunction artifactKey(ref: SemanticArtifactRef): string {\n\treturn `${ref.id}@${ref.version}`;\n}\n\nfunction operationKey(kind: OperationKindRef): string {\n\treturn `${artifactKey(kind.artifact)}#${kind.name}`;\n}\n\nfunction ruleKey(rule: TransitionRule): string {\n\treturn `${artifactKey(rule.artifact)}#${rule.id}`;\n}\n\nfunction ruleRefKey(ref: RuleRef): string {\n\treturn `${artifactKey(ref.pack)}#${ref.id}`;\n}\n\nfunction sameArtifact(\n\tleft: SemanticArtifactRef,\n\tright: SemanticArtifactRef,\n): boolean {\n\treturn left.id === right.id && left.version === right.version;\n}\n\nexport function serverVersionNum(engineVersion: string): number | undefined {\n\tconst trimmed = engineVersion.trim();\n\tif (trimmed.length === 0 || trimmed === 'unknown') {\n\t\treturn undefined;\n\t}\n\tif (/^\\d+$/.test(trimmed)) {\n\t\tconst parsed = Number.parseInt(trimmed, 10);\n\t\tif (!Number.isFinite(parsed)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn trimmed.length >= 5 ? parsed : parsed * 10_000;\n\t}\n\tconst match = /^(\\d+)(?:\\.(\\d+))?/.exec(trimmed);\n\tif (!match) {\n\t\treturn undefined;\n\t}\n\tconst major = Number.parseInt(match[1] ?? '', 10);\n\tconst minor = Number.parseInt(match[2] ?? '0', 10);\n\tif (!Number.isFinite(major) || !Number.isFinite(minor)) {\n\t\treturn undefined;\n\t}\n\treturn major * 10_000 + minor * 100;\n}\n\nfunction capabilityAvailable(\n\tdescriptor: CapabilityDescriptor,\n\tcontext: ObservationContext,\n): boolean {\n\tswitch (descriptor.predicate.kind) {\n\t\tcase 'minServerVersionNum': {\n\t\t\tconst actual = serverVersionNum(context.engineVersion);\n\t\t\treturn (\n\t\t\t\tactual !== undefined &&\n\t\t\t\tactual >= descriptor.predicate.minServerVersionNum\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Members an operation runtime used to carry when it took connections out of a\n * pool itself. Core owns acquisition and release now, so a pack still declaring\n * them was built against a contract that no longer holds: core would never call\n * them, and the pack would believe it was managing a connection nobody hands it.\n * Recognising such a pack would make that silent, so it is refused instead.\n */\nconst RETIRED_CONNECTION_OWNERSHIP_MEMBERS = ['checkout', 'release'] as const;\n\nfunction retiredConnectionOwnershipMember(value: object): string | undefined {\n\treturn RETIRED_CONNECTION_OWNERSHIP_MEMBERS.find((member) => member in value);\n}\n\nexport function isOperationRuntime(\n\tsemantics: RegisteredOperationSemantics,\n): semantics is OperationRuntime {\n\tif (retiredConnectionOwnershipMember(semantics) !== undefined) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t'writeIntentJournal' in semantics &&\n\t\t'begin' in semantics &&\n\t\t'setLockTimeout' in semantics &&\n\t\t'acquireLocks' in semantics &&\n\t\t'observeContext' in semantics &&\n\t\t'observeOperation' in semantics &&\n\t\t'checkGuard' in semantics &&\n\t\t'executeOperation' in semantics &&\n\t\t'writeCompletionJournal' in semantics &&\n\t\t'commit' in semantics &&\n\t\t'rollback' in semantics &&\n\t\t'writeObservedJournal' in semantics &&\n\t\t'isLockTimeout' in semantics\n\t);\n}\n\nexport type RulePrecedenceResolution =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly rule: TransitionRule;\n\t\t\treadonly facts: readonly RulePrecedenceFact[];\n\t\t\treadonly reason: string;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly detail: string;\n\t };\n\nfunction validateRulePrecedenceFacts(\n\tfacts: readonly RulePrecedenceFact[],\n\trules: readonly TransitionRule[],\n): readonly RulePrecedenceFact[] {\n\tconst rulesByKey = new Map(rules.map((rule) => [ruleKey(rule), rule]));\n\tconst seenPairs = new Set<string>();\n\tconst edges = new Map<string, Set<string>>();\n\tconst visitState = new Map<string, 'visiting' | 'visited'>();\n\n\tfor (const fact of facts) {\n\t\tconst higherKey = ruleRefKey(fact.higher);\n\t\tconst lowerKey = ruleRefKey(fact.lower);\n\t\tif (!rulesByKey.has(higherKey)) {\n\t\t\tthrow new Error(\n\t\t\t\t`rule precedence higher ref did not resolve: ${higherKey}`,\n\t\t\t);\n\t\t}\n\t\tif (!rulesByKey.has(lowerKey)) {\n\t\t\tthrow new Error(`rule precedence lower ref did not resolve: ${lowerKey}`);\n\t\t}\n\t\tif (higherKey === lowerKey) {\n\t\t\tthrow new Error(`rule precedence self-reference for ${higherKey}`);\n\t\t}\n\t\tconst pairKey = `${higherKey}>${lowerKey}`;\n\t\tconst reversePairKey = `${lowerKey}>${higherKey}`;\n\t\tif (seenPairs.has(pairKey)) {\n\t\t\tthrow new Error(`duplicate rule precedence fact for ${pairKey}`);\n\t\t}\n\t\tif (seenPairs.has(reversePairKey)) {\n\t\t\tthrow new Error(\n\t\t\t\t`conflicting rule precedence facts for ${pairKey} and ${reversePairKey}`,\n\t\t\t);\n\t\t}\n\t\tseenPairs.add(pairKey);\n\t\tconst outgoing = edges.get(higherKey) ?? new Set<string>();\n\t\toutgoing.add(lowerKey);\n\t\tedges.set(higherKey, outgoing);\n\t}\n\n\tconst visit = (key: string, trail: readonly string[]): void => {\n\t\tconst state = visitState.get(key);\n\t\tif (state === 'visited') {\n\t\t\treturn;\n\t\t}\n\t\tif (state === 'visiting') {\n\t\t\tthrow new Error(\n\t\t\t\t`cyclic rule precedence facts: ${[...trail, key].join(' -> ')}`,\n\t\t\t);\n\t\t}\n\t\tvisitState.set(key, 'visiting');\n\t\tfor (const lower of edges.get(key) ?? []) {\n\t\t\tvisit(lower, [...trail, key]);\n\t\t}\n\t\tvisitState.set(key, 'visited');\n\t};\n\n\tfor (const key of edges.keys()) {\n\t\tvisit(key, []);\n\t}\n\n\treturn facts;\n}\n\nexport class PackRegistry {\n\tprivate readonly rules: readonly TransitionRule[];\n\tprivate readonly operationSemantics: readonly RegisteredOperationSemantics[];\n\tprivate readonly issuers: readonly ObservationIssuer[];\n\tprivate readonly rulePrecedence: readonly RulePrecedenceFact[];\n\tprivate readonly issuerByArtifact: ReadonlyMap<string, ObservationIssuer>;\n\tprivate readonly equivalenceByArtifact: ReadonlyMap<\n\t\tstring,\n\t\tEquivalenceCapability\n\t>;\n\tprivate readonly compositionFactOwnerByKind: ReadonlyMap<\n\t\tstring,\n\t\tCompositionFactSatisfactionOwner\n\t>;\n\tprivate readonly capabilityDescriptors: readonly CapabilityDescriptor[];\n\tprivate readonly nameNormalizer: ComparatorNameNormalizer | undefined;\n\tprivate readonly privilegeMergers: readonly NonNullable<\n\t\tObservationIssuer['mergeObservationPrivileges']\n\t>[];\n\tprivate readonly transactionCoordinatorBySemantics: WeakMap<\n\t\tRegisteredOperationSemantics,\n\t\tTransactionCoordinatorBinding\n\t>;\n\n\tconstructor(packs: readonly TransitionPack[]) {\n\t\tthis.rules = packs.flatMap((pack) => [...pack.rules]);\n\t\tthis.operationSemantics = packs.flatMap((pack) => [\n\t\t\t...pack.operationSemantics,\n\t\t]);\n\t\tthis.issuers = packs.map((pack) => pack.issuer);\n\t\tthis.privilegeMergers = [\n\t\t\t...new Set(\n\t\t\t\tthis.issuers.flatMap((issuer) =>\n\t\t\t\t\tissuer.mergeObservationPrivileges\n\t\t\t\t\t\t? [issuer.mergeObservationPrivileges.bind(issuer)]\n\t\t\t\t\t\t: [],\n\t\t\t\t),\n\t\t\t),\n\t\t];\n\t\tthis.capabilityDescriptors = packs.flatMap((pack) => [\n\t\t\t...(pack.capabilityDescriptors ?? []),\n\t\t]);\n\t\tconst normalizers = packs.flatMap((pack) =>\n\t\t\tpack.comparatorNameNormalizer ? [pack.comparatorNameNormalizer] : [],\n\t\t);\n\t\tconst distinctNormalizers = new Set(normalizers);\n\t\tif (distinctNormalizers.size > 1) {\n\t\t\tthrow new Error('ambiguous transition comparator name normalizer');\n\t\t}\n\t\tthis.nameNormalizer = normalizers[0];\n\t\tconst ruleKeys = new Set<string>();\n\t\tfor (const rule of this.rules) {\n\t\t\tconst key = ruleKey(rule);\n\t\t\tif (ruleKeys.has(key)) {\n\t\t\t\tthrow new Error(`duplicate transition rule registration for ${key}`);\n\t\t\t}\n\t\t\truleKeys.add(key);\n\t\t}\n\t\tthis.rulePrecedence = validateRulePrecedenceFacts(\n\t\t\tpacks.flatMap((pack) => [...(pack.rulePrecedence ?? [])]),\n\t\t\tthis.rules,\n\t\t);\n\t\tconst issuerArtifactKeys = new Set<string>();\n\t\tfor (const issuer of this.issuers) {\n\t\t\tconst key = artifactKey(issuer.artifact);\n\t\t\tif (issuerArtifactKeys.has(key)) {\n\t\t\t\tthrow new Error(`duplicate transition issuer registration for ${key}`);\n\t\t\t}\n\t\t\tissuerArtifactKeys.add(key);\n\t\t}\n\t\tconst issuerByArtifact = new Map<string, ObservationIssuer>();\n\t\tconst equivalenceByArtifact = new Map<string, EquivalenceCapability>();\n\t\tconst bindIssuer = (key: string, issuer: ObservationIssuer) => {\n\t\t\tconst prior = issuerByArtifact.get(key);\n\t\t\tif (prior && prior !== issuer) {\n\t\t\t\tthrow new Error(`ambiguous transition issuer registration for ${key}`);\n\t\t\t}\n\t\t\tissuerByArtifact.set(key, issuer);\n\t\t};\n\t\tconst bindEquivalence = (\n\t\t\tkey: string,\n\t\t\tequivalence: EquivalenceCapability,\n\t\t) => {\n\t\t\tconst prior = equivalenceByArtifact.get(key);\n\t\t\tif (prior && prior !== equivalence) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ambiguous transition equivalence registration for ${key}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tequivalenceByArtifact.set(key, equivalence);\n\t\t};\n\t\tconst compositionFactOwnerByKind = new Map<\n\t\t\tstring,\n\t\t\tCompositionFactSatisfactionOwner\n\t\t>();\n\t\tconst transactionCoordinatorBySemantics = new WeakMap<\n\t\t\tRegisteredOperationSemantics,\n\t\t\tTransactionCoordinatorBinding\n\t\t>();\n\t\tconst bindCompositionFactOwner = (\n\t\t\tkind: string,\n\t\t\towner: CompositionFactSatisfactionOwner,\n\t\t) => {\n\t\t\tconst prior = compositionFactOwnerByKind.get(kind);\n\t\t\tif (prior && prior !== owner) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ambiguous composition fact satisfaction owner for ${kind}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcompositionFactOwnerByKind.set(kind, owner);\n\t\t};\n\t\tfor (const pack of packs) {\n\t\t\tconst retiredMember = pack.executionCoordinator\n\t\t\t\t? retiredConnectionOwnershipMember(pack.executionCoordinator)\n\t\t\t\t: undefined;\n\t\t\tif (retiredMember !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`transition pack executionCoordinator declares retired connection ownership member ${retiredMember}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst transactionDomain =\n\t\t\t\tpack.transactionDomain ?? pack.executionCoordinator?.transactionDomain;\n\t\t\tif (pack.executionCoordinator && !transactionDomain) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'transition pack executionCoordinator must declare a transactionDomain',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!pack.executionCoordinator && transactionDomain) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'transition pack transactionDomain requires an executionCoordinator',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tpack.executionCoordinator &&\n\t\t\t\ttransactionDomain !== pack.executionCoordinator.transactionDomain\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'transition pack transactionDomain must match its executionCoordinator transactionDomain',\n\t\t\t\t);\n\t\t\t}\n\t\t\tbindIssuer(artifactKey(pack.issuer.artifact), pack.issuer);\n\t\t\tif (pack.equivalence) {\n\t\t\t\tbindEquivalence(\n\t\t\t\t\tartifactKey(pack.equivalence.artifact),\n\t\t\t\t\tpack.equivalence,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const rule of pack.rules) {\n\t\t\t\tbindIssuer(artifactKey(rule.artifact), pack.issuer);\n\t\t\t\tif (pack.equivalence) {\n\t\t\t\t\tbindEquivalence(artifactKey(rule.artifact), pack.equivalence);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const semantics of pack.operationSemantics) {\n\t\t\t\tbindIssuer(artifactKey(semantics.artifact), pack.issuer);\n\t\t\t\tif (pack.equivalence) {\n\t\t\t\t\tbindEquivalence(artifactKey(semantics.artifact), pack.equivalence);\n\t\t\t\t}\n\t\t\t\tif (semantics.operationKind) {\n\t\t\t\t\tbindIssuer(\n\t\t\t\t\t\tartifactKey(semantics.operationKind.artifact),\n\t\t\t\t\t\tpack.issuer,\n\t\t\t\t\t);\n\t\t\t\t\tif (pack.equivalence) {\n\t\t\t\t\t\tbindEquivalence(\n\t\t\t\t\t\t\tartifactKey(semantics.operationKind.artifact),\n\t\t\t\t\t\t\tpack.equivalence,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pack.executionCoordinator && transactionDomain) {\n\t\t\t\t\ttransactionCoordinatorBySemantics.set(semantics, {\n\t\t\t\t\t\tcoordinator: pack.executionCoordinator,\n\t\t\t\t\t\ttransactionDomain,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pack.satisfiesCompositionFact) {\n\t\t\t\tconst owner: CompositionFactSatisfactionOwner = {\n\t\t\t\t\tcompositionFactKinds: pack.compositionFactKinds ?? [],\n\t\t\t\t\tsatisfiesCompositionFact: pack.satisfiesCompositionFact,\n\t\t\t\t};\n\t\t\t\tfor (const kind of owner.compositionFactKinds) {\n\t\t\t\t\tbindCompositionFactOwner(kind, owner);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.issuerByArtifact = issuerByArtifact;\n\t\tthis.equivalenceByArtifact = equivalenceByArtifact;\n\t\tthis.compositionFactOwnerByKind = compositionFactOwnerByKind;\n\t\tthis.transactionCoordinatorBySemantics = transactionCoordinatorBySemantics;\n\t}\n\n\tallRules(): readonly TransitionRule[] {\n\t\treturn this.rules;\n\t}\n\n\tdefaultIssuer(): ObservationIssuer | undefined {\n\t\treturn this.issuers[0];\n\t}\n\n\tcomparatorNameNormalizer(): ComparatorNameNormalizer | undefined {\n\t\treturn this.nameNormalizer;\n\t}\n\n\tresolveRule(ref: RuleRef): TransitionRule | undefined {\n\t\treturn this.rules.find(\n\t\t\t(rule) => rule.id === ref.id && sameArtifact(rule.artifact, ref.pack),\n\t\t);\n\t}\n\n\tresolveRulePrecedence(\n\t\trules: readonly TransitionRule[],\n\t): RulePrecedenceResolution {\n\t\tif (rules.length === 0) {\n\t\t\treturn { ok: false, detail: 'missing matching transition rules' };\n\t\t}\n\t\tif (rules.length === 1) {\n\t\t\tconst rule = rules[0];\n\t\t\tif (!rule) {\n\t\t\t\treturn { ok: false, detail: 'missing matching transition rule' };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\trule,\n\t\t\t\tfacts: [],\n\t\t\t\treason: 'single recognized transition rule',\n\t\t\t};\n\t\t}\n\n\t\tconst matchingKeys = new Set(rules.map((rule) => ruleKey(rule)));\n\t\tconst facts = this.rulePrecedence.filter(\n\t\t\t(fact) =>\n\t\t\t\tmatchingKeys.has(ruleRefKey(fact.higher)) &&\n\t\t\t\tmatchingKeys.has(ruleRefKey(fact.lower)),\n\t\t);\n\t\tconst reachable = new Map<string, Set<string>>();\n\t\tfor (const rule of rules) {\n\t\t\treachable.set(ruleKey(rule), new Set<string>());\n\t\t}\n\t\tfor (const fact of facts) {\n\t\t\treachable.get(ruleRefKey(fact.higher))?.add(ruleRefKey(fact.lower));\n\t\t}\n\n\t\tlet changed = true;\n\t\twhile (changed) {\n\t\t\tchanged = false;\n\t\t\tfor (const lowerSet of reachable.values()) {\n\t\t\t\tfor (const lower of [...lowerSet]) {\n\t\t\t\t\tfor (const transitiveLower of reachable.get(lower) ?? []) {\n\t\t\t\t\t\tif (!lowerSet.has(transitiveLower)) {\n\t\t\t\t\t\t\tlowerSet.add(transitiveLower);\n\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (let leftIndex = 0; leftIndex < rules.length; leftIndex += 1) {\n\t\t\tconst left = rules[leftIndex];\n\t\t\tif (!left) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst leftKey = ruleKey(left);\n\t\t\tfor (\n\t\t\t\tlet rightIndex = leftIndex + 1;\n\t\t\t\trightIndex < rules.length;\n\t\t\t\trightIndex += 1\n\t\t\t) {\n\t\t\t\tconst right = rules[rightIndex];\n\t\t\t\tif (!right) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst rightKey = ruleKey(right);\n\t\t\t\tif (\n\t\t\t\t\t!reachable.get(leftKey)?.has(rightKey) &&\n\t\t\t\t\t!reachable.get(rightKey)?.has(leftKey)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tdetail: `rule precedence is not total between ${leftKey} and ${rightKey}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst maximal = rules.filter((rule) => {\n\t\t\tconst key = ruleKey(rule);\n\t\t\treturn rules.every((candidate) => {\n\t\t\t\tconst candidateKey = ruleKey(candidate);\n\t\t\t\treturn candidateKey === key || !reachable.get(candidateKey)?.has(key);\n\t\t\t});\n\t\t});\n\t\tif (maximal.length !== 1 || !maximal[0]) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: 'rule precedence did not yield a unique maximal rule',\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\trule: maximal[0],\n\t\t\tfacts,\n\t\t\treason: facts.map((fact) => fact.reason).join('; '),\n\t\t};\n\t}\n\n\tresolveIssuer(ref?: SemanticArtifactRef): ObservationIssuer | undefined {\n\t\tif (!ref) {\n\t\t\treturn this.defaultIssuer();\n\t\t}\n\t\treturn this.issuerByArtifact.get(artifactKey(ref));\n\t}\n\n\tresolveEquivalence(\n\t\tref?: SemanticArtifactRef,\n\t): EquivalenceCapability | undefined {\n\t\tif (!ref) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.equivalenceByArtifact.get(artifactKey(ref));\n\t}\n\n\tcontextWithDerivedCapabilities(\n\t\tcontext: ObservationContext,\n\t): ObservationContext {\n\t\tif (this.capabilityDescriptors.length === 0) {\n\t\t\treturn context;\n\t\t}\n\t\tconst capabilities = this.capabilityDescriptors.flatMap((descriptor) =>\n\t\t\tcapabilityAvailable(descriptor, context) ? [descriptor.id] : [],\n\t\t);\n\t\treturn {\n\t\t\t...context,\n\t\t\tcapabilities: [\n\t\t\t\t...new Set([...context.capabilities, ...capabilities]),\n\t\t\t].sort(),\n\t\t};\n\t}\n\n\tmergeObservationContexts(\n\t\tleft: ObservationContext,\n\t\tright: ObservationContext,\n\t): ObservationContextMergeResult {\n\t\tconst merger =\n\t\t\tthis.privilegeMergers.length === 1 ? this.privilegeMergers[0] : undefined;\n\t\tconst result = mergeCompatibleObservationContexts(left, right, merger);\n\t\tif (\n\t\t\tresult.ok ||\n\t\t\tthis.privilegeMergers.length <= 1 ||\n\t\t\tresult.detail !==\n\t\t\t\t'candidate proof contexts differ in privileges and no issuer privilege merger is registered'\n\t\t) {\n\t\t\treturn result;\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail:\n\t\t\t\t'candidate proof contexts differ in privileges and privilege merging is ambiguous',\n\t\t};\n\t}\n\n\tsatisfiesCompositionFact(\n\t\tfact: Parameters<\n\t\t\tCompositionFactSatisfactionOwner['satisfiesCompositionFact']\n\t\t>[0],\n\t\tcurrent: ModelIR,\n\t\tcontext: ObservationContext,\n\t): boolean {\n\t\tconst owner = this.compositionFactOwnerByKind.get(fact.kind);\n\t\tif (!owner) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\treturn owner.satisfiesCompositionFact(fact, current, context) === true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tresolveOperation(operation: PhysicalOperation): OperationResolution {\n\t\tconst key = operationKey(operation.operationKind);\n\t\tconst matches = this.operationSemantics.filter((semantics) => {\n\t\t\tif (semantics.operationKind) {\n\t\t\t\tif (operationKey(semantics.operationKind) !== key) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn semantics.supportsOperation?.(operation) ?? true;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tartifactKey(semantics.artifact) !==\n\t\t\t\tartifactKey(operation.operationKind.artifact)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn semantics.supportsOperation?.(operation) ?? false;\n\t\t});\n\t\tconst match = matches[0];\n\t\tif (matches.length === 1 && match) {\n\t\t\treturn { ok: true, semantics: match };\n\t\t}\n\t\tif (matches.length > 1) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `ambiguous operation runtime for ${key}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: `operation runtime missing for ${key}`,\n\t\t};\n\t}\n\n\ttransactionCoordinatorFor(\n\t\tsemantics: RegisteredOperationSemantics,\n\t): TransactionCoordinatorBinding | undefined {\n\t\treturn this.transactionCoordinatorBySemantics.get(semantics);\n\t}\n}\n\nexport function createPackRegistry(\n\tpacks: readonly TransitionPack[],\n): PackRegistry {\n\treturn new PackRegistry(packs);\n}\n\nexport type {\n\tTransitionLessor,\n\tTransitionQueryClient,\n\tTransitionSessionClient,\n} from '@dbsp/types';\n","import type {\n\tApplyPolicy,\n\tAssumption,\n\tResourceAddress,\n\tResourceSelector,\n\tTrustRoot,\n} from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport function sameTrustRoot(left: TrustRoot, right: TrustRoot): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nexport function sameResource(\n\tleft: ResourceAddress,\n\tright: ResourceAddress,\n): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nexport function resourceIsWithin(\n\tresource: ResourceAddress,\n\tparent: ResourceAddress,\n): boolean {\n\tif (sameResource(resource, parent)) {\n\t\treturn true;\n\t}\n\tif (\n\t\tresource.engine !== parent.engine ||\n\t\tresource.database !== parent.database\n\t) {\n\t\treturn false;\n\t}\n\tif (parent.kind === 'database') {\n\t\treturn true;\n\t}\n\tif (parent.kind === 'schema') {\n\t\treturn resource.schema === parent.name;\n\t}\n\tif (resource.schema !== parent.schema) {\n\t\treturn false;\n\t}\n\treturn resource.qualifiedBy?.includes(parent.name) ?? false;\n}\n\nexport function selectorMatchesResource(\n\tselector: ResourceSelector,\n\tresource: ResourceAddress,\n): boolean {\n\tif (selector.within && !resourceIsWithin(resource, selector.within)) {\n\t\treturn false;\n\t}\n\tif (selector.kind && selector.kind !== resource.kind) {\n\t\treturn false;\n\t}\n\tif (selector.schema && selector.schema !== resource.schema) {\n\t\treturn false;\n\t}\n\tif (selector.name && selector.name !== resource.name) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function resourceScopeCovers(\n\tscope: readonly ResourceAddress[],\n\trequired: readonly ResourceAddress[],\n): boolean {\n\treturn required.every((resource) =>\n\t\tscope.some((covering) => resourceIsWithin(resource, covering)),\n\t);\n}\n\nexport function assumptionAccepted(\n\tassumption: Assumption,\n\tpolicy: ApplyPolicy,\n): boolean {\n\treturn policy.accepts.some((acceptance) => {\n\t\tif (acceptance.class !== assumption.class) {\n\t\t\treturn false;\n\t\t}\n\t\tif (\n\t\t\tacceptance.fromTrustRoot &&\n\t\t\t!sameTrustRoot(acceptance.fromTrustRoot, assumption.asserter)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tif (assumption.scope.length === 0) {\n\t\t\treturn !acceptance.withinScope || acceptance.withinScope.length === 0;\n\t\t}\n\t\tif (!acceptance.withinScope || acceptance.withinScope.length === 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn assumption.scope.every((resource) =>\n\t\t\tacceptance.withinScope?.some((selector) =>\n\t\t\t\tselectorMatchesResource(selector, resource),\n\t\t\t),\n\t\t);\n\t});\n}\n","import type {\n\tApplyPolicy,\n\tApplyResult,\n\tAssumption,\n\tDurableIntentRecord,\n\tEvidenceId,\n\tFingerprintManifest,\n\tIssuedObservation,\n\tObservationContext,\n\tOperationEffectAssessment,\n\tOutcomeReason,\n\tPlanAssessment,\n\tProvenPlanShape,\n\tProvenPlanStep,\n\tRecoveryArtefact,\n\tStepJournal,\n\tTransactionalCompletionRecord,\n\tTransitionJournalEvent,\n\tTransitionRunJournal,\n} from '@dbsp/types';\nimport {\n\tmatchLiveObservationContext,\n\tmatchObservationContextIdentity,\n\tmatchRunObservationContext,\n} from './context-match.js';\nimport { validateExecutionContract } from './execution-contract.js';\nimport { semanticArtifactId } from './ids.js';\nimport { transitionPlanDigest } from './plan-digest.js';\nimport {\n\tisOperationRuntime,\n\ttype PackRegistry,\n\ttype TransitionExecutionClient,\n} from './registry.js';\nimport { assumptionAccepted } from './resource-scope.js';\nimport { stableJson } from './stable-json.js';\nimport {\n\tacquireTransitionTargetLease,\n\tisExclusiveTransitionTarget,\n\tisTransitionLessor,\n\ttype TransitionLease,\n\ttype TransitionReadTarget,\n\ttransitionLessorRejectionAssessment,\n} from './transition-lessor.js';\nimport { validateTransitionRelationalInvariants } from './validation.js';\n\nconst RESUMER_ARTIFACT = {\n\tid: semanticArtifactId('dbsp.core.transition.resume'),\n\tversion: '0.1.0',\n};\n\nexport interface ResumeTransitionInput {\n\treadonly journal: VerifiedRecoveryJournal;\n\treadonly readContext: (\n\t\ttarget: TransitionReadTarget,\n\t\trun: TransitionRunJournal['run'],\n\t) => Promise<ObservationContext>;\n\treadonly policy?: ApplyPolicy;\n\treadonly target: TransitionReadTarget;\n\treadonly admitRecovery?: import('./index.js').TransitionRecoveryAdmission;\n}\n\n/**\n * A frozen journal whose run identity, durable digest, external review digest,\n * and plan structure were verified together. The WeakSet is the runtime brand:\n * callers may cast a lookalike, but recovery will not accept it.\n */\nexport type VerifiedRecoveryJournal = TransitionRunJournal & {\n\treadonly plan: ProvenPlanShape;\n};\n\nexport type RecoveryJournalLoadResult =\n\t| { readonly ok: true; readonly journal: VerifiedRecoveryJournal }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code:\n\t\t\t\t| 'load-failed'\n\t\t\t\t| 'run-id-mismatch'\n\t\t\t\t| 'plan-digest-mismatch'\n\t\t\t\t| 'plan-invalid'\n\t\t\t\t| 'event-invalid';\n\t\t\treadonly detail: string;\n\t };\n\ntype StepEvents = {\n\treadonly intent?: TransitionJournalEvent & {\n\t\treadonly record: DurableIntentRecord;\n\t};\n\treadonly completion?: TransitionJournalEvent & {\n\t\treadonly record: TransactionalCompletionRecord;\n\t};\n\treadonly observed?: TransitionJournalEvent & { readonly record: StepJournal };\n};\n\ntype GroupEventsResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly grouped: ReadonlyMap<string, StepEvents>;\n\t }\n\t| { readonly ok: false; readonly detail: string };\n\nconst verifiedRecoveryJournals = new WeakSet<object>();\n\nfunction deepFreeze<T>(value: T): T {\n\tif (value !== null && typeof value === 'object') {\n\t\tfor (const child of Object.values(value)) {\n\t\t\tdeepFreeze(child);\n\t\t}\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\nfunction snapshotLoadedRun<T>(value: T): T {\n\tconst serialized = JSON.stringify(value);\n\tif (serialized === undefined) {\n\t\tthrow new Error('loaded transition journal is not JSON serializable');\n\t}\n\treturn deepFreeze(JSON.parse(serialized) as T);\n}\n\n/** Load exactly once, snapshot and freeze the complete durable evidence set. */\nexport async function loadVerifiedRecoveryJournal(\n\trunId: string,\n\texpectedPlanDigest: string,\n\tloadCurrent: (\n\t\trunId: string,\n\t) => Promise<TransitionRunJournal & { readonly plan: ProvenPlanShape }>,\n): Promise<RecoveryJournalLoadResult> {\n\tlet loaded: TransitionRunJournal & { readonly plan: ProvenPlanShape };\n\ttry {\n\t\tloaded = snapshotLoadedRun(await loadCurrent(runId));\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'load-failed',\n\t\t\tdetail: `transition run ${runId} could not be loaded: ${errorDetail(error)}`,\n\t\t};\n\t}\n\tif (loaded.run.runId !== runId) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'run-id-mismatch',\n\t\t\tdetail: 'loaded journal run id does not match requested run id',\n\t\t};\n\t}\n\tlet observedPlanDigest: string;\n\ttry {\n\t\tobservedPlanDigest = transitionPlanDigest(loaded.plan);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'plan-invalid',\n\t\t\tdetail: `loaded plan could not be digested: ${errorDetail(error)}`,\n\t\t};\n\t}\n\tif (observedPlanDigest !== expectedPlanDigest) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'plan-digest-mismatch',\n\t\t\tdetail: 'reviewed plan digest does not match the loaded plan',\n\t\t};\n\t}\n\tif (loaded.run.planDigest !== observedPlanDigest) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'plan-invalid',\n\t\t\tdetail: 'loaded plan digest does not match run metadata',\n\t\t};\n\t}\n\ttry {\n\t\tconst diagnostic = validateTransitionRelationalInvariants({\n\t\t\tkind: 'plan',\n\t\t\tplan: loaded.plan,\n\t\t});\n\t\tif (!diagnostic.ok) {\n\t\t\treturn { ok: false, code: 'plan-invalid', detail: diagnostic.detail };\n\t\t}\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'plan-invalid',\n\t\t\tdetail: `loaded plan could not be validated: ${errorDetail(error)}`,\n\t\t};\n\t}\n\tconst stepById = new Map(\n\t\tloaded.plan.steps.map((step) => [step.stepId, step]),\n\t);\n\tconst events = groupEvents(loaded.events, loaded.run.runId, stepById);\n\tif (!events.ok) {\n\t\treturn { ok: false, code: 'event-invalid', detail: events.detail };\n\t}\n\tverifiedRecoveryJournals.add(loaded);\n\treturn { ok: true, journal: loaded };\n}\n\nfunction errorDetail(error: unknown): string {\n\treturn error instanceof Error ? error.message : 'unknown error';\n}\nfunction planEvidenceContext(\n\tplan: ProvenPlanShape,\n): ObservationContext | undefined {\n\treturn plan.observations.find(\n\t\t(observation) => observation.role === 'evidence',\n\t)?.context;\n}\n\nfunction assessment(\n\treason: OutcomeReason,\n\tlifecycle: PlanAssessment['lifecycle'],\n\tcontinuation: PlanAssessment['continuation'],\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle,\n\t\tcontinuation,\n\t\treasons: [reason],\n\t};\n}\n\nfunction completedAssessment(): PlanAssessment {\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance: 'accepted-under-assumptions',\n\t\tlifecycle: 'completed',\n\t\tcontinuation: 'none',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'proven-applicable',\n\t\t\t\tclaim: 'dbsp.transition.resume.completed' as never,\n\t\t\t\tscope: [],\n\t\t\t},\n\t\t],\n\t};\n}\n\n/**\n * Every refusal here concerns a run that was already durable, and none of them\n * can read what that run did: the journal could not be loaded, or it was loaded\n * and could not be interpreted, so its completion events — if any — were never\n * validated. `planned` would assert that nothing happened, which is exactly what\n * is unknown. Only a journal that validated and proved itself empty may claim\n * that. The continuation stays `replan-required` rather than `resume-possible`:\n * corrupt or unreadable durable data does not repair itself on retry, whereas\n * replanning observes live state and is safe whatever the earlier run did.\n */\nfunction contextMismatch(\n\tdetail: string,\n\tjournals: readonly StepJournal[] = [],\n\tobservations: readonly IssuedObservation[] = [],\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment(\n\t\t\t{\n\t\t\t\tcode: 'context-mismatch',\n\t\t\t\tartifact: RESUMER_ARTIFACT,\n\t\t\t\tfact: { key: 'resume', value: detail },\n\t\t\t\tscope: [],\n\t\t\t\tdetail,\n\t\t\t},\n\t\t\t'outcome-unknown',\n\t\t\t'replan-required',\n\t\t),\n\t\tjournals,\n\t\tobservations,\n\t};\n}\n\n/** The recovery-admission phase owns target-read failures. */\nfunction recoveryReadFailure(detail: string): ApplyResult {\n\treturn {\n\t\t...contextMismatch(detail),\n\t\trecoveryOutcome: 'recovery-read-failed',\n\t};\n}\n\nfunction unacceptedStepAssumption(\n\tplan: ProvenPlanShape,\n\tstep: ProvenPlanStep,\n\tassumption: Assumption,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment(\n\t\t\t{\n\t\t\t\tcode: 'uncomposable',\n\t\t\t\tfragments: plan.steps.map(\n\t\t\t\t\t(candidate) => candidate.selectionRationale.chosen,\n\t\t\t\t),\n\t\t\t\tassumption: assumption.id,\n\t\t\t\tscope: assumption.scope,\n\t\t\t\tdetail: `resume policy did not accept assumption ${assumption.id} required by step ${step.stepId}`,\n\t\t\t},\n\t\t\t'planned',\n\t\t\t'replan-required',\n\t\t),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction unacceptedPlanAssumption(\n\tplan: ProvenPlanShape,\n\tassumption: Assumption,\n): ApplyResult {\n\treturn {\n\t\tassessment: assessment(\n\t\t\t{\n\t\t\t\tcode: 'uncomposable',\n\t\t\t\tfragments: plan.steps.map((step) => step.selectionRationale.chosen),\n\t\t\t\tassumption: assumption.id,\n\t\t\t\tscope: assumption.scope,\n\t\t\t\tdetail: 'resume policy did not accept required plan assumption',\n\t\t\t},\n\t\t\t'planned',\n\t\t\t'replan-required',\n\t\t),\n\t\tjournals: [],\n\t\tobservations: [],\n\t};\n}\n\nfunction evidenceIds(\n\tobservations: readonly IssuedObservation[],\n): readonly EvidenceId[] {\n\treturn observations\n\t\t.filter((observation) => observation.role === 'evidence')\n\t\t.map((observation) => observation.id);\n}\n\nfunction recordedAt(): string {\n\treturn new Date().toISOString();\n}\n\nfunction fingerprintMatches(\n\texpected: FingerprintManifest,\n\tactual: FingerprintManifest,\n): boolean {\n\treturn expected.digest === actual.digest;\n}\n\nfunction eventRecordIsIntent(\n\tevent: TransitionJournalEvent,\n): event is TransitionJournalEvent & { readonly record: DurableIntentRecord } {\n\treturn event.event === 'intent';\n}\n\nfunction eventRecordIsCompletion(\n\tevent: TransitionJournalEvent,\n): event is TransitionJournalEvent & {\n\treadonly record: TransactionalCompletionRecord;\n} {\n\treturn event.event === 'completion';\n}\n\nfunction eventRecordIsObserved(\n\tevent: TransitionJournalEvent,\n): event is TransitionJournalEvent & { readonly record: StepJournal } {\n\treturn event.event === 'observed';\n}\n\nfunction sameOperationShape(\n\tstep: ProvenPlanStep,\n\tevent: TransitionJournalEvent,\n): boolean {\n\treturn (\n\t\tevent.operationRef === step.operation.ref &&\n\t\tstableJson(event.operationKind) === stableJson(step.operation.operationKind)\n\t);\n}\n\nfunction validateIntentRecordIdentity(params: {\n\treadonly event: TransitionJournalEvent;\n\treadonly step: ProvenPlanStep;\n\treadonly record: DurableIntentRecord;\n}): string | undefined {\n\tif (params.record.stepId !== params.event.stepId) {\n\t\treturn `intent event for ${params.event.stepId} embeds record for ${params.record.stepId}`;\n\t}\n\tif (params.record.runId && params.record.runId !== params.event.runId) {\n\t\treturn `intent record runId ${params.record.runId} does not match event runId ${params.event.runId}`;\n\t}\n\tif (params.record.run && params.record.run.runId !== params.event.runId) {\n\t\treturn `intent record run metadata ${params.record.run.runId} does not match event runId ${params.event.runId}`;\n\t}\n\tif (params.record.operation.ref !== params.event.operationRef) {\n\t\treturn `intent event operationRef ${params.event.operationRef} embeds operation ${params.record.operation.ref}`;\n\t}\n\tif (\n\t\tstableJson(params.record.operation.operationKind) !==\n\t\tstableJson(params.event.operationKind)\n\t) {\n\t\treturn `intent event ${params.event.stepId} embeds a different operation kind`;\n\t}\n\tif (\n\t\tstableJson(params.record.operation) !== stableJson(params.step.operation)\n\t) {\n\t\treturn `intent event ${params.event.stepId} embeds an operation that does not match the plan step`;\n\t}\n\treturn undefined;\n}\n\nfunction validateCompletionRecordIdentity(params: {\n\treadonly event: TransitionJournalEvent;\n\treadonly record: TransactionalCompletionRecord;\n}): string | undefined {\n\tif (params.record.stepId !== params.event.stepId) {\n\t\treturn `completion event for ${params.event.stepId} embeds record for ${params.record.stepId}`;\n\t}\n\tif (params.record.runId && params.record.runId !== params.event.runId) {\n\t\treturn `completion record runId ${params.record.runId} does not match event runId ${params.event.runId}`;\n\t}\n\treturn undefined;\n}\n\nfunction validateObservedRecordIdentity(params: {\n\treadonly event: TransitionJournalEvent;\n\treadonly step: ProvenPlanStep;\n\treadonly record: StepJournal;\n}): string | undefined {\n\tconst intentMismatch = validateIntentRecordIdentity({\n\t\tevent: params.event,\n\t\tstep: params.step,\n\t\trecord: params.record.intent,\n\t});\n\tif (intentMismatch) {\n\t\treturn intentMismatch;\n\t}\n\tconst completion = params.record.transactionalCompletion;\n\tif (completion) {\n\t\tconst completionMismatch = validateCompletionRecordIdentity({\n\t\t\tevent: params.event,\n\t\t\trecord: completion,\n\t\t});\n\t\tif (completionMismatch) {\n\t\t\treturn completionMismatch;\n\t\t}\n\t}\n\tconst observedOutcome = params.record.observedOutcome;\n\tif (observedOutcome && observedOutcome.stepId !== params.event.stepId) {\n\t\treturn `observed event for ${params.event.stepId} embeds observed outcome for ${observedOutcome.stepId}`;\n\t}\n\treturn undefined;\n}\n\nfunction validateJournalEventIdentity(params: {\n\treadonly event: TransitionJournalEvent;\n\treadonly runId: string;\n\treadonly stepById: ReadonlyMap<string, ProvenPlanStep>;\n}): string | undefined {\n\tif (params.event.runId !== params.runId) {\n\t\treturn `journal event runId ${params.event.runId} does not match run ${params.runId}`;\n\t}\n\tconst step = params.stepById.get(params.event.stepId);\n\tif (!step) {\n\t\treturn `journal event references missing step ${params.event.stepId}`;\n\t}\n\tif (!sameOperationShape(step, params.event)) {\n\t\treturn `journal event ${params.event.stepId} operation identity does not match the plan step`;\n\t}\n\tif (eventRecordIsIntent(params.event)) {\n\t\treturn validateIntentRecordIdentity({\n\t\t\tevent: params.event,\n\t\t\tstep,\n\t\t\trecord: params.event.record,\n\t\t});\n\t}\n\tif (eventRecordIsCompletion(params.event)) {\n\t\treturn validateCompletionRecordIdentity({\n\t\t\tevent: params.event,\n\t\t\trecord: params.event.record,\n\t\t});\n\t}\n\tif (eventRecordIsObserved(params.event)) {\n\t\treturn validateObservedRecordIdentity({\n\t\t\tevent: params.event,\n\t\t\tstep,\n\t\t\trecord: params.event.record,\n\t\t});\n\t}\n\treturn `journal event ${params.event.stepId} has unknown event type ${params.event.event}`;\n}\n\nfunction groupEvents(\n\tevents: readonly TransitionJournalEvent[],\n\trunId: string,\n\tstepById: ReadonlyMap<string, ProvenPlanStep>,\n): GroupEventsResult {\n\tconst grouped = new Map<string, StepEvents>();\n\tfor (const event of [...events].sort((left, right) => left.seq - right.seq)) {\n\t\tconst identityMismatch = validateJournalEventIdentity({\n\t\t\tevent,\n\t\t\trunId,\n\t\t\tstepById,\n\t\t});\n\t\tif (identityMismatch) {\n\t\t\treturn { ok: false, detail: identityMismatch };\n\t\t}\n\t\tconst current = grouped.get(event.stepId) ?? {};\n\t\tif (eventRecordIsIntent(event)) {\n\t\t\tgrouped.set(event.stepId, { ...current, intent: event });\n\t\t\tcontinue;\n\t\t}\n\t\tif (eventRecordIsCompletion(event)) {\n\t\t\tgrouped.set(event.stepId, { ...current, completion: event });\n\t\t\tcontinue;\n\t\t}\n\t\tif (eventRecordIsObserved(event)) {\n\t\t\tgrouped.set(event.stepId, { ...current, observed: event });\n\t\t}\n\t}\n\treturn { ok: true, grouped };\n}\n\nfunction latestIntent(\n\tstep: ProvenPlanStep,\n\tevents: StepEvents | undefined,\n): DurableIntentRecord {\n\treturn (\n\t\tevents?.intent?.record ??\n\t\tevents?.observed?.record.intent ?? {\n\t\t\tstepId: step.stepId,\n\t\t\toperation: step.operation,\n\t\t\trecordedAt: recordedAt(),\n\t\t}\n\t);\n}\n\nfunction orderedPlanSteps(\n\tplan: ProvenPlanShape,\n\tstepById: ReadonlyMap<string, ProvenPlanStep>,\n): readonly ProvenPlanStep[] {\n\treturn plan.segments.flatMap((segment) =>\n\t\tsegment.stepIds\n\t\t\t.map((stepId) => stepById.get(stepId))\n\t\t\t.filter((step): step is ProvenPlanStep => step !== undefined),\n\t);\n}\n\nfunction resumeRequiredResult(params: {\n\treadonly step: ProvenPlanStep;\n\treadonly completed: readonly StepJournal[];\n\treadonly observations: readonly IssuedObservation[];\n\treadonly recovery?: readonly RecoveryArtefact[];\n}): ApplyResult {\n\tconst hasCompleted = params.completed.length > 0;\n\treturn {\n\t\tassessment: assessment(\n\t\t\t{\n\t\t\t\tcode: 'resume-required',\n\t\t\t\tstepId: params.step.stepId,\n\t\t\t\trecovery: params.recovery ?? [],\n\t\t\t\tscope: [],\n\t\t\t\tdetail:\n\t\t\t\t\t'remaining work is known after reconciliation; re-prove from the observed state before applying it',\n\t\t\t},\n\t\t\thasCompleted ? 'partially-applied' : 'planned',\n\t\t\t'resume-possible',\n\t\t),\n\t\tjournals: params.completed,\n\t\tobservations: params.observations,\n\t};\n}\n\nfunction unknownResult(params: {\n\treadonly step: ProvenPlanStep;\n\treadonly completed: readonly StepJournal[];\n\treadonly observations: readonly IssuedObservation[];\n\treadonly journal?: StepJournal;\n\treadonly detail?: string;\n}): ApplyResult {\n\tconst journals = params.journal\n\t\t? [...params.completed, params.journal]\n\t\t: params.completed;\n\treturn {\n\t\tassessment: assessment(\n\t\t\t{\n\t\t\t\tcode: 'unknown-step-result',\n\t\t\t\tstepId: params.step.stepId,\n\t\t\t\toperationKind: params.step.operation.operationKind,\n\t\t\t\toperationRef: params.step.operation.ref,\n\t\t\t\tscope: [],\n\t\t\t\t...(params.detail ? { detail: params.detail } : {}),\n\t\t\t},\n\t\t\t'outcome-unknown',\n\t\t\t'human-intervention-required',\n\t\t),\n\t\tjournals,\n\t\tobservations: params.observations,\n\t};\n}\n\nfunction stoppedJournalResult(params: {\n\treadonly plan: ProvenPlanShape;\n\treadonly step: ProvenPlanStep;\n\treadonly journal: StepJournal;\n\treadonly completed: readonly StepJournal[];\n\treadonly observations: readonly IssuedObservation[];\n}): ApplyResult {\n\tconst hasCompleted = params.completed.length > 0;\n\tswitch (params.journal.outcome) {\n\t\tcase 'guard-timeout':\n\t\t\treturn {\n\t\t\t\tassessment: assessment(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'guard-timeout',\n\t\t\t\t\t\tstepId: params.step.stepId,\n\t\t\t\t\t\toperationKind: params.step.operation.operationKind,\n\t\t\t\t\t\toperationRef: params.step.operation.ref,\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t},\n\t\t\t\t\thasCompleted ? 'partially-applied' : 'planned',\n\t\t\t\t\thasCompleted ? 'resume-possible' : 'replan-required',\n\t\t\t\t),\n\t\t\t\tjournals: [...params.completed, params.journal],\n\t\t\t\tobservations: params.observations,\n\t\t\t};\n\t\tcase 'guard-failed':\n\t\t\treturn {\n\t\t\t\tassessment: assessment(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'guard-failed',\n\t\t\t\t\t\tstepId: params.step.stepId,\n\t\t\t\t\t\toperationKind: params.step.operation.operationKind,\n\t\t\t\t\t\toperationRef: params.step.operation.ref,\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\trecovery: params.journal.recovery ?? [],\n\t\t\t\t\t},\n\t\t\t\t\thasCompleted ? 'partially-applied' : 'planned',\n\t\t\t\t\thasCompleted ? 'resume-possible' : 'replan-required',\n\t\t\t\t),\n\t\t\t\tjournals: [...params.completed, params.journal],\n\t\t\t\tobservations: params.observations,\n\t\t\t};\n\t\tcase 'operation-failed-not-applied':\n\t\t\treturn {\n\t\t\t\tassessment: assessment(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'operation-failed-not-applied',\n\t\t\t\t\t\tstepId: params.step.stepId,\n\t\t\t\t\t\toperationKind: params.step.operation.operationKind,\n\t\t\t\t\t\toperationRef: params.step.operation.ref,\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t'journal reports a rolled-back operation failure; no work from that segment was completed',\n\t\t\t\t\t},\n\t\t\t\t\thasCompleted ? 'partially-applied' : 'planned',\n\t\t\t\t\thasCompleted ? 'resume-possible' : 'replan-required',\n\t\t\t\t),\n\t\t\t\tjournals: [...params.completed, params.journal],\n\t\t\t\tobservations: params.observations,\n\t\t\t};\n\t\tcase 'partially-applied':\n\t\t\treturn {\n\t\t\t\tassessment: assessment(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'partially-applied',\n\t\t\t\t\t\tstepId: params.step.stepId,\n\t\t\t\t\t\toperationKind: params.step.operation.operationKind,\n\t\t\t\t\t\toperationRef: params.step.operation.ref,\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t...(params.journal.recovery\n\t\t\t\t\t\t\t? { recovery: params.journal.recovery }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t'journal reports a partial outcome; recovery requires a human or adapter-proven repair action',\n\t\t\t\t\t},\n\t\t\t\t\t'partially-applied',\n\t\t\t\t\t'human-intervention-required',\n\t\t\t\t),\n\t\t\t\tjournals: [...params.completed, params.journal],\n\t\t\t\tobservations: params.observations,\n\t\t\t};\n\t\tcase 'unknown-step-result':\n\t\tcase 'context-mismatch':\n\t\t\treturn unknownResult({\n\t\t\t\tstep: params.step,\n\t\t\t\tcompleted: params.completed,\n\t\t\t\tobservations: params.observations,\n\t\t\t\tjournal: params.journal,\n\t\t\t\tdetail: `journal reports ${params.journal.outcome}`,\n\t\t\t});\n\t\tcase 'completed':\n\t\t\tthrow new Error('completed journal passed to stoppedJournalResult');\n\t}\n}\n\nfunction completedJournal(\n\tintent: DurableIntentRecord,\n\tcompletion: TransactionalCompletionRecord | undefined,\n\tobservations: readonly IssuedObservation[],\n): StepJournal {\n\tconst observedOutcome = {\n\t\tstepId: intent.stepId,\n\t\tobservations: evidenceIds(observations),\n\t\trecordedAt: recordedAt(),\n\t};\n\treturn completion\n\t\t? {\n\t\t\t\tintent,\n\t\t\t\toutcome: 'completed',\n\t\t\t\ttransactionalCompletion: completion,\n\t\t\t\tobservedOutcome,\n\t\t\t}\n\t\t: {\n\t\t\t\tintent,\n\t\t\t\toutcome: 'completed',\n\t\t\t\tobservedOutcome,\n\t\t\t};\n}\n\ntype StepObservation =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly observations: readonly IssuedObservation[];\n\t\t\treadonly fingerprint: FingerprintManifest;\n\t\t\t/** Journal this observation on the same session it was observed from. */\n\t\t\treadonly writeJournal: (journal: StepJournal) => Promise<void>;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly detail: string;\n\t };\n\nasync function withObservedStep<T>(\n\tregistry: PackRegistry,\n\tstep: ProvenPlanStep,\n\ttarget: TransitionReadTarget,\n\tbaseContext: ObservationContext,\n\tphase: 'before' | 'after',\n\tuse: (observation: StepObservation) => Promise<T>,\n): Promise<T> {\n\tconst resolution = registry.resolveOperation(step.operation);\n\tif (!resolution.ok || !isOperationRuntime(resolution.semantics)) {\n\t\treturn use({ ok: false, detail: 'operation runtime missing' });\n\t}\n\tconst runtime = resolution.semantics;\n\tconst issuer = registry.resolveIssuer(step.operation.operationKind.artifact);\n\tif (!issuer) {\n\t\treturn use({ ok: false, detail: 'operation observation issuer missing' });\n\t}\n\tlet lease: TransitionLease | undefined;\n\tlet failed = false;\n\tlet failure: unknown;\n\tlet clientCompromised = false;\n\ttry {\n\t\tlet observation: StepObservation;\n\t\ttry {\n\t\t\tlease = await acquireTransitionTargetLease(target);\n\t\t\tconst client: TransitionExecutionClient = {\n\t\t\t\topaqueClient: lease.session,\n\t\t\t\tmarkClientCompromised: () => {\n\t\t\t\t\tclientCompromised = true;\n\t\t\t\t},\n\t\t\t};\n\t\t\tlet context = await runtime.observeContext(\n\t\t\t\tclient,\n\t\t\t\tstep.operation,\n\t\t\t\tbaseContext,\n\t\t\t);\n\t\t\tcontext = registry.contextWithDerivedCapabilities(context);\n\t\t\tconst liveContextMatch = matchLiveObservationContext({\n\t\t\t\texpected: baseContext,\n\t\t\t\tactual: context,\n\t\t\t});\n\t\t\tif (!liveContextMatch.ok) {\n\t\t\t\tobservation = { ok: false, detail: liveContextMatch.detail };\n\t\t\t} else {\n\t\t\t\tconst observed = await runtime.observeOperation(\n\t\t\t\t\tclient,\n\t\t\t\t\tstep.operation,\n\t\t\t\t\tcontext,\n\t\t\t\t\tphase,\n\t\t\t\t\tissuer,\n\t\t\t\t);\n\t\t\t\tobservation = {\n\t\t\t\t\tok: true,\n\t\t\t\t\tobservations: observed.observations,\n\t\t\t\t\tfingerprint: observed.fingerprint,\n\t\t\t\t\twriteJournal: async (journal) =>\n\t\t\t\t\t\truntime.writeObservedJournal(client, journal),\n\t\t\t\t};\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailed = true;\n\t\t\tfailure = error;\n\t\t\tobservation = {\n\t\t\t\tok: false,\n\t\t\t\tdetail: errorDetail(error),\n\t\t\t};\n\t\t}\n\t\ttry {\n\t\t\treturn await use(observation);\n\t\t} catch (error) {\n\t\t\tfailed = true;\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\tif (lease) {\n\t\t\tawait lease.release(\n\t\t\t\tfailed || clientCompromised\n\t\t\t\t\t? {\n\t\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\tfailure ??\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t'transition observation marked its PostgreSQL client compromised',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction stepAssumption(\n\tplan: ProvenPlanShape,\n\tassumptionId: string,\n): Assumption | undefined {\n\treturn plan.assumptions.find((assumption) => assumption.id === assumptionId);\n}\n\nfunction validatePolicyForStep(\n\tplan: ProvenPlanShape,\n\tstep: ProvenPlanStep,\n\tpolicy: ApplyPolicy,\n): ApplyResult | undefined {\n\tfor (const assumptionId of step.restsOnAssumptions) {\n\t\tconst assumption = stepAssumption(plan, assumptionId);\n\t\tif (assumption && !assumptionAccepted(assumption, policy)) {\n\t\t\treturn unacceptedStepAssumption(plan, step, assumption);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isExecutionAdmissionAssumption(assumption: Assumption): boolean {\n\t// This gates a fresh durable apply, which `resume` never performs. Recovery\n\t// must still report the observed state of an already-recorded intent; CLI\n\t// recovery separately verifies its durable authorization before calling here.\n\treturn assumption.class === 'non-transactional-segment';\n}\n\nasync function resumeTransitionRunInternal(\n\tregistry: PackRegistry,\n\tinput: ResumeTransitionInput,\n\trunId: string,\n\tcompleted: StepJournal[],\n\tobservations: IssuedObservation[],\n): Promise<ApplyResult> {\n\tif (!verifiedRecoveryJournals.has(input.journal)) {\n\t\treturn contextMismatch(\n\t\t\t'recovery journal was not loaded and verified by the durable boundary',\n\t\t);\n\t}\n\tconst loaded = input.journal;\n\tif (loaded.run.runId !== runId) {\n\t\treturn contextMismatch(\n\t\t\t'loaded journal run id does not match requested run id',\n\t\t);\n\t}\n\tconst stepById = new Map(\n\t\tloaded.plan.steps.map((step) => [step.stepId, step]),\n\t);\n\t// Event identity is durable evidence, so validate it before interpreting any\n\t// authorization. A malformed non-empty stream is never a pristine run.\n\tconst groupedResult = groupEvents(loaded.events, loaded.run.runId, stepById);\n\tif (!groupedResult.ok) {\n\t\treturn contextMismatch(groupedResult.detail);\n\t}\n\tconst grouped = groupedResult.grouped;\n\tif (loaded.events.length === 0) {\n\t\tconst firstStep = orderedPlanSteps(loaded.plan, stepById)[0];\n\t\tif (!firstStep) {\n\t\t\treturn {\n\t\t\t\tassessment: completedAssessment(),\n\t\t\t\tjournals: [],\n\t\t\t\tobservations: [],\n\t\t\t};\n\t\t}\n\t\treturn resumeRequiredResult({\n\t\t\tstep: firstStep,\n\t\t\tcompleted: [],\n\t\t\tobservations: [],\n\t\t});\n\t}\n\tconst contract = input.admitRecovery\n\t\t? validateExecutionContract(loaded.plan.executionContract)\n\t\t: undefined;\n\tif (contract && !contract.ok) {\n\t\treturn contextMismatch(\n\t\t\t`recovery admission contract is invalid: ${contract.detail}`,\n\t\t);\n\t}\n\tconst evidenceContext = planEvidenceContext(loaded.plan);\n\tif (!evidenceContext) {\n\t\treturn contextMismatch('loaded plan contains no durable evidence context');\n\t}\n\tconst referencedAssumptions = new Set<string>();\n\tif (!input.policy) {\n\t\treturn contextMismatch('attempted recovery has no durable authorization');\n\t}\n\tfor (const step of loaded.plan.steps) {\n\t\tfor (const assumptionId of step.restsOnAssumptions) {\n\t\t\treferencedAssumptions.add(assumptionId);\n\t\t}\n\t\tconst policyFailure = validatePolicyForStep(\n\t\t\tloaded.plan,\n\t\t\tstep,\n\t\t\tinput.policy,\n\t\t);\n\t\tif (policyFailure) {\n\t\t\treturn policyFailure;\n\t\t}\n\t}\n\tfor (const assumption of loaded.plan.assumptions) {\n\t\tif (\n\t\t\t!referencedAssumptions.has(assumption.id) &&\n\t\t\t!isExecutionAdmissionAssumption(assumption) &&\n\t\t\t!assumptionAccepted(assumption, input.policy)\n\t\t) {\n\t\t\treturn unacceptedPlanAssumption(loaded.plan, assumption);\n\t\t}\n\t}\n\n\tif (\n\t\t!isTransitionLessor(input.target) &&\n\t\t!isExclusiveTransitionTarget(input.target)\n\t) {\n\t\t// Resume accepts journaled outcomes only after re-observing them through the\n\t\t// target, so grouped records alone are not honest result journals here.\n\t\treturn {\n\t\t\tassessment: transitionLessorRejectionAssessment(\n\t\t\t\tRESUMER_ARTIFACT,\n\t\t\t\tloaded.events.length === 0 ? 'planned' : 'outcome-unknown',\n\t\t\t),\n\t\t\tjournals: [],\n\t\t\tobservations: [],\n\t\t};\n\t}\n\t// Same contract as the loader above, and for the same reason: a resume that\n\t// cannot read the live database must return a blocked assessment, not reject\n\t// its promise. Wrapping only the loader made \"database unreachable\" behave\n\t// differently depending on which call the outage landed on.\n\tlet baseContext: ObservationContext;\n\ttry {\n\t\tif (input.admitRecovery) {\n\t\t\tif (!contract?.ok)\n\t\t\t\treturn contextMismatch('recovery admission contract is unavailable');\n\t\t\tconst admitted = await input.admitRecovery(\n\t\t\t\tinput.target,\n\t\t\t\tcontract.contract,\n\t\t\t);\n\t\t\tif (!admitted.ok) return recoveryReadFailure(admitted.detail);\n\t\t\tbaseContext = admitted.context;\n\t\t} else {\n\t\t\tbaseContext = await input.readContext(input.target, loaded.run);\n\t\t}\n\t} catch (error) {\n\t\treturn recoveryReadFailure(\n\t\t\t`transition run ${runId} target context could not be read: ${errorDetail(error)}`,\n\t\t);\n\t}\n\tif (!input.admitRecovery) {\n\t\tconst runContextMatch = matchRunObservationContext({\n\t\t\trun: loaded.run,\n\t\t\tactual: baseContext,\n\t\t});\n\t\tif (!runContextMatch.ok) return contextMismatch(runContextMatch.detail);\n\t\tconst evidenceIdentityMatch = matchObservationContextIdentity({\n\t\t\texpected: baseContext,\n\t\t\tactual: evidenceContext,\n\t\t\tlabel: 'loaded plan evidence context',\n\t\t});\n\t\tif (!evidenceIdentityMatch.ok) {\n\t\t\treturn contextMismatch(\n\t\t\t\t`loaded plan evidence context does not match run proof context: ${evidenceIdentityMatch.detail}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst operationEffectsByRef = new Map<string, OperationEffectAssessment>();\n\tfor (const step of loaded.plan.steps) {\n\t\tconst effectsResolution = registry.resolveOperation(step.operation);\n\t\tif (!effectsResolution.ok) {\n\t\t\treturn contextMismatch(effectsResolution.detail);\n\t\t}\n\t\t// `effectsOf` belongs to a pack, so it is third-party code reached with a\n\t\t// plan and a context this process did not mint. It gets the same treatment.\n\t\ttry {\n\t\t\toperationEffectsByRef.set(\n\t\t\t\tstep.operation.ref,\n\t\t\t\teffectsResolution.semantics.effectsOf(step.operation, baseContext),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\treturn contextMismatch(\n\t\t\t\t`operation ${step.operation.ref} effects could not be resolved: ${errorDetail(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tlet semanticDiagnostic: ReturnType<\n\t\ttypeof validateTransitionRelationalInvariants\n\t>;\n\ttry {\n\t\tsemanticDiagnostic = validateTransitionRelationalInvariants({\n\t\t\tkind: 'plan',\n\t\t\tplan: loaded.plan,\n\t\t\toperationEffectsByRef,\n\t\t});\n\t} catch (error) {\n\t\treturn contextMismatch(\n\t\t\t`loaded plan could not be semantically validated: ${errorDetail(error)}`,\n\t\t);\n\t}\n\tif (!semanticDiagnostic.ok) {\n\t\treturn contextMismatch(\n\t\t\t`loaded plan failed semantic invariant validation: ${semanticDiagnostic.detail}`,\n\t\t);\n\t}\n\tconst orderedSteps = orderedPlanSteps(loaded.plan, stepById);\n\n\tfor (const step of orderedSteps) {\n\t\tconst events = grouped.get(step.stepId);\n\t\tif (!events?.intent && !events?.observed) {\n\t\t\treturn resumeRequiredResult({\n\t\t\t\tstep,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t});\n\t\t}\n\t\tconst intent = latestIntent(step, events);\n\t\tconst observedJournal = events?.observed?.record;\n\t\tif (observedJournal && observedJournal.outcome !== 'completed') {\n\t\t\treturn stoppedJournalResult({\n\t\t\t\tplan: loaded.plan,\n\t\t\t\tstep,\n\t\t\t\tjournal: observedJournal,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t});\n\t\t}\n\n\t\tconst completion = events?.completion?.record;\n\t\tconst effects = operationEffectsByRef.get(step.operation.ref);\n\t\tif (!effects) {\n\t\t\treturn unknownResult({\n\t\t\t\tstep,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t\tdetail: 'operation effects missing',\n\t\t\t});\n\t\t}\n\t\tconst transactional =\n\t\t\teffects.effects.execution.transaction !== 'forbids-transaction';\n\n\t\tif (observedJournal?.outcome === 'completed' || completion) {\n\t\t\tconst after = await withObservedStep(\n\t\t\t\tregistry,\n\t\t\t\tstep,\n\t\t\t\tinput.target,\n\t\t\t\tbaseContext,\n\t\t\t\t'after',\n\t\t\t\tasync (observation) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!observation.ok ||\n\t\t\t\t\t\t!fingerprintMatches(step.expectedAfter, observation.fingerprint)\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unmatched' as const,\n\t\t\t\t\t\t\tdetail: observation.ok\n\t\t\t\t\t\t\t\t? 'current fingerprint no longer matches expectedAfter'\n\t\t\t\t\t\t\t\t: observation.detail,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst journal =\n\t\t\t\t\t\tobservedJournal?.outcome === 'completed'\n\t\t\t\t\t\t\t? observedJournal\n\t\t\t\t\t\t\t: completedJournal(intent, completion, observation.observations);\n\t\t\t\t\tif (!observedJournal) {\n\t\t\t\t\t\tawait observation.writeJournal(journal);\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\tobservations: observation.observations,\n\t\t\t\t\t\tjournal,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (after.kind === 'completed') {\n\t\t\t\tobservations.push(...after.observations);\n\t\t\t\tcompleted.push(after.journal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn unknownResult({\n\t\t\t\tstep,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t\tdetail: after.detail,\n\t\t\t});\n\t\t}\n\n\t\tif (transactional) {\n\t\t\tconst before = await withObservedStep(\n\t\t\t\tregistry,\n\t\t\t\tstep,\n\t\t\t\tinput.target,\n\t\t\t\tbaseContext,\n\t\t\t\t'before',\n\t\t\t\tasync (observation) => ({\n\t\t\t\t\tkind:\n\t\t\t\t\t\tobservation.ok &&\n\t\t\t\t\t\tfingerprintMatches(step.expectedBefore, observation.fingerprint)\n\t\t\t\t\t\t\t? ('resume-required' as const)\n\t\t\t\t\t\t\t: ('unmatched' as const),\n\t\t\t\t\tobservations: observation.ok ? observation.observations : [],\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (before.kind === 'resume-required') {\n\t\t\t\tobservations.push(...before.observations);\n\t\t\t\treturn resumeRequiredResult({\n\t\t\t\t\tstep,\n\t\t\t\t\tcompleted,\n\t\t\t\t\tobservations,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst after = await withObservedStep(\n\t\t\t\tregistry,\n\t\t\t\tstep,\n\t\t\t\tinput.target,\n\t\t\t\tbaseContext,\n\t\t\t\t'after',\n\t\t\t\tasync (observation) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!observation.ok ||\n\t\t\t\t\t\t!fingerprintMatches(step.expectedAfter, observation.fingerprint)\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn { kind: 'unmatched' as const };\n\t\t\t\t\t}\n\t\t\t\t\tconst journal = completedJournal(\n\t\t\t\t\t\tintent,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tobservation.observations,\n\t\t\t\t\t);\n\t\t\t\t\tawait observation.writeJournal(journal);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\tobservations: observation.observations,\n\t\t\t\t\t\tjournal,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (after.kind === 'completed') {\n\t\t\t\tobservations.push(...after.observations);\n\t\t\t\tcompleted.push(after.journal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn unknownResult({\n\t\t\t\tstep,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t\tdetail:\n\t\t\t\t\t'transactional intent had no completion and current state matches neither expectedBefore nor expectedAfter',\n\t\t\t});\n\t\t}\n\n\t\tconst after = await withObservedStep(\n\t\t\tregistry,\n\t\t\tstep,\n\t\t\tinput.target,\n\t\t\tbaseContext,\n\t\t\t'after',\n\t\t\tasync (observation) => {\n\t\t\t\tif (\n\t\t\t\t\t!observation.ok ||\n\t\t\t\t\t!fingerprintMatches(step.expectedAfter, observation.fingerprint)\n\t\t\t\t) {\n\t\t\t\t\treturn { kind: 'unmatched' as const };\n\t\t\t\t}\n\t\t\t\tconst journal = completedJournal(\n\t\t\t\t\tintent,\n\t\t\t\t\tundefined,\n\t\t\t\t\tobservation.observations,\n\t\t\t\t);\n\t\t\t\tawait observation.writeJournal(journal);\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\tobservations: observation.observations,\n\t\t\t\t\tjournal,\n\t\t\t\t};\n\t\t\t},\n\t\t);\n\t\tif (after.kind === 'completed') {\n\t\t\tobservations.push(...after.observations);\n\t\t\tcompleted.push(after.journal);\n\t\t\tcontinue;\n\t\t}\n\t\tconst before = await withObservedStep(\n\t\t\tregistry,\n\t\t\tstep,\n\t\t\tinput.target,\n\t\t\tbaseContext,\n\t\t\t'before',\n\t\t\tasync (observation) => ({\n\t\t\t\tkind:\n\t\t\t\t\tobservation.ok &&\n\t\t\t\t\tfingerprintMatches(step.expectedBefore, observation.fingerprint)\n\t\t\t\t\t\t? ('resume-required' as const)\n\t\t\t\t\t\t: ('unmatched' as const),\n\t\t\t\tobservations: observation.ok ? observation.observations : [],\n\t\t\t}),\n\t\t);\n\t\tif (before.kind === 'resume-required') {\n\t\t\tobservations.push(...before.observations);\n\t\t\treturn resumeRequiredResult({\n\t\t\t\tstep,\n\t\t\t\tcompleted,\n\t\t\t\tobservations,\n\t\t\t});\n\t\t}\n\t\treturn unknownResult({\n\t\t\tstep,\n\t\t\tcompleted,\n\t\t\tobservations,\n\t\t\tdetail:\n\t\t\t\t'non-atomic intent had no completion and adapter observation could not classify it as completed or absent',\n\t\t});\n\t}\n\n\treturn {\n\t\tassessment: completedAssessment(),\n\t\tjournals: completed,\n\t\tobservations,\n\t};\n}\n\nexport async function resumeTransitionRun(\n\tregistry: PackRegistry,\n\tinput: ResumeTransitionInput,\n): Promise<ApplyResult> {\n\tconst completed: StepJournal[] = [];\n\tconst observations: IssuedObservation[] = [];\n\tconst runId = input.journal.run.runId;\n\t// For ordinary failures--an unreachable database, a throwing pack, or a rejected\n\t// journal write--this boundary returns a blocked assessment with steps reconciled\n\t// so far rather than rejecting. Inputs engineered to throw from caller-owned\n\t// accessors are outside this contract: that caller already executes in-process.\n\ttry {\n\t\treturn await resumeTransitionRunInternal(\n\t\t\tregistry,\n\t\t\tinput,\n\t\t\trunId,\n\t\t\tcompleted,\n\t\t\tobservations,\n\t\t);\n\t} catch (error) {\n\t\treturn contextMismatch(\n\t\t\t`transition run ${runId} could not be resumed: ${errorDetail(error)}`,\n\t\t\tcompleted,\n\t\t\tobservations,\n\t\t);\n\t}\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n\tIssuedObservation,\n\tObservationContext,\n\tTransitionRunMetadata,\n} from '@dbsp/types';\nimport { observationContextDigest } from './context-match.js';\nimport { semanticArtifactId } from './ids.js';\nimport type { InProcessProvenPlan } from './index.js';\nimport { transitionPlanDigest } from './plan-digest.js';\nimport { stableJson } from './stable-json.js';\n\n/**\n * The planning artifact, rather than the applier, owns metadata for a run that\n * has been proven but not yet executed. A durable plan must describe the core\n * planner that made its proof; it must not claim that an applier minted it.\n */\nconst TRANSITION_PLANNER_ARTIFACT = {\n\tid: semanticArtifactId('dbsp.core.transition.planner'),\n\tversion: '0.3.0',\n};\n\nfunction evidenceContext(\n\tobservations: readonly IssuedObservation[],\n): ObservationContext {\n\tconst evidence = observations.filter(\n\t\t(observation) => observation.role === 'evidence',\n\t);\n\tconst first = evidence[0]?.context;\n\tif (!first) {\n\t\tthrow new Error(\n\t\t\t'internal error: minted proven plan has no evidence observation context',\n\t\t);\n\t}\n\tconst expected = stableJson(first);\n\tfor (const observation of evidence.slice(1)) {\n\t\tif (stableJson(observation.context) !== expected) {\n\t\t\tthrow new Error(\n\t\t\t\t'internal error: minted proven plan evidence observations do not share one context',\n\t\t\t);\n\t\t}\n\t}\n\treturn first;\n}\n\n/**\n * Mint metadata for a proven transition before making it durable.\n *\n * The target digest is deliberately derived from the plan's evidence, not a\n * caller-supplied snapshot. That is the exact context resume verifies.\n */\nexport function createTransitionRunMetadata(\n\tplan: InProcessProvenPlan,\n): TransitionRunMetadata {\n\tconst context = evidenceContext(plan.observations);\n\treturn {\n\t\trunId: `dbsp-${randomUUID()}`,\n\t\tplanDigest: transitionPlanDigest(plan),\n\t\ttargetContextDigest: observationContextDigest(context),\n\t\tdatabaseId: context.databaseId,\n\t\tcoreVersion: TRANSITION_PLANNER_ARTIFACT.version,\n\t\tstartedAt: new Date().toISOString(),\n\t\treplayability: 'replayable',\n\t};\n}\n\n/** Label a generator removal before persistence; it can never become replayable. */\nexport function markGeneratorRemovalNonReplayable(\n\trun: TransitionRunMetadata,\n): TransitionRunMetadata {\n\treturn { ...run, replayability: 'non-replayable-generator-removal' };\n}\n","import type { CheckConstraintIR } from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport type CheckSetEntry = Pick<\n\tCheckConstraintIR,\n\t'name' | 'expression' | 'notValid'\n>;\n\nexport type CheckDelta =\n\t| { readonly kind: 'none' }\n\t| {\n\t\t\treadonly kind: 'add-check';\n\t\t\treadonly check: CheckSetEntry;\n\t\t\treadonly expectedBefore: readonly CheckSetEntry[];\n\t\t\treadonly expectedAfter: readonly CheckSetEntry[];\n\t }\n\t| {\n\t\t\treadonly kind: 'expression-mismatch';\n\t\t\treadonly desired: CheckSetEntry;\n\t\t\treadonly current: CheckSetEntry;\n\t\t\treadonly expectedBefore: readonly CheckSetEntry[];\n\t\t\treadonly expectedAfter: readonly CheckSetEntry[];\n\t }\n\t| { readonly kind: 'unsupported' };\n\nconst CHECK_NOT_VALID_SUFFIX =\n\t/^(?<clause>\\s*CHECK\\s*\\(.*\\)(?:\\s+NO\\s+INHERIT)?)\\s+NOT\\s+VALID\\s*$/isu;\nconst CHECK_NO_INHERIT_SUFFIX =\n\t/^\\s*CHECK\\s*\\(.*\\)\\s+NO\\s+INHERIT(?:\\s+NOT\\s+VALID)?\\s*$/isu;\n\nfunction normalizedCheck(check: CheckConstraintIR): CheckSetEntry {\n\treturn {\n\t\tname: check.name,\n\t\texpression: check.expression,\n\t\t...(check.notValid !== undefined ? { notValid: check.notValid } : {}),\n\t};\n}\n\nfunction isNotValid(check: CheckSetEntry): boolean {\n\treturn (\n\t\tcheck.notValid === true ||\n\t\tCHECK_NOT_VALID_SUFFIX.test(check.expression.trim())\n\t);\n}\n\nfunction isNoInherit(check: CheckSetEntry): boolean {\n\treturn CHECK_NO_INHERIT_SUFFIX.test(check.expression.trim());\n}\n\nfunction hasUnsupportedShape(check: CheckSetEntry): boolean {\n\treturn isNotValid(check) || isNoInherit(check);\n}\n\nfunction byName(left: CheckSetEntry, right: CheckSetEntry): number {\n\treturn left.name.localeCompare(right.name);\n}\n\nfunction sortedChecks(\n\tchecks: readonly CheckConstraintIR[] | undefined,\n): readonly CheckSetEntry[] {\n\treturn [...(checks ?? [])].map(normalizedCheck).sort(byName);\n}\n\nfunction hasDuplicateNames(checks: readonly CheckSetEntry[]): boolean {\n\treturn new Set(checks.map((check) => check.name)).size !== checks.length;\n}\n\nfunction checkKeySet(checks: readonly CheckSetEntry[]): ReadonlySet<string> {\n\treturn new Set(checks.map((check) => check.name));\n}\n\n// Shared by the core comparator and adapter add-check rule; keep this as the\n// single table CHECK classifier.\nexport function checkDelta(\n\tdesiredChecks: readonly CheckConstraintIR[] | undefined,\n\tcurrentChecks: readonly CheckConstraintIR[] | undefined,\n): CheckDelta {\n\tconst desired = sortedChecks(desiredChecks);\n\tconst current = sortedChecks(currentChecks);\n\tif (stableJson(desired) === stableJson(current)) {\n\t\treturn { kind: 'none' };\n\t}\n\tif (hasDuplicateNames(desired) || hasDuplicateNames(current)) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tif ([...desired, ...current].some(hasUnsupportedShape)) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\n\tconst desiredNames = checkKeySet(desired);\n\tconst currentNames = checkKeySet(current);\n\tconst added = desired.filter((check) => !currentNames.has(check.name));\n\tconst removed = current.filter((check) => !desiredNames.has(check.name));\n\n\tif (removed.length > 0) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tif (added.length > 1) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\n\tconst mismatches = desired.flatMap((desiredCheck) => {\n\t\tconst currentCheck = current.find(\n\t\t\t(candidate) => candidate.name === desiredCheck.name,\n\t\t);\n\t\treturn currentCheck && stableJson(desiredCheck) !== stableJson(currentCheck)\n\t\t\t? [{ desired: desiredCheck, current: currentCheck }]\n\t\t\t: [];\n\t});\n\tif (mismatches.length > 1) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst mismatch = mismatches[0];\n\tif (mismatch) {\n\t\tif (added.length > 0) {\n\t\t\treturn { kind: 'unsupported' };\n\t\t}\n\t\treturn {\n\t\t\tkind: 'expression-mismatch',\n\t\t\tdesired: mismatch.desired,\n\t\t\tcurrent: mismatch.current,\n\t\t\texpectedBefore: current,\n\t\t\texpectedAfter: desired,\n\t\t};\n\t}\n\n\tconst check = added[0];\n\tif (!check) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\treturn {\n\t\tkind: 'add-check',\n\t\tcheck,\n\t\texpectedBefore: current,\n\t\texpectedAfter: desired,\n\t};\n}\n","import type { EnumIR } from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport type EnumAddDelta =\n\t| { readonly kind: 'none' }\n\t| {\n\t\t\treadonly kind: 'add-label';\n\t\t\treadonly label: string;\n\t\t\treadonly after?: string;\n\t }\n\t| { readonly kind: 'unsupported' };\n\nexport interface EnumAddDeltaOptions {\n\treadonly targetSchema?: string;\n}\n\nexport function resolveEnumSchemaForComparison(\n\tenumDef: EnumIR,\n\ttargetSchema?: string,\n): EnumIR {\n\tif (enumDef.schema !== undefined || targetSchema === undefined) {\n\t\treturn enumDef;\n\t}\n\treturn { ...enumDef, schema: targetSchema };\n}\n\n// Shared by the core comparator and adapter enum-add rules; keep this as the\n// single enum-add classifier.\nexport function enumAddDelta(\n\tdesired: EnumIR,\n\tcurrent: EnumIR,\n\toptions: EnumAddDeltaOptions = {},\n): EnumAddDelta {\n\tconst resolvedDesired = resolveEnumSchemaForComparison(\n\t\tdesired,\n\t\toptions.targetSchema,\n\t);\n\tconst resolvedCurrent = resolveEnumSchemaForComparison(\n\t\tcurrent,\n\t\toptions.targetSchema,\n\t);\n\tif (resolvedDesired.schema !== resolvedCurrent.schema) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tif (\n\t\tstableJson(resolvedDesired.values) === stableJson(resolvedCurrent.values)\n\t) {\n\t\treturn { kind: 'none' };\n\t}\n\tif (new Set(resolvedDesired.values).size !== resolvedDesired.values.length) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tif (new Set(resolvedCurrent.values).size !== resolvedCurrent.values.length) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst desiredValueSet = new Set(resolvedDesired.values);\n\tif (resolvedCurrent.values.some((value) => !desiredValueSet.has(value))) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst currentValueSet = new Set(resolvedCurrent.values);\n\tconst added = resolvedDesired.values.filter(\n\t\t(value) => !currentValueSet.has(value),\n\t);\n\tif (added.length !== 1) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst withoutAdded = resolvedDesired.values.filter(\n\t\t(value) => value !== added[0],\n\t);\n\tif (stableJson(withoutAdded) !== stableJson(resolvedCurrent.values)) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst label = added[0];\n\tif (label === undefined) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst index = resolvedDesired.values.indexOf(label);\n\tif (index <= 0) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\tconst appended = index === resolvedDesired.values.length - 1;\n\tif (appended) {\n\t\treturn { kind: 'add-label', label };\n\t}\n\tconst after = resolvedDesired.values[index - 1];\n\treturn typeof after === 'string'\n\t\t? {\n\t\t\t\tkind: 'add-label',\n\t\t\t\tlabel,\n\t\t\t\tafter,\n\t\t\t}\n\t\t: { kind: 'unsupported' };\n}\n","import type { IndexIR } from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport type IndexSetEntry = {\n\treadonly name: string;\n\treadonly columns: readonly string[];\n\treadonly unique?: boolean;\n\treadonly valid?: boolean;\n\treadonly ready?: boolean;\n\treadonly method?: string;\n\treadonly where?: string;\n\treadonly expressions?: readonly string[];\n\treadonly include?: readonly string[];\n\treadonly opclass?: Readonly<Record<string, string>>;\n\treadonly with?: Readonly<Record<string, string>>;\n\treadonly nullsNotDistinct?: boolean;\n};\n\nexport type IndexDelta =\n\t| { readonly kind: 'none' }\n\t| {\n\t\t\treadonly kind: 'add-unique-index';\n\t\t\treadonly index: IndexSetEntry;\n\t\t\treadonly expectedBefore: readonly IndexSetEntry[];\n\t\t\treadonly expectedAfter: readonly IndexSetEntry[];\n\t }\n\t| { readonly kind: 'unsupported' };\n\nexport function defaultIndexName(\n\ttableName: string,\n\tindex: Pick<IndexIR, 'name' | 'columns'>,\n): string {\n\treturn index.name ?? `idx_${tableName}_${index.columns.join('_')}`;\n}\n\nfunction nonEmptyArray<T>(\n\tvalue: readonly T[] | undefined,\n): value is readonly T[] {\n\treturn value !== undefined && value.length > 0;\n}\n\nfunction nonEmptyRecord(\n\tvalue: Readonly<Record<string, string>> | undefined,\n): value is Readonly<Record<string, string>> {\n\treturn value !== undefined && Object.keys(value).length > 0;\n}\n\nfunction normalizedMethod(index: IndexIR): string | undefined {\n\treturn index.method && index.method !== 'btree' ? index.method : undefined;\n}\n\ntype IndexPerspective = 'desired' | 'current';\n\nfunction normalizedCatalogFlag(\n\tvalue: boolean | undefined,\n\tperspective: IndexPerspective,\n): boolean | undefined {\n\tif (perspective === 'desired') {\n\t\treturn value === false ? false : undefined;\n\t}\n\treturn value === true ? undefined : false;\n}\n\nexport function normalizedIndex(\n\ttableName: string,\n\tindex: IndexIR,\n\tperspective: IndexPerspective = 'desired',\n): IndexSetEntry {\n\tconst method = normalizedMethod(index);\n\treturn {\n\t\tname: defaultIndexName(tableName, index),\n\t\tcolumns: [...index.columns],\n\t\t...(index.unique ? { unique: true } : {}),\n\t\t...(normalizedCatalogFlag(index.valid, perspective) === false\n\t\t\t? { valid: false }\n\t\t\t: {}),\n\t\t...(normalizedCatalogFlag(index.ready, perspective) === false\n\t\t\t? { ready: false }\n\t\t\t: {}),\n\t\t...(method ? { method } : {}),\n\t\t...(index.where ? { where: index.where } : {}),\n\t\t...(nonEmptyArray(index.expressions)\n\t\t\t? { expressions: [...index.expressions] }\n\t\t\t: {}),\n\t\t...(nonEmptyArray(index.include) ? { include: [...index.include] } : {}),\n\t\t...(nonEmptyRecord(index.opclass) ? { opclass: index.opclass } : {}),\n\t\t...(nonEmptyRecord(index.with) ? { with: index.with } : {}),\n\t\t...(index.nullsNotDistinct ? { nullsNotDistinct: true } : {}),\n\t};\n}\n\nfunction byName(left: IndexSetEntry, right: IndexSetEntry): number {\n\treturn left.name.localeCompare(right.name);\n}\n\nfunction sortedIndexes(\n\ttableName: string,\n\tindexes: readonly IndexIR[],\n\tperspective: IndexPerspective,\n): readonly IndexSetEntry[] {\n\treturn [...indexes]\n\t\t.map((index) => normalizedIndex(tableName, index, perspective))\n\t\t.sort(byName);\n}\n\nfunction hasDuplicateNames(indexes: readonly IndexSetEntry[]): boolean {\n\treturn new Set(indexes.map((index) => index.name)).size !== indexes.length;\n}\n\nfunction indexKeySet(indexes: readonly IndexSetEntry[]): ReadonlySet<string> {\n\treturn new Set(indexes.map((index) => index.name));\n}\n\nfunction hasOnlyPlainColumns(index: IndexSetEntry): boolean {\n\treturn (\n\t\tindex.columns.length > 0 &&\n\t\tindex.columns.every(\n\t\t\t(column) => typeof column === 'string' && column.length > 0,\n\t\t)\n\t);\n}\n\nfunction hasUnsupportedShape(index: IndexSetEntry): boolean {\n\treturn (\n\t\tindex.unique !== true ||\n\t\tindex.valid === false ||\n\t\tindex.ready === false ||\n\t\tindex.method !== undefined ||\n\t\tindex.where !== undefined ||\n\t\tnonEmptyArray(index.expressions) ||\n\t\tnonEmptyArray(index.include) ||\n\t\tnonEmptyRecord(index.opclass) ||\n\t\tnonEmptyRecord(index.with) ||\n\t\tindex.nullsNotDistinct === true ||\n\t\t!hasOnlyPlainColumns(index)\n\t);\n}\n\nfunction structurallyEquivalentUniqueIndex(\n\tleft: IndexSetEntry,\n\tright: IndexSetEntry,\n): boolean {\n\tif (hasUnsupportedShape(left) || hasUnsupportedShape(right)) {\n\t\treturn false;\n\t}\n\treturn stableJson(left.columns) === stableJson(right.columns);\n}\n\nfunction existingValidEquivalent(\n\tadded: IndexSetEntry,\n\tcurrent: readonly IndexSetEntry[],\n): boolean {\n\treturn current.some(\n\t\t(candidate) =>\n\t\t\tcandidate.name !== added.name &&\n\t\t\tcandidate.valid !== false &&\n\t\t\tcandidate.ready !== false &&\n\t\t\tstructurallyEquivalentUniqueIndex(candidate, added),\n\t);\n}\n\n// Shared by the core comparator and adapter PostgreSQL CIC rule. This is the\n// intentionally narrow first slice: exactly one plain UNIQUE btree index add.\nexport function indexDelta(\n\ttableName: string,\n\tdesiredIndexes: readonly IndexIR[],\n\tcurrentIndexes: readonly IndexIR[],\n): IndexDelta {\n\tconst desired = sortedIndexes(tableName, desiredIndexes, 'desired');\n\tconst current = sortedIndexes(tableName, currentIndexes, 'current');\n\tif (stableJson(desired) === stableJson(current)) {\n\t\treturn { kind: 'none' };\n\t}\n\tif (hasDuplicateNames(desired) || hasDuplicateNames(current)) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\n\tconst desiredNames = indexKeySet(desired);\n\tconst currentNames = indexKeySet(current);\n\tconst added = desired.filter((index) => !currentNames.has(index.name));\n\tconst removed = current.filter((index) => !desiredNames.has(index.name));\n\tif (removed.length > 0 || added.length !== 1) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\n\tconst mismatches = desired.filter((desiredIndex) => {\n\t\tconst currentIndex = current.find(\n\t\t\t(candidate) => candidate.name === desiredIndex.name,\n\t\t);\n\t\treturn (\n\t\t\tcurrentIndex && stableJson(currentIndex) !== stableJson(desiredIndex)\n\t\t);\n\t});\n\tif (mismatches.length > 0) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\n\tconst index = added[0];\n\tif (\n\t\t!index ||\n\t\thasUnsupportedShape(index) ||\n\t\texistingValidEquivalent(index, current)\n\t) {\n\t\treturn { kind: 'unsupported' };\n\t}\n\treturn {\n\t\tkind: 'add-unique-index',\n\t\tindex,\n\t\texpectedBefore: current,\n\t\texpectedAfter: desired,\n\t};\n}\n","import type {\n\tCheckConstraintIR,\n\tColumnIR,\n\tComparator,\n\tCompareOutcome,\n\tEnumIR,\n\tEquivalenceContext,\n\tForeignKeyIR,\n\tIndexIR,\n\tLogicalIdentity,\n\tModelIR,\n\tObservationRequest,\n\tProofObligation,\n\tProposition,\n\tRecognitionResult,\n\tRelationIR,\n\tResourceAddress,\n\tRuleRef,\n\tSemanticArtifactRef,\n\tSequenceIR,\n\tTableIR,\n\tTransitionCandidate,\n\tTransitionRule,\n\tUnknownTransitionRecognition,\n} from '@dbsp/types';\nimport { checkDelta } from './check-delta.js';\nimport { enumAddDelta } from './enum-delta.js';\nimport { assertDeclaredEnumMapIdentity } from './enum-name.js';\nimport { semanticArtifactId } from './ids.js';\nimport {\n\tdefaultIndexName,\n\tindexDelta,\n\tnormalizedIndex,\n} from './index-delta.js';\nimport type { PackRegistry } from './registry.js';\nimport { stableJson } from './stable-json.js';\n\nconst COMPARATOR_ARTIFACT: SemanticArtifactRef = {\n\tid: semanticArtifactId('dbsp.core.transition.comparator'),\n\tversion: '0.1.0',\n};\n\nconst TRANSITION_COMPARE_CURRENT_MODEL = Symbol.for(\n\t'dbsp.core.transition.compare.current-model',\n);\n\ntype CompareOutcomeWithCurrentModel = CompareOutcome & {\n\treadonly [TRANSITION_COMPARE_CURRENT_MODEL]?: ModelIR;\n};\n\nexport function transitionCompareCurrentModel(\n\tcompare: CompareOutcome,\n): ModelIR | undefined {\n\treturn (compare as CompareOutcomeWithCurrentModel)[\n\t\tTRANSITION_COMPARE_CURRENT_MODEL\n\t];\n}\n\nexport function withTransitionCompareCurrentModel<T extends CompareOutcome>(\n\tcompare: T,\n\tcurrent: ModelIR,\n): T {\n\tObject.defineProperty(compare, TRANSITION_COMPARE_CURRENT_MODEL, {\n\t\tvalue: current,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t\twritable: false,\n\t});\n\treturn compare;\n}\n\nfunction columnChanged(\n\tdesired: ColumnIR | undefined,\n\tcurrent: ColumnIR | undefined,\n): boolean {\n\tif (!desired || !current) {\n\t\treturn true;\n\t}\n\treturn (\n\t\tstableJson(columnForComparison(desired, desired)) !==\n\t\tstableJson(columnForComparison(current, desired))\n\t);\n}\n\ntype ColumnFieldName = string;\n\ntype NormalizeIdentifier = (identifier: string) => string;\n\ntype NormalizationConflict =\n\t| { readonly kind: 'table'; readonly table: string }\n\t| {\n\t\t\treadonly kind: 'column';\n\t\t\treadonly table: string;\n\t\t\treadonly column: string;\n\t }\n\t| {\n\t\t\treadonly kind: 'check';\n\t\t\treadonly table: string;\n\t\t\treadonly check: string;\n\t }\n\t| {\n\t\t\treadonly kind: 'relation';\n\t\t\treadonly source: string;\n\t\t\treadonly relation: string;\n\t }\n\t| { readonly kind: 'enum'; readonly enum: string }\n\t| { readonly kind: 'sequence'; readonly sequence: string };\n\ntype ManagedCollectionPolicy =\n\t| { readonly managed: false }\n\t| {\n\t\t\treadonly managed: true;\n\t\t\t/**\n\t\t\t * Undefined keys means an explicit empty desired collection: manage the\n\t\t\t * whole current collection and assert it is empty.\n\t\t\t */\n\t\t\treadonly keys?: ReadonlySet<string>;\n\t };\n\ntype ManagedModelCollections = {\n\treadonly extensions: ManagedCollectionPolicy;\n\treadonly sequences: ManagedCollectionPolicy;\n\treadonly enums: ManagedCollectionPolicy;\n\treadonly relations: ManagedCollectionPolicy;\n};\n\ntype ModelLevelCollectionsComparison = {\n\treadonly relations: unknown;\n\treadonly enums: unknown;\n\treadonly extensions: readonly string[];\n\treadonly sequences: unknown;\n};\n\nfunction normalizeColumnList(\n\tcolumns: readonly string[],\n\tnormalize: NormalizeIdentifier,\n): readonly string[] {\n\treturn columns.map((column) => normalize(column));\n}\n\nfunction normalizeColumnRef(\n\tref: string | readonly string[] | undefined,\n\tnormalize: NormalizeIdentifier,\n): string | readonly string[] | undefined {\n\tif (Array.isArray(ref)) {\n\t\treturn normalizeColumnList(ref, normalize);\n\t}\n\treturn typeof ref === 'string' ? normalize(ref) : ref;\n}\n\nfunction normalizeDefinedColumnRef(\n\tref: string | readonly string[],\n\tnormalize: NormalizeIdentifier,\n): string | readonly string[] {\n\treturn typeof ref === 'string'\n\t\t? normalize(ref)\n\t\t: normalizeColumnList(ref, normalize);\n}\n\nfunction normalizeForeignKey(\n\tforeignKey: ForeignKeyIR,\n\tnormalize: NormalizeIdentifier,\n): ForeignKeyIR {\n\treturn {\n\t\t...foreignKey,\n\t\tcolumns: normalizeColumnList(foreignKey.columns, normalize),\n\t\treferences: {\n\t\t\t...foreignKey.references,\n\t\t\ttable: normalize(foreignKey.references.table),\n\t\t\tcolumns: normalizeColumnList(foreignKey.references.columns, normalize),\n\t\t},\n\t};\n}\n\nfunction normalizeIndex(\n\tindex: IndexIR,\n\tnormalize: NormalizeIdentifier,\n): IndexIR {\n\treturn {\n\t\t...index,\n\t\tcolumns: normalizeColumnList(index.columns, normalize),\n\t\t...(index.include\n\t\t\t? { include: normalizeColumnList(index.include, normalize) }\n\t\t\t: {}),\n\t\t...(index.opclass\n\t\t\t? {\n\t\t\t\t\topclass: Object.fromEntries(\n\t\t\t\t\t\tObject.entries(index.opclass).map(([column, value]) => [\n\t\t\t\t\t\t\tnormalize(column),\n\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t]),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nfunction normalizeRelation(\n\trelation: RelationIR,\n\tnormalize: NormalizeIdentifier,\n): RelationIR {\n\tconst { foreignKey, otherKey, sourceKey, targetKey, through, ...rest } =\n\t\trelation;\n\treturn {\n\t\t...rest,\n\t\tname: normalize(relation.name),\n\t\tsource: normalize(relation.source),\n\t\ttarget: normalize(relation.target),\n\t\t...(through !== undefined\n\t\t\t? { through: typeof through === 'string' ? normalize(through) : through }\n\t\t\t: {}),\n\t\t...(foreignKey !== undefined\n\t\t\t? { foreignKey: normalizeColumnRef(foreignKey, normalize) }\n\t\t\t: {}),\n\t\t...(otherKey !== undefined\n\t\t\t? {\n\t\t\t\t\totherKey:\n\t\t\t\t\t\ttypeof otherKey === 'string' ? normalize(otherKey) : otherKey,\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(sourceKey !== undefined\n\t\t\t? { sourceKey: normalizeColumnRef(sourceKey, normalize) }\n\t\t\t: {}),\n\t\t...(targetKey !== undefined\n\t\t\t? { targetKey: normalizeColumnRef(targetKey, normalize) }\n\t\t\t: {}),\n\t};\n}\n\nfunction normalizeTable(\n\ttable: TableIR,\n\tnormalize: NormalizeIdentifier,\n): {\n\treadonly table: TableIR;\n\treadonly conflicts: readonly NormalizationConflict[];\n} {\n\tconst tableName = normalize(table.name);\n\tconst conflicts: NormalizationConflict[] = [];\n\tconst seenColumns = new Set<string>();\n\tconst columns = table.columns.map((column) => {\n\t\tconst name = normalize(column.name);\n\t\tif (seenColumns.has(name)) {\n\t\t\tconflicts.push({ kind: 'column', table: tableName, column: name });\n\t\t}\n\t\tseenColumns.add(name);\n\t\treturn { ...column, name };\n\t});\n\tconst seenChecks = new Set<string>();\n\tconst checkConstraints = table.checkConstraints?.map((check) => {\n\t\tconst name = normalize(check.name);\n\t\tif (seenChecks.has(name)) {\n\t\t\tconflicts.push({ kind: 'check', table: tableName, check: name });\n\t\t}\n\t\tseenChecks.add(name);\n\t\treturn { ...check, name };\n\t});\n\treturn {\n\t\ttable: {\n\t\t\t...table,\n\t\t\tname: tableName,\n\t\t\tcolumns,\n\t\t\t...(checkConstraints !== undefined ? { checkConstraints } : {}),\n\t\t\t...(table.primaryKey !== undefined\n\t\t\t\t? { primaryKey: normalizeDefinedColumnRef(table.primaryKey, normalize) }\n\t\t\t\t: {}),\n\t\t\tforeignKeys: table.foreignKeys.map((foreignKey) =>\n\t\t\t\tnormalizeForeignKey(foreignKey, normalize),\n\t\t\t),\n\t\t\tindexes: table.indexes.map((index) => normalizeIndex(index, normalize)),\n\t\t\t...(table.pseudoColumns\n\t\t\t\t? {\n\t\t\t\t\t\tpseudoColumns: table.pseudoColumns.map((pseudoColumn) => ({\n\t\t\t\t\t\t\t...pseudoColumn,\n\t\t\t\t\t\t\ttable: normalize(pseudoColumn.table),\n\t\t\t\t\t\t\tforeignKeyColumn: normalize(pseudoColumn.foreignKeyColumn),\n\t\t\t\t\t\t\ttargetColumn: normalize(pseudoColumn.targetColumn),\n\t\t\t\t\t\t})),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(table.partition\n\t\t\t\t? {\n\t\t\t\t\t\tpartition: {\n\t\t\t\t\t\t\t...table.partition,\n\t\t\t\t\t\t\tcolumns: normalizeColumnList(table.partition.columns, normalize),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t},\n\t\tconflicts,\n\t};\n}\n\nfunction checkForComparison(check: CheckConstraintIR): CheckConstraintIR {\n\tconst { requiresEnumLabels: _requiresEnumLabels, ...physicalCheck } = check;\n\treturn physicalCheck;\n}\n\nfunction checksForComparison(\n\tchecks: readonly CheckConstraintIR[] | undefined,\n): readonly CheckConstraintIR[] | undefined {\n\treturn checks?.map(checkForComparison);\n}\n\nfunction logicalIdentityForComparison(identity: LogicalIdentity | undefined):\n\t| {\n\t\t\treadonly id: string;\n\t\t\treadonly carrier:\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: string;\n\t\t\t\t\t\treadonly authenticated: false;\n\t\t\t\t }\n\t\t\t\t| undefined;\n\t }\n\t| undefined {\n\tif (identity === undefined) {\n\t\treturn undefined;\n\t}\n\t// A malformed identity that reached comparison without a carrier (e.g. a\n\t// spoofed/legacy db-side shape that bypassed validation) must NOT crash the\n\t// comparator. Reflect the missing carrier as `undefined` so it compares as a\n\t// real difference against a well-formed carrier (fail closed → surfaces as\n\t// drift), never silently equal.\n\treturn {\n\t\tid: identity.id,\n\t\tcarrier: identity.carrier\n\t\t\t? {\n\t\t\t\t\tkind: identity.carrier.kind,\n\t\t\t\t\tauthenticated: identity.carrier.authenticated,\n\t\t\t\t}\n\t\t\t: undefined,\n\t};\n}\n\nfunction columnForComparison(\n\tcolumn: ColumnIR,\n\tdesiredIntent: ColumnIR = column,\n): unknown {\n\tconst {\n\t\tjs: _js,\n\t\tlogicalIdentity: _logicalIdentity,\n\t\tuniqueConstraintName: _uniqueConstraintName,\n\t\t...rest\n\t} = column;\n\tconst logicalIdentity = logicalIdentityForComparison(column.logicalIdentity);\n\tconst base = logicalIdentity ? { ...rest, logicalIdentity } : rest;\n\treturn Object.hasOwn(desiredIntent, 'uniqueConstraintName')\n\t\t? { ...base, uniqueConstraintName: column.uniqueConstraintName }\n\t\t: base;\n}\n\nfunction logicalIdentityChanged(\n\tdesired: { readonly logicalIdentity?: LogicalIdentity } | undefined,\n\tcurrent: { readonly logicalIdentity?: LogicalIdentity } | undefined,\n): boolean {\n\tif (!desired || !current) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tstableJson(logicalIdentityForComparison(desired.logicalIdentity)) !==\n\t\tstableJson(logicalIdentityForComparison(current.logicalIdentity))\n\t);\n}\n\nfunction normalizeNamedMap<T extends { readonly name: string }>(\n\titems: ReadonlyMap<string, T> | undefined,\n\tnormalize: NormalizeIdentifier,\n\tkind: 'enum' | 'sequence',\n): {\n\treadonly items: ReadonlyMap<string, T> | undefined;\n\treadonly conflicts: readonly NormalizationConflict[];\n} {\n\tif (!items) {\n\t\treturn { items: undefined, conflicts: [] };\n\t}\n\tconst normalizedItems = new Map<string, T>();\n\tconst conflicts: NormalizationConflict[] = [];\n\tfor (const item of items.values()) {\n\t\tconst normalized = { ...item, name: normalize(item.name) };\n\t\tif (normalizedItems.has(normalized.name)) {\n\t\t\tconflicts.push(\n\t\t\t\tkind === 'enum'\n\t\t\t\t\t? { kind: 'enum', enum: normalized.name }\n\t\t\t\t\t: { kind: 'sequence', sequence: normalized.name },\n\t\t\t);\n\t\t}\n\t\tnormalizedItems.set(normalized.name, normalized);\n\t}\n\treturn { items: normalizedItems, conflicts };\n}\n\nfunction normalizeCurrentModelForComparison(\n\tmodel: ModelIR,\n\tnormalize: NormalizeIdentifier,\n): {\n\treadonly model: ModelIR;\n\treadonly conflicts: readonly NormalizationConflict[];\n} {\n\tconst conflicts: NormalizationConflict[] = [];\n\tconst tables = new Map<string, TableIR>();\n\tfor (const table of model.tables.values()) {\n\t\tconst normalized = normalizeTable(table, normalize);\n\t\tif (tables.has(normalized.table.name)) {\n\t\t\tconflicts.push({ kind: 'table', table: normalized.table.name });\n\t\t}\n\t\ttables.set(normalized.table.name, normalized.table);\n\t\tconflicts.push(...normalized.conflicts);\n\t}\n\tconst relations = new Map<string, RelationIR>();\n\tfor (const relation of model.relations.values()) {\n\t\tconst normalized = normalizeRelation(relation, normalize);\n\t\tconst key = `${normalized.source}.${normalized.name}`;\n\t\tif (relations.has(key)) {\n\t\t\tconflicts.push({\n\t\t\t\tkind: 'relation',\n\t\t\t\tsource: normalized.source,\n\t\t\t\trelation: normalized.name,\n\t\t\t});\n\t\t}\n\t\trelations.set(key, normalized);\n\t}\n\tconst externalTables = model.externalTables\n\t\t? new Set([...model.externalTables].map((table) => normalize(table)))\n\t\t: undefined;\n\tconst enums = normalizeNamedMap<EnumIR>(model.enums, (name) => name, 'enum');\n\tconst sequences = normalizeNamedMap<SequenceIR>(\n\t\tmodel.sequences,\n\t\tnormalize,\n\t\t'sequence',\n\t);\n\tconflicts.push(...enums.conflicts, ...sequences.conflicts);\n\treturn {\n\t\tmodel: {\n\t\t\t...model,\n\t\t\ttables,\n\t\t\t...(externalTables ? { externalTables } : {}),\n\t\t\trelations,\n\t\t\t...(enums.items ? { enums: enums.items } : {}),\n\t\t\t...(sequences.items ? { sequences: sequences.items } : {}),\n\t\t\tgetTable: (name: string) => tables.get(name),\n\t\t\tgetRelation: (qualifiedName: string) => relations.get(qualifiedName),\n\t\t\tgetRelationsFrom: (sourceTable: string) =>\n\t\t\t\t[...relations.values()].filter(\n\t\t\t\t\t(relation) => relation.source === sourceTable,\n\t\t\t\t),\n\t\t\tgetRelationsTo: (targetTable: string) =>\n\t\t\t\t[...relations.values()].filter(\n\t\t\t\t\t(relation) => relation.target === targetTable,\n\t\t\t\t),\n\t\t\tisAmbiguous: (sourceTable: string, targetTable: string) => {\n\t\t\t\tconst matches = [...relations.values()].filter(\n\t\t\t\t\t(relation) =>\n\t\t\t\t\t\trelation.source === sourceTable && relation.target === targetTable,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tambiguous: matches.length > 1,\n\t\t\t\t\toptions: matches.map((relation) => relation.name),\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t\tconflicts,\n\t};\n}\n\nfunction tableForComparison(\n\ttable: TableIR,\n\tperspective: 'desired' | 'current' = 'desired',\n\tdesiredIntentTable: TableIR = table,\n): unknown {\n\tconst logicalIdentity = logicalIdentityForComparison(table.logicalIdentity);\n\treturn {\n\t\tname: table.name,\n\t\t...(logicalIdentity ? { logicalIdentity } : {}),\n\t\tcolumns: table.columns.map((column) =>\n\t\t\tcolumnForComparison(\n\t\t\t\tcolumn,\n\t\t\t\tdesiredIntentTable.columns.find(\n\t\t\t\t\t(desiredColumn) => desiredColumn.name === column.name,\n\t\t\t\t) ?? column,\n\t\t\t),\n\t\t),\n\t\tprimaryKey: table.primaryKey,\n\t\tforeignKeys: table.foreignKeys,\n\t\tindexes: table.indexes.map((index) =>\n\t\t\tnormalizedIndex(table.name, index, perspective),\n\t\t),\n\t\tcheckConstraints: checksForComparison(table.checkConstraints),\n\t\tpseudoColumns: table.pseudoColumns,\n\t\tcomment: table.comment,\n\t\tpartition: table.partition,\n\t\trlsEnabled: table.rlsEnabled,\n\t\tpolicies: table.policies,\n\t};\n}\n\nfunction externalTableNames(\n\tdesired: ModelIR,\n\tcurrent: ModelIR,\n): ReadonlySet<string> {\n\tconst desiredManagedTables = new Set(desired.tables.keys());\n\treturn new Set(\n\t\t[\n\t\t\t...(desired.externalTables ?? []),\n\t\t\t...(current.externalTables ?? []),\n\t\t].filter((table) => !desiredManagedTables.has(table)),\n\t);\n}\n\nfunction relationTouchesExternalTable(\n\trelation: RelationIR,\n\texternalTables: ReadonlySet<string>,\n): boolean {\n\treturn (\n\t\texternalTables.has(relation.source) ||\n\t\texternalTables.has(relation.target) ||\n\t\t(typeof relation.through === 'string' &&\n\t\t\texternalTables.has(relation.through))\n\t);\n}\n\nfunction managedRelationsForComparison(\n\trelations: ReadonlyMap<string, RelationIR> | undefined,\n\texternalTables: ReadonlySet<string>,\n): ReadonlyMap<string, RelationIR> {\n\treturn new Map(\n\t\t[...(relations ?? new Map<string, RelationIR>()).entries()].filter(\n\t\t\t([, relation]) => !relationTouchesExternalTable(relation, externalTables),\n\t\t),\n\t);\n}\n\nfunction modelRelations(\n\tmodel: ModelIR,\n): ReadonlyMap<string, RelationIR> | undefined {\n\treturn (model as { readonly relations?: ReadonlyMap<string, RelationIR> })\n\t\t.relations;\n}\n\nfunction managedMapPolicy<T>(\n\titems: ReadonlyMap<string, T> | undefined,\n): ManagedCollectionPolicy {\n\tif (items === undefined) {\n\t\treturn { managed: false };\n\t}\n\tif (items.size === 0) {\n\t\treturn { managed: true };\n\t}\n\treturn { managed: true, keys: new Set(items.keys()) };\n}\n\nfunction managedListPolicy(\n\titems: readonly string[] | undefined,\n): ManagedCollectionPolicy {\n\tif (items === undefined) {\n\t\treturn { managed: false };\n\t}\n\tif (items.length === 0) {\n\t\treturn { managed: true };\n\t}\n\treturn { managed: true, keys: new Set(items) };\n}\n\nfunction managedRelationPolicy(\n\trelations: ReadonlyMap<string, RelationIR> | undefined,\n\texternalTables: ReadonlySet<string>,\n): ManagedCollectionPolicy {\n\tif (relations === undefined) {\n\t\treturn { managed: false };\n\t}\n\tif (relations.size === 0) {\n\t\treturn { managed: true };\n\t}\n\treturn {\n\t\tmanaged: true,\n\t\tkeys: new Set(\n\t\t\tmanagedRelationsForComparison(relations, externalTables).keys(),\n\t\t),\n\t};\n}\n\nfunction managedModelCollections(\n\tdesired: ModelIR,\n\texternalTables: ReadonlySet<string>,\n): ManagedModelCollections {\n\treturn {\n\t\textensions: managedListPolicy(desired.extensions),\n\t\tsequences: managedMapPolicy(desired.sequences),\n\t\tenums: managedMapPolicy(desired.enums),\n\t\trelations: managedRelationPolicy(modelRelations(desired), externalTables),\n\t};\n}\n\nfunction isManagedCollectionKey(\n\tpolicy: ManagedCollectionPolicy,\n\tkey: string,\n): boolean {\n\treturn policy.managed && (policy.keys === undefined || policy.keys.has(key));\n}\n\nfunction projectManagedMapEntries<T>(\n\titems: ReadonlyMap<string, T> | undefined,\n\tpolicy: ManagedCollectionPolicy,\n\tvalueForEntry: (name: string, value: T) => T = (_name, value) => value,\n): readonly (readonly [string, T])[] {\n\tif (!policy.managed) {\n\t\treturn [];\n\t}\n\treturn [...(items ?? new Map<string, T>()).entries()]\n\t\t.filter(([name]) => isManagedCollectionKey(policy, name))\n\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t.map(([name, value]) => [name, valueForEntry(name, value)] as const);\n}\n\nfunction extensionNamesForComparison(\n\textensions: readonly string[] | undefined,\n\tpolicy: ManagedCollectionPolicy,\n): readonly string[] {\n\tif (!policy.managed) {\n\t\treturn [];\n\t}\n\treturn [...new Set(extensions ?? [])]\n\t\t.filter((extension) => isManagedCollectionKey(policy, extension))\n\t\t.sort((left, right) => left.localeCompare(right));\n}\n\nfunction modelLevelCollectionsForComparison(\n\tmodel: ModelIR,\n\texternalTables: ReadonlySet<string>,\n\tmanagedCollections: ManagedModelCollections,\n\toptions: {\n\t\treadonly enumValueForComparison?: (name: string, enumDef: EnumIR) => EnumIR;\n\t} = {},\n): ModelLevelCollectionsComparison {\n\treturn {\n\t\trelations: projectManagedMapEntries(\n\t\t\tmanagedRelationsForComparison(modelRelations(model), externalTables),\n\t\t\tmanagedCollections.relations,\n\t\t),\n\t\tenums: projectManagedMapEntries(\n\t\t\tmodel.enums,\n\t\t\tmanagedCollections.enums,\n\t\t\toptions.enumValueForComparison,\n\t\t),\n\t\textensions: extensionNamesForComparison(\n\t\t\tmodel.extensions,\n\t\t\tmanagedCollections.extensions,\n\t\t),\n\t\tsequences: projectManagedMapEntries(\n\t\t\tmodel.sequences,\n\t\t\tmanagedCollections.sequences,\n\t\t\t(_name, sequence) => {\n\t\t\t\tconst { adopt: _adopt, ...shape } = sequence;\n\t\t\t\treturn shape;\n\t\t\t},\n\t\t),\n\t};\n}\n\nfunction modelForComparison(\n\tmodel: ModelIR,\n\texternalTables: ReadonlySet<string>,\n\tmanagedCollections: ManagedModelCollections,\n\tperspective: 'desired' | 'current' = 'desired',\n\tdesiredIntent: ModelIR = model,\n): unknown {\n\treturn {\n\t\ttables: [...model.tables.entries()]\n\t\t\t.filter(([name]) => !externalTables.has(name))\n\t\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t\t.map(([name, table]) => [\n\t\t\t\tname,\n\t\t\t\ttableForComparison(\n\t\t\t\t\ttable,\n\t\t\t\t\tperspective,\n\t\t\t\t\tdesiredIntent.getTable(name) ?? table,\n\t\t\t\t),\n\t\t\t]),\n\t\t...modelLevelCollectionsForComparison(\n\t\t\tmodel,\n\t\t\texternalTables,\n\t\t\tmanagedCollections,\n\t\t),\n\t};\n}\n\nfunction columnWithRevertedFields(\n\tdesired: ColumnIR,\n\tcurrent: ColumnIR,\n\tfields: ReadonlySet<ColumnFieldName>,\n): ColumnIR {\n\tconst reverted: Record<string, unknown> = { ...desired };\n\tconst currentRecord = current as unknown as Record<string, unknown>;\n\tfor (const field of fields) {\n\t\tif (Object.hasOwn(current, field)) {\n\t\t\treverted[field] = currentRecord[field];\n\t\t} else {\n\t\t\tdelete reverted[field];\n\t\t}\n\t}\n\treturn reverted as unknown as ColumnIR;\n}\n\nfunction columnChangeKey(table: string, column: string): string {\n\treturn JSON.stringify([table, column]);\n}\n\nfunction declaredColumnFieldsFor(\n\trule: TransitionRule,\n): readonly ColumnFieldName[] {\n\treturn rule.consumesColumnFields ?? [];\n}\n\nfunction addColumnFieldCoverage(\n\tcoverage: Map<string, Set<ColumnFieldName>>,\n\tkey: string,\n\tfields: readonly ColumnFieldName[],\n): void {\n\tif (fields.length === 0) {\n\t\treturn;\n\t}\n\tconst existing = coverage.get(key) ?? new Set<ColumnFieldName>();\n\tfor (const field of fields) {\n\t\texisting.add(field);\n\t}\n\tcoverage.set(key, existing);\n}\n\nfunction mergeColumnFieldCoverage(\n\t...maps: readonly ReadonlyMap<string, ReadonlySet<ColumnFieldName>>[]\n): ReadonlyMap<string, ReadonlySet<ColumnFieldName>> {\n\tconst merged = new Map<string, Set<ColumnFieldName>>();\n\tfor (const map of maps) {\n\t\tfor (const [key, fields] of map) {\n\t\t\taddColumnFieldCoverage(merged, key, [...fields]);\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction recognizedColumnFieldsAreDisjoint(\n\trecognized: readonly RecognizedRuleEntry[],\n): boolean {\n\tif (recognized.length < 2) {\n\t\treturn false;\n\t}\n\tconst claimed = new Set<ColumnFieldName>();\n\tfor (const entry of recognized) {\n\t\tconst fields = declaredColumnFieldsFor(entry.rule);\n\t\tif (fields.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (const field of fields) {\n\t\t\tif (claimed.has(field)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tclaimed.add(field);\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction revertRecognizedColumnChanges(\n\tdesired: ModelIR,\n\tcurrent: ModelIR,\n\trecognizedColumnFields: ReadonlyMap<string, ReadonlySet<ColumnFieldName>>,\n\texternalTables: ReadonlySet<string>,\n\tmanagedCollections: ManagedModelCollections,\n\trecognizedTableKeys: ReadonlySet<string> = new Set(),\n\trecognizedEnumKeys: ReadonlySet<string> = new Set(),\n\trecognizedCheckKeys: ReadonlySet<string> = new Set(),\n\trecognizedCheckReplacements: ReadonlyMap<\n\t\tstring,\n\t\tCheckConstraintIR\n\t> = new Map(),\n\trecognizedIndexKeys: ReadonlySet<string> = new Set(),\n): unknown {\n\treturn {\n\t\ttables: [...desired.tables.entries()]\n\t\t\t.filter(([name]) => !externalTables.has(name))\n\t\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t\t.map(([name, table]) => {\n\t\t\t\tconst currentTable = current.getTable(name);\n\t\t\t\tconst tableWithRevertedIdentity =\n\t\t\t\t\trecognizedTableKeys.has(name) && currentTable\n\t\t\t\t\t\t? tableWithLogicalIdentity(table, currentTable.logicalIdentity)\n\t\t\t\t\t\t: table;\n\t\t\t\tconst revertedChecks = revertRecognizedCheckChanges(\n\t\t\t\t\tname,\n\t\t\t\t\ttableWithRevertedIdentity.checkConstraints,\n\t\t\t\t\tcurrentTable?.checkConstraints,\n\t\t\t\t\trecognizedCheckKeys,\n\t\t\t\t\trecognizedCheckReplacements,\n\t\t\t\t);\n\t\t\t\tconst revertedIndexes = revertRecognizedIndexChanges(\n\t\t\t\t\tname,\n\t\t\t\t\ttableWithRevertedIdentity.indexes,\n\t\t\t\t\tcurrentTable?.indexes,\n\t\t\t\t\trecognizedIndexKeys,\n\t\t\t\t);\n\t\t\t\tconst tableWithRevertedColumns = {\n\t\t\t\t\t...tableWithRevertedIdentity,\n\t\t\t\t\tcolumns: tableWithRevertedIdentity.columns.map((column) => {\n\t\t\t\t\t\tconst key = JSON.stringify([name, column.name]);\n\t\t\t\t\t\tconst currentColumn = currentTable?.columns.find(\n\t\t\t\t\t\t\t(candidate) => candidate.name === column.name,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst fields = recognizedColumnFields.get(key);\n\t\t\t\t\t\treturn fields && currentColumn\n\t\t\t\t\t\t\t? columnWithRevertedFields(column, currentColumn, fields)\n\t\t\t\t\t\t\t: column;\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t\tconst tableWithRevertedChecks =\n\t\t\t\t\trevertedChecks === undefined\n\t\t\t\t\t\t? (({ checkConstraints: _checkConstraints, ...rest }: TableIR) =>\n\t\t\t\t\t\t\t\trest)(tableWithRevertedColumns)\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...tableWithRevertedColumns,\n\t\t\t\t\t\t\t\tcheckConstraints: revertedChecks,\n\t\t\t\t\t\t\t};\n\t\t\t\treturn [\n\t\t\t\t\tname,\n\t\t\t\t\ttableForComparison({\n\t\t\t\t\t\t...tableWithRevertedChecks,\n\t\t\t\t\t\tindexes: revertedIndexes,\n\t\t\t\t\t}),\n\t\t\t\t];\n\t\t\t}),\n\t\t...modelLevelCollectionsForComparison(\n\t\t\tdesired,\n\t\t\texternalTables,\n\t\t\tmanagedCollections,\n\t\t\t{\n\t\t\t\tenumValueForComparison: (name, enumDef) => {\n\t\t\t\t\tconst currentEnum = current.enums?.get(name);\n\t\t\t\t\treturn recognizedEnumKeysForName(recognizedEnumKeys, name) &&\n\t\t\t\t\t\tcurrentEnum\n\t\t\t\t\t\t? currentEnum\n\t\t\t\t\t\t: enumDef;\n\t\t\t\t},\n\t\t\t},\n\t\t),\n\t};\n}\n\nfunction tableWithLogicalIdentity(\n\ttable: TableIR,\n\tidentity: LogicalIdentity | undefined,\n): TableIR {\n\tconst { logicalIdentity: _logicalIdentity, ...rest } = table;\n\treturn identity ? { ...rest, logicalIdentity: identity } : rest;\n}\n\nfunction recognizedEnumKeysForName(\n\trecognizedEnumKeys: ReadonlySet<string>,\n\tname: string,\n): boolean {\n\tfor (const key of recognizedEnumKeys) {\n\t\tconst parsed = JSON.parse(key) as unknown;\n\t\tif (Array.isArray(parsed) && parsed.length === 2 && parsed[0] === name) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction normalizationConflictIsManaged(\n\tconflict: NormalizationConflict,\n\tmanagedCollections: ManagedModelCollections,\n): boolean {\n\tswitch (conflict.kind) {\n\t\tcase 'relation':\n\t\t\treturn isManagedCollectionKey(\n\t\t\t\tmanagedCollections.relations,\n\t\t\t\t`${conflict.source}.${conflict.relation}`,\n\t\t\t);\n\t\tcase 'enum':\n\t\t\treturn isManagedCollectionKey(managedCollections.enums, conflict.enum);\n\t\tcase 'sequence':\n\t\t\treturn isManagedCollectionKey(\n\t\t\t\tmanagedCollections.sequences,\n\t\t\t\tconflict.sequence,\n\t\t\t);\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\nfunction managedMapRecognitionKeys<T>(\n\tdesired: ReadonlyMap<string, T> | undefined,\n\tcurrent: ReadonlyMap<string, T> | undefined,\n\tpolicy: ManagedCollectionPolicy,\n): ReadonlySet<string> {\n\tif (!policy.managed) {\n\t\treturn new Set();\n\t}\n\tif (policy.keys !== undefined) {\n\t\treturn new Set(policy.keys);\n\t}\n\treturn new Set([\n\t\t...(desired ?? new Map<string, T>()).keys(),\n\t\t...(current ?? new Map<string, T>()).keys(),\n\t]);\n}\n\nfunction revertRecognizedCheckChanges(\n\ttableName: string,\n\tdesiredChecks: readonly CheckConstraintIR[] | undefined,\n\tcurrentChecks: readonly CheckConstraintIR[] | undefined,\n\trecognizedCheckKeys: ReadonlySet<string>,\n\trecognizedCheckReplacements: ReadonlyMap<string, CheckConstraintIR>,\n): readonly CheckConstraintIR[] | undefined {\n\tif (recognizedCheckKeys.size === 0 || desiredChecks === undefined) {\n\t\treturn desiredChecks;\n\t}\n\tconst reverted: CheckConstraintIR[] = [];\n\tfor (const check of desiredChecks) {\n\t\tconst key = JSON.stringify([tableName, check.name]);\n\t\tif (!recognizedCheckKeys.has(key)) {\n\t\t\treverted.push(check);\n\t\t\tcontinue;\n\t\t}\n\t\tconst replacement = recognizedCheckReplacements.get(key);\n\t\tif (replacement) {\n\t\t\treverted.push(replacement);\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentCheck = currentChecks?.find(\n\t\t\t(candidate) => candidate.name === check.name,\n\t\t);\n\t\tif (currentCheck) {\n\t\t\treverted.push(currentCheck);\n\t\t}\n\t}\n\tif (reverted.length === 0 && currentChecks === undefined) {\n\t\treturn undefined;\n\t}\n\treturn reverted;\n}\n\nfunction checkChangeKey(tableName: string, checkName: string): string {\n\treturn JSON.stringify([tableName, checkName]);\n}\n\nfunction indexChangeKey(\n\ttableName: string,\n\tindex: Pick<IndexIR, 'name' | 'columns'>,\n): string {\n\treturn JSON.stringify([tableName, defaultIndexName(tableName, index)]);\n}\n\nfunction revertRecognizedIndexChanges(\n\ttableName: string,\n\tdesiredIndexes: readonly IndexIR[],\n\tcurrentIndexes: readonly IndexIR[] | undefined,\n\trecognizedIndexKeys: ReadonlySet<string>,\n): readonly IndexIR[] {\n\tif (recognizedIndexKeys.size === 0) {\n\t\treturn desiredIndexes;\n\t}\n\tconst currentByName = new Map(\n\t\t(currentIndexes ?? []).map((index) => [\n\t\t\tdefaultIndexName(tableName, index),\n\t\t\tindex,\n\t\t]),\n\t);\n\tconst reverted: IndexIR[] = [];\n\tfor (const index of desiredIndexes) {\n\t\tconst key = indexChangeKey(tableName, index);\n\t\tif (!recognizedIndexKeys.has(key)) {\n\t\t\treverted.push(index);\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = currentByName.get(defaultIndexName(tableName, index));\n\t\tif (current) {\n\t\t\treverted.push(current);\n\t\t}\n\t}\n\treturn reverted;\n}\n\nfunction resourceForColumn(\n\tengine: string,\n\ttable: string,\n\tcolumn?: string,\n): ResourceAddress {\n\tconst resource: ResourceAddress = {\n\t\tengine,\n\t\tdatabase: 'model',\n\t\tkind: column ? 'column' : 'table',\n\t\tname: column ?? table,\n\t};\n\treturn column ? { ...resource, qualifiedBy: [table] } : resource;\n}\n\nfunction resourceForCheck(\n\tengine: string,\n\ttable: string,\n\tcheck?: string,\n): ResourceAddress {\n\tif (!check) {\n\t\treturn resourceForColumn(engine, table);\n\t}\n\treturn {\n\t\tengine,\n\t\tdatabase: 'model',\n\t\tkind: 'check-constraint',\n\t\tname: check,\n\t\tqualifiedBy: [table],\n\t};\n}\n\nfunction resourceForIndex(\n\tengine: string,\n\ttable: string,\n\tindex?: string,\n): ResourceAddress {\n\tif (!index) {\n\t\treturn resourceForColumn(engine, table);\n\t}\n\treturn {\n\t\tengine,\n\t\tdatabase: 'model',\n\t\tkind: 'index',\n\t\tname: index,\n\t\tqualifiedBy: [table],\n\t};\n}\n\nfunction resourceForEnum(\n\tengine: string,\n\tenumDef: EnumIR | undefined,\n\tname: string,\n): ResourceAddress {\n\tconst resource: ResourceAddress = {\n\t\tengine,\n\t\tdatabase: 'model',\n\t\tkind: 'type',\n\t\tname,\n\t\tqualifiedBy: ['enum'],\n\t};\n\treturn enumDef?.schema ? { ...resource, schema: enumDef.schema } : resource;\n}\n\nfunction resourceForNormalizationConflict(\n\tengine: string,\n\tconflict: NormalizationConflict,\n): ResourceAddress {\n\tswitch (conflict.kind) {\n\t\tcase 'column':\n\t\t\treturn resourceForColumn(engine, conflict.table, conflict.column);\n\t\tcase 'check':\n\t\t\treturn resourceForCheck(engine, conflict.table, conflict.check);\n\t\tcase 'table':\n\t\t\treturn resourceForColumn(engine, conflict.table);\n\t\tcase 'relation':\n\t\t\treturn {\n\t\t\t\tengine,\n\t\t\t\tdatabase: 'model',\n\t\t\t\tkind: 'relation',\n\t\t\t\tname: conflict.relation,\n\t\t\t\tqualifiedBy: [conflict.source],\n\t\t\t};\n\t\tcase 'enum':\n\t\t\treturn {\n\t\t\t\tengine,\n\t\t\t\tdatabase: 'model',\n\t\t\t\tkind: 'type',\n\t\t\t\tname: conflict.enum,\n\t\t\t\tqualifiedBy: ['enum'],\n\t\t\t};\n\t\tcase 'sequence':\n\t\t\treturn {\n\t\t\t\tengine,\n\t\t\t\tdatabase: 'model',\n\t\t\t\tkind: 'sequence',\n\t\t\t\tname: conflict.sequence,\n\t\t\t};\n\t}\n}\n\nfunction noDriftProposition(): Proposition {\n\treturn {\n\t\tkind: 'dbsp.model.no-drift',\n\t\tscope: [\n\t\t\t{\n\t\t\t\tengine: 'model',\n\t\t\t\tdatabase: 'model',\n\t\t\t\tkind: 'schema',\n\t\t\t\tname: 'model',\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction makeFocusedModel(table: TableIR, column: ColumnIR): ModelIR {\n\tconst { checkConstraints: _checkConstraints, ...tableWithoutChecks } = table;\n\tconst tables = new Map<string, TableIR>([\n\t\t[\n\t\t\ttable.name,\n\t\t\t{\n\t\t\t\t...tableWithoutChecks,\n\t\t\t\tcolumns: [column],\n\t\t\t},\n\t\t],\n\t]);\n\treturn {\n\t\ttables,\n\t\trelations: new Map(),\n\t\tgetTable: (name: string) => tables.get(name),\n\t\tgetRelation: () => undefined,\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\nfunction makeFocusedTableModel(table: TableIR): ModelIR {\n\tconst { checkConstraints: _checkConstraints, ...tableWithoutChecks } = table;\n\tconst tables = new Map<string, TableIR>([\n\t\t[\n\t\t\ttable.name,\n\t\t\t{\n\t\t\t\t...tableWithoutChecks,\n\t\t\t\tcolumns: [],\n\t\t\t\tindexes: [],\n\t\t\t\tforeignKeys: [],\n\t\t\t},\n\t\t],\n\t]);\n\treturn {\n\t\ttables,\n\t\trelations: new Map(),\n\t\tgetTable: (name: string) => tables.get(name),\n\t\tgetRelation: () => undefined,\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\nfunction makeFocusedEnumModel(enumDef: EnumIR): ModelIR {\n\tconst enums = new Map<string, EnumIR>([[enumDef.name, enumDef]]);\n\treturn {\n\t\ttables: new Map(),\n\t\trelations: new Map(),\n\t\tenums,\n\t\tgetTable: () => undefined,\n\t\tgetRelation: () => undefined,\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\nfunction makeFocusedCheckModel(table: TableIR): ModelIR {\n\tconst { columns: _columns, ...tableWithoutColumns } = table;\n\tconst tables = new Map<string, TableIR>([\n\t\t[\n\t\t\ttable.name,\n\t\t\t{\n\t\t\t\t...tableWithoutColumns,\n\t\t\t\tcolumns: [],\n\t\t\t},\n\t\t],\n\t]);\n\treturn {\n\t\ttables,\n\t\trelations: new Map(),\n\t\tgetTable: (name: string) => tables.get(name),\n\t\tgetRelation: () => undefined,\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\nfunction makeFocusedIndexModel(table: TableIR): ModelIR {\n\tconst { checkConstraints: _checkConstraints, ...tableWithoutChecks } = table;\n\tconst tables = new Map<string, TableIR>([[table.name, tableWithoutChecks]]);\n\treturn {\n\t\ttables,\n\t\trelations: new Map(),\n\t\tgetTable: (name: string) => tables.get(name),\n\t\tgetRelation: () => undefined,\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\nfunction requestToObligation(\n\trequest: ObservationRequest,\n\tappliesTo?: string,\n): ProofObligation {\n\tconst propositionBase = {\n\t\tkind: request.kind,\n\t\tscope: request.scope,\n\t};\n\tconst proposition: Proposition =\n\t\trequest.detail === undefined\n\t\t\t? propositionBase\n\t\t\t: { ...propositionBase, detail: request.detail };\n\tconst obligation: ProofObligation = {\n\t\tproposition,\n\t\tscope: request.scope,\n\t\tdischargeableBy: [request],\n\t};\n\treturn appliesTo ? { ...obligation, appliesTo } : obligation;\n}\n\nfunction ruleRef(rule: TransitionRule): RuleRef {\n\treturn {\n\t\tid: rule.id,\n\t\tpack: rule.artifact,\n\t};\n}\n\ntype RecognizedRuleEntry = {\n\treadonly rule: TransitionRule;\n\treadonly result: Extract<\n\t\tRecognitionResult<unknown>,\n\t\t{ readonly recognized: true }\n\t>;\n};\n\nfunction candidateFromRule(\n\trule: TransitionRule,\n\tresult: Extract<RecognitionResult<unknown>, { readonly recognized: true }>,\n\trecognizedRules: readonly TransitionRule[],\n\twhy: string,\n): TransitionCandidate {\n\tconst { match } = result;\n\tconst required = rule.requiredObservations(match);\n\tconst ref = ruleRef(rule);\n\tconst candidate = {\n\t\trule: ref,\n\t\tmatch,\n\t\trequiredObservations: required,\n\t\tobligations: required.map((request) => requestToObligation(request)),\n\t\tselectionRationale: {\n\t\t\tchosen: ref,\n\t\t\toverRules: recognizedRules\n\t\t\t\t.filter((candidate) => candidate !== rule)\n\t\t\t\t.map((candidate) => ruleRef(candidate)),\n\t\t\twhy,\n\t\t},\n\t};\n\treturn result.claimDrafts\n\t\t? { ...candidate, claimDrafts: result.claimDrafts }\n\t\t: candidate;\n}\n\ntype ArbitrationResult =\n\t| {\n\t\t\treadonly kind: 'candidate';\n\t\t\treadonly candidate: TransitionCandidate;\n\t\t\treadonly candidateRule: TransitionRule;\n\t }\n\t| {\n\t\t\treadonly kind: 'ambiguous';\n\t\t\treadonly candidates: readonly RuleRef[];\n\t };\n\nfunction arbitrateRecognizedRules(\n\tregistry: PackRegistry,\n\trecognized: readonly RecognizedRuleEntry[],\n): ArbitrationResult {\n\tconst recognizedRules = recognized.map((entry) => entry.rule);\n\tif (recognized.length === 1) {\n\t\tconst entry = recognized[0];\n\t\tif (!entry) {\n\t\t\treturn { kind: 'ambiguous', candidates: [] };\n\t\t}\n\t\treturn {\n\t\t\tkind: 'candidate',\n\t\t\tcandidateRule: entry.rule,\n\t\t\tcandidate: candidateFromRule(\n\t\t\t\tentry.rule,\n\t\t\t\tentry.result,\n\t\t\t\trecognizedRules,\n\t\t\t\t'recognized transition rule',\n\t\t\t),\n\t\t};\n\t}\n\n\tconst resolution = registry.resolveRulePrecedence(recognizedRules);\n\tif (!resolution.ok) {\n\t\treturn {\n\t\t\tkind: 'ambiguous',\n\t\t\tcandidates: recognizedRules.map((entry) => ruleRef(entry)),\n\t\t};\n\t}\n\tconst chosenEntry = recognized.find(\n\t\t(entry) => entry.rule === resolution.rule,\n\t);\n\tif (!chosenEntry) {\n\t\treturn {\n\t\t\tkind: 'ambiguous',\n\t\t\tcandidates: recognizedRules.map((entry) => ruleRef(entry)),\n\t\t};\n\t}\n\treturn {\n\t\tkind: 'candidate',\n\t\tcandidateRule: chosenEntry.rule,\n\t\tcandidate: candidateFromRule(\n\t\t\tchosenEntry.rule,\n\t\t\tchosenEntry.result,\n\t\t\trecognizedRules,\n\t\t\t`recognized transition rule selected by declared precedence: ${resolution.reason}`,\n\t\t),\n\t};\n}\n\nexport function createComparator(registry: PackRegistry): Comparator {\n\treturn {\n\t\tartifact: COMPARATOR_ARTIFACT,\n\t\tcompare(\n\t\t\tdesired: ModelIR,\n\t\t\tcurrent: ModelIR,\n\t\t\tcontext?: EquivalenceContext,\n\t\t): CompareOutcome {\n\t\t\tassertDeclaredEnumMapIdentity(desired.enums);\n\t\t\tconst engine =\n\t\t\t\tcontext?.engine ??\n\t\t\t\tregistry.allRules()[0]?.support.engine ??\n\t\t\t\t'unknown-transition-engine';\n\t\t\tconst recognitionContextFor = (rule: TransitionRule) => {\n\t\t\t\tconst equivalence = registry.resolveEquivalence(rule.artifact);\n\t\t\t\tconst recognitionContext: EquivalenceContext = {\n\t\t\t\t\t...(context ?? {}),\n\t\t\t\t\tengine,\n\t\t\t\t};\n\t\t\t\treturn equivalence\n\t\t\t\t\t? { equivalence, context: recognitionContext }\n\t\t\t\t\t: { context: recognitionContext };\n\t\t\t};\n\t\t\tconst normalizeCurrentIdentifier =\n\t\t\t\tregistry.comparatorNameNormalizer()?.normalizeCurrentIdentifier ??\n\t\t\t\t((identifier: string) => identifier);\n\t\t\tconst normalizedCurrent = normalizeCurrentModelForComparison(\n\t\t\t\tcurrent,\n\t\t\t\tnormalizeCurrentIdentifier,\n\t\t\t);\n\t\t\tconst currentForComparison = normalizedCurrent.model;\n\t\t\tconst ignoredExternalTables = externalTableNames(\n\t\t\t\tdesired,\n\t\t\t\tcurrentForComparison,\n\t\t\t);\n\t\t\tconst managedCollections = managedModelCollections(\n\t\t\t\tdesired,\n\t\t\t\tignoredExternalTables,\n\t\t\t);\n\t\t\tconst blockingNormalizationConflicts = normalizedCurrent.conflicts.filter(\n\t\t\t\t(conflict) =>\n\t\t\t\t\tnormalizationConflictIsManaged(conflict, managedCollections),\n\t\t\t);\n\t\t\tif (blockingNormalizationConflicts.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'unsupported',\n\t\t\t\t\tchanges: blockingNormalizationConflicts.map((conflict) =>\n\t\t\t\t\t\tresourceForNormalizationConflict(engine, conflict),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst desiredComparison = modelForComparison(\n\t\t\t\tdesired,\n\t\t\t\tignoredExternalTables,\n\t\t\t\tmanagedCollections,\n\t\t\t\t'desired',\n\t\t\t);\n\t\t\tconst currentComparison = modelForComparison(\n\t\t\t\tcurrentForComparison,\n\t\t\t\tignoredExternalTables,\n\t\t\t\tmanagedCollections,\n\t\t\t\t'current',\n\t\t\t\tdesired,\n\t\t\t);\n\t\t\tif (stableJson(desiredComparison) === stableJson(currentComparison)) {\n\t\t\t\treturn { kind: 'no-drift', claimedInvariant: noDriftProposition() };\n\t\t\t}\n\n\t\t\tconst candidates: TransitionCandidate[] = [];\n\t\t\tconst unknownRecognitions: UnknownTransitionRecognition[] = [];\n\t\t\tconst unsupported: ResourceAddress[] = [];\n\t\t\tconst recognizedColumnFields = new Map<string, Set<ColumnFieldName>>();\n\t\t\tconst pendingColumnFields = new Map<string, Set<ColumnFieldName>>();\n\t\t\tconst recognizedTableKeys = new Set<string>();\n\t\t\tconst pendingTableKeys = new Set<string>();\n\t\t\tconst recognizedEnumKeys = new Set<string>();\n\t\t\tconst pendingEnumKeys = new Set<string>();\n\t\t\tconst recognizedCheckKeys = new Set<string>();\n\t\t\tconst pendingCheckKeys = new Set<string>();\n\t\t\tconst pendingCheckReplacements = new Map<string, CheckConstraintIR>();\n\t\t\tconst recognizedIndexKeys = new Set<string>();\n\t\t\tconst pendingIndexKeys = new Set<string>();\n\n\t\t\tconst tableNames = new Set<string>([\n\t\t\t\t...desired.tables.keys(),\n\t\t\t\t...currentForComparison.tables.keys(),\n\t\t\t]);\n\n\t\t\tfor (const tableName of tableNames) {\n\t\t\t\tif (ignoredExternalTables.has(tableName)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst desiredTable = desired.getTable(tableName);\n\t\t\t\tconst currentTable = currentForComparison.getTable(tableName);\n\t\t\t\tif (!desiredTable || !currentTable) {\n\t\t\t\t\tunsupported.push(resourceForColumn(engine, tableName));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (logicalIdentityChanged(desiredTable, currentTable)) {\n\t\t\t\t\tconst focusedDesired = makeFocusedTableModel(desiredTable);\n\t\t\t\t\tconst focusedCurrent = makeFocusedTableModel(currentTable);\n\t\t\t\t\tconst recognitionEntries = registry.allRules().map((rule) => ({\n\t\t\t\t\t\trule,\n\t\t\t\t\t\tresult: rule.recognize(\n\t\t\t\t\t\t\tfocusedDesired,\n\t\t\t\t\t\t\tfocusedCurrent,\n\t\t\t\t\t\t\trecognitionContextFor(rule),\n\t\t\t\t\t\t),\n\t\t\t\t\t}));\n\t\t\t\t\tconst recognized = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: true }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === true,\n\t\t\t\t\t);\n\t\t\t\t\tconst unknown = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: 'unknown' }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === 'unknown',\n\t\t\t\t\t);\n\n\t\t\t\t\tif (recognized.length === 0) {\n\t\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\t\tfor (const entry of unknown) {\n\t\t\t\t\t\t\t\tunknownRecognitions.push({\n\t\t\t\t\t\t\t\t\trule: ruleRef(entry.rule),\n\t\t\t\t\t\t\t\t\tdesired: focusedDesired,\n\t\t\t\t\t\t\t\t\tcurrent: focusedCurrent,\n\t\t\t\t\t\t\t\t\tobligations: entry.result.obligations,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpendingTableKeys.add(tableName);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsupported.push(resourceForColumn(engine, tableName));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst arbitration = arbitrateRecognizedRules(registry, recognized);\n\t\t\t\t\tif (arbitration.kind === 'ambiguous') {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'ambiguous',\n\t\t\t\t\t\t\tcandidates: arbitration.candidates,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcandidates.push(arbitration.candidate);\n\t\t\t\t\trecognizedTableKeys.add(tableName);\n\t\t\t\t\tpendingTableKeys.add(tableName);\n\t\t\t\t}\n\n\t\t\t\tconst columnNames = new Set<string>([\n\t\t\t\t\t...desiredTable.columns.map((column) => column.name),\n\t\t\t\t\t...currentTable.columns.map((column) => column.name),\n\t\t\t\t]);\n\n\t\t\t\tfor (const columnName of columnNames) {\n\t\t\t\t\tconst desiredColumn = desiredTable.columns.find(\n\t\t\t\t\t\t(column) => column.name === columnName,\n\t\t\t\t\t);\n\t\t\t\t\tconst currentColumn = currentTable.columns.find(\n\t\t\t\t\t\t(column) => column.name === columnName,\n\t\t\t\t\t);\n\t\t\t\t\tif (!columnChanged(desiredColumn, currentColumn)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!desiredColumn || !currentColumn) {\n\t\t\t\t\t\tunsupported.push(resourceForColumn(engine, tableName, columnName));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst columnKey = columnChangeKey(tableName, columnName);\n\n\t\t\t\t\tconst focusedDesired = makeFocusedModel(desiredTable, desiredColumn);\n\t\t\t\t\tconst focusedCurrent = makeFocusedModel(currentTable, currentColumn);\n\t\t\t\t\tconst recognitionEntries = registry.allRules().map((rule) => ({\n\t\t\t\t\t\trule,\n\t\t\t\t\t\tresult: rule.recognize(\n\t\t\t\t\t\t\tfocusedDesired,\n\t\t\t\t\t\t\tfocusedCurrent,\n\t\t\t\t\t\t\trecognitionContextFor(rule),\n\t\t\t\t\t\t),\n\t\t\t\t\t}));\n\t\t\t\t\tconst recognized = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: true }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === true,\n\t\t\t\t\t);\n\t\t\t\t\tconst unknown = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: 'unknown' }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === 'unknown',\n\t\t\t\t\t);\n\n\t\t\t\t\tif (recognized.length === 0) {\n\t\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\t\tfor (const entry of unknown) {\n\t\t\t\t\t\t\t\tunknownRecognitions.push({\n\t\t\t\t\t\t\t\t\trule: ruleRef(entry.rule),\n\t\t\t\t\t\t\t\t\tdesired: focusedDesired,\n\t\t\t\t\t\t\t\t\tcurrent: focusedCurrent,\n\t\t\t\t\t\t\t\t\tobligations: entry.result.obligations,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\taddColumnFieldCoverage(\n\t\t\t\t\t\t\t\t\tpendingColumnFields,\n\t\t\t\t\t\t\t\t\tcolumnKey,\n\t\t\t\t\t\t\t\t\tdeclaredColumnFieldsFor(entry.rule),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsupported.push(resourceForColumn(engine, tableName, columnName));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (recognizedColumnFieldsAreDisjoint(recognized)) {\n\t\t\t\t\t\tfor (const entry of recognized) {\n\t\t\t\t\t\t\tcandidates.push(\n\t\t\t\t\t\t\t\tcandidateFromRule(\n\t\t\t\t\t\t\t\t\tentry.rule,\n\t\t\t\t\t\t\t\t\tentry.result,\n\t\t\t\t\t\t\t\t\t[entry.rule],\n\t\t\t\t\t\t\t\t\t'recognized transition rule with disjoint column field coverage',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\taddColumnFieldCoverage(\n\t\t\t\t\t\t\t\trecognizedColumnFields,\n\t\t\t\t\t\t\t\tcolumnKey,\n\t\t\t\t\t\t\t\tdeclaredColumnFieldsFor(entry.rule),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\taddColumnFieldCoverage(\n\t\t\t\t\t\t\t\tpendingColumnFields,\n\t\t\t\t\t\t\t\tcolumnKey,\n\t\t\t\t\t\t\t\tdeclaredColumnFieldsFor(entry.rule),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst arbitration = arbitrateRecognizedRules(registry, recognized);\n\t\t\t\t\tif (arbitration.kind === 'ambiguous') {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'ambiguous',\n\t\t\t\t\t\t\tcandidates: arbitration.candidates,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcandidates.push(arbitration.candidate);\n\t\t\t\t\taddColumnFieldCoverage(\n\t\t\t\t\t\trecognizedColumnFields,\n\t\t\t\t\t\tcolumnKey,\n\t\t\t\t\t\tdeclaredColumnFieldsFor(arbitration.candidateRule),\n\t\t\t\t\t);\n\t\t\t\t\taddColumnFieldCoverage(\n\t\t\t\t\t\tpendingColumnFields,\n\t\t\t\t\t\tcolumnKey,\n\t\t\t\t\t\tdeclaredColumnFieldsFor(arbitration.candidateRule),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst tableCheckDelta = checkDelta(\n\t\t\t\t\tdesiredTable.checkConstraints,\n\t\t\t\t\tcurrentTable.checkConstraints,\n\t\t\t\t);\n\t\t\t\tif (tableCheckDelta.kind === 'unsupported') {\n\t\t\t\t\tunsupported.push(resourceForCheck(engine, tableName));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tableCheckDelta.kind !== 'none') {\n\t\t\t\t\tconst checkName =\n\t\t\t\t\t\ttableCheckDelta.kind === 'add-check'\n\t\t\t\t\t\t\t? tableCheckDelta.check.name\n\t\t\t\t\t\t\t: tableCheckDelta.desired.name;\n\t\t\t\t\tconst checkKey = checkChangeKey(tableName, checkName);\n\t\t\t\t\tif (tableCheckDelta.kind === 'expression-mismatch') {\n\t\t\t\t\t\tpendingCheckKeys.add(checkKey);\n\t\t\t\t\t\tconst currentCheck = currentTable.checkConstraints?.find(\n\t\t\t\t\t\t\t(candidate) => candidate.name === tableCheckDelta.current.name,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (currentCheck) {\n\t\t\t\t\t\t\tpendingCheckReplacements.set(checkKey, currentCheck);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst focusedDesired = makeFocusedCheckModel(desiredTable);\n\t\t\t\t\tconst focusedCurrent = makeFocusedCheckModel(currentTable);\n\t\t\t\t\tconst recognitionEntries = registry.allRules().map((rule) => ({\n\t\t\t\t\t\trule,\n\t\t\t\t\t\tresult: rule.recognize(\n\t\t\t\t\t\t\tfocusedDesired,\n\t\t\t\t\t\t\tfocusedCurrent,\n\t\t\t\t\t\t\trecognitionContextFor(rule),\n\t\t\t\t\t\t),\n\t\t\t\t\t}));\n\t\t\t\t\tconst recognized = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: true }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === true,\n\t\t\t\t\t);\n\t\t\t\t\tconst unknown = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: 'unknown' }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === 'unknown',\n\t\t\t\t\t);\n\t\t\t\t\tconst recognizedUnsupported = recognitionEntries.find(\n\t\t\t\t\t\t(entry) => entry.result.recognized === 'unsupported',\n\t\t\t\t\t);\n\n\t\t\t\t\tif (recognized.length === 0) {\n\t\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\t\tfor (const entry of unknown) {\n\t\t\t\t\t\t\t\tunknownRecognitions.push({\n\t\t\t\t\t\t\t\t\trule: ruleRef(entry.rule),\n\t\t\t\t\t\t\t\t\tdesired: focusedDesired,\n\t\t\t\t\t\t\t\t\tcurrent: focusedCurrent,\n\t\t\t\t\t\t\t\t\tobligations: entry.result.obligations,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpendingCheckKeys.add(checkKey);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (recognizedUnsupported?.result.recognized === 'unsupported') {\n\t\t\t\t\t\t\tunsupported.push(...recognizedUnsupported.result.changes);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsupported.push(resourceForCheck(engine, tableName, checkName));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst arbitration = arbitrateRecognizedRules(registry, recognized);\n\t\t\t\t\tif (arbitration.kind === 'ambiguous') {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'ambiguous',\n\t\t\t\t\t\t\tcandidates: arbitration.candidates,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcandidates.push(arbitration.candidate);\n\t\t\t\t\trecognizedCheckKeys.add(checkKey);\n\t\t\t\t\tpendingCheckKeys.add(checkKey);\n\t\t\t\t}\n\n\t\t\t\tconst tableIndexDelta = indexDelta(\n\t\t\t\t\ttableName,\n\t\t\t\t\tdesiredTable.indexes,\n\t\t\t\t\tcurrentTable.indexes,\n\t\t\t\t);\n\t\t\t\tif (tableIndexDelta.kind === 'unsupported') {\n\t\t\t\t\tunsupported.push(resourceForIndex(engine, tableName));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tableIndexDelta.kind === 'add-unique-index') {\n\t\t\t\t\tconst indexKey = indexChangeKey(tableName, tableIndexDelta.index);\n\t\t\t\t\tconst focusedDesired = makeFocusedIndexModel(desiredTable);\n\t\t\t\t\tconst focusedCurrent = makeFocusedIndexModel(currentTable);\n\t\t\t\t\tconst recognitionEntries = registry.allRules().map((rule) => ({\n\t\t\t\t\t\trule,\n\t\t\t\t\t\tresult: rule.recognize(\n\t\t\t\t\t\t\tfocusedDesired,\n\t\t\t\t\t\t\tfocusedCurrent,\n\t\t\t\t\t\t\trecognitionContextFor(rule),\n\t\t\t\t\t\t),\n\t\t\t\t\t}));\n\t\t\t\t\tconst recognized = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: true }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === true,\n\t\t\t\t\t);\n\t\t\t\t\tconst unknown = recognitionEntries.filter(\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t): entry is {\n\t\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t\t{ readonly recognized: 'unknown' }\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t} => entry.result.recognized === 'unknown',\n\t\t\t\t\t);\n\t\t\t\t\tconst recognizedUnsupported = recognitionEntries.find(\n\t\t\t\t\t\t(entry) => entry.result.recognized === 'unsupported',\n\t\t\t\t\t);\n\n\t\t\t\t\tif (recognized.length === 0) {\n\t\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\t\tfor (const entry of unknown) {\n\t\t\t\t\t\t\t\tunknownRecognitions.push({\n\t\t\t\t\t\t\t\t\trule: ruleRef(entry.rule),\n\t\t\t\t\t\t\t\t\tdesired: focusedDesired,\n\t\t\t\t\t\t\t\t\tcurrent: focusedCurrent,\n\t\t\t\t\t\t\t\t\tobligations: entry.result.obligations,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpendingIndexKeys.add(indexKey);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (recognizedUnsupported?.result.recognized === 'unsupported') {\n\t\t\t\t\t\t\tunsupported.push(...recognizedUnsupported.result.changes);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsupported.push(\n\t\t\t\t\t\t\tresourceForIndex(engine, tableName, tableIndexDelta.index.name),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst arbitration = arbitrateRecognizedRules(registry, recognized);\n\t\t\t\t\tif (arbitration.kind === 'ambiguous') {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'ambiguous',\n\t\t\t\t\t\t\tcandidates: arbitration.candidates,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcandidates.push(arbitration.candidate);\n\t\t\t\t\trecognizedIndexKeys.add(indexKey);\n\t\t\t\t\tpendingIndexKeys.add(indexKey);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst enumNames = managedMapRecognitionKeys(\n\t\t\t\tdesired.enums,\n\t\t\t\tcurrentForComparison.enums,\n\t\t\t\tmanagedCollections.enums,\n\t\t\t);\n\n\t\t\tfor (const enumName of enumNames) {\n\t\t\t\tconst desiredEnum = desired.enums?.get(enumName);\n\t\t\t\tconst currentEnum = currentForComparison.enums?.get(enumName);\n\t\t\t\tif (!desiredEnum || !currentEnum) {\n\t\t\t\t\tunsupported.push(\n\t\t\t\t\t\tresourceForEnum(engine, desiredEnum ?? currentEnum, enumName),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst delta = enumAddDelta(\n\t\t\t\t\tdesiredEnum,\n\t\t\t\t\tcurrentEnum,\n\t\t\t\t\tcontext?.targetSchema === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { targetSchema: context.targetSchema },\n\t\t\t\t);\n\t\t\t\tif (delta.kind === 'none') {\n\t\t\t\t\tpendingEnumKeys.add(JSON.stringify([enumName, null]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (delta.kind === 'unsupported') {\n\t\t\t\t\tunsupported.push(resourceForEnum(engine, desiredEnum, enumName));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst focusedDesired = makeFocusedEnumModel(desiredEnum);\n\t\t\t\tconst focusedCurrent = makeFocusedEnumModel(currentEnum);\n\t\t\t\tconst recognitionEntries = registry.allRules().map((rule) => ({\n\t\t\t\t\trule,\n\t\t\t\t\tresult: rule.recognize(\n\t\t\t\t\t\tfocusedDesired,\n\t\t\t\t\t\tfocusedCurrent,\n\t\t\t\t\t\trecognitionContextFor(rule),\n\t\t\t\t\t),\n\t\t\t\t}));\n\t\t\t\tconst recognized = recognitionEntries.filter(\n\t\t\t\t\t(\n\t\t\t\t\t\tentry,\n\t\t\t\t\t): entry is {\n\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t{ readonly recognized: true }\n\t\t\t\t\t\t>;\n\t\t\t\t\t} => entry.result.recognized === true,\n\t\t\t\t);\n\t\t\t\tconst unknown = recognitionEntries.filter(\n\t\t\t\t\t(\n\t\t\t\t\t\tentry,\n\t\t\t\t\t): entry is {\n\t\t\t\t\t\treadonly rule: TransitionRule;\n\t\t\t\t\t\treadonly result: Extract<\n\t\t\t\t\t\t\tRecognitionResult<unknown>,\n\t\t\t\t\t\t\t{ readonly recognized: 'unknown' }\n\t\t\t\t\t\t>;\n\t\t\t\t\t} => entry.result.recognized === 'unknown',\n\t\t\t\t);\n\n\t\t\t\tif (recognized.length === 0) {\n\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\tfor (const entry of unknown) {\n\t\t\t\t\t\t\tunknownRecognitions.push({\n\t\t\t\t\t\t\t\trule: ruleRef(entry.rule),\n\t\t\t\t\t\t\t\tdesired: focusedDesired,\n\t\t\t\t\t\t\t\tcurrent: focusedCurrent,\n\t\t\t\t\t\t\t\tobligations: entry.result.obligations,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpendingEnumKeys.add(JSON.stringify([enumName, delta.label]));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tunsupported.push(resourceForEnum(engine, desiredEnum, enumName));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst arbitration = arbitrateRecognizedRules(registry, recognized);\n\t\t\t\tif (arbitration.kind === 'ambiguous') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'ambiguous',\n\t\t\t\t\t\tcandidates: arbitration.candidates,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcandidates.push(arbitration.candidate);\n\t\t\t\trecognizedEnumKeys.add(JSON.stringify([enumName, delta.label]));\n\t\t\t\tpendingEnumKeys.add(JSON.stringify([enumName, delta.label]));\n\t\t\t}\n\n\t\t\tconst hiddenDiffsRemain =\n\t\t\t\tstableJson(\n\t\t\t\t\trevertRecognizedColumnChanges(\n\t\t\t\t\t\tdesired,\n\t\t\t\t\t\tcurrentForComparison,\n\t\t\t\t\t\tmergeColumnFieldCoverage(\n\t\t\t\t\t\t\trecognizedColumnFields,\n\t\t\t\t\t\t\tpendingColumnFields,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tignoredExternalTables,\n\t\t\t\t\t\tmanagedCollections,\n\t\t\t\t\t\tnew Set([...recognizedTableKeys, ...pendingTableKeys]),\n\t\t\t\t\t\tnew Set([...recognizedEnumKeys, ...pendingEnumKeys]),\n\t\t\t\t\t\tnew Set([...recognizedCheckKeys, ...pendingCheckKeys]),\n\t\t\t\t\t\tpendingCheckReplacements,\n\t\t\t\t\t\tnew Set([...recognizedIndexKeys, ...pendingIndexKeys]),\n\t\t\t\t\t),\n\t\t\t\t) !== stableJson(currentComparison);\n\t\t\tif (hiddenDiffsRemain) {\n\t\t\t\tunsupported.push({\n\t\t\t\t\tengine,\n\t\t\t\t\tdatabase: 'model',\n\t\t\t\t\tkind: 'schema',\n\t\t\t\t\tname: 'model',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (unsupported.length > 0) {\n\t\t\t\treturn { kind: 'unsupported', changes: unsupported };\n\t\t\t}\n\n\t\t\tif (unknownRecognitions.length > 0 && candidates.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'uncomposable',\n\t\t\t\t\tcandidates,\n\t\t\t\t\trecognitions: unknownRecognitions,\n\t\t\t\t\tobligations: [\n\t\t\t\t\t\t...candidates.flatMap((candidate) => [...candidate.obligations]),\n\t\t\t\t\t\t...unknownRecognitions.flatMap((entry) => [...entry.obligations]),\n\t\t\t\t\t],\n\t\t\t\t\tdetail:\n\t\t\t\t\t\t'mixed recognized and unknown transition changes cannot be retried without proving the whole diff',\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (unknownRecognitions.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'unknown',\n\t\t\t\t\trecognitions: unknownRecognitions,\n\t\t\t\t\tobligations: unknownRecognitions.flatMap((entry) => [\n\t\t\t\t\t\t...entry.obligations,\n\t\t\t\t\t]),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (candidates.length === 0) {\n\t\t\t\treturn withTransitionCompareCurrentModel(\n\t\t\t\t\t{ kind: 'no-drift', claimedInvariant: noDriftProposition() },\n\t\t\t\t\tcurrent,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn withTransitionCompareCurrentModel(\n\t\t\t\t{\n\t\t\t\t\tkind: 'transitions',\n\t\t\t\t\tcandidates,\n\t\t\t\t\tobligations: candidates.flatMap((candidate) => [\n\t\t\t\t\t\t...candidate.obligations,\n\t\t\t\t\t]),\n\t\t\t\t},\n\t\t\t\tcurrent,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type {\n\tEvidenceObservation,\n\tJsonValue,\n\tObservationContext,\n\tObservationRequest,\n\tProofObligation,\n\tProposition,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { matchLiveObservationContext } from './context-match.js';\nimport { stableJson } from './stable-json.js';\n\ntype BooleanEvidenceClaim = {\n\treadonly kind: string;\n\treadonly holds: boolean;\n\treadonly scope?: readonly ResourceAddress[];\n\treadonly detail?: JsonValue;\n\treadonly proposition?: unknown;\n};\n\nexport type EvidenceConclusion =\n\t| 'established'\n\t| 'undischarged'\n\t| 'refuted'\n\t| 'conflicted';\n\nexport type EvidenceEntailmentResult = {\n\treadonly conclusion: EvidenceConclusion;\n\treadonly supportedBy: readonly EvidenceObservation[];\n};\n\nfunction isJsonObject(\n\tvalue: unknown,\n): value is Readonly<Record<string, unknown>> {\n\treturn value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nfunction sameScope(\n\tleft: readonly ResourceAddress[],\n\tright: readonly ResourceAddress[],\n): boolean {\n\treturn sameJson(left, right);\n}\n\nfunction sameProposition(left: Proposition, right: Proposition): boolean {\n\treturn (\n\t\tleft.kind === right.kind &&\n\t\tsameScope(left.scope, right.scope) &&\n\t\tsameJson(left.detail, right.detail)\n\t);\n}\n\nexport function observationRequestForProposition(\n\tproposition: Proposition,\n): ObservationRequest {\n\treturn proposition.detail === undefined\n\t\t? {\n\t\t\t\tkind: proposition.kind,\n\t\t\t\tscope: proposition.scope,\n\t\t\t}\n\t\t: {\n\t\t\t\tkind: proposition.kind,\n\t\t\t\tscope: proposition.scope,\n\t\t\t\tdetail: proposition.detail,\n\t\t\t};\n}\n\nexport function sameObservationRequest(\n\tleft: ObservationRequest,\n\tright: ObservationRequest,\n): boolean {\n\treturn (\n\t\tleft.kind === right.kind &&\n\t\tsameScope(left.scope, right.scope) &&\n\t\tsameJson(left.detail, right.detail)\n\t);\n}\n\nfunction normalizeResourceForContext(\n\tresource: ResourceAddress,\n\tcontext: ObservationContext,\n): ResourceAddress {\n\treturn {\n\t\t...resource,\n\t\tdatabase:\n\t\t\tresource.database === 'model' ? context.databaseId : resource.database,\n\t\t...(resource.schema == null &&\n\t\tcontext.targetSchema &&\n\t\tresource.kind !== 'engine'\n\t\t\t? { schema: context.targetSchema }\n\t\t\t: {}),\n\t};\n}\n\nfunction normalizeScopeForContext(\n\tscope: readonly ResourceAddress[],\n\tcontext: ObservationContext,\n): readonly ResourceAddress[] {\n\treturn scope.map((resource) =>\n\t\tnormalizeResourceForContext(resource, context),\n\t);\n}\n\nfunction normalizeRequestDetailForContext(\n\tdetail: ObservationRequest['detail'],\n\tcontext: ObservationContext,\n): ObservationRequest['detail'] {\n\tif (!isJsonObject(detail)) {\n\t\treturn detail;\n\t}\n\tif (\n\t\t'schema' in detail &&\n\t\t(detail.schema === null || detail.schema === undefined) &&\n\t\tcontext.targetSchema\n\t) {\n\t\treturn { ...detail, schema: context.targetSchema };\n\t}\n\treturn detail;\n}\n\nexport function normalizeObservationRequestForContext(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): ObservationRequest {\n\tconst scope = normalizeScopeForContext(request.scope, context);\n\tconst detail = normalizeRequestDetailForContext(request.detail, context);\n\treturn detail === undefined\n\t\t? { kind: request.kind, scope }\n\t\t: { kind: request.kind, scope, detail };\n}\n\nexport function normalizePropositionForContext(\n\tproposition: Proposition,\n\tcontext: ObservationContext,\n): Proposition {\n\tconst request = normalizeObservationRequestForContext(\n\t\tobservationRequestForProposition(proposition),\n\t\tcontext,\n\t);\n\treturn request.detail === undefined\n\t\t? { kind: request.kind, scope: request.scope }\n\t\t: { kind: request.kind, scope: request.scope, detail: request.detail };\n}\n\nexport function sameObservationRequestInContext(\n\tleft: ObservationRequest,\n\tright: ObservationRequest,\n\tcontext?: ObservationContext,\n): boolean {\n\tif (!context) {\n\t\treturn sameObservationRequest(left, right);\n\t}\n\treturn sameObservationRequest(\n\t\tnormalizeObservationRequestForContext(left, context),\n\t\tnormalizeObservationRequestForContext(right, context),\n\t);\n}\n\nfunction resourceMatchesRequestedScope(\n\trequested: ResourceAddress,\n\tobserved: ResourceAddress,\n\tcontext?: ObservationContext,\n): boolean {\n\tconst left = context\n\t\t? normalizeResourceForContext(requested, context)\n\t\t: requested;\n\tconst right = context\n\t\t? normalizeResourceForContext(observed, context)\n\t\t: observed;\n\treturn (\n\t\tleft.engine === right.engine &&\n\t\tleft.database === right.database &&\n\t\tleft.kind === right.kind &&\n\t\tleft.name === right.name &&\n\t\tsameJson(left.qualifiedBy, right.qualifiedBy) &&\n\t\tleft.schema === right.schema\n\t);\n}\n\nfunction schemaMatchesRequested(\n\trequested: unknown,\n\tobserved: unknown,\n\tcontext?: ObservationContext,\n): boolean {\n\tif (sameJson(requested, observed)) {\n\t\treturn true;\n\t}\n\treturn (\n\t\t(requested == null && observed == null) ||\n\t\t(requested == null &&\n\t\t\ttypeof observed === 'string' &&\n\t\t\tcontext?.targetSchema === observed)\n\t);\n}\n\nfunction detailMatchesRequested(\n\trequested: ObservationRequest['detail'],\n\tobserved: ObservationRequest['detail'],\n\tcontext?: ObservationContext,\n): boolean {\n\tconst left = context\n\t\t? normalizeRequestDetailForContext(requested, context)\n\t\t: requested;\n\tconst right = context\n\t\t? normalizeRequestDetailForContext(observed, context)\n\t\t: observed;\n\tif (sameJson(left, right)) {\n\t\treturn true;\n\t}\n\tif (!isJsonObject(left) || !isJsonObject(right)) {\n\t\treturn false;\n\t}\n\tfor (const [key, value] of Object.entries(left)) {\n\t\tconst observedValue = right[key];\n\t\tif (\n\t\t\tkey === 'schema' &&\n\t\t\tschemaMatchesRequested(value, observedValue, context)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!sameJson(value, observedValue)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tfor (const key of Object.keys(right)) {\n\t\tif (!(key in left)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nexport function observationRequestMatchesInContext(\n\trequested: ObservationRequest,\n\tobserved: ObservationRequest,\n\tcontext?: ObservationContext,\n): boolean {\n\treturn (\n\t\trequested.kind === observed.kind &&\n\t\trequested.scope.length === observed.scope.length &&\n\t\trequested.scope.every((resource, index) =>\n\t\t\tresourceMatchesRequestedScope(\n\t\t\t\tresource,\n\t\t\t\tobserved.scope[index] as ResourceAddress,\n\t\t\t\tcontext,\n\t\t\t),\n\t\t) &&\n\t\tdetailMatchesRequested(requested.detail, observed.detail, context)\n\t);\n}\n\ntype ConcreteIdentity = ReadonlyMap<string, ReadonlySet<string>>;\n\nconst DETAIL_TARGET_IDENTITY_FIELDS = new Set([\n\t'database',\n\t'engine',\n\t'index',\n\t'label',\n\t'logicalId',\n\t'name',\n\t'object',\n\t'schema',\n\t'table',\n\t'column',\n\t'constraint',\n\t'type',\n]);\n\nfunction identityKey(value: unknown): string {\n\treturn stableJson(value);\n}\n\nfunction addConcreteIdentityValue(\n\tidentity: Map<string, Set<string>>,\n\tfield: string,\n\tvalue: unknown,\n): void {\n\tif (value === null || value === undefined) {\n\t\treturn;\n\t}\n\tlet values = identity.get(field);\n\tif (!values) {\n\t\tvalues = new Set<string>();\n\t\tidentity.set(field, values);\n\t}\n\tvalues.add(identityKey(value));\n}\n\nfunction addSchemaIdentityValue(\n\tidentity: Map<string, Set<string>>,\n\tvalue: unknown,\n\tcontext: ObservationContext,\n): void {\n\tconst schema =\n\t\tvalue === null || value === undefined ? context.targetSchema : value;\n\taddConcreteIdentityValue(identity, 'schema', schema);\n}\n\nfunction addDatabaseIdentityValue(\n\tidentity: Map<string, Set<string>>,\n\tvalue: unknown,\n\tcontext: ObservationContext,\n): void {\n\tconst database = value === 'model' ? context.databaseId : value;\n\taddConcreteIdentityValue(identity, 'database', database);\n}\n\nfunction addResourceIdentity(\n\tidentity: Map<string, Set<string>>,\n\tresource: ResourceAddress,\n\tcontext: ObservationContext,\n): void {\n\taddConcreteIdentityValue(identity, 'engine', resource.engine);\n\taddDatabaseIdentityValue(identity, resource.database, context);\n\tif (\n\t\tresource.schema !== undefined ||\n\t\t(resource.kind !== 'engine' &&\n\t\t\tresource.kind !== 'database' &&\n\t\t\tcontext.targetSchema)\n\t) {\n\t\taddSchemaIdentityValue(identity, resource.schema, context);\n\t}\n\n\tswitch (resource.kind) {\n\t\tcase 'engine':\n\t\tcase 'database':\n\t\t\treturn;\n\t\tcase 'schema':\n\t\t\taddConcreteIdentityValue(identity, 'schema', resource.name);\n\t\t\treturn;\n\t\tcase 'table':\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'table', resource.name);\n\t\t\tbreak;\n\t\tcase 'column':\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'column', resource.name);\n\t\t\tif (resource.qualifiedBy?.[0]) {\n\t\t\t\taddConcreteIdentityValue(identity, 'table', resource.qualifiedBy[0]);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'check-constraint':\n\t\tcase 'constraint':\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'constraint', resource.name);\n\t\t\tif (resource.qualifiedBy?.[0]) {\n\t\t\t\taddConcreteIdentityValue(identity, 'table', resource.qualifiedBy[0]);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'index':\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'index', resource.name);\n\t\t\tif (resource.qualifiedBy?.[0]) {\n\t\t\t\taddConcreteIdentityValue(identity, 'table', resource.qualifiedBy[0]);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'type':\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'type', resource.name);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\taddConcreteIdentityValue(identity, 'resourceKind', resource.kind);\n\t\t\taddConcreteIdentityValue(identity, 'name', resource.name);\n\t\t\tif (resource.qualifiedBy) {\n\t\t\t\taddConcreteIdentityValue(identity, 'qualifiedBy', resource.qualifiedBy);\n\t\t\t}\n\t}\n}\n\nfunction addRequestDetailIdentity(\n\tidentity: Map<string, Set<string>>,\n\tdetail: ObservationRequest['detail'],\n\tcontext: ObservationContext,\n): void {\n\tif (!isJsonObject(detail)) {\n\t\treturn;\n\t}\n\tfor (const [field, value] of Object.entries(detail)) {\n\t\tif (!DETAIL_TARGET_IDENTITY_FIELDS.has(field)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (field === 'schema') {\n\t\t\taddSchemaIdentityValue(identity, value, context);\n\t\t} else if (field === 'database') {\n\t\t\taddDatabaseIdentityValue(identity, value, context);\n\t\t} else {\n\t\t\taddConcreteIdentityValue(identity, field, value);\n\t\t}\n\t}\n}\n\nfunction concreteIdentityForRequest(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): ConcreteIdentity {\n\tconst identity = new Map<string, Set<string>>();\n\tfor (const resource of request.scope) {\n\t\taddResourceIdentity(identity, resource, context);\n\t}\n\taddRequestDetailIdentity(identity, request.detail, context);\n\treturn identity;\n}\n\nfunction concreteIdentityMismatch(\n\trequested: ConcreteIdentity,\n\tobserved: ConcreteIdentity,\n\toptions: { readonly ignoreResourceKind?: boolean } = {},\n): string | undefined {\n\tfor (const [field, requestedValues] of requested) {\n\t\tif (options.ignoreResourceKind && field === 'resourceKind') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst observedValues = observed.get(field);\n\t\tif (!observedValues || observedValues.size === 0) {\n\t\t\treturn field;\n\t\t}\n\t\tfor (const requestedValue of requestedValues) {\n\t\t\tif (!observedValues.has(requestedValue)) {\n\t\t\t\treturn field;\n\t\t\t}\n\t\t}\n\t\tfor (const observedValue of observedValues) {\n\t\t\tif (!requestedValues.has(observedValue)) {\n\t\t\t\treturn field;\n\t\t\t}\n\t\t}\n\t}\n\tconst requestedSchemas = requested.get('schema');\n\tconst observedSchemas = observed.get('schema');\n\tif (\n\t\t(!requestedSchemas || requestedSchemas.size === 0) &&\n\t\tobservedSchemas &&\n\t\tobservedSchemas.size > 0\n\t) {\n\t\treturn 'schema';\n\t}\n\treturn undefined;\n}\n\nfunction concreteIdentityIsEmpty(identity: ConcreteIdentity): boolean {\n\tfor (const values of identity.values()) {\n\t\tif (values.size > 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nconst SPECIFIC_TARGET_FIELDS = new Set([\n\t'column',\n\t'constraint',\n\t'index',\n\t'label',\n\t'logicalId',\n\t'object',\n\t'type',\n]);\n\nfunction hasSpecificTargetField(identity: ConcreteIdentity): boolean {\n\tfor (const field of SPECIFIC_TARGET_FIELDS) {\n\t\tif ((identity.get(field)?.size ?? 0) > 0) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nexport function observationRequestTargetsSameConcreteIdentity(\n\trequested: ObservationRequest,\n\tobserved: ObservationRequest,\n\tcontext: ObservationContext,\n): boolean {\n\tconst requestedIdentity = concreteIdentityForRequest(requested, context);\n\tif (concreteIdentityIsEmpty(requestedIdentity)) {\n\t\treturn observationRequestMatchesInContext(requested, observed, context);\n\t}\n\treturn (\n\t\trequested.kind === observed.kind &&\n\t\tconcreteIdentityMismatch(\n\t\t\trequestedIdentity,\n\t\t\tconcreteIdentityForRequest(observed, context),\n\t\t) === undefined\n\t);\n}\n\nfunction observationRequestBindsPropositionTarget(\n\tobserved: ObservationRequest,\n\tproposition: Proposition,\n\tcontext: ObservationContext,\n): boolean {\n\tconst requestedIdentity = concreteIdentityForRequest(\n\t\tobservationRequestForProposition(proposition),\n\t\tcontext,\n\t);\n\tif (concreteIdentityIsEmpty(requestedIdentity)) {\n\t\treturn observationRequestMatchesInContext(\n\t\t\tobservationRequestForProposition(proposition),\n\t\t\tobserved,\n\t\t\tcontext,\n\t\t);\n\t}\n\treturn (\n\t\tconcreteIdentityMismatch(\n\t\t\trequestedIdentity,\n\t\t\tconcreteIdentityForRequest(observed, context),\n\t\t\t{ ignoreResourceKind: hasSpecificTargetField(requestedIdentity) },\n\t\t) === undefined\n\t);\n}\n\nfunction sameResource(left: ResourceAddress, right: ResourceAddress): boolean {\n\treturn sameJson(left, right);\n}\n\nfunction resourceCovers(\n\tcarrier: ResourceAddress,\n\ttarget: ResourceAddress,\n): boolean {\n\tif (sameResource(carrier, target)) {\n\t\treturn true;\n\t}\n\treturn (\n\t\tcarrier.engine === target.engine &&\n\t\tcarrier.database === target.database &&\n\t\tcarrier.schema === target.schema &&\n\t\t(target.qualifiedBy?.includes(carrier.name) ?? false)\n\t);\n}\n\nfunction scopeCarriesProposition(\n\tcarrier: readonly ResourceAddress[],\n\ttarget: readonly ResourceAddress[],\n): boolean {\n\treturn target.every((resource) =>\n\t\tcarrier.some((candidate) => resourceCovers(candidate, resource)),\n\t);\n}\n\nfunction propositionFromClaim(\n\tclaim: BooleanEvidenceClaim,\n): Proposition | undefined {\n\tconst proposition = claim.proposition;\n\tif (isJsonObject(proposition)) {\n\t\tconst kind = proposition.kind;\n\t\tconst scope = proposition.scope;\n\t\tif (typeof kind === 'string' && Array.isArray(scope)) {\n\t\t\treturn proposition.detail === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tkind,\n\t\t\t\t\t\tscope: scope as readonly ResourceAddress[],\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind,\n\t\t\t\t\t\tscope: scope as readonly ResourceAddress[],\n\t\t\t\t\t\tdetail: proposition.detail as JsonValue,\n\t\t\t\t\t};\n\t\t}\n\t}\n\tif (claim.scope) {\n\t\treturn claim.detail === undefined\n\t\t\t? { kind: claim.kind, scope: claim.scope }\n\t\t\t: { kind: claim.kind, scope: claim.scope, detail: claim.detail };\n\t}\n\tif (claim.detail !== undefined) {\n\t\treturn { kind: claim.kind, scope: [], detail: claim.detail };\n\t}\n\treturn undefined;\n}\n\nfunction requestEnvelopeEntailsProposition(\n\trequest: ObservationRequest,\n\tclaim: BooleanEvidenceClaim,\n\tproposition: Proposition,\n): boolean {\n\tif (claim.kind !== proposition.kind) {\n\t\treturn false;\n\t}\n\tif (request.kind === proposition.kind) {\n\t\treturn observationRequestMatchesInContext(\n\t\t\tobservationRequestForProposition(proposition),\n\t\t\trequest,\n\t\t);\n\t}\n\treturn (\n\t\tsameJson(request.detail, proposition.detail) &&\n\t\tscopeCarriesProposition(request.scope, proposition.scope)\n\t);\n}\n\nexport function claimEntailsProposition(params: {\n\treadonly evidence: EvidenceObservation;\n\treadonly claim: BooleanEvidenceClaim;\n\treadonly proposition: Proposition;\n\treadonly expectedContext?: ObservationContext;\n}): boolean {\n\tconst proposition = params.expectedContext\n\t\t? normalizePropositionForContext(params.proposition, params.expectedContext)\n\t\t: params.proposition;\n\tif (params.claim.kind !== proposition.kind) {\n\t\treturn false;\n\t}\n\tif (\n\t\t!observationRequestBindsPropositionTarget(\n\t\t\tparams.evidence.request,\n\t\t\tproposition,\n\t\t\tparams.expectedContext ?? params.evidence.context,\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tconst claimProposition = propositionFromClaim(params.claim);\n\tif (claimProposition) {\n\t\tconst scope =\n\t\t\tclaimProposition.scope.length === 0\n\t\t\t\t? params.evidence.request.scope\n\t\t\t\t: claimProposition.scope;\n\t\tconst raw =\n\t\t\tclaimProposition.detail === undefined\n\t\t\t\t? { kind: claimProposition.kind, scope }\n\t\t\t\t: {\n\t\t\t\t\t\tkind: claimProposition.kind,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tdetail: claimProposition.detail,\n\t\t\t\t\t};\n\t\tconst normalized = params.expectedContext\n\t\t\t? normalizePropositionForContext(raw, params.expectedContext)\n\t\t\t: raw;\n\t\treturn sameProposition(normalized, proposition);\n\t}\n\treturn requestEnvelopeEntailsProposition(\n\t\tparams.expectedContext\n\t\t\t? normalizeObservationRequestForContext(\n\t\t\t\t\tparams.evidence.request,\n\t\t\t\t\tparams.expectedContext,\n\t\t\t\t)\n\t\t\t: params.evidence.request,\n\t\tparams.claim,\n\t\tproposition,\n\t);\n}\n\nexport function evidenceBooleanClaims(\n\tevidence: EvidenceObservation,\n): readonly BooleanEvidenceClaim[] {\n\tconst value = evidence.result.value;\n\tif (!isJsonObject(value)) {\n\t\treturn [];\n\t}\n\tconst claims = value.claims;\n\tif (Array.isArray(claims)) {\n\t\treturn claims.flatMap((claim) => {\n\t\t\tif (!isJsonObject(claim)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn typeof claim.kind === 'string' && typeof claim.holds === 'boolean'\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: claim.kind,\n\t\t\t\t\t\t\tholds: claim.holds,\n\t\t\t\t\t\t\t...(Array.isArray(claim.scope)\n\t\t\t\t\t\t\t\t? { scope: claim.scope as readonly ResourceAddress[] }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...(claim.detail !== undefined\n\t\t\t\t\t\t\t\t? { detail: claim.detail as JsonValue }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...('proposition' in claim\n\t\t\t\t\t\t\t\t? { proposition: claim.proposition }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t} as BooleanEvidenceClaim,\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t});\n\t}\n\tif (typeof value.holds === 'boolean') {\n\t\treturn [\n\t\t\tevidence.request.detail === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tkind: evidence.request.kind,\n\t\t\t\t\t\tholds: value.holds,\n\t\t\t\t\t\tscope: evidence.request.scope,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind: evidence.request.kind,\n\t\t\t\t\t\tholds: value.holds,\n\t\t\t\t\t\tscope: evidence.request.scope,\n\t\t\t\t\t\tdetail: evidence.request.detail,\n\t\t\t\t\t},\n\t\t];\n\t}\n\treturn [];\n}\n\nfunction requestMatchesObligation(\n\tobligation: ProofObligation,\n\trequest: ObservationRequest,\n\texpectedContext?: ObservationContext,\n): boolean {\n\tconst dischargeable = obligation.dischargeableBy ?? [];\n\treturn dischargeable.some((candidate) =>\n\t\texpectedContext\n\t\t\t? observationRequestTargetsSameConcreteIdentity(\n\t\t\t\t\tcandidate,\n\t\t\t\t\trequest,\n\t\t\t\t\texpectedContext,\n\t\t\t\t)\n\t\t\t: observationRequestMatchesInContext(candidate, request),\n\t);\n}\n\nexport function evidenceContextMatches(\n\tevidence: EvidenceObservation,\n\texpectedContext?: ObservationContext,\n): boolean {\n\tif (!transactionSnapshotContextMatches(evidence, expectedContext)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t!expectedContext ||\n\t\tmatchLiveObservationContext({\n\t\t\texpected: expectedContext,\n\t\t\tactual: evidence.context,\n\t\t\tlabel: 'evidence observation context',\n\t\t}).ok\n\t);\n}\n\nfunction hasTransactionBinding(context: ObservationContext): boolean {\n\treturn (\n\t\ttypeof context.transaction === 'string' &&\n\t\tcontext.transaction.trim().length > 0\n\t);\n}\n\nfunction transactionSnapshotContextMatches(\n\tevidence: EvidenceObservation,\n\texpectedContext?: ObservationContext,\n): boolean {\n\tif (evidence.stability !== 'transaction-snapshot') {\n\t\treturn true;\n\t}\n\treturn (\n\t\texpectedContext !== undefined &&\n\t\thasTransactionBinding(evidence.context) &&\n\t\thasTransactionBinding(expectedContext) &&\n\t\tevidence.context.transaction === expectedContext.transaction\n\t);\n}\n\nfunction conclusionKey(params: {\n\treadonly evidence: EvidenceObservation;\n\treadonly proposition: Proposition;\n\treadonly expectedContext?: ObservationContext;\n}): string {\n\tconst context = params.expectedContext;\n\tconst propositionRequest = observationRequestForProposition(\n\t\tparams.proposition,\n\t);\n\treturn stableJson({\n\t\trequest: context\n\t\t\t? normalizeObservationRequestForContext(propositionRequest, context)\n\t\t\t: propositionRequest,\n\t\tproposition: params.proposition,\n\t\tcontext: context ?? params.evidence.context,\n\t});\n}\n\nexport function concludeEvidenceForObligation(params: {\n\treadonly obligation: ProofObligation;\n\treadonly evidence: readonly EvidenceObservation[];\n\treadonly expectedContext?: ObservationContext;\n}): EvidenceEntailmentResult {\n\tconst proposition = params.expectedContext\n\t\t? normalizePropositionForContext(\n\t\t\t\tparams.obligation.proposition,\n\t\t\t\tparams.expectedContext,\n\t\t\t)\n\t\t: params.obligation.proposition;\n\tconst requestMatches = params.evidence.filter(\n\t\t(item) =>\n\t\t\trequestMatchesObligation(\n\t\t\t\tparams.obligation,\n\t\t\t\titem.request,\n\t\t\t\tparams.expectedContext,\n\t\t\t) && evidenceContextMatches(item, params.expectedContext),\n\t);\n\tconst entailing: {\n\t\treadonly evidence: EvidenceObservation;\n\t\treadonly holds: boolean;\n\t\treadonly key: string;\n\t}[] = [];\n\tfor (const item of requestMatches) {\n\t\tfor (const claim of evidenceBooleanClaims(item)) {\n\t\t\tif (\n\t\t\t\tclaimEntailsProposition({\n\t\t\t\t\tevidence: item,\n\t\t\t\t\tclaim,\n\t\t\t\t\tproposition,\n\t\t\t\t\t...(params.expectedContext\n\t\t\t\t\t\t? { expectedContext: params.expectedContext }\n\t\t\t\t\t\t: {}),\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tentailing.push({\n\t\t\t\t\tevidence: item,\n\t\t\t\t\tholds: claim.holds,\n\t\t\t\t\tkey: conclusionKey({\n\t\t\t\t\t\tevidence: item,\n\t\t\t\t\t\tproposition,\n\t\t\t\t\t\t...(params.expectedContext\n\t\t\t\t\t\t\t? { expectedContext: params.expectedContext }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tconst grouped = new Map<\n\t\tstring,\n\t\t{\n\t\t\treadonly trueEvidence: EvidenceObservation[];\n\t\t\treadonly falseEvidence: EvidenceObservation[];\n\t\t}\n\t>();\n\tfor (const item of entailing) {\n\t\tconst current = grouped.get(item.key) ?? {\n\t\t\ttrueEvidence: [],\n\t\t\tfalseEvidence: [],\n\t\t};\n\t\tif (item.holds) {\n\t\t\tcurrent.trueEvidence.push(item.evidence);\n\t\t} else {\n\t\t\tcurrent.falseEvidence.push(item.evidence);\n\t\t}\n\t\tgrouped.set(item.key, current);\n\t}\n\tfor (const group of grouped.values()) {\n\t\tif (group.trueEvidence.length > 0 && group.falseEvidence.length > 0) {\n\t\t\treturn {\n\t\t\t\tconclusion: 'conflicted',\n\t\t\t\tsupportedBy: [...group.trueEvidence, ...group.falseEvidence],\n\t\t\t};\n\t\t}\n\t}\n\tconst trueEvidence = entailing\n\t\t.filter((item) => item.holds)\n\t\t.map((item) => item.evidence);\n\tif (trueEvidence.length > 0) {\n\t\treturn { conclusion: 'established', supportedBy: trueEvidence };\n\t}\n\tconst falseEvidence = entailing\n\t\t.filter((item) => !item.holds)\n\t\t.map((item) => item.evidence);\n\tif (falseEvidence.length > 0) {\n\t\treturn { conclusion: 'refuted', supportedBy: falseEvidence };\n\t}\n\treturn { conclusion: 'undischarged', supportedBy: requestMatches };\n}\n","import type {\n\tEvidenceObservation,\n\tEvidenceObservationFilters,\n\tEvidenceView,\n\tObservationContext,\n\tObservationRequest,\n\tProofObligation,\n\tSemanticArtifactRef,\n} from '@dbsp/types';\nimport {\n\tconcludeEvidenceForObligation,\n\tevidenceContextMatches,\n\tnormalizeObservationRequestForContext,\n\tobservationRequestForProposition,\n\tobservationRequestMatchesInContext,\n} from './evidence-match.js';\nimport { stableJson } from './stable-json.js';\n\nfunction isJsonObject(\n\tvalue: unknown,\n): value is Readonly<Record<string, unknown>> {\n\treturn value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sameArtifact(\n\tleft: SemanticArtifactRef,\n\tright: SemanticArtifactRef,\n): boolean {\n\treturn left.id === right.id && left.version === right.version;\n}\n\nexport function minServerVersionNum(\n\trequest: ObservationRequest,\n): number | undefined {\n\tif (!isJsonObject(request.detail)) {\n\t\treturn undefined;\n\t}\n\tconst value = request.detail.minServerVersionNum;\n\treturn typeof value === 'number' && Number.isFinite(value)\n\t\t? value\n\t\t: undefined;\n}\n\nexport function normalizeMinServerVersionRequest(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): ObservationRequest {\n\tconst minimum = minServerVersionNum(request);\n\tif (minimum === undefined) {\n\t\treturn request;\n\t}\n\treturn {\n\t\t...request,\n\t\tscope: request.scope.map((resource) => ({\n\t\t\t...resource,\n\t\t\tdatabase: context.databaseId,\n\t\t})),\n\t\tdetail: {\n\t\t\t...(isJsonObject(request.detail) ? request.detail : {}),\n\t\t\tminServerVersionNum: minimum,\n\t\t},\n\t};\n}\n\nfunction minServerVersionRequestKey(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): string | undefined {\n\tconst normalized = normalizeMinServerVersionRequest(request, context);\n\tif (!isJsonObject(normalized.detail)) {\n\t\treturn undefined;\n\t}\n\tconst minimum = minServerVersionNum(normalized);\n\tif (minimum === undefined) {\n\t\treturn undefined;\n\t}\n\tconst { minServerVersionNum: _minimum, ...detail } = normalized.detail;\n\treturn stableJson({\n\t\tkind: normalized.kind,\n\t\tscope: normalized.scope,\n\t\tdetail,\n\t});\n}\n\nexport function strongestMinServerVersionRequests(\n\trequests: readonly ObservationRequest[],\n\tcontext: ObservationContext,\n): ReadonlyMap<string, ObservationRequest> {\n\tconst strongest = new Map<string, ObservationRequest>();\n\tfor (const request of requests) {\n\t\tconst key = minServerVersionRequestKey(request, context);\n\t\tif (!key) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst normalized = normalizeMinServerVersionRequest(request, context);\n\t\tconst prior = strongest.get(key);\n\t\tif (\n\t\t\t!prior ||\n\t\t\t(minServerVersionNum(normalized) ?? 0) > (minServerVersionNum(prior) ?? 0)\n\t\t) {\n\t\t\tstrongest.set(key, normalized);\n\t\t}\n\t}\n\treturn strongest;\n}\n\nexport function canonicalMinServerVersionRequest(\n\trequest: ObservationRequest,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): ObservationRequest {\n\tconst key = minServerVersionRequestKey(request, context);\n\treturn (key ? strongest.get(key) : undefined) ?? request;\n}\n\nexport function uniqueRequests(\n\trequests: readonly ObservationRequest[],\n): readonly ObservationRequest[] {\n\tconst seen = new Set<string>();\n\tconst unique: ObservationRequest[] = [];\n\tfor (const request of requests) {\n\t\tconst key = stableJson(request);\n\t\tif (seen.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(key);\n\t\tunique.push(request);\n\t}\n\treturn unique;\n}\n\nexport function canonicalProofRequestsForCandidate(\n\trequests: readonly ObservationRequest[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly ObservationRequest[] {\n\treturn uniqueRequests(\n\t\trequests.map((request) =>\n\t\t\tcanonicalMinServerVersionRequest(request, strongest, context),\n\t\t),\n\t);\n}\n\nexport function evaluationRequestsForCandidate(\n\trequests: readonly ObservationRequest[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly ObservationRequest[] {\n\treturn uniqueRequests([\n\t\t...requests.map((request) =>\n\t\t\tnormalizeMinServerVersionRequest(request, context),\n\t\t),\n\t\t...canonicalProofRequestsForCandidate(requests, strongest, context),\n\t]);\n}\n\nexport function isCanonicalMinServerVersionEvidence(\n\tevidence: EvidenceObservation,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): boolean {\n\tconst key = minServerVersionRequestKey(evidence.request, context);\n\tif (!key) {\n\t\treturn true;\n\t}\n\tconst canonical = strongest.get(key);\n\treturn (\n\t\tcanonical !== undefined &&\n\t\tstableJson(normalizeMinServerVersionRequest(evidence.request, context)) ===\n\t\t\tstableJson(canonical)\n\t);\n}\n\nexport function canonicalEvidence(\n\tevidence: readonly EvidenceObservation[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly EvidenceObservation[] {\n\treturn evidence.filter((item) =>\n\t\tisCanonicalMinServerVersionEvidence(item, strongest, context),\n\t);\n}\n\nexport function canonicalizeObligation(\n\tobligation: ProofObligation,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): ProofObligation {\n\tconst canonicalPropositionRequest = canonicalMinServerVersionRequest(\n\t\tobservationRequestForProposition(obligation.proposition),\n\t\tstrongest,\n\t\tcontext,\n\t);\n\tconst proposition =\n\t\tminServerVersionNum(canonicalPropositionRequest) === undefined\n\t\t\t? obligation.proposition\n\t\t\t: canonicalPropositionRequest.detail === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tkind: canonicalPropositionRequest.kind,\n\t\t\t\t\t\tscope: canonicalPropositionRequest.scope,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind: canonicalPropositionRequest.kind,\n\t\t\t\t\t\tscope: canonicalPropositionRequest.scope,\n\t\t\t\t\t\tdetail: canonicalPropositionRequest.detail,\n\t\t\t\t\t};\n\tconst dischargeableBy = obligation.dischargeableBy?.map((request) =>\n\t\tcanonicalMinServerVersionRequest(request, strongest, context),\n\t);\n\treturn {\n\t\t...obligation,\n\t\tproposition,\n\t\tscope:\n\t\t\tminServerVersionNum(canonicalPropositionRequest) === undefined\n\t\t\t\t? obligation.scope\n\t\t\t\t: canonicalPropositionRequest.scope,\n\t\t...(dischargeableBy ? { dischargeableBy } : {}),\n\t};\n}\n\nfunction requestObligation(request: ObservationRequest): ProofObligation {\n\tconst proposition =\n\t\trequest.detail === undefined\n\t\t\t? { kind: request.kind, scope: request.scope }\n\t\t\t: { kind: request.kind, scope: request.scope, detail: request.detail };\n\treturn {\n\t\tproposition,\n\t\tscope: request.scope,\n\t\tdischargeableBy: [request],\n\t};\n}\n\nfunction isProofObligation(\n\ttarget: ObservationRequest | ProofObligation,\n): target is ProofObligation {\n\treturn 'proposition' in target;\n}\n\nfunction filtersMatch(\n\tobservation: EvidenceObservation,\n\tfilters?: EvidenceObservationFilters,\n): boolean {\n\tif (filters?.source && observation.source !== filters.source) {\n\t\treturn false;\n\t}\n\treturn !filters?.issuer || sameArtifact(observation.issuer, filters.issuer);\n}\n\nclass CoreEvidenceView implements EvidenceView {\n\treadonly context: ObservationContext;\n\tprivate readonly evidence: readonly EvidenceObservation[];\n\tprivate readonly strongest: ReadonlyMap<string, ObservationRequest>;\n\n\tconstructor(\n\t\tevidence: readonly EvidenceObservation[],\n\t\tcontext: ObservationContext,\n\t\trequests: readonly ObservationRequest[] = [],\n\t) {\n\t\tthis.context = context;\n\t\tthis.evidence = evidence;\n\t\tthis.strongest = strongestMinServerVersionRequests(\n\t\t\t[...requests, ...evidence.map((item) => item.request)],\n\t\t\tcontext,\n\t\t);\n\t}\n\n\tnormalizeRequest(request: ObservationRequest): ObservationRequest {\n\t\tconst normalized = normalizeObservationRequestForContext(\n\t\t\trequest,\n\t\t\tthis.context,\n\t\t);\n\t\treturn canonicalMinServerVersionRequest(\n\t\t\tnormalized,\n\t\t\tthis.strongest,\n\t\t\tthis.context,\n\t\t);\n\t}\n\n\tobservationsFor(\n\t\trequest: ObservationRequest,\n\t\tfilters?: EvidenceObservationFilters,\n\t): readonly EvidenceObservation[] {\n\t\tconst normalized = this.normalizeRequest(request);\n\t\treturn this.evidence.filter(\n\t\t\t(observation) =>\n\t\t\t\tfiltersMatch(observation, filters) &&\n\t\t\t\tisCanonicalMinServerVersionEvidence(\n\t\t\t\t\tobservation,\n\t\t\t\t\tthis.strongest,\n\t\t\t\t\tthis.context,\n\t\t\t\t) &&\n\t\t\t\tevidenceContextMatches(observation, this.context) &&\n\t\t\t\tobservationRequestMatchesInContext(\n\t\t\t\t\tnormalized,\n\t\t\t\t\tobservation.request,\n\t\t\t\t\tthis.context,\n\t\t\t\t),\n\t\t);\n\t}\n\n\tclaimHolds(target: ObservationRequest | ProofObligation) {\n\t\tconst obligation = canonicalizeObligation(\n\t\t\tisProofObligation(target) ? target : requestObligation(target),\n\t\t\tthis.strongest,\n\t\t\tthis.context,\n\t\t);\n\t\treturn concludeEvidenceForObligation({\n\t\t\tobligation,\n\t\t\tevidence: canonicalEvidence(this.evidence, this.strongest, this.context),\n\t\t\texpectedContext: this.context,\n\t\t});\n\t}\n}\n\nexport function createEvidenceView(params: {\n\treadonly evidence: readonly EvidenceObservation[];\n\treadonly context: ObservationContext;\n\treadonly requests?: readonly ObservationRequest[];\n}): EvidenceView {\n\treturn new CoreEvidenceView(params.evidence, params.context, params.requests);\n}\n","import type {\n\tAdvisoryObservation,\n\tApplicableAssessment,\n\tAssumption,\n\tClaimId,\n\tCompareOutcome,\n\tContextFact,\n\tEvidenceObservation,\n\tInapplicableAssessment,\n\tIssuedObservation,\n\tModelIR,\n\tObservationContext,\n\tObservationIssuer,\n\tObservationRequest,\n\tOperationEffectAssessment,\n\tOutcomeReason,\n\tPhysicalOperation,\n\tPlanAssessment,\n\tProofClaim,\n\tProofClaimDraft,\n\tProofObligation,\n\tProposition,\n\tProvenApplyGuard,\n\tProvenPlanShape,\n\tRecognitionResult,\n\tResourceAddress,\n\tResourceSelector,\n\tRuleRef,\n\tSemanticArtifactRef,\n\tTransitionCandidate,\n\tTransitionFragment,\n\tTransitionLessor,\n\tTransitionRule,\n\tTransitionSessionClient,\n\tUnknownTransitionRecognition,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport { transitionCompareCurrentModel } from './comparator.js';\nimport {\n\ttype CompositionOperation,\n\tcomposeOperations,\n\ttransitionCompositionFactKey,\n} from './composer.js';\nimport { matchLiveObservationContext } from './context-match.js';\nimport { createEvidenceView } from './evidence-access.js';\nimport {\n\tconcludeEvidenceForObligation,\n\tobservationRequestForProposition,\n\tsameObservationRequest,\n} from './evidence-match.js';\nimport { assumptionId, claimId, semanticArtifactId } from './ids.js';\nimport type { EstablishedProofClaim, ProveOutcome, Prover } from './index.js';\nimport { mintInProcessPlan } from './minting.js';\nimport type { PackRegistry, RegisteredOperationSemantics } from './registry.js';\nimport { stableJson } from './stable-json.js';\nimport {\n\tacquireTransitionLease,\n\tisTransitionLessor,\n\ttype TransitionLease,\n\ttype TransitionLeaseFailure,\n\ttransitionLessorRejectionAssessment,\n} from './transition-lessor.js';\nimport { validateTransitionRelationalInvariants } from './validation.js';\n\nconst PROVER_ARTIFACT: SemanticArtifactRef = {\n\tid: semanticArtifactId('dbsp.core.transition.prover'),\n\tversion: '0.1.0',\n};\n\nconst NON_TRANSACTIONAL_SEGMENT_ASSUMPTION_ID = assumptionId(\n\t'dbsp.core.transition.prover.non-transactional-segment',\n);\n\nconst DECLARABLE_KINDS = new Set([\n\t'table',\n\t'column',\n\t'index',\n\t'constraint',\n\t'enum',\n\t'sequence',\n\t'extension',\n]);\n\nfunction declarableKind(\n\tkind: string,\n): import('@dbsp/types').DeclarableKind | undefined {\n\tif (kind === 'check-constraint') return 'constraint';\n\tif (kind === 'type') return 'enum';\n\treturn DECLARABLE_KINDS.has(kind)\n\t\t? (kind as import('@dbsp/types').DeclarableKind)\n\t\t: undefined;\n}\n\nfunction claimAddressFromSelector(\n\tselector: ResourceSelector,\n\tcontext: ObservationContext,\n): import('@dbsp/types').ManagedStepClaimMaterial['address'] | undefined {\n\tif (!selector.kind || !selector.name) return undefined;\n\tconst kind = declarableKind(selector.kind);\n\tif (!kind) return undefined;\n\tconst parent = selector.within;\n\tconst schema = selector.schema ?? parent?.schema ?? context.targetSchema;\n\tif (kind !== 'extension' && !schema) return undefined;\n\treturn {\n\t\tengine: context.engine,\n\t\tdatabase: context.databaseId,\n\t\t...(kind === 'extension' ? {} : { schema }),\n\t\t...(parent === undefined ? {} : { parent }),\n\t\tkind,\n\t\tname: selector.name,\n\t\tscope: kind === 'extension' ? 'database' : 'schema',\n\t};\n}\n\n/**\n * A managed claim is deliberately derived only while the plan is being\n * proved. The executor receives this immutable material and never parses SQL\n * or re-renders an operation to recover it.\n */\nfunction managedClaimMaterial(\n\truntime: RegisteredOperationSemantics,\n\toperation: PhysicalOperation,\n\tcontext: ObservationContext,\n): import('@dbsp/types').ManagedStepClaimMaterial | undefined {\n\tif (runtime.executionContractEligibility?.eligible !== true) return undefined;\n\tif (!runtime.renderPlanSql) return undefined;\n\tconst sql = runtime.renderPlanSql(operation, context);\n\tif (!sql.trim()) return undefined;\n\tconst effects = runtime.effectsOf(operation, context).effects;\n\tconst writes = effects.writes;\n\tconst addresses = writes\n\t\t.map((write) => claimAddressFromSelector(write, context))\n\t\t.filter(\n\t\t\t(\n\t\t\t\taddress,\n\t\t\t): address is import('@dbsp/types').ManagedStepClaimMaterial['address'] =>\n\t\t\t\taddress !== undefined,\n\t\t);\n\tif (addresses.length !== 1) return undefined;\n\tconst address = addresses[0];\n\tif (!address) return undefined;\n\tconst readsAddress = effects.reads\n\t\t.map((read) => claimAddressFromSelector(read, context))\n\t\t.some((read) => read !== undefined && sameLedgerAddress(address, read));\n\treturn {\n\t\tclaimId: claimId(`dbsp.transition.plan.${operation.ref}`),\n\t\tplannedClaimKey: `step:${operation.ref}/root`,\n\t\taddress,\n\t\tclaimKind: 'intent',\n\t\tstatementBundle: { statements: [{ ordinal: 0, sql }] },\n\t\trequiresVacancy: !readsAddress,\n\t};\n}\n\nfunction sameArtifact(\n\tleft: SemanticArtifactRef,\n\tright: SemanticArtifactRef,\n): boolean {\n\treturn left.id === right.id && left.version === right.version;\n}\n\nfunction blockedAssessment(reason: OutcomeReason): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'replan-required',\n\t\treasons: [reason],\n\t};\n}\n\nfunction inapplicableAssessment(reason: OutcomeReason): InapplicableAssessment {\n\treturn {\n\t\tdecision: 'inapplicable',\n\t\tassurance: 'established',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'none',\n\t\treasons: [reason],\n\t};\n}\n\nfunction applicableAssessment(\n\tclaim: ClaimId,\n\tassumptions: readonly Assumption[],\n): ApplicableAssessment {\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance:\n\t\t\tassumptions.length === 0 ? 'established' : 'accepted-under-assumptions',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'none',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'proven-applicable',\n\t\t\t\tclaim,\n\t\t\t\tscope: [],\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction equivalenceContextFromObservation(context: ObservationContext) {\n\tconst searchPath = context.searchPath;\n\tconst targetSchema = (context as { readonly targetSchema?: string })\n\t\t.targetSchema;\n\treturn {\n\t\tengine: context.engine,\n\t\t...(context.databaseId ? { databaseId: context.databaseId } : {}),\n\t\t...(targetSchema ? { targetSchema } : {}),\n\t\t...(searchPath ? { searchPath } : {}),\n\t\tproofObservationContext: context,\n\t};\n}\n\nfunction uncomposable(\n\tfragments: readonly TransitionFragment[],\n\tdetail: string,\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'uncomposable',\n\t\tfragments: fragments.map((fragment) => fragment.generatedBy),\n\t\tscope: [],\n\t\tdetail,\n\t});\n}\n\nfunction uncomposableCandidates(\n\tcandidates: readonly TransitionCandidate[],\n\tdetail: string,\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'uncomposable',\n\t\tfragments: candidateRefs(candidates),\n\t\tscope: [],\n\t\tdetail,\n\t});\n}\n\nfunction unsupportedCompositionRequirement(\n\tdetail: string,\n\tchanges: readonly ResourceAddress[],\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'unsupported-transition',\n\t\tchanges,\n\t\tscope: changes,\n\t\tdetail,\n\t});\n}\n\nfunction artifactMismatch(\n\tartifact: SemanticArtifactRef,\n\tfact: string,\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'context-mismatch',\n\t\tartifact,\n\t\tfact: { key: 'semantic-artifact', value: fact },\n\t\tscope: [],\n\t});\n}\n\nfunction unsupported(\n\tcompare: Extract<CompareOutcome, { kind: 'unsupported' }>,\n) {\n\treturn blockedAssessment({\n\t\tcode: 'unsupported-transition',\n\t\tchanges: compare.changes,\n\t\tscope: compare.changes,\n\t});\n}\n\nfunction ambiguous(compare: Extract<CompareOutcome, { kind: 'ambiguous' }>) {\n\treturn blockedAssessment({\n\t\tcode: 'ambiguous-rule',\n\t\tcandidates: compare.candidates,\n\t\tscope: [],\n\t});\n}\n\nfunction uncomposableCompare(\n\tcompare: Extract<CompareOutcome, { kind: 'uncomposable' }>,\n) {\n\treturn blockedAssessment({\n\t\tcode: 'uncomposable',\n\t\tfragments: [\n\t\t\t...candidateRefs(compare.candidates),\n\t\t\t...compare.recognitions.map((recognition) => recognition.rule),\n\t\t],\n\t\tscope: [],\n\t\tdetail: compare.detail,\n\t});\n}\n\nfunction uniqueAssumptions(\n\tassumptions: readonly Assumption[],\n): readonly Assumption[] {\n\tconst seen = new Map<string, Assumption>();\n\tconst unique: Assumption[] = [];\n\tfor (const assumption of assumptions) {\n\t\tconst prior = seen.get(assumption.id);\n\t\tif (prior) {\n\t\t\tif (stableJson(prior) !== stableJson(assumption)) {\n\t\t\t\tthrow new Error(`conflicting assumption id ${assumption.id}`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tseen.set(assumption.id, assumption);\n\t\tunique.push(assumption);\n\t}\n\treturn unique;\n}\n\nfunction uniqueAssumptionIds(\n\tassumptionIds: readonly Assumption['id'][],\n): readonly Assumption['id'][] {\n\tconst seen = new Set<string>();\n\tconst unique: Assumption['id'][] = [];\n\tfor (const assumptionId of assumptionIds) {\n\t\tif (seen.has(assumptionId)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(assumptionId);\n\t\tunique.push(assumptionId);\n\t}\n\treturn unique;\n}\n\nfunction nonTransactionalSegmentAssumption(\n\toperations: readonly CompositionOperation[],\n\tsegments: ProvenPlanShape['segments'],\n): Assumption | undefined {\n\tconst nonTransactionalStepIds = new Set(\n\t\tsegments\n\t\t\t.filter((segment) => segment.transaction === 'forbids-transaction')\n\t\t\t.flatMap((segment) => segment.stepIds),\n\t);\n\tif (nonTransactionalStepIds.size === 0) return undefined;\n\tconst scopeByResource = new Map<string, ResourceAddress>();\n\tfor (const entry of operations) {\n\t\tif (!nonTransactionalStepIds.has(`step:${entry.operation.ref}`)) continue;\n\t\tfor (const assumption of entry.effects.restsOn) {\n\t\t\tfor (const resource of assumption.scope) {\n\t\t\t\tscopeByResource.set(stableJson(resource), resource);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tid: NON_TRANSACTIONAL_SEGMENT_ASSUMPTION_ID,\n\t\tclass: 'non-transactional-segment',\n\t\tasserter: { kind: 'pack', artifact: PROVER_ARTIFACT },\n\t\tstatement:\n\t\t\t'The plan contains a segment that must execute outside a transaction block.',\n\t\tscope: [...scopeByResource.values()],\n\t};\n}\n\nfunction stepAssumptionClosure(params: {\n\treadonly effects: OperationEffectAssessment;\n\treadonly requiredClaims: readonly ProofClaim[];\n\treadonly allClaims: readonly ProofClaim[];\n\treadonly guards: readonly ProvenApplyGuard[];\n}): readonly Assumption['id'][] {\n\tconst claimById = new Map(params.allClaims.map((claim) => [claim.id, claim]));\n\tconst assumptionIds: Assumption['id'][] = [\n\t\t...params.effects.restsOn.map((assumption) => assumption.id),\n\t\t...params.requiredClaims.flatMap((claim) => [...claim.assumes]),\n\t];\n\tfor (const guard of params.guards) {\n\t\tconst binding = guard.protocol.binding;\n\t\tif (!binding) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (binding.kind === 'external-ddl-exclusion') {\n\t\t\tassumptionIds.push(binding.assumption);\n\t\t\tcontinue;\n\t\t}\n\t\tif (binding.kind === 'stable-identity') {\n\t\t\tconst identityClaim = claimById.get(binding.identityClaim);\n\t\t\tif (identityClaim) {\n\t\t\t\tassumptionIds.push(...identityClaim.assumes);\n\t\t\t}\n\t\t}\n\t}\n\treturn uniqueAssumptionIds(assumptionIds);\n}\n\nfunction operationPackSemanticsMissing(\n\teffects: ReturnType<RegisteredOperationSemantics['effectsOf']>,\n\toperation: PhysicalOperation,\n): boolean {\n\treturn !effects.restsOn.some(\n\t\t(assumption) =>\n\t\t\tassumption.class === 'operation-pack-semantics' &&\n\t\t\tassumption.asserter.kind === 'pack' &&\n\t\t\tsameArtifact(\n\t\t\t\tassumption.asserter.artifact,\n\t\t\t\toperation.operationKind.artifact,\n\t\t\t),\n\t);\n}\n\nfunction operationEffects(\n\tsemantics: RegisteredOperationSemantics,\n\toperation: PhysicalOperation,\n\tcontext: ObservationContext,\n) {\n\treturn semantics.effectsOf(operation, context);\n}\n\nfunction isJsonObject(\n\tvalue: unknown,\n): value is Readonly<Record<string, unknown>> {\n\treturn value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nclass ObservationContextMismatchError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'ObservationContextMismatchError';\n\t}\n}\n\nfunction verifyCapturedTargetIdentity(\n\texpected: ObservationContext,\n\tactual: ObservationContext,\n): void {\n\tif (expected.postgresqlTargetIdentity === undefined) return;\n\tif (\n\t\tstableJson(expected.postgresqlTargetIdentity) !==\n\t\tstableJson(actual.postgresqlTargetIdentity)\n\t) {\n\t\tthrow new ObservationContextMismatchError(\n\t\t\t'proof observation target identity does not match the target captured before evidence collection',\n\t\t);\n\t}\n}\n\ntype IssuedObservationValidationResult =\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly detail: string };\n\nfunction validateIssuedObservation(\n\tobservation: IssuedObservation,\n\tcontext: ObservationContext,\n): IssuedObservationValidationResult {\n\tconst contextMatch = matchLiveObservationContext({\n\t\texpected: context,\n\t\tactual: observation.context,\n\t\tlabel: `observation ${observation.id} context`,\n\t});\n\tif (!contextMatch.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: contextMatch.detail,\n\t\t};\n\t}\n\tconst role = (observation as { readonly role?: unknown }).role;\n\tif (role === 'evidence') {\n\t\tconst evidence = observation as EvidenceObservation;\n\t\tif (\n\t\t\ttypeof evidence.source !== 'string' ||\n\t\t\t!isJsonObject(evidence.validity) ||\n\t\t\t!Array.isArray(evidence.validity.invalidatedBy)\n\t\t) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `evidence observation ${evidence.id} has an invalid evidence source/validity shape`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true };\n\t}\n\tif (role === 'advisory') {\n\t\tconst advisory = observation as AdvisoryObservation;\n\t\tif ('source' in advisory) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `advisory observation ${advisory.id} must not carry an evidence source`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true };\n\t}\n\treturn {\n\t\tok: false,\n\t\tdetail: `observation ${\n\t\t\t(observation as { readonly id?: string }).id ?? 'unknown'\n\t\t} has an invalid role`,\n\t};\n}\n\nasync function checkoutProofClient(\n\ttarget: TransitionLessor,\n): Promise<TransitionLease> {\n\treturn acquireTransitionLease(target);\n}\n\ntype DurableConclusion = 'established' | 'undischarged' | 'refuted';\n\nfunction conclusionForObligation(\n\tobligation: ProofObligation,\n\tevidence: readonly EvidenceObservation[],\n\texpectedContext?: ObservationContext,\n): {\n\treadonly conclusion: DurableConclusion;\n\treadonly supportedBy: readonly EvidenceObservation[];\n} {\n\tconst result = concludeEvidenceForObligation({\n\t\tobligation,\n\t\tevidence,\n\t\t...(expectedContext ? { expectedContext } : {}),\n\t});\n\tif (result.conclusion === 'conflicted') {\n\t\treturn {\n\t\t\tconclusion: 'undischarged',\n\t\t\tsupportedBy: result.supportedBy,\n\t\t};\n\t}\n\treturn {\n\t\tconclusion: result.conclusion,\n\t\tsupportedBy: result.supportedBy,\n\t};\n}\n\nfunction proofClaimForObligation(\n\tobligation: ProofObligation,\n\tevidence: readonly EvidenceObservation[],\n\tindex: number,\n\tsemantics: SemanticArtifactRef,\n\texpectedContext?: ObservationContext,\n): ProofClaim {\n\tconst { conclusion, supportedBy } = conclusionForObligation(\n\t\tobligation,\n\t\tevidence,\n\t\texpectedContext,\n\t);\n\tconst id = claimId(\n\t\t`dbsp.transition.claim.${index}.${obligation.proposition.kind}`,\n\t);\n\tconst supportedByIds = supportedBy.map((item) => item.id);\n\tif (conclusion === 'established') {\n\t\treturn {\n\t\t\tid,\n\t\t\tproposition: obligation.proposition,\n\t\t\tscope: obligation.scope,\n\t\t\tsupportedBy: supportedByIds,\n\t\t\tassumes: [],\n\t\t\tsemantics: [semantics],\n\t\t\tderivedBy: {\n\t\t\t\tsemantics,\n\t\t\t\tinputs: supportedByIds,\n\t\t\t\tproposition: obligation.proposition,\n\t\t\t\tconclusion,\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tid,\n\t\tproposition: obligation.proposition,\n\t\tscope: obligation.scope,\n\t\tsupportedBy: supportedByIds,\n\t\tassumes: [],\n\t\tsemantics: [semantics],\n\t\tderivedBy: {\n\t\t\tsemantics,\n\t\t\tinputs: supportedByIds,\n\t\t\tproposition: obligation.proposition,\n\t\t\tconclusion,\n\t\t},\n\t};\n}\n\nfunction proofClaimForDraft(draft: ProofClaimDraft, index: number): ProofClaim {\n\tconst supportedBy = [...(draft.supportedBy ?? [])];\n\tconst assumptions = [...(draft.assumes ?? [])];\n\tconst conclusion =\n\t\tdraft.conclusion === 'established' && assumptions.length > 0\n\t\t\t? 'established-under-assumptions'\n\t\t\t: draft.conclusion;\n\tconst id = claimId(\n\t\t`dbsp.transition.claim.draft.${index}.${draft.proposition.kind}.${stableJson(\n\t\t\t{\n\t\t\t\tconclusion,\n\t\t\t\tproposition: draft.proposition,\n\t\t\t\tsemantics: draft.semantics,\n\t\t\t},\n\t\t)}`,\n\t);\n\tif (conclusion === 'established') {\n\t\treturn {\n\t\t\tid,\n\t\t\tproposition: draft.proposition,\n\t\t\tscope: draft.scope,\n\t\t\tsupportedBy,\n\t\t\tassumes: [],\n\t\t\tsemantics: [draft.semantics],\n\t\t\tderivedBy: {\n\t\t\t\tsemantics: draft.semantics,\n\t\t\t\tinputs: supportedBy,\n\t\t\t\tproposition: draft.proposition,\n\t\t\t\tconclusion,\n\t\t\t},\n\t\t};\n\t}\n\tif (conclusion === 'established-under-assumptions') {\n\t\tif (assumptions.length === 0) {\n\t\t\tthrow new Error('established-under-assumptions claim lacks assumptions');\n\t\t}\n\t\treturn {\n\t\t\tid,\n\t\t\tproposition: draft.proposition,\n\t\t\tscope: draft.scope,\n\t\t\tsupportedBy,\n\t\t\tassumes: assumptions as [\n\t\t\t\tProofClaim['assumes'][number],\n\t\t\t\t...ProofClaim['assumes'][number][],\n\t\t\t],\n\t\t\tsemantics: [draft.semantics],\n\t\t\tderivedBy: {\n\t\t\t\tsemantics: draft.semantics,\n\t\t\t\tinputs: supportedBy,\n\t\t\t\tproposition: draft.proposition,\n\t\t\t\tconclusion,\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tid,\n\t\tproposition: draft.proposition,\n\t\tscope: draft.scope,\n\t\tsupportedBy,\n\t\tassumes: assumptions,\n\t\tsemantics: [draft.semantics],\n\t\tderivedBy: {\n\t\t\tsemantics: draft.semantics,\n\t\t\tinputs: supportedBy,\n\t\t\tproposition: draft.proposition,\n\t\t\tconclusion,\n\t\t},\n\t};\n}\n\nfunction missingEvidenceAssessment(\n\tobligation: ProofObligation,\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'insufficient-evidence',\n\t\tobligation,\n\t\tscope: obligation.scope,\n\t});\n}\n\nfunction refutedClaimDetail(claim: ProofClaim): string {\n\tconst detail = claim.proposition.detail;\n\treturn typeof detail === 'string' ? detail : claim.proposition.kind;\n}\n\nfunction refutedAssessment(claim: ProofClaim): InapplicableAssessment {\n\treturn inapplicableAssessment({\n\t\tcode: 'proven-inapplicable',\n\t\tclaim: claim.id,\n\t\tscope: claim.scope,\n\t\tdetail: refutedClaimDetail(claim),\n\t});\n}\n\nasync function issueObservations(\n\tissuer: ObservationIssuer | undefined,\n\trequests: readonly ObservationRequest[],\n\ttarget: TransitionSessionClient,\n\tcontext: ObservationContext,\n\tissuedRequestKeys: Set<string> = new Set(),\n): Promise<{\n\treadonly evidence: readonly EvidenceObservation[];\n\treadonly advisory: readonly AdvisoryObservation[];\n}> {\n\tif (!issuer) {\n\t\treturn { evidence: [], advisory: [] };\n\t}\n\tconst uniqueRequests = requests.filter((request) => {\n\t\tconst key = stableJson({ issuer: issuer.artifact, request });\n\t\tif (issuedRequestKeys.has(key)) {\n\t\t\treturn false;\n\t\t}\n\t\tissuedRequestKeys.add(key);\n\t\treturn true;\n\t});\n\tconst issued: (EvidenceObservation | AdvisoryObservation)[] = [];\n\tfor (const request of uniqueRequests) {\n\t\tconst observation = await issuer.execute(request, target, context);\n\t\tconst validation = validateIssuedObservation(observation, context);\n\t\tif (!validation.ok) {\n\t\t\tthrow new ObservationContextMismatchError(validation.detail);\n\t\t}\n\t\tissued.push(observation);\n\t}\n\treturn {\n\t\tevidence: issued.filter(\n\t\t\t(observation): observation is EvidenceObservation =>\n\t\t\t\tobservation.role === 'evidence',\n\t\t),\n\t\tadvisory: issued.filter(\n\t\t\t(observation): observation is AdvisoryObservation =>\n\t\t\t\tobservation.role === 'advisory',\n\t\t),\n\t};\n}\n\nfunction establishedNoDriftClaim(\n\tcompare: Extract<CompareOutcome, { kind: 'no-drift' }>,\n): EstablishedProofClaim {\n\treturn {\n\t\tid: claimId('dbsp.transition.claim.no-drift'),\n\t\tproposition: compare.claimedInvariant,\n\t\tscope: compare.claimedInvariant.scope,\n\t\tsupportedBy: [],\n\t\tassumes: [],\n\t\tsemantics: [PROVER_ARTIFACT],\n\t\tderivedBy: {\n\t\t\tsemantics: PROVER_ARTIFACT,\n\t\t\tinputs: [],\n\t\t\tproposition: compare.claimedInvariant,\n\t\t\tconclusion: 'established',\n\t\t},\n\t};\n}\n\nfunction establishedNoDriftClaimFromDraft(\n\tdraft: ProofClaimDraft<'established'>,\n\tindex: number,\n): EstablishedProofClaim {\n\tconst claim = proofClaimForDraft(draft, index);\n\tif (\n\t\tclaim.derivedBy.conclusion !== 'established' ||\n\t\tclaim.assumes.length !== 0\n\t) {\n\t\tthrow new Error(\n\t\t\t'no-drift recognition did not produce an established claim',\n\t\t);\n\t}\n\treturn claim as EstablishedProofClaim;\n}\n\nfunction candidateRefs(\n\tcandidates: readonly TransitionCandidate[],\n): readonly RuleRef[] {\n\treturn candidates.map((candidate) => candidate.rule);\n}\n\nfunction requestToObligation(\n\trequest: ObservationRequest,\n\tappliesTo?: string,\n): ProofObligation {\n\tconst propositionBase = {\n\t\tkind: request.kind,\n\t\tscope: request.scope,\n\t};\n\tconst proposition: Proposition =\n\t\trequest.detail === undefined\n\t\t\t? propositionBase\n\t\t\t: { ...propositionBase, detail: request.detail };\n\tconst obligation: ProofObligation = {\n\t\tproposition,\n\t\tscope: request.scope,\n\t\tdischargeableBy: [request],\n\t};\n\treturn appliesTo ? { ...obligation, appliesTo } : obligation;\n}\n\nfunction candidateFromRecognition(\n\trule: TransitionRule,\n\tresult: Extract<RecognitionResult<unknown>, { readonly recognized: true }>,\n): TransitionCandidate {\n\tconst requiredObservations = rule.requiredObservations(result.match);\n\tconst ref = { id: rule.id, pack: rule.artifact };\n\tconst candidate = {\n\t\trule: ref,\n\t\tmatch: result.match,\n\t\trequiredObservations,\n\t\tobligations: requiredObservations.map((request) =>\n\t\t\trequestToObligation(request),\n\t\t),\n\t\tselectionRationale: {\n\t\t\tchosen: ref,\n\t\t\toverRules: [ref],\n\t\t\twhy: 'recognized transition rule after discharging recognition obligations',\n\t\t},\n\t};\n\treturn result.claimDrafts\n\t\t? { ...candidate, claimDrafts: result.claimDrafts }\n\t\t: candidate;\n}\n\ntype ObservationIssueState = {\n\treadonly issuer: ObservationIssuer;\n\treadonly client: TransitionSessionClient;\n\treadonly proofContext: ObservationContext;\n\treadonly issuedRequestKeys: Set<string>;\n\treadonly evidence: readonly EvidenceObservation[];\n\treadonly advisory: readonly AdvisoryObservation[];\n};\n\nfunction appendIssued(\n\tleft: {\n\t\treadonly evidence: readonly EvidenceObservation[];\n\t\treadonly advisory: readonly AdvisoryObservation[];\n\t},\n\tright: {\n\t\treadonly evidence: readonly EvidenceObservation[];\n\t\treadonly advisory: readonly AdvisoryObservation[];\n\t},\n) {\n\treturn {\n\t\tevidence: [...left.evidence, ...right.evidence],\n\t\tadvisory: [...left.advisory, ...right.advisory],\n\t};\n}\n\nfunction appendUniqueEvidence(\n\ttarget: EvidenceObservation[],\n\tseen: Map<string, EvidenceObservation>,\n\tevidence: readonly EvidenceObservation[],\n): string | undefined {\n\tfor (const observation of evidence) {\n\t\tconst prior = seen.get(observation.id);\n\t\tif (prior) {\n\t\t\tif (stableJson(prior) !== stableJson(observation)) {\n\t\t\t\treturn `duplicate observation id ${observation.id} has conflicting results`;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tseen.set(observation.id, observation);\n\t\ttarget.push(observation);\n\t}\n\treturn undefined;\n}\n\nfunction appendUniqueClaims(\n\ttarget: ProofClaim[],\n\tseen: Map<string, ProofClaim>,\n\tclaims: readonly ProofClaim[],\n): string | undefined {\n\tfor (const claim of claims) {\n\t\tconst prior = seen.get(claim.id);\n\t\tif (prior) {\n\t\t\tif (stableJson(prior) !== stableJson(claim)) {\n\t\t\t\treturn `duplicate claim id ${claim.id} has conflicting claims`;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tseen.set(claim.id, claim);\n\t\ttarget.push(claim);\n\t}\n\treturn undefined;\n}\n\nfunction firstRefutedRecognitionClaim(\n\tresult: Extract<RecognitionResult<unknown>, { readonly recognized: false }>,\n): ProofClaim | undefined {\n\tconst claimDrafts = (\n\t\tresult as { readonly claimDrafts?: readonly ProofClaimDraft[] }\n\t).claimDrafts;\n\tconst draft = claimDrafts?.find(\n\t\t(candidate): candidate is ProofClaimDraft<'refuted'> =>\n\t\t\tcandidate.conclusion === 'refuted',\n\t);\n\treturn draft ? proofClaimForDraft(draft, 0) : undefined;\n}\n\nfunction recognitionResultWithEvidenceSupport<\n\tT extends RecognitionResult<unknown>,\n>(result: T, evidence: readonly EvidenceObservation[]): T {\n\tconst evidenceIds = evidence.map((item) => item.id);\n\tif (result.recognized === 'no-drift' && evidenceIds.length > 0) {\n\t\treturn {\n\t\t\t...result,\n\t\t\tclaimDraft: {\n\t\t\t\t...result.claimDraft,\n\t\t\t\tsupportedBy: [\n\t\t\t\t\t...new Set([\n\t\t\t\t\t\t...(result.claimDraft.supportedBy ?? []),\n\t\t\t\t\t\t...evidenceIds,\n\t\t\t\t\t]),\n\t\t\t\t],\n\t\t\t},\n\t\t} as T;\n\t}\n\tconst claimDrafts = (\n\t\tresult as { readonly claimDrafts?: readonly ProofClaimDraft[] }\n\t).claimDrafts;\n\tif (evidenceIds.length === 0 || !claimDrafts?.length) {\n\t\treturn result;\n\t}\n\treturn {\n\t\t...result,\n\t\tclaimDrafts: claimDrafts.map((draft) => ({\n\t\t\t...draft,\n\t\t\tsupportedBy: [...new Set([...(draft.supportedBy ?? []), ...evidenceIds])],\n\t\t})),\n\t} as T;\n}\n\nfunction parseVersion(value: string): readonly number[] {\n\tconst trimmed = value.trim();\n\tif (/^\\d+$/.test(trimmed) && trimmed.length >= 5) {\n\t\tconst serverVersionNum = Number.parseInt(trimmed, 10);\n\t\tif (Number.isFinite(serverVersionNum)) {\n\t\t\treturn [\n\t\t\t\tMath.trunc(serverVersionNum / 10_000),\n\t\t\t\tMath.trunc((serverVersionNum % 10_000) / 100),\n\t\t\t\tserverVersionNum % 100,\n\t\t\t];\n\t\t}\n\t}\n\treturn trimmed\n\t\t.split(/[.-]/)\n\t\t.map((part) => Number.parseInt(part, 10))\n\t\t.filter((part) => Number.isFinite(part));\n}\n\nfunction compareVersions(left: string, right: string): number {\n\tconst leftParts = parseVersion(left);\n\tconst rightParts = parseVersion(right);\n\tconst length = Math.max(leftParts.length, rightParts.length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst leftPart = leftParts[index] ?? 0;\n\t\tconst rightPart = rightParts[index] ?? 0;\n\t\tif (leftPart !== rightPart) {\n\t\t\treturn leftPart < rightPart ? -1 : 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction versionInRange(\n\tversion: string,\n\trange: TransitionRule['support']['versions'][number],\n): boolean {\n\tif (range.min && compareVersions(version, range.min) < 0) {\n\t\treturn false;\n\t}\n\tif (range.max && compareVersions(version, range.max) > 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ntype RuleSupportMismatch = {\n\treadonly detail: string;\n\treadonly fact: ContextFact;\n};\n\nfunction ruleSupportMismatch(\n\trule: TransitionRule,\n\tcontext: ObservationContext,\n): RuleSupportMismatch | undefined {\n\tif (rule.support.engine !== context.engine) {\n\t\treturn {\n\t\t\tdetail: `rule requires engine ${rule.support.engine}, got ${context.engine}`,\n\t\t\tfact: { key: 'context.engine', value: context.engine },\n\t\t};\n\t}\n\tif (\n\t\trule.support.versions.length > 0 &&\n\t\t!rule.support.versions.some((range) =>\n\t\t\tversionInRange(context.engineVersion, range),\n\t\t)\n\t) {\n\t\treturn {\n\t\t\tdetail: `rule does not support engine version ${context.engineVersion}`,\n\t\t\tfact: { key: 'context.engineVersion', value: context.engineVersion },\n\t\t};\n\t}\n\tconst missingCapabilities = rule.support.requiredCapabilities.filter(\n\t\t(capability) => !context.capabilities.includes(capability),\n\t);\n\tif (missingCapabilities.length > 0) {\n\t\tconst first = missingCapabilities[0] ?? 'unknown';\n\t\treturn {\n\t\t\tdetail: `missing required capabilities: ${missingCapabilities.join(', ')}`,\n\t\t\tfact: {\n\t\t\t\tkey: `context.capability.${first}.available`,\n\t\t\t\tvalue: 'false',\n\t\t\t},\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction supportMismatchAssessment(\n\tcandidate: TransitionCandidate,\n\tmismatch: RuleSupportMismatch,\n): InapplicableAssessment {\n\treturn inapplicableAssessment({\n\t\tcode: 'context-mismatch',\n\t\tartifact: candidate.rule.pack,\n\t\tfact: mismatch.fact,\n\t\tscope: [],\n\t\tdetail: mismatch.detail,\n\t});\n}\n\nfunction evaluationBlockedAssessment(\n\tevaluation: { readonly obligations: readonly ProofObligation[] },\n\tdetail: string,\n): PlanAssessment {\n\tconst obligation = evaluation.obligations[0];\n\tif (obligation) {\n\t\treturn missingEvidenceAssessment(obligation);\n\t}\n\treturn blockedAssessment({\n\t\tcode: 'insufficient-evidence',\n\t\tobligation: {\n\t\t\tproposition: { kind: 'unknown', scope: [] },\n\t\t\tscope: [],\n\t\t},\n\t\tscope: [],\n\t\tdetail,\n\t});\n}\n\nfunction sameObservationRequests(\n\tleft: readonly ObservationRequest[],\n\tright: readonly ObservationRequest[],\n): boolean {\n\treturn (\n\t\tleft.length === right.length &&\n\t\tleft.every((request, index) => {\n\t\t\tconst other = right[index];\n\t\t\treturn other !== undefined && sameObservationRequest(request, other);\n\t\t})\n\t);\n}\n\nfunction minServerVersionNum(request: ObservationRequest): number | undefined {\n\tif (!isJsonObject(request.detail)) {\n\t\treturn undefined;\n\t}\n\tconst value = request.detail.minServerVersionNum;\n\treturn typeof value === 'number' && Number.isFinite(value)\n\t\t? value\n\t\t: undefined;\n}\n\nfunction normalizeMinServerVersionRequest(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): ObservationRequest {\n\tconst minimum = minServerVersionNum(request);\n\tif (minimum === undefined) {\n\t\treturn request;\n\t}\n\treturn {\n\t\t...request,\n\t\tscope: request.scope.map((resource) => ({\n\t\t\t...resource,\n\t\t\tdatabase: context.databaseId,\n\t\t})),\n\t\tdetail: {\n\t\t\t...(isJsonObject(request.detail) ? request.detail : {}),\n\t\t\tminServerVersionNum: minimum,\n\t\t},\n\t};\n}\n\nfunction minServerVersionRequestKey(\n\trequest: ObservationRequest,\n\tcontext: ObservationContext,\n): string | undefined {\n\tconst normalized = normalizeMinServerVersionRequest(request, context);\n\tif (!isJsonObject(normalized.detail)) {\n\t\treturn undefined;\n\t}\n\tconst minimum = minServerVersionNum(normalized);\n\tif (minimum === undefined) {\n\t\treturn undefined;\n\t}\n\tconst { minServerVersionNum: _minimum, ...detail } = normalized.detail;\n\treturn stableJson({\n\t\tkind: normalized.kind,\n\t\tscope: normalized.scope,\n\t\tdetail,\n\t});\n}\n\nfunction strongestMinServerVersionRequests(\n\trequests: readonly ObservationRequest[],\n\tcontext: ObservationContext,\n): ReadonlyMap<string, ObservationRequest> {\n\tconst strongest = new Map<string, ObservationRequest>();\n\tfor (const request of requests) {\n\t\tconst key = minServerVersionRequestKey(request, context);\n\t\tif (!key) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst normalized = normalizeMinServerVersionRequest(request, context);\n\t\tconst prior = strongest.get(key);\n\t\tif (\n\t\t\t!prior ||\n\t\t\t(minServerVersionNum(normalized) ?? 0) > (minServerVersionNum(prior) ?? 0)\n\t\t) {\n\t\t\tstrongest.set(key, normalized);\n\t\t}\n\t}\n\treturn strongest;\n}\n\nfunction canonicalMinServerVersionRequest(\n\trequest: ObservationRequest,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): ObservationRequest {\n\tconst key = minServerVersionRequestKey(request, context);\n\treturn (key ? strongest.get(key) : undefined) ?? request;\n}\n\nfunction uniqueRequests(\n\trequests: readonly ObservationRequest[],\n): readonly ObservationRequest[] {\n\tconst seen = new Set<string>();\n\tconst unique: ObservationRequest[] = [];\n\tfor (const request of requests) {\n\t\tconst key = stableJson(request);\n\t\tif (seen.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(key);\n\t\tunique.push(request);\n\t}\n\treturn unique;\n}\n\nfunction evaluationRequestsForCandidate(\n\trequests: readonly ObservationRequest[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly ObservationRequest[] {\n\treturn uniqueRequests([\n\t\t...requests.map((request) =>\n\t\t\tnormalizeMinServerVersionRequest(request, context),\n\t\t),\n\t\t...canonicalProofRequestsForCandidate(requests, strongest, context),\n\t]);\n}\n\nfunction canonicalProofRequestsForCandidate(\n\trequests: readonly ObservationRequest[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly ObservationRequest[] {\n\treturn uniqueRequests(\n\t\trequests.map((request) =>\n\t\t\tcanonicalMinServerVersionRequest(request, strongest, context),\n\t\t),\n\t);\n}\n\nfunction isCanonicalMinServerVersionEvidence(\n\tevidence: EvidenceObservation,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): boolean {\n\tconst key = minServerVersionRequestKey(evidence.request, context);\n\tif (!key) {\n\t\treturn true;\n\t}\n\tconst canonical = strongest.get(key);\n\treturn (\n\t\tcanonical !== undefined &&\n\t\tstableJson(normalizeMinServerVersionRequest(evidence.request, context)) ===\n\t\t\tstableJson(canonical)\n\t);\n}\n\nfunction canonicalEvidence(\n\tevidence: readonly EvidenceObservation[],\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): readonly EvidenceObservation[] {\n\treturn evidence.filter((item) =>\n\t\tisCanonicalMinServerVersionEvidence(item, strongest, context),\n\t);\n}\n\nfunction canonicalizeObligation(\n\tobligation: ProofObligation,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): ProofObligation {\n\tconst canonicalPropositionRequest = canonicalMinServerVersionRequest(\n\t\tobservationRequestForProposition(obligation.proposition),\n\t\tstrongest,\n\t\tcontext,\n\t);\n\tconst proposition =\n\t\tminServerVersionNum(canonicalPropositionRequest) === undefined\n\t\t\t? obligation.proposition\n\t\t\t: canonicalPropositionRequest.detail === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tkind: canonicalPropositionRequest.kind,\n\t\t\t\t\t\tscope: canonicalPropositionRequest.scope,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind: canonicalPropositionRequest.kind,\n\t\t\t\t\t\tscope: canonicalPropositionRequest.scope,\n\t\t\t\t\t\tdetail: canonicalPropositionRequest.detail,\n\t\t\t\t\t};\n\tconst dischargeableBy = obligation.dischargeableBy?.map((request) =>\n\t\tcanonicalMinServerVersionRequest(request, strongest, context),\n\t);\n\treturn {\n\t\t...obligation,\n\t\tproposition,\n\t\tscope:\n\t\t\tminServerVersionNum(canonicalPropositionRequest) === undefined\n\t\t\t\t? obligation.scope\n\t\t\t\t: canonicalPropositionRequest.scope,\n\t\t...(dischargeableBy ? { dischargeableBy } : {}),\n\t};\n}\n\nfunction canonicalizeFragmentObligations(\n\tfragment: TransitionFragment,\n\tstrongest: ReadonlyMap<string, ObservationRequest>,\n\tcontext: ObservationContext,\n): TransitionFragment {\n\treturn {\n\t\t...fragment,\n\t\tobligations: fragment.obligations.map((obligation) =>\n\t\t\tcanonicalizeObligation(obligation, strongest, context),\n\t\t),\n\t};\n}\n\nfunction canonicalObligationClaimKey(\n\tobligation: ProofObligation,\n): string | undefined {\n\tif (\n\t\tminServerVersionNum(\n\t\t\tobservationRequestForProposition(obligation.proposition),\n\t\t) === undefined\n\t) {\n\t\treturn undefined;\n\t}\n\treturn stableJson({\n\t\tproposition: obligation.proposition,\n\t\tscope: obligation.scope,\n\t});\n}\n\nfunction fallbackUnknownObligation(\n\trecognition: UnknownTransitionRecognition,\n): ProofObligation {\n\treturn (\n\t\trecognition.obligations[0] ?? {\n\t\t\tproposition: {\n\t\t\t\tkind: 'dbsp.transition.recognition.unknown',\n\t\t\t\tscope: [],\n\t\t\t\tdetail: recognition.rule.id,\n\t\t\t},\n\t\t\tscope: [],\n\t\t}\n\t);\n}\n\ntype CompositionDeclaration = NonNullable<TransitionFragment['composition']>;\ntype CompositionProducer = NonNullable<\n\tCompositionDeclaration['produces']\n>[number];\ntype CompositionRequirement = NonNullable<\n\tCompositionDeclaration['requires']\n>[number];\n\nfunction compositionRequirementNeedsCommittedProducer(\n\trequirement: CompositionRequirement,\n\tproducer: CompositionProducer,\n): boolean {\n\treturn (\n\t\trequirement.needs === 'producer-after-commit' ||\n\t\tproducer.available === 'after-commit'\n\t);\n}\n\nfunction compositionRequirementSatisfaction(\n\tregistry: PackRegistry,\n\tdeclarations: readonly CompositionDeclaration[],\n\tcurrent: ModelIR | undefined,\n\tcontext: ObservationContext,\n):\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly assessment: PlanAssessment } {\n\tconst producersByFact = new Map<string, CompositionProducer[]>();\n\tfor (const declaration of declarations) {\n\t\tfor (const producer of declaration.produces ?? []) {\n\t\t\tconst key = transitionCompositionFactKey(producer.fact);\n\t\t\tproducersByFact.set(key, [...(producersByFact.get(key) ?? []), producer]);\n\t\t}\n\t}\n\tfor (const declaration of declarations) {\n\t\tfor (const requirement of declaration.requires ?? []) {\n\t\t\tif (\n\t\t\t\tcurrent &&\n\t\t\t\tregistry.satisfiesCompositionFact(requirement.fact, current, context)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst producers =\n\t\t\t\tproducersByFact.get(transitionCompositionFactKey(requirement.fact)) ??\n\t\t\t\t[];\n\t\t\tif (producers.length === 1) {\n\t\t\t\tconst producer = producers[0];\n\t\t\t\tif (!producer) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tassessment: unsupportedCompositionRequirement(\n\t\t\t\t\t\t\t`unsatisfied composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tcompositionRequirementNeedsCommittedProducer(requirement, producer)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tassessment: unsupportedCompositionRequirement(\n\t\t\t\t\t\t\t`composition requirement ${requirement.opRef} requires ${requirement.fact.kind} from same-plan producer ${producer.opRef}, but ${requirement.needs} / ${producer.available} facts must be proven against committed state`,\n\t\t\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (producers.length > 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tassessment: unsupportedCompositionRequirement(\n\t\t\t\t\t`unsatisfied composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nasync function proveTransitions(\n\tregistry: PackRegistry,\n\tcompare: Extract<CompareOutcome, { readonly kind: 'transitions' }>,\n\ttarget: TransitionLessor,\n\tcontext: ObservationContext,\n\tinitialState?: ObservationIssueState,\n): Promise<ProveOutcome> {\n\tif (compare.candidates.length === 0) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposableCandidates(\n\t\t\t\tcompare.candidates,\n\t\t\t\t'missing transition candidate',\n\t\t\t),\n\t\t};\n\t}\n\tif (initialState && compare.candidates.length !== 1) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposableCandidates(\n\t\t\t\tcompare.candidates,\n\t\t\t\t'initial observation replay only supports one transition candidate',\n\t\t\t),\n\t\t};\n\t}\n\n\tconst committedCurrent = transitionCompareCurrentModel(compare);\n\tconst fragments: TransitionFragment[] = [];\n\tconst planEvidence: EvidenceObservation[] = [];\n\tconst planEvidenceById = new Map<string, EvidenceObservation>();\n\tconst planClaims: ProofClaim[] = [];\n\tconst planClaimsById = new Map<string, ProofClaim>();\n\tconst planAssumptions: Assumption[] = [];\n\tconst operationInputs: CompositionOperation[] = [];\n\tconst compositionDeclarations: NonNullable<\n\t\tTransitionFragment['composition']\n\t>[] = [];\n\tconst stepInputs = new Map<\n\t\tstring,\n\t\t{\n\t\t\treadonly fragment: TransitionFragment;\n\t\t\treadonly operation: PhysicalOperation;\n\t\t\treadonly semantics: RegisteredOperationSemantics;\n\t\t\treadonly effects: OperationEffectAssessment;\n\t\t\treadonly fingerprints: ReturnType<\n\t\t\t\tRegisteredOperationSemantics['buildFingerprints']\n\t\t\t>;\n\t\t\treadonly requiredClaims: readonly ClaimId[];\n\t\t\treadonly guards: readonly ProvenApplyGuard[];\n\t\t\treadonly restsOnAssumptions: readonly Assumption['id'][];\n\t\t}\n\t>();\n\tlet sharedProofContext: ObservationContext | undefined;\n\tlet claimIndex = 0;\n\n\ttype PreparedCandidate = {\n\t\treadonly candidate: TransitionCandidate;\n\t\treadonly rule: TransitionRule;\n\t\treadonly issuer: ObservationIssuer | undefined;\n\t\treadonly requiredObservations: readonly ObservationRequest[];\n\t};\n\tconst preparedCandidates = new Map<TransitionCandidate, PreparedCandidate>();\n\tlet minServerVersionRequests = new Map<string, ObservationRequest>();\n\tconst obligationClaimByCanonicalKey = new Map<string, ProofClaim>();\n\tconst multiCandidateSnapshot = !initialState && compare.candidates.length > 1;\n\tlet sharedLease: TransitionLease | undefined;\n\tlet sharedClient: TransitionSessionClient | undefined;\n\tlet sharedReleaseFailure: TransitionLeaseFailure | undefined;\n\tconst sharedIssuedRequestKeys = new Set<string>();\n\tlet sharedIssued: {\n\t\treadonly evidence: readonly EvidenceObservation[];\n\t\treadonly advisory: readonly AdvisoryObservation[];\n\t} = { evidence: [], advisory: [] };\n\n\ttry {\n\t\tif (multiCandidateSnapshot) {\n\t\t\tsharedLease = await checkoutProofClient(target);\n\t\t\tsharedClient = sharedLease.session;\n\t\t\tconst allRequiredObservations: ObservationRequest[] = [];\n\t\t\tfor (const candidate of compare.candidates) {\n\t\t\t\tconst rule = registry.resolveRule(candidate.rule);\n\t\t\t\tif (!rule) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: blockedAssessment({\n\t\t\t\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\t\t\t\tcandidates: candidateRefs(compare.candidates),\n\t\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\t\tdetail: 'rule pack id did not resolve',\n\t\t\t\t\t\t}),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet requiredObservations: readonly ObservationRequest[];\n\t\t\t\ttry {\n\t\t\t\t\trequiredObservations = rule.requiredObservations(candidate.match);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'candidate required observation resolution failed',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(candidate.requiredObservations) ||\n\t\t\t\t\t!sameObservationRequests(\n\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\tcandidate.requiredObservations,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\t\t'candidate required observations do not match resolved rule',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst issuer = registry.resolveIssuer(candidate.rule.pack);\n\t\t\t\tconst candidateContext = registry.contextWithDerivedCapabilities(\n\t\t\t\t\tissuer?.readContext\n\t\t\t\t\t\t? await issuer.readContext(\n\t\t\t\t\t\t\t\tsharedClient,\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: context,\n\t\t\t\t);\n\t\t\t\tverifyCapturedTargetIdentity(context, candidateContext);\n\t\t\t\tif (!sharedProofContext) {\n\t\t\t\t\tsharedProofContext = candidateContext;\n\t\t\t\t} else {\n\t\t\t\t\tconst merged = registry.mergeObservationContexts(\n\t\t\t\t\t\tsharedProofContext,\n\t\t\t\t\t\tcandidateContext,\n\t\t\t\t\t);\n\t\t\t\t\tif (!merged.ok) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\t\tassessment: artifactMismatch(PROVER_ARTIFACT, merged.detail),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tsharedProofContext = merged.context;\n\t\t\t\t}\n\t\t\t\tpreparedCandidates.set(candidate, {\n\t\t\t\t\tcandidate,\n\t\t\t\t\trule,\n\t\t\t\t\tissuer,\n\t\t\t\t\trequiredObservations,\n\t\t\t\t});\n\t\t\t\tallRequiredObservations.push(...requiredObservations);\n\t\t\t}\n\t\t\tif (sharedProofContext) {\n\t\t\t\tminServerVersionRequests = new Map(\n\t\t\t\t\tstrongestMinServerVersionRequests(\n\t\t\t\t\t\tallRequiredObservations,\n\t\t\t\t\t\tsharedProofContext,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tfor (const candidate of compare.candidates) {\n\t\t\tconst prepared = preparedCandidates.get(candidate);\n\t\t\tconst rule = prepared?.rule ?? registry.resolveRule(candidate.rule);\n\t\t\tif (!rule) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: blockedAssessment({\n\t\t\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\t\t\tcandidates: candidateRefs(compare.candidates),\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\tdetail: 'rule pack id did not resolve',\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet requiredObservations: readonly ObservationRequest[];\n\t\t\tif (prepared) {\n\t\t\t\trequiredObservations = prepared.requiredObservations;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\trequiredObservations = rule.requiredObservations(candidate.match);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: 'candidate required observation resolution failed',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(candidate.requiredObservations) ||\n\t\t\t\t\t!sameObservationRequests(\n\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\tcandidate.requiredObservations,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\t\t'candidate required observations do not match resolved rule',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst issuer =\n\t\t\t\tprepared?.issuer ?? registry.resolveIssuer(candidate.rule.pack);\n\t\t\tlet proofContext = context;\n\t\t\tlet issued: Awaited<ReturnType<typeof issueObservations>>;\n\t\t\tif (issuer) {\n\t\t\t\tif (initialState) {\n\t\t\t\t\tif (initialState.issuer !== issuer) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\t\t\t\tPROVER_ARTIFACT,\n\t\t\t\t\t\t\t\t'recognition observations were issued by a different issuer',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tproofContext = initialState.proofContext;\n\t\t\t\t\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\t\t\t\t\tif (supportMismatch) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\t\tassessment: supportMismatchAssessment(candidate, supportMismatch),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst additional = await issueObservations(\n\t\t\t\t\t\tissuer,\n\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\tinitialState.client,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t\tinitialState.issuedRequestKeys,\n\t\t\t\t\t);\n\t\t\t\t\tissued = appendIssued(initialState, additional);\n\t\t\t\t} else if (sharedClient) {\n\t\t\t\t\tproofContext = sharedProofContext ?? context;\n\n\t\t\t\t\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\t\t\t\t\tif (supportMismatch) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\t\tassessment: supportMismatchAssessment(candidate, supportMismatch),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst additional = await issueObservations(\n\t\t\t\t\t\tissuer,\n\t\t\t\t\t\tevaluationRequestsForCandidate(\n\t\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\t\tminServerVersionRequests,\n\t\t\t\t\t\t\tproofContext,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tsharedClient,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t\tsharedIssuedRequestKeys,\n\t\t\t\t\t);\n\t\t\t\t\tissued = appendIssued(sharedIssued, additional);\n\t\t\t\t\tsharedIssued = appendIssued(sharedIssued, additional);\n\t\t\t\t} else {\n\t\t\t\t\tlet lease: TransitionLease | undefined;\n\t\t\t\t\tlet client: TransitionSessionClient | undefined;\n\t\t\t\t\tlet releaseFailure: TransitionLeaseFailure | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlease = await checkoutProofClient(target);\n\t\t\t\t\t\tclient = lease.session;\n\t\t\t\t\t\tproofContext = issuer.readContext\n\t\t\t\t\t\t\t? await issuer.readContext(client, context, requiredObservations)\n\t\t\t\t\t\t\t: context;\n\t\t\t\t\t\tverifyCapturedTargetIdentity(context, proofContext);\n\t\t\t\t\t\tproofContext =\n\t\t\t\t\t\t\tregistry.contextWithDerivedCapabilities(proofContext);\n\n\t\t\t\t\t\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\t\t\t\t\t\tif (supportMismatch) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\t\t\tassessment: supportMismatchAssessment(\n\t\t\t\t\t\t\t\t\tcandidate,\n\t\t\t\t\t\t\t\t\tsupportMismatch,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tissued = await issueObservations(\n\t\t\t\t\t\t\tissuer,\n\t\t\t\t\t\t\trequiredObservations,\n\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\tproofContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treleaseFailure = { error };\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\t\t\t\tPROVER_ARTIFACT,\n\t\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t\t: 'proof observation failed',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t};\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (lease) {\n\t\t\t\t\t\t\tawait lease.release(releaseFailure);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tproofContext =\n\t\t\t\t\tinitialState?.proofContext ??\n\t\t\t\t\tsharedProofContext ??\n\t\t\t\t\tregistry.contextWithDerivedCapabilities(proofContext);\n\t\t\t\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\t\t\t\tif (supportMismatch) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\tassessment: supportMismatchAssessment(candidate, supportMismatch),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tissued = initialState\n\t\t\t\t\t? { evidence: initialState.evidence, advisory: initialState.advisory }\n\t\t\t\t\t: { evidence: [], advisory: [] };\n\t\t\t}\n\t\t\tif (!sharedProofContext) {\n\t\t\t\tsharedProofContext = proofContext;\n\t\t\t} else {\n\t\t\t\tconst merged = registry.mergeObservationContexts(\n\t\t\t\t\tsharedProofContext,\n\t\t\t\t\tproofContext,\n\t\t\t\t);\n\t\t\t\tif (!merged.ok) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: artifactMismatch(PROVER_ARTIFACT, merged.detail),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tsharedProofContext = merged.context;\n\t\t\t}\n\n\t\t\tconst proofEvidence = multiCandidateSnapshot\n\t\t\t\t? canonicalEvidence(\n\t\t\t\t\t\tissued.evidence,\n\t\t\t\t\t\tminServerVersionRequests,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t)\n\t\t\t\t: issued.evidence;\n\t\t\tconst evidenceView = createEvidenceView({\n\t\t\t\tevidence: proofEvidence,\n\t\t\t\tcontext: proofContext,\n\t\t\t\trequests: candidate.requiredObservations,\n\t\t\t});\n\t\t\tconst evaluation = rule.evaluate(\n\t\t\t\tcandidate.match,\n\t\t\t\tevidenceView,\n\t\t\t\tissued.advisory,\n\t\t\t);\n\t\t\tif (evaluation.outcome === 'blocked') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: evaluationBlockedAssessment(\n\t\t\t\t\t\tevaluation,\n\t\t\t\t\t\t'rule evaluation blocked',\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (evaluation.outcome === 'inapplicable') {\n\t\t\t\tconst claims = evaluation.obligations.map((obligation, index) =>\n\t\t\t\t\tproofClaimForObligation(\n\t\t\t\t\t\tobligation,\n\t\t\t\t\t\tproofEvidence,\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\tissuer?.artifact ?? PROVER_ARTIFACT,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst refuted = claims.find(\n\t\t\t\t\t(claim) => claim.derivedBy.conclusion === 'refuted',\n\t\t\t\t);\n\t\t\t\tif (refuted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\tassessment: refutedAssessment(refuted),\n\t\t\t\t\t\tclaim: refuted,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\t'rule evaluated inapplicable',\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet fragment: TransitionFragment;\n\t\t\ttry {\n\t\t\t\tfragment = rule.generateCandidate(candidate.match, evaluation);\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposableCandidates(\n\t\t\t\t\t\tcompare.candidates,\n\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: 'candidate generation failed',\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (fragment.operations.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposable([fragment], 'missing operation'),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (\n\t\t\t\tfragment.generatedBy.id !== candidate.rule.id ||\n\t\t\t\t!sameArtifact(fragment.generatedBy.pack, candidate.rule.pack)\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: blockedAssessment({\n\t\t\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\t\t\tcandidates: [candidate.rule, fragment.generatedBy],\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\tdetail: 'generated fragment rule did not match candidate',\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\t\t\tfragment = {\n\t\t\t\t...fragment,\n\t\t\t\tselectionRationale: candidate.selectionRationale,\n\t\t\t};\n\t\t\tif (multiCandidateSnapshot) {\n\t\t\t\tfragment = canonicalizeFragmentObligations(\n\t\t\t\t\tfragment,\n\t\t\t\t\tminServerVersionRequests,\n\t\t\t\t\tproofContext,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst operationEffectsByRef = new Map<\n\t\t\t\tstring,\n\t\t\t\tOperationEffectAssessment\n\t\t\t>();\n\t\t\tconst operationSemanticsByRef = new Map<\n\t\t\t\tstring,\n\t\t\t\tRegisteredOperationSemantics\n\t\t\t>();\n\t\t\tfor (const operation of fragment.operations) {\n\t\t\t\tconst operationResolution = registry.resolveOperation(operation);\n\t\t\t\tif (!operationResolution.ok) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\t\t\toperation.operationKind.artifact,\n\t\t\t\t\t\t\toperationResolution.detail,\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst semantics = operationResolution.semantics;\n\t\t\t\tif (\n\t\t\t\t\t!sameArtifact(semantics.artifact, operation.operationKind.artifact)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\t\t\tsemantics.artifact,\n\t\t\t\t\t\t\t'operation pack id mismatch',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst effects = operationEffects(semantics, operation, proofContext);\n\t\t\t\tif (operationPackSemanticsMissing(effects, operation)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposable(\n\t\t\t\t\t\t\t[fragment],\n\t\t\t\t\t\t\t'missing operation-pack-semantics assumption',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\toperationEffectsByRef.set(operation.ref, effects);\n\t\t\t\toperationSemanticsByRef.set(operation.ref, semantics);\n\t\t\t}\n\n\t\t\tlet assumptions: readonly Assumption[];\n\t\t\ttry {\n\t\t\t\tassumptions = uniqueAssumptions([\n\t\t\t\t\t...evaluation.assumptions,\n\t\t\t\t\t...fragment.assumptions,\n\t\t\t\t\t...fragment.operations.flatMap((operation) => [\n\t\t\t\t\t\t...(operationEffectsByRef.get(operation.ref)?.restsOn ?? []),\n\t\t\t\t\t]),\n\t\t\t\t]);\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposable(\n\t\t\t\t\t\t[fragment],\n\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: 'conflicting assumption ids',\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet draftClaims: readonly ProofClaim[];\n\t\t\ttry {\n\t\t\t\tdraftClaims = [\n\t\t\t\t\t...(candidate.claimDrafts ?? []),\n\t\t\t\t\t...(fragment.claimDrafts ?? []),\n\t\t\t\t].map((draft) => proofClaimForDraft(draft, claimIndex++));\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposable(\n\t\t\t\t\t\t[fragment],\n\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: 'claim draft materialization failed',\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst obligationClaims = fragment.obligations.map((obligation) => ({\n\t\t\t\tobligation,\n\t\t\t\tclaim: (() => {\n\t\t\t\t\tconst key = canonicalObligationClaimKey(obligation);\n\t\t\t\t\tconst prior = key\n\t\t\t\t\t\t? obligationClaimByCanonicalKey.get(key)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (prior) {\n\t\t\t\t\t\treturn prior;\n\t\t\t\t\t}\n\t\t\t\t\tconst claim = proofClaimForObligation(\n\t\t\t\t\t\tobligation,\n\t\t\t\t\t\tproofEvidence,\n\t\t\t\t\t\tclaimIndex++,\n\t\t\t\t\t\tissuer?.artifact ?? PROVER_ARTIFACT,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t);\n\t\t\t\t\tif (key) {\n\t\t\t\t\t\tobligationClaimByCanonicalKey.set(key, claim);\n\t\t\t\t\t}\n\t\t\t\t\treturn claim;\n\t\t\t\t})(),\n\t\t\t}));\n\t\t\tconst claims = [\n\t\t\t\t...draftClaims,\n\t\t\t\t...obligationClaims.map((entry) => entry.claim),\n\t\t\t];\n\n\t\t\tconst undischarged = claims.find(\n\t\t\t\t(claim) => claim.derivedBy.conclusion === 'undischarged',\n\t\t\t);\n\t\t\tif (undischarged) {\n\t\t\t\tconst obligation = fragment.obligations.find(\n\t\t\t\t\t(item) => item.proposition.kind === undischarged.proposition.kind,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: missingEvidenceAssessment(\n\t\t\t\t\t\tobligation ?? {\n\t\t\t\t\t\t\tproposition: undischarged.proposition,\n\t\t\t\t\t\t\tscope: undischarged.scope,\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst refuted = claims.find(\n\t\t\t\t(claim) => claim.derivedBy.conclusion === 'refuted',\n\t\t\t);\n\t\t\tif (refuted) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\tassessment: refutedAssessment(refuted),\n\t\t\t\t\tclaim: refuted,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst invariants = validateTransitionRelationalInvariants({\n\t\t\t\tkind: 'fragment',\n\t\t\t\tfragment,\n\t\t\t\tclaims,\n\t\t\t\tassumptions,\n\t\t\t});\n\t\t\tif (!invariants.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: uncomposable([fragment], invariants.detail),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const operation of fragment.operations) {\n\t\t\t\tconst semantics = operationSemanticsByRef.get(operation.ref);\n\t\t\t\tconst effects = operationEffectsByRef.get(operation.ref);\n\t\t\t\tif (!semantics || !effects) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: uncomposable([fragment], 'missing operation effects'),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet fingerprints: ReturnType<\n\t\t\t\t\tRegisteredOperationSemantics['buildFingerprints']\n\t\t\t\t>;\n\t\t\t\ttry {\n\t\t\t\t\tfingerprints = semantics.buildFingerprints(\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tproofEvidence,\n\t\t\t\t\t\tproofContext,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\t\t\tsemantics.artifact,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? `fingerprint construction failed: ${error.message}`\n\t\t\t\t\t\t\t\t: 'fingerprint construction failed',\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst operationObligationClaims = obligationClaims.filter(\n\t\t\t\t\t(entry) => entry.obligation.appliesTo === operation.ref,\n\t\t\t\t);\n\t\t\t\tconst requiredClaimEntries = [\n\t\t\t\t\t...draftClaims,\n\t\t\t\t\t...operationObligationClaims.map((entry) => entry.claim),\n\t\t\t\t];\n\t\t\t\tconst requiredClaims = [\n\t\t\t\t\t...draftClaims.map((claim) => claim.id),\n\t\t\t\t\t...operationObligationClaims.map((entry) => entry.claim.id),\n\t\t\t\t];\n\t\t\t\tconst stepGuards = fragment.guards.filter(\n\t\t\t\t\t(guard) => guard.appliesTo === operation.ref,\n\t\t\t\t) as readonly ProvenApplyGuard[];\n\t\t\t\tstepInputs.set(operation.ref, {\n\t\t\t\t\tfragment,\n\t\t\t\t\toperation,\n\t\t\t\t\tsemantics,\n\t\t\t\t\teffects,\n\t\t\t\t\tfingerprints,\n\t\t\t\t\trequiredClaims,\n\t\t\t\t\tguards: stepGuards,\n\t\t\t\t\trestsOnAssumptions: stepAssumptionClosure({\n\t\t\t\t\t\teffects,\n\t\t\t\t\t\trequiredClaims: requiredClaimEntries,\n\t\t\t\t\t\tallClaims: claims,\n\t\t\t\t\t\tguards: stepGuards,\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\toperationInputs.push({\n\t\t\t\t\toperation,\n\t\t\t\t\teffects,\n\t\t\t\t\trequiredClaims: requiredClaimEntries.map((claim) => ({\n\t\t\t\t\t\tid: claim.id,\n\t\t\t\t\t\tproposition: claim.proposition.kind,\n\t\t\t\t\t\tscope: claim.scope,\n\t\t\t\t\t})),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tfragments.push(fragment);\n\t\t\tcompositionDeclarations.push(\n\t\t\t\t...(fragment.composition ? [fragment.composition] : []),\n\t\t\t);\n\t\t\tconst evidenceConflict = appendUniqueEvidence(\n\t\t\t\tplanEvidence,\n\t\t\t\tplanEvidenceById,\n\t\t\t\tproofEvidence,\n\t\t\t);\n\t\t\tif (evidenceConflict) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: artifactMismatch(PROVER_ARTIFACT, evidenceConflict),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst claimConflict = appendUniqueClaims(\n\t\t\t\tplanClaims,\n\t\t\t\tplanClaimsById,\n\t\t\t\tclaims,\n\t\t\t);\n\t\t\tif (claimConflict) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: artifactMismatch(PROVER_ARTIFACT, claimConflict),\n\t\t\t\t};\n\t\t\t}\n\t\t\tplanAssumptions.push(...assumptions);\n\t\t}\n\t} catch (error) {\n\t\tsharedReleaseFailure = { error };\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: artifactMismatch(\n\t\t\t\tPROVER_ARTIFACT,\n\t\t\t\terror instanceof Error ? error.message : 'proof observation failed',\n\t\t\t),\n\t\t};\n\t} finally {\n\t\tif (sharedLease) {\n\t\t\tawait sharedLease.release(sharedReleaseFailure);\n\t\t}\n\t}\n\n\tlet assumptions: readonly Assumption[];\n\ttry {\n\t\tassumptions = uniqueAssumptions(planAssumptions);\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposable(\n\t\t\t\tfragments,\n\t\t\t\terror instanceof Error ? error.message : 'conflicting assumption ids',\n\t\t\t),\n\t\t};\n\t}\n\tconst composition = composeOperations(\n\t\toperationInputs,\n\t\tcompositionDeclarations,\n\t);\n\tconst requirementSatisfaction = compositionRequirementSatisfaction(\n\t\tregistry,\n\t\tcompositionDeclarations,\n\t\tcommittedCurrent,\n\t\tsharedProofContext ?? context,\n\t);\n\tif (!requirementSatisfaction.ok) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: requirementSatisfaction.assessment,\n\t\t};\n\t}\n\tif (!composition.ok) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposable(fragments, composition.detail),\n\t\t};\n\t}\n\tconst nonTransactionalAssumption = nonTransactionalSegmentAssumption(\n\t\toperationInputs,\n\t\tcomposition.segments,\n\t);\n\tif (nonTransactionalAssumption) {\n\t\ttry {\n\t\t\tassumptions = uniqueAssumptions([\n\t\t\t\t...assumptions,\n\t\t\t\tnonTransactionalAssumption,\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: 'blocked',\n\t\t\t\tassessment: uncomposable(\n\t\t\t\t\tfragments,\n\t\t\t\t\terror instanceof Error ? error.message : 'conflicting assumption ids',\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t}\n\tconst segmentByStepId = new Map<string, string>();\n\tfor (const segment of composition.segments) {\n\t\tfor (const stepId of segment.stepIds) {\n\t\t\tsegmentByStepId.set(stepId, segment.segmentId);\n\t\t}\n\t}\n\tconst primaryClaim =\n\t\tplanClaims[0]?.id ?? claimId('dbsp.transition.claim.plan');\n\tconst guardedSteps = composition.operations.map((entry) => {\n\t\tconst input = stepInputs.get(entry.operation.ref);\n\t\tif (!input) {\n\t\t\tthrow new Error(\n\t\t\t\t`internal error: missing composed operation ${entry.operation.ref}`,\n\t\t\t);\n\t\t}\n\t\tconst currentStepId = `step:${entry.operation.ref}`;\n\t\tconst segmentId = segmentByStepId.get(currentStepId);\n\t\tif (!segmentId) {\n\t\t\tthrow new Error(\n\t\t\t\t`internal error: composed step ${currentStepId} has no segment`,\n\t\t\t);\n\t\t}\n\t\tconst managedClaim = managedClaimMaterial(\n\t\t\tinput.semantics,\n\t\t\tinput.operation,\n\t\t\tsharedProofContext ?? context,\n\t\t);\n\t\tif (\n\t\t\tinput.semantics.executionContractEligibility?.eligible === true &&\n\t\t\tmanagedClaim === undefined\n\t\t) {\n\t\t\treturn {\n\t\t\t\tkind: 'underivable-managed-claim' as const,\n\t\t\t\toperation: input.operation,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: 'step' as const,\n\t\t\tstep: {\n\t\t\t\tstepId: currentStepId,\n\t\t\t\tsegmentId,\n\t\t\t\toperation: input.operation,\n\t\t\t\texpectedBefore: input.fingerprints.expectedBefore,\n\t\t\t\texpectedAfter: input.fingerprints.expectedAfter,\n\t\t\t\trequiredClaims: input.requiredClaims,\n\t\t\t\testablishesClaims: [],\n\t\t\t\tinvalidatesClaims: input.effects.effects.invalidates,\n\t\t\t\tguards: input.guards,\n\t\t\t\trestsOnAssumptions: input.restsOnAssumptions,\n\t\t\t\tselectionRationale: input.fragment.selectionRationale,\n\t\t\t\t...(managedClaim === undefined ? {} : { managedClaim }),\n\t\t\t},\n\t\t};\n\t});\n\tconst underivable = guardedSteps.find(\n\t\t(step) => step.kind === 'underivable-managed-claim',\n\t);\n\tif (underivable) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposable(\n\t\t\t\tfragments,\n\t\t\t\t`managed-eligible operation ${underivable.operation.ref} cannot derive immutable managed claim material`,\n\t\t\t),\n\t\t};\n\t}\n\tconst guardedPlan: ProvenPlanShape = {\n\t\tobservations: planEvidence,\n\t\tclaims: planClaims,\n\t\tassumptions,\n\t\tpreconditions: fragments.flatMap((fragment) =>\n\t\t\tfragment.obligations.map((obligation) => ({\n\t\t\t\tproposition: obligation.proposition,\n\t\t\t\tscope: obligation.scope,\n\t\t\t})),\n\t\t),\n\t\tsegments: composition.segments,\n\t\tsteps: guardedSteps.map((entry) => {\n\t\t\tif (entry.kind !== 'step')\n\t\t\t\tthrow new Error('internal error: blocked managed claim reached plan');\n\t\t\treturn entry.step;\n\t\t}),\n\t\tpostconditions: [],\n\t};\n\tconst operationEffectsByPlanRef = new Map(\n\t\t[...stepInputs.entries()].map(([ref, input]) => [ref, input.effects]),\n\t);\n\n\tconst planInvariants = validateTransitionRelationalInvariants({\n\t\tkind: 'plan',\n\t\tplan: guardedPlan,\n\t\toperationEffectsByRef: operationEffectsByPlanRef,\n\t});\n\tif (!planInvariants.ok) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: uncomposable(fragments, planInvariants.detail),\n\t\t};\n\t}\n\n\tconst plan = mintInProcessPlan(guardedPlan);\n\treturn {\n\t\tkind: 'proven',\n\t\tplan,\n\t\tassessment: applicableAssessment(primaryClaim, assumptions),\n\t};\n}\n\nasync function retryUnknownRecognition(\n\tregistry: PackRegistry,\n\tcompare: Extract<CompareOutcome, { readonly kind: 'unknown' }>,\n\ttarget: TransitionLessor,\n\tcontext: ObservationContext,\n): Promise<ProveOutcome> {\n\tif (compare.recognitions.length !== 1) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: blockedAssessment({\n\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\tcandidates: compare.recognitions.map((recognition) => recognition.rule),\n\t\t\t\tscope: [],\n\t\t\t\tdetail:\n\t\t\t\t\t'multiple transition recognitions require unresolved equivalence evidence',\n\t\t\t}),\n\t\t};\n\t}\n\tconst recognition = compare.recognitions[0];\n\tif (!recognition) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: evaluationBlockedAssessment(\n\t\t\t\t{ obligations: compare.obligations },\n\t\t\t\t'missing unknown transition recognition',\n\t\t\t),\n\t\t};\n\t}\n\tconst rule = registry.resolveRule(recognition.rule);\n\tif (!rule) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: blockedAssessment({\n\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\tcandidates: [recognition.rule],\n\t\t\t\tscope: [],\n\t\t\t\tdetail: 'rule pack id did not resolve',\n\t\t\t}),\n\t\t};\n\t}\n\n\tconst recognitionRequests = recognition.obligations.flatMap((obligation) => [\n\t\t...(obligation.dischargeableBy ?? []),\n\t]);\n\tconst issuer = registry.resolveIssuer(recognition.rule.pack);\n\tif (issuer) {\n\t\tlet lease: TransitionLease | undefined;\n\t\tlet client: TransitionSessionClient | undefined;\n\t\tlet releaseFailure: TransitionLeaseFailure | undefined;\n\t\tconst issuedRequestKeys = new Set<string>();\n\t\ttry {\n\t\t\tlease = await checkoutProofClient(target);\n\t\t\tclient = lease.session;\n\t\t\tlet proofContext = issuer.readContext\n\t\t\t\t? await issuer.readContext(client, context, recognitionRequests)\n\t\t\t\t: context;\n\t\t\tverifyCapturedTargetIdentity(context, proofContext);\n\t\t\tproofContext = registry.contextWithDerivedCapabilities(proofContext);\n\t\t\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\t\t\tif (supportMismatch) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\tassessment: inapplicableAssessment({\n\t\t\t\t\t\tcode: 'context-mismatch',\n\t\t\t\t\t\tartifact: rule.artifact,\n\t\t\t\t\t\tfact: supportMismatch.fact,\n\t\t\t\t\t\tscope: [],\n\t\t\t\t\t\tdetail: supportMismatch.detail,\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst issued = await issueObservations(\n\t\t\t\tissuer,\n\t\t\t\trecognitionRequests,\n\t\t\t\tclient,\n\t\t\t\tproofContext,\n\t\t\t\tissuedRequestKeys,\n\t\t\t);\n\t\t\tconst equivalence = registry.resolveEquivalence(rule.artifact);\n\t\t\tconst evidenceView = createEvidenceView({\n\t\t\t\tevidence: issued.evidence,\n\t\t\t\tcontext: proofContext,\n\t\t\t\trequests: recognitionRequests,\n\t\t\t});\n\t\t\tconst retried = recognitionResultWithEvidenceSupport(\n\t\t\t\trule.recognize(\n\t\t\t\t\trecognition.desired,\n\t\t\t\t\trecognition.current,\n\t\t\t\t\tequivalence\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tequivalence,\n\t\t\t\t\t\t\t\tcontext: equivalenceContextFromObservation(proofContext),\n\t\t\t\t\t\t\t\tevidence: evidenceView,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tcontext: equivalenceContextFromObservation(proofContext),\n\t\t\t\t\t\t\t\tevidence: evidenceView,\n\t\t\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tissued.evidence,\n\t\t\t);\n\t\t\tif (retried.recognized === 'unknown') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: missingEvidenceAssessment(\n\t\t\t\t\t\tretried.obligations[0] ?? fallbackUnknownObligation(recognition),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (retried.recognized === 'no-drift') {\n\t\t\t\tconst claim = establishedNoDriftClaimFromDraft(retried.claimDraft, 0);\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'no-drift',\n\t\t\t\t\tclaim,\n\t\t\t\t\tassessment: applicableAssessment(claim.id, []),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (retried.recognized === 'unsupported') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: blockedAssessment({\n\t\t\t\t\t\tcode: 'unsupported-transition',\n\t\t\t\t\t\tchanges: retried.changes,\n\t\t\t\t\t\tscope: retried.changes,\n\t\t\t\t\t\t...(retried.detail ? { detail: retried.detail } : {}),\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!retried.recognized) {\n\t\t\t\tconst refuted = firstRefutedRecognitionClaim(retried);\n\t\t\t\tif (refuted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'inapplicable',\n\t\t\t\t\t\tassessment: refutedAssessment(refuted),\n\t\t\t\t\t\tclaim: refuted,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: missingEvidenceAssessment(\n\t\t\t\t\t\tfallbackUnknownObligation(recognition),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst candidate = candidateFromRecognition(rule, retried);\n\t\t\treturn await proveTransitions(\n\t\t\t\tregistry,\n\t\t\t\t{\n\t\t\t\t\tkind: 'transitions',\n\t\t\t\t\tcandidates: [candidate],\n\t\t\t\t\tobligations: candidate.obligations,\n\t\t\t\t},\n\t\t\t\ttarget,\n\t\t\t\tcontext,\n\t\t\t\t{\n\t\t\t\t\tissuer,\n\t\t\t\t\tclient,\n\t\t\t\t\tproofContext,\n\t\t\t\t\tissuedRequestKeys,\n\t\t\t\t\tevidence: issued.evidence,\n\t\t\t\t\tadvisory: issued.advisory,\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\treleaseFailure = { error };\n\t\t\treturn {\n\t\t\t\tkind: 'blocked',\n\t\t\t\tassessment: artifactMismatch(\n\t\t\t\t\tPROVER_ARTIFACT,\n\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: 'recognition/proof observation failed',\n\t\t\t\t),\n\t\t\t};\n\t\t} finally {\n\t\t\tif (lease) {\n\t\t\t\tawait lease.release(releaseFailure);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst proofContext = registry.contextWithDerivedCapabilities(context);\n\tconst supportMismatch = ruleSupportMismatch(rule, proofContext);\n\tif (supportMismatch) {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: artifactMismatch(\n\t\t\t\trule.artifact,\n\t\t\t\t`rule support mismatch while retrying recognition: ${supportMismatch.detail}`,\n\t\t\t),\n\t\t};\n\t}\n\tconst equivalence = registry.resolveEquivalence(rule.artifact);\n\tconst retried = rule.recognize(\n\t\trecognition.desired,\n\t\trecognition.current,\n\t\tequivalence\n\t\t\t? {\n\t\t\t\t\tequivalence,\n\t\t\t\t\tcontext: equivalenceContextFromObservation(proofContext),\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tcontext: equivalenceContextFromObservation(proofContext),\n\t\t\t\t},\n\t);\n\tif (retried.recognized === 'unknown') {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: missingEvidenceAssessment(\n\t\t\t\tretried.obligations[0] ?? fallbackUnknownObligation(recognition),\n\t\t\t),\n\t\t};\n\t}\n\tif (retried.recognized === 'no-drift') {\n\t\tconst claim = establishedNoDriftClaimFromDraft(retried.claimDraft, 0);\n\t\treturn {\n\t\t\tkind: 'no-drift',\n\t\t\tclaim,\n\t\t\tassessment: applicableAssessment(claim.id, []),\n\t\t};\n\t}\n\tif (retried.recognized === 'unsupported') {\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: blockedAssessment({\n\t\t\t\tcode: 'unsupported-transition',\n\t\t\t\tchanges: retried.changes,\n\t\t\t\tscope: retried.changes,\n\t\t\t\t...(retried.detail ? { detail: retried.detail } : {}),\n\t\t\t}),\n\t\t};\n\t}\n\tif (!retried.recognized) {\n\t\tconst refuted = firstRefutedRecognitionClaim(retried);\n\t\tif (refuted) {\n\t\t\treturn {\n\t\t\t\tkind: 'inapplicable',\n\t\t\t\tassessment: refutedAssessment(refuted),\n\t\t\t\tclaim: refuted,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: 'blocked',\n\t\t\tassessment: missingEvidenceAssessment(\n\t\t\t\tfallbackUnknownObligation(recognition),\n\t\t\t),\n\t\t};\n\t}\n\tconst candidate = candidateFromRecognition(rule, retried);\n\treturn proveTransitions(\n\t\tregistry,\n\t\t{\n\t\t\tkind: 'transitions',\n\t\t\tcandidates: [candidate],\n\t\t\tobligations: candidate.obligations,\n\t\t},\n\t\ttarget,\n\t\tcontext,\n\t);\n}\n\nexport function createProver(registry: PackRegistry): Prover {\n\treturn {\n\t\tartifact: PROVER_ARTIFACT,\n\t\tasync prove(\n\t\t\tcompare: CompareOutcome,\n\t\t\ttarget: TransitionLessor,\n\t\t\tcontext: ObservationContext,\n\t\t): Promise<ProveOutcome> {\n\t\t\tswitch (compare.kind) {\n\t\t\t\tcase 'no-drift': {\n\t\t\t\t\tconst claim = establishedNoDriftClaim(compare);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'no-drift',\n\t\t\t\t\t\tclaim,\n\t\t\t\t\t\tassessment: applicableAssessment(claim.id, []),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase 'unsupported':\n\t\t\t\t\treturn { kind: 'blocked', assessment: unsupported(compare) };\n\t\t\t\tcase 'unknown':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'ambiguous':\n\t\t\t\t\treturn { kind: 'blocked', assessment: ambiguous(compare) };\n\t\t\t\tcase 'uncomposable':\n\t\t\t\t\treturn { kind: 'blocked', assessment: uncomposableCompare(compare) };\n\t\t\t\tcase 'transitions':\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!isTransitionLessor(target)) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'blocked',\n\t\t\t\t\tassessment: transitionLessorRejectionAssessment(PROVER_ARTIFACT),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn compare.kind === 'unknown'\n\t\t\t\t? retryUnknownRecognition(registry, compare, target, context)\n\t\t\t\t: proveTransitions(registry, compare, target, context);\n\t\t},\n\t};\n}\n","import type {\n\tClaimId,\n\tClaimSelector,\n\tGuardedPlanSegment,\n\tOperationEffectAssessment,\n\tPhysicalOperation,\n\tResourceAddress,\n\tResourceSelector,\n\tTransitionFragmentComposition,\n} from '@dbsp/types';\nimport { stableJson } from './stable-json.js';\n\nexport interface CompositionOperation {\n\treadonly operation: PhysicalOperation;\n\treadonly effects: OperationEffectAssessment;\n\treadonly requiredClaims?: readonly CompositionRequiredClaim[];\n}\n\nexport interface CompositionRequiredClaim {\n\treadonly id: ClaimId;\n\treadonly proposition: string;\n\treadonly scope: readonly ResourceAddress[];\n}\n\nexport interface OrderedCompositionOperation extends CompositionOperation {\n\treadonly dependsOn: readonly string[];\n\treadonly requiresCommitBefore: boolean;\n}\n\nexport type CompositionResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly operations: readonly OrderedCompositionOperation[];\n\t\t\treadonly segments: readonly GuardedPlanSegment[];\n\t }\n\t| { readonly ok: false; readonly detail: string };\n\ntype DeclaredEdge = {\n\treadonly before: string;\n\treadonly after: string;\n\treadonly requiresCommitBetween: boolean;\n\treadonly reason: string;\n};\ntype CompositionFact = NonNullable<\n\tTransitionFragmentComposition['produces']\n>[number]['fact'];\n\nfunction sameResource(left: ResourceAddress, right: ResourceAddress): boolean {\n\treturn stableJson(left) === stableJson(right);\n}\n\nfunction resourceIsWithin(\n\tresource: ResourceAddress,\n\tparent: ResourceAddress,\n): boolean {\n\tif (sameResource(resource, parent)) {\n\t\treturn true;\n\t}\n\treturn (\n\t\tresource.engine === parent.engine &&\n\t\tresource.database === parent.database &&\n\t\tresource.schema === parent.schema &&\n\t\t(resource.qualifiedBy?.includes(parent.name) ?? false)\n\t);\n}\n\nfunction resourcesIntersect(\n\tleft: ResourceAddress,\n\tright: ResourceAddress,\n): boolean {\n\treturn (\n\t\tsameResource(left, right) ||\n\t\tresourceIsWithin(left, right) ||\n\t\tresourceIsWithin(right, left)\n\t);\n}\n\nfunction selectorDescribesResource(\n\tselector: ResourceSelector,\n\tresource: ResourceAddress,\n): boolean {\n\tif (selector.kind && selector.kind !== resource.kind) {\n\t\treturn false;\n\t}\n\tif (selector.schema && selector.schema !== resource.schema) {\n\t\treturn false;\n\t}\n\tif (selector.name && selector.name !== resource.name) {\n\t\treturn false;\n\t}\n\tif (selector.within && !resourceIsWithin(resource, selector.within)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction selectorIsWithinResource(\n\tselector: ResourceSelector,\n\tresource: ResourceAddress,\n): boolean {\n\treturn selector.within\n\t\t? resourcesIntersect(selector.within, resource)\n\t\t: false;\n}\n\nfunction resourceIsWithinSelector(\n\tresource: ResourceAddress,\n\tselector: ResourceSelector,\n): boolean {\n\tif (!selector.name) {\n\t\treturn false;\n\t}\n\tif (selector.schema && selector.schema !== resource.schema) {\n\t\treturn false;\n\t}\n\treturn resource.qualifiedBy?.includes(selector.name) ?? false;\n}\n\nfunction selectorIntersectsResource(\n\tselector: ResourceSelector,\n\tresource: ResourceAddress,\n): boolean {\n\treturn (\n\t\tselectorDescribesResource(selector, resource) ||\n\t\tselectorIsWithinResource(selector, resource) ||\n\t\tresourceIsWithinSelector(resource, selector)\n\t);\n}\n\nfunction selectorFieldsCompatible(\n\tleft: ResourceSelector,\n\tright: ResourceSelector,\n): boolean {\n\tif (left.kind && right.kind && left.kind !== right.kind) {\n\t\treturn false;\n\t}\n\tif (left.schema && right.schema && left.schema !== right.schema) {\n\t\treturn false;\n\t}\n\tif (left.name && right.name && left.name !== right.name) {\n\t\treturn false;\n\t}\n\tif (\n\t\tleft.within &&\n\t\tright.within &&\n\t\t!resourcesIntersect(left.within, right.within)\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction selectorIntersectsSelector(\n\tleft: ResourceSelector,\n\tright: ResourceSelector,\n): boolean {\n\treturn (\n\t\tstableJson(left) === stableJson(right) ||\n\t\t(left.within ? selectorIntersectsResource(right, left.within) : false) ||\n\t\t(right.within ? selectorIntersectsResource(left, right.within) : false) ||\n\t\tselectorFieldsCompatible(left, right)\n\t);\n}\n\nfunction writesIntersect(\n\tleft: OperationEffectAssessment,\n\tright: OperationEffectAssessment,\n): boolean {\n\treturn left.effects.writes.some((leftWrite) =>\n\t\tright.effects.writes.some((rightWrite) =>\n\t\t\tselectorIntersectsSelector(leftWrite, rightWrite),\n\t\t),\n\t);\n}\n\nfunction writesIntersectReadsOrLocks(\n\twriter: OperationEffectAssessment,\n\tuser: OperationEffectAssessment,\n): boolean {\n\treturn writer.effects.writes.some(\n\t\t(write) =>\n\t\t\tuser.effects.reads.some((read) =>\n\t\t\t\tselectorIntersectsSelector(write, read),\n\t\t\t) ||\n\t\t\tuser.effects.locks.some((lock) =>\n\t\t\t\tselectorIntersectsResource(write, lock.resource),\n\t\t\t),\n\t);\n}\n\nfunction effectsInteract(\n\tleft: OperationEffectAssessment,\n\tright: OperationEffectAssessment,\n): boolean {\n\treturn (\n\t\twritesIntersect(left, right) ||\n\t\twritesIntersectReadsOrLocks(left, right) ||\n\t\twritesIntersectReadsOrLocks(right, left)\n\t);\n}\n\nfunction resourceOrderKey(resource: ResourceAddress): string {\n\treturn stableJson([\n\t\tresource.engine,\n\t\tresource.database,\n\t\tresource.schema ?? '',\n\t\tresource.name,\n\t\tresource.kind,\n\t\tstableJson(resource.qualifiedBy ?? []),\n\t]);\n}\n\nfunction selectorOrderKey(selector: ResourceSelector): string {\n\treturn stableJson([\n\t\tselector.within?.engine ?? '',\n\t\tselector.within?.database ?? '',\n\t\tselector.schema ?? selector.within?.schema ?? '',\n\t\tselector.name ?? selector.within?.name ?? '',\n\t\tselector.kind ?? '',\n\t\tselector.within ? resourceOrderKey(selector.within) : '',\n\t\tstableJson(selector),\n\t]);\n}\n\nfunction sortedKeys(values: readonly string[]): readonly string[] {\n\treturn [...values].sort();\n}\n\nfunction stableCompositionOrderKey(\n\tentry: CompositionOperation,\n): readonly string[] {\n\tconst effects = entry.effects.effects;\n\treturn [\n\t\tstableJson(sortedKeys(effects.writes.map(selectorOrderKey))),\n\t\tstableJson(\n\t\t\tsortedKeys(effects.locks.map((lock) => resourceOrderKey(lock.resource))),\n\t\t),\n\t\tstableJson(sortedKeys(effects.reads.map(selectorOrderKey))),\n\t\tstableJson(entry.operation.operationKind),\n\t\tentry.operation.ref,\n\t];\n}\n\nfunction compareStableCompositionOrder(\n\tleft: CompositionOperation,\n\tright: CompositionOperation,\n): number {\n\tconst leftKey = stableCompositionOrderKey(left);\n\tconst rightKey = stableCompositionOrderKey(right);\n\tconst length = Math.max(leftKey.length, rightKey.length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst leftPart = leftKey[index] ?? '';\n\t\tconst rightPart = rightKey[index] ?? '';\n\t\tif (leftPart < rightPart) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (leftPart > rightPart) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction selectorMatchesClaim(\n\tselector: ClaimSelector,\n\tclaim: CompositionRequiredClaim,\n): boolean {\n\tif (selector.proposition && selector.proposition !== claim.proposition) {\n\t\treturn false;\n\t}\n\tif (claim.scope.length === 0) {\n\t\treturn (\n\t\t\tselector.scope.kind === undefined &&\n\t\t\tselector.scope.schema === undefined &&\n\t\t\tselector.scope.name === undefined &&\n\t\t\tselector.scope.within === undefined\n\t\t);\n\t}\n\treturn claim.scope.some((resource) =>\n\t\tselectorIntersectsResource(selector.scope, resource),\n\t);\n}\n\nfunction invalidatesRequiredClaim(\n\tinvalidator: CompositionOperation,\n\ttarget: CompositionOperation,\n): boolean {\n\treturn invalidator.effects.effects.invalidates.some((selector) =>\n\t\t(target.requiredClaims ?? []).some((claim) =>\n\t\t\tselectorMatchesClaim(selector, claim),\n\t\t),\n\t);\n}\n\nfunction requiredClaimsInvalidate(\n\tleft: CompositionOperation,\n\tright: CompositionOperation,\n): boolean {\n\treturn (\n\t\tinvalidatesRequiredClaim(left, right) ||\n\t\tinvalidatesRequiredClaim(right, left)\n\t);\n}\n\nfunction invalidatedRequiredClaimDetail(\n\toperations: readonly OrderedCompositionOperation[],\n): string | undefined {\n\tconst claimById = new Map<ClaimId, CompositionRequiredClaim>();\n\tfor (const entry of operations) {\n\t\tfor (const claim of entry.requiredClaims ?? []) {\n\t\t\tconst prior = claimById.get(claim.id);\n\t\t\tif (prior && stableJson(prior) !== stableJson(claim)) {\n\t\t\t\treturn `conflicting required claim metadata for ${claim.id}`;\n\t\t\t}\n\t\t\tclaimById.set(claim.id, claim);\n\t\t}\n\t}\n\n\tconst invalidatedBy = new Map<ClaimId, string>();\n\tfor (const entry of operations) {\n\t\tfor (const claim of entry.requiredClaims ?? []) {\n\t\t\tconst invalidatingRef = invalidatedBy.get(claim.id);\n\t\t\tif (invalidatingRef) {\n\t\t\t\treturn `operation ${entry.operation.ref} requires claim ${claim.id} invalidated by earlier operation ${invalidatingRef}`;\n\t\t\t}\n\t\t}\n\t\tfor (const selector of entry.effects.effects.invalidates) {\n\t\t\tfor (const claim of claimById.values()) {\n\t\t\t\tif (selectorMatchesClaim(selector, claim)) {\n\t\t\t\t\tinvalidatedBy.set(claim.id, entry.operation.ref);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction hasContextMutation(entry: CompositionOperation): boolean {\n\treturn entry.effects.effects.contextMutations.length > 0;\n}\n\nfunction stepId(operation: PhysicalOperation): string {\n\treturn `step:${operation.ref}`;\n}\n\nfunction commitBoundaryBefore(\n\tcommitBoundary: CompositionOperation['effects']['effects']['execution']['commitBoundary'],\n): boolean {\n\treturn commitBoundary === 'before' || commitBoundary === 'before-and-after';\n}\n\nfunction commitBoundaryAfter(\n\tcommitBoundary: CompositionOperation['effects']['effects']['execution']['commitBoundary'],\n): boolean {\n\treturn commitBoundary === 'after' || commitBoundary === 'before-and-after';\n}\n\nfunction postconditionVisibleOnlyAfterCommit(\n\texecution: CompositionOperation['effects']['effects']['execution'],\n): boolean {\n\treturn execution.postconditionVisibility === 'after-commit';\n}\n\nfunction segmentTransaction(\n\tcurrent: GuardedPlanSegment['transaction'] | undefined,\n\tnext: GuardedPlanSegment['transaction'],\n): GuardedPlanSegment['transaction'] {\n\tif (current === 'requires-new' || next === 'requires-new') {\n\t\treturn 'requires-new';\n\t}\n\tif (current === 'forbids-transaction' || next === 'forbids-transaction') {\n\t\treturn 'forbids-transaction';\n\t}\n\treturn 'joins-current';\n}\n\nfunction composeSegments(\n\toperations: readonly OrderedCompositionOperation[],\n): readonly GuardedPlanSegment[] {\n\tconst segments: GuardedPlanSegment[] = [];\n\tlet current:\n\t\t| {\n\t\t\t\tsegmentId: string;\n\t\t\t\tstepIds: string[];\n\t\t\t\ttransaction: GuardedPlanSegment['transaction'];\n\t\t\t\tcommitBoundaryBefore: boolean;\n\t\t\t\tcommitBoundaryAfter: boolean;\n\t\t }\n\t\t| undefined;\n\tlet nextSegmentHasBoundaryBefore = false;\n\n\tconst flush = (commitAfter: boolean) => {\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\t\tcurrent.commitBoundaryAfter = current.commitBoundaryAfter || commitAfter;\n\t\tsegments.push({\n\t\t\tsegmentId: current.segmentId,\n\t\t\tstepIds: [...current.stepIds],\n\t\t\ttransaction: current.transaction,\n\t\t\tcommitBoundaryBefore: current.commitBoundaryBefore,\n\t\t\tcommitBoundaryAfter: current.commitBoundaryAfter,\n\t\t});\n\t\tnextSegmentHasBoundaryBefore = current.commitBoundaryAfter;\n\t\tcurrent = undefined;\n\t};\n\n\tfor (const entry of operations) {\n\t\tconst execution = entry.effects.effects.execution;\n\t\tconst startsNewSegment =\n\t\t\tentry.requiresCommitBefore ||\n\t\t\texecution.transaction === 'requires-new' ||\n\t\t\texecution.transaction === 'forbids-transaction' ||\n\t\t\tpostconditionVisibleOnlyAfterCommit(execution) ||\n\t\t\tcommitBoundaryBefore(execution.commitBoundary) ||\n\t\t\tcurrent?.transaction === 'forbids-transaction';\n\t\tif (current && startsNewSegment) {\n\t\t\tflush(true);\n\t\t}\n\t\tif (!current) {\n\t\t\tcurrent = {\n\t\t\t\tsegmentId: `segment:${segments.length}`,\n\t\t\t\tstepIds: [],\n\t\t\t\ttransaction: execution.transaction,\n\t\t\t\tcommitBoundaryBefore: nextSegmentHasBoundaryBefore,\n\t\t\t\tcommitBoundaryAfter: false,\n\t\t\t};\n\t\t\tnextSegmentHasBoundaryBefore = false;\n\t\t} else {\n\t\t\tcurrent.transaction = segmentTransaction(\n\t\t\t\tcurrent.transaction,\n\t\t\t\texecution.transaction,\n\t\t\t);\n\t\t}\n\t\tcurrent.stepIds.push(stepId(entry.operation));\n\t\tif (\n\t\t\texecution.transaction === 'forbids-transaction' ||\n\t\t\tpostconditionVisibleOnlyAfterCommit(execution) ||\n\t\t\tcommitBoundaryAfter(execution.commitBoundary)\n\t\t) {\n\t\t\tflush(true);\n\t\t}\n\t}\n\tflush(false);\n\treturn segments;\n}\n\ntype ConstraintBuildResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly dependents: ReadonlyMap<string, Set<string>>;\n\t\t\treadonly dependencyRefs: ReadonlyMap<string, Set<string>>;\n\t\t\treadonly commitEdges: ReadonlySet<string>;\n\t\t\treadonly declaredPairs: ReadonlySet<string>;\n\t }\n\t| { readonly ok: false; readonly detail: string };\n\ntype DeclaredEdgesResult =\n\t| { readonly ok: true; readonly edges: readonly DeclaredEdge[] }\n\t| { readonly ok: false; readonly detail: string };\n\nfunction edgeKey(before: string, after: string): string {\n\treturn stableJson([before, after]);\n}\n\nfunction unorderedEdgeKey(left: string, right: string): string {\n\treturn stableJson([left, right].sort());\n}\n\nexport function transitionCompositionFactKey(fact: CompositionFact): string {\n\treturn stableJson({\n\t\tkind: fact.kind,\n\t\tresource: fact.resource,\n\t\tdetail: fact.detail,\n\t});\n}\n\nfunction addConstraint(\n\tdependents: Map<string, Set<string>>,\n\tdependencyRefs: Map<string, Set<string>>,\n\tcommitEdges: Set<string>,\n\tdeclaredPairs: Set<string>,\n\tedge: DeclaredEdge,\n): void {\n\tdependents.get(edge.before)?.add(edge.after);\n\tdependencyRefs.get(edge.after)?.add(edge.before);\n\tdeclaredPairs.add(unorderedEdgeKey(edge.before, edge.after));\n\tif (edge.requiresCommitBetween) {\n\t\tcommitEdges.add(edgeKey(edge.before, edge.after));\n\t}\n}\n\nfunction declaredEdges(\n\tdeclarations: readonly TransitionFragmentComposition[],\n\tknownRefs: ReadonlySet<string>,\n\toptions: { readonly allowExternalRequirements: boolean },\n): DeclaredEdgesResult {\n\tconst edges: DeclaredEdge[] = [];\n\tconst producersByFact = new Map<\n\t\tstring,\n\t\t{\n\t\t\treadonly opRef: string;\n\t\t\treadonly available: 'after-operation' | 'after-commit';\n\t\t}[]\n\t>();\n\n\tfor (const declaration of declarations) {\n\t\tfor (const producer of declaration.produces ?? []) {\n\t\t\tif (!knownRefs.has(producer.opRef)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `composition producer ${producer.opRef} references an unknown operation`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst key = transitionCompositionFactKey(producer.fact);\n\t\t\tconst bucket = producersByFact.get(key) ?? [];\n\t\t\tbucket.push({\n\t\t\t\topRef: producer.opRef,\n\t\t\t\tavailable: producer.available,\n\t\t\t});\n\t\t\tproducersByFact.set(key, bucket);\n\t\t}\n\t}\n\n\tfor (const declaration of declarations) {\n\t\tfor (const requirement of declaration.requires ?? []) {\n\t\t\tif (!knownRefs.has(requirement.opRef)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `composition requirement ${requirement.opRef} references an unknown operation`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst matches =\n\t\t\t\tproducersByFact.get(transitionCompositionFactKey(requirement.fact)) ??\n\t\t\t\t[];\n\t\t\tif (matches.length === 0) {\n\t\t\t\tif (options.allowExternalRequirements) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `unsatisfied composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (matches.length > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `ambiguous composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst producer = matches[0];\n\t\t\tif (!producer) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `unsatisfied composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tedges.push({\n\t\t\t\tbefore: producer.opRef,\n\t\t\t\tafter: requirement.opRef,\n\t\t\t\trequiresCommitBetween:\n\t\t\t\t\trequirement.needs === 'producer-after-commit' ||\n\t\t\t\t\tproducer.available === 'after-commit',\n\t\t\t\treason: `composition requirement ${requirement.fact.kind}`,\n\t\t\t});\n\t\t}\n\n\t\tfor (const order of declaration.order ?? []) {\n\t\t\tif (!knownRefs.has(order.before)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `composition order ${order.before} -> ${order.after} references an unknown before operation`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!knownRefs.has(order.after)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `composition order ${order.before} -> ${order.after} references an unknown after operation`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tedges.push({\n\t\t\t\tbefore: order.before,\n\t\t\t\tafter: order.after,\n\t\t\t\trequiresCommitBetween: order.requiresCommitBetween === true,\n\t\t\t\treason: order.reason,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { ok: true, edges };\n}\n\nfunction buildConstraints(\n\toperations: readonly CompositionOperation[],\n\tdeclarations: readonly TransitionFragmentComposition[],\n): ConstraintBuildResult {\n\tconst dependents = new Map<string, Set<string>>();\n\tconst dependencyRefs = new Map<string, Set<string>>();\n\tconst commitEdges = new Set<string>();\n\tconst declaredPairs = new Set<string>();\n\tfor (const entry of operations) {\n\t\tdependents.set(entry.operation.ref, new Set());\n\t\tdependencyRefs.set(entry.operation.ref, new Set());\n\t}\n\n\tif (operations.length > 1 && operations.some(hasContextMutation)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail:\n\t\t\t\t'composition contains contextMutations without an explicit context dependency proof',\n\t\t};\n\t}\n\n\tconst knownRefs = new Set(operations.map((entry) => entry.operation.ref));\n\tconst operationByRef = new Map(\n\t\toperations.map((entry) => [entry.operation.ref, entry]),\n\t);\n\tconst edges = declaredEdges(declarations, knownRefs, {\n\t\tallowExternalRequirements: operations.length === 1,\n\t});\n\tif (!edges.ok) {\n\t\treturn edges;\n\t}\n\tfor (const edge of edges.edges) {\n\t\tconst before = operationByRef.get(edge.before);\n\t\tconst after = operationByRef.get(edge.after);\n\t\tconst effectsRequireCommit =\n\t\t\tbefore !== undefined && after !== undefined\n\t\t\t\t? effectsInteract(before.effects, after.effects)\n\t\t\t\t: false;\n\t\taddConstraint(dependents, dependencyRefs, commitEdges, declaredPairs, {\n\t\t\t...edge,\n\t\t\trequiresCommitBetween: edge.requiresCommitBetween || effectsRequireCommit,\n\t\t});\n\t}\n\n\tfor (let leftIndex = 0; leftIndex < operations.length; leftIndex += 1) {\n\t\tconst left = operations[leftIndex];\n\t\tif (!left) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (\n\t\t\tlet rightIndex = leftIndex + 1;\n\t\t\trightIndex < operations.length;\n\t\t\trightIndex += 1\n\t\t) {\n\t\t\tconst right = operations[rightIndex];\n\t\t\tif (!right) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst leftRef = left.operation.ref;\n\t\t\tconst rightRef = right.operation.ref;\n\t\t\tif (\n\t\t\t\t!declaredPairs.has(unorderedEdgeKey(leftRef, rightRef)) &&\n\t\t\t\t(effectsInteract(left.effects, right.effects) ||\n\t\t\t\t\trequiredClaimsInvalidate(left, right))\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tdetail: `unproven interaction between ${leftRef} and ${rightRef} — declare an order`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tok: true,\n\t\tdependents,\n\t\tdependencyRefs,\n\t\tcommitEdges,\n\t\tdeclaredPairs,\n\t};\n}\n\nexport function composeOperations(\n\toperations: readonly CompositionOperation[],\n\tdeclarations: readonly TransitionFragmentComposition[] = [],\n): CompositionResult {\n\tif (operations.length === 0) {\n\t\treturn { ok: false, detail: 'missing operations' };\n\t}\n\tconst byRef = new Map<string, CompositionOperation>();\n\tfor (const entry of operations) {\n\t\tif (byRef.has(entry.operation.ref)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `duplicate operation ref ${entry.operation.ref}`,\n\t\t\t};\n\t\t}\n\t\tbyRef.set(entry.operation.ref, entry);\n\t\tif (\n\t\t\toperations.length > 1 &&\n\t\t\tentry.effects.effects.externalEffects.couldNotAccountFor.length > 0\n\t\t) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `operation ${entry.operation.ref} has unaccounted external effects`,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst constraints = buildConstraints(operations, declarations);\n\tif (!constraints.ok) {\n\t\treturn constraints;\n\t}\n\tconst { dependents, dependencyRefs, commitEdges } = constraints;\n\tconst indegree = new Map<string, number>();\n\tconst compareRefs = (left: string, right: string): number => {\n\t\tconst leftEntry = byRef.get(left);\n\t\tconst rightEntry = byRef.get(right);\n\t\tif (!leftEntry || !rightEntry) {\n\t\t\treturn left < right ? -1 : left > right ? 1 : 0;\n\t\t}\n\t\treturn compareStableCompositionOrder(leftEntry, rightEntry);\n\t};\n\tfor (const entry of operations) {\n\t\tindegree.set(\n\t\t\tentry.operation.ref,\n\t\t\tdependencyRefs.get(entry.operation.ref)?.size ?? 0,\n\t\t);\n\t}\n\n\tconst ordered: OrderedCompositionOperation[] = [];\n\tconst emitted = new Set<string>();\n\tlet ready = operations\n\t\t.filter((entry) => indegree.get(entry.operation.ref) === 0)\n\t\t.map((entry) => entry.operation.ref)\n\t\t.sort(compareRefs);\n\twhile (ordered.length < operations.length) {\n\t\tif (ready.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: 'composition dependency cycle detected',\n\t\t\t};\n\t\t}\n\n\t\tconst ref = ready[0];\n\t\tif (!ref) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: 'composition dependency cycle detected',\n\t\t\t};\n\t\t}\n\t\tready = ready.slice(1);\n\t\tconst entry = byRef.get(ref);\n\t\tif (!entry) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tdetail: `composition references unknown operation ${ref}`,\n\t\t\t};\n\t\t}\n\t\tconst dependencies = [...(dependencyRefs.get(ref) ?? [])].sort(compareRefs);\n\t\tordered.push({\n\t\t\t...entry,\n\t\t\tdependsOn: dependencies,\n\t\t\trequiresCommitBefore: dependencies.some((dependency) =>\n\t\t\t\tcommitEdges.has(edgeKey(dependency, ref)),\n\t\t\t),\n\t\t});\n\t\temitted.add(ref);\n\t\tfor (const dependent of dependents.get(ref) ?? []) {\n\t\t\tconst next = (indegree.get(dependent) ?? 0) - 1;\n\t\t\tindegree.set(dependent, next);\n\t\t\tif (next === 0 && !emitted.has(dependent)) {\n\t\t\t\tready.push(dependent);\n\t\t\t}\n\t\t}\n\t\tready = ready.sort(compareRefs);\n\t}\n\n\tconst invalidatedClaimDetail = invalidatedRequiredClaimDetail(ordered);\n\tif (invalidatedClaimDetail) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tdetail: invalidatedClaimDetail,\n\t\t};\n\t}\n\n\treturn {\n\t\tok: true,\n\t\toperations: ordered,\n\t\tsegments: composeSegments(ordered),\n\t};\n}\n","import type {\n\tCompareOutcome,\n\tModelIR,\n\tObservationContext,\n\tPlanAssessment,\n\tResourceAddress,\n\tTransitionCandidate,\n\tTransitionFragmentComposition,\n} from '@dbsp/types';\nimport {\n\ttransitionCompareCurrentModel,\n\twithTransitionCompareCurrentModel,\n} from './comparator.js';\nimport { transitionCompositionFactKey } from './composer.js';\nimport type { PackRegistry } from './registry.js';\nimport { stableJson } from './stable-json.js';\n\ntype TransitionCompare = Extract<\n\tCompareOutcome,\n\t{ readonly kind: 'transitions' }\n>;\ntype CompositionProducer = NonNullable<\n\tTransitionFragmentComposition['produces']\n>[number];\ntype CompositionRequirement = NonNullable<\n\tTransitionFragmentComposition['requires']\n>[number];\n\nexport interface StagedCompositionCandidate {\n\treadonly candidate: TransitionCandidate;\n\treadonly index: number;\n\treadonly composition?: TransitionFragmentComposition;\n\treadonly opRefs: readonly string[];\n}\n\nexport type StagedCompositionPreflight =\n\t| {\n\t\t\treadonly kind: 'provable-in-stages';\n\t\t\treadonly ready: readonly StagedCompositionCandidate[];\n\t\t\treadonly pending: readonly StagedCompositionCandidate[];\n\t\t\treadonly detail?: string;\n\t }\n\t| {\n\t\t\treadonly kind: 'unsupported-transition';\n\t\t\treadonly assessment: PlanAssessment;\n\t };\n\nexport interface StagedCompositionPreflightInput {\n\treadonly compare: TransitionCompare;\n\treadonly current: ModelIR;\n\treadonly context: ObservationContext;\n}\n\nfunction uniqueResources(\n\tresources: readonly ResourceAddress[],\n): readonly ResourceAddress[] {\n\tconst byKey = new Map<string, ResourceAddress>();\n\tfor (const resource of resources) {\n\t\tbyKey.set(stableJson(resource), resource);\n\t}\n\treturn [...byKey.values()];\n}\n\nfunction candidateResources(\n\tcandidates: readonly TransitionCandidate[],\n): readonly ResourceAddress[] {\n\treturn uniqueResources(\n\t\tcandidates.flatMap((candidate) =>\n\t\t\tcandidate.obligations.flatMap((obligation) => [...obligation.scope]),\n\t\t),\n\t);\n}\n\nfunction unsupportedAssessment(\n\tdetail: string,\n\tchanges: readonly ResourceAddress[],\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'replan-required',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'unsupported-transition',\n\t\t\t\tchanges,\n\t\t\t\tscope: changes,\n\t\t\t\tdetail,\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction unsupported(\n\tdetail: string,\n\tcandidates: readonly TransitionCandidate[],\n\textraChanges: readonly ResourceAddress[] = [],\n): StagedCompositionPreflight {\n\tconst changes = uniqueResources([\n\t\t...candidateResources(candidates),\n\t\t...extraChanges,\n\t]);\n\treturn {\n\t\tkind: 'unsupported-transition',\n\t\tassessment: unsupportedAssessment(detail, changes),\n\t};\n}\n\nfunction ambiguousRule(\n\tdetail: string,\n\tcandidates: readonly TransitionCandidate[],\n): StagedCompositionPreflight {\n\treturn {\n\t\tkind: 'unsupported-transition',\n\t\tassessment: {\n\t\t\tdecision: 'blocked',\n\t\t\tassurance: 'unproven',\n\t\t\tlifecycle: 'planned',\n\t\t\tcontinuation: 'replan-required',\n\t\t\treasons: [\n\t\t\t\t{\n\t\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\t\tcandidates: candidates.map((candidate) => candidate.rule),\n\t\t\t\t\tscope: candidateResources(candidates),\n\t\t\t\t\tdetail,\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t};\n}\n\nfunction compositionOpRefs(\n\tcomposition: TransitionFragmentComposition | undefined,\n): readonly string[] {\n\treturn [\n\t\t...(composition?.produces ?? []).map((producer) => producer.opRef),\n\t\t...(composition?.requires ?? []).map((requirement) => requirement.opRef),\n\t\t...(composition?.order ?? []).flatMap((order) => [\n\t\t\torder.before,\n\t\t\torder.after,\n\t\t]),\n\t].filter((value, index, values) => values.indexOf(value) === index);\n}\n\nfunction requirementNeedsCommit(\n\trequirement: CompositionRequirement,\n\tproducer: CompositionProducer,\n): boolean {\n\treturn (\n\t\trequirement.needs === 'producer-after-commit' ||\n\t\tproducer.available === 'after-commit'\n\t);\n}\n\nexport function preflightStagedComposition(\n\tregistry: PackRegistry,\n\tinput: StagedCompositionPreflightInput,\n): StagedCompositionPreflight {\n\tconst entries: StagedCompositionCandidate[] = [];\n\tconst ownerByOpRef = new Map<string, StagedCompositionCandidate>();\n\tfor (const [index, candidate] of input.compare.candidates.entries()) {\n\t\tconst rule = registry.resolveRule(candidate.rule);\n\t\tif (!rule) {\n\t\t\treturn unsupported(\n\t\t\t\t`transition rule ${candidate.rule.id} did not resolve`,\n\t\t\t\tinput.compare.candidates,\n\t\t\t);\n\t\t}\n\t\tlet composition: TransitionFragmentComposition | undefined;\n\t\ttry {\n\t\t\tcomposition = rule.declareComposition?.(candidate.match, input.context);\n\t\t} catch (error) {\n\t\t\treturn unsupported(\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: 'transition composition declaration failed',\n\t\t\t\tinput.compare.candidates,\n\t\t\t);\n\t\t}\n\t\tconst entry: StagedCompositionCandidate = {\n\t\t\tcandidate,\n\t\t\tindex,\n\t\t\t...(composition ? { composition } : {}),\n\t\t\topRefs: compositionOpRefs(composition),\n\t\t};\n\t\tfor (const opRef of entry.opRefs) {\n\t\t\tif (ownerByOpRef.has(opRef)) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`duplicate composition operation ref ${opRef}`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t);\n\t\t\t}\n\t\t\townerByOpRef.set(opRef, entry);\n\t\t}\n\t\tentries.push(entry);\n\t}\n\n\tconst producersByFact = new Map<\n\t\tstring,\n\t\treadonly {\n\t\t\treadonly entry: StagedCompositionCandidate;\n\t\t\treadonly producer: CompositionProducer;\n\t\t}[]\n\t>();\n\tfor (const entry of entries) {\n\t\tfor (const producer of entry.composition?.produces ?? []) {\n\t\t\tconst owner = ownerByOpRef.get(producer.opRef);\n\t\t\tif (owner !== entry) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`composition producer ${producer.opRef} references an unknown operation`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t\t[producer.fact.resource],\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = transitionCompositionFactKey(producer.fact);\n\t\t\tproducersByFact.set(key, [\n\t\t\t\t...(producersByFact.get(key) ?? []),\n\t\t\t\t{ entry, producer },\n\t\t\t]);\n\t\t}\n\t}\n\n\tconst pendingByIndex = new Map<number, Set<number>>();\n\tlet declaredRequirementCount = 0;\n\tfor (const entry of entries) {\n\t\tfor (const requirement of entry.composition?.requires ?? []) {\n\t\t\tdeclaredRequirementCount += 1;\n\t\t\tconst owner = ownerByOpRef.get(requirement.opRef);\n\t\t\tif (owner !== entry) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`composition requirement ${requirement.opRef} references an unknown operation`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tregistry.satisfiesCompositionFact(\n\t\t\t\t\trequirement.fact,\n\t\t\t\t\tinput.current,\n\t\t\t\t\tinput.context,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst producers =\n\t\t\t\tproducersByFact.get(transitionCompositionFactKey(requirement.fact)) ??\n\t\t\t\t[];\n\t\t\tif (producers.length === 0) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`unsatisfied composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (producers.length > 1) {\n\t\t\t\treturn ambiguousRule(\n\t\t\t\t\t`ambiguous composition requirement ${requirement.opRef} requires ${requirement.fact.kind}`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst producer = producers[0];\n\t\t\tif (!producer || producer.entry === entry) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`composition requirement ${requirement.opRef} is not staged by a prior producer`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!requirementNeedsCommit(requirement, producer.producer)) {\n\t\t\t\treturn unsupported(\n\t\t\t\t\t`composition requirement ${requirement.opRef} does not declare a producer-commit edge`,\n\t\t\t\t\tinput.compare.candidates,\n\t\t\t\t\t[requirement.fact.resource],\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst producerIndexes = pendingByIndex.get(entry.index) ?? new Set();\n\t\t\tproducerIndexes.add(producer.entry.index);\n\t\t\tpendingByIndex.set(entry.index, producerIndexes);\n\t\t}\n\t}\n\n\tconst ready = entries.filter((entry) => !pendingByIndex.has(entry.index));\n\tconst pending = entries.filter((entry) => pendingByIndex.has(entry.index));\n\n\tif (input.compare.candidates.length > 1 && declaredRequirementCount === 0) {\n\t\treturn unsupported(\n\t\t\t'multi-candidate transition has no declared composition dependency',\n\t\t\tinput.compare.candidates,\n\t\t);\n\t}\n\tfor (const [candidateIndex, producerIndexes] of pendingByIndex) {\n\t\tif (producerIndexes.size !== 1) {\n\t\t\tconst candidate = entries[candidateIndex];\n\t\t\treturn unsupported(\n\t\t\t\t`staged candidate ${\n\t\t\t\t\tcandidate?.candidate.rule.id ?? candidateIndex\n\t\t\t\t} does not have exactly one producer`,\n\t\t\t\tinput.compare.candidates,\n\t\t\t);\n\t\t}\n\t}\n\tif (input.compare.candidates.length > 1 && pending.length > 0) {\n\t\tconst producerIndexes = new Set(\n\t\t\t[...pendingByIndex.values()].flatMap((indexes) => [...indexes]),\n\t\t);\n\t\tconst disconnectedReady = ready.filter(\n\t\t\t(entry) => !producerIndexes.has(entry.index),\n\t\t);\n\t\tif (disconnectedReady.length > 0) {\n\t\t\treturn unsupported(\n\t\t\t\t'multi-candidate transition contains an unconnected ready candidate',\n\t\t\t\tinput.compare.candidates,\n\t\t\t);\n\t\t}\n\t}\n\tif (ready.length === 0) {\n\t\treturn unsupported(\n\t\t\t'staged transition has no ready candidate',\n\t\t\tinput.compare.candidates,\n\t\t);\n\t}\n\n\treturn {\n\t\tkind: 'provable-in-stages',\n\t\tready,\n\t\tpending,\n\t\t...(pending.length > 0\n\t\t\t? { detail: 'transition is provable in stages' }\n\t\t\t: {}),\n\t};\n}\n\nexport function chooseReadyCandidate(\n\tpreflight: Extract<\n\t\tStagedCompositionPreflight,\n\t\t{ readonly kind: 'provable-in-stages' }\n\t>,\n): StagedCompositionCandidate {\n\tconst candidate = [...preflight.ready].sort(\n\t\t(left, right) => left.index - right.index,\n\t)[0];\n\tif (!candidate) {\n\t\tthrow new Error('staged composition preflight has no ready candidate');\n\t}\n\treturn candidate;\n}\n\nexport function projectCompareToSingleCandidate(\n\tcompare: TransitionCompare,\n\tentry: StagedCompositionCandidate,\n): TransitionCompare {\n\tif (compare.candidates[entry.index] !== entry.candidate) {\n\t\tthrow new Error('ready candidate does not belong to the supplied compare');\n\t}\n\tconst projected: TransitionCompare = {\n\t\tkind: 'transitions',\n\t\tcandidates: [entry.candidate],\n\t\tobligations: entry.candidate.obligations,\n\t};\n\tconst current = transitionCompareCurrentModel(compare);\n\treturn current\n\t\t? withTransitionCompareCurrentModel(projected, current)\n\t\t: projected;\n}\n","import type {\n\tApplyPolicy,\n\tApplyResult,\n\tCompareOutcome,\n\tEquivalenceContext,\n\tIssuedObservation,\n\tModelIR,\n\tObservationContext,\n\tOutcomeReason,\n\tPlanAssessment,\n\tResourceAddress,\n\tStepJournal,\n\tTransitionCandidate,\n\tTransitionLessor,\n} from '@dbsp/types';\nimport { createApplier } from './applier.js';\nimport { createComparator } from './comparator.js';\nimport { claimId, semanticArtifactId } from './ids.js';\nimport type { TransitionRunPersister } from './index.js';\nimport { createProver } from './prover.js';\nimport type { PackRegistry } from './registry.js';\nimport { stableJson } from './stable-json.js';\nimport {\n\tchooseReadyCandidate,\n\tpreflightStagedComposition,\n\tprojectCompareToSingleCandidate,\n} from './staging.js';\nimport {\n\tisTransitionLessor,\n\ttransitionLessorRejectionAssessment,\n} from './transition-lessor.js';\n\nexport interface StagedTransitionInput {\n\treadonly desired: ModelIR;\n\treadonly loadCurrent: () => Promise<ModelIR>;\n\treadonly readContext: () => Promise<ObservationContext>;\n\treadonly target: TransitionLessor;\n\treadonly policy: ApplyPolicy;\n\treadonly maxIterations?: number;\n}\n\nexport interface StagedTransitionOrchestrator {\n\tapplyStagedTransition(input: StagedTransitionInput): Promise<ApplyResult>;\n}\n\nconst STAGED_ORCHESTRATOR_ARTIFACT = {\n\tid: semanticArtifactId('dbsp.core.transition.staged-orchestrator'),\n\tversion: '0.1.0',\n};\n\nfunction uniqueResources(\n\tresources: readonly ResourceAddress[],\n): readonly ResourceAddress[] {\n\tconst byKey = new Map<string, ResourceAddress>();\n\tfor (const resource of resources) {\n\t\tbyKey.set(stableJson(resource), resource);\n\t}\n\treturn [...byKey.values()];\n}\n\nfunction candidateResources(\n\tcandidates: readonly TransitionCandidate[],\n): readonly ResourceAddress[] {\n\treturn uniqueResources(\n\t\tcandidates.flatMap((candidate) =>\n\t\t\tcandidate.obligations.flatMap((obligation) => [...obligation.scope]),\n\t\t),\n\t);\n}\n\nfunction equivalenceContextFromObservation(\n\tcontext: ObservationContext,\n): EquivalenceContext & {\n\treadonly proofObservationContext: ObservationContext;\n} {\n\treturn {\n\t\tengine: context.engine,\n\t\t...(context.databaseId ? { databaseId: context.databaseId } : {}),\n\t\t...(context.targetSchema ? { targetSchema: context.targetSchema } : {}),\n\t\t...(context.searchPath ? { searchPath: context.searchPath } : {}),\n\t\tproofObservationContext: context,\n\t};\n}\n\nfunction blockedAssessment(reason: OutcomeReason): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'replan-required',\n\t\treasons: [reason],\n\t};\n}\n\nfunction unsupportedAssessment(\n\tdetail: string,\n\tchanges: readonly ResourceAddress[],\n): PlanAssessment {\n\treturn blockedAssessment({\n\t\tcode: 'unsupported-transition',\n\t\tchanges,\n\t\tscope: changes,\n\t\tdetail,\n\t});\n}\n\nfunction compareBlockedAssessment(compare: CompareOutcome): PlanAssessment {\n\tswitch (compare.kind) {\n\t\tcase 'unsupported':\n\t\t\treturn unsupportedAssessment(\n\t\t\t\t'compare returned an unsupported transition',\n\t\t\t\tcompare.changes,\n\t\t\t);\n\t\tcase 'ambiguous':\n\t\t\treturn blockedAssessment({\n\t\t\t\tcode: 'ambiguous-rule',\n\t\t\t\tcandidates: compare.candidates,\n\t\t\t\tscope: [],\n\t\t\t\tdetail: 'compare returned ambiguous transition rules',\n\t\t\t});\n\t\tcase 'unknown': {\n\t\t\tconst obligation = compare.obligations[0];\n\t\t\tif (obligation) {\n\t\t\t\treturn blockedAssessment({\n\t\t\t\t\tcode: 'insufficient-evidence',\n\t\t\t\t\tobligation,\n\t\t\t\t\tscope: obligation.scope,\n\t\t\t\t\tdetail: 'compare returned unknown transition recognition',\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn unsupportedAssessment(\n\t\t\t\t'compare returned unknown transition recognition',\n\t\t\t\t[],\n\t\t\t);\n\t\t}\n\t\tcase 'uncomposable':\n\t\t\treturn blockedAssessment({\n\t\t\t\tcode: 'uncomposable',\n\t\t\t\tfragments: compare.candidates.map((candidate) => candidate.rule),\n\t\t\t\tscope: candidateResources(compare.candidates),\n\t\t\t\tdetail: compare.detail,\n\t\t\t});\n\t\tcase 'transitions':\n\t\t\treturn unsupportedAssessment(\n\t\t\t\t'transition compare contained no candidate to stage',\n\t\t\t\tcandidateResources(compare.candidates),\n\t\t\t);\n\t\tcase 'no-drift':\n\t\t\treturn noDriftAssessment();\n\t}\n}\n\nfunction obligationResources(\n\tobligations: readonly { readonly scope: readonly ResourceAddress[] }[],\n): readonly ResourceAddress[] {\n\treturn uniqueResources(\n\t\tobligations.flatMap((obligation) => [...obligation.scope]),\n\t);\n}\n\nfunction convergenceProvenAssessment(\n\tcompare: Extract<CompareOutcome, { readonly kind: 'unknown' }>,\n): PlanAssessment {\n\treturn unsupportedAssessment(\n\t\t'post-apply convergence proof returned an executable plan for remaining drift; staged transition orchestration did not recognize a stageable transition candidate',\n\t\tobligationResources(compare.obligations),\n\t);\n}\n\nfunction noDriftAssessment(): PlanAssessment {\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance: 'established',\n\t\tlifecycle: 'completed',\n\t\tcontinuation: 'none',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'proven-applicable',\n\t\t\t\tclaim: claimId('dbsp.transition.claim.no-drift'),\n\t\t\t\tscope: [],\n\t\t\t\tdetail: 'no drift remains after staged transition orchestration',\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction hasAppliedWork(journals: readonly StepJournal[]): boolean {\n\treturn journals.some((journal) =>\n\t\t['completed', 'partially-applied', 'unknown-step-result'].includes(\n\t\t\tjournal.outcome,\n\t\t),\n\t);\n}\n\nfunction aggregateAssessment(\n\tassessment: PlanAssessment,\n\tjournals: readonly StepJournal[],\n): PlanAssessment {\n\tif (!hasAppliedWork(journals) || assessment.decision === 'applicable') {\n\t\treturn assessment;\n\t}\n\treturn {\n\t\t...assessment,\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'partially-applied',\n\t\tcontinuation: 'resume-possible',\n\t};\n}\n\nfunction resultWithAggregate(\n\tassessment: PlanAssessment,\n\tjournals: readonly StepJournal[],\n\tobservations: readonly IssuedObservation[],\n\trecovery?: ApplyResult['recovery'],\n): ApplyResult {\n\treturn {\n\t\tassessment: aggregateAssessment(assessment, journals),\n\t\tjournals,\n\t\tobservations,\n\t\t...(recovery ? { recovery } : {}),\n\t};\n}\n\nfunction candidateProgressKey(entry: {\n\treadonly candidate: TransitionCandidate;\n\treadonly opRefs: readonly string[];\n}): string {\n\treturn entry.opRefs.length > 0\n\t\t? stableJson({ opRefs: entry.opRefs })\n\t\t: stableJson({\n\t\t\t\trule: entry.candidate.rule,\n\t\t\t\tmatch: entry.candidate.match,\n\t\t\t});\n}\n\nfunction completedJournalRefs(\n\tjournals: readonly StepJournal[],\n): readonly string[] {\n\treturn journals\n\t\t.filter((journal) => journal.outcome === 'completed')\n\t\t.map((journal) => journal.intent.operation.ref);\n}\n\nexport function createStagedTransitionOrchestrator(\n\tregistry: PackRegistry,\n\tpersister: TransitionRunPersister,\n): StagedTransitionOrchestrator {\n\tconst comparator = createComparator(registry);\n\tconst prover = createProver(registry);\n\tconst applier = createApplier(registry, persister);\n\treturn {\n\t\tasync applyStagedTransition(\n\t\t\tinput: StagedTransitionInput,\n\t\t): Promise<ApplyResult> {\n\t\t\tconst journals: StepJournal[] = [];\n\t\t\tconst observations: IssuedObservation[] = [];\n\t\t\tconst completedProgress = new Set<string>();\n\t\t\tconst maxIterations = input.maxIterations ?? 32;\n\t\t\tconst targetRejectionResult = (): ApplyResult =>\n\t\t\t\tresultWithAggregate(\n\t\t\t\t\ttransitionLessorRejectionAssessment(STAGED_ORCHESTRATOR_ARTIFACT),\n\t\t\t\t\tjournals,\n\t\t\t\t\tobservations,\n\t\t\t\t);\n\t\t\tconst proveAtTargetBoundary = async (\n\t\t\t\tcompare: CompareOutcome,\n\t\t\t\tcontext: ObservationContext,\n\t\t\t): Promise<\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: 'proof';\n\t\t\t\t\t\treadonly proof: Awaited<ReturnType<typeof prover.prove>>;\n\t\t\t\t }\n\t\t\t\t| { readonly kind: 'target-rejected' }\n\t\t\t> => {\n\t\t\t\tif (!isTransitionLessor(input.target)) {\n\t\t\t\t\treturn { kind: 'target-rejected' };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'proof',\n\t\t\t\t\tproof: await prover.prove(compare, input.target, context),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tfor (let iteration = 0; iteration < maxIterations; iteration += 1) {\n\t\t\t\tconst context = await input.readContext();\n\t\t\t\tconst current = await input.loadCurrent();\n\t\t\t\tconst compare = comparator.compare(\n\t\t\t\t\tinput.desired,\n\t\t\t\t\tcurrent,\n\t\t\t\t\tequivalenceContextFromObservation(context),\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tcompare.kind === 'no-drift' ||\n\t\t\t\t\t(compare.kind === 'transitions' && compare.candidates.length === 0)\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tassessment: noDriftAssessment(),\n\t\t\t\t\t\tjournals,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (compare.kind !== 'transitions') {\n\t\t\t\t\tif (compare.kind === 'unknown' && hasAppliedWork(journals)) {\n\t\t\t\t\t\tconst proofAtBoundary = await proveAtTargetBoundary(\n\t\t\t\t\t\t\tcompare,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (proofAtBoundary.kind === 'target-rejected') {\n\t\t\t\t\t\t\treturn targetRejectionResult();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { proof } = proofAtBoundary;\n\t\t\t\t\t\tswitch (proof.kind) {\n\t\t\t\t\t\t\tcase 'no-drift':\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tassessment: noDriftAssessment(),\n\t\t\t\t\t\t\t\t\tjournals,\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcase 'blocked':\n\t\t\t\t\t\t\tcase 'inapplicable':\n\t\t\t\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\t\t\t\tproof.assessment,\n\t\t\t\t\t\t\t\t\tjournals,\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcase 'proven':\n\t\t\t\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\t\t\t\tconvergenceProvenAssessment(compare),\n\t\t\t\t\t\t\t\t\tjournals,\n\t\t\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\tcompareBlockedAssessment(compare),\n\t\t\t\t\t\tjournals,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst preflight = preflightStagedComposition(registry, {\n\t\t\t\t\tcompare,\n\t\t\t\t\tcurrent,\n\t\t\t\t\tcontext,\n\t\t\t\t});\n\t\t\t\tif (preflight.kind === 'unsupported-transition') {\n\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\tpreflight.assessment,\n\t\t\t\t\t\tjournals,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst ready = chooseReadyCandidate(preflight);\n\t\t\t\tconst progressKey = candidateProgressKey(ready);\n\t\t\t\tif (completedProgress.has(progressKey)) {\n\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\tunsupportedAssessment(\n\t\t\t\t\t\t\t'staged transition did not converge; the same ready candidate remained after a completed apply',\n\t\t\t\t\t\t\tcandidateResources(compare.candidates),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tjournals,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst segmentCompare = projectCompareToSingleCandidate(compare, ready);\n\t\t\t\tconst proofAtBoundary = await proveAtTargetBoundary(\n\t\t\t\t\tsegmentCompare,\n\t\t\t\t\tcontext,\n\t\t\t\t);\n\t\t\t\tif (proofAtBoundary.kind === 'target-rejected') {\n\t\t\t\t\treturn targetRejectionResult();\n\t\t\t\t}\n\t\t\t\tconst { proof } = proofAtBoundary;\n\t\t\t\tif (proof.kind !== 'proven') {\n\t\t\t\t\treturn resultWithAggregate(proof.assessment, journals, observations);\n\t\t\t\t}\n\n\t\t\t\tconst applyResult = await applier.apply(\n\t\t\t\t\t{ plan: proof.plan, assessment: proof.assessment },\n\t\t\t\t\tinput.policy,\n\t\t\t\t\tinput.target,\n\t\t\t\t);\n\t\t\t\tjournals.push(...applyResult.journals);\n\t\t\t\tobservations.push(...applyResult.observations);\n\n\t\t\t\tif (\n\t\t\t\t\tapplyResult.assessment.decision !== 'applicable' ||\n\t\t\t\t\tapplyResult.assessment.lifecycle !== 'completed'\n\t\t\t\t) {\n\t\t\t\t\treturn resultWithAggregate(\n\t\t\t\t\t\tapplyResult.assessment,\n\t\t\t\t\t\tjournals,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t\tapplyResult.recovery,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tfor (const ref of completedJournalRefs(applyResult.journals)) {\n\t\t\t\t\tcompletedProgress.add(stableJson({ opRefs: [ref] }));\n\t\t\t\t}\n\t\t\t\tcompletedProgress.add(progressKey);\n\t\t\t}\n\n\t\t\treturn resultWithAggregate(\n\t\t\t\tunsupportedAssessment(\n\t\t\t\t\t`staged transition did not converge within ${maxIterations} iterations`,\n\t\t\t\t\t[],\n\t\t\t\t),\n\t\t\t\tjournals,\n\t\t\t\tobservations,\n\t\t\t);\n\t\t},\n\t};\n}\n","/**\n * Adapter interface for database adapters.\n *\n * Type definitions live in @dbsp/types. This module re-exports them\n * and provides runtime functions and error classes.\n *\n * @module adapter\n */\n\n// Re-export all adapter types from @dbsp/types for backward compatibility\nexport type {\n\tAdapter,\n\tAdapterCapabilities,\n\tAdapterLogger,\n\tAdapterStreamOptions,\n\tAliasIncludedColumnsMode,\n\tAlterColumnOptions,\n\tBaseAdapter,\n\tCompiledQuery,\n\tCompileOnlyAdapter,\n\tCompileOptions,\n\tCompileResultWithIncludes,\n\tCompilingAdapter,\n\tConnectionAvailability,\n\tCreateIndexOptions,\n\tDbCasing,\n\tDropIndexOptions,\n\tDump,\n\tDumpMeta,\n\tDumpSequenceStep,\n\tExecutingAdapter,\n\tIndexColumnDef,\n\tIndexInfo,\n\tIndexMethod,\n\tIntrospectingAdapter,\n\tIntrospectionOptions,\n\tIntrospectionResult,\n\tNqlRuntimeBinding,\n\tRawSqlAdapter,\n\tStreamingAdapter,\n\tSubqueryIncludeInfo,\n\tTableDDLGeneratorAdapter,\n\tTransactionalAdapter,\n\tTransactionOptions,\n\tTruncateOptions,\n\tVacuumOptions,\n} from '@dbsp/types';\n\nimport type {\n\tAdapter,\n\tAdapterCapabilities,\n\tBaseAdapter,\n\tCompiledQuery,\n\tExecutingAdapter,\n\tIntrospectingAdapter,\n\tRawSqlAdapter,\n\tStreamingAdapter,\n\tTransactionalAdapter,\n} from '@dbsp/types';\nimport { ExecutionError } from './dx/errors.js';\n\n// ============================================================================\n// Feature Detection Helpers (DX-104)\n// ============================================================================\n\n/**\n * Check if adapter supports execution.\n */\nexport function supportsExecution(\n\tadapter: BaseAdapter,\n): adapter is ExecutingAdapter {\n\tconst connectionProvider = adapter as BaseAdapter & {\n\t\texecutionAvailable?: () => boolean;\n\t\tgetPoolInstance?: () => unknown;\n\t};\n\tif (typeof connectionProvider.executionAvailable === 'function') {\n\t\treturn connectionProvider.executionAvailable();\n\t}\n\tif (typeof connectionProvider.getPoolInstance === 'function') {\n\t\ttry {\n\t\t\tconnectionProvider.getPoolInstance();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn (\n\t\ttypeof (adapter as ExecutingAdapter).execute === 'function' &&\n\t\ttypeof (adapter as ExecutingAdapter).executeOne === 'function' &&\n\t\ttypeof (adapter as ExecutingAdapter).executeOneOrThrow === 'function'\n\t);\n}\n\n/**\n * Refuse execution for adapters that explicitly report no connection.\n *\n * The availability declaration is optional so existing third-party adapters\n * continue through the established capability checks unchanged.\n */\nexport function assertConnectionAvailable(\n\tadapter: BaseAdapter,\n\toperation: string,\n): void {\n\tconst availability = adapter.connectionAvailability;\n\tif (availability?.status === 'unavailable') {\n\t\tthrow new ExecutionError({\n\t\t\toperation,\n\t\t\treason: availability.reason,\n\t\t\tfix: availability.fix,\n\t\t});\n\t}\n}\n\n/**\n * The execution funnel for compiled queries.\n *\n * Every core terminal delegates to this function immediately before it reaches\n * an adapter's execute() method, so connectionless adapters are refused\n * consistently without each terminal owning an availability check.\n */\nexport function executeCompiledQuery<T>(\n\tadapter: Adapter,\n\tquery: CompiledQuery<T>,\n\toperation: string,\n): Promise<T[]> {\n\tassertConnectionAvailable(adapter, operation);\n\treturn adapter.execute(query);\n}\n\n/**\n * Metadata-returning branch of the compiled-query execution funnel.\n */\nexport function executeCompiledQueryWithMeta(\n\tadapter: Adapter,\n\tquery: CompiledQuery,\n\toperation: string,\n): Promise<{\n\treadonly rows: readonly unknown[];\n\treadonly rowCount: number;\n\treadonly command?: string;\n}> {\n\tassertConnectionAvailable(adapter, operation);\n\tif (typeof adapter.executeWithMeta !== 'function') {\n\t\tthrow new ExecutionError({\n\t\t\toperation,\n\t\t\treason: 'this adapter does not implement executeWithMeta',\n\t\t\tfix: 'Use an adapter that implements executeWithMeta.',\n\t\t});\n\t}\n\treturn adapter.executeWithMeta(query);\n}\n\n/**\n * Check if adapter supports streaming.\n */\nexport function supportsStreaming(\n\tadapter: BaseAdapter,\n): adapter is StreamingAdapter {\n\treturn (\n\t\tadapter.capabilities?.supportsStreaming === true &&\n\t\t'stream' in adapter &&\n\t\ttypeof (adapter as StreamingAdapter).stream === 'function'\n\t);\n}\n\n/**\n * Check if adapter supports introspection.\n */\nexport function supportsIntrospection(\n\tadapter: BaseAdapter,\n): adapter is IntrospectingAdapter {\n\treturn (\n\t\t'introspect' in adapter &&\n\t\ttypeof (adapter as IntrospectingAdapter).introspect === 'function'\n\t);\n}\n\n/**\n * Check if adapter supports transactions.\n */\nexport function supportsTransactions<DB>(\n\tadapter: BaseAdapter,\n): adapter is TransactionalAdapter<DB> {\n\treturn (\n\t\tadapter.capabilities?.supportsTransactions === true &&\n\t\t'transaction' in adapter &&\n\t\t'withSchema' in adapter &&\n\t\ttypeof (adapter as TransactionalAdapter<DB>).transaction === 'function'\n\t);\n}\n\n/**\n * Check if adapter supports raw SQL execution.\n */\nexport function supportsRawSql(adapter: BaseAdapter): adapter is RawSqlAdapter {\n\treturn (\n\t\t'executeRaw' in adapter &&\n\t\ttypeof (adapter as RawSqlAdapter).executeRaw === 'function'\n\t);\n}\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error thrown when an operation requires an adapter but none was provided.\n */\nexport class AdapterRequiredError extends Error {\n\tconstructor(operation: string) {\n\t\tsuper(\n\t\t\t`Operation '${operation}' requires an adapter. ` +\n\t\t\t\t'Pass an adapter when creating the ORM: createOrm({ model, adapter })',\n\t\t);\n\t\tthis.name = 'AdapterRequiredError';\n\t}\n}\n\n/**\n * Error thrown when an operation requires a capability the adapter doesn't support.\n */\nexport class UnsupportedCapabilityError extends Error {\n\tconstructor(operation: string, capability: keyof AdapterCapabilities) {\n\t\tsuper(\n\t\t\t`Operation '${operation}' requires capability '${capability}' ` +\n\t\t\t\t'which is not supported by the current adapter.',\n\t\t);\n\t\tthis.name = 'UnsupportedCapabilityError';\n\t}\n}\n\n/**\n * Assert that an adapter supports a required capability.\n */\nexport function assertCapability(\n\tadapter: Adapter,\n\tcapability: keyof AdapterCapabilities,\n\toperation: string,\n): void {\n\tif (!adapter.capabilities[capability]) {\n\t\tthrow new UnsupportedCapabilityError(operation, capability);\n\t}\n}\n","import { validateIdentifier } from './errors.js';\n\n// ============================================================================\n// Structured PostgreSQL type-name grammar\n// ============================================================================\n\n/**\n * Fixed allowlist of known multi-word PostgreSQL base types (case-insensitive).\n * These are the only multi-word base types accepted by the structured grammar;\n * all other base types must be strict SQL identifiers (optionally schema-qualified).\n */\nconst MULTIWORD_BASE_TYPES: readonly string[] = [\n\t'timestamp with time zone',\n\t'timestamp without time zone',\n\t'time with time zone',\n\t'time without time zone',\n\t'double precision',\n\t'character varying',\n\t'bit varying',\n];\n\n/** Match a strict SQL identifier: letter or underscore, then letters/digits/underscores. */\nconst IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Validate a PostgreSQL type name for use in CAST($N AS type[]).\n *\n * Accepted grammar (structured, not a broad character-class):\n * typeName = trim(base [modifier] [arraySuffix])\n *\n * arraySuffix = \"[]\" — at most ONE level; \"int4[][]\" is rejected as a\n * raw type-name input (array-ness is handled by the\n * batch-values layer which appends its own \"[]\").\n * modifier = \"(\" digits \")\" | \"(\" digits \",\" digits \")\"\n * — e.g. \"(255)\", \"(10,2)\"; any other parenthesised\n * content is rejected.\n * base = multiWordType | ident | ident \".\" ident\n * multiWordType = one of: \"timestamp with time zone\",\n * \"timestamp without time zone\",\n * \"time with time zone\",\n * \"time without time zone\",\n * \"double precision\",\n * \"character varying\",\n * \"bit varying\"\n * ident = [A-Za-z_][A-Za-z0-9_]*\n *\n * Examples that pass: int4, text, uuid, numeric(10,2), varchar(255),\n * timestamp with time zone, myschema.myenum, int4[].\n * Examples that throw: empty string, int4[][], int4) ; DROP TABLE x; --,\n * foo'bar, int4)); JOIN users ON true.\n *\n * @internal — exported for adapter compile-time revalidation only.\n */\nexport function validateTypeName(typeName: string): void {\n\tconst raw = typeName.trim();\n\tif (raw.length === 0) {\n\t\tthrow new Error(\n\t\t\t`batchValues: invalid type name '${typeName}'. Type names must not be empty.`,\n\t\t);\n\t}\n\n\tlet rest = raw;\n\n\t// ── Step 1: strip at most ONE trailing array suffix \"[]\" ─────────────────\n\t// More than one \"[]\" (e.g. \"int4[][]\") is rejected by the grammar: after\n\t// stripping one, the remaining rest must NOT end in \"[]\" again.\n\tif (rest.endsWith('[]')) {\n\t\trest = rest.slice(0, -2);\n\t\tif (rest.endsWith('[]')) {\n\t\t\tthrow new Error(\n\t\t\t\t`batchValues: invalid type name '${typeName}'. ` +\n\t\t\t\t\t'At most one array suffix \"[]\" is allowed as a raw type-name input. ' +\n\t\t\t\t\t'Use \"int4[]\" not \"int4[][]\".',\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Step 2: strip optional modifier \"(N)\" or \"(N,M)\" ─────────────────────\n\t// Only digits inside parens; any other parenthesised content is rejected.\n\tconst modifierMatch = rest.match(/\\(([^)]*)\\)$/);\n\tif (modifierMatch) {\n\t\tconst inner = modifierMatch[1] ?? '';\n\t\tif (!/^\\d+(?:,\\d+)?$/.test(inner)) {\n\t\t\tthrow new Error(\n\t\t\t\t`batchValues: invalid type name '${typeName}'. ` +\n\t\t\t\t\t`Type modifier must be \"(N)\" or \"(N,M)\" with digits only; got \"(${inner})\".`,\n\t\t\t);\n\t\t}\n\t\trest = rest.slice(0, rest.length - modifierMatch[0].length).trimEnd();\n\t}\n\n\t// ── Step 3: validate the base type ───────────────────────────────────────\n\tconst baseLower = rest.toLowerCase();\n\n\t// (a) Multi-word allowlist (case-insensitive)\n\tif (MULTIWORD_BASE_TYPES.includes(baseLower)) {\n\t\treturn; // valid\n\t}\n\n\t// (b) Strict identifier, optionally schema-qualified: ident | ident.ident\n\tconst parts = rest.split('.');\n\tif (parts.length > 2) {\n\t\tthrow new Error(\n\t\t\t`batchValues: invalid type name '${typeName}'. ` +\n\t\t\t\t'Schema-qualified types allow at most one dot (schema.type).',\n\t\t);\n\t}\n\tfor (const part of parts) {\n\t\tif (!IDENT_RE.test(part)) {\n\t\t\tthrow new Error(\n\t\t\t\t`batchValues: invalid type name '${typeName}'. ` +\n\t\t\t\t\t`Base type \"${part}\" is not a valid SQL identifier ` +\n\t\t\t\t\t'([A-Za-z_][A-Za-z0-9_]*) and is not in the multi-word type allowlist.',\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * BatchValuesRef — a virtual batch data source backed by unnest($1::type[], ...).\n *\n * Created via `orm.batchValues(data, columns, types, opts?)`.\n * Used as a source in `.from()` or `.join()` to operate on a set of\n * parameter-bound arrays without a real table.\n *\n * @example Batch UPDATE\n * ```typescript\n * const batch = orm.batchValues(\n * [ids, calleeIds],\n * ['id', 'callee_id'],\n * ['integer', 'integer'],\n * );\n * await orm.modify(calls)\n * .join(batch, { on: eq('calls.id', ref('batch.id')) })\n * .set({ callee_id: ref('batch.callee_id') })\n * .execute();\n * ```\n *\n * @example Batch lookup with ordinality\n * ```typescript\n * const requested = orm.batchValues(\n * [paths, names],\n * ['path', 'name'],\n * ['text', 'text'],\n * { ordinality: true },\n * );\n * await orm.from(requested)\n * .join('files', { on: eq('files.path', ref('requested.path')) })\n * .orderBy('requested.ord')\n * .all();\n * ```\n */\nexport type BatchValuesOptions = {\n\t/** Add WITH ORDINALITY -- appends an 'ord' column with row numbers */\n\treadonly ordinality?: boolean;\n\t/** Alias for the unnest source in SQL (default: 'batch') */\n\treadonly alias?: string;\n};\n\n/**\n * A virtual batch data source backed by `unnest($1::type[], $2::type[], ...)`.\n *\n * Not a QueryBuilder -- it is a lightweight descriptor passed to `.from()` or\n * `.join()`. The adapter compiles it to a RangeFunction AST node.\n */\nexport type BatchValuesRef = {\n\treadonly __kind: 'batchValues';\n\t/** Column-major data arrays: one array per column */\n\treadonly data: readonly unknown[][];\n\t/** Column names for the unnest alias clause */\n\treadonly columns: readonly string[];\n\t/** PostgreSQL type names for CAST ($1::type[]) -- e.g. 'integer', 'text' */\n\treadonly types: readonly string[];\n\t/** SQL alias used to reference this source (default: 'batch') */\n\treadonly alias: string;\n\t/** When true, WITH ORDINALITY is emitted -- adds an 'ord' column */\n\treadonly ordinality: boolean;\n};\n\n/**\n * Type guard for BatchValuesRef.\n */\nexport function isBatchValuesRef(value: unknown): value is BatchValuesRef {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'__kind' in value &&\n\t\t(value as BatchValuesRef).__kind === 'batchValues'\n\t);\n}\n\n/**\n * Factory function -- create a BatchValuesRef descriptor.\n *\n * @param data Column-major arrays: `[idsArray, namesArray, ...]`\n * @param columns Column names: `['id', 'name', ...]`\n * @param types PG type names: `['integer', 'text', ...]`\n * @param opts Optional: alias and ordinality flag\n */\nexport function batchValues(\n\tdata: readonly unknown[][],\n\tcolumns: readonly string[],\n\ttypes: readonly string[],\n\topts?: BatchValuesOptions,\n): BatchValuesRef {\n\tif (data.length !== columns.length || data.length !== types.length) {\n\t\tthrow new Error(\n\t\t\t'batchValues: data, columns, and types must have the same length ' +\n\t\t\t\t`(got ${data.length}, ${columns.length}, ${types.length})`,\n\t\t);\n\t}\n\tif (columns.length === 0) {\n\t\tthrow new Error('batchValues: at least one column is required');\n\t}\n\t// Security: validate type names to prevent SQL injection via CAST($N AS type[]).\n\t// Uses the type-name-safe validator (allows spaces, parens, brackets, dots)\n\t// so that complex types like 'varchar(255)', 'numeric(10,2)', 'int4[]',\n\t// and 'timestamp with time zone' are accepted while injection chars are rejected.\n\t// Normalize (trim) each type name before validation so that the stored descriptor\n\t// holds clean values — the adapter's compile-time array check (endsWith('[]'))\n\t// must see a trimmed string or it produces the wrong cast shape.\n\tconst normalizedTypes = types.map((t) => t.trim());\n\tfor (const t of normalizedTypes) {\n\t\tvalidateTypeName(t);\n\t}\n\t// Security: validate alias and column names centrally so BOTH the\n\t// orm.from(batchValues(...)) and orm...join(batchValues(...)) paths are\n\t// protected at the source. The deparser emits these as SQL identifiers\n\t// in AS alias(col1, col2) — an unvalidated name could inject SQL.\n\tconst alias = opts?.alias ?? 'batch';\n\tvalidateIdentifier(alias, 'alias');\n\tfor (const col of columns) {\n\t\tvalidateIdentifier(col, 'column');\n\t}\n\t// Defensive copies: freeze all returned arrays so post-construction mutation\n\t// of the caller's arrays cannot change what gets compiled.\n\t// Vector 1 (mutation): caller mutates original arrays after batchValues() returns.\n\t// Each data row is also copied so the caller cannot mutate individual arrays.\n\t// The inner Object.freeze returns `readonly unknown[]` but BatchValuesRef.data\n\t// declares `readonly unknown[][]` (inner arrays typed as mutable unknown[]).\n\t// The cast is safe: callers only read from data[], never write to inner arrays.\n\tconst frozenData: readonly unknown[][] = Object.freeze(\n\t\tdata.map((row) => Object.freeze([...row]) as unknown[]),\n\t);\n\tconst frozenColumns: readonly string[] = Object.freeze([...columns]);\n\t// Store normalized (trimmed) type names so the adapter's compile-time checks\n\t// (e.g. endsWith('[]')) work correctly without re-trimming at every call site.\n\tconst frozenTypes: readonly string[] = Object.freeze([...normalizedTypes]);\n\treturn Object.freeze({\n\t\t__kind: 'batchValues',\n\t\tdata: frozenData,\n\t\tcolumns: frozenColumns,\n\t\ttypes: frozenTypes,\n\t\talias,\n\t\tordinality: opts?.ordinality ?? false,\n\t});\n}\n","import { COLUMN_META } from './symbols.js';\nimport type { ColumnRef } from './table-ref.js';\n\n/**\n * Extract the column name from a ColumnRef or string.\n * @internal Shared helper — used by filters, functions, window-functions, typed-query-builder.\n */\nexport function getColumnName(\n\tfield: ColumnRef<string, string, unknown> | string,\n): string {\n\tif (typeof field === 'string') {\n\t\treturn field;\n\t}\n\tconst colName = field[COLUMN_META];\n\tif (colName === undefined) {\n\t\tthrow new Error('Invalid ColumnRef: missing COLUMN_META');\n\t}\n\treturn colName;\n}\n","/**\n * @module window-functions\n * Fluent builders for SQL window functions (ROW_NUMBER, RANK, SUM OVER, etc.).\n *\n * Extracted from filters.ts for SRP (Audit #19).\n *\n * @example\n * ```typescript\n * import { rowNumber, wSum, rank } from '@dbsp/core';\n *\n * // Ranking\n * rowNumber().orderBy('created_at', 'desc').as('rn')\n *\n * // Running total with partition\n * wSum('amount').partitionBy('user_id').orderBy('date').as('running_total')\n * ```\n */\n\nimport type { Mutable } from '@dbsp/types/internal';\nimport type {\n\tAggregateWindowIntent,\n\tOffsetWindowIntent,\n\tRankingWindowIntent,\n\tWindowIntent,\n} from '../intent-ast.js';\nimport { getColumnName } from './column-utils.js';\nimport type { ColumnRef } from './table-ref.js';\nimport type { ExpressionSpec } from './types.js';\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\n// ============================================================================\n// WindowBuilder\n// ============================================================================\n\n/**\n * Internal state for WindowBuilder.\n * Distinguishes between ranking (no field), aggregate (requires field), and offset (requires field).\n */\ntype WindowFunctionKind =\n\t| { type: 'ranking'; fn: 'row_number' | 'rank' | 'dense_rank' }\n\t| {\n\t\t\ttype: 'aggregate';\n\t\t\tfn: 'sum' | 'avg' | 'count' | 'min' | 'max';\n\t\t\tfield?: string;\n\t }\n\t| { type: 'offset'; fn: 'lag' | 'lead'; field: string };\n\n/**\n * Fluent builder for window functions.\n *\n * Create via factory functions: rowNumber(), rank(), sum(field), etc.\n * Chain with .partitionBy(), .orderBy(), then finalize with .as(alias).\n *\n * @example\n * ```typescript\n * // Ranking\n * rowNumber().orderBy('created_at', 'desc').as('rn')\n *\n * // Aggregate with partition\n * sum('amount').partitionBy('user_id').orderBy('date').as('running_total')\n *\n * // Multiple partition/order fields (chaining appends)\n * rank().partitionBy('dept').partitionBy('team').orderBy('salary', 'desc').as('rank')\n * ```\n */\nexport class WindowBuilder {\n\tprivate constructor(\n\t\tprivate readonly fnKind: WindowFunctionKind,\n\t\tprivate readonly partitions: readonly string[] = [],\n\t\tprivate readonly orders: readonly {\n\t\t\tfield: string;\n\t\t\tdirection: 'asc' | 'desc';\n\t\t}[] = [],\n\t) {}\n\n\t/**\n\t * Create a ranking window builder (row_number, rank, dense_rank)\n\t * @internal Use factory functions instead: rowNumber(), rank(), denseRank()\n\t */\n\tstatic ranking(fn: 'row_number' | 'rank' | 'dense_rank'): WindowBuilder {\n\t\treturn new WindowBuilder({ type: 'ranking', fn });\n\t}\n\n\t/**\n\t * Create an aggregate window builder (sum, avg, count, min, max)\n\t * @internal Use factory functions instead: sum(field), avg(field), etc.\n\t */\n\tstatic aggregate(\n\t\tfn: 'sum' | 'avg' | 'count' | 'min' | 'max',\n\t\tfield?: string,\n\t): WindowBuilder {\n\t\treturn new WindowBuilder({\n\t\t\ttype: 'aggregate',\n\t\t\tfn,\n\t\t\t...(field !== undefined ? { field } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * Create an offset window builder (lag, lead)\n\t * @internal Use factory functions instead: lag(field), lead(field)\n\t */\n\tstatic offset(fn: 'lag' | 'lead', field: string): WindowBuilder {\n\t\treturn new WindowBuilder({ type: 'offset', fn, field });\n\t}\n\n\t/**\n\t * Add partition field(s) to the OVER clause.\n\t * Multiple calls APPEND fields (not replace).\n\t * Supports both string field names and ColumnRef (DX-040).\n\t *\n\t * @example\n\t * sum('amount').partitionBy('user_id').partitionBy('category')\n\t * // → PARTITION BY \"user_id\", \"category\"\n\t *\n\t * @example DX-040 with ColumnRef\n\t * rank().partitionBy(users.dept).orderBy(users.salary, 'desc')\n\t */\n\tpartitionBy(\n\t\t...fields: (string | ColumnRef<string, string, unknown>)[]\n\t): WindowBuilder {\n\t\tconst fieldNames = fields.map((f) =>\n\t\t\ttypeof f === 'string' ? f : getColumnName(f),\n\t\t);\n\t\treturn new WindowBuilder(\n\t\t\tthis.fnKind,\n\t\t\t[...this.partitions, ...fieldNames],\n\t\t\tthis.orders,\n\t\t);\n\t}\n\n\t/**\n\t * Add order field to the OVER clause.\n\t * Multiple calls APPEND fields (not replace).\n\t * Supports both string field names and ColumnRef (DX-040).\n\t *\n\t * @param field - Column name or ColumnRef to order by\n\t * @param direction - Sort direction: 'asc' (default) or 'desc'\n\t *\n\t * @example\n\t * rowNumber().orderBy('created_at').orderBy('id', 'desc')\n\t * // → ORDER BY \"created_at\" ASC, \"id\" DESC\n\t *\n\t * @example DX-040 with ColumnRef\n\t * rank().partitionBy(users.dept).orderBy(users.salary, 'desc')\n\t */\n\torderBy(\n\t\tfield: string | ColumnRef<string, string, unknown>,\n\t\tdirection: 'asc' | 'desc' = 'asc',\n\t): WindowBuilder {\n\t\tconst fieldName = typeof field === 'string' ? field : getColumnName(field);\n\t\treturn new WindowBuilder(this.fnKind, this.partitions, [\n\t\t\t...this.orders,\n\t\t\t{ field: fieldName, direction },\n\t\t]);\n\t}\n\n\t/**\n\t * Finalize the window expression with an alias.\n\t * Returns ExpressionSpec for use in columns().\n\t *\n\t * @param alias - Required alias for the result column\n\t *\n\t * @example\n\t * columns(['id', rowNumber().orderBy('date').as('rn')])\n\t */\n\tas(alias: string): ExpressionSpec {\n\t\treturn {\n\t\t\t__expr: true,\n\t\t\tintent: this.toWindowIntent(alias),\n\t\t};\n\t}\n\n\t/**\n\t * Convert builder state to WindowIntent — produces the correct discriminated branch.\n\t * - ranking → RankingWindowIntent (no field)\n\t * - aggregate → AggregateWindowIntent (field required; COUNT uses '*' when omitted)\n\t * - offset → OffsetWindowIntent (field required)\n\t */\n\tprivate toWindowIntent(alias: string): WindowIntent {\n\t\tconst over: Mutable<RankingWindowIntent['over']> = {};\n\t\tif (this.partitions.length > 0) {\n\t\t\tover.partitionBy = this.partitions;\n\t\t}\n\t\tif (this.orders.length > 0) {\n\t\t\tover.orderBy = this.orders;\n\t\t}\n\n\t\tif (this.fnKind.type === 'ranking') {\n\t\t\treturn {\n\t\t\t\tkind: 'window',\n\t\t\t\tfunction: this.fnKind.fn,\n\t\t\t\talias,\n\t\t\t\tover,\n\t\t\t} satisfies RankingWindowIntent;\n\t\t}\n\n\t\tif (this.fnKind.type === 'offset') {\n\t\t\treturn {\n\t\t\t\tkind: 'window',\n\t\t\t\tfunction: this.fnKind.fn,\n\t\t\t\tfield: this.fnKind.field,\n\t\t\t\talias,\n\t\t\t\tover,\n\t\t\t} satisfies OffsetWindowIntent;\n\t\t}\n\n\t\t// aggregate — COUNT(*) omits field (undefined); sum/avg/min/max always have a field\n\t\tconst { field } = this.fnKind;\n\t\treturn {\n\t\t\tkind: 'window',\n\t\t\tfunction: this.fnKind.fn,\n\t\t\t...(field !== undefined && { field }),\n\t\t\talias,\n\t\t\tover,\n\t\t} satisfies AggregateWindowIntent;\n\t}\n}\n\n// ============================================================================\n// Window Function Factory Functions\n// ============================================================================\n\n/**\n * ROW_NUMBER window function: sequential row number within partition\n *\n * @example\n * rowNumber().orderBy('created_at', 'desc').as('rn')\n * // → ROW_NUMBER() OVER (ORDER BY \"created_at\" DESC) AS \"rn\"\n */\nexport function rowNumber(): WindowBuilder {\n\treturn WindowBuilder.ranking('row_number');\n}\n\n/**\n * RANK window function: rank with gaps for ties\n *\n * @example\n * rank().partitionBy('category').orderBy('price').as('price_rank')\n * // → RANK() OVER (PARTITION BY \"category\" ORDER BY \"price\" ASC) AS \"price_rank\"\n */\nexport function rank(): WindowBuilder {\n\treturn WindowBuilder.ranking('rank');\n}\n\n/**\n * DENSE_RANK window function: rank without gaps\n *\n * @example\n * denseRank().partitionBy('dept').orderBy('salary', 'desc').as('salary_rank')\n * // → DENSE_RANK() OVER (PARTITION BY \"dept\" ORDER BY \"salary\" DESC) AS \"salary_rank\"\n */\nexport function denseRank(): WindowBuilder {\n\treturn WindowBuilder.ranking('dense_rank');\n}\n\n/**\n * SUM window function: running/cumulative sum\n *\n * @param field - Field to sum\n *\n * @example\n * wSum('amount').partitionBy('user_id').orderBy('date').as('running_total')\n * // → SUM(\"amount\") OVER (PARTITION BY \"user_id\" ORDER BY \"date\" ASC) AS \"running_total\"\n */\nexport function wSum(field: string): WindowBuilder {\n\treturn WindowBuilder.aggregate('sum', field);\n}\n\n/**\n * AVG window function: running/cumulative average\n *\n * @param field - Field to average\n *\n * @example\n * wAvg('price').partitionBy('category').as('avg_price')\n * // → AVG(\"price\") OVER (PARTITION BY \"category\") AS \"avg_price\"\n */\nexport function wAvg(field: string): WindowBuilder {\n\treturn WindowBuilder.aggregate('avg', field);\n}\n\n/**\n * COUNT window function: count within partition.\n * When called with no argument, produces COUNT(*) OVER (...).\n *\n * @param field - Optional field to count. Omit for COUNT(*).\n *\n * @example COUNT(*) OVER()\n * wCount().over({ partitionBy: ['project_id'] }).as('total')\n * // → COUNT(*) OVER (PARTITION BY \"project_id\") AS \"total\"\n *\n * @example COUNT(field) OVER()\n * wCount('id').partitionBy('category').as('items_in_category')\n * // → COUNT(\"id\") OVER (PARTITION BY \"category\") AS \"items_in_category\"\n */\nexport function wCount(field?: string): WindowBuilder {\n\treturn WindowBuilder.aggregate('count', field);\n}\n\n/**\n * MIN window function: minimum value within partition\n *\n * @param field - Field to find minimum of\n *\n * @example\n * wMin('price').partitionBy('category').as('min_price')\n * // → MIN(\"price\") OVER (PARTITION BY \"category\") AS \"min_price\"\n */\nexport function wMin(field: string): WindowBuilder {\n\treturn WindowBuilder.aggregate('min', field);\n}\n\n/**\n * MAX window function: maximum value within partition\n *\n * @param field - Field to find maximum of\n *\n * @example\n * wMax('price').partitionBy('category').as('max_price')\n * // → MAX(\"price\") OVER (PARTITION BY \"category\") AS \"max_price\"\n */\nexport function wMax(field: string): WindowBuilder {\n\treturn WindowBuilder.aggregate('max', field);\n}\n\n/**\n * LAG window function: access previous row value\n *\n * @param field - Field to access from previous row\n *\n * @example\n * lag('amount').orderBy('date').as('prev_amount')\n * // → LAG(\"amount\") OVER (ORDER BY \"date\" ASC) AS \"prev_amount\"\n */\nexport function lag(field: string): WindowBuilder {\n\treturn WindowBuilder.offset('lag', field);\n}\n\n/**\n * LEAD window function: access next row value\n *\n * @param field - Field to access from next row\n *\n * @example\n * lead('amount').orderBy('date').as('next_amount')\n * // → LEAD(\"amount\") OVER (ORDER BY \"date\" ASC) AS \"next_amount\"\n */\nexport function lead(field: string): WindowBuilder {\n\treturn WindowBuilder.offset('lead', field);\n}\n","/**\n * @module filters\n * Drizzle-like filter helpers for ergonomic WHERE clause building.\n *\n * These are pure factory functions that return WhereIntent objects.\n * They can be composed with and(), or(), not() for complex conditions.\n *\n * @example\n * ```typescript\n * import { eq, and, gt, like } from '@dbsp/core';\n *\n * // Simple equality\n * orm.select('users').where(eq('status', 'active'))\n *\n * // Combined conditions\n * orm.select('users').where(\n * and(\n * eq('status', 'active'),\n * gt('age', 18),\n * like('email', '%@example.com')\n * )\n * )\n * ```\n */\n\nimport type { Mutable } from '@dbsp/types/internal';\nimport type {\n\tComparisonOperator,\n\tQueryIntent,\n\tRecursiveExistsOptions,\n\tWhereAndIntent,\n\tWhereAnyIntent,\n\tWhereComparisonIntent,\n\tWhereExistsIntent,\n\tWhereInIntent,\n\tWhereIntent,\n\tWhereLikeIntent,\n\tWhereNotExistsIntent,\n\tWhereNotIntent,\n\tWhereNullIntent,\n\tWhereOrIntent,\n\tWhereRangeIntent,\n\tWhereRawExistsIntent,\n\tWhereRawNotExistsIntent,\n\tWhereRelationFilterIntent,\n} from '../intent-ast.js';\nimport { getColumnName } from './column-utils.js';\nimport { InvalidOperationError, validateIdentifier } from './errors.js';\nimport type {\n\tSubqueryBuilder,\n\tSubqueryExpression,\n} from './subquery-builder.js';\nimport {\n\ttype ColumnRef,\n\tRELATION_META,\n\ttype RelationRef,\n} from './table-ref.js';\nimport type { AliasedExprColumn, ExpressionSpec } from './types.js';\n\n// ============================================================================\n// Type-Safe Column Reference Support (DX-040)\n// ============================================================================\n\n// ============================================================================\n// Distinct Field Helper (for aggregates)\n// ============================================================================\n\n/**\n * Represents a field with DISTINCT modifier for aggregate functions.\n *\n * @example\n * ```typescript\n * count(distinct('customerId')) // COUNT(DISTINCT customerId)\n * sum(distinct('amount'), 'uniqueSum') // SUM(DISTINCT amount) AS uniqueSum\n * ```\n */\nexport interface DistinctField {\n\treadonly field: string;\n\treadonly distinct: true;\n}\n\n/**\n * Helper to mark a field as DISTINCT for aggregate functions.\n *\n * @param field - The field name to apply DISTINCT to\n * @returns A DistinctField object that can be passed to aggregate functions\n *\n * @example\n * ```typescript\n * import { distinct } from '@dbsp/core';\n *\n * // COUNT(DISTINCT customerId)\n * orm.select('orders').count(distinct('customerId')).execute();\n *\n * // COUNT(DISTINCT customerId) AS unique_customers\n * orm.select('orders').count(distinct('customerId'), 'unique_customers').execute();\n *\n * // SUM(DISTINCT amount) - rare but valid SQL\n * orm.select('orders').sum(distinct('amount'), 'unique_total').execute();\n * ```\n */\nexport function distinct(field: string): DistinctField {\n\treturn { field, distinct: true };\n}\n\n/**\n * Type guard to check if a value is a DistinctField. Purely structural:\n * DistinctField is a public, exported interface (`{ field: string; distinct:\n * true }`), so a value built without calling distinct() — object spread,\n * `satisfies DistinctField`, JSON round-trip — is still typecheck-valid and\n * must be recognized the same way as one built by distinct() itself.\n * Recognition must stay uniform across every consumer (.count()/.sum()/\n * .avg(), fn()) — a stricter check in one and not the others would silently\n * drop DISTINCT in whichever consumer rejects it, the exact silent-wrong-\n * result class this whole guard exists to prevent.\n */\nexport function isDistinctField(value: unknown): value is DistinctField {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'field' in value &&\n\t\ttypeof (value as DistinctField).field === 'string' &&\n\t\t'distinct' in value &&\n\t\t(value as DistinctField).distinct === true\n\t);\n}\n\n// ============================================================================\n// Comparison Operators\n// ============================================================================\n\ntype ComparisonFilter = {\n\t<T extends string, C extends string, V>(\n\t\tfield: ColumnRef<T, C, V>,\n\t\tvalue: V,\n\t): WhereComparisonIntent;\n\t(field: string, value: unknown): WhereComparisonIntent;\n};\n\nfunction createComparisonFilter(\n\toperator: ComparisonOperator,\n): ComparisonFilter {\n\treturn (\n\t\tfield: ColumnRef<string, string, unknown> | string,\n\t\tvalue: unknown,\n\t): WhereComparisonIntent => ({\n\t\tkind: 'comparison',\n\t\tfield: getColumnName(field),\n\t\toperator,\n\t\tvalue,\n\t});\n}\n\n/**\n * Equals comparison: field = value\n *\n * @example eq('status', 'active') → status = 'active'\n * @example eq(users.name, 'John') → type-safe with ColumnRef (DX-040)\n */\nexport const eq: ComparisonFilter = createComparisonFilter('eq');\n\n/**\n * Not equals comparison: field != value\n *\n * @example neq('status', 'deleted') → status != 'deleted'\n * @example neq(users.status, 'deleted') → type-safe with ColumnRef (DX-040)\n */\nexport const neq: ComparisonFilter = createComparisonFilter('neq');\n\n/**\n * Greater than comparison: field > value\n *\n * @example gt('age', 18) → age > 18\n * @example gt(users.age, 18) → type-safe with ColumnRef (DX-040)\n */\nexport const gt: ComparisonFilter = createComparisonFilter('gt');\n\n/**\n * Greater than or equal comparison: field >= value\n *\n * @example gte('age', 18) → age >= 18\n * @example gte(users.age, 18) → type-safe with ColumnRef (DX-040)\n */\nexport const gte: ComparisonFilter = createComparisonFilter('gte');\n\n/**\n * Less than comparison: field < value\n *\n * @example lt('price', 100) → price < 100\n * @example lt(products.price, 100) → type-safe with ColumnRef (DX-040)\n */\nexport const lt: ComparisonFilter = createComparisonFilter('lt');\n\n/**\n * Less than or equal comparison: field <= value\n *\n * @example lte('price', 100) → price <= 100\n * @example lte(products.price, 100) → type-safe with ColumnRef (DX-040)\n */\nexport const lte: ComparisonFilter = createComparisonFilter('lte');\n\n/**\n * Null-safe inequality: field IS DISTINCT FROM value\n *\n * Unlike neq(), returns true when one side is NULL and the other is not.\n * Standard SQL (SQL:2003).\n *\n * @example isDistinctFrom('status', 'active') → status IS DISTINCT FROM 'active'\n * @example isDistinctFrom(users.status, null) → status IS DISTINCT FROM NULL\n */\nexport const isDistinctFrom: ComparisonFilter =\n\tcreateComparisonFilter('isDistinctFrom');\n\n// ============================================================================\n// String Operators\n// ============================================================================\n\n/**\n * LIKE pattern matching: field LIKE pattern\n *\n * @param field - Column name or ColumnRef (must be string type)\n * @param pattern - SQL LIKE pattern (use % for wildcards)\n * @param caseInsensitive - If true, uses ILIKE (PostgreSQL) or LOWER()\n *\n * @example like('name', '%john%') → name LIKE '%john%'\n * @example like('email', '%@example.com', true) → email ILIKE '%@example.com'\n * @example like(users.name, '%John%') → type-safe with ColumnRef (DX-040)\n */\nexport function like<T extends string, C extends string>(\n\tfield: ColumnRef<T, C, string>,\n\tpattern: string,\n\toptions?: boolean | { caseInsensitive?: boolean; escape?: string },\n): WhereLikeIntent;\nexport function like(\n\tfield: string,\n\tpattern: string,\n\toptions?: boolean | { caseInsensitive?: boolean; escape?: string },\n): WhereLikeIntent;\nexport function like(\n\tfield: ColumnRef<string, string, string> | string,\n\tpattern: string,\n\toptions?: boolean | { caseInsensitive?: boolean; escape?: string },\n): WhereLikeIntent {\n\tconst caseInsensitive =\n\t\ttypeof options === 'boolean' ? options : options?.caseInsensitive;\n\tconst escapeChar = typeof options === 'object' ? options.escape : undefined;\n\n\tconst intent: WhereLikeIntent = {\n\t\tkind: 'like',\n\t\tfield: getColumnName(field),\n\t\tpattern,\n\t};\n\tconst withCi =\n\t\tcaseInsensitive !== undefined ? { ...intent, caseInsensitive } : intent;\n\tif (escapeChar !== undefined) {\n\t\treturn { ...withCi, escape: escapeChar };\n\t}\n\treturn withCi;\n}\n\n// ============================================================================\n// Array Operators\n// ============================================================================\n\n/**\n * IN array check: field IN (values)\n *\n * @example inArray('status', ['active', 'pending']) → status IN ('active', 'pending')\n * @example inArray(users.role, ['admin', 'moderator']) → type-safe (DX-040)\n */\nexport function inArray<T extends string, C extends string, V>(\n\tfield: ColumnRef<T, C, V>,\n\tvalues: readonly V[],\n): WhereInIntent;\nexport function inArray(\n\tfield: string,\n\tvalues: readonly unknown[],\n): WhereInIntent;\nexport function inArray(\n\tfield: ColumnRef<string, string, unknown> | string,\n\tvalues: readonly unknown[],\n): WhereInIntent {\n\treturn { kind: 'in', field: getColumnName(field), values };\n}\n\n/**\n * IN subquery: field IN (SELECT ...)\n *\n * Creates a WHERE condition that checks if a field's value exists\n * in the result set of a subquery.\n *\n * @example\n * // Users who have posts\n * orm.select('users').where(inSubquery('id',\n * subquery('posts').select('userId')\n * )).all()\n * // SQL: SELECT * FROM users WHERE id = ANY(SELECT user_id FROM posts)\n */\nexport function inSubquery(\n\tfield: ColumnRef<string, string, unknown> | string,\n\tquery: SubqueryBuilder | SubqueryExpression,\n): WhereInIntent {\n\tconst expr =\n\t\t'build' in query\n\t\t\t? (query as SubqueryBuilder).build()\n\t\t\t: (query as SubqueryExpression);\n\treturn {\n\t\tkind: 'in',\n\t\tfield: getColumnName(field),\n\t\tsubquery: expr.toIntent(),\n\t};\n}\n\n/**\n * Array membership filter using PostgreSQL ANY() operator.\n * Compiles to: \"col\" = ANY($N::type[])\n *\n * Unlike inArray(), any() produces an explicit type-cast in the SQL.\n * Use this when you need guaranteed type safety with array parameters.\n *\n * @example\n * orm.select('symbols').where(any('id', [1, 2, 3])).all()\n * // SQL: SELECT * FROM \"symbols\" WHERE \"id\" = ANY($1::int[])\n */\nexport function any(\n\tfield: ColumnRef<string, string, unknown> | string,\n\tvalues: readonly unknown[],\n): WhereAnyIntent {\n\treturn { kind: 'any', field: getColumnName(field), values };\n}\n\n// ============================================================================\n// Null Operators\n// ============================================================================\n\n/**\n * IS NULL check: field IS NULL\n *\n * @example isNull('deletedAt') → deletedAt IS NULL\n * @example isNull(users.deletedAt) → type-safe (DX-040)\n */\nexport function isNull<T extends string, C extends string, V>(\n\tfield: ColumnRef<T, C, V>,\n): WhereNullIntent;\nexport function isNull(field: string): WhereNullIntent;\nexport function isNull(\n\tfield: ColumnRef<string, string, unknown> | string,\n): WhereNullIntent {\n\treturn { kind: 'null', field: getColumnName(field), operator: 'isNull' };\n}\n\n// ============================================================================\n// Range Operators (PostgreSQL)\n// ============================================================================\n\n/**\n * Range value for PostgreSQL range types.\n * @see WhereRangeIntent\n */\nimport type { RangeOperand, RangeValue } from '@dbsp/types';\n\nexport type { RangeOperand, RangeValue } from '@dbsp/types';\n\n/**\n * Range OVERLAPS check: field && range (PostgreSQL)\n * Tests if two ranges have any points in common.\n *\n * @example rangeOverlaps('dates', { lower: '2025-01-15', upper: '2025-01-20' })\n * → dates && '[2025-01-15,2025-01-20)'\n *\n * @param field - Column name containing a range type\n * @param value - Range value with lower/upper bounds\n */\nexport function rangeOverlaps(\n\tfield: string,\n\tvalue: RangeValue,\n): WhereRangeIntent {\n\treturn { kind: 'range', field, operator: 'overlaps', value };\n}\n\n/**\n * Range CONTAINS check: field @> value (PostgreSQL)\n * Tests if the range contains a point or another range.\n *\n * @example rangeContains('salary_range', 50000)\n * → salary_range @> 50000\n * @example rangeContains('date_range', { lower: '2025-01-01', upper: '2025-01-05' })\n * → date_range @> '[2025-01-01,2025-01-05)'\n *\n * @param field - Column name containing a range type\n * @param value - Scalar value or range to check containment\n */\nexport function rangeContains(\n\tfield: string,\n\tvalue: RangeOperand,\n): WhereRangeIntent {\n\treturn { kind: 'range', field, operator: 'contains', value };\n}\n\n/**\n * Range CONTAINED BY check: field <@ range (PostgreSQL)\n * Tests if the field's range is fully contained within another range.\n *\n * @example rangeContainedBy('event_dates', { lower: '2025-01-01', upper: '2025-12-31' })\n * → event_dates <@ '[2025-01-01,2025-12-31)'\n *\n * @param field - Column name containing a range type\n * @param value - Range that should contain the field's range\n */\nexport function rangeContainedBy(\n\tfield: string,\n\tvalue: RangeValue,\n): WhereRangeIntent {\n\treturn { kind: 'range', field, operator: 'containedBy', value };\n}\n\n/**\n * IS NOT NULL check: field IS NOT NULL\n *\n * @example isNotNull('email') → email IS NOT NULL\n * @example isNotNull(users.email) → type-safe (DX-040)\n */\nexport function isNotNull<T extends string, C extends string, V>(\n\tfield: ColumnRef<T, C, V>,\n): WhereNullIntent;\nexport function isNotNull(field: string): WhereNullIntent;\nexport function isNotNull(\n\tfield: ColumnRef<string, string, unknown> | string,\n): WhereNullIntent {\n\treturn { kind: 'null', field: getColumnName(field), operator: 'isNotNull' };\n}\n\n// ============================================================================\n// Logical Operators\n// ============================================================================\n\n/**\n * Logical AND: all conditions must match\n *\n * Accepts variadic arguments or a single array.\n *\n * @example and(eq('a', 1), gt('b', 2)) → a = 1 AND b > 2\n * @example and([eq('a', 1), gt('b', 2)]) → a = 1 AND b > 2\n */\nexport function and(\n\t...conditions: WhereIntent[] | [readonly WhereIntent[]]\n): WhereAndIntent {\n\t// Handle both variadic and array forms\n\tconst flatConditions =\n\t\tconditions.length === 1 && Array.isArray(conditions[0])\n\t\t\t? (conditions[0] as readonly WhereIntent[])\n\t\t\t: (conditions as WhereIntent[]);\n\n\treturn { kind: 'and', conditions: flatConditions };\n}\n\n/**\n * Logical OR: at least one condition must match\n *\n * Accepts variadic arguments or a single array.\n *\n * @example or(eq('status', 'active'), eq('status', 'pending'))\n * @example or([eq('status', 'active'), eq('status', 'pending')])\n */\nexport function or(\n\t...conditions: WhereIntent[] | [readonly WhereIntent[]]\n): WhereOrIntent {\n\t// Handle both variadic and array forms\n\tconst flatConditions =\n\t\tconditions.length === 1 && Array.isArray(conditions[0])\n\t\t\t? (conditions[0] as readonly WhereIntent[])\n\t\t\t: (conditions as WhereIntent[]);\n\n\treturn { kind: 'or', conditions: flatConditions };\n}\n\n/**\n * Logical NOT: condition must not match\n *\n * @example not(eq('deleted', true)) → NOT (deleted = true)\n */\nexport function not(condition: WhereIntent): WhereNotIntent {\n\treturn { kind: 'not', condition };\n}\n\n// ============================================================================\n// Relation Operators\n// ============================================================================\n\n/**\n * EXISTS subquery: filter by existence of related records\n *\n * @param relation - Relation name defined in schema\n * @param options - Optional nested filter on related records, with optional recursive options\n *\n * @example exists('posts') → EXISTS (SELECT 1 FROM posts WHERE ...)\n * @example exists('posts', { where: eq('published', true) })\n * @example exists('ancestors', { recursive: { direction: 'up', through: 'parent', maxDepth: 10 }, where: eq('name', 'Electronics') })\n */\nexport function exists(\n\trelation: string,\n\toptions?: {\n\t\twhere?: WhereIntent;\n\t\trecursive?: RecursiveExistsOptions;\n\t\tinclude?: Record<string, { join?: 'inner' | 'left' }>;\n\t},\n): WhereExistsIntent {\n\tconst result: Mutable<WhereExistsIntent> = { kind: 'exists', relation };\n\tif (options?.where !== undefined) {\n\t\tresult.where = options.where;\n\t}\n\tif (options?.recursive !== undefined) {\n\t\tresult.recursive = options.recursive;\n\t}\n\tif (options?.include !== undefined) {\n\t\tresult.include = options.include;\n\t}\n\treturn result;\n}\n\n/**\n * NOT EXISTS subquery: filter by absence of related records\n *\n * @param relation - Relation name defined in schema\n * @param options - Optional nested filter on related records, with optional recursive options\n *\n * @example notExists('comments') → NOT EXISTS (SELECT 1 FROM comments WHERE ...)\n * @example notExists('ancestors', { recursive: { direction: 'up', through: 'parent' }, where: eq('name', 'Obsolete') })\n */\nexport function notExists(\n\trelation: string,\n\toptions?: {\n\t\twhere?: WhereIntent;\n\t\trecursive?: RecursiveExistsOptions;\n\t\tinclude?: Record<string, { join?: 'inner' | 'left' }>;\n\t},\n): WhereNotExistsIntent {\n\tconst result: Mutable<WhereNotExistsIntent> = {\n\t\tkind: 'notExists',\n\t\trelation,\n\t};\n\tif (options?.where !== undefined) {\n\t\tresult.where = options.where;\n\t}\n\tif (options?.recursive !== undefined) {\n\t\tresult.recursive = options.recursive;\n\t}\n\tif (options?.include !== undefined) {\n\t\tresult.include = options.include;\n\t}\n\treturn result;\n}\n\n/**\n * EXISTS with an arbitrary subquery (not FK-resolved).\n *\n * Use when the subquery does not follow a declared schema relation.\n * Accepts a SubqueryBuilder (must have `.build()`) or any builder\n * exposing `buildIntent(): QueryIntent` (e.g. QueryBuilder).\n *\n * **Limitation:** correlated subqueries (using `outerRef()` inside the inner WHERE)\n * are NOT supported and will throw at compile time. For correlated EXISTS over an\n * FK-declared relation, use `exists('relation', { where: ... outerRef(...) })` instead.\n *\n * @param subquery - A SubqueryBuilder or any object with buildIntent()\n *\n * @example\n * // EXISTS (SELECT 1 FROM audit_log WHERE audit_log.entity_type = 'login')\n * // Uncorrelated: no reference to the outer row — inner filter is a plain value.\n * rawExists(subquery('audit_log').select('id').where(eq('entityType', 'login')))\n *\n * @example\n * // EXISTS with a full query builder — polymorphic table, no FK to source\n * rawExists(orm.select('sessions').where(and(eq('status', 'active'), gt('expiresAt', new Date()))))\n */\nexport function rawExists(\n\tsq: SubqueryBuilder | { buildIntent(): QueryIntent },\n): WhereRawExistsIntent {\n\tconst intent =\n\t\t'buildIntent' in sq\n\t\t\t? (sq as { buildIntent(): QueryIntent }).buildIntent()\n\t\t\t: (sq as SubqueryBuilder).build().toIntent();\n\treturn { kind: 'rawExists', subquery: intent };\n}\n\n/**\n * NOT EXISTS with an arbitrary subquery (not FK-resolved).\n *\n * Use when the subquery does not follow a declared schema relation.\n * Accepts a SubqueryBuilder (must have `.build()`) or any builder\n * exposing `buildIntent(): QueryIntent` (e.g. QueryBuilder).\n *\n * **Limitation:** correlated subqueries (using `outerRef()` inside the inner WHERE)\n * are NOT supported and will throw at compile time. For correlated NOT EXISTS over an\n * FK-declared relation, use `notExists('relation', { where: ... outerRef(...) })` instead.\n *\n * @param subquery - A SubqueryBuilder or any object with buildIntent()\n *\n * @example\n * // NOT EXISTS (SELECT 1 FROM bans WHERE bans.reason = 'spam')\n * // Uncorrelated: inner filter is a plain value, no reference to the outer row.\n * rawNotExists(subquery('bans').select('id').where(eq('reason', 'spam')))\n */\nexport function rawNotExists(\n\tsq: SubqueryBuilder | { buildIntent(): QueryIntent },\n): WhereRawNotExistsIntent {\n\tconst intent =\n\t\t'buildIntent' in sq\n\t\t\t? (sq as { buildIntent(): QueryIntent }).buildIntent()\n\t\t\t: (sq as SubqueryBuilder).build().toIntent();\n\treturn { kind: 'rawNotExists', subquery: intent };\n}\n\n// ============================================================================\n// Quantified Relation Filters (DX-040 Block 7)\n// ============================================================================\n\n/**\n * Get relation name from a RelationRef.\n * @internal\n */\nfunction getRelationName(\n\trel: RelationRef<string, unknown, 'belongsTo' | 'hasMany' | 'hasOne'>,\n): string {\n\tconst meta = rel[RELATION_META];\n\tif (!meta) {\n\t\tthrow new Error('Invalid RelationRef: missing RELATION_META');\n\t}\n\treturn meta.target;\n}\n\n/**\n * EVERY quantifier: filter parent by condition that ALL related records must match\n *\n * This generates SQL like: NOT EXISTS (SELECT 1 FROM related WHERE NOT condition)\n *\n * @param relation - RelationRef from schema (e.g., users.posts)\n * @param filter - Callback that receives relation and returns a filter condition\n *\n * @example\n * ```typescript\n * // Find users where ALL their posts are published\n * orm.from(users)\n * .where(every(users.posts, p => eq(p.published, true)))\n *\n * // SQL: ... WHERE NOT EXISTS (\n * // SELECT 1 FROM posts WHERE posts.author_id = users.id AND NOT (posts.published = true)\n * // )\n * ```\n */\nexport function every<TTarget extends string, TTargetType>(\n\trelation: RelationRef<TTarget, TTargetType[], 'hasMany'>,\n\tfilter: (rel: RelationRef<TTarget, TTargetType[], 'hasMany'>) => WhereIntent,\n): WhereRelationFilterIntent {\n\tconst relationName = getRelationName(relation);\n\tconst where = filter(relation);\n\treturn {\n\t\tkind: 'relationFilter',\n\t\trelation: relationName,\n\t\twhere,\n\t\tmode: 'every',\n\t};\n}\n\n/**\n * NONE quantifier: filter parent by condition that NO related records match\n *\n * This is equivalent to: NOT EXISTS (SELECT 1 FROM related WHERE condition)\n *\n * @param relation - RelationRef from schema (e.g., users.posts)\n * @param filter - Callback that receives relation and returns a filter condition\n *\n * @example\n * ```typescript\n * // Find users with no flagged posts\n * orm.from(users)\n * .where(none(users.posts, p => eq(p.flagged, true)))\n *\n * // SQL: ... WHERE NOT EXISTS (\n * // SELECT 1 FROM posts WHERE posts.author_id = users.id AND posts.flagged = true\n * // )\n * ```\n */\nexport function none<TTarget extends string, TTargetType>(\n\trelation: RelationRef<TTarget, TTargetType[], 'hasMany'>,\n\tfilter: (rel: RelationRef<TTarget, TTargetType[], 'hasMany'>) => WhereIntent,\n): WhereRelationFilterIntent {\n\tconst relationName = getRelationName(relation);\n\tconst where = filter(relation);\n\treturn {\n\t\tkind: 'relationFilter',\n\t\trelation: relationName,\n\t\twhere,\n\t\tmode: 'none',\n\t};\n}\n\n/**\n * SOME quantifier: filter parent by condition that at least one related record matches\n *\n * This is the default behavior for relation filters and is equivalent to EXISTS.\n *\n * @param relation - RelationRef from schema (e.g., users.posts)\n * @param filter - Callback that receives relation and returns a filter condition\n *\n * @example\n * ```typescript\n * // Find users with at least one published post\n * orm.from(users)\n * .where(some(users.posts, p => eq(p.published, true)))\n *\n * // SQL: ... WHERE EXISTS (\n * // SELECT 1 FROM posts WHERE posts.author_id = users.id AND posts.published = true\n * // )\n * ```\n */\nexport function some<TTarget extends string, TTargetType>(\n\trelation: RelationRef<TTarget, TTargetType[], 'hasMany'>,\n\tfilter: (rel: RelationRef<TTarget, TTargetType[], 'hasMany'>) => WhereIntent,\n): WhereRelationFilterIntent {\n\tconst relationName = getRelationName(relation);\n\tconst where = filter(relation);\n\treturn {\n\t\tkind: 'relationFilter',\n\t\trelation: relationName,\n\t\twhere,\n\t\tmode: 'some',\n\t};\n}\n\n// ============================================================================\n// Expression Helpers\n// ============================================================================\n\n/**\n * COALESCE expression: returns first non-null value from a list of fields\n *\n * Use this for locale fallback patterns (e.g., FR → EN → default)\n *\n * @param fields - Array of field names to check in order\n * @param as - Required alias for the result column\n *\n * @example\n * ```typescript\n * // Locale fallback: prefer French, fall back to English\n * coalesce(['name_fr', 'name_en'], 'display_name')\n * // → COALESCE(name_fr, name_en) AS display_name\n *\n * // Use in QueryBuilder select with expressions\n * orm.select('products')\n * .selectWithExpressions(['id', 'sku'], [\n * coalesce(['title_fr', 'title_en', 'title_default'], 'title')\n * ])\n * ```\n */\nexport function coalesce(\n\tfields: readonly string[],\n\tas: string,\n): ExpressionSpec {\n\tif (fields.length === 0) {\n\t\tthrow new Error('coalesce() requires at least one field');\n\t}\n\tif (!as || as.trim() === '') {\n\t\tthrow new Error('coalesce() requires a non-empty alias');\n\t}\n\t// FIND-008: Validate all field names and the alias as SQL identifiers\n\tfor (const f of fields) {\n\t\tvalidateIdentifier(f, 'column');\n\t}\n\tvalidateIdentifier(as, 'column');\n\treturn {\n\t\t__expr: true,\n\t\tintent: { kind: 'coalesce', fields, as },\n\t};\n}\n\n/**\n * Raw SQL expression (escape hatch for advanced use cases).\n *\n * @warning **SECURITY RISK: SQL INJECTION VULNERABILITY**\n *\n * This function bypasses ALL SQL injection protections. The SQL fragment\n * is inserted directly into queries without sanitization.\n *\n * **NEVER:**\n * - Interpolate user input: `raw(\\`WHERE name = '\\${userInput}'\\`, 'x')` ❌\n * - Use request parameters: `raw(req.query.field, 'x')` ❌\n * - Trust client-side data: `raw(formData.expression, 'x')` ❌\n *\n * **SAFE USAGE:**\n * - Hardcoded expressions: `raw('NOW()', 'current_time')` ✅\n * - Constants: `raw('price_cents / 100.0', 'price_dollars')` ✅\n * - Server-controlled values only\n *\n * For user-provided values, use parameterized queries via the standard\n * filter functions (eq, gt, like, etc.) which properly escape values.\n *\n * @param sqlFragment - Raw SQL fragment. **Must be safe - no user input!**\n * @param as - Required alias for the result column\n * @returns ExpressionSpec for use in select()\n *\n * @example\n * ```typescript\n * // SAFE: Hardcoded expressions\n * raw('NOW()', 'current_time')\n * // → NOW() AS current_time\n *\n * raw('price_cents / 100.0', 'price_dollars')\n * // → price_cents / 100.0 AS price_dollars\n *\n * // DANGEROUS - SQL INJECTION RISK!\n * // raw(`WHERE name = '${userInput}'`, 'x') // NEVER DO THIS!\n * ```\n *\n * @see {@link https://owasp.org/www-community/attacks/SQL_Injection | OWASP SQL Injection}\n * @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html | OWASP Parameterization}\n */\nexport function raw(sqlFragment: string, as: string): ExpressionSpec {\n\tif (typeof as !== 'string' || as.trim().length === 0) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'raw',\n\t\t\t\"raw() requires an alias as second argument, e.g. raw('COUNT(*)', 'count')\",\n\t\t);\n\t}\n\t// FIND-008: Validate the alias as a SQL identifier; sqlFragment is an intentional raw escape hatch\n\tvalidateIdentifier(as, 'column');\n\treturn {\n\t\t__expr: true,\n\t\tintent: { kind: 'raw', sql: sqlFragment, as },\n\t};\n}\n\n/**\n * Creates a column alias expression as a typed dbsp expression intent.\n * Preferred over raw() for simple column aliasing as it's type-safe and dialect-portable.\n *\n * Compilers render the alias from structured column and alias fields - no raw SQL.\n *\n * @param column - Column name to select\n * @param alias - Alias for the result column\n * @returns ExpressionSpec for use in columns()\n *\n * @example\n * ```typescript\n * // Simple column alias\n * col('name', 'userName')\n * // → SELECT \"name\" AS \"userName\"\n *\n * // Multiple columns with aliases\n * orm.select('users').columns([\n * 'id',\n * col('name', 'userName'),\n * col('email', 'userEmail'),\n * ])\n * ```\n */\nexport function col(column: string, alias: string): ExpressionSpec {\n\t// FIND-008: Validate column name and alias as SQL identifiers (same strictness as coalesce)\n\tvalidateIdentifier(column, 'column');\n\tvalidateIdentifier(alias, 'column');\n\treturn {\n\t\t__expr: true,\n\t\tintent: { kind: 'columnAlias', column, alias },\n\t};\n}\n\n/**\n * Creates a relation column expression for selecting a column from a related table.\n *\n * Names a relation whose JOIN the query has already emitted. The compiler resolves\n * that relation to its emitted SQL alias and renders a dialect-specific aliased\n * column. Without an emitted alias, it reports\n * `relation column \"<relation>\".\"<column>\" has no emitted alias in this query`.\n *\n * It does not derive a join: choosing its type, null behavior, and row\n * multiplication is a separate caller-owned query decision.\n *\n * @param relation - Relation path to traverse (dot-separated for multi-level)\n * @param column - Column name to select from the target relation\n * @param as - Alias for the result column\n * @returns ExpressionSpec for use in columns()\n *\n * @example\n * ```typescript\n * // A relation join supplies the emitted alias.\n * orm.select('products')\n * .join('category')\n * .columns(['name', relationColumn('category', 'name', 'categoryName')])\n *\n * // An include with an explicit outer join supplies the alias too. A bare\n * // include aggregates the relation instead, so the column lands inside\n * // `<relation>_json` rather than at the top level under its own alias (#793).\n * orm.select('products')\n * .include('category', { join: 'left' })\n * .columns(['name', relationColumn('category', 'name', 'categoryName')])\n * ```\n */\nexport function relationColumn<A extends string>(\n\trelation: string,\n\tcolumn: string,\n\tas: A,\n): AliasedExprColumn<A> {\n\t// FIND-008: Validate relation path segments, column, and alias as SQL identifiers.\n\t// relation may be dot-separated (e.g. 'category.parent') — validate each segment individually.\n\t// Keep the explicit empty guard so callers get the descriptive \"relation path\" message for ''.\n\t// Non-empty but invalid strings (whitespace, injection chars) are caught by validateIdentifier.\n\tif (!relation) {\n\t\tthrow new Error('relationColumn() requires a non-empty relation path');\n\t}\n\tfor (const segment of relation.split('.')) {\n\t\tvalidateIdentifier(segment, 'relation');\n\t}\n\t// Allow the wildcard '*' as a valid column value — the adapter compiler\n\t// handles it as A_Star (unquoted star) for relation.* expansion.\n\t// Any other column value must pass identifier validation.\n\tif (column !== '*') {\n\t\tvalidateIdentifier(column, 'column');\n\t}\n\tvalidateIdentifier(as as string, 'column');\n\treturn {\n\t\t__expr: true,\n\t\tintent: { kind: 'relationColumn', relation, column, as },\n\t} as unknown as AliasedExprColumn<A>;\n}\n\n// ============================================================================\n// Raw SQL Set Expression (for doUpdate() / set() mutations)\n// ============================================================================\n\n/**\n * Symbol to identify raw SQL expression values in set() / doUpdate()\n * @internal\n */\nexport const SQL_RAW_MARKER = Symbol.for('dbsp:raw-sql');\n\n/**\n * A raw SQL expression for use in mutation set values (doUpdate / set).\n * Created by the {@link sql} function.\n */\nexport interface SqlRawExpression {\n\treadonly [SQL_RAW_MARKER]: true;\n\treadonly sql: string;\n}\n\n/**\n * Create a raw SQL expression for use in `doUpdate()` and `set()` mutation values.\n *\n * @warning **SECURITY RISK: SQL INJECTION VULNERABILITY**\n * The SQL fragment is inserted **WITHOUT** parameterization.\n * Only use with hardcoded expressions — **NEVER** with user input.\n *\n * **SAFE USAGE:**\n * - Hardcoded functions: `sql('now()')` ✅\n * - Excluded references: `sql('excluded.count + 1')` ✅\n * - Server-controlled literals: `sql('gen_random_uuid()')` ✅\n *\n * **NEVER:**\n * - Interpolate user input: `` sql(`'${userInput}'`) `` ❌\n * - Use request parameters: `sql(req.query.expr)` ❌\n *\n * @param sqlFragment - Raw SQL fragment (must be safe — no user input!)\n * @returns SqlRawExpression for use in doUpdate() / set()\n *\n * @example\n * ```typescript\n * orm.upsert('files')\n * .values({ id: 1, name: 'test' })\n * .onConflict(['id'])\n * .doUpdate({ last_parsed: sql('now()'), count: sql('excluded.count + 1') })\n * .execute();\n *\n * orm.update('files')\n * .set({ last_parsed: sql('now()') })\n * .where(eq('id', 1))\n * .execute();\n * ```\n *\n * @see {@link https://owasp.org/www-community/attacks/SQL_Injection | OWASP SQL Injection}\n */\nexport function sql(sqlFragment: string): SqlRawExpression {\n\tif (!sqlFragment || sqlFragment.trim() === '') {\n\t\tthrow new Error('sql() requires a non-empty SQL fragment');\n\t}\n\treturn { [SQL_RAW_MARKER]: true, sql: sqlFragment };\n}\n\n/**\n * Type guard: check if a value is a raw SQL expression created by {@link sql}.\n */\nexport function isSqlRaw(value: unknown): value is SqlRawExpression {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tSQL_RAW_MARKER in value &&\n\t\t(value as Record<symbol, unknown>)[SQL_RAW_MARKER] === true\n\t);\n}\n\n// ============================================================================\n// Window Functions (re-exported from window-functions.ts)\n// ============================================================================\n\nexport {\n\tdenseRank,\n\tlag,\n\tlead,\n\trank,\n\trowNumber,\n\tWindowBuilder,\n\twAvg,\n\twCount,\n\twMax,\n\twMin,\n\twSum,\n} from './window-functions.js';\n","/**\n * @module expressions\n * Dialect-agnostic expression primitives for custom operators, functions, and type casts.\n *\n * These primitives allow constructing arbitrary SQL expressions in a safe, parameterized\n * way — without raw SQL concatenation. Designed as the foundation for dialect extensions\n * (e.g., pgvector, ParadeDB) and advanced query needs.\n *\n * @example\n * ```typescript\n * import { op, ref, param, cast, fn, literal } from '@dbsp/core';\n *\n * // pgvector cosine distance: vector <=> $1::vector\n * const dist = op('<=>', ref('embedding'), cast(param([0.1, 0.2, 0.3]), 'vector'));\n *\n * // Use in SELECT with alias\n * orm.select('items').column(dist.as('score'))\n *\n * // Use in WHERE\n * orm.select('items').where(dist.gte(0.5))\n *\n * // Use in ORDER BY\n * orm.select('items').orderBy(dist, 'asc')\n * ```\n */\n\nimport type {\n\tAggOrderByArg,\n\tArrayExpressionIntent,\n\tCastExpressionIntent,\n\tCustomFnExpressionIntent,\n\tCustomOpExpressionIntent,\n\tExpressionIntent,\n\tLiteralExpressionIntent,\n\tNamedArgExpressionIntent,\n\tParamExpressionIntent,\n\tPredicateOperator,\n\tRefExpressionIntent,\n\tStandaloneWhereExpressionIntent,\n\tStarExpressionIntent,\n\tUnaryExpressionIntent,\n\tWhereExpressionIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\nimport { InvalidOperationError } from './errors.js';\nimport type { DistinctField } from './filters.js';\nimport { isDistinctField as isDistinctFieldValue } from './filters.js';\nimport type { ExpressionSpec } from './types.js';\n\n// ============================================================================\n// Validation patterns\n// ============================================================================\n\nconst OPERATOR_PATTERN = /^[a-zA-Z_<>=!@#%^&|~*+\\-/.]+$/;\nconst FUNCTION_NAME_PATTERN =\n\t/^[a-zA-Z_][a-zA-Z0-9_]*(\\.[a-zA-Z_][a-zA-Z0-9_]*)*$/;\nconst TYPE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\n// ============================================================================\n// ExprInput type\n// ============================================================================\n\n/**\n * Accepted input types for op() and fn() arguments.\n * - `ExpressionRef` → used as-is\n * - `string` → implicitly converted to ref() (column reference)\n * - `number | boolean | readonly unknown[]` → implicitly converted to param() (bound value)\n *\n * Use `ref()` / `param()` explicitly for ambiguous cases (e.g., a string that is a value,\n * not a column name → use `literal()` instead).\n */\n/**\n * Accepted input types for op() and fn() arguments.\n * - `ExpressionRef` → used as-is\n * - `string` → implicitly converted to ref() (column reference)\n * - `number | boolean | readonly unknown[]` → implicitly converted to param() (bound value)\n * - `AggOrderByArg` → ORDER BY entry inside an aggregate (fn() only)\n *\n * Use `ref()` / `param()` explicitly for ambiguous cases (e.g., a string that is a value,\n * not a column name → use `literal()` instead).\n */\nexport type ExprInput =\n\t| ExpressionRef\n\t| ExpressionSpec\n\t| AggOrderByArg\n\t| string\n\t| number\n\t| boolean\n\t| readonly unknown[];\n\nexport type { PredicateOperator } from '@dbsp/types';\n\ntype BinaryPredicateOperator = Exclude<PredicateOperator, 'AND' | 'OR' | 'NOT'>;\n\ntype NonPredicateOperator<TOperator extends string> =\n\tTOperator extends PredicateOperator ? never : TOperator;\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nfunction toExpressionIntent(input: ExprInput): ExpressionIntent {\n\t// ExpressionRef check first — fastest path for the common case.\n\tif (input instanceof ExpressionRef) return input.intent;\n\t// Duck-type check AFTER instanceof: SubqueryExpression.asExpr() returns a plain\n\t// { __expr: true, intent } object (not an ExpressionRef instance), so instanceof\n\t// would miss it. Order matters: instanceof must come first.\n\tif (\n\t\ttypeof input === 'object' &&\n\t\tinput !== null &&\n\t\t'__expr' in input &&\n\t\t(input as { __expr: unknown }).__expr === true &&\n\t\t'intent' in input\n\t) {\n\t\treturn (input as { intent: ExpressionIntent }).intent;\n\t}\n\tif (typeof input === 'string') {\n\t\treturn { kind: 'ref', column: input } satisfies RefExpressionIntent;\n\t}\n\treturn { kind: 'param', value: input } satisfies ParamExpressionIntent;\n}\n\n// ============================================================================\n// ExpressionRef — chainable wrapper around ExpressionIntent\n// ============================================================================\n\n/**\n * A chainable wrapper around an ExpressionIntent.\n *\n * Created by factory functions (`op`, `fn`, `ref`, `param`, `cast`, `literal`, `unary`).\n * Can be used in:\n * - `.column(expr.as('alias'))` — SELECT with alias\n * - `.where(expr.gte(0.5))` — WHERE with comparison\n * - `.orderBy(expr, 'asc')` — ORDER BY expression\n *\n * Implements the `ExpressionSpec` duck-type interface (`__expr: true`, `intent`).\n */\nexport class ExpressionRef {\n\treadonly __expr: true = true;\n\treadonly intent: ExpressionIntent;\n\n\tconstructor(intent: ExpressionIntent) {\n\t\tthis.intent = Object.freeze(intent);\n\t}\n\n\t/**\n\t * Set an alias for this expression in SELECT.\n\t * Returns a new ExpressionRef — does not mutate.\n\t */\n\tas(alias: string): ExpressionRef {\n\t\treturn new ExpressionRef({\n\t\t\t...this.intent,\n\t\t\tas: alias,\n\t\t} as ExpressionIntent);\n\t}\n\n\t/** WHERE: expr = value */\n\teq(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'eq', value };\n\t}\n\n\t/** WHERE: expr != value */\n\tneq(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'neq', value };\n\t}\n\n\t/** WHERE: expr > value */\n\tgt(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'gt', value };\n\t}\n\n\t/** WHERE: expr >= value */\n\tgte(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'gte', value };\n\t}\n\n\t/** WHERE: expr < value */\n\tlt(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'lt', value };\n\t}\n\n\t/** WHERE: expr <= value */\n\tlte(value: unknown): WhereExpressionIntent {\n\t\treturn { kind: 'expression', expr: this.intent, operator: 'lte', value };\n\t}\n\n\t/**\n\t * Add a FILTER (WHERE ...) clause to this function expression.\n\t * Valid on `fn()` expressions (customFn kind), including DISTINCT calls\n\t * produced by `fn(aggName, distinct(field))` (still customFn kind).\n\t * Returns a new ExpressionRef — does not mutate.\n\t *\n\t * NOTE: the FILTER clause is only emitted when the expression is used in\n\t * column position (`.columns([...])`) — the adapter patches it in at that\n\t * one SELECT-list branch (compiler.ts). Using `.filter()` inside\n\t * `.orderBy()`, `.having()`, `cast()`, or any other nested context compiles\n\t * successfully but silently drops the FILTER clause (tracked separately,\n\t * not specific to DISTINCT).\n\t *\n\t * @example fn('array_agg', ref('name')).filter(eq('active', true))\n\t * → array_agg(\"name\") FILTER (WHERE \"active\" = $1) // in .columns()\n\t * @example fn('count', distinct('id')).filter(eq('active', true))\n\t * → count(DISTINCT id) FILTER (WHERE \"active\" = $1) // in .columns()\n\t * @throws Error if called on any other expression kind\n\t */\n\tfilter(condition: WhereIntent): ExpressionRef {\n\t\tif (this.intent.kind !== 'customFn') {\n\t\t\tthrow new Error(\n\t\t\t\t`filter() can only be used on function expressions created with fn(). Got kind: '${this.intent.kind}'`,\n\t\t\t);\n\t\t}\n\t\treturn new ExpressionRef({\n\t\t\t...this.intent,\n\t\t\tfilter: condition,\n\t\t} as CustomFnExpressionIntent);\n\t}\n}\n\n/** Marker used to identify an invalid predicate from a different core copy. */\nexport const PREDICATE_REF_DISCRIMINATOR = 'dbsp.predicate.v1' as const;\n\n/**\n * A predicate that is also a scalar expression.\n *\n * Its one canonical representation is the expression intent inherited from\n * `ExpressionRef`; the WHERE form is derived when a builder consumes it.\n */\nclass ExpressionPredicateRef extends ExpressionRef {\n\treadonly __predicateRef = PREDICATE_REF_DISCRIMINATOR;\n\tdeclare readonly intent: StandaloneWhereExpressionIntent;\n\n\tconstructor(intent: StandaloneWhereExpressionIntent) {\n\t\tsuper(Object.freeze(intent));\n\t\tObject.freeze(this);\n\t}\n\n\toverride as(alias: string): PredicateExpressionRef {\n\t\treturn new ExpressionPredicateRef({\n\t\t\t...this.intent,\n\t\t\tas: alias,\n\t\t} as StandaloneWhereExpressionIntent);\n\t}\n}\n\n/** A scalar predicate created by `op()`, `boolFn()`, or `unsafeAsPredicate()`. */\nexport type PredicateExpressionRef = ExpressionPredicateRef;\n\n/**\n * A composed predicate has no scalar-expression representation in this API.\n * Its canonical representation is the complete WHERE intent.\n */\nclass WhereOnlyPredicateRef {\n\treadonly __predicateRef = PREDICATE_REF_DISCRIMINATOR;\n\n\tconstructor(readonly intent: WhereIntent) {\n\t\tif (intent.kind === 'and' || intent.kind === 'or') {\n\t\t\tObject.freeze(intent.conditions);\n\t\t}\n\t\tObject.freeze(intent);\n\t\tObject.freeze(this);\n\t}\n}\n\n/** A composed predicate that is accepted only in `.where()`. */\nexport type WhereOnlyPredicate = WhereOnlyPredicateRef;\n\n/**\n * A value accepted by `.where()` as a predicate.\n *\n * The constructors are intentionally module-private. Use `op()`, predicate\n * helpers, or `unsafeAsPredicate()` instead.\n */\nexport type PredicateRef = PredicateExpressionRef | WhereOnlyPredicate;\n\n/**\n * Recognize only predicate instances constructed by this installed core copy.\n *\n * A predicate from another installed copy is unsupported: reconstruct it with\n * this module's predicate factories before passing it to a builder.\n */\nexport function isPredicateRef(value: unknown): value is PredicateRef {\n\treturn (\n\t\tvalue instanceof ExpressionPredicateRef ||\n\t\tvalue instanceof WhereOnlyPredicateRef\n\t);\n}\n\n/** @internal Detect a rejected foreign predicate before object-filter conversion. */\nexport function hasPredicateRefDiscriminator(value: unknown): boolean {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as { __predicateRef?: unknown }).__predicateRef ===\n\t\t\tPREDICATE_REF_DISCRIMINATOR\n\t);\n}\n\nfunction isExpressionPredicateRef(\n\tpredicate: PredicateRef,\n): predicate is PredicateExpressionRef {\n\treturn '__expr' in predicate && predicate.__expr === true;\n}\n\n/** Derive the WHERE representation from a predicate's single canonical intent. */\nexport function predicateWhereIntent(predicate: PredicateRef): WhereIntent {\n\treturn isExpressionPredicateRef(predicate)\n\t\t? { kind: 'expression', expr: predicate.intent }\n\t\t: predicate.intent;\n}\n\n// ============================================================================\n// Factory functions\n// ============================================================================\n\n/**\n * Column reference — refers to a named column (or table.column).\n *\n * @example ref('embedding') → \"embedding\"\n * @example ref('t.score') → \"t\".\"score\"\n */\nexport function ref(column: string): ExpressionRef {\n\treturn new ExpressionRef({\n\t\tkind: 'ref',\n\t\tcolumn,\n\t} satisfies RefExpressionIntent);\n}\n\n/**\n * Parameterized value — automatically bound as $N.\n * Use for user-supplied values, vectors, dynamic data.\n *\n * @example param([0.1, 0.2]) → $1 (with value bound to $1)\n */\nexport function param(value: unknown): ExpressionRef {\n\treturn new ExpressionRef({\n\t\tkind: 'param',\n\t\tvalue,\n\t} satisfies ParamExpressionIntent);\n}\n\n/**\n * Type cast — compiles to expr::typeName or CAST(expr AS typeName).\n *\n * @example cast(param([0.1, 0.2]), 'vector') → $1::vector\n * @throws Error if typeName fails validation (injection guard)\n */\nexport function cast(expr: ExpressionRef, typeName: string): ExpressionRef {\n\tif (!TYPE_NAME_PATTERN.test(typeName)) {\n\t\tthrow new Error(`Invalid type name: ${typeName}`);\n\t}\n\treturn new ExpressionRef({\n\t\tkind: 'cast',\n\t\texpr: expr.intent,\n\t\ttypeName,\n\t} satisfies CastExpressionIntent);\n}\n\n/**\n * Custom binary operator — left OP right.\n * Implicit conversions: string → ref(), number/boolean/array → param().\n *\n * @example op('<=>', ref('embedding'), cast(param([0.1]), 'vector'))\n * @example op('<=>', 'embedding', [0.1, 0.2]) // implicit conversions\n * @throws Error if operator fails validation (injection guard)\n */\n/** Logical AND / OR — both operands must be predicates. */\nexport function op(\n\toperator: 'AND' | 'OR',\n\tleft: PredicateRef,\n\tright: PredicateRef,\n): WhereOnlyPredicate;\n\n/** Logical NOT — its sole operand must be a predicate. */\nexport function op(operator: 'NOT', operand: PredicateRef): WhereOnlyPredicate;\n\n/** Predicate binary operators accept expression operands. */\nexport function op(\n\toperator: BinaryPredicateOperator,\n\tleft: ExprInput,\n\tright: ExprInput,\n): ExpressionPredicateRef;\n\n/** Any non-predicate operator remains an ordinary expression. */\nexport function op<TOperator extends string>(\n\toperator: NonPredicateOperator<TOperator>,\n\tleft: ExprInput,\n\tright: ExprInput,\n): ExpressionRef;\n\nexport function op(\n\toperator: string,\n\t...operands: (ExprInput | PredicateRef | undefined)[]\n): ExpressionRef | WhereOnlyPredicateRef {\n\tconst [left, right] = operands;\n\tif (!operator || !OPERATOR_PATTERN.test(operator)) {\n\t\tthrow new Error(`Invalid operator: ${operator}`);\n\t}\n\n\tif (operator === 'AND' || operator === 'OR') {\n\t\tif (operands.length !== 2) {\n\t\t\tthrow new Error(`${operator} requires exactly two predicate operands`);\n\t\t}\n\t\tif (!isPredicateRef(left) || !isPredicateRef(right)) {\n\t\t\tthrow new Error(`${operator} requires predicate operands`);\n\t\t}\n\t\treturn new WhereOnlyPredicateRef({\n\t\t\tkind: operator === 'AND' ? 'and' : 'or',\n\t\t\tconditions: [predicateWhereIntent(left), predicateWhereIntent(right)],\n\t\t});\n\t}\n\n\tif (operator === 'NOT') {\n\t\tif (operands.length !== 1) {\n\t\t\tthrow new Error('NOT requires exactly one predicate operand');\n\t\t}\n\t\tif (!isPredicateRef(left)) {\n\t\t\tthrow new Error('NOT requires a predicate operand');\n\t\t}\n\t\treturn new WhereOnlyPredicateRef({\n\t\t\tkind: 'not',\n\t\t\tcondition: predicateWhereIntent(left),\n\t\t});\n\t}\n\n\tif (operands.length !== 2) {\n\t\tthrow new Error(`${operator} requires exactly two expression operands`);\n\t}\n\n\tconst intent = {\n\t\tkind: 'customOp',\n\t\toperator,\n\t\tleft: toExpressionIntent(left as ExprInput),\n\t\tright: toExpressionIntent(right as ExprInput),\n\t} satisfies CustomOpExpressionIntent;\n\n\tif (isPredicateOperator(operator)) {\n\t\treturn new ExpressionPredicateRef(intent);\n\t}\n\treturn new ExpressionRef(intent);\n}\n\n/**\n * Assert that an arbitrary expression is boolean for use in WHERE.\n *\n * Use this only for a user-defined operator whose boolean result cannot be\n * represented by the closed PredicateOperator union.\n */\nexport function unsafeAsPredicate(expr: ExpressionRef): PredicateExpressionRef {\n\tif (expr instanceof ExpressionPredicateRef) return expr;\n\tif (!isStandaloneWhereExpressionIntent(expr.intent)) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'unsafeAsPredicate',\n\t\t\t`unsupported standalone WHERE expression kind '${expr.intent.kind}'`,\n\t\t);\n\t}\n\treturn new ExpressionPredicateRef(expr.intent);\n}\n\nfunction isStandaloneWhereExpressionIntent(\n\tintent: ExpressionIntent,\n): intent is StandaloneWhereExpressionIntent {\n\tswitch (intent.kind) {\n\t\tcase 'customOp':\n\t\tcase 'customFn':\n\t\tcase 'ref':\n\t\tcase 'param':\n\t\tcase 'cast':\n\t\tcase 'literal':\n\t\tcase 'unary':\n\t\tcase 'namedArg':\n\t\tcase 'star':\n\t\tcase 'array':\n\t\tcase 'subquery':\n\t\tcase 'relationColumn':\n\t\tcase 'case':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction isPredicateOperator(operator: string): operator is PredicateOperator {\n\treturn (\n\t\toperator === '=' ||\n\t\toperator === '!=' ||\n\t\toperator === '<>' ||\n\t\toperator === '<' ||\n\t\toperator === '<=' ||\n\t\toperator === '>' ||\n\t\toperator === '>=' ||\n\t\toperator === '@@' ||\n\t\toperator === '@@@' ||\n\t\toperator === '&&' ||\n\t\toperator === '<@' ||\n\t\toperator === '@>'\n\t);\n}\n\n/**\n * Custom function call — name(args...).\n * Supports schema-qualified names (e.g., 'paradedb.score', 'ST_Distance').\n * Implicit conversions: string → ref(), number/boolean/array → param().\n *\n * @example fn('now') → now()\n * @example fn('paradedb.score', ref('id')) → paradedb.score(\"id\")\n * @throws Error if name fails validation (injection guard)\n */\n/**\n * Custom function call — name(args...).\n * Supports schema-qualified names (e.g., 'paradedb.score', 'ST_Distance').\n * Implicit conversions: string → ref(), number/boolean/array → param().\n *\n * Pass `aggOrderBy('col', 'asc')` args to add ORDER BY inside aggregates:\n * `fn('array_agg', ref('name'), aggOrderBy('path'))` → array_agg(\"name\" ORDER BY \"path\" ASC)\n *\n * @example fn('now') → now()\n * @example fn('paradedb.score', ref('id')) → paradedb.score(\"id\")\n * @example fn('array_agg', ref('name'), aggOrderBy('path')) → array_agg(\"name\" ORDER BY \"path\" ASC)\n * @example fn('count', distinct('id')) → count(DISTINCT id)\n * @example fn('string_agg', distinct('x'), literal(',')) → string_agg(DISTINCT x, ',')\n * @throws Error if name fails validation (injection guard)\n */\nexport function fn(\n\tname: string,\n\t...args: (ExprInput | DistinctField)[]\n): ExpressionRef {\n\tif (!name || !FUNCTION_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`Invalid function name: ${name}`);\n\t}\n\t// A DistinctField argument (e.g. fn('count', distinct('id'))) marks the call\n\t// DISTINCT and is otherwise compiled like any other arg — via its underlying\n\t// ref (toExpressionIntent(field)). This routes through the SAME customFn path\n\t// every other fn() call uses (compileExpressionIntent → funcCall(..., { distinct })),\n\t// so DISTINCT works in every context (columns/orderBy/having/cast/nested), not just\n\t// .columns(). No name whitelist: PostgreSQL validates aggregate-ness at call time.\n\t//\n\t// SQL DISTINCT is a call-level modifier rendered BEFORE the whole argument list\n\t// (func(DISTINCT a, b, ...)) — it is not attached to a specific argument. So\n\t// distinct() is only accepted as the FIRST argument: accepting it at any later\n\t// position (e.g. fn('string_agg', literal(','), distinct('name'))) would compile\n\t// to `string_agg(DISTINCT ',', name)`, misrepresenting which argument the caller\n\t// meant as distinct.\n\tconst regularArgs: ExpressionIntent[] = [];\n\tconst orderByArgs: AggOrderByArg[] = [];\n\tlet distinct = false;\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i] as ExprInput | DistinctField;\n\t\tif (isDistinctField(arg)) {\n\t\t\tif (i !== 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`fn('${name}', ...): distinct() is only supported as the first argument — ` +\n\t\t\t\t\t\t'SQL DISTINCT applies to the whole argument list, not a single position.',\n\t\t\t\t);\n\t\t\t}\n\t\t\t// DESIGN BOUND: COUNT(DISTINCT *) (and DISTINCT on any other star\n\t\t\t// aggregate) is invalid PostgreSQL — '*' has no columns to\n\t\t\t// deduplicate on. This is the honest typed path (fn(name,\n\t\t\t// distinct(field))) and gets a clear error here, same as\n\t\t\t// buildAggregate's equivalent check for .count/.sum/.avg(distinct(...)).\n\t\t\t// The generic NQL function path (compiler.ts's compileGenericNqlFunction,\n\t\t\t// reached via selectNqlFunction / nested 'aggregate' records) and the\n\t\t\t// direct custom-expression path (custom.ts's 'customFn' case) do NOT\n\t\t\t// have an equivalent guard — they're reached only via hand-built\n\t\t\t// PlanDecision/ExpressionIntent objects (bypassing the typed DX API\n\t\t\t// entirely, e.g. NQL parsing or hand-assembled intent JSON), and a\n\t\t\t// DISTINCT * there compiles to SQL PostgreSQL itself rejects with a\n\t\t\t// syntax error. That's an accepted, loud-failure bound — not a\n\t\t\t// silent-wrong-result — so it is intentionally not pre-guarded at\n\t\t\t// every chokepoint; this comment is the record of that decision.\n\t\t\tconst field = arg.field;\n\t\t\tif (field === '*') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`fn('${name}', distinct('*')): DISTINCT on '*' is not valid SQL — ` +\n\t\t\t\t\t\t\"'*' has no columns to deduplicate on. Provide a specific column, \" +\n\t\t\t\t\t\t`or omit distinct() (e.g. fn('${name}', star())) for a plain star call.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdistinct = true;\n\t\t\tregularArgs.push(toExpressionIntent(field));\n\t\t} else if (isAggOrderByArg(arg)) {\n\t\t\torderByArgs.push(arg);\n\t\t} else {\n\t\t\tregularArgs.push(toExpressionIntent(arg));\n\t\t}\n\t}\n\tconst intent: CustomFnExpressionIntent = {\n\t\tkind: 'customFn',\n\t\tname,\n\t\targs: regularArgs,\n\t\t...(distinct ? { distinct: true } : {}),\n\t\t...(orderByArgs.length > 0 ? { aggOrderBy: orderByArgs } : {}),\n\t};\n\treturn new ExpressionRef(intent);\n}\n\n/**\n * Declare that a custom function call is boolean-valued for use in WHERE.\n *\n * This has the same trust boundary as the SQL function name and arguments the\n * caller writes: use it only when the declared function returns boolean.\n * Unlike `fn()`, which builds a scalar expression, `boolFn()` builds a\n * predicate that can be passed directly to `.where()`.\n *\n * @example boolFn('jsonb_exists', ref('data'), literal('phone'))\n * @throws Error if name fails validation (injection guard)\n */\nexport function boolFn(\n\tname: string,\n\t...args: (ExprInput | DistinctField)[]\n): PredicateExpressionRef {\n\treturn new ExpressionPredicateRef(\n\t\tfn(name, ...args).intent as CustomFnExpressionIntent,\n\t);\n}\n\n/**\n * Literal value — inlined directly in SQL (not bound as parameter).\n * Use to distinguish SQL string literals from column references.\n *\n * | Call | SQL |\n * |------|-----|\n * | `literal(42)` | `42` (inline integer) |\n * | `literal('text')` | `'text'` (SQL string literal) |\n * | `literal(null)` | `NULL` |\n *\n * @example literal(1) → 1 (for: 1 - (col <=> vec))\n */\nexport function literal(\n\tvalue: string | number | boolean | null,\n): ExpressionRef {\n\treturn new ExpressionRef({\n\t\tkind: 'literal',\n\t\tvalue,\n\t} satisfies LiteralExpressionIntent);\n}\n\n/**\n * Unary operator — OP expr (prefix form).\n *\n * @example unary('NOT', ref('active')) → NOT \"active\"\n * @example unary('-', ref('score')) → -\"score\"\n * @throws Error if operator fails validation (injection guard)\n */\nexport function unary(operator: string, expr: ExprInput): ExpressionRef {\n\tif (!operator || !OPERATOR_PATTERN.test(operator)) {\n\t\tthrow new Error(`Invalid operator: ${operator}`);\n\t}\n\treturn new ExpressionRef({\n\t\tkind: 'unary',\n\t\toperator,\n\t\toperand: toExpressionIntent(expr),\n\t} satisfies UnaryExpressionIntent);\n}\n\n/**\n * Named argument for function calls: name => value.\n * Use inside fn() args to produce PostgreSQL named-argument syntax.\n *\n * @example namedArg('field', literal('name_searchable'))\n * → field => 'name_searchable'\n * @example namedArg('query_string', param('hello'))\n * → query_string => $1\n */\nexport function namedArg(name: string, value: ExprInput): ExpressionRef {\n\tif (!name || !FUNCTION_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`namedArg: invalid argument name: ${name}`);\n\t}\n\treturn new ExpressionRef({\n\t\tkind: 'namedArg',\n\t\tname,\n\t\tvalue: toExpressionIntent(value),\n\t} satisfies NamedArgExpressionIntent);\n}\n\n/** SQL wildcard (*) — use in fn('count', star()) for COUNT(*) */\nexport function star(): ExpressionRef {\n\treturn new ExpressionRef({ kind: 'star' } satisfies StarExpressionIntent);\n}\n\n/**\n * PostgreSQL ARRAY constructor: ARRAY[item1, item2, ...]\n *\n * @example array(literal(1), literal(2), literal(3)) → ARRAY[1, 2, 3]\n * @example array(ref('name'), ref('kind')) → ARRAY[\"name\", \"kind\"]\n */\nexport function array(...items: ExprInput[]): ExpressionRef {\n\treturn new ExpressionRef({\n\t\tkind: 'array',\n\t\telements: items.map(toExpressionIntent),\n\t} satisfies ArrayExpressionIntent);\n}\n\n// ============================================================================\n// Aggregate ORDER BY helpers (FR-9)\n// ============================================================================\n\n/**\n * Type guard for DistinctField — distinguishes the `distinct('col')` marker\n * from regular ExprInput values inside fn() argument lists. Delegates the\n * core recognition to filters.ts's isDistinctField (the single canonical\n * check, shared with .count()/.sum()/.avg()) and additionally excludes\n * arrays/ExpressionRef, which are other possible ExprInput shapes here.\n */\nfunction isDistinctField(input: unknown): input is DistinctField {\n\treturn (\n\t\t!Array.isArray(input) &&\n\t\t!(input instanceof ExpressionRef) &&\n\t\tisDistinctFieldValue(input)\n\t);\n}\n\n/**\n * Type guard for AggOrderByArg — distinguishes aggregate ORDER BY markers\n * from regular ExprInput values inside fn() argument lists.\n */\nfunction isAggOrderByArg(input: ExprInput): input is AggOrderByArg {\n\treturn (\n\t\ttypeof input === 'object' &&\n\t\tinput !== null &&\n\t\t!Array.isArray(input) &&\n\t\t!(input instanceof ExpressionRef) &&\n\t\t'__aggOrderBy' in input &&\n\t\t(input as AggOrderByArg).__aggOrderBy === true\n\t);\n}\n\n/**\n * Creates an ORDER BY marker for use as an argument to `fn()`.\n * When passed to `fn()`, the compiler places it in the aggregate's\n * ORDER BY clause instead of in the regular argument list.\n *\n * @example fn('array_agg', ref('name'), aggOrderBy('path')) → array_agg(\"name\" ORDER BY \"path\" ASC)\n * @example fn('array_agg', ref('name'), aggOrderBy('path', 'desc')) → array_agg(\"name\" ORDER BY \"path\" DESC)\n */\nexport function aggOrderBy(\n\tfield: string,\n\tdirection: 'asc' | 'desc' = 'asc',\n): AggOrderByArg {\n\treturn { __aggOrderBy: true, field, direction };\n}\n\n/**\n * Shorthand for `fn('array_agg', col, ...orderByArgs)`.\n *\n * @example arrayAgg(ref('name')) → array_agg(\"name\")\n * @example arrayAgg(ref('name'), aggOrderBy('path')) → array_agg(\"name\" ORDER BY \"path\" ASC)\n * @example arrayAgg('name', aggOrderBy('path', 'desc')) → array_agg(\"name\" ORDER BY \"path\" DESC)\n * @example arrayAgg(distinct('name')) → array_agg(DISTINCT name)\n */\nexport function arrayAgg(\n\tcol: ExpressionRef | string | DistinctField,\n\t...rest: AggOrderByArg[]\n): ExpressionRef {\n\tconst colExpr: ExpressionRef | DistinctField =\n\t\ttypeof col === 'string' ? ref(col) : col;\n\treturn fn('array_agg', colExpr, ...rest);\n}\n\n/**\n * Shorthand for `fn('string_agg', col, separator, ...orderByArgs)`.\n *\n * @example stringAgg(ref('name'), literal(',')) → string_agg(\"name\", ',')\n * @example stringAgg(ref('name'), literal(','), aggOrderBy('name')) → string_agg(\"name\", ',' ORDER BY \"name\" ASC)\n * @example stringAgg(distinct('name'), literal(',')) → string_agg(DISTINCT name, ',')\n */\nexport function stringAgg(\n\tcol: ExpressionRef | string | DistinctField,\n\tseparator: ExpressionRef,\n\t...rest: AggOrderByArg[]\n): ExpressionRef {\n\tconst colExpr: ExpressionRef | DistinctField =\n\t\ttypeof col === 'string' ? ref(col) : col;\n\treturn fn('string_agg', colExpr, separator, ...rest);\n}\n","import type {\n\tCaseExpressionIntent,\n\tExpressionIntent,\n\tWhereIntent,\n} from '@dbsp/types';\nimport { ExpressionRef } from './expressions.js';\n\nfunction toResultIntent(\n\tvalue: ExpressionRef | string | number | boolean | null | undefined,\n): ExpressionIntent {\n\tif (value instanceof ExpressionRef) {\n\t\treturn value.intent;\n\t}\n\tif (value === null || value === undefined) {\n\t\treturn { kind: 'literal', value: null } satisfies ExpressionIntent;\n\t}\n\tif (typeof value === 'string') {\n\t\treturn { kind: 'ref', column: value } satisfies ExpressionIntent;\n\t}\n\treturn { kind: 'literal', value } satisfies ExpressionIntent;\n}\n\nexport type CaseValue = ExpressionRef | string | number | boolean | null;\n\nexport class CaseBuilder {\n\tprivate readonly branches: ReadonlyArray<{\n\t\treadonly condition: WhereIntent;\n\t\treadonly result: ExpressionIntent;\n\t}>;\n\n\tconstructor(\n\t\tbranches: ReadonlyArray<{\n\t\t\treadonly condition: WhereIntent;\n\t\t\treadonly result: ExpressionIntent;\n\t\t}>,\n\t) {\n\t\tthis.branches = branches;\n\t}\n\n\twhen(condition: WhereIntent, thenValue: CaseValue): CaseBuilder {\n\t\treturn new CaseBuilder([\n\t\t\t...this.branches,\n\t\t\t{ condition, result: toResultIntent(thenValue) },\n\t\t]);\n\t}\n\n\telse(elseValue: CaseValue): ExpressionRef {\n\t\tconst intent: CaseExpressionIntent = {\n\t\t\tkind: 'case',\n\t\t\twhen: this.branches,\n\t\t\telse: toResultIntent(elseValue),\n\t\t};\n\t\treturn new ExpressionRef(intent as ExpressionIntent);\n\t}\n\n\tas(alias: string): ExpressionRef {\n\t\treturn this.toExpr().as(alias);\n\t}\n\n\ttoExpr(): ExpressionRef {\n\t\tconst intent: CaseExpressionIntent = {\n\t\t\tkind: 'case',\n\t\t\twhen: this.branches,\n\t\t};\n\t\treturn new ExpressionRef(intent as ExpressionIntent);\n\t}\n}\n\nexport function caseWhen(\n\tcondition: WhereIntent,\n\tthenValue: CaseValue,\n): CaseBuilder {\n\treturn new CaseBuilder([{ condition, result: toResultIntent(thenValue) }]);\n}\n","/**\n * Shared builder utilities for CTE and recursive query builders.\n */\n\nimport type { Adapter } from '@dbsp/types';\nimport { InvalidOperationError } from './errors.js';\n\n/**\n * Asserts that an adapter is present, throwing a descriptive error if not.\n *\n * @param adapter - The adapter instance (may be undefined)\n * @param operationName - The public API operation name, used in the error message\n * @returns The validated adapter\n */\nexport function requireAdapter(\n\tadapter: Adapter | undefined,\n\toperationName: string,\n): Adapter {\n\tif (!adapter) {\n\t\tthrow new InvalidOperationError(\n\t\t\toperationName,\n\t\t\t'This operation requires an adapter \\u2014 pass an adapter when creating the ORM',\n\t\t);\n\t}\n\treturn adapter;\n}\n","/**\n * CTE builder with unnest() support (BATCH-001 Block 5).\n *\n * Provides a fluent API for building CTE queries backed by unnest() arrays,\n * optionally with WITH ORDINALITY for 0-based indexing.\n *\n * @example\n * ```typescript\n * const result = orm.withCte('lookups')\n * .fromUnnest({ parent_file_id: [1, 2, 3], parent_name: ['Foo', 'Bar', 'Baz'] })\n * .withIndex('idx')\n * .query(orm.select('symbols'))\n * .dump();\n * ```\n */\n\nimport type {\n\tAdapter,\n\tCompiledQuery,\n\tCteQueryIntent,\n\tModelIR,\n\tUnnestCteIntent,\n} from '@dbsp/types';\nimport { executeCompiledQuery } from '../adapter.js';\nimport { requireAdapter as requireAdapterUtil } from './builder-utils.js';\nimport { InvalidOperationError } from './errors.js';\nimport type { QueryBuilderImpl } from './query-builder.js';\nimport type { QueryBuilder } from './query-builder-types.js';\n\n// ============================================================================\n// CteBuilder\n// ============================================================================\n\n/**\n * Fluent builder for constructing a CTE definition backed by unnest() arrays.\n *\n * Obtain via `orm.withCte(name)`.\n */\nexport class CteBuilder {\n\tprivate readonly cteName: string;\n\tprivate readonly adapter: Adapter | undefined;\n\tprivate readonly schemaName: string | undefined;\n\tprivate readonly model: ModelIR | undefined;\n\tprivate unnestColumns: Record<string, readonly unknown[]> | undefined;\n\tprivate indexColumnName: string | undefined;\n\n\tconstructor(\n\t\tname: string,\n\t\tadapter?: Adapter,\n\t\tschemaName?: string,\n\t\tmodel?: ModelIR,\n\t) {\n\t\tthis.cteName = name;\n\t\tthis.adapter = adapter;\n\t\tthis.schemaName = schemaName;\n\t\tthis.model = model;\n\t}\n\n\t/**\n\t * Provide the column arrays for the unnest() CTE.\n\t * All arrays must have the same length.\n\t *\n\t * @param columns - A record of column name → array of values.\n\t */\n\tfromUnnest(columns: Record<string, readonly unknown[]>): this {\n\t\tconst lengths = Object.values(columns).map((arr) => arr.length);\n\t\tif (lengths.length > 1 && !lengths.every((l) => l === lengths[0])) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'withCte',\n\t\t\t\t`Array length mismatch in CTE unnest columns: lengths are [${lengths.join(', ')}]`,\n\t\t\t);\n\t\t}\n\t\tthis.unnestColumns = columns;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a 0-based ordinality index column (uses WITH ORDINALITY).\n\t *\n\t * @param columnName - The name of the index column in the CTE.\n\t */\n\twithIndex(columnName: string): this {\n\t\tthis.indexColumnName = columnName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Attach an outer query and produce a CteQueryBuilder for execution.\n\t *\n\t * @param selectBuilder - A QueryBuilder (from orm.select(...))\n\t */\n\tquery<TResult = unknown>(\n\t\tselectBuilder: QueryBuilder<TResult>,\n\t): CteQueryBuilder<TResult> {\n\t\tif (!this.unnestColumns) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'withCte',\n\t\t\t\t'CTE requires a data source — call .fromUnnest() first',\n\t\t\t);\n\t\t}\n\n\t\tconst cteIntent: UnnestCteIntent = {\n\t\t\tkind: 'unnestCte',\n\t\t\tname: this.cteName,\n\t\t\tcolumns: this.unnestColumns,\n\t\t\t...(this.indexColumnName !== undefined && {\n\t\t\t\tindexColumn: this.indexColumnName,\n\t\t\t}),\n\t\t};\n\n\t\treturn new CteQueryBuilder<TResult>(\n\t\t\tcteIntent,\n\t\t\tselectBuilder as QueryBuilderImpl<TResult>,\n\t\t\tthis.adapter,\n\t\t\tthis.schemaName,\n\t\t\tthis.model,\n\t\t);\n\t}\n}\n\n// ============================================================================\n// CteQueryBuilder\n// ============================================================================\n\n/**\n * Result of compiling a CTE query.\n */\nexport interface CteDump {\n\treadonly sql: string;\n\treadonly params: readonly unknown[];\n\treadonly intent: CteQueryIntent;\n}\n\n/**\n * Fluent builder for executing a WITH ... SELECT query.\n *\n * Produced by `CteBuilder.query()`.\n */\nexport class CteQueryBuilder<TResult = unknown> {\n\tprivate readonly cteIntent: UnnestCteIntent;\n\tprivate readonly outerBuilder: QueryBuilderImpl<TResult>;\n\tprivate readonly adapter: Adapter | undefined;\n\tprivate readonly schemaName: string | undefined;\n\tprivate readonly model: ModelIR | undefined;\n\n\tconstructor(\n\t\tcteIntent: UnnestCteIntent,\n\t\touterBuilder: QueryBuilderImpl<TResult>,\n\t\tadapter?: Adapter,\n\t\tschemaName?: string,\n\t\tmodel?: ModelIR,\n\t) {\n\t\tthis.cteIntent = cteIntent;\n\t\tthis.outerBuilder = outerBuilder;\n\t\tthis.adapter = adapter;\n\t\tthis.schemaName = schemaName;\n\t\tthis.model = model;\n\t}\n\n\t/**\n\t * Build the CteQueryIntent AST.\n\t */\n\tbuildIntent(): CteQueryIntent {\n\t\tconst queryIntent = this.outerBuilder.buildIntent();\n\t\treturn {\n\t\t\tkind: 'cteQuery',\n\t\t\tctes: [this.cteIntent],\n\t\t\tquery: queryIntent,\n\t\t};\n\t}\n\n\tprivate requireAdapter(): Adapter {\n\t\treturn requireAdapterUtil(this.adapter, 'withCte');\n\t}\n\n\tprivate compileOptions():\n\t\t| { readonly schemaName?: string; readonly model?: ModelIR }\n\t\t| undefined {\n\t\tif (this.schemaName === undefined && this.model === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\t...(this.schemaName !== undefined && { schemaName: this.schemaName }),\n\t\t\t...(this.model !== undefined && { model: this.model }),\n\t\t};\n\t}\n\n\t/**\n\t * Compile to SQL and return an observability dump.\n\t */\n\tdump(): CteDump {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst intent = this.buildIntent();\n\t\tconst compileOptions = this.compileOptions();\n\n\t\tconst compiled: CompiledQuery = adapter.compileCteQuery(\n\t\t\tintent,\n\t\t\tcompileOptions,\n\t\t);\n\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparams: compiled.parameters,\n\t\t\tintent,\n\t\t};\n\t}\n\n\t/**\n\t * Execute the CTE query and return all results.\n\t */\n\tasync all(): Promise<TResult[]> {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst intent = this.buildIntent();\n\t\tconst compileOptions = this.compileOptions();\n\n\t\tconst compiled = adapter.compileCteQuery<TResult>(intent, compileOptions);\n\n\t\treturn executeCompiledQuery(adapter, compiled, 'withCte().all()');\n\t}\n\n\t/**\n\t * Alias for all().\n\t */\n\texecute(): Promise<TResult[]> {\n\t\treturn this.all();\n\t}\n}\n","import type { DDLFeature, DialectCapabilities, ModelIR } from '@dbsp/types';\n\n// ---------------------------------------------------------------------------\n// FeatureChecker interface (OCP-001: Open/Closed for feature negotiation)\n// ---------------------------------------------------------------------------\n\n/**\n * Restricted key type: only keys of DialectCapabilities whose value is boolean\n * (or optional boolean). Prevents custom checkers from targeting non-boolean\n * fields (name, recursivePathStyle, identifierQuote, etc.) where a truthy\n * guard would silently break at runtime.\n */\nexport type DialectCapabilityFlag = Extract<\n\t{\n\t\t[K in keyof DialectCapabilities]: NonNullable<\n\t\t\tDialectCapabilities[K]\n\t\t> extends boolean\n\t\t\t? K\n\t\t\t: never;\n\t}[keyof DialectCapabilities],\n\tstring\n>;\n\n/**\n * A self-contained checker for a single DDL feature.\n * Add a new feature by appending a FeatureChecker to DEFAULT_FEATURE_CHECKERS\n * -- no edits to negotiateFeatures() required.\n *\n * Note: when multiple checkers target the same `capability`, all run in array\n * order and each can emit warnings/errors. Deduplication by capability is the\n * caller's responsibility.\n */\nexport interface FeatureChecker {\n\t/** Capability flag key — restricted to boolean-valued fields of DialectCapabilities. */\n\treadonly capability: DialectCapabilityFlag;\n\t/** DDLFeature name used in warn/error messages and behavior lookup. */\n\treadonly feature: DDLFeature;\n\t/**\n\t * Walk the ModelIR and return locations where this feature is used.\n\t * Return empty array if the feature is not used anywhere.\n\t */\n\tdetectUsage(model: ModelIR): readonly FeatureUsage[];\n}\n\n/** Location descriptor returned by FeatureChecker.detectUsage(). */\nexport interface FeatureUsage {\n\treadonly table?: string;\n\treadonly column?: string;\n\t/** Human-readable element label used in warn/error messages. */\n\treadonly detail: string;\n}\n\n// ---------------------------------------------------------------------------\n// Default registry -- one entry per supportsDDL* capability flag\n// ---------------------------------------------------------------------------\n\n/**\n * Default feature checkers -- mirrors the 17 supportsDDL* flags that\n * negotiateFeatures() previously checked inline.\n *\n * Each checker preserves exactly the same detection logic (same guards,\n * same element label format) that was previously inlined in negotiateFeatures().\n */\nexport const DEFAULT_FEATURE_CHECKERS: readonly FeatureChecker[] =\n\tObject.freeze<readonly FeatureChecker[]>([\n\t\t// -----------------------------------------------------------------------\n\t\t// Schema-level features\n\t\t// -----------------------------------------------------------------------\n\t\t{\n\t\t\tcapability: 'supportsDDLEnumTypes',\n\t\t\tfeature: 'enum',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.enums?.size) return [];\n\t\t\t\treturn [...model.enums.keys()].map((name) => ({ detail: name }));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLSequences',\n\t\t\tfeature: 'sequence',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.sequences?.size) return [];\n\t\t\t\treturn [...model.sequences.keys()].map((name) => ({ detail: name }));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLExtensions',\n\t\t\tfeature: 'extension',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.extensions?.length) return [];\n\t\t\t\treturn model.extensions.map((ext) => ({ detail: ext }));\n\t\t\t},\n\t\t},\n\n\t\t// -----------------------------------------------------------------------\n\t\t// Table-level features\n\t\t// -----------------------------------------------------------------------\n\t\t{\n\t\t\tcapability: 'supportsDDLPartitioning',\n\t\t\tfeature: 'partition',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tif (table.partition) {\n\t\t\t\t\t\tusages.push({ table: tableName, detail: tableName });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLComments',\n\t\t\tfeature: 'comment',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tif (table.comment) {\n\t\t\t\t\t\tusages.push({ table: tableName, detail: `${tableName} (table)` });\n\t\t\t\t\t}\n\t\t\t\t\tfor (const col of table.columns) {\n\t\t\t\t\t\tif (col.comment) {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tcolumn: col.name,\n\t\t\t\t\t\t\t\tdetail: `${tableName}.${col.name} (column)`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLCheckConstraints',\n\t\t\tfeature: 'checkConstraint',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tif (table.checkConstraints?.length) {\n\t\t\t\t\t\tfor (const chk of table.checkConstraints) {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tdetail: `${tableName}.${chk.name}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLOnUpdateFK',\n\t\t\tfeature: 'onUpdateFK',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const fk of table.foreignKeys) {\n\t\t\t\t\t\tif (fk.onUpdate && fk.onUpdate !== 'NO ACTION') {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tdetail: `${tableName} FK → ${fk.references.table}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLDeferredFK',\n\t\t\tfeature: 'deferredFK',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const fk of table.foreignKeys) {\n\t\t\t\t\t\tif (fk.deferred) {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tdetail: `${tableName} FK → ${fk.references.table}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\n\t\t// -----------------------------------------------------------------------\n\t\t// Column-level features\n\t\t// -----------------------------------------------------------------------\n\t\t{\n\t\t\tcapability: 'supportsDDLIdentityColumns',\n\t\t\tfeature: 'identity',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const col of table.columns) {\n\t\t\t\t\t\tif (col.identity) {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tcolumn: col.name,\n\t\t\t\t\t\t\t\tdetail: `${tableName}.${col.name}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLCollation',\n\t\t\tfeature: 'collation',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const col of table.columns) {\n\t\t\t\t\t\tif (col.collation) {\n\t\t\t\t\t\t\tusages.push({\n\t\t\t\t\t\t\t\ttable: tableName,\n\t\t\t\t\t\t\t\tcolumn: col.name,\n\t\t\t\t\t\t\t\tdetail: `${tableName}.${col.name}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\n\t\t// -----------------------------------------------------------------------\n\t\t// Index-level features\n\t\t// -----------------------------------------------------------------------\n\t\t{\n\t\t\tcapability: 'supportsDDLIndexMethods',\n\t\t\tfeature: 'indexMethod',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.method && idx.method !== 'btree') {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLIndexOpclass',\n\t\t\tfeature: 'indexOpclass',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.opclass && Object.keys(idx.opclass).length > 0) {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLIndexInclude',\n\t\t\tfeature: 'indexInclude',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.include?.length) {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLPartialIndexes',\n\t\t\tfeature: 'partialIndex',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.where) {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLExpressionIndexes',\n\t\t\tfeature: 'expressionIndex',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.expressions?.length) {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tcapability: 'supportsDDLIndexNullsNotDistinct',\n\t\t\tfeature: 'indexNullsNotDistinct',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tfor (const idx of table.indexes) {\n\t\t\t\t\t\tif (idx.nullsNotDistinct === true) {\n\t\t\t\t\t\t\tconst idxName = idx.name ?? `idx on ${tableName}`;\n\t\t\t\t\t\t\tusages.push({ table: tableName, detail: idxName });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\n\t\t// -----------------------------------------------------------------------\n\t\t// Row-Level Security\n\t\t// -----------------------------------------------------------------------\n\t\t{\n\t\t\tcapability: 'supportsDDLRowLevelSecurity',\n\t\t\tfeature: 'rowLevelSecurity',\n\t\t\tdetectUsage(model) {\n\t\t\t\tif (!model.tables) return [];\n\t\t\t\tconst usages: FeatureUsage[] = [];\n\t\t\t\tfor (const [tableName, table] of model.tables) {\n\t\t\t\t\tif (table.rlsEnabled || table.policies?.length) {\n\t\t\t\t\t\tusages.push({ table: tableName, detail: tableName });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn usages;\n\t\t\t},\n\t\t},\n\t]);\n","/**\n * @dbsp/core — Full-Text Search Helpers (FR-5)\n *\n * High-level cross-DB-friendly helpers that wrap the low-level ParadeDB\n * expression primitives (bm25Search / score from adapter-pgsql) using only\n * core expression building blocks.\n *\n * These helpers are ParadeDB/PostgreSQL-first; other adapters are expected\n * to either support the same SQL or receive a capability error at runtime.\n */\n\nimport type { ExpressionRef, PredicateExpressionRef } from './expressions.js';\nimport { array, fn, literal, namedArg, op, param, ref } from './expressions.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A single field to include in a full-text search, with an optional boost weight.\n */\nexport type FullTextSearchField = {\n\t/** Column name in the BM25 index */\n\treadonly name: string;\n\t/** Boost multiplier (higher = more important). Default: 1.0 */\n\treadonly boost: number;\n};\n\n/**\n * Options for fullTextSearch().\n */\nexport type FullTextSearchOptions = {\n\t/** The query string (will be bound as a single $N parameter shared across all fields). */\n\treadonly query: unknown;\n\t/** Fields to search with per-field boost weights. */\n\treadonly fields: readonly FullTextSearchField[];\n\t/**\n\t * Table name or alias to qualify the left side of the @@@ operator.\n\t * Must match the exact table name (or alias) as it appears in the FROM clause.\n\t * In the standard ORM pipeline the root table has no alias, so pass the root table name.\n\t *\n\t * @example\n\t * fullTextSearch({ query, fields, tableAlias: 'symbols' })\n\t * // → \"symbols\" @@@ paradedb.boolean(...)\n\t */\n\treadonly tableAlias: string;\n};\n\n// ============================================================================\n// fullTextSearch()\n// ============================================================================\n\n/**\n * High-level full-text search filter for ParadeDB BM25 index.\n *\n * Produces:\n * ```sql\n * \"tableAlias\" @@@ paradedb.boolean(\n * should => ARRAY[\n * paradedb.boost(weight1, paradedb.parse(field => 'field1', query_string => $N)),\n * paradedb.boost(weight2, paradedb.parse(field => 'field2', query_string => $N)),\n * ...\n * ]\n * )\n * ```\n *\n * The same query value is bound to separate $N parameters, one per field.\n *\n * @param options.query - Query string (bound as a single parameter)\n * @param options.fields - Fields to search with per-field boost weights\n * @param options.tableAlias - Table name or alias as it appears in the FROM clause (required).\n * In the standard ORM pipeline the root table has no alias — pass the root table name directly.\n * @returns ExpressionRef for use in .where()\n *\n * @example\n * ```typescript\n * import { fullTextSearch } from '@dbsp/core';\n *\n * .where(fullTextSearch({\n * query: searchTerm,\n * tableAlias: 'symbols',\n * fields: [\n * { name: 'name', boost: 3.0 },\n * { name: 'doc', boost: 1.0 },\n * ],\n * }))\n * ```\n */\nexport function fullTextSearch({\n\tquery,\n\tfields,\n\ttableAlias,\n}: FullTextSearchOptions): PredicateExpressionRef {\n\tconst queryParam = param(query);\n\tconst boostExprs = fields.map(({ name: fieldName, boost: weight }) =>\n\t\tfn(\n\t\t\t'paradedb.boost',\n\t\t\tliteral(weight),\n\t\t\tfn(\n\t\t\t\t'paradedb.parse',\n\t\t\t\tnamedArg('field', literal(fieldName)),\n\t\t\t\tnamedArg('query_string', queryParam),\n\t\t\t),\n\t\t),\n\t);\n\tconst booleanExpr = fn(\n\t\t'paradedb.boolean',\n\t\tnamedArg('should', array(...boostExprs)),\n\t);\n\treturn op('@@@', ref(tableAlias), booleanExpr);\n}\n\n// ============================================================================\n// textScore()\n// ============================================================================\n\n/**\n * BM25 relevance score expression for ParadeDB.\n *\n * Produces: paradedb.score(\"keyField\")\n *\n * Use in .columns() to include the score in results, and in .orderBy() to rank\n * results by relevance. Requires a BM25 index with the given key field on the table.\n *\n * @param keyField - The primary key field of the BM25 index (default: 'id')\n * @returns ExpressionRef for use in .columns() and .orderBy()\n *\n * @example\n * ```typescript\n * import { textScore } from '@dbsp/core';\n *\n * .columns(['*', textScore().as('score')])\n * .orderBy(textScore(), 'desc')\n * // SQL: SELECT *, paradedb.score(\"id\") AS \"score\" ... ORDER BY paradedb.score(\"id\") DESC\n * ```\n */\nexport function textScore(keyField = 'id'): ExpressionRef {\n\treturn fn('paradedb.score', ref(keyField));\n}\n","/**\n * Hook composition utilities (ARCH-008).\n * Provides compose/pipe for combining multiple hooks into one,\n * and priority-ordered registration helpers.\n */\n\nimport type {\n\tAfterMutationHook,\n\tAfterQueryHook,\n\tBeforeMutationHook,\n\tBeforeQueryHook,\n\tErrorHookContext,\n\tMutationHookContext,\n\tOnErrorHook,\n\tQueryHookContext,\n} from './hooks.js';\n\n// ============================================================================\n// Priority\n// ============================================================================\n\n/**\n * Priority levels for hook ordering.\n * Hooks with higher priority run first when sorted.\n */\nexport type HookPriority = 'critical' | 'high' | 'normal' | 'low';\n\nconst PRIORITY_ORDER: Record<HookPriority, number> = {\n\tcritical: 0,\n\thigh: 1,\n\tnormal: 2,\n\tlow: 3,\n};\n\n/**\n * A hook wrapped with an explicit priority for ordering.\n * Use {@link sortByPriority} to produce an ordered array.\n */\nexport type PrioritizedHook<TFn> = {\n\treadonly hook: TFn;\n\treadonly priority: HookPriority;\n};\n\n/**\n * Wraps a hook with a priority level for use with {@link sortByPriority}.\n *\n * @example\n * ```typescript\n * const hooks = [\n * withPriority(auditHook, 'low'),\n * withPriority(authHook, 'critical'),\n * ];\n * const ordered = sortByPriority(hooks); // authHook runs first\n * ```\n */\nexport function withPriority<TFn>(\n\thook: TFn,\n\tpriority: HookPriority,\n): PrioritizedHook<TFn> {\n\treturn { hook, priority };\n}\n\n/**\n * Sorts an array of prioritized hooks by priority (critical → high → normal → low).\n * Stable: hooks with the same priority retain their original relative order.\n *\n * @returns A new array of unwrapped hook functions in priority order.\n */\nexport function sortByPriority<TFn>(\n\thooks: readonly PrioritizedHook<TFn>[],\n): TFn[] {\n\treturn [...hooks]\n\t\t.sort((a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority])\n\t\t.map((p) => p.hook);\n}\n\n// ============================================================================\n// BeforeQueryHook composition\n// ============================================================================\n\n/**\n * Composes multiple {@link BeforeQueryHook}s into one (right-to-left execution).\n * The rightmost hook runs first; its output feeds into the next.\n * If a hook returns `undefined`, the current context is passed unchanged.\n *\n * @example\n * ```typescript\n * const composed = composeBeforeQueryHooks(loggingHook, tracingHook);\n * // tracingHook runs first, then loggingHook\n * ```\n */\nexport function composeBeforeQueryHooks(\n\t...hooks: BeforeQueryHook[]\n): BeforeQueryHook {\n\t// reverse so rightmost runs first\n\tconst ordered = [...hooks].reverse();\n\treturn async (ctx: QueryHookContext): Promise<QueryHookContext> => {\n\t\tlet current: QueryHookContext = ctx;\n\t\tfor (const hook of ordered) {\n\t\t\tconst result = await hook(current);\n\t\t\tif (result !== undefined) {\n\t\t\t\tcurrent = result;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n/**\n * Pipes multiple {@link BeforeQueryHook}s together (left-to-right execution).\n * The leftmost hook runs first; its output feeds into the next.\n * If a hook returns `undefined`, the current context is passed unchanged.\n *\n * @example\n * ```typescript\n * const piped = pipeBeforeQueryHooks(tracingHook, loggingHook);\n * // tracingHook runs first, then loggingHook\n * ```\n */\nexport function pipeBeforeQueryHooks(\n\t...hooks: BeforeQueryHook[]\n): BeforeQueryHook {\n\treturn async (ctx: QueryHookContext): Promise<QueryHookContext> => {\n\t\tlet current: QueryHookContext = ctx;\n\t\tfor (const hook of hooks) {\n\t\t\tconst result = await hook(current);\n\t\t\tif (result !== undefined) {\n\t\t\t\tcurrent = result;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n// ============================================================================\n// AfterQueryHook composition\n// ============================================================================\n\n/**\n * Composes multiple {@link AfterQueryHook}s into one (right-to-left execution).\n * The rightmost hook runs first; its output becomes the result for the next.\n * If a hook returns `undefined`, the current result is passed unchanged.\n */\nexport function composeAfterQueryHooks(\n\t...hooks: AfterQueryHook[]\n): AfterQueryHook {\n\tconst ordered = [...hooks].reverse();\n\treturn async <R>(ctx: QueryHookContext, result: R): Promise<R> => {\n\t\tlet current: R = result;\n\t\tfor (const hook of ordered) {\n\t\t\tconst next = await hook(ctx, current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tcurrent = next as R;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n/**\n * Pipes multiple {@link AfterQueryHook}s together (left-to-right execution).\n * The leftmost hook runs first; its output becomes the result for the next.\n * If a hook returns `undefined`, the current result is passed unchanged.\n */\nexport function pipeAfterQueryHooks(\n\t...hooks: AfterQueryHook[]\n): AfterQueryHook {\n\treturn async <R>(ctx: QueryHookContext, result: R): Promise<R> => {\n\t\tlet current: R = result;\n\t\tfor (const hook of hooks) {\n\t\t\tconst next = await hook(ctx, current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tcurrent = next as R;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n// ============================================================================\n// BeforeMutationHook composition\n// ============================================================================\n\n/**\n * Composes multiple {@link BeforeMutationHook}s into one (right-to-left execution).\n * If a hook returns `undefined`, the current context is passed unchanged.\n */\nexport function composeBeforeMutationHooks(\n\t...hooks: BeforeMutationHook[]\n): BeforeMutationHook {\n\tconst ordered = [...hooks].reverse();\n\treturn async <T>(\n\t\tctx: MutationHookContext<T>,\n\t): Promise<MutationHookContext<T>> => {\n\t\tlet current: MutationHookContext<T> = ctx;\n\t\tfor (const hook of ordered) {\n\t\t\tconst result = await hook(current);\n\t\t\tif (result !== undefined) {\n\t\t\t\tcurrent = result;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n/**\n * Pipes multiple {@link BeforeMutationHook}s together (left-to-right execution).\n * If a hook returns `undefined`, the current context is passed unchanged.\n */\nexport function pipeBeforeMutationHooks(\n\t...hooks: BeforeMutationHook[]\n): BeforeMutationHook {\n\treturn async <T>(\n\t\tctx: MutationHookContext<T>,\n\t): Promise<MutationHookContext<T>> => {\n\t\tlet current: MutationHookContext<T> = ctx;\n\t\tfor (const hook of hooks) {\n\t\t\tconst result = await hook(current);\n\t\t\tif (result !== undefined) {\n\t\t\t\tcurrent = result;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n// ============================================================================\n// AfterMutationHook composition\n// ============================================================================\n\n/**\n * Composes multiple {@link AfterMutationHook}s into one (right-to-left execution).\n * If a hook returns `undefined`, the current rows are passed unchanged.\n */\nexport function composeAfterMutationHooks(\n\t...hooks: AfterMutationHook[]\n): AfterMutationHook {\n\tconst ordered = [...hooks].reverse();\n\treturn async <T>(ctx: MutationHookContext<T>, result: T[]): Promise<T[]> => {\n\t\tlet current: T[] = result;\n\t\tfor (const hook of ordered) {\n\t\t\tconst next = await hook(ctx, current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tcurrent = next;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n/**\n * Pipes multiple {@link AfterMutationHook}s together (left-to-right execution).\n * If a hook returns `undefined`, the current rows are passed unchanged.\n */\nexport function pipeAfterMutationHooks(\n\t...hooks: AfterMutationHook[]\n): AfterMutationHook {\n\treturn async <T>(ctx: MutationHookContext<T>, result: T[]): Promise<T[]> => {\n\t\tlet current: T[] = result;\n\t\tfor (const hook of hooks) {\n\t\t\tconst next = await hook(ctx, current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tcurrent = next;\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t};\n}\n\n// ============================================================================\n// OnErrorHook composition\n// ============================================================================\n\n/**\n * Composes multiple {@link OnErrorHook}s into one (right-to-left execution).\n * Each hook receives the error from the previous; if a hook returns `undefined`,\n * the current error is passed unchanged.\n */\nexport function composeOnErrorHooks(...hooks: OnErrorHook[]): OnErrorHook {\n\tconst ordered = [...hooks].reverse();\n\treturn async (ctx: ErrorHookContext): Promise<undefined | Error> => {\n\t\tlet currentCtx: ErrorHookContext = ctx;\n\t\tfor (const hook of ordered) {\n\t\t\tconst result = await hook(currentCtx);\n\t\t\tif (result !== undefined) {\n\t\t\t\t// Pass the transformed error forward via a new context\n\t\t\t\tcurrentCtx = { ...currentCtx, error: result };\n\t\t\t}\n\t\t}\n\t\treturn currentCtx.error;\n\t};\n}\n\n/**\n * Pipes multiple {@link OnErrorHook}s together (left-to-right execution).\n * Each hook receives the error from the previous; if a hook returns `undefined`,\n * the current error is passed unchanged.\n */\nexport function pipeOnErrorHooks(...hooks: OnErrorHook[]): OnErrorHook {\n\treturn async (ctx: ErrorHookContext): Promise<undefined | Error> => {\n\t\tlet currentCtx: ErrorHookContext = ctx;\n\t\tfor (const hook of hooks) {\n\t\t\tconst result = await hook(currentCtx);\n\t\t\tif (result !== undefined) {\n\t\t\t\tcurrentCtx = { ...currentCtx, error: result };\n\t\t\t}\n\t\t}\n\t\treturn currentCtx.error;\n\t};\n}\n","/**\n * @module hooks\n * Query/Mutation hook system for cross-cutting concerns.\n * Part of E17b: Query Hooks System.\n *\n * Hooks enable intercepting query/mutation execution for logging,\n * auditing, caching, data transformation, and tenant injection.\n *\n * @example\n * ```typescript\n * const hooks = createHookManager()\n * .beforeQuery(ctx => {\n * console.log(`Query on ${ctx.table}`);\n * return ctx;\n * })\n * .afterQuery((ctx, results) => {\n * console.log(`Got ${results.length} rows in ${ctx.duration}ms`);\n * return results;\n * });\n *\n * const orm = createOrm({ schema, adapter, hooks });\n * ```\n */\n\nimport type {\n\tBatchUpdateIntent,\n\tDeleteIntent,\n\tInsertFromIntent,\n\tInsertIntent,\n\tQueryIntent,\n\tUpdateIntent,\n\tUpsertFromIntent,\n\tUpsertIntent,\n} from '../intent-ast.js';\n\n// ============================================================================\n// Hook Context Types\n// ============================================================================\n\n/** Query execution result types for afterQuery generics */\nexport type QueryResultType = 'all' | 'first' | 'exists';\n\n/**\n * Context passed to query hooks (beforeQuery/afterQuery).\n * Frozen via Object.freeze — hooks must return new objects to modify.\n */\nexport type QueryHookContext = {\n\treadonly table: string;\n\treadonly operation: 'select';\n\treadonly intent: QueryIntent;\n\treadonly schemaName?: string;\n\treadonly inTransaction?: boolean;\n\treadonly correlationId?: string;\n\treadonly resultType: QueryResultType;\n\treadonly isStreaming?: boolean;\n\t// Available in afterQuery only:\n\treadonly sql?: string;\n\t/** Query parameters. May contain PII — redact before logging. */\n\treadonly parameters?: readonly unknown[];\n\treadonly duration?: number;\n};\n\n/** Union of all mutation intent types */\n/** Union of all mutation intent types */\nexport type MutationIntent =\n\t| InsertIntent\n\t| InsertFromIntent\n\t| UpdateIntent\n\t| BatchUpdateIntent\n\t| DeleteIntent\n\t| UpsertIntent\n\t| UpsertFromIntent;\n\n/** Mutation operation types */\nexport type MutationOperation =\n\t| 'insert'\n\t| 'insert_from'\n\t| 'update'\n\t| 'batchUpdate'\n\t| 'delete'\n\t| 'upsert'\n\t| 'upsert_from';\n\n/**\n * Context passed to mutation hooks (beforeMutation/afterMutation).\n * Frozen via Object.freeze — hooks must return new objects to modify.\n */\nexport type MutationHookContext<T = unknown> = {\n\treadonly table: string;\n\treadonly operation: MutationOperation;\n\treadonly intent: MutationIntent;\n\treadonly schemaName?: string;\n\treadonly inTransaction?: boolean;\n\treadonly correlationId?: string;\n\treadonly cardinality: 'single' | 'bulk';\n\treadonly data?: T | T[] | Partial<T>;\n\t// Available in afterMutation only:\n\treadonly sql?: string;\n\t/** Query parameters. May contain PII — redact before logging. */\n\treadonly parameters?: readonly unknown[];\n\treadonly duration?: number;\n\treadonly affectedRows?: number;\n};\n\n/** Hook phase identifier */\nexport type HookPhase =\n\t| 'beforeQuery'\n\t| 'afterQuery'\n\t| 'beforeMutation'\n\t| 'afterMutation';\n\n/**\n * Context passed to onError hooks.\n */\nexport type ErrorHookContext = {\n\treadonly table: string;\n\treadonly operation: string;\n\treadonly error: Error;\n\treadonly intent: QueryIntent | MutationIntent;\n\treadonly phase: HookPhase;\n\treadonly sql?: string;\n\treadonly inTransaction?: boolean;\n};\n\n// ============================================================================\n// Hook Signatures\n// ============================================================================\n\n/** Hook invoked before query execution. Can modify intent via return. */\nexport type BeforeQueryHook = (\n\tctx: QueryHookContext,\n) => QueryHookContext | Promise<QueryHookContext> | undefined;\n\n/** Observer invoked after query execution. Its return value is ignored. */\nexport type AfterQueryObserver = (\n\tctx: QueryHookContext,\n\tresult: unknown,\n) => void | Promise<void>;\n\n/** Hook invoked after query execution. Can transform results without changing their shape. */\nexport type AfterQueryHook = <R>(\n\tctx: QueryHookContext,\n\tresult: R,\n) => R | Promise<R> | undefined;\n\n/** Hook invoked before mutation execution. Can modify context via return. */\nexport type BeforeMutationHook = <T>(\n\tctx: MutationHookContext<T>,\n) => MutationHookContext<T> | Promise<MutationHookContext<T>> | undefined;\n\n/** Observer invoked after mutation execution. Its return value is ignored. */\nexport type AfterMutationObserver = (\n\tctx: MutationHookContext,\n\tresult: unknown,\n) => void | Promise<void>;\n\ntype ObserverRegistration<\n\tT extends (...args: never[]) => unknown,\n\tTObserver extends (...args: never[]) => unknown,\n> = ReturnType<T> extends ReturnType<TObserver> ? unknown : never;\n\n/** Hook invoked after mutation execution. Can transform RETURNING results without changing their shape. */\nexport type AfterMutationHook = <T>(\n\tctx: MutationHookContext<T>,\n\tresult: T[],\n) => T[] | Promise<T[]> | undefined;\n\n/** Hook invoked on query/mutation errors. Can transform the error. */\nexport type OnErrorHook = (\n\tctx: ErrorHookContext,\n) => undefined | Error | Promise<undefined | Error>;\n\n/**\n * Error handler for hook failures.\n * Returns 'continue' to skip failed hook, 'abort' to propagate error.\n */\nexport type HookErrorHandler = (\n\terror: Error,\n\thookName: string,\n\tctx: QueryHookContext | MutationHookContext,\n\tphase: string,\n) => 'continue' | 'abort';\n\n/**\n * Diagnostic sink for observer failures and snapshot skips.\n *\n * Unlike {@link HookErrorHandler}, this handler has no control-flow return:\n * observer diagnostics always go to a void sink and can never abort work that\n * has already executed.\n */\nexport type ObserverErrorHandler = (\n\terror: Error,\n\tobserverName: string,\n\tphase: 'afterQuery' | 'afterMutation',\n) => void | Promise<void>;\n\n/** @internal Normalize unknown thrown values without allowing coercion to throw. */\nexport function normalizeHookError(error: unknown): Error {\n\tif (error instanceof Error) return error;\n\ttry {\n\t\treturn new Error(String(error), { cause: error });\n\t} catch {\n\t\treturn new Error('Unknown hook error', { cause: error });\n\t}\n}\n\ntype ObserverSnapshot<T> = { readonly value: T } | { readonly error: unknown };\n\nfunction snapshotForObserver<T>(value: T): ObserverSnapshot<T> {\n\ttry {\n\t\treturn { value: structuredClone(value) };\n\t} catch (error) {\n\t\treturn { error };\n\t}\n}\n\nfunction reportObserverDiagnostic(...args: readonly unknown[]): void {\n\ttry {\n\t\tconsole.error(...args);\n\t} catch {\n\t\t// Diagnostics are a void sink: a replaced console must not affect callers.\n\t}\n}\n\nasync function reportObserverFailure(\n\terror: unknown,\n\thookName: string,\n\tphase: 'afterQuery' | 'afterMutation',\n\tonObserverError?: ObserverErrorHandler,\n): Promise<void> {\n\tconst normalized = normalizeHookError(error);\n\tif (onObserverError) {\n\t\ttry {\n\t\t\tawait onObserverError(normalized, hookName, phase);\n\t\t\treturn;\n\t\t} catch (sinkError) {\n\t\t\treportObserverDiagnostic(\n\t\t\t\t`[dbsp] ${phase} observer error sink failed:`,\n\t\t\t\tnormalizeHookError(sinkError),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}\n\treportObserverDiagnostic(\n\t\t`[dbsp] ${phase} observer failed (${hookName}):`,\n\t\tnormalized,\n\t);\n}\n\n// ============================================================================\n// Hook Manager Interface\n// ============================================================================\n\n/** Immutable builder interface for registering hooks */\nexport interface HookManager {\n\tbeforeQuery(hook: BeforeQueryHook): HookManager;\n\tobserveAfterQuery<T extends AfterQueryObserver>(\n\t\tobserver: T & ObserverRegistration<T, AfterQueryObserver>,\n\t): HookManager;\n\tafterQuery(hook: AfterQueryHook): HookManager;\n\tbeforeMutation(hook: BeforeMutationHook): HookManager;\n\tobserveAfterMutation<T extends AfterMutationObserver>(\n\t\tobserver: T & ObserverRegistration<T, AfterMutationObserver>,\n\t): HookManager;\n\tafterMutation(hook: AfterMutationHook): HookManager;\n\tonError(hook: OnErrorHook): HookManager;\n\tfreeze(): HookManager;\n}\n\n// ============================================================================\n// Internal Hook Storage\n// ============================================================================\n\n/** @internal Hook storage — exposed for runner access */\nexport type HookStore = {\n\treadonly beforeQuery: readonly BeforeQueryHook[];\n\treadonly afterQueryObservers: readonly AfterQueryObserver[];\n\treadonly afterQuery: readonly AfterQueryHook[];\n\treadonly beforeMutation: readonly BeforeMutationHook[];\n\treadonly afterMutationObservers: readonly AfterMutationObserver[];\n\treadonly afterMutation: readonly AfterMutationHook[];\n\treadonly onError: readonly OnErrorHook[];\n\treadonly frozen: boolean;\n};\n\n// ============================================================================\n// Hook Manager Implementation\n// ============================================================================\n\nclass HookManagerImpl implements HookManager {\n\tprivate readonly store: HookStore;\n\n\tconstructor(store?: HookStore) {\n\t\tthis.store = store ?? {\n\t\t\tbeforeQuery: [],\n\t\t\tafterQueryObservers: [],\n\t\t\tafterQuery: [],\n\t\t\tbeforeMutation: [],\n\t\t\tafterMutationObservers: [],\n\t\t\tafterMutation: [],\n\t\t\tonError: [],\n\t\t\tfrozen: false,\n\t\t};\n\t}\n\n\tbeforeQuery(hook: BeforeQueryHook): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tbeforeQuery: [...this.store.beforeQuery, hook],\n\t\t});\n\t}\n\n\tobserveAfterQuery<T extends AfterQueryObserver>(\n\t\tobserver: T & ObserverRegistration<T, AfterQueryObserver>,\n\t): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tafterQueryObservers: [...this.store.afterQueryObservers, observer],\n\t\t});\n\t}\n\n\tafterQuery(hook: AfterQueryHook): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tafterQuery: [...this.store.afterQuery, hook],\n\t\t});\n\t}\n\n\tbeforeMutation(hook: BeforeMutationHook): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tbeforeMutation: [...this.store.beforeMutation, hook],\n\t\t});\n\t}\n\n\tobserveAfterMutation<T extends AfterMutationObserver>(\n\t\tobserver: T & ObserverRegistration<T, AfterMutationObserver>,\n\t): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tafterMutationObservers: [...this.store.afterMutationObservers, observer],\n\t\t});\n\t}\n\n\tafterMutation(hook: AfterMutationHook): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tafterMutation: [...this.store.afterMutation, hook],\n\t\t});\n\t}\n\n\tonError(hook: OnErrorHook): HookManager {\n\t\tthis.assertNotFrozen();\n\t\treturn new HookManagerImpl({\n\t\t\t...this.store,\n\t\t\tonError: [...this.store.onError, hook],\n\t\t});\n\t}\n\n\tfreeze(): HookManager {\n\t\tif (this.store.frozen) return this;\n\t\treturn new HookManagerImpl({ ...this.store, frozen: true });\n\t}\n\n\t/** @internal Access hook store for runner */\n\tgetStore(): HookStore {\n\t\treturn this.store;\n\t}\n\n\tprivate assertNotFrozen(): void {\n\t\tif (this.store.frozen) {\n\t\t\tthrow new Error(\n\t\t\t\t'HookManager is frozen — hooks cannot be added after ORM creation. ' +\n\t\t\t\t\t'Register all hooks before passing to createOrm().',\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Hook Runner\n// ============================================================================\n\n/**\n * @internal\n * Extracts the hook store from a HookManager.\n * Used by ORM internals to access hooks for execution.\n */\nexport function getHookStore(manager: HookManager): HookStore {\n\treturn (manager as HookManagerImpl).getStore();\n}\n\n// ============================================================================\n// Re-entrancy Guard (INV-07)\n// ============================================================================\n\n/**\n * @internal\n * Tracks hook stores that are currently executing hooks.\n * Prevents infinite loops when hooks issue queries/mutations.\n */\nconst activeHookStores = new WeakSet<HookStore>();\n\n/**\n * @internal\n * Marks a hook store as actively executing hooks.\n * Returns a cleanup function to call when done.\n */\nexport function enterHookExecution(store: HookStore): () => void {\n\tactiveHookStores.add(store);\n\treturn () => activeHookStores.delete(store);\n}\n\n/**\n * @internal\n * Executes `fn` within a re-entrancy guard.\n * While `fn` runs, `hasHooks(store)` returns false — preventing infinite loops\n * when hooks issue queries/mutations themselves.\n */\nexport async function withReentrancyGuard<R>(\n\tstore: HookStore,\n\tfn: (store: HookStore) => Promise<R>,\n): Promise<R> {\n\tconst exit = enterHookExecution(store);\n\ttry {\n\t\treturn await fn(store);\n\t} finally {\n\t\texit();\n\t}\n}\n\n/**\n * @internal\n * Checks whether a hook manager has any hooks registered\n * AND is not currently in a re-entrant execution.\n * Used for zero-cost optimization: skip hook execution when no hooks exist\n * or when called from within a hook (preventing infinite loops).\n */\nexport function hasHooks(store: HookStore): boolean {\n\t// Re-entrancy guard: if this store is already executing hooks, skip\n\tif (activeHookStores.has(store)) return false;\n\n\treturn (\n\t\tstore.beforeQuery.length > 0 ||\n\t\tstore.afterQueryObservers.length > 0 ||\n\t\tstore.afterQuery.length > 0 ||\n\t\tstore.beforeMutation.length > 0 ||\n\t\tstore.afterMutationObservers.length > 0 ||\n\t\tstore.afterMutation.length > 0 ||\n\t\tstore.onError.length > 0\n\t);\n}\n\ntype SnapshotObserver<TContext> = (\n\tctx: TContext,\n\tresult: unknown,\n) => void | Promise<void>;\n\nasync function runObservers<TContext>(\n\tobservers: readonly SnapshotObserver<TContext>[],\n\tctx: TContext,\n\tresult: unknown,\n\tphase: 'afterQuery' | 'afterMutation',\n\tonObserverError?: ObserverErrorHandler,\n): Promise<void> {\n\tfor (let i = observers.length - 1; i >= 0; i--) {\n\t\tconst observer = observers[i];\n\t\tif (!observer) continue;\n\t\tconst hookName = observer.name || 'anonymous';\n\t\tconst contextSnapshot = snapshotForObserver(ctx);\n\t\tconst resultSnapshot = snapshotForObserver(result);\n\t\tif ('error' in contextSnapshot) {\n\t\t\tawait reportObserverFailure(\n\t\t\t\tnew Error('Observer skipped because its snapshot could not be cloned', {\n\t\t\t\t\tcause: contextSnapshot.error,\n\t\t\t\t}),\n\t\t\t\thookName,\n\t\t\t\tphase,\n\t\t\t\tonObserverError,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif ('error' in resultSnapshot) {\n\t\t\tawait reportObserverFailure(\n\t\t\t\tnew Error('Observer skipped because its snapshot could not be cloned', {\n\t\t\t\t\tcause: resultSnapshot.error,\n\t\t\t\t}),\n\t\t\t\thookName,\n\t\t\t\tphase,\n\t\t\t\tonObserverError,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tawait observer(\n\t\t\t\tObject.freeze(contextSnapshot.value),\n\t\t\t\tresultSnapshot.value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tawait reportObserverFailure(error, hookName, phase, onObserverError);\n\t\t}\n\t}\n}\n\n/**\n * @internal\n * Runs afterQuery observers in reverse registration order (LIFO).\n * Observer return values are intentionally ignored.\n */\nexport async function runAfterQueryObservers(\n\tobservers: readonly AfterQueryObserver[],\n\tctx: QueryHookContext,\n\tresult: unknown,\n\tonObserverError?: ObserverErrorHandler,\n): Promise<void> {\n\tif (observers.length === 0) return;\n\treturn runObservers(observers, ctx, result, 'afterQuery', onObserverError);\n}\n\n/**\n * @internal\n * Runs beforeQuery hooks in registration order (FIFO).\n * Returns the (potentially modified) context.\n * Context is frozen before each hook invocation.\n */\nexport async function runBeforeQueryHooks(\n\thooks: readonly BeforeQueryHook[],\n\tctx: QueryHookContext,\n\tonHookError?: HookErrorHandler,\n): Promise<QueryHookContext> {\n\tlet current = ctx;\n\tfor (const hook of hooks) {\n\t\tconst frozen = Object.freeze({ ...current });\n\t\ttry {\n\t\t\tconst result = await hook(frozen);\n\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\tcurrent = result;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (onHookError) {\n\t\t\t\tconst action = onHookError(\n\t\t\t\t\tnormalizeHookError(error),\n\t\t\t\t\thook.name || 'anonymous',\n\t\t\t\t\tfrozen,\n\t\t\t\t\t'beforeQuery',\n\t\t\t\t);\n\t\t\t\tif (action === 'continue') continue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * @internal\n * Runs afterMutation observers in reverse registration order (LIFO).\n * Observer return values are intentionally ignored.\n */\nexport async function runAfterMutationObservers(\n\tobservers: readonly AfterMutationObserver[],\n\tctx: MutationHookContext,\n\tresult: unknown,\n\tonObserverError?: ObserverErrorHandler,\n): Promise<void> {\n\tif (observers.length === 0) return;\n\treturn runObservers(observers, ctx, result, 'afterMutation', onObserverError);\n}\n\n/**\n * @internal\n * Runs afterQuery hooks in reverse registration order (LIFO — middleware semantics).\n * Returns the (potentially transformed) result.\n */\nexport async function runAfterQueryHooks<R>(\n\thooks: readonly AfterQueryHook[],\n\tctx: QueryHookContext,\n\tresult: R,\n\tonHookError?: HookErrorHandler,\n): Promise<R> {\n\tlet current = result;\n\t// LIFO order: last registered hook runs first\n\tfor (let i = hooks.length - 1; i >= 0; i--) {\n\t\tconst hook = hooks[i];\n\t\tif (!hook) continue;\n\t\tconst frozen = Object.freeze({ ...ctx });\n\t\ttry {\n\t\t\tconst transformed = await hook(frozen, current);\n\t\t\tif (transformed !== undefined && transformed !== null) {\n\t\t\t\tcurrent = transformed;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (onHookError) {\n\t\t\t\tconst action = onHookError(\n\t\t\t\t\tnormalizeHookError(error),\n\t\t\t\t\thook.name || 'anonymous',\n\t\t\t\t\tfrozen,\n\t\t\t\t\t'afterQuery',\n\t\t\t\t);\n\t\t\t\tif (action === 'continue') continue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * @internal\n * Runs beforeMutation hooks in registration order (FIFO).\n */\nexport async function runBeforeMutationHooks<T>(\n\thooks: readonly BeforeMutationHook[],\n\tctx: MutationHookContext<T>,\n\tonHookError?: HookErrorHandler,\n): Promise<MutationHookContext<T>> {\n\tlet current = ctx;\n\tfor (const hook of hooks) {\n\t\tconst frozen = Object.freeze({ ...current });\n\t\ttry {\n\t\t\tconst result = await hook(frozen);\n\t\t\tif (result !== undefined && result !== null) {\n\t\t\t\tcurrent = result as MutationHookContext<T>;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (onHookError) {\n\t\t\t\tconst action = onHookError(\n\t\t\t\t\tnormalizeHookError(error),\n\t\t\t\t\thook.name || 'anonymous',\n\t\t\t\t\tfrozen,\n\t\t\t\t\t'beforeMutation',\n\t\t\t\t);\n\t\t\t\tif (action === 'continue') continue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * @internal\n * Runs afterMutation hooks in reverse registration order (LIFO).\n */\nexport async function runAfterMutationHooks<T>(\n\thooks: readonly AfterMutationHook[],\n\tctx: MutationHookContext<T>,\n\tresult: T[],\n\tonHookError?: HookErrorHandler,\n): Promise<T[]> {\n\tlet current = result;\n\tfor (let i = hooks.length - 1; i >= 0; i--) {\n\t\tconst hook = hooks[i];\n\t\tif (!hook) continue;\n\t\tconst frozen = Object.freeze({ ...ctx });\n\t\ttry {\n\t\t\tconst transformed = await hook(frozen, current);\n\t\t\tif (transformed !== undefined && transformed !== null) {\n\t\t\t\tcurrent = transformed as T[];\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (onHookError) {\n\t\t\t\tconst action = onHookError(\n\t\t\t\t\tnormalizeHookError(error),\n\t\t\t\t\thook.name || 'anonymous',\n\t\t\t\t\tfrozen,\n\t\t\t\t\t'afterMutation',\n\t\t\t\t);\n\t\t\t\tif (action === 'continue') continue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * @internal\n * Runs onError hooks. Returns transformed error or original.\n */\nexport async function runOnErrorHooks(\n\thooks: readonly OnErrorHook[],\n\tctx: ErrorHookContext,\n): Promise<Error> {\n\tlet currentError = ctx.error;\n\tfor (const hook of hooks) {\n\t\tconst frozen = Object.freeze({ ...ctx, error: currentError });\n\t\ttry {\n\t\t\tconst result = await hook(frozen);\n\t\t\tif (result instanceof Error) {\n\t\t\t\tcurrentError = result;\n\t\t\t}\n\t\t} catch {\n\t\t\t// onError hooks should not throw; if they do, ignore and continue\n\t\t}\n\t}\n\treturn currentError;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\n/**\n * Creates a new HookManager instance for registering query/mutation hooks.\n *\n * @example\n * ```typescript\n * const hooks = createHookManager()\n * .beforeQuery(ctx => { console.log(ctx.table); return ctx; })\n * .afterQuery((ctx, results) => results);\n * ```\n */\nexport function createHookManager(): HookManager {\n\treturn new HookManagerImpl();\n}\n","import type { IncludeIntent } from '../intent-ast.js';\nimport type { RelationHints } from './types.js';\n\n/**\n * Apply relation hint to a single include recursively.\n */\nexport function applyHintToIncludeRecursive(\n\tinc: IncludeIntent,\n\trelationHints: RelationHints,\n): IncludeIntent {\n\t// If already has explicit via, don't override\n\tif (inc.via !== undefined) {\n\t\t// But still process nested includes\n\t\tif (inc.include && inc.include.length > 0) {\n\t\t\treturn {\n\t\t\t\t...inc,\n\t\t\t\tinclude: inc.include.map((nested) =>\n\t\t\t\t\tapplyHintToIncludeRecursive(nested, relationHints),\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\treturn inc;\n\t}\n\n\t// Check if we have a hint for this target\n\tconst hint = relationHints[inc.relation];\n\tconst result: IncludeIntent = hint ? { ...inc, via: hint } : inc;\n\n\t// Process nested includes\n\tif (result.include && result.include.length > 0) {\n\t\treturn {\n\t\t\t...result,\n\t\t\tinclude: result.include.map((nested) =>\n\t\t\t\tapplyHintToIncludeRecursive(nested, relationHints),\n\t\t\t),\n\t\t};\n\t}\n\n\treturn result;\n}\n","/**\n * @module subquery-builder\n * Subquery builder for scalar subquery expressions in WHERE clauses.\n * DX-012 Block 3\n */\n\nimport type {\n\tComparisonOperator,\n\tQueryIntent,\n\tSubqueryRefIntent,\n\tWhereIntent,\n\tWhereSubqueryIntent,\n} from '../intent-ast.js';\nimport type { ExpressionSpec } from './types.js';\n\n// ============================================================================\n// Subquery Builder\n// ============================================================================\n\n/**\n * Fluent builder for scalar subqueries.\n * Produces a SubqueryExpression that can be used with comparison operators.\n *\n * @example\n * // Basic scalar subquery\n * query('products')\n * .where({ price: { $eq: subquery('prices').select('max_price').where({ categoryId: outerRef('categoryId') }) } })\n *\n * // With aggregate\n * query('products')\n * .where({ avgRating: { $gt: subquery('reviews').where({ productId: outerRef('id') }).avg('rating') } })\n */\nexport class SubqueryBuilder {\n\tprivate readonly _from: string;\n\tprivate _select?: string;\n\tprivate _where?: WhereIntent;\n\tprivate _aggregate?: {\n\t\tfn: 'count' | 'sum' | 'avg' | 'min' | 'max';\n\t\tfield: string;\n\t};\n\n\tconstructor(table: string) {\n\t\tthis._from = table;\n\t}\n\n\t/**\n\t * Specify the field to select from the subquery.\n\t * For scalar subqueries, this should be a single field.\n\t */\n\tselect(field: string): SubqueryBuilder {\n\t\tconst clone = this.clone();\n\t\tclone._select = field;\n\t\treturn clone;\n\t}\n\n\t/**\n\t * Add a WHERE condition to the subquery.\n\t * Can include outerRef() to create correlated subqueries.\n\t */\n\twhere(condition: WhereIntent): SubqueryBuilder {\n\t\tconst clone = this.clone();\n\t\tclone._where = condition;\n\t\treturn clone;\n\t}\n\n\t// ========================================================================\n\t// Aggregate Methods\n\t// ========================================================================\n\n\t/**\n\t * COUNT aggregate - count rows in subquery\n\t */\n\tcount(field = '*'): SubqueryExpression {\n\t\tconst clone = this.clone();\n\t\tclone._aggregate = { fn: 'count', field };\n\t\treturn clone.build();\n\t}\n\n\t/**\n\t * SUM aggregate - sum values in subquery\n\t */\n\tsum(field: string): SubqueryExpression {\n\t\tconst clone = this.clone();\n\t\tclone._aggregate = { fn: 'sum', field };\n\t\treturn clone.build();\n\t}\n\n\t/**\n\t * AVG aggregate - average values in subquery\n\t */\n\tavg(field: string): SubqueryExpression {\n\t\tconst clone = this.clone();\n\t\tclone._aggregate = { fn: 'avg', field };\n\t\treturn clone.build();\n\t}\n\n\t/**\n\t * MIN aggregate - minimum value in subquery\n\t */\n\tmin(field: string): SubqueryExpression {\n\t\tconst clone = this.clone();\n\t\tclone._aggregate = { fn: 'min', field };\n\t\treturn clone.build();\n\t}\n\n\t/**\n\t * MAX aggregate - maximum value in subquery\n\t */\n\tmax(field: string): SubqueryExpression {\n\t\tconst clone = this.clone();\n\t\tclone._aggregate = { fn: 'max', field };\n\t\treturn clone.build();\n\t}\n\n\t// ========================================================================\n\t// Build Methods\n\t// ========================================================================\n\n\t/**\n\t * Build the SubqueryExpression for use in WHERE conditions.\n\t * Called automatically by aggregate methods or explicitly when using select().\n\t */\n\tbuild(): SubqueryExpression {\n\t\tif (!this._select && !this._aggregate) {\n\t\t\tthrow new Error(\n\t\t\t\t'Subquery must have either select() or an aggregate function',\n\t\t\t);\n\t\t}\n\n\t\t// Build a full QueryIntent — subqueries are queries with contextual validation\n\t\tconst selectField = this._select ?? this._aggregate?.field ?? '*';\n\n\t\tconst intent: QueryIntent = {\n\t\t\ttype: 'select',\n\t\t\tfrom: this._from,\n\t\t\t// Aggregate overrides plain field select\n\t\t\tselect: this._aggregate\n\t\t\t\t? {\n\t\t\t\t\t\ttype: 'aggregate',\n\t\t\t\t\t\taggregates: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfunction: this._aggregate.fn,\n\t\t\t\t\t\t\t\tfield: this._aggregate.field,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t}\n\t\t\t\t: { type: 'fields', fields: [selectField] },\n\t\t\t...(this._where && { where: this._where }),\n\t\t};\n\n\t\treturn new SubqueryExpression(intent);\n\t}\n\n\t/**\n\t * Get the intent for debugging/inspection.\n\t */\n\tdump(): QueryIntent {\n\t\treturn this.build().toIntent();\n\t}\n\n\t/**\n\t * Wrap this subquery as an ExpressionSpec for use as a SELECT column.\n\t * Shorthand for `.build().asExpr(alias)`.\n\t *\n\t * @param alias - Column alias for the result\n\t * @returns ExpressionSpec suitable for passing to .columns()\n\t *\n\t * @example\n\t * // SELECT id, (SELECT count(*) FROM calls WHERE symbol_id = s.id) AS call_count\n\t * query('symbols').columns([\n\t * 'id',\n\t * subquery('calls').where({ symbolId: outerRef('id') }).count().asExpr('call_count'),\n\t * ])\n\t */\n\tasExpr(alias: string): ExpressionSpec {\n\t\treturn this.build().asExpr(alias);\n\t}\n\n\t/**\n\t * Create a clone of this builder (immutable pattern).\n\t */\n\tprivate clone(): SubqueryBuilder {\n\t\tconst clone = new SubqueryBuilder(this._from);\n\t\tif (this._select !== undefined) clone._select = this._select;\n\t\tif (this._where !== undefined) clone._where = this._where;\n\t\tif (this._aggregate !== undefined) clone._aggregate = this._aggregate;\n\t\treturn clone;\n\t}\n}\n\n// ============================================================================\n// Subquery Expression\n// ============================================================================\n\n/**\n * Result of building a subquery.\n * This can be used as a value in comparison operations.\n */\nexport class SubqueryExpression {\n\treadonly _type = 'subquery' as const;\n\treadonly intent: QueryIntent;\n\n\tconstructor(intent: QueryIntent) {\n\t\tthis.intent = intent;\n\t}\n\n\t/**\n\t * Get the underlying intent.\n\t */\n\ttoIntent(): QueryIntent {\n\t\treturn this.intent;\n\t}\n\n\t/**\n\t * Create a WhereSubqueryIntent for comparison.\n\t * Used internally by object filter syntax.\n\t */\n\ttoWhereIntent(\n\t\tfield: string,\n\t\toperator: ComparisonOperator,\n\t): WhereSubqueryIntent {\n\t\treturn {\n\t\t\tkind: 'subquery',\n\t\t\tfield,\n\t\t\toperator,\n\t\t\tsubquery: this.intent,\n\t\t};\n\t}\n\n\t/**\n\t * Wrap this subquery as an ExpressionSpec for use as a SELECT column.\n\t *\n\t * @param alias - Column alias for the result (required: SELECT expressions need a name)\n\t * @returns ExpressionSpec suitable for passing to .columns()\n\t *\n\t * @example\n\t * // SELECT id, (SELECT count(*) FROM calls WHERE calls.symbol_id = s.id) AS call_count\n\t * // FROM symbols s\n\t * query('symbols').columns([\n\t * 'id',\n\t * subquery('calls').count().asExpr('call_count'),\n\t * ])\n\t */\n\tasExpr(alias: string): ExpressionSpec {\n\t\treturn {\n\t\t\t__expr: true,\n\t\t\tintent: { kind: 'subquery', query: this.intent, as: alias },\n\t\t};\n\t}\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a scalar subquery builder.\n *\n * @param table - Table name for the subquery\n * @returns SubqueryBuilder for method chaining\n *\n * @example\n * // Find products where price equals max price in category\n * query('products').where({\n * price: {\n * $eq: subquery('products')\n * .select('price')\n * .where({ categoryId: outerRef('categoryId') })\n * .max('price')\n * }\n * })\n */\nexport function subquery(table: string): SubqueryBuilder {\n\treturn new SubqueryBuilder(table);\n}\n\n/**\n * Create a reference to a parent query column.\n * Used in subquery WHERE conditions to create correlated subqueries.\n *\n * @param column - Column name (e.g., 'id') or qualified name (e.g., 't0.id')\n * @returns SubqueryRefIntent\n *\n * @example\n * // Reference parent 'id' column in subquery\n * subquery('reviews').where({ productId: outerRef('id') })\n */\nexport function outerRef(column: string): SubqueryRefIntent {\n\t// `outer: true` is the discriminator that distinguishes this genuine\n\t// outer-query reference from an inner `ref()` (RefExpressionIntent), which\n\t// has the same structural shape `{ kind: 'ref', column }`. Without the\n\t// marker, any subquery using `ref('a').gt(ref('b'))` as an inner WHERE\n\t// condition would be falsely rejected as \"correlated subquery not supported\".\n\t//\n\t// `SubqueryRefIntent` now declares `readonly outer?: true` so the object\n\t// literal is type-safe and no cast is needed.\n\treturn {\n\t\tkind: 'ref',\n\t\tcolumn,\n\t\touter: true,\n\t};\n}\n\n// ============================================================================\n// Type Guard\n// ============================================================================\n\n/**\n * Check if a value is a SubqueryExpression.\n * Used to detect subqueries in object filter processing.\n */\nexport function isSubqueryExpression(\n\tvalue: unknown,\n): value is SubqueryExpression {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'_type' in value &&\n\t\t(value as Record<string, unknown>)._type === 'subquery'\n\t);\n}\n","/**\n * @module object-filter\n * Object filter syntax for ergonomic WHERE clause building.\n *\n * Converts Prisma/Drizzle-like object syntax to WhereIntent:\n * - `{ status: 'active' }` → `eq('status', 'active')`\n * - `{ age: { $gt: 18 } }` → `gt('age', 18)`\n * - `{ status: 'active', role: 'admin' }` → `and(eq('status', 'active'), eq('role', 'admin'))`\n *\n * @example\n * ```typescript\n * import { createOrm } from '@dbsp/core';\n *\n * // Object syntax (new)\n * orm.select('users').where({ status: 'active', age: { $gte: 18 } })\n *\n * // Equivalent to (legacy)\n * orm.select('users').where(and(eq('status', 'active'), gte('age', 18)))\n * ```\n */\n\nimport type {\n\tComparisonOperator,\n\tWhereAndIntent,\n\tWhereComparisonIntent,\n\tWhereInIntent,\n\tWhereIntent,\n\tWhereLikeIntent,\n\tWhereNullIntent,\n\tWhereSubqueryIntent,\n} from '../intent-ast.js';\nimport { InvalidOperationError } from './errors.js';\nimport {\n\tisSubqueryExpression,\n\ttype SubqueryExpression,\n} from './subquery-builder.js';\n\n// ============================================================================\n// Operator Types\n// ============================================================================\n\n/**\n * Comparison operators for object filter syntax.\n * Use `$` prefix to distinguish from field names.\n * Values can be literal values or SubqueryExpression for scalar subqueries.\n */\nexport interface FilterOperators<T = unknown> {\n\t/** Equals (explicit) - value or subquery */\n\treadonly $eq?: T | SubqueryExpression;\n\t/** Not equals - value or subquery */\n\treadonly $neq?: T | SubqueryExpression;\n\t/** Greater than - value or subquery */\n\treadonly $gt?: T | SubqueryExpression;\n\t/** Greater than or equal - value or subquery */\n\treadonly $gte?: T | SubqueryExpression;\n\t/** Less than - value or subquery */\n\treadonly $lt?: T | SubqueryExpression;\n\t/** Less than or equal - value or subquery */\n\treadonly $lte?: T | SubqueryExpression;\n\t/** In array */\n\treadonly $in?: readonly T[];\n\t/** LIKE pattern matching */\n\treadonly $like?: string;\n\t/** Case-insensitive LIKE (ILIKE in PostgreSQL) */\n\treadonly $ilike?: string;\n\t/** IS NOT NULL check */\n\treadonly $notNull?: true;\n}\n\n/**\n * Filter value for a single field.\n * Can be:\n * - Direct value (equality)\n * - null (IS NULL)\n * - Operator object ({ $gt: 18 })\n */\nexport type FilterValue<T = unknown> = T | null | FilterOperators<T>;\n\n/**\n * Object filter type for WHERE clause.\n * Maps field names to filter values.\n *\n * @typeParam T - The row type for type-safe field names.\n *\n * @example\n * ```typescript\n * // Simple equality\n * const filter: WhereFilter<User> = { status: 'active' };\n *\n * // With operators\n * const filter: WhereFilter<User> = {\n * status: 'active',\n * age: { $gte: 18 },\n * email: { $like: '%@example.com' },\n * };\n * ```\n */\nexport type WhereFilter<T = Record<string, unknown>> = {\n\treadonly [K in keyof T]?: FilterValue<T[K]>;\n};\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Check if a value is a WhereIntent (not an object filter).\n */\nexport function isWhereIntent(value: unknown): value is WhereIntent {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'kind' in value &&\n\t\ttypeof (value as Record<string, unknown>).kind === 'string'\n\t);\n}\n\n/**\n * Check if a value is an operator object (has $-prefixed keys).\n */\nfunction isOperatorObject(value: unknown): value is FilterOperators {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\tconst keys = Object.keys(value);\n\treturn keys.length > 0 && keys.every((k) => k.startsWith('$'));\n}\n\n// ============================================================================\n// Conversion Functions\n// ============================================================================\n\n/**\n * Convert a single field-value pair to WhereIntent.\n */\nfunction convertFieldValue(field: string, value: FilterValue): WhereIntent {\n\t// Handle null → isNull\n\tif (value === null) {\n\t\treturn {\n\t\t\tkind: 'null',\n\t\t\tfield,\n\t\t\toperator: 'isNull',\n\t\t} satisfies WhereNullIntent;\n\t}\n\n\t// Handle operator object\n\tif (isOperatorObject(value)) {\n\t\treturn convertOperatorObject(field, value);\n\t}\n\n\t// Handle direct value → equality\n\treturn {\n\t\tkind: 'comparison',\n\t\tfield,\n\t\toperator: 'eq',\n\t\tvalue,\n\t} satisfies WhereComparisonIntent;\n}\n\n/**\n * Create a comparison intent (value or subquery).\n */\nfunction createComparisonIntent(\n\tfield: string,\n\toperator: ComparisonOperator,\n\tvalue: unknown,\n): WhereIntent {\n\tif (isSubqueryExpression(value)) {\n\t\treturn value.toWhereIntent(field, operator) satisfies WhereSubqueryIntent;\n\t}\n\treturn {\n\t\tkind: 'comparison',\n\t\tfield,\n\t\toperator,\n\t\tvalue,\n\t} satisfies WhereComparisonIntent;\n}\n\n/**\n * Convert an operator object to WhereIntent.\n */\nfunction convertOperatorObject(\n\tfield: string,\n\tops: FilterOperators,\n): WhereIntent {\n\tconst conditions: WhereIntent[] = [];\n\n\t// $eq\n\tif (Object.hasOwn(ops, '$eq') && ops.$eq !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'eq', ops.$eq));\n\t}\n\n\t// $neq\n\tif (Object.hasOwn(ops, '$neq') && ops.$neq !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'neq', ops.$neq));\n\t}\n\n\t// $gt\n\tif (Object.hasOwn(ops, '$gt') && ops.$gt !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'gt', ops.$gt));\n\t}\n\n\t// $gte\n\tif (Object.hasOwn(ops, '$gte') && ops.$gte !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'gte', ops.$gte));\n\t}\n\n\t// $lt\n\tif (Object.hasOwn(ops, '$lt') && ops.$lt !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'lt', ops.$lt));\n\t}\n\n\t// $lte\n\tif (Object.hasOwn(ops, '$lte') && ops.$lte !== undefined) {\n\t\tconditions.push(createComparisonIntent(field, 'lte', ops.$lte));\n\t}\n\n\t// $in\n\tif (Object.hasOwn(ops, '$in') && ops.$in !== undefined) {\n\t\tconditions.push({\n\t\t\tkind: 'in',\n\t\t\tfield,\n\t\t\tvalues: ops.$in,\n\t\t} satisfies WhereInIntent);\n\t}\n\n\t// $like\n\tif (Object.hasOwn(ops, '$like') && ops.$like !== undefined) {\n\t\tconditions.push({\n\t\t\tkind: 'like',\n\t\t\tfield,\n\t\t\tpattern: ops.$like,\n\t\t} satisfies WhereLikeIntent);\n\t}\n\n\t// $ilike (case-insensitive)\n\tif (Object.hasOwn(ops, '$ilike') && ops.$ilike !== undefined) {\n\t\tconditions.push({\n\t\t\tkind: 'like',\n\t\t\tfield,\n\t\t\tpattern: ops.$ilike,\n\t\t\tcaseInsensitive: true,\n\t\t} satisfies WhereLikeIntent);\n\t}\n\n\t// $notNull\n\tif (Object.hasOwn(ops, '$notNull') && ops.$notNull === true) {\n\t\tconditions.push({\n\t\t\tkind: 'null',\n\t\t\tfield,\n\t\t\toperator: 'isNotNull',\n\t\t} satisfies WhereNullIntent);\n\t}\n\n\t// Return single condition or AND\n\tif (conditions.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Invalid filter: operator object for field \"${field}\" has no recognized operators`,\n\t\t);\n\t}\n\n\tif (conditions.length === 1) {\n\t\t// Type assertion safe: length check guarantees element exists\n\t\treturn conditions[0] as WhereIntent;\n\t}\n\n\treturn { kind: 'and', conditions } satisfies WhereAndIntent;\n}\n\n// Keys that must never appear in a filter object — they target prototype slots\n// and can poison object properties on older engines. Defined at module scope\n// so the Set is allocated once, not per call.\nconst FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Convert an object filter to WhereIntent.\n *\n * @param filter - Object filter with field-value pairs\n * @returns WhereIntent for use in QueryBuilder.where()\n *\n * @example\n * ```typescript\n * // Single field\n * objectToWhereIntent({ status: 'active' })\n * // → { kind: 'comparison', field: 'status', operator: 'eq', value: 'active' }\n *\n * // Multiple fields (AND)\n * objectToWhereIntent({ status: 'active', role: 'admin' })\n * // → { kind: 'and', conditions: [...] }\n *\n * // With operators\n * objectToWhereIntent({ age: { $gte: 18, $lt: 65 } })\n * // → { kind: 'and', conditions: [gte, lt] }\n * ```\n */\nexport function objectToWhereIntent(\n\tfilter: WhereFilter<Record<string, unknown>>,\n): WhereIntent {\n\t// FIND-005: Reject prototype-poisoning keys before any processing.\n\t// Object.keys() already returns only own enumerable properties — the\n\t// hasOwn check below was redundant and has been removed.\n\tfor (const key of Object.keys(filter)) {\n\t\tif (FORBIDDEN_KEYS.has(key)) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'where',\n\t\t\t\t`Filter key not allowed: ${key}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst entries = Object.entries(filter);\n\n\tif (entries.length === 0) {\n\t\tthrow new Error('Invalid filter: empty object');\n\t}\n\n\tconst conditions: WhereIntent[] = entries.map(([field, value]) =>\n\t\tconvertFieldValue(field, value as FilterValue),\n\t);\n\n\t// Single condition → return directly\n\tif (conditions.length === 1) {\n\t\t// Type assertion safe: length check guarantees element exists\n\t\treturn conditions[0] as WhereIntent;\n\t}\n\n\t// Multiple conditions → AND\n\treturn { kind: 'and', conditions } satisfies WhereAndIntent;\n}\n","/**\n * @fileoverview Core DX layer type definitions.\n *\n * Contains shared types used across the query builder, ORM instance,\n * and other DX components: column specs, ordering, includes, hierarchy, etc.\n *\n * Split files are re-exported for backward compatibility:\n * - pagination-types.ts: Pagination and streaming types\n * - query-builder-types.ts: QueryBuilder interface\n * - orm-instance-types.ts: OrmInstance and OrmOptions\n *\n * @module types\n * @since DX-001\n */\n\nimport type {\n\tExpressionIntent,\n\tSelectIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\n\n// ============================================================================\n// Re-exports from split files (backward compatibility)\n// ============================================================================\n\nexport type {\n\tOrmInstance,\n\tOrmInstanceInternal,\n\tOrmOptions,\n\tOrmOptionsWithAdapter,\n\tOrmOptionsWithModel,\n\tSelectExpressionResult,\n} from './orm-instance-types.js';\nexport type {\n\tCursorPaginatedResult,\n\tCursorPaginateOptions,\n\tPaginatedResult,\n\tPaginateOptions,\n\tStreamOptions,\n} from './pagination-types.js';\nexport type { DumpMetaInput, QueryBuilder } from './query-builder-types.js';\n\n// ============================================================================\n// Expression & Column Types\n// ============================================================================\n\n/**\n * A wrapper around an ExpressionIntent that marks it for use in columns().\n * The __expr marker allows runtime detection of expression vs string columns.\n *\n * Create these using helper functions like coalesce() or raw().\n */\nexport interface ExpressionSpec {\n\treadonly __expr: true;\n\treadonly intent: ExpressionIntent;\n}\n\n/**\n * An ExpressionSpec that carries its alias as a phantom type parameter.\n * This allows .columns() to extend the result type with the aliased property.\n *\n * Created by relationColumn(relation, column, alias) when the alias is a\n * string literal — TypeScript captures the exact string type, enabling\n * .columns() to extend TResult with { [alias]: TValue }.\n *\n * @typeParam TAlias - The string literal type of the alias\n * @typeParam TValue - The value type (defaults to unknown)\n */\nexport interface AliasedExprColumn<TAlias extends string, TValue = unknown>\n\textends ExpressionSpec {\n\t/** @internal phantom brand — never set at runtime */\n\treadonly __alias: TAlias;\n\t/** @internal phantom brand — never set at runtime */\n\treadonly __value: TValue;\n}\n\n/**\n * A column specification - either a field name or an expression.\n *\n * @example\n * ```typescript\n * // Simple field\n * 'id'\n *\n * // Expression (via coalesce helper)\n * coalesce(['name_fr', 'name_en'], 'name')\n * ```\n */\nexport type ColumnSpec = string | ExpressionSpec;\n\n/**\n * Type guard to check if a ColumnSpec is an ExpressionSpec.\n */\nexport function isExpressionSpec(spec: ColumnSpec): spec is ExpressionSpec {\n\treturn (\n\t\ttypeof spec === 'object' &&\n\t\tspec !== null &&\n\t\t'__expr' in spec &&\n\t\tspec.__expr === true\n\t);\n}\n\n// ============================================================================\n// Aggregate Types\n// ============================================================================\n\n/**\n * Options for aggregate functions.\n */\nexport interface AggregateOptions {\n\t/**\n\t * Field to aggregate (required for SUM, AVG, MIN, MAX; optional for COUNT).\n\t */\n\treadonly field?: string;\n\t/**\n\t * Alias for the result column.\n\t */\n\treadonly as?: string;\n}\n\n// ============================================================================\n// Relation Hints\n// ============================================================================\n\n/**\n * Mapping of target table to preferred relation name.\n * Used to resolve ambiguous relations automatically.\n *\n * @example\n * ```typescript\n * const hints: RelationHints = {\n * posts: 'authoredPosts', // When including 'posts', use 'authoredPosts' relation\n * };\n * ```\n */\nexport type RelationHints = Readonly<Record<string, string>>;\n\n// ============================================================================\n// OrderBy Shorthand Types (DX-024)\n// ============================================================================\n\n/**\n * Sort direction for orderBy (re-exported from @dbsp/types).\n */\nimport type { SortDirection } from '@dbsp/types';\n\nexport type { SortDirection } from '@dbsp/types';\n\n/**\n * Where to place NULL values in sort order.\n */\nexport type NullsPosition = 'first' | 'last';\n\n/**\n * Object form for orderBy - map of field to direction.\n *\n * @example\n * ```typescript\n * { created_at: 'desc', name: 'asc' }\n * ```\n */\nexport type OrderByRecord = Readonly<Record<string, SortDirection>>;\n\n/**\n * Advanced orderBy specification with nulls handling.\n *\n * @example\n * ```typescript\n * { column: 'created_at', direction: 'desc', nulls: 'last' }\n * ```\n */\nexport interface OrderBySpec {\n\treadonly column: string;\n\treadonly direction?: SortDirection;\n\treadonly nulls?: NullsPosition;\n}\n\n/**\n * All valid orderBy input types.\n */\nexport type OrderByInput =\n\t| string // Simple: 'field'\n\t| OrderByRecord // Object: { field: 'desc' }\n\t| readonly OrderBySpec[]; // Array: [{ column, direction, nulls }]\n\n// ============================================================================\n// Include Types\n// ============================================================================\n\n/**\n * Options for the include() method on QueryBuilder.\n * Maps to IncludeIntent fields with developer-friendly naming.\n */\nexport interface IncludeOptions {\n\t/**\n\t * Explicit relation name for disambiguation.\n\t * Use when multiple relations exist between same tables.\n\t *\n\t * @example\n\t * ```typescript\n\t * // User has authoredPosts and reviewedPosts relations to Post\n\t * query('users').include('posts', { via: 'authoredPosts' })\n\t * ```\n\t */\n\treadonly via?: string;\n\n\t/**\n\t * Filter conditions on related records.\n\t */\n\treadonly where?: WhereIntent;\n\n\t/**\n\t * What columns to select from related records.\n\t */\n\treadonly select?: SelectIntent;\n\n\t/**\n\t * Nested includes for deep loading.\n\t */\n\treadonly include?: readonly NestedInclude[];\n\n\t/**\n\t * Join type for the include when using the 'join' strategy.\n\t * - 'left' (default): LEFT JOIN — all root rows returned, NULL for unmatched relations\n\t * - 'inner': INNER JOIN — only root rows WITH a matching related record are returned\n\t *\n\t * Forces the 'join' include strategy (overrides auto-selection).\n\t *\n\t * @example\n\t * include('file', { join: 'inner' })\n\t * // → INNER JOIN files ON files.id = symbols.file_id\n\t */\n\treadonly join?: 'inner' | 'left';\n}\n\n/**\n * Options for recursive include traversal on self-referential relations.\n *\n * @example\n * ```typescript\n * // Traverse ancestors (nested format)\n * query('categories').where(eq('id', 5)).include('parent', {\n * recursive: true,\n * direction: 'ancestors'\n * })\n *\n * // Traverse descendants (flat format with depth)\n * query('categories').where(eq('id', 1)).include('children', {\n * recursive: true,\n * direction: 'descendants',\n * flat: true,\n * maxDepth: 10\n * })\n * ```\n */\nexport interface RecursiveIncludeOptions extends IncludeOptions {\n\t/**\n\t * Enable recursive CTE traversal.\n\t * MUST be `true` when using recursive options.\n\t */\n\treadonly recursive: true;\n\n\t/**\n\t * Direction of traversal.\n\t * - 'ancestors': Traverse up the hierarchy (parent → grandparent → ...)\n\t * - 'descendants': Traverse down the hierarchy (children → grandchildren → ...)\n\t *\n\t * REQUIRED when `recursive: true`.\n\t */\n\treadonly direction: 'ancestors' | 'descendants';\n\n\t/**\n\t * Output format.\n\t * - false (default): Nested object structure (parent: { parent: { ... } })\n\t * - true: Flat array with depth field ([{ id: 2, depth: 1 }, { id: 1, depth: 2 }])\n\t *\n\t * When flat=true, property is renamed: parent → ancestors, children → descendants\n\t */\n\treadonly flat?: boolean;\n\n\t/**\n\t * Exclude the source node from results.\n\t * @default false\n\t */\n\treadonly omitSelf?: boolean;\n\n\t/**\n\t * Maximum traversal depth.\n\t * @default 100 (safety limit)\n\t */\n\treadonly maxDepth?: number;\n\n\t/**\n\t * Include depth column in results.\n\t * Automatically true when flat=true.\n\t */\n\treadonly includeDepth?: boolean;\n}\n\n/**\n * Union type for include options: regular or recursive.\n */\nexport type IncludeOptionsWithRecursive =\n\t| IncludeOptions\n\t| RecursiveIncludeOptions;\n\n/**\n * Include with relation name for nested includes.\n * Used when building nested include hierarchies.\n */\nexport interface NestedInclude extends IncludeOptions {\n\t/**\n\t * The relation name or target table for this nested include.\n\t */\n\treadonly relation: string;\n}\n\n// ============================================================================\n// Hierarchy Types (DX-022)\n// ============================================================================\n\n/**\n * Options for hierarchy traversal shortcuts (ancestors, descendants, subtree).\n */\nexport interface HierarchyOptions {\n\t/**\n\t * The column that references the parent node (for adjacency list pattern).\n\t * @example 'parentCategoryId', 'parentId', 'managerId'\n\t */\n\treadonly parentId: string;\n\n\t/**\n\t * The column that identifies a node (default: 'id').\n\t */\n\treadonly nodeId?: string;\n\n\t/**\n\t * Optional CTE name (default: auto-generated based on table name).\n\t */\n\treadonly cteName?: string;\n}\n\n/**\n * Options for listAncestors/listDescendants methods (DX-022).\n * These methods execute immediately and return flat arrays.\n */\nexport interface ListHierarchyOptions {\n\t/**\n\t * The column that references the parent node (for adjacency list pattern).\n\t * This is used to auto-detect the self-referential relation.\n\t * @example 'parentCategoryId', 'parentId', 'managerId'\n\t */\n\treadonly parentId: string;\n\n\t/**\n\t * The column that identifies a node (default: 'id').\n\t */\n\treadonly nodeId?: string;\n\n\t/**\n\t * Maximum depth to traverse (default: 100).\n\t */\n\treadonly maxDepth?: number;\n}\n","/**\n * IntentBuilder - Builds QueryIntent AST from builder state.\n *\n * DX-103: Extracted from QueryBuilderImpl to separate intent construction\n * from execution, hydration, and other concerns.\n *\n * @module intent-builder\n */\n\nimport type { Mutable } from '@dbsp/types/internal';\nimport type {\n\tAggregateIntent,\n\tColumnExpressionIntent,\n\tExpressionIntent,\n\tIncludeIntent,\n\tIncludeRecursiveOptions,\n\tOrderByIntent,\n\tQueryIntent,\n\tSelectAggregateIntent,\n\tSelectIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\n\nimport { InvalidOperationError } from './errors.js';\nimport { and } from './filters.js';\nimport { applyHintToIncludeRecursive } from './include-hints.js';\nimport {\n\tisWhereIntent,\n\tobjectToWhereIntent,\n\ttype WhereFilter,\n} from './object-filter.js';\nimport {\n\ttype AggregateOptions,\n\ttype ColumnSpec,\n\ttype ExpressionSpec,\n\ttype IncludeOptionsWithRecursive,\n\tisExpressionSpec,\n\ttype NestedInclude,\n\ttype OrderByRecord,\n\ttype OrderBySpec,\n\ttype RecursiveIncludeOptions,\n\ttype RelationHints,\n\ttype SortDirection,\n} from './types.js';\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if options indicate a recursive include.\n */\nexport function isRecursiveIncludeOptions(\n\toptions?: IncludeOptionsWithRecursive,\n): options is RecursiveIncludeOptions {\n\treturn (\n\t\toptions !== undefined &&\n\t\t'recursive' in options &&\n\t\toptions.recursive === true\n\t);\n}\n\n/**\n * Convert IncludeOptions to IncludeIntent.\n * Handles exactOptionalPropertyTypes by only including defined properties.\n */\nexport function includeOptionsToIntent(\n\trelation: string,\n\toptions?: IncludeOptionsWithRecursive,\n): IncludeIntent {\n\tif (!options) {\n\t\treturn { relation };\n\t}\n\n\tconst intent: Mutable<IncludeIntent> = { relation };\n\n\tif (options.via !== undefined) {\n\t\tintent.via = options.via;\n\t}\n\tif (options.where !== undefined) {\n\t\tintent.where = options.where;\n\t}\n\tif (options.select !== undefined) {\n\t\tintent.select = options.select;\n\t}\n\tif (options.include !== undefined && options.include.length > 0) {\n\t\tintent.include = options.include.map((nested) =>\n\t\t\tnestedIncludeToIntent(nested),\n\t\t);\n\t}\n\n\tif (options.join !== undefined) {\n\t\tintent.join = options.join;\n\t}\n\n\t// Handle recursive options (DX-017)\n\tif (isRecursiveIncludeOptions(options)) {\n\t\tconst recursiveOpts: Mutable<IncludeRecursiveOptions> = {};\n\t\t// Only set maxDepth if defined\n\t\tif (options.maxDepth !== undefined) {\n\t\t\trecursiveOpts.maxDepth = options.maxDepth;\n\t\t}\n\t\t// Convert includeDepth to track.depth\n\t\tif (options.includeDepth) {\n\t\t\trecursiveOpts.track = { depth: true };\n\t\t}\n\t\tintent.recursive = recursiveOpts;\n\t}\n\n\treturn intent as IncludeIntent;\n}\n\n/**\n * Convert NestedInclude to IncludeIntent.\n */\nexport function nestedIncludeToIntent(nested: NestedInclude): IncludeIntent {\n\tconst intent: Mutable<IncludeIntent> = { relation: nested.relation };\n\n\tif (nested.via !== undefined) {\n\t\tintent.via = nested.via;\n\t}\n\tif (nested.where !== undefined) {\n\t\tintent.where = nested.where;\n\t}\n\tif (nested.select !== undefined) {\n\t\tintent.select = nested.select;\n\t}\n\tif (nested.include !== undefined && nested.include.length > 0) {\n\t\tintent.include = nested.include.map((n) => nestedIncludeToIntent(n));\n\t}\n\n\treturn intent as IncludeIntent;\n}\n\n/**\n * Parse dot notation include into nested IncludeIntent.\n *\n * @example\n * 'posts.comments.author' becomes:\n * { relation: 'posts', include: [{ relation: 'comments', include: [{ relation: 'author' }] }] }\n */\nexport function parseDotNotationInclude(\n\tpath: string,\n\toptions?: IncludeOptionsWithRecursive,\n): IncludeIntent {\n\tconst parts = path.split('.');\n\tif (parts.length === 0) {\n\t\tthrow new Error('Invalid include path');\n\t}\n\n\t// Build from the end (deepest level) to the beginning\n\t// Options apply to the deepest (last) relation\n\tconst lastPart = parts[parts.length - 1];\n\tif (!lastPart) {\n\t\tthrow new Error('Invalid include path: empty segment');\n\t}\n\tlet current: IncludeIntent = includeOptionsToIntent(lastPart, options);\n\n\t// Work backwards through the path, wrapping each level.\n\t// Propagate the `join` option to intermediate wrappers so the planner\n\t// picks the join strategy for ALL hops, not just the leaf.\n\t// Without this, `.include('a.b', {join:'inner'})` produces an outer 'a'\n\t// with no join → json_agg strategy → 'a' table not in outer FROM →\n\t// the leaf 'b' JOIN ON clause references a table missing from outer FROM.\n\tfor (let i = parts.length - 2; i >= 0; i--) {\n\t\tconst part = parts[i];\n\t\tif (!part) continue;\n\t\tcurrent =\n\t\t\toptions?.join !== undefined\n\t\t\t\t? { relation: part, join: options.join, include: [current] }\n\t\t\t\t: { relation: part, include: [current] };\n\t}\n\n\treturn current;\n}\n\n/**\n * Validate recursive include options.\n * Throws InvalidOperationError if:\n * - Relation is not self-referential (source !== target)\n * - Direction is missing\n * - Direction conflicts with relation cardinality\n */\nexport function validateRecursiveInclude(\n\tmodel: ModelIR,\n\tsourceTable: string,\n\trelationName: string,\n\toptions: RecursiveIncludeOptions,\n): void {\n\t// Get the relation from the model\n\tconst qualifiedName = `${sourceTable}.${relationName}`;\n\tconst relation = model.getRelation(qualifiedName);\n\n\tif (!relation) {\n\t\t// Let the planner handle the \"relation not found\" error\n\t\treturn;\n\t}\n\n\t// Check if direction is provided (INV-2)\n\tif (!options.direction) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'recursive include',\n\t\t\t`'direction' is required when using recursive: true. ` +\n\t\t\t\t`Use 'ancestors' for parent traversal or 'descendants' for children traversal.`,\n\t\t);\n\t}\n\n\t// Check if relation is self-referential (INV-1, PRE-1)\n\tif (relation.source !== relation.target) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'recursive include',\n\t\t\t`Recursive include requires a self-referential relation. ` +\n\t\t\t\t`Relation '${relationName}' connects '${relation.source}' to '${relation.target}', ` +\n\t\t\t\t`but both must be the same table for recursive traversal.`,\n\t\t);\n\t}\n\n\t// Check direction vs relation type (PRE-2, PRE-3, ERR-3)\n\t// ancestors requires belongsTo/hasOne (to-one), descendants requires hasMany (to-many)\n\tconst { direction } = options;\n\tconst relType = relation.type;\n\n\tif (direction === 'ancestors') {\n\t\t// ancestors traversal: follow the \"parent\" direction (N:1 or 1:1)\n\t\t// The relation should be belongsTo or hasOne (e.g., category -> parent category)\n\t\tif (relType === 'hasMany' || relType === 'belongsToMany') {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'recursive include',\n\t\t\t\t`Direction 'ancestors' requires a to-one relation (belongsTo or hasOne). ` +\n\t\t\t\t\t`Relation '${relationName}' has type '${relType}'. ` +\n\t\t\t\t\t`Use 'descendants' for hasMany/belongsToMany relations.`,\n\t\t\t);\n\t\t}\n\t} else if (direction === 'descendants') {\n\t\t// descendants traversal: follow the \"children\" direction (1:N)\n\t\t// The relation should be hasMany (e.g., category -> child categories)\n\t\tif (relType === 'belongsTo' || relType === 'hasOne') {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'recursive include',\n\t\t\t\t`Direction 'descendants' requires a to-many relation (hasMany). ` +\n\t\t\t\t\t`Relation '${relationName}' has type '${relType}'. ` +\n\t\t\t\t\t`Use 'ancestors' for belongsTo/hasOne relations.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ============================================================================\n// RecursiveIncludeConfig\n// ============================================================================\n\n/**\n * Configuration for a recursive include.\n * Stores the relation name and recursive options for later processing.\n */\nexport interface RecursiveIncludeConfig {\n\treadonly relation: string;\n\treadonly options: RecursiveIncludeOptions;\n}\n\n// ============================================================================\n// IntentBuilderState\n// ============================================================================\n\n/**\n * Internal state for intent building.\n * Encapsulates all the mutable state that gets accumulated via builder methods.\n * Note: Optional properties explicitly allow undefined for exactOptionalPropertyTypes compliance.\n */\nexport interface IntentBuilderState {\n\treadonly from: string;\n\tselectIntent?: SelectIntent | undefined;\n\twhereIntents: WhereIntent[];\n\thavingIntents: WhereIntent[];\n\tincludes: IncludeIntent[];\n\trecursiveIncludes: RecursiveIncludeConfig[];\n\taggregates: AggregateIntent[];\n\tgroupByFields: string[];\n\torderByIntents: OrderByIntent[];\n\tlimitValue?: number | undefined;\n\toffsetValue?: number | undefined;\n\tisDistinct?: boolean | undefined;\n}\n\n// ============================================================================\n// IntentBuilder\n// ============================================================================\n\n/**\n * Builds QueryIntent AST from accumulated state.\n *\n * This class is responsible for:\n * - Accumulating filter, select, include, and ordering state\n * - Converting builder method calls to intent AST nodes\n * - Building the final QueryIntent for planning\n *\n * @typeParam TResult - The expected result type (for type inference)\n */\nexport class IntentBuilder<TResult = unknown> {\n\tprivate readonly model: ModelIR;\n\tprivate readonly relationHints: RelationHints;\n\treadonly state: IntentBuilderState;\n\n\tconstructor(\n\t\tmodel: ModelIR,\n\t\tfrom: string,\n\t\trelationHints: RelationHints = {},\n\t\tinitialState?: Partial<IntentBuilderState>,\n\t) {\n\t\tthis.model = model;\n\t\tthis.relationHints = relationHints;\n\t\tthis.state = {\n\t\t\tfrom,\n\t\t\twhereIntents: initialState?.whereIntents\n\t\t\t\t? [...initialState.whereIntents]\n\t\t\t\t: [],\n\t\t\thavingIntents: initialState?.havingIntents\n\t\t\t\t? [...initialState.havingIntents]\n\t\t\t\t: [],\n\t\t\tincludes: initialState?.includes ? [...initialState.includes] : [],\n\t\t\trecursiveIncludes: initialState?.recursiveIncludes\n\t\t\t\t? [...initialState.recursiveIncludes]\n\t\t\t\t: [],\n\t\t\taggregates: initialState?.aggregates ? [...initialState.aggregates] : [],\n\t\t\tgroupByFields: initialState?.groupByFields\n\t\t\t\t? [...initialState.groupByFields]\n\t\t\t\t: [],\n\t\t\torderByIntents: initialState?.orderByIntents\n\t\t\t\t? [...initialState.orderByIntents]\n\t\t\t\t: [],\n\t\t\tselectIntent: initialState?.selectIntent,\n\t\t\tlimitValue: initialState?.limitValue,\n\t\t\toffsetValue: initialState?.offsetValue,\n\t\t\tisDistinct: initialState?.isDistinct,\n\t\t};\n\t}\n\n\t/**\n\t * Add an include to the builder.\n\t */\n\taddInclude(relation: string, options?: IncludeOptionsWithRecursive): void {\n\t\t// Validate recursive includes (self-referential relations)\n\t\tif (isRecursiveIncludeOptions(options)) {\n\t\t\tvalidateRecursiveInclude(this.model, this.state.from, relation, options);\n\t\t\t// Note: recursive options are now converted to IncludeIntent.recursive\n\t\t\t// by includeOptionsToIntent, no longer stored separately\n\t\t}\n\n\t\t// Support dot notation for nested includes: 'posts.comments.author'\n\t\tif (relation.includes('.')) {\n\t\t\tthis.state.includes.push(parseDotNotationInclude(relation, options));\n\t\t} else {\n\t\t\tthis.state.includes.push(includeOptionsToIntent(relation, options));\n\t\t}\n\t}\n\n\t/**\n\t * Set column selection.\n\t */\n\tsetColumns(columns: readonly ColumnSpec[]): void {\n\t\t// Build columns array (direct ExpressionIntent format - NQL compatible)\n\t\tconst expressionColumns: ExpressionIntent[] = [];\n\t\tlet hasExpressions = false;\n\n\t\tfor (const col of columns) {\n\t\t\tif (isExpressionSpec(col)) {\n\t\t\t\thasExpressions = true;\n\t\t\t\texpressionColumns.push((col as ExpressionSpec).intent);\n\t\t\t} else {\n\t\t\t\t// Simple field → ColumnExpressionIntent (kind: 'column')\n\t\t\t\texpressionColumns.push({ kind: 'column', column: col as string });\n\t\t\t}\n\t\t}\n\n\t\t// Use SelectWithExpressionsIntent if we have any expressions\n\t\tif (hasExpressions) {\n\t\t\tthis.state.selectIntent = {\n\t\t\t\ttype: 'expressions',\n\t\t\t\tcolumns: expressionColumns,\n\t\t\t};\n\t\t} else {\n\t\t\t// Simple fields only - extract field names\n\t\t\tconst fields = expressionColumns.map(\n\t\t\t\t(c) => (c as ColumnExpressionIntent).column,\n\t\t\t);\n\t\t\tthis.state.selectIntent = { type: 'fields', fields };\n\t\t}\n\t}\n\n\t/**\n\t * Add a WHERE condition.\n\t */\n\taddWhere(condition: WhereIntent | WhereFilter<TResult>): void {\n\t\t// Convert object filter to WhereIntent if needed\n\t\tconst intent = isWhereIntent(condition)\n\t\t\t? condition\n\t\t\t: objectToWhereIntent(condition as WhereFilter<Record<string, unknown>>);\n\t\tthis.state.whereIntents.push(intent);\n\t}\n\n\t/**\n\t * Add an aggregate function.\n\t * DX-034: Now supports distinct flag for COUNT(DISTINCT field), etc.\n\t */\n\taddAggregate(\n\t\tfunc: 'count' | 'sum' | 'avg' | 'min' | 'max',\n\t\tfield?: string,\n\t\toptions?: AggregateOptions & { distinct?: boolean },\n\t): void {\n\t\tconst resolvedField = field ?? options?.field;\n\t\tconst as = options?.as;\n\t\tconst distinct = options?.distinct ? true : undefined;\n\n\t\tlet agg: AggregateIntent;\n\t\tif (func === 'count') {\n\t\t\t// count may omit field (defaults to '*')\n\t\t\tagg = {\n\t\t\t\tfunction: 'count',\n\t\t\t\t...(resolvedField !== undefined && { field: resolvedField }),\n\t\t\t\t...(as !== undefined && { as }),\n\t\t\t\t...(distinct !== undefined && { distinct }),\n\t\t\t};\n\t\t} else {\n\t\t\t// all other aggregates require field\n\t\t\tagg = {\n\t\t\t\tfunction: func,\n\t\t\t\tfield: resolvedField ?? '',\n\t\t\t\t...(as !== undefined && { as }),\n\t\t\t\t...(distinct !== undefined && { distinct }),\n\t\t\t};\n\t\t}\n\t\tthis.state.aggregates.push(agg);\n\t}\n\n\t/**\n\t * Add GROUP BY fields.\n\t */\n\taddGroupBy(fields: readonly string[]): void {\n\t\tthis.state.groupByFields.push(...fields);\n\t}\n\n\t/**\n\t * Add a HAVING condition for filtering on aggregates.\n\t * DX-034: HAVING is applied after GROUP BY.\n\t */\n\taddHaving(condition: WhereIntent): void {\n\t\tthis.state.havingIntents.push(condition);\n\t}\n\n\t/**\n\t * Set SELECT DISTINCT mode.\n\t * DX-034: Deduplicates result rows.\n\t */\n\tsetDistinct(value: boolean = true): void {\n\t\tthis.state.isDistinct = value;\n\t}\n\n\t/**\n\t * Add ORDER BY clauses.\n\t */\n\taddOrderBy(\n\t\tfieldOrRecordOrSpecs: string | OrderByRecord | readonly OrderBySpec[],\n\t\tdirection?: SortDirection,\n\t): void {\n\t\t// String form: orderBy('field') or orderBy('field', 'desc')\n\t\tif (typeof fieldOrRecordOrSpecs === 'string') {\n\t\t\tthis.state.orderByIntents.push({\n\t\t\t\tfield: fieldOrRecordOrSpecs,\n\t\t\t\tdirection: direction ?? 'asc',\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Array form: orderBy([{ column, direction, nulls }])\n\t\tif (Array.isArray(fieldOrRecordOrSpecs)) {\n\t\t\tfor (const spec of fieldOrRecordOrSpecs) {\n\t\t\t\tthis.state.orderByIntents.push({\n\t\t\t\t\tfield: spec.column,\n\t\t\t\t\tdirection: spec.direction ?? 'asc',\n\t\t\t\t\tnulls: spec.nulls,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Object form: orderBy({ field1: 'desc', field2: 'asc' })\n\t\tfor (const [field, dir] of Object.entries(fieldOrRecordOrSpecs)) {\n\t\t\tthis.state.orderByIntents.push({\n\t\t\t\tfield,\n\t\t\t\tdirection: dir,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Set LIMIT value.\n\t */\n\tsetLimit(count: number): void {\n\t\tthis.state.limitValue = count;\n\t}\n\n\t/**\n\t * Set OFFSET value.\n\t */\n\tsetOffset(count: number): void {\n\t\tthis.state.offsetValue = count;\n\t}\n\n\t/**\n\t * Build the QueryIntent from accumulated state.\n\t * Handles exactOptionalPropertyTypes by only including defined properties.\n\t */\n\tbuildIntent(): QueryIntent {\n\t\tconst intent: Mutable<QueryIntent> = {\n\t\t\ttype: 'select',\n\t\t\tfrom: this.state.from,\n\t\t};\n\n\t\t// Handle aggregates - convert to SelectAggregateIntent\n\t\tif (this.state.aggregates.length > 0) {\n\t\t\tconst aggregateSelect: Mutable<SelectAggregateIntent> = {\n\t\t\t\ttype: 'aggregate',\n\t\t\t\taggregates: [...this.state.aggregates],\n\t\t\t};\n\t\t\t// Add group by fields to the select for projection\n\t\t\tif (this.state.groupByFields.length > 0) {\n\t\t\t\taggregateSelect.fields = [...this.state.groupByFields];\n\t\t\t}\n\t\t\tintent.select = aggregateSelect as SelectAggregateIntent;\n\t\t} else if (this.state.selectIntent !== undefined) {\n\t\t\tintent.select = this.state.selectIntent;\n\t\t}\n\n\t\t// Combine multiple where conditions with AND\n\t\tif (this.state.whereIntents.length === 1) {\n\t\t\tconst singleWhere = this.state.whereIntents[0];\n\t\t\tif (singleWhere !== undefined) {\n\t\t\t\tintent.where = singleWhere;\n\t\t\t}\n\t\t} else if (this.state.whereIntents.length > 1) {\n\t\t\tintent.where = and(...this.state.whereIntents);\n\t\t}\n\n\t\tif (this.state.includes.length > 0) {\n\t\t\tintent.include = this.state.includes;\n\t\t}\n\n\t\tif (this.state.groupByFields.length > 0) {\n\t\t\tintent.groupBy = [...this.state.groupByFields];\n\t\t}\n\n\t\t// DX-034: HAVING clause for filtering on aggregates\n\t\tif (this.state.havingIntents.length === 1) {\n\t\t\tconst singleHaving = this.state.havingIntents[0];\n\t\t\tif (singleHaving !== undefined) {\n\t\t\t\tintent.having = singleHaving;\n\t\t\t}\n\t\t} else if (this.state.havingIntents.length > 1) {\n\t\t\tintent.having = and(...this.state.havingIntents);\n\t\t}\n\n\t\t// DX-034: SELECT DISTINCT\n\t\tif (this.state.isDistinct) {\n\t\t\tintent.distinct = true;\n\t\t}\n\n\t\tif (this.state.orderByIntents.length > 0) {\n\t\t\tintent.orderBy = [...this.state.orderByIntents];\n\t\t}\n\n\t\tif (this.state.limitValue !== undefined) {\n\t\t\tintent.limit = this.state.limitValue;\n\t\t}\n\n\t\tif (this.state.offsetValue !== undefined) {\n\t\t\tintent.offset = this.state.offsetValue;\n\t\t}\n\n\t\treturn intent as QueryIntent;\n\t}\n\n\t/**\n\t * Apply relation hints to includes that don't have explicit `via`.\n\t */\n\tapplyRelationHints(intent: QueryIntent): QueryIntent {\n\t\tif (!intent.include || Object.keys(this.relationHints).length === 0) {\n\t\t\treturn intent;\n\t\t}\n\n\t\tconst updatedIncludes = intent.include.map((inc) =>\n\t\t\tapplyHintToIncludeRecursive(inc, this.relationHints),\n\t\t);\n\n\t\treturn {\n\t\t\t...intent,\n\t\t\tinclude: updatedIncludes,\n\t\t};\n\t}\n\n\t/**\n\t * Clone the current state for immutable builder pattern.\n\t */\n\tclone(): IntentBuilder<TResult> {\n\t\treturn new IntentBuilder<TResult>(\n\t\t\tthis.model,\n\t\t\tthis.state.from,\n\t\t\t{ ...this.relationHints },\n\t\t\t{\n\t\t\t\tselectIntent: this.state.selectIntent,\n\t\t\t\twhereIntents: [...this.state.whereIntents],\n\t\t\t\thavingIntents: [...this.state.havingIntents],\n\t\t\t\tincludes: [...this.state.includes],\n\t\t\t\trecursiveIncludes: [...this.state.recursiveIncludes],\n\t\t\t\taggregates: [...this.state.aggregates],\n\t\t\t\tgroupByFields: [...this.state.groupByFields],\n\t\t\t\torderByIntents: [...this.state.orderByIntents],\n\t\t\t\tlimitValue: this.state.limitValue,\n\t\t\t\toffsetValue: this.state.offsetValue,\n\t\t\t\tisDistinct: this.state.isDistinct,\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * DX-023: Lightweight ModelIR Definition\n *\n * Provides a simplified API for defining relations from a database row map type.\n * Instead of verbose column definitions, developers can focus solely on relations\n * using shorthand syntax with automatic FK inference.\n *\n * @example\n * ```typescript\n * import { defineModel } from '@dbsp/core';\n *\n * interface Database {\n * users: { id: number; name: string; };\n * posts: { id: number; user_id: number; title: string; };\n * }\n *\n * const model = defineModel<Database>({\n * relations: {\n * 'users.posts': '1:N',\n * 'posts.author': ['N:1', 'users'],\n * },\n * });\n * ```\n */\n\nimport { singularize } from '../conventions.js';\nimport type {\n\tCardinality as ModelCardinality,\n\tModelIR,\n\tOptionality,\n\tRelationIR,\n\tRelationType,\n\tTableIR,\n} from '../index.js';\n\n// Re-export for backwards compatibility\nexport { singularize };\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Cardinality shorthand notation.\n *\n * | Shorthand | Relation Type | Source Side | Target Side |\n * |-----------|---------------|-------------|-------------|\n * | `'1:N'` | hasMany | one | many |\n * | `'N:1'` | belongsTo | many | one |\n * | `'1:1'` | hasOne | one | one |\n * | `'M:N'` | belongsToMany | many | many |\n */\nexport type CardinalityShorthand = '1:N' | 'N:1' | '1:1' | 'M:N';\n\n/**\n * Object form for relation definition with full control.\n */\nexport interface RelationObjectDef {\n\t/** Cardinality shorthand */\n\treadonly cardinality: CardinalityShorthand;\n\t/** Explicit foreign key column(s) */\n\treadonly fk?: string | readonly string[];\n\t/** Explicit target table (if different from inferred) */\n\treadonly target?: string;\n\t/** Junction table for M:N relations */\n\treadonly through?: string;\n}\n\n/**\n * Tuple form for relation definition: [cardinality, target]\n */\nexport type RelationTupleDef = readonly [CardinalityShorthand, string];\n\n/**\n * All supported forms for relation definition.\n *\n * - **Simple:** `'1:N'` - target inferred from relation name\n * - **Tuple:** `['N:1', 'users']` - explicit target\n * - **Object:** `{ cardinality: '1:N', fk: 'order_uuid' }` - full control\n */\nexport type RelationShorthand =\n\t| CardinalityShorthand\n\t| RelationTupleDef\n\t| RelationObjectDef;\n\n/**\n * Relation key format: `'sourceTable.relationName'`\n */\nexport type RelationKey<DB> =\n\tDB extends Record<string, unknown>\n\t\t? `${Extract<keyof DB, string>}.${string}`\n\t\t: string;\n\n/**\n * Lightweight relations definition with type-safe keys.\n */\nexport type LightweightRelationsDef<DB> = {\n\treadonly [K in RelationKey<DB>]?: RelationShorthand;\n};\n\n/**\n * Options for defineModel function.\n */\nexport interface DefineModelOptions<DB> {\n\t/** Relation definitions using shorthand syntax */\n\treadonly relations: LightweightRelationsDef<DB>;\n}\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Error thrown when a relation definition is invalid.\n *\n * @example\n * ```typescript\n * defineModel<DB>({ relations: { 'users.posts': '2:N' } });\n * // Throws: InvalidRelationDefinitionError: Invalid cardinality '2:N'\n * ```\n */\nexport class InvalidRelationDefinitionError extends Error {\n\toverride readonly name = 'InvalidRelationDefinitionError' as const;\n\n\t/** The relation key that caused the error */\n\treadonly relationKey: string;\n\n\t/** Specific reason for the error */\n\treadonly reason: string;\n\n\t/** Suggested fix, if available */\n\treadonly suggestion?: string;\n\n\tconstructor(opts: {\n\t\trelationKey: string;\n\t\treason: string;\n\t\tsuggestion?: string;\n\t}) {\n\t\tlet message = `Invalid relation definition for '${opts.relationKey}': ${opts.reason}`;\n\t\tif (opts.suggestion) {\n\t\t\tmessage += `\\n\\nSuggestion: ${opts.suggestion}`;\n\t\t}\n\n\t\tsuper(message);\n\t\tthis.relationKey = opts.relationKey;\n\t\tthis.reason = opts.reason;\n\t\tif (opts.suggestion) {\n\t\t\tthis.suggestion = opts.suggestion;\n\t\t}\n\n\t\tObject.setPrototypeOf(this, InvalidRelationDefinitionError.prototype);\n\t}\n}\n\n// ============================================================================\n// Parsing\n// ============================================================================\n\n/**\n * Valid cardinality values.\n */\nconst VALID_CARDINALITIES = new Set<string>(['1:N', 'N:1', '1:1', 'M:N']);\n\n/**\n * Maps cardinality shorthand to relation type.\n */\nconst CARDINALITY_TO_TYPE: Record<CardinalityShorthand, RelationType> = {\n\t'1:N': 'hasMany',\n\t'N:1': 'belongsTo',\n\t'1:1': 'hasOne',\n\t'M:N': 'belongsToMany',\n};\n\n/**\n * Maps cardinality shorthand to ModelIR cardinality.\n * ModelIR uses 'one' or 'many' to describe the target side cardinality.\n */\nconst CARDINALITY_TO_MODEL: Record<CardinalityShorthand, ModelCardinality> = {\n\t'1:N': 'many', // Target side is many\n\t'N:1': 'one', // Target side is one\n\t'1:1': 'one', // Target side is one\n\t'M:N': 'many', // Target side is many\n};\n\n/**\n * Type guard for CardinalityShorthand.\n */\nexport function isCardinalityShorthand(\n\tvalue: unknown,\n): value is CardinalityShorthand {\n\treturn typeof value === 'string' && VALID_CARDINALITIES.has(value);\n}\n\n/**\n * Type guard for RelationTupleDef.\n */\nexport function isRelationTupleDef(value: unknown): value is RelationTupleDef {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length === 2 &&\n\t\tisCardinalityShorthand(value[0]) &&\n\t\ttypeof value[1] === 'string'\n\t);\n}\n\n/**\n * Type guard for RelationObjectDef.\n */\nexport function isRelationObjectDef(\n\tvalue: unknown,\n): value is RelationObjectDef {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\treturn false;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\treturn isCardinalityShorthand(obj.cardinality);\n}\n\n/**\n * Parsed relation key information.\n */\nexport interface ParsedRelationKey {\n\treadonly sourceTable: string;\n\treadonly relationName: string;\n}\n\n/**\n * Parses a relation key into source table and relation name.\n *\n * @param key - The relation key in format 'sourceTable.relationName'\n * @returns Parsed key components\n * @throws InvalidRelationDefinitionError if key format is invalid\n */\nexport function parseRelationKey(key: string): ParsedRelationKey {\n\tconst dotIndex = key.indexOf('.');\n\tif (dotIndex === -1 || dotIndex === 0 || dotIndex === key.length - 1) {\n\t\tthrow new InvalidRelationDefinitionError({\n\t\t\trelationKey: key,\n\t\t\treason: \"Invalid key format. Expected 'sourceTable.relationName'\",\n\t\t\tsuggestion: \"Use format like 'users.posts' or 'posts.author'\",\n\t\t});\n\t}\n\n\treturn {\n\t\tsourceTable: key.slice(0, dotIndex),\n\t\trelationName: key.slice(dotIndex + 1),\n\t};\n}\n\n/**\n * Parsed relation definition.\n */\nexport interface ParsedRelationDef {\n\treadonly cardinality: CardinalityShorthand;\n\treadonly relationType: RelationType;\n\treadonly modelCardinality: ModelCardinality;\n\treadonly target: string | undefined;\n\treadonly fk: string | readonly string[] | undefined;\n\treadonly through: string | undefined;\n}\n\n/**\n * Parses a relation shorthand value into its components.\n *\n * @param key - The relation key for error messages\n * @param value - The relation shorthand value\n * @returns Parsed relation definition\n * @throws InvalidRelationDefinitionError if value is invalid\n */\nexport function parseRelationDef(\n\tkey: string,\n\tvalue: RelationShorthand,\n): ParsedRelationDef {\n\t// Form 1: Simple shorthand - '1:N'\n\tif (isCardinalityShorthand(value)) {\n\t\treturn {\n\t\t\tcardinality: value,\n\t\t\trelationType: CARDINALITY_TO_TYPE[value],\n\t\t\tmodelCardinality: CARDINALITY_TO_MODEL[value],\n\t\t\ttarget: undefined,\n\t\t\tfk: undefined,\n\t\t\tthrough: undefined,\n\t\t};\n\t}\n\n\t// Form 2: Tuple - ['N:1', 'users']\n\tif (isRelationTupleDef(value)) {\n\t\tconst [cardinality, target] = value;\n\t\treturn {\n\t\t\tcardinality,\n\t\t\trelationType: CARDINALITY_TO_TYPE[cardinality],\n\t\t\tmodelCardinality: CARDINALITY_TO_MODEL[cardinality],\n\t\t\ttarget,\n\t\t\tfk: undefined,\n\t\t\tthrough: undefined,\n\t\t};\n\t}\n\n\t// Form 3: Object - { cardinality: '1:N', fk: 'order_uuid' }\n\tif (isRelationObjectDef(value)) {\n\t\tconst { cardinality, fk, target, through } = value;\n\t\treturn {\n\t\t\tcardinality,\n\t\t\trelationType: CARDINALITY_TO_TYPE[cardinality],\n\t\t\tmodelCardinality: CARDINALITY_TO_MODEL[cardinality],\n\t\t\ttarget,\n\t\t\tfk,\n\t\t\tthrough,\n\t\t};\n\t}\n\n\t// Invalid format\n\tconst valueStr =\n\t\ttypeof value === 'object' ? JSON.stringify(value) : String(value);\n\tthrow new InvalidRelationDefinitionError({\n\t\trelationKey: key,\n\t\treason: `Invalid relation definition format: ${valueStr}`,\n\t\tsuggestion:\n\t\t\t\"Use one of: '1:N', ['N:1', 'targetTable'], or { cardinality: '1:N', fk: 'column' }\",\n\t});\n}\n\n// ============================================================================\n// FK Inference\n// ============================================================================\n\n/**\n * Infers the foreign key column name based on convention.\n *\n * Convention: `{singular_table_name}_id`\n *\n * For hasMany/hasOne (1:N, 1:1): FK is on target table, named after source\n * For belongsTo (N:1): FK is on source table, named after target\n * For belongsToMany (M:N): FKs are on junction table\n *\n * @param tableName - The table name to base the FK on\n * @returns Inferred FK column name\n */\nexport function inferForeignKey(tableName: string): string {\n\tconst singular = singularize(tableName);\n\t// Convert to snake_case if needed (handle camelCase table names)\n\tconst snakeCase = singular.replace(/([A-Z])/g, '_$1').toLowerCase();\n\t// Remove leading underscore if present\n\tconst cleanSnakeCase = snakeCase.startsWith('_')\n\t\t? snakeCase.slice(1)\n\t\t: snakeCase;\n\treturn `${cleanSnakeCase}_id`;\n}\n\n// ============================================================================\n// ModelIR Builder\n// ============================================================================\n\n/**\n * Builds a ModelIR from lightweight relation definitions.\n *\n * @param options - The defineModel options\n * @returns A ModelIR instance\n */\nexport function defineModel<DB = Record<string, unknown>>(\n\toptions: DefineModelOptions<DB>,\n): ModelIR {\n\tconst { relations } = options;\n\n\t// Collect all tables from relation keys\n\tconst tableNames = new Set<string>();\n\tconst relationEntries: Array<{\n\t\tkey: string;\n\t\tparsed: ParsedRelationKey;\n\t\tdef: ParsedRelationDef;\n\t}> = [];\n\n\t// First pass: parse all relation definitions and collect table names\n\tfor (const [key, value] of Object.entries(relations)) {\n\t\tif (value === undefined) continue;\n\n\t\tconst parsed = parseRelationKey(key);\n\t\tconst def = parseRelationDef(key, value as RelationShorthand);\n\n\t\ttableNames.add(parsed.sourceTable);\n\n\t\t// Determine target table\n\t\tlet target = def.target;\n\t\tif (target === undefined) {\n\t\t\t// Infer target from relation name\n\t\t\ttarget = parsed.relationName;\n\t\t}\n\t\ttableNames.add(target);\n\n\t\t// Validate M:N has through\n\t\tif (def.cardinality === 'M:N' && def.through === undefined) {\n\t\t\tthrow new InvalidRelationDefinitionError({\n\t\t\t\trelationKey: key,\n\t\t\t\treason:\n\t\t\t\t\t\"M:N relations require a 'through' option specifying the junction table\",\n\t\t\t\tsuggestion: `Use { cardinality: 'M:N', through: 'junction_table' }`,\n\t\t\t});\n\t\t}\n\n\t\t// Add junction table if M:N\n\t\tif (def.through !== undefined) {\n\t\t\ttableNames.add(def.through);\n\t\t}\n\n\t\trelationEntries.push({ key, parsed, def });\n\t}\n\n\t// Build tables map (minimal: just table name, no columns)\n\t// We infer that each table has an 'id' primary key by convention\n\tconst tables = new Map<string, TableIR>();\n\tfor (const name of tableNames) {\n\t\ttables.set(name, {\n\t\t\tname,\n\t\t\tcolumns: [],\n\t\t\tprimaryKey: 'id',\n\t\t\tforeignKeys: [],\n\t\t\tindexes: [],\n\t\t});\n\t}\n\n\t// Build relations map\n\tconst relationsMap = new Map<string, RelationIR>();\n\n\tfor (const { key, parsed, def } of relationEntries) {\n\t\t// Determine target\n\t\tconst target = def.target ?? parsed.relationName;\n\n\t\t// Determine FK\n\t\tlet foreignKey = def.fk;\n\t\tif (foreignKey === undefined) {\n\t\t\t// Infer FK based on relation type\n\t\t\tif (def.relationType === 'belongsTo') {\n\t\t\t\t// FK is on source table, named after target\n\t\t\t\tforeignKey = inferForeignKey(target);\n\t\t\t} else if (\n\t\t\t\tdef.relationType === 'hasMany' ||\n\t\t\t\tdef.relationType === 'hasOne'\n\t\t\t) {\n\t\t\t\t// FK is on target table, named after source\n\t\t\t\tforeignKey = inferForeignKey(parsed.sourceTable);\n\t\t\t}\n\t\t\t// For belongsToMany, FKs are typically inferred from the junction table\n\t\t\t// and would need explicit definition\n\t\t}\n\n\t\t// Determine optionality (default to optional for now)\n\t\tconst optionality: Optionality =\n\t\t\tdef.relationType === 'belongsTo' ? 'optional' : 'required';\n\n\t\tconst qualifiedName = key;\n\t\tconst relation: RelationIR = {\n\t\t\tname: parsed.relationName,\n\t\t\ttype: def.relationType,\n\t\t\tsource: parsed.sourceTable,\n\t\t\ttarget,\n\t\t\tthrough: def.through,\n\t\t\tforeignKey: foreignKey,\n\t\t\tcardinality: def.modelCardinality,\n\t\t\toptionality,\n\t\t\tincludeStrategy: 'auto',\n\t\t\tfilterStrategy: 'auto',\n\t\t\tjoinDefault: 'auto',\n\t\t};\n\n\t\trelationsMap.set(qualifiedName, relation);\n\t}\n\n\t// Create ModelIR implementation\n\treturn new LightweightModelIR(tables, relationsMap);\n}\n\n/**\n * Lightweight ModelIR implementation.\n */\nclass LightweightModelIR implements ModelIR {\n\treadonly tables: ReadonlyMap<string, TableIR>;\n\treadonly relations: ReadonlyMap<string, RelationIR>;\n\n\tconstructor(\n\t\ttables: ReadonlyMap<string, TableIR>,\n\t\trelations: ReadonlyMap<string, RelationIR>,\n\t) {\n\t\tthis.tables = tables;\n\t\tthis.relations = relations;\n\t}\n\n\tgetTable(name: string): TableIR | undefined {\n\t\treturn this.tables.get(name);\n\t}\n\n\tgetRelation(qualifiedName: string): RelationIR | undefined {\n\t\treturn this.relations.get(qualifiedName);\n\t}\n\n\tgetRelationsFrom(sourceTable: string): readonly RelationIR[] {\n\t\tconst result: RelationIR[] = [];\n\t\tfor (const [key, relation] of this.relations) {\n\t\t\tif (key.startsWith(`${sourceTable}.`)) {\n\t\t\t\tresult.push(relation);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetRelationsTo(targetTable: string): readonly RelationIR[] {\n\t\tconst result: RelationIR[] = [];\n\t\tfor (const relation of this.relations.values()) {\n\t\t\tif (relation.target === targetTable) {\n\t\t\t\tresult.push(relation);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tisAmbiguous(\n\t\tsourceTable: string,\n\t\ttargetTable: string,\n\t): { ambiguous: boolean; options: readonly string[] } {\n\t\tconst relationsToTarget: string[] = [];\n\t\tfor (const [key, relation] of this.relations) {\n\t\t\tif (\n\t\t\t\tkey.startsWith(`${sourceTable}.`) &&\n\t\t\t\trelation.target === targetTable\n\t\t\t) {\n\t\t\t\trelationsToTarget.push(relation.name);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tambiguous: relationsToTarget.length > 1,\n\t\t\toptions: relationsToTarget,\n\t\t};\n\t}\n}\n","/**\n * @module mutation-builders\n * Mutation builders for insert, update, and delete operations.\n * Part of DX-010: Mutations.\n */\n\nimport {\n\ttype Adapter,\n\ttype CompiledQuery,\n\ttype CompileOptions,\n\ttype DumpMeta,\n\ttype DumpSequenceStep,\n\texecuteCompiledQuery,\n\texecuteCompiledQueryWithMeta,\n} from '../adapter.js';\nimport type {\n\tBatchUpdateIntent,\n\tDeleteIntent,\n\tInsertIntent,\n\tMutationIntent,\n\tUpdateIntent,\n\tUpsertConflictAction,\n\tUpsertConflictTarget,\n\tUpsertIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\nimport {\n\tExecutionError,\n\tInvalidOperationError,\n\tUnsafeOperationError,\n} from './errors.js';\nimport {\n\thasPredicateRefDiscriminator,\n\tisPredicateRef,\n\ttype PredicateRef,\n\tpredicateWhereIntent,\n} from './expressions.js';\nimport type { SqlRawExpression } from './filters.js';\nimport type {\n\tHookErrorHandler,\n\tHookStore,\n\tMutationHookContext,\n\tMutationOperation,\n\tObserverErrorHandler,\n} from './hooks.js';\nimport {\n\thasHooks,\n\tnormalizeHookError,\n\trunAfterMutationHooks,\n\trunAfterMutationObservers,\n\trunBeforeMutationHooks,\n\trunOnErrorHooks,\n\twithReentrancyGuard,\n} from './hooks.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A row shape accepted by INSERT and UPSERT values().\n *\n * The public ORM type carries row types, but not the per-column default or\n * serial metadata needed to make only generated columns optional. Until that\n * schema metadata is threaded through the mutation builders (#449), every row\n * column is optional here. Keys and value types remain constrained to the row\n * type; the database enforces required columns.\n */\nexport type Insertable<T> = T extends object\n\t? Partial<T>\n\t: Record<string, unknown>;\n\n/** A partial row shape accepted by UPDATE and UPSERT update operations. */\nexport type Updateable<T> = T extends object\n\t? { [K in keyof T]?: T[K] | SqlRawExpression }\n\t: Record<string, unknown>;\n\n/** A scalar-only partial row shape accepted by batchSet(). */\ntype BatchUpdateable<T> = T extends object\n\t? Partial<T>\n\t: Record<string, unknown>;\n\n/**\n * Reject keys outside a mutation payload's row shape, including when callers\n * pass an object through a variable rather than an object literal.\n */\ntype ExactMutationPayload<TInput, TShape> = TInput &\n\tRecord<Exclude<keyof TInput, keyof TShape>, never>;\n\ntype ExactMutationRows<TInput extends readonly unknown[], TShape> = TInput & {\n\treadonly [K in keyof TInput]: ExactMutationPayload<TInput[K], TShape>;\n};\n\n/**\n * Column names accepted by a mutation on a row shape.\n *\n * The tuple prevents conditional-type distribution: a mutation whose table is\n * a union may only name columns shared by every possible target table.\n */\ntype MutationKey<T> = [T] extends [object] ? Extract<keyof T, string> : string;\n\ntype MutationReturningRow<T, K extends MutationKey<T>> = T extends object\n\t? Pick<T, Extract<K, keyof T>>\n\t: Record<string, unknown>;\n\ntype MutationWhereCondition = WhereIntent | PredicateRef;\n\nfunction toWhereIntent(condition: MutationWhereCondition): WhereIntent {\n\tif (isPredicateRef(condition)) return predicateWhereIntent(condition);\n\tif (hasPredicateRefDiscriminator(condition)) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'where',\n\t\t\t\"predicate belongs to another @dbsp/core copy; reconstruct it with this copy's predicate factories\",\n\t\t);\n\t}\n\treturn condition;\n}\n\nfunction assertNonEmptyMutationRows(\n\toperation: 'insert' | 'upsert',\n\tvalues: readonly unknown[],\n): asserts values is readonly Record<string, unknown>[] {\n\tfor (const value of values) {\n\t\tif (value === null || typeof value !== 'object' || Array.isArray(value)) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\toperation,\n\t\t\t\t`${operation} values() requires every row to be a non-null, non-array object`,\n\t\t\t);\n\t\t}\n\t\tif (Object.keys(value).length === 0) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\toperation,\n\t\t\t\t`${operation} values() requires every row to contain at least one column`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction assertMutationPayloadColumns(\n\toperation: 'insert' | 'update' | 'upsert',\n\tmodel: ModelIR,\n\ttable: string,\n\tpayload: Record<string, unknown>,\n): void {\n\tconst tableIR = model.getTable(table);\n\t// Mutation compilation renders the payload columns when no model table is\n\t// available. Match that lookup boundary here: only validate when ModelIR\n\t// resolved the target table, otherwise leave enforcement to the database.\n\tif (!tableIR) return;\n\tconst allowedColumns = new Set(tableIR.columns.map((column) => column.name));\n\tconst offendingKeys = Object.keys(payload).filter(\n\t\t(key) => !allowedColumns.has(key),\n\t);\n\tif (offendingKeys.length > 0) {\n\t\tthrow new InvalidOperationError(\n\t\t\toperation,\n\t\t\t`${operation} payload contains columns not present in model for table '${table}': ${offendingKeys.join(', ')}`,\n\t\t);\n\t}\n}\n\nfunction assertMutationObjectPayload(\n\toperation: 'update' | 'upsert',\n\tpayload: unknown,\n): asserts payload is Record<string, unknown> {\n\tif (\n\t\tpayload === null ||\n\t\ttypeof payload !== 'object' ||\n\t\tArray.isArray(payload)\n\t) {\n\t\tthrow new InvalidOperationError(\n\t\t\toperation,\n\t\t\t`${operation} payload must be a non-null, non-array object`,\n\t\t);\n\t}\n}\n\n/**\n * Dump output for mutations.\n * Similar to query Dump but without plan (mutations don't use the planner).\n */\nexport interface MutationDump {\n\t/** Compiled SQL string */\n\treadonly sql: string;\n\t/** Bound parameter values */\n\treadonly parameters: readonly unknown[];\n\t/** The mutation intent */\n\treadonly intent: MutationIntent;\n\t/** Optional metadata */\n\treadonly meta?: DumpMeta;\n\t/** Compile-only statement sequence for multi-statement NQL programs. */\n\treadonly sequence?: readonly DumpSequenceStep[];\n}\n\n/**\n * Compile a mutation intent through the adapter's mutation-specific compiler.\n *\n * Shared by the fluent mutation builders and NQL tag mutation support so the\n * intent-type dispatch stays in one place.\n */\nexport function compileMutationIntent(\n\tadapter: Adapter,\n\tintent: MutationIntent,\n\toptions?: CompileOptions,\n): CompiledQuery {\n\tswitch (intent.type) {\n\t\tcase 'insert':\n\t\t\treturn adapter.compileInsert(intent, options);\n\t\tcase 'insert_from':\n\t\t\treturn adapter.compileInsertFrom(intent, options);\n\t\tcase 'update':\n\t\t\treturn adapter.compileUpdate(intent, options);\n\t\tcase 'batchUpdate':\n\t\t\treturn adapter.compileBatchUpdate(intent, options);\n\t\tcase 'delete':\n\t\t\treturn adapter.compileDelete(intent, options);\n\t\tcase 'upsert':\n\t\t\treturn adapter.compileUpsert(intent, options);\n\t\tcase 'upsert_from':\n\t\t\treturn adapter.compileUpsertFrom(intent, options);\n\t}\n\tconst _exhaustive: never = intent;\n\tthrow new Error(\n\t\t`Unsupported mutation type: ${(_exhaustive as { type: string }).type}`,\n\t);\n}\n\n/** Shared base options for all mutation builders */\ntype MutationBaseOpts = {\n\ttable: string;\n\tmodel: ModelIR;\n\tadapter?: Adapter | undefined;\n\tschemaName?: string | undefined;\n\thookStore?: HookStore | undefined;\n\tonHookError?: HookErrorHandler | undefined;\n\tonObserverError?: ObserverErrorHandler | undefined;\n\tinTransaction?: boolean | undefined;\n};\n\nexport type PreparedMutationExecution<T> = {\n\treadonly sql: string;\n\treadonly parameters: readonly unknown[];\n\treadonly execute: () => Promise<PreparedMutationExecutionResult<T>>;\n\treadonly getAfterMutationResult?: (result: T) => readonly unknown[];\n\treadonly mapAfterMutationResult?: (\n\t\tresult: T,\n\t\ttransformed: readonly unknown[],\n\t) => T;\n\treadonly returnAfterMutationResult?: boolean;\n};\n\nexport type PreparedMutationExecutionResult<T> = {\n\treadonly result: T;\n\treadonly affectedRows?: number;\n};\n\nexport type RunMutationWithHooksOptions<\n\tT,\n\tTIntent extends MutationIntent = MutationIntent,\n> = {\n\treadonly table: string;\n\treadonly intent: TIntent;\n\treadonly hookStore?: HookStore | undefined;\n\treadonly onHookError?: HookErrorHandler | undefined;\n\treadonly onObserverError?: ObserverErrorHandler | undefined;\n\treadonly schemaName?: string | undefined;\n\treadonly inTransaction?: boolean | undefined;\n\treadonly prepare: (intent: TIntent) => PreparedMutationExecution<T>;\n};\n\nexport async function runMutationWithHooks<\n\tT,\n\tTIntent extends MutationIntent = MutationIntent,\n>(opts: RunMutationWithHooksOptions<T, TIntent>): Promise<T> {\n\tconst execution = await runMutationWithHooksMeta(opts);\n\treturn execution.result;\n}\n\nasync function runMutationWithHooksMeta<\n\tT,\n\tTIntent extends MutationIntent = MutationIntent,\n>(\n\topts: RunMutationWithHooksOptions<T, TIntent>,\n): Promise<PreparedMutationExecutionResult<T>> {\n\tif (!opts.hookStore || !hasHooks(opts.hookStore)) {\n\t\tconst prepared = opts.prepare(opts.intent);\n\t\treturn prepared.execute();\n\t}\n\n\treturn withReentrancyGuard(opts.hookStore, (store) =>\n\t\trunMutationWithHooksInner(opts, store),\n\t);\n}\n\nasync function runMutationWithHooksInner<\n\tT,\n\tTIntent extends MutationIntent = MutationIntent,\n>(\n\topts: RunMutationWithHooksOptions<T, TIntent>,\n\tstore: HookStore,\n): Promise<PreparedMutationExecutionResult<T>> {\n\tconst { intent } = opts;\n\tconst operation = intent.type as MutationOperation;\n\tconst startTime = Date.now();\n\tconst { cardinality, data } = extractMutationIntentData(intent);\n\n\tlet ctx: MutationHookContext = Object.freeze({\n\t\ttable: opts.table,\n\t\toperation,\n\t\tintent,\n\t\tcardinality,\n\t\tdata,\n\t\t...(opts.schemaName !== undefined ? { schemaName: opts.schemaName } : {}),\n\t\t...(opts.inTransaction ? { inTransaction: true } : {}),\n\t});\n\n\ttry {\n\t\tif (store.beforeMutation.length > 0) {\n\t\t\tctx = await runBeforeMutationHooks(\n\t\t\t\tstore.beforeMutation,\n\t\t\t\tctx,\n\t\t\t\topts.onHookError,\n\t\t\t);\n\t\t}\n\n\t\tconst executedIntent = intent;\n\t\tconst prepared = opts.prepare(executedIntent);\n\t\tconst duration = Date.now() - startTime;\n\t\tconst execution = await prepared.execute();\n\t\tlet result = execution.result;\n\n\t\tif (\n\t\t\tstore.afterMutationObservers.length > 0 ||\n\t\t\tstore.afterMutation.length > 0\n\t\t) {\n\t\t\tconst { cardinality: executedCardinality, data: executedData } =\n\t\t\t\textractMutationIntentData(executedIntent);\n\t\t\tconst afterCtx: MutationHookContext = Object.freeze({\n\t\t\t\ttable: executedIntent.table,\n\t\t\t\toperation: executedIntent.type as MutationOperation,\n\t\t\t\tintent: executedIntent,\n\t\t\t\tcardinality: executedCardinality,\n\t\t\t\t...(executedData !== undefined ? { data: executedData } : {}),\n\t\t\t\t...(opts.schemaName !== undefined\n\t\t\t\t\t? { schemaName: opts.schemaName }\n\t\t\t\t\t: {}),\n\t\t\t\t...(opts.inTransaction !== undefined\n\t\t\t\t\t? { inTransaction: opts.inTransaction }\n\t\t\t\t\t: {}),\n\t\t\t\t...(ctx.correlationId !== undefined\n\t\t\t\t\t? { correlationId: ctx.correlationId }\n\t\t\t\t\t: {}),\n\t\t\t\tsql: prepared.sql,\n\t\t\t\tparameters: prepared.parameters,\n\t\t\t\tduration,\n\t\t\t\t...(execution.affectedRows !== undefined\n\t\t\t\t\t? { affectedRows: execution.affectedRows }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tconst afterMutationResult = [\n\t\t\t\t...(prepared.getAfterMutationResult?.(execution.result) ?? []),\n\t\t\t];\n\t\t\tawait runAfterMutationObservers(\n\t\t\t\tstore.afterMutationObservers,\n\t\t\t\tafterCtx,\n\t\t\t\tafterMutationResult,\n\t\t\t\topts.onObserverError,\n\t\t\t);\n\t\t\tconst transformed = await runAfterMutationHooks(\n\t\t\t\tstore.afterMutation,\n\t\t\t\tafterCtx,\n\t\t\t\tafterMutationResult,\n\t\t\t\topts.onHookError,\n\t\t\t);\n\t\t\tif (prepared.returnAfterMutationResult) {\n\t\t\t\tresult =\n\t\t\t\t\tprepared.mapAfterMutationResult?.(result, transformed) ??\n\t\t\t\t\t(transformed as T);\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tresult,\n\t\t\t...(execution.affectedRows !== undefined\n\t\t\t\t? { affectedRows: execution.affectedRows }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\tif (store.onError.length > 0) {\n\t\t\tconst errorCtx = {\n\t\t\t\ttable: opts.table,\n\t\t\t\toperation,\n\t\t\t\terror: normalizeHookError(error),\n\t\t\t\tintent,\n\t\t\t\tphase: 'beforeMutation' as const,\n\t\t\t\t...(opts.schemaName !== undefined\n\t\t\t\t\t? { schemaName: opts.schemaName }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tconst transformed = await runOnErrorHooks(store.onError, errorCtx);\n\t\t\tthrow transformed;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction extractMutationIntentData(intent: MutationIntent): {\n\tcardinality: 'single' | 'bulk';\n\tdata: unknown;\n} {\n\tif (intent.type === 'insert' || intent.type === 'upsert') {\n\t\tconst values = (intent as InsertIntent | UpsertIntent).values;\n\t\treturn {\n\t\t\tcardinality: values.length > 1 ? 'bulk' : 'single',\n\t\t\tdata: values.length > 1 ? values : values[0],\n\t\t};\n\t}\n\tif (intent.type === 'update') {\n\t\treturn {\n\t\t\tcardinality: 'single',\n\t\t\tdata: (intent as UpdateIntent).set,\n\t\t};\n\t}\n\tif (intent.type === 'batchUpdate') {\n\t\treturn {\n\t\t\tcardinality: 'bulk',\n\t\t\tdata: (intent as BatchUpdateIntent).updates,\n\t\t};\n\t}\n\tif (intent.type === 'insert_from' || intent.type === 'upsert_from') {\n\t\treturn { cardinality: 'bulk', data: undefined };\n\t}\n\treturn { cardinality: 'single', data: undefined };\n}\n\n// ============================================================================\n// Abstract Base\n// ============================================================================\n\n/**\n * Abstract base class for mutation builders.\n * Consolidates shared fields, adapter validation, dump(), and execute() logic.\n *\n * Subclasses implement:\n * - `buildIntent()`: construct the mutation-specific intent\n * - `compileIntent()`: call the correct adapter.compile* method\n * - `operationName`: label used in error messages\n */\nabstract class MutationBuilderBase<\n\tT,\n\tTIntent extends\n\t\t| InsertIntent\n\t\t| UpdateIntent\n\t\t| BatchUpdateIntent\n\t\t| DeleteIntent\n\t\t| UpsertIntent,\n> {\n\tprotected readonly table: string;\n\tprotected readonly model: ModelIR;\n\tprotected readonly adapter: Adapter | undefined;\n\tprotected readonly schemaName: string | undefined;\n\tprotected readonly returningColumns: readonly string[] | undefined;\n\tprotected readonly hookStore: HookStore | undefined;\n\tprotected readonly onHookError: HookErrorHandler | undefined;\n\tprotected readonly onObserverError: ObserverErrorHandler | undefined;\n\tprotected readonly inTransaction: boolean | undefined;\n\n\tprotected constructor(\n\t\topts: MutationBaseOpts & {\n\t\t\treturning?: readonly string[] | undefined;\n\t\t},\n\t) {\n\t\tthis.table = opts.table;\n\t\tthis.model = opts.model;\n\t\tthis.adapter = opts.adapter;\n\t\tthis.schemaName = opts.schemaName;\n\t\tthis.returningColumns = opts.returning;\n\t\tthis.hookStore = opts.hookStore;\n\t\tthis.onHookError = opts.onHookError;\n\t\tthis.onObserverError = opts.onObserverError;\n\t\tthis.inTransaction = opts.inTransaction;\n\t}\n\n\t/** Label used in ExecutionError messages (e.g. 'insert', 'update'). */\n\tprotected abstract readonly operationName: string;\n\n\t/** Construct the mutation-specific intent AST node. */\n\tprotected abstract buildIntent(): TIntent;\n\n\t/** Delegate to the adapter's mutation-specific compile method. */\n\tprotected abstract compileIntent(\n\t\tadapter: Adapter,\n\t\tintent: TIntent,\n\t\toptions?: CompileOptions,\n\t): CompiledQuery;\n\n\tprotected get baseOpts(): MutationBaseOpts {\n\t\treturn {\n\t\t\ttable: this.table,\n\t\t\tmodel: this.model,\n\t\t\tadapter: this.adapter,\n\t\t\tschemaName: this.schemaName,\n\t\t\thookStore: this.hookStore,\n\t\t\tonHookError: this.onHookError,\n\t\t\tonObserverError: this.onObserverError,\n\t\t\tinTransaction: this.inTransaction,\n\t\t};\n\t}\n\n\t/** Require a configured adapter or throw. */\n\tprotected requireAdapter(operation: string): Adapter {\n\t\tif (!this.adapter) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation,\n\t\t\t\treason: 'Adapter not configured',\n\t\t\t\tfix: 'Pass adapter option when creating ORM: createOrm({ model, adapter })',\n\t\t\t});\n\t\t}\n\t\treturn this.adapter;\n\t}\n\n\tdump(extraOptions?: CompileOptions): MutationDump {\n\t\tconst adapter = this.requireAdapter('dump');\n\t\tconst intent = this.buildIntent();\n\t\tconst compileOptions: CompileOptions = {\n\t\t\tmodel: this.model,\n\t\t\t...(this.schemaName !== undefined && { schemaName: this.schemaName }),\n\t\t\t...extraOptions,\n\t\t};\n\t\tconst compiled = this.compileIntent(\n\t\t\tadapter,\n\t\t\tintent,\n\t\t\tObject.keys(compileOptions).length > 0 ? compileOptions : undefined,\n\t\t);\n\n\t\tconst meta: DumpMeta = {\n\t\t\tcompiledAt: new Date(),\n\t\t\t...(this.schemaName !== undefined && { schema: this.schemaName }),\n\t\t\t...(extraOptions?.queryName !== undefined && {\n\t\t\t\tqueryName: extraOptions.queryName,\n\t\t\t}),\n\t\t\t...(extraOptions?.correlationId !== undefined && {\n\t\t\t\tcorrelationId: extraOptions.correlationId,\n\t\t\t}),\n\t\t};\n\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparameters: compiled.parameters,\n\t\t\tintent,\n\t\t\tmeta,\n\t\t};\n\t}\n\n\tasync execute(): Promise<T> {\n\t\tconst adapter = this.requireAdapter(this.operationName);\n\t\tconst intent = this.buildIntent();\n\n\t\treturn runMutationWithHooks({\n\t\t\ttable: this.table,\n\t\t\tintent,\n\t\t\thookStore: this.hookStore,\n\t\t\tonHookError: this.onHookError,\n\t\t\tonObserverError: this.onObserverError,\n\t\t\tschemaName: this.schemaName,\n\t\t\tinTransaction: this.inTransaction,\n\t\t\tprepare: (preparedIntent) =>\n\t\t\t\tthis.prepareMutationExecution(adapter, preparedIntent),\n\t\t});\n\t}\n\n\tasync affectedRows(): Promise<number> {\n\t\tconst adapter = this.requireAdapter(this.operationName);\n\t\tconst intent = this.buildIntent();\n\t\tconst operation = `${this.operationName}.affectedRows()`;\n\t\tif (typeof adapter.executeWithMeta !== 'function') {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation,\n\t\t\t\treason:\n\t\t\t\t\t'this adapter does not support affectedRows(); it does not implement executeWithMeta',\n\t\t\t\tfix: 'Use an adapter that implements executeWithMeta, or call execute() when row count metadata is not required.',\n\t\t\t});\n\t\t}\n\t\tconst execution = await runMutationWithHooksMeta({\n\t\t\ttable: this.table,\n\t\t\tintent,\n\t\t\thookStore: this.hookStore,\n\t\t\tonHookError: this.onHookError,\n\t\t\tonObserverError: this.onObserverError,\n\t\t\tschemaName: this.schemaName,\n\t\t\tinTransaction: this.inTransaction,\n\t\t\tprepare: (preparedIntent) =>\n\t\t\t\tthis.prepareMutationExecution(adapter, preparedIntent, operation),\n\t\t});\n\t\tif (execution.affectedRows === undefined) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation,\n\t\t\t\treason:\n\t\t\t\t\t'this adapter does not support affectedRows(); it did not return executeWithMeta metadata',\n\t\t\t\tfix: 'Use an adapter that implements executeWithMeta and returns rowCount metadata.',\n\t\t\t});\n\t\t}\n\t\treturn execution.affectedRows;\n\t}\n\n\tprivate prepareMutationExecution(\n\t\tadapter: Adapter,\n\t\tintent: TIntent,\n\t\toperation = `${this.operationName}()`,\n\t): PreparedMutationExecution<T> {\n\t\tconst compileOptions: CompileOptions = {\n\t\t\tmodel: this.model,\n\t\t\t...(this.schemaName ? { schemaName: this.schemaName } : {}),\n\t\t};\n\t\tconst compiled = this.compileIntent(adapter, intent, compileOptions);\n\n\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\treturn {\n\t\t\t\tsql: compiled.sql,\n\t\t\t\tparameters: compiled.parameters,\n\t\t\t\texecute: async () => {\n\t\t\t\t\tif (typeof adapter.executeWithMeta === 'function') {\n\t\t\t\t\t\tconst result = await executeCompiledQueryWithMeta(\n\t\t\t\t\t\t\tadapter,\n\t\t\t\t\t\t\tcompiled,\n\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tresult: result.rows as T,\n\t\t\t\t\t\t\taffectedRows: result.rowCount,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst result = await executeCompiledQuery(\n\t\t\t\t\t\tadapter,\n\t\t\t\t\t\tcompiled,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tresult: result as T,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tgetAfterMutationResult: (result) => result as unknown[],\n\t\t\t\treturnAfterMutationResult: true,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparameters: compiled.parameters,\n\t\t\texecute: async () => {\n\t\t\t\tif (typeof adapter.executeWithMeta === 'function') {\n\t\t\t\t\tconst result = await executeCompiledQueryWithMeta(\n\t\t\t\t\t\tadapter,\n\t\t\t\t\t\tcompiled,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tresult: undefined as T,\n\t\t\t\t\t\taffectedRows: result.rowCount,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tawait executeCompiledQuery(adapter, compiled, operation);\n\t\t\t\treturn {\n\t\t\t\t\tresult: undefined as T,\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetAfterMutationResult: () => [],\n\t\t};\n\t}\n}\n\n// ============================================================================\n// Insert Builder\n// ============================================================================\n\n/**\n * Builder for INSERT operations.\n * Immutable - each method returns a new builder instance.\n */\nexport class InsertBuilder<\n\tTRow = unknown,\n\tTResult = void,\n> extends MutationBuilderBase<TResult, InsertIntent> {\n\tprivate readonly valuesData: readonly Record<string, unknown>[];\n\n\tprotected readonly operationName = 'insert';\n\n\tconstructor(\n\t\topts: MutationBaseOpts & {\n\t\t\tvalues?: readonly Record<string, unknown>[] | undefined;\n\t\t\treturning?: readonly string[] | undefined;\n\t\t},\n\t) {\n\t\tsuper(opts);\n\t\tthis.valuesData = opts.values ?? [];\n\t}\n\n\t/**\n\t * Set values to insert.\n\t * Accepts a single object or an array for bulk insert.\n\t */\n\tvalues<TInput extends Insertable<TRow> | readonly Insertable<TRow>[]>(\n\t\tdata: TInput &\n\t\t\t(TInput extends readonly Insertable<TRow>[]\n\t\t\t\t? ExactMutationRows<TInput, Insertable<TRow>>\n\t\t\t\t: ExactMutationPayload<TInput, Insertable<TRow>>),\n\t): InsertBuilder<TRow, TResult>;\n\tvalues(\n\t\tdata: Insertable<TRow> | readonly Insertable<TRow>[],\n\t): InsertBuilder<TRow, TResult> {\n\t\tconst valueArray = Array.isArray(data) ? data : [data];\n\t\tassertNonEmptyMutationRows('insert', valueArray);\n\t\tfor (const value of valueArray) {\n\t\t\tassertMutationPayloadColumns('insert', this.model, this.table, value);\n\t\t}\n\t\treturn new InsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: valueArray as readonly Record<string, unknown>[],\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Specify columns to return after insert (DX-026).\n\t * Requires adapter support for RETURNING clause.\n\t *\n\t * @example\n\t * ```typescript\n\t * const inserted = await orm.insert(User)\n\t * .values({ name: 'Alice', email: 'alice@example.com' })\n\t * .returning(['id', 'created_at'])\n\t * .execute();\n\t * // inserted = [{ id: 1, created_at: '2024-01-01T00:00:00Z' }]\n\t * ```\n\t */\n\treturning<K extends MutationKey<TRow>>(\n\t\tcolumns: readonly K[],\n\t): InsertBuilder<TRow, MutationReturningRow<TRow, K>[]> {\n\t\treturn new InsertBuilder<TRow, MutationReturningRow<TRow, K>[]>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\treturning: columns,\n\t\t});\n\t}\n\n\tprotected buildIntent(): InsertIntent {\n\t\tif (this.valuesData.length === 0) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'insert',\n\t\t\t\t'No values provided for insert',\n\t\t\t);\n\t\t}\n\n\t\tconst intent: InsertIntent = {\n\t\t\ttype: 'insert',\n\t\t\ttable: this.table,\n\t\t\tvalues: this.valuesData,\n\t\t};\n\n\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\treturn { ...intent, returning: this.returningColumns };\n\t\t}\n\n\t\treturn intent;\n\t}\n\n\tprotected compileIntent(\n\t\tadapter: Adapter,\n\t\tintent: InsertIntent,\n\t\toptions?: CompileOptions,\n\t): CompiledQuery {\n\t\treturn compileMutationIntent(adapter, intent, options);\n\t}\n}\n\n// ============================================================================\n// Update Builder\n// ============================================================================\n\n/**\n * Builder for UPDATE operations.\n * Immutable - each method returns a new builder instance.\n */\nexport class UpdateBuilder<\n\tTRow = unknown,\n\tTResult = void,\n> extends MutationBuilderBase<TResult, UpdateIntent | BatchUpdateIntent> {\n\tprivate readonly setData: Record<string, unknown>;\n\tprivate readonly whereIntent: WhereIntent | undefined;\n\tprivate readonly allowAllFlag: boolean;\n\tprivate readonly batchMatchColumns: readonly string[] | undefined;\n\tprivate readonly batchData: readonly Record<string, unknown>[] | undefined;\n\n\tprotected readonly operationName = 'update';\n\n\tconstructor(\n\t\topts: MutationBaseOpts & {\n\t\t\tset?: Record<string, unknown> | undefined;\n\t\t\twhere?: WhereIntent | undefined;\n\t\t\tallowAll?: boolean | undefined;\n\t\t\treturning?: readonly string[] | undefined;\n\t\t\tbatchMatchColumns?: readonly string[] | undefined;\n\t\t\tbatchData?: readonly Record<string, unknown>[] | undefined;\n\t\t},\n\t) {\n\t\tsuper(opts);\n\t\tthis.setData = opts.set ?? {};\n\t\tthis.whereIntent = opts.where;\n\t\tthis.allowAllFlag = opts.allowAll ?? false;\n\t\tthis.batchMatchColumns = opts.batchMatchColumns;\n\t\tthis.batchData = opts.batchData;\n\t}\n\n\t/**\n\t * Set fields to update.\n\t * Multiple calls merge fields (last value wins).\n\t * When combined with batchSet(), these become scalar SET assignments applied to all rows.\n\t */\n\tset<TInput extends Updateable<TRow>>(\n\t\tdata: ExactMutationPayload<TInput, Updateable<TRow>>,\n\t): UpdateBuilder<TRow, TResult> {\n\t\tassertMutationObjectPayload('update', data);\n\t\tassertMutationPayloadColumns('update', this.model, this.table, data);\n\t\treturn new UpdateBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tset: { ...this.setData, ...data },\n\t\t\twhere: this.whereIntent,\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\treturning: this.returningColumns,\n\t\t\tbatchMatchColumns: this.batchMatchColumns,\n\t\t\tbatchData: this.batchData,\n\t\t});\n\t}\n\n\t/**\n\t * Add WHERE condition.\n\t */\n\twhere(condition: MutationWhereCondition): UpdateBuilder<TRow, TResult> {\n\t\treturn new UpdateBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tset: this.setData,\n\t\t\twhere: toWhereIntent(condition),\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\treturning: this.returningColumns,\n\t\t\tbatchMatchColumns: this.batchMatchColumns,\n\t\t\tbatchData: this.batchData,\n\t\t});\n\t}\n\n\t/**\n\t * Specify columns to return after update (DX-026).\n\t * Requires adapter support for RETURNING clause.\n\t *\n\t * @example\n\t * ```typescript\n\t * const updated = await orm.update(User)\n\t * .set({ status: 'active' })\n\t * .where({ type: 'comparison', field: 'id', operator: '=', value: 1 })\n\t * .returning(['id', 'status', 'updated_at'])\n\t * .execute();\n\t * ```\n\t */\n\treturning<K extends MutationKey<TRow>>(\n\t\tcolumns: readonly K[],\n\t): UpdateBuilder<TRow, MutationReturningRow<TRow, K>[]> {\n\t\treturn new UpdateBuilder<TRow, MutationReturningRow<TRow, K>[]>({\n\t\t\t...this.baseOpts,\n\t\t\tset: this.setData,\n\t\t\twhere: this.whereIntent,\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\treturning: columns,\n\t\t\tbatchMatchColumns: this.batchMatchColumns,\n\t\t\tbatchData: this.batchData,\n\t\t});\n\t}\n\n\t/**\n\t * Batch update multiple rows using unnest FROM strategy (BATCH-001).\n\t *\n\t * Generates:\n\t * UPDATE \"table\" SET \"col\" = t.\"col\"\n\t * FROM unnest(CAST($1 AS type[]), CAST($2 AS type[])) AS t(\"match_col\", \"col\")\n\t * WHERE \"table\".\"match_col\" = t.\"match_col\"\n\t *\n\t * Can be chained with .set() for scalar values applied to all rows.\n\t *\n\t * @param matchColumn - Column(s) used to identify rows to update\n\t * @param data - Array of row objects containing match + update column values\n\t *\n\t * @example\n\t * ```typescript\n\t * await orm.update('calls')\n\t * .batchSet('id', [{ id: 10, callee_id: 42 }, { id: 20, callee_id: 43 }])\n\t * .execute();\n\t * ```\n\t */\n\tbatchSet<TInput extends BatchUpdateable<TRow>>(\n\t\tmatchColumn: MutationKey<TRow> | MutationKey<TRow>[],\n\t\tdata: readonly ExactMutationPayload<TInput, BatchUpdateable<TRow>>[],\n\t): UpdateBuilder<TRow, TResult> {\n\t\tconst matchColumns = Array.isArray(matchColumn)\n\t\t\t? matchColumn\n\t\t\t: [matchColumn];\n\t\tfor (const row of data) {\n\t\t\tassertMutationObjectPayload('update', row);\n\t\t\tassertMutationPayloadColumns('update', this.model, this.table, row);\n\t\t}\n\t\treturn new UpdateBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tset: this.setData,\n\t\t\twhere: this.whereIntent,\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\treturning: this.returningColumns,\n\t\t\tbatchMatchColumns: matchColumns as string[],\n\t\t\tbatchData: data as readonly Record<string, unknown>[],\n\t\t});\n\t}\n\n\tprotected buildIntent(): UpdateIntent | BatchUpdateIntent {\n\t\t// Batch path\n\t\tif (this.batchMatchColumns && this.batchData) {\n\t\t\tif (this.batchData.length === 0) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'update',\n\t\t\t\t\t'batchSet requires at least one row',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst intent: BatchUpdateIntent = {\n\t\t\t\ttype: 'batchUpdate',\n\t\t\t\ttable: this.table,\n\t\t\t\tmatchColumns: this.batchMatchColumns,\n\t\t\t\tupdates: this.batchData,\n\t\t\t};\n\n\t\t\tif (Object.keys(this.setData).length > 0) {\n\t\t\t\tObject.assign(intent, { scalarSet: this.setData });\n\t\t\t}\n\t\t\tif (this.whereIntent) {\n\t\t\t\tObject.assign(intent, { where: this.whereIntent });\n\t\t\t}\n\t\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\t\tObject.assign(intent, { returning: this.returningColumns });\n\t\t\t}\n\n\t\t\treturn intent;\n\t\t}\n\n\t\t// Regular update path\n\t\tif (Object.keys(this.setData).length === 0) {\n\t\t\tthrow new InvalidOperationError('update', 'No fields to update');\n\t\t}\n\n\t\tif (!this.whereIntent && !this.allowAllFlag) {\n\t\t\tthrow new UnsafeOperationError(\n\t\t\t\t'update',\n\t\t\t\t'WHERE clause required. Use updateAll() for full-table updates.',\n\t\t\t);\n\t\t}\n\n\t\tconst intent: UpdateIntent = {\n\t\t\ttype: 'update',\n\t\t\ttable: this.table,\n\t\t\tset: this.setData,\n\t\t};\n\n\t\tif (this.whereIntent) {\n\t\t\tObject.assign(intent, { where: this.whereIntent });\n\t\t}\n\t\tif (this.allowAllFlag) {\n\t\t\tObject.assign(intent, { allowAll: true });\n\t\t}\n\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\tObject.assign(intent, { returning: this.returningColumns });\n\t\t}\n\n\t\treturn intent;\n\t}\n\n\tprotected compileIntent(\n\t\tadapter: Adapter,\n\t\tintent: UpdateIntent | BatchUpdateIntent,\n\t\toptions?: CompileOptions,\n\t): CompiledQuery {\n\t\treturn compileMutationIntent(adapter, intent, options);\n\t}\n}\n\n// ============================================================================\n// Delete Builder\n// ============================================================================\n\n/**\n * Builder for DELETE operations.\n * Immutable - each method returns a new builder instance.\n */\nexport class DeleteBuilder<\n\tTRow = unknown,\n\tTResult = void,\n> extends MutationBuilderBase<TResult, DeleteIntent> {\n\tprivate readonly whereIntent: WhereIntent | undefined;\n\tprivate readonly allowAllFlag: boolean;\n\tprivate readonly cascadeRelations: boolean | readonly string[] | undefined;\n\n\tprotected readonly operationName = 'delete';\n\n\tconstructor(\n\t\topts: MutationBaseOpts & {\n\t\t\twhere?: WhereIntent | undefined;\n\t\t\tallowAll?: boolean | undefined;\n\t\t\tcascade?: boolean | readonly string[] | undefined;\n\t\t\treturning?: readonly string[] | undefined;\n\t\t},\n\t) {\n\t\tsuper(opts);\n\t\tthis.whereIntent = opts.where;\n\t\tthis.allowAllFlag = opts.allowAll ?? false;\n\t\tthis.cascadeRelations = opts.cascade;\n\t}\n\n\t/**\n\t * Add WHERE condition.\n\t */\n\twhere(condition: MutationWhereCondition): DeleteBuilder<TRow, TResult> {\n\t\treturn new DeleteBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\twhere: toWhereIntent(condition),\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\tcascade: this.cascadeRelations,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Enable cascade delete.\n\t * Without arguments: deletes ALL related records.\n\t * With array: deletes only specified relations.\n\t */\n\tcascade(relations?: readonly string[]): DeleteBuilder<TRow, TResult> {\n\t\treturn new DeleteBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\twhere: this.whereIntent,\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\tcascade: relations ?? true,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Specify columns to return after delete (DX-026).\n\t * Requires adapter support for RETURNING clause.\n\t *\n\t * @example\n\t * ```typescript\n\t * const deleted = await orm.delete(User)\n\t * .where({ type: 'comparison', field: 'id', operator: '=', value: 1 })\n\t * .returning(['id', 'email'])\n\t * .execute();\n\t * ```\n\t */\n\treturning<K extends MutationKey<TRow>>(\n\t\tcolumns: readonly K[],\n\t): DeleteBuilder<TRow, MutationReturningRow<TRow, K>[]> {\n\t\treturn new DeleteBuilder<TRow, MutationReturningRow<TRow, K>[]>({\n\t\t\t...this.baseOpts,\n\t\t\twhere: this.whereIntent,\n\t\t\tallowAll: this.allowAllFlag,\n\t\t\tcascade: this.cascadeRelations,\n\t\t\treturning: columns,\n\t\t});\n\t}\n\n\tprotected buildIntent(): DeleteIntent {\n\t\tif (!this.whereIntent && !this.allowAllFlag) {\n\t\t\tthrow new UnsafeOperationError(\n\t\t\t\t'delete',\n\t\t\t\t'WHERE clause required. Use deleteAll() for full-table deletes.',\n\t\t\t);\n\t\t}\n\n\t\tconst intent: DeleteIntent = {\n\t\t\ttype: 'delete',\n\t\t\ttable: this.table,\n\t\t};\n\n\t\tif (this.whereIntent) {\n\t\t\tObject.assign(intent, { where: this.whereIntent });\n\t\t}\n\t\tif (this.allowAllFlag) {\n\t\t\tObject.assign(intent, { allowAll: true });\n\t\t}\n\t\tif (this.cascadeRelations !== undefined) {\n\t\t\tObject.assign(intent, { cascade: this.cascadeRelations });\n\t\t}\n\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\tObject.assign(intent, { returning: this.returningColumns });\n\t\t}\n\n\t\treturn intent;\n\t}\n\n\tprotected compileIntent(\n\t\tadapter: Adapter,\n\t\tintent: DeleteIntent,\n\t\toptions?: CompileOptions,\n\t): CompiledQuery {\n\t\treturn compileMutationIntent(adapter, intent, options);\n\t}\n}\n\n// ============================================================================\n// Upsert Builder (DX-026)\n// ============================================================================\n\n/**\n * Builder for UPSERT operations (INSERT ... ON CONFLICT ... DO UPDATE/NOTHING).\n * Immutable - each method returns a new builder instance.\n *\n * @example\n * ```typescript\n * // Basic upsert with doUpdate\n * await orm.upsert(User)\n * .values({ id: 1, name: 'Alice', email: 'alice@example.com' })\n * .onConflict(['id'])\n * .doUpdate({ name: 'Alice Updated' })\n * .execute();\n *\n * // Upsert with doNothing\n * await orm.upsert(User)\n * .values({ id: 1, name: 'Alice' })\n * .onConflict(['id'])\n * .doNothing()\n * .execute();\n *\n * // Upsert with constraint name\n * await orm.upsert(User)\n * .values({ id: 1, name: 'Alice' })\n * .onConflictConstraint('users_pkey')\n * .doUpdate() // Auto-update non-conflict columns\n * .returning(['id', 'updated_at'])\n * .execute();\n * ```\n */\nexport class UpsertBuilder<\n\tTRow = unknown,\n\tTResult = void,\n> extends MutationBuilderBase<TResult, UpsertIntent> {\n\tprivate readonly valuesData: readonly Record<string, unknown>[];\n\tprivate readonly conflictTarget: UpsertConflictTarget | undefined;\n\tprivate readonly conflictAction: UpsertConflictAction | undefined;\n\n\tprotected readonly operationName = 'upsert';\n\n\tconstructor(\n\t\topts: MutationBaseOpts & {\n\t\t\tvalues?: readonly Record<string, unknown>[] | undefined;\n\t\t\tonConflict?: UpsertConflictTarget | undefined;\n\t\t\taction?: UpsertConflictAction | undefined;\n\t\t\treturning?: readonly string[] | undefined;\n\t\t},\n\t) {\n\t\tsuper(opts);\n\t\tthis.valuesData = opts.values ?? [];\n\t\tthis.conflictTarget = opts.onConflict;\n\t\tthis.conflictAction = opts.action;\n\t}\n\n\t/**\n\t * Set values to insert.\n\t * Accepts a single object or an array for bulk upsert.\n\t */\n\tvalues<TInput extends Insertable<TRow> | readonly Insertable<TRow>[]>(\n\t\tdata: TInput &\n\t\t\t(TInput extends readonly Insertable<TRow>[]\n\t\t\t\t? ExactMutationRows<TInput, Insertable<TRow>>\n\t\t\t\t: ExactMutationPayload<TInput, Insertable<TRow>>),\n\t): UpsertBuilder<TRow, TResult>;\n\tvalues(\n\t\tdata: Insertable<TRow> | readonly Insertable<TRow>[],\n\t): UpsertBuilder<TRow, TResult> {\n\t\tconst valueArray = Array.isArray(data) ? data : [data];\n\t\tassertNonEmptyMutationRows('upsert', valueArray);\n\t\tfor (const value of valueArray) {\n\t\t\tassertMutationPayloadColumns('upsert', this.model, this.table, value);\n\t\t}\n\t\treturn new UpsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: valueArray as readonly Record<string, unknown>[],\n\t\t\tonConflict: this.conflictTarget,\n\t\t\taction: this.conflictAction,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Specify conflict target by column names.\n\t * These columns determine conflict detection.\n\t */\n\tonConflict(\n\t\tcolumns: readonly MutationKey<TRow>[],\n\t): UpsertBuilder<TRow, TResult> {\n\t\treturn new UpsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: { columns: columns as readonly string[] },\n\t\t\taction: this.conflictAction,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Specify conflict target by constraint name.\n\t * Alternative to onConflict() for named constraints.\n\t */\n\tonConflictConstraint(constraintName: string): UpsertBuilder<TRow, TResult> {\n\t\treturn new UpsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: { constraint: constraintName },\n\t\t\taction: this.conflictAction,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * On conflict, update the specified fields.\n\t * If no fields specified, auto-updates all non-conflict columns.\n\t *\n\t * @param set - Optional fields to update on conflict\n\t * @param where - Optional condition for the update\n\t */\n\tdoUpdate<TInput extends Updateable<TRow>>(\n\t\tset?: ExactMutationPayload<TInput, Updateable<TRow>>,\n\t\twhere?: MutationWhereCondition,\n\t): UpsertBuilder<TRow, TResult> {\n\t\tif (set !== undefined) {\n\t\t\tassertMutationObjectPayload('upsert', set);\n\t\t\tassertMutationPayloadColumns('upsert', this.model, this.table, set);\n\t\t}\n\t\tconst action: UpsertConflictAction = {\n\t\t\ttype: 'doUpdate',\n\t\t\t...(set !== undefined && { set: set as Record<string, unknown> }),\n\t\t\t...(where && { where: toWhereIntent(where) }),\n\t\t};\n\t\treturn new UpsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: this.conflictTarget,\n\t\t\taction,\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * On conflict, do nothing (skip the insert).\n\t */\n\tdoNothing(): UpsertBuilder<TRow, TResult> {\n\t\treturn new UpsertBuilder<TRow, TResult>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: this.conflictTarget,\n\t\t\taction: { type: 'doNothing' },\n\t\t\treturning: this.returningColumns,\n\t\t});\n\t}\n\n\t/**\n\t * Specify columns to return after upsert (DX-026).\n\t * Requires adapter support for RETURNING clause.\n\t */\n\treturning<K extends MutationKey<TRow>>(\n\t\tcolumns: readonly K[],\n\t): UpsertBuilder<TRow, MutationReturningRow<TRow, K>[]> {\n\t\treturn new UpsertBuilder<TRow, MutationReturningRow<TRow, K>[]>({\n\t\t\t...this.baseOpts,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: this.conflictTarget,\n\t\t\taction: this.conflictAction,\n\t\t\treturning: columns,\n\t\t});\n\t}\n\n\tprotected buildIntent(): UpsertIntent {\n\t\tif (this.valuesData.length === 0) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'upsert',\n\t\t\t\t'No values provided for upsert',\n\t\t\t);\n\t\t}\n\n\t\tif (!this.conflictTarget) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'upsert',\n\t\t\t\t'No conflict target specified. Use onConflict() or onConflictConstraint().',\n\t\t\t);\n\t\t}\n\n\t\tif (!this.conflictAction) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'upsert',\n\t\t\t\t'No conflict action specified. Use doUpdate() or doNothing().',\n\t\t\t);\n\t\t}\n\n\t\tconst intent: UpsertIntent = {\n\t\t\ttype: 'upsert',\n\t\t\ttable: this.table,\n\t\t\tvalues: this.valuesData,\n\t\t\tonConflict: this.conflictTarget,\n\t\t\taction: this.conflictAction,\n\t\t};\n\n\t\tif (this.returningColumns && this.returningColumns.length > 0) {\n\t\t\treturn { ...intent, returning: this.returningColumns };\n\t\t}\n\n\t\treturn intent;\n\t}\n\n\tprotected compileIntent(\n\t\tadapter: Adapter,\n\t\tintent: UpsertIntent,\n\t\toptions?: CompileOptions,\n\t): CompiledQuery {\n\t\treturn compileMutationIntent(adapter, intent, options);\n\t}\n}\n","import type {\n\tDDLFeature,\n\tDialectCapabilities,\n\tFeatureBehaviorConfig,\n\tFeatureWarning,\n\tModelIR,\n\tUnsupportedFeatureBehavior,\n} from '@dbsp/types';\n\n/** Error thrown when behavior = 'error' and unsupported feature detected */\nexport class UnsupportedFeatureError extends Error {\n\tconstructor(\n\t\treadonly feature: string,\n\t\treadonly adapter: string,\n\t\treadonly element: string,\n\t) {\n\t\tsuper(\n\t\t\t`Unsupported feature \"${feature}\" on adapter \"${adapter}\" for \"${element}\"`,\n\t\t);\n\t\tthis.name = 'UnsupportedFeatureError';\n\t}\n}\n\nimport {\n\tDEFAULT_FEATURE_CHECKERS,\n\ttype FeatureChecker,\n} from './feature-checkers.js';\n\nexport type { FeatureChecker, FeatureUsage } from './feature-checkers.js';\nexport { DEFAULT_FEATURE_CHECKERS } from './feature-checkers.js';\n\nexport interface NegotiationResult {\n\treadonly warnings: readonly FeatureWarning[];\n}\n\n/** Resolve effective behavior for a specific feature */\nfunction resolveBehavior(\n\tfeature: DDLFeature,\n\tconfig: UnsupportedFeatureBehavior | FeatureBehaviorConfig,\n): UnsupportedFeatureBehavior {\n\tif (typeof config === 'string') return config;\n\treturn config.overrides?.[feature] ?? config.default;\n}\n\n/**\n * Cross-check ModelIR features against DialectCapabilities.\n * Emits warnings or throws based on UnsupportedFeatureBehavior.\n *\n * INV-06: MUST NOT modify the ModelIR.\n * ERR-02: error mode throws on FIRST unsupported feature (fail-fast).\n * ERR-03: warning mode collects ALL warnings.\n *\n * OCP-001: extend by adding FeatureChecker entries to DEFAULT_FEATURE_CHECKERS\n * (or pass a custom checkers array) -- no edits to this function required.\n */\nexport function negotiateFeatures(\n\tmodel: ModelIR,\n\tcapabilities: DialectCapabilities,\n\tbehavior: UnsupportedFeatureBehavior | FeatureBehaviorConfig = 'warning',\n\tcheckers: readonly FeatureChecker[] = DEFAULT_FEATURE_CHECKERS,\n): NegotiationResult {\n\tconst warnings: FeatureWarning[] = [];\n\tconst adapterName = capabilities.name;\n\n\tfor (const checker of checkers) {\n\t\tif (capabilities[checker.capability]) continue; // supported\n\t\tconst usages = checker.detectUsage(model);\n\t\tif (usages.length === 0) continue; // not used\n\t\tconst effectiveBehavior = resolveBehavior(checker.feature, behavior);\n\t\tif (effectiveBehavior === 'ignore') continue;\n\t\tfor (const usage of usages) {\n\t\t\tif (effectiveBehavior === 'error') {\n\t\t\t\tthrow new UnsupportedFeatureError(\n\t\t\t\t\tchecker.feature,\n\t\t\t\t\tadapterName,\n\t\t\t\t\tusage.detail,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// warning mode\n\t\t\tconst message = `Unsupported feature \"${checker.feature}\" on adapter \"${adapterName}\" for \"${usage.detail}\"`;\n\t\t\twarnings.push({\n\t\t\t\tfeature: checker.feature,\n\t\t\t\tadapter: adapterName,\n\t\t\t\telement: usage.detail,\n\t\t\t\tmessage,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { warnings };\n}\n","/**\n * @fileoverview NQL template literal integration for type-safe queries (DX-040 Block 8).\n *\n * Provides a type-safe way to use NQL queries with explicit type annotation:\n * ```typescript\n * const users = await orm.nql<{ name: string; email: string }>`users | select name, email`.all();\n * ```\n *\n * Each non-raw `${value}` interpolation is converted into a generated NQL named\n * parameter (`:__p0`, `:__p1`, ...) and forwarded to the compiler through its\n * params map. Values never touch NQL source text. Use `nqlRaw()` only for trusted\n * dynamic NQL fragments that must participate in parsing, such as an ORDER BY\n * clause assembled from application-controlled choices.\n *\n * @module nql\n * @since DX-040\n */\n\nimport {\n\ttype CompiledNqlQuery,\n\ttype NqlCompilerOptions,\n\tNqlLexer,\n\tcompile as nqlCompile,\n} from '@dbsp/nql';\nimport type {\n\tColumnListInput,\n\tNqlBindingRelationFilterMetadata,\n\tNqlBindingVirtualRelation,\n} from '@dbsp/types';\nimport { resolveJsonAggOrderKey } from '@dbsp/types';\nimport {\n\texplainUnsupportedNqlBindingIncludeHop,\n\tgetTrustedNqlRelationFilterFields,\n\tNQL_INTERNAL_COMPILER_OPTIONS,\n\ttype NqlBindingIncludeNodeShape,\n\ttype NqlBindingIncludeRelationShape,\n} from '@dbsp/types/internal';\nimport {\n\ttype Adapter,\n\tassertConnectionAvailable,\n\ttype CompileOptions,\n\ttype DbCasing,\n\ttype Dump,\n\ttype DumpMeta,\n\ttype DumpSequenceStep,\n\texecuteCompiledQuery,\n\texecuteCompiledQueryWithMeta,\n\ttype NqlRuntimeBinding,\n\tsupportsTransactions,\n} from '../adapter.js';\nimport type { DialectCapabilities } from '../dialects/index.js';\nimport type {\n\tIncludeIntent,\n\tMutationIntent,\n\tQueryIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\nimport type { ModelIR, RelationIR } from '../model-ir.js';\nimport type { PlanDecision, PlanReport } from '../planner.js';\nimport { plan as executePlan } from '../planner.js';\nimport { ExecutionError } from './errors.js';\nimport type {\n\tHookErrorHandler,\n\tHookStore,\n\tObserverErrorHandler,\n} from './hooks.js';\nimport {\n\thydrateJsonAggIncludes,\n\tplanForJsonAggHydration,\n} from './hydration-utils.js';\nimport {\n\ttype MutationDump,\n\trunMutationWithHooks,\n} from './mutation-builders.js';\nimport type { DumpMetaInput } from './query-builder-types.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * NQL query builder with type-safe result.\n *\n * @typeParam T - The expected result row type\n */\nexport interface NqlBuilder<T> {\n\t/** Execute query and return all results */\n\tall(): Promise<T[]>;\n\t/** Execute query or mutation and discard any returned rows */\n\trun(): Promise<void>;\n\t/** Execute query and return first result or null */\n\tfirst(): Promise<T | null>;\n\t/** Get the IntentIR for debugging. Throws for CTE and set-operation queries. */\n\ttoIntentIR(): QueryIntent | MutationIntent;\n\t/** Get the execution plan. Throws for mutations and CTE and set-operation queries. */\n\tplan(): PlanReport;\n\t/** Get full dump. Mutations return MutationDump without a plan. */\n\tdump(meta?: DumpMetaInput): Dump | MutationDump;\n}\n\n/**\n * NQL template tag function type.\n *\n * @example\n * ```typescript\n * orm.nql<{ name: string }>`users | select name`\n * ```\n */\nexport type NqlTag = <T>(\n\tstrings: TemplateStringsArray,\n\t...values: unknown[]\n) => NqlBuilder<T>;\n\ndeclare const NQL_RAW_FRAGMENT_TYPE: unique symbol;\n\n/**\n * Trusted NQL source fragment for `nql` template interpolation.\n *\n * Never wrap untrusted input in `nqlRaw()`: raw fragments are spliced verbatim\n * into NQL source and parsed as query structure.\n *\n * @public\n */\nexport interface NqlRawFragment {\n\treadonly fragment: string;\n\treadonly [NQL_RAW_FRAGMENT_TYPE]: true;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nconst NQL_RAW_FRAGMENT = Symbol('NqlRawFragment');\n\ntype RuntimeNqlRawFragment = NqlRawFragment & {\n\treadonly [NQL_RAW_FRAGMENT]: true;\n};\n\ninterface GeneratedParamRange {\n\treadonly name: string;\n\treadonly start: number;\n\treadonly end: number;\n}\n\ninterface AssembledNqlTemplate {\n\treadonly query: string;\n\treadonly params: Readonly<Record<string, unknown>>;\n\treadonly hasBoundParams: boolean;\n\treadonly sourceError: string | undefined;\n}\n\ntype CompiledNqlIntent =\n\t| {\n\t\t\treadonly kind: 'query';\n\t\t\treadonly bundle: CompiledNqlQuery;\n\t\t\treadonly intent: QueryIntent;\n\t }\n\t| {\n\t\t\treadonly kind: 'mutation';\n\t\t\treadonly bundle: CompiledNqlQuery;\n\t\t\treadonly intent: MutationIntent;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * CTE and set-operation bundles are executable reads, but do not have a\n\t\t\t * QueryIntent that the semantic planner can consume.\n\t\t\t */\n\t\t\treadonly kind: 'unplannedRead';\n\t\t\treadonly bundle: CompiledNqlQuery;\n\t\t\treadonly intent:\n\t\t\t\t| NonNullable<CompiledNqlQuery['cteQuery']>\n\t\t\t\t| NonNullable<CompiledNqlQuery['setOperation']>;\n\t };\n\nconst UNPLANNED_NQL_READ_PLAN_ERROR =\n\t'NQL CTE and set-operation queries do not have execution plans.';\n\nconst UNPLANNED_NQL_READ_INTENT_ERROR =\n\t'NQL CTE and set-operation queries do not have IntentIR.';\n\nconst UNPLANNED_NQL_READ_PROGRAM_ERROR =\n\t'NQL CTE and set-operation queries are not supported after mutation or snapshot bindings.';\n\nfunction hasNqlBindings(bundle: CompiledNqlQuery): boolean {\n\treturn (bundle.bindings?.size ?? 0) > 0;\n}\n\nfunction isBindingFinalQuery(bundle: CompiledNqlQuery): boolean {\n\treturn (\n\t\tbundle.query !== undefined &&\n\t\t(bundle.bindings?.has(bundle.query.from) ?? false)\n\t);\n}\n\nfunction formatBindingRelationPath(path: string | readonly string[]): string {\n\treturn typeof path === 'string' ? path : path.join('.');\n}\n\nfunction findBindingFinalRelationFilter(\n\twhere: WhereIntent,\n): string | undefined {\n\tswitch (where.kind) {\n\t\tcase 'and':\n\t\tcase 'or':\n\t\t\tfor (const condition of where.conditions) {\n\t\t\t\tconst found = findBindingFinalRelationFilter(condition);\n\t\t\t\tif (found !== undefined) return found;\n\t\t\t}\n\t\t\treturn undefined;\n\t\tcase 'not':\n\t\t\treturn findBindingFinalRelationFilter(where.condition);\n\t\tcase 'relationFilter':\n\t\t\tif (getTrustedNqlRelationFilterFields(where) !== undefined) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn formatBindingRelationPath(where.relation);\n\t\tcase 'exists':\n\t\tcase 'notExists':\n\t\t\treturn where.relation;\n\t\tcase 'rawExists':\n\t\tcase 'rawNotExists':\n\t\t\treturn 'raw EXISTS';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction bindingFinalIncludeError(\n\tbindingName: string,\n\trelation: string,\n\treason: string,\n): Error {\n\treturn new Error(\n\t\t`NQL binding-final query '${bindingName}' cannot use relation include '${relation}' (ref-#192): ${reason}.`,\n\t);\n}\n\nfunction getBindingRelationMetadata(\n\tbundle: CompiledNqlQuery,\n\tbindingName: string,\n): NqlBindingRelationFilterMetadata | undefined {\n\treturn bundle.bindingOutputSchemas?.get(bindingName)?.relationFilters;\n}\n\nfunction getScalarBindingRelationsByName(\n\tbundle: CompiledNqlQuery,\n\tbindingName: string,\n): Map<string, NqlBindingVirtualRelation> {\n\tconst metadata = getBindingRelationMetadata(bundle, bindingName);\n\tconst relations = new Map<string, NqlBindingVirtualRelation>();\n\tfor (const relation of metadata?.scalarRelations ?? []) {\n\t\trelations.set(relation.relation, relation);\n\t}\n\treturn relations;\n}\n\nfunction bindingIncludeNodeShape(\n\tinclude: IncludeIntent,\n): NqlBindingIncludeNodeShape {\n\treturn include as unknown as NqlBindingIncludeNodeShape;\n}\n\nfunction virtualRelationIncludeShape(\n\trelation: NqlBindingVirtualRelation,\n): NqlBindingIncludeRelationShape {\n\tconst relationType = relation.relationType;\n\tconst foreignKey =\n\t\trelationType === 'belongsTo'\n\t\t\t? relation.sourceColumn\n\t\t\t: relationType === 'hasOne' || relationType === 'hasMany'\n\t\t\t\t? relation.targetColumn\n\t\t\t\t: undefined;\n\treturn {\n\t\ttype: relationType,\n\t\tforeignKey,\n\t\tsource: relation.sourceTable,\n\t\ttarget: relation.targetTable,\n\t\t...(relation.through !== undefined && { through: relation.through }),\n\t\t...(relation.throughTargetColumn !== undefined && {\n\t\t\totherKey: relation.throughTargetColumn,\n\t\t}),\n\t};\n}\n\nconst BINDING_INCLUDE_NODE_ONLY_RELATION: NqlBindingIncludeRelationShape = {\n\ttype: 'hasMany',\n\tforeignKey: '__dbsp_binding_include_node__',\n\tsource: '__dbsp_binding_include_source__',\n\ttarget: '__dbsp_binding_include_target__',\n};\n\nfunction assertSupportedBindingIncludeNodeShape(\n\tbindingName: string,\n\trootIncludeRelation: string,\n\tinclude: IncludeIntent,\n\treasonPrefix = '',\n): void {\n\tconst unsupportedReason = explainUnsupportedNqlBindingIncludeHop(\n\t\tinclude.relation,\n\t\tBINDING_INCLUDE_NODE_ONLY_RELATION,\n\t\tbindingIncludeNodeShape(include),\n\t);\n\tif (unsupportedReason) {\n\t\tthrow bindingFinalIncludeError(\n\t\t\tbindingName,\n\t\t\trootIncludeRelation,\n\t\t\t`${reasonPrefix}${unsupportedReason}`,\n\t\t);\n\t}\n}\n\nfunction bindingIncludeCoversRelationPath(\n\tinclude: IncludeIntent,\n\tsegments: readonly string[],\n): boolean {\n\tconst [head, ...tail] = segments;\n\tif (!head || include.relation !== head) return false;\n\tif (tail.length === 0) return true;\n\treturn (include.include ?? []).some((child) =>\n\t\tbindingIncludeCoversRelationPath(child, tail),\n\t);\n}\n\nfunction bindingIncludesCoverRelationPath(\n\tincludes: readonly IncludeIntent[] | undefined,\n\trelationPath: string,\n): boolean {\n\tconst segments = relationPath.split('.');\n\tif (segments.some((segment) => segment.length === 0)) return false;\n\treturn (includes ?? []).some((include) =>\n\t\tbindingIncludeCoversRelationPath(include, segments),\n\t);\n}\n\nfunction trustedBindingRelationColumnIsAdmitted(\n\tcolumn: Extract<\n\t\tNonNullable<QueryIntent['select']>,\n\t\t{ readonly type: 'expressions' }\n\t>['columns'][number],\n): boolean {\n\tif (column.kind !== 'relationColumn') return false;\n\tconst trusted = getTrustedNqlRelationFilterFields(column);\n\tif (trusted?.selectedColumn === undefined) return false;\n\tconst isDotted = column.relation.split('.').length > 1;\n\tif (trusted.cardinality === 'one') {\n\t\treturn !isDotted || trusted.hops.length > 0;\n\t}\n\tconst hasCompleteManyToManyProof =\n\t\t(trusted.relationType === 'manyToMany' ||\n\t\t\ttrusted.relationType === 'belongsToMany') &&\n\t\ttrusted.through !== undefined &&\n\t\ttrusted.throughSourceColumn !== undefined &&\n\t\ttrusted.throughTargetColumn !== undefined;\n\treturn (\n\t\ttrusted.cardinality === 'many' &&\n\t\t(trusted.relationType === 'hasMany' || hasCompleteManyToManyProof) &&\n\t\t!isDotted &&\n\t\ttrusted.hops.length === 0\n\t);\n}\n\nfunction assertProvenBindingInclude(\n\tbindingName: string,\n\tinclude: IncludeIntent,\n\tprovenRelations: ReadonlyMap<string, NqlBindingVirtualRelation>,\n): NqlBindingVirtualRelation {\n\tconst proven = provenRelations.get(include.relation);\n\tif (!proven) {\n\t\tthrow bindingFinalIncludeError(\n\t\t\tbindingName,\n\t\t\tinclude.relation,\n\t\t\t'the relation is not in the binding proven virtual-relation set',\n\t\t);\n\t}\n\tconst unsupportedReason = explainUnsupportedNqlBindingIncludeHop(\n\t\tinclude.relation,\n\t\tvirtualRelationIncludeShape(proven),\n\t\tbindingIncludeNodeShape(include),\n\t);\n\tif (unsupportedReason) {\n\t\tthrow bindingFinalIncludeError(\n\t\t\tbindingName,\n\t\t\tinclude.relation,\n\t\t\tunsupportedReason,\n\t\t);\n\t}\n\treturn proven;\n}\n\nfunction getProvenBindingIncludes(\n\tintent: QueryIntent,\n\tbundle: CompiledNqlQuery,\n): Map<string, NqlBindingVirtualRelation> {\n\tconst provenRelations = getScalarBindingRelationsByName(bundle, intent.from);\n\tconst provenIncludes = new Map<string, NqlBindingVirtualRelation>();\n\tfor (const include of intent.include ?? []) {\n\t\tconst proven = assertProvenBindingInclude(\n\t\t\tintent.from,\n\t\t\tinclude,\n\t\t\tprovenRelations,\n\t\t);\n\t\tprovenIncludes.set(include.relation, proven);\n\t}\n\treturn provenIncludes;\n}\n\nfunction assertBindingFinalQueryCanUseSyntheticPlan(\n\tintent: QueryIntent,\n\tbundle: CompiledNqlQuery,\n): void {\n\tgetProvenBindingIncludes(intent, bundle);\n\tconst relationColumns =\n\t\tintent.select?.type === 'expressions'\n\t\t\t? intent.select.columns.flatMap((column) => {\n\t\t\t\t\tif (column.kind !== 'relationColumn') return [];\n\t\t\t\t\tif (\n\t\t\t\t\t\tcolumn.column === '*' &&\n\t\t\t\t\t\tbindingIncludesCoverRelationPath(intent.include, column.relation)\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\tif (trustedBindingRelationColumnIsAdmitted(column)) {\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\treturn [column.relation];\n\t\t\t\t})\n\t\t\t: [];\n\tconst relationFilter = intent.where\n\t\t? findBindingFinalRelationFilter(intent.where)\n\t\t: undefined;\n\tconst havingRelationFilter = intent.having\n\t\t? findBindingFinalRelationFilter(intent.having)\n\t\t: undefined;\n\tif (\n\t\trelationColumns.length > 0 ||\n\t\t(intent.joins?.length ?? 0) > 0 ||\n\t\trelationFilter !== undefined ||\n\t\thavingRelationFilter !== undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t`NQL binding-final query '${intent.from}' cannot select relation columns, use includes, joins, or relation filters. Relation planning requires a physical model table, not a CTE binding.`,\n\t\t);\n\t}\n}\n\nfunction createBindingIncludeDecision(\n\tintent: QueryIntent,\n\tinclude: IncludeIntent,\n\trelation: NqlBindingVirtualRelation,\n\tindex: number,\n\tmodel: ModelIR,\n): PlanDecision {\n\tconst relationType = relation.relationType as\n\t\t| 'belongsTo'\n\t\t| 'hasOne'\n\t\t| 'hasMany';\n\tconst foreignKey =\n\t\trelationType === 'belongsTo'\n\t\t\t? relation.sourceColumn\n\t\t\t: relation.targetColumn;\n\tconst parentKey =\n\t\trelationType === 'belongsTo'\n\t\t\t? relation.targetColumn\n\t\t\t: relation.sourceColumn;\n\tconst targetTable = model.getTable(relation.targetTable);\n\tconst targetOrder = targetTable\n\t\t? resolveJsonAggOrderKey(targetTable)\n\t\t: undefined;\n\n\treturn {\n\t\tid: `binding-include-${index}`,\n\t\ttype: 'include-strategy',\n\t\tcontext: {\n\t\t\tsourceTable: intent.from,\n\t\t\ttarget: relation.targetTable,\n\t\t\trelation: relation.relation,\n\t\t\trelationType,\n\t\t\tforeignKey,\n\t\t\tparentKey,\n\t\t\t...(targetOrder &&\n\t\t\t\ttargetOrder.columns.length > 0 && {\n\t\t\t\t\ttargetOrderKey: targetOrder.columns,\n\t\t\t\t}),\n\t\t\t...(targetOrder?.fallback && { orderByFallback: true }),\n\t\t\tincludeAlias: include.relation,\n\t\t\tintentPath: `include[${index}]`,\n\t\t},\n\t\tchoice: 'json_agg',\n\t\treasoning:\n\t\t\t'NQL binding-final include uses proven binding virtual relation metadata and the json_agg include pipeline.',\n\t\talternatives: [],\n\t};\n}\n\nfunction findModelRelation(\n\tmodel: ModelIR,\n\tsourceTable: string,\n\trelationName: string,\n): RelationIR | undefined {\n\treturn (\n\t\tmodel.getRelation(`${sourceTable}.${relationName}`) ??\n\t\tmodel\n\t\t\t.getRelationsFrom(sourceTable)\n\t\t\t.find((relation) => relation.name === relationName)\n\t);\n}\n\nfunction parentKeyForRelation(relation: RelationIR): ColumnListInput {\n\tif (relation.type === 'belongsTo') return relation.targetKey;\n\treturn relation.sourceKey;\n}\n\nfunction assertSupportedBindingIncludeHop(\n\tbindingName: string,\n\trootIncludeRelation: string,\n\trelationName: string,\n\trelation: NqlBindingIncludeRelationShape,\n\tinclude: IncludeIntent,\n\treasonPrefix = '',\n): void {\n\tconst unsupportedReason = explainUnsupportedNqlBindingIncludeHop(\n\t\trelationName,\n\t\trelation,\n\t\tbindingIncludeNodeShape(include),\n\t);\n\tif (unsupportedReason) {\n\t\tthrow bindingFinalIncludeError(\n\t\t\tbindingName,\n\t\t\trootIncludeRelation,\n\t\t\t`${reasonPrefix}${unsupportedReason}`,\n\t\t);\n\t}\n}\n\nfunction assertSupportedBindingTailIncludeTree(\n\tbindingName: string,\n\trootInclude: IncludeIntent,\n\tsourceTable: string,\n\tincludes: readonly IncludeIntent[],\n\tmodel: ModelIR,\n): void {\n\tfor (const include of includes) {\n\t\tassertSupportedBindingIncludeNodeShape(\n\t\t\tbindingName,\n\t\t\trootInclude.relation,\n\t\t\tinclude,\n\t\t\t'tail ',\n\t\t);\n\t\tconst relation = findModelRelation(model, sourceTable, include.relation);\n\t\tif (!relation) {\n\t\t\tthrow bindingFinalIncludeError(\n\t\t\t\tbindingName,\n\t\t\t\trootInclude.relation,\n\t\t\t\t`tail relation '${include.relation}' is not declared on table '${sourceTable}'`,\n\t\t\t);\n\t\t}\n\t\tassertSupportedBindingIncludeHop(\n\t\t\tbindingName,\n\t\t\trootInclude.relation,\n\t\t\tinclude.relation,\n\t\t\trelation,\n\t\t\tinclude,\n\t\t\t'tail ',\n\t\t);\n\t\tassertSupportedBindingTailIncludeTree(\n\t\t\tbindingName,\n\t\t\trootInclude,\n\t\t\trelation.target,\n\t\t\tinclude.include ?? [],\n\t\t\tmodel,\n\t\t);\n\t}\n}\n\nfunction rebaseBindingTailIntentPath(\n\tintentPath: string | undefined,\n\tincludeIndex: number,\n): string {\n\treturn `include[${includeIndex}]${intentPath ? `.${intentPath}` : ''}`;\n}\n\nfunction createBindingTailIncludeDecisions(\n\tbindingName: string,\n\tinclude: IncludeIntent,\n\tfirstHopRelation: NqlBindingVirtualRelation,\n\tincludeIndex: number,\n\tmodel: ModelIR,\n): PlanDecision[] {\n\tconst nestedIncludes = include.include ?? [];\n\tif (nestedIncludes.length === 0) return [];\n\tassertSupportedBindingTailIncludeTree(\n\t\tbindingName,\n\t\tinclude,\n\t\tfirstHopRelation.targetTable,\n\t\tnestedIncludes,\n\t\tmodel,\n\t);\n\n\tconst tailPlan = executePlan(\n\t\t{\n\t\t\ttype: 'select',\n\t\t\tfrom: firstHopRelation.targetTable,\n\t\t\tinclude: nestedIncludes,\n\t\t},\n\t\tmodel,\n\t\t{ defaultIncludeStrategy: 'json_agg' },\n\t);\n\n\treturn tailPlan.decisions\n\t\t.filter((decision) => decision.type === 'include-strategy')\n\t\t.map((decision, tailIndex) => {\n\t\t\tconst sourceTable = decision.context.sourceTable;\n\t\t\tconst relationName = decision.context.relation;\n\t\t\tif (!relationName) {\n\t\t\t\tthrow bindingFinalIncludeError(\n\t\t\t\t\tbindingName,\n\t\t\t\t\tinclude.relation,\n\t\t\t\t\t'tail include planning produced a decision without a relation name',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst relation = findModelRelation(model, sourceTable, relationName);\n\t\t\tif (!relation) {\n\t\t\t\tthrow bindingFinalIncludeError(\n\t\t\t\t\tbindingName,\n\t\t\t\t\tinclude.relation,\n\t\t\t\t\t`tail relation '${relationName}' is not declared on table '${sourceTable}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertSupportedBindingIncludeHop(\n\t\t\t\tbindingName,\n\t\t\t\tinclude.relation,\n\t\t\t\trelationName,\n\t\t\t\trelation,\n\t\t\t\t{ relation: relationName },\n\t\t\t\t'tail ',\n\t\t\t);\n\t\t\tconst baseContext = { ...decision.context };\n\t\t\tdelete (baseContext as { foreignKey?: unknown }).foreignKey;\n\t\t\tdelete (baseContext as { parentKey?: unknown }).parentKey;\n\t\t\tdelete (baseContext as { targetOrderKey?: unknown }).targetOrderKey;\n\t\t\tdelete (baseContext as { orderByFallback?: unknown }).orderByFallback;\n\t\t\tconst parentKey = parentKeyForRelation(relation);\n\t\t\tconst targetTable = model.getTable(relation.target);\n\t\t\tconst targetOrder = targetTable\n\t\t\t\t? resolveJsonAggOrderKey(targetTable)\n\t\t\t\t: undefined;\n\t\t\treturn {\n\t\t\t\t...decision,\n\t\t\t\tid: `binding-include-${includeIndex}-tail-${tailIndex}`,\n\t\t\t\tchoice: 'json_agg',\n\t\t\t\treasoning:\n\t\t\t\t\t'NQL binding-final tail include uses real-table relation metadata and is forced through the json_agg include pipeline.',\n\t\t\t\tcontext: {\n\t\t\t\t\t...baseContext,\n\t\t\t\t\tsourceTable: relation.source,\n\t\t\t\t\ttarget: relation.target,\n\t\t\t\t\trelation: relation.name,\n\t\t\t\t\trelationType: relation.type,\n\t\t\t\t\t...(relation.foreignKey !== undefined && {\n\t\t\t\t\t\tforeignKey: relation.foreignKey,\n\t\t\t\t\t}),\n\t\t\t\t\t// Leave parentKey absent when RelationIR does not specify it so the\n\t\t\t\t\t// adapter applies the same defaultPkColumnName fallback as real-table includes.\n\t\t\t\t\t...(parentKey !== undefined && { parentKey }),\n\t\t\t\t\t...(targetOrder &&\n\t\t\t\t\t\ttargetOrder.columns.length > 0 && {\n\t\t\t\t\t\t\ttargetOrderKey: targetOrder.columns,\n\t\t\t\t\t\t}),\n\t\t\t\t\t...(targetOrder?.fallback && { orderByFallback: true }),\n\t\t\t\t\tintentPath: rebaseBindingTailIntentPath(\n\t\t\t\t\t\tdecision.context.intentPath,\n\t\t\t\t\t\tincludeIndex,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t};\n\t\t});\n}\n\nfunction createBindingFinalPlan(\n\tintent: QueryIntent,\n\tbundle: CompiledNqlQuery,\n\tmodel: ModelIR,\n\tdialectCapabilities?: DialectCapabilities,\n): PlanReport {\n\tassertBindingFinalQueryCanUseSyntheticPlan(intent, bundle);\n\tconst provenIncludes = getProvenBindingIncludes(intent, bundle);\n\tconst decisions = (intent.include ?? []).flatMap((include, index) => {\n\t\tif (dialectCapabilities?.supportsJsonAgg === false) {\n\t\t\tthrow bindingFinalIncludeError(\n\t\t\t\tintent.from,\n\t\t\t\tinclude.relation,\n\t\t\t\t'JSON aggregation for binding includes is not supported by this adapter',\n\t\t\t);\n\t\t}\n\t\tconst proven = provenIncludes.get(include.relation);\n\t\tif (!proven) {\n\t\t\tthrow bindingFinalIncludeError(\n\t\t\t\tintent.from,\n\t\t\t\tinclude.relation,\n\t\t\t\t'include relation proof was not emitted by the binding compiler',\n\t\t\t);\n\t\t}\n\t\tconst firstHopDecision = createBindingIncludeDecision(\n\t\t\tintent,\n\t\t\tinclude,\n\t\t\tproven,\n\t\t\tindex,\n\t\t\tmodel,\n\t\t);\n\t\treturn [\n\t\t\tfirstHopDecision,\n\t\t\t...createBindingTailIncludeDecisions(\n\t\t\t\tintent.from,\n\t\t\t\tinclude,\n\t\t\t\tproven,\n\t\t\t\tindex,\n\t\t\t\tmodel,\n\t\t\t),\n\t\t];\n\t});\n\treturn {\n\t\trootTable: intent.from,\n\t\tdecisions,\n\t\twarnings: [],\n\t\tctes: [],\n\t\tintent,\n\t\tmetadata: {\n\t\t\tplanningTimeMs: 0,\n\t\t\trelationsAnalyzed: 0,\n\t\t\tisAmbiguous: false,\n\t\t},\n\t};\n}\n\nfunction bindingFinalPlanHasJsonAggIncludes(planReport: PlanReport): boolean {\n\treturn planReport.decisions.some(\n\t\t(decision) =>\n\t\t\tdecision.type === 'include-strategy' && decision.choice === 'json_agg',\n\t);\n}\n\n/**\n * Mark a trusted fragment to splice verbatim into an NQL template.\n *\n * Never pass untrusted input to this function.\n *\n * @public\n */\nexport function nqlRaw(fragment: string): NqlRawFragment {\n\tif (typeof fragment !== 'string') {\n\t\tthrow new TypeError('nqlRaw() expects a string fragment');\n\t}\n\n\tconst raw = { fragment } as RuntimeNqlRawFragment;\n\tObject.defineProperty(raw, NQL_RAW_FRAGMENT, {\n\t\tvalue: true,\n\t\tenumerable: false,\n\t});\n\treturn Object.freeze(raw);\n}\n\nfunction isNqlRawFragment(value: unknown): value is NqlRawFragment {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\tif (!Object.hasOwn(value, NQL_RAW_FRAGMENT)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value as Record<typeof NQL_RAW_FRAGMENT, unknown>)[NQL_RAW_FRAGMENT] ===\n\t\ttrue\n\t);\n}\n\nfunction isInsideGeneratedRange(\n\tstart: number,\n\tend: number,\n\tgeneratedRanges: readonly GeneratedParamRange[],\n): boolean {\n\treturn generatedRanges.some(\n\t\t(range) => start >= range.start && end <= range.end,\n\t);\n}\n\nfunction findOverlappingGeneratedRange(\n\tstart: number,\n\tend: number,\n\tgeneratedRanges: readonly GeneratedParamRange[],\n): GeneratedParamRange | undefined {\n\treturn generatedRanges.find(\n\t\t(range) => start < range.end && end > range.start,\n\t);\n}\n\nfunction findExactGeneratedRange(\n\tname: string,\n\tstart: number,\n\tend: number,\n\tgeneratedRanges: readonly GeneratedParamRange[],\n): GeneratedParamRange | undefined {\n\treturn generatedRanges.find(\n\t\t(range) =>\n\t\t\trange.name === name && range.start === start && range.end === end,\n\t);\n}\n\nfunction generatedParamLexError(name: string): string {\n\treturn `Generated NQL parameter :${name} was not recognized as exactly one NamedParam token after raw-fragment assembly; check adjacent nqlRaw() fragments for quotes, comments, or identifier text that can swallow the placeholder.`;\n}\n\nfunction findInternalParamSourceError(\n\tquery: string,\n\tgeneratedRanges: readonly GeneratedParamRange[],\n): string | undefined {\n\tconst lexResult = NqlLexer.tokenize(query);\n\tconst generatedTokenCounts = new Map<string, number>(\n\t\tgeneratedRanges.map((range) => [range.name, 0]),\n\t);\n\n\tfor (const token of lexResult.tokens) {\n\t\tif (token.tokenType.name !== 'NamedParam') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst name = token.image.slice(1);\n\t\tif (!name.startsWith('__p')) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst start = token.startOffset;\n\t\tconst end = (token.endOffset ?? start + token.image.length - 1) + 1;\n\t\tconst exactGeneratedRange = findExactGeneratedRange(\n\t\t\tname,\n\t\t\tstart,\n\t\t\tend,\n\t\t\tgeneratedRanges,\n\t\t);\n\t\tif (exactGeneratedRange) {\n\t\t\tgeneratedTokenCounts.set(\n\t\t\t\texactGeneratedRange.name,\n\t\t\t\t(generatedTokenCounts.get(exactGeneratedRange.name) ?? 0) + 1,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst overlappingGeneratedRange = findOverlappingGeneratedRange(\n\t\t\tstart,\n\t\t\tend,\n\t\t\tgeneratedRanges,\n\t\t);\n\t\tif (overlappingGeneratedRange) {\n\t\t\treturn generatedParamLexError(overlappingGeneratedRange.name);\n\t\t}\n\n\t\tif (!isInsideGeneratedRange(start, end, generatedRanges)) {\n\t\t\treturn `Reserved NQL parameter namespace \"__p\" cannot be referenced by user source (${token.image}).`;\n\t\t}\n\t}\n\n\tfor (const range of generatedRanges) {\n\t\tif (generatedTokenCounts.get(range.name) !== 1) {\n\t\t\treturn generatedParamLexError(range.name);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction assembleNqlTemplate(\n\tstrings: TemplateStringsArray,\n\tvalues: readonly unknown[],\n): AssembledNqlTemplate {\n\tconst params = Object.create(null) as Record<string, unknown>;\n\tconst generatedRanges: GeneratedParamRange[] = [];\n\tlet query = strings[0] ?? '';\n\tlet boundIndex = 0;\n\n\tfor (let i = 0; i < values.length; i++) {\n\t\tconst value = values[i];\n\t\tif (isNqlRawFragment(value)) {\n\t\t\tquery += value.fragment;\n\t\t} else {\n\t\t\tconst name = `__p${boundIndex++}`;\n\t\t\tconst placeholder = `:${name}`;\n\t\t\tconst start = query.length;\n\t\t\tquery += placeholder;\n\t\t\tgeneratedRanges.push({ name, start, end: start + placeholder.length });\n\t\t\tparams[name] = value;\n\t\t}\n\t\tquery += strings[i + 1] ?? '';\n\t}\n\n\treturn {\n\t\tquery,\n\t\tparams,\n\t\thasBoundParams: boundIndex > 0,\n\t\tsourceError: findInternalParamSourceError(query, generatedRanges),\n\t};\n}\n\nfunction hasMutationBindingBodies(bundle: CompiledNqlQuery): boolean {\n\treturn (bundle.mutationBindings?.size ?? 0) > 0;\n}\n\nfunction hasSnapshotReadBindingSteps(bundle: CompiledNqlQuery): boolean {\n\treturn (\n\t\tbundle.nqlProgramSequence?.some(\n\t\t\t(step) => step.kind === 'query' && step.snapshot === true,\n\t\t) ?? false\n\t);\n}\n\nfunction hasExecutableNqlProgramSequence(bundle: CompiledNqlQuery): boolean {\n\treturn (\n\t\thasMutationBindingBodies(bundle) || hasSnapshotReadBindingSteps(bundle)\n\t);\n}\n\nfunction requireMutationBindingColumns(\n\tbundle: CompiledNqlQuery,\n\tbindName: string,\n): readonly string[] {\n\tconst columns = bundle.bindingOutputSchemas?.get(bindName)?.columns;\n\tif (columns === undefined || columns.length === 0) {\n\t\tthrow new Error(\n\t\t\t`NQL mutation binding '${bindName}' cannot be materialized because its projected column schema is unavailable.`,\n\t\t);\n\t}\n\treturn columns;\n}\n\nfunction toSnakeCaseIdentifier(identifier: string): string {\n\tif (!identifier) return identifier;\n\n\tconst leadingUnderscores = identifier.match(/^_+/)?.[0] ?? '';\n\tconst rest = identifier.slice(leadingUnderscores.length);\n\tif (!rest) return identifier;\n\n\tconst snakeCase = rest\n\t\t.replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n\t\t.toLowerCase();\n\n\treturn leadingUnderscores + snakeCase;\n}\n\nfunction toDatabaseColumnName(column: string, dbCasing?: DbCasing): string {\n\treturn dbCasing === 'snake_case' ? toSnakeCaseIdentifier(column) : column;\n}\n\nfunction toRuntimeBindingRow(\n\tbindName: string,\n\trow: unknown,\n\tcolumns: readonly string[],\n\tdbCasing?: DbCasing,\n): Readonly<Record<string, unknown>> {\n\tif (typeof row !== 'object' || row === null || Array.isArray(row)) {\n\t\tthrow new Error(\n\t\t\t`NQL mutation binding '${bindName}' returned a non-object row; runtime VALUES materialization requires object rows keyed by projected column name.`,\n\t\t);\n\t}\n\tconst source = row as Record<string, unknown>;\n\tconst materialized: Record<string, unknown> = {};\n\tfor (const column of columns) {\n\t\tconst dbColumn = toDatabaseColumnName(column, dbCasing);\n\t\tconst sourceColumn = Object.hasOwn(source, column)\n\t\t\t? column\n\t\t\t: dbColumn !== column && Object.hasOwn(source, dbColumn)\n\t\t\t\t? dbColumn\n\t\t\t\t: undefined;\n\t\tif (sourceColumn === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`NQL mutation binding '${bindName}' returned a row without projected column '${column}'.`,\n\t\t\t);\n\t\t}\n\t\tmaterialized[column] = source[sourceColumn];\n\t}\n\treturn materialized;\n}\n\nfunction createRuntimeBinding(\n\tbundle: CompiledNqlQuery,\n\tbindName: string,\n\trows: readonly unknown[],\n\tdbCasing?: DbCasing,\n): NqlRuntimeBinding {\n\tconst columns = requireMutationBindingColumns(bundle, bindName);\n\tconst outputSchema = bundle.bindingOutputSchemas?.get(bindName);\n\tconst columnTypes = outputSchema?.columnTypes;\n\tconst declaredOutputs = outputSchema?.declaredOutputs;\n\treturn {\n\t\tcolumns,\n\t\trows: rows.map((row) =>\n\t\t\ttoRuntimeBindingRow(bindName, row, columns, dbCasing),\n\t\t),\n\t\t...(declaredOutputs !== undefined && { declaredOutputs }),\n\t\t...(columnTypes !== undefined && { columnTypes }),\n\t};\n}\n\ntype NqlProgramStep =\n\t| {\n\t\t\treadonly kind: 'query';\n\t\t\treadonly intent: QueryIntent;\n\t\t\treadonly bindName?: string;\n\t\t\treadonly final: boolean;\n\t\t\treadonly snapshot?: true;\n\t\t\treadonly bindingDependencies?: readonly string[];\n\t }\n\t| {\n\t\t\treadonly kind: 'mutation';\n\t\t\treadonly intent: MutationIntent;\n\t\t\treadonly bindName?: string;\n\t\t\treadonly final: boolean;\n\t\t\treadonly bindingDependencies?: readonly string[];\n\t };\n\ntype NqlMutationStatementResult = {\n\treadonly rawRows: unknown[];\n\treadonly transformedRows: unknown[];\n};\n\ntype NqlMutationStatementExecution = NqlMutationStatementResult & {\n\treadonly hookRows: unknown[];\n};\n\ntype NqlProgramSequenceStepWithDependencies = NonNullable<\n\tCompiledNqlQuery['nqlProgramSequence']\n>[number] & {\n\treadonly bindingDependencies?: readonly string[];\n};\n\nfunction bindingEntryIsFinal(\n\tcompiledIntent: CompiledNqlIntent,\n\tbindName: string,\n\tboundQuery: QueryIntent,\n\tsourceBundle: CompiledNqlQuery,\n): boolean {\n\tif (compiledIntent.kind === 'query') {\n\t\treturn boundQuery === compiledIntent.intent;\n\t}\n\treturn (\n\t\tcompiledIntent.kind === 'mutation' &&\n\t\tsourceBundle.mutationBindings?.get(bindName) === compiledIntent.intent\n\t);\n}\n\nfunction orderedSequenceStepToProgramStep(\n\tstep: NonNullable<CompiledNqlQuery['nqlProgramSequence']>[number],\n): NqlProgramStep {\n\tconst dependencyStep = step as NqlProgramSequenceStepWithDependencies;\n\tif (step.kind === 'query') {\n\t\treturn {\n\t\t\tkind: 'query',\n\t\t\tintent: step.query as QueryIntent,\n\t\t\t...(step.bindName !== undefined && { bindName: step.bindName }),\n\t\t\tfinal: step.final,\n\t\t\t...(step.snapshot === true && { snapshot: true }),\n\t\t\t...(dependencyStep.bindingDependencies !== undefined && {\n\t\t\t\tbindingDependencies: dependencyStep.bindingDependencies,\n\t\t\t}),\n\t\t};\n\t}\n\treturn {\n\t\tkind: 'mutation',\n\t\tintent: step.mutation as MutationIntent,\n\t\t...(step.bindName !== undefined && { bindName: step.bindName }),\n\t\tfinal: step.final,\n\t\t...(dependencyStep.bindingDependencies !== undefined && {\n\t\t\tbindingDependencies: dependencyStep.bindingDependencies,\n\t\t}),\n\t};\n}\n\nconst structuredCloneFn = (\n\tglobalThis as {\n\t\treadonly structuredClone?: (value: unknown) => unknown;\n\t}\n).structuredClone;\n\n/**\n * Snapshot mutation RETURNING rows before afterMutation hooks can mutate them.\n *\n * The residual contract is per top-level column value: plain data\n * (objects/arrays/JSON values/Date/Map/Set) is deep-copied with\n * structuredClone, while values with a custom prototype are preserved by\n * reference. If structuredClone is unavailable or rejects a value, that value is\n * preserved by reference.\n */\nfunction hasCustomSnapshotPrototype(value: unknown): boolean {\n\tif (value === null || typeof value !== 'object') return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (\n\t\tprototype !== Object.prototype &&\n\t\tprototype !== null &&\n\t\tprototype !== Array.prototype &&\n\t\tprototype !== Date.prototype &&\n\t\tprototype !== Map.prototype &&\n\t\tprototype !== Set.prototype\n\t);\n}\n\nfunction cloneMutationSnapshotColumnValue(value: unknown): unknown {\n\tif (hasCustomSnapshotPrototype(value) || structuredCloneFn === undefined) {\n\t\treturn value;\n\t}\n\ttry {\n\t\treturn structuredCloneFn(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\nfunction snapshotMutationRows(rows: readonly unknown[]): unknown[] {\n\treturn rows.map((row) => {\n\t\tif (row === null || typeof row !== 'object') {\n\t\t\treturn cloneMutationSnapshotColumnValue(row);\n\t\t}\n\t\tconst snapshot = { ...(row as Record<PropertyKey, unknown>) } as Record<\n\t\t\tPropertyKey,\n\t\t\tunknown\n\t\t>;\n\t\tfor (const key of Reflect.ownKeys(snapshot)) {\n\t\t\tsnapshot[key] = cloneMutationSnapshotColumnValue(snapshot[key]);\n\t\t}\n\t\treturn snapshot;\n\t});\n}\n\nfunction assertNqlProgramSteps(\n\tcompiledIntent: CompiledNqlIntent,\n\tsteps: readonly NqlProgramStep[],\n): void {\n\tif (steps.length === 0) {\n\t\tthrow new Error('NQL program sequence did not contain any statements.');\n\t}\n\tconst finalIndexes = steps\n\t\t.map((step, index) => (step.final ? index : -1))\n\t\t.filter((index) => index !== -1);\n\tif (finalIndexes.length !== 1 || finalIndexes[0] !== steps.length - 1) {\n\t\tthrow new Error(\n\t\t\t'NQL program sequence must contain exactly one final statement at the end.',\n\t\t);\n\t}\n\tconst finalStep = steps.at(-1);\n\tif (finalStep === undefined) {\n\t\tthrow new Error('NQL program sequence did not contain a final statement.');\n\t}\n\tif (\n\t\tfinalStep.kind !== compiledIntent.kind ||\n\t\tfinalStep.intent !== compiledIntent.intent\n\t) {\n\t\tthrow new Error(\n\t\t\t'NQL program sequence final statement does not match the compiled NQL result.',\n\t\t);\n\t}\n\tconst seenBindNames = new Set<string>();\n\tfor (const step of steps) {\n\t\tif (step.kind === 'query' && step.snapshot === true) {\n\t\t\tif (step.bindName === undefined || step.final) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'NQL program sequence query snapshots must be named non-final statements.',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (step.bindName === undefined) continue;\n\t\tif (seenBindNames.has(step.bindName)) {\n\t\t\tthrow new Error(\n\t\t\t\t`NQL program sequence contains duplicate binding '${step.bindName}'.`,\n\t\t\t);\n\t\t}\n\t\tseenBindNames.add(step.bindName);\n\t\tif (!(compiledIntent.bundle.bindings?.has(step.bindName) ?? false)) {\n\t\t\tthrow new Error(\n\t\t\t\t`NQL program sequence references unknown binding '${step.bindName}'.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction createNqlProgramSteps(\n\tcompiledIntent: CompiledNqlIntent,\n): readonly NqlProgramStep[] {\n\tconst sourceBundle = compiledIntent.bundle;\n\tif (sourceBundle.nqlProgramSequence !== undefined) {\n\t\tconst steps = sourceBundle.nqlProgramSequence.map(\n\t\t\torderedSequenceStepToProgramStep,\n\t\t);\n\t\tassertNqlProgramSteps(compiledIntent, steps);\n\t\treturn steps;\n\t}\n\n\tconst bindingEntries = [...(sourceBundle.bindings ?? new Map())];\n\tconst steps: NqlProgramStep[] = bindingEntries.map(\n\t\t([bindName, boundQuery]) => {\n\t\t\tconst boundMutation = sourceBundle.mutationBindings?.get(bindName);\n\t\t\tif (boundMutation !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: 'mutation',\n\t\t\t\t\tintent: boundMutation as MutationIntent,\n\t\t\t\t\tbindName,\n\t\t\t\t\tfinal: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: 'query',\n\t\t\t\tintent: boundQuery as QueryIntent,\n\t\t\t\tbindName,\n\t\t\t\tfinal: false,\n\t\t\t};\n\t\t},\n\t);\n\n\tconst lastBindingEntry = bindingEntries.at(-1);\n\tconst finalIsBound =\n\t\tlastBindingEntry !== undefined &&\n\t\tbindingEntryIsFinal(\n\t\t\tcompiledIntent,\n\t\t\tlastBindingEntry[0],\n\t\t\tlastBindingEntry[1] as QueryIntent,\n\t\t\tsourceBundle,\n\t\t);\n\n\tif (finalIsBound) {\n\t\tconst lastStep = steps.at(-1);\n\t\tif (lastStep === undefined) return steps;\n\t\tsteps[steps.length - 1] = { ...lastStep, final: true };\n\t\treturn steps;\n\t}\n\n\tif (compiledIntent.kind === 'query') {\n\t\tsteps.push({\n\t\t\tkind: 'query',\n\t\t\tintent: compiledIntent.intent,\n\t\t\tfinal: true,\n\t\t});\n\t} else if (compiledIntent.kind === 'mutation') {\n\t\tsteps.push({\n\t\t\tkind: 'mutation',\n\t\t\tintent: compiledIntent.intent,\n\t\t\tfinal: true,\n\t\t});\n\t} else {\n\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t}\n\tassertNqlProgramSteps(compiledIntent, steps);\n\treturn steps;\n}\n\nfunction renumberDumpSqlParams(sql: string, offset: number): string {\n\tif (offset === 0) return sql;\n\treturn sql.replace(/\\$(\\d+)/g, (_match, num) => {\n\t\treturn `$${Number.parseInt(num, 10) + offset}`;\n\t});\n}\n\nfunction joinDumpSequenceSql(sequence: readonly DumpSequenceStep[]): string {\n\tlet parameterOffset = 0;\n\treturn sequence\n\t\t.map((step) => {\n\t\t\tconst sql = renumberDumpSqlParams(step.sql, parameterOffset);\n\t\t\tparameterOffset += step.params.length;\n\t\t\treturn sql;\n\t\t})\n\t\t.join(';\\n');\n}\n\nfunction flattenDumpSequenceParams(\n\tsequence: readonly DumpSequenceStep[],\n): readonly unknown[] {\n\treturn sequence.flatMap((step) => [...step.params]);\n}\n\nfunction filterMapByBindingDependencies<T>(\n\tsource: ReadonlyMap<string, T> | undefined,\n\tbindingDependencies: readonly string[] | undefined,\n): Map<string, T> {\n\tif (source === undefined) return new Map();\n\tif (bindingDependencies === undefined) return new Map(source);\n\tconst filtered = new Map<string, T>();\n\tfor (const bindName of bindingDependencies) {\n\t\tconst value = source.get(bindName);\n\t\tif (value !== undefined) {\n\t\t\tfiltered.set(bindName, value);\n\t\t}\n\t}\n\treturn filtered;\n}\n\nfunction filterOptionalMapByBindingDependencies<T>(\n\tsource: ReadonlyMap<string, T> | undefined,\n\tbindingDependencies: readonly string[] | undefined,\n): ReadonlyMap<string, T> | undefined {\n\tconst filtered = filterMapByBindingDependencies(source, bindingDependencies);\n\treturn filtered.size > 0 ? filtered : undefined;\n}\n\nfunction runtimeSourceBindingNames(\n\tsourceBundle: CompiledNqlQuery,\n): ReadonlySet<string> | undefined {\n\tconst names = new Set<string>();\n\tfor (const name of sourceBundle.mutationBindings?.keys() ?? []) {\n\t\tnames.add(name);\n\t}\n\tfor (const step of sourceBundle.nqlProgramSequence ?? []) {\n\t\tif (\n\t\t\tstep.kind === 'query' &&\n\t\t\tstep.snapshot === true &&\n\t\t\tstep.bindName !== undefined\n\t\t) {\n\t\t\tnames.add(step.bindName);\n\t\t}\n\t}\n\treturn names.size > 0 ? names : undefined;\n}\n\n// Inline read bindings are cheap SQL CTEs and remain always-emitted; bindings\n// materialized into runtime VALUES rows are dependency-filtered.\nfunction filterMapByRuntimeBindingDependencies<T>(\n\tsource: ReadonlyMap<string, T> | undefined,\n\truntimeSourceBindings: ReadonlySet<string> | undefined,\n\tbindingDependencies: readonly string[] | undefined,\n): Map<string, T> {\n\tif (source === undefined) return new Map();\n\tif (\n\t\tbindingDependencies === undefined ||\n\t\truntimeSourceBindings === undefined ||\n\t\truntimeSourceBindings.size === 0\n\t) {\n\t\treturn new Map(source);\n\t}\n\n\tconst dependencies = new Set(bindingDependencies);\n\tconst filtered = new Map<string, T>();\n\tfor (const [bindName, value] of source) {\n\t\tif (!runtimeSourceBindings.has(bindName) || dependencies.has(bindName)) {\n\t\t\tfiltered.set(bindName, value);\n\t\t}\n\t}\n\treturn filtered;\n}\n\nfunction filterOptionalMapByNames<T>(\n\tsource: ReadonlyMap<string, T> | undefined,\n\tnames: Iterable<string>,\n): ReadonlyMap<string, T> | undefined {\n\tif (source === undefined) return undefined;\n\tconst filtered = new Map<string, T>();\n\tfor (const name of names) {\n\t\tconst value = source.get(name);\n\t\tif (value !== undefined) {\n\t\t\tfiltered.set(name, value);\n\t\t}\n\t}\n\treturn filtered.size > 0 ? filtered : undefined;\n}\n\n/**\n * Create an NQL template tag function.\n *\n * Each non-raw `${value}` in the template is bound as a generated named param.\n * Use `nqlRaw()` only for trusted dynamic NQL structure.\n *\n * @param schemaDefinition - Schema definition for validation\n * @param model - ModelIR for plan execution\n * @param adapter - Optional adapter for query execution\n * @param schemaName - Optional schema name for multi-tenant queries\n * @param hookStore - Optional hook storage for query and mutation hooks\n * @param onHookError - Optional control-flow handler for hook failures\n * @param inTransaction - Whether execution is already within a transaction\n * @param onObserverError - Optional non-fatal diagnostic sink for observer failures\n * @returns NQL template tag function\n */\nexport function createNqlTag(\n\t_schemaDefinition: unknown,\n\tmodel: ModelIR,\n\tadapter?: Adapter<unknown>,\n\tschemaName?: string,\n\thookStore?: HookStore,\n\tonHookError?: HookErrorHandler,\n\tinTransaction?: boolean,\n\tonObserverError?: ObserverErrorHandler,\n): NqlTag {\n\treturn function nql<T>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: unknown[]\n\t): NqlBuilder<T> {\n\t\tconst assembled = assembleNqlTemplate(strings, values);\n\n\t\treturn new NqlBuilderImpl<T>(\n\t\t\tassembled.query,\n\t\t\tassembled.params,\n\t\t\tassembled.hasBoundParams,\n\t\t\tassembled.sourceError,\n\t\t\tmodel,\n\t\t\tadapter,\n\t\t\tschemaName,\n\t\t\thookStore,\n\t\t\tonHookError,\n\t\t\tonObserverError,\n\t\t\tinTransaction,\n\t\t);\n\t};\n}\n\n/**\n * NQL builder implementation.\n * @internal\n */\nclass NqlBuilderImpl<T> implements NqlBuilder<T> {\n\tprivate _compiled: CompiledNqlIntent | undefined;\n\tprivate readonly query: string;\n\tprivate readonly params: Readonly<Record<string, unknown>>;\n\tprivate readonly hasBoundParams: boolean;\n\tprivate readonly sourceError: string | undefined;\n\tprivate readonly model: ModelIR;\n\tprivate readonly _schemaName: string | undefined;\n\tprivate readonly adapter: Adapter<unknown> | undefined;\n\tprivate readonly hookStore: HookStore | undefined;\n\tprivate readonly onHookError: HookErrorHandler | undefined;\n\tprivate readonly onObserverError: ObserverErrorHandler | undefined;\n\tprivate readonly inTransaction: boolean | undefined;\n\n\tconstructor(\n\t\tquery: string,\n\t\tparams: Readonly<Record<string, unknown>>,\n\t\thasBoundParams: boolean,\n\t\tsourceError: string | undefined,\n\t\tmodel: ModelIR,\n\t\tadapter: Adapter<unknown> | undefined,\n\t\tschemaName: string | undefined,\n\t\thookStore: HookStore | undefined,\n\t\tonHookError: HookErrorHandler | undefined,\n\t\tonObserverError: ObserverErrorHandler | undefined,\n\t\tinTransaction: boolean | undefined,\n\t) {\n\t\tthis.query = query;\n\t\tthis.params = params;\n\t\tthis.hasBoundParams = hasBoundParams;\n\t\tthis.sourceError = sourceError;\n\t\tthis.model = model;\n\t\tthis.adapter = adapter;\n\t\tthis._schemaName = schemaName;\n\t\tthis.hookStore = hookStore;\n\t\tthis.onHookError = onHookError;\n\t\tthis.onObserverError = onObserverError;\n\t\tthis.inTransaction = inTransaction;\n\t}\n\n\tprivate compile(): CompiledNqlIntent {\n\t\tif (this._compiled) {\n\t\t\treturn this._compiled;\n\t\t}\n\n\t\tif (this.sourceError !== undefined) {\n\t\t\tthrow new Error(`NQL compilation failed: ${this.sourceError}`);\n\t\t}\n\n\t\t// Extract dynamic pseudo-column keywords from model configuration\n\t\tconst compilerOptions = {\n\t\t\t...(extractPseudoColumnKeywords(this.model) ?? {}),\n\t\t\tparams: this.params,\n\t\t\t[NQL_INTERNAL_COMPILER_OPTIONS]: { allowInternalParams: true },\n\t\t} satisfies NqlCompilerOptions & {\n\t\t\treadonly [NQL_INTERNAL_COMPILER_OPTIONS]: {\n\t\t\t\treadonly allowInternalParams: true;\n\t\t\t};\n\t\t};\n\n\t\t// Use integrated @dbsp/nql compiler with dynamic keywords\n\t\tconst result = nqlCompile(\n\t\t\tthis.query,\n\t\t\tthis.model,\n\t\t\tundefined,\n\t\t\tcompilerOptions,\n\t\t);\n\t\tif (!result.success) {\n\t\t\tconst errors =\n\t\t\t\tresult.errors?.map((e) => e.message).join(', ') ?? 'Unknown error';\n\t\t\tconst rawHint = this.hasBoundParams\n\t\t\t\t? ' If an interpolation was intended as NQL structure, wrap a trusted fragment with nqlRaw().'\n\t\t\t\t: '';\n\t\t\tthrow new Error(`NQL compilation failed: ${errors}${rawHint}`);\n\t\t}\n\t\tconst bundle = result.ast;\n\t\tif (!bundle) {\n\t\t\tthrow new Error('NQL compilation failed: no query AST produced');\n\t\t}\n\t\tif (bundle.query) {\n\t\t\t// Type assertion: NQL imports QueryIntent from @dbsp/types (ARCH-007),\n\t\t\t// structurally identical to core's re-export.\n\t\t\tthis._compiled = {\n\t\t\t\tkind: 'query',\n\t\t\t\tbundle,\n\t\t\t\tintent: bundle.query as QueryIntent,\n\t\t\t};\n\t\t\treturn this._compiled;\n\t\t}\n\t\tif (bundle.mutation) {\n\t\t\tthis._compiled = {\n\t\t\t\tkind: 'mutation',\n\t\t\t\tbundle,\n\t\t\t\tintent: bundle.mutation as MutationIntent,\n\t\t\t};\n\t\t\treturn this._compiled;\n\t\t}\n\t\tif (bundle.cteQuery !== undefined) {\n\t\t\tthis._compiled = {\n\t\t\t\tkind: 'unplannedRead',\n\t\t\t\tbundle,\n\t\t\t\tintent: bundle.cteQuery,\n\t\t\t};\n\t\t\treturn this._compiled;\n\t\t}\n\t\tif (bundle.setOperation !== undefined) {\n\t\t\tthis._compiled = {\n\t\t\t\tkind: 'unplannedRead',\n\t\t\t\tbundle,\n\t\t\t\tintent: bundle.setOperation,\n\t\t\t};\n\t\t\treturn this._compiled;\n\t\t}\n\t\tthrow new Error('NQL compilation failed: no query AST produced');\n\t}\n\n\ttoIntentIR(): QueryIntent | MutationIntent {\n\t\tconst compiled = this.compile();\n\t\tif (compiled.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_INTENT_ERROR);\n\t\t}\n\t\treturn compiled.intent;\n\t}\n\n\tprivate planInternal(): PlanReport {\n\t\tconst compiled = this.compile();\n\t\tif (compiled.kind === 'mutation') {\n\t\t\tthrow new Error(\n\t\t\t\t'NQL mutations do not have execution plans; use dump() for SQL and parameters.',\n\t\t\t);\n\t\t}\n\t\tif (compiled.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PLAN_ERROR);\n\t\t}\n\t\treturn executePlan(compiled.intent, this.model);\n\t}\n\n\tplan(): PlanReport {\n\t\tconst compiled = this.compile();\n\t\tif (compiled.kind === 'mutation') {\n\t\t\tthrow new Error(\n\t\t\t\t'NQL mutations do not have execution plans; use dump() for SQL and parameters.',\n\t\t\t);\n\t\t}\n\t\tif (compiled.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PLAN_ERROR);\n\t\t}\n\t\treturn isBindingFinalQuery(compiled.bundle)\n\t\t\t? createBindingFinalPlan(\n\t\t\t\t\tcompiled.intent,\n\t\t\t\t\tcompiled.bundle,\n\t\t\t\t\tthis.model,\n\t\t\t\t\tthis.adapter?.dialectCapabilities,\n\t\t\t\t)\n\t\t\t: this.planInternal();\n\t}\n\n\tdump(meta?: DumpMetaInput): Dump | MutationDump {\n\t\tconst compiledIntent = this.compile();\n\t\tif (\n\t\t\tcompiledIntent.kind === 'unplannedRead' &&\n\t\t\thasExecutableNqlProgramSequence(compiledIntent.bundle)\n\t\t) {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t\t}\n\t\tif (compiledIntent.kind === 'unplannedRead') {\n\t\t\treturn this.dumpUnplannedNqlRead(compiledIntent.bundle, meta);\n\t\t}\n\t\tif (hasExecutableNqlProgramSequence(compiledIntent.bundle)) {\n\t\t\treturn this.dumpNqlProgramSequence(compiledIntent, meta);\n\t\t}\n\t\tif (compiledIntent.kind === 'mutation') {\n\t\t\treturn this.dumpMutation(\n\t\t\t\tthis.createFinalNqlStatementBundle(compiledIntent),\n\t\t\t\tcompiledIntent.intent,\n\t\t\t\tmeta,\n\t\t\t);\n\t\t}\n\n\t\tconst bindingFinalQuery = isBindingFinalQuery(compiledIntent.bundle);\n\t\tconst planReport = bindingFinalQuery\n\t\t\t? createBindingFinalPlan(\n\t\t\t\t\tcompiledIntent.intent,\n\t\t\t\t\tcompiledIntent.bundle,\n\t\t\t\t\tthis.model,\n\t\t\t\t\tthis.adapter?.dialectCapabilities,\n\t\t\t\t)\n\t\t\t: this.planInternal();\n\n\t\tif (!this.adapter) {\n\t\t\treturn {\n\t\t\t\tplan: planReport,\n\t\t\t\tsql: '[No adapter - SQL not available]',\n\t\t\t\tparams: [],\n\t\t\t\t...(meta !== undefined && { meta }),\n\t\t\t};\n\t\t}\n\n\t\tconst finalBundle = this.createFinalNqlStatementBundle(\n\t\t\tcompiledIntent,\n\t\t\tbindingFinalPlanHasJsonAggIncludes(planReport) ? planReport : undefined,\n\t\t);\n\t\tconst compiled =\n\t\t\tbindingFinalQuery || hasNqlBindings(finalBundle)\n\t\t\t\t? this.adapter.compile<T>(finalBundle, this.nqlBundleCompileOptions())\n\t\t\t\t: this.adapter.compile<T>(planReport);\n\n\t\ttry {\n\t\t\treturn this.adapter.createDump(planReport, compiled, meta);\n\t\t} catch (err) {\n\t\t\tif (\n\t\t\t\terr instanceof Error &&\n\t\t\t\terr.message.toLowerCase().includes('not implemented')\n\t\t\t) {\n\t\t\t\t// Fallback for mock adapters that don't implement createDump\n\t\t\t\tconst base: Dump = {\n\t\t\t\t\tplan: planReport,\n\t\t\t\t\tsql: compiled.sql,\n\t\t\t\t\tparams: compiled.parameters as readonly unknown[],\n\t\t\t\t};\n\t\t\t\tif (meta !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\t...(meta.queryName !== undefined && {\n\t\t\t\t\t\t\t\tqueryName: meta.queryName,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(meta.correlationId !== undefined && {\n\t\t\t\t\t\t\t\tcorrelationId: meta.correlationId,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn base;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate dumpUnplannedNqlRead(\n\t\tbundle: CompiledNqlQuery,\n\t\tmeta?: DumpMetaInput,\n\t): Dump {\n\t\tif (!this.adapter) {\n\t\t\treturn {\n\t\t\t\tsql: '[No adapter - SQL not available]',\n\t\t\t\tparams: [],\n\t\t\t\t...(meta !== undefined && { meta }),\n\t\t\t};\n\t\t}\n\n\t\tconst compiled = this.adapter.compile<T>(\n\t\t\tbundle,\n\t\t\tthis.nqlBundleCompileOptions(),\n\t\t);\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparams: compiled.parameters as readonly unknown[],\n\t\t\tmeta: {\n\t\t\t\t...(this._schemaName !== undefined && { schema: this._schemaName }),\n\t\t\t\tcompiledAt: new Date(),\n\t\t\t\t...meta,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate requireAdapter(operation: string): Adapter<unknown> {\n\t\tif (!this.adapter) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation,\n\t\t\t\treason: 'Adapter not configured',\n\t\t\t\tfix: 'Pass adapter option when creating ORM: createOrm({ model, adapter })',\n\t\t\t});\n\t\t}\n\t\treturn this.adapter;\n\t}\n\n\tprivate mutationCompileOptions(extraOptions?: DumpMetaInput): CompileOptions {\n\t\treturn {\n\t\t\tmodel: this.model,\n\t\t\t...(this._schemaName !== undefined && { schemaName: this._schemaName }),\n\t\t\t...extraOptions,\n\t\t};\n\t}\n\n\tprivate nqlBundleCompileOptions(): CompileOptions {\n\t\treturn {\n\t\t\tmodel: this.model,\n\t\t\t...(this._schemaName !== undefined && { schemaName: this._schemaName }),\n\t\t};\n\t}\n\n\tprivate createNqlStatementBundle(\n\t\tstatement:\n\t\t\t| { readonly query: QueryIntent }\n\t\t\t| { readonly mutation: MutationIntent },\n\t\tbindings: ReadonlyMap<string, QueryIntent>,\n\t\truntimeBindings: ReadonlyMap<string, NqlRuntimeBinding>,\n\t\tsourceBundle: CompiledNqlQuery,\n\t\tbindingDependencies?: readonly string[],\n\t\tplanReport?: PlanReport,\n\t): CompiledNqlQuery {\n\t\tconst statementBindings = filterMapByRuntimeBindingDependencies(\n\t\t\tbindings,\n\t\t\truntimeSourceBindingNames(sourceBundle),\n\t\t\tbindingDependencies,\n\t\t);\n\t\tconst statementRuntimeBindings = filterMapByBindingDependencies(\n\t\t\truntimeBindings,\n\t\t\tbindingDependencies,\n\t\t);\n\t\tconst emittedBindingNames = new Set([\n\t\t\t...statementBindings.keys(),\n\t\t\t...statementRuntimeBindings.keys(),\n\t\t]);\n\t\tconst statementBindingOutputSchemas = filterOptionalMapByNames(\n\t\t\tsourceBundle.bindingOutputSchemas,\n\t\t\temittedBindingNames,\n\t\t);\n\t\tconst statementMutationBindings = filterOptionalMapByBindingDependencies(\n\t\t\tsourceBundle.mutationBindings,\n\t\t\tbindingDependencies,\n\t\t);\n\t\treturn {\n\t\t\t...statement,\n\t\t\t...(planReport !== undefined && { plan: planReport }),\n\t\t\t...(statementBindings.size > 0 && { bindings: statementBindings }),\n\t\t\t...(statementBindingOutputSchemas !== undefined && {\n\t\t\t\tbindingOutputSchemas: statementBindingOutputSchemas,\n\t\t\t}),\n\t\t\t...(statementMutationBindings !== undefined && {\n\t\t\t\tmutationBindings: statementMutationBindings,\n\t\t\t}),\n\t\t\t...(statementRuntimeBindings.size > 0 && {\n\t\t\t\truntimeBindings: statementRuntimeBindings,\n\t\t\t}),\n\t\t};\n\t}\n\n\tprivate createFinalNqlStatementBundle(\n\t\tcompiledIntent: CompiledNqlIntent,\n\t\tplanReport?: PlanReport,\n\t): CompiledNqlQuery {\n\t\tif (compiledIntent.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t\t}\n\t\tconst finalStep = createNqlProgramSteps(compiledIntent).at(-1);\n\t\tif (compiledIntent.kind === 'query') {\n\t\t\treturn this.createNqlStatementBundle(\n\t\t\t\t{ query: compiledIntent.intent },\n\t\t\t\tcompiledIntent.bundle.bindings ?? new Map(),\n\t\t\t\tcompiledIntent.bundle.runtimeBindings ?? new Map(),\n\t\t\t\tcompiledIntent.bundle,\n\t\t\t\tfinalStep?.bindingDependencies,\n\t\t\t\tplanReport,\n\t\t\t);\n\t\t}\n\t\treturn this.createNqlStatementBundle(\n\t\t\t{ mutation: compiledIntent.intent },\n\t\t\tcompiledIntent.bundle.bindings ?? new Map(),\n\t\t\tcompiledIntent.bundle.runtimeBindings ?? new Map(),\n\t\t\tcompiledIntent.bundle,\n\t\t\tfinalStep?.bindingDependencies,\n\t\t\tplanReport,\n\t\t);\n\t}\n\n\tprivate runMutationStatement(\n\t\tadapter: Adapter<unknown>,\n\t\tbundle: CompiledNqlQuery,\n\t\tintent: MutationIntent,\n\t\tinTransaction: boolean | undefined,\n\t): Promise<NqlMutationStatementResult> {\n\t\tconst hasReturning = (intent.returning?.length ?? 0) > 0;\n\t\treturn runMutationWithHooks<NqlMutationStatementExecution, MutationIntent>({\n\t\t\ttable: intent.table,\n\t\t\tintent,\n\t\t\thookStore: this.hookStore,\n\t\t\tonHookError: this.onHookError,\n\t\t\tonObserverError: this.onObserverError,\n\t\t\tschemaName: this._schemaName,\n\t\t\tinTransaction,\n\t\t\tprepare: () => {\n\t\t\t\tconst compiled = adapter.compile<unknown[]>(\n\t\t\t\t\tbundle,\n\t\t\t\t\tthis.mutationCompileOptions(),\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tsql: compiled.sql,\n\t\t\t\t\tparameters: compiled.parameters,\n\t\t\t\t\texecute: async () => {\n\t\t\t\t\t\tif (typeof adapter.executeWithMeta === 'function') {\n\t\t\t\t\t\t\tconst metadata = await executeCompiledQueryWithMeta(\n\t\t\t\t\t\t\t\tadapter,\n\t\t\t\t\t\t\t\tcompiled,\n\t\t\t\t\t\t\t\t'nql().all()',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst hookRows = metadata.rows as unknown[];\n\t\t\t\t\t\t\tconst rawRows = snapshotMutationRows(hookRows);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\trawRows,\n\t\t\t\t\t\t\t\t\thookRows,\n\t\t\t\t\t\t\t\t\ttransformedRows: hookRows,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\taffectedRows: metadata.rowCount,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst hookRows = (await executeCompiledQuery(\n\t\t\t\t\t\t\tadapter,\n\t\t\t\t\t\t\tcompiled,\n\t\t\t\t\t\t\t'nql().all()',\n\t\t\t\t\t\t)) as unknown[];\n\t\t\t\t\t\tconst rawRows = snapshotMutationRows(hookRows);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\trawRows,\n\t\t\t\t\t\t\t\thookRows,\n\t\t\t\t\t\t\t\ttransformedRows: hookRows,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tgetAfterMutationResult: (result) =>\n\t\t\t\t\t\thasReturning ? result.hookRows : [],\n\t\t\t\t\tmapAfterMutationResult: (result, transformedRows) => ({\n\t\t\t\t\t\trawRows: result.rawRows,\n\t\t\t\t\t\thookRows: result.hookRows,\n\t\t\t\t\t\ttransformedRows: [...transformedRows],\n\t\t\t\t\t}),\n\t\t\t\t\treturnAfterMutationResult: hasReturning,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async executeNqlProgramSequence(\n\t\tcompiledIntent: CompiledNqlIntent,\n\t\tadapter: Adapter<unknown>,\n\t): Promise<T[]> {\n\t\tif (compiledIntent.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t\t}\n\t\tassertConnectionAvailable(adapter, 'nql().all()');\n\t\tif (!supportsTransactions(adapter)) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation: 'nql',\n\t\t\t\treason:\n\t\t\t\t\t'NQL programs with mutation bindings require adapter transaction support',\n\t\t\t\tfix: 'Use an adapter that implements transaction(fn), such as the PostgreSQL adapter.',\n\t\t\t});\n\t\t}\n\n\t\treturn adapter.transaction(async (txAdapter) => {\n\t\t\tconst sourceBundle = compiledIntent.bundle;\n\t\t\tconst priorBindings = new Map<string, QueryIntent>();\n\t\t\tconst runtimeBindings = new Map<string, NqlRuntimeBinding>();\n\t\t\tconst steps = createNqlProgramSteps(compiledIntent);\n\t\t\tlet finalRows: unknown[] = [];\n\n\t\t\tfor (const step of steps) {\n\t\t\t\tif (step.kind === 'mutation') {\n\t\t\t\t\tif ((step.intent.returning?.length ?? 0) === 0 && step.bindName) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`NQL mutation binding '${step.bindName}' cannot execute without a RETURNING projection.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst statementBundle = this.createNqlStatementBundle(\n\t\t\t\t\t\t{ mutation: step.intent },\n\t\t\t\t\t\tpriorBindings,\n\t\t\t\t\t\truntimeBindings,\n\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\tstep.bindingDependencies,\n\t\t\t\t\t);\n\t\t\t\t\tconst rows = await this.runMutationStatement(\n\t\t\t\t\t\ttxAdapter as Adapter<unknown>,\n\t\t\t\t\t\tstatementBundle,\n\t\t\t\t\t\tstep.intent,\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t);\n\t\t\t\t\tif (step.bindName) {\n\t\t\t\t\t\truntimeBindings.set(\n\t\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\t\tcreateRuntimeBinding(\n\t\t\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\t\t\trows.rawRows,\n\t\t\t\t\t\t\t\ttxAdapter.dbCasing,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (step.final) {\n\t\t\t\t\t\tfinalRows = rows.transformedRows;\n\t\t\t\t\t}\n\t\t\t\t} else if (step.snapshot === true && step.bindName !== undefined) {\n\t\t\t\t\tconst statementBundle = this.createNqlStatementBundle(\n\t\t\t\t\t\t{ query: step.intent },\n\t\t\t\t\t\tpriorBindings,\n\t\t\t\t\t\truntimeBindings,\n\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\tstep.bindingDependencies,\n\t\t\t\t\t);\n\t\t\t\t\tconst compiled = txAdapter.compile<unknown[]>(\n\t\t\t\t\t\tstatementBundle,\n\t\t\t\t\t\tthis.nqlBundleCompileOptions(),\n\t\t\t\t\t);\n\t\t\t\t\tconst rows = await txAdapter.execute(compiled);\n\t\t\t\t\truntimeBindings.set(\n\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\tcreateRuntimeBinding(\n\t\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\t\tsnapshotMutationRows(rows),\n\t\t\t\t\t\t\ttxAdapter.dbCasing,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else if (step.final) {\n\t\t\t\t\tconst planReport =\n\t\t\t\t\t\tisBindingFinalQuery(compiledIntent.bundle) &&\n\t\t\t\t\t\tcompiledIntent.kind === 'query'\n\t\t\t\t\t\t\t? createBindingFinalPlan(\n\t\t\t\t\t\t\t\t\tstep.intent,\n\t\t\t\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\t\t\t\tthis.model,\n\t\t\t\t\t\t\t\t\ttxAdapter.dialectCapabilities,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst statementBundle = this.createNqlStatementBundle(\n\t\t\t\t\t\t{ query: step.intent },\n\t\t\t\t\t\tpriorBindings,\n\t\t\t\t\t\truntimeBindings,\n\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\tstep.bindingDependencies,\n\t\t\t\t\t\tplanReport !== undefined &&\n\t\t\t\t\t\t\tbindingFinalPlanHasJsonAggIncludes(planReport)\n\t\t\t\t\t\t\t? planReport\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t);\n\t\t\t\t\tconst compiled = txAdapter.compile<T>(\n\t\t\t\t\t\tstatementBundle,\n\t\t\t\t\t\tthis.nqlBundleCompileOptions(),\n\t\t\t\t\t);\n\t\t\t\t\tfinalRows = await txAdapter.execute(compiled);\n\t\t\t\t\tif (\n\t\t\t\t\t\tplanReport !== undefined &&\n\t\t\t\t\t\tbindingFinalPlanHasJsonAggIncludes(planReport)\n\t\t\t\t\t) {\n\t\t\t\t\t\thydrateJsonAggIncludes(\n\t\t\t\t\t\t\tfinalRows as T[],\n\t\t\t\t\t\t\tplanForJsonAggHydration(planReport, compiled),\n\t\t\t\t\t\t\tthis.model,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (step.bindName) {\n\t\t\t\t\tconst boundQuery = sourceBundle.bindings?.get(step.bindName);\n\t\t\t\t\tif (boundQuery !== undefined) {\n\t\t\t\t\t\tpriorBindings.set(step.bindName, boundQuery as QueryIntent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn finalRows as T[];\n\t\t});\n\t}\n\n\tprivate dumpNqlProgramSequence(\n\t\tcompiledIntent: CompiledNqlIntent,\n\t\tmeta?: DumpMetaInput,\n\t): Dump | MutationDump {\n\t\tif (compiledIntent.kind === 'unplannedRead') {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t\t}\n\t\tconst adapter = this.requireAdapter('dump');\n\t\tconst sourceBundle = compiledIntent.bundle;\n\t\tconst priorBindings = new Map<string, QueryIntent>();\n\t\tconst runtimeBindings = new Map<string, NqlRuntimeBinding>();\n\t\tconst sequence: DumpSequenceStep[] = [];\n\t\tconst steps = createNqlProgramSteps(compiledIntent);\n\n\t\tconst dumpRuntimeBindingPreview = (bindName: string): NqlRuntimeBinding => {\n\t\t\tconst outputSchema = sourceBundle.bindingOutputSchemas?.get(bindName);\n\t\t\tconst columnTypes = outputSchema?.columnTypes;\n\t\t\tconst declaredOutputs = outputSchema?.declaredOutputs;\n\t\t\treturn {\n\t\t\t\tcolumns: requireMutationBindingColumns(sourceBundle, bindName),\n\t\t\t\trows: [],\n\t\t\t\t...(declaredOutputs !== undefined && { declaredOutputs }),\n\t\t\t\t...(columnTypes !== undefined && { columnTypes }),\n\t\t\t};\n\t\t};\n\n\t\tfor (const step of steps) {\n\t\t\tif (step.kind === 'mutation') {\n\t\t\t\tconst statementBundle = this.createNqlStatementBundle(\n\t\t\t\t\t{ mutation: step.intent },\n\t\t\t\t\tpriorBindings,\n\t\t\t\t\truntimeBindings,\n\t\t\t\t\tsourceBundle,\n\t\t\t\t\tstep.bindingDependencies,\n\t\t\t\t);\n\t\t\t\tconst compiled = adapter.compile(\n\t\t\t\t\tstatementBundle,\n\t\t\t\t\tthis.mutationCompileOptions(),\n\t\t\t\t);\n\t\t\t\tsequence.push({\n\t\t\t\t\tkind: 'mutation',\n\t\t\t\t\t...(step.bindName !== undefined && { bindName: step.bindName }),\n\t\t\t\t\tsql: compiled.sql,\n\t\t\t\t\tparams: compiled.parameters,\n\t\t\t\t});\n\t\t\t\tif (step.bindName !== undefined) {\n\t\t\t\t\truntimeBindings.set(\n\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\tdumpRuntimeBindingPreview(step.bindName),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst planReport =\n\t\t\t\t\tstep.final &&\n\t\t\t\t\tisBindingFinalQuery(compiledIntent.bundle) &&\n\t\t\t\t\tcompiledIntent.kind === 'query'\n\t\t\t\t\t\t? createBindingFinalPlan(\n\t\t\t\t\t\t\t\tstep.intent,\n\t\t\t\t\t\t\t\tsourceBundle,\n\t\t\t\t\t\t\t\tthis.model,\n\t\t\t\t\t\t\t\tadapter.dialectCapabilities,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst statementBundle = this.createNqlStatementBundle(\n\t\t\t\t\t{ query: step.intent },\n\t\t\t\t\tpriorBindings,\n\t\t\t\t\truntimeBindings,\n\t\t\t\t\tsourceBundle,\n\t\t\t\t\tstep.bindingDependencies,\n\t\t\t\t\tplanReport !== undefined &&\n\t\t\t\t\t\tbindingFinalPlanHasJsonAggIncludes(planReport)\n\t\t\t\t\t\t? planReport\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t\tconst compiled = adapter.compile(\n\t\t\t\t\tstatementBundle,\n\t\t\t\t\tthis.nqlBundleCompileOptions(),\n\t\t\t\t);\n\t\t\t\tsequence.push({\n\t\t\t\t\tkind: 'query',\n\t\t\t\t\t...(step.bindName !== undefined && { bindName: step.bindName }),\n\t\t\t\t\tsql: compiled.sql,\n\t\t\t\t\tparams: compiled.parameters,\n\t\t\t\t});\n\t\t\t\tif (step.snapshot === true && step.bindName !== undefined) {\n\t\t\t\t\truntimeBindings.set(\n\t\t\t\t\t\tstep.bindName,\n\t\t\t\t\t\tdumpRuntimeBindingPreview(step.bindName),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (step.bindName !== undefined) {\n\t\t\t\tconst boundQuery = sourceBundle.bindings?.get(step.bindName);\n\t\t\t\tif (boundQuery !== undefined) {\n\t\t\t\t\tpriorBindings.set(step.bindName, boundQuery as QueryIntent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst finalStep = steps.at(-1);\n\t\tif (finalStep?.kind === 'query') {\n\t\t\tconst planReport = isBindingFinalQuery(compiledIntent.bundle)\n\t\t\t\t? createBindingFinalPlan(\n\t\t\t\t\t\tfinalStep.intent,\n\t\t\t\t\t\tcompiledIntent.bundle,\n\t\t\t\t\t\tthis.model,\n\t\t\t\t\t\tthis.adapter?.dialectCapabilities,\n\t\t\t\t\t)\n\t\t\t\t: this.planInternal();\n\t\t\tconst dumpMeta: DumpMeta = {\n\t\t\t\tcompiledAt: new Date(),\n\t\t\t\t...(this._schemaName !== undefined && { schema: this._schemaName }),\n\t\t\t\t...(meta?.queryName !== undefined && { queryName: meta.queryName }),\n\t\t\t\t...(meta?.correlationId !== undefined && {\n\t\t\t\t\tcorrelationId: meta.correlationId,\n\t\t\t\t}),\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tplan: planReport,\n\t\t\t\tsql: joinDumpSequenceSql(sequence),\n\t\t\t\tparams: flattenDumpSequenceParams(sequence),\n\t\t\t\tmeta: dumpMeta,\n\t\t\t\tsequence,\n\t\t\t};\n\t\t}\n\t\tif (finalStep?.kind !== 'mutation') {\n\t\t\tthrow new Error(\n\t\t\t\t'NQL program sequence did not contain a final statement.',\n\t\t\t);\n\t\t}\n\n\t\tconst dumpMeta: DumpMeta = {\n\t\t\tcompiledAt: new Date(),\n\t\t\t...(this._schemaName !== undefined && { schema: this._schemaName }),\n\t\t\t...(meta?.queryName !== undefined && { queryName: meta.queryName }),\n\t\t\t...(meta?.correlationId !== undefined && {\n\t\t\t\tcorrelationId: meta.correlationId,\n\t\t\t}),\n\t\t};\n\n\t\treturn {\n\t\t\tsql: joinDumpSequenceSql(sequence),\n\t\t\tparameters: flattenDumpSequenceParams(sequence),\n\t\t\tintent: finalStep.intent,\n\t\t\tmeta: dumpMeta,\n\t\t\tsequence,\n\t\t};\n\t}\n\n\tprivate dumpMutation(\n\t\tbundle: CompiledNqlQuery,\n\t\tintent: MutationIntent,\n\t\tmeta?: DumpMetaInput,\n\t): MutationDump {\n\t\tconst adapter = this.requireAdapter('dump');\n\t\tconst compiled = adapter.compile(bundle, this.mutationCompileOptions(meta));\n\n\t\tconst dumpMeta: DumpMeta = {\n\t\t\tcompiledAt: new Date(),\n\t\t\t...(this._schemaName !== undefined && { schema: this._schemaName }),\n\t\t\t...(meta?.queryName !== undefined && { queryName: meta.queryName }),\n\t\t\t...(meta?.correlationId !== undefined && {\n\t\t\t\tcorrelationId: meta.correlationId,\n\t\t\t}),\n\t\t};\n\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparameters: compiled.parameters,\n\t\t\tintent,\n\t\t\tmeta: dumpMeta,\n\t\t};\n\t}\n\n\tasync all(): Promise<T[]> {\n\t\tconst adapter = this.adapter;\n\t\tconst compiledIntent = this.compile();\n\t\tif (!adapter) {\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot execute query: no adapter configured. ' +\n\t\t\t\t\t(compiledIntent.kind === 'unplannedRead'\n\t\t\t\t\t\t? 'Pass an adapter to createOrm().'\n\t\t\t\t\t\t: 'Pass an adapter to createOrm() or use .toIntentIR() / .plan() for debugging.'),\n\t\t\t);\n\t\t}\n\n\t\tif (\n\t\t\tcompiledIntent.kind === 'unplannedRead' &&\n\t\t\thasExecutableNqlProgramSequence(compiledIntent.bundle)\n\t\t) {\n\t\t\tthrow new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);\n\t\t}\n\t\tif (hasExecutableNqlProgramSequence(compiledIntent.bundle)) {\n\t\t\treturn this.executeNqlProgramSequence(compiledIntent, adapter);\n\t\t}\n\t\tassertConnectionAvailable(adapter, 'nql().all()');\n\t\tif (compiledIntent.kind === 'unplannedRead') {\n\t\t\tconst compiled = adapter.compile<T>(\n\t\t\t\tcompiledIntent.bundle,\n\t\t\t\tthis.nqlBundleCompileOptions(),\n\t\t\t);\n\t\t\treturn executeCompiledQuery(adapter, compiled, 'nql().all()');\n\t\t}\n\t\tif (compiledIntent.kind === 'mutation') {\n\t\t\treturn (\n\t\t\t\tawait this.runMutationStatement(\n\t\t\t\t\tadapter,\n\t\t\t\t\tthis.createFinalNqlStatementBundle(compiledIntent),\n\t\t\t\t\tcompiledIntent.intent,\n\t\t\t\t\tthis.inTransaction,\n\t\t\t\t)\n\t\t\t).transformedRows as T[];\n\t\t}\n\n\t\tif (isBindingFinalQuery(compiledIntent.bundle)) {\n\t\t\tconst planReport = createBindingFinalPlan(\n\t\t\t\tcompiledIntent.intent,\n\t\t\t\tcompiledIntent.bundle,\n\t\t\t\tthis.model,\n\t\t\t\tadapter.dialectCapabilities,\n\t\t\t);\n\t\t\tconst compiled = adapter.compile<T>(\n\t\t\t\tthis.createFinalNqlStatementBundle(\n\t\t\t\t\tcompiledIntent,\n\t\t\t\t\tbindingFinalPlanHasJsonAggIncludes(planReport)\n\t\t\t\t\t\t? planReport\n\t\t\t\t\t\t: undefined,\n\t\t\t\t),\n\t\t\t\tthis.nqlBundleCompileOptions(),\n\t\t\t);\n\t\t\tconst rows = await executeCompiledQuery(adapter, compiled, 'nql().all()');\n\t\t\tif (bindingFinalPlanHasJsonAggIncludes(planReport)) {\n\t\t\t\thydrateJsonAggIncludes(\n\t\t\t\t\trows,\n\t\t\t\t\tplanForJsonAggHydration(planReport, compiled),\n\t\t\t\t\tthis.model,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn rows;\n\t\t}\n\n\t\tconst planReport = this.planInternal();\n\t\tconst finalBundle = this.createFinalNqlStatementBundle(compiledIntent);\n\t\tconst compiled = hasNqlBindings(finalBundle)\n\t\t\t? adapter.compile<T>(finalBundle, this.nqlBundleCompileOptions())\n\t\t\t: adapter.compile<T>(planReport);\n\t\treturn executeCompiledQuery(adapter, compiled, 'nql().all()');\n\t}\n\n\tasync run(): Promise<void> {\n\t\tawait this.all();\n\t}\n\n\tasync first(): Promise<T | null> {\n\t\tconst rows = await this.all();\n\t\treturn rows[0] ?? null;\n\t}\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Extract pseudo-column keywords from model configuration.\n * Collects all configured roles and recursive keywords from all tables'\n * pseudoColumns metadata, falling back to defaults if no configuration exists.\n */\nexport function extractPseudoColumnKeywords(\n\tmodel: ModelIR,\n): NqlCompilerOptions | undefined {\n\tconst allKeywords = new Set<string>();\n\tconst recursiveKeywords = new Set<string>();\n\n\tfor (const table of model.tables.values()) {\n\t\tif (!table.pseudoColumns) continue;\n\t\tfor (const pc of table.pseudoColumns) {\n\t\t\tallKeywords.add(pc.parentRole.toLowerCase());\n\t\t\tallKeywords.add(pc.childRole.toLowerCase());\n\t\t\tallKeywords.add(pc.ascendantKeyword.toLowerCase());\n\t\t\tallKeywords.add(pc.descendantKeyword.toLowerCase());\n\t\t\trecursiveKeywords.add(pc.ascendantKeyword.toLowerCase());\n\t\t\trecursiveKeywords.add(pc.descendantKeyword.toLowerCase());\n\t\t}\n\t}\n\n\t// No pseudo-columns configured → let compiler use defaults\n\tif (allKeywords.size === 0) return undefined;\n\n\treturn {\n\t\tpseudoColumnKeywords: [...allKeywords],\n\t\trecursiveKeywords: [...recursiveKeywords],\n\t};\n}\n","/**\n * Shared hydration utilities for json_agg include results.\n *\n * Extracted from ResultHydrator and QueryBuilderImpl to avoid duplication (DRY).\n */\nimport {\n\tconvertBigintJsReadValue,\n\ttype NestedOutputReadHandling,\n} from '@dbsp/types';\nimport type { CompiledQuery } from '../adapter.js';\nimport type { ModelIR, RelationType } from '../model-ir.js';\nimport type { PlanReport } from '../planner.js';\n\nfunction isRootIncludeDecision(\n\tdecision: PlanReport['decisions'][number],\n): boolean {\n\tconst intentPath = decision.context.intentPath;\n\treturn typeof intentPath !== 'string' || !intentPath.includes('.include[');\n}\n\ntype JsonAggRelationInfo = {\n\treadonly isToOne: boolean;\n\treadonly includeAlias?: string;\n\treadonly canonicalName?: string;\n\treadonly sourceTable?: string;\n\treadonly targetTable?: string;\n\treadonly columnKeyMap?: JsonAggColumnKeyMap;\n\treadonly nestedReadTransforms?: JsonAggNestedReadTransformMap;\n};\n\ntype NestedRelationInfo = {\n\treadonly targetTable: string;\n\treadonly isToOne: boolean;\n\treadonly columnKeyMap?: JsonAggColumnKeyMap;\n\treadonly nestedReadTransforms?: JsonAggNestedReadTransformMap;\n};\n\ntype JsonAggColumnKeyMap = ReadonlyMap<string, string>;\ntype JsonAggNestedReadTransformMap = ReadonlyMap<\n\tstring,\n\tNestedOutputReadHandling\n>;\n\nexport function planForJsonAggHydration(\n\tplanReport: PlanReport,\n\tquery?: CompiledQuery,\n): PlanReport {\n\treturn query?.hydrationPlan ?? planReport;\n}\n\nfunction relationTypeIsToOne(type: RelationType | undefined): boolean {\n\treturn type === 'belongsTo' || type === 'hasOne';\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction camelize(value: string): string {\n\treturn value.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction snakeCase(value: string): string {\n\treturn value.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n}\n\nfunction keyCandidates(name: string): readonly string[] {\n\treturn [...new Set([name, camelize(name), snakeCase(name)])];\n}\n\nfunction readJsonAggColumnKeyMap(\n\tcontext: PlanReport['decisions'][number]['context'],\n): JsonAggColumnKeyMap | undefined {\n\tconst raw = context.jsonAggColumnKeyMap;\n\tif (!isRecord(raw)) return undefined;\n\tconst entries = Object.entries(raw).filter(\n\t\t(entry): entry is [string, string] => typeof entry[1] === 'string',\n\t);\n\treturn entries.length > 0 ? new Map(entries) : undefined;\n}\n\nfunction isNestedOutputReadHandling(\n\tvalue: unknown,\n): value is NestedOutputReadHandling {\n\treturn (\n\t\tisRecord(value) &&\n\t\tvalue.kind === 'nestedTransform' &&\n\t\ttypeof value.table === 'string' &&\n\t\ttypeof value.column === 'string' &&\n\t\t(value.outputKey === undefined || typeof value.outputKey === 'string') &&\n\t\t(value.js === 'bigint' || value.js === 'number' || value.js === 'string')\n\t);\n}\n\nfunction readJsonAggNestedReadTransforms(\n\tcontext: PlanReport['decisions'][number]['context'],\n): JsonAggNestedReadTransformMap | undefined {\n\tconst raw = context.jsonAggNestedReadTransforms;\n\tif (!Array.isArray(raw)) return undefined;\n\tconst entries: [string, NestedOutputReadHandling][] = [];\n\tfor (const item of raw) {\n\t\tif (isNestedOutputReadHandling(item)) {\n\t\t\tentries.push([\n\t\t\t\titem.outputKey !== undefined && item.outputKey !== item.column\n\t\t\t\t\t? item.outputKey\n\t\t\t\t\t: item.column,\n\t\t\t\titem,\n\t\t\t]);\n\t\t}\n\t}\n\treturn entries.length > 0 ? new Map(entries) : undefined;\n}\n\nfunction findExistingKey(\n\trecord: Record<string, unknown>,\n\tname: string,\n\tcolumnKeyMap?: JsonAggColumnKeyMap,\n): string | undefined {\n\tif (columnKeyMap) {\n\t\tfor (const [emittedKey, modelKey] of columnKeyMap) {\n\t\t\tif (modelKey === name && Object.hasOwn(record, emittedKey)) {\n\t\t\t\treturn emittedKey;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\tfor (const candidate of keyCandidates(name)) {\n\t\tif (Object.hasOwn(record, candidate)) return candidate;\n\t}\n\treturn undefined;\n}\n\nfunction renameExistingKey(\n\trecord: Record<string, unknown>,\n\tfromKey: string,\n\ttoKey: string,\n): string {\n\tif (fromKey === toKey) return fromKey;\n\tif (!Object.hasOwn(record, toKey)) {\n\t\trecord[toKey] = record[fromKey];\n\t}\n\tdelete record[fromKey];\n\treturn toKey;\n}\n\nfunction resolveDecisionTargetTable(\n\tinfo: JsonAggRelationInfo,\n\tmodel: ModelIR | undefined,\n): string | undefined {\n\tif (info.targetTable) return info.targetTable;\n\tif (!model || !info.sourceTable || !info.canonicalName) return undefined;\n\treturn model.getRelation(`${info.sourceTable}.${info.canonicalName}`)?.target;\n}\n\nfunction addNestedRelationInfo(\n\tlookup: Map<string, Map<string, NestedRelationInfo>>,\n\tsourceTable: string | undefined,\n\tkey: string | undefined,\n\tinfo: NestedRelationInfo | undefined,\n): void {\n\tif (!sourceTable || !key || !info) return;\n\tconst byKey =\n\t\tlookup.get(sourceTable) ?? new Map<string, NestedRelationInfo>();\n\tbyKey.set(key, info);\n\tlookup.set(sourceTable, byKey);\n}\n\nfunction buildNestedRelationLookup(\n\tplanReport: PlanReport,\n\tmodel: ModelIR | undefined,\n): Map<string, Map<string, NestedRelationInfo>> {\n\tconst lookup = new Map<string, Map<string, NestedRelationInfo>>();\n\tfor (const decision of planReport.decisions) {\n\t\tif (decision.type !== 'include-strategy') continue;\n\t\tconst sourceTable = decision.context.sourceTable;\n\t\tconst canonicalName = decision.context.relation;\n\t\tconst includeAlias = decision.context.includeAlias;\n\t\tconst targetTable =\n\t\t\tdecision.context.target ??\n\t\t\t(sourceTable && canonicalName && model\n\t\t\t\t? model.getRelation(`${sourceTable}.${canonicalName}`)?.target\n\t\t\t\t: undefined);\n\t\tif (!sourceTable || !targetTable) continue;\n\t\tconst columnKeyMap = readJsonAggColumnKeyMap(decision.context);\n\t\tconst nestedReadTransforms = readJsonAggNestedReadTransforms(\n\t\t\tdecision.context,\n\t\t);\n\t\tconst info = {\n\t\t\ttargetTable,\n\t\t\tisToOne: relationTypeIsToOne(decision.context.relationType),\n\t\t\t...(columnKeyMap ? { columnKeyMap } : {}),\n\t\t\t...(nestedReadTransforms ? { nestedReadTransforms } : {}),\n\t\t};\n\t\taddNestedRelationInfo(lookup, sourceTable, canonicalName, info);\n\t\taddNestedRelationInfo(lookup, sourceTable, includeAlias, info);\n\t}\n\treturn lookup;\n}\n\nfunction convertJsonAggPayload(\n\tvalue: unknown,\n\ttableName: string | undefined,\n\tmodel: ModelIR | undefined,\n\tlookup: ReadonlyMap<string, ReadonlyMap<string, NestedRelationInfo>>,\n\tcolumnKeyMap?: JsonAggColumnKeyMap,\n\tnestedReadTransforms?: JsonAggNestedReadTransformMap,\n): unknown {\n\tif (!model || !tableName) return value;\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) =>\n\t\t\tconvertJsonAggPayload(\n\t\t\t\titem,\n\t\t\t\ttableName,\n\t\t\t\tmodel,\n\t\t\t\tlookup,\n\t\t\t\tcolumnKeyMap,\n\t\t\t\tnestedReadTransforms,\n\t\t\t),\n\t\t);\n\t}\n\tif (!isRecord(value)) return value;\n\n\tconst table = model.getTable(tableName);\n\tif (table) {\n\t\t// A renamed projection cannot be discovered by walking model column names.\n\t\t// `outputKey` is intentionally opt-in: legacy metadata remains column-based.\n\t\tfor (const [key, transform] of nestedReadTransforms ?? []) {\n\t\t\tif (\n\t\t\t\ttransform.outputKey !== undefined &&\n\t\t\t\ttransform.outputKey !== transform.column &&\n\t\t\t\tObject.hasOwn(value, key) &&\n\t\t\t\ttransform.table === tableName\n\t\t\t) {\n\t\t\t\tvalue[key] = convertBigintJsReadValue(value[key], transform.js, {\n\t\t\t\t\ttable: transform.table,\n\t\t\t\t\tcolumn: transform.column,\n\t\t\t\t\toutputKey: key,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tfor (const column of table.columns) {\n\t\t\tconst key = findExistingKey(value, column.name, columnKeyMap);\n\t\t\tif (key === undefined) continue;\n\t\t\tconst outputKey = renameExistingKey(value, key, column.name);\n\t\t\tconst transform = nestedReadTransforms?.get(outputKey);\n\t\t\tif (\n\t\t\t\ttransform?.kind === 'nestedTransform' &&\n\t\t\t\t(transform.outputKey === undefined ||\n\t\t\t\t\ttransform.outputKey === transform.column) &&\n\t\t\t\ttransform.table === tableName &&\n\t\t\t\ttransform.column === column.name\n\t\t\t) {\n\t\t\t\tvalue[outputKey] = convertBigintJsReadValue(\n\t\t\t\t\tvalue[outputKey],\n\t\t\t\t\ttransform.js,\n\t\t\t\t\t{\n\t\t\t\t\t\ttable: transform.table,\n\t\t\t\t\t\tcolumn: transform.column,\n\t\t\t\t\t\toutputKey,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst relationInfos = lookup.get(tableName);\n\tif (!relationInfos) return value;\n\tfor (const [relationKey, info] of relationInfos) {\n\t\tconst key = findExistingKey(value, relationKey);\n\t\tif (key === undefined) continue;\n\t\tconst converted = convertJsonAggPayload(\n\t\t\tvalue[key],\n\t\t\tinfo.targetTable,\n\t\t\tmodel,\n\t\t\tlookup,\n\t\t\tinfo.columnKeyMap,\n\t\t\tinfo.nestedReadTransforms,\n\t\t);\n\t\tvalue[key] =\n\t\t\tinfo.isToOne && Array.isArray(converted)\n\t\t\t\t? converted.length > 0\n\t\t\t\t\t? converted[0]\n\t\t\t\t\t: null\n\t\t\t\t: converted;\n\t}\n\treturn value;\n}\n\n/**\n * Hydrate json_agg include columns in query results.\n *\n * Parses `{relation}_json` columns from json_agg subqueries into proper\n * nested objects/arrays, handles CamelCasePlugin column name transforms,\n * and unwraps to-one relations from arrays to single objects.\n */\nexport function hydrateJsonAggIncludes<T>(\n\tresults: T[],\n\tplanReport: PlanReport,\n\tmodel?: ModelIR,\n): void {\n\t// Find root json_agg include decisions. Nested json_agg decisions are emitted\n\t// inside the root JSON payload and do not produce top-level *_json columns.\n\tconst jsonAggDecisions = planReport.decisions.filter(\n\t\t(d) =>\n\t\t\td.type === 'include-strategy' &&\n\t\t\td.choice === 'json_agg' &&\n\t\t\tisRootIncludeDecision(d),\n\t);\n\n\tif (jsonAggDecisions.length === 0) {\n\t\treturn;\n\t}\n\n\t// Build map of relation names -> relation type\n\t// The adapter compiler uses the canonical relation name (context.relation) for\n\t// the JSON column alias (e.g., 'author_posts' → 'author_posts_json').\n\t// We also track the includeAlias (user-provided name) for fallback matching.\n\t// STRAT-SIMPLIFY: Track to-one relations for [0] extraction\n\tconst relationInfo = new Map<string, JsonAggRelationInfo>();\n\tconst nestedRelationLookup = buildNestedRelationLookup(planReport, model);\n\tfor (const decision of jsonAggDecisions) {\n\t\tconst canonicalName = decision.context?.relation;\n\t\tconst includeAlias = decision.context?.includeAlias;\n\t\tconst relationType = decision.context?.relationType;\n\t\tconst isToOne = relationTypeIsToOne(relationType);\n\t\tconst sourceTable = decision.context?.sourceTable;\n\t\tconst targetTable = decision.context?.target;\n\t\tconst columnKeyMap = readJsonAggColumnKeyMap(decision.context);\n\t\tconst nestedReadTransforms = readJsonAggNestedReadTransforms(\n\t\t\tdecision.context,\n\t\t);\n\n\t\t// Primary key: canonical relation name (matches adapter SQL alias)\n\t\tif (typeof canonicalName === 'string') {\n\t\t\tconst info: JsonAggRelationInfo = {\n\t\t\t\tisToOne,\n\t\t\t\tincludeAlias:\n\t\t\t\t\ttypeof includeAlias === 'string' ? includeAlias : canonicalName,\n\t\t\t\tcanonicalName,\n\t\t\t\t...(sourceTable !== undefined ? { sourceTable } : {}),\n\t\t\t\t...(targetTable !== undefined ? { targetTable } : {}),\n\t\t\t\t...(columnKeyMap ? { columnKeyMap } : {}),\n\t\t\t\t...(nestedReadTransforms ? { nestedReadTransforms } : {}),\n\t\t\t};\n\t\t\trelationInfo.set(canonicalName, info);\n\t\t} else if (typeof includeAlias === 'string') {\n\t\t\t// Fallback: use includeAlias if no canonical name\n\t\t\tconst info: JsonAggRelationInfo = {\n\t\t\t\tisToOne,\n\t\t\t\tincludeAlias,\n\t\t\t\t...(sourceTable !== undefined ? { sourceTable } : {}),\n\t\t\t\t...(targetTable !== undefined ? { targetTable } : {}),\n\t\t\t\t...(columnKeyMap ? { columnKeyMap } : {}),\n\t\t\t\t...(nestedReadTransforms ? { nestedReadTransforms } : {}),\n\t\t\t};\n\t\t\trelationInfo.set(includeAlias, info);\n\t\t}\n\t}\n\n\tif (relationInfo.size === 0) {\n\t\treturn;\n\t}\n\n\t// Process each result row\n\tfor (const row of results) {\n\t\tif (typeof row !== 'object' || row === null) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst record = row as Record<string, unknown>;\n\n\t\tfor (const [relationName, info] of relationInfo) {\n\t\t\t// The adapter generates the JSON column alias from the canonical relation name\n\t\t\t// (e.g., 'author_posts' → 'author_posts_json'). The naming plugin may\n\t\t\t// transform it to camelCase (e.g., 'authorPostsJson').\n\t\t\t// We try both the canonical name and the includeAlias as base names.\n\t\t\tconst candidates = [relationName];\n\t\t\tif (info.includeAlias && info.includeAlias !== relationName) {\n\t\t\t\tcandidates.push(info.includeAlias);\n\t\t\t}\n\n\t\t\tlet actualColumnName: string | null = null;\n\t\t\tfor (const baseName of candidates) {\n\t\t\t\tconst snakeJson = `${baseName}_json`;\n\t\t\t\tconst camelJson = snakeJson.replace(/_([a-z])/g, (_, c: string) =>\n\t\t\t\t\tc.toUpperCase(),\n\t\t\t\t);\n\t\t\t\tif (Object.hasOwn(record, snakeJson)) {\n\t\t\t\t\tactualColumnName = snakeJson;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (Object.hasOwn(record, camelJson)) {\n\t\t\t\t\tactualColumnName = camelJson;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (actualColumnName) {\n\t\t\t\tconst jsonValue = record[actualColumnName];\n\n\t\t\t\t// Parse JSON if it's a string\n\t\t\t\tlet parsed: unknown;\n\t\t\t\tif (typeof jsonValue === 'string') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = JSON.parse(jsonValue);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tparsed = info.isToOne ? null : [];\n\t\t\t\t\t}\n\t\t\t\t} else if (Array.isArray(jsonValue)) {\n\t\t\t\t\tparsed = jsonValue;\n\t\t\t\t} else if (jsonValue === null || jsonValue === undefined) {\n\t\t\t\t\tparsed = info.isToOne ? null : [];\n\t\t\t\t} else {\n\t\t\t\t\tparsed = jsonValue;\n\t\t\t\t}\n\n\t\t\t\t// STRAT-SIMPLIFY: For to-one relations, unwrap array to single object\n\t\t\t\tif (info.isToOne && Array.isArray(parsed)) {\n\t\t\t\t\tparsed = parsed.length > 0 ? parsed[0] : null;\n\t\t\t\t}\n\t\t\t\tparsed = convertJsonAggPayload(\n\t\t\t\t\tparsed,\n\t\t\t\t\tresolveDecisionTargetTable(info, model),\n\t\t\t\t\tmodel,\n\t\t\t\t\tnestedRelationLookup,\n\t\t\t\t\tinfo.columnKeyMap,\n\t\t\t\t\tinfo.nestedReadTransforms,\n\t\t\t\t);\n\n\t\t\t\t// Set property using includeAlias (user-facing name, e.g., 'posts')\n\t\t\t\t// and remove the raw JSON column\n\t\t\t\tconst outputKey = info.includeAlias ?? relationName;\n\t\t\t\trecord[outputKey] = parsed;\n\t\t\t\tdelete record[actualColumnName];\n\t\t\t}\n\t\t}\n\t}\n}\n","import {\n\tconvertBigintJsReadValue,\n\ttype PinnedConnectionOptions,\n} from '@dbsp/types';\nimport {\n\ttype Adapter,\n\tassertConnectionAvailable,\n\tsupportsTransactions,\n\ttype TransactionOptions,\n} from '../adapter.js';\nimport type { DialectCapabilities } from '../dialects/index.js';\nimport type { ModelIR } from '../model-ir.js';\nimport type { PlanOptions } from '../planner.js';\nimport type { BatchValuesOptions, BatchValuesRef } from './batch-values.js';\nimport { batchValues } from './batch-values.js';\nimport { CteBuilder } from './cte-builder.js';\nimport {\n\tExecutionError,\n\tInvalidOperationError,\n\tvalidateIdentifier,\n} from './errors.js';\nimport { eq } from './filters.js';\nimport {\n\textractRecursiveField,\n\tfindSelfRefRelation,\n} from './hierarchy-helpers.js';\nimport type {\n\tHookErrorHandler,\n\tHookStore,\n\tObserverErrorHandler,\n} from './hooks.js';\nimport {\n\tDeleteBuilder,\n\tInsertBuilder,\n\tUpdateBuilder,\n\tUpsertBuilder,\n} from './mutation-builders.js';\nimport { createNqlTag, type NqlTag } from './nql.js';\nimport type {\n\tRawReadOptions,\n\tSelectExpressionResult,\n} from './orm-instance-types.js';\nimport { QueryBuilderImpl } from './query-builder.js';\nimport type { QueryBuilderContext } from './query-builder-context.js';\nimport {\n\tcreateRawCteBuilder,\n\ttype RawCteQueryBuilder,\n\ttype RecursiveOptions,\n} from './raw-cte-builder.js';\nimport type { DefaultFilters } from './schema.js';\nimport { TABLE_META } from './symbols.js';\nimport type {\n\tAlterColumnOptions,\n\tCreateIndexOptions,\n\tDropIndexOptions,\n\tIndexInfo,\n\tTableDDL,\n\tTruncateOptions,\n\tVacuumOptions,\n} from './table-ddl-types.js';\nimport type { InferTableRow, TableRef } from './table-ref.js';\nimport type {\n\tExpressionSpec,\n\tListHierarchyOptions,\n\tOrmInstance,\n\tOrmInstanceInternal,\n\tQueryBuilder,\n\tRelationHints,\n} from './types.js';\n\n/**\n * Quote a PostgreSQL identifier (table/schema/column name).\n * Simple double-quoting — no validation, validation is caller's responsibility.\n */\n\n/**\n * Build the qualified table reference string for DDL statements.\n */\n\n/**\n * Build the DDL methods object for a specific table.\n */\n// ─── DDL SQL generation helpers ──────────────────────────────────────────────\n\n/** Double-quote a PostgreSQL identifier. */\nfunction quoteIdent(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nconst DEFAULT_DDL_SCHEMA_NAME = 'public';\n\nfunction resolveDDLSchemaName(schemaName: string | undefined): string {\n\tconst resolved = schemaName ?? DEFAULT_DDL_SCHEMA_NAME;\n\tvalidateIdentifier(resolved, 'schema');\n\treturn resolved;\n}\n\nfunction sanitizeDropIndexOptions(\n\toptions: DropIndexOptions | undefined,\n): DropIndexOptions | undefined {\n\tif (options === undefined || !('schema' in options)) {\n\t\treturn options;\n\t}\n\tconst { schema: _schema, ...rest } = options as DropIndexOptions & {\n\t\treadonly schema?: unknown;\n\t};\n\treturn Object.keys(rest).length > 0 ? rest : undefined;\n}\n\n/** Build a qualified `\"schema\".\"table\"` reference. */\nfunction buildQualifiedTable(tableName: string, schemaName: string): string {\n\treturn `${quoteIdent(schemaName)}.${quoteIdent(tableName)}`;\n}\n\nfunction generateTruncateSQL(\n\ttableName: string,\n\tschemaName: string,\n\toptions: TruncateOptions | undefined,\n): string {\n\tconst parts = [`TRUNCATE ${buildQualifiedTable(tableName, schemaName)}`];\n\tif (options?.restartIdentity) parts.push('RESTART IDENTITY');\n\tif (options?.cascade) parts.push('CASCADE');\n\treturn parts.join(' ');\n}\n\nfunction generateVacuumSQL(\n\ttableName: string,\n\tschemaName: string,\n\toptions: VacuumOptions | undefined,\n): string {\n\tconst modifiers: string[] = [];\n\tif (options?.full) modifiers.push('FULL');\n\tif (options?.analyze) modifiers.push('ANALYZE');\n\tconst mod = modifiers.length > 0 ? `(${modifiers.join(', ')}) ` : '';\n\treturn `VACUUM ${mod}${buildQualifiedTable(tableName, schemaName)}`;\n}\n\nfunction createUnsupportedTransactionError(): ExecutionError {\n\treturn new ExecutionError({\n\t\toperation: 'transaction()',\n\t\treason:\n\t\t\t'The adapter does not declare capabilities.supportsTransactions: true for this ORM instance.',\n\t\tfix: 'Use an adapter that implements transaction() and withSchema(), and declare adapter.capabilities.supportsTransactions: true.',\n\t});\n}\n\nfunction createUnsupportedPinnedConnectionError(): ExecutionError {\n\treturn new ExecutionError({\n\t\toperation: 'withPinnedConnection()',\n\t\treason:\n\t\t\t'The adapter does not declare capabilities.supportsPinnedConnections: true and implement withPinnedConnection() for this ORM instance.',\n\t\tfix: 'Use an adapter that implements withPinnedConnection(), and declare adapter.capabilities.supportsPinnedConnections: true.',\n\t});\n}\n\nfunction hasTransactionOptions(\n\toptions: TransactionOptions | undefined,\n): boolean {\n\treturn (\n\t\toptions != null &&\n\t\t(options.isolationLevel !== undefined ||\n\t\t\toptions.readOnly !== undefined ||\n\t\t\toptions.lockTimeoutMs !== undefined ||\n\t\t\toptions.statementTimeoutMs !== undefined ||\n\t\t\toptions.signal !== undefined)\n\t);\n}\n\nfunction supportsPinnedConnections<DB>(\n\tadapter: Adapter<DB>,\n): adapter is Adapter<DB> & {\n\twithPinnedConnection<T>(\n\t\tfn: (adapter: Adapter<DB>) => Promise<T>,\n\t\toptions?: PinnedConnectionOptions,\n\t): Promise<T>;\n} {\n\treturn (\n\t\tadapter.capabilities.supportsPinnedConnections === true &&\n\t\ttypeof adapter.withPinnedConnection === 'function'\n\t);\n}\n\nfunction applyBigintReads<T>(\n\trow: T,\n\tbigintReads: NonNullable<RawReadOptions['bigintReads']>,\n): T {\n\tif (row === null || typeof row !== 'object') return row;\n\n\tconst rowRecord = row as Record<string, unknown>;\n\tconst converted = { ...rowRecord };\n\tfor (const [outputKey, js] of Object.entries(bigintReads)) {\n\t\tif (!(outputKey in rowRecord)) continue;\n\t\tconverted[outputKey] = convertBigintJsReadValue(rowRecord[outputKey], js, {\n\t\t\ttable: '(raw)',\n\t\t\tcolumn: outputKey,\n\t\t\toutputKey,\n\t\t});\n\t}\n\treturn converted as T;\n}\n\nfunction adapterTransactionState(\n\tadapter: Adapter<unknown>,\n\toperation: string,\n\tstatement: string,\n): boolean {\n\tconst inTransaction = (adapter as { readonly inTransaction?: unknown })\n\t\t.inTransaction;\n\tif (typeof inTransaction !== 'boolean') {\n\t\tthrow new InvalidOperationError(\n\t\t\toperation,\n\t\t\t`${statement} requires an adapter that exposes inTransaction: boolean; dbsp refuses to run it when transaction state is unknown.`,\n\t\t);\n\t}\n\treturn inTransaction;\n}\n\nfunction assertOutsideTransaction(\n\tadapter: Adapter<unknown>,\n\toperation: string,\n\tstatement: string,\n): void {\n\tif (adapterTransactionState(adapter, operation, statement)) {\n\t\tthrow new InvalidOperationError(\n\t\t\toperation,\n\t\t\t`${statement} cannot run inside a transaction block`,\n\t\t);\n\t}\n}\n\nfunction generateAlterColumnSQL(\n\ttableName: string,\n\tschemaName: string | undefined,\n\tcolumn: string,\n\toptions: AlterColumnOptions,\n): string {\n\tconst tbl = buildQualifiedTable(tableName, resolveDDLSchemaName(schemaName));\n\tconst col = quoteIdent(column);\n\tconst clauses: string[] = [];\n\n\tif (options.type !== undefined) {\n\t\tlet clause = `ALTER COLUMN ${col} TYPE ${options.type}`;\n\t\tif (options.using !== undefined) {\n\t\t\tclause += ` USING ${options.using}`;\n\t\t}\n\t\tclauses.push(clause);\n\t}\n\tif (options.setNotNull === true) {\n\t\tclauses.push(`ALTER COLUMN ${col} SET NOT NULL`);\n\t} else if (options.setNotNull === false) {\n\t\tclauses.push(`ALTER COLUMN ${col} DROP NOT NULL`);\n\t}\n\tif (options.dropDefault === true) {\n\t\tclauses.push(`ALTER COLUMN ${col} DROP DEFAULT`);\n\t} else if (options.setDefault !== undefined) {\n\t\tclauses.push(`ALTER COLUMN ${col} SET DEFAULT ${options.setDefault}`);\n\t}\n\tif (clauses.length === 0) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'alterColumn',\n\t\t\t'At least one alteration option must be specified.',\n\t\t);\n\t}\n\treturn `ALTER TABLE ${tbl} ${clauses.join(', ')}`;\n}\n\nfunction generateDropIndexSQL(\n\tname: string,\n\tschemaName: string,\n\toptions: DropIndexOptions | undefined,\n): string {\n\tconst parts: string[] = ['DROP INDEX'];\n\tif (options?.concurrently) parts.push('CONCURRENTLY');\n\tif (options?.ifExists) parts.push('IF EXISTS');\n\tparts.push(`${quoteIdent(schemaName)}.${quoteIdent(name)}`);\n\tif (options?.cascade) parts.push('CASCADE');\n\treturn parts.join(' ');\n}\n\n// ─── indexes sub-API builder ──────────────────────────────────────────────────\n\nfunction buildIndexAPI(\n\ttableName: string,\n\tschemaName: string | undefined,\n\tadapter: Adapter<unknown> | undefined,\n\trequireAdapter: () => Adapter<unknown>,\n): TableDDL['indexes'] {\n\treturn {\n\t\tasync create(opts: CreateIndexOptions): Promise<void> {\n\t\t\tconst a = requireAdapter();\n\t\t\tif (opts.concurrently) {\n\t\t\t\tassertOutsideTransaction(a, 'createIndex', 'CREATE INDEX CONCURRENTLY');\n\t\t\t}\n\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\tconst sql = a.generateCreateIndex(tableName, ddlSchemaName, opts);\n\t\t\tawait a.executeDDL?.(sql);\n\t\t},\n\n\t\tasync drop(name: string, options?: DropIndexOptions): Promise<void> {\n\t\t\tconst a = requireAdapter();\n\t\t\tif (options?.concurrently) {\n\t\t\t\tassertOutsideTransaction(a, 'dropIndex', 'DROP INDEX CONCURRENTLY');\n\t\t\t}\n\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\tconst sanitizedOptions = sanitizeDropIndexOptions(options);\n\t\t\tconst sql = a.generateDropIndex\n\t\t\t\t? a.generateDropIndex(name, ddlSchemaName, sanitizedOptions)\n\t\t\t\t: generateDropIndexSQL(name, ddlSchemaName, sanitizedOptions);\n\t\t\tawait a.executeDDL?.(sql);\n\t\t},\n\n\t\tasync list(options?: { namePattern?: string }): Promise<IndexInfo[]> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'indexes.list',\n\t\t\t\t\t'indexes.list() requires an adapter.',\n\t\t\t\t);\n\t\t\t}\n\t\t\t// DB-agnostic core must not emit database-specific catalog SQL.\n\t\t\t// Listing indexes requires the adapter to implement listIndexes()\n\t\t\t// (mirrors indexes.exists() below); fail loud rather than fall back\n\t\t\t// to a PostgreSQL-only pg_index/pg_indexes query.\n\t\t\tif (!adapter.listIndexes) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'indexes.list',\n\t\t\t\t\t'indexes.list() requires an adapter that implements listIndexes().',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn adapter.listIndexes(tableName, schemaName, options);\n\t\t},\n\n\t\tasync exists(name: string): Promise<boolean> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'indexes.exists',\n\t\t\t\t\t'indexes.exists() requires an adapter.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!adapter.indexExists) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'indexes.exists',\n\t\t\t\t\t'indexes.exists() requires an adapter that implements indexExists().',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn adapter.indexExists(name, tableName, schemaName);\n\t\t},\n\t};\n}\n\n// ─── Public assembler ─────────────────────────────────────────────────────────\n\n/**\n * Build the DDL methods object for a specific table.\n */\nfunction buildTableDDL(\n\ttableName: string,\n\tschemaName: string | undefined,\n\tadapter: Adapter<unknown> | undefined,\n): TableDDL {\n\tfunction requireAdapter(): Adapter<unknown> {\n\t\tif (!adapter?.executeDDL) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'table DDL',\n\t\t\t\t'executeDDL() requires an adapter that supports DDL execution. ' +\n\t\t\t\t\t'Pass an adapter with executeDDL when creating the ORM.',\n\t\t\t);\n\t\t}\n\t\treturn adapter;\n\t}\n\n\treturn {\n\t\tasync truncate(options?: TruncateOptions): Promise<void> {\n\t\t\tconst a = requireAdapter();\n\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\tconst sql = a.generateTruncate\n\t\t\t\t? a.generateTruncate(tableName, ddlSchemaName, options)\n\t\t\t\t: generateTruncateSQL(tableName, ddlSchemaName, options);\n\t\t\tawait a.executeDDL?.(sql);\n\t\t},\n\n\t\tasync vacuum(options?: VacuumOptions): Promise<void> {\n\t\t\tconst a = requireAdapter();\n\t\t\tassertOutsideTransaction(a, 'vacuum', 'VACUUM');\n\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\tconst sql = a.generateVacuum\n\t\t\t\t? a.generateVacuum(tableName, ddlSchemaName, options)\n\t\t\t\t: generateVacuumSQL(tableName, ddlSchemaName, options);\n\t\t\tawait a.executeDDL?.(sql);\n\t\t},\n\n\t\tasync alterColumn(\n\t\t\tcolumn: string,\n\t\t\toptions: AlterColumnOptions,\n\t\t): Promise<void> {\n\t\t\tvalidateIdentifier(tableName, 'table');\n\t\t\tvalidateIdentifier(column, 'column');\n\t\t\tconst a = requireAdapter();\n\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\tconst sql = a.generateAlterColumn\n\t\t\t\t? a.generateAlterColumn(tableName, ddlSchemaName, column, options)\n\t\t\t\t: generateAlterColumnSQL(tableName, ddlSchemaName, column, options);\n\t\t\tawait a.executeDDL?.(sql);\n\t\t},\n\n\t\tindexes: buildIndexAPI(tableName, schemaName, adapter, requireAdapter),\n\n\t\tasync storageSize(): Promise<number> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'storageSize',\n\t\t\t\t\t'storageSize() requires an adapter.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!adapter.storageSize) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'storageSize',\n\t\t\t\t\t'storageSize() requires an adapter that implements storageSize().',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn adapter.storageSize(tableName, schemaName);\n\t\t},\n\t};\n}\n\n/**\n * Wrap a tables proxy (from createTablesProxy or schema.tables) with DDL methods.\n * The returned proxy intercepts property access on each table name and augments\n * the returned TableRef object with a `TableDDL` mixin.\n */\nexport function wrapTablesProxyWithDDL(\n\ttablesProxy: object,\n\tadapter: Adapter<unknown> | undefined,\n\tschemaName: string | undefined,\n): object {\n\t// Cache augmented table objects to preserve referential equality\n\tconst cache = new Map<string, object>();\n\n\treturn new Proxy(tablesProxy, {\n\t\tget(target, prop, receiver) {\n\t\t\t// Pass through Symbol and non-string properties unchanged\n\t\t\tif (typeof prop !== 'string') {\n\t\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t\t}\n\n\t\t\tif (cache.has(prop)) {\n\t\t\t\treturn cache.get(prop);\n\t\t\t}\n\n\t\t\tconst tableRef = Reflect.get(target, prop, receiver);\n\t\t\tif (tableRef === undefined || tableRef === null) {\n\t\t\t\treturn tableRef;\n\t\t\t}\n\n\t\t\t// Augment the TableRef with DDL methods\n\t\t\tconst ddl = buildTableDDL(prop, schemaName, adapter);\n\t\t\tconst augmented = Object.assign(Object.create(null), tableRef, ddl);\n\t\t\tcache.set(prop, augmented);\n\t\t\treturn augmented;\n\t\t},\n\t});\n}\n\n/**\n * Internal factory for creating ORM instances.\n * Supports optional schema name for multi-tenant scenarios.\n *\n * @typeParam DB - Database schema type (passed through from createOrm)\n */\nexport function createOrmInstance<DB = Record<string, unknown>>(\n\tmodel: ModelIR,\n\tstrictMode: boolean,\n\trelationHints: RelationHints,\n\tadapter?: Adapter<DB>,\n\tschemaName?: string,\n\tdialectCapabilities?: DialectCapabilities,\n\tschemaDefinition?: unknown,\n\tglobalPlanOptions?: PlanOptions,\n\tdefaultFilters?: DefaultFilters,\n\thookStore?: HookStore,\n\tonHookError?: HookErrorHandler,\n\tinTransaction?: boolean,\n\ttablesProxy?: object,\n\tonObserverError?: ObserverErrorHandler,\n): OrmInstanceInternal<DB> {\n\t// Create NQL template tag (DX-040)\n\t// NQL compiler is now integrated directly - @dbsp/nql is imported in nql.ts\n\tconst nql: NqlTag = createNqlTag(\n\t\tschemaDefinition,\n\t\tmodel,\n\t\tadapter as Adapter<unknown> | undefined,\n\t\tschemaName,\n\t\thookStore,\n\t\tonHookError,\n\t\tinTransaction,\n\t\tonObserverError,\n\t);\n\n\t// Helper: build a MutationBuilder options object (shared across mutation methods)\n\tconst mutationOpts = {\n\t\tmodel,\n\t\tadapter,\n\t\tschemaName,\n\t\thookStore,\n\t\tonHookError,\n\t\tonObserverError,\n\t\tinTransaction,\n\t} as const;\n\n\t// Context bag for QueryBuilderImpl — eliminates the 12-param positional constructor\n\tconst queryCtx: QueryBuilderContext = {\n\t\tmodel,\n\t\tstrictMode,\n\t\t...(adapter !== undefined ? { adapter: adapter as Adapter<unknown> } : {}),\n\t\t...(schemaName !== undefined ? { schemaName } : {}),\n\t\t...(dialectCapabilities !== undefined ? { dialectCapabilities } : {}),\n\t\t...(globalPlanOptions !== undefined\n\t\t\t? { planOptionsOverride: globalPlanOptions }\n\t\t\t: {}),\n\t\t...(defaultFilters !== undefined ? { defaultFilters } : {}),\n\t\t...(hookStore !== undefined ? { hookStore } : {}),\n\t\t...(onHookError !== undefined ? { onHookError } : {}),\n\t\t...(onObserverError !== undefined ? { onObserverError } : {}),\n\t\t...(inTransaction !== undefined ? { inTransaction } : {}),\n\t};\n\n\t// Wrap the tables proxy to augment each table access with DDL methods\n\tconst tablesDDLProxy = wrapTablesProxyWithDDL(\n\t\ttablesProxy ?? {},\n\t\tadapter as Adapter<unknown> | undefined,\n\t\tschemaName,\n\t);\n\n\treturn {\n\t\tstrictMode,\n\t\t// Reflect the REAL transaction state of the backing adapter so callers can\n\t\t// enforce a top-level precondition. This is authoritative even when the ORM\n\t\t// was handed an adapter ALREADY inside a caller-owned transaction (e.g. a\n\t\t// borrowed pg client mid-BEGIN): the adapter tracks the connection's actual\n\t\t// state, which dbsp's construction-time nesting flag alone cannot see. Falls\n\t\t// back to that flag only when no adapter exposes the state (e.g. a compile-only\n\t\t// ORM). withSchema/transaction() re-derive it from their own (scoped/tx)\n\t\t// adapter, so every instance reports the state of the connection it uses.\n\t\tget inTransaction(): boolean {\n\t\t\tconst adapterState = (\n\t\t\t\tadapter as { readonly inTransaction?: unknown } | undefined\n\t\t\t)?.inTransaction;\n\t\t\treturn typeof adapterState === 'boolean'\n\t\t\t\t? adapterState\n\t\t\t\t: (inTransaction ?? false);\n\t\t},\n\t\tnql,\n\t\ttables: tablesDDLProxy as OrmInstance<DB>['tables'],\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic constraint — TTable is inferred by callers; TableRef generics are statically erased in this implementation signature\n\t\tfrom<TTable extends TableRef<any, any, any>>(\n\t\t\ttable: TTable | BatchValuesRef,\n\t\t):\n\t\t\t| QueryBuilder<InferTableRow<TTable>>\n\t\t\t| QueryBuilder<Record<string, unknown>> {\n\t\t\t// BatchValuesRef path\n\t\t\tif (\n\t\t\t\ttypeof table === 'object' &&\n\t\t\t\ttable !== null &&\n\t\t\t\t'__kind' in table &&\n\t\t\t\t(table as unknown as BatchValuesRef).__kind === 'batchValues'\n\t\t\t) {\n\t\t\t\tconst bv = table as unknown as BatchValuesRef;\n\t\t\t\tconst builder = new QueryBuilderImpl<Record<string, unknown>>(\n\t\t\t\t\tqueryCtx,\n\t\t\t\t\tbv.alias,\n\t\t\t\t\trelationHints,\n\t\t\t\t);\n\t\t\t\tbuilder.batchValuesSource = {\n\t\t\t\t\tdata: bv.data,\n\t\t\t\t\tcolumns: bv.columns,\n\t\t\t\t\ttypes: bv.types,\n\t\t\t\t\talias: bv.alias,\n\t\t\t\t\tordinality: bv.ordinality,\n\t\t\t\t};\n\t\t\t\treturn builder;\n\t\t\t}\n\t\t\tconst tableRef = table as TTable;\n\t\t\tconst tableName = tableRef[TABLE_META];\n\t\t\tif (tableName === undefined) {\n\t\t\t\tthrow new Error('Invalid TableRef: missing TABLE_META symbol');\n\t\t\t}\n\t\t\treturn new QueryBuilderImpl<InferTableRow<TTable>>(\n\t\t\t\tqueryCtx,\n\t\t\t\ttableName as string,\n\t\t\t\trelationHints,\n\t\t\t);\n\t\t},\n\t\tselect<K extends keyof DB & string, TResult = DB[K]>(\n\t\t\tfrom: K,\n\t\t): QueryBuilder<TResult> {\n\t\t\treturn new QueryBuilderImpl<TResult>(\n\t\t\t\tqueryCtx,\n\t\t\t\tfrom as string,\n\t\t\t\trelationHints,\n\t\t\t);\n\t\t},\n\t\twithSchema(schemaName: string): OrmInstanceInternal<DB> {\n\t\t\t// Always validate schema name — even without an adapter — to prevent injection\n\t\t\tvalidateIdentifier(schemaName, 'schema');\n\t\t\tif (adapter) {\n\t\t\t\tadapter.validateIdentifier(schemaName, 'schema');\n\t\t\t}\n\t\t\t// Create a schema-scoped adapter if we have one\n\t\t\tconst scopedAdapter = adapter?.withSchema(schemaName);\n\t\t\treturn createOrmInstance(\n\t\t\t\tmodel,\n\t\t\t\tstrictMode,\n\t\t\t\trelationHints,\n\t\t\t\tscopedAdapter as Adapter<DB> | undefined,\n\t\t\t\tschemaName,\n\t\t\t\tdialectCapabilities,\n\t\t\t\tschemaDefinition,\n\t\t\t\tglobalPlanOptions,\n\t\t\t\tdefaultFilters,\n\t\t\t\thookStore,\n\t\t\t\tonHookError,\n\t\t\t\tinTransaction,\n\t\t\t\ttablesProxy,\n\t\t\t\tonObserverError,\n\t\t\t);\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Hierarchy List Methods (DX-022)\n\t\t// Returns flat arrays, uses include() with recursive: true internally\n\t\t// =====================================================================\n\n\t\t/**\n\t\t * List all ancestors of a node as a flat array.\n\t\t * Uses the new include({ recursive: true }) API internally.\n\t\t *\n\t\t * @param table - The table name\n\t\t * @param nodeIdValue - The starting node's ID value\n\t\t * @param options - Options including parentId column name\n\t\t * @returns Promise resolving to array of ancestor records\n\t\t */\n\t\tasync listAncestors<TResult = unknown>(\n\t\t\ttable: string,\n\t\t\tnodeIdValue: unknown,\n\t\t\toptions: ListHierarchyOptions,\n\t\t): Promise<TResult[]> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'listAncestors() requires an adapter. ' +\n\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// FIND-001: Validate table against known tables before use in error messages\n\t\t\tif (!model.getTable(table)) {\n\t\t\t\tthrow new InvalidOperationError('listAncestors', 'Table not found');\n\t\t\t}\n\n\t\t\t// FIND-007: Cap maxDepth to prevent infinite/excessive recursion.\n\t\t\t// Use isSafeInteger to reject fractional values (e.g. 1.5) that\n\t\t\t// Number.isFinite would accept.\n\t\t\tconst MAX_RECURSION_DEPTH = 1000;\n\t\t\tconst rawMaxDepth = options.maxDepth ?? 100;\n\t\t\tif (!Number.isSafeInteger(rawMaxDepth) || rawMaxDepth < 1) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'listAncestors',\n\t\t\t\t\t'maxDepth must be a positive safe integer',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst safeMaxDepth = Math.min(rawMaxDepth, MAX_RECURSION_DEPTH);\n\n\t\t\t// Find the self-referential relation that matches the parent direction\n\t\t\tconst selfRefRelation = findSelfRefRelation(model, table, 'ancestors');\n\t\t\tif (!selfRefRelation) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'listAncestors',\n\t\t\t\t\t'Table has no self-referential belongsTo/hasOne relation for ancestor traversal',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nodeIdCol = options.nodeId ?? 'id';\n\n\t\t\t// Hierarchy helpers historically did NOT propagate inTransaction. Preserve that behavior.\n\t\t\tconst { inTransaction: _ignored, ...hierarchyCtxBase } = queryCtx;\n\t\t\tconst hierarchyCtx: QueryBuilderContext = hierarchyCtxBase;\n\n\t\t\tconst builder = new QueryBuilderImpl<TResult>(\n\t\t\t\thierarchyCtx,\n\t\t\t\ttable,\n\t\t\t\trelationHints,\n\t\t\t);\n\n\t\t\tconst result = await builder\n\t\t\t\t.where(eq(nodeIdCol, nodeIdValue))\n\t\t\t\t.include(selfRefRelation.name, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tdirection: 'ancestors',\n\t\t\t\t\tflat: true,\n\t\t\t\t\tomitSelf: true,\n\t\t\t\t\tmaxDepth: safeMaxDepth,\n\t\t\t\t})\n\t\t\t\t.first();\n\n\t\t\t// Result shape from include({ recursive, direction: 'ancestors' }):\n\t\t\t// { id, ..., ancestors: [...] }\n\t\t\treturn extractRecursiveField<TResult>(result, 'ancestors');\n\t\t},\n\n\t\t/**\n\t\t * List all descendants of a node as a flat array.\n\t\t * Uses the new include({ recursive: true }) API internally.\n\t\t *\n\t\t * @param table - The table name\n\t\t * @param nodeIdValue - The starting node's ID value\n\t\t * @param options - Options including parentId column name\n\t\t * @returns Promise resolving to array of descendant records\n\t\t */\n\t\tasync listDescendants<TResult = unknown>(\n\t\t\ttable: string,\n\t\t\tnodeIdValue: unknown,\n\t\t\toptions: ListHierarchyOptions,\n\t\t): Promise<TResult[]> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'listDescendants() requires an adapter. ' +\n\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// FIND-001: Validate table against known tables before use in error messages\n\t\t\tif (!model.getTable(table)) {\n\t\t\t\tthrow new InvalidOperationError('listDescendants', 'Table not found');\n\t\t\t}\n\n\t\t\t// FIND-007: Cap maxDepth to prevent infinite/excessive recursion.\n\t\t\t// Use isSafeInteger to reject fractional values (e.g. 1.5) that\n\t\t\t// Number.isFinite would accept.\n\t\t\tconst MAX_RECURSION_DEPTH = 1000;\n\t\t\tconst rawMaxDepth = options.maxDepth ?? 100;\n\t\t\tif (!Number.isSafeInteger(rawMaxDepth) || rawMaxDepth < 1) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'listDescendants',\n\t\t\t\t\t'maxDepth must be a positive safe integer',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst safeMaxDepth = Math.min(rawMaxDepth, MAX_RECURSION_DEPTH);\n\n\t\t\t// Find the self-referential relation that matches the children direction\n\t\t\tconst selfRefRelation = findSelfRefRelation(model, table, 'descendants');\n\t\t\tif (!selfRefRelation) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'listDescendants',\n\t\t\t\t\t'Table has no self-referential hasMany relation for descendant traversal',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nodeIdCol = options.nodeId ?? 'id';\n\n\t\t\t// Hierarchy helpers historically did NOT propagate inTransaction. Preserve that behavior.\n\t\t\tconst { inTransaction: _ignored, ...hierarchyCtxBase } = queryCtx;\n\t\t\tconst hierarchyCtx: QueryBuilderContext = hierarchyCtxBase;\n\n\t\t\tconst builder = new QueryBuilderImpl<TResult>(\n\t\t\t\thierarchyCtx,\n\t\t\t\ttable,\n\t\t\t\trelationHints,\n\t\t\t);\n\n\t\t\tconst result = await builder\n\t\t\t\t.where(eq(nodeIdCol, nodeIdValue))\n\t\t\t\t.include(selfRefRelation.name, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tdirection: 'descendants',\n\t\t\t\t\tflat: true,\n\t\t\t\t\tomitSelf: true,\n\t\t\t\t\tmaxDepth: safeMaxDepth,\n\t\t\t\t})\n\t\t\t\t.first();\n\n\t\t\t// Result shape from include({ recursive, direction: 'descendants' }):\n\t\t\t// { id, ..., descendants: [...] }\n\t\t\treturn extractRecursiveField<TResult>(result, 'descendants');\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Typed Mutation Entry Points (DX-040-SURFACE)\n\t\t// Extract table name from TableRef metadata and delegate to string methods\n\t\t// =====================================================================\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic constraint — TTable is inferred by callers; TableRef generics are statically erased in this implementation signature\n\t\tinto<TTable extends TableRef<any, any, any>>(\n\t\t\ttableRef: TTable,\n\t\t): InsertBuilder<InferTableRow<TTable>> {\n\t\t\tconst tableName = tableRef[TABLE_META];\n\t\t\tif (tableName === undefined) {\n\t\t\t\tthrow new Error('Invalid TableRef: missing TABLE_META symbol');\n\t\t\t}\n\t\t\treturn new InsertBuilder({\n\t\t\t\ttable: tableName as string,\n\t\t\t\t...mutationOpts,\n\t\t\t}) as InsertBuilder<InferTableRow<TTable>>;\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic constraint — TTable is inferred by callers; TableRef generics are statically erased in this implementation signature\n\t\tmodify<TTable extends TableRef<any, any, any>>(\n\t\t\ttableRef: TTable,\n\t\t): UpdateBuilder<InferTableRow<TTable>> {\n\t\t\tconst tableName = tableRef[TABLE_META];\n\t\t\tif (tableName === undefined) {\n\t\t\t\tthrow new Error('Invalid TableRef: missing TABLE_META symbol');\n\t\t\t}\n\t\t\treturn new UpdateBuilder({\n\t\t\t\ttable: tableName as string,\n\t\t\t\t...mutationOpts,\n\t\t\t}) as UpdateBuilder<InferTableRow<TTable>>;\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic constraint — TTable is inferred by callers; TableRef generics are statically erased in this implementation signature\n\t\tremoveFrom<TTable extends TableRef<any, any, any>>(\n\t\t\ttableRef: TTable,\n\t\t): DeleteBuilder<InferTableRow<TTable>> {\n\t\t\tconst tableName = tableRef[TABLE_META];\n\t\t\tif (tableName === undefined) {\n\t\t\t\tthrow new Error('Invalid TableRef: missing TABLE_META symbol');\n\t\t\t}\n\t\t\treturn new DeleteBuilder({\n\t\t\t\ttable: tableName as string,\n\t\t\t\t...mutationOpts,\n\t\t\t}) as DeleteBuilder<InferTableRow<TTable>>;\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic constraint — TTable is inferred by callers; TableRef generics are statically erased in this implementation signature\n\t\tupsertInto<TTable extends TableRef<any, any, any>>(\n\t\t\ttableRef: TTable,\n\t\t): UpsertBuilder<InferTableRow<TTable>> {\n\t\t\tconst tableName = tableRef[TABLE_META];\n\t\t\tif (tableName === undefined) {\n\t\t\t\tthrow new Error('Invalid TableRef: missing TABLE_META symbol');\n\t\t\t}\n\t\t\treturn new UpsertBuilder({\n\t\t\t\ttable: tableName as string,\n\t\t\t\t...mutationOpts,\n\t\t\t}) as UpsertBuilder<InferTableRow<TTable>>;\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Mutation Methods (DX-010)\n\t\t// =====================================================================\n\n\t\tinsert<K extends keyof DB & string>(table: K): InsertBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new InsertBuilder<DB[K]>({ table, ...mutationOpts });\n\t\t},\n\n\t\tupdate<K extends keyof DB & string>(table: K): UpdateBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new UpdateBuilder<DB[K]>({ table, ...mutationOpts });\n\t\t},\n\n\t\tdelete<K extends keyof DB & string>(table: K): DeleteBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new DeleteBuilder<DB[K]>({ table, ...mutationOpts });\n\t\t},\n\n\t\tupdateAll<K extends keyof DB & string>(table: K): UpdateBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new UpdateBuilder<DB[K]>({\n\t\t\t\ttable,\n\t\t\t\tallowAll: true,\n\t\t\t\t...mutationOpts,\n\t\t\t});\n\t\t},\n\n\t\tdeleteAll<K extends keyof DB & string>(table: K): DeleteBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new DeleteBuilder<DB[K]>({\n\t\t\t\ttable,\n\t\t\t\tallowAll: true,\n\t\t\t\t...mutationOpts,\n\t\t\t});\n\t\t},\n\n\t\t// DX-026: Upsert support\n\t\tupsert<K extends keyof DB & string>(table: K): UpsertBuilder<DB[K]> {\n\t\t\tvalidateIdentifier(table, 'table');\n\t\t\treturn new UpsertBuilder<DB[K]>({ table, ...mutationOpts });\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Transaction Methods (DX-025)\n\t\t// =====================================================================\n\n\t\t// NOT `async`, and that is load-bearing. An async method awaits whatever it\n\t\t// returns and re-wraps it in a fresh Promise — which would mean the language\n\t\t// itself attaches to the adapter's promise, and an adapter that needs to know\n\t\t// whether the CALLER awaited a nested transaction would see every one of them\n\t\t// as awaited, by core, before the caller ever touched it. So the adapter's\n\t\t// promise is passed through untouched. The guards still reject rather than\n\t\t// throwing synchronously, because that is what callers already rely on.\n\t\ttransaction<T>(\n\t\t\tfn: (tx: OrmInstance<DB>) => Promise<T>,\n\t\t\toptions?: TransactionOptions,\n\t\t): Promise<T> {\n\t\t\tif (!adapter) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t'transaction() requires an adapter. ' +\n\t\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tassertConnectionAvailable(adapter, 'transaction()');\n\t\t\t} catch (error) {\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\n\t\t\tif (!supportsTransactions<DB>(adapter)) {\n\t\t\t\treturn Promise.reject(createUnsupportedTransactionError());\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\thasTransactionOptions(options) &&\n\t\t\t\tadapter.capabilities.supportsTransactionOptions !== true\n\t\t\t) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t'This adapter does not support transaction options (isolationLevel/readOnly/lockTimeoutMs/statementTimeoutMs/signal); it does not declare supportsTransactionOptions.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Passthrough to adapter's transaction API.\n\t\t\t//\n\t\t\t// The try/catch is not decoration. This method is NOT async (see above), so\n\t\t\t// an adapter throwing synchronously out of transaction() would throw\n\t\t\t// synchronously out of here — and a method typed `Promise<T>` must reject\n\t\t\t// rather than throw, or `.catch()` and `await expect(...).rejects` stop\n\t\t\t// working on it. The async wrapper converted that for free; dropping it to\n\t\t\t// keep the adapter's promise identity means converting it by hand.\n\t\t\t//\n\t\t\t// The promise itself is still returned untouched. Only a synchronous throw\n\t\t\t// becomes a rejection.\n\t\t\ttry {\n\t\t\t\treturn adapter.transaction(async (txAdapter) => {\n\t\t\t\t\t// Create a transaction-scoped ORM instance with inTransaction=true\n\t\t\t\t\tconst txOrm = createOrmInstance<DB>(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tstrictMode,\n\t\t\t\t\t\trelationHints,\n\t\t\t\t\t\ttxAdapter as Adapter<DB>,\n\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\tdialectCapabilities,\n\t\t\t\t\t\tschemaDefinition,\n\t\t\t\t\t\tglobalPlanOptions,\n\t\t\t\t\t\tdefaultFilters,\n\t\t\t\t\t\thookStore,\n\t\t\t\t\t\tonHookError,\n\t\t\t\t\t\ttrue, // inTransaction\n\t\t\t\t\t\ttablesProxy,\n\t\t\t\t\t\tonObserverError,\n\t\t\t\t\t);\n\t\t\t\t\treturn fn(txOrm);\n\t\t\t\t}, options);\n\t\t\t} catch (error) {\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\t\t},\n\n\t\twithPinnedConnection<T>(\n\t\t\tfn: (pinned: OrmInstance<DB>) => Promise<T>,\n\t\t\toptions?: PinnedConnectionOptions,\n\t\t): Promise<T> {\n\t\t\tif (!adapter) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t'withPinnedConnection() requires an adapter. ' +\n\t\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tassertConnectionAvailable(adapter, 'withPinnedConnection()');\n\t\t\t} catch (error) {\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\n\t\t\tif (!supportsPinnedConnections<DB>(adapter)) {\n\t\t\t\treturn Promise.reject(createUnsupportedPinnedConnectionError());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn adapter.withPinnedConnection(async (pinnedAdapter) => {\n\t\t\t\t\tconst pinnedOrm = createOrmInstance<DB>(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tstrictMode,\n\t\t\t\t\t\trelationHints,\n\t\t\t\t\t\tpinnedAdapter as Adapter<DB>,\n\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\tdialectCapabilities,\n\t\t\t\t\t\tschemaDefinition,\n\t\t\t\t\t\tglobalPlanOptions,\n\t\t\t\t\t\tdefaultFilters,\n\t\t\t\t\t\thookStore,\n\t\t\t\t\t\tonHookError,\n\t\t\t\t\t\tpinnedAdapter.inTransaction,\n\t\t\t\t\t\ttablesProxy,\n\t\t\t\t\t\tonObserverError,\n\t\t\t\t\t);\n\t\t\t\t\treturn fn(pinnedOrm);\n\t\t\t\t}, options);\n\t\t\t} catch (error) {\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Raw SQL Execution (DX-027)\n\t\t// =====================================================================\n\n\t\t/**\n\t\t * Execute raw SQL directly - escape hatch for queries that cannot\n\t\t * be expressed via the intent system.\n\t\t *\n\t\t * @warning **SECURITY RISK: POTENTIAL SQL INJECTION**\n\t\t *\n\t\t * This method bypasses the semantic planner and all type safety.\n\t\t * Always use parameter placeholders ($1, $2, etc.) for values.\n\t\t *\n\t\t * **SAFE:**\n\t\t * ```typescript\n\t\t * orm.raw('SELECT * FROM users WHERE id = $1', [userId]);\n\t\t * ```\n\t\t *\n\t\t * **DANGEROUS - NEVER DO THIS:**\n\t\t * ```typescript\n\t\t * orm.raw(`SELECT * FROM users WHERE id = ${userId}`);\n\t\t * ```\n\t\t *\n\t\t * @param sqlString - SQL with parameter placeholders ($1, $2, etc.)\n\t\t * @param parameters - Values to bind (safely escaped by driver)\n\t\t * @returns Promise resolving to typed results\n\t\t *\n\t\t * @see {@link https://owasp.org/www-community/attacks/SQL_Injection | OWASP SQL Injection}\n\t\t */\n\t\tasync raw<T = unknown>(\n\t\t\tsqlString: string,\n\t\t\tparameters: readonly unknown[] = [],\n\t\t\toptions?: RawReadOptions,\n\t\t): Promise<T[]> {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'raw() requires an adapter. ' +\n\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Passthrough to adapter's executeRaw API\n\t\t\tconst rows = await adapter.executeRaw<T>(sqlString, parameters);\n\t\t\tconst bigintReads = options?.bigintReads;\n\t\t\tif (!bigintReads || Object.keys(bigintReads).length === 0) {\n\t\t\t\treturn rows;\n\t\t\t}\n\t\t\treturn rows.map((row) => applyBigintReads(row, bigintReads));\n\t\t},\n\n\t\tbatchValues(\n\t\t\tdata: readonly unknown[][],\n\t\t\tcolumns: readonly string[],\n\t\t\ttypes: readonly string[],\n\t\t\topts?: BatchValuesOptions,\n\t\t): BatchValuesRef {\n\t\t\treturn batchValues(data, columns, types, opts);\n\t\t},\n\n\t\tselectExpression(expr: ExpressionSpec): SelectExpressionResult {\n\t\t\tif (!adapter) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'selectExpression() requires an adapter. ' +\n\t\t\t\t\t\t'Pass an adapter when creating the ORM.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst compiled = adapter.compileSelectExpression(expr.intent);\n\t\t\treturn {\n\t\t\t\tsql: compiled.sql,\n\t\t\t\tparameters: compiled.parameters,\n\t\t\t\texecute<T = unknown>(): Promise<T[]> {\n\t\t\t\t\treturn adapter?.executeRaw<T>(compiled.sql, compiled.parameters);\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\n\t\twithCte(name: string): CteBuilder {\n\t\t\treturn new CteBuilder(name, adapter, schemaName, model);\n\t\t},\n\n\t\trecursive<TResult = unknown>(\n\t\t\tname: string,\n\t\t\toptions: RecursiveOptions,\n\t\t): RawCteQueryBuilder<TResult> {\n\t\t\treturn createRawCteBuilder<TResult>(\n\t\t\t\tname,\n\t\t\t\toptions,\n\t\t\t\tadapter,\n\t\t\t\tschemaName,\n\t\t\t\tmodel,\n\t\t\t);\n\t\t},\n\n\t\t// =====================================================================\n\t\t// Global DDL Shortcuts (F-005)\n\t\t// =====================================================================\n\n\t\tddl: {\n\t\t\t/**\n\t\t\t * Drop an index by name (not table-scoped).\n\t\t\t *\n\t\t\t * @param name - Index name to drop\n\t\t\t * @param options - Optional DROP INDEX options\n\t\t\t */\n\t\t\tasync dropIndex(name: string, options?: DropIndexOptions): Promise<void> {\n\t\t\t\tif (!adapter?.executeDDL) {\n\t\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t\t'ddl.dropIndex',\n\t\t\t\t\t\t'executeDDL() requires an adapter that supports DDL execution.',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// The table-scoped `.indexes.drop()` refuses this; so must the global\n\t\t\t\t// shortcut. PostgreSQL cannot run DROP INDEX CONCURRENTLY inside a\n\t\t\t\t// transaction block, and reaching the database to be told so aborts the\n\t\t\t\t// transaction you were in.\n\t\t\t\tif (options?.concurrently) {\n\t\t\t\t\tassertOutsideTransaction(\n\t\t\t\t\t\tadapter,\n\t\t\t\t\t\t'dropIndex',\n\t\t\t\t\t\t'DROP INDEX CONCURRENTLY',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// FIND-003: Validate index name and schema before building SQL\n\t\t\t\tvalidateIdentifier(name, 'index');\n\t\t\t\tconst ddlSchemaName = resolveDDLSchemaName(schemaName);\n\t\t\t\tconst sanitizedOptions = sanitizeDropIndexOptions(options);\n\t\t\t\tconst sql = adapter.generateDropIndex\n\t\t\t\t\t? adapter.generateDropIndex(name, ddlSchemaName, sanitizedOptions)\n\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\tconst parts: string[] = ['DROP INDEX'];\n\t\t\t\t\t\t\tif (sanitizedOptions?.concurrently) parts.push('CONCURRENTLY');\n\t\t\t\t\t\t\tif (sanitizedOptions?.ifExists) parts.push('IF EXISTS');\n\t\t\t\t\t\t\tparts.push(\n\t\t\t\t\t\t\t\t`\"${ddlSchemaName.replace(/\"/g, '\"\"')}\".\"${name.replace(/\"/g, '\"\"')}\"`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (sanitizedOptions?.cascade) parts.push('CASCADE');\n\t\t\t\t\t\t\treturn parts.join(' ');\n\t\t\t\t\t\t})();\n\t\t\t\tawait adapter.executeDDL(sql);\n\t\t\t},\n\t\t},\n\t};\n}\n","/**\n * @module dx/hierarchy-helpers\n * Pure helper functions for recursive/hierarchical query support.\n */\n\nimport type { ModelIR } from '../model-ir.js';\n\n/**\n * Extract a named field from a recursive query result.\n *\n * Recursive includes (`ancestors` / `descendants`) add a dynamic property to each row.\n * This helper safely extracts that property without `as any` casts.\n *\n * @internal\n */\nexport function extractRecursiveField<T>(\n\tresult: T | null | undefined,\n\tfield: 'ancestors' | 'descendants',\n): T[] {\n\tif (result == null) return [];\n\tconst row = result as Record<string, unknown>;\n\treturn (row[field] as T[]) ?? [];\n}\n\n/**\n * Find a self-referential relation on a table that matches the desired direction.\n *\n * @param model - The model IR\n * @param table - The table name\n * @param direction - 'ancestors' (needs belongsTo/hasOne) or 'descendants' (needs hasMany)\n * @returns The matching relation or null if not found\n */\nexport function findSelfRefRelation(\n\tmodel: ModelIR,\n\ttable: string,\n\tdirection: 'ancestors' | 'descendants',\n): { name: string; type: string } | null {\n\t// Get all relations from this table\n\tconst tableRelations = model.getRelationsFrom(table);\n\tif (!tableRelations || tableRelations.length === 0) {\n\t\treturn null;\n\t}\n\n\t// Find self-referential relations that match the direction\n\tfor (const relation of tableRelations) {\n\t\t// Must be self-referential\n\t\tif (relation.source !== relation.target) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if direction matches relation type\n\t\tif (direction === 'ancestors') {\n\t\t\t// Need belongsTo or hasOne for ancestor traversal\n\t\t\tif (relation.type === 'belongsTo' || relation.type === 'hasOne') {\n\t\t\t\treturn { name: relation.name, type: relation.type };\n\t\t\t}\n\t\t} else {\n\t\t\t// Need hasMany for descendant traversal\n\t\t\tif (relation.type === 'hasMany') {\n\t\t\t\treturn { name: relation.name, type: relation.type };\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n","/**\n * @fileoverview Shared existence-check intent construction (#230).\n *\n * `buildExistsIntent()` was duplicated (three copies — the plain builder path\n * in both `typed-query-builder.ts` and `query-builder.ts`, plus the hook-aware\n * path's `buildExistsIntentFromIntent()` in `query-builder.ts`), and every\n * copy unconditionally stripped `include` from the intent. That silently\n * discarded a filtering include's JOIN/WHERE from an EXISTS check whenever\n * the include carried row-restricting power (`join: 'inner'`, `left` +\n * `where`, etc.) — `.exists()` then returned wrong results (#230).\n *\n * Correct-by-construction design: the exists intent is the full base intent,\n * unchanged, with `orderBy` stripped (irrelevant once wrapped in EXISTS) and\n * `existsWrap`/`limit: 1` added. NOTHING prunes `include` — not here, not in\n * the planner, not in the compiler. Every include is planned and compiled\n * exactly as for the full query; the adapter's existsWrap wrap then replaces\n * the SELECT target list with `1`. That single swap is what makes pruning\n * unnecessary AND correct:\n *\n * - Target-list hydration (the default `json_agg` strategy, a scalar\n * subquery in the SELECT list) is discarded for free — zero FROM cost.\n * - FROM joins (`inner`/`left`/`lateral`/`cte`, including recursive CTEs)\n * ride along untouched, so they filter (inner / include `where`) and\n * multiply (to-many, for `offset`/`groupBy`/`having`) EXACTLY as they do\n * in the full query — the exists FROM clause is identical to it.\n *\n * Any strategy-based pruning is unsound: whether an include can change the\n * existence result depends on its RESOLVED strategy plus aggregate-vs-multiply\n * plus cardinality plus the presence of `offset`/`groupBy`/`having` — the full\n * compiler semantics. Three prior pruning attempts (intent-shape, planner\n * resolved-strategy, compiler decision-guard) each leaked a wrong-result or\n * regression case. Keeping everything sidesteps the whole class.\n *\n * Consequences of keeping every include (intentional — the price of soundness):\n * - `.exists()` on a recursive include builds its CTE, and throws on a dialect\n * without `supportsRecursiveCTE`, just like the full query — not a cheaper\n * shortcut.\n * - `.exists()` PLANS every include, so an invalid include (a strict-mode\n * ambiguous relation, an unsupported forced strategy, an invalid recursive\n * flag) throws during planning EXACTLY as `.dump()`/`.all()` would — even\n * for a default `json_agg` include whose hydration `existsWrap` later\n * discards from the SQL. This is deliberate: `.exists()` and the full query\n * share one query builder and must agree on validity; making `.exists()`\n * silently accept an include the full query rejects would require guessing,\n * pre-planning, which includes are \"discarded\" — the unsound pruning above.\n * Consistency (\"if `.dump()` throws, `.exists()` throws\") beats a\n * lightweight-but-divergent check.\n *\n * This module only builds the exists intent; it never inspects or prunes\n * `include`.\n */\n\nimport type { QueryIntent } from '../intent-ast.js';\n\n/**\n * Build an existence-check intent from a base QueryIntent.\n *\n * Strips `orderBy` (irrelevant once wrapped in EXISTS), sets `existsWrap` and\n * `limit: 1`, and keeps every include unchanged. Nothing prunes includes: the\n * adapter's existsWrap wrap replaces the target list with `1`, which discards\n * target-list hydration for free and lets FROM joins ride along and\n * filter/multiply exactly as in the full query (see module doc).\n *\n * @param baseIntent - The intent to wrap (built via the caller's own `buildIntent()`).\n */\nexport function buildExistsIntent(baseIntent: QueryIntent): QueryIntent {\n\tconst { orderBy: _orderBy, ...rest } = baseIntent as QueryIntent & {\n\t\torderBy?: unknown;\n\t};\n\t// EXISTS only needs to know whether ≥1 row survives the query's offset, so a\n\t// LIMIT of 1 is sufficient (and cheapest) for any positive user limit. But an\n\t// explicit `.limit(0)` means \"no rows\" — the result set is empty, so\n\t// existence must be false. Preserve that 0; cap everything else to 1.\n\tconst existsLimit = baseIntent.limit === 0 ? 0 : 1;\n\treturn { ...rest, existsWrap: true, limit: existsLimit };\n}\n","/**\n * Pagination implementation extracted from QueryBuilderImpl.\n *\n * Free functions that accept a QueryBuilderImpl instance and implement the\n * paginate / cursorPaginate logic. They access only fields and methods\n * declared @internal public on QueryBuilderImpl.\n *\n * @internal\n */\n\nimport type { OrderByIntent, WhereIntent } from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\nimport { InvalidOperationError } from './errors.js';\nimport type { QueryBuilderImpl } from './query-builder.js';\nimport type {\n\tCursorPaginatedResult,\n\tCursorPaginateOptions,\n\tPaginatedResult,\n\tPaginateOptions,\n\tSortDirection,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Internal cursor key resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the cursor key for an orderBy entry.\n * Returns null for expression-based entries without an alias (FIND-019).\n */\nfunction resolveCursorKey(orderBy: OrderByIntent): string | null {\n\tif (typeof orderBy === 'string') return orderBy;\n\tif (typeof orderBy.field === 'string') return orderBy.field;\n\tconst alias = (orderBy as { alias?: string }).alias;\n\treturn alias ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// buildCursorConditions\n// ---------------------------------------------------------------------------\n\n/**\n * Build cursor conditions for cursor pagination.\n * FIND-019: expression-based orderBy (fn(), caseWhen()) has no .field — require\n * alias or return null so the caller skips the condition gracefully.\n *\n * @internal\n */\nexport function buildCursorConditions<TResult>(\n\tbuilder: QueryBuilderImpl<TResult>,\n\tcursorValues: Record<string, unknown>,\n\tdirection: 'forward' | 'backward',\n): WhereIntent | null {\n\tif (builder.orderByIntents.length === 1) {\n\t\tconst orderBy = builder.orderByIntents[0];\n\t\tif (!orderBy) return null;\n\n\t\tconst field = resolveCursorKey(orderBy);\n\t\tif (field === null) return null;\n\n\t\tconst sortDir =\n\t\t\ttypeof orderBy === 'string'\n\t\t\t\t? 'asc'\n\t\t\t\t: ((orderBy.direction as string) ?? 'asc');\n\t\tconst cursorValue = cursorValues[field];\n\n\t\tif (cursorValue === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isAsc =\n\t\t\tsortDir === 'asc' ? direction === 'forward' : direction === 'backward';\n\t\treturn {\n\t\t\tkind: 'comparison',\n\t\t\tfield,\n\t\t\toperator: isAsc ? 'gt' : 'lt',\n\t\t\tvalue: cursorValue,\n\t\t};\n\t}\n\n\tconst conditions: WhereIntent[] = [];\n\n\tfor (let i = 0; i < builder.orderByIntents.length; i++) {\n\t\tconst parts: WhereIntent[] = [];\n\n\t\tfor (let j = 0; j <= i; j++) {\n\t\t\tconst orderBy = builder.orderByIntents[j];\n\t\t\tif (!orderBy) continue;\n\n\t\t\tconst field = resolveCursorKey(orderBy);\n\t\t\tif (field === null) continue;\n\n\t\t\tconst sortDir =\n\t\t\t\ttypeof orderBy === 'string'\n\t\t\t\t\t? 'asc'\n\t\t\t\t\t: ((orderBy.direction as string) ?? 'asc');\n\t\t\tconst cursorValue = cursorValues[field];\n\n\t\t\tif (cursorValue === undefined) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif (j < i) {\n\t\t\t\tparts.push({\n\t\t\t\t\tkind: 'comparison',\n\t\t\t\t\tfield,\n\t\t\t\t\toperator: 'eq',\n\t\t\t\t\tvalue: cursorValue,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst isAsc =\n\t\t\t\t\tsortDir === 'asc'\n\t\t\t\t\t\t? direction === 'forward'\n\t\t\t\t\t\t: direction === 'backward';\n\t\t\t\tparts.push({\n\t\t\t\t\tkind: 'comparison',\n\t\t\t\t\tfield,\n\t\t\t\t\toperator: isAsc ? 'gt' : 'lt',\n\t\t\t\t\tvalue: cursorValue,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (parts.length > 0) {\n\t\t\tconditions.push(\n\t\t\t\tparts.length === 1\n\t\t\t\t\t? (parts[0] as WhereIntent)\n\t\t\t\t\t: { kind: 'and', conditions: parts },\n\t\t\t);\n\t\t}\n\t}\n\n\tif (conditions.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst firstCondition = conditions[0];\n\treturn conditions.length === 1 && firstCondition !== undefined\n\t\t? firstCondition\n\t\t: { kind: 'or', conditions };\n}\n\n// ---------------------------------------------------------------------------\n// buildCursor\n// ---------------------------------------------------------------------------\n\n/**\n * Build cursor from a row using orderBy fields.\n * FIND-019: expression-based orderBy entries (fn(), caseWhen(), etc.) have no\n * .field string. Require an explicit alias or throw.\n *\n * @internal\n */\nexport function buildCursor<TResult>(\n\tbuilder: QueryBuilderImpl<TResult>,\n\trow: Record<string, unknown>,\n): string {\n\tconst cursorData: Record<string, unknown> = Object.create(null);\n\n\tfor (const orderBy of builder.orderByIntents) {\n\t\tif (!orderBy) continue;\n\t\tif (typeof orderBy === 'string') {\n\t\t\tcursorData[orderBy] = row[orderBy];\n\t\t} else {\n\t\t\tconst field = orderBy.field;\n\t\t\tif (typeof field === 'string') {\n\t\t\t\tcursorData[field] = row[field];\n\t\t\t} else {\n\t\t\t\tconst alias = (orderBy as { alias?: string }).alias;\n\t\t\t\tif (!alias) {\n\t\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t\t'cursorPaginate',\n\t\t\t\t\t\t'cursorPaginate requires orderBy entries with a string column name or an explicit alias. ' +\n\t\t\t\t\t\t\t'Use .orderBy(fn(...).as(\"alias\")) or .orderBy(\"column\") to enable cursor-based pagination.',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcursorData[alias] = row[alias];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Buffer.from(JSON.stringify(cursorData), 'utf-8').toString('base64');\n}\n\n// ---------------------------------------------------------------------------\n// paginate\n// ---------------------------------------------------------------------------\n\n/**\n * Execute offset-based pagination for a QueryBuilderImpl.\n *\n * @internal\n */\nexport async function paginate<TResult>(\n\tbuilder: QueryBuilderImpl<TResult>,\n\toptions?: PaginateOptions,\n): Promise<PaginatedResult<TResult>> {\n\tconst page = options?.page ?? 1;\n\tconst perPage = options?.perPage ?? 20;\n\tconst withCount = options?.withCount ?? true;\n\n\tif (!Number.isSafeInteger(page) || page < 1) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'paginate',\n\t\t\t'page must be a positive safe integer. Use page: 1 for the first page',\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(perPage) || perPage < 1) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'paginate',\n\t\t\t'perPage must be a positive safe integer',\n\t\t);\n\t}\n\n\tconst offset = (page - 1) * perPage;\n\n\tconst paginatedBuilder = builder.clone();\n\tpaginatedBuilder.limitValue = perPage;\n\tpaginatedBuilder.offsetValue = offset;\n\n\tconst data = await paginatedBuilder.all();\n\n\tlet total: number | undefined;\n\tlet totalPages: number | undefined;\n\n\tif (withCount) {\n\t\t// FIND-018 (M-1 fix): when groupBy or explicit joins are present, compile\n\t\t// the base query as a subquery and wrap it with SELECT COUNT(*) FROM (...)\n\t\t// to always get a single scalar regardless of query shape.\n\t\t// For simple queries (no groupBy, no joins), the direct COUNT(*) path\n\t\t// is retained for efficiency.\n\t\tconst adapter = builder.getConfiguredAdapter();\n\t\tconst compileOptions: { schemaName?: string; model: ModelIR } = {\n\t\t\tmodel: builder.ctx.model,\n\t\t};\n\t\tif (builder.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = builder.ctx.schemaName;\n\t\t}\n\n\t\tconst hasGroupBy = builder.groupByFields.length > 0;\n\t\tconst hasJoins = builder.joinIntents.length > 0;\n\n\t\tif (hasGroupBy || hasJoins) {\n\t\t\tconst baseBuilder = builder.clone();\n\t\t\tbaseBuilder.limitValue = undefined;\n\t\t\tbaseBuilder.offsetValue = undefined;\n\t\t\tbaseBuilder.orderByIntents.splice(0);\n\t\t\tbaseBuilder.includes.splice(0);\n\t\t\tbaseBuilder.recursiveIncludes.splice(0);\n\t\t\tbaseBuilder.aggregates.splice(0);\n\t\t\tbaseBuilder.selectIntent = undefined;\n\n\t\t\tconst basePlan = baseBuilder.plan();\n\t\t\tconst baseCompiled = adapter.compile(basePlan, compileOptions);\n\n\t\t\tconst wrapSql = `SELECT COUNT(*) AS \"_count\" FROM (${baseCompiled.sql}) _count_subq`;\n\t\t\tconst wrapResult = await adapter.executeRaw<{ _count: string | number }>(\n\t\t\t\twrapSql,\n\t\t\t\tbaseCompiled.parameters,\n\t\t\t);\n\t\t\ttotal = Number(wrapResult[0]?._count ?? 0);\n\t\t} else {\n\t\t\tconst countBuilder = builder.clone() as unknown as QueryBuilderImpl<{\n\t\t\t\t_count: number;\n\t\t\t}>;\n\t\t\tcountBuilder.limitValue = undefined;\n\t\t\tcountBuilder.offsetValue = undefined;\n\t\t\tcountBuilder.orderByIntents.splice(0);\n\t\t\tcountBuilder.aggregates.splice(0, countBuilder.aggregates.length, {\n\t\t\t\tfunction: 'count',\n\t\t\t\tas: '_count',\n\t\t\t});\n\t\t\tcountBuilder.includes.splice(0);\n\t\t\tcountBuilder.recursiveIncludes.splice(0);\n\t\t\tcountBuilder.selectIntent = undefined;\n\n\t\t\tconst countResult = await countBuilder.all();\n\t\t\ttotal = Number(countResult[0]?._count ?? 0);\n\t\t}\n\t\ttotalPages = Math.ceil(total / perPage);\n\t}\n\n\tconst hasNextPage = withCount\n\t\t? page < (totalPages ?? 1)\n\t\t: data.length === perPage;\n\tconst hasPrevPage = page > 1;\n\n\treturn {\n\t\tdata,\n\t\tpagination: {\n\t\t\tpage,\n\t\t\tperPage,\n\t\t\t...(total !== undefined && { total }),\n\t\t\t...(totalPages !== undefined && { totalPages }),\n\t\t\thasNextPage,\n\t\t\thasPrevPage,\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// cursorPaginate\n// ---------------------------------------------------------------------------\n\n/**\n * Execute cursor-based pagination for a QueryBuilderImpl.\n *\n * @internal\n */\nexport async function cursorPaginate<TResult>(\n\tbuilder: QueryBuilderImpl<TResult>,\n\toptions?: CursorPaginateOptions,\n): Promise<CursorPaginatedResult<TResult>> {\n\tconst limit = options?.limit ?? 20;\n\tconst cursor = options?.cursor ?? null;\n\tconst direction = options?.direction ?? 'forward';\n\n\t// FIND-021: Validate limit is a safe non-negative integer (0 is accepted — returns empty page)\n\tif (!Number.isSafeInteger(limit) || limit < 0) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'cursorPaginate',\n\t\t\t'limit must be a non-negative safe integer',\n\t\t);\n\t}\n\n\t// Require orderBy for stable cursor pagination\n\tif (builder.orderByIntents.length === 0) {\n\t\tthrow new InvalidOperationError(\n\t\t\t'cursorPaginate',\n\t\t\t'Cursor pagination requires an orderBy clause. Add .orderBy(\"id\") or similar before .cursorPaginate()',\n\t\t);\n\t}\n\n\t// Decode cursor if provided\n\tlet cursorValues: Record<string, unknown> | null = null;\n\tif (cursor) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(Buffer.from(cursor, 'base64').toString('utf-8'));\n\t\t} catch {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'cursorPaginate',\n\t\t\t\t'Invalid cursor format. Use a cursor returned from a previous cursorPaginate() call',\n\t\t\t);\n\t\t}\n\t\t// FIND-004: Validate cursor decodes to a plain object (not array/primitive)\n\t\tif (\n\t\t\ttypeof parsed !== 'object' ||\n\t\t\tparsed === null ||\n\t\t\tArray.isArray(parsed)\n\t\t) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'cursorPaginate',\n\t\t\t\t'Invalid cursor: must decode to an object',\n\t\t\t);\n\t\t}\n\t\t// Use Object.create(null)-safe iteration to avoid prototype pollution\n\t\tconst safeValues: Record<string, unknown> = Object.create(null);\n\t\tfor (const key of Object.keys(parsed)) {\n\t\t\tif (Object.hasOwn(parsed as Record<string, unknown>, key)) {\n\t\t\t\t(safeValues as Record<string, unknown>)[key] = (\n\t\t\t\t\tparsed as Record<string, unknown>\n\t\t\t\t)[key];\n\t\t\t}\n\t\t}\n\t\tcursorValues = safeValues;\n\t}\n\n\t// Build cursor conditions based on orderBy fields\n\tconst paginatedBuilder = builder.clone();\n\tif (cursorValues) {\n\t\tconst cursorConditions = buildCursorConditions(\n\t\t\tbuilder,\n\t\t\tcursorValues,\n\t\t\tdirection,\n\t\t);\n\t\tif (cursorConditions) {\n\t\t\tpaginatedBuilder.whereIntents.push(cursorConditions);\n\t\t}\n\t}\n\n\t// FIND-020: For backward pagination, invert every ORDER BY direction so the\n\t// DB returns rows immediately BEFORE the cursor. We then reverse the result\n\t// slice to restore the original ordering for the caller.\n\tif (direction === 'backward') {\n\t\tpaginatedBuilder.orderByIntents.splice(\n\t\t\t0,\n\t\t\tpaginatedBuilder.orderByIntents.length,\n\t\t\t...paginatedBuilder.orderByIntents.map((ob) => ({\n\t\t\t\t...ob,\n\t\t\t\tdirection: (ob.direction === 'asc' ? 'desc' : 'asc') as SortDirection,\n\t\t\t})),\n\t\t);\n\t}\n\n\t// Fetch one extra to determine if there's a next page\n\tpaginatedBuilder.limitValue = limit + 1;\n\n\t// Execute query\n\tconst rawResults = await paginatedBuilder.all();\n\n\tconst hasMore = rawResults.length > limit;\n\tconst sliced = hasMore ? rawResults.slice(0, limit) : rawResults;\n\n\t// For backward direction, reverse results to restore original ordering\n\tconst data = direction === 'backward' ? sliced.slice().reverse() : sliced;\n\n\tconst nextCursor =\n\t\thasMore && data.length > 0\n\t\t\t? buildCursor(builder, data[data.length - 1] as Record<string, unknown>)\n\t\t\t: null;\n\tconst prevCursor =\n\t\tdata.length > 0\n\t\t\t? buildCursor(builder, data[0] as Record<string, unknown>)\n\t\t\t: null;\n\n\treturn {\n\t\tdata,\n\t\tnextCursor,\n\t\tprevCursor:\n\t\t\tdirection === 'forward' ? (cursor ? prevCursor : null) : prevCursor,\n\t\thasNextPage: direction === 'forward' ? hasMore : cursor !== null,\n\t\thasPrevPage: direction === 'forward' ? cursor !== null : hasMore,\n\t};\n}\n","/**\n * ResultHydrator - Handles result hydration and recursive include processing.\n *\n * DX-103: Extracted from QueryBuilderImpl to subquery hydration logic\n * from intent building and query execution.\n *\n * @module result-hydrator\n */\n\nimport { toColumnList } from '@dbsp/types';\nimport type { Mutable } from '@dbsp/types/internal';\nimport {\n\ttype Adapter,\n\ttype CompiledQuery,\n\ttype CompileOptions,\n\texecuteCompiledQuery,\n\ttype SubqueryIncludeInfo,\n} from '../adapter.js';\nimport type { RecursiveIntent, WhereIntent } from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\nimport type { PlanReport } from '../planner.js';\nimport { planRecursive } from '../planner.js';\nimport { RelationNotFoundError } from './errors.js';\nimport {\n\thydrateJsonAggIncludes as hydrateJsonAggIncludesShared,\n\tplanForJsonAggHydration,\n} from './hydration-utils.js';\nimport type { RecursiveIncludeConfig } from './intent-builder.js';\nimport {\n\tcountDistinctRelationPathsByName,\n\tderiveRelationPathFromIntentPath,\n} from './relation-paths.js';\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/** A database result row — typed loosely since row shapes are dynamic. */\ntype ResultRow = Record<string, unknown>;\n\n/**\n * Options for hydrating includes.\n * Requires model (unlike CompileOptions where it's optional).\n */\nexport type HydrateOptions = Omit<CompileOptions, 'model'> & { model: ModelIR };\n\n// ============================================================================\n// ResultHydrator\n// ============================================================================\n\n/**\n * Handles result hydration including:\n * - Subquery include hydration for hasMany relations\n * - Recursive include processing via CTEs\n * - Building nested hierarchies from flat results\n *\n * @typeParam TResult - The expected result type\n */\n\n/**\n * NUL byte (U+0000) used as the composite-key separator. Kept as a named\n * constant because literal control characters are invisible in diffs and\n * can be corrupted by editor normalization.\n */\nconst COMPOSITE_KEY_SEP = '\\0';\n\ntype JoinHydrationInfo = {\n\treadonly relationPath: string;\n\treadonly segments: readonly string[];\n\treadonly keyPrefix: string;\n\treadonly keyPrefixWithDot: string;\n};\n\nfunction stringProp(\n\tsource: Record<string, unknown> | undefined,\n\tkey: string,\n): string | undefined {\n\tconst value = source?.[key];\n\treturn typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction resolveJoinIncludePath(\n\tplanReport: PlanReport,\n\tdecision: PlanReport['decisions'][number],\n): string | undefined {\n\tconst context = decision.context;\n\tconst decisionRecord = decision as unknown as Record<string, unknown>;\n\tconst contextRecord = context as Record<string, unknown> | undefined;\n\tconst explicitRelationPath =\n\t\tstringProp(decisionRecord, 'relationPath') ??\n\t\tstringProp(contextRecord, 'relationPath');\n\tif (explicitRelationPath) return explicitRelationPath;\n\n\tconst fallbackRelation =\n\t\tstringProp(contextRecord, 'relation') ??\n\t\tstringProp(contextRecord, 'includeAlias') ??\n\t\tstringProp(decisionRecord, 'relationName');\n\tconst intentPath = stringProp(contextRecord, 'intentPath');\n\n\treturn deriveRelationPathFromIntentPath(\n\t\tArray.isArray(planReport.intent?.include)\n\t\t\t? (planReport.intent.include as readonly unknown[])\n\t\t\t: undefined,\n\t\tintentPath,\n\t\tfallbackRelation,\n\t);\n}\n\nfunction lastRelationSegment(path: string): string {\n\tconst segments = path.split('.');\n\treturn segments[segments.length - 1] ?? path;\n}\n\nfunction resolveJoinRelationName(\n\tdecision: PlanReport['decisions'][number],\n\trelationPath: string,\n): string {\n\tconst context = decision.context as Record<string, unknown> | undefined;\n\tconst decisionRecord = decision as unknown as Record<string, unknown>;\n\treturn (\n\t\tstringProp(context, 'relation') ??\n\t\tstringProp(context, 'includeAlias') ??\n\t\tstringProp(decisionRecord, 'relationName') ??\n\t\tlastRelationSegment(relationPath)\n\t);\n}\n\nfunction collectJoinHydrationInfos(\n\tplanReport: PlanReport,\n): JoinHydrationInfo[] {\n\tconst candidates: Array<{\n\t\trelationName: string;\n\t\trelationPath: string;\n\t\thydrationPrefix?: string;\n\t}> = [];\n\n\tfor (const decision of planReport.decisions) {\n\t\tif (decision.type !== 'include-strategy' || decision.choice !== 'join') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst relationPath = resolveJoinIncludePath(planReport, decision);\n\t\tif (!relationPath) continue;\n\n\t\tconst relationName = resolveJoinRelationName(decision, relationPath);\n\t\tconst decisionRecord = decision as unknown as Record<string, unknown>;\n\t\tconst contextRecord = decision.context as\n\t\t\t| Record<string, unknown>\n\t\t\t| undefined;\n\t\tconst hydrationPrefix =\n\t\t\tstringProp(decisionRecord, 'hydrationPrefix') ??\n\t\t\tstringProp(contextRecord, 'hydrationPrefix');\n\n\t\tcandidates.push({\n\t\t\trelationName,\n\t\t\trelationPath,\n\t\t\t...(hydrationPrefix && { hydrationPrefix }),\n\t\t});\n\t}\n\n\tconst pathCountsByRelationName = countDistinctRelationPathsByName(candidates);\n\tconst infosByPath = new Map<string, JoinHydrationInfo>();\n\tfor (const candidate of candidates) {\n\t\tif (infosByPath.has(candidate.relationPath)) continue;\n\n\t\tconst usesFullPath =\n\t\t\t(pathCountsByRelationName.get(candidate.relationName) ?? 0) > 1;\n\t\tconst keyPrefix =\n\t\t\tcandidate.hydrationPrefix ??\n\t\t\t(usesFullPath ? candidate.relationPath : candidate.relationName);\n\t\tif (!keyPrefix) continue;\n\n\t\tinfosByPath.set(candidate.relationPath, {\n\t\t\trelationPath: candidate.relationPath,\n\t\t\tsegments: candidate.relationPath.split('.'),\n\t\t\tkeyPrefix,\n\t\t\tkeyPrefixWithDot: `${keyPrefix}.`,\n\t\t});\n\t}\n\n\treturn [...infosByPath.values()];\n}\n\nfunction findLongestJoinInfo(\n\tkey: string,\n\tinfos: readonly JoinHydrationInfo[],\n): JoinHydrationInfo | undefined {\n\tlet best: JoinHydrationInfo | undefined;\n\tfor (const info of infos) {\n\t\tif (!key.startsWith(info.keyPrefixWithDot)) continue;\n\t\tif (!best || info.keyPrefixWithDot.length > best.keyPrefixWithDot.length) {\n\t\t\tbest = info;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction assignNestedValue(\n\ttarget: Record<string, unknown>,\n\tpath: readonly string[],\n\tvalue: unknown,\n): void {\n\tlet cursor = target;\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst segment = path[i];\n\t\tif (!segment) return;\n\t\tconst existing = cursor[segment];\n\t\tif (existing === null) {\n\t\t\t// Parent-null precedence: a LEFT JOIN miss for an ancestor must not be\n\t\t\t// resurrected by deeper fallback keys from the same flat row.\n\t\t\treturn;\n\t\t} else if (typeof existing !== 'object' || Array.isArray(existing)) {\n\t\t\tcursor[segment] = {};\n\t\t}\n\t\tcursor = cursor[segment] as Record<string, unknown>;\n\t}\n\n\tconst leaf = path[path.length - 1];\n\tif (leaf) cursor[leaf] = value;\n}\n\nfunction assignColumnValue(\n\ttarget: Record<string, unknown>,\n\tcolumnPath: string,\n\tvalue: unknown,\n): void {\n\tconst segments = columnPath.split('.').filter(Boolean);\n\tif (segments.length === 0) return;\n\tassignNestedValue(target, segments, value);\n}\n\nexport class ResultHydrator<TResult = unknown> {\n\tprivate readonly model: ModelIR;\n\tprivate readonly from: string;\n\tprivate readonly schemaName: string | undefined;\n\n\tconstructor(model: ModelIR, from: string, schemaName?: string) {\n\t\tthis.model = model;\n\t\tthis.from = from;\n\t\tthis.schemaName = schemaName;\n\t}\n\n\t/**\n\t * Hydrate subquery includes (hasMany relations) into main results.\n\t */\n\tasync hydrateIncludes(\n\t\tresults: TResult[],\n\t\tsubqueryIncludes: readonly SubqueryIncludeInfo[],\n\t\tadapter: Adapter,\n\t\tcompileOptions: HydrateOptions,\n\t): Promise<void> {\n\t\tif (results.length === 0) return;\n\n\t\tfor (const includeInfo of subqueryIncludes) {\n\t\t\t// Extract parent IDs from results using sourceKey.\n\t\t\t// PERF (FIND-054): single-pass for-loop avoids the intermediate array\n\t\t\t// that .map().filter() allocates (2 passes + length-N temp array).\n\t\t\tconst parentIds: unknown[] = [];\n\t\t\tfor (const r of results) {\n\t\t\t\tconst id = this.extractQueryKeyValue(\n\t\t\t\t\tr as Record<string, unknown>,\n\t\t\t\t\tincludeInfo.sourceKey,\n\t\t\t\t);\n\t\t\t\tif (id !== undefined && id !== null) parentIds.push(id);\n\t\t\t}\n\n\t\t\tif (parentIds.length === 0) continue;\n\n\t\t\t// Compile and execute the include query\n\t\t\tconst includeQuery = adapter.compileSubqueryInclude(\n\t\t\t\tincludeInfo,\n\t\t\t\tparentIds,\n\t\t\t\tcompileOptions,\n\t\t\t);\n\t\t\tconst childResults = await executeCompiledQuery(\n\t\t\t\tadapter,\n\t\t\t\tincludeQuery,\n\t\t\t\t'all()',\n\t\t\t);\n\n\t\t\t// Group children by foreign key\n\t\t\tconst childrenByParentId = new Map<unknown, unknown[]>();\n\t\t\tfor (const child of childResults) {\n\t\t\t\tconst parentId = this.extractKeyValue(\n\t\t\t\t\tchild as Record<string, unknown>,\n\t\t\t\t\tincludeInfo.foreignKey,\n\t\t\t\t);\n\t\t\t\tif (parentId !== undefined) {\n\t\t\t\t\tconst existing = childrenByParentId.get(parentId);\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\texisting.push(child);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchildrenByParentId.set(parentId, [child]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Attach children to parent objects\n\t\t\t// For to-one relations (belongsTo/hasOne), unwrap to single object\n\t\t\tconst isToOne =\n\t\t\t\tincludeInfo.relationType === 'belongsTo' ||\n\t\t\t\tincludeInfo.relationType === 'hasOne';\n\t\t\tfor (const result of results) {\n\t\t\t\tconst parentId = this.extractKeyValue(\n\t\t\t\t\tresult as Record<string, unknown>,\n\t\t\t\t\tincludeInfo.sourceKey,\n\t\t\t\t);\n\t\t\t\tconst children = childrenByParentId.get(parentId) ?? [];\n\t\t\t\t(result as Record<string, unknown>)[includeInfo.relationName] = isToOne\n\t\t\t\t\t? (children[0] ?? null)\n\t\t\t\t\t: children;\n\t\t\t}\n\n\t\t\t// Process nested includes recursively if present\n\t\t\tif (includeInfo.nestedIncludes && includeInfo.nestedIncludes.length > 0) {\n\t\t\t\t// Flatten all children for nested hydration.\n\t\t\t\t// PERF (FIND-055): avoid Array.from().flat() which allocates an array-of-arrays\n\t\t\t\t// then flattens it; a double for-loop uses a single allocation.\n\t\t\t\tconst allChildren: Record<string, unknown>[] = [];\n\t\t\t\tfor (const arr of childrenByParentId.values()) {\n\t\t\t\t\tfor (const item of arr)\n\t\t\t\t\t\tallChildren.push(item as Record<string, unknown>);\n\t\t\t\t}\n\t\t\t\tif (allChildren.length > 0) {\n\t\t\t\t\tawait this.hydrateIncludes(\n\t\t\t\t\t\tallChildren as TResult[],\n\t\t\t\t\t\tincludeInfo.nestedIncludes,\n\t\t\t\t\t\tadapter,\n\t\t\t\t\t\tcompileOptions,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Hydrate JOIN includes by grouping dot-prefixed columns into nested objects.\n\t * E2E-004: JOIN strategy for to-one relations returns columns like \"author.id\", \"author.name\".\n\t */\n\thydrateJoinIncludes(results: TResult[], planReport: PlanReport): void {\n\t\tconst joinInfos = collectJoinHydrationInfos(planReport);\n\t\tif (joinInfos.length === 0) return;\n\t\tconst infosByDepth = [...joinInfos].sort(\n\t\t\t(a, b) => a.segments.length - b.segments.length,\n\t\t);\n\n\t\t// Process each result row\n\t\tfor (const row of results) {\n\t\t\tif (typeof row !== 'object' || row === null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst record = row as Record<string, unknown>;\n\t\t\tconst valuesByPath = new Map<\n\t\t\t\tstring,\n\t\t\t\t{ values: Record<string, unknown>; allNull: boolean }\n\t\t\t>();\n\n\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\tconst info = findLongestJoinInfo(key, joinInfos);\n\t\t\t\tif (!info) continue;\n\n\t\t\t\tconst value = record[key];\n\t\t\t\tlet entry = valuesByPath.get(info.relationPath);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tentry = { values: {}, allNull: true };\n\t\t\t\t\tvaluesByPath.set(info.relationPath, entry);\n\t\t\t\t}\n\t\t\t\tassignColumnValue(\n\t\t\t\t\tentry.values,\n\t\t\t\t\tkey.slice(info.keyPrefixWithDot.length),\n\t\t\t\t\tvalue,\n\t\t\t\t);\n\t\t\t\tif (value !== null && value !== undefined) entry.allNull = false;\n\t\t\t\tdelete record[key];\n\t\t\t}\n\n\t\t\tfor (const info of infosByDepth) {\n\t\t\t\tconst entry = valuesByPath.get(info.relationPath);\n\t\t\t\tif (!entry) continue;\n\t\t\t\tassignNestedValue(\n\t\t\t\t\trecord,\n\t\t\t\t\tinfo.segments,\n\t\t\t\t\tentry.allNull ? null : entry.values,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Hydrate json_agg includes by parsing JSON columns and renaming them.\n\t * E2E-004: json_agg strategy returns data as JSON string in *_json columns.\n\t * STRAT-SIMPLIFY: For to-one relations (belongsTo/hasOne), unwrap array to single object.\n\t */\n\thydrateJsonAggIncludes(\n\t\tresults: TResult[],\n\t\tplanReport: PlanReport,\n\t\tquery?: CompiledQuery,\n\t): void {\n\t\thydrateJsonAggIncludesShared(\n\t\t\tresults,\n\t\t\tplanForJsonAggHydration(planReport, query),\n\t\t\tthis.model,\n\t\t);\n\t}\n\n\t/**\n\t * Process recursive includes via CTEs.\n\t */\n\tasync processRecursiveIncludes(\n\t\tresults: unknown[],\n\t\trecursiveIncludes: readonly RecursiveIncludeConfig[],\n\t\tadapter: Adapter,\n\t): Promise<void> {\n\t\tif (results.length === 0) return;\n\n\t\tfor (const config of recursiveIncludes) {\n\t\t\tawait this.processOneRecursiveInclude(\n\t\t\t\tresults as ResultRow[],\n\t\t\t\tconfig,\n\t\t\t\tadapter,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Process a single recursive include.\n\t */\n\tprivate async processOneRecursiveInclude(\n\t\tresults: ResultRow[],\n\t\tconfig: RecursiveIncludeConfig,\n\t\tadapter: Adapter,\n\t): Promise<void> {\n\t\tconst { relation, options } = config;\n\t\tconst {\n\t\t\tdirection,\n\t\t\tflat = false,\n\t\t\tomitSelf = false,\n\t\t\tmaxDepth = 100,\n\t\t\tincludeDepth = false,\n\t\t} = options;\n\n\t\t// Get relation metadata\n\t\tconst qualifiedName = `${this.from}.${relation}`;\n\t\tconst relationMeta = this.model.getRelation(qualifiedName);\n\t\tif (!relationMeta) {\n\t\t\t// Get available relations for helpful error message\n\t\t\tconst tableRelations = this.model.getRelationsFrom(this.from);\n\t\t\tconst available = tableRelations?.map((r) => r.name) ?? [];\n\t\t\tthrow new RelationNotFoundError({\n\t\t\t\ttable: this.from,\n\t\t\t\trequested: relation,\n\t\t\t\tavailable,\n\t\t\t});\n\t\t}\n\n\t\t// Determine the foreign key column from relation metadata\n\t\tconst fkColumn = this.getForeignKeyColumn(relationMeta.foreignKey);\n\n\t\t// Collect IDs from the main results (primary key values)\n\t\t// For ancestors: we start from the record's own ID and traverse up via parent\n\t\t// For descendants: we start from the record's own ID and traverse down via children\n\t\tconst startIds = results\n\t\t\t.map((r) => r.id as unknown)\n\t\t\t.filter((id) => id !== undefined && id !== null);\n\n\t\tif (startIds.length === 0) return;\n\n\t\t// Build RecursiveIntent\n\t\tconst cteName = `_recursive_${relation}_${direction}`;\n\t\tconst recursiveIntent = this.buildRecursiveIntent(\n\t\t\tcteName,\n\t\t\trelationMeta,\n\t\t\tstartIds,\n\t\t\tdirection,\n\t\t\tmaxDepth,\n\t\t\tincludeDepth,\n\t\t);\n\n\t\t// Plan and compile the recursive query\n\t\tconst report = planRecursive(recursiveIntent, this.model);\n\n\t\t// Build compile options with exactOptionalPropertyTypes compliance\n\t\tconst compileOptions: { schemaName?: string } = {};\n\t\tif (this.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.schemaName;\n\t\t}\n\n\t\tconst compiledRecursive = adapter.compileRecursive(\n\t\t\treport,\n\t\t\tthis.model,\n\t\t\tcompileOptions,\n\t\t);\n\n\t\t// Execute\n\t\tconst recursiveRows = (await executeCompiledQuery(\n\t\t\tadapter,\n\t\t\tcompiledRecursive,\n\t\t\t'all()',\n\t\t)) as Record<string, unknown>[];\n\n\t\t// Merge results back into main results\n\t\tthis.mergeRecursiveResults(\n\t\t\tresults,\n\t\t\trecursiveRows,\n\t\t\trelation,\n\t\t\tdirection,\n\t\t\tfkColumn,\n\t\t\tflat,\n\t\t\tomitSelf,\n\t\t);\n\t}\n\n\t/**\n\t * Build a RecursiveIntent for CTE execution.\n\t */\n\tprivate buildRecursiveIntent(\n\t\tcteName: string,\n\t\trelationMeta: ReturnType<ModelIR['getRelation']> & object,\n\t\tstartIds: unknown[],\n\t\tdirection: 'ancestors' | 'descendants',\n\t\tmaxDepth: number,\n\t\tincludeDepth: boolean,\n\t): RecursiveIntent {\n\t\tconst { source, foreignKey } = relationMeta;\n\n\t\t// Get the foreign key as a string (use first element if array)\n\t\tconst fkColumn = this.getForeignKeyColumn(foreignKey);\n\n\t\t// For self-referential relations:\n\t\t// - ancestors: traverse via parent (belongsTo) - follow foreignKey to parent\n\t\t// - descendants: traverse via children (hasMany) - find rows where foreignKey = our id\n\n\t\t// Build the start WHERE clause to filter by the starting IDs\n\t\tconst startWhere: WhereIntent =\n\t\t\tstartIds.length === 1\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'comparison',\n\t\t\t\t\t\tfield: 'id',\n\t\t\t\t\t\toperator: 'eq',\n\t\t\t\t\t\tvalue: startIds[0],\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind: 'in',\n\t\t\t\t\t\tfield: 'id',\n\t\t\t\t\t\tvalues: startIds as (string | number | boolean)[],\n\t\t\t\t\t};\n\n\t\t// Build traversal config based on direction\n\t\tconst traversal = this.buildTraversalConfig(source, fkColumn, direction);\n\n\t\t// Build the intent\n\t\tconst intent: Mutable<RecursiveIntent> = {\n\t\t\ttype: 'recursive',\n\t\t\tcteName,\n\t\t\tstart: {\n\t\t\t\tfrom: source,\n\t\t\t\tnodeIdExpr: { kind: 'column', name: 'id' },\n\t\t\t\twhere: startWhere,\n\t\t\t},\n\t\t\ttraversal,\n\t\t\tmaxDepth,\n\t\t};\n\n\t\t// Add depth tracking if requested\n\t\tif (includeDepth) {\n\t\t\tintent.track = { depth: {} };\n\t\t}\n\n\t\treturn intent as RecursiveIntent;\n\t}\n\n\t/**\n\t * Get the foreign key column name from relation metadata.\n\t */\n\tprivate getForeignKeyColumn(\n\t\tforeignKey: string | readonly string[] | undefined,\n\t): string {\n\t\tconst columns = toColumnList(foreignKey);\n\t\tif (columns.length === 0) {\n\t\t\treturn 'parent_id'; // Default convention for self-referential\n\t\t}\n\t\tif (columns.length !== 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recursive include hydration requires a single-column self-referential foreign key; got ${JSON.stringify(columns)}.`,\n\t\t\t);\n\t\t}\n\t\t// biome-ignore lint/style/noNonNullAssertion: columns.length === 1 guaranteed by the throw above (length !== 1 already handled)\n\t\treturn columns[0]!;\n\t}\n\n\t/**\n\t * Build traversal config for recursive CTE.\n\t */\n\tprivate buildTraversalConfig(\n\t\tnodeTable: string,\n\t\tparentIdColumn: string,\n\t\tdirection: 'ancestors' | 'descendants',\n\t): RecursiveIntent['traversal'] {\n\t\t// For self-referential adjacency list:\n\t\t// - ancestors: currentRow.foreignKey = nextRow.id (follow parent pointer)\n\t\t// - descendants: currentRow.id = nextRow.foreignKey (find children)\n\t\treturn {\n\t\t\tkind: 'adjacency',\n\t\t\tnodeTable,\n\t\t\tnodeId: 'id',\n\t\t\tparentId: parentIdColumn,\n\t\t\tdirection,\n\t\t};\n\t}\n\n\t/**\n\t * Merge recursive results back into main results.\n\t */\n\tprivate mergeRecursiveResults(\n\t\tresults: ResultRow[],\n\t\trecursiveRows: ResultRow[],\n\t\trelation: string,\n\t\tdirection: 'ancestors' | 'descendants',\n\t\tforeignKey: string,\n\t\tflat: boolean,\n\t\tomitSelf: boolean,\n\t): void {\n\t\t// Build a map from start ID to recursive results\n\t\tconst resultsByStartId = new Map<unknown, ResultRow[]>();\n\n\t\tfor (const row of recursiveRows) {\n\t\t\t// The recursive CTE returns rows with a _start_id or similar marker\n\t\t\t// For now, we group by the root ID that started the traversal\n\t\t\tconst startId = row._root_id ?? row.id;\n\t\t\tconst existing = resultsByStartId.get(startId) ?? [];\n\n\t\t\t// Apply omitSelf filter\n\t\t\tif (omitSelf && row.depth === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\texisting.push(row);\n\t\t\tresultsByStartId.set(startId, existing);\n\t\t}\n\n\t\t// Determine output property name based on direction\n\t\tconst outputProperty =\n\t\t\tdirection === 'ancestors'\n\t\t\t\t? relation === 'parent'\n\t\t\t\t\t? 'ancestors'\n\t\t\t\t\t: `${relation}_ancestors`\n\t\t\t\t: relation === 'children'\n\t\t\t\t\t? 'descendants'\n\t\t\t\t\t: `${relation}_descendants`;\n\n\t\t// Attach to main results\n\t\tfor (const result of results) {\n\t\t\tconst id = result.id as unknown;\n\t\t\tconst recursiveData = resultsByStartId.get(id) ?? [];\n\n\t\t\tif (flat) {\n\t\t\t\t// Flat: array of all results\n\t\t\t\tresult[outputProperty] = recursiveData;\n\t\t\t} else {\n\t\t\t\t// Nested: build tree structure\n\t\t\t\tresult[outputProperty] = this.buildNestedHierarchy(\n\t\t\t\t\trecursiveData,\n\t\t\t\t\tdirection,\n\t\t\t\t\tforeignKey,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Build nested hierarchy from flat recursive results.\n\t */\n\tprivate buildNestedHierarchy(\n\t\trows: ResultRow[],\n\t\tdirection: 'ancestors' | 'descendants',\n\t\tforeignKey: string,\n\t): ResultRow | ResultRow[] | null {\n\t\tif (rows.length === 0) return direction === 'ancestors' ? null : [];\n\n\t\t// Sort by depth\n\t\tconst sorted = [...rows].sort(\n\t\t\t(a, b) => ((a.depth as number) ?? 0) - ((b.depth as number) ?? 0),\n\t\t);\n\n\t\tif (direction === 'ancestors') {\n\t\t\t// For ancestors, build a chain: self -> parent -> grandparent\n\t\t\t// Return the immediate parent with nested ancestors\n\t\t\tlet current = null;\n\t\t\tfor (let i = sorted.length - 1; i >= 0; i--) {\n\t\t\t\tconst row = sorted[i];\n\t\t\t\tconst node = { ...row };\n\t\t\t\tif (current !== null) {\n\t\t\t\t\tnode[direction === 'ancestors' ? 'parent' : 'children'] = current;\n\t\t\t\t}\n\t\t\t\tcurrent = node;\n\t\t\t}\n\t\t\treturn current;\n\t\t}\n\n\t\t// For descendants, build a tree structure\n\t\tconst nodeMap = new Map<unknown, ResultRow>();\n\t\tconst roots: ResultRow[] = [];\n\n\t\tfor (const row of sorted) {\n\t\t\tconst node = { ...row, children: [] };\n\t\t\tnodeMap.set(row.id, node);\n\n\t\t\tconst parentId = row[foreignKey] as unknown;\n\t\t\tif (parentId !== null && parentId !== undefined) {\n\t\t\t\tconst parent = nodeMap.get(parentId);\n\t\t\t\tif (parent) {\n\t\t\t\t\t(parent.children as ResultRow[]).push(node);\n\t\t\t\t} else {\n\t\t\t\t\troots.push(node);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\troots.push(node);\n\t\t\t}\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\t/**\n\t * Extract a key value from an object, handling composite keys.\n\t *\n\t * Fast path: NUL-byte separator for the common case of string/number PKs\n\t * (~5× faster than JSON.stringify). Fallback: if any serialized part\n\t * contains a NUL byte (e.g. bytea PKs stored as strings), two distinct\n\t * keys could collide under the fast path — use JSON.stringify in that\n\t * case (slower but collision-safe for any value content).\n\t */\n\tprivate extractKeyValue(\n\t\tobj: Record<string, unknown>,\n\t\tkey: string | readonly string[],\n\t): unknown {\n\t\tconst columns = toColumnList(key);\n\t\tif (columns.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (columns.length === 1) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: columns.length === 1 guaranteed by the enclosing if-block\n\t\t\treturn obj[columns[0]!];\n\t\t}\n\t\t// Composite key: build a string key for Map grouping.\n\t\tconst values = columns.map((k) => obj[k]);\n\t\t// Return undefined if any component is missing\n\t\tif (values.some((v) => v === undefined || v === null)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parts = values.map((v) => String(v));\n\t\tif (parts.some((p) => p.includes(COMPOSITE_KEY_SEP))) {\n\t\t\t// Collision-safe fallback — slower but correct for any value content.\n\t\t\t// Stringify `parts` (already normalized to strings via String(v))\n\t\t\t// rather than `values` because JSON.stringify throws on bigint,\n\t\t\t// and composite PKs may legitimately contain bigint values.\n\t\t\treturn JSON.stringify(parts);\n\t\t}\n\t\treturn parts.join(COMPOSITE_KEY_SEP);\n\t}\n\n\tprivate extractQueryKeyValue(\n\t\tobj: Record<string, unknown>,\n\t\tkey: string | readonly string[],\n\t): unknown {\n\t\tconst columns = toColumnList(key);\n\t\tif (columns.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (columns.length === 1) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: columns.length === 1 guaranteed by the enclosing if-block\n\t\t\treturn obj[columns[0]!];\n\t\t}\n\t\tconst values = columns.map((k) => obj[k]);\n\t\treturn values.some((v) => v === undefined || v === null)\n\t\t\t? undefined\n\t\t\t: values;\n\t}\n}\n","/**\n * Shared helpers for relation-dotted include path identity.\n *\n * Planner intent paths are positional (`include[0].include[1]`). Join identity\n * and hydration keys use the relation chain actually traversed\n * (`definition.file`, `manager.manager`), so every consumer must derive that\n * string the same way.\n */\n\nexport type RelationPathIncludeNode = {\n\treadonly relation?: unknown;\n\treadonly via?: unknown;\n\treadonly include?: readonly unknown[];\n};\n\nexport type RelationPathUsage = {\n\treadonly relationName?: string | null | undefined;\n\treadonly relationPath?: string | null | undefined;\n};\n\nfunction nonEmptyString(value: unknown): string | undefined {\n\treturn typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction includeNode(value: unknown): RelationPathIncludeNode | undefined {\n\treturn value !== null && typeof value === 'object'\n\t\t? (value as RelationPathIncludeNode)\n\t\t: undefined;\n}\n\nfunction parseIntentPathIndexes(intentPath: string): number[] {\n\tconst indexes: number[] = [];\n\tconst indexPattern = /include\\[(\\d+)\\]/g;\n\tlet execResult = indexPattern.exec(intentPath);\n\n\twhile (execResult !== null) {\n\t\tconst rawIndex = execResult[1];\n\t\tif (rawIndex === undefined) break;\n\t\tindexes.push(parseInt(rawIndex, 10));\n\t\texecResult = indexPattern.exec(intentPath);\n\t}\n\n\treturn indexes;\n}\n\nexport function deriveRelationPathFromIntentPath(\n\tincludes: readonly unknown[] | undefined,\n\tintentPath: string | undefined,\n\tfallbackRelation: string | undefined,\n): string | undefined {\n\tif (includes && intentPath) {\n\t\tlet current: readonly unknown[] = includes;\n\t\tconst path: string[] = [];\n\n\t\tfor (const index of parseIntentPathIndexes(intentPath)) {\n\t\t\tconst item = includeNode(current[index]);\n\t\t\tif (!item) break;\n\n\t\t\tconst segment = nonEmptyString(item.via) ?? nonEmptyString(item.relation);\n\t\t\tif (!segment) break;\n\n\t\t\tpath.push(segment);\n\t\t\tcurrent = Array.isArray(item.include) ? item.include : [];\n\t\t}\n\n\t\tif (path.length > 0) return path.join('.');\n\t}\n\n\treturn nonEmptyString(fallbackRelation);\n}\n\nexport function countDistinctRelationPathsByName(\n\tusages: readonly RelationPathUsage[],\n): Map<string, number> {\n\tconst pathsByRelationName = new Map<string, Set<string>>();\n\n\tfor (const usage of usages) {\n\t\tconst relationName = nonEmptyString(usage.relationName);\n\t\tif (!relationName) continue;\n\n\t\tconst relationPath = nonEmptyString(usage.relationPath) ?? relationName;\n\t\tconst paths = pathsByRelationName.get(relationName) ?? new Set<string>();\n\t\tpaths.add(relationPath);\n\t\tpathsByRelationName.set(relationName, paths);\n\t}\n\n\tconst counts = new Map<string, number>();\n\tfor (const [relationName, paths] of pathsByRelationName) {\n\t\tcounts.set(relationName, paths.size);\n\t}\n\n\treturn counts;\n}\n","/**\n * @fileoverview SetOperationBuilder — fluent API for UNION / INTERSECT / EXCEPT.\n *\n * Returned by `.union()`, `.unionAll()`, `.intersect()`, `.except()` on QueryBuilder.\n * Stores a SetOperationIntent tree and provides dump() + execute helpers.\n *\n * Architecture note: SQL compilation is delegated to the adapter via\n * `adapter.compileSetOperation()` so that `@dbsp/core` remains DB-agnostic.\n */\n\nimport {\n\ttype Adapter,\n\ttype Dump,\n\ttype DumpMeta,\n\texecuteCompiledQuery,\n} from '../adapter.js';\nimport type {\n\tQueryIntent,\n\tSetOperationIntent,\n\tSetOperationType,\n} from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\nimport { ExecutionError } from './errors.js';\nimport type { QueryBuilder } from './types.js';\n\n// ============================================================================\n// Public interface\n// ============================================================================\n\n/**\n * Fluent builder for set operations (UNION / INTERSECT / EXCEPT).\n *\n * @typeParam TResult - Result row type\n *\n * @example\n * ```typescript\n * const q1 = orm.select('employees').where(eq('active', true));\n * const q2 = orm.select('contractors').where(eq('active', true));\n *\n * // UNION (deduplicates rows)\n * const dump = q1.union(q2).dump();\n *\n * // UNION ALL (keeps duplicates)\n * const rows = await q1.unionAll(q2).all();\n *\n * // Chain: (q1 UNION q2) INTERSECT q3\n * const nested = q1.union(q2).intersect(q3);\n * ```\n */\nexport interface SetOperationBuilder<TResult = unknown> {\n\t/** Combine via UNION (deduplicates rows). */\n\tunion(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Combine via UNION ALL (keeps duplicates). */\n\tunionAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Combine via INTERSECT (rows in both). */\n\tintersect(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Combine via INTERSECT ALL (rows in both, with duplicates). */\n\tintersectAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Combine via EXCEPT (rows in left but not right). */\n\texcept(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Combine via EXCEPT ALL (rows in left but not right, with duplicates). */\n\texceptAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult>;\n\n\t/** Compile to SQL and return a Dump (no execution). Requires adapter. */\n\tdump(): Dump;\n\n\t/** Execute and return all rows. Requires adapter. */\n\tall(): Promise<TResult[]>;\n\n\t/** Execute and return first row. Requires adapter. */\n\tfirst(): Promise<TResult | undefined>;\n\n\t/** The underlying SetOperationIntent (for inspection / testing). */\n\treadonly intent: SetOperationIntent;\n}\n\n// ============================================================================\n// Builder context interface\n// ============================================================================\n\n/** Minimal interface to extract a QueryIntent from a builder. @internal */\nexport interface QueryIntentSource {\n\tbuildIntent(): QueryIntent;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/** @internal */\nexport class SetOperationBuilderImpl<TResult = unknown>\n\timplements SetOperationBuilder<TResult>\n{\n\treadonly intent: SetOperationIntent;\n\tprivate readonly model: ModelIR;\n\tprivate readonly adapter: Adapter | undefined;\n\tprivate readonly schemaName: string | undefined;\n\n\tconstructor(\n\t\tintent: SetOperationIntent,\n\t\tmodel: ModelIR,\n\t\tadapter?: Adapter,\n\t\tschemaName?: string,\n\t) {\n\t\tthis.intent = intent;\n\t\tthis.model = model;\n\t\tthis.adapter = adapter;\n\t\tthis.schemaName = schemaName;\n\t}\n\n\tunion(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('union', false, other);\n\t}\n\n\tunionAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('union', true, other);\n\t}\n\n\tintersect(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('intersect', false, other);\n\t}\n\n\tintersectAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('intersect', true, other);\n\t}\n\n\texcept(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('except', false, other);\n\t}\n\n\texceptAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn this.combine('except', true, other);\n\t}\n\n\tprivate combine(\n\t\top: SetOperationType,\n\t\tall: boolean,\n\t\tother: QueryBuilder<TResult>,\n\t): SetOperationBuilder<TResult> {\n\t\tconst rightIntent = (other as unknown as QueryIntentSource).buildIntent();\n\t\tconst newIntent: SetOperationIntent = {\n\t\t\tkind: 'setOperation',\n\t\t\top,\n\t\t\tall,\n\t\t\tleft: this.intent,\n\t\t\tright: rightIntent,\n\t\t};\n\t\treturn new SetOperationBuilderImpl<TResult>(\n\t\t\tnewIntent,\n\t\t\tthis.model,\n\t\t\tthis.adapter,\n\t\t\tthis.schemaName,\n\t\t);\n\t}\n\n\tdump(): Dump {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst compiled = adapter.compileSetOperation(this.intent, this.model);\n\t\t// Set operations bypass the semantic planner — no PlanReport is produced.\n\t\t// compiledAt is always included so observability hooks that read\n\t\t// dump.meta?.compiledAt receive a consistent shape regardless of query type.\n\t\tconst meta: DumpMeta = {\n\t\t\tcompiledAt: new Date(),\n\t\t\t...(this.schemaName !== undefined ? { schema: this.schemaName } : {}),\n\t\t};\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparams: compiled.parameters,\n\t\t\tmeta,\n\t\t};\n\t}\n\n\tasync all(): Promise<TResult[]> {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst compiled = adapter.compileSetOperation<TResult>(\n\t\t\tthis.intent,\n\t\t\tthis.model,\n\t\t);\n\t\treturn executeCompiledQuery(adapter, compiled, 'set operation all()');\n\t}\n\n\tasync first(): Promise<TResult | undefined> {\n\t\tconst rows = await this.all();\n\t\treturn rows[0];\n\t}\n\n\tprivate requireAdapter(): Adapter {\n\t\tif (!this.adapter) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation: 'set operation execution',\n\t\t\t\treason: 'Adapter not configured',\n\t\t\t\tfix: 'Pass an adapter to createOrm({ adapter: yourAdapter })',\n\t\t\t});\n\t\t}\n\t\treturn this.adapter;\n\t}\n}\n\n// ============================================================================\n// Factory helper\n// ============================================================================\n\n/**\n * Build a SetOperationIntent from two query intent sources.\n * @internal\n */\nexport function buildSetOperationIntent(\n\top: SetOperationType,\n\tall: boolean,\n\tleft: QueryIntentSource,\n\tright: QueryIntentSource,\n): SetOperationIntent {\n\treturn {\n\t\tkind: 'setOperation',\n\t\top,\n\t\tall,\n\t\tleft: left.buildIntent(),\n\t\tright: right.buildIntent(),\n\t};\n}\n","/**\n * Stream implementation extracted from QueryBuilderImpl.\n *\n * Free function that accepts a QueryBuilderImpl instance and implements the\n * stream() logic. It accesses only fields and methods declared\n * @internal public on QueryBuilderImpl.\n *\n * @internal\n */\n\nimport {\n\ttype AdapterStreamOptions,\n\tassertConnectionAvailable,\n\ttype CompiledQuery,\n\ttype Dump,\n\tsupportsStreaming,\n} from '../adapter.js';\nimport type { ModelIR } from '../model-ir.js';\nimport type { PlanOptions } from '../planner.js';\nimport { ExecutionError } from './errors.js';\nimport type { QueryHookContext } from './hooks.js';\nimport {\n\thasHooks,\n\tnormalizeHookError,\n\trunBeforeQueryHooks,\n\trunOnErrorHooks,\n\twithReentrancyGuard,\n} from './hooks.js';\nimport type { QueryBuilderImpl } from './query-builder.js';\nimport type { StreamOptions } from './types.js';\n\nfunction createUnsupportedStreamingError(): ExecutionError {\n\treturn new ExecutionError({\n\t\toperation: 'stream()',\n\t\treason:\n\t\t\t'The adapter declares supportsStreaming: false for this ORM instance.',\n\t\tfix: 'Use an adapter configuration that supports streaming.',\n\t});\n}\n\nfunction hasStreamTransactionBeginOptions(\n\toptions: StreamOptions | undefined,\n): boolean {\n\treturn (\n\t\toptions != null &&\n\t\t(options.isolationLevel !== undefined ||\n\t\t\toptions.readOnly !== undefined ||\n\t\t\toptions.lockTimeoutMs !== undefined ||\n\t\t\toptions.statementTimeoutMs !== undefined)\n\t);\n}\n\nfunction hasRuntimeStreamSignalOption(\n\toptions: StreamOptions | undefined,\n): boolean {\n\treturn typeof options === 'object' && options !== null && 'signal' in options;\n}\n\nfunction createAdapterStreamOptions(\n\toptions: StreamOptions | undefined,\n): AdapterStreamOptions | undefined {\n\tif (\n\t\toptions === undefined ||\n\t\t(options.chunkSize === undefined &&\n\t\t\t!hasStreamTransactionBeginOptions(options))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\t...(options.chunkSize !== undefined && { chunkSize: options.chunkSize }),\n\t\t...(options.isolationLevel !== undefined && {\n\t\t\tisolationLevel: options.isolationLevel,\n\t\t}),\n\t\t...(options.readOnly !== undefined && { readOnly: options.readOnly }),\n\t\t...(options.lockTimeoutMs !== undefined && {\n\t\t\tlockTimeoutMs: options.lockTimeoutMs,\n\t\t}),\n\t\t...(options.statementTimeoutMs !== undefined && {\n\t\t\tstatementTimeoutMs: options.statementTimeoutMs,\n\t\t}),\n\t};\n}\n\n/**\n * Create a lazy AsyncIterableIterator for streaming query results.\n *\n * Extracted from QueryBuilderImpl.stream(). All hook semantics, lazy\n * compilation, and onStart callback behaviour are preserved identically.\n *\n * @internal\n */\nexport function stream<TResult>(\n\tbuilder: QueryBuilderImpl<TResult>,\n\toptions?: StreamOptions,\n): AsyncIterableIterator<TResult> {\n\tconst adapter = builder.getConfiguredAdapter();\n\tconst hasBeginOptions = hasStreamTransactionBeginOptions(options);\n\tconst hasSignalOption = hasRuntimeStreamSignalOption(options);\n\tconst adapterOptions = createAdapterStreamOptions(options);\n\n\t// E17b: Fire beforeQuery hook with isStreaming=true (afterQuery does NOT fire for streams)\n\tconst hookStore = builder.ctx.hookStore;\n\tconst onHookError = builder.ctx.onHookError;\n\tconst table = builder.from;\n\tconst schemaName = builder.ctx.schemaName;\n\tconst txFlag = builder.ctx.inTransaction;\n\n\t// Capture builder references needed inside the lazy iterator closure.\n\t// These are captured once to avoid re-reading mutable builder state on\n\t// every next() call (the builder could theoretically be modified between\n\t// iterator creation and first consumption).\n\tconst onStartCallback = options?.onStart;\n\n\t// FIND-017: dumpResult (planning + compilation) MUST happen AFTER\n\t// beforeQuery hooks run, because hooks can modify the intent (e.g. inject\n\t// a tenant WHERE clause). Moving compilation inside the lazy iterator's\n\t// first-next guard ensures hook changes are reflected in the executed SQL.\n\tlet compiledQuery: CompiledQuery<TResult> | null = null;\n\tlet capturedDump: Dump | null = null;\n\tlet adapterIterator: AsyncIterableIterator<TResult> | null = null;\n\tlet onStartCalled = false;\n\tlet hooksFired = false;\n\n\tconst lazyIterator: AsyncIterableIterator<TResult> = {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tassertConnectionAvailable(adapter, 'stream()');\n\t\t\tif (!supportsStreaming(adapter)) {\n\t\t\t\tthrow createUnsupportedStreamingError();\n\t\t\t}\n\t\t\tif (hasSignalOption) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'stream() does not support signal; AbortSignal is only supported by transaction().',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\thasBeginOptions &&\n\t\t\t\tadapter.capabilities.supportsTransactionOptions !== true\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'This adapter does not support stream transaction options (isolationLevel/readOnly/lockTimeoutMs/statementTimeoutMs); it does not declare supportsTransactionOptions.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// E17b: Fire beforeQuery on first iteration (lazy), then compile with\n\t\t\t// the hook-modified intent.\n\t\t\tif (!hooksFired) {\n\t\t\t\thooksFired = true;\n\n\t\t\t\tif (hookStore && hasHooks(hookStore)) {\n\t\t\t\t\t// Build raw intent (without defaultFilters) — hooks see raw intent\n\t\t\t\t\tconst rawIntent = builder.buildIntent(false);\n\t\t\t\t\tconst ctx: QueryHookContext = {\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\toperation: 'select',\n\t\t\t\t\t\tintent: rawIntent,\n\t\t\t\t\t\tresultType: 'all',\n\t\t\t\t\t\tisStreaming: true,\n\t\t\t\t\t\t...(schemaName !== undefined && { schemaName }),\n\t\t\t\t\t\t...(txFlag && { inTransaction: true }),\n\t\t\t\t\t};\n\n\t\t\t\t\tlet hookIntent = rawIntent;\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// INV-07: Re-entrancy guard — prevent infinite loops from hooks issuing queries\n\t\t\t\t\t\tconst afterHookCtx = await withReentrancyGuard(hookStore, (s) =>\n\t\t\t\t\t\t\trunBeforeQueryHooks(s.beforeQuery, ctx, onHookError),\n\t\t\t\t\t\t);\n\t\t\t\t\t\thookIntent = afterHookCtx.intent;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (hookStore.onError.length > 0) {\n\t\t\t\t\t\t\tthrow await runOnErrorHooks(hookStore.onError, {\n\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\toperation: 'select',\n\t\t\t\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\t\t\t\tintent: rawIntent,\n\t\t\t\t\t\t\t\tphase: 'beforeQuery',\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Apply defaultFilters AFTER hooks (INV-01: cannot be bypassed)\n\t\t\t\t\tconst intentAfterDefaults =\n\t\t\t\t\t\tbuilder.applyDefaultFiltersToIntent(hookIntent);\n\t\t\t\t\tconst intentWithHints =\n\t\t\t\t\t\tbuilder.applyRelationHints(intentAfterDefaults);\n\t\t\t\t\tconst planOptions: PlanOptions = {\n\t\t\t\t\t\t...(builder.ctx.dialectCapabilities && {\n\t\t\t\t\t\t\tdialectCapabilities: builder.ctx.dialectCapabilities,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...builder.ctx.planOptionsOverride,\n\t\t\t\t\t};\n\t\t\t\t\tconst planReport = builder.planWithAmbiguityHandling(\n\t\t\t\t\t\tintentWithHints,\n\t\t\t\t\t\tplanOptions,\n\t\t\t\t\t);\n\t\t\t\t\tconst compileOptions: { schemaName?: string; model: ModelIR } = {\n\t\t\t\t\t\tmodel: builder.ctx.model,\n\t\t\t\t\t};\n\t\t\t\t\tif (schemaName !== undefined) {\n\t\t\t\t\t\tcompileOptions.schemaName = schemaName;\n\t\t\t\t\t}\n\t\t\t\t\tconst compiled = adapter.compile<TResult>(planReport, compileOptions);\n\t\t\t\t\tcompiledQuery = compiled;\n\t\t\t\t\tcapturedDump = adapter.createDump(planReport, compiled);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcapturedDump.meta?.schema === undefined &&\n\t\t\t\t\t\tschemaName !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tcapturedDump = {\n\t\t\t\t\t\t\t...capturedDump,\n\t\t\t\t\t\t\tmeta: { ...capturedDump.meta, schema: schemaName },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst planReport = builder.plan();\n\t\t\t\t\tconst compileOptions: { schemaName?: string; model: ModelIR } = {\n\t\t\t\t\t\tmodel: builder.ctx.model,\n\t\t\t\t\t};\n\t\t\t\t\tif (schemaName !== undefined) {\n\t\t\t\t\t\tcompileOptions.schemaName = schemaName;\n\t\t\t\t\t}\n\t\t\t\t\tconst compiled = adapter.compile<TResult>(planReport, compileOptions);\n\t\t\t\t\tcompiledQuery = compiled;\n\t\t\t\t\tcapturedDump = adapter.createDump(planReport, compiled);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcapturedDump.meta?.schema === undefined &&\n\t\t\t\t\t\tschemaName !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tcapturedDump = {\n\t\t\t\t\t\t\t...capturedDump,\n\t\t\t\t\t\t\tmeta: { ...capturedDump.meta, schema: schemaName },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Initialize adapter iterator lazily (compiledQuery is now set)\n\t\t\tif (!adapterIterator) {\n\t\t\t\t// compiledQuery is guaranteed non-null: hooksFired is true at this\n\t\t\t\t// point, meaning the block above has completed and set compiledQuery.\n\t\t\t\tadapterIterator = adapter.stream<TResult>(\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: invariant — hooksFired=true means the block above set compiledQuery before reaching this branch\n\t\t\t\t\tcompiledQuery!,\n\t\t\t\t\tadapterOptions,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Call onStart only once, on first next() call\n\t\t\tif (!onStartCalled && onStartCallback && capturedDump) {\n\t\t\t\tonStartCalled = true;\n\t\t\t\tonStartCallback(capturedDump);\n\t\t\t}\n\n\t\t\treturn adapterIterator.next();\n\t\t},\n\t\tasync return(value?: TResult) {\n\t\t\tif (adapterIterator?.return) {\n\t\t\t\treturn adapterIterator.return(value);\n\t\t\t}\n\t\t\treturn { done: true as const, value: undefined };\n\t\t},\n\t\tasync throw(error?: unknown) {\n\t\t\t// E17b: Fire onError for stream errors\n\t\t\tif (hookStore && hookStore.onError.length > 0 && error instanceof Error) {\n\t\t\t\tconst rawIntent = builder.buildIntent(false);\n\t\t\t\tconst finalError = await runOnErrorHooks(hookStore.onError, {\n\t\t\t\t\ttable,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror,\n\t\t\t\t\tintent: rawIntent,\n\t\t\t\t\tphase: 'afterQuery',\n\t\t\t\t});\n\t\t\t\tthrow finalError;\n\t\t\t}\n\t\t\tif (adapterIterator?.throw) {\n\t\t\t\treturn adapterIterator.throw(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t},\n\t};\n\n\treturn lazyIterator;\n}\n","/* biome-ignore-all lint/style/noNonNullAssertion: Builder internals use non-null assertions on validated state */\nimport type { Mutable } from '@dbsp/types/internal';\nimport { type Adapter, type Dump, executeCompiledQuery } from '../adapter.js';\nimport type {\n\tAggregateIntent,\n\tColumnExpressionIntent,\n\tExpressionIntent,\n\tIncludeIntent,\n\tJoinIntent,\n\tOrderByIntent,\n\tQueryIntent,\n\tSelectAggregateIntent,\n\tSelectIntent,\n\tWhereIntent,\n} from '../intent-ast.js';\nimport type { ModelIR } from '../model-ir.js';\nimport type { PlanOptions, PlanReport } from '../planner.js';\nimport { AmbiguousPlanError, plan } from '../planner.js';\nimport type { BatchValuesRef } from './batch-values.js';\nimport { isBatchValuesRef } from './batch-values.js';\nimport {\n\tAmbiguousRelationError,\n\tExecutionError,\n\tInvalidOperationError,\n\tNotFoundError,\n\tvalidateIdentifier,\n} from './errors.js';\nimport { buildExistsIntent } from './exists-intent.js';\nimport {\n\tExpressionRef,\n\thasPredicateRefDiscriminator,\n\tisPredicateRef,\n\ttype PredicateRef,\n\tpredicateWhereIntent,\n} from './expressions.js';\nimport {\n\tand,\n\ttype DistinctField,\n\teq,\n\tinArray,\n\tisDistinctField,\n} from './filters.js';\nimport {\n\ttype HookStore,\n\thasHooks,\n\tnormalizeHookError,\n\ttype QueryHookContext,\n\ttype QueryResultType,\n\trunAfterQueryHooks,\n\trunAfterQueryObservers,\n\trunBeforeQueryHooks,\n\trunOnErrorHooks,\n\twithReentrancyGuard,\n} from './hooks.js';\nimport { applyHintToIncludeRecursive } from './include-hints.js';\nimport {\n\tincludeOptionsToIntent,\n\tisRecursiveIncludeOptions,\n\tparseDotNotationInclude,\n\ttype RecursiveIncludeConfig,\n\tvalidateRecursiveInclude,\n} from './intent-builder.js';\nimport { emitWarning } from './logger.js';\nimport {\n\tisWhereIntent,\n\tobjectToWhereIntent,\n\ttype WhereFilter,\n} from './object-filter.js';\nimport * as paginationImpl from './pagination-impl.js';\nimport type { QueryBuilderContext } from './query-builder-context.js';\nimport type { DumpMetaInput } from './query-builder-types.js';\nimport { ResultHydrator } from './result-hydrator.js';\nimport {\n\tbuildSetOperationIntent,\n\ttype QueryIntentSource,\n\ttype SetOperationBuilder,\n\tSetOperationBuilderImpl,\n} from './set-operation-builder.js';\nimport * as streamImpl from './stream-impl.js';\nimport {\n\ttype AggregateOptions,\n\ttype AliasedExprColumn,\n\ttype ColumnSpec,\n\ttype CursorPaginatedResult,\n\ttype CursorPaginateOptions,\n\ttype ExpressionSpec,\n\ttype IncludeOptionsWithRecursive,\n\tisExpressionSpec,\n\ttype OrderByRecord,\n\ttype OrderBySpec,\n\ttype PaginatedResult,\n\ttype PaginateOptions,\n\ttype QueryBuilder,\n\ttype RelationHints,\n\ttype SortDirection,\n\ttype StreamOptions,\n} from './types.js';\n/**\n * Internal query builder implementation.\n */\nexport class QueryBuilderImpl<TResult = unknown>\n\timplements QueryBuilder<TResult>\n{\n\t/** @internal — read by stream-impl and pagination-impl */\n\treadonly ctx: QueryBuilderContext;\n\t/** @internal — read by stream-impl */\n\treadonly from: string;\n\t/** @internal — mutated by pagination-impl on clones */\n\treadonly includes: IncludeIntent[] = [];\n\t/** @internal — mutated by pagination-impl on clones */\n\treadonly recursiveIncludes: RecursiveIncludeConfig[] = [];\n\tprivate readonly relationHints: RelationHints;\n\t/** @internal — mutated by pagination-impl on clones */\n\tselectIntent: SelectIntent | undefined = undefined;\n\t/** @internal — mutated by pagination-impl on clones */\n\twhereIntents: WhereIntent[] = [];\n\tprivate strictModeOverride: boolean | undefined = undefined;\n\t/** @internal — mutated by pagination-impl on clones */\n\taggregates: AggregateIntent[] = [];\n\t/** @internal — read by pagination-impl */\n\tgroupByFields: string[] = [];\n\t/** @internal — read by pagination-impl and cursor helpers */\n\torderByIntents: OrderByIntent[] = [];\n\t/** @internal — mutated by pagination-impl on clones */\n\tlimitValue: number | undefined = undefined;\n\t/** @internal — mutated by pagination-impl on clones */\n\toffsetValue: number | undefined = undefined;\n\tprivate havingIntents: WhereIntent[] = [];\n\tprivate isDistinctQuery = false;\n\tprivate distinctOnColumns: string[] = [];\n\tprivate skipDefaultFilters = false;\n\tprivate lockIntent: import('@dbsp/types').LockIntent | undefined = undefined;\n\t/** @internal — read by pagination-impl */\n\tjoinIntents: JoinIntent[] = [];\n\t/** When set, FROM clause is a BatchValues unnest() source, not a table */\n\tbatchValuesSource?: import('@dbsp/types').BatchValuesJoinPayload;\n\n\tconstructor(\n\t\tctx: QueryBuilderContext,\n\t\tfrom: string,\n\t\trelationHints: RelationHints = {},\n\t) {\n\t\tthis.ctx = ctx;\n\t\tthis.from = from;\n\t\tthis.relationHints = relationHints;\n\t}\n\n\tinclude(\n\t\trelation: string,\n\t\toptions?: IncludeOptionsWithRecursive,\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\n\t\t// Validate recursive includes (DX-017)\n\t\tif (isRecursiveIncludeOptions(options)) {\n\t\t\tvalidateRecursiveInclude(this.ctx.model, this.from, relation, options);\n\t\t\t// DX-017: No longer store separately - let includeOptionsToIntent handle conversion\n\t\t}\n\n\t\t// Support dot notation for nested includes: 'posts.comments.author'\n\t\tif (relation.includes('.')) {\n\t\t\tbuilder.includes.push(parseDotNotationInclude(relation, options));\n\t\t} else {\n\t\t\tbuilder.includes.push(includeOptionsToIntent(relation, options));\n\t\t}\n\t\treturn builder;\n\t}\n\n\t// Overload: typed columns (string keys only) → Pick<TResult, K>\n\tcolumns<K extends keyof TResult & string>(\n\t\tcolumns: readonly K[],\n\t): QueryBuilder<Pick<TResult, K>>;\n\t// Overload: mixed strings + AliasedExprColumn → extends result type with aliased props\n\tcolumns<\n\t\tconst T extends readonly (\n\t\t\t| (keyof TResult & string)\n\t\t\t| AliasedExprColumn<string>\n\t\t)[],\n\t>(\n\t\tcolumns: T,\n\t): QueryBuilder<\n\t\tPick<TResult, Extract<T[number], keyof TResult & string>> & {\n\t\t\t[E in Extract<\n\t\t\t\tT[number],\n\t\t\t\tAliasedExprColumn<string>\n\t\t\t> as E['__alias']]: E['__value'];\n\t\t}\n\t>;\n\t// Overload: mixed columns (strings + expressions) → TResult\n\tcolumns(columns: readonly ColumnSpec[]): QueryBuilder<TResult>;\n\t// Implementation — cast to TResult to match the most general overload signature.\n\t// The overloads above refine the type; the implementation signature is intentionally\n\t// broad to satisfy all three overloads (TypeScript requires an assignable\n\t// implementation signature).\n\t// biome-ignore lint/suspicious/noExplicitAny: implementation signature accepts erased type — public overloads above guarantee the correct narrowed return type for callers\n\tcolumns(columns: readonly ColumnSpec[]): QueryBuilder<any> {\n\t\tconst builder = this.clone();\n\n\t\t// Build columns array (direct ExpressionIntent format - NQL compatible)\n\t\tconst expressionColumns: ExpressionIntent[] = [];\n\t\tlet hasExpressions = false;\n\n\t\tfor (const col of columns) {\n\t\t\tif (isExpressionSpec(col)) {\n\t\t\t\thasExpressions = true;\n\t\t\t\texpressionColumns.push(col.intent);\n\t\t\t} else {\n\t\t\t\t// Simple field → ColumnExpressionIntent (kind: 'column')\n\t\t\t\texpressionColumns.push({ kind: 'column', column: col });\n\t\t\t}\n\t\t}\n\n\t\t// Use SelectWithExpressionsIntent if we have any expressions\n\t\tif (hasExpressions) {\n\t\t\tbuilder.selectIntent = {\n\t\t\t\ttype: 'expressions',\n\t\t\t\tcolumns: expressionColumns,\n\t\t\t};\n\t\t} else {\n\t\t\t// Simple fields only - extract field names\n\t\t\tconst fields = expressionColumns.map(\n\t\t\t\t(c) => (c as ColumnExpressionIntent).column,\n\t\t\t);\n\t\t\tbuilder.selectIntent = { type: 'fields', fields };\n\t\t}\n\n\t\t// Cast is safe: the public overloads above guarantee the correct narrowed type.\n\t\t// biome-ignore lint/suspicious/noExplicitAny: implementation signature cast — public overloads above guarantee the correct narrowed type for callers\n\t\treturn builder as QueryBuilder<any>;\n\t}\n\n\tcoalesce<K extends keyof TResult & string, Alias extends string>(\n\t\tfields: readonly K[],\n\t\tas: Alias,\n\t): QueryBuilder<TResult & { [P in Alias]: NonNullable<TResult[K]> }> {\n\t\tconst builder = this.clone();\n\n\t\t// Create CoalesceExpressionIntent\n\t\tconst coalesceIntent: ExpressionIntent = {\n\t\t\tkind: 'coalesce',\n\t\t\tfields: fields as readonly string[],\n\t\t\tas,\n\t\t};\n\n\t\t// If we already have a SelectWithExpressionsIntent, add to it\n\t\tif (builder.selectIntent?.type === 'expressions') {\n\t\t\tbuilder.selectIntent = {\n\t\t\t\ttype: 'expressions',\n\t\t\t\tcolumns: [...builder.selectIntent.columns, coalesceIntent],\n\t\t\t};\n\t\t} else if (builder.selectIntent?.type === 'fields') {\n\t\t\t// Convert fields to expressions and add coalesce\n\t\t\tconst fieldExpressions: ExpressionIntent[] =\n\t\t\t\tbuilder.selectIntent.fields.map(\n\t\t\t\t\t(field) => ({ kind: 'column', column: field }) as ExpressionIntent,\n\t\t\t\t);\n\t\t\tbuilder.selectIntent = {\n\t\t\t\ttype: 'expressions',\n\t\t\t\tcolumns: [...fieldExpressions, coalesceIntent],\n\t\t\t};\n\t\t} else {\n\t\t\t// No select intent yet - start with coalesce only\n\t\t\t// This means SELECT * plus the coalesce column\n\t\t\tbuilder.selectIntent = {\n\t\t\t\ttype: 'expressions',\n\t\t\t\tcolumns: [coalesceIntent],\n\t\t\t};\n\t\t}\n\n\t\t// SAFETY: coalesce() adds a computed column to the result type.\n\t\t// The runtime value is identical (same QueryBuilderImpl), only the\n\t\t// phantom TResult type parameter changes — invariant in QueryBuilder,\n\t\t// hence the double cast.\n\t\treturn builder as unknown as QueryBuilder<\n\t\t\tTResult & { [P in Alias]: NonNullable<TResult[K]> }\n\t\t>;\n\t}\n\n\tcount(\n\t\tfieldOrOptions?: AggregateOptions | string | DistinctField,\n\t\tas?: string,\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\n\t\tlet field: string | undefined;\n\t\tlet alias: string | undefined = as;\n\t\tlet distinct: boolean | undefined;\n\n\t\tif (fieldOrOptions === undefined) {\n\t\t\t// count() - COUNT(*)\n\t\t} else if (typeof fieldOrOptions === 'string') {\n\t\t\t// count('field', 'alias') - COUNT(field)\n\t\t\tfield = fieldOrOptions;\n\t\t} else if (isDistinctField(fieldOrOptions)) {\n\t\t\t// count(distinct('field'), 'alias') - COUNT(DISTINCT field)\n\t\t\tfield = fieldOrOptions.field;\n\t\t\tdistinct = true;\n\t\t} else {\n\t\t\t// count({ field, as }) - AggregateOptions\n\t\t\tfield = fieldOrOptions.field;\n\t\t\talias = fieldOrOptions.as ?? as;\n\t\t}\n\n\t\tconst agg: AggregateIntent = {\n\t\t\tfunction: 'count',\n\t\t\t...(field !== undefined && { field }),\n\t\t\t...(alias !== undefined && { as: alias }),\n\t\t\t...(distinct !== undefined && { distinct }),\n\t\t};\n\t\tbuilder.aggregates.push(agg);\n\t\treturn builder;\n\t}\n\n\tsum(field: string | DistinctField, as?: string): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tconst isDistinct = isDistinctField(field);\n\t\tconst fieldName = isDistinct ? field.field : field;\n\t\tconst agg: AggregateIntent = {\n\t\t\tfunction: 'sum',\n\t\t\tfield: fieldName,\n\t\t\t...(isDistinct && { distinct: true }),\n\t\t\t...(as !== undefined && { as }),\n\t\t};\n\t\tbuilder.aggregates.push(agg);\n\t\treturn builder;\n\t}\n\n\tavg(field: string | DistinctField, as?: string): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tconst isDistinct = isDistinctField(field);\n\t\tconst fieldName = isDistinct ? field.field : field;\n\t\tconst agg: AggregateIntent = {\n\t\t\tfunction: 'avg',\n\t\t\tfield: fieldName,\n\t\t\t...(isDistinct && { distinct: true }),\n\t\t\t...(as !== undefined && { as }),\n\t\t};\n\t\tbuilder.aggregates.push(agg);\n\t\treturn builder;\n\t}\n\n\tmin(field: string, as?: string): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tconst agg: AggregateIntent = {\n\t\t\tfunction: 'min',\n\t\t\tfield,\n\t\t\t...(as !== undefined && { as }),\n\t\t};\n\t\tbuilder.aggregates.push(agg);\n\t\treturn builder;\n\t}\n\n\tmax(field: string, as?: string): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tconst agg: AggregateIntent = {\n\t\t\tfunction: 'max',\n\t\t\tfield,\n\t\t\t...(as !== undefined && { as }),\n\t\t};\n\t\tbuilder.aggregates.push(agg);\n\t\treturn builder;\n\t}\n\n\tgroupBy(fields: readonly string[]): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.groupByFields.push(...fields);\n\t\treturn builder;\n\t}\n\n\thaving(condition: WhereIntent): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.havingIntents.push(condition);\n\t\treturn builder;\n\t}\n\n\tdistinct(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.isDistinctQuery = true;\n\t\treturn builder;\n\t}\n\n\t/**\n\t * Apply PostgreSQL DISTINCT ON (...) to the query.\n\t *\n\t * @param columns - One or more column names to deduplicate on\n\t * @returns A new QueryBuilder with DISTINCT ON applied\n\t *\n\t * @example\n\t * ```typescript\n\t * orm.select('users').distinctOn('department').all();\n\t * // SQL: SELECT DISTINCT ON (\"department\") * FROM \"users\"\n\t *\n\t * orm.select('logs').distinctOn('user_id', 'action').all();\n\t * // SQL: SELECT DISTINCT ON (\"user_id\", \"action\") * FROM \"logs\"\n\t * ```\n\t */\n\tdistinctOn(...columns: string[]): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.distinctOnColumns = columns;\n\t\treturn builder;\n\t}\n\n\t// --------------------------------------------------------------------------\n\t// Row-level locking (E15)\n\t// --------------------------------------------------------------------------\n\n\tforUpdate(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = {\n\t\t\tstrength: 'forUpdate',\n\t\t\twaitPolicy: builder.lockIntent?.waitPolicy ?? 'block',\n\t\t};\n\t\treturn builder;\n\t}\n\n\tforShare(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = {\n\t\t\tstrength: 'forShare',\n\t\t\twaitPolicy: builder.lockIntent?.waitPolicy ?? 'block',\n\t\t};\n\t\treturn builder;\n\t}\n\n\tforNoKeyUpdate(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = {\n\t\t\tstrength: 'forNoKeyUpdate',\n\t\t\twaitPolicy: builder.lockIntent?.waitPolicy ?? 'block',\n\t\t};\n\t\treturn builder;\n\t}\n\n\tforKeyShare(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = {\n\t\t\tstrength: 'forKeyShare',\n\t\t\twaitPolicy: builder.lockIntent?.waitPolicy ?? 'block',\n\t\t};\n\t\treturn builder;\n\t}\n\n\tlock(\n\t\tstrength: import('@dbsp/types').LockStrength,\n\t\twaitPolicy?: import('@dbsp/types').LockWaitPolicy,\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = { strength, waitPolicy: waitPolicy ?? 'block' };\n\t\treturn builder;\n\t}\n\n\tskipLocked(): QueryBuilder<TResult> {\n\t\tif (!this.lockIntent) {\n\t\t\tthrow new Error(\n\t\t\t\t'skipLocked() requires a preceding lock method (forUpdate, forShare, etc.)',\n\t\t\t);\n\t\t}\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = { ...this.lockIntent, waitPolicy: 'skipLocked' };\n\t\treturn builder;\n\t}\n\n\tnoWait(): QueryBuilder<TResult> {\n\t\tif (!this.lockIntent) {\n\t\t\tthrow new Error(\n\t\t\t\t'noWait() requires a preceding lock method (forUpdate, forShare, etc.)',\n\t\t\t);\n\t\t}\n\t\tconst builder = this.clone();\n\t\tbuilder.lockIntent = { ...this.lockIntent, waitPolicy: 'noWait' };\n\t\treturn builder;\n\t}\n\n\torderBy(\n\t\tfieldOrRecordOrSpecs:\n\t\t\t| string\n\t\t\t| OrderByRecord\n\t\t\t| readonly OrderBySpec[]\n\t\t\t| ExpressionRef\n\t\t\t| ExpressionSpec,\n\t\tdirection?: SortDirection,\n\t\toptions?: { nulls?: import('./types.js').NullsPosition },\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\n\t\t// ExpressionRef form: orderBy(expr) or orderBy(expr, 'desc') or orderBy(expr, 'desc', { nulls: 'last' })\n\t\tif (fieldOrRecordOrSpecs instanceof ExpressionRef) {\n\t\t\tbuilder.orderByIntents.push({\n\t\t\t\texpression: fieldOrRecordOrSpecs.intent,\n\t\t\t\tdirection: direction ?? 'asc',\n\t\t\t\t...(options?.nulls !== undefined ? { nulls: options.nulls } : {}),\n\t\t\t});\n\t\t\treturn builder;\n\t\t}\n\n\t\t// ExpressionSpec form: orderBy(relationColumn(...)) or other plain ExpressionSpec objects\n\t\tif (isExpressionSpec(fieldOrRecordOrSpecs as ColumnSpec)) {\n\t\t\tbuilder.orderByIntents.push({\n\t\t\t\texpression: (fieldOrRecordOrSpecs as { intent: ExpressionIntent })\n\t\t\t\t\t.intent,\n\t\t\t\tdirection: direction ?? 'asc',\n\t\t\t\t...(options?.nulls !== undefined ? { nulls: options.nulls } : {}),\n\t\t\t});\n\t\t\treturn builder;\n\t\t}\n\n\t\t// String form: orderBy('field') or orderBy('field', 'desc') or orderBy('field', 'desc', { nulls: 'last' })\n\t\tif (typeof fieldOrRecordOrSpecs === 'string') {\n\t\t\tbuilder.orderByIntents.push({\n\t\t\t\tfield: fieldOrRecordOrSpecs,\n\t\t\t\tdirection: direction ?? 'asc',\n\t\t\t\t...(options?.nulls !== undefined ? { nulls: options.nulls } : {}),\n\t\t\t});\n\t\t\treturn builder;\n\t\t}\n\n\t\t// Array form: orderBy([{ column, direction, nulls }])\n\t\tif (Array.isArray(fieldOrRecordOrSpecs)) {\n\t\t\tfor (const spec of fieldOrRecordOrSpecs) {\n\t\t\t\tbuilder.orderByIntents.push({\n\t\t\t\t\tfield: spec.column,\n\t\t\t\t\tdirection: spec.direction ?? 'asc',\n\t\t\t\t\tnulls: spec.nulls,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn builder;\n\t\t}\n\n\t\t// Object form: orderBy({ field1: 'desc', field2: 'asc' })\n\t\tfor (const [field, dir] of Object.entries(fieldOrRecordOrSpecs)) {\n\t\t\tbuilder.orderByIntents.push({\n\t\t\t\tfield,\n\t\t\t\tdirection: dir,\n\t\t\t});\n\t\t}\n\t\treturn builder;\n\t}\n\n\tlimit(count: number): QueryBuilder<TResult> {\n\t\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'limit',\n\t\t\t\t'limit must be a non-negative safe integer',\n\t\t\t);\n\t\t}\n\t\tconst builder = this.clone();\n\t\tbuilder.limitValue = count;\n\t\treturn builder;\n\t}\n\n\toffset(count: number): QueryBuilder<TResult> {\n\t\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'offset',\n\t\t\t\t'offset must be a non-negative safe integer',\n\t\t\t);\n\t\t}\n\t\tconst builder = this.clone();\n\t\tbuilder.offsetValue = count;\n\t\treturn builder;\n\t}\n\n\twhere(\n\t\tcondition: WhereIntent | PredicateRef | WhereFilter<TResult>,\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tif (isPredicateRef(condition)) {\n\t\t\tbuilder.whereIntents.push(predicateWhereIntent(condition));\n\t\t\treturn builder;\n\t\t}\n\t\tif (hasPredicateRefDiscriminator(condition)) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'where',\n\t\t\t\t\"predicate belongs to another @dbsp/core copy; reconstruct it with this copy's predicate factories\",\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tcondition instanceof ExpressionRef ||\n\t\t\tisExpressionSpec(condition as ColumnSpec)\n\t\t) {\n\t\t\tthrow new InvalidOperationError(\n\t\t\t\t'where',\n\t\t\t\t'expected a PredicateRef; use unsafeAsPredicate() to assert a deliberate boolean expression',\n\t\t\t);\n\t\t}\n\t\t// Convert object filter to WhereIntent if needed\n\t\tconst intent = isWhereIntent(condition)\n\t\t\t? condition\n\t\t\t: objectToWhereIntent(condition as WhereFilter<Record<string, unknown>>);\n\t\tbuilder.whereIntents.push(intent);\n\t\treturn builder;\n\t}\n\n\tjoin(\n\t\trelationOrTableOrBatch: string | BatchValuesRef,\n\t\topts?: { type?: 'inner' | 'left'; on?: WhereIntent; as?: string },\n\t): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tconst type = opts?.type ?? 'inner';\n\n\t\tif (isBatchValuesRef(relationOrTableOrBatch)) {\n\t\t\tconst bv = relationOrTableOrBatch;\n\t\t\tif (!opts?.on) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'join(batchValuesRef): an `on` condition is required for BatchValues joins',\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Validate all identifiers that reach SQL as quoted names in the\n\t\t\t// unnest() RangeFunction: source alias, column aliases, and the\n\t\t\t// explicit join alias override (opts.as).\n\t\t\tvalidateIdentifier(bv.alias, 'alias');\n\t\t\tfor (const col of bv.columns) {\n\t\t\t\tvalidateIdentifier(col, 'column');\n\t\t\t}\n\t\t\tif (opts.as !== undefined) {\n\t\t\t\tvalidateIdentifier(opts.as, 'alias');\n\t\t\t}\n\t\t\tconst joinIntent: JoinIntent = {\n\t\t\t\tbatchValues: {\n\t\t\t\t\tdata: bv.data,\n\t\t\t\t\tcolumns: bv.columns,\n\t\t\t\t\ttypes: bv.types,\n\t\t\t\t\talias: bv.alias,\n\t\t\t\t\tordinality: bv.ordinality,\n\t\t\t\t},\n\t\t\t\ton: opts.on,\n\t\t\t\ttype,\n\t\t\t\t...(opts.as !== undefined ? { alias: opts.as } : { alias: bv.alias }),\n\t\t\t};\n\t\t\tbuilder.joinIntents.push(joinIntent);\n\t\t} else {\n\t\t\t// FIND-011: Validate string table/relation argument\n\t\t\tvalidateIdentifier(relationOrTableOrBatch, 'table');\n\t\t\t// FIND-008: Validate the as alias when provided\n\t\t\tif (opts?.as !== undefined) {\n\t\t\t\tvalidateIdentifier(opts.as, 'alias');\n\t\t\t}\n\t\t\tconst joinIntent: JoinIntent = opts?.on\n\t\t\t\t? {\n\t\t\t\t\t\ttable: relationOrTableOrBatch,\n\t\t\t\t\t\ton: opts.on,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\t...(opts.as !== undefined && { alias: opts.as }),\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\trelation: relationOrTableOrBatch,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\t...(opts?.as !== undefined && { alias: opts.as }),\n\t\t\t\t\t};\n\t\t\tbuilder.joinIntents.push(joinIntent);\n\t\t}\n\t\treturn builder;\n\t}\n\n\twithStrictMode(strict: boolean): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.strictModeOverride = strict;\n\t\treturn builder;\n\t}\n\n\twithRelationHint(target: string, relation: string): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\t(builder.relationHints as Record<string, string>)[target] = relation;\n\t\treturn builder;\n\t}\n\n\twithPlanOptions(options: PlanOptions): QueryBuilder<TResult> {\n\t\treturn this.cloneWithCtxOverride({\n\t\t\tplanOptionsOverride: {\n\t\t\t\t...this.ctx.planOptionsOverride,\n\t\t\t\t...options,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Get effective strict mode (override takes precedence over ORM-level).\n\t */\n\tprivate getEffectiveStrictMode(): boolean {\n\t\treturn this.strictModeOverride !== undefined\n\t\t\t? this.strictModeOverride\n\t\t\t: this.ctx.strictMode;\n\t}\n\n\tplan(): PlanReport {\n\t\tconst intent = this.buildIntent();\n\n\t\t// E15: Warn when lock is used outside a transaction context\n\t\tif (intent.lock && !this.ctx.inTransaction) {\n\t\t\temitWarning(\n\t\t\t\t'[dbsp] Row-level lock (FOR UPDATE/SHARE) used outside a transaction. ' +\n\t\t\t\t\t'Locks are only effective within a transaction.',\n\t\t\t\t'runtime',\n\t\t\t);\n\t\t}\n\n\t\t// Apply relation hints to includes before planning\n\t\tconst intentWithHints = this.applyRelationHints(intent);\n\n\t\t// Build plan options: dialectCapabilities + per-query overrides\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...(this.ctx.dialectCapabilities && {\n\t\t\t\tdialectCapabilities: this.ctx.dialectCapabilities,\n\t\t\t}),\n\t\t\t// planOptions (global + per-query) take highest precedence\n\t\t\t...this.ctx.planOptionsOverride,\n\t\t};\n\n\t\ttry {\n\t\t\treturn plan(intentWithHints, this.ctx.model, planOptions);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AmbiguousPlanError) {\n\t\t\t\treturn this.handleAmbiguity(error, intentWithHints, planOptions);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync all(): Promise<TResult[]> {\n\t\tconst adapter = this.getConfiguredAdapter();\n\n\t\t// E17b: Hook-aware execution path\n\t\tif (this.ctx.hookStore && hasHooks(this.ctx.hookStore)) {\n\t\t\treturn this.executeWithHooks(adapter, 'all');\n\t\t}\n\n\t\t// Fast path: no hooks — existing behavior, zero overhead\n\t\tconst planReport = this.plan();\n\n\t\t// Build compile options with exactOptionalPropertyTypes compliance\n\t\tconst compileOptions: {\n\t\t\tschemaName?: string;\n\t\t\tmodel: ModelIR;\n\t\t} = { model: this.ctx.model };\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\n\t\t// Use compileWithIncludes to get subquery include info for hasMany relations\n\t\tconst compiledWithIncludes = adapter.compileWithIncludes(\n\t\t\tplanReport,\n\t\t\tcompileOptions,\n\t\t);\n\t\tconst mainResults = (await executeCompiledQuery(\n\t\t\tadapter,\n\t\t\tcompiledWithIncludes.main,\n\t\t\t'all()',\n\t\t)) as TResult[];\n\n\t\t// Create hydrator for result transformation (AUD-005)\n\t\tconst hydrator = new ResultHydrator<TResult>(\n\t\t\tthis.ctx.model,\n\t\t\tthis.from,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\n\t\t// E2E-004: Hydrate json_agg includes by parsing JSON columns\n\t\thydrator.hydrateJsonAggIncludes(\n\t\t\tmainResults,\n\t\t\tplanReport,\n\t\t\tcompiledWithIncludes.main,\n\t\t);\n\n\t\t// E2E-004: Hydrate JOIN includes by grouping dot-prefixed columns\n\t\thydrator.hydrateJoinIncludes(mainResults, planReport);\n\n\t\t// Process subquery includes (hasMany hydration - DX-033)\n\t\tif (compiledWithIncludes.subqueryIncludes.length > 0) {\n\t\t\tawait hydrator.hydrateIncludes(\n\t\t\t\tmainResults,\n\t\t\t\tcompiledWithIncludes.subqueryIncludes,\n\t\t\t\tadapter,\n\t\t\t\tcompileOptions,\n\t\t\t);\n\t\t}\n\n\t\t// Process recursive includes if any\n\t\tif (this.recursiveIncludes.length > 0) {\n\t\t\tawait hydrator.processRecursiveIncludes(\n\t\t\t\tmainResults,\n\t\t\t\tthis.recursiveIncludes,\n\t\t\t\tadapter,\n\t\t\t);\n\t\t}\n\n\t\treturn mainResults;\n\t}\n\n\tasync first(): Promise<TResult | undefined> {\n\t\t// E17b: Hook-aware path — hooks see resultType='first'\n\t\tif (this.ctx.hookStore && hasHooks(this.ctx.hookStore)) {\n\t\t\tconst adapter = this.getConfiguredAdapter();\n\t\t\tconst rows = await this.executeWithHooks<TResult[]>(adapter, 'first');\n\t\t\treturn rows[0];\n\t\t}\n\t\tconst rows = await this.all();\n\t\treturn rows[0];\n\t}\n\n\tasync firstOrThrow(): Promise<TResult> {\n\t\tconst result = await this.first();\n\t\tif (result === undefined) {\n\t\t\tthrow new NotFoundError(this.from);\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync byId(\n\t\tvalue: string | number | Record<string, unknown>,\n\t): Promise<TResult | undefined> {\n\t\tconst condition = this.buildPkCondition(value);\n\t\treturn this.where(condition).first();\n\t}\n\n\tasync byIdOrThrow(\n\t\tvalue: string | number | Record<string, unknown>,\n\t): Promise<TResult> {\n\t\tconst result = await this.byId(value);\n\t\tif (result === undefined) {\n\t\t\tthrow new NotFoundError(\n\t\t\t\tthis.from,\n\t\t\t\t`No record found with the specified primary key`,\n\t\t\t);\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync byIds(values: readonly (string | number)[]): Promise<TResult[]> {\n\t\tif (values.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\treturn this.where(inArray(this.getSimplePkColumn(), [...values])).all();\n\t}\n\n\t/**\n\t * Get the simple primary key column name for the current table.\n\t * Returns the first PK column if composite, falls back to 'id' if undefined.\n\t */\n\tprivate getSimplePkColumn(): string {\n\t\tconst table = this.ctx.model.getTable(this.from);\n\t\tconst pk = table?.primaryKey;\n\t\tif (typeof pk === 'string') {\n\t\t\treturn pk;\n\t\t}\n\t\tif (Array.isArray(pk) && pk.length > 0) {\n\t\t\treturn pk[0]!;\n\t\t}\n\t\treturn 'id'; // fallback for legacy schemas without explicit PK\n\t}\n\n\t/**\n\t * Build a where condition for a primary key lookup.\n\t * Supports simple PKs (string | number) and composite PKs (object).\n\t */\n\tprivate buildPkCondition(\n\t\tvalue: string | number | Record<string, unknown>,\n\t): WhereIntent {\n\t\tif (typeof value === 'string' || typeof value === 'number') {\n\t\t\t// Simple PK - use schema-defined PK column\n\t\t\treturn eq(this.getSimplePkColumn(), value);\n\t\t}\n\t\t// FIND-009: Validate composite PK keys against schema-defined primary key columns\n\t\tconst table = this.ctx.model.getTable(this.from);\n\t\tif (!table) {\n\t\t\tthrow new InvalidOperationError('byId', 'Unknown table');\n\t\t}\n\t\tconst rawPk = table.primaryKey ?? [];\n\t\tconst knownPkCols = new Set(typeof rawPk === 'string' ? [rawPk] : rawPk);\n\t\t// Composite PK - validate keys then build AND condition\n\t\tconst entries = Object.entries(value);\n\t\tif (entries.length === 0) {\n\t\t\tthrow new Error('Composite primary key cannot be empty');\n\t\t}\n\t\tif (knownPkCols.size > 0) {\n\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\tif (!knownPkCols.has(key)) {\n\t\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t\t'byId',\n\t\t\t\t\t\t`Unknown primary key column: ${key}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (entries.length === 1) {\n\t\t\tconst entry = entries[0];\n\t\t\tif (!entry) {\n\t\t\t\tthrow new Error('Composite primary key entry missing');\n\t\t\t}\n\t\t\tconst [field, fieldValue] = entry;\n\t\t\treturn eq(field, fieldValue);\n\t\t}\n\t\tconst conditions = entries.map(([field, fieldValue]) =>\n\t\t\teq(field, fieldValue),\n\t\t);\n\t\treturn and(...conditions);\n\t}\n\n\tdump(meta?: DumpMetaInput): Dump {\n\t\tconst adapter = this.getConfiguredAdapter();\n\t\tconst planReport = this.plan();\n\n\t\t// Build compile options with exactOptionalPropertyTypes compliance\n\t\tconst compileOptions: {\n\t\t\tschemaName?: string;\n\t\t\tmodel: ModelIR;\n\t\t} = { model: this.ctx.model };\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\n\t\tconst compiled = adapter.compile(planReport, compileOptions);\n\n\t\t// Build DumpMeta: adapter-level schema + caller-supplied queryName/correlationId\n\t\tconst dumpMeta: DumpMetaInput = {\n\t\t\t...(meta?.queryName !== undefined && { queryName: meta.queryName }),\n\t\t\t...(meta?.correlationId !== undefined && {\n\t\t\t\tcorrelationId: meta.correlationId,\n\t\t\t}),\n\t\t};\n\n\t\t// Use adapter.createDump() to properly capture adapter's schema\n\t\t// Then merge with context schema if needed\n\t\tconst dump = adapter.createDump(planReport, compiled, dumpMeta);\n\n\t\t// If adapter didn't set schema but context has one, add it\n\t\tif (dump.meta?.schema === undefined && this.ctx.schemaName !== undefined) {\n\t\t\treturn {\n\t\t\t\t...dump,\n\t\t\t\tmeta: {\n\t\t\t\t\t...dump.meta,\n\t\t\t\t\tschema: this.ctx.schemaName,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn dump;\n\t}\n\n\tasync exists(): Promise<boolean> {\n\t\tconst adapter = this.getConfiguredAdapter();\n\n\t\t// E17b: Hook-aware path for exists()\n\t\tif (this.ctx.hookStore && hasHooks(this.ctx.hookStore)) {\n\t\t\t// INV-07: Re-entrancy guard\n\t\t\treturn withReentrancyGuard(this.ctx.hookStore, (s) =>\n\t\t\t\tthis.existsWithHooks(adapter, s),\n\t\t\t);\n\t\t}\n\n\t\t// Fast path: no hooks\n\t\tconst existsIntent = this.buildExistsIntent();\n\t\tconst intentWithHints = this.applyRelationHints(existsIntent);\n\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...(this.ctx.dialectCapabilities && {\n\t\t\t\tdialectCapabilities: this.ctx.dialectCapabilities,\n\t\t\t}),\n\t\t\t...this.ctx.planOptionsOverride,\n\t\t};\n\n\t\tconst planReport = this.planWithAmbiguityHandling(\n\t\t\tintentWithHints,\n\t\t\tplanOptions,\n\t\t);\n\n\t\tconst compileOptions: {\n\t\t\tschemaName?: string;\n\t\t\tmodel: ModelIR;\n\t\t} = { model: this.ctx.model };\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\n\t\tconst compiled = adapter.compile(planReport, compileOptions);\n\t\tconst rows = await executeCompiledQuery(adapter, compiled, 'exists()');\n\t\treturn (\n\t\t\trows.length > 0 && (rows[0] as Record<string, unknown>).exists === true\n\t\t);\n\t}\n\n\tprivate async existsWithHooks(\n\t\tadapter: Adapter,\n\t\tstore: HookStore,\n\t): Promise<boolean> {\n\t\tconst startTime = Date.now();\n\n\t\t// Build raw intent (without defaultFilters) for hooks\n\t\tconst rawIntent = this.buildIntent(false);\n\t\tconst beforeCtx: QueryHookContext = {\n\t\t\ttable: rawIntent.from,\n\t\t\toperation: 'select',\n\t\t\tintent: rawIntent,\n\t\t\tresultType: 'exists',\n\t\t\t...(this.ctx.schemaName !== undefined && {\n\t\t\t\tschemaName: this.ctx.schemaName,\n\t\t\t}),\n\t\t\t...(this.ctx.inTransaction && { inTransaction: true }),\n\t\t};\n\n\t\t// Run beforeQuery hooks\n\t\tlet intent: QueryIntent;\n\t\tlet afterHookCtx: QueryHookContext;\n\t\ttry {\n\t\t\tafterHookCtx = await runBeforeQueryHooks(\n\t\t\t\tstore.beforeQuery,\n\t\t\t\tbeforeCtx,\n\t\t\t\tthis.ctx.onHookError,\n\t\t\t);\n\t\t\tintent = afterHookCtx.intent;\n\t\t} catch (error) {\n\t\t\tif (store.onError.length > 0) {\n\t\t\t\tthrow await runOnErrorHooks(store.onError, {\n\t\t\t\t\ttable: this.from,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\tintent: rawIntent,\n\t\t\t\t\tphase: 'beforeQuery',\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\t// Apply defaultFilters AFTER hooks (INV-01)\n\t\tintent = this.applyDefaultFiltersToIntent(intent);\n\n\t\t// Build exists-wrapped intent from the (potentially modified) intent\n\t\tconst existsIntent = this.buildExistsIntentFromIntent(intent);\n\t\tconst intentWithHints = this.applyRelationHints(existsIntent);\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...(this.ctx.dialectCapabilities && {\n\t\t\t\tdialectCapabilities: this.ctx.dialectCapabilities,\n\t\t\t}),\n\t\t\t...this.ctx.planOptionsOverride,\n\t\t};\n\t\tconst planReport = this.planWithAmbiguityHandling(\n\t\t\tintentWithHints,\n\t\t\tplanOptions,\n\t\t);\n\t\tconst compileOptions: { schemaName?: string; model: ModelIR } = {\n\t\t\tmodel: this.ctx.model,\n\t\t};\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\t\tconst compiled = adapter.compile(planReport, compileOptions);\n\t\tconst rows = await executeCompiledQuery(adapter, compiled, 'exists()');\n\t\tconst result =\n\t\t\trows.length > 0 && (rows[0] as Record<string, unknown>).exists === true;\n\n\t\t// afterQuery with boolean result\n\t\tconst afterCtx: QueryHookContext = {\n\t\t\ttable: intent.from,\n\t\t\toperation: 'select',\n\t\t\tintent,\n\t\t\tresultType: 'exists',\n\t\t\tsql: compiled.sql,\n\t\t\tparameters: compiled.parameters,\n\t\t\tduration: Date.now() - startTime,\n\t\t\t...(this.ctx.schemaName !== undefined && {\n\t\t\t\tschemaName: this.ctx.schemaName,\n\t\t\t}),\n\t\t\t...(this.ctx.inTransaction !== undefined && {\n\t\t\t\tinTransaction: this.ctx.inTransaction,\n\t\t\t}),\n\t\t\t...(afterHookCtx.correlationId !== undefined && {\n\t\t\t\tcorrelationId: afterHookCtx.correlationId,\n\t\t\t}),\n\t\t};\n\t\ttry {\n\t\t\tawait runAfterQueryObservers(\n\t\t\t\tstore.afterQueryObservers,\n\t\t\t\tafterCtx,\n\t\t\t\tresult,\n\t\t\t\tthis.ctx.onObserverError,\n\t\t\t);\n\t\t\treturn await runAfterQueryHooks(\n\t\t\t\tstore.afterQuery,\n\t\t\t\tafterCtx,\n\t\t\t\tresult,\n\t\t\t\tthis.ctx.onHookError,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (store.onError.length > 0) {\n\t\t\t\tthrow await runOnErrorHooks(store.onError, {\n\t\t\t\t\ttable: this.from,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\tintent,\n\t\t\t\t\tphase: 'afterQuery',\n\t\t\t\t\tsql: compiled.sql,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\texistsDump(): Dump {\n\t\tconst adapter = this.getConfiguredAdapter();\n\t\tconst existsIntent = this.buildExistsIntent();\n\t\tconst intentWithHints = this.applyRelationHints(existsIntent);\n\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...(this.ctx.dialectCapabilities && {\n\t\t\t\tdialectCapabilities: this.ctx.dialectCapabilities,\n\t\t\t}),\n\t\t\t...this.ctx.planOptionsOverride,\n\t\t};\n\n\t\tconst planReport = this.planWithAmbiguityHandling(\n\t\t\tintentWithHints,\n\t\t\tplanOptions,\n\t\t);\n\n\t\tconst compileOptions: {\n\t\t\tschemaName?: string;\n\t\t\tmodel: ModelIR;\n\t\t} = { model: this.ctx.model };\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\n\t\tconst compiled = adapter.compile(planReport, compileOptions);\n\t\tconst dump = adapter.createDump(planReport, compiled);\n\n\t\tif (dump.meta?.schema === undefined && this.ctx.schemaName !== undefined) {\n\t\t\treturn {\n\t\t\t\t...dump,\n\t\t\t\tmeta: {\n\t\t\t\t\t...dump.meta,\n\t\t\t\t\tschema: this.ctx.schemaName,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn dump;\n\t}\n\n\texecute(): Promise<TResult[]> {\n\t\treturn this.all();\n\t}\n\n\tstream(options?: StreamOptions): AsyncIterableIterator<TResult> {\n\t\treturn streamImpl.stream(this, options);\n\t}\n\n\t/**\n\t * Execute the query with offset-based pagination.\n\t */\n\tasync paginate(options?: PaginateOptions): Promise<PaginatedResult<TResult>> {\n\t\treturn paginationImpl.paginate(this, options);\n\t}\n\n\t/**\n\t * Execute the query with cursor-based pagination.\n\t */\n\tasync cursorPaginate(\n\t\toptions?: CursorPaginateOptions,\n\t): Promise<CursorPaginatedResult<TResult>> {\n\t\treturn paginationImpl.cursorPaginate(this, options);\n\t}\n\n\t/**\n\t * Get configured adapter, throwing if not configured.\n\t * @throws {ExecutionError} If adapter is not configured\n\t * @returns The configured adapter instance\n\t */\n\t/** @internal — called by pagination-impl and stream-impl */\n\tgetConfiguredAdapter(): Adapter {\n\t\tif (!this.ctx.adapter) {\n\t\t\tthrow new ExecutionError({\n\t\t\t\toperation: 'query execution',\n\t\t\t\treason: 'Adapter not configured',\n\t\t\t\tfix: 'Pass an adapter to createOrm({ adapter: yourAdapter })',\n\t\t\t});\n\t\t}\n\t\treturn this.ctx.adapter;\n\t}\n\n\t/**\n\t * Apply relation hints to includes that don't have explicit `via`.\n\t */\n\t/** @internal — called by stream-impl */\n\tapplyRelationHints(intent: QueryIntent): QueryIntent {\n\t\tif (!intent.include || Object.keys(this.relationHints).length === 0) {\n\t\t\treturn intent;\n\t\t}\n\n\t\tconst updatedIncludes = intent.include.map((inc) =>\n\t\t\tapplyHintToIncludeRecursive(inc, this.relationHints),\n\t\t);\n\n\t\treturn {\n\t\t\t...intent,\n\t\t\tinclude: updatedIncludes,\n\t\t};\n\t}\n\n\t/**\n\t * Build the QueryIntent from current state.\n\t * Handles exactOptionalPropertyTypes by only including defined properties.\n\t */\n\t/** @internal Used by CteQueryBuilder to access query intent without executing. */\n\tbuildIntent(applyDefaultFilters = true): QueryIntent {\n\t\tconst intent: Mutable<QueryIntent> = {\n\t\t\ttype: 'select',\n\t\t\tfrom: this.from,\n\t\t};\n\n\t\t// Handle aggregates - convert to SelectAggregateIntent\n\t\tif (this.aggregates.length > 0) {\n\t\t\tconst aggregateSelect: Mutable<SelectAggregateIntent> = {\n\t\t\t\ttype: 'aggregate',\n\t\t\t\taggregates: [...this.aggregates],\n\t\t\t};\n\t\t\t// Add group by fields to the select for projection\n\t\t\tif (this.groupByFields.length > 0) {\n\t\t\t\taggregateSelect.fields = [...this.groupByFields];\n\t\t\t}\n\t\t\tintent.select = aggregateSelect as SelectAggregateIntent;\n\t\t} else if (this.selectIntent !== undefined) {\n\t\t\tintent.select = this.selectIntent;\n\t\t}\n\n\t\t// Combine default filter (soft delete) with user-provided where conditions\n\t\tconst allWhereIntents: WhereIntent[] = [];\n\n\t\t// Prepend default filter for this table (if configured and not skipped)\n\t\tif (applyDefaultFilters) {\n\t\t\tconst tableDefaultFilter =\n\t\t\t\t!this.skipDefaultFilters && this.ctx.defaultFilters\n\t\t\t\t\t? this.ctx.defaultFilters[this.from]\n\t\t\t\t\t: undefined;\n\t\t\tif (tableDefaultFilter) {\n\t\t\t\tallWhereIntents.push(tableDefaultFilter);\n\t\t\t}\n\t\t}\n\n\t\t// Add user-provided filters\n\t\tallWhereIntents.push(...this.whereIntents);\n\n\t\t// Combine with AND\n\t\tif (allWhereIntents.length === 1) {\n\t\t\tconst singleWhere = allWhereIntents[0];\n\t\t\tif (singleWhere !== undefined) {\n\t\t\t\tintent.where = singleWhere;\n\t\t\t}\n\t\t} else if (allWhereIntents.length > 1) {\n\t\t\tintent.where = and(...allWhereIntents);\n\t\t}\n\n\t\t// Combine multiple having conditions with AND (DX-034)\n\t\tif (this.havingIntents.length === 1) {\n\t\t\tconst singleHaving = this.havingIntents[0];\n\t\t\tif (singleHaving !== undefined) {\n\t\t\t\tintent.having = singleHaving;\n\t\t\t}\n\t\t} else if (this.havingIntents.length > 1) {\n\t\t\tintent.having = and(...this.havingIntents);\n\t\t}\n\n\t\t// Add SELECT DISTINCT flag (DX-034)\n\t\tif (this.isDistinctQuery) {\n\t\t\tintent.distinct = true;\n\t\t}\n\n\t\t// Add DISTINCT ON columns (PostgreSQL-specific)\n\t\tif (this.distinctOnColumns.length > 0) {\n\t\t\tintent.distinctOn = [...this.distinctOnColumns];\n\t\t}\n\n\t\tif (this.includes.length > 0) {\n\t\t\tintent.include = this.includes;\n\t\t}\n\t\tif (this.groupByFields.length > 0) {\n\t\t\tintent.groupBy = [...this.groupByFields];\n\t\t}\n\t\tif (this.orderByIntents.length > 0) {\n\t\t\tintent.orderBy = [...this.orderByIntents];\n\t\t}\n\t\tif (this.limitValue !== undefined) {\n\t\t\tintent.limit = this.limitValue;\n\t\t}\n\t\tif (this.offsetValue !== undefined) {\n\t\t\tintent.offset = this.offsetValue;\n\t\t}\n\n\t\t// Lock clause (E15)\n\t\tif (this.lockIntent) {\n\t\t\tif (this.groupByFields.length > 0) {\n\t\t\t\tthrow new InvalidOperationError(\n\t\t\t\t\t'lock',\n\t\t\t\t\t'FOR UPDATE/SHARE is incompatible with GROUP BY',\n\t\t\t\t);\n\t\t\t}\n\t\t\tintent.lock = this.lockIntent;\n\t\t}\n\n\t\t// JOIN clauses (FR-10)\n\t\tif (this.joinIntents.length > 0) {\n\t\t\tintent.joins = [...this.joinIntents];\n\t\t}\n\n\t\t// BatchValues as primary FROM source\n\t\tif (this.batchValuesSource) {\n\t\t\tintent.batchValuesSource = this.batchValuesSource;\n\t\t}\n\n\t\treturn intent as QueryIntent;\n\t}\n\n\t/**\n\t * Apply defaultFilters to an intent (E17b: applied AFTER hooks for INV-01).\n\t * @internal\n\t */\n\t/** @internal — called by stream-impl */\n\tapplyDefaultFiltersToIntent(intent: QueryIntent): QueryIntent {\n\t\tif (this.skipDefaultFilters || !this.ctx.defaultFilters) return intent;\n\t\tconst tableDefaultFilter = this.ctx.defaultFilters[this.from];\n\t\tif (!tableDefaultFilter) return intent;\n\n\t\tconst existingWhere = intent.where;\n\t\tconst newWhere = existingWhere\n\t\t\t? and(tableDefaultFilter, existingWhere)\n\t\t\t: tableDefaultFilter;\n\n\t\treturn { ...intent, where: newWhere };\n\t}\n\n\t/**\n\t * Execute a query with hook interception (E17b).\n\t * Flow: buildIntent(raw) → beforeQuery → defaultFilters → plan → execute → hydrate → afterQuery\n\t * @internal\n\t */\n\tprivate async executeWithHooks<R>(\n\t\tadapter: Adapter,\n\t\tresultType: QueryResultType,\n\t): Promise<R> {\n\t\tconst store = this.ctx.hookStore;\n\t\tif (!store) throw new Error('executeWithHooks called without hookStore');\n\t\t// INV-07: Re-entrancy guard — prevent infinite loops from hooks issuing queries\n\t\treturn withReentrancyGuard(store, (s) =>\n\t\t\tthis.executeWithHooksInner<R>(adapter, resultType, s),\n\t\t);\n\t}\n\n\tprivate async executeWithHooksInner<R>(\n\t\tadapter: Adapter,\n\t\tresultType: QueryResultType,\n\t\tstore: HookStore,\n\t): Promise<R> {\n\t\tconst startTime = Date.now();\n\n\t\t// 1. Build intent WITHOUT defaultFilters — hooks see raw intent\n\t\tconst rawIntent = this.buildIntent(false);\n\n\t\t// 2. Build beforeQuery context\n\t\tconst beforeCtx: QueryHookContext = {\n\t\t\ttable: this.from,\n\t\t\toperation: 'select',\n\t\t\tintent: rawIntent,\n\t\t\tresultType,\n\t\t\t...(this.ctx.schemaName !== undefined && {\n\t\t\t\tschemaName: this.ctx.schemaName,\n\t\t\t}),\n\t\t\t...(this.ctx.inTransaction && { inTransaction: true }),\n\t\t};\n\n\t\t// 3. Run beforeQuery hooks (FIFO) — may modify intent\n\t\tlet intent: QueryIntent;\n\t\tlet afterHookCtx: QueryHookContext;\n\t\ttry {\n\t\t\tafterHookCtx = await runBeforeQueryHooks(\n\t\t\t\tstore.beforeQuery,\n\t\t\t\tbeforeCtx,\n\t\t\t\tthis.ctx.onHookError,\n\t\t\t);\n\t\t\tintent = afterHookCtx.intent;\n\t\t} catch (error) {\n\t\t\t// Run onError hooks for beforeQuery failures\n\t\t\tif (store.onError.length > 0) {\n\t\t\t\tconst finalError = await runOnErrorHooks(store.onError, {\n\t\t\t\t\ttable: this.from,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\tintent: rawIntent,\n\t\t\t\t\tphase: 'beforeQuery',\n\t\t\t\t});\n\t\t\t\tthrow finalError;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\t// 4. Apply defaultFilters AFTER hooks (INV-01: cannot be bypassed)\n\t\tintent = this.applyDefaultFiltersToIntent(intent);\n\n\t\t// 5. Apply relation hints and plan\n\t\tconst intentWithHints = this.applyRelationHints(intent);\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...(this.ctx.dialectCapabilities && {\n\t\t\t\tdialectCapabilities: this.ctx.dialectCapabilities,\n\t\t\t}),\n\t\t\t...this.ctx.planOptionsOverride,\n\t\t};\n\n\t\tconst planReport = this.planWithAmbiguityHandling(\n\t\t\tintentWithHints,\n\t\t\tplanOptions,\n\t\t);\n\n\t\t// 6. Compile and execute\n\t\tconst compileOptions: { schemaName?: string; model: ModelIR } = {\n\t\t\tmodel: this.ctx.model,\n\t\t};\n\t\tif (this.ctx.schemaName !== undefined) {\n\t\t\tcompileOptions.schemaName = this.ctx.schemaName;\n\t\t}\n\n\t\tconst compiledWithIncludes = adapter.compileWithIncludes(\n\t\t\tplanReport,\n\t\t\tcompileOptions,\n\t\t);\n\n\t\tlet mainResults: TResult[];\n\t\ttry {\n\t\t\tmainResults = (await executeCompiledQuery(\n\t\t\t\tadapter,\n\t\t\t\tcompiledWithIncludes.main,\n\t\t\t\t'all()',\n\t\t\t)) as TResult[];\n\t\t} catch (error) {\n\t\t\tif (store.onError.length > 0) {\n\t\t\t\tconst finalError = await runOnErrorHooks(store.onError, {\n\t\t\t\t\ttable: this.from,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\tintent,\n\t\t\t\t\tphase: 'afterQuery',\n\t\t\t\t\tsql: compiledWithIncludes.main.sql,\n\t\t\t\t});\n\t\t\t\tthrow finalError;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\t// 7. Hydrate\n\t\tconst hydrator = new ResultHydrator<TResult>(\n\t\t\tthis.ctx.model,\n\t\t\tthis.from,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t\thydrator.hydrateJsonAggIncludes(\n\t\t\tmainResults,\n\t\t\tplanReport,\n\t\t\tcompiledWithIncludes.main,\n\t\t);\n\t\thydrator.hydrateJoinIncludes(mainResults, planReport);\n\t\tif (compiledWithIncludes.subqueryIncludes.length > 0) {\n\t\t\tawait hydrator.hydrateIncludes(\n\t\t\t\tmainResults,\n\t\t\t\tcompiledWithIncludes.subqueryIncludes,\n\t\t\t\tadapter,\n\t\t\t\tcompileOptions,\n\t\t\t);\n\t\t}\n\t\tif (this.recursiveIncludes.length > 0) {\n\t\t\tawait hydrator.processRecursiveIncludes(\n\t\t\t\tmainResults,\n\t\t\t\tthis.recursiveIncludes,\n\t\t\t\tadapter,\n\t\t\t);\n\t\t}\n\n\t\t// 8. Build afterQuery context with timing + SQL info\n\t\tconst duration = Date.now() - startTime;\n\t\tconst afterCtx: QueryHookContext = {\n\t\t\ttable: intent.from,\n\t\t\toperation: 'select',\n\t\t\tintent,\n\t\t\tresultType,\n\t\t\tsql: compiledWithIncludes.main.sql,\n\t\t\tparameters: compiledWithIncludes.main.parameters,\n\t\t\tduration,\n\t\t\t...(this.ctx.schemaName !== undefined && {\n\t\t\t\tschemaName: this.ctx.schemaName,\n\t\t\t}),\n\t\t\t...(this.ctx.inTransaction !== undefined && {\n\t\t\t\tinTransaction: this.ctx.inTransaction,\n\t\t\t}),\n\t\t\t...(afterHookCtx.correlationId !== undefined && {\n\t\t\t\tcorrelationId: afterHookCtx.correlationId,\n\t\t\t}),\n\t\t};\n\n\t\t// 9. Run afterQuery hooks (LIFO) — may transform results\n\t\ttry {\n\t\t\tawait runAfterQueryObservers(\n\t\t\t\tstore.afterQueryObservers,\n\t\t\t\tafterCtx,\n\t\t\t\tmainResults,\n\t\t\t\tthis.ctx.onObserverError,\n\t\t\t);\n\t\t\t// SAFETY: R defaults to TResult[] from callers; afterQuery hooks may\n\t\t\t// transform the shape, hence the generic. The double cast bridges\n\t\t\t// the gap between the concrete TResult[] and the generic R.\n\t\t\tconst finalResults = await runAfterQueryHooks(\n\t\t\t\tstore.afterQuery,\n\t\t\t\tafterCtx,\n\t\t\t\tmainResults as unknown as R,\n\t\t\t\tthis.ctx.onHookError,\n\t\t\t);\n\t\t\treturn finalResults;\n\t\t} catch (error) {\n\t\t\tif (store.onError.length > 0) {\n\t\t\t\tconst finalError = await runOnErrorHooks(store.onError, {\n\t\t\t\t\ttable: this.from,\n\t\t\t\t\toperation: 'select',\n\t\t\t\t\terror: normalizeHookError(error),\n\t\t\t\t\tintent,\n\t\t\t\t\tphase: 'afterQuery',\n\t\t\t\t\tsql: compiledWithIncludes.main.sql,\n\t\t\t\t});\n\t\t\t\tthrow finalError;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Build an existence-check intent from current state.\n\t * Strips orderBy (irrelevant once wrapped in EXISTS), sets existsWrap and\n\t * limit: 1, and keeps every include unchanged; the compiler decides which\n\t * include contributions still need to be emitted (see exists-intent.ts\n\t * and shouldEmitInclude() in the pgsql compiler) (#230).\n\t */\n\tprivate buildExistsIntent(): QueryIntent {\n\t\treturn buildExistsIntent(this.buildIntent());\n\t}\n\n\t/**\n\t * Build exists-wrapped intent from a pre-built intent (E17b: for hook-aware path).\n\t * @internal\n\t */\n\tprivate buildExistsIntentFromIntent(baseIntent: QueryIntent): QueryIntent {\n\t\treturn buildExistsIntent(baseIntent);\n\t}\n\n\t/**\n\t * Handle ambiguity based on strict mode setting.\n\t */\n\n\t/**\n\t * Thin wrapper around the planner that applies the same ambiguity-handling\n\t * logic as `plan()` (the builder method). Used by exists/existsDump paths\n\t * which build their own planOptions and therefore cannot call `this.plan()`\n\t * directly (which would rebuild the intent from scratch).\n\t *\n\t * FIND-016: exists() / existsDump() called the raw planner function directly,\n\t * bypassing the ambiguity catch that lives in the builder's plan() wrapper.\n\t */\n\t/** @internal — called by stream-impl */\n\tplanWithAmbiguityHandling(\n\t\tintent: QueryIntent,\n\t\tplanOptions: PlanOptions,\n\t): PlanReport {\n\t\ttry {\n\t\t\treturn plan(intent, this.ctx.model, planOptions);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AmbiguousPlanError) {\n\t\t\t\treturn this.handleAmbiguity(error, intent, planOptions);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate handleAmbiguity(\n\t\terror: AmbiguousPlanError,\n\t\tintent: QueryIntent,\n\t\tbasePlanOptions: PlanOptions = {},\n\t): PlanReport {\n\t\tif (this.getEffectiveStrictMode()) {\n\t\t\t// Strict mode: convert to AmbiguousRelationError and throw\n\t\t\tthrow new AmbiguousRelationError(\n\t\t\t\terror.sourceTable,\n\t\t\t\terror.targetTable,\n\t\t\t\terror.options,\n\t\t\t);\n\t\t}\n\n\t\t// Lenient mode: deterministic tie-break — sort alphabetically so that\n\t\t// schema definition order does not influence which relation is chosen.\n\t\t// This ensures stable query results across schema refactoring.\n\t\t// FIND-015: picking options[0] without sorting is non-deterministic.\n\t\tconst sortedOptions = error.options.slice().sort();\n\t\tconst firstRelation = sortedOptions[0];\n\t\tif (!firstRelation) {\n\t\t\tthrow error; // Safety: should never happen\n\t\t}\n\n\t\tconst disambiguateKey = `${error.sourceTable}.${error.targetTable}`;\n\t\tconst planOptions: PlanOptions = {\n\t\t\t...basePlanOptions,\n\t\t\tdisambiguate: {\n\t\t\t\t...basePlanOptions.disambiguate,\n\t\t\t\t[disambiguateKey]: firstRelation, // alphabetically-first (see sortedOptions)\n\t\t\t},\n\t\t};\n\n\t\t// Re-plan with disambiguation\n\t\tconst result = plan(intent, this.ctx.model, planOptions);\n\n\t\t// Add warning about automatic disambiguation.\n\t\t// The chosen relation is the alphabetically-first name (deterministic\n\t\t// tie-break), not insertion order, so schema refactoring cannot silently\n\t\t// change query results.\n\t\tconst warning = {\n\t\t\tcode: 'AMBIGUOUS_RELATION' as const,\n\t\t\tmessage:\n\t\t\t\t`Ambiguous relation to '${error.targetTable}' from '${error.sourceTable}' ` +\n\t\t\t\t`was automatically resolved to '${firstRelation}' (alphabetical tie-break). ` +\n\t\t\t\t`Available options: ${sortedOptions.join(', ')}.`,\n\t\t\tsuggestion: `Use { via: '${firstRelation}' } or another option to make this explicit.`,\n\t\t};\n\n\t\treturn {\n\t\t\t...result,\n\t\t\twarnings: [...result.warnings, warning],\n\t\t};\n\t}\n\n\t/**\n\t * Create a shallow clone of this builder.\n\t *\n\t * The cloned builder owns its own `planOptionsOverride` object reference so\n\t * per-builder overrides do not leak across clones; all other ctx fields are\n\t * intentionally shared by reference — model / adapter / hookStore are part\n\t * of the ORM instance's stable configuration and are treated as read-only\n\t * for the lifetime of the builder chain.\n\t *\n\t * @internal — called by pagination-impl and stream-impl\n\t */\n\tclone(): QueryBuilderImpl<TResult> {\n\t\t// Shallow-clone planOptionsOverride so the cloned builder owns its own\n\t\t// reference and per-builder overrides do not leak across clones.\n\t\treturn this.cloneWithCtxOverride(\n\t\t\tthis.ctx.planOptionsOverride !== undefined\n\t\t\t\t? { planOptionsOverride: { ...this.ctx.planOptionsOverride } }\n\t\t\t\t: {},\n\t\t);\n\t}\n\n\t/**\n\t * Build a new builder whose ctx merges `ctxOverride` over the source ctx.\n\t * Pure merge: callers own the policy of what to spread/clone.\n\t *\n\t * @internal — used by clone() and withPlanOptions().\n\t */\n\tprivate cloneWithCtxOverride(\n\t\tctxOverride: Partial<QueryBuilderContext>,\n\t): QueryBuilderImpl<TResult> {\n\t\tconst builder = new QueryBuilderImpl<TResult>(\n\t\t\t{ ...this.ctx, ...ctxOverride },\n\t\t\tthis.from,\n\t\t\t{\n\t\t\t\t...this.relationHints,\n\t\t\t},\n\t\t);\n\t\t// Clone array state\n\t\tbuilder.includes.push(...this.includes);\n\t\tbuilder.recursiveIncludes.push(...this.recursiveIncludes);\n\t\tbuilder.whereIntents.push(...this.whereIntents);\n\t\tbuilder.havingIntents.push(...this.havingIntents);\n\t\tbuilder.aggregates.push(...this.aggregates);\n\t\tbuilder.groupByFields.push(...this.groupByFields);\n\t\tbuilder.orderByIntents.push(...this.orderByIntents);\n\t\t// Clone scalar state\n\t\tbuilder.selectIntent = this.selectIntent;\n\t\tbuilder.isDistinctQuery = this.isDistinctQuery;\n\t\tbuilder.distinctOnColumns = [...this.distinctOnColumns];\n\t\tbuilder.skipDefaultFilters = this.skipDefaultFilters;\n\t\tbuilder.strictModeOverride = this.strictModeOverride;\n\t\tbuilder.limitValue = this.limitValue;\n\t\tbuilder.offsetValue = this.offsetValue;\n\t\tbuilder.lockIntent = this.lockIntent;\n\t\tbuilder.joinIntents.push(...this.joinIntents);\n\t\tif (this.batchValuesSource) {\n\t\t\tbuilder.batchValuesSource = this.batchValuesSource;\n\t\t}\n\t\treturn builder;\n\t}\n\n\t/**\n\t * Disable default filters (e.g., soft delete) for this query.\n\t * Use when you need to query deleted/inactive records.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Query all products including soft-deleted ones\n\t * const allProducts = await orm\n\t * .select('products')\n\t * .withoutDefaultFilters()\n\t * .all();\n\t * ```\n\t */\n\t// --------------------------------------------------------------------------\n\t// Set operations (UNION / INTERSECT / EXCEPT)\n\t// --------------------------------------------------------------------------\n\n\tunion(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'union',\n\t\t\t\tfalse,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\tunionAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'union',\n\t\t\t\ttrue,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\tintersect(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'intersect',\n\t\t\t\tfalse,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\tintersectAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'intersect',\n\t\t\t\ttrue,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\texcept(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'except',\n\t\t\t\tfalse,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\texceptAll(other: QueryBuilder<TResult>): SetOperationBuilder<TResult> {\n\t\treturn new SetOperationBuilderImpl(\n\t\t\tbuildSetOperationIntent(\n\t\t\t\t'except',\n\t\t\t\ttrue,\n\t\t\t\tthis,\n\t\t\t\tother as unknown as QueryIntentSource,\n\t\t\t),\n\t\t\tthis.ctx.model,\n\t\t\tthis.ctx.adapter,\n\t\t\tthis.ctx.schemaName,\n\t\t);\n\t}\n\n\twithoutDefaultFilters(): QueryBuilder<TResult> {\n\t\tconst builder = this.clone();\n\t\tbuilder.skipDefaultFilters = true;\n\t\treturn builder;\n\t}\n}\n","/**\n * Raw CTE builder — WITH RECURSIVE support via explicit base/step query builders (FR-8).\n *\n * Provides a fluent API for building arbitrary WITH RECURSIVE queries from\n * a base (anchor) QueryBuilder and a step (recursive) QueryBuilder.\n *\n * @example\n * ```typescript\n * const chain = orm.recursive('parent_chain', {\n * base: orm.select('symbols').where(eq('id', rootId)),\n * step: orm.select('parent_chain'),\n * maxDepth: 10,\n * unionAll: true,\n * });\n * const results = await chain.columns(['id', 'name', 'depth']).orderBy('depth').all();\n * ```\n */\n\nimport type {\n\tAdapter,\n\tCompiledQuery,\n\tCteQueryIntent,\n\tModelIR,\n\tOrderByIntent,\n\tQueryIntent,\n\tRawCteIntent,\n\tSelectWithExpressionsIntent,\n\tWhereIntent,\n} from '@dbsp/types';\nimport { executeCompiledQuery } from '../adapter.js';\nimport { requireAdapter as requireAdapterUtil } from './builder-utils.js';\nimport type { QueryBuilderImpl } from './query-builder.js';\nimport type { QueryBuilder } from './query-builder-types.js';\n\n/**\n * Options for `orm.recursive()`.\n */\nexport interface RecursiveOptions {\n\t/** Base (anchor) query — produces the starting rows. */\n\treadonly base: QueryBuilder<unknown>;\n\t/** Recursive step query — references the CTE name as its FROM table. */\n\treadonly step: QueryBuilder<unknown>;\n\t/** Maximum recursion depth (guards against infinite loops). */\n\treadonly maxDepth?: number;\n\t/**\n\t * Column name in the step query that tracks depth (used with maxDepth).\n\t * When set, injects WHERE <depthColumn> < maxDepth into the step during compilation.\n\t * @default 'depth'\n\t */\n\treadonly depthColumn?: string;\n\t/** When true (default), use UNION ALL. When false, use UNION (deduplicates). */\n\treadonly unionAll?: boolean;\n}\n\n/**\n * Result of compiling a recursive CTE query.\n */\nexport interface RecursiveDump {\n\treadonly sql: string;\n\treadonly params: readonly unknown[];\n\treadonly intent: CteQueryIntent;\n}\n\n/**\n * Fluent builder for constructing and executing a WITH RECURSIVE query.\n *\n * Obtain via `orm.recursive(name, options)`.\n */\nexport class RawCteQueryBuilder<TResult = unknown> {\n\tprivate readonly cteName: string;\n\tprivate readonly rawCteIntent: RawCteIntent;\n\tprivate readonly adapter: Adapter | undefined;\n\tprivate readonly schemaName: string | undefined;\n\tprivate readonly model: ModelIR | undefined;\n\n\tprivate outerSelect: SelectWithExpressionsIntent | undefined;\n\tprivate outerWhere: WhereIntent | undefined;\n\tprivate outerOrderBy: OrderByIntent[] | undefined;\n\tprivate outerLimit: number | undefined;\n\tprivate outerOffset: number | undefined;\n\n\tconstructor(\n\t\tcteName: string,\n\t\trawCteIntent: RawCteIntent,\n\t\tadapter?: Adapter,\n\t\tschemaName?: string,\n\t\tmodel?: ModelIR,\n\t) {\n\t\tthis.cteName = cteName;\n\t\tthis.rawCteIntent = rawCteIntent;\n\t\tthis.adapter = adapter;\n\t\tthis.schemaName = schemaName;\n\t\tthis.model = model;\n\t}\n\n\t/**\n\t * Select specific columns from the CTE result.\n\t */\n\tcolumns(cols: readonly string[]): this {\n\t\tthis.outerSelect = {\n\t\t\ttype: 'expressions',\n\t\t\tcolumns: cols.map((column) => ({ kind: 'column', column })),\n\t\t};\n\t\treturn this;\n\t}\n\n\t/**\n\t * Filter the outer query result.\n\t */\n\twhere(condition: WhereIntent): this {\n\t\tthis.outerWhere = condition;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Order the outer query result.\n\t */\n\torderBy(column: string, direction: 'asc' | 'desc' = 'asc'): this {\n\t\tconst clause: OrderByIntent = { field: column, direction };\n\t\tthis.outerOrderBy = [...(this.outerOrderBy ?? []), clause];\n\t\treturn this;\n\t}\n\n\t/**\n\t * Limit the number of rows returned.\n\t */\n\tlimit(n: number): this {\n\t\tthis.outerLimit = n;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Skip the first N rows.\n\t */\n\toffset(n: number): this {\n\t\tthis.outerOffset = n;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Build the CteQueryIntent AST.\n\t */\n\tbuildIntent(): CteQueryIntent {\n\t\tconst outerIntent: QueryIntent = {\n\t\t\ttype: 'select',\n\t\t\tfrom: this.cteName,\n\t\t\t...(this.outerSelect !== undefined && { select: this.outerSelect }),\n\t\t\t...(this.outerWhere !== undefined && { where: this.outerWhere }),\n\t\t\t...(this.outerOrderBy !== undefined && { orderBy: this.outerOrderBy }),\n\t\t\t...(this.outerLimit !== undefined && { limit: this.outerLimit }),\n\t\t\t...(this.outerOffset !== undefined && { offset: this.outerOffset }),\n\t\t};\n\n\t\treturn {\n\t\t\tkind: 'cteQuery',\n\t\t\tctes: [this.rawCteIntent],\n\t\t\tquery: outerIntent,\n\t\t};\n\t}\n\n\tprivate requireAdapter(): Adapter {\n\t\treturn requireAdapterUtil(this.adapter, 'recursive');\n\t}\n\n\t/**\n\t * Compile to SQL and return an observability dump.\n\t */\n\tdump(): RecursiveDump {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst intent = this.buildIntent();\n\t\tconst compileOptions =\n\t\t\tthis.schemaName !== undefined || this.model !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(this.schemaName !== undefined && {\n\t\t\t\t\t\t\tschemaName: this.schemaName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...(this.model !== undefined && { model: this.model }),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst compiled: CompiledQuery = adapter.compileCteQuery(\n\t\t\tintent,\n\t\t\tcompileOptions,\n\t\t);\n\t\treturn {\n\t\t\tsql: compiled.sql,\n\t\t\tparams: compiled.parameters,\n\t\t\tintent,\n\t\t};\n\t}\n\n\t/**\n\t * Execute the recursive CTE query and return all matching rows.\n\t */\n\tasync all(): Promise<TResult[]> {\n\t\tconst adapter = this.requireAdapter();\n\t\tconst intent = this.buildIntent();\n\t\tconst compileOptions =\n\t\t\tthis.schemaName !== undefined || this.model !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(this.schemaName !== undefined && {\n\t\t\t\t\t\t\tschemaName: this.schemaName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...(this.model !== undefined && { model: this.model }),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst compiled = adapter.compileCteQuery<TResult>(intent, compileOptions);\n\t\treturn executeCompiledQuery(adapter, compiled, 'recursive().all()');\n\t}\n\n\t/**\n\t * Alias for `all()`.\n\t */\n\texecute(): Promise<TResult[]> {\n\t\treturn this.all();\n\t}\n}\n\n/**\n * Create a RawCteQueryBuilder from named builder instances.\n */\nexport function createRawCteBuilder<TResult = unknown>(\n\tcteName: string,\n\toptions: RecursiveOptions,\n\tadapter?: Adapter,\n\tschemaName?: string,\n\tmodel?: ModelIR,\n): RawCteQueryBuilder<TResult> {\n\tconst baseIntent = (\n\t\toptions.base as unknown as QueryBuilderImpl<unknown>\n\t).buildIntent();\n\tconst stepIntent = (\n\t\toptions.step as unknown as QueryBuilderImpl<unknown>\n\t).buildIntent();\n\n\tconst rawCteIntent: RawCteIntent = {\n\t\tkind: 'rawCte',\n\t\tname: cteName,\n\t\tbase: baseIntent,\n\t\tstep: stepIntent,\n\t\tunionAll: options.unionAll ?? true,\n\t\t...(options.maxDepth !== undefined && { maxDepth: options.maxDepth }),\n\t\t...(options.depthColumn !== undefined && {\n\t\t\tdepthColumn: options.depthColumn,\n\t\t}),\n\t};\n\n\treturn new RawCteQueryBuilder<TResult>(\n\t\tcteName,\n\t\trawCteIntent,\n\t\tadapter,\n\t\tschemaName,\n\t\tmodel,\n\t);\n}\n","import type {\n\tFeatureBehaviorConfig,\n\tUnsupportedFeatureBehavior,\n} from '@dbsp/types';\nimport type { Adapter } from '../adapter.js';\nimport type { ModelIR } from '../model-ir.js';\nimport type { PlanOptions } from '../planner.js';\nimport { NamingConventionMismatchError } from './errors.js';\nimport {\n\tgetHookStore,\n\ttype HookErrorHandler,\n\ttype HookManager,\n\ttype ObserverErrorHandler,\n} from './hooks.js';\nimport type { WarningCategory } from './logger.js';\nimport { negotiateFeatures } from './negotiate-features.js';\nimport { createOrmInstance } from './orm-instance.js';\nimport type {\n\tDefaultFilters,\n\tInferDB,\n\tSchema,\n\tSchemaDefinition,\n} from './schema.js';\nimport { createTablesProxy } from './table-ref-factory.js';\nimport type { OrmInstance } from './types.js';\n\n// ============================================================================\n// ARCH-006: Simplified ORM Entry Point\n// ============================================================================\n\n/**\n * ARCH-006: Simplified ORM options.\n *\n * Uses the unified Schema API with required schema and adapter.\n * The schema must be created with `schema()` + `ref()`.\n *\n * @example Full ORM with adapter\n * ```typescript\n * const orm = createOrm({ schema: mySchema, adapter });\n * const users = await orm.select('users').all();\n * ```\n *\n * @example Tests with mock adapter\n * ```typescript\n * import { createMockAdapter } from './test-utils.js';\n * const orm = createOrm({ schema: mySchema, adapter: createMockAdapter() });\n * ```\n */\nexport interface SimplifiedOrmOptions<\n\tT extends SchemaDefinition = SchemaDefinition,\n> {\n\t/**\n\t * Schema created with schema() + ref().\n\t * Either schema or model is required.\n\t */\n\treadonly schema?: Schema<T>;\n\n\t/**\n\t * ModelIR directly (alternative to schema).\n\t * Use this when you have ModelIR from introspection or external source.\n\t * Either schema or model is required.\n\t */\n\treadonly model?: ModelIR;\n\n\t/**\n\t * Adapter for database operations.\n\t *\n\t * Required — provides dialect capabilities for planner strategy selection.\n\t * For compile-only usage (no DB), use `createMockAdapter()` from test-utils\n\t * or `createPgsqlCompileOnlyAdapter()` from adapter-pgsql.\n\t */\n\treadonly adapter: Adapter<unknown>;\n\n\t/**\n\t * Enable strict mode validation (default: false).\n\t */\n\treadonly strictMode?: boolean;\n\n\t// ============================================================\n\t// Global Limits (NQL-ALIGN Block 3)\n\t// ============================================================\n\n\t/**\n\t * Maximum depth for recursive CTE queries.\n\t * Prevents infinite recursion in tree/graph traversals.\n\t * @default 10\n\t */\n\treadonly maxDepth?: number;\n\n\t/**\n\t * Maximum number of relation hops in a single query.\n\t * Limits paths like `user.posts.comments.author.profile`.\n\t * @default 5\n\t */\n\treadonly maxTableHops?: number;\n\n\t/**\n\t * Maximum nesting depth for CASE expressions.\n\t * Prevents overly complex conditional logic.\n\t * @default 10\n\t */\n\treadonly maxNestedCase?: number;\n\n\t/**\n\t * Global plan options passed to the semantic planner for every query.\n\t * Per-query overrides via `.withPlanOptions()` take precedence.\n\t *\n\t * @example\n\t * ```typescript\n\t * const orm = createOrm({\n\t * schema,\n\t * adapter,\n\t * planOptions: {\n\t * defaultIncludeStrategy: 'subquery',\n\t * enableCTEs: true,\n\t * maxIncludeDepth: 3,\n\t * },\n\t * });\n\t * ```\n\t */\n\treadonly planOptions?: PlanOptions;\n\n\t/**\n\t * Hook manager for query/mutation interception (E17b).\n\t * Created via `createHookManager()`.\n\t * Hooks are frozen on ORM creation — no hooks can be added after.\n\t */\n\treadonly hooks?: HookManager;\n\n\t/**\n\t * Error handler for hook failures (E17b).\n\t * Called when a hook throws. Returns 'continue' to skip the failed hook,\n\t * or 'abort' to propagate the error.\n\t */\n\treadonly onHookError?: HookErrorHandler;\n\n\t/**\n\t * Non-fatal diagnostic sink for observer failures and snapshot skips.\n\t * Its return value is ignored and it can never abort query or mutation work.\n\t */\n\treadonly onObserverError?: ObserverErrorHandler;\n\n\t/**\n\t * Behavior when schema uses features the adapter doesn't support.\n\t * Default: 'warning' (emit warning + skip).\n\t * Use 'error' for strict environments, 'ignore' to suppress.\n\t * Pass FeatureBehaviorConfig for per-feature overrides.\n\t */\n\treadonly unsupportedFeatures?:\n\t\t| UnsupportedFeatureBehavior\n\t\t| FeatureBehaviorConfig;\n\n\t/**\n\t * Suppress `'dx'` warnings (e.g. reserved-word column access) for this\n\t * ORM instance (#159). Union'd with the `DBSP_SUPPRESS_DX_WARNINGS` env\n\t * gate — a warning is suppressed if EITHER applies.\n\t *\n\t * Deliberately DX-only (not `WarningCategory[]`): `'runtime'` warnings\n\t * (raw-SQL usage) are emitted by the adapter's compiler, which has no\n\t * per-ORM-instance context, so a `'runtime'` entry here would silently\n\t * do nothing. `'runtime'` warnings are controlled only by the adapter's\n\t * `NODE_ENV` gate and the global logger (e.g. `silentLogger`) — not by\n\t * `DBSP_SUPPRESS_DX_WARNINGS` or this option.\n\t *\n\t * @example\n\t * ```typescript\n\t * const orm = createOrm({ schema, adapter, suppressDxWarnings: true });\n\t * ```\n\t */\n\treadonly suppressDxWarnings?: boolean;\n}\n\n/**\n * Create an ORM instance with the specified configuration.\n *\n * @typeParam DB - Database row map type.\n * Keys are table names, values are row types.\n * When provided, query() provides autocomplete and type inference.\n *\n * @param options - Configuration options including model and strictMode\n * @returns An ORM instance for building and planning queries\n *\n * @example With schema() + ref() API (recommended)\n * ```typescript\n * import { schema, ref, createOrm } from '@dbsp/core';\n *\n * const mySchema = schema({\n * users: {\n * id: 'uuid',\n * name: 'string',\n * },\n * posts: {\n * id: 'uuid',\n * title: 'string',\n * authorId: ref('users.id'),\n * },\n * });\n *\n * const orm = createOrm({ schema: mySchema, adapter });\n *\n * // Table names autocomplete, results are typed!\n * const users = await orm.select('users').all();\n *\n * // Include relations with type inference\n * const usersWithPosts = await orm.select('users').include('posts').all();\n * ```\n */\n/**\n * ARCH-006: Creates an ORM instance from a schema.\n *\n * This is the single entry point for creating ORM instances.\n * The schema must be created with `schema()` + `ref()`.\n *\n * For database introspection (when available), use the adapter's introspect method:\n * ```typescript\n * const model = await adapter.introspect({ schema: 'public' });\n * const orm = createOrm({ schema: model, adapter });\n * ```\n *\n * @param options - ORM options with required schema\n * @returns ORM instance for querying\n *\n * @example With database adapter\n * ```typescript\n * const orm = createOrm({ schema: mySchema, adapter });\n * const users = await orm.select('users').all();\n * ```\n */\nexport function createOrm<T extends SchemaDefinition>(\n\toptions: SimplifiedOrmOptions<T>,\n): OrmInstance<InferDB<T>> {\n\tconst {\n\t\tschema: schemaObj,\n\t\tmodel: modelDirect,\n\t\tadapter,\n\t\tstrictMode = false,\n\t\tplanOptions: globalPlanOptions,\n\t\thooks: hookManager,\n\t\tonHookError,\n\t\tonObserverError,\n\t\tunsupportedFeatures,\n\t\tsuppressDxWarnings,\n\t} = options;\n\n\t// Derive the internal, general-shaped suppress list from the DX-only\n\t// public option (#159 finding 2 — 'runtime' would be a silent no-op here\n\t// since raw-SQL warnings have no per-ORM-instance context).\n\tconst suppressWarnings: readonly WarningCategory[] | undefined =\n\t\tsuppressDxWarnings ? ['dx'] : undefined;\n\n\t// ARCH-006: Either schema or model is required\n\t// Schema provides full type inference; model is simpler for introspection/tests\n\tlet model: ModelIR;\n\tlet schemaDefinition: unknown;\n\tlet defaultFilters: DefaultFilters | undefined;\n\n\tif (schemaObj && 'model' in schemaObj) {\n\t\t// Full schema object provided\n\t\tmodel = schemaObj.model;\n\t\tschemaDefinition = schemaObj.definition;\n\t\tdefaultFilters = schemaObj.defaultFilters;\n\n\t\t// ARCH-006: Validate casing consistency\n\t\tif (\n\t\t\tadapter &&\n\t\t\tschemaObj.dbCasing &&\n\t\t\tadapter.dbCasing &&\n\t\t\tschemaObj.dbCasing !== adapter.dbCasing\n\t\t) {\n\t\t\tthrow new NamingConventionMismatchError({\n\t\t\t\tschemaCasing: schemaObj.dbCasing,\n\t\t\t\tadapterCasing: adapter.dbCasing,\n\t\t\t});\n\t\t}\n\t} else if (modelDirect) {\n\t\t// ModelIR provided directly (simpler API for introspection/tests)\n\t\tmodel = modelDirect;\n\t\tschemaDefinition = undefined; // NQL will work without schema validation\n\t\tdefaultFilters = undefined;\n\t} else {\n\t\tthrow new Error(\n\t\t\t'Invalid options: must provide either schema (from schema() function) ' +\n\t\t\t\t'or model (ModelIR). For database introspection, use getSchemaFromDb() ' +\n\t\t\t\t'from the adapter (e.g. adapter.introspect()).',\n\t\t);\n\t}\n\n\t// CAPS-003: Feature negotiation — cross-check ModelIR against adapter capabilities\n\tif (adapter?.dialectCapabilities) {\n\t\tconst result = negotiateFeatures(\n\t\t\tmodel,\n\t\t\tadapter.dialectCapabilities,\n\t\t\tunsupportedFeatures ?? 'warning',\n\t\t);\n\t\tfor (const w of result.warnings) {\n\t\t\tconsole.warn(`[dbsp] ${w.message}`);\n\t\t}\n\t}\n\n\t// E17b: Freeze hook manager on ORM creation — no hooks can be added after\n\tconst frozenHookStore = hookManager\n\t\t? getHookStore(hookManager.freeze())\n\t\t: undefined;\n\n\t// DX-040-SURFACE: Build tables proxy for type-safe table access\n\t// Use schema's pre-built proxy if available, otherwise build from model.\n\t// When suppressWarnings is set, always rebuild via createTablesProxy so\n\t// per-instance suppression reaches createTableRef even when a pre-built\n\t// schema.tables proxy exists (#159) — reusing schemaObj.tables verbatim\n\t// would silently ignore the option.\n\tconst tablesProxy: object =\n\t\tschemaObj && 'tables' in schemaObj && !suppressWarnings\n\t\t\t? (schemaObj.tables as object)\n\t\t\t: createTablesProxy(\n\t\t\t\t\tmodel,\n\t\t\t\t\tmodel.tables ? [...model.tables.keys()] : [],\n\t\t\t\t\tsuppressWarnings ? { suppressWarnings } : undefined,\n\t\t\t\t);\n\n\t// Create ORM instance with ModelIR\n\t// Cast to InferDB<T> since createOrmInstance uses internal types\n\treturn createOrmInstance(\n\t\tmodel,\n\t\tstrictMode,\n\t\t{}, // relationHints removed in ARCH-006\n\t\tadapter,\n\t\tundefined, // schemaName\n\t\tadapter.dialectCapabilities,\n\t\tschemaDefinition,\n\t\tglobalPlanOptions,\n\t\tdefaultFilters,\n\t\tfrozenHookStore,\n\t\tonHookError,\n\t\tundefined, // inTransaction\n\t\ttablesProxy,\n\t\tonObserverError,\n\t) as unknown as OrmInstance<InferDB<T>>;\n}\n","/**\n * @module range\n * PostgreSQL range operator helpers — expression-level (ExpressionRef) API.\n *\n * Provides three operators for PostgreSQL range types:\n * - `rangeOverlaps` — `&&` (any points in common)\n * - `rangeContains` — `@>` (range contains range or element)\n * - `rangeContainedBy` — `<@` (range is contained by another range)\n *\n * Tuple form: `rangeOverlaps('period', ['2024-01-01', '2024-01-31'])` → ExpressionRef\n * Compiles to: `\"period\" && daterange($1, $2)`\n *\n * Object form: `rangeOverlaps('period', { lower: '2024-01-01', upper: '2024-01-31' })` → WhereRangeIntent\n * Handled by the planner's range pipeline (backward-compatible path).\n *\n * @example\n * ```typescript\n * import { rangeOverlaps, rangeContains, rangeContainedBy } from '@dbsp/core';\n *\n * orm.select('bookings').where(rangeOverlaps('period', ['2024-01-01', '2024-01-31']))\n * orm.select('events').where(rangeContains('dateRange', ['2024-06-15', '2024-06-15']))\n * orm.select('events').where(rangeContainedBy('dateRange', ['2024-01-01', '2024-12-31']))\n * ```\n */\n\nimport type { RangeOperand, RangeValue } from '@dbsp/types';\nimport type { WhereRangeIntent } from '../intent-ast.js';\nimport {\n\ttype ExpressionRef,\n\tfn,\n\top,\n\ttype PredicateExpressionRef,\n\tparam,\n\tref,\n} from './expressions.js';\n\nexport type { RangeOperand, RangeValue } from '@dbsp/types';\n\n// ============================================================================\n// RangeType\n// ============================================================================\n\n/**\n * PostgreSQL range type names.\n *\n * Used as the third argument to range helpers to control the constructor\n * function emitted in SQL (e.g. `daterange($1, $2)`, `int4range($1, $2)`).\n *\n * Defaults to `'daterange'` when omitted.\n */\nexport type RangeType =\n\t| 'int4range'\n\t| 'int8range'\n\t| 'numrange'\n\t| 'tsrange'\n\t| 'tstzrange'\n\t| 'daterange';\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\n/**\n * Build the range constructor call: `rangeType(param(lower), param(upper))`\n */\nfunction makeRangeFn(\n\trange: readonly [unknown, unknown],\n\trangeType: RangeType,\n): ExpressionRef {\n\treturn fn(rangeType, param(range[0]), param(range[1]));\n}\n\n/**\n * Assert that `arr` is a 2-element tuple.\n * Throws a clear error for 0-, 1-, or 3+-element arrays so callers get\n * actionable feedback instead of silently producing bad SQL.\n */\nfunction assertTupleLength(arr: unknown[]): void {\n\tif (arr.length !== 2) {\n\t\tthrow new Error(\n\t\t\t`range tuple must have exactly 2 elements (got ${arr.length}); use [lower, upper] or pass a RangeValue object`,\n\t\t);\n\t}\n}\n\n// ============================================================================\n// rangeOverlaps — &&\n// ============================================================================\n\n/**\n * Range OVERLAPS — tuple API: `\"column\" && rangeType($1, $2)` (ExpressionRef)\n *\n * @example rangeOverlaps('period', ['2024-01-01', '2024-01-31'])\n * → \"period\" && daterange($1, $2)\n * @example rangeOverlaps('span', [1, 100], 'int4range')\n * → \"span\" && int4range($1, $2)\n */\nexport function rangeOverlaps(\n\tcolumn: string,\n\trange: readonly [unknown, unknown],\n\trangeType?: RangeType,\n): PredicateExpressionRef;\n\n/**\n * Range OVERLAPS — object API: delegates to WhereRangeIntent (planner path)\n *\n * @example rangeOverlaps('dates', { lower: '2025-01-15', upper: '2025-01-20' })\n */\nexport function rangeOverlaps(\n\tfield: string,\n\t// #444: PostgreSQL only defines && for two ranges; keep scalar RHS rejected.\n\tvalue: RangeValue,\n): WhereRangeIntent;\n\nexport function rangeOverlaps(\n\tfieldOrColumn: string,\n\tvalueOrRange: RangeOperand | readonly [unknown, unknown],\n\trangeType: RangeType = 'daterange',\n): PredicateExpressionRef | WhereRangeIntent {\n\tif (Array.isArray(valueOrRange)) {\n\t\tassertTupleLength(valueOrRange);\n\t\tconst tuple = valueOrRange as unknown as readonly [unknown, unknown];\n\t\treturn op('&&', ref(fieldOrColumn), makeRangeFn(tuple, rangeType));\n\t}\n\treturn {\n\t\tkind: 'range',\n\t\tfield: fieldOrColumn,\n\t\toperator: 'overlaps',\n\t\t// Cast: non-array branch is RangeOperand (tuple path already returned above)\n\t\tvalue: valueOrRange as RangeOperand,\n\t};\n}\n\n// ============================================================================\n// rangeContains — @>\n// ============================================================================\n\n/**\n * Range CONTAINS — tuple API: `\"column\" @> rangeType($1, $2)` (ExpressionRef)\n *\n * @example rangeContains('dateRange', ['2024-06-15', '2024-06-15'])\n * → \"dateRange\" @> daterange($1, $2)\n */\nexport function rangeContains(\n\tcolumn: string,\n\trange: readonly [unknown, unknown],\n\trangeType?: RangeType,\n): PredicateExpressionRef;\n\n/**\n * Range CONTAINS — object API: delegates to WhereRangeIntent (planner path)\n *\n * @example rangeContains('date_range', { lower: '2025-01-01', upper: '2025-01-05' })\n */\nexport function rangeContains(\n\tfield: string,\n\tvalue: RangeOperand,\n): WhereRangeIntent;\n\nexport function rangeContains(\n\tfieldOrColumn: string,\n\tvalueOrRange: RangeOperand | readonly [unknown, unknown],\n\trangeType: RangeType = 'daterange',\n): PredicateExpressionRef | WhereRangeIntent {\n\tif (Array.isArray(valueOrRange)) {\n\t\tassertTupleLength(valueOrRange);\n\t\tconst tuple = valueOrRange as unknown as readonly [unknown, unknown];\n\t\treturn op('@>', ref(fieldOrColumn), makeRangeFn(tuple, rangeType));\n\t}\n\treturn {\n\t\tkind: 'range',\n\t\tfield: fieldOrColumn,\n\t\toperator: 'contains',\n\t\tvalue: valueOrRange as RangeOperand,\n\t};\n}\n\n// ============================================================================\n// rangeContainedBy — <@\n// ============================================================================\n\n/**\n * Range CONTAINED BY — tuple API: `\"column\" <@ rangeType($1, $2)` (ExpressionRef)\n *\n * @example rangeContainedBy('dateRange', ['2024-01-01', '2024-12-31'])\n * → \"dateRange\" <@ daterange($1, $2)\n */\nexport function rangeContainedBy(\n\tcolumn: string,\n\trange: readonly [unknown, unknown],\n\trangeType?: RangeType,\n): PredicateExpressionRef;\n\n/**\n * Range CONTAINED BY — object API: delegates to WhereRangeIntent (planner path)\n *\n * @example rangeContainedBy('event_dates', { lower: '2025-01-01', upper: '2025-12-31' })\n */\nexport function rangeContainedBy(\n\tfield: string,\n\t// #444: scalar containment has the element on the left, not the RHS here.\n\tvalue: RangeValue,\n): WhereRangeIntent;\n\nexport function rangeContainedBy(\n\tfieldOrColumn: string,\n\tvalueOrRange: RangeOperand | readonly [unknown, unknown],\n\trangeType: RangeType = 'daterange',\n): PredicateExpressionRef | WhereRangeIntent {\n\tif (Array.isArray(valueOrRange)) {\n\t\tassertTupleLength(valueOrRange);\n\t\tconst tuple = valueOrRange as unknown as readonly [unknown, unknown];\n\t\treturn op('<@', ref(fieldOrColumn), makeRangeFn(tuple, rangeType));\n\t}\n\treturn {\n\t\tkind: 'range',\n\t\tfield: fieldOrColumn,\n\t\toperator: 'containedBy',\n\t\tvalue: valueOrRange as RangeOperand,\n\t};\n}\n","/**\n * Dialect Capabilities Registry\n *\n * CORE-004: Centralized module for SQL dialect capabilities.\n * Avoids duplication across adapters by providing a single source of truth.\n *\n * Type definitions live in @dbsp/types. This module re-exports them\n * and provides runtime constants and functions.\n */\n\nimport type {\n\tColumnType,\n\tDDLFeature,\n\tDDLFeatureVersionRange,\n} from '@dbsp/types';\n\n// Re-export all dialect types from @dbsp/types for backward compatibility\nexport type {\n\tCommonColumnType,\n\tDDLFeatureVersionRange,\n\tDialectCapabilities,\n\tDialectName,\n\tDuckDBColumnType,\n\tIsTypeSupported,\n\tMSSQLColumnType,\n\tMySQLColumnType,\n\tPostgresColumnType,\n\tPostgresOnlyColumnType,\n\tSQLiteColumnType,\n\tSupportedColumnTypes,\n} from '@dbsp/types';\n\nimport type { DialectCapabilities } from '@dbsp/types';\n\n/**\n * PostgreSQL dialect capabilities.\n * The most feature-rich dialect, serves as the reference implementation.\n */\nexport const POSTGRESQL_CAPABILITIES: DialectCapabilities = {\n\tname: 'postgresql',\n\n\t// Features\n\tsupportsReturning: true,\n\tsupportsRecursiveCTE: true,\n\tsupportsWindowFunctions: true,\n\tsupportsArrayType: true,\n\tsupportsRangeTypes: true, // PostgreSQL has native range types (daterange, int4range, etc.)\n\tsupportsJsonType: true,\n\tsupportsJsonOperators: true, // PG: ->, ->>, @>, <@, ?, #>, #>>\n\tsupportsRowLevelLocks: true,\n\tsupportsLockWaitPolicies: true,\n\tsupportsSchemas: true,\n\n\t// Include Strategy Capabilities (CORE-006)\n\tsupportsLateralJoin: true,\n\tsupportsJsonAgg: true,\n\n\t// DDL Feature Support (CAPS-001)\n\tsupportsDDLEnumTypes: true,\n\tsupportsDDLSequences: true,\n\tsupportsDDLExtensions: true,\n\tsupportsDDLPartitioning: true,\n\tsupportsDDLCheckConstraints: true,\n\tsupportsDDLOnUpdateFK: true,\n\tsupportsDDLDeferredFK: true,\n\tsupportsDDLIdentityColumns: true,\n\tsupportsDDLCollation: true,\n\tsupportsDDLComments: true,\n\tsupportsDDLIndexMethods: true,\n\tsupportsDDLIndexOpclass: true,\n\tsupportsDDLIndexInclude: true,\n\tsupportsDDLIndexNullsNotDistinct: true,\n\tsupportsDDLPartialIndexes: true,\n\tsupportsDDLExpressionIndexes: true,\n\tsupportsDDLRowLevelSecurity: true,\n\n\t// Syntax\n\trecursivePathStyle: 'array',\n\tstringConcatStyle: 'operator',\n\tidentifierQuote: '\"',\n\tparameterStyle: 'dollar',\n\tlimitStyle: 'limit-offset',\n\tbooleanStyle: 'native',\n};\n\n/**\n * MySQL dialect capabilities.\n */\nexport const MYSQL_CAPABILITIES: DialectCapabilities = {\n\tname: 'mysql',\n\n\t// Features\n\tsupportsReturning: false, // MySQL 8.0.21+ has limited support\n\tsupportsRecursiveCTE: true, // MySQL 8.0+\n\tsupportsWindowFunctions: true, // MySQL 8.0+\n\tsupportsArrayType: false,\n\tsupportsRangeTypes: false, // MySQL has no native range types\n\tsupportsJsonType: true,\n\tsupportsJsonOperators: false, // MySQL uses JSON_EXTRACT() functions, not operators\n\t// Coarse PostgreSQL-shaped lock flags; revisit MySQL with per-strength caps.\n\tsupportsRowLevelLocks: false,\n\tsupportsLockWaitPolicies: false,\n\tsupportsSchemas: true, // MySQL uses database as schema\n\n\t// Include Strategy Capabilities (CORE-006)\n\tsupportsLateralJoin: false, // MySQL 8.0.14+ has LATERAL but limited\n\tsupportsJsonAgg: true, // JSON_ARRAYAGG() in MySQL 8.0+\n\n\t// Syntax\n\trecursivePathStyle: 'string',\n\tstringConcatStyle: 'function',\n\tidentifierQuote: '`',\n\tparameterStyle: 'question',\n\tlimitStyle: 'limit-offset',\n\tbooleanStyle: 'numeric',\n};\n\n/**\n * SQLite dialect capabilities.\n */\nexport const SQLITE_CAPABILITIES: DialectCapabilities = {\n\tname: 'sqlite',\n\n\t// Features\n\tsupportsReturning: true, // SQLite 3.35+\n\tsupportsRecursiveCTE: true,\n\tsupportsWindowFunctions: true, // SQLite 3.25+\n\tsupportsArrayType: false,\n\tsupportsRangeTypes: false, // SQLite has no native range types\n\tsupportsJsonType: true, // SQLite 3.38+ (JSON1 extension)\n\tsupportsJsonOperators: false, // SQLite uses json_extract() functions\n\tsupportsRowLevelLocks: false,\n\tsupportsLockWaitPolicies: false,\n\tsupportsSchemas: false, // SQLite uses ATTACH for multiple databases\n\n\t// Include Strategy Capabilities (CORE-006)\n\tsupportsLateralJoin: false, // Not supported\n\tsupportsJsonAgg: false, // json_group_array exists but is limited\n\n\t// Syntax\n\trecursivePathStyle: 'string',\n\tstringConcatStyle: 'operator',\n\tidentifierQuote: '\"',\n\tparameterStyle: 'question',\n\tlimitStyle: 'limit-offset',\n\tbooleanStyle: 'numeric',\n};\n\n/**\n * DuckDB dialect capabilities.\n * Analytical database with PostgreSQL-compatible syntax.\n */\nexport const DUCKDB_CAPABILITIES: DialectCapabilities = {\n\tname: 'duckdb',\n\n\t// Features\n\tsupportsReturning: true,\n\tsupportsRecursiveCTE: true,\n\tsupportsWindowFunctions: true,\n\tsupportsArrayType: true, // DuckDB has LIST type\n\tsupportsRangeTypes: false, // DuckDB has no native range types like PostgreSQL\n\tsupportsJsonType: true,\n\tsupportsJsonOperators: false, // DuckDB uses json_extract() style\n\tsupportsRowLevelLocks: false,\n\tsupportsLockWaitPolicies: false,\n\tsupportsSchemas: true,\n\n\t// Include Strategy Capabilities (CORE-006)\n\tsupportsLateralJoin: true, // DuckDB supports LATERAL\n\tsupportsJsonAgg: true, // list_agg / json_group_array\n\n\t// Syntax\n\trecursivePathStyle: 'array', // DuckDB uses LIST which is similar\n\tstringConcatStyle: 'operator',\n\tidentifierQuote: '\"',\n\tparameterStyle: 'dollar',\n\tlimitStyle: 'limit-offset',\n\tbooleanStyle: 'native',\n};\n\n/**\n * MSSQL dialect capabilities.\n */\nexport const MSSQL_CAPABILITIES: DialectCapabilities = {\n\tname: 'mssql',\n\n\t// Features\n\tsupportsReturning: true, // OUTPUT clause\n\tsupportsRecursiveCTE: true,\n\tsupportsWindowFunctions: true,\n\tsupportsArrayType: false,\n\tsupportsRangeTypes: false, // MSSQL has no native range types\n\tsupportsJsonType: true, // SQL Server 2016+\n\tsupportsJsonOperators: false, // MSSQL uses JSON_VALUE/JSON_QUERY functions\n\t// Coarse PostgreSQL-shaped lock flags; revisit MSSQL hints with per-strength caps.\n\tsupportsRowLevelLocks: false,\n\tsupportsLockWaitPolicies: false,\n\tsupportsSchemas: true,\n\n\t// Include Strategy Capabilities (CORE-006)\n\tsupportsLateralJoin: true, // CROSS APPLY / OUTER APPLY\n\tsupportsJsonAgg: false, // FOR JSON exists but different semantics\n\n\t// Syntax\n\trecursivePathStyle: 'string',\n\tstringConcatStyle: 'function', // CONCAT() or +\n\tidentifierQuote: '[',\n\tparameterStyle: 'named', // @param\n\tlimitStyle: 'top', // TOP or OFFSET FETCH\n\tbooleanStyle: 'numeric',\n};\n\n/**\n * Compare two version strings numerically (e.g., '8.0.16' vs '8.0.15').\n * Returns: -1 if a < b, 0 if equal, 1 if a > b.\n * Supports any number of segments (3.8, 8.0.16, 15.0.1.2).\n */\nfunction compareVersions(a: string, b: string): number {\n\tconst partsA = a.split('.').map(Number);\n\tconst partsB = b.split('.').map(Number);\n\tconst len = Math.max(partsA.length, partsB.length);\n\tfor (let i = 0; i < len; i++) {\n\t\tconst segA = partsA[i] ?? 0;\n\t\tconst segB = partsB[i] ?? 0;\n\t\tif (segA < segB) return -1;\n\t\tif (segA > segB) return 1;\n\t}\n\treturn 0;\n}\n\n/** Maps DDLFeature name → DialectCapabilities flag name */\nconst FEATURE_TO_FLAG: Record<DDLFeature, string> = {\n\tenum: 'supportsDDLEnumTypes',\n\tsequence: 'supportsDDLSequences',\n\textension: 'supportsDDLExtensions',\n\tpartition: 'supportsDDLPartitioning',\n\tcheckConstraint: 'supportsDDLCheckConstraints',\n\tonUpdateFK: 'supportsDDLOnUpdateFK',\n\tdeferredFK: 'supportsDDLDeferredFK',\n\tidentity: 'supportsDDLIdentityColumns',\n\tcollation: 'supportsDDLCollation',\n\tcomment: 'supportsDDLComments',\n\tindexMethod: 'supportsDDLIndexMethods',\n\tindexOpclass: 'supportsDDLIndexOpclass',\n\tindexInclude: 'supportsDDLIndexInclude',\n\tpartialIndex: 'supportsDDLPartialIndexes',\n\texpressionIndex: 'supportsDDLExpressionIndexes',\n\tindexNullsNotDistinct: 'supportsDDLIndexNullsNotDistinct',\n\trowLevelSecurity: 'supportsDDLRowLevelSecurity',\n};\n\n/**\n * Factory helper for adapter authors to create DialectCapabilities.\n * All DDL flags default to false (unsupported) unless overridden.\n * Required fields (name, syntax variants) must be provided.\n *\n * @param overrides - Required syntax fields plus any capability overrides.\n * @param options - Optional version-aware resolution. When `version` and\n * `versionRequirements` are both provided, features outside their version\n * range are set to `undefined` (unsupported) in the returned capabilities.\n */\nexport function createDialectCapabilities(\n\toverrides: Partial<DialectCapabilities> &\n\t\tPick<\n\t\t\tDialectCapabilities,\n\t\t\t| 'name'\n\t\t\t| 'identifierQuote'\n\t\t\t| 'parameterStyle'\n\t\t\t| 'limitStyle'\n\t\t\t| 'booleanStyle'\n\t\t\t| 'recursivePathStyle'\n\t\t\t| 'stringConcatStyle'\n\t\t>,\n\toptions?: {\n\t\t/** Current database version (e.g., '8.0.16', '3.35.0') */\n\t\tversion?: string;\n\t\t/** Per-feature version requirements. Features outside the range are set to undefined. */\n\t\tversionRequirements?: Partial<Record<DDLFeature, DDLFeatureVersionRange>>;\n\t},\n): DialectCapabilities {\n\tconst result: Record<string, unknown> = {\n\t\t// Feature defaults (all false = unsupported)\n\t\tsupportsReturning: false,\n\t\tsupportsRecursiveCTE: false,\n\t\tsupportsWindowFunctions: false,\n\t\tsupportsArrayType: false,\n\t\tsupportsRangeTypes: false,\n\t\tsupportsJsonType: false,\n\t\tsupportsJsonOperators: false,\n\t\tsupportsRowLevelLocks: false,\n\t\tsupportsLockWaitPolicies: false,\n\t\tsupportsSchemas: false,\n\t\tsupportsLateralJoin: false,\n\t\tsupportsJsonAgg: false,\n\t\t// DDL flags all default to undefined (unsupported per INV-02)\n\t\t...overrides,\n\t};\n\n\tif (options?.version && options?.versionRequirements) {\n\t\tconst ver = options.version;\n\t\tconst reqs = options.versionRequirements;\n\t\tfor (const [feature, range] of Object.entries(reqs) as [\n\t\t\tDDLFeature,\n\t\t\tDDLFeatureVersionRange,\n\t\t][]) {\n\t\t\tconst flagName = FEATURE_TO_FLAG[feature];\n\t\t\tif (!flagName) continue;\n\t\t\tconst meetsMin = !range.min || compareVersions(ver, range.min) >= 0;\n\t\t\tconst meetsMax = !range.max || compareVersions(ver, range.max) <= 0;\n\t\t\tif (!meetsMin || !meetsMax) {\n\t\t\t\tdelete result[flagName];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result as unknown as DialectCapabilities;\n}\n\n/**\n * Registry of all known dialect capabilities.\n * Use `registerDialect()` to add custom dialects.\n */\nconst dialectRegistry: Map<string, DialectCapabilities> = new Map([\n\t['postgresql', POSTGRESQL_CAPABILITIES],\n\t['postgres', POSTGRESQL_CAPABILITIES], // Alias\n\t['pg', POSTGRESQL_CAPABILITIES], // Alias\n\t['mysql', MYSQL_CAPABILITIES],\n\t['sqlite', SQLITE_CAPABILITIES],\n\t['duckdb', DUCKDB_CAPABILITIES],\n\t['mssql', MSSQL_CAPABILITIES],\n\t['sqlserver', MSSQL_CAPABILITIES], // Alias\n]);\n\n/**\n * Error thrown when a dialect is not found in the registry.\n */\nexport class UnknownDialectError extends Error {\n\tconstructor(\n\t\tpublic readonly dialectName: string,\n\t\tpublic readonly availableDialects: string[],\n\t) {\n\t\tconst available = availableDialects.join(', ');\n\t\tsuper(`Unknown dialect '${dialectName}'. Available dialects: ${available}`);\n\t\tthis.name = 'UnknownDialectError';\n\t}\n}\n\n/**\n * Get capabilities for a known dialect.\n *\n * @param dialectName - The dialect identifier (e.g., 'postgresql', 'mysql')\n * @returns The dialect capabilities\n * @throws UnknownDialectError if the dialect is not registered\n *\n * @example\n * ```typescript\n * const caps = getDialectCapabilities('postgresql');\n * if (caps.supportsReturning) {\n * // Add RETURNING clause\n * }\n * ```\n */\nexport function getDialectCapabilities(\n\tdialectName: string,\n): DialectCapabilities {\n\tconst normalized = dialectName.toLowerCase();\n\tconst capabilities = dialectRegistry.get(normalized);\n\n\tif (!capabilities) {\n\t\tconst available = Array.from(dialectRegistry.keys()).filter(\n\t\t\t(key) => dialectRegistry.get(key)?.name === key, // Only show primary names, not aliases\n\t\t);\n\t\tthrow new UnknownDialectError(dialectName, available);\n\t}\n\n\treturn capabilities;\n}\n\n/**\n * Check if a dialect is registered.\n *\n * @param dialectName - The dialect identifier\n * @returns true if the dialect is known\n */\nexport function isKnownDialect(dialectName: string): boolean {\n\treturn dialectRegistry.has(dialectName.toLowerCase());\n}\n\n/**\n * Get all registered dialect names (primary names only, not aliases).\n *\n * @returns Array of dialect names\n */\nexport function getAvailableDialects(): string[] {\n\tconst seen = new Set<string>();\n\tconst result: string[] = [];\n\n\tfor (const [_key, caps] of dialectRegistry) {\n\t\tif (!seen.has(caps.name)) {\n\t\t\tseen.add(caps.name);\n\t\t\tresult.push(caps.name);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Register a custom dialect or override an existing one.\n *\n * @param dialectName - The dialect identifier\n * @param capabilities - The dialect capabilities\n *\n * @example\n * ```typescript\n * // Register a custom dialect\n * registerDialect('cockroachdb', {\n * ...POSTGRESQL_CAPABILITIES,\n * name: 'cockroachdb',\n * // Override specific capabilities\n * });\n *\n * // Add an alias\n * registerDialect('crdb', getDialectCapabilities('cockroachdb'));\n * ```\n */\nexport function registerDialect(\n\tdialectName: string,\n\tcapabilities: DialectCapabilities,\n): void {\n\tdialectRegistry.set(dialectName.toLowerCase(), capabilities);\n}\n\n/**\n * Create custom capabilities by extending a base dialect.\n *\n * @param base - The base dialect to extend\n * @param overrides - Partial capabilities to override\n * @returns New capabilities object\n *\n * @example\n * ```typescript\n * const cockroachCaps = extendDialect(POSTGRESQL_CAPABILITIES, {\n * name: 'cockroachdb',\n * supportsArrayType: false, // CockroachDB has limited array support\n * });\n * registerDialect('cockroachdb', cockroachCaps);\n * ```\n */\nexport function extendDialect(\n\tbase: DialectCapabilities,\n\toverrides: Partial<DialectCapabilities> & { name: string },\n): DialectCapabilities {\n\treturn { ...base, ...overrides };\n}\n\n// ============================================================================\n// Dialect Type Errors\n// ============================================================================\n\n/**\n * Error thrown when a column type is not supported by the target dialect.\n *\n * @example\n * ```typescript\n * // PostgreSQL range types are not supported in MySQL\n * throw new UnhandledTypeInDialect('daterange', 'mysql', 'Range types are PostgreSQL-specific');\n * ```\n */\nexport class UnhandledTypeInDialect extends Error {\n\tconstructor(\n\t\t/** The column type that is not supported */\n\t\tpublic readonly columnType: ColumnType | string,\n\t\t/** The dialect that doesn't support the type */\n\t\tpublic readonly dialectName: string,\n\t\t/** Optional hint for the user */\n\t\tpublic readonly hint?: string,\n\t) {\n\t\tconst hintSuffix = hint ? ` Hint: ${hint}` : '';\n\t\tsuper(\n\t\t\t`Type '${columnType}' is not supported by dialect '${dialectName}'.${hintSuffix}`,\n\t\t);\n\t\tthis.name = 'UnhandledTypeInDialect';\n\t}\n}\n\n/**\n * Check if a column type is supported by a dialect at runtime.\n * Returns true if supported, throws UnhandledTypeInDialect if not.\n *\n * @param type - The column type to check\n * @param dialectName - The target dialect\n * @param capabilities - The dialect capabilities\n * @throws UnhandledTypeInDialect if the type is not supported\n *\n * @example\n * ```typescript\n * assertTypeSupported('daterange', 'postgresql', pgCaps); // OK\n * assertTypeSupported('daterange', 'mysql', mysqlCaps); // throws!\n * ```\n */\nexport function assertTypeSupported(\n\ttype: ColumnType,\n\tdialectName: string,\n\tcapabilities: DialectCapabilities,\n): void {\n\t// Range types require supportsRangeTypes\n\tconst rangeTypes: ColumnType[] = [\n\t\t'daterange',\n\t\t'tsrange',\n\t\t'tstzrange',\n\t\t'int4range',\n\t\t'int8range',\n\t\t'numrange',\n\t];\n\n\tif (rangeTypes.includes(type) && !capabilities.supportsRangeTypes) {\n\t\tthrow new UnhandledTypeInDialect(\n\t\t\ttype,\n\t\t\tdialectName,\n\t\t\t'Range types are PostgreSQL-specific. Consider using separate start/end columns instead.',\n\t\t);\n\t}\n\n\t// JSONB specifically requires PostgreSQL\n\tif (type === 'jsonb' && dialectName !== 'postgresql') {\n\t\tthrow new UnhandledTypeInDialect(\n\t\t\ttype,\n\t\t\tdialectName,\n\t\t\t\"Use 'json' type instead, which is supported by most dialects.\",\n\t\t);\n\t}\n}\n","/**\n * Adapter-agnostic SQL utilities.\n *\n * Pure string helpers that work with any SQL dialect.\n * Placed in core so every package can use them without\n * pulling in a specific adapter dependency.\n */\n\n/**\n * Normalize SQL for comparison: collapse whitespace, lowercase, trim.\n * Useful for golden-file tests and assertion systems.\n */\nexport function normalizeSQL(sql: string): string {\n\treturn sql\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/g, ' ')\n\t\t.replace(/\\s*,\\s*/g, ', ')\n\t\t.replace(/\\(\\s+/g, '(')\n\t\t.replace(/\\s+\\)/g, ')')\n\t\t.replace(/;\\s*$/, '')\n\t\t.trim();\n}\n","/**\n * Individual assertion evaluators for the assertion system.\n *\n * Each function takes inputs and returns an AssertionOutcome.\n * Grouped by domain: general, SQL, params, DB, intent.\n */\n\nimport { normalizeSQL } from '../sql-utils.js';\nimport type { AssertionType, TableAssertionData } from './assertion-parser.js';\nimport type {\n\tAssertionOutcome,\n\tAssertionQueryResult,\n\tIntentSummary,\n} from './types.js';\n\n// Re-export normalizeSQL from core (canonical location)\nexport { normalizeSQL };\n\n// ============================================================\n// Helpers\n// ============================================================\n\n/**\n * Convert camelCase to snake_case\n */\nfunction toSnakeCase(str: string): string {\n\treturn str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n// ============================================================\n// GENERAL ASSERTIONS\n// ============================================================\n\n/**\n * Assert that a string contains a substring\n */\nexport function assertContains(\n\tfield: string,\n\tactual: string,\n\texpected: string,\n\toriginalType?: AssertionType,\n): AssertionOutcome {\n\tconst passed = actual.includes(expected);\n\treturn {\n\t\ttype: originalType ?? (`${field}.contains` as AssertionType),\n\t\texpected,\n\t\tactual: passed ? undefined : actual, // Full value, no truncation\n\t\tpassed,\n\t\tmessage: passed ? undefined : `Expected ${field} to contain \"${expected}\"`,\n\t};\n}\n\n/**\n * Assert exact string equality\n */\nexport function assertEquals(\n\tfield: string,\n\tactual: string,\n\texpected: string,\n): AssertionOutcome {\n\tconst passed = actual.trim() === expected.trim();\n\treturn {\n\t\ttype: `${field}.equals` as AssertionType,\n\t\texpected,\n\t\tactual: passed ? undefined : actual, // Full value, no truncation\n\t\tpassed,\n\t\tmessage: passed ? undefined : `Expected ${field} to equal \"${expected}\"`,\n\t};\n}\n\n/**\n * Assert string matches regex\n */\nexport function assertMatches(\n\tfield: string,\n\tactual: string,\n\tpattern: string,\n): AssertionOutcome {\n\tconst regex = new RegExp(pattern);\n\tconst passed = regex.test(actual);\n\treturn {\n\t\ttype: `${field}.matches` as AssertionType,\n\t\texpected: pattern,\n\t\tactual: passed ? undefined : actual, // Full value, no truncation\n\t\tpassed,\n\t\tmessage: passed ? undefined : `Expected ${field} to match /${pattern}/`,\n\t};\n}\n\n/**\n * Assert query success/failure\n */\nexport function assertSuccess(\n\tactual: boolean,\n\texpected: boolean,\n): AssertionOutcome {\n\tconst passed = actual === expected;\n\treturn {\n\t\ttype: 'success',\n\t\texpected,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Expected query to ${expected ? 'succeed' : 'fail'}, but it ${actual ? 'succeeded' : 'failed'}`,\n\t};\n}\n\n// ============================================================\n// SQL ASSERTIONS\n// ============================================================\n\n/**\n * Assert SQL equality with normalization\n */\nexport function assertSQLEquals(\n\tactual: string,\n\texpected: string,\n): AssertionOutcome {\n\tconst normalizedActual = normalizeSQL(actual);\n\tconst normalizedExpected = normalizeSQL(expected);\n\tconst passed = normalizedActual === normalizedExpected;\n\n\treturn {\n\t\ttype: 'sql.equals',\n\t\texpected,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `SQL mismatch:\\n Expected: ${expected}\\n Actual: ${actual}`,\n\t};\n}\n\n/**\n * Factory for SQL identifier assertions (table/column).\n * Matches: logical name, physical snake_case, or quoted variants.\n */\nfunction createSQLIdentifierAssertion(\n\tassertionType: AssertionType,\n\tlabel: string,\n) {\n\treturn (sql: string, name: string): AssertionOutcome => {\n\t\tconst normalizedSql = sql.toLowerCase();\n\t\tconst logicalLower = name.toLowerCase();\n\t\tconst physicalSnake = toSnakeCase(name).toLowerCase();\n\n\t\tconst found =\n\t\t\tnormalizedSql.includes(logicalLower) ||\n\t\t\tnormalizedSql.includes(physicalSnake) ||\n\t\t\tnormalizedSql.includes(`\"${logicalLower}\"`) ||\n\t\t\tnormalizedSql.includes(`\"${physicalSnake}\"`);\n\n\t\treturn {\n\t\t\ttype: assertionType,\n\t\t\texpected: name,\n\t\t\tactual: found ? undefined : sql,\n\t\t\tpassed: found,\n\t\t\tmessage: found\n\t\t\t\t? undefined\n\t\t\t\t: `Expected SQL to reference ${label} \"${name}\"${physicalSnake !== logicalLower ? ` (or \"${physicalSnake}\")` : ''}`,\n\t\t};\n\t};\n}\n\nexport const assertSQLTable = createSQLIdentifierAssertion(\n\t'sql.table',\n\t'table',\n);\nexport const assertSQLColumn = createSQLIdentifierAssertion(\n\t'sql.column',\n\t'column',\n);\n\n/**\n * Assert SQL references a table via JOIN or CTE\n * Detects: LEFT/RIGHT/INNER/FULL/CROSS JOIN, WITH clause (CTE)\n * Handles schema-qualified names: \"schema\".\"table\" and plain \"table\"\n */\nexport function assertSQLJoin(\n\tsql: string,\n\ttableName: string,\n): AssertionOutcome {\n\tconst normalizedSql = sql.toLowerCase();\n\tconst tableNameLower = tableName.toLowerCase();\n\tconst tableSnake = toSnakeCase(tableName).toLowerCase();\n\n\t// Check for any type of JOIN (left, right, inner, full, cross)\n\tconst joinPattern = /\\b(left|right|inner|full|cross)?\\s*join\\b/;\n\tconst hasJoin = joinPattern.test(normalizedSql);\n\n\t// Check for CTE (WITH clause)\n\tconst ctePattern = new RegExp(\n\t\t`\\\\bwith\\\\b[^)]*\\\\b(${tableNameLower}|${tableSnake})\\\\b`,\n\t);\n\tconst hasCte = ctePattern.test(normalizedSql);\n\n\t// Check for table name (handles schema-qualified: \"schema\".\"table\")\n\t// Match: \"table\", \"schema\".\"table\", table (unquoted)\n\tconst tablePatterns = [\n\t\t`\"${tableNameLower}\"`, // quoted logical\n\t\t`\"${tableSnake}\"`, // quoted physical\n\t\t`.${tableNameLower}`, // after schema dot\n\t\t`.${tableSnake}`, // after schema dot (snake)\n\t\t` ${tableNameLower} `, // unquoted with spaces\n\t\t` ${tableSnake} `, // unquoted snake\n\t];\n\tconst hasTable = tablePatterns.some((p) => normalizedSql.includes(p));\n\n\t// Pass if: (has JOIN AND has table) OR (has CTE with table)\n\tconst found = (hasJoin && hasTable) || hasCte;\n\n\treturn {\n\t\ttype: 'sql.join',\n\t\texpected: tableName,\n\t\tactual: found ? undefined : sql,\n\t\tpassed: found,\n\t\tmessage: found\n\t\t\t? undefined\n\t\t\t: `Expected SQL to reference \"${tableName}\" via JOIN or CTE`,\n\t};\n}\n\n// ============================================================\n// PARAMS ASSERTIONS\n// ============================================================\n\n/**\n * Assert params array equality\n */\nexport function assertParamsEquals(\n\tactual: readonly unknown[],\n\texpected: unknown[],\n): AssertionOutcome {\n\tconst actualStr = JSON.stringify(actual);\n\tconst expectedStr = JSON.stringify(expected);\n\tconst passed = actualStr === expectedStr;\n\n\treturn {\n\t\ttype: 'params.equals',\n\t\texpected,\n\t\tactual: passed ? undefined : [...actual],\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Params mismatch:\\n Expected: ${expectedStr}\\n Actual: ${actualStr}`,\n\t};\n}\n\n/**\n * Assert params array length\n */\nexport function assertParamsLength(\n\tactual: readonly unknown[],\n\texpected: number,\n): AssertionOutcome {\n\tconst passed = actual.length === expected;\n\treturn {\n\t\ttype: 'params.length',\n\t\texpected,\n\t\tactual: passed ? undefined : actual.length,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Expected ${expected} params, got ${actual.length}`,\n\t};\n}\n\n/**\n * Assert parameter types (string, number, boolean, null, object)\n */\nexport function assertParamsType(\n\tparams: readonly unknown[],\n\texpectedTypes: string[],\n): AssertionOutcome {\n\tif (params.length !== expectedTypes.length) {\n\t\treturn {\n\t\t\ttype: 'params.type',\n\t\t\texpected: expectedTypes,\n\t\t\tactual: params.map((p) => typeof p),\n\t\t\tpassed: false,\n\t\t\tmessage: `Expected ${expectedTypes.length} params, got ${params.length}`,\n\t\t};\n\t}\n\n\tconst actualTypes: string[] = [];\n\tconst mismatches: string[] = [];\n\n\tfor (let i = 0; i < params.length; i++) {\n\t\tconst param = params[i];\n\t\tconst expectedType = expectedTypes[i];\n\t\tlet actualType: string;\n\n\t\tif (param === null) {\n\t\t\tactualType = 'null';\n\t\t} else if (Array.isArray(param)) {\n\t\t\tactualType = 'array';\n\t\t} else if (typeof param === 'object') {\n\t\t\tactualType = 'object';\n\t\t} else {\n\t\t\tactualType = typeof param;\n\t\t}\n\n\t\tactualTypes.push(actualType);\n\n\t\tif (actualType !== expectedType) {\n\t\t\tmismatches.push(\n\t\t\t\t`Index ${i}: expected ${expectedType}, got ${actualType}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst passed = mismatches.length === 0;\n\n\treturn {\n\t\ttype: 'params.type',\n\t\texpected: expectedTypes,\n\t\tactual: passed ? undefined : actualTypes,\n\t\tpassed,\n\t\tmessage: passed ? undefined : `Type mismatch: ${mismatches.join('; ')}`,\n\t};\n}\n\n/**\n * Spec format for asserting parameter value by index\n */\ninterface ParamsValueSpec {\n\tindex: number;\n\tvalue: unknown;\n}\n\n/**\n * Assert specific parameter value by index\n * Value format: { index: number, value: unknown }\n */\nexport function assertParamsValue(\n\tparams: readonly unknown[],\n\tspec: unknown,\n): AssertionOutcome {\n\tconst { index, value } =\n\t\ttypeof spec === 'object' && spec !== null\n\t\t\t? (spec as ParamsValueSpec)\n\t\t\t: { index: 0, value: spec };\n\n\tif (index >= params.length) {\n\t\treturn {\n\t\t\ttype: 'params.value',\n\t\t\texpected: value,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: `No param at index ${index} (only ${params.length} params)`,\n\t\t};\n\t}\n\n\tconst actual = params[index];\n\tconst passed = JSON.stringify(actual) === JSON.stringify(value);\n\n\treturn {\n\t\ttype: 'params.value',\n\t\texpected: value,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Param at index ${index}: expected ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n\t};\n}\n\n// ============================================================\n// DB ASSERTIONS (require database connection)\n// ============================================================\n\ntype RowCountComparator = (actual: number, expected: number) => boolean;\n\nfunction createRowCountAssertion(\n\tassertionType: AssertionType,\n\tcompare: RowCountComparator,\n\tmessageTemplate: (expected: number, actual: number) => string,\n) {\n\treturn (result: AssertionQueryResult, expected: number): AssertionOutcome => {\n\t\tconst rowCount = result.rowCount ?? 0;\n\t\tconst passed = compare(rowCount, expected);\n\t\treturn {\n\t\t\ttype: assertionType,\n\t\t\texpected,\n\t\t\tactual: passed ? undefined : rowCount,\n\t\t\tpassed,\n\t\t\tmessage: passed ? undefined : messageTemplate(expected, rowCount),\n\t\t};\n\t};\n}\n\nexport const assertDbRowsEquals = createRowCountAssertion(\n\t'db.rows.equals',\n\t(a, e) => a === e,\n\t(e, a) => `Expected ${e} rows, got ${a}`,\n);\n\nexport const assertDbRowsMin = createRowCountAssertion(\n\t'db.rows.min',\n\t(a, e) => a >= e,\n\t(e, a) => `Expected at least ${e} rows, got ${a}`,\n);\n\nexport const assertDbRowsMax = createRowCountAssertion(\n\t'db.rows.max',\n\t(a, e) => a <= e,\n\t(e, a) => `Expected at most ${e} rows, got ${a}`,\n);\n\n/**\n * Assert column exists in result\n */\nexport function assertDbColumnExists(\n\tresult: AssertionQueryResult,\n\tcolumnName: string,\n): AssertionOutcome {\n\tconst columns = result.columns ?? [];\n\tconst columnLower = columnName.toLowerCase();\n\tconst columnSnake = toSnakeCase(columnName).toLowerCase();\n\n\tconst found = columns.some((col) => {\n\t\tconst colLower = col.toLowerCase();\n\t\treturn colLower === columnLower || colLower === columnSnake;\n\t});\n\n\treturn {\n\t\ttype: 'db.column.exists',\n\t\texpected: columnName,\n\t\tactual: found ? undefined : columns,\n\t\tpassed: found,\n\t\tmessage: found\n\t\t\t? undefined\n\t\t\t: `Column \"${columnName}\" not found in result. Available: ${columns.join(', ')}`,\n\t};\n}\n\n/**\n * Spec format for asserting cell value in result\n */\ninterface CellValueSpec {\n\trow: number;\n\tcolumn: string;\n\tvalue: unknown;\n}\n\n/**\n * Assert specific cell value in result\n * Value format: { row: number, column: string, value: unknown }\n */\nexport function assertDbValueEquals(\n\tresult: AssertionQueryResult,\n\tspec: unknown,\n): AssertionOutcome {\n\tconst { row, column, value } =\n\t\ttypeof spec === 'object' && spec !== null\n\t\t\t? (spec as CellValueSpec)\n\t\t\t: { row: 0, column: '', value: spec };\n\n\tconst rows = result.rows ?? [];\n\tif (row >= rows.length) {\n\t\treturn {\n\t\t\ttype: 'db.value.equals',\n\t\t\texpected: value,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: `No row at index ${row} (only ${rows.length} rows)`,\n\t\t};\n\t}\n\n\tconst rowData = rows[row] as Record<string, unknown> | undefined;\n\tif (!rowData) {\n\t\treturn {\n\t\t\ttype: 'db.value.equals',\n\t\t\texpected: value,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: `Row ${row} is empty`,\n\t\t};\n\t}\n\n\t// Try both exact column name and snake_case\n\tconst actual = rowData[column] ?? rowData[toSnakeCase(column)];\n\tconst passed = JSON.stringify(actual) === JSON.stringify(value);\n\n\treturn {\n\t\ttype: 'db.value.equals',\n\t\texpected: value,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Value at [${row}][\"${column}\"]: expected ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n\t};\n}\n\n/**\n * Assert db.output table: compare parsed markdown table against actual DB rows.\n * - Row count must match exactly\n * - Only listed columns are checked (extra actual columns ignored)\n * - Values compared as trimmed strings\n * - \"NULL\" (case-sensitive) matches null/undefined actual values\n */\nexport function assertDbOutput(\n\tresult: AssertionQueryResult,\n\ttableData: TableAssertionData,\n): AssertionOutcome {\n\tconst { columns, rows: expectedRows } = tableData;\n\tconst actualRows = (result.rows ?? []) as Record<string, unknown>[];\n\n\t// Normalize a value for string comparison (Date → ISO, etc.)\n\tconst normalize = (val: unknown): string => {\n\t\tif (val === null || val === undefined) return 'NULL';\n\t\tif (val instanceof Date) return val.toISOString();\n\t\tif (typeof val === 'object') return JSON.stringify(val);\n\t\treturn String(val);\n\t};\n\n\t// Helper: format actual rows as markdown table for error messages\n\tconst formatActualTable = (): string => {\n\t\tif (actualRows.length === 0) return '(no rows)';\n\t\tconst actualCols =\n\t\t\tcolumns.length > 0\n\t\t\t\t? columns\n\t\t\t\t: Object.keys(actualRows[0] as Record<string, unknown>);\n\t\tconst header = `| ${actualCols.join(' | ')} |`;\n\t\tconst separator = `| ${actualCols.map(() => '---').join(' | ')} |`;\n\t\tconst rows = actualRows.map((row) => {\n\t\t\tconst cells = actualCols.map((col) => normalize(row[col]));\n\t\t\treturn `| ${cells.join(' | ')} |`;\n\t\t});\n\t\treturn [header, separator, ...rows].join('\\n');\n\t};\n\n\t// Row count check\n\tif (actualRows.length !== expectedRows.length) {\n\t\treturn {\n\t\t\ttype: 'db.output',\n\t\t\texpected: `${expectedRows.length} rows`,\n\t\t\tactual: `${actualRows.length} rows`,\n\t\t\tpassed: false,\n\t\t\tmessage: `Expected ${expectedRows.length} rows, got ${actualRows.length}\\nActual data:\\n${formatActualTable()}`,\n\t\t};\n\t}\n\n\t// Check expected columns exist in actual result (if any rows)\n\tif (actualRows.length > 0) {\n\t\tconst firstRow = actualRows[0] as Record<string, unknown>;\n\t\tfor (const col of columns) {\n\t\t\tif (!(col in firstRow)) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'db.output',\n\t\t\t\t\texpected: `column \"${col}\" in results`,\n\t\t\t\t\tactual: `columns: ${Object.keys(firstRow).join(', ')}`,\n\t\t\t\t\tpassed: false,\n\t\t\t\t\tmessage: `Expected column \"${col}\" not found in results. Available: ${Object.keys(firstRow).join(', ')}\\nActual data:\\n${formatActualTable()}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t// Row-by-row, column-by-column comparison\n\tfor (let r = 0; r < expectedRows.length; r++) {\n\t\tconst expectedRow = expectedRows[r];\n\t\tconst actualRow = actualRows[r];\n\t\tif (!expectedRow || !actualRow) continue;\n\n\t\tfor (let c = 0; c < columns.length; c++) {\n\t\t\tconst col = columns[c];\n\t\t\tif (!col) continue;\n\t\t\tconst expectedVal = expectedRow[c] ?? '';\n\t\t\tconst actualVal = actualRow[col];\n\t\t\tconst normalizedActual = normalize(actualVal);\n\n\t\t\t// NULL handling: \"NULL\" (case-sensitive) matches null/undefined\n\t\t\tconst expectedIsNull = expectedVal === 'NULL';\n\t\t\tconst actualIsNull = actualVal === null || actualVal === undefined;\n\n\t\t\tif (expectedIsNull && actualIsNull) continue;\n\t\t\tif (expectedIsNull !== actualIsNull) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'db.output',\n\t\t\t\t\texpected: expectedVal,\n\t\t\t\t\tactual: normalizedActual,\n\t\t\t\t\tpassed: false,\n\t\t\t\t\tmessage: `Row ${r + 1}, column \"${col}\": expected ${expectedVal}, got ${normalizedActual}\\nActual data:\\n${formatActualTable()}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// String comparison (trimmed, with Date→ISO normalization)\n\t\t\tif (normalizedActual.trim() !== expectedVal.trim()) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'db.output',\n\t\t\t\t\texpected: expectedVal,\n\t\t\t\t\tactual: normalizedActual,\n\t\t\t\t\tpassed: false,\n\t\t\t\t\tmessage: `Row ${r + 1}, column \"${col}\": expected \"${expectedVal}\", got \"${normalizedActual}\"\\nActual data:\\n${formatActualTable()}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttype: 'db.output',\n\t\texpected: `${expectedRows.length} rows matching`,\n\t\tactual: `${expectedRows.length} rows matching`,\n\t\tpassed: true,\n\t\tmessage: undefined,\n\t};\n}\n\n// ============================================================\n// INTENT AST ASSERTIONS (semantic verification)\n// ============================================================\n\n/**\n * Assert intent type (query, insert, update, delete, upsert)\n */\nexport function assertIntentType(\n\tresult: AssertionQueryResult,\n\texpected: string,\n): AssertionOutcome {\n\tconst actual = result.intent?.type;\n\n\tif (!result.intent) {\n\t\treturn {\n\t\t\ttype: 'intent.type',\n\t\t\texpected,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: 'No intent available (command or parse error)',\n\t\t};\n\t}\n\n\tconst passed = actual === expected;\n\n\treturn {\n\t\ttype: 'intent.type',\n\t\texpected,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Expected intent type \"${expected}\", got \"${actual}\"`,\n\t};\n}\n\n/**\n * Assert main table name (logical name)\n */\nexport function assertIntentTable(\n\tresult: AssertionQueryResult,\n\texpected: string,\n): AssertionOutcome {\n\tconst actual = result.intent?.table;\n\n\tif (!result.intent) {\n\t\treturn {\n\t\t\ttype: 'intent.table',\n\t\t\texpected,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: 'No intent available (command or parse error)',\n\t\t};\n\t}\n\n\t// Compare case-insensitively for flexibility\n\tconst passed = actual?.toLowerCase() === expected.toLowerCase();\n\n\treturn {\n\t\ttype: 'intent.table',\n\t\texpected,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Expected table \"${expected}\", got \"${actual}\"`,\n\t};\n}\n\n/**\n * Assert relations joined via `with` keyword\n * Value can be a single string or array of strings\n */\nexport function assertIntentWith(\n\tresult: AssertionQueryResult,\n\texpected: string | string[],\n): AssertionOutcome {\n\tconst actual = result.intent?.with ?? [];\n\tconst expectedArray = Array.isArray(expected) ? expected : [expected];\n\n\tif (!result.intent) {\n\t\treturn {\n\t\t\ttype: 'intent.with',\n\t\t\texpected: expectedArray,\n\t\t\tactual: undefined,\n\t\t\tpassed: false,\n\t\t\tmessage: 'No intent available (command or parse error)',\n\t\t};\n\t}\n\n\t// Check if all expected relations are present (case-insensitive)\n\tconst actualLower = actual.map((r: string) => r.toLowerCase());\n\tconst missing = expectedArray.filter(\n\t\t(e) => !actualLower.includes(e.toLowerCase()),\n\t);\n\n\tconst passed = missing.length === 0;\n\n\treturn {\n\t\ttype: 'intent.with',\n\t\texpected: expectedArray,\n\t\tactual: passed ? undefined : actual,\n\t\tpassed,\n\t\tmessage: passed\n\t\t\t? undefined\n\t\t\t: `Missing relations: ${missing.join(', ')}. Found: ${actual.join(', ')}`,\n\t};\n}\n\n/**\n * Factory for intent boolean flag assertions (hasWhere, hasGroupBy, hasOrderBy).\n */\nfunction createIntentBooleanAssertion(\n\tassertionType: AssertionType,\n\tfield: keyof IntentSummary,\n) {\n\treturn (\n\t\tresult: AssertionQueryResult,\n\t\texpected: boolean,\n\t): AssertionOutcome => {\n\t\tif (!result.intent) {\n\t\t\treturn {\n\t\t\t\ttype: assertionType,\n\t\t\t\texpected,\n\t\t\t\tactual: undefined,\n\t\t\t\tpassed: false,\n\t\t\t\tmessage: 'No intent available (command or parse error)',\n\t\t\t};\n\t\t}\n\n\t\tconst actual = (result.intent[field] as boolean) ?? false;\n\t\tconst passed = actual === expected;\n\n\t\treturn {\n\t\t\ttype: assertionType,\n\t\t\texpected,\n\t\t\tactual: passed ? undefined : actual,\n\t\t\tpassed,\n\t\t\tmessage: passed\n\t\t\t\t? undefined\n\t\t\t\t: `Expected ${String(field)}=${expected}, got ${actual}`,\n\t\t};\n\t};\n}\n\nexport const assertIntentHasWhere = createIntentBooleanAssertion(\n\t'intent.hasWhere',\n\t'hasWhere',\n);\nexport const assertIntentHasGroupBy = createIntentBooleanAssertion(\n\t'intent.hasGroupBy',\n\t'hasGroupBy',\n);\nexport const assertIntentHasOrderBy = createIntentBooleanAssertion(\n\t'intent.hasOrderBy',\n\t'hasOrderBy',\n);\n","/**\n * Assertion Parser for .assert.dbsp files.\n *\n * Parses YAML-like assertion files that validate query output.\n * Each assertion block starts with \"---\" followed by query reference.\n *\n * Pure string parser — zero external dependencies.\n */\n\nimport type { JsonValue } from '@dbsp/types';\n\n// Valid assertion types\nexport const ASSERTION_TYPES = [\n\t// Existing (keep for backward compat)\n\t'output.contains',\n\t'output.equals',\n\t'output.matches',\n\t'sql.equals',\n\t'sql.matches',\n\t'params.equals',\n\t'params.length',\n\t'plan.contains',\n\t'success',\n\t'error.contains',\n\n\t// NEW: Typed SQL assertions\n\t'sql.table', // Table name (logical or physical)\n\t'sql.column', // Column name in SQL\n\t'sql.join', // JOIN clause present\n\n\t// NEW: Typed params assertions\n\t'params.type', // Type validation per param\n\t'params.value', // Specific param value by index\n\n\t// NEW: DB-only assertions (skipped in dry-run)\n\t'db.success', // Success check (skipped in dry-run)\n\t'db.output.contains', // Output contains (skipped in dry-run)\n\t'db.rows.equals', // Exact row count\n\t'db.rows.min', // At least N rows\n\t'db.rows.max', // At most N rows\n\t'db.output', // Table block assertion (multiline row comparison)\n\t'db.column.exists', // Column in result\n\t'db.value.equals', // Specific cell value\n\n\t// NEW: Intent AST assertions (semantic verification)\n\t'intent.type', // Intent type (query/insert/update/delete/upsert)\n\t'intent.table', // Main table name (logical)\n\t'intent.with', // Relations joined via `with` keyword (was 'include')\n\t'intent.hasWhere', // Has WHERE clause (true/false)\n\t'intent.hasGroupBy', // Has GROUP BY (true/false)\n\t'intent.hasOrderBy', // Has ORDER BY (true/false)\n] as const;\n\nexport type AssertionType = (typeof ASSERTION_TYPES)[number];\n\n/**\n * Check if an assertion type requires database connection\n * All db.* assertions need actual query execution\n */\nexport function requiresDatabase(type: AssertionType): boolean {\n\treturn type.startsWith('db.');\n}\n\n/**\n * Parsed table data for db.output table assertions.\n * columns: header names; rows: cell values as trimmed strings.\n */\nexport interface TableAssertionData {\n\tcolumns: string[];\n\trows: string[][];\n}\n\n/** Values representable in an assertion file, plus the parsed db.output table. */\nexport type AssertionValue = JsonValue | TableAssertionData;\n\n/**\n * A single assertion within a block\n */\nexport interface Assertion {\n\ttype: AssertionType;\n\tvalue: AssertionValue;\n\tline: number;\n}\n\n/**\n * A block of assertions for a single query\n */\nexport interface AssertionBlock {\n\t/** Query index (0-based) if using \"query: N\" */\n\tqueryIndex?: number;\n\t/** Query text pattern if using \"match: text\" */\n\tqueryMatch?: string;\n\t/** Line number where the block starts */\n\tstartLine: number;\n\t/** All assertions in this block */\n\tassertions: Assertion[];\n}\n\n/**\n * Result of parsing an assertion file\n */\nexport interface ParseResult {\n\tblocks: AssertionBlock[];\n\terrors: ParseError[];\n}\n\n/**\n * A parsing error with location information\n */\nexport interface ParseError {\n\tline: number;\n\tmessage: string;\n}\n\n/**\n * Parse an assertion file content into structured blocks\n *\n * @param content - The raw content of the .assert.dbsp file\n * @returns ParseResult with blocks and any parsing errors\n */\nexport function parseAssertionFile(content: string): ParseResult {\n\tconst lines = content.split('\\n');\n\tconst blocks: AssertionBlock[] = [];\n\tconst errors: ParseError[] = [];\n\n\tlet currentBlock: AssertionBlock | null = null;\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst lineNum = i + 1; // 1-based line numbers for user display\n\t\tconst line = lines[i];\n\t\tif (line === undefined) continue;\n\t\tconst trimmed = line.trim();\n\n\t\t// Skip empty lines and comments\n\t\tif (!trimmed || trimmed.startsWith('#')) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check for block start: --- query: N or --- match: text\n\t\tif (trimmed.startsWith('---')) {\n\t\t\t// Save previous block if exists\n\t\t\tif (currentBlock) {\n\t\t\t\tblocks.push(currentBlock);\n\t\t\t}\n\n\t\t\tconst blockHeader = trimmed.slice(3).trim();\n\t\t\tconst parsed = parseBlockHeader(blockHeader, lineNum);\n\n\t\t\tif (parsed.error || !parsed.block) {\n\t\t\t\terrors.push({\n\t\t\t\t\tline: lineNum,\n\t\t\t\t\tmessage: parsed.error ?? 'Invalid block header',\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else {\n\t\t\t\tcurrentBlock = {\n\t\t\t\t\t...parsed.block,\n\t\t\t\t\tstartLine: lineNum,\n\t\t\t\t\tassertions: [],\n\t\t\t\t};\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Parse assertion line within a block\n\t\tif (currentBlock) {\n\t\t\tconst assertion = parseAssertionLine(trimmed, lineNum);\n\t\t\tif (assertion.error) {\n\t\t\t\terrors.push({ line: lineNum, message: assertion.error });\n\t\t\t} else if (assertion.assertion) {\n\t\t\t\t// db.output table block: collect pipe-delimited rows from subsequent lines\n\t\t\t\tif (\n\t\t\t\t\tassertion.assertion.type === 'db.output' &&\n\t\t\t\t\tassertion.assertion.value === ''\n\t\t\t\t) {\n\t\t\t\t\tconst tableResult = parseTableBlock(lines, i + 1);\n\t\t\t\t\tif (tableResult.error) {\n\t\t\t\t\t\terrors.push({ line: lineNum, message: tableResult.error });\n\t\t\t\t\t} else if (tableResult.data) {\n\t\t\t\t\t\tassertion.assertion.value = tableResult.data;\n\t\t\t\t\t\tcurrentBlock.assertions.push(assertion.assertion);\n\t\t\t\t\t}\n\t\t\t\t\ti += tableResult.linesConsumed; // skip past consumed table lines\n\t\t\t\t} else {\n\t\t\t\t\tcurrentBlock.assertions.push(assertion.assertion);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Assertion outside of any block\n\t\t\terrors.push({\n\t\t\t\tline: lineNum,\n\t\t\t\tmessage:\n\t\t\t\t\t'Assertion found outside of any block. Start a block with \"--- query: N\" or \"--- match: text\"',\n\t\t\t});\n\t\t}\n\t}\n\n\t// Don't forget the last block\n\tif (currentBlock) {\n\t\tblocks.push(currentBlock);\n\t}\n\n\treturn { blocks, errors };\n}\n\n/**\n * Parse a block header (after the \"---\")\n */\nfunction parseBlockHeader(\n\theader: string,\n\t_line: number,\n): { block?: Partial<AssertionBlock>; error?: string } {\n\t// Handle \"query: N\"\n\tconst queryMatch = header.match(/^query:\\s*(\\d+)$/);\n\tconst queryIndexStr = queryMatch?.[1];\n\tif (queryIndexStr !== undefined) {\n\t\tconst index = parseInt(queryIndexStr, 10);\n\t\treturn { block: { queryIndex: index } };\n\t}\n\n\t// Handle \"match: text\"\n\tconst matchMatch = header.match(/^match:\\s*(.+)$/);\n\tconst matchText = matchMatch?.[1];\n\tif (matchText !== undefined) {\n\t\tconst text = matchText.trim();\n\t\tif (!text) {\n\t\t\treturn { error: 'Empty match pattern' };\n\t\t}\n\t\treturn { block: { queryMatch: text } };\n\t}\n\n\t// Invalid header format\n\treturn {\n\t\terror: `Invalid block header: \"${header}\". Expected \"query: N\" or \"match: text\"`,\n\t};\n}\n\n/**\n * Parse a single assertion line\n */\nfunction parseAssertionLine(\n\tline: string,\n\tlineNum: number,\n): { assertion?: Assertion; error?: string } {\n\t// Find the colon separator\n\tconst colonIndex = line.indexOf(':');\n\tif (colonIndex === -1) {\n\t\treturn {\n\t\t\terror: `Invalid assertion syntax: \"${line}\". Expected \"type: value\"`,\n\t\t};\n\t}\n\n\tconst typeStr = line.slice(0, colonIndex).trim();\n\tconst valueStr = line.slice(colonIndex + 1).trim();\n\n\t// Validate assertion type\n\tif (!isValidAssertionType(typeStr)) {\n\t\treturn {\n\t\t\terror: `Unknown assertion type: \"${typeStr}\". Valid types: ${ASSERTION_TYPES.join(', ')}`,\n\t\t};\n\t}\n\n\tconst type = typeStr as AssertionType;\n\n\t// Parse value based on type\n\tconst parsedValue = parseAssertionValue(type, valueStr);\n\tif (parsedValue.error || parsedValue.value === undefined) {\n\t\treturn { error: parsedValue.error ?? 'Failed to parse assertion value' };\n\t}\n\n\treturn {\n\t\tassertion: {\n\t\t\ttype,\n\t\t\tvalue: parsedValue.value,\n\t\t\tline: lineNum,\n\t\t},\n\t};\n}\n\n/**\n * Check if a string is a valid assertion type\n */\nfunction isValidAssertionType(type: string): type is AssertionType {\n\treturn ASSERTION_TYPES.includes(type as AssertionType);\n}\n\n/**\n * Parse the value part of an assertion based on its type\n */\nfunction parseAssertionValue(\n\ttype: AssertionType,\n\tvalueStr: string,\n): { value?: AssertionValue; error?: string } {\n\tswitch (type) {\n\t\t// Boolean value\n\t\tcase 'success':\n\t\tcase 'db.success':\n\t\tcase 'intent.hasWhere':\n\t\tcase 'intent.hasGroupBy':\n\t\tcase 'intent.hasOrderBy':\n\t\t\tif (valueStr === 'true') return { value: true };\n\t\t\tif (valueStr === 'false') return { value: false };\n\t\t\treturn {\n\t\t\t\terror: `Invalid boolean value for \"${type}\": \"${valueStr}\". Expected \"true\" or \"false\"`,\n\t\t\t};\n\n\t\t// Numeric value\n\t\tcase 'params.length':\n\t\tcase 'db.rows.equals':\n\t\tcase 'db.rows.min':\n\t\tcase 'db.rows.max': {\n\t\t\tconst num = parseInt(valueStr, 10);\n\t\t\tif (Number.isNaN(num) || num < 0) {\n\t\t\t\treturn {\n\t\t\t\t\terror: `Invalid number for \"${type}\": \"${valueStr}\". Expected non-negative integer`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { value: num };\n\t\t}\n\n\t\t// JSON array value\n\t\tcase 'params.equals':\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(valueStr);\n\t\t\t\tif (!Array.isArray(parsed)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: `Invalid params.equals value: expected JSON array, got ${typeof parsed}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: parsed };\n\t\t\t} catch (_e) {\n\t\t\t\treturn { error: `Invalid JSON for \"params.equals\": ${valueStr}` };\n\t\t\t}\n\n\t\t// JSON array value for params.type\n\t\tcase 'params.type':\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(valueStr);\n\t\t\t\tif (!Array.isArray(parsed)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: `Invalid params.type value: expected JSON array, got ${typeof parsed}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: parsed };\n\t\t\t} catch (_e) {\n\t\t\t\treturn { error: `Invalid JSON for \"params.type\": ${valueStr}` };\n\t\t\t}\n\n\t\t// JSON value for params.value (format: \"index:value\")\n\t\tcase 'params.value':\n\t\t\t// Format: index:value or just value (for simple cases)\n\t\t\treturn { value: valueStr };\n\n\t\t// JSON/any value for db.value.equals\n\t\tcase 'db.value.equals':\n\t\t\t// Try to parse as JSON, otherwise treat as string\n\t\t\ttry {\n\t\t\t\treturn { value: JSON.parse(valueStr) };\n\t\t\t} catch {\n\t\t\t\treturn { value: valueStr };\n\t\t\t}\n\n\t\t// Table block assertion: db.output has no inline value (table follows on next lines)\n\t\tcase 'db.output':\n\t\t\treturn { value: '' }; // Marker — table data parsed separately by parseAssertionFile\n\n\t\t// String values (all others)\n\t\tcase 'output.contains':\n\t\tcase 'output.equals':\n\t\tcase 'output.matches':\n\t\tcase 'sql.equals':\n\t\tcase 'sql.matches':\n\t\tcase 'sql.table':\n\t\tcase 'sql.column':\n\t\tcase 'sql.join':\n\t\tcase 'plan.contains':\n\t\tcase 'error.contains':\n\t\tcase 'db.column.exists':\n\t\tcase 'db.output.contains':\n\t\tcase 'intent.type':\n\t\tcase 'intent.table':\n\t\tcase 'intent.with':\n\t\t\t// For regex types, validate the pattern\n\t\t\tif (type.endsWith('.matches')) {\n\t\t\t\ttry {\n\t\t\t\t\tnew RegExp(valueStr);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\treturn { error: `Invalid regex pattern: \"${valueStr}\"` };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { value: valueStr };\n\n\t\tdefault:\n\t\t\treturn { error: `Unhandled assertion type: ${type}` };\n\t}\n}\n\n// ============================================================================\n// Table block parsing helpers (for db.output)\n// ============================================================================\n\n/**\n * Check if a pipe-delimited line is a separator row (e.g. |---|---|)\n */\nfunction isSeparatorRow(line: string): boolean {\n\treturn /^\\|[\\s\\-:|]+\\|$/.test(line.trim());\n}\n\n/**\n * Parse a pipe-delimited row into an array of trimmed cell values.\n * Handles escaped pipes (\\|) within cell values.\n */\nfunction parseTableCells(line: string): string[] {\n\tlet inner = line.trim();\n\t// Strip leading/trailing pipes\n\tif (inner.startsWith('|')) inner = inner.slice(1);\n\tif (inner.endsWith('|')) inner = inner.slice(0, -1);\n\n\tconst cells: string[] = [];\n\tlet current = '';\n\tfor (let i = 0; i < inner.length; i++) {\n\t\tif (inner[i] === '\\\\' && i + 1 < inner.length && inner[i + 1] === '|') {\n\t\t\tcurrent += '|';\n\t\t\ti++; // skip escaped pipe\n\t\t} else if (inner[i] === '|') {\n\t\t\tcells.push(current.trim());\n\t\t\tcurrent = '';\n\t\t} else {\n\t\t\tcurrent += inner[i];\n\t\t}\n\t}\n\tcells.push(current.trim());\n\treturn cells;\n}\n\n/**\n * Parse a table block starting at `startIndex` in the lines array.\n * Collects pipe-delimited rows, skips blanks and separator rows.\n * Returns parsed TableAssertionData and number of lines consumed.\n */\nfunction parseTableBlock(\n\tlines: string[],\n\tstartIndex: number,\n): { data?: TableAssertionData; linesConsumed: number; error?: string } {\n\tconst tableLines: string[] = [];\n\tlet consumed = 0;\n\n\tfor (let j = startIndex; j < lines.length; j++) {\n\t\tconst raw = lines[j];\n\t\tif (raw === undefined) break;\n\t\tconst trimmed = raw.trim();\n\n\t\t// Blank lines within table are ignored (not terminators)\n\t\tif (!trimmed) {\n\t\t\tconsumed++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Pipe-delimited line → part of the table\n\t\tif (trimmed.startsWith('|')) {\n\t\t\ttableLines.push(trimmed);\n\t\t\tconsumed++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Any other line (including --- block headers) → end of table\n\t\tbreak;\n\t}\n\n\tif (tableLines.length === 0) {\n\t\treturn {\n\t\t\tlinesConsumed: consumed,\n\t\t\terror: 'db.output: expected table rows starting with |',\n\t\t};\n\t}\n\n\t// Filter out separator rows\n\tconst dataLines = tableLines.filter((l) => !isSeparatorRow(l));\n\tif (dataLines.length === 0) {\n\t\treturn {\n\t\t\tlinesConsumed: consumed,\n\t\t\terror: 'db.output: table has only separator rows, no header or data',\n\t\t};\n\t}\n\n\tconst headerLine = dataLines[0] as string;\n\tconst columns = parseTableCells(headerLine);\n\tconst rows = dataLines.slice(1).map((l) => parseTableCells(l));\n\n\treturn { data: { columns, rows }, linesConsumed: consumed };\n}\n\n/**\n * Validate that all query references in assertion blocks are valid\n *\n * @param blocks - Parsed assertion blocks\n * @param queryCount - Number of queries in the query file\n * @param queries - The actual query strings (for match validation)\n * @returns Array of validation errors\n */\nexport function validateAssertionBlocks(\n\tblocks: AssertionBlock[],\n\tqueryCount: number,\n\tqueries: string[],\n): ParseError[] {\n\tconst errors: ParseError[] = [];\n\n\tfor (const block of blocks) {\n\t\t// Validate query index\n\t\tif (block.queryIndex !== undefined) {\n\t\t\tif (block.queryIndex < 0 || block.queryIndex >= queryCount) {\n\t\t\t\terrors.push({\n\t\t\t\t\tline: block.startLine,\n\t\t\t\t\tmessage: `Query index ${block.queryIndex} out of bounds (0-${queryCount - 1})`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Validate query match and check for ambiguity\n\t\tif (block.queryMatch !== undefined) {\n\t\t\tconst matchingIndices = queries\n\t\t\t\t.map((q, i) => (q.trim() === block.queryMatch?.trim() ? i : -1))\n\t\t\t\t.filter((i) => i !== -1);\n\n\t\t\tif (matchingIndices.length === 0) {\n\t\t\t\terrors.push({\n\t\t\t\t\tline: block.startLine,\n\t\t\t\t\tmessage: `No query matches \"${block.queryMatch}\"`,\n\t\t\t\t});\n\t\t\t} else if (matchingIndices.length > 1) {\n\t\t\t\t// ERR-06: Ambiguous match\n\t\t\t\terrors.push({\n\t\t\t\t\tline: block.startLine,\n\t\t\t\t\tmessage: `Ambiguous match: '${block.queryMatch}' matches queries ${matchingIndices.join(', ')}. Use query index instead.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Warn if block has no assertions\n\t\tif (block.assertions.length === 0) {\n\t\t\terrors.push({\n\t\t\t\tline: block.startLine,\n\t\t\t\tmessage: 'Block has no assertions',\n\t\t\t});\n\t\t}\n\t}\n\n\treturn errors;\n}\n\n/**\n * Resolve which query index a block refers to\n *\n * @param block - The assertion block\n * @param queries - The query strings\n * @returns The resolved query index, or -1 if not found\n */\nexport function resolveQueryIndex(\n\tblock: AssertionBlock,\n\tqueries: string[],\n): number {\n\tif (block.queryIndex !== undefined) {\n\t\treturn block.queryIndex;\n\t}\n\n\tif (block.queryMatch !== undefined) {\n\t\tconst index = queries.findIndex(\n\t\t\t(q) => q.trim() === block.queryMatch?.trim(),\n\t\t);\n\t\treturn index;\n\t}\n\n\treturn -1;\n}\n","/**\n * Assertion Runner for .assert.dbsp files.\n *\n * Runs assertions against query results and collects pass/fail outcomes.\n * Shared by CLI and GUI sidecar.\n */\n\nimport {\n\tassertContains,\n\tassertDbColumnExists,\n\tassertDbOutput,\n\tassertDbRowsEquals,\n\tassertDbRowsMax,\n\tassertDbRowsMin,\n\tassertDbValueEquals,\n\tassertEquals,\n\tassertIntentHasGroupBy,\n\tassertIntentHasOrderBy,\n\tassertIntentHasWhere,\n\tassertIntentTable,\n\tassertIntentType,\n\tassertIntentWith,\n\tassertMatches,\n\tassertParamsEquals,\n\tassertParamsLength,\n\tassertParamsType,\n\tassertParamsValue,\n\tassertSQLColumn,\n\tassertSQLEquals,\n\tassertSQLJoin,\n\tassertSQLTable,\n\tassertSuccess,\n} from './assertion-functions.js';\nimport type {\n\tAssertion,\n\tAssertionBlock,\n\tTableAssertionData,\n} from './assertion-parser.js';\nimport { resolveQueryIndex } from './assertion-parser.js';\nimport type {\n\tAssertionOutcome,\n\tAssertionQueryResult,\n\tAssertionSummary,\n\tQueryAssertionResult,\n} from './types.js';\n\n/**\n * Run all assertion blocks against query results\n *\n * @param blocks - Parsed assertion blocks\n * @param results - Query execution results\n * @param queries - Original query strings (for matching)\n * @param hasDb - Whether a database connection is available (for db.* assertions)\n * @returns Summary with detailed results\n */\nexport function runAssertions(\n\tblocks: AssertionBlock[],\n\tresults: AssertionQueryResult[],\n\tqueries: string[],\n\thasDb = false,\n): AssertionSummary {\n\tconst queryResults: QueryAssertionResult[] = [];\n\tlet totalPassed = 0;\n\tlet totalFailed = 0;\n\tlet totalSkipped = 0;\n\n\tfor (const block of blocks) {\n\t\tconst queryIndex = resolveQueryIndex(block, queries);\n\n\t\t// Skip if query index couldn't be resolved (validation should catch this earlier)\n\t\tif (queryIndex === -1 || queryIndex >= results.length) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst result = results[queryIndex];\n\t\tif (!result) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst outcomes: AssertionOutcome[] = [];\n\t\tlet allPassed = true;\n\n\t\tfor (const assertion of block.assertions) {\n\t\t\tconst outcome = runSingleAssertion(assertion, result, hasDb);\n\t\t\toutcomes.push(outcome);\n\n\t\t\tif (outcome.skipped) {\n\t\t\t\ttotalSkipped++;\n\t\t\t} else if (outcome.passed) {\n\t\t\t\ttotalPassed++;\n\t\t\t} else {\n\t\t\t\ttotalFailed++;\n\t\t\t\tallPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tqueryResults.push({\n\t\t\tqueryIndex,\n\t\t\tquery: result.query,\n\t\t\tquerySuccess: result.success,\n\t\t\tassertions: outcomes,\n\t\t\tpassed: allPassed,\n\t\t});\n\t}\n\n\treturn {\n\t\ttotal: totalPassed + totalFailed + totalSkipped,\n\t\tpassed: totalPassed,\n\t\tfailed: totalFailed,\n\t\tskipped: totalSkipped,\n\t\tresults: queryResults,\n\t};\n}\n\n/**\n * Run a single assertion against a query result\n */\nfunction runSingleAssertion(\n\tassertion: Assertion,\n\tresult: AssertionQueryResult,\n\thasDb: boolean,\n): AssertionOutcome {\n\tconst { type, value } = assertion;\n\n\t// Skip db.* assertions when no database connection\n\tif (type.startsWith('db.') && !hasDb) {\n\t\treturn {\n\t\t\ttype,\n\t\t\texpected: value,\n\t\t\tactual: undefined,\n\t\t\tpassed: true, // Consider skipped as not-failed\n\t\t\tmessage: undefined,\n\t\t\tskipped: true,\n\t\t\tskipReason: 'No database connection (dry-run mode)',\n\t\t};\n\t}\n\n\tswitch (type) {\n\t\t// Output assertions\n\t\tcase 'output.contains':\n\t\t\treturn assertContains('output', result.output ?? '', value as string);\n\n\t\tcase 'output.equals':\n\t\t\treturn assertEquals('output', result.output ?? '', value as string);\n\n\t\tcase 'output.matches':\n\t\t\treturn assertMatches('output', result.output ?? '', value as string);\n\n\t\t// SQL assertions\n\t\tcase 'sql.equals':\n\t\t\treturn assertSQLEquals(result.sql ?? '', value as string);\n\n\t\tcase 'sql.matches':\n\t\t\treturn assertMatches('sql', result.sql ?? '', value as string);\n\n\t\tcase 'sql.table':\n\t\t\treturn assertSQLTable(result.sql ?? '', value as string);\n\n\t\tcase 'sql.column':\n\t\t\treturn assertSQLColumn(result.sql ?? '', value as string);\n\n\t\tcase 'sql.join':\n\t\t\treturn assertSQLJoin(result.sql ?? '', value as string);\n\n\t\t// Params assertions\n\t\tcase 'params.equals':\n\t\t\treturn assertParamsEquals(result.params ?? [], value as unknown[]);\n\n\t\tcase 'params.length':\n\t\t\treturn assertParamsLength(result.params ?? [], value as number);\n\n\t\tcase 'params.type':\n\t\t\treturn assertParamsType(result.params ?? [], value as string[]);\n\n\t\tcase 'params.value':\n\t\t\treturn assertParamsValue(result.params ?? [], value as unknown);\n\n\t\t// Plan assertion (plan info is in output)\n\t\tcase 'plan.contains':\n\t\t\treturn assertContains('plan', result.output ?? '', value as string);\n\n\t\t// Success assertion\n\t\tcase 'success':\n\t\t\treturn assertSuccess(result.success, value as boolean);\n\n\t\t// Error assertion\n\t\tcase 'error.contains':\n\t\t\treturn assertContains('error', result.error ?? '', value as string);\n\n\t\t// DB assertions (require database connection)\n\t\tcase 'db.success':\n\t\t\t// Use dbSuccess if available, fall back to success for backwards compatibility\n\t\t\treturn assertSuccess(\n\t\t\t\tresult.dbSuccess ?? result.success,\n\t\t\t\tvalue as boolean,\n\t\t\t);\n\n\t\tcase 'db.output':\n\t\t\treturn assertDbOutput(result, value as TableAssertionData);\n\n\t\tcase 'db.output.contains':\n\t\t\treturn assertContains(\n\t\t\t\t'output',\n\t\t\t\tresult.output ?? '',\n\t\t\t\tvalue as string,\n\t\t\t\t'db.output.contains',\n\t\t\t);\n\n\t\tcase 'db.rows.equals':\n\t\t\treturn assertDbRowsEquals(result, value as number);\n\n\t\tcase 'db.rows.min':\n\t\t\treturn assertDbRowsMin(result, value as number);\n\n\t\tcase 'db.rows.max':\n\t\t\treturn assertDbRowsMax(result, value as number);\n\n\t\tcase 'db.column.exists':\n\t\t\treturn assertDbColumnExists(result, value as string);\n\n\t\tcase 'db.value.equals':\n\t\t\treturn assertDbValueEquals(result, value as unknown);\n\n\t\t// Intent AST assertions\n\t\tcase 'intent.type':\n\t\t\treturn assertIntentType(result, value as string);\n\n\t\tcase 'intent.table':\n\t\t\treturn assertIntentTable(result, value as string);\n\n\t\tcase 'intent.with':\n\t\t\treturn assertIntentWith(result, value as string | string[]);\n\n\t\tcase 'intent.hasWhere':\n\t\t\treturn assertIntentHasWhere(result, value as boolean);\n\n\t\tcase 'intent.hasGroupBy':\n\t\t\treturn assertIntentHasGroupBy(result, value as boolean);\n\n\t\tcase 'intent.hasOrderBy':\n\t\t\treturn assertIntentHasOrderBy(result, value as boolean);\n\n\t\tdefault:\n\t\t\treturn {\n\t\t\t\ttype,\n\t\t\t\texpected: value,\n\t\t\t\tactual: undefined,\n\t\t\t\tpassed: false,\n\t\t\t\tmessage: `Unknown assertion type: ${type}`,\n\t\t\t};\n\t}\n}\n","/**\n * Shared assertion types for .assert.dbsp evaluation.\n *\n * Used by both CLI (assertion-runner) and GUI sidecar (assertion-handler).\n */\n\nimport type { AssertionType } from './assertion-parser.js';\n\n// ── Intent summary (inline — no dependency on CLI's nql-executor) ──\n\n/**\n * Lightweight summary of a compiled query intent.\n * Populated by the NQL executor after compilation.\n */\nexport interface IntentSummary {\n\ttype: 'query' | 'insert' | 'update' | 'delete' | 'upsert' | 'setOperation';\n\ttable: string;\n\twith: string[];\n\thasWhere: boolean;\n\thasGroupBy: boolean;\n\thasOrderBy: boolean;\n\tctes: string[];\n}\n\n// ── Query result (sidecar-friendly version of CLI's BatchResult) ──\n\n/**\n * Portable query result for assertion evaluation.\n * Both CLI (via BatchResult adapter) and sidecar produce this shape.\n */\nexport interface AssertionQueryResult {\n\tquery: string;\n\tsuccess: boolean;\n\tdbSuccess?: boolean;\n\toutput?: string;\n\tsql?: string;\n\tparams?: readonly unknown[];\n\terror?: string;\n\trowCount?: number;\n\tcolumns?: string[];\n\trows?: unknown[];\n\tintent?: IntentSummary;\n}\n\n// ── Assertion outcome ──\n\n/**\n * Result of running a single assertion.\n */\nexport interface AssertionOutcome {\n\ttype: AssertionType;\n\texpected: unknown;\n\tactual: unknown;\n\tpassed: boolean;\n\tmessage: string | undefined;\n\t/** True if assertion was skipped (e.g., db.* without DB connection) */\n\tskipped?: boolean;\n\t/** Reason for skipping */\n\tskipReason?: string;\n}\n\n// ── Aggregated results ──\n\n/**\n * Result of running all assertions for a single query.\n */\nexport interface QueryAssertionResult {\n\tqueryIndex: number;\n\tquery: string;\n\tquerySuccess: boolean;\n\tassertions: AssertionOutcome[];\n\tpassed: boolean;\n}\n\n/**\n * Summary of all assertion results.\n */\nexport interface AssertionSummary {\n\ttotal: number;\n\tpassed: number;\n\tfailed: number;\n\tskipped: number;\n\tresults: QueryAssertionResult[];\n}\n\n/**\n * Determine whether a query result represents end-to-end success\n * (compile + DB execution combined).\n *\n * Truth table:\n * | success | dbSuccess | result |\n * |---------|------------|--------|\n * | false | (any) | false |\n * | true | undefined | true | (compile-only mode — no DB)\n * | true | true | true |\n * | true | false | false |\n *\n * Contract: conforming producers either omit `dbSuccess` (compile-only\n * mode — no DB execution) or set it to a real boolean reflecting DB\n * outcome.\n *\n * Stable predicate — the truth table above IS the contract; callers may\n * rely on its exact behavior. As a `@public` helper, the implementation\n * is also defensive: malformed input (`null`, `undefined`, missing\n * `success`, non-boolean `success`) returns `false` rather than throwing\n * or returning a non-boolean.\n *\n * @public\n */\nexport function isOverallSuccess(r: {\n\tsuccess: boolean;\n\tdbSuccess?: boolean;\n}): boolean {\n\treturn Boolean(r) && r.success === true && r.dbSuccess !== false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDO,SAAS,2BACf,OACA,kBACA,cACA,YACA,WACuB;AAGvB,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EACpB;AACD;AAMO,SAAS,gBAAgB,UAAoC;AAEnE,MAAI,SAAS,WAAW;AACvB,WAAO,SAAS,UAAU,cAAc,OACrC,iBACA;AAAA,EACJ;AAGA,UAAQ,SAAS,MAAM;AAAA,IACtB,KAAK;AAAA,IACL,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,IACR,KAAK;AACJ,aAAO;AAAA,EACT;AACD;AAKO,SAAS,oBACf,UAC4D;AAC5D,SAAO,SAAS,cAAc;AAC/B;AAMO,SAAS,kBAAkB,UAA+B;AAChE,SAAO,SAAS,WAAW,SAAS;AACrC;AAMO,SAAS,wBACf,WACA,iBACA,WAAW,IACS;AACpB,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACV;AACD;;;AClIA;AAWA;AAAA,4BAAc;;;ACKd,SAAS,kBAAkB,YAAgD;AAC1E,SAAO,cAAc,QAAQ,WAAW,KAAK,EAAE,SAAS;AACzD;AAEA,SAAS,kBACR,UACqB;AACrB,QAAM,KAAK,UAAU;AACrB,SAAO,OAAO,OAAO,WAAW,GAAG,KAAK,IAAI;AAC7C;AAEA,SAAS,SA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KAAK;AACJ,aAAO,mBAAmB,QAAQ,KAAe;AAAA,IAElD,KAAK;AACJ,aAAO,gBAAgB,QAAQ,KAAe;AAAA,IAE/C,KAAK;AACJ,aAAO,gBAAgB,QAAQ,KAAe;AAAA,IAE/C,KAAK;AACJ,aAAO,qBAAqB,QAAQ,KAAe;AAAA,IAEpD,KAAK;AACJ,aAAO,oBAAoB,QAAQ,KAAgB;AAAA;AAAA,IAGpD,KAAK;AACJ,aAAO,iBAAiB,QAAQ,KAAe;AAAA,IAEhD,KAAK;AACJ,aAAO,kBAAkB,QAAQ,KAAe;AAAA,IAEjD,KAAK;AACJ,aAAO,iBAAiB,QAAQ,KAA0B;AAAA,IAE3D,KAAK;AACJ,aAAO,qBAAqB,QAAQ,KAAgB;AAAA,IAErD,KAAK;AACJ,aAAO,uBAAuB,QAAQ,KAAgB;AAAA,IAEvD,KAAK;AACJ,aAAO,uBAAuB,QAAQ,KAAgB;AAAA,IAEvD;AACC,aAAO;AAAA,QACN;AAAA,QACA,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,SAAS,2BAA2B,IAAI;AAAA,MACzC;AAAA,EACF;AACD;;;AC9IO,SAAS,iBAAiB,GAGrB;AACX,SAAO,QAAQ,CAAC,KAAK,EAAE,YAAY,QAAQ,EAAE,cAAc;AAC5D;","names":["col","hasExternalSchema","ref","col","col","randomUUID","plan","createHash","canonicalJson","parsed","lifecycle","ref","plan","evidenceId","assumptionId","claimId","stepId","operationEffects","assumption","plan","createHash","ref","sameArtifact","sameTrustRoot","sameResource","deepFreeze","plan","lifecycle","stepId","assumptionId","evidenceContext","after","before","plan","plan","assessment","lifecycle","completedAssessment","evidenceIds","recordedAt","fingerprintMatches","errorDetail","assumptionId","randomUUID","stepId","journal","hasAppliedWork","result","completion","sql","check","byName","hasDuplicateNames","hasUnsupportedShape","index","ref","candidate","unsupported","schema","sameResource","resourceCovers","raw","isJsonObject","sameArtifact","sameArtifact","sameResource","resourceIsWithin","ref","DECLARABLE_KINDS","schema","sql","address","sameArtifact","assumptionId","isJsonObject","uniqueRequests","requestToObligation","ref","evidenceIds","serverVersionNum","minServerVersionNum","normalizeMinServerVersionRequest","minServerVersionRequestKey","strongestMinServerVersionRequests","canonicalMinServerVersionRequest","isCanonicalMinServerVersionEvidence","canonicalEvidence","canonicalizeObligation","claims","refuted","assumptions","stepId","plan","recognition","proofContext","supportMismatch","equivalence","retried","candidate","unsupported","uniqueResources","candidateResources","equivalenceContextFromObservation","blockedAssessment","unsupportedAssessment","assessment","proofAtBoundary","proof","ref","raw","col","fn","ref","distinct","isDistinctField","col","col","ref","fn","col","distinct","snakeCase","payload","result","intent","resolveJsonAggOrderKey","isRecord","raw","record","relationKey","resolveJsonAggOrderKey","raw","strings","snakeCase","steps","sql","hookRows","rawRows","dumpMeta","compiled","planReport","convertBigintJsReadValue","toColumnList","nonEmptyString","record","toColumnList","op","col","distinct","rows","convertBigintJsReadValue","col","requireAdapter","sql","schemaName","fn","ref","compareVersions","sql","sql","param","col","raw"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @dbsp/core\n * Schema definition and query planning for db-semantic-planner.\n */\n\n// ============================================================================\n// ModelIR Types\n// ============================================================================\n\nexport type {\n\tCardinality,\n\tColumnIR,\n\tColumnType,\n\tIncludeStrategy,\n\tIndexIR,\n\tModelIR,\n\tOptionality,\n\tTableIR,\n} from './model-ir.js';\n\n// CLI-NQL: Relation kind helpers and pseudo-column factory\n\n// ============================================================================\n// IntentAST Types\n// ============================================================================\n\nexport type {\n\tAggregateExpressionIntent,\n\tAggregateIntent,\n\tExpressionIntent,\n\tIncludeIntent,\n\tInsertFromIntent,\n\tInsertIntent,\n\tJoinIntent,\n\tMutationIntent,\n\tOrderByIntent,\n\tQueryIntent,\n\tRecursiveIntent,\n\tSelectAggregateIntent,\n\tSelectFieldsIntent,\n\tSelectIntent,\n\tSelectWithExpressionsIntent,\n\tSubqueryRefIntent,\n\tUpsertFromIntent,\n\tWhereAndIntent,\n\tWhereComparisonIntent,\n\tWhereInIntent,\n\tWhereIntent,\n\tWhereLikeIntent,\n\tWhereNotIntent,\n\tWhereNullIntent,\n\tWhereOrIntent,\n\tWhereRangeIntent,\n\tWindowIntent,\n} from './intent-ast.js';\nexport {\n\tisDeleteIntent,\n\tisInsertIntent,\n\tisUpdateIntent,\n\tisUpsertIntent,\n} from './intent-ast.js';\n\n// ============================================================================\n// Schema DSL (User-facing API)\n// ============================================================================\n\n// ARCH-005: Unified Schema API\nexport {\n\ttype ColumnDef,\n\tgetSchemaFromDb,\n\tisRef,\n\ttype JsonValue,\n\ttype ManyToManyDefinition,\n\ttype ManyToManyOptions,\n\tmanyToMany,\n\ttype RefOptions,\n\tref,\n\ttype Schema,\n\ttype SchemaColumnType,\n\ttype SchemaDefinition,\n\ttype SchemaTableOptions,\n\ttype SelfRefRoles,\n\tschema,\n\ttype TableDef,\n} from './dx/schema.js';\n\n// ============================================================================\n// Conventions (pluralization and casing)\n// ============================================================================\n\nexport {\n\tIRREGULAR_PLURALS,\n\tpluralize,\n\tsingularize,\n} from './conventions.js';\n\n// ============================================================================\n// Semantic Planner\n// ============================================================================\n\nexport { AmbiguousIncludeError } from '@dbsp/types';\nexport type {\n\tPlanDecision,\n\tPlanOptions,\n\tPlanReport,\n\tPlanWarning,\n} from './planner.js';\nexport {\n\tAmbiguousPlanError,\n\tplan,\n\tplanRecursive,\n} from './planner.js';\n\n// ============================================================================\n// ADR-0003 Transition Planner Interfaces\n// ============================================================================\n\nexport type {\n\tAssumption,\n\tProvenPlanStep,\n} from './transition/index.js';\nexport {\n\tadmitRecordedIdentity,\n\tcreateStagedTransitionOrchestrator,\n\tisOperationRuntime,\n} from './transition/index.js';\n\n// ============================================================================\n// Implementation (for advanced use cases)\n// ============================================================================\n\nexport { ModelIRImpl } from './model-impl.js';\n\n// ============================================================================\n// Adapter Interface (for multi-adapter support)\n// ============================================================================\n\nexport type {\n\tAdapter,\n\tAdapterLogger,\n\tBaseAdapter,\n\tCompiledQuery,\n\tCompileOptions,\n\tCompilingAdapter,\n\tDbCasing,\n\tDump,\n\tExecutingAdapter,\n\tIntrospectingAdapter,\n\tRawSqlAdapter,\n\tStreamingAdapter,\n\tTransactionalAdapter,\n} from './adapter.js';\n\n// ============================================================================\n// DX Layer (Developer Experience)\n// ============================================================================\n\nexport {\n\ttype AfterMutationHook,\n\ttype AfterMutationObserver,\n\ttype AfterQueryHook,\n\ttype AfterQueryObserver,\n\ttype AggregateOptions,\n\ttype AlterColumnOptions,\n\tAmbiguousRelationError,\n\taggOrderBy,\n\tand,\n\tany,\n\tarray,\n\tarrayAgg,\n\ttype BatchValuesOptions,\n\ttype BatchValuesRef,\n\ttype BeforeMutationHook,\n\ttype BeforeQueryHook,\n\tbatchValues,\n\tboolFn,\n\tCaseBuilder,\n\ttype CaseValue,\n\tColumnNotFoundError,\n\ttype ColumnRef,\n\ttype ColumnSpec,\n\ttype CreateIndexOptions,\n\tCteBuilder,\n\tCteQueryBuilder,\n\ttype CursorPaginatedResult,\n\ttype CursorPaginateOptions,\n\tcaseWhen,\n\tcast,\n\tcoalesce,\n\tcol,\n\tcreateHookManager,\n\tcreateOrm,\n\tcreateRawCteBuilder,\n\tDeleteBuilder,\n\ttype DistinctField,\n\ttype DropIndexOptions,\n\tdenseRank,\n\tdistinct,\n\tErrorCode,\n\tErrors,\n\tExecutionError,\n\tExpressionRef,\n\ttype ExpressionSpec,\n\temitWarning,\n\teq,\n\tevery,\n\texists,\n\texprRef,\n\textractPseudoColumnKeywords,\n\ttype FullTextSearchField,\n\tfn,\n\tfullTextSearch,\n\tgetLogger,\n\tgt,\n\tgte,\n\ttype HookManager,\n\ttype IncludeOptions,\n\ttype IndexColumnDef,\n\ttype IndexInfo,\n\ttype IndexMethod,\n\ttype InferTableRow,\n\tInsertBuilder,\n\tInvalidOperationError,\n\tinArray,\n\tinSubquery,\n\tisBatchValuesRef,\n\tisDistinctFrom,\n\tisNotNull,\n\tisNull,\n\tisSqlRaw,\n\ttype Logger,\n\tlag,\n\tlead,\n\tlike,\n\tliteral,\n\tlt,\n\tlte,\n\ttype MutationDump,\n\ttype MutationHookContext,\n\tNotFoundError,\n\ttype NqlBuilder,\n\ttype NqlTag,\n\tnamedArg,\n\tneq,\n\tnone,\n\tnot,\n\tnotExists,\n\tnqlRaw,\n\ttype OnErrorHook,\n\ttype OrmInstance,\n\ttype OrmOf,\n\top,\n\tor,\n\touterRef,\n\ttype PaginatedResult,\n\ttype PaginateOptions,\n\ttype PredicateExpressionRef,\n\ttype PredicateRef,\n\tparam,\n\ttype QueryBuilder,\n\ttype QueryHookContext,\n\ttype RangeType,\n\ttype RangeValue,\n\tRawCteQueryBuilder,\n\ttype RecursiveOptions,\n\ttype RelationHints,\n\tRelationNotFoundError,\n\ttype RelationRef,\n\tResultHydrator,\n\trangeContainedBy,\n\trangeContains,\n\trangeOverlaps,\n\trank,\n\traw,\n\trawExists,\n\trelationColumn,\n\tresetLogger,\n\trowNumber,\n\ttype SchemaIndexOptions,\n\ttype SchemaOptions,\n\ttype SetOperationBuilder,\n\ttype SqlRawExpression,\n\ttype StreamOptions,\n\tSubqueryBuilder,\n\tSubqueryExpression,\n\tsetLogger,\n\tsilentLogger,\n\tsome,\n\tsql,\n\tstar,\n\tsubquery,\n\tTABLE_META,\n\ttype TableDDL,\n\ttype TableIndexes,\n\tTableNotFoundError,\n\ttype TableRef,\n\ttype TruncateOptions,\n\ttextScore,\n\tUnsafeOperationError,\n\tUpdateBuilder,\n\tUpsertBuilder,\n\tunary,\n\tunsafeAsPredicate,\n\ttype VacuumOptions,\n\ttype WarningCategory,\n\twAvg,\n\twCount,\n\twMax,\n\twMin,\n\twSum,\n} from './dx/index.js';\n\n// ============================================================================\n// Dialect Capabilities (CORE-004)\n// ============================================================================\n\nexport type { DialectCapabilities } from './dialects/index.js';\nexport { POSTGRESQL_CAPABILITIES } from './dialects/index.js';\n\n// ============================================================================\n// SQL Utilities\n// ============================================================================\n\nexport { normalizeSQL } from './sql-utils.js';\n\n// ============================================================================\n// Assertion System (.assert.dbsp)\n// ============================================================================\n\nexport type {\n\tAssertion,\n\tAssertionOutcome,\n\tAssertionQueryResult,\n\tAssertionSummary,\n\tIntentSummary,\n\tParseError,\n\tParseResult,\n\tQueryAssertionResult,\n} from './assert/index.js';\nexport {\n\tassertEquals,\n\tassertParamsEquals,\n\tassertParamsType,\n\tassertSQLEquals,\n\tparseAssertionFile,\n\trunAssertions,\n\tvalidateAssertionBlocks,\n} from './assert/index.js';\n\nexport { InvalidJsonAggPayloadError } from './dx/include-payload-hydration.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAS,6BAA6B;","names":[]}