{"version":3,"sources":["../src/store/collection-surface.ts","../src/store/recorded-coordinate-guard.ts","../src/store/collections/temporal-read-params.ts","../src/store/store-view.ts","../src/utils/path.ts","../src/query/compiler/emitter/plan-inspector.ts","../src/query/compiler/emitter/recursive.ts","../src/query/compiler/emitter/set-operations.ts","../src/query/compiler/emitter/standard.ts","../src/utils/identifier.ts","../src/query/ast.ts","../src/query/compiler/identity-traversal.ts","../src/query/compiler/inverse-traversal-guard.ts","../src/query/compiler/limit-offset.ts","../src/query/compiler/typed-json-extract.ts","../src/query/compiler/utils.ts","../src/query/compiler/emitter/standard-builders.ts","../src/query/compiler/passes/fulltext.ts","../src/query/compiler/passes/fusion.ts","../src/query/compiler/passes/recursive.ts","../src/query/compiler/passes/runner.ts","../src/query/compiler/passes/temporal.ts","../src/query/compiler/passes/vector.ts","../src/query/compiler/plan/lowering.ts","../src/query/compiler/recorded-current-index-guard.ts","../src/query/compiler/expression-subquery-scope.ts","../src/query/compiler/standard-pass-pipeline.ts","../src/query/compiler/recursive.ts","../src/query/builder/one-statement-sharing.ts","../src/query/execution/value-decoder.ts","../src/store/neighbors.ts","../src/store/recursive-cte.ts","../src/store/subgraph.ts","../src/query/compiler/traversal-stage-validation.ts","../src/query/compiler/recursive-chain.ts","../src/query/compiler/set-operations.ts","../src/query/compiler/index.ts","../src/query/execution/result-mapper.ts","../src/query/builder/order-by-field.ts","../src/query/cursor.ts","../src/query/execution/pagination.ts","../src/query/execution/selectable-alias.ts","../src/query/execution/field-tracker.ts","../src/query/execution/selective-result-mapper.ts","../src/query/execution/schema-checked-read.ts","../src/query/builder/read-instant-template.ts","../src/query/builder/prepared-query.ts","../src/query/builder/aggregates.ts","../src/query/builder/expression-scope.ts","../src/query/builder/validation.ts","../src/query/builder/ast-builder.ts","../src/query/builder/internal-context.ts","../src/query/builder/compile-options.ts","../src/query/builder/one-statement-batch.ts","../src/query/builder/one-statement-provenance.ts","../src/query/builder/terminal-query.ts","../src/query/builder/executable-query.ts","../src/query/compiler/relation-aggregate-validation.ts","../src/query/compiler/relations.ts","../src/query/builder/prepared-bindings.ts","../src/query/builder/render-query-sql.ts","../src/query/builder/relation.ts","../src/query/builder/executable-projection-query.ts","../src/query/builder/executable-aggregate-query.ts","../src/core/runtime-kind.ts","../src/query/builder/dynamic.ts","../src/query/builder/expression-context.ts","../src/query/builder/expression-subqueries.ts","../src/query/builder/recursive-stop.ts","../src/query/builder/traversal-builder.ts","../src/query/builder/query-builder.ts","../src/query/builder/unionable-query.ts","../src/query/builder/fragment.ts","../src/query/builder/index.ts","../src/query/builder.ts","../src/store/fulltext-rebuild.ts","../src/store/search.ts","../src/store/search-facade.ts","../src/store/store-analysis.ts","../src/backend/branded.ts","../src/backend/heterogeneous-node-upsert-batch.ts","../src/graph-extension/classify.ts","../src/schema/evolution-plan.ts","../src/store/algorithms/context.ts","../src/store/algorithms/degree.ts","../src/store/algorithms/iterative-graph-operation.ts","../src/store/algorithms/label-propagation.ts","../src/store/algorithms/page-rank.ts","../src/store/algorithms/breadth-first.ts","../src/store/algorithms/reachable.ts","../src/store/algorithms/shortest-path.ts","../src/store/algorithms/weakly-connected-components.ts","../src/store/algorithms/weighted-shortest-path.ts","../src/store/algorithms/index.ts","../src/store/claims/verify.ts","../src/store/operations/edge-identity.ts","../src/store/collections/coalesce.ts","../src/store/collections/edge-collection.ts","../src/store/collections/node-collection.ts","../src/store/collection-factory.ts","../src/store/evolution.ts","../src/store/execution-lifetime.ts","../src/store/history-store-backend.ts","../src/store/introspect.ts","../src/store/materialize-shared.ts","../src/store/materialize-indexes.ts","../src/store/materialize-removals.ts","../src/store/operations/edge-write-fences.ts","../src/store/operations/edge-operations.ts","../src/store/recorded-read-service.ts","../src/store/transaction-receipt.ts","../src/store/store.ts"],"names":["ConfigurationError","resolveReadCoordinate","nowIso","describeCoordinate","coordinateContext","target","requireDefined","storeRuntime","withRecordedCoordinate","assertRecordedInstantOwnershipMatch","SQLITE_PATH_DELIMITER","PG_ARRAY_START","PG_ARRAY_END","PG_PATH_ELEMENT_SEPARATOR","CompilerInvariantError","sql","MAX_PG_IDENTIFIER_LENGTH","fnv1aBase36","optionalRecordedInstantParts","isEngineNativeRecordedReadBinding","refuseEngineNativeRecordedIdentityRead","requireRecursiveTraversalVerdict","historicalIdentityPeerClassQuery","IDENTITY_PEER_CLASS_COLUMNS","compileKindFilter","field","jsonPointer","getFieldPointer","parseJsonPointer","ALIAS_CTE_PREFIX","compilePredicateClauses","getPredicatesForAlias","getNodeKindsForAlias","expr","validateAggregateOperand","compileLegacyAggregateExpression","compileFieldValue","compileDatabaseExpression","getHybridTargetAlias","EMBEDDINGS_CTE_ALIAS","FULLTEXT_CTE_ALIAS","HYBRID_CANDIDATES_CTE_ALIAS","UnsupportedPredicateError","resolveNullOrdering","compileOrderTerm","compilePredicateExpression","vectorSlotKey","assertApproximateMetricSupported","vectorScoreExpression","vectorMinScoreCondition","extractFulltextMatchPredicates","UnsupportedBackendCapabilityError","currentReadInstantFor","compileTemporalFilter","extractTemporalOptions","extractVectorSimilarityPredicates","hasVariableLengthTraversal","getDialect","entry","expressionContainsAggregate","visitExpressionChildren","buildPredicateIndex","collectRequiredColumnsByAlias","assertRecursiveTraversalSupported","compileRecursiveBranch","compileFieldValueFromColumn","asCompiledRowsSql","backendDerivationRoot","currentReadInstant","createSchemaIntrospector","ValidationError","rowToEdge","normalizeRowTimestamp","normalizeRequiredRowTimestamp","rowToNode","assertRecursiveTraversal","recordedReadSchemaFor","DEFAULT_SQL_SCHEMA","resolveRecursiveTraversal","hasOwnKey","validateProjectionField","markForceCustomPlan","rowToNodeMeta","rowToEdgeMeta","nodeAliases","columns","compileQuery","assumeRecursiveTraversalSupported","expressionContext","requireSqlSchema","scopes","recursiveResultAlias","markAnnIndexScan","asCompiledSelectSql","compileSetOperation","annIndexScanTypes","withPinnedReadInstant","traversal","groupBy","having","path","createDataKeyedBag","fieldRef","resolveJsonPointer","buildContext","DEFAULT_STREAM_BATCH_SIZE","value","isInteropProbeKey","NODE_META_KEYS","EDGE_META_KEYS","compareStrings","SchemaChangedError","isSqlPlaceholder","CURRENT_READ_INSTANT_PLACEHOLDER","isRawExecutable","readOwnProperty","bindSqlValue","isParameterRef","normalizeDatabaseLiteral","isCollectRecordOperand","rawRows","collectOperandExpressions","resolveParameterValueType","resolveBackendFulltext","resolveDeclaredFulltextLanguage","resolveEmbeddingFields","chunk","withRecordedRelationsPrecondition","rows","outputName","aliasObject","DEFAULT_PAGINATION_LIMIT","isPortableCountDistinctValueType","isAggregateExpression","haveCompatibleCollectionElements","NOT_COMPUTED","createFieldExpression","sourceAst","RuntimeKindTokenError","buildFieldBuilderForTypeInfo","property","child","createExistsSubqueryExpression","createScalarSubqueryExpression","max","min","stringField","numberField","baseField","dateField","arrayField","objectField","KindNotFoundError","isEdgeTargetMap","EndpointError","coordinate","createOuterReferenceExpression","createFulltextAccessor","projectionOutputNames","runOptionallyInTransaction","assertFulltextMember","getSearchableFields","rowPropsToObject","computeFulltextContent","getEmbeddingFields","compareCodePoints","rank","assertVectorMinScore","bindExtraIfReachable","BATCH_POINT_READ","batchPointReadVerdict","TypeGraphError","encodeJsonPointerSegment","StaleVersionError","SchemaMismatchError","sha256Hex","sortedReplacer","serializeSchemaProperties","count","IncompatibleChangeError","canonicalEqual","freezeDeep","mergeGraphExtension","plan","prepareNewSchemaVersion","resolveGraphVectorSlots","assertValidRecordedInstant","INTERNAL_TEMPORARY_WRITES","postgresReadWriteRefusedSqlState","generateId","asCompiledTemporaryStatementSql","postgresTemporaryTableUnavailableSqlState","GraphAlgorithmConvergenceError","sqlValueList","isPresent","createWorkingTable","initializeWorkingTable","runLabelPropagationRound","extractMemberships","applyNextLabels","InvalidEdgeWeightError","createSqlSchema","uniquenessClaimTarget","subClassComponent","isSameClaimOwner","disjointnessClaimAxis","DISJOINT_CONSTRAINT_NAME","edgeCardinalityClaimTarget","compareClaimTargets","EDGE_IDENTITY_MISMATCH_CODE","isCanonicalIsoDate","statedBoundMatchesStored","preservesImmutableLowerBound","validityEndAfterMutation","encodeTupleKey","executeEdgeCreate","executeEdgeCreateNoReturnBatch","executeEdgeCreateBatch","executeEdgeUpdate","executeEdgeUpsertUpdateBatch","executeEdgeResolvedMutationSet","executeEdgeDelete","executeEdgeDeleteBatch","executeEdgeHardDelete","endpointSetReadMembers","getEdgeRowsByIds","assertValidityEndMutation","assertClearValidToSupported","results","runResolvedMutationSetConverging","NodeNotFoundError","ENTITY_ALREADY_EXISTS_CODE","executeNodeCreate","executeNodeCreateNoReturnBatch","executeNodeCreateBatch","executeNodeUpdate","executeNodeSetUpdate","executeNodeUpsertUpdateBatch","executeNodeResolvedMutationSet","executeNodeReplacementBatch","executeNodeDelete","executeNodeDeleteBatch","executeNodeHardDelete","getNodeRowsByIds","result","SchemaContentConflictError","TransactionClosedError","GRAPH_BACKEND_PROJECTION_KEYS","deriveBackend","inheritRecordedTransactionBindings","projectBackend","extensionKindNames","projectTargetKinds","buildGraphExtensionOntologyKeySet","getTypeName","compileTimeOntologyKey","canonicalAnnotations","isPostgresConcurrentDdlRaceError","isKnownKind","requireCatalog","resolveSystemIndexNames","generateIndexDDL","isOptimisticRetryTier","runRetriedUnit","OPTIMISTIC_RETRY_ATTEMPTS","delay","SYSTEM_INDEX_DECLARATIONS","resolveSystemIndexTableName","systemIndexName","generateSystemIndexDDL","serializeIndexDeclaration","parseSerializedSchema","materializeOne","closeRecordedHardDeletedKind","buildHardDeleteEdgeClaimsByNodeKind","buildHardDeleteUniquesByConcreteKind","buildHardDeleteEdgeClaimsByEdgeKind","asCompiledStatementSql","isMissingTableError","DatabaseOperationError","EdgeNotFoundError","edgeCardinalityClaim","assertEdgeMatchIdentityBackendSupport","validateEdgeEndpoints","validateEdgeProps","resolveEdgeMatchIdentityStorage","validateStatedValidityLowerBound","validateOptionalCanonicalIsoDate","assertOrderedValidityWindow","checkCardinalityConstraint","EndpointNotFoundError","EdgeMatchIdentityConflictError","isBundledRootAutocommitEligible","canFuseSchemaFenceInFirstWrite","isAutocommitSingleStatementWrite","edgeWritePlan","edgeWriteNeedsConstraintFence","unfencedTarget","isSchemaFencedInsertEligible","hasLeasedSchemaFence","lockSchemaVersionForStoreWrite","diagnoseFusedSchemaFenceNoRow","AutocommitWriteRequiresTransaction","prepared","edgeCardinalityClaimMode","work","withAlreadyExistsTranslation","executeAuthoritativeGraphCommand","claimEdgeCardinality","memoizeLeasedSchemaFence","runAutocommitSingleStatementWritePlan","runWritePlan","runHookedWritePlan","createEdgeBatchValidationBackend","edgeCardinalityClaimRefusal","AtomicEdgeBatchEndpointRefusalError","AtomicEdgeBatchCardinalityRefusalError","classifyDurableEdgeBatchOutcomes","resolveAtomicEdgeBatchExecutor","nestedManagedWriteTarget","edgeMatchIdentityUpdateRefusal","assertWritableValidityWindow","assertsStoredWindowState","resolveAtomicEdgeResolvedUpdateBatchExecutor","runAtomicProgramWithHooks","writeResultAlwaysChanges","unsupportedResolvedMutationSet","resolveAtomicEdgeResolvedMutationSetExecutor","ResolvedMutationSetMoved","appliedResolvedMutationSet","atomicResolvedUpdateAttemptBudget","resolveAtomicEdgeDeleteBatchExecutor","assertAtomicDeleteSchemaFenceMatched","AtomicEdgeDeleteIdentityRefusalError","canonicalPersistedJsonValue","normalizePersistedEdgeMatchProps","forceTransactionRead","CardinalityError","buildEdgeMatchKey","endpointKey","resolveAtomicEdgeConvergenceExecutor","AtomicEdgeConvergenceTombstoneRefusalError","assertGraphCommandConvergenceIsolation","recordedBindParamBudget","projectGraphBackend","parseRecordedInstant","recordedReadSqlSchema","requireRecordedReadBinding","POSTGRES_ROW_MAPPER_CONFIG","SQLITE_ROW_MAPPER_CONFIG","asRecordedInstant","commitNewSchemaVersionIfKindsEmpty","countSchemaKindRows","STORE_RUNTIME","statementExecutionVerdict","resolveBatchWriteVerdict","batchRefusalSuffix","batchRefusalDetails","resolveWriteFencePlan","refuseUnfencedOperationalIdentity","resolveRecordedTimeOwnership","refuseUnfencedClockAllocation","assertRevisionTrackableBackend","requireExternalRecordedReadSource","createRecordedReadBinding","createEngineRecordedReadBinding","requireRecordedTime","createRecordedBackend","createClaimsVerdictThunk","endpointSetReadVerdict","uniqueSidecarBatchVerdict","contributionHealthVerdict","recordedRevisionOriginsVerdict","createNodeRowMapper","createEdgeRowMapper","buildKindRegistry","options","lockRecordedGraphWrite","applyResolvedNodeClaims","backend","liveNodeKindsSharingIds","loadAssertionsByIds","toTransferAssertion","loadCurrentStructuralClasses","createIdentityFacade","createIdentityReadFacade","identitySchemaCommitPreflight","validateIdentityForContext","removeIdentityKindsForContext","createRecordedTransactionScope","readIdentityAssertionsForInterchange","readIdentityAssertionPageAtTarget","lockIdentityGraph","foldIdentityForCreatedNodes","importIdentityAssertionsIntoTarget","assertAffectedIdentityClassesConsistent","applyIdentityChangesForContext","getSchemaChanges","requiresMigration","AUTO_REFRESH_STATISTICS_ROW_THRESHOLD","prepareNodeReplacement","nodeUpsertDirtyCheck","executeNodeGetOrCreateByConstraint","executeNodeBulkGetOrCreateByConstraint","executeNodeFindByConstraint","executeNodeBulkFindByConstraint","executeNodeBulkFindByIndex","recordedInstantWallTime","readRecordedClock","createEngineRecordedInstant","ensureRevisionOrigin","withRecordedFlushObserver","createMutationWitness","registerRecordedIdentityMutationWitness","runInTransactionContext","withTransactionSchemaFenceLease","withWriteTransactionSession","recordedCaptureRequiresCallbackTransactionError","assertRecordedCaptureTransactionIsolation","bindEvolvedTransactionStore","withPreAcquiredTransactionSchemaFenceLease","validateNodeProps","withRecordedNodeMutationTarget","createTransactionReadBackend","TRANSACTION_RUNTIME","forceRecordedGraphRevision","throwHistoryUnsafeSqlAccess","throwRevisionTrackingUnsafeSqlAccess","bindTransactionStore","refKey","mintsOriginNamespacedAnchor","ensureRevisionOriginsRelation","resetRevisionOrigin","advanceRevisionClock","adopt","outcome","inspectAdoptedIdentityStorage","ensureIdentitySchemaStorage","commitNewSchemaVersion","commitNewSchemaVersionWithPreflight","EagerMaterializationError","requireExtras","CONTRIBUTION_HEALTH","bindExtra","ContributionRebuildUnsupportedError","planRemovals","stripGraphExtension","applyDeprecatedKinds","identityKindCascadeNeeded","ensureSchema","loadActiveSchemaWithBootstrap","detachIdentityForNode","requireNodeValidityEndCompatible","renderSql","validityWindowContainsInstant","replacement","assertCurrentRecordedSchema","META_EDGE_DISJOINT_WITH","META_EDGE_EQUIVALENT_TO","META_EDGE_SAME_AS","META_EDGE_SUB_CLASS_OF","MigrationError","runInWriteTransaction","rebuildIdentityClosureForContext","loadAndMergeGraphExtensionDocument","serializeSchema","loadAndVerifyGraph"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,IAAM,wBAAA,GAA2B;AAAA,EACtC,SAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF;AAGO,IAAM,uBAAA,GAA0B;AAAA,EACrC,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA;AACF;AAGO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,QAAA;AAAA,EACA,kBAAA;AAAA,EACA,QAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,sBAAA;AAAA,EACA,YAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF,CAAA;AAGO,IAAM,wBAAA,GAA2B;AAAA,EACtC,SAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA;AACF;AAOO,IAAM,qBAAA,GAAwB;AAAA,EACnC,eAAA;AAAA,EACA,aAAA;AAAA,EACA;AACF,CAAA;AAOO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,QAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA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AAC,qBAAA,CAAsB,KAAK,CAAA,EAAG,SAAS,MAAM,CAAA;AACvD","file":"chunk-OBEYH22Q.cjs","sourcesContent":["import { type GraphDef } from \"../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { type IdentityFacade } from \"../identity/types\";\nimport type {\n  EdgeCollection,\n  NodeCollection,\n  StoreViewEdgeCollection,\n  StoreViewNodeCollection,\n} from \"./types\";\n\n/**\n * StoreView collection surface buckets.\n *\n * The live NodeCollection / EdgeCollection partition into buckets a StoreView\n * treats differently:\n *\n * - temporal reads honor the pinned coordinate;\n * - current reads have no temporal axis and are refused on temporal pins;\n * - writes are never available on a read-only view; and\n * - batch reads require store.batch() and are absent from a view.\n *\n * These arrays are the single runtime source of truth for the proxy routing and\n * the type-level source for the derived StoreView collection types. The\n * StoreView surface-classification test asserts they exactly partition the live\n * collection methods so new collection methods cannot be silently omitted.\n */\n\n/** Temporal-aware node read method names. */\nexport const NODE_TEMPORAL_READ_NAMES = [\n  \"getById\",\n  \"getByIds\",\n  \"find\",\n  \"count\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Current-state-only node reads (constraint / index lookups). */\nexport const CURRENT_ONLY_READ_NAMES = [\n  \"findByConstraint\",\n  \"bulkFindByConstraint\",\n  \"bulkFindByIndex\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Node write method names: never available on a read-only StoreView. */\nexport const NODE_WRITE_NAMES = [\n  \"create\",\n  \"createFromRecord\",\n  \"update\",\n  \"compareAndSet\",\n  \"updateWhere\",\n  \"delete\",\n  \"hardDelete\",\n  \"upsertById\",\n  \"upsertByIdFromRecord\",\n  \"bulkCreate\",\n  \"bulkReplaceById\",\n  \"bulkUpsertById\",\n  \"bulkInsert\",\n  \"bulkDelete\",\n  \"getOrCreateByConstraint\",\n  \"bulkGetOrCreateByConstraint\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Temporal-aware edge read method names. */\nexport const EDGE_TEMPORAL_READ_NAMES = [\n  \"getById\",\n  \"getByIds\",\n  \"find\",\n  \"count\",\n  \"findFrom\",\n  \"findTo\",\n  \"bulkFindFrom\",\n  \"bulkFindTo\",\n  \"findByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n  AnyEdgeType,\n  NodeType,\n  NodeType\n>)[];\n\n/** Deferred edge batch-read method names. */\nexport const EDGE_BATCH_READ_NAMES = [\n  \"batchFindFrom\",\n  \"batchFindTo\",\n  \"batchFindByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n  AnyEdgeType,\n  NodeType,\n  NodeType\n>)[];\n\n/** Edge write method names: never available on a read-only StoreView. */\nexport const EDGE_WRITE_NAMES = [\n  \"create\",\n  \"update\",\n  \"delete\",\n  \"hardDelete\",\n  \"bulkCreate\",\n  \"bulkUpsertById\",\n  \"bulkInsert\",\n  \"bulkDelete\",\n  \"getOrCreateByEndpoints\",\n  \"bulkGetOrCreateByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n  AnyEdgeType,\n  NodeType,\n  NodeType\n>)[];\n\n/** Identity facade read method names: available on a read-only StoreView. */\nexport const IDENTITY_READ_NAMES = [\n  \"representativeOf\",\n  \"membersOf\",\n  \"nodesOf\",\n  \"areSame\",\n  \"areDifferent\",\n  \"assertionsOf\",\n] as const satisfies readonly (keyof IdentityFacade<GraphDef>)[];\n\n/** Identity facade write method names: never available on a read-only view. */\nexport const IDENTITY_WRITE_NAMES = [\n  \"assertSame\",\n  \"assertDifferent\",\n  \"bulkAssertSame\",\n  \"bulkAssertDifferent\",\n  \"retractAssertion\",\n  \"retractSameAssertion\",\n  \"retractDifferentAssertion\",\n  \"bulkRetractAssertions\",\n] as const satisfies readonly (keyof IdentityFacade<GraphDef>)[];\n\n/** Recorded-time collection point reads that reconstruct safely by id. */\nexport const RECORDED_POINT_READ_NAMES = [\n  \"getById\",\n  \"getByIds\",\n] as const satisfies readonly (keyof StoreViewNodeCollection<NodeType> &\n  keyof StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType>)[];\n","import { ConfigurationError } from \"../errors\";\n\ntype RecordedCoordinateGuardOptions = Readonly<{\n  code: string;\n  message: string;\n  context?: Readonly<Record<string, unknown>>;\n  suggestion?: string;\n}>;\n\ntype RecordedCoordinateOptions = Readonly<{ recordedAsOf?: unknown }>;\n\nfunction hasOwnRecordedAsOf(\n  options: unknown,\n): options is RecordedCoordinateOptions {\n  return (\n    typeof options === \"object\" &&\n    options !== null &&\n    Object.hasOwn(options, \"recordedAsOf\")\n  );\n}\n\nfunction ownRecordedAsOf(options: unknown): unknown {\n  return hasOwnRecordedAsOf(options) ? options.recordedAsOf : undefined;\n}\n\nexport function assertNoRecordedCoordinate(\n  options: unknown,\n  guard: RecordedCoordinateGuardOptions,\n): void {\n  const recordedAsOf = ownRecordedAsOf(options);\n  if (recordedAsOf === undefined) return;\n\n  throw new ConfigurationError(\n    guard.message,\n    {\n      ...guard.context,\n      code: guard.code,\n      recordedAsOf,\n    },\n    guard.suggestion === undefined ?\n      undefined\n    : { suggestion: guard.suggestion },\n  );\n}\n","/**\n * Shared temporal read-parameter resolution for collection reads.\n */\nimport {\n  type ReadCoordinate,\n  type RecordedInstant,\n  resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport { nowIso } from \"../../utils/date\";\nimport { assertNoRecordedCoordinate } from \"../recorded-coordinate-guard\";\nimport { type QueryOptions } from \"../types\";\n\ntype ValidReadParams = Omit<QueryOptions, \"recordedAsOf\">;\n\nexport type InternalReadParams = ValidReadParams &\n  Readonly<{ recordedAsOf?: RecordedInstant }>;\n\nfunction validReadParams(coordinate: ReadCoordinate): ValidReadParams {\n  const { mode, asOf } = coordinate.valid;\n  return asOf === undefined ?\n      { temporalMode: mode }\n    : { temporalMode: mode, asOf };\n}\n\nexport function withValidCoordinate(coordinate: ReadCoordinate): QueryOptions {\n  assertNoRecordedCoordinate(\n    coordinate.recorded === undefined ?\n      undefined\n    : { recordedAsOf: coordinate.recorded.asOf },\n    {\n      code: \"RECORDED_COLLECTION_READ_UNSUPPORTED\",\n      message:\n        \"Collection reads on StoreView cannot carry recorded-time coordinates.\",\n    },\n  );\n  return validReadParams(coordinate);\n}\n\n/**\n * Flattens a {@link ReadCoordinate} into the `QueryOptions` temporal argument\n * every pinned read accepts. The single point that knows the wire shape of the\n * temporal axis: a `StoreView` injects its coordinate by passing this as a\n * read's trailing temporal argument (or spreading it into an algorithm /\n * subgraph option object). When a new axis (recorded time) is added to\n * {@link ReadCoordinate}, only this function and the backend params change —\n * never the call sites.\n */\nexport function withCoordinate(coordinate: ReadCoordinate): InternalReadParams {\n  const valid = validReadParams(coordinate);\n  return coordinate.recorded === undefined ?\n      valid\n    : { ...valid, recordedAsOf: coordinate.recorded.asOf };\n}\n\n/**\n * The temporal slice of a `findNodesByKind` / `findEdgesByKind` /\n * `count*` parameter object.\n */\nexport type TemporalReadParams = Readonly<{\n  excludeDeleted: boolean;\n  temporalMode: TemporalMode;\n  asOf?: string;\n}>;\n\n/**\n * Resolves the temporal portion of a collection read's backend params:\n * the per-call `temporalMode` wins, falling back to the graph default;\n * soft-deletes are excluded except under `includeTombstones`. An `asOf` is\n * rejected unless the mode is `\"asOf\"` (via {@link resolveReadCoordinate}), so\n * a pinned `current + asOf` is a caller error here exactly as it is on the\n * query, subgraph, algorithm, and StoreView paths — never a silent pin. The\n * backend filter still needs a concrete instant for `current`, so this defaults\n * it to \"now\" once the coordinate is validated.\n *\n * Single source of truth for `find` / `count` / endpoint reads across the\n * node and edge collections, so the resolution rules cannot drift between\n * them.\n */\nexport function resolveTemporalReadParams(\n  options: InternalReadParams | undefined,\n  defaultTemporalMode: TemporalMode,\n): TemporalReadParams {\n  assertNoRecordedCoordinate(options, {\n    code: \"RECORDED_COLLECTION_READ_UNSUPPORTED\",\n    message: \"Broad collection reads cannot honor recorded-time coordinates.\",\n    suggestion:\n      \"Use store.asOfRecorded(...).nodes.Kind.getById/getByIds for point reads, or query() for recorded-time scans.\",\n  });\n\n  const { valid } = resolveReadCoordinate(\n    options?.temporalMode ?? defaultTemporalMode,\n    options?.asOf,\n  );\n  const { mode, asOf } = valid;\n  const base = {\n    excludeDeleted: mode !== \"includeTombstones\",\n    temporalMode: mode,\n  } as const;\n  if (mode === \"current\" || mode === \"asOf\") {\n    return {\n      ...base,\n      asOf: asOf ?? nowIso(),\n    };\n  }\n  return base;\n}\n","/**\n * StoreView — a read-only `(mode, asOf)` lens over a {@link Store}.\n *\n * A `StoreView` pins a temporal coordinate and routes every supported\n * read through it, mirroring Datomic's `(d/as-of db t)` database value\n * and SQL:2011 `FOR SYSTEM_TIME AS OF`. It is *read-only by\n * construction*: mutating \"the graph as of last Tuesday\" is incoherent,\n * so writes stay on the live `Store`.\n *\n * The view is an explicit read context, not a single default flip — the\n * temporal seam is not uniform across surfaces (the query builder\n * hardcodes `\"current\"`, `subgraph` reads `graph.defaults` directly,\n * collections apply a per-call default). The view therefore injects its\n * pinned {@link ReadCoordinate} into each surface it hands out through one\n * helper ({@link withCoordinate}), so a future temporal axis (recorded\n * time) lands on every surface at once instead of splitting by surface.\n *\n * Built on the public `Store` surface (plus one internal sealed-query\n * seam), so it composes the same reads `branch()` / `merge()` consume.\n */\nimport { assertRecordedInstantOwnershipMatch } from \"../backend/capabilities/recorded-time-ownership\";\nimport {\n  type AllNodeTypes,\n  type EdgeKinds,\n  type GraphDef,\n  type NodeKinds,\n} from \"../core/define-graph\";\nimport {\n  coordinateContext,\n  describeCoordinate,\n  type ReadCoordinate,\n  type RecordedInstant,\n  resolveReadCoordinate,\n  withRecordedCoordinate,\n} from \"../core/temporal\";\nimport {\n  type AnyEdgeType,\n  type NodeId,\n  type NodeType,\n  type TemporalMode,\n} from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { type IdentityReadFacade } from \"../identity/types\";\nimport { type InitialQueryBuilder } from \"../query/builder\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n  type BaseTraversalOptions,\n  type DegreeOptions,\n  type InternalGraphAlgorithms,\n  type LabelPropagationMembership,\n  type LabelPropagationOptions,\n  type NeighborsOptions,\n  type NodeIdentifier,\n  type PageRankOptions,\n  type PageRankScore,\n  type PersonalizedPageRankOptions,\n  type ReachableNode,\n  type ReachableOptions,\n  type ShortestPathOptions,\n  type ShortestPathResult,\n  type TemporalAlgorithmOptions,\n  type WeaklyConnectedComponentMembership,\n  type WeaklyConnectedComponentsOptions,\n  type WeightedShortestPathOptions,\n  type WeightedShortestPathResult,\n} from \"./algorithms\";\nimport {\n  CURRENT_ONLY_READ_NAMES,\n  EDGE_BATCH_READ_NAMES,\n  type EDGE_TEMPORAL_READ_NAMES,\n  type NODE_TEMPORAL_READ_NAMES,\n  type RECORDED_POINT_READ_NAMES,\n} from \"./collection-surface\";\nimport {\n  withCoordinate,\n  withValidCoordinate,\n} from \"./collections/temporal-read-params\";\nimport { storeRuntime } from \"./runtime-port\";\nimport { type StoreSearch } from \"./search-facade\";\nimport { type Store, type ViewIdentityAccess } from \"./store\";\nimport {\n  type InternalSubgraphOptions,\n  type SubgraphOptions,\n  type SubgraphProject,\n  type SubgraphResult,\n} from \"./subgraph\";\nimport {\n  type BulkFindEdgesFromParams,\n  type BulkFindEdgesFromResult,\n  type BulkFindEdgesToParams,\n  type BulkFindEdgesToResult,\n  type DynamicStoreViewEdgeCollection,\n  type EdgeBulkFindEndpointOptions,\n  type EdgeCollection,\n  type NodeCollection,\n  type NodeCurrentReads,\n  type RecordedStoreViewEdgeCollection,\n  type RecordedStoreViewEdgeCollections,\n  type RecordedStoreViewNodeCollection,\n  type RecordedStoreViewNodeCollections,\n  type StoreViewEdgeCollection,\n  type StoreViewEdgeCollections,\n  type StoreViewNodeCollection,\n  type StoreViewNodeCollections,\n} from \"./types\";\n\n// ============================================================\n// Public coordinate + view-scoped option types\n// ============================================================\n\n/**\n * The temporal coordinate a {@link StoreView} pins. A discriminated union on\n * `mode`: `asOf` is *required* for `\"asOf\"` and *rejected* (`never`) for every\n * other mode, so the type mirrors the runtime contract. `view({ mode: \"asOf\" })`\n * (missing timestamp) and `view({ mode: \"current\", asOf })` (pinning an instant\n * outside `\"asOf\"`) are both compile errors, not merely runtime\n * `ValidationError`s.\n */\nexport type StoreViewCoordinate =\n  | Readonly<{ mode: \"asOf\"; asOf: string }>\n  | Readonly<{ mode: Exclude<TemporalMode, \"asOf\">; asOf?: never }>;\n\n/**\n * {@link Store.subgraph} options with the temporal axis removed — the\n * view's pinned coordinate supplies it.\n */\nexport type StoreViewSubgraphOptions<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Omit<\n  SubgraphOptions<G, EK, NK, P>,\n  \"temporalMode\" | \"asOf\" | \"recordedAsOf\"\n>;\n\n/** `reachable` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewReachableOptions<G extends GraphDef> = Omit<\n  ReachableOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** `shortestPath` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewShortestPathOptions<G extends GraphDef> = Omit<\n  ShortestPathOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/**\n * `weightedShortestPath` options with the temporal axis removed (the pin\n * supplies it).\n */\nexport type StoreViewWeightedShortestPathOptions<G extends GraphDef> = Omit<\n  WeightedShortestPathOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** `canReach` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewCanReachOptions<G extends GraphDef> = Omit<\n  BaseTraversalOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** `neighbors` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewNeighborsOptions<G extends GraphDef> = Omit<\n  NeighborsOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** `degree` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewDegreeOptions<G extends GraphDef> = Omit<\n  DegreeOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** WCC options with the temporal axis removed (the view's pin supplies it). */\nexport type StoreViewWeaklyConnectedComponentsOptions<G extends GraphDef> =\n  Omit<WeaklyConnectedComponentsOptions<G>, keyof TemporalAlgorithmOptions>;\n\n/** Label-propagation options pinned to the view's temporal coordinate. */\nexport type StoreViewLabelPropagationOptions<G extends GraphDef> = Omit<\n  LabelPropagationOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** PageRank options with the temporal axis removed (the view supplies it). */\nexport type StoreViewPageRankOptions<G extends GraphDef> = Omit<\n  PageRankOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** Personalized PageRank options pinned to the view's temporal coordinate. */\nexport type StoreViewPersonalizedPageRankOptions<G extends GraphDef> = Omit<\n  PersonalizedPageRankOptions<G>,\n  keyof TemporalAlgorithmOptions\n>;\n\n/** Graph-algorithm facade sealed to a {@link StoreView}'s coordinate. */\nexport type StoreViewGraphAlgorithms<G extends GraphDef> = Readonly<{\n  shortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewShortestPathOptions<G>,\n  ) => Promise<ShortestPathResult | undefined>;\n  weightedShortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewWeightedShortestPathOptions<G>,\n  ) => Promise<WeightedShortestPathResult | undefined>;\n  reachable: (\n    from: NodeIdentifier,\n    options: StoreViewReachableOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n  canReach: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewCanReachOptions<G>,\n  ) => Promise<boolean>;\n  neighbors: (\n    node: NodeIdentifier,\n    options: StoreViewNeighborsOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n  degree: (\n    node: NodeIdentifier,\n    options?: StoreViewDegreeOptions<G>,\n  ) => Promise<number>;\n  labelPropagation: (\n    options: StoreViewLabelPropagationOptions<G>,\n  ) => Promise<readonly LabelPropagationMembership[]>;\n  weaklyConnectedComponents: (\n    options: StoreViewWeaklyConnectedComponentsOptions<G>,\n  ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n  pageRank: (\n    options: StoreViewPageRankOptions<G>,\n  ) => Promise<readonly PageRankScore[]>;\n  personalizedPageRank: (\n    options: StoreViewPersonalizedPageRankOptions<G>,\n  ) => Promise<readonly PageRankScore[]>;\n}>;\n\nfunction isReadCoordinate(\n  coordinate: StoreViewCoordinate | ReadCoordinate,\n): coordinate is ReadCoordinate {\n  return \"valid\" in coordinate;\n}\n\n// ============================================================\n// Read-only collection wrapping\n// ============================================================\n\n/**\n * Property keys that look like member access but are JS / Promise interop\n * probes, not graph kinds or collection methods. Resolving them to\n * `undefined` keeps `view.nodes` / `view.edges` (and the refusing search\n * facade) from being mistaken for a thenable when accidentally awaited,\n * and keeps inspection / serialization from tripping the unknown-kind\n * guard.\n */\nconst NON_KIND_KEYS: ReadonlySet<string> = new Set([\n  \"then\",\n  \"catch\",\n  \"finally\",\n  \"toJSON\",\n]);\n\n/**\n * Returns a function that refuses a write or unsupported-read method on a\n * read-only view with a descriptive error, rather than silently ignoring\n * the pin or failing with an opaque `undefined is not a function`.\n */\nfunction createReadOnlyRefusal(\n  entity: \"node\" | \"edge\",\n  method: string,\n  coordinate: ReadCoordinate,\n): () => never {\n  return () => {\n    throw new ConfigurationError(\n      `'${method}' is not available on a read-only StoreView (${describeCoordinate(coordinate)}). ` +\n        `A time-pinned view is a read perspective — perform writes on the live Store.`,\n      {\n        code: \"STORE_VIEW_READ_ONLY\",\n        entity,\n        method,\n        ...coordinateContext(coordinate),\n      },\n    );\n  };\n}\n\n/**\n * Returns a function that refuses a current-state-only read (constraint /\n * index / endpoint lookup) on a *temporal* view via Promise rejection. Such\n * reads have no temporal axis — they always reflect current state — so on a\n * non-`current` pin they would silently lie. On a `current` view they are\n * delegated straight to the live collection instead of refused.\n */\nfunction createCurrentOnlyRefusal(\n  entity: \"node\" | \"edge\",\n  method: string,\n  coordinate: ReadCoordinate,\n): () => Promise<never> {\n  return () =>\n    Promise.reject(\n      new ConfigurationError(\n        `'${method}' is not available on a StoreView (${describeCoordinate(coordinate)}). ` +\n          `Constraint / index / endpoint lookups read current state only and ` +\n          `cannot honor a temporal coordinate — use a current-mode view or the live Store.`,\n        {\n          code: \"STORE_VIEW_CURRENT_ONLY\",\n          entity,\n          method,\n          ...coordinateContext(coordinate),\n        },\n      ),\n    );\n}\n\n/**\n * Returns a function that refuses a deferred edge batch read\n * ({@link EDGE_BATCH_READ_NAMES}) on a read-only view. These reads are *reads*,\n * not writes, but they only resolve through `store.batch(...)`, which a view\n * does not expose — so the view cannot honor them. The refusal is\n * synchronous because the live method returns a `BatchableQuery` synchronously\n * (it is invoked, not awaited), so a misuse fail-louds at the call site instead\n * of being routed through the write-refusal fallthrough and mislabeled a write.\n */\nfunction createBatchReadRefusal(\n  entity: \"node\" | \"edge\",\n  method: string,\n  coordinate: ReadCoordinate,\n): () => never {\n  return () => {\n    throw new ConfigurationError(\n      `'${method}' is not available on a read-only StoreView (${describeCoordinate(coordinate)}). ` +\n        `Batch endpoint reads resolve through store.batch(...), which a view does not expose — ` +\n        `use the live Store's batch(...), or the view's findFrom / findTo / findByEndpoints for single reads.`,\n      {\n        code: \"STORE_VIEW_BATCH_UNAVAILABLE\",\n        entity,\n        method,\n        ...coordinateContext(coordinate),\n      },\n    );\n  };\n}\n\nfunction createRecordedUnsupportedRefusal(\n  entity: \"node\" | \"edge\",\n  method: string,\n  coordinate: ReadCoordinate,\n): () => Promise<never> {\n  return () =>\n    Promise.reject(\n      new ConfigurationError(\n        `'${method}' is not available on a RecordedStoreView (${describeCoordinate(coordinate)}). ` +\n          `Recorded-time reads are reconstructing reads; this view exposes only query, ` +\n          `subgraph, graph algorithms, and collection getById/getByIds/scan reads.`,\n        {\n          code: \"RECORDED_STORE_VIEW_UNSUPPORTED\",\n          entity,\n          method,\n          ...coordinateContext(coordinate),\n        },\n      ),\n    );\n}\n\n/**\n * Current-state-only collection reads: they take no temporal coordinate, so\n * the view delegates them on a `current` pin and refuses them on a temporal\n * pin rather than silently returning current data. Derived from the same\n * {@link CURRENT_ONLY_READ_NAMES} array that defines the `NodeCurrentReads`\n * type, so the runtime routing decision cannot drift from the type partition.\n */\nconst CURRENT_ONLY_READS: ReadonlySet<string> = new Set(\n  CURRENT_ONLY_READ_NAMES,\n);\n\n/**\n * Deferred edge batch reads ({@link EDGE_BATCH_READ_NAMES}): refused on every\n * view (current or temporal) because they resolve through `store.batch(...)`,\n * which a view does not expose. Routed to {@link createBatchReadRefusal} so they\n * are categorized as reads rather than misrouted through the write fallthrough.\n */\nconst EDGE_BATCH_READS: ReadonlySet<string> = new Set(EDGE_BATCH_READ_NAMES);\n\n/**\n * Wraps a `reads` object so its supported reads pass through while any other\n * method that exists on the live collection is handled by `resolveLiveOnly` —\n * the one piece that differs between the read-only (valid-time) and recorded\n * facades. The frozen target and the rejecting `set` / `defineProperty` /\n * `deleteProperty` traps make the view read-only by construction at runtime, and\n * `Object.hasOwn` — not `in` — lets inherited `Object.prototype` members\n * (`toString`, `valueOf`, …) pass straight through so coercion / logging works.\n */\nfunction collectionReadProxy<T extends object>(\n  reads: T,\n  live: object,\n  resolveLiveOnly: (property: string) => unknown,\n): T {\n  const target = Object.freeze(reads) as T;\n  return new Proxy(target, {\n    get(target, property, receiver) {\n      if (\n        typeof property === \"string\" &&\n        !Object.hasOwn(target, property) &&\n        Object.hasOwn(live, property)\n      ) {\n        return resolveLiveOnly(property);\n      }\n      return Reflect.get(target, property, receiver);\n    },\n    has(target, property) {\n      // Mirror `get`: a property is \"present\" if the proxy resolves a value for\n      // it — the pinned reads (own keys of target), any live-collection method\n      // (delegated or refused), or an inherited Object.prototype member. Keeps\n      // `\"method\" in view.collection` consistent with property access.\n      return (\n        (typeof property === \"string\" && Object.hasOwn(live, property)) ||\n        Reflect.has(target, property)\n      );\n    },\n    set() {\n      return false;\n    },\n    defineProperty() {\n      return false;\n    },\n    deleteProperty() {\n      return false;\n    },\n  });\n}\n\n/**\n * Read-only valid-time collection facade. Writes refuse synchronously\n * ({@link createReadOnlyRefusal}); current-state-only reads refuse via Promise\n * rejection on a temporal pin but are delegated to the live collection on a\n * `current` view ({@link CURRENT_ONLY_READS}).\n */\nfunction readOnlyCollectionProxy<T extends object>(\n  reads: T,\n  live: object,\n  coordinate: ReadCoordinate,\n  entity: \"node\" | \"edge\",\n): T {\n  const isCurrent = coordinate.valid.mode === \"current\";\n  return collectionReadProxy(reads, live, (property) => {\n    if (CURRENT_ONLY_READS.has(property)) {\n      return isCurrent ?\n          (live as Record<string, unknown>)[property]\n        : createCurrentOnlyRefusal(entity, property, coordinate);\n    }\n    if (EDGE_BATCH_READS.has(property)) {\n      return createBatchReadRefusal(entity, property, coordinate);\n    }\n    return createReadOnlyRefusal(entity, property, coordinate);\n  });\n}\n\n/**\n * Recorded-time collection facade: any live-collection method that is not a\n * supported reconstructing read refuses uniformly.\n */\nfunction recordedCollectionProxy<T extends object>(\n  reads: T,\n  live: object,\n  coordinate: ReadCoordinate,\n  entity: \"node\" | \"edge\",\n): T {\n  return collectionReadProxy(reads, live, (property) => {\n    if (EDGE_BATCH_READS.has(property)) {\n      return createBatchReadRefusal(entity, property, coordinate);\n    }\n    return createRecordedUnsupportedRefusal(entity, property, coordinate);\n  });\n}\n\nfunction pinnedNodeCollection(\n  live: NodeCollection<NodeType, string>,\n  coordinate: ReadCoordinate,\n): StoreViewNodeCollection<NodeType> {\n  const temporal = withValidCoordinate(coordinate);\n  // Only the temporal reads live in the literal; the proxy serves the\n  // current-only reads (delegate on a `current` pin, refuse on a temporal pin).\n  const reads: Omit<\n    StoreViewNodeCollection<NodeType>,\n    keyof NodeCurrentReads<NodeType>\n  > &\n    Readonly<{\n      [\n        Method in (typeof NODE_TEMPORAL_READ_NAMES)[number]\n      ]: StoreViewNodeCollection<NodeType>[Method];\n    }> = {\n    getById: (id) => live.getById(id, temporal),\n    getByIds: (ids) => live.getByIds(ids, temporal),\n    find: (filter) => live.find(filter, temporal),\n    count: () => live.count(temporal),\n  };\n  return readOnlyCollectionProxy(\n    reads,\n    live,\n    coordinate,\n    \"node\",\n  ) as StoreViewNodeCollection<NodeType>;\n}\n\nfunction pinnedEdgeCollection(\n  live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n  coordinate: ReadCoordinate,\n): StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> {\n  const temporal = withValidCoordinate(coordinate);\n  const reads: StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> &\n    Readonly<{\n      [\n        Method in (typeof EDGE_TEMPORAL_READ_NAMES)[number]\n      ]: StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType>[Method];\n    }> = {\n    getById: (id) => live.getById(id, temporal),\n    getByIds: (ids) => live.getByIds(ids, temporal),\n    find: (filter) => live.find(filter, temporal),\n    count: (filter) => live.count(filter, temporal),\n    findFrom: (from) => live.findFrom(from, temporal),\n    findTo: (to) => live.findTo(to, temporal),\n    bulkFindFrom: (froms, options) =>\n      live.bulkFindFrom(froms, { ...options, ...temporal }),\n    bulkFindTo: (tos, options) =>\n      live.bulkFindTo(tos, { ...options, ...temporal }),\n    findByEndpoints: (from, to, options) =>\n      live.findByEndpoints(from, to, options, temporal),\n  };\n  return readOnlyCollectionProxy(reads, live, coordinate, \"edge\");\n}\n\n/**\n * Builds the lazy, per-kind caching proxy that fronts the pinned\n * collections. Shared by the valid-time and recorded views' `nodes` and\n * `edges`: indexing the live proxy throws `KindNotFoundError` for an unknown\n * kind, so the view refuses an unknown kind the same way the live store does —\n * while interop probes ({@link NON_KIND_KEYS}) resolve to `undefined`. `wrap`\n * receives the resolved `kind` so the recorded view can route point reads\n * through the store's recorded seams.\n */\nfunction pinnedCollections<L, W>(\n  live: object,\n  coordinate: ReadCoordinate,\n  isKind: (kind: string) => boolean,\n  wrap: (kind: string, liveCollection: L, coordinate: ReadCoordinate) => W,\n): Record<string, W> {\n  const cache = new Map<string, W>();\n  return new Proxy(\n    {},\n    {\n      get(target, kind, receiver) {\n        if (typeof kind !== \"string\") return;\n        if (!isKind(kind)) {\n          if (NON_KIND_KEYS.has(kind)) return;\n          if (Object.hasOwn(Object.prototype, kind)) {\n            const inheritedValue: unknown = Reflect.get(target, kind, receiver);\n            return inheritedValue;\n          }\n        }\n        const cached = cache.get(kind);\n        if (cached !== undefined) return cached;\n        const wrapped = wrap(\n          kind,\n          requireDefined((live as Record<string, L>)[kind]),\n          coordinate,\n        );\n        cache.set(kind, wrapped);\n        return wrapped;\n      },\n    },\n  );\n}\n\nfunction pinnedNodeCollectionsFor<G extends GraphDef, W>(\n  store: Store<G>,\n  coordinate: ReadCoordinate,\n  wrap: (\n    kind: string,\n    live: NodeCollection<NodeType, string>,\n    coordinate: ReadCoordinate,\n  ) => W,\n): Record<string, W> {\n  return pinnedCollections(\n    store.nodes,\n    coordinate,\n    (kind) => Object.hasOwn(store.graph.nodes, kind),\n    wrap,\n  );\n}\n\nfunction pinnedEdgeCollectionsFor<G extends GraphDef, W>(\n  store: Store<G>,\n  coordinate: ReadCoordinate,\n  wrap: (\n    kind: string,\n    live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n    coordinate: ReadCoordinate,\n  ) => W,\n): Record<string, W> {\n  return pinnedCollections(\n    store.edges,\n    coordinate,\n    (kind) => Object.hasOwn(store.graph.edges, kind),\n    wrap,\n  );\n}\n\nfunction recordedNodeCollection<G extends GraphDef>(\n  store: Store<G>,\n  kind: string,\n  live: NodeCollection<NodeType, string>,\n  coordinate: ReadCoordinate,\n): RecordedStoreViewNodeCollection<NodeType> {\n  const reads: RecordedStoreViewNodeCollection<NodeType> &\n    Readonly<{\n      [\n        Method in (typeof RECORDED_POINT_READ_NAMES)[number]\n      ]: RecordedStoreViewNodeCollection<NodeType>[Method];\n    }> = {\n    getById: (id) =>\n      storeRuntime(store).recordedNodeGetById(kind, id, coordinate),\n    getByIds: (ids) =>\n      storeRuntime(store).recordedNodeGetByIds(kind, ids, coordinate),\n    scan: (options) =>\n      storeRuntime(store).recordedNodeScan(kind, coordinate, options),\n  };\n  return recordedCollectionProxy(reads, live, coordinate, \"node\");\n}\n\nfunction recordedEdgeCollection<G extends GraphDef>(\n  store: Store<G>,\n  kind: string,\n  live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n  coordinate: ReadCoordinate,\n): RecordedStoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> {\n  const reads: RecordedStoreViewEdgeCollection<\n    AnyEdgeType,\n    NodeType,\n    NodeType\n  > &\n    Readonly<{\n      [\n        Method in (typeof RECORDED_POINT_READ_NAMES)[number]\n      ]: RecordedStoreViewEdgeCollection<\n        AnyEdgeType,\n        NodeType,\n        NodeType\n      >[Method];\n    }> = {\n    getById: (id) =>\n      storeRuntime(store).recordedEdgeGetById(kind, id, coordinate),\n    getByIds: (ids) =>\n      storeRuntime(store).recordedEdgeGetByIds(kind, ids, coordinate),\n    scan: (options) =>\n      storeRuntime(store).recordedEdgeScan(kind, coordinate, options),\n  };\n  return recordedCollectionProxy(reads, live, coordinate, \"edge\");\n}\n\n// ============================================================\n// Read-only search facade\n// ============================================================\n\n/**\n * The non-mutating read methods of {@link StoreSearch}. The `satisfies`\n * constraint binds each name to a real `StoreSearch` member, so a rename or\n * removal of one of these methods is a compile error here rather than a silent\n * routing gap. (Completeness for a *newly added* read method would need a\n * StoreSearch read/write type split, mirroring the node collection's — tracked\n * separately.)\n */\nconst READ_SEARCH_METHOD_NAMES = [\n  \"fulltext\",\n  \"vector\",\n  \"hybrid\",\n] as const satisfies readonly (keyof StoreSearch<GraphDef>)[];\nconst READ_SEARCH_METHODS: ReadonlySet<string> = new Set(\n  READ_SEARCH_METHOD_NAMES,\n);\n\ntype SearchInvocation = (...args: readonly unknown[]) => unknown;\n\nfunction searchProxy<G extends GraphDef>(\n  resolve: (method: string) => SearchInvocation | undefined,\n): StoreSearch<G> {\n  return new Proxy({} as StoreSearch<G>, {\n    get(target, method, receiver) {\n      // Interop probes must resolve to `undefined` so the facade is not\n      // mistaken for a thenable.\n      if (typeof method !== \"string\" || NON_KIND_KEYS.has(method)) {\n        return;\n      }\n      // Inherited Object.prototype members (toString / valueOf / …) pass\n      // through so coercion / logging of the facade stays safe.\n      if (Object.hasOwn(Object.prototype, method)) {\n        const inheritedValue: unknown = Reflect.get(target, method, receiver);\n        return inheritedValue;\n      }\n      return resolve(method);\n    },\n    has(target, method) {\n      if (typeof method !== \"string\") return Reflect.has(target, method);\n      if (NON_KIND_KEYS.has(method)) return false;\n      if (Object.hasOwn(Object.prototype, method)) return true;\n      return resolve(method) !== undefined;\n    },\n  });\n}\n\n/**\n * Builds the error a refused search method rejects with. A `current` view\n * still refuses the mutating maintenance op (`rebuildFulltext`) because the\n * view is read-only; a non-`current` view refuses *all* search because the\n * fulltext / vector index reflects current state only and historical\n * relevance is out of scope.\n */\nfunction searchRefusal(\n  method: string,\n  coordinate: ReadCoordinate,\n  isCurrent: boolean,\n): ConfigurationError {\n  return isCurrent ?\n      new ConfigurationError(\n        `store.search.${method} is a maintenance write and is not available on a ` +\n          `read-only StoreView. Run it on the live Store.`,\n        {\n          code: \"STORE_VIEW_READ_ONLY\",\n          method,\n          ...coordinateContext(coordinate),\n        },\n      )\n    : new ConfigurationError(\n        `store.search.${method} is not available on a StoreView (${describeCoordinate(coordinate)}). ` +\n          `The fulltext / vector index reflects current state only; historical ` +\n          `relevance is out of scope for a temporal view. Use a current-mode ` +\n          `view or query the live Store.`,\n        {\n          code: \"STORE_VIEW_SEARCH_UNSUPPORTED\",\n          method,\n          ...coordinateContext(coordinate),\n        },\n      );\n}\n\n/**\n * The view's search facade. On a `current` view the read methods\n * (`fulltext` / `vector` / `hybrid`) delegate to the live `store.search`;\n * every other case refuses via Promise rejection — `rebuildFulltext` (a\n * maintenance write) on any view, and *all* search on a non-`current`\n * view. A Proxy (not a fixed literal) so a future `StoreSearch` method is\n * refused, not silently passed through, on a temporal view.\n */\nfunction pinnedSearch<G extends GraphDef>(\n  store: Store<G>,\n  coordinate: ReadCoordinate,\n): StoreSearch<G> {\n  const isCurrent = coordinate.valid.mode === \"current\";\n  const live =\n    isCurrent ?\n      (store.search as unknown as Record<string, SearchInvocation>)\n    : undefined;\n  return searchProxy<G>((method) => {\n    if (live !== undefined && READ_SEARCH_METHODS.has(method)) {\n      const liveMethod = live[method];\n      if (liveMethod !== undefined) {\n        return (...args: readonly unknown[]) =>\n          Reflect.apply(liveMethod, live, args);\n      }\n    }\n    return () => Promise.reject(searchRefusal(method, coordinate, isCurrent));\n  });\n}\n\n/**\n * Builds the error a refused {@link RecordedStoreView} search method rejects\n * with. Unlike {@link searchRefusal}, the recorded view refuses search for\n * *every* method regardless of the composed valid-time mode, so there is no\n * `current` delegating branch.\n */\nfunction recordedSearchRefusal(\n  method: string,\n  coordinate: ReadCoordinate,\n): ConfigurationError {\n  return new ConfigurationError(\n    `store.search.${method} is not available on a RecordedStoreView (${describeCoordinate(coordinate)}). ` +\n      `The fulltext / vector index reflects current state only and cannot answer a ` +\n      `recorded-time query. Run search on the live Store.`,\n    {\n      code: \"RECORDED_STORE_VIEW_SEARCH_UNSUPPORTED\",\n      method,\n      ...coordinateContext(coordinate),\n    },\n  );\n}\n\n/**\n * The recorded view's search facade: every method refuses. It never delegates\n * to the live `store.search` even when the composed valid-time mode is\n * `current` — a recorded-time read reconstructs from the history relations,\n * while the fulltext / vector index reflects current state only, so serving a\n * live hit would be a silent lie. A Proxy (not a fixed literal) so a future\n * `StoreSearch` method refuses too instead of resolving to `undefined`.\n */\nfunction recordedSearch<G extends GraphDef>(\n  coordinate: ReadCoordinate,\n): StoreSearch<G> {\n  return searchProxy<G>(\n    (method) => () => Promise.reject(recordedSearchRefusal(method, coordinate)),\n  );\n}\n\n// ============================================================\n// Coordinate-pinned view base\n// ============================================================\n\n/**\n * Shared base for the read-only views. Holds the pinned {@link ReadCoordinate}\n * and delegates the graph algorithms, `subgraph`, and `query` to the live store\n * with that coordinate flattened into each call. {@link StoreView} (valid-time)\n * and {@link RecordedStoreView} (recorded-time) extend it; only the surfaces\n * that genuinely differ — collections, search, and the coordinate-changing\n * helpers — live on the subclasses.\n */\nabstract class CoordinatePinnedView<G extends GraphDef> {\n  protected readonly store: Store<G>;\n  protected readonly coordinate: ReadCoordinate;\n  #algorithmFacade: StoreViewGraphAlgorithms<G> | undefined;\n  #internalAlgorithms: InternalGraphAlgorithms<G> | undefined;\n\n  constructor(store: Store<G>, coordinate: ReadCoordinate) {\n    this.store = store;\n    this.coordinate = coordinate;\n\n    // `identity` is typed by {@link ViewIdentityAccess} on the view aliases, so\n    // it is present only for graphs that declared `identity: { ... }` — a class\n    // member could not be conditional that way. Installing it here keeps the\n    // runtime accessor (and its IDENTITY_NOT_ENABLED refusal for JS callers)\n    // while leaving the class type free of an always-present member. Mirrors\n    // the `search` backstop on RecordedStoreView.\n    Object.defineProperty(this, \"identity\", {\n      enumerable: false,\n      get: (): IdentityReadFacade<G> =>\n        storeRuntime(this.store).identityAtCoordinate(this.coordinate),\n    });\n  }\n\n  /** The temporal mode this view reads in. */\n  get mode(): TemporalMode {\n    return this.coordinate.valid.mode;\n  }\n\n  /** The pinned valid-time `asOf` timestamp, or `undefined` for other modes. */\n  get asOf(): string | undefined {\n    return this.coordinate.valid.asOf;\n  }\n\n  /**\n   * A query builder pinned to this view's coordinate. The temporal axis is\n   * sealed: calling `.temporal(...)` on the returned builder throws, so the\n   * view's coordinate cannot be overridden on a per-query basis.\n   */\n  query(): InitialQueryBuilder<G, \"sealed\"> {\n    return storeRuntime(this.store).sealedQuery(this.coordinate);\n  }\n\n  protected internalAlgorithms(): InternalGraphAlgorithms<G> {\n    this.#internalAlgorithms ??= storeRuntime(\n      this.store,\n    ).algorithmsAtCoordinate(this.coordinate);\n    return this.#internalAlgorithms;\n  }\n\n  /** Graph algorithms pinned to this view's immutable temporal coordinate. */\n  get algorithms(): StoreViewGraphAlgorithms<G> {\n    this.#algorithmFacade ??= Object.freeze({\n      shortestPath: (from, to, options) => this.shortestPath(from, to, options),\n      weightedShortestPath: (from, to, options) =>\n        this.weightedShortestPath(from, to, options),\n      reachable: (from, options) => this.reachable(from, options),\n      canReach: (from, to, options) => this.canReach(from, to, options),\n      neighbors: (node, options) => this.neighbors(node, options),\n      degree: (node, options) => this.degree(node, options),\n      labelPropagation: (options) => this.labelPropagation(options),\n      weaklyConnectedComponents: (options) =>\n        this.weaklyConnectedComponents(options),\n      pageRank: (options) => this.pageRank(options),\n      personalizedPageRank: (options) => this.personalizedPageRank(options),\n    });\n    return this.#algorithmFacade;\n  }\n\n  /** Extracts a subgraph at this view's pinned coordinate. */\n  subgraph<\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: StoreViewSubgraphOptions<G, EK, NK, P>,\n  ): Promise<SubgraphResult<G, NK, EK, P>> {\n    const internalOptions = {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    } as InternalSubgraphOptions<G, EK, NK, P>;\n    return storeRuntime(this.store).subgraphAtCoordinate(\n      rootId,\n      internalOptions,\n    );\n  }\n\n  /** Shortest path between two nodes at this view's pinned coordinate. */\n  shortestPath(\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewShortestPathOptions<G>,\n  ): Promise<ShortestPathResult | undefined> {\n    return this.internalAlgorithms().shortestPath(from, to, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Minimum-total-weight path at this view's pinned coordinate. */\n  weightedShortestPath(\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewWeightedShortestPathOptions<G>,\n  ): Promise<WeightedShortestPathResult | undefined> {\n    return this.internalAlgorithms().weightedShortestPath(from, to, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Nodes reachable from `from` at this view's pinned coordinate. */\n  reachable(\n    from: NodeIdentifier,\n    options: StoreViewReachableOptions<G>,\n  ): Promise<readonly ReachableNode[]> {\n    return this.internalAlgorithms().reachable(from, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Whether `to` is reachable from `from` at this view's pinned coordinate. */\n  canReach(\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: StoreViewCanReachOptions<G>,\n  ): Promise<boolean> {\n    return this.internalAlgorithms().canReach(from, to, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** The k-hop neighborhood of `node` at this view's pinned coordinate. */\n  neighbors(\n    node: NodeIdentifier,\n    options: StoreViewNeighborsOptions<G>,\n  ): Promise<readonly ReachableNode[]> {\n    return this.internalAlgorithms().neighbors(node, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Counts active edges incident to `node` at this view's pinned coordinate. */\n  degree(\n    node: NodeIdentifier,\n    options?: StoreViewDegreeOptions<G>,\n  ): Promise<number> {\n    return this.internalAlgorithms().degree(node, {\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Deterministic label-propagation memberships at this view's coordinate. */\n  labelPropagation(\n    options: StoreViewLabelPropagationOptions<G>,\n  ): Promise<readonly LabelPropagationMembership[]> {\n    return this.internalAlgorithms().labelPropagation({\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Exact WCC memberships at this view's pinned coordinate. */\n  weaklyConnectedComponents(\n    options: StoreViewWeaklyConnectedComponentsOptions<G>,\n  ): Promise<readonly WeaklyConnectedComponentMembership[]> {\n    return this.internalAlgorithms().weaklyConnectedComponents({\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Global PageRank scores at this view's pinned coordinate. */\n  pageRank(\n    options: StoreViewPageRankOptions<G>,\n  ): Promise<readonly PageRankScore[]> {\n    return this.internalAlgorithms().pageRank({\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n\n  /** Personalized PageRank scores at this view's pinned coordinate. */\n  personalizedPageRank(\n    options: StoreViewPersonalizedPageRankOptions<G>,\n  ): Promise<readonly PageRankScore[]> {\n    return this.internalAlgorithms().personalizedPageRank({\n      ...options,\n      ...withCoordinate(this.coordinate),\n    });\n  }\n}\n\n// ============================================================\n// StoreView\n// ============================================================\n\n/** The runtime half of {@link StoreView}; see that alias for the contract. */\nclass StoreViewImplementation<\n  G extends GraphDef,\n> extends CoordinatePinnedView<G> {\n  #nodes: StoreViewNodeCollections<G> | undefined;\n  #edges: StoreViewEdgeCollections<G> | undefined;\n  #search: StoreSearch<G> | undefined;\n\n  constructor(\n    store: Store<G>,\n    coordinate: StoreViewCoordinate | ReadCoordinate,\n  ) {\n    super(\n      store,\n      isReadCoordinate(coordinate) ? coordinate : (\n        resolveReadCoordinate(\n          coordinate.mode,\n          coordinate.asOf,\n          'Use store.asOf(\"2026-01-01T00:00:00.000Z\") or store.view({ mode: \"asOf\", asOf }).',\n        )\n      ),\n    );\n  }\n\n  /** Dynamic endpoint reads remain bound to this view's coordinate. */\n  getEdgeCollection<K extends EdgeKinds<G>>(\n    kind: K,\n  ): DynamicStoreViewEdgeCollection<G[\"edges\"][K][\"type\"]> | undefined;\n  getEdgeCollection(kind: string): DynamicStoreViewEdgeCollection | undefined;\n  getEdgeCollection(kind: string): unknown {\n    if (this.store.getEdgeCollection(kind) === undefined) return undefined;\n    return this.edges[kind as EdgeKinds<G>];\n  }\n\n  /** Adds a recorded-time pin, returning the narrow reconstructing view. */\n  asOfRecorded(recordedAsOf: RecordedInstant): RecordedStoreView<G> {\n    return new RecordedStoreView(\n      this.store,\n      withRecordedCoordinate(this.coordinate, recordedAsOf),\n    );\n  }\n\n  /** Read-only node collections pinned to this view's coordinate. */\n  get nodes(): StoreViewNodeCollections<G> {\n    this.#nodes ??= pinnedNodeCollectionsFor(\n      this.store,\n      this.coordinate,\n      (_kind, live: NodeCollection<NodeType, string>, coordinate) =>\n        pinnedNodeCollection(live, coordinate),\n    ) as unknown as StoreViewNodeCollections<G>;\n    return this.#nodes;\n  }\n\n  /** Read-only edge collections pinned to this view's coordinate. */\n  get edges(): StoreViewEdgeCollections<G> {\n    this.#edges ??= pinnedEdgeCollectionsFor(\n      this.store,\n      this.coordinate,\n      (\n        _kind,\n        live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n        coordinate,\n      ) => pinnedEdgeCollection(live, coordinate),\n    ) as unknown as StoreViewEdgeCollections<G>;\n    return this.#edges;\n  }\n\n  /** Heterogeneous multi-kind edge read pinned to this view's coordinate. */\n  bulkFindEdgesFrom<const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesFromParams<G, K>,\n    options?: Omit<EdgeBulkFindEndpointOptions, \"temporalMode\" | \"asOf\">,\n  ): Promise<readonly BulkFindEdgesFromResult<G, K>[]> {\n    return this.store.bulkFindEdgesFrom(params, {\n      ...options,\n      ...withValidCoordinate(this.coordinate),\n    });\n  }\n\n  /** Inbound multi-kind edge read pinned to this view's coordinate. */\n  bulkFindEdgesTo<const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesToParams<G, K>,\n    options?: Omit<EdgeBulkFindEndpointOptions, \"temporalMode\" | \"asOf\">,\n  ): Promise<readonly BulkFindEdgesToResult<G, K>[]> {\n    return this.store.bulkFindEdgesTo(params, {\n      ...options,\n      ...withValidCoordinate(this.coordinate),\n    });\n  }\n\n  /**\n   * Read-only search facade. On a `current` view the read methods\n   * (`fulltext` / `vector` / `hybrid`) delegate to the live `store.search`,\n   * while the mutating `rebuildFulltext` is refused — the view is read-only.\n   * On any non-`current` pin every search method refuses: the fulltext /\n   * vector index reflects current state only, so historical relevance is\n   * out of scope.\n   */\n  get search(): StoreSearch<G> {\n    this.#search ??= pinnedSearch<G>(this.store, this.coordinate);\n    return this.#search;\n  }\n}\n\n/**\n * A read-only `(mode, asOf)` lens over a {@link Store}. Construct one via\n * {@link Store.asOf} (valid-time) or {@link Store.view} (any public\n * mode), never directly.\n *\n * Carries `identity` — pinned identity reads — only when the graph declared\n * `identity: { ... }`. That conditional presence is why this is a type alias\n * over an implementation class plus {@link ViewIdentityAccess} rather than a\n * class declaration, which would put the member on every graph's view.\n * `instanceof StoreView` still works.\n *\n * @example\n * ```typescript\n * const past = store.asOf(\"2026-01-01T00:00:00.000Z\");\n * const alice = await past.nodes.Person.getById(aliceId);\n * const jobs = await past.edges.worksAt.findFrom(alice!);\n * const reach = await past.reachable(alice!, { edges: [\"knows\"] });\n * ```\n */\nexport type StoreView<G extends GraphDef> = StoreViewImplementation<G> &\n  ViewIdentityAccess<G>;\n\nexport const StoreView = StoreViewImplementation as unknown as new <\n  G extends GraphDef,\n>(\n  store: Store<G>,\n  coordinate: StoreViewCoordinate | ReadCoordinate,\n) => StoreView<G>;\n\n/**\n * The runtime half of {@link RecordedStoreView}; see that alias for the\n * contract.\n */\nclass RecordedStoreViewImplementation<\n  G extends GraphDef,\n> extends CoordinatePinnedView<G> {\n  #nodes: RecordedStoreViewNodeCollections<G> | undefined;\n  #edges: RecordedStoreViewEdgeCollections<G> | undefined;\n\n  constructor(store: Store<G>, coordinate: ReadCoordinate) {\n    super(store, coordinate);\n    if (!store.recordedReadBound) {\n      throw new ConfigurationError(\n        \"asOfRecorded() requires a recorded read relation.\",\n        { code: \"ASOF_RECORDED_REQUIRES_BINDING\" },\n        {\n          suggestion:\n            \"Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n        },\n      );\n    }\n    if (coordinate.recorded === undefined) {\n      throw new ConfigurationError(\n        \"RecordedStoreView requires a recorded-time coordinate.\",\n        { code: \"RECORDED_STORE_VIEW_MISSING_COORDINATE\" },\n      );\n    }\n    // Both `store.asOfRecorded(...)` and `store.asOf(...).asOfRecorded(...)`\n    // construct a RecordedStoreView here, so this is the one place every\n    // asOfRecorded anchor is checked against this store's own recorded-time\n    // ownership before any read compiles.\n    assertRecordedInstantOwnershipMatch(\n      store.recordedTimeOwnership,\n      coordinate.recorded.asOf,\n      \"asOfRecorded\",\n    );\n\n    // `search` is intentionally absent from the typed recorded surface (a TS\n    // caller gets a compile error). It is installed here as a runtime-only\n    // backstop — invisible to the class type — so a JS caller reaching past the\n    // types gets a clear refusal rather than a bare `TypeError`. The fulltext /\n    // vector index reflects current state only and cannot answer a\n    // recorded-time query; the facade refuses every method. Mirrors the\n    // per-collection runtime refusals ({@link recordedCollectionProxy}).\n    let searchBackstop: StoreSearch<G> | undefined;\n    Object.defineProperty(this, \"search\", {\n      enumerable: false,\n      get(): StoreSearch<G> {\n        searchBackstop ??= recordedSearch<G>(coordinate);\n        return searchBackstop;\n      },\n    });\n  }\n\n  /** The recorded/system-time anchor this view reconstructs. */\n  get asOfRecorded(): RecordedInstant {\n    const recorded = this.coordinate.recorded;\n    if (recorded === undefined) {\n      throw new ConfigurationError(\n        \"RecordedStoreView requires a recorded-time coordinate.\",\n        { code: \"RECORDED_STORE_VIEW_MISSING_COORDINATE\" },\n      );\n    }\n    return recorded.asOf;\n  }\n\n  /** Recorded-time node reconstructing-read collections. */\n  get nodes(): RecordedStoreViewNodeCollections<G> {\n    this.#nodes ??= pinnedNodeCollectionsFor(\n      this.store,\n      this.coordinate,\n      (kind, live: NodeCollection<NodeType, string>, coordinate) =>\n        recordedNodeCollection(this.store, kind, live, coordinate),\n    ) as unknown as RecordedStoreViewNodeCollections<G>;\n    return this.#nodes;\n  }\n\n  /** Recorded-time edge reconstructing-read collections. */\n  get edges(): RecordedStoreViewEdgeCollections<G> {\n    this.#edges ??= pinnedEdgeCollectionsFor(\n      this.store,\n      this.coordinate,\n      (\n        kind,\n        live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n        coordinate,\n      ) => recordedEdgeCollection(this.store, kind, live, coordinate),\n    ) as unknown as RecordedStoreViewEdgeCollections<G>;\n    return this.#edges;\n  }\n}\n\n/**\n * A narrow recorded-time read lens. It preserves the valid-time coordinate\n * carried by the source view and adds a recorded/system-time pin. Collection\n * reads expose point reconstruction and bounded scans; broad collection\n * predicates, endpoint reads, search, and further coordinate changes are absent\n * from the typed surface and refused by the runtime proxies for JS callers.\n *\n * Like {@link StoreView}, an alias over an implementation class so `identity`\n * is present only for identity-enabled graphs.\n */\nexport type RecordedStoreView<G extends GraphDef> =\n  RecordedStoreViewImplementation<G> & ViewIdentityAccess<G>;\n\nexport const RecordedStoreView =\n  RecordedStoreViewImplementation as unknown as new <G extends GraphDef>(\n    store: Store<G>,\n    coordinate: ReadCoordinate,\n  ) => RecordedStoreView<G>;\n","/**\n * Path utilities for variable-length traversal results.\n *\n * SQLite doesn't support native arrays, so paths are stored as pipe-delimited\n * strings: \"|id1|id2|id3|\". PostgreSQL returns native arrays.\n */\nimport {\n  PG_ARRAY_END,\n  PG_ARRAY_START,\n  PG_PATH_ELEMENT_SEPARATOR,\n  SQLITE_PATH_DELIMITER,\n} from \"../constants\";\n\n/**\n * Parses a SQLite path string into an array of node IDs.\n *\n * @param path - Pipe-delimited path string like \"|id1|id2|id3|\"\n * @returns Array of node IDs like [\"id1\", \"id2\", \"id3\"]\n *\n * @example\n * parseSqlitePath(\"|abc|def|ghi|\") // [\"abc\", \"def\", \"ghi\"]\n * parseSqlitePath(\"|single|\") // [\"single\"]\n * parseSqlitePath(\"||\") // []\n */\nexport function parseSqlitePath(path: string): readonly string[] {\n  const emptyPath = `${SQLITE_PATH_DELIMITER}${SQLITE_PATH_DELIMITER}`;\n  if (!path || path === emptyPath) return [];\n\n  // Remove leading and trailing pipes, then split\n  const trimmed = path.slice(1, -1);\n  if (trimmed === \"\") return [];\n\n  return trimmed.split(SQLITE_PATH_DELIMITER);\n}\n\n/**\n * Type guard to check if a value is a SQLite path string.\n * SQLite paths start and end with \"|\".\n */\nexport function isSqlitePath(value: unknown): value is string {\n  return (\n    typeof value === \"string\" &&\n    value.startsWith(SQLITE_PATH_DELIMITER) &&\n    value.endsWith(SQLITE_PATH_DELIMITER)\n  );\n}\n\n/**\n * Normalizes a path value to an array.\n * - If already an array (PostgreSQL native), returns as-is\n * - If a SQLite path string (|id1|id2|), parses it\n * - If a PostgreSQL text array ({id1,id2}), parses it\n * - Otherwise returns empty array\n */\nexport function normalizePath(value: unknown): readonly string[] {\n  if (Array.isArray(value)) {\n    return value as string[];\n  }\n  if (isSqlitePath(value)) {\n    return parseSqlitePath(value);\n  }\n  if (isPostgresTextArray(value)) {\n    return parsePostgresTextArray(value);\n  }\n  return [];\n}\n\n/**\n * Separator woven into the composite `kind || SEP || id` path tokens that\n * identity-expanded traversals use for cycle detection, so folded peers (same\n * id, different kind) stay distinct. U+001F (unit separator) is a control\n * character that cannot occur in a node kind, so `kind || SEP || id` never\n * collides across distinct (kind, id) pairs the way a printable delimiter\n * could.\n */\nexport const IDENTITY_PATH_TOKEN_SEPARATOR = \"\\u001F\";\n\n/**\n * Strips the composite wrapper from identity-expanded traversal path tokens,\n * restoring the bare node ids that the public path contract promises.\n *\n * Splits at the FIRST separator: node kinds are identifier-like and cannot\n * contain U+001F, so the first occurrence is always the (kind, id) boundary and\n * everything after it is the id verbatim — including an id that itself contains\n * the separator. Tokens with no separator are returned unchanged.\n */\nexport function stripIdentityPathTokens(\n  path: readonly string[],\n): readonly string[] {\n  return path.map((token) => stripIdentityPathToken(token));\n}\n\nfunction stripIdentityPathToken(token: string): string {\n  const separatorIndex = token.indexOf(IDENTITY_PATH_TOKEN_SEPARATOR);\n  if (separatorIndex === -1) return token;\n  return token.slice(separatorIndex + IDENTITY_PATH_TOKEN_SEPARATOR.length);\n}\n\n/**\n * Type guard for PostgreSQL text array format: {id1,id2,id3}\n */\nfunction isPostgresTextArray(value: unknown): value is string {\n  return (\n    typeof value === \"string\" &&\n    value.startsWith(PG_ARRAY_START) &&\n    value.endsWith(PG_ARRAY_END)\n  );\n}\n\n/**\n * Parses a PostgreSQL text array string into an array of strings.\n * Input format: {id1,id2,id3} or {} for empty.\n */\nfunction parsePostgresTextArray(value: string): readonly string[] {\n  const inner = value.slice(1, -1);\n  if (inner === \"\") return [];\n  return inner.split(PG_PATH_ELEMENT_SEPARATOR);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport {\n  type LimitOffsetPlanNode,\n  type LogicalPlan,\n  type LogicalPlanNode,\n  type ProjectPlanNode,\n  type SortPlanNode,\n} from \"../plan\";\n\nexport type ProjectPlanShape = Readonly<{\n  hasAggregate: boolean;\n  hasFulltextMatch: boolean;\n  hasLimitOffset: boolean;\n  hasRecursiveExpand: boolean;\n  hasSetOperation: boolean;\n  hasSort: boolean;\n  hasVectorKnn: boolean;\n  limitOffsetNode: LimitOffsetPlanNode | undefined;\n  rootProjectNode: ProjectPlanNode;\n  sortNode: SortPlanNode | undefined;\n}>;\n\nexport type SetOperationPlanShape = Readonly<{\n  hasLimitOffset: boolean;\n  hasSetOperation: boolean;\n  hasSort: boolean;\n  limitOffsetNode: LimitOffsetPlanNode | undefined;\n  sortNode: SortPlanNode | undefined;\n}>;\n\nfunction collectPlanOperations(node: LogicalPlanNode, ops: Set<string>): void {\n  ops.add(node.op);\n\n  switch (node.op) {\n    case \"aggregate\":\n    case \"result_filter\":\n    case \"filter\":\n    case \"fulltext_match\":\n    case \"join\":\n    case \"limit_offset\":\n    case \"project\":\n    case \"recursive_expand\":\n    case \"sort\":\n    case \"vector_knn\": {\n      collectPlanOperations(node.input, ops);\n      return;\n    }\n    case \"set_op\": {\n      collectPlanOperations(node.left, ops);\n      collectPlanOperations(node.right, ops);\n      return;\n    }\n    case \"scan\": {\n      return;\n    }\n  }\n}\n\nfunction findUnaryNodeInProjectChain<TNode extends LogicalPlanNode>(\n  rootNode: ProjectPlanNode,\n  op: TNode[\"op\"],\n): TNode | undefined {\n  let currentNode: LogicalPlanNode = rootNode.input;\n\n  for (;;) {\n    if (currentNode.op === op) {\n      return currentNode as TNode;\n    }\n\n    switch (currentNode.op) {\n      case \"aggregate\":\n      case \"result_filter\":\n      case \"filter\":\n      case \"fulltext_match\":\n      case \"join\":\n      case \"limit_offset\":\n      case \"recursive_expand\":\n      case \"sort\":\n      case \"vector_knn\": {\n        currentNode = currentNode.input;\n        continue;\n      }\n      case \"project\":\n      case \"scan\":\n      case \"set_op\": {\n        return undefined;\n      }\n    }\n  }\n}\n\nfunction inspectProjectPlan(logicalPlan: LogicalPlan): ProjectPlanShape {\n  if (logicalPlan.root.op !== \"project\") {\n    throw new CompilerInvariantError(\n      `SQL emitter expected logical plan root to be \"project\", got \"${logicalPlan.root.op}\"`,\n      { component: \"plan-inspector\" },\n    );\n  }\n\n  const operations = new Set<string>();\n  collectPlanOperations(logicalPlan.root, operations);\n\n  const limitOffsetNode = findUnaryNodeInProjectChain<LimitOffsetPlanNode>(\n    logicalPlan.root,\n    \"limit_offset\",\n  );\n  const sortNode = findUnaryNodeInProjectChain<SortPlanNode>(\n    logicalPlan.root,\n    \"sort\",\n  );\n\n  return {\n    hasAggregate: operations.has(\"aggregate\"),\n    hasFulltextMatch: operations.has(\"fulltext_match\"),\n    hasLimitOffset: operations.has(\"limit_offset\"),\n    hasRecursiveExpand: operations.has(\"recursive_expand\"),\n    hasSetOperation: operations.has(\"set_op\"),\n    hasSort: operations.has(\"sort\"),\n    hasVectorKnn: operations.has(\"vector_knn\"),\n    limitOffsetNode,\n    rootProjectNode: logicalPlan.root,\n    sortNode,\n  };\n}\n\nexport function inspectStandardProjectPlan(\n  logicalPlan: LogicalPlan,\n): ProjectPlanShape {\n  const shape = inspectProjectPlan(logicalPlan);\n  if (shape.hasSetOperation) {\n    throw new CompilerInvariantError(\n      'Standard SQL emitter does not support plans containing \"set_op\" nodes',\n      { component: \"plan-inspector\" },\n    );\n  }\n  if (shape.hasRecursiveExpand) {\n    throw new CompilerInvariantError(\n      'Standard SQL emitter does not support plans containing \"recursive_expand\" nodes',\n      { component: \"plan-inspector\" },\n    );\n  }\n  return shape;\n}\n\nexport function inspectRecursiveProjectPlan(\n  logicalPlan: LogicalPlan,\n): ProjectPlanShape {\n  const shape = inspectProjectPlan(logicalPlan);\n  if (!shape.hasRecursiveExpand) {\n    throw new CompilerInvariantError(\n      'Recursive SQL emitter expected logical plan to contain a \"recursive_expand\" node',\n      { component: \"plan-inspector\" },\n    );\n  }\n  if (shape.hasSetOperation) {\n    throw new CompilerInvariantError(\n      'Recursive SQL emitter does not support plans containing \"set_op\" nodes',\n      { component: \"plan-inspector\" },\n    );\n  }\n  return shape;\n}\n\nfunction findTopLevelLimitOffsetNode(\n  rootNode: LogicalPlanNode,\n): LimitOffsetPlanNode | undefined {\n  let currentNode: LogicalPlanNode = rootNode;\n\n  for (;;) {\n    if (currentNode.op === \"limit_offset\") {\n      return currentNode;\n    }\n\n    switch (currentNode.op) {\n      case \"aggregate\":\n      case \"result_filter\":\n      case \"filter\":\n      case \"fulltext_match\":\n      case \"join\":\n      case \"project\":\n      case \"recursive_expand\":\n      case \"sort\":\n      case \"vector_knn\": {\n        currentNode = currentNode.input;\n        continue;\n      }\n      case \"scan\":\n      case \"set_op\": {\n        return undefined;\n      }\n    }\n  }\n}\n\nfunction findTopLevelSortNode(\n  rootNode: LogicalPlanNode,\n): SortPlanNode | undefined {\n  let currentNode: LogicalPlanNode = rootNode;\n\n  for (;;) {\n    if (currentNode.op === \"sort\") {\n      return currentNode;\n    }\n\n    switch (currentNode.op) {\n      case \"aggregate\":\n      case \"result_filter\":\n      case \"filter\":\n      case \"fulltext_match\":\n      case \"join\":\n      case \"limit_offset\":\n      case \"project\":\n      case \"recursive_expand\":\n      case \"vector_knn\": {\n        currentNode = currentNode.input;\n        continue;\n      }\n      case \"scan\":\n      case \"set_op\": {\n        return undefined;\n      }\n    }\n  }\n}\n\nexport function inspectSetOperationPlan(\n  logicalPlan: LogicalPlan,\n): SetOperationPlanShape {\n  const operations = new Set<string>();\n  collectPlanOperations(logicalPlan.root, operations);\n\n  if (!operations.has(\"set_op\")) {\n    throw new CompilerInvariantError(\n      'Set-operation SQL emitter expected logical plan to contain a \"set_op\" node',\n      { component: \"plan-inspector\" },\n    );\n  }\n\n  const limitOffsetNode = findTopLevelLimitOffsetNode(logicalPlan.root);\n  const sortNode = findTopLevelSortNode(logicalPlan.root);\n\n  return {\n    hasLimitOffset: limitOffsetNode !== undefined,\n    hasSetOperation: true,\n    hasSort: sortNode !== undefined,\n    limitOffsetNode,\n    sortNode,\n  };\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectRecursiveProjectPlan } from \"./plan-inspector\";\n\nexport type RecursiveQueryEmitterInput = Readonly<{\n  depthFilter: SqlFragment;\n  limitOffset?: SqlFragment;\n  logicalPlan: LogicalPlan;\n  orderBy?: SqlFragment;\n  /**\n   * Non-recursive CTE definitions the recursive CTE reads, in dependency order.\n   * They join the same `WITH RECURSIVE` list — both dialects accept a mix.\n   */\n  precedingCtes?: readonly SqlFragment[];\n  projection: SqlFragment;\n  recursiveCte: SqlFragment;\n  resultAlias?: string;\n}>;\n\nfunction assertRecursiveEmitterClauseAlignment(\n  logicalPlan: LogicalPlan,\n  input: RecursiveQueryEmitterInput,\n): void {\n  const planShape = inspectRecursiveProjectPlan(logicalPlan);\n  if (planShape.hasSort && input.orderBy === undefined) {\n    throw new CompilerInvariantError(\n      \"Recursive SQL emitter expected ORDER BY clause for plan containing a sort node\",\n      { component: \"recursive-emitter\" },\n    );\n  }\n  if (!planShape.hasSort && input.orderBy !== undefined) {\n    throw new CompilerInvariantError(\n      \"Recursive SQL emitter received ORDER BY clause for a plan without sort nodes\",\n      { component: \"recursive-emitter\" },\n    );\n  }\n  if (planShape.hasLimitOffset && input.limitOffset === undefined) {\n    throw new CompilerInvariantError(\n      \"Recursive SQL emitter expected LIMIT/OFFSET clause for plan containing a limit_offset node\",\n      { component: \"recursive-emitter\" },\n    );\n  }\n  if (!planShape.hasLimitOffset && input.limitOffset !== undefined) {\n    throw new CompilerInvariantError(\n      \"Recursive SQL emitter received LIMIT/OFFSET clause for a plan without limit_offset nodes\",\n      { component: \"recursive-emitter\" },\n    );\n  }\n}\n\nexport function emitRecursiveQuerySql(\n  input: RecursiveQueryEmitterInput,\n): SqlFragment {\n  assertRecursiveEmitterClauseAlignment(input.logicalPlan, input);\n\n  const cteList = sql.join(\n    [...(input.precedingCtes ?? []), input.recursiveCte],\n    sql`, `,\n  );\n  const parts: SqlFragment[] = [\n    sql`WITH RECURSIVE`,\n    cteList,\n    sql`SELECT ${input.projection}`,\n    input.resultAlias === undefined ?\n      sql`FROM recursive_cte`\n    : sql`FROM recursive_cte AS ${sql.identifier(input.resultAlias)}`,\n    input.depthFilter,\n  ];\n\n  if (input.orderBy !== undefined) {\n    parts.push(input.orderBy);\n  }\n  if (input.limitOffset !== undefined) {\n    parts.push(input.limitOffset);\n  }\n\n  return sql.join(parts, sql` `);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectSetOperationPlan } from \"./plan-inspector\";\n\nexport type SetOperationQueryEmitterInput = Readonly<{\n  baseQuery: SqlFragment;\n  ctes?: readonly SqlFragment[];\n  logicalPlan: LogicalPlan;\n  suffixClauses?: readonly SqlFragment[];\n}>;\n\nfunction assertSetOperationEmitterClauseAlignment(\n  logicalPlan: LogicalPlan,\n  suffixClauses: readonly SqlFragment[] | undefined,\n): void {\n  const shape = inspectSetOperationPlan(logicalPlan);\n  const hasSuffixClauses =\n    suffixClauses !== undefined && suffixClauses.length > 0;\n\n  if (!shape.hasSort && !shape.hasLimitOffset && hasSuffixClauses) {\n    throw new CompilerInvariantError(\n      \"Set-operation SQL emitter received suffix clauses for a plan without top-level sort or limit_offset nodes\",\n      { component: \"set-operation-emitter\" },\n    );\n  }\n\n  if (!hasSuffixClauses) {\n    if (shape.hasSort || shape.hasLimitOffset) {\n      throw new CompilerInvariantError(\n        \"Set-operation SQL emitter expected suffix clauses for plan containing top-level sort or limit_offset nodes\",\n        { component: \"set-operation-emitter\" },\n      );\n    }\n    return;\n  }\n\n  const limitOffsetClauseCount =\n    shape.limitOffsetNode === undefined ?\n      0\n    : (shape.limitOffsetNode.limit === undefined ? 0 : 1) +\n      (shape.limitOffsetNode.offset === undefined ? 0 : 1);\n  const expectedClauseCount =\n    (shape.sortNode === undefined ? 0 : 1) + limitOffsetClauseCount;\n\n  if (suffixClauses.length !== expectedClauseCount) {\n    throw new CompilerInvariantError(\n      `Set-operation SQL emitter expected ${String(expectedClauseCount)} top-level suffix clause(s) from logical plan, got ${String(suffixClauses.length)}`,\n      { component: \"set-operation-emitter\" },\n    );\n  }\n}\n\nexport function emitSetOperationQuerySql(\n  input: SetOperationQueryEmitterInput,\n): SqlFragment {\n  assertSetOperationEmitterClauseAlignment(\n    input.logicalPlan,\n    input.suffixClauses,\n  );\n\n  const parts: SqlFragment[] = [];\n  if (input.ctes !== undefined && input.ctes.length > 0) {\n    parts.push(sql`WITH ${sql.join([...input.ctes], sql`, `)}`);\n  }\n\n  parts.push(input.baseQuery);\n\n  if (input.suffixClauses !== undefined && input.suffixClauses.length > 0) {\n    parts.push(...input.suffixClauses);\n  }\n\n  return sql.join(parts, sql` `);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectStandardProjectPlan } from \"./plan-inspector\";\n\nexport type StandardQueryEmitterInput = Readonly<{\n  ctes: readonly SqlFragment[];\n  fromClause: SqlFragment;\n  where?: SqlFragment;\n  groupBy?: SqlFragment;\n  having?: SqlFragment;\n  limitOffset?: SqlFragment;\n  logicalPlan: LogicalPlan;\n  orderBy?: SqlFragment;\n  projection: SqlFragment;\n}>;\n\nfunction assertStandardEmitterClauseAlignment(\n  logicalPlan: LogicalPlan,\n  input: StandardQueryEmitterInput,\n): void {\n  const planShape = inspectStandardProjectPlan(logicalPlan);\n  if (input.groupBy !== undefined && !planShape.hasAggregate) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter received GROUP BY clause for a plan without aggregate nodes\",\n      { component: \"standard-emitter\" },\n    );\n  }\n  if (input.having !== undefined && !planShape.hasAggregate) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter received HAVING clause for a plan without aggregate nodes\",\n      { component: \"standard-emitter\" },\n    );\n  }\n  const expectsOrderBy =\n    planShape.hasSort || planShape.hasVectorKnn || planShape.hasFulltextMatch;\n  if (expectsOrderBy && input.orderBy === undefined) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter expected ORDER BY clause for plan containing a sort, vector_knn, or fulltext_match node\",\n      { component: \"standard-emitter\" },\n    );\n  }\n  if (!expectsOrderBy && input.orderBy !== undefined) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter received ORDER BY clause for a plan without sort, vector_knn, or fulltext_match nodes\",\n      { component: \"standard-emitter\" },\n    );\n  }\n  if (planShape.hasLimitOffset && input.limitOffset === undefined) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter expected LIMIT/OFFSET clause for plan containing a limit_offset node\",\n      { component: \"standard-emitter\" },\n    );\n  }\n  if (!planShape.hasLimitOffset && input.limitOffset !== undefined) {\n    throw new CompilerInvariantError(\n      \"Standard SQL emitter received LIMIT/OFFSET clause for a plan without limit_offset nodes\",\n      { component: \"standard-emitter\" },\n    );\n  }\n}\n\nexport function emitStandardQuerySql(\n  input: StandardQueryEmitterInput,\n): SqlFragment {\n  assertStandardEmitterClauseAlignment(input.logicalPlan, input);\n\n  const parts: SqlFragment[] = [];\n  if (input.ctes.length > 0) {\n    parts.push(sql`WITH ${sql.join([...input.ctes], sql`, `)}`);\n  }\n\n  parts.push(sql`SELECT ${input.projection}`, input.fromClause);\n\n  if (input.where !== undefined) parts.push(input.where);\n\n  if (input.groupBy !== undefined) {\n    parts.push(input.groupBy);\n  }\n  if (input.having !== undefined) {\n    parts.push(input.having);\n  }\n  if (input.orderBy !== undefined) {\n    parts.push(input.orderBy);\n  }\n  if (input.limitOffset !== undefined) {\n    parts.push(input.limitOffset);\n  }\n\n  return sql.join(parts, sql` `);\n}\n","/**\n * Bounding for generated SQL identifiers (column aliases, index names).\n *\n * PostgreSQL silently truncates any identifier longer than 63 *bytes* —\n * not characters — keeping only the leading bytes. Two distinct generated\n * identifiers that share a >63-byte prefix therefore collapse onto the same\n * physical name, producing an \"ambiguous column\" error or, worse, a\n * silently wrong value.\n *\n * `boundPgIdentifier` closes that gap: a name that already fits is returned\n * verbatim (short, human-readable identifiers stay readable and previously\n * emitted SQL is unchanged), and a name that does not is truncated by BYTE\n * length to leave room for a deterministic hash suffix computed from the\n * caller's FULL, untruncated input. Hashing the untruncated input is what\n * makes two colliding names diverge — the bytes truncation would discard\n * still shape the suffix.\n */\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../constants\";\nimport { fnv1aBase36 } from \"./hash\";\nimport { requireDefined } from \"./presence\";\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * Truncates a string so its UTF-8 byte length does not exceed maxBytes.\n * Avoids splitting in the middle of a multi-byte character.\n */\nexport function truncateToBytes(value: string, maxBytes: number): string {\n  const encoded = TEXT_ENCODER.encode(value);\n  if (encoded.byteLength <= maxBytes) return value;\n\n  // Walk backwards from the limit to find a clean character boundary.\n  // UTF-8 continuation bytes have the form 10xxxxxx (0x80..0xBF).\n  let end = maxBytes;\n  while (\n    end > 0 &&\n    requireDefined(encoded[end]) >= 0x80 &&\n    requireDefined(encoded[end]) < 0xc0\n  ) {\n    end--;\n  }\n\n  return new TextDecoder().decode(encoded.slice(0, end));\n}\n\n/**\n * Bounds `name` to PostgreSQL's 63-byte identifier limit.\n *\n * Returns `name` unchanged when its UTF-8 byte length already fits, so\n * short identifiers keep their exact, readable form. Otherwise the name is\n * truncated by BYTE length to leave room for `\"_\" + fnv1aBase36(hashInput)`,\n * and the hash is appended — guaranteeing the result stays within the limit\n * while distinguishing inputs that share a truncated prefix.\n *\n * `hashInput` must be the caller's full, untruncated discriminator (for\n * example `alias + \"\\0\" + field`): hashing the already-truncated `name`\n * would not disambiguate a collision.\n */\nexport function boundPgIdentifier(name: string, hashInput: string): string {\n  if (TEXT_ENCODER.encode(name).byteLength <= MAX_PG_IDENTIFIER_LENGTH) {\n    return name;\n  }\n\n  const hash = fnv1aBase36(hashInput);\n  const truncated = truncateToBytes(\n    name,\n    MAX_PG_IDENTIFIER_LENGTH - 1 - hash.length,\n  );\n  return `${truncated}_${hash}`;\n}\n","/**\n * Query AST types.\n *\n * Defines the abstract syntax tree for TypeGraph queries.\n * This portable representation can be compiled to SQL (today)\n * or other query languages (Cypher, SPARQL) in the future.\n */\nimport {\n  type KindEntity,\n  type NullCheckOp,\n  type TemporalMode,\n} from \"../core/types\";\nimport { type DatabaseExpression } from \"./expressions\";\nimport { type JsonPointer } from \"./json-pointer\";\n\n// ============================================================\n// Predicate Expressions\n// ============================================================\n\n/**\n * A field reference in a predicate.\n */\nexport type FieldRef<\n  Value = unknown,\n  Alias extends string = string,\n  Path extends readonly string[] = readonly string[],\n  PropertyPath extends readonly string[] = readonly string[],\n> = Readonly<{\n  __type: \"field_ref\";\n  alias: Alias;\n  path: Path; // [\"props\", \"name\"] or [\"id\"]\n  jsonPointer?: JsonPointer | undefined; // JSON Pointer into props\n  valueType?: ValueType | undefined;\n  elementType?: ValueType | undefined;\n  /** Whether this field can be absent in the current query row. */\n  nullable?: boolean | undefined;\n  /** @internal Carries the public value type without affecting the AST. */\n  readonly __value?: {\n    bivarianceHack(value: Value): void;\n  }[\"bivarianceHack\"];\n  /** @internal Carries the public property path without affecting the AST. */\n  readonly __propertyPath?: PropertyPath | undefined;\n}>;\n\n/**\n * A literal value in a predicate.\n */\nexport type LiteralValue = Readonly<{\n  __type: \"literal\";\n  value: string | number | boolean;\n  valueType?: ValueType | undefined;\n}>;\n\n/**\n * A parameter reference for prepared queries.\n *\n * Used in place of a literal value to create parameterized queries\n * that can be executed multiple times with different bindings.\n */\nexport type ParameterRef = Readonly<{\n  __type: \"parameter\";\n  name: string;\n  valueType?: ValueType | undefined;\n}>;\n\n/**\n * Supported value types for predicates.\n */\nexport type ValueType =\n  | \"string\"\n  | \"number\"\n  | \"boolean\"\n  | \"date\"\n  | \"array\"\n  | \"object\"\n  | \"embedding\"\n  | \"unknown\";\n\n/**\n * Comparison operators.\n */\nexport type ComparisonOp =\n  \"eq\" | \"neq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\" | \"notIn\";\n\n/**\n * String operators.\n */\nexport type StringOp =\n  \"contains\" | \"startsWith\" | \"endsWith\" | \"like\" | \"ilike\";\n\n/**\n * A comparison predicate.\n */\nexport type ComparisonPredicate = Readonly<{\n  __type: \"comparison\";\n  op: ComparisonOp;\n  left: FieldRef;\n  right: FieldRef | LiteralValue | LiteralValue[] | ParameterRef;\n}>;\n\n/** A lexicographic comparison between equally sized scalar field/value tuples. */\nexport type TupleComparisonPredicate = Readonly<{\n  __type: \"tuple_comparison\";\n  op: \"gt\" | \"lt\";\n  fields: readonly [FieldRef, ...FieldRef[]];\n  values: readonly [LiteralValue, ...LiteralValue[]];\n}>;\n\n/**\n * A string predicate.\n */\nexport type StringPredicate = Readonly<{\n  __type: \"string_op\";\n  op: StringOp;\n  field: FieldRef;\n  pattern: string | ParameterRef;\n}>;\n\n/**\n * A null check predicate.\n */\nexport type NullPredicate = Readonly<{\n  __type: \"null_check\";\n  op: NullCheckOp;\n  field: FieldRef;\n}>;\n\n/**\n * A between predicate.\n */\nexport type BetweenPredicate = Readonly<{\n  __type: \"between\";\n  field: FieldRef;\n  lower: LiteralValue | ParameterRef;\n  upper: LiteralValue | ParameterRef;\n}>;\n\n// ============================================================\n// Array Predicates\n// ============================================================\n\n/**\n * Array operators.\n */\nexport type ArrayOp =\n  | \"contains\" // Array contains a single value\n  | \"containsAll\" // Array contains all specified values\n  | \"containsAny\" // Array contains any of the specified values (overlaps)\n  | \"isEmpty\" // Array is empty\n  | \"isNotEmpty\" // Array is not empty\n  | \"lengthEq\" // Array length equals\n  | \"lengthGt\" // Array length greater than\n  | \"lengthGte\" // Array length greater than or equal\n  | \"lengthLt\" // Array length less than\n  | \"lengthLte\"; // Array length less than or equal\n\n/**\n * An array predicate.\n */\nexport type ArrayPredicate = Readonly<{\n  __type: \"array_op\";\n  op: ArrayOp;\n  field: FieldRef;\n  values?: readonly LiteralValue[]; // For contains/containsAll/containsAny\n  length?: number; // For length comparisons\n}>;\n\n// ============================================================\n// Object/JSON Predicates\n// ============================================================\n\n/**\n * Object operators.\n */\nexport type ObjectOp =\n  | \"hasKey\" // Object has a specific key at root level\n  | \"hasPath\" // Object has a nested path\n  | \"pathEquals\" // Value at path equals\n  | \"pathContains\" // Value at path contains (for nested arrays)\n  | \"pathIsNull\" // Value at path is null\n  | \"pathIsNotNull\"; // Value at path is not null\n\n/**\n * An object/JSON predicate.\n */\nexport type ObjectPredicate = Readonly<{\n  __type: \"object_op\";\n  op: ObjectOp;\n  field: FieldRef;\n  pointer: JsonPointer; // Relative JSON Pointer\n  value?: LiteralValue; // For pathEquals, pathContains\n  valueType?: ValueType;\n  elementType?: ValueType;\n}>;\n\n/**\n * Logical AND predicate.\n */\ntype AndPredicate = Readonly<{\n  __type: \"and\";\n  predicates: readonly PredicateExpression[];\n}>;\n\n/**\n * Logical OR predicate.\n */\ntype OrPredicate = Readonly<{\n  __type: \"or\";\n  predicates: readonly PredicateExpression[];\n}>;\n\n/**\n * Logical NOT predicate.\n */\ntype NotPredicate = Readonly<{\n  __type: \"not\";\n  predicate: PredicateExpression;\n}>;\n\n/** A typed Boolean database expression used as a SQL predicate. */\ntype DatabaseExpressionPredicate = Readonly<{\n  __type: \"database_expression_predicate\";\n  expression: DatabaseExpression<boolean | undefined>;\n}>;\n\n/**\n * An aggregate comparison predicate (for HAVING clauses).\n */\nexport type AggregateComparisonPredicate = Readonly<{\n  __type: \"aggregate_comparison\";\n  op: ComparisonOp;\n  aggregate: AggregateExpr;\n  value: LiteralValue;\n}>;\n\n// ============================================================\n// Subquery Predicates\n// ============================================================\n\n/**\n * An EXISTS subquery predicate.\n * Tests whether the subquery returns any rows.\n */\nexport type ExistsSubquery = Readonly<{\n  __type: \"exists\";\n  subquery: QueryAst;\n  negated: boolean; // for NOT EXISTS\n}>;\n\n/**\n * An IN subquery predicate.\n * Tests whether a field value is in the subquery results.\n */\nexport type InSubquery = Readonly<{\n  __type: \"in_subquery\";\n  field: FieldRef;\n  subquery: QueryAst;\n  negated: boolean; // for NOT IN\n}>;\n\n// ============================================================\n// Vector Predicates\n// ============================================================\n\n/**\n * Vector similarity metric types.\n */\nexport type VectorMetricType = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * A vector similarity predicate.\n * Finds nodes with embeddings similar to the query embedding.\n *\n * This predicate affects query execution by:\n * - Joining with the embeddings table\n * - Adding ORDER BY distance (ascending)\n * - Applying LIMIT (top k results)\n * - Optionally filtering by minimum score\n */\nexport type VectorSimilarityPredicate = Readonly<{\n  __type: \"vector_similarity\";\n  /** The embedding field reference */\n  field: FieldRef;\n  /** The query embedding to compare against */\n  queryEmbedding: readonly number[];\n  /**\n   * Similarity metric. Omitted when the caller didn't pass one — the compiler\n   * then uses the field's DECLARED `embedding()` metric (resolved per kind),\n   * falling back to \"cosine\" only when no declaration is available.\n   */\n  metric?: VectorMetricType;\n  /** Maximum number of results to return */\n  limit: number;\n  /** Optional minimum similarity score (0-1 for cosine) */\n  minScore?: number;\n  /**\n   * Retrieve each kind's candidates via the engine's native ANN structure\n   * instead of an exact distance scan (see `SimilarToOptions.approximate`).\n   */\n  approximate?: boolean;\n}>;\n\n// ============================================================\n// Fulltext Predicates\n// ============================================================\n\nimport type { FulltextQueryMode } from \"../backend/types\";\n\n/**\n * A fulltext MATCH predicate.\n *\n * Finds nodes whose combined searchable content matches the query. Affects\n * query execution by joining with the fulltext table, adding an ORDER BY\n * on relevance rank (descending), and applying a LIMIT (top k).\n */\nexport type FulltextMatchPredicate = Readonly<{\n  __type: \"fulltext_match\";\n  /**\n   * Reserved for forward compatibility with per-field fulltext dispatch.\n   * Today only `field.alias` is consumed: the MATCH always targets the\n   * combined `content` column, so `field.path` is a synthetic\n   * `[\"$fulltext\"]` marker rather than a real props path. Future\n   * strategies (per-field indexes, `setweight()`-style boosts) can use\n   * the full `FieldRef` without breaking the AST shape.\n   */\n  field: FieldRef;\n  /** The user-supplied query string. */\n  query: string;\n  /** Parse mode for the query string. Default: \"websearch\". */\n  mode: FulltextQueryMode;\n  /** Language override for query parsing. */\n  language?: string;\n  /** Maximum number of results to return. */\n  limit: number;\n  /** Minimum relevance to include (backend-native units). */\n  minScore?: number;\n}>;\n\n/**\n * Fusion options for hybrid (vector + fulltext) queries.\n *\n * Shared between:\n * - Query-builder path: `QueryBuilder.fuseWith()` stores this on `QueryAst`.\n * - Store path: `store.search.hybrid(kind, { fusion })` accepts the same shape.\n *\n * Only applied when the query contains both a vector and a fulltext\n * predicate. Defaults (when omitted): RRF with k=60 and equal weights.\n */\nexport type HybridFusionOptions = Readonly<{\n  /** RRF is the only currently supported fusion method. */\n  method?: \"rrf\";\n  /** RRF constant. The classic value is 60. */\n  k?: number;\n  /** Per-source weights. Default: { vector: 1, fulltext: 1 }. */\n  weights?: Readonly<{\n    vector?: number;\n    fulltext?: number;\n  }>;\n}>;\n\n/**\n * Classic RRF constant. Shared by the store-level JS fusion in\n * `store.search.hybrid` and the SQL emitter — keep both paths reading\n * the same number so their top-k never drifts on ties.\n */\nexport const DEFAULT_RRF_K = 60;\n\n/** Default per-source RRF weight when none is supplied. */\nexport const DEFAULT_RRF_WEIGHT = 1;\n\n/**\n * All predicate expression types.\n */\nexport type PredicateExpression =\n  | ComparisonPredicate\n  | TupleComparisonPredicate\n  | StringPredicate\n  | NullPredicate\n  | BetweenPredicate\n  | ArrayPredicate\n  | ObjectPredicate\n  | AndPredicate\n  | OrPredicate\n  | NotPredicate\n  | AggregateComparisonPredicate\n  | ExistsSubquery\n  | InSubquery\n  | VectorSimilarityPredicate\n  | FulltextMatchPredicate\n  | DatabaseExpressionPredicate;\n\n// ============================================================\n// Query Start\n// ============================================================\n\n/**\n * The starting point of a query (the FROM clause).\n */\ntype QueryStart = Readonly<{\n  alias: string;\n  kinds: readonly string[]; // Expanded via ontology if includeSubClasses\n  includeSubClasses: boolean;\n}>;\n\n// ============================================================\n// Traversals\n// ============================================================\n\n/**\n * Direction of edge traversal.\n */\nexport type TraversalDirection = \"out\" | \"in\";\n\n/**\n * Traversal ontology expansion behavior.\n *\n * - `\"none\"` — follow only the exact edge kind specified\n * - `\"implying\"` — also follow edge kinds that imply the specified kind (subClassOf)\n * - `\"inverse\"` — also follow the ontological inverse edge kind (inverseOf)\n * - `\"all\"` — follow both implying and inverse expansions\n */\nexport type TraversalExpansion = \"none\" | \"implying\" | \"inverse\" | \"all\";\n\n/**\n * Cycle handling policy for recursive traversals.\n */\nexport type RecursiveCyclePolicy = \"prevent\" | \"allow\";\n\n/**\n * Variable-length traversal specification for recursive graph traversals.\n */\nexport type VariableLengthSpec = Readonly<{\n  /** Minimum number of hops before including results (default: 1) */\n  minDepth: number;\n  /** Maximum number of hops (-1 = unlimited, default: -1) */\n  maxDepth: number;\n  /**\n   * Cycle handling mode.\n   *\n   * - \"prevent\": Track visited nodes per path and reject revisits\n   * - \"allow\": Skip cycle checks (faster, may revisit nodes)\n   */\n  cyclePolicy: RecursiveCyclePolicy;\n  /** Optional column alias for projected traversal path array */\n  pathAlias?: string;\n  /** Qualified paths include alternating node and edge references. */\n  pathFormat?: \"qualified\";\n  /** Optional column alias for projected traversal depth */\n  depthAlias?: string;\n  /** Stop expanding a matching node, optionally omitting that node from results. */\n  stopExpansion?: Readonly<{\n    expression: PredicateExpression;\n    emitStopNode: boolean;\n  }>;\n}>;\n\n/**\n * A traversal step in the query.\n */\nexport type Traversal = Readonly<{\n  edgeAlias: string;\n  edgeKinds: readonly string[]; // Expanded via ontology based on traversal expand mode\n  /**\n   * Edge kinds traversed in the opposite direction.\n   *\n   * Populated when query options request inverse/symmetric expansion.\n   */\n  inverseEdgeKinds?: readonly string[];\n  direction: TraversalDirection;\n  nodeAlias: string;\n  nodeKinds: readonly string[];\n  joinFromAlias: string;\n  joinEdgeField: \"from_id\" | \"to_id\";\n  /** If true, use LEFT JOIN instead of INNER JOIN (optional match) */\n  optional: boolean;\n  /** Expand this hop through coordinate-visible Operational Identity members. */\n  includeIdentityMembers?: boolean;\n  /** Variable-length traversal configuration (for recursive CTEs) */\n  variableLength?: VariableLengthSpec;\n}>;\n\n/**\n * Returns the full set of edge kind names for a traversal, merging\n * forward and inverse kinds with deduplication.\n */\nexport function mergeEdgeKinds(traversal: Traversal): readonly string[] {\n  const inverse = traversal.inverseEdgeKinds;\n  if (inverse === undefined || inverse.length === 0) return traversal.edgeKinds;\n\n  return [\n    ...traversal.edgeKinds,\n    ...inverse.filter((kind) => !traversal.edgeKinds.includes(kind)),\n  ];\n}\n\n// ============================================================\n// Aggregations\n// ============================================================\n\n/**\n * Supported aggregate functions.\n */\ntype AggregateFunction =\n  \"count\" | \"countDistinct\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\n/**\n * An aggregate expression.\n */\nexport type AggregateExpr<\n  Function extends AggregateFunction = AggregateFunction,\n  Field extends FieldRef = FieldRef,\n> = Readonly<{\n  __type: \"aggregate\";\n  function: Function;\n  field: Field;\n}>;\n\n/**\n * A GROUP BY specification.\n */\nexport type GroupBySpec = Readonly<{\n  fields: readonly (DatabaseExpression | FieldRef)[];\n}>;\n\n// ============================================================\n// Projections\n// ============================================================\n\n/**\n * A projected field in the SELECT clause.\n * Can be either a direct field reference or an aggregate expression.\n */\nexport type ProjectedField = Readonly<{\n  outputName: string;\n  source: AggregateExpr | DatabaseExpression | FieldRef;\n  /** Override the CTE alias for this field (used for edge fields in node CTEs) */\n  cteAlias?: string;\n}>;\n\n/**\n * The projection (SELECT) clause.\n */\nexport type Projection = Readonly<{\n  fields: readonly ProjectedField[];\n}>;\n\n/**\n * A selectively projected field for optimized queries.\n *\n * Used when the select callback only accesses specific fields,\n * allowing the compiler to generate optimized SQL that fetches\n * only those fields instead of the full props blob.\n */\nexport type SelectiveField = Readonly<{\n  /** The alias (node or edge) this field belongs to */\n  alias: string;\n  /** The field name (e.g., \"email\", \"name\", \"id\") */\n  field: string;\n  /** The output column name in the result (e.g., \"p_email\") */\n  outputName: string;\n  /** True if this is a system field (id, kind, etc.), false for props */\n  isSystemField: boolean;\n  /**\n   * Optional value type for props fields.\n   *\n   * When present, the compiler can use type-aware JSON extraction\n   * (e.g. numeric/date casts) to better match predicate compilation\n   * and enable expression index coverage.\n   */\n  valueType?: ValueType | undefined;\n}>;\n\n// ============================================================\n// Ordering\n// ============================================================\n\n/**\n * Null ordering preference.\n */\ntype NullOrdering = \"first\" | \"last\";\n\n/**\n * Sort direction.\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * An ordering specification.\n */\nexport type OrderSpec = Readonly<{\n  field: DatabaseExpression | FieldRef;\n  direction: SortDirection;\n  nulls?: NullOrdering;\n}>;\n\n/**\n * An ordering specification for aggregate queries.\n *\n * Unlike {@link OrderSpec}, this references a projected SELECT-list output\n * column by name rather than a `FieldRef` into a source table/CTE. Aggregate\n * query projections always assign an output alias to every grouped field\n * and aggregate expression (via `.aggregate({ outputName: ... })`), so\n * ordering by that alias works uniformly for both — and both SQLite and\n * PostgreSQL allow `ORDER BY` to reference a SELECT-list alias directly, so\n * no re-derivation of the underlying expression (and no dialect seam) is\n * needed.\n */\nexport type AggregateOrderSpec = Readonly<{\n  outputName: string;\n  direction: SortDirection;\n  nulls?: NullOrdering;\n}>;\n\n// ============================================================\n// Node Predicate\n// ============================================================\n\n/**\n * A predicate applied to a specific node or edge alias.\n */\nexport type NodePredicate = Readonly<{\n  targetAlias: string;\n  /** Whether this predicate targets a node or edge. Defaults to \"node\". */\n  targetType?: KindEntity;\n  expression: PredicateExpression;\n}>;\n\n// ============================================================\n// Temporal Options\n// ============================================================\n\n/**\n * Temporal query options.\n */\ntype TemporalOptions = Readonly<{\n  mode: TemporalMode;\n  asOf?: string;\n}>;\n\n// ============================================================\n// Query AST\n// ============================================================\n\n/**\n * The complete query AST.\n */\nexport type QueryAst = Readonly<{\n  /** Runtime identity for validating expression and outer-reference scope. */\n  expressionScope?: symbol;\n  /** The graph ID this query is for (used for subqueries) */\n  graphId?: string;\n  start: QueryStart;\n  traversals: readonly Traversal[];\n  predicates: readonly NodePredicate[];\n  /** Filters completed match rows, after expansion/candidate generation and before grouping/ranges. */\n  resultPredicate?: PredicateExpression;\n  projection: Projection;\n  temporalMode: TemporalOptions;\n  /** Recorded/system-time timestamp for recorded-pinned reads. */\n  recordedAsOf?: string;\n  orderBy?: readonly OrderSpec[];\n  limit?: number;\n  offset?: number;\n  /** GROUP BY specification for aggregate queries */\n  groupBy?: GroupBySpec;\n  /** HAVING clause - predicates applied after GROUP BY */\n  having?: PredicateExpression;\n  /**\n   * ORDER BY specification for aggregate queries, referencing projected\n   * output aliases (grouped fields or aggregate expressions) instead of\n   * source-table field refs. See {@link AggregateOrderSpec}.\n   */\n  aggregateOrderBy?: readonly AggregateOrderSpec[];\n  /**\n   * Selective fields for optimized queries.\n   * When present, the compiler generates SQL that only fetches these specific\n   * fields instead of the full props blob, enabling covered index usage.\n   */\n  selectiveFields?: readonly SelectiveField[];\n  /** Fusion options for hybrid queries. Ignored unless both predicates present. */\n  fusion?: HybridFusionOptions;\n}>;\n\n// ============================================================\n// Set Operations\n// ============================================================\n\n/**\n * Set operation types for combining queries.\n */\nexport type SetOperationType = \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n\n/**\n * A set operation combining two queries.\n */\nexport type SetOperation = Readonly<{\n  __type: \"set_operation\";\n  operator: SetOperationType;\n  left: ComposableQuery;\n  right: ComposableQuery;\n  orderBy?: readonly OrderSpec[];\n  limit?: number;\n  offset?: number;\n}>;\n\n/**\n * A composable query - either a base query or a set operation.\n */\nexport type ComposableQuery = QueryAst | SetOperation;\n","import { isEngineNativeRecordedReadBinding } from \"../../backend/capabilities/recorded-time-ownership\";\nimport { optionalRecordedInstantParts } from \"../../core/temporal\";\nimport {\n  historicalIdentityPeerClassQuery,\n  type HistoricalIdentitySqlCoordinate,\n  IDENTITY_PEER_CLASS_COLUMNS,\n  refuseEngineNativeRecordedIdentityRead,\n} from \"../../identity/historical-sql\";\nimport { type QueryAst } from \"../ast\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { type TemporalFilterPass } from \"./passes\";\nimport {\n  type PredicateCompilerContext,\n  requireRecursiveTraversalVerdict,\n} from \"./predicates\";\n\n/**\n * Name of the query-level relation holding the identity classes a **historical**\n * traversal expands through. One per statement: the relation depends only on the\n * graph, the read coordinate and the identity profile, so every traversal step of\n * a query shares it.\n */\nexport const IDENTITY_CLASS_CTE_ALIAS = \"identity_peer_class\";\n\n/** Alias the frontier expansion gives the peer members of a frontier row's class. */\nconst PEER_CLASS_ALIAS = \"identity_peer\";\n\n/** Alias of the closure row naming the class a current-coordinate frontier row is in. */\nconst CURRENT_SEED_CLASS_ALIAS = \"identity_seed_class\";\n\n/** Alias of the node row a current-coordinate member is checked visible through. */\nconst CURRENT_MEMBER_NODE_ALIAS = \"identity_peer_node\";\n\n/**\n * Resolves the read coordinate an identity reconstruction must be evaluated at,\n * or `undefined` when the query reads the present and can therefore reach the\n * maintained closure directly.\n *\n * Sole owner of the current/historical split: {@link compileIdentityClassCte}\n * and {@link planIdentityFrontierExpansion} pick opposite strategies off this one\n * answer, and a query whose CTE and whose traversal steps disagreed about the\n * coordinate would compile a step reading a relation that was never emitted.\n */\nfunction historicalCoordinate(\n  input: Readonly<{\n    ast: QueryAst;\n    ctx: PredicateCompilerContext;\n    temporalFilterPass: TemporalFilterPass;\n  }>,\n): HistoricalIdentitySqlCoordinate | undefined {\n  const { ast, ctx, temporalFilterPass } = input;\n  const recorded = optionalRecordedInstantParts(\n    ast.recordedAsOf,\n    \"recordedAsOf\",\n  );\n  if (recorded === undefined && ast.temporalMode.mode === \"current\") {\n    return undefined;\n  }\n  if (\n    recorded !== undefined &&\n    isEngineNativeRecordedReadBinding(ctx.recordedReadBinding)\n  ) {\n    refuseEngineNativeRecordedIdentityRead(\"historical identity expansion\");\n  }\n  return {\n    validMode: ast.temporalMode.mode,\n    validAsOf: ast.temporalMode.asOf,\n    recorded,\n    currentInstant: temporalFilterPass.currentInstant,\n  };\n}\n\n/**\n * Emits the query-level CTE definition backing **historical** identity expansion,\n * or `undefined` when the query expands no identity or reads the present.\n *\n * A past coordinate has no closure to read — the relation has to be\n * reconstructed from the assertion ledger (see\n * {@link historicalIdentityPeerClassQuery}), which is a recursive fixed point\n * over the whole ledger no frontier row can narrow. Paying for it once per\n * statement rather than once per traversal step is what typegraph#310 bought, so\n * it stays hoisted and materialized. The current coordinate needs no such\n * relation: the closure is already the answer, and\n * {@link planIdentityFrontierExpansion} seeks into it from the frontier instead.\n *\n * Callers must place the definition ahead of the traversal relations that read\n * it. It depends on no other CTE, so the head of the `WITH` list is always\n * valid.\n */\nexport function compileIdentityClassCte(\n  input: Readonly<{\n    ast: QueryAst;\n    ctx: PredicateCompilerContext;\n    graphId: string;\n    temporalFilterPass: TemporalFilterPass;\n  }>,\n): SqlFragment | undefined {\n  const { ast, ctx, graphId, temporalFilterPass } = input;\n  const expandsIdentity = ast.traversals.some(\n    (traversal) => traversal.includeIdentityMembers === true,\n  );\n  if (!expandsIdentity) return undefined;\n  const coordinate = historicalCoordinate({ ast, ctx, temporalFilterPass });\n  if (coordinate === undefined) return undefined;\n\n  const recursiveTraversal = requireRecursiveTraversalVerdict(\n    ctx,\n    \"historical identity expansion\",\n  );\n  const peerClasses = historicalIdentityPeerClassQuery({\n    schema: ctx.schema,\n    graphId,\n    coordinate,\n    sameIdAcrossKinds: ctx.identitySameIdAcrossKinds ?? \"fold\",\n    recursiveTraversal,\n  });\n  // MATERIALIZED is load-bearing, not a hint. Left inlinable, SQLite pushes the\n  // relation down to each reference site, and a per-step reference is then\n  // rebuilt per candidate (source row, edge) pair — the quadratic term\n  // typegraph#310 removes. The expansion below reads it from an uncorrelated\n  // join for the same reason.\n  return sql`\n    ${sql.identifier(IDENTITY_CLASS_CTE_ALIAS)}(${IDENTITY_PEER_CLASS_COLUMNS}) AS MATERIALIZED (\n      ${peerClasses}\n    )\n  `;\n}\n\n/**\n * How a traversal step reaches the identity class of its frontier rows.\n *\n * `frontierJoin` widens the step's FROM list from \"the frontier\" to \"the\n * frontier's class members\"; `memberKind`/`memberId` then name the member a\n * candidate edge must attach to, so the edge join is an ordinary equality — the\n * same shape a traversal without identity expansion uses. `whereClauses` carries\n * conditions the widening needs in the step's WHERE rather than in a join\n * condition; emitters must include them in every branch of the step.\n */\nexport type IdentityFrontierExpansion = Readonly<{\n  frontierJoin: SqlFragment;\n  memberId: SqlFragment;\n  memberKind: SqlFragment;\n  whereClauses: readonly SqlFragment[];\n}>;\n\n/**\n * Widens a **current**-coordinate traversal step's frontier to the identity\n * classes of its rows, seeking from the frontier rather than from the closure.\n *\n * Three seeks per frontier row, each one bounded by the row before it:\n *\n * 1. the frontier row's class label, through the closure's\n *    `(graph_id, member_kind, member_id)` primary key;\n * 2. that class's members, through the closure's\n *    `(graph_id, class_kind, class_id)` index;\n * 3. each member's node row, through the nodes primary key, filtered to members\n *    visible at the read coordinate.\n *\n * The peer relation — every member paired with every other — is therefore never\n * built for classes the query does not touch. Building it graph-wide instead\n * costs the sum of the squares of *all* class sizes before a single frontier\n * predicate applies, which is quadratic in the identity population for a\n * traversal that reads one row (typegraph#432).\n *\n * The joins are outer so a frontier row in no class survives: the closure stores\n * no row for a singleton class, and the `COALESCE` pair below then supplies the\n * frontier row itself. A row whose class *is* stored appears among its own class\n * members, so the fallback is not double-counted.\n *\n * Member visibility cannot ride the node join alone: an outer join keeps the\n * member row when its node is invisible, and `COALESCE` would then read that row\n * as the \"no class\" case and re-emit the frontier row once per invisible peer.\n * The guard states the distinction the join cannot — a member row is admitted\n * only with a visible node behind it, and only the genuine no-class row reaches\n * the fallback.\n *\n * No `DISTINCT`: `(graph_id, member_kind, member_id)` is the closure's primary\n * key, so the frontier row seeks at most one class label and each member of that\n * class yields exactly one row, with the node join on the nodes primary key. One\n * `(frontier row, member)` pair cannot be produced twice — which is what keeps a\n * physical edge from being multiplied when the step joins the widened frontier.\n */\nfunction planCurrentIdentityFrontierExpansion(\n  input: Readonly<{\n    ctx: PredicateCompilerContext;\n    graphId: string;\n    previousId: SqlFragment;\n    previousKind: SqlFragment;\n    temporalFilterPass: TemporalFilterPass;\n  }>,\n): IdentityFrontierExpansion {\n  const { ctx, graphId, previousId, previousKind, temporalFilterPass } = input;\n  const seedClass = sql.raw(CURRENT_SEED_CLASS_ALIAS);\n  const peer = sql.raw(PEER_CLASS_ALIAS);\n  const memberNode = sql.raw(CURRENT_MEMBER_NODE_ALIAS);\n  return {\n    frontierJoin: sql`\n      LEFT JOIN ${ctx.schema.identityClosureTable} ${seedClass}\n        ON ${seedClass}.graph_id = ${graphId}\n       AND ${seedClass}.member_kind = ${previousKind}\n       AND ${seedClass}.member_id = ${previousId}\n      LEFT JOIN ${ctx.schema.identityClosureTable} ${peer}\n        ON ${peer}.graph_id = ${seedClass}.graph_id\n       AND ${peer}.class_kind = ${seedClass}.class_kind\n       AND ${peer}.class_id = ${seedClass}.class_id\n      LEFT JOIN ${ctx.schema.nodesTable} ${memberNode}\n        ON ${memberNode}.graph_id = ${peer}.graph_id\n       AND ${memberNode}.kind = ${peer}.member_kind\n       AND ${memberNode}.id = ${peer}.member_id\n       AND ${temporalFilterPass.forAlias(CURRENT_MEMBER_NODE_ALIAS)}\n    `,\n    memberId: sql`COALESCE(${peer}.member_id, ${previousId})`,\n    memberKind: sql`COALESCE(${peer}.member_kind, ${previousKind})`,\n    whereClauses: [\n      sql`(${peer}.member_id IS NULL OR ${memberNode}.id IS NOT NULL)`,\n    ],\n  };\n}\n\n/**\n * Widens a **historical**-coordinate traversal step's frontier from the hoisted\n * class relation {@link compileIdentityClassCte} emitted.\n *\n * The widening is an outer join against that relation. It holds only nodes that\n * have at least one peer, so the `COALESCE` pair supplies the frontier row itself\n * both when it has no peers at all and, redundantly, as its own class member. A\n * frontier row is always visible at the read coordinate — the relation it comes\n * from filters on the same coordinate — so the self case needs no separate\n * visibility check, and peers carry theirs inside the relation.\n */\nfunction planHistoricalIdentityFrontierExpansion(\n  input: Readonly<{\n    previousId: SqlFragment;\n    previousKind: SqlFragment;\n  }>,\n): IdentityFrontierExpansion {\n  const { previousId, previousKind } = input;\n  const peer = sql.identifier(PEER_CLASS_ALIAS);\n  return {\n    frontierJoin: sql`\n      LEFT JOIN ${sql.identifier(IDENTITY_CLASS_CTE_ALIAS)} ${peer}\n        ON ${peer}.seed_kind = ${previousKind}\n       AND ${peer}.seed_id = ${previousId}\n    `,\n    memberId: sql`COALESCE(${peer}.id, ${previousId})`,\n    memberKind: sql`COALESCE(${peer}.kind, ${previousKind})`,\n    whereClauses: [],\n  };\n}\n\n/**\n * Plans the frontier widening for an identity-expanded traversal step, at either\n * read coordinate.\n *\n * The two coordinates are deliberately *different* strategies rather than one\n * relation with two sources. A historical class is a fixed point over the\n * assertion ledger that no frontier row narrows, so it is reconstructed once per\n * statement and read from a hoisted relation; the current class is a key seek\n * into a maintained closure, so it is reached from the frontier and never\n * materialized graph-wide. Both are one shared compilation path across dialects:\n * neither branches on the backend.\n *\n * Both produce the same downstream shape — a widened frontier plus the\n * `(kind, id)` a candidate edge must attach to — so the emitters consume one\n * interface.\n */\nexport function planIdentityFrontierExpansion(\n  input: Readonly<{\n    ast: QueryAst;\n    ctx: PredicateCompilerContext;\n    graphId: string;\n    previousId: SqlFragment;\n    previousKind: SqlFragment;\n    temporalFilterPass: TemporalFilterPass;\n  }>,\n): IdentityFrontierExpansion {\n  const { ast, ctx, graphId, previousId, previousKind, temporalFilterPass } =\n    input;\n  const coordinate = historicalCoordinate({ ast, ctx, temporalFilterPass });\n  if (coordinate !== undefined) {\n    return planHistoricalIdentityFrontierExpansion({\n      previousId,\n      previousKind,\n    });\n  }\n  return planCurrentIdentityFrontierExpansion({\n    ctx,\n    graphId,\n    previousId,\n    previousKind,\n    temporalFilterPass,\n  });\n}\n","import { sql, type SqlFragment } from \"../sql-fragment\";\n\ntype KindFilterCompiler = (overlappingKinds: readonly string[]) => SqlFragment;\n\n/**\n * Prevents a direction:\"both\" traversal from returning a true self-loop twice.\n * Node identity is `(kind, id)`, so equal ids across different kinds remain a\n * real two-node edge and must not be suppressed.\n */\nexport function compileInverseTraversalDuplicateGuard(\n  directEdgeKinds: readonly string[],\n  inverseEdgeKinds: readonly string[],\n  compileKindFilter: KindFilterCompiler,\n): SqlFragment | undefined {\n  const overlappingKinds = inverseEdgeKinds.filter((kind) =>\n    directEdgeKinds.includes(kind),\n  );\n  if (overlappingKinds.length === 0) {\n    return undefined;\n  }\n  return sql`NOT (e.from_id = e.to_id AND e.from_kind = e.to_kind AND ${compileKindFilter(overlappingKinds)})`;\n}\n","import type { DialectAdapter } from \"../dialect/types\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/** SQL bounds, including the engine's unbounded LIMIT token for an offset-only query. */\nexport function compileLimitOffsetClauses(\n  limit: number | undefined,\n  offset: number | undefined,\n  dialect: DialectAdapter,\n): readonly SqlFragment[] {\n  return [\n    ...(limit === undefined ? [] : [sql`LIMIT ${limit}`]),\n    ...(offset === undefined ?\n      []\n    : [\n        limit === undefined ?\n          sql`LIMIT ${dialect.unboundedLimit()} OFFSET ${offset}`\n        : sql`OFFSET ${offset}`,\n      ]),\n  ];\n}\n","import { type SelectiveField } from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type JsonPointer, jsonPointer } from \"../json-pointer\";\nimport { type SqlFragment } from \"../sql-fragment\";\n\ntype JsonExtractFallback = \"json\" | \"text\";\n\ntype TypedJsonExtractInput = Readonly<{\n  column: SqlFragment;\n  dialect: DialectAdapter;\n  fallback?: JsonExtractFallback;\n  pointer: JsonPointer;\n  valueType: string | undefined;\n}>;\n\nexport function compileTypedJsonExtract(\n  input: TypedJsonExtractInput,\n): SqlFragment {\n  const { column, dialect, pointer, valueType } = input;\n  const fallback = input.fallback ?? \"json\";\n\n  switch (valueType) {\n    case \"string\": {\n      return dialect.jsonExtractText(column, pointer);\n    }\n    case \"number\": {\n      return dialect.jsonExtractNumber(column, pointer);\n    }\n    case \"boolean\": {\n      return dialect.jsonExtractBoolean(column, pointer);\n    }\n    case \"date\": {\n      return dialect.jsonExtractDate(column, pointer);\n    }\n    case \"array\":\n    case \"object\":\n    case \"embedding\":\n    case \"unknown\":\n    case undefined: {\n      return fallback === \"text\" ?\n          dialect.jsonExtractText(column, pointer)\n        : dialect.jsonExtract(column, pointer);\n    }\n    default: {\n      return fallback === \"text\" ?\n          dialect.jsonExtractText(column, pointer)\n        : dialect.jsonExtract(column, pointer);\n    }\n  }\n}\n\n/**\n * Extracts a single top-level selective-projection field from a JSON props\n * column, typed by the field's declared value type.\n *\n * Shared by both projection shapes: the standard emitter pushes this extraction\n * into a CTE synthetic column, while the recursive emitter applies it in the\n * outer SELECT over the props carried through the recursive CTE. The two SQL\n * shapes differ by design, but they must extract identically — centralizing the\n * pointer/valueType wiring here keeps their extraction semantics from drifting.\n */\nexport function compileSelectivePropsExtraction(\n  field: SelectiveField,\n  column: SqlFragment,\n  dialect: DialectAdapter,\n): SqlFragment {\n  return compileTypedJsonExtract({\n    column,\n    dialect,\n    pointer: jsonPointer([field.field]),\n    valueType: field.valueType,\n  });\n}\n","/**\n * Shared Compiler Utilities\n *\n * Functions and constants shared between the standard and recursive compilers.\n */\nimport { type AggregateExpr, type FieldRef, type SelectiveField } from \"../ast\";\nimport { parseJsonPointer } from \"../json-pointer\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { getFieldPointer } from \"./predicates\";\n\n// ============================================================\n// Constants\n// ============================================================\n\nexport const NODE_COLUMNS = [\n  \"id\",\n  \"kind\",\n  \"props\",\n  \"version\",\n  \"valid_from\",\n  \"valid_to\",\n  \"created_at\",\n  \"updated_at\",\n  \"deleted_at\",\n] as const;\n\nexport const EDGE_COLUMNS = [\n  \"id\",\n  \"kind\",\n  \"from_id\",\n  \"to_id\",\n  \"props\",\n  \"valid_from\",\n  \"valid_to\",\n  \"created_at\",\n  \"updated_at\",\n  \"deleted_at\",\n] as const;\n\nexport type RequiredColumnsByAlias = ReadonlyMap<string, ReadonlySet<string>>;\nexport const EMPTY_REQUIRED_COLUMNS = new Set<string>();\n\n// ============================================================\n// SQL Helpers\n// ============================================================\n\nexport function quoteIdentifier(identifier: string): SqlFragment {\n  return sql.identifier(identifier);\n}\n\n// ============================================================\n// Column Projection\n// ============================================================\n\n/**\n * Determines whether a column should be included in the projection.\n *\n * @param requiredColumns - Set of columns required by the query, or undefined to include all.\n * @param column - The column name to check.\n * @param alwaysRequiredColumns - Optional set of columns that are always projected\n *   (e.g. join keys in recursive CTEs). Pass only from recursive compiler callers.\n */\nexport function shouldProjectColumn(\n  requiredColumns: ReadonlySet<string> | undefined,\n  column: string,\n  alwaysRequiredColumns?: ReadonlySet<string>,\n): boolean {\n  if (alwaysRequiredColumns?.has(column)) return true;\n  if (requiredColumns === undefined) return true;\n  return requiredColumns.has(column);\n}\n\n// ============================================================\n// Required Column Tracking\n// ============================================================\n\nexport function addRequiredColumn(\n  requiredColumnsByAlias: Map<string, Set<string>>,\n  alias: string,\n  column: string,\n): void {\n  const existing = requiredColumnsByAlias.get(alias);\n  if (existing) {\n    existing.add(column);\n    return;\n  }\n  requiredColumnsByAlias.set(alias, new Set([column]));\n}\n\nexport function markFieldRefAsRequired(\n  requiredColumnsByAlias: Map<string, Set<string>>,\n  field: FieldRef,\n): void {\n  const column = field.path[0];\n  if (column === undefined) return;\n  addRequiredColumn(requiredColumnsByAlias, field.alias, column);\n}\n\nexport function mapSelectiveSystemFieldToColumn(field: string): string {\n  if (field === \"fromId\") return \"from_id\";\n  if (field === \"toId\") return \"to_id\";\n  if (field.startsWith(\"meta.\")) {\n    return field\n      .slice(5)\n      .replaceAll(/([A-Z])/g, \"_$1\")\n      .toLowerCase();\n  }\n  return field;\n}\n\nexport function markSelectiveFieldAsRequired(\n  requiredColumnsByAlias: Map<string, Set<string>>,\n  field: SelectiveField,\n): void {\n  if (field.isSystemField) {\n    addRequiredColumn(\n      requiredColumnsByAlias,\n      field.alias,\n      mapSelectiveSystemFieldToColumn(field.field),\n    );\n    return;\n  }\n  addRequiredColumn(requiredColumnsByAlias, field.alias, \"props\");\n}\n\nfunction getTopLevelPropsFieldName(field: FieldRef): string | undefined {\n  const pointer = getFieldPointer(field);\n  if (pointer === undefined) return undefined;\n\n  const segments = parseJsonPointer(pointer);\n  return segments.length === 1 ? segments[0] : undefined;\n}\n\nexport function findSelectivePropsFieldForFieldRef(\n  selectiveFields: readonly SelectiveField[] | undefined,\n  field: FieldRef,\n): SelectiveField | undefined {\n  if (selectiveFields === undefined || selectiveFields.length === 0) {\n    return undefined;\n  }\n\n  const propsFieldName = getTopLevelPropsFieldName(field);\n  if (propsFieldName === undefined) return undefined;\n\n  return selectiveFields.find(\n    (selectiveField) =>\n      !selectiveField.isSystemField &&\n      selectiveField.alias === field.alias &&\n      selectiveField.field === propsFieldName,\n  );\n}\n\n// ============================================================\n// AST Type Guards\n// ============================================================\n\nexport function isIdFieldRef(field: FieldRef): boolean {\n  return (\n    field.path.length === 1 &&\n    field.path[0] === \"id\" &&\n    field.jsonPointer === undefined\n  );\n}\n\nexport function isAggregateExpr(\n  source: FieldRef | AggregateExpr,\n): source is AggregateExpr {\n  return \"__type\" in source && source.__type === \"aggregate\";\n}\n","import { UnsupportedPredicateError } from \"../../../errors\";\nimport { boundPgIdentifier } from \"../../../utils/identifier\";\nimport { requireDefined } from \"../../../utils/presence\";\nimport {\n  type AggregateExpr,\n  DEFAULT_RRF_K,\n  DEFAULT_RRF_WEIGHT,\n  type FieldRef,\n  type FulltextMatchPredicate,\n  type HybridFusionOptions,\n  type QueryAst,\n  type SelectiveField,\n  type VectorSimilarityPredicate,\n} from \"../../ast\";\nimport { type DialectAdapter } from \"../../dialect/types\";\nimport {\n  assertApproximateMetricSupported,\n  vectorMinScoreCondition,\n  vectorScoreExpression,\n} from \"../../dialect/vector-strategy\";\nimport { type DatabaseExpression } from \"../../expressions\";\nimport { compileOrderTerm, resolveNullOrdering } from \"../../order\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { validateAggregateOperand } from \"../aggregate-validation\";\nimport {\n  compileDatabaseExpression,\n  compileLegacyAggregateExpression,\n} from \"../database-expressions\";\nimport { planIdentityFrontierExpansion } from \"../identity-traversal\";\nimport { compileInverseTraversalDuplicateGuard } from \"../inverse-traversal-guard\";\nimport { compileLimitOffsetClauses } from \"../limit-offset\";\nimport { type TemporalFilterPass } from \"../passes\";\nimport {\n  compileKindFilter,\n  compilePredicateClauses,\n  getHybridTargetAlias,\n  getNodeKindsForAlias,\n  getPredicatesForAlias,\n  type PredicateIndex,\n} from \"../predicate-utils\";\nimport {\n  compileFieldValue,\n  compilePredicateExpression,\n  type PredicateCompilerContext,\n} from \"../predicates\";\nimport {\n  ALIAS_CTE_PREFIX,\n  EMBEDDINGS_CTE_ALIAS,\n  FULLTEXT_CTE_ALIAS,\n  HYBRID_CANDIDATES_CTE_ALIAS,\n  vectorSlotKey,\n} from \"../schema\";\nimport { compileSelectivePropsExtraction } from \"../typed-json-extract\";\nimport {\n  EDGE_COLUMNS,\n  EMPTY_REQUIRED_COLUMNS,\n  findSelectivePropsFieldForFieldRef,\n  isAggregateExpr,\n  mapSelectiveSystemFieldToColumn,\n  NODE_COLUMNS,\n  quoteIdentifier,\n  type RequiredColumnsByAlias,\n  shouldProjectColumn,\n} from \"../utils\";\n\nexport type StandardEmitterPredicateIndex = PredicateIndex;\n\nfunction compileColumnReference(\n  tableAlias: string | undefined,\n  column: string,\n): SqlFragment {\n  if (tableAlias === undefined) {\n    return sql.raw(column);\n  }\n  return sql`${sql.raw(tableAlias)}.${sql.raw(column)}`;\n}\n\nfunction qualifyColumn(owner: string, name: string): SqlFragment {\n  return sql`${quoteIdentifier(owner)}.${quoteIdentifier(name)}`;\n}\n\nconst SCOPED_RELEVANCE_NODES_ALIAS = \"scoped_relevance_nodes\";\n\n/**\n * Builds a synthetic CTE column name for a selectively-extracted props field.\n *\n * Length-prefixes each component (`<length>:<value>`) rather than joining\n * `alias`/`field` on a bare `_`: alias and field are both attacker/user-controlled\n * strings that may themselves contain `_`, so naive concatenation lets two distinct\n * (alias, field) pairs collide on the same column name (e.g. alias=\"p_full\",\n * field=\"name\" vs. alias=\"p\", field=\"full_name\" would otherwise both produce\n * \"__tg_p_full_name\"). The length prefix makes the encoding unambiguous regardless\n * of what characters alias/field contain.\n *\n * The encoding is unbounded, but PostgreSQL truncates identifiers at 63 bytes,\n * so `boundPgIdentifier` hash-guards long names: two pairs whose encodings share\n * a >63-byte prefix would otherwise collapse onto the same physical column.\n * Short names are returned verbatim, preserving the readable `__tg_...` form.\n */\nfunction selectivePropsCteColumnName(field: SelectiveField): string {\n  const { alias, field: fieldName } = field;\n  const encoded = `__tg_${alias.length}:${alias}:${fieldName.length}:${fieldName}`;\n  return boundPgIdentifier(encoded, `${alias}\\0${fieldName}`);\n}\n\nfunction buildScopedNodeIdsSubquery(nodeAlias: string): SqlFragment {\n  const cteAlias = `${ALIAS_CTE_PREFIX}${nodeAlias}`;\n  return sql`\n    (\n        SELECT DISTINCT\n          ${qualifyColumn(cteAlias, `${nodeAlias}_id`)} AS node_id,\n          ${qualifyColumn(cteAlias, `${nodeAlias}_kind`)} AS node_kind\n        FROM ${quoteIdentifier(cteAlias)}\n      ) AS ${sql.raw(SCOPED_RELEVANCE_NODES_ALIAS)}\n  `;\n}\n\ntype CompileSelectivePropsSelectColumnsInput = Readonly<{\n  alias: string;\n  dialect: DialectAdapter;\n  selectiveFields: readonly SelectiveField[] | undefined;\n  tableAlias: string | undefined;\n}>;\n\nfunction compileSelectivePropsSelectColumns(\n  input: CompileSelectivePropsSelectColumnsInput,\n): SqlFragment[] {\n  const { alias, dialect, selectiveFields, tableAlias } = input;\n  const propsFields =\n    selectiveFields?.filter(\n      (field) => !field.isSystemField && field.alias === alias,\n    ) ?? [];\n  if (propsFields.length === 0) return [];\n\n  const propsColumn = compileColumnReference(tableAlias, \"props\");\n  return propsFields.map((field) => {\n    const extracted = compileSelectivePropsExtraction(\n      field,\n      propsColumn,\n      dialect,\n    );\n    return sql`${extracted} AS ${quoteIdentifier(selectivePropsCteColumnName(field))}`;\n  });\n}\n\nfunction appendSelectivePropsColumns(\n  baseColumns: readonly SqlFragment[],\n  input: CompileSelectivePropsSelectColumnsInput,\n): SqlFragment[] {\n  return [...baseColumns, ...compileSelectivePropsSelectColumns(input)];\n}\n\ntype CompileNodeSelectColumnsInput = Readonly<{\n  alias: string;\n  dialect: DialectAdapter;\n  requiredColumns: ReadonlySet<string> | undefined;\n  selectiveFields: readonly SelectiveField[] | undefined;\n  tableAlias: string | undefined;\n}>;\n\nfunction compileNodeSelectColumns(\n  input: CompileNodeSelectColumnsInput,\n): SqlFragment[] {\n  const { alias, dialect, requiredColumns, selectiveFields, tableAlias } =\n    input;\n  const baseColumns = NODE_COLUMNS.filter(\n    (column) =>\n      column === \"id\" ||\n      column === \"kind\" ||\n      shouldProjectColumn(requiredColumns, column),\n  ).map(\n    (column) =>\n      sql`${compileColumnReference(tableAlias, column)} AS ${sql.raw(`${alias}_${column}`)}`,\n  );\n  return appendSelectivePropsColumns(baseColumns, {\n    alias,\n    dialect,\n    selectiveFields,\n    tableAlias,\n  });\n}\n\ntype CompileEdgeSelectColumnsInput = Readonly<{\n  alias: string;\n  dialect: DialectAdapter;\n  requiredColumns: ReadonlySet<string> | undefined;\n  selectiveFields: readonly SelectiveField[] | undefined;\n  tableAlias: string | undefined;\n}>;\n\nfunction compileEdgeSelectColumns(\n  input: CompileEdgeSelectColumnsInput,\n): SqlFragment[] {\n  const { alias, dialect, requiredColumns, selectiveFields, tableAlias } =\n    input;\n  const baseColumns = EDGE_COLUMNS.filter((column) =>\n    shouldProjectColumn(requiredColumns, column),\n  ).map(\n    (column) =>\n      sql`${compileColumnReference(tableAlias, column)} AS ${sql.raw(`${alias}_${column}`)}`,\n  );\n  return appendSelectivePropsColumns(baseColumns, {\n    alias,\n    dialect,\n    selectiveFields,\n    tableAlias,\n  });\n}\n\ntype BuildStandardStartCteInput = Readonly<{\n  ast: QueryAst;\n  ctx: PredicateCompilerContext;\n  graphId: string;\n  predicateIndex: StandardEmitterPredicateIndex;\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n  temporalFilterPass: TemporalFilterPass;\n  /**\n   * Optional LIMIT/OFFSET to apply inside the start CTE. Used by the count\n   * aggregate fast path to push limits past the GROUP BY when it's safe.\n   */\n  limitOffset?: Readonly<{ limit: number; offset?: number | undefined }>;\n}>;\n\nexport function buildStandardStartCte(\n  input: BuildStandardStartCteInput,\n): SqlFragment {\n  const { ast, ctx, graphId, predicateIndex, requiredColumnsByAlias } = input;\n  const alias = ast.start.alias;\n  const kinds = ast.start.kinds;\n  const cteMaterialization =\n    ctx.dialect.capabilities.emitNotMaterializedHint ?\n      sql`NOT MATERIALIZED `\n    : sql``;\n\n  const kindFilter = compileKindFilter(sql.raw(\"kind\"), kinds);\n  const temporalFilter = input.temporalFilterPass.forAlias();\n  const cteContext: PredicateCompilerContext = { ...ctx, cteColumnPrefix: \"\" };\n  const predicateClauses = compilePredicateClauses(\n    getPredicatesForAlias(predicateIndex, alias, \"node\"),\n    cteContext,\n  );\n\n  const whereClauses = [\n    sql`graph_id = ${graphId}`,\n    kindFilter,\n    temporalFilter,\n    ...predicateClauses,\n  ];\n\n  const effectiveRequiredColumns =\n    requiredColumnsByAlias ?\n      (requiredColumnsByAlias.get(alias) ?? EMPTY_REQUIRED_COLUMNS)\n    : undefined;\n\n  const limitClause =\n    input.limitOffset === undefined ? sql``\n    : input.limitOffset.offset === undefined ?\n      sql`\n        LIMIT ${input.limitOffset.limit}\n      `\n    : sql`\n      LIMIT ${input.limitOffset.limit} OFFSET ${input.limitOffset.offset}\n    `;\n\n  return sql`\n    cte_${sql.raw(alias)} AS ${cteMaterialization}(\n      SELECT ${sql.join(\n        compileNodeSelectColumns({\n          alias,\n          dialect: ctx.dialect,\n          requiredColumns: effectiveRequiredColumns,\n          selectiveFields: ast.selectiveFields,\n          tableAlias: undefined,\n        }),\n        sql`, `,\n      )}\n      FROM ${ctx.schema.nodesTable}\n      WHERE ${sql.join(whereClauses, sql` AND `)}${limitClause}\n    )\n  `;\n}\n\ntype BuildStandardTraversalCteInput = Readonly<{\n  ast: QueryAst;\n  carryForwardPreviousColumns: boolean;\n  ctx: PredicateCompilerContext;\n  graphId: string;\n  materializeCte: boolean;\n  predicateIndex: StandardEmitterPredicateIndex;\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n  temporalFilterPass: TemporalFilterPass;\n  traversalIndex: number;\n  traversalLimit: number | undefined;\n}>;\n\nexport function buildStandardTraversalCte(\n  input: BuildStandardTraversalCteInput,\n): SqlFragment {\n  const {\n    ast,\n    carryForwardPreviousColumns,\n    ctx,\n    graphId,\n    materializeCte,\n    predicateIndex,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    traversalIndex,\n    traversalLimit,\n  } = input;\n  const traversal = requireDefined(ast.traversals[traversalIndex]);\n  const traversalLimitValue =\n    traversalIndex === ast.traversals.length - 1 ? traversalLimit : undefined;\n\n  const previousNodeKinds = getNodeKindsForAlias(ast, traversal.joinFromAlias);\n  const directEdgeKinds = [...new Set(traversal.edgeKinds)];\n  const inverseEdgeKinds =\n    traversal.inverseEdgeKinds === undefined ?\n      []\n    : [...new Set(traversal.inverseEdgeKinds)];\n\n  const nodeKinds = traversal.nodeKinds;\n  const nodeKindFilter = compileKindFilter(sql.raw(\"n.kind\"), nodeKinds);\n\n  const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n  const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n  const nodeCteContext: PredicateCompilerContext = {\n    ...ctx,\n    cteColumnPrefix: \"n\",\n  };\n  const nodePredicateClauses = compilePredicateClauses(\n    getPredicatesForAlias(predicateIndex, traversal.nodeAlias, \"node\"),\n    nodeCteContext,\n  );\n\n  const edgeCteContext: PredicateCompilerContext = {\n    ...ctx,\n    cteColumnPrefix: \"e\",\n  };\n  const edgePredicateClauses = compilePredicateClauses(\n    getPredicatesForAlias(predicateIndex, traversal.edgeAlias, \"edge\"),\n    edgeCteContext,\n  );\n\n  const baseWhereClauses = [\n    sql`e.graph_id = ${graphId}`,\n    nodeKindFilter,\n    edgeTemporalFilter,\n    nodeTemporalFilter,\n    ...nodePredicateClauses,\n    ...edgePredicateClauses,\n  ];\n\n  const previousAlias = traversal.joinFromAlias;\n  const edgeAlias = traversal.edgeAlias;\n  const nodeAlias = traversal.nodeAlias;\n  const requiredNodeColumns =\n    requiredColumnsByAlias ?\n      (requiredColumnsByAlias.get(nodeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n    : undefined;\n  const requiredEdgeColumns =\n    requiredColumnsByAlias ?\n      (requiredColumnsByAlias.get(edgeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n    : undefined;\n  const previousRowColumns =\n    carryForwardPreviousColumns ?\n      [sql`cte_${sql.raw(previousAlias)}.*`]\n    : [\n        sql`cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id AS ${sql.raw(previousAlias)}_id`,\n        sql`cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind AS ${sql.raw(previousAlias)}_kind`,\n      ];\n  const selectColumns = [\n    ...previousRowColumns,\n    ...compileEdgeSelectColumns({\n      alias: edgeAlias,\n      dialect: ctx.dialect,\n      requiredColumns: requiredEdgeColumns,\n      selectiveFields: ast.selectiveFields,\n      tableAlias: \"e\",\n    }),\n    ...compileNodeSelectColumns({\n      alias: nodeAlias,\n      dialect: ctx.dialect,\n      requiredColumns: requiredNodeColumns,\n      selectiveFields: ast.selectiveFields,\n      tableAlias: \"n\",\n    }),\n  ];\n  const cteMaterialization =\n    materializeCte ? sql`MATERIALIZED `\n    : ctx.dialect.capabilities.emitNotMaterializedHint ? sql`NOT MATERIALIZED `\n    : sql``;\n\n  const previousIdColumn = sql`cte_${sql.raw(previousAlias)}.${sql.raw(`${previousAlias}_id`)}`;\n  const previousKindColumn = sql`cte_${sql.raw(previousAlias)}.${sql.raw(`${previousAlias}_kind`)}`;\n  const identityFrontierExpansion =\n    traversal.includeIdentityMembers === true ?\n      planIdentityFrontierExpansion({\n        ast,\n        ctx,\n        graphId,\n        previousId: previousIdColumn,\n        previousKind: previousKindColumn,\n        temporalFilterPass,\n      })\n    : undefined;\n\n  // A widened frontier reaches the edge through COALESCE over an outer join, so\n  // the engine sees no plain frontier-to-edge equality to plan from and may drive\n  // the nested loop from the edge table instead — a rescan of every candidate\n  // edge per frontier row, which is the cost typegraph#270 removes. Pinning the\n  // frontier ahead of the edge table restores the indexed\n  // (graph_id, from_kind, from_id) seek on engines that read FROM order as a\n  // directive; the same planner control the recursive emitter applies to its\n  // worktable, so it rides the same capability. A traversal without identity\n  // expansion joins on the frontier's own columns and needs no pin, so its SQL is\n  // left untouched.\n  const pinFrontierAheadOfEdges =\n    identityFrontierExpansion !== undefined &&\n    ctx.dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;\n\n  /**\n   * Connects a candidate edge to the frontier. A widened frontier and a plain\n   * one join the edge the same way — on the frontier row's (kind, id) or on the\n   * class member's — so no traversal reaches an edge through a correlated\n   * membership test.\n   */\n  function compileSourceJoin(\n    branch: Readonly<{\n      joinField: \"from_id\" | \"to_id\";\n      joinKindField: \"from_kind\" | \"to_kind\";\n    }>,\n  ): SqlFragment {\n    const edgeId = sql`e.${sql.raw(branch.joinField)}`;\n    const edgeKind = sql`e.${sql.raw(branch.joinKindField)}`;\n    if (identityFrontierExpansion !== undefined) {\n      return sql`\n        ${identityFrontierExpansion.memberId} = ${edgeId}\n        AND ${identityFrontierExpansion.memberKind} = ${edgeKind}\n      `;\n    }\n    return sql`\n      ${previousIdColumn} = ${edgeId}\n      AND ${previousKindColumn} = ${edgeKind}\n    `;\n  }\n\n  function compileTraversalBranch(\n    branch: Readonly<{\n      duplicateGuard?: SqlFragment | undefined;\n      edgeKinds: readonly string[];\n      joinField: \"from_id\" | \"to_id\";\n      joinKindField: \"from_kind\" | \"to_kind\";\n      targetField: \"from_id\" | \"to_id\";\n      targetKindField: \"from_kind\" | \"to_kind\";\n    }>,\n  ): SqlFragment {\n    const whereClauses = [\n      ...baseWhereClauses,\n      // Conditions the frontier widening cannot state in a join condition —\n      // currently the member-visibility guard. Every branch of the step carries\n      // them, because every branch reads the widened frontier.\n      ...(identityFrontierExpansion?.whereClauses ?? []),\n      compileKindFilter(sql.raw(\"e.kind\"), branch.edgeKinds),\n      compileKindFilter(sql.raw(`e.${branch.targetKindField}`), nodeKinds),\n    ];\n\n    if (traversal.includeIdentityMembers !== true) {\n      whereClauses.push(\n        compileKindFilter(\n          sql.raw(`e.${branch.joinKindField}`),\n          previousNodeKinds,\n        ),\n      );\n    }\n\n    if (branch.duplicateGuard !== undefined) {\n      whereClauses.push(branch.duplicateGuard);\n    }\n\n    const sourceJoin = compileSourceJoin(branch);\n    const frontierJoin = identityFrontierExpansion?.frontierJoin ?? sql``;\n\n    // The target join is spelled out in both orderings rather than hoisted into\n    // a shared fragment: interpolating one would surround it with the\n    // fragment's own leading and trailing newlines, and a traversal that needs\n    // no pin has to compile byte-identically to what it did before the pin\n    // existed. The recursive emitter repeats it for the same reason.\n    if (pinFrontierAheadOfEdges) {\n      return sql`\n        SELECT ${sql.join(selectColumns, sql`, `)}\n        FROM cte_${sql.raw(previousAlias)}\n        ${frontierJoin}\n        CROSS JOIN ${ctx.schema.edgesTable} e\n        JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n          AND n.id = e.${sql.raw(branch.targetField)}\n          AND n.kind = e.${sql.raw(branch.targetKindField)}\n        WHERE ${sql.join([sourceJoin, ...whereClauses], sql` AND `)}\n      `;\n    }\n\n    return sql`\n      SELECT ${sql.join(selectColumns, sql`, `)}\n      FROM cte_${sql.raw(previousAlias)}\n      ${frontierJoin}\n      JOIN ${ctx.schema.edgesTable} e ON ${sourceJoin}\n      JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n        AND n.id = e.${sql.raw(branch.targetField)}\n        AND n.kind = e.${sql.raw(branch.targetKindField)}\n      WHERE ${sql.join(whereClauses, sql` AND `)}\n    `;\n  }\n\n  const directJoinField = traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n  const directTargetField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n  const directJoinKindField =\n    traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n  const directTargetKindField =\n    traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n  const directBranch = compileTraversalBranch({\n    edgeKinds: directEdgeKinds,\n    joinField: directJoinField,\n    joinKindField: directJoinKindField,\n    targetField: directTargetField,\n    targetKindField: directTargetKindField,\n  });\n\n  if (inverseEdgeKinds.length === 0) {\n    if (traversalLimitValue !== undefined) {\n      return sql`\n        cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n          SELECT * FROM (\n            ${directBranch}\n          ) AS traversal_rows\n          LIMIT ${traversalLimitValue}\n        )\n      `;\n    }\n\n    return sql`\n      cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n        ${directBranch}\n      )\n    `;\n  }\n\n  const inverseJoinField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n  const inverseTargetField =\n    traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n  const inverseJoinKindField =\n    traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n  const inverseTargetKindField =\n    traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n\n  const duplicateGuard = compileInverseTraversalDuplicateGuard(\n    directEdgeKinds,\n    inverseEdgeKinds,\n    (overlappingKinds) =>\n      compileKindFilter(sql.raw(\"e.kind\"), overlappingKinds),\n  );\n\n  const inverseBranch = compileTraversalBranch({\n    duplicateGuard,\n    edgeKinds: inverseEdgeKinds,\n    joinField: inverseJoinField,\n    joinKindField: inverseJoinKindField,\n    targetField: inverseTargetField,\n    targetKindField: inverseTargetKindField,\n  });\n\n  if (traversalLimitValue !== undefined) {\n    return sql`\n      cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n        SELECT * FROM (\n          ${directBranch}\n          UNION ALL\n          ${inverseBranch}\n        ) AS traversal_rows\n        LIMIT ${traversalLimitValue}\n      )\n    `;\n  }\n\n  return sql`\n    cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n      ${directBranch}\n      UNION ALL\n      ${inverseBranch}\n    )\n  `;\n}\n\nfunction compileAggregateExprFromSource(\n  expr: AggregateExpr,\n  dialect: DialectAdapter,\n  cteAliasOverride?: string,\n): SqlFragment {\n  validateAggregateOperand(expr);\n  const { field } = expr;\n  return compileLegacyAggregateExpression(expr, {\n    dialect,\n    resolveFieldCteAlias() {\n      return cteAliasOverride ?? `cte_${field.alias}`;\n    },\n  });\n}\n\nfunction compileProjectedSource(\n  field: {\n    cteAlias?: string;\n    source: DatabaseExpression | FieldRef | AggregateExpr;\n  },\n  ast: QueryAst,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const { dialect } = ctx;\n  if (field.source.__type === \"database_expression\") {\n    return compileStandardDatabaseExpression(\n      ast,\n      field.source,\n      ctx,\n      field.cteAlias,\n    );\n  }\n  if (isAggregateExpr(field.source)) {\n    return compileAggregateExprFromSource(\n      field.source,\n      dialect,\n      field.cteAlias,\n    );\n  }\n  const cteAlias = field.cteAlias ?? `cte_${field.source.alias}`;\n  return compileFieldValue(\n    field.source,\n    dialect,\n    field.source.valueType,\n    cteAlias,\n  );\n}\n\ntype BuildStandardProjectionInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias?: string;\n  ctx: PredicateCompilerContext;\n}>;\n\nexport function buildStandardProjection(\n  input: BuildStandardProjectionInput,\n): SqlFragment {\n  const { ast, collapsedTraversalCteAlias, ctx } = input;\n  if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n    return compileSelectiveProjection(\n      ast.selectiveFields,\n      ast,\n      collapsedTraversalCteAlias,\n    );\n  }\n\n  const fields = ast.projection.fields;\n  if (fields.length === 0) {\n    return sql.raw(\"*\");\n  }\n\n  const projectedFields = fields.map((field) => {\n    const source = compileProjectedSource(field, ast, ctx);\n    return sql`${source} AS ${quoteIdentifier(field.outputName)}`;\n  });\n  return sql.join(projectedFields, sql`, `);\n}\n\n/**\n * Builds a map from query aliases (node and edge) to their CTE table names.\n * Edge aliases map to the CTE of the traversal node they are co-projected with.\n */\nfunction buildAliasToCteMap(ast: QueryAst): Map<string, string> {\n  const map = new Map<string, string>([\n    [ast.start.alias, `cte_${ast.start.alias}`],\n  ]);\n  for (const traversal of ast.traversals) {\n    map.set(traversal.nodeAlias, `cte_${traversal.nodeAlias}`);\n    map.set(traversal.edgeAlias, `cte_${traversal.nodeAlias}`);\n  }\n  return map;\n}\n\nfunction compileSelectiveProjection(\n  fields: readonly SelectiveField[],\n  ast: QueryAst,\n  collapsedTraversalCteAlias?: string,\n): SqlFragment {\n  const aliasToCte = buildAliasToCteMap(ast);\n\n  const columns = fields.map((field) => {\n    const cteAlias =\n      collapsedTraversalCteAlias ??\n      aliasToCte.get(field.alias) ??\n      `cte_${field.alias}`;\n\n    if (field.isSystemField) {\n      const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n\n      return sql`${sql.raw(cteAlias)}.${sql.raw(`${field.alias}_${dbColumn}`)} AS ${quoteIdentifier(field.outputName)}`;\n    }\n\n    return sql`${sql.raw(cteAlias)}.${quoteIdentifier(selectivePropsCteColumnName(field))} AS ${quoteIdentifier(field.outputName)}`;\n  });\n\n  return sql.join(columns, sql`, `);\n}\n\nfunction compileOrderFieldValue(\n  ast: QueryAst,\n  field: DatabaseExpression | FieldRef,\n  dialect: DialectAdapter,\n  cteAlias: string,\n): SqlFragment {\n  if (field.__type === \"database_expression\") {\n    return compileStandardDatabaseExpression(ast, field, dialect, cteAlias);\n  }\n  const selectiveField = findSelectivePropsFieldForFieldRef(\n    ast.selectiveFields,\n    field,\n  );\n  if (selectiveField !== undefined) {\n    return sql`${sql.raw(cteAlias)}.${quoteIdentifier(selectivePropsCteColumnName(selectiveField))}`;\n  }\n\n  return compileFieldValue(field, dialect, field.valueType, cteAlias);\n}\n\nfunction compileStandardDatabaseExpression(\n  ast: QueryAst,\n  expression: DatabaseExpression,\n  context: PredicateCompilerContext | DialectAdapter,\n  cteAliasOverride?: string,\n  allowAggregates = true,\n): SqlFragment {\n  const ctx = isPredicateCompilerContext(context) ? context : undefined;\n  const dialect =\n    isPredicateCompilerContext(context) ? context.dialect : context;\n  const aliasToCte = buildAliasToCteMap(ast);\n  return compileDatabaseExpression(expression, {\n    allowAggregates,\n    ...(allowAggregates ? {} : { aggregateClause: \"GROUP BY\" }),\n    dialect,\n    orderedAggregates: ctx?.orderedAggregates ?? true,\n    ...(ctx?.compileExpressionSubquery === undefined ?\n      {}\n    : { compileSubquery: ctx.compileExpressionSubquery }),\n    ...(ctx?.compileExpressionOuterReference === undefined ?\n      {}\n    : { compileOuterReference: ctx.compileExpressionOuterReference }),\n    resolveFieldCteAlias(field) {\n      return cteAliasOverride ?? aliasToCte.get(field.alias);\n    },\n  });\n}\n\nfunction isPredicateCompilerContext(\n  context: DialectAdapter | PredicateCompilerContext,\n): context is PredicateCompilerContext {\n  return \"schema\" in context;\n}\n\nfunction buildRelevanceJoins(\n  vectorPredicate: VectorSimilarityPredicate | undefined,\n  fulltextPredicate: FulltextMatchPredicate | undefined,\n): SqlFragment[] {\n  const hybridTargetAlias = getHybridTargetAlias(\n    vectorPredicate,\n    fulltextPredicate,\n  );\n  if (hybridTargetAlias !== undefined) {\n    return [\n      buildHybridCandidateJoin(hybridTargetAlias),\n      buildRelevanceJoin(EMBEDDINGS_CTE_ALIAS, hybridTargetAlias, \"LEFT JOIN\"),\n      buildRelevanceJoin(FULLTEXT_CTE_ALIAS, hybridTargetAlias, \"LEFT JOIN\"),\n    ];\n  }\n\n  const joins: SqlFragment[] = [];\n  if (vectorPredicate) {\n    joins.push(\n      buildRelevanceJoin(EMBEDDINGS_CTE_ALIAS, vectorPredicate.field.alias),\n    );\n  }\n  if (fulltextPredicate) {\n    joins.push(\n      buildRelevanceJoin(FULLTEXT_CTE_ALIAS, fulltextPredicate.field.alias),\n    );\n  }\n  return joins;\n}\n\nfunction buildHybridCandidateJoin(nodeAlias: string): SqlFragment {\n  const candidateCte = sql.raw(HYBRID_CANDIDATES_CTE_ALIAS);\n  const node = sql.raw(`${ALIAS_CTE_PREFIX}${nodeAlias}`);\n  const idColumn = sql.raw(`${nodeAlias}_id`);\n  const kindColumn = sql.raw(`${nodeAlias}_kind`);\n  return sql`INNER JOIN ${candidateCte} ON ${candidateCte}.node_id = ${node}.${idColumn} AND ${candidateCte}.node_kind = ${node}.${kindColumn}`;\n}\n\nfunction buildRelevanceJoin(\n  cteAlias: string,\n  nodeAlias: string,\n  joinType = \"INNER JOIN\",\n): SqlFragment {\n  const cte = sql.raw(cteAlias);\n  const node = sql.raw(`${ALIAS_CTE_PREFIX}${nodeAlias}`);\n  const idColumn = sql.raw(`${nodeAlias}_id`);\n  const kindColumn = sql.raw(`${nodeAlias}_kind`);\n  return sql`${sql.raw(joinType)} ${cte} ON ${cte}.node_id = ${node}.${idColumn} AND ${cte}.node_kind = ${node}.${kindColumn}`;\n}\n\ntype BuildStandardFromClauseInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias?: string;\n  fulltextPredicate?: FulltextMatchPredicate;\n  vectorPredicate?: VectorSimilarityPredicate;\n}>;\n\nexport function buildStandardFromClause(\n  input: BuildStandardFromClauseInput,\n): SqlFragment {\n  const {\n    ast,\n    collapsedTraversalCteAlias,\n    fulltextPredicate,\n    vectorPredicate,\n  } = input;\n  if (collapsedTraversalCteAlias !== undefined) {\n    return sql`FROM ${sql.raw(collapsedTraversalCteAlias)}`;\n  }\n\n  const startAlias = ast.start.alias;\n  const fromClause = sql`FROM cte_${sql.raw(startAlias)}`;\n\n  const joins: SqlFragment[] = [];\n  for (const traversal of ast.traversals) {\n    const cteAlias = `cte_${traversal.nodeAlias}`;\n    const previousAlias = traversal.joinFromAlias;\n    const joinType = traversal.optional ? \"LEFT JOIN\" : \"INNER JOIN\";\n    joins.push(\n      sql`${sql.raw(joinType)} ${sql.raw(cteAlias)} ON ${sql.raw(cteAlias)}.${sql.raw(previousAlias)}_id = cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id AND ${sql.raw(cteAlias)}.${sql.raw(previousAlias)}_kind = cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind`,\n    );\n  }\n\n  // Node IDs are unique only within a kind (PK is graph_id, kind, id),\n  // so the relevance-CTE joins must include node_kind. Without it,\n  // polymorphic queries would cross-join on user-supplied ids shared\n  // across kinds.\n  for (const join of buildRelevanceJoins(vectorPredicate, fulltextPredicate)) {\n    joins.push(join);\n  }\n\n  return joins.length === 0 ?\n      fromClause\n    : sql`${fromClause} ${sql.join(joins, sql` `)}`;\n}\n\ntype BuildStandardOrderByInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias?: string;\n  dialect: DialectAdapter;\n}>;\n\nexport function buildStandardOrderBy(\n  input: BuildStandardOrderByInput,\n): SqlFragment | undefined {\n  const { ast, collapsedTraversalCteAlias, dialect } = input;\n  const fieldOrderBy = ast.orderBy ?? [];\n  const aggregateOrderBy = ast.aggregateOrderBy ?? [];\n  if (fieldOrderBy.length === 0 && aggregateOrderBy.length === 0) {\n    return undefined;\n  }\n\n  // Only built when there's a FieldRef-based order spec to resolve against\n  // a CTE — the aggregate-alias loop below references the SELECT-list\n  // output alias directly and never needs it, which matters because the\n  // common case for `.aggregate().orderBy(...)` has `fieldOrderBy` empty.\n  const aliasToCte =\n    fieldOrderBy.length > 0 ? buildAliasToCteMap(ast) : undefined;\n  const parts: SqlFragment[] = [];\n  for (const orderSpec of fieldOrderBy) {\n    const valueType = orderSpec.field.valueType;\n    if (valueType === \"array\" || valueType === \"object\") {\n      throw new UnsupportedPredicateError(\n        \"Ordering by JSON arrays or objects is not supported\",\n      );\n    }\n    const cteAlias =\n      collapsedTraversalCteAlias ??\n      (orderSpec.field.__type === \"field_ref\" ?\n        (aliasToCte?.get(orderSpec.field.alias) ??\n        `cte_${orderSpec.field.alias}`)\n      : undefined) ??\n      \"\";\n    const field = compileOrderFieldValue(\n      ast,\n      orderSpec.field,\n      dialect,\n      cteAlias,\n    );\n    const nulls = resolveNullOrdering(orderSpec);\n    parts.push(compileOrderTerm(field, orderSpec.direction, nulls));\n  }\n\n  // Aggregate ordering references the projected SELECT-list output alias\n  // directly rather than recompiling a FieldRef/AggregateExpr — every\n  // `.aggregate()` field (grouped or aggregated) is always projected with\n  // an alias, and both SQLite and PostgreSQL allow ORDER BY to reference\n  // it, so this needs no per-CTE or per-dialect resolution.\n  //\n  for (const orderSpec of aggregateOrderBy) {\n    const column = quoteIdentifier(orderSpec.outputName);\n    const nulls = resolveNullOrdering(orderSpec);\n    parts.push(compileOrderTerm(column, orderSpec.direction, nulls));\n  }\n\n  return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\n// ============================================================\n// Late materialization (deferred projection)\n// ============================================================\n//\n// For an ORDER BY … LIMIT query whose projection reads columns beyond the\n// ordering/identity keys, the flat plan carries every projected column (e.g. a\n// large `content` prop) through the sorter for every candidate row and then\n// discards all but the LIMIT survivors. Late materialization sorts+limits a\n// *lean* candidate set (identity + sort keys only), then re-joins the physical\n// node table by `(graph_id, kind, id)` to fetch the deferred columns for only\n// the surviving rows. See the standard emitter's late-materialization branch\n// for the eligibility gate; these builders assume it already held.\n\nexport const LATE_MAT_TOPK_CTE_ALIAS = \"cte_lm_topk\";\nconst LATE_MAT_SORT_KEY_PREFIX = \"__lm_sk\";\nconst LATE_MAT_PHYSICAL_ALIAS_PREFIX = \"lm_\";\n\nexport function lateMaterializedPhysicalAlias(alias: string): string {\n  return `${LATE_MAT_PHYSICAL_ALIAS_PREFIX}${alias}`;\n}\n\n/** Node aliases in the query: the start alias plus each traversal's node. */\nfunction lateMaterializedNodeAliases(ast: QueryAst): readonly string[] {\n  return [\n    ast.start.alias,\n    ...ast.traversals.map((traversal) => traversal.nodeAlias),\n  ];\n}\n\n/**\n * Node aliases the projection actually reads — the physical tables the outer\n * SELECT must re-join. Edge aliases are gated out upstream, so every projected\n * alias resolves to a node table here.\n */\nexport function lateMaterializedProjectedNodeAliases(\n  ast: QueryAst,\n): readonly string[] {\n  const referenced = new Set<string>();\n  for (const field of ast.selectiveFields ?? []) {\n    referenced.add(field.alias);\n  }\n  return lateMaterializedNodeAliases(ast).filter((alias) =>\n    referenced.has(alias),\n  );\n}\n\ntype BuildLateMaterializedTopKCteInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias?: string;\n  dialect: DialectAdapter;\n  fromClause: SqlFragment;\n  where?: SqlFragment;\n  limit: number;\n  offset?: number | undefined;\n}>;\n\n/**\n * The topK CTE: selects each node alias's identity `(id, kind)` plus each sort\n * key value (aliased `__lm_sk{n}` so the outer SELECT can re-order the survivors\n * without re-extracting), ordered and limited on the lean candidate set.\n *\n * When the traversal rowset is collapsed onto a single CTE, every alias's\n * identity is carried into that one CTE (keyed by alias prefix), so all columns\n * resolve against `collapsedTraversalCteAlias` and the FROM references it alone.\n */\nexport function buildLateMaterializedTopKCte(\n  input: BuildLateMaterializedTopKCteInput,\n): SqlFragment {\n  const { ast, collapsedTraversalCteAlias, dialect, fromClause } = input;\n  const aliasToCte = buildAliasToCteMap(ast);\n  const cteAliasFor = (alias: string): string =>\n    collapsedTraversalCteAlias ??\n    aliasToCte.get(alias) ??\n    `${ALIAS_CTE_PREFIX}${alias}`;\n\n  const columns: SqlFragment[] = [];\n  for (const alias of lateMaterializedNodeAliases(ast)) {\n    const cteAlias = cteAliasFor(alias);\n    columns.push(\n      sql`${qualifyColumn(cteAlias, `${alias}_id`)} AS ${sql.raw(`${alias}_id`)}`,\n      sql`${qualifyColumn(cteAlias, `${alias}_kind`)} AS ${sql.raw(`${alias}_kind`)}`,\n    );\n  }\n  for (const [index, orderSpec] of (ast.orderBy ?? []).entries()) {\n    const value = compileOrderFieldValue(\n      ast,\n      orderSpec.field,\n      dialect,\n      orderSpec.field.__type === \"field_ref\" ?\n        cteAliasFor(orderSpec.field.alias)\n      : (collapsedTraversalCteAlias ?? \"\"),\n    );\n    columns.push(\n      sql`${value} AS ${sql.raw(`${LATE_MAT_SORT_KEY_PREFIX}${index}`)}`,\n    );\n  }\n\n  const innerOrderBy = buildStandardOrderBy({\n    ast,\n    dialect,\n    ...(collapsedTraversalCteAlias === undefined ?\n      {}\n    : { collapsedTraversalCteAlias }),\n  });\n  const limitOffset = buildLimitOffsetClause({\n    limit: input.limit,\n    offset: input.offset,\n    dialect,\n  });\n\n  const parts: SqlFragment[] = [\n    sql`SELECT ${sql.join(columns, sql`, `)}`,\n    fromClause,\n  ];\n  if (input.where !== undefined) parts.push(input.where);\n  if (innerOrderBy !== undefined) parts.push(innerOrderBy);\n  if (limitOffset !== undefined) parts.push(limitOffset);\n\n  return sql`${sql.raw(LATE_MAT_TOPK_CTE_ALIAS)} AS (${sql.join(parts, sql` `)})`;\n}\n\n/**\n * The outer projection: each selective field sourced from the re-joined\n * physical node table alias `lm_<alias>` rather than a candidate CTE, so the\n * deferred columns are read only for the surviving rows.\n */\nexport function buildLateMaterializedOuterProjection(\n  ast: QueryAst,\n  dialect: DialectAdapter,\n): SqlFragment {\n  const columns = (ast.selectiveFields ?? []).map((field) => {\n    const physicalAlias = lateMaterializedPhysicalAlias(field.alias);\n    if (field.isSystemField) {\n      const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n      return sql`${compileColumnReference(physicalAlias, dbColumn)} AS ${quoteIdentifier(field.outputName)}`;\n    }\n    const extracted = compileSelectivePropsExtraction(\n      field,\n      compileColumnReference(physicalAlias, \"props\"),\n      dialect,\n    );\n    return sql`${extracted} AS ${quoteIdentifier(field.outputName)}`;\n  });\n  return sql.join(columns, sql`, `);\n}\n\n/**\n * The outer ORDER BY: re-orders the LIMIT survivors by the `__lm_sk{n}` sort\n * values carried out of the topK CTE, matching `buildStandardOrderBy`'s\n * null-ordering semantics.\n */\nexport function buildLateMaterializedOuterOrderBy(\n  ast: QueryAst,\n): SqlFragment | undefined {\n  const orderBy = ast.orderBy ?? [];\n  if (orderBy.length === 0) return undefined;\n  const topk = sql.raw(LATE_MAT_TOPK_CTE_ALIAS);\n  const parts: SqlFragment[] = [];\n  for (const [index, orderSpec] of orderBy.entries()) {\n    const column = sql`${topk}.${sql.raw(`${LATE_MAT_SORT_KEY_PREFIX}${index}`)}`;\n    const nulls = resolveNullOrdering(orderSpec);\n    parts.push(compileOrderTerm(column, orderSpec.direction, nulls));\n  }\n  return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\nfunction fieldRefKey(field: FieldRef): string {\n  const pointer = field.jsonPointer ?? \"\";\n  return `${field.alias}:${field.path.join(\".\")}:${pointer}`;\n}\n\nfunction resolveEmbeddingFieldPath(field: FieldRef): string {\n  if (\n    field.jsonPointer !== undefined &&\n    field.jsonPointer !== \"\" &&\n    field.jsonPointer !== \"/\"\n  ) {\n    return field.jsonPointer.replace(/^\\//u, \"\").replaceAll(\"/\", \".\");\n  }\n\n  if (field.path[0] === \"props\") {\n    return field.path.slice(1).join(\".\");\n  }\n\n  return field.path.join(\".\");\n}\n\ntype BuildStandardGroupByInput = Readonly<{\n  ast: QueryAst;\n  dialect: DialectAdapter;\n}>;\n\nexport function buildStandardGroupBy(\n  input: BuildStandardGroupByInput,\n): SqlFragment | undefined {\n  const { ast, dialect } = input;\n  if (!ast.groupBy || ast.groupBy.fields.length === 0) {\n    return undefined;\n  }\n\n  const seenKeys = new Set<string>();\n  const allFields: (DatabaseExpression | FieldRef)[] = [];\n\n  for (const projectedField of ast.projection.fields) {\n    if (projectedField.source.__type === \"field_ref\") {\n      const key = fieldRefKey(projectedField.source);\n      if (!seenKeys.has(key)) {\n        seenKeys.add(key);\n        allFields.push(projectedField.source);\n      }\n    }\n  }\n\n  for (const field of ast.groupBy.fields) {\n    if (field.__type === \"database_expression\") {\n      allFields.push(field);\n      continue;\n    }\n    const key = fieldRefKey(field);\n    if (!seenKeys.has(key)) {\n      seenKeys.add(key);\n      allFields.push(field);\n    }\n  }\n\n  if (allFields.length === 0) {\n    return undefined;\n  }\n\n  const aliasToCte = buildAliasToCteMap(ast);\n  const parts = allFields.map((field) =>\n    field.__type === \"database_expression\" ?\n      compileStandardDatabaseExpression(ast, field, dialect, undefined, false)\n    : compileFieldValue(\n        field,\n        dialect,\n        field.valueType,\n        aliasToCte.get(field.alias) ?? `cte_${field.alias}`,\n      ),\n  );\n\n  return sql`GROUP BY ${sql.join(parts, sql`, `)}`;\n}\n\n/** Filters completed alias matches, never the candidate or optional-match CTEs. */\nexport function buildStandardResultWhere(\n  input: Readonly<{\n    ast: QueryAst;\n    ctx: PredicateCompilerContext;\n  }>,\n): SqlFragment | undefined {\n  const { ast, ctx } = input;\n  if (ast.resultPredicate === undefined) return undefined;\n  const aliases = buildAliasToCteMap(ast);\n  const condition = compilePredicateExpression(ast.resultPredicate, {\n    ...ctx,\n    databaseExpressionAggregates: false,\n    resolveFieldCteAlias: (field) =>\n      aliases.get(field.alias) ?? `cte_${field.alias}`,\n  });\n  return sql`WHERE ${condition}`;\n}\n\ntype BuildStandardHavingInput = Readonly<{\n  ast: QueryAst;\n  ctx: PredicateCompilerContext;\n}>;\n\nexport function buildStandardHaving(\n  input: BuildStandardHavingInput,\n): SqlFragment | undefined {\n  const { ast, ctx } = input;\n  if (!ast.having) {\n    return undefined;\n  }\n\n  const condition = compilePredicateExpression(ast.having, {\n    ...ctx,\n    databaseExpressionAggregates: true,\n  });\n  return sql`HAVING ${condition}`;\n}\n\ntype BuildStandardEmbeddingsCteInput = Readonly<{\n  ctx: PredicateCompilerContext;\n  graphId: string;\n  nodeKinds: readonly string[];\n  vectorPredicate: VectorSimilarityPredicate;\n}>;\n\n/**\n * Builds the relevance CTE for a `field.similarTo(...)` predicate in the query\n * builder.\n *\n * Default (exact): splices the strategy's `distanceExpression` and scans each\n * declaring kind's per-field table (`ORDER BY distance LIMIT k`). On\n * pgvector >= 0.8 the planner can serve this shape from an HNSW index for a\n * single-kind alias; on the SQLite-family engines it is a full scan.\n *\n * Opt-in (`{ approximate: true }`): each declaring kind's branch compiles to\n * the strategy's own search SQL — the engine-native ANN form (vec0\n * `MATCH … k=`, libSQL `vector_top_k`, pgvector's index-eligible scan) —\n * scoped to the alias's candidate nodes via the same `candidates` pushdown\n * the search facade uses. Semantics become approximate (index recall); a\n * slot declared `indexType: \"none\"` degrades to the exact scan, and a\n * `metric` override the slot's ANN structure cannot serve is refused rather\n * than degraded (see {@link assertApproximateMetricSupported}).\n */\nexport function buildStandardEmbeddingsCte(\n  input: BuildStandardEmbeddingsCteInput,\n): SqlFragment {\n  const { ctx, graphId, nodeKinds, vectorPredicate } = input;\n  const { field, metric, minScore, queryEmbedding } = vectorPredicate;\n\n  if (nodeKinds.length === 0) {\n    throw new UnsupportedPredicateError(\n      \"Vector predicate must resolve to at least one node kind\",\n    );\n  }\n\n  const { vectorStrategy } = ctx;\n  if (vectorStrategy === undefined) {\n    throw new UnsupportedPredicateError(\n      \"Vector similarity predicate requires a backend with a vector strategy\",\n    );\n  }\n\n  const fieldPath = resolveEmbeddingFieldPath(field);\n  const vectorSlots = ctx.vectorSlots;\n  const scopedNodes = buildScopedNodeIdsSubquery(field.alias);\n\n  // Only the kinds in this alias that actually DECLARE the embedding\n  // field back a per-field table. Skipping kinds without a slot keeps\n  // similarTo() from referencing a table that was never created and\n  // stops rank weight leaking from kinds that happen to share a\n  // field_path but don't embed it.\n  const declaringKinds = nodeKinds.filter((kind) =>\n    vectorSlots?.has(vectorSlotKey(kind, fieldPath)),\n  );\n\n  // Per-kind relevance scan against the strategy's typed per-field\n  // table. The strategy owns the engine-specific distance fragment\n  // (`<=>` / `vec_distance_cosine` / `vector_distance_cos`); the score\n  // and minScore math around it stays shared so the OUTPUT columns\n  // (node_id, node_kind, distance, score, ord) are identical across\n  // engines and the hybrid RRF / vector ORDER BY paths are untouched.\n  const branches = declaringKinds.map((kind) => {\n    const tableName = vectorStrategy.tableName(graphId, kind, fieldPath);\n    const slotDescriptor = vectorSlots?.get(vectorSlotKey(kind, fieldPath));\n    // Use the predicate's explicit metric if given, else this kind's DECLARED\n    // metric (the one its ANN index was built for). Resolving per kind keeps an\n    // includeSubClasses union correct when subkinds declare different metrics.\n    const branchMetric = metric ?? slotDescriptor?.metric ?? \"cosine\";\n\n    // Approximate opt-in: retrieve this kind's candidates via the\n    // strategy's own search SQL — the engine's native ANN form — scoped to\n    // the alias's candidate nodes (predicates, currency, traversal\n    // reachability) via the same `candidates` pushdown the search facade\n    // uses. A slot declared `indexType: \"none\"` compiles to the strategy's\n    // exact scan, so the opt-in degrades to today's semantics. Distance is\n    // re-derived from the strategy's score convention (cosine score =\n    // `1 - distance`; l2 / inner_product score = raw distance) so the\n    // shared ORDER BY / ROW_NUMBER machinery below is untouched.\n    //\n    // The ANN path additionally requires the effective metric to MATCH the\n    // slot's declared metric: every engine materializes metric-specific\n    // ANN structures (vec0 bakes `distance_metric` into the virtual table,\n    // libSQL's DiskANN index and pgvector's operator class are built for\n    // one metric), so retrieving by the declared metric and re-scoring\n    // under an overridden one would silently miss the override metric's\n    // true nearest neighbors.\n    //\n    // A caller who STATED `approximate: true` for such a slot is refused\n    // ({@link assertApproximateMetricSupported}) rather than quietly served\n    // the exact scan: the two options cannot both be honored, and which one\n    // was dropped is not something the caller can see in the results. Where\n    // nothing was stated the fallback stays silent because nothing is being\n    // ignored — engines whose `buildSearch` is EXACT (vec0's brute-force C\n    // KNN) serve the non-approximate branch through the engine form when the\n    // metric matches (identical results to the SQL distance scan at engine\n    // speed: 489ms -> 113ms at 50k on the SQLite lane) and through the SQL\n    // scan when it does not.\n    if (slotDescriptor !== undefined) {\n      assertApproximateMetricSupported({\n        approximate: vectorPredicate.approximate,\n        requestedMetric: metric,\n        declaredMetric: slotDescriptor.metric,\n        indexType: slotDescriptor.indexType,\n        nodeKind: kind,\n        fieldPath,\n      });\n    }\n    const engineFormEligible =\n      vectorPredicate.approximate === true ||\n      vectorStrategy.searchIsExact === true;\n    const annSlot =\n      engineFormEligible && branchMetric === slotDescriptor?.metric ?\n        slotDescriptor\n      : undefined;\n    if (annSlot !== undefined) {\n      ctx.annIndexTypes?.add(annSlot.indexType);\n      // Membership candidates WITHOUT the scoped subquery's DISTINCT:\n      // strategies embed these as `node_id IN (...)`, where duplicates\n      // cannot change the result — and the DISTINCT is what kept\n      // PostgreSQL off the ordered ANN index scan entirely (verified:\n      // the identical statement flips from a full sort to an HNSW\n      // Index Scan when the DISTINCT is dropped; even\n      // `enable_seqscan = off` could not rescue the DISTINCT form).\n      // The JOIN consumers (exact branch, fulltext CTE) keep\n      // buildScopedNodeIdsSubquery's DISTINCT — a join DOES multiply\n      // rows on duplicates.\n      const candidateCte = `${ALIAS_CTE_PREFIX}${field.alias}`;\n      const kindCandidates = sql`SELECT ${qualifyColumn(candidateCte, `${field.alias}_id`)} FROM ${quoteIdentifier(candidateCte)} WHERE ${qualifyColumn(candidateCte, `${field.alias}_kind`)} = ${kind}`;\n      const annSql = vectorStrategy.buildSearch(\n        {\n          graphId,\n          nodeKind: kind,\n          fieldPath,\n          dimensions: annSlot.dimensions,\n          metric: branchMetric,\n          indexType: annSlot.indexType,\n        },\n        {\n          graphId,\n          nodeKind: kind,\n          fieldPath,\n          queryEmbedding,\n          metric: branchMetric,\n          dimensions: annSlot.dimensions,\n          indexType: annSlot.indexType,\n          limit: vectorPredicate.limit,\n          ...(minScore === undefined ? {} : { minScore }),\n        },\n        kindCandidates,\n      );\n      const distanceFromScore =\n        branchMetric === \"cosine\" ? sql.raw(\"(1.0 - score)\") : sql.raw(\"score\");\n      return sql`\n        SELECT node_id, ${kind} AS node_kind, ${distanceFromScore} AS distance, score\n        FROM (${annSql}) AS tg_ann_src\n      `;\n    }\n    const distanceExpr = vectorStrategy.distanceExpression(\n      qualifyColumn(tableName, \"embedding\"),\n      queryEmbedding,\n      branchMetric,\n    );\n    // EXACT MEANS EXACT: this branch is the non-approximate path, but on\n    // pgvector any `ORDER BY embedding <=> q LIMIT k` whose expression\n    // matches the ANN opclass is silently served by the HNSW/IVFFlat\n    // index — approximate results with plan-dependent recall (measured\n    // recall 0.980 unfiltered, 0.000 under a selective filter at 50k,\n    // where the index frontier starves). `+ 0.0` makes the ordered\n    // expression unmatchable to the opclass, forcing the true flat scan;\n    // numerically identity, and inert on engines whose ANN forms are\n    // opt-in anyway (vec0 MATCH, libSQL vector_top_k). The sanctioned\n    // index path is `approximate: true` above.\n    const exactDistanceExpr = sql`(${distanceExpr} + 0.0)`;\n    const scoreExpr = vectorScoreExpression(distanceExpr, branchMetric);\n\n    const conditions: SqlFragment[] = [\n      sql`${qualifyColumn(tableName, \"graph_id\")} = ${graphId}`,\n    ];\n    if (minScore !== undefined) {\n      // minScore validation (finiteness, cosine range) is handled by the\n      // vector predicate pass in passes/vector.ts — no redundant check.\n      conditions.push(\n        vectorMinScoreCondition(distanceExpr, branchMetric, minScore),\n      );\n    }\n\n    return sql`\n      SELECT\n        ${qualifyColumn(tableName, \"node_id\")} AS node_id,\n        ${kind} AS node_kind,\n        ${exactDistanceExpr} AS distance,\n        ${scoreExpr} AS score\n      FROM ${quoteIdentifier(tableName)}\n      INNER JOIN ${scopedNodes}\n        ON ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_id`)} =\n           ${qualifyColumn(tableName, \"node_id\")}\n       AND ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_kind`)} = ${kind}\n      WHERE ${sql.join(conditions, sql` AND `)}\n    `;\n  });\n\n  // No declaring kind → emit a CTE with the right column shape that\n  // yields no rows, so the rest of the emitter (which always references\n  // cte_embeddings) compiles and simply matches nothing.\n  const unionBody =\n    branches.length === 0 ?\n      emptyEmbeddingsBody()\n    : sql.join(\n        branches,\n        sql`\n          UNION ALL\n        `,\n      );\n\n  // Inner SELECT applies the predicate's k-cutoff, then ROW_NUMBER ranks\n  // over that bounded set. Without the inner LIMIT, a hybrid query would\n  // assign vector ordinals to every candidate, letting documents far\n  // outside the requested top-k contribute to the RRF fused score and\n  // reorder final results.\n  return sql`\n    ${sql.raw(EMBEDDINGS_CTE_ALIAS)} AS (\n      SELECT\n        node_id,\n        node_kind,\n        distance,\n        score,\n        ROW_NUMBER() OVER (ORDER BY distance ASC) AS ord\n      FROM (\n        ${unionBody}\n        ORDER BY distance ASC\n        LIMIT ${vectorPredicate.limit}\n      ) AS vec_inner\n    )\n  `;\n}\n\n/**\n * A no-row inner body carrying the exact `(node_id, node_kind, distance,\n * score)` column contract, used when no kind in the alias declares the\n * embedding field. `WHERE 1 = 0` keeps the planner from scanning.\n */\nfunction emptyEmbeddingsBody(): SqlFragment {\n  return sql`\n    SELECT\n      CAST(NULL AS TEXT) AS node_id,\n      CAST(NULL AS TEXT) AS node_kind,\n      CAST(NULL AS REAL) AS distance,\n      CAST(NULL AS REAL) AS score\n    WHERE 1 = 0\n  `;\n}\n\n// ============================================================\n// Fulltext Search CTE\n// ============================================================\n\ntype BuildStandardFulltextCteInput = Readonly<{\n  ctx: PredicateCompilerContext;\n  fulltextPredicate: FulltextMatchPredicate;\n  graphId: string;\n  nodeKinds: readonly string[];\n}>;\n\nexport function buildStandardFulltextCte(\n  input: BuildStandardFulltextCteInput,\n): SqlFragment {\n  const { ctx, fulltextPredicate, graphId, nodeKinds } = input;\n  const { dialect, schema } = ctx;\n  const { query, mode, language, limit, minScore } = fulltextPredicate;\n\n  if (nodeKinds.length === 0) {\n    throw new UnsupportedPredicateError(\n      \"Fulltext predicate must resolve to at least one node kind\",\n    );\n  }\n\n  const tableName = schema.tables.fulltext;\n  const scopedNodes = buildScopedNodeIdsSubquery(fulltextPredicate.field.alias);\n  const fulltextStrategy = dialect.fulltext;\n  if (fulltextStrategy === undefined) {\n    throw new UnsupportedPredicateError(\n      `Fulltext match predicates are not supported for dialect \"${dialect.name}\"`,\n    );\n  }\n  // Parse the query with a CONSTANT language whenever possible: the\n  // caller's explicit override, else the one declared language shared by\n  // every kind in the alias (rows are written with their kind's declared\n  // language, so this matches the stored tsv). A constant keeps the\n  // tsquery plan-time-stable, so PostgreSQL's GIN index on `tsv` can\n  // serve the match — the per-row `websearch_to_tsquery(\"language\", ...)`\n  // fallback (mixed-language aliases only) forces a scan of the kinds'\n  // rows.\n  const effectiveLanguage =\n    language ?? sharedDeclaredLanguage(ctx.fulltextLanguages, nodeKinds);\n  const matchCondition = fulltextStrategy.matchCondition(\n    tableName,\n    query,\n    mode,\n    effectiveLanguage,\n  );\n  const rankExpression = fulltextStrategy.rankExpression(\n    tableName,\n    query,\n    mode,\n    effectiveLanguage,\n  );\n\n  const conditions: SqlFragment[] = [\n    sql`${qualifyColumn(tableName, \"graph_id\")} = ${graphId}`,\n    compileKindFilter(qualifyColumn(tableName, \"node_kind\"), nodeKinds),\n    matchCondition,\n  ];\n  if (minScore !== undefined) {\n    conditions.push(sql`${rankExpression} >= ${minScore}`);\n  }\n\n  // Inner SELECT computes the rank once into an alias, outer SELECT\n  // adds the ordinal via ROW_NUMBER. Two reasons to nest:\n  // (1) Postgres re-evaluates `ts_rank_cd(...)` if it's repeated across\n  // SELECT/ORDER BY, so referencing the alias avoids duplicate work.\n  // (2) SQLite FTS5's bm25() cannot appear inside a window function's\n  // OVER clause — the auxiliary-function context is restricted.\n  return sql`\n    ${sql.raw(FULLTEXT_CTE_ALIAS)} AS (\n      SELECT\n        node_id,\n        node_kind,\n        rank,\n        ROW_NUMBER() OVER (ORDER BY rank DESC, node_id ASC) AS ord\n      FROM (\n        SELECT\n          ${qualifyColumn(tableName, \"node_id\")} AS node_id,\n          ${qualifyColumn(tableName, \"node_kind\")} AS node_kind,\n          ${rankExpression} AS rank\n        FROM ${schema.fulltextTable}\n        INNER JOIN ${scopedNodes}\n          ON ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_id`)} =\n             ${qualifyColumn(tableName, \"node_id\")}\n         AND ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_kind`)} =\n             ${qualifyColumn(tableName, \"node_kind\")}\n        WHERE ${sql.join(conditions, sql` AND `)}\n        ORDER BY rank DESC, ${qualifyColumn(tableName, \"node_id\")} ASC\n        LIMIT ${limit}\n      ) AS fts_inner\n    )\n  `;\n}\n\n/**\n * The single declared language shared by every kind in the alias that\n * declares searchable fields, or `undefined` when they disagree (or none\n * declares any — such kinds contribute no fulltext rows either way).\n */\nfunction sharedDeclaredLanguage(\n  fulltextLanguages: ReadonlyMap<string, string> | undefined,\n  nodeKinds: readonly string[],\n): string | undefined {\n  if (fulltextLanguages === undefined) return undefined;\n  const languages = new Set<string>();\n  for (const kind of nodeKinds) {\n    const language = fulltextLanguages.get(kind);\n    if (language !== undefined) languages.add(language);\n  }\n  if (languages.size !== 1) return undefined;\n  return [...languages][0];\n}\n\nexport function buildStandardHybridCandidateCte(): SqlFragment {\n  return sql`\n    ${sql.raw(HYBRID_CANDIDATES_CTE_ALIAS)} AS (\n      SELECT node_id, node_kind FROM ${sql.raw(EMBEDDINGS_CTE_ALIAS)}\n      UNION\n      SELECT node_id, node_kind FROM ${sql.raw(FULLTEXT_CTE_ALIAS)}\n    )\n  `;\n}\n\n/**\n * Compiles user-supplied `orderBy` clauses into `SqlFragment` values suitable\n * for appending after a relevance-driven primary ORDER BY (vector,\n * fulltext, or hybrid RRF).\n */\nfunction compileUserOrderBy(\n  ast: QueryAst,\n  dialect: DialectAdapter,\n): readonly SqlFragment[] {\n  if (!ast.orderBy || ast.orderBy.length === 0) return [];\n\n  const aliasToCte = buildAliasToCteMap(ast);\n  const fragments: SqlFragment[] = [];\n  for (const orderSpec of ast.orderBy) {\n    const valueType = orderSpec.field.valueType;\n    if (valueType === \"array\" || valueType === \"object\") {\n      throw new UnsupportedPredicateError(\n        \"Ordering by JSON arrays or objects is not supported\",\n      );\n    }\n    const cteAlias =\n      orderSpec.field.__type === \"field_ref\" ?\n        (aliasToCte.get(orderSpec.field.alias) ??\n        `${ALIAS_CTE_PREFIX}${orderSpec.field.alias}`)\n      : \"\";\n    const field = compileOrderFieldValue(\n      ast,\n      orderSpec.field,\n      dialect,\n      cteAlias,\n    );\n    const nulls = resolveNullOrdering(orderSpec);\n    fragments.push(compileOrderTerm(field, orderSpec.direction, nulls));\n  }\n  return fragments;\n}\n\ntype BuildStandardFulltextOrderByInput = Readonly<{\n  ast: QueryAst;\n  dialect: DialectAdapter;\n}>;\n\n/**\n * ORDER BY clause when only a fulltext predicate is present.\n * Orders by rank DESC then any user-supplied ORDER BY as tiebreakers.\n */\nexport function buildStandardFulltextOrderBy(\n  input: BuildStandardFulltextOrderByInput,\n): SqlFragment {\n  const { ast, dialect } = input;\n  const rankOrder = sql.raw(`${FULLTEXT_CTE_ALIAS}.rank DESC`);\n  const userOrders = compileUserOrderBy(ast, dialect);\n  return sql`ORDER BY ${sql.join([rankOrder, ...userOrders], sql`, `)}`;\n}\n\n/**\n * ORDER BY clause when BOTH vector and fulltext predicates are present.\n *\n * Reciprocal Rank Fusion at SQL level. Each CTE emits an `ord` ordinal\n * via ROW_NUMBER; the outer ORDER BY blends them as\n * `w_vec / (k + ord_vec) + w_ft / (k + ord_ft)`. NULL `ord` (a node\n * matched by only one source) makes that source's term NULL → COALESCE-to-0\n * absorbs it. User-supplied `orderBy` clauses follow as tiebreakers,\n * matching the single-source paths so pagination stays stable across\n * RRF score ties.\n *\n * Defaults: k=60, vector weight = fulltext weight = 1. Override via\n * `.fuseWith({ k, weights })` on the query builder.\n */\n\ntype BuildStandardHybridRrfOrderByInput = Readonly<{\n  ast: QueryAst;\n  dialect: DialectAdapter;\n  fusion: HybridFusionOptions | undefined;\n}>;\n\nexport function buildStandardHybridRrfOrderBy(\n  input: BuildStandardHybridRrfOrderByInput,\n): SqlFragment {\n  const { ast, dialect, fusion } = input;\n  const k = fusion?.k ?? DEFAULT_RRF_K;\n  const vectorWeight = fusion?.weights?.vector ?? DEFAULT_RRF_WEIGHT;\n  const fulltextWeight = fusion?.weights?.fulltext ?? DEFAULT_RRF_WEIGHT;\n\n  // Invariant: validateHybridFusionOptions has already rejected\n  // non-finite / negative values before we reach here. sql.raw on these\n  // numeric constants is deliberate — they're schema-level config, not\n  // user-bindable.\n  // `* 1.0` is also deliberate: PostgreSQL otherwise performs integer\n  // division when the default weight and rank constant are integers. Keep\n  // this promotion in lockstep with the backend hybrid statement emitter.\n  const rrfOrder = sql.raw(\n    `(COALESCE((${vectorWeight} * 1.0) / (${k} + ${EMBEDDINGS_CTE_ALIAS}.ord), 0) + ` +\n      `COALESCE((${fulltextWeight} * 1.0) / (${k} + ${FULLTEXT_CTE_ALIAS}.ord), 0)) DESC`,\n  );\n  // Deterministic tiebreak on the CTE-projected node_id. At least one of\n  // the two CTEs always has a non-NULL node_id for any row returned by\n  // the LEFT JOIN-union shape, so COALESCE always resolves. This matches\n  // `store.search.hybrid`'s JS-side code-unit `compareStrings(nodeId)`\n  // tiebreak so the two paths produce identical top-k under ties (SQLite\n  // BINARY collation is code-unit order for the ASCII id alphabet).\n  const idTiebreak = sql.raw(\n    `COALESCE(${FULLTEXT_CTE_ALIAS}.node_id, ${EMBEDDINGS_CTE_ALIAS}.node_id) ASC`,\n  );\n  const userOrders = compileUserOrderBy(ast, dialect);\n  return sql`ORDER BY ${sql.join([rrfOrder, ...userOrders, idTiebreak], sql`, `)}`;\n}\n\ntype BuildStandardVectorOrderByInput = Readonly<{\n  ast: QueryAst;\n  dialect: DialectAdapter;\n}>;\n\nexport function buildStandardVectorOrderBy(\n  input: BuildStandardVectorOrderByInput,\n): SqlFragment {\n  const { ast, dialect } = input;\n  const distanceOrder = sql.raw(`${EMBEDDINGS_CTE_ALIAS}.distance ASC`);\n  const userOrders = compileUserOrderBy(ast, dialect);\n  return sql`ORDER BY ${sql.join([distanceOrder, ...userOrders], sql`, `)}`;\n}\n\ntype BuildLimitOffsetClauseInput = Readonly<{\n  dialect: DialectAdapter;\n  limit: number | undefined;\n  offset: number | undefined;\n}>;\n\nexport function buildLimitOffsetClause(\n  input: BuildLimitOffsetClauseInput,\n): SqlFragment | undefined {\n  const parts = compileLimitOffsetClauses(\n    input.limit,\n    input.offset,\n    input.dialect,\n  );\n  return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\n}\n","import {\n  UnsupportedBackendCapabilityError,\n  UnsupportedPredicateError,\n} from \"../../../errors\";\nimport type { FulltextMatchPredicate, QueryAst } from \"../../ast\";\nimport type { DialectAdapter } from \"../../dialect\";\nimport { extractFulltextMatchPredicates } from \"../predicates\";\n\nexport type FulltextPredicatePassResult = Readonly<{\n  fulltextPredicate: FulltextMatchPredicate | undefined;\n}>;\n\n/**\n * Validates fulltext predicate placement and cardinality.\n *\n * Invariants mirror the vector predicate pass:\n * - Fulltext predicates must not appear under OR/NOT branches.\n * - At most one fulltext predicate is allowed per query.\n * - The dialect must declare fulltext support.\n */\nexport function runFulltextPredicatePass(\n  ast: QueryAst,\n  dialect: DialectAdapter,\n): FulltextPredicatePassResult {\n  const fulltextPredicates = extractFulltextMatchPredicates(ast.predicates);\n  if (fulltextPredicates.length > 1) {\n    throw new UnsupportedPredicateError(\n      \"Multiple fulltext match predicates in a single query are not supported\",\n    );\n  }\n\n  const fulltextPredicate = fulltextPredicates[0];\n  if (fulltextPredicate === undefined) {\n    return { fulltextPredicate: undefined };\n  }\n\n  if (!dialect.capabilities.supportsFulltext) {\n    throw new UnsupportedBackendCapabilityError(\n      \"$fulltext.matches()\",\n      \"fulltext\",\n      { dialect: dialect.name, reason: \"fulltext_unsupported\" },\n      \"This backend declares no fulltext capability: it was created with `fulltext: false`, or it omits `capabilities.fulltext`.\",\n    );\n  }\n\n  const strategy = dialect.fulltext;\n  if (strategy === undefined) {\n    throw new UnsupportedPredicateError(\n      `Dialect \"${dialect.name}\" advertises fulltext support but has no strategy configured`,\n    );\n  }\n\n  if (!strategy.supportedModes.includes(fulltextPredicate.mode)) {\n    throw new UnsupportedPredicateError(\n      `Fulltext query mode \"${fulltextPredicate.mode}\" is not supported by the \"${strategy.name}\" strategy. Supported modes: ${strategy.supportedModes.join(\", \")}.`,\n    );\n  }\n\n  if (\n    fulltextPredicate.language !== undefined &&\n    !strategy.supportsLanguageOverride\n  ) {\n    throw new UnsupportedPredicateError(\n      `Fulltext strategy \"${strategy.name}\" does not honor a per-query \\`language\\` override ` +\n        `(its tokenizer is fixed at table-create time). Drop the option, or use a strategy ` +\n        `that advertises \\`supportsLanguageOverride: true\\`.`,\n    );\n  }\n\n  if (\n    !Number.isFinite(fulltextPredicate.limit) ||\n    fulltextPredicate.limit <= 0\n  ) {\n    throw new UnsupportedPredicateError(\n      `Fulltext match limit must be a positive finite number, got ${String(fulltextPredicate.limit)}`,\n    );\n  }\n\n  const { minScore } = fulltextPredicate;\n  if (minScore !== undefined && !Number.isFinite(minScore)) {\n    throw new UnsupportedPredicateError(\n      `Fulltext minScore must be a finite number, got ${String(minScore)}`,\n    );\n  }\n\n  return { fulltextPredicate };\n}\n","import { UnsupportedPredicateError } from \"../../../errors\";\nimport type {\n  FulltextMatchPredicate,\n  HybridFusionOptions,\n  QueryAst,\n  VectorSimilarityPredicate,\n} from \"../../ast\";\n\nexport type FusionConfigPassResult = Readonly<{\n  fusion: HybridFusionOptions | undefined;\n}>;\n\n/**\n * Validates that `.fuseWith()` configuration is coherent with the query\n * shape. Runs after the vector and fulltext predicate passes.\n *\n * - When no `fusion` is configured, returns `{ fusion: undefined }`.\n * - When `fusion` is configured but either predicate is missing, throws.\n * - When the predicates target different aliases, throws.\n */\nexport function runFusionConfigPass(\n  ast: QueryAst,\n  vectorPredicate: VectorSimilarityPredicate | undefined,\n  fulltextPredicate: FulltextMatchPredicate | undefined,\n): FusionConfigPassResult {\n  const fusion = ast.fusion;\n  if (fusion === undefined) return { fusion: undefined };\n\n  if (vectorPredicate === undefined || fulltextPredicate === undefined) {\n    throw new UnsupportedPredicateError(\n      `.fuseWith() requires both a .similarTo() and a .$fulltext.matches() ` +\n        `predicate in the same query. Remove .fuseWith(), or add the missing ` +\n        `predicate.`,\n    );\n  }\n  if (vectorPredicate.field.alias !== fulltextPredicate.field.alias) {\n    throw new UnsupportedPredicateError(\n      `.fuseWith() requires .similarTo() and .$fulltext.matches() to target ` +\n        `the same node alias. Got vector=${vectorPredicate.field.alias}, ` +\n        `fulltext=${fulltextPredicate.field.alias}.`,\n    );\n  }\n  return { fusion };\n}\n","import {\n  CompilerInvariantError,\n  UnsupportedPredicateError,\n} from \"../../../errors\";\nimport type { QueryAst, Traversal, VariableLengthSpec } from \"../../ast\";\n\n/**\n * Traversal with required variable-length spec.\n */\nexport type VariableLengthTraversal = Traversal & {\n  variableLength: VariableLengthSpec;\n};\n\n/**\n * Selects and validates the variable-length traversal target for recursive compilation.\n *\n * Invariants:\n * - Query must contain exactly one variable-length traversal.\n * - Recursive mode currently supports only a single traversal in the query.\n */\nexport function runRecursiveTraversalSelectionPass(\n  ast: QueryAst,\n): VariableLengthTraversal {\n  const variableLengthTraversal = ast.traversals.find(\n    (traversal): traversal is VariableLengthTraversal =>\n      traversal.variableLength !== undefined,\n  );\n\n  if (variableLengthTraversal === undefined) {\n    throw new CompilerInvariantError(\"No variable-length traversal found\");\n  }\n\n  if (ast.traversals.length > 1) {\n    throw new UnsupportedPredicateError(\n      \"Variable-length traversals with multiple traversals are not yet supported. \" +\n        \"Please use a single variable-length traversal.\",\n    );\n  }\n\n  return variableLengthTraversal;\n}\n","export type CompilerPass<TState, TPassName extends string, TOutput> = Readonly<{\n  name: TPassName;\n  execute: (state: TState) => TOutput;\n  update: (state: TState, output: TOutput) => TState;\n}>;\n\nexport type CompilerPassResult<TState> = Readonly<{\n  state: TState;\n}>;\n\nexport function runCompilerPass<TState, TPassName extends string, TOutput>(\n  state: TState,\n  pass: CompilerPass<TState, TPassName, TOutput>,\n): CompilerPassResult<TState> {\n  const output = pass.execute(state);\n  return {\n    state: pass.update(state, output),\n  };\n}\n","import type { QueryAst } from \"../../ast\";\nimport { type SqlFragment } from \"../../sql-fragment\";\nimport { type RecordedReadBinding } from \"../schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstantFor,\n  extractTemporalOptions,\n  type ReadInstantMode,\n} from \"../temporal\";\n\nexport type TemporalFilterPass = Readonly<{\n  forAlias: (tableAlias?: string) => SqlFragment;\n  /**\n   * The bound \"current\" valid-time read instant, sampled once when this pass is\n   * created — the same value {@link forAlias} compares against. Exposed so\n   * point-in-time predicates that must NOT widen with the node-visibility mode\n   * (e.g. identity-assertion validity) can pin to the identical instant instead\n   * of resampling the clock, which would break the single-snapshot invariant.\n   */\n  currentInstant: SqlFragment;\n}>;\n\n/**\n * Creates a temporal filter pass bound to a query AST.\n *\n * Invariant: all temporal clauses for a query use the same \"current\" instant,\n * bound once here from the application clock. In `\"literal\"` mode that is a\n * concrete value; in `\"placeholder\"` mode it is the reserved read-instant\n * placeholder (filled fresh per execution by the query builder's template\n * cache) — see {@link currentReadInstantFor}.\n */\nexport function createTemporalFilterPass(\n  ast: QueryAst,\n  readInstant: ReadInstantMode = \"literal\",\n  recordedReadBinding?: RecordedReadBinding,\n): TemporalFilterPass {\n  const currentTimestamp = currentReadInstantFor(readInstant);\n  return {\n    forAlias(tableAlias?: string): SqlFragment {\n      return compileTemporalFilter({\n        ...extractTemporalOptions(ast, tableAlias),\n        currentTimestamp,\n        recordedReadBinding,\n      });\n    },\n    currentInstant: currentTimestamp,\n  };\n}\n","import { type VectorMetric } from \"../../../backend/types\";\nimport { UnsupportedPredicateError } from \"../../../errors\";\nimport type { QueryAst, VectorSimilarityPredicate } from \"../../ast\";\nimport type { DialectAdapter } from \"../../dialect\";\nimport { type VectorStrategy } from \"../../dialect/vector-strategy\";\nimport { extractVectorSimilarityPredicates } from \"../predicates\";\n\nexport type VectorPredicatePassResult = Readonly<{\n  vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\n/**\n * Validates vector predicate placement, cardinality, and metric support.\n *\n * Invariants:\n * - Vector predicates must not appear under OR/NOT branches.\n * - At most one vector predicate is allowed per query.\n * - The requested metric must be supported by the active vector strategy.\n *\n * `vectorStrategy` is the backend-declared strategy that will generate the\n * relevance SQL (passed by the standard compile path). When present it is the\n * authoritative source for supported metrics — a custom strategy override may\n * advertise a different metric set than the dialect's built-in default. It is\n * omitted only by the plan-lowering path (recursive / set-operation queries),\n * which has no strategy plumbed and falls back to the dialect's metric list.\n */\nexport function runVectorPredicatePass(\n  ast: QueryAst,\n  dialect: DialectAdapter,\n  vectorStrategy?: VectorStrategy,\n): VectorPredicatePassResult {\n  const vectorPredicates = extractVectorSimilarityPredicates(ast.predicates);\n  if (vectorPredicates.length > 1) {\n    throw new UnsupportedPredicateError(\n      \"Multiple vector similarity predicates in a single query are not supported\",\n    );\n  }\n\n  const vectorPredicate = vectorPredicates[0];\n  if (vectorPredicate === undefined) {\n    return { vectorPredicate: undefined };\n  }\n\n  const predicateStrategy = dialect.capabilities.vectorPredicateStrategy;\n  if (predicateStrategy === \"unsupported\" || !dialect.supportsVectors) {\n    throw new UnsupportedPredicateError(\n      `Vector similarity predicates are not supported for dialect \"${dialect.name}\"`,\n    );\n  }\n\n  // Only an EXPLICIT metric is validated here. When omitted, the compiler\n  // resolves the field's declared `embedding()` metric per kind (validated\n  // when the field's index was materialized), so there is nothing to check yet.\n  if (vectorPredicate.metric !== undefined) {\n    const supportedMetrics: readonly VectorMetric[] =\n      vectorStrategy?.capabilities.metrics ??\n      dialect.capabilities.vectorMetrics;\n    if (!supportedMetrics.includes(vectorPredicate.metric)) {\n      throw new UnsupportedPredicateError(\n        vectorStrategy === undefined ?\n          `Vector metric \"${vectorPredicate.metric}\" is not supported for dialect \"${dialect.name}\"`\n        : `Vector metric \"${vectorPredicate.metric}\" is not supported by vector strategy \"${vectorStrategy.name}\" (supported: ${supportedMetrics.join(\", \")})`,\n      );\n    }\n  }\n\n  if (!Number.isFinite(vectorPredicate.limit) || vectorPredicate.limit <= 0) {\n    throw new UnsupportedPredicateError(\n      `Vector predicate limit must be a positive finite number, got ${String(vectorPredicate.limit)}`,\n    );\n  }\n\n  const { minScore } = vectorPredicate;\n  if (minScore !== undefined) {\n    if (!Number.isFinite(minScore)) {\n      throw new UnsupportedPredicateError(\n        `Vector minScore must be a finite number, got ${String(minScore)}`,\n      );\n    }\n    if (vectorPredicate.metric === \"cosine\" && Math.abs(minScore) > 1) {\n      throw new UnsupportedPredicateError(\n        `Cosine minScore must be between -1 and 1, got ${String(minScore)}`,\n      );\n    }\n  }\n\n  return { vectorPredicate };\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { requireDefined } from \"../../../utils/presence\";\nimport type {\n  AggregateExpr,\n  ComposableQuery,\n  FulltextMatchPredicate,\n  NodePredicate,\n  QueryAst,\n  SetOperation,\n  VectorSimilarityPredicate,\n} from \"../../ast\";\nimport {\n  getDialect,\n  type SqlDialect,\n  type VectorStrategy,\n} from \"../../dialect\";\nimport {\n  runFulltextPredicatePass,\n  runRecursiveTraversalSelectionPass,\n  runVectorPredicatePass,\n  type VariableLengthTraversal,\n} from \"../passes\";\nimport type {\n  AggregatePlanNode,\n  LimitOffsetPlanNode,\n  LogicalPlan,\n  LogicalPlanNode,\n  ProjectPlanNode,\n  ResultFilterPlanNode,\n} from \"./types\";\n\nexport type LowerStandardQueryToLogicalPlanInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias?: string;\n  dialect: SqlDialect;\n  effectiveLimit?: number;\n  fulltextPredicate?: FulltextMatchPredicate;\n  graphId: string;\n  vectorPredicate?: VectorSimilarityPredicate;\n}>;\n\nexport type LowerRecursiveQueryToLogicalPlanInput = Readonly<{\n  ast: QueryAst;\n  dialect: SqlDialect;\n  graphId: string;\n  traversal?: VariableLengthTraversal;\n}>;\n\nexport type LowerSetOperationToLogicalPlanInput = Readonly<{\n  dialect: SqlDialect;\n  graphId: string;\n  op: SetOperation;\n  /**\n   * The backend-configured vector strategy, threaded so a set-operation leaf's\n   * vector predicate validates against the same metric set as standalone leaf\n   * compilation (rather than only the dialect's fallback metric list).\n   */\n  vectorStrategy?: VectorStrategy;\n}>;\n\n/**\n * Creates a sequential plan node ID generator scoped to a single compilation invocation.\n * IDs are NOT stable across compilations — different compilations of the same query\n * may produce different IDs depending on pass execution order.\n */\nfunction createPlanNodeIdFactory(): () => string {\n  let current = 0;\n  return function nextPlanNodeId(): string {\n    current += 1;\n    return `plan_${current.toString(36)}`;\n  };\n}\n\nfunction extractAggregateExpressions(ast: QueryAst): readonly AggregateExpr[] {\n  const aggregates: AggregateExpr[] = [];\n\n  for (const field of ast.projection.fields) {\n    if (\"__type\" in field.source && field.source.__type === \"aggregate\") {\n      aggregates.push(field.source);\n    }\n  }\n\n  return aggregates;\n}\n\nfunction getAliasPredicates(\n  ast: QueryAst,\n  alias: string,\n  predicateTargetType: \"edge\" | \"node\",\n): readonly NodePredicate[] {\n  return ast.predicates.filter((predicate) => {\n    const targetType = predicate.targetType ?? \"node\";\n    return (\n      predicate.targetAlias === alias && targetType === predicateTargetType\n    );\n  });\n}\n\nfunction wrapWithAliasFilterNode(\n  currentNode: LogicalPlanNode,\n  ast: QueryAst,\n  alias: string,\n  predicateTargetType: \"edge\" | \"node\",\n  nextPlanNodeId: () => string,\n): LogicalPlanNode {\n  const aliasPredicates = getAliasPredicates(ast, alias, predicateTargetType);\n  if (aliasPredicates.length === 0) {\n    return currentNode;\n  }\n\n  return {\n    alias,\n    id: nextPlanNodeId(),\n    input: currentNode,\n    op: \"filter\",\n    predicateTargetType,\n    predicates: aliasPredicates.map((predicate) => predicate.expression),\n  };\n}\n\nfunction appendAggregateSortLimitAndProjectNodes(\n  currentNode: LogicalPlanNode,\n  ast: QueryAst,\n  nextPlanNodeId: () => string,\n  limit: number | undefined,\n  collapsedTraversalCteAlias?: string,\n): LogicalPlanNode {\n  let node: LogicalPlanNode =\n    ast.resultPredicate === undefined ?\n      currentNode\n    : ({\n        id: nextPlanNodeId(),\n        input: currentNode,\n        op: \"result_filter\",\n        predicate: ast.resultPredicate,\n      } satisfies ResultFilterPlanNode);\n\n  const aggregateExpressions = extractAggregateExpressions(ast);\n  if (\n    aggregateExpressions.length > 0 ||\n    ast.groupBy !== undefined ||\n    ast.having !== undefined\n  ) {\n    const aggregateNode: AggregatePlanNode = {\n      aggregates: aggregateExpressions,\n      groupBy: ast.groupBy?.fields ?? [],\n      id: nextPlanNodeId(),\n      input: node,\n      op: \"aggregate\",\n    };\n    node =\n      ast.having === undefined ?\n        aggregateNode\n      : { ...aggregateNode, having: ast.having };\n  }\n\n  const hasFieldOrderBy = ast.orderBy !== undefined && ast.orderBy.length > 0;\n  const hasAggregateOrderBy =\n    ast.aggregateOrderBy !== undefined && ast.aggregateOrderBy.length > 0;\n  if (hasFieldOrderBy || hasAggregateOrderBy) {\n    // The sort node's presence (not its `orderBy` payload) is what the\n    // emitter's plan-shape invariant reads — see `hasSort` in\n    // emitter/plan-inspector.ts. `orderBy` here can be `[]` when only\n    // `ast.aggregateOrderBy` is set; that's fine today since nothing reads\n    // this field's contents, only whether the node exists.\n    node = {\n      id: nextPlanNodeId(),\n      input: node,\n      op: \"sort\",\n      orderBy: ast.orderBy ?? [],\n    };\n  }\n\n  if (limit !== undefined || ast.offset !== undefined) {\n    const limitOffsetNodeBase: Omit<LimitOffsetPlanNode, \"limit\" | \"offset\"> = {\n      id: nextPlanNodeId(),\n      input: node,\n      op: \"limit_offset\",\n    };\n    const hasLimit = limit !== undefined;\n    const hasOffset = ast.offset !== undefined;\n\n    if (hasLimit && hasOffset) {\n      node = {\n        ...limitOffsetNodeBase,\n        limit,\n        offset: ast.offset,\n      };\n    } else if (hasLimit) {\n      node = { ...limitOffsetNodeBase, limit };\n    } else if (hasOffset) {\n      node = { ...limitOffsetNodeBase, offset: ast.offset };\n    } else {\n      throw new CompilerInvariantError(\n        \"limit_offset node requires limit or offset to be present\",\n      );\n    }\n  }\n\n  const projectNodeBase: Omit<ProjectPlanNode, \"collapsedTraversalAlias\"> = {\n    fields: ast.projection.fields,\n    id: nextPlanNodeId(),\n    input: node,\n    op: \"project\",\n  };\n  return collapsedTraversalCteAlias === undefined ? projectNodeBase : (\n      {\n        ...projectNodeBase,\n        collapsedTraversalAlias: collapsedTraversalCteAlias,\n      }\n    );\n}\n\ntype LowerStandardQueryToLogicalPlanNodeInput =\n  LowerStandardQueryToLogicalPlanInput &\n    Readonly<{\n      nextPlanNodeId: () => string;\n    }>;\n\nfunction lowerStandardQueryToLogicalPlanNode(\n  input: LowerStandardQueryToLogicalPlanNodeInput,\n): LogicalPlanNode {\n  const { ast, nextPlanNodeId } = input;\n\n  let currentNode: LogicalPlanNode = {\n    alias: ast.start.alias,\n    graphId: input.graphId,\n    id: nextPlanNodeId(),\n    kinds: ast.start.kinds,\n    op: \"scan\",\n    source: \"nodes\",\n  };\n\n  currentNode = wrapWithAliasFilterNode(\n    currentNode,\n    ast,\n    ast.start.alias,\n    \"node\",\n    nextPlanNodeId,\n  );\n\n  for (const traversal of ast.traversals) {\n    currentNode = {\n      direction: traversal.direction,\n      edgeAlias: traversal.edgeAlias,\n      edgeKinds: traversal.edgeKinds,\n      id: nextPlanNodeId(),\n      input: currentNode,\n      inverseEdgeKinds: traversal.inverseEdgeKinds ?? [],\n      joinFromAlias: traversal.joinFromAlias,\n      joinType: traversal.optional ? \"left\" : \"inner\",\n      nodeAlias: traversal.nodeAlias,\n      nodeKinds: traversal.nodeKinds,\n      op: \"join\",\n    };\n\n    currentNode = wrapWithAliasFilterNode(\n      currentNode,\n      ast,\n      traversal.edgeAlias,\n      \"edge\",\n      nextPlanNodeId,\n    );\n    currentNode = wrapWithAliasFilterNode(\n      currentNode,\n      ast,\n      traversal.nodeAlias,\n      \"node\",\n      nextPlanNodeId,\n    );\n  }\n\n  if (input.vectorPredicate !== undefined) {\n    currentNode = {\n      id: nextPlanNodeId(),\n      input: currentNode,\n      op: \"vector_knn\",\n      predicate: input.vectorPredicate,\n    };\n  }\n\n  if (input.fulltextPredicate !== undefined) {\n    currentNode = {\n      id: nextPlanNodeId(),\n      input: currentNode,\n      op: \"fulltext_match\",\n      predicate: input.fulltextPredicate,\n    };\n  }\n\n  return appendAggregateSortLimitAndProjectNodes(\n    currentNode,\n    ast,\n    nextPlanNodeId,\n    input.effectiveLimit,\n    input.collapsedTraversalCteAlias,\n  );\n}\n\ntype LowerRecursiveQueryToLogicalPlanNodeInput =\n  LowerRecursiveQueryToLogicalPlanInput &\n    Readonly<{\n      nextPlanNodeId: () => string;\n    }>;\n\nfunction lowerRecursiveQueryToLogicalPlanNode(\n  input: LowerRecursiveQueryToLogicalPlanNodeInput,\n): LogicalPlanNode {\n  const { ast, nextPlanNodeId } = input;\n  const traversal =\n    input.traversal ?? runRecursiveTraversalSelectionPass(input.ast);\n\n  let currentNode: LogicalPlanNode = {\n    alias: ast.start.alias,\n    graphId: input.graphId,\n    id: nextPlanNodeId(),\n    kinds: ast.start.kinds,\n    op: \"scan\",\n    source: \"nodes\",\n  };\n\n  currentNode = wrapWithAliasFilterNode(\n    currentNode,\n    ast,\n    ast.start.alias,\n    \"node\",\n    nextPlanNodeId,\n  );\n\n  currentNode = {\n    edgeAlias: traversal.edgeAlias,\n    edgeKinds: traversal.edgeKinds,\n    id: nextPlanNodeId(),\n    input: currentNode,\n    inverseEdgeKinds: traversal.inverseEdgeKinds ?? [],\n    nodeAlias: traversal.nodeAlias,\n    nodeKinds: traversal.nodeKinds,\n    op: \"recursive_expand\",\n    traversal: traversal.variableLength,\n  };\n\n  currentNode = wrapWithAliasFilterNode(\n    currentNode,\n    ast,\n    traversal.edgeAlias,\n    \"edge\",\n    nextPlanNodeId,\n  );\n  currentNode = wrapWithAliasFilterNode(\n    currentNode,\n    ast,\n    traversal.nodeAlias,\n    \"node\",\n    nextPlanNodeId,\n  );\n\n  return appendAggregateSortLimitAndProjectNodes(\n    currentNode,\n    ast,\n    nextPlanNodeId,\n    ast.limit,\n  );\n}\n\nfunction lowerComposableQueryToLogicalPlanNode(\n  query: ComposableQuery,\n  dialect: SqlDialect,\n  graphId: string,\n  nextPlanNodeId: () => string,\n  vectorStrategy: VectorStrategy | undefined,\n): LogicalPlanNode {\n  if (\"__type\" in query) {\n    return lowerSetOperationToLogicalPlanNode(\n      query,\n      graphId,\n      dialect,\n      nextPlanNodeId,\n      vectorStrategy,\n    );\n  }\n\n  const hasVariableLengthTraversal = query.traversals.some(\n    (traversal) => traversal.variableLength !== undefined,\n  );\n  if (hasVariableLengthTraversal) {\n    return lowerRecursiveQueryToLogicalPlanNode({\n      ast: query,\n      dialect,\n      graphId,\n      nextPlanNodeId,\n    });\n  }\n\n  const dialectAdapter = getDialect(dialect);\n  const vectorPredicate = runVectorPredicatePass(\n    query,\n    dialectAdapter,\n    vectorStrategy,\n  ).vectorPredicate;\n  const fulltextPredicate = runFulltextPredicatePass(\n    query,\n    dialectAdapter,\n  ).fulltextPredicate;\n  const effectiveLimit = query.limit;\n  const loweringInput = {\n    ast: query,\n    dialect,\n    graphId,\n    nextPlanNodeId,\n    ...(effectiveLimit === undefined ? {} : { effectiveLimit }),\n    ...(vectorPredicate === undefined ? {} : { vectorPredicate }),\n    ...(fulltextPredicate === undefined ? {} : { fulltextPredicate }),\n  };\n  return lowerStandardQueryToLogicalPlanNode(loweringInput);\n}\n\nfunction lowerSetOperationToLogicalPlanNode(\n  op: SetOperation,\n  graphId: string,\n  dialect: SqlDialect,\n  nextPlanNodeId: () => string,\n  vectorStrategy: VectorStrategy | undefined,\n): LogicalPlanNode {\n  let currentNode: LogicalPlanNode = {\n    id: nextPlanNodeId(),\n    left: lowerComposableQueryToLogicalPlanNode(\n      op.left,\n      dialect,\n      graphId,\n      nextPlanNodeId,\n      vectorStrategy,\n    ),\n    op: \"set_op\",\n    operator: op.operator,\n    right: lowerComposableQueryToLogicalPlanNode(\n      op.right,\n      dialect,\n      graphId,\n      nextPlanNodeId,\n      vectorStrategy,\n    ),\n  };\n\n  if (op.orderBy !== undefined && op.orderBy.length > 0) {\n    currentNode = {\n      id: nextPlanNodeId(),\n      input: currentNode,\n      op: \"sort\",\n      orderBy: op.orderBy,\n    };\n  }\n\n  if (op.limit !== undefined || op.offset !== undefined) {\n    const limitOffsetBase = {\n      id: nextPlanNodeId(),\n      input: currentNode,\n      op: \"limit_offset\" as const,\n    };\n    if (op.limit !== undefined && op.offset !== undefined) {\n      currentNode = { ...limitOffsetBase, limit: op.limit, offset: op.offset };\n    } else if (op.limit === undefined) {\n      currentNode = { ...limitOffsetBase, offset: requireDefined(op.offset) };\n    } else {\n      currentNode = { ...limitOffsetBase, limit: op.limit };\n    }\n  }\n\n  return currentNode;\n}\n\nexport function lowerStandardQueryToLogicalPlan(\n  input: LowerStandardQueryToLogicalPlanInput,\n): LogicalPlan {\n  const nextPlanNodeId = createPlanNodeIdFactory();\n  return {\n    metadata: {\n      dialect: input.dialect,\n      graphId: input.graphId,\n    },\n    root: lowerStandardQueryToLogicalPlanNode({\n      ...input,\n      nextPlanNodeId,\n    }),\n  };\n}\n\nexport function lowerRecursiveQueryToLogicalPlan(\n  input: LowerRecursiveQueryToLogicalPlanInput,\n): LogicalPlan {\n  const nextPlanNodeId = createPlanNodeIdFactory();\n  return {\n    metadata: {\n      dialect: input.dialect,\n      graphId: input.graphId,\n    },\n    root: lowerRecursiveQueryToLogicalPlanNode({\n      ...input,\n      nextPlanNodeId,\n    }),\n  };\n}\n\nexport function lowerSetOperationToLogicalPlan(\n  input: LowerSetOperationToLogicalPlanInput,\n): LogicalPlan {\n  const nextPlanNodeId = createPlanNodeIdFactory();\n  return {\n    metadata: {\n      dialect: input.dialect,\n      graphId: input.graphId,\n    },\n    root: lowerSetOperationToLogicalPlanNode(\n      input.op,\n      input.graphId,\n      input.dialect,\n      nextPlanNodeId,\n      input.vectorStrategy,\n    ),\n  };\n}\n","import { UnsupportedPredicateError } from \"../../errors\";\nimport type {\n  FulltextMatchPredicate,\n  QueryAst,\n  VectorSimilarityPredicate,\n} from \"../ast\";\nimport {\n  extractFulltextMatchPredicates,\n  extractVectorSimilarityPredicates,\n} from \"./predicates\";\n\ntype CurrentIndexUsage = Readonly<{\n  usesVectorPredicate: boolean;\n  usesFulltextPredicate: boolean;\n}>;\n\nexport function assertRecordedQueryDoesNotUseCurrentIndexes(\n  ast: QueryAst,\n  vectorPredicate: VectorSimilarityPredicate | undefined,\n  fulltextPredicate: FulltextMatchPredicate | undefined,\n): void {\n  assertRecordedQueryHasNoCurrentIndexUsage(ast, {\n    usesVectorPredicate: vectorPredicate !== undefined,\n    usesFulltextPredicate: fulltextPredicate !== undefined,\n  });\n}\n\nexport function assertRecordedQueryAstDoesNotUseCurrentIndexes(\n  ast: QueryAst,\n): void {\n  if (ast.recordedAsOf === undefined) return;\n  const vectorPredicates = extractVectorSimilarityPredicates(ast.predicates);\n  const fulltextPredicates = extractFulltextMatchPredicates(ast.predicates);\n  assertRecordedQueryHasNoCurrentIndexUsage(ast, {\n    usesVectorPredicate: vectorPredicates.length > 0,\n    usesFulltextPredicate: fulltextPredicates.length > 0,\n  });\n}\n\nfunction assertRecordedQueryHasNoCurrentIndexUsage(\n  ast: QueryAst,\n  usage: CurrentIndexUsage,\n): void {\n  if (ast.recordedAsOf === undefined) return;\n  if (!usage.usesVectorPredicate && !usage.usesFulltextPredicate) return;\n\n  throwRecordedCurrentIndexError(ast.recordedAsOf, usage);\n}\n\nfunction throwRecordedCurrentIndexError(\n  recordedAsOf: string,\n  usage: CurrentIndexUsage,\n): never {\n  throw new UnsupportedPredicateError(\n    \"Recorded-time queries cannot use vector or fulltext predicates because those indexes reflect current state.\",\n    {\n      recordedAsOf,\n      ...usage,\n    },\n    {\n      suggestion:\n        \"Use ordinary property predicates on the recorded view, or run vector/fulltext predicates against the live Store.\",\n    },\n  );\n}\n","import type { FieldRef, QueryAst } from \"../ast\";\nimport type { DatabaseExpression } from \"../expressions\";\n\nconst ALIAS_KEYS = new Set([\n  \"alias\",\n  \"depthAlias\",\n  \"edgeAlias\",\n  \"fromAlias\",\n  \"joinFromAlias\",\n  \"nodeAlias\",\n  \"pathAlias\",\n  \"startAlias\",\n  \"targetAlias\",\n]);\nexport type ExpressionAliasScope = ReadonlyMap<string, string>;\n\nexport function namespaceExpressionSubquery(\n  ast: QueryAst,\n  prefix: string,\n): Readonly<{ ast: QueryAst; aliases: ExpressionAliasScope }> {\n  const rewrittenAliases = new Map<string, string>([\n    [ast.start.alias, `${prefix}a0`],\n  ]);\n  const physicalAliases = new Map(rewrittenAliases);\n  for (const [index, traversal] of ast.traversals.entries()) {\n    const edgeAlias = `${prefix}e${index}`;\n    const nodeAlias = `${prefix}a${index + 1}`;\n    rewrittenAliases.set(traversal.edgeAlias, edgeAlias);\n    rewrittenAliases.set(traversal.nodeAlias, nodeAlias);\n    physicalAliases.set(traversal.edgeAlias, nodeAlias);\n    physicalAliases.set(traversal.nodeAlias, nodeAlias);\n  }\n  function rewrite(value: unknown, key?: string): unknown {\n    if (typeof value === \"string\" && key !== undefined && ALIAS_KEYS.has(key))\n      return rewrittenAliases.get(value) ?? value;\n    if (Array.isArray(value)) return value.map((entry) => rewrite(entry));\n    if (typeof value !== \"object\" || value === null || value instanceof Date)\n      return value;\n    const record = value as Readonly<Record<string, unknown>>;\n    if (\n      record[\"__type\"] === \"literal\" ||\n      record[\"kind\"] === \"literal\" ||\n      record[\"kind\"] === \"outer_reference\" ||\n      record[\"kind\"] === \"exists_subquery\" ||\n      record[\"kind\"] === \"scalar_subquery\"\n    )\n      return value;\n    return Object.fromEntries(\n      Object.entries(record).map(([entryKey, entry]) => [\n        entryKey,\n        rewrite(entry, entryKey),\n      ]),\n    );\n  }\n  return { aliases: physicalAliases, ast: rewrite(ast) as QueryAst };\n}\n\n/** Visits enclosing fields referenced anywhere in a nested query, without lifting its local fields. */\nexport function visitCorrelatedExpressionFields(\n  ast: QueryAst,\n  scopeIdentity: symbol,\n  visit: (field: FieldRef) => void,\n): void {\n  function walk(value: unknown): void {\n    if (Array.isArray(value)) {\n      for (const entry of value) walk(entry);\n      return;\n    }\n    if (typeof value !== \"object\" || value === null || value instanceof Date)\n      return;\n    const record = value as Readonly<Record<string, unknown>>;\n    if (record[\"__type\"] === \"literal\" || record[\"kind\"] === \"literal\") return;\n    if (record[\"__type\"] === \"database_expression\") {\n      const expression = value as DatabaseExpression;\n      if (expression.node.kind === \"outer_reference\") {\n        const { outerScopeIdentity, expression: outer } = expression.node;\n        if (outerScopeIdentity === scopeIdentity && outer.node.kind === \"field\")\n          visit(outer.node.field);\n        return;\n      }\n    }\n    for (const entry of Object.values(record)) walk(entry);\n  }\n  walk(ast);\n}\n","import type {\n  FieldRef,\n  FulltextMatchPredicate,\n  HybridFusionOptions,\n  PredicateExpression,\n  QueryAst,\n  VectorSimilarityPredicate,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type DatabaseExpression } from \"../expressions\";\nimport {\n  expressionContainsAggregate,\n  visitExpressionChildren,\n} from \"./expression-inspection\";\nimport { visitCorrelatedExpressionFields } from \"./expression-subquery-scope\";\nimport {\n  createTemporalFilterPass,\n  runCompilerPass,\n  runFulltextPredicatePass,\n  runFusionConfigPass,\n  runVectorPredicatePass,\n  type TemporalFilterPass,\n} from \"./passes\";\nimport { type LogicalPlan, lowerStandardQueryToLogicalPlan } from \"./plan\";\nimport {\n  buildPredicateIndex,\n  getPredicatesForAlias,\n  type PredicateIndex,\n} from \"./predicate-utils\";\nimport { type PredicateCompilerContext } from \"./predicates\";\nimport { assertRecordedQueryDoesNotUseCurrentIndexes } from \"./recorded-current-index-guard\";\nimport {\n  addRequiredColumn,\n  findSelectivePropsFieldForFieldRef,\n  isIdFieldRef,\n  mapSelectiveSystemFieldToColumn,\n  markFieldRefAsRequired,\n  type RequiredColumnsByAlias,\n} from \"./utils\";\n\n/**\n * Heuristics for pushing LIMIT into traversal CTEs to cap intermediate row counts.\n * - 8x multiplier accounts for edge fan-out (each node may connect to multiple edges).\n * - 10K cap prevents runaway memory allocation for large intermediate result sets.\n */\nconst TRAVERSAL_LIMIT_PUSHDOWN_MULTIPLIER = 8;\nconst TRAVERSAL_LIMIT_PUSHDOWN_MAX = 10_000;\n\nfunction isColumnPruningEnabled(ast: QueryAst): boolean {\n  if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n    return true;\n  }\n  if (ast.groupBy || ast.having) {\n    return true;\n  }\n  return ast.projection.fields.some(\n    (field) =>\n      field.source.__type === \"aggregate\" ||\n      (field.source.__type === \"database_expression\" &&\n        expressionContainsAggregate(field.source)),\n  );\n}\n\nexport function visitExpressionFields(\n  expression: DatabaseExpression,\n  visit: (field: FieldRef) => void,\n): void {\n  const node = expression.node;\n  if (node.kind === \"field\") {\n    visit(node.field);\n    return;\n  }\n  if (node.kind === \"exists_subquery\" || node.kind === \"scalar_subquery\") {\n    visitCorrelatedExpressionFields(\n      node.subquery,\n      expression.scopeIdentity,\n      visit,\n    );\n    return;\n  }\n  visitExpressionChildren(expression, (operand) => {\n    visitExpressionFields(operand, visit);\n  });\n}\n\nexport function markPredicateFieldsAsRequired(\n  requiredColumnsByAlias: Map<string, Set<string>>,\n  expression: PredicateExpression,\n): void {\n  switch (expression.__type) {\n    case \"comparison\": {\n      markFieldRefAsRequired(requiredColumnsByAlias, expression.left);\n      return;\n    }\n    case \"tuple_comparison\": {\n      for (const field of expression.fields)\n        markFieldRefAsRequired(requiredColumnsByAlias, field);\n      return;\n    }\n    case \"string_op\":\n    case \"null_check\":\n    case \"between\":\n    case \"array_op\":\n    case \"object_op\": {\n      markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n      return;\n    }\n    case \"and\":\n    case \"or\": {\n      for (const predicate of expression.predicates) {\n        markPredicateFieldsAsRequired(requiredColumnsByAlias, predicate);\n      }\n      return;\n    }\n    case \"not\": {\n      markPredicateFieldsAsRequired(\n        requiredColumnsByAlias,\n        expression.predicate,\n      );\n      return;\n    }\n    case \"aggregate_comparison\": {\n      markFieldRefAsRequired(\n        requiredColumnsByAlias,\n        expression.aggregate.field,\n      );\n      return;\n    }\n    case \"in_subquery\": {\n      markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n      return;\n    }\n    case \"vector_similarity\": {\n      markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n      return;\n    }\n    case \"fulltext_match\": {\n      markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n      return;\n    }\n    case \"exists\": {\n      return;\n    }\n    case \"database_expression_predicate\": {\n      visitExpressionFields(expression.expression, (field) => {\n        markFieldRefAsRequired(requiredColumnsByAlias, field);\n      });\n      return;\n    }\n  }\n}\n\n/**\n * Collects the columns each alias must carry out of its CTE.\n *\n * `includeProjection` (default true) folds in the SELECT-list fields. The late\n * materialization path passes `false` to build a *lean* candidate CTE that\n * carries only identity, ordering, and predicate columns — the projection-only\n * columns (e.g. a large `content` prop) are deferred and re-fetched by identity\n * for the surviving rows, not materialized for every candidate.\n */\nexport function collectRequiredColumnsByAlias(\n  ast: QueryAst,\n  options?: Readonly<{ includeProjection?: boolean }>,\n): RequiredColumnsByAlias {\n  const includeProjection = options?.includeProjection ?? true;\n  const requiredColumnsByAlias = new Map<string, Set<string>>();\n\n  addRequiredColumn(requiredColumnsByAlias, ast.start.alias, \"id\");\n  for (const traversal of ast.traversals) {\n    addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"id\");\n  }\n\n  const hasSelectiveFields = (ast.selectiveFields?.length ?? 0) > 0;\n\n  if (includeProjection) {\n    if (hasSelectiveFields) {\n      for (const field of ast.selectiveFields ?? []) {\n        if (field.isSystemField) {\n          addRequiredColumn(\n            requiredColumnsByAlias,\n            field.alias,\n            mapSelectiveSystemFieldToColumn(field.field),\n          );\n        }\n      }\n    } else {\n      for (const projectedField of ast.projection.fields) {\n        const source = projectedField.source;\n        if (source.__type === \"field_ref\") {\n          markFieldRefAsRequired(requiredColumnsByAlias, source);\n        } else if (source.__type === \"aggregate\") {\n          addRequiredColumn(requiredColumnsByAlias, source.field.alias, \"id\");\n          markFieldRefAsRequired(requiredColumnsByAlias, source.field);\n        } else {\n          visitExpressionFields(source, (field) => {\n            markFieldRefAsRequired(requiredColumnsByAlias, field);\n          });\n        }\n      }\n    }\n  }\n\n  if (ast.groupBy) {\n    for (const field of ast.groupBy.fields) {\n      if (field.__type === \"field_ref\") {\n        markFieldRefAsRequired(requiredColumnsByAlias, field);\n      } else {\n        visitExpressionFields(field, (referencedField) => {\n          markFieldRefAsRequired(requiredColumnsByAlias, referencedField);\n        });\n      }\n    }\n  }\n\n  if (ast.orderBy) {\n    for (const orderSpec of ast.orderBy) {\n      if (orderSpec.field.__type === \"database_expression\") {\n        visitExpressionFields(orderSpec.field, (field) => {\n          markFieldRefAsRequired(requiredColumnsByAlias, field);\n        });\n        continue;\n      }\n      if (\n        findSelectivePropsFieldForFieldRef(\n          ast.selectiveFields,\n          orderSpec.field,\n        ) !== undefined\n      ) {\n        continue;\n      }\n      markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n    }\n  }\n\n  if (ast.resultPredicate !== undefined) {\n    markPredicateFieldsAsRequired(requiredColumnsByAlias, ast.resultPredicate);\n  }\n\n  if (ast.having) {\n    markPredicateFieldsAsRequired(requiredColumnsByAlias, ast.having);\n  }\n\n  if (!hasSelectiveFields) {\n    for (const predicate of ast.predicates) {\n      markPredicateFieldsAsRequired(\n        requiredColumnsByAlias,\n        predicate.expression,\n      );\n    }\n  }\n\n  return requiredColumnsByAlias;\n}\n\nfunction hasIdEqualityPredicate(\n  expression: PredicateExpression,\n  alias: string,\n): boolean {\n  switch (expression.__type) {\n    case \"comparison\": {\n      return (\n        expression.op === \"eq\" &&\n        expression.left.alias === alias &&\n        isIdFieldRef(expression.left)\n      );\n    }\n    case \"tuple_comparison\": {\n      return false;\n    }\n    case \"and\": {\n      return expression.predicates.some((predicate) =>\n        hasIdEqualityPredicate(predicate, alias),\n      );\n    }\n    case \"or\":\n    case \"not\":\n    case \"string_op\":\n    case \"null_check\":\n    case \"between\":\n    case \"array_op\":\n    case \"object_op\":\n    case \"aggregate_comparison\":\n    case \"exists\":\n    case \"in_subquery\":\n    case \"vector_similarity\":\n    case \"fulltext_match\": {\n      return false;\n    }\n    case \"database_expression_predicate\": {\n      return false;\n    }\n  }\n}\n\nfunction isStartAliasBoundToSingleId(\n  ast: QueryAst,\n  predicateIndex: PredicateIndex,\n): boolean {\n  return getPredicatesForAlias(predicateIndex, ast.start.alias, \"node\").some(\n    (predicate) =>\n      hasIdEqualityPredicate(predicate.expression, ast.start.alias),\n  );\n}\n\nfunction resolveTraversalCteLimit(\n  ast: QueryAst,\n  predicateIndex: PredicateIndex,\n): number | undefined {\n  if (ast.limit === undefined) {\n    return undefined;\n  }\n\n  if (ast.offset !== undefined) {\n    return undefined;\n  }\n\n  if (ast.limit <= 0) {\n    return 0;\n  }\n\n  if (ast.groupBy || ast.having || ast.resultPredicate !== undefined) {\n    return undefined;\n  }\n\n  if (ast.orderBy && ast.orderBy.length > 0) {\n    return undefined;\n  }\n\n  if (ast.traversals.length < 2) {\n    return undefined;\n  }\n\n  if (ast.traversals.some((traversal) => traversal.optional)) {\n    return undefined;\n  }\n\n  if (!isStartAliasBoundToSingleId(ast, predicateIndex)) {\n    return undefined;\n  }\n\n  const pushdownLimit = Math.min(\n    ast.limit * TRAVERSAL_LIMIT_PUSHDOWN_MULTIPLIER,\n    TRAVERSAL_LIMIT_PUSHDOWN_MAX,\n  );\n\n  return Math.max(ast.limit, pushdownLimit);\n}\n\nfunction canCollapseSelectiveTraversalRowset(\n  ast: QueryAst,\n  vectorPredicate: VectorSimilarityPredicate | undefined,\n  fulltextPredicate: FulltextMatchPredicate | undefined,\n): boolean {\n  if (vectorPredicate !== undefined) {\n    return false;\n  }\n\n  if (fulltextPredicate !== undefined) {\n    return false;\n  }\n\n  if (ast.traversals.length === 0) {\n    return false;\n  }\n\n  if (ast.traversals.some((traversal) => traversal.optional)) {\n    return false;\n  }\n\n  let expectedJoinFromAlias = ast.start.alias;\n  for (const traversal of ast.traversals) {\n    if (traversal.joinFromAlias !== expectedJoinFromAlias) {\n      return false;\n    }\n    expectedJoinFromAlias = traversal.nodeAlias;\n  }\n\n  if (!ast.selectiveFields || ast.selectiveFields.length === 0) {\n    return false;\n  }\n\n  if (ast.groupBy || ast.having || ast.resultPredicate !== undefined) {\n    return false;\n  }\n\n  if (\n    ast.projection.fields.some((field) => field.source.__type === \"aggregate\")\n  ) {\n    return false;\n  }\n\n  return true;\n}\n\nexport function shouldMaterializeTraversalCte(\n  dialect: DialectAdapter,\n  traversalCount: number,\n  traversalIndex: number,\n): boolean {\n  if (!dialect.capabilities.materializeIntermediateTraversalCtes) {\n    return false;\n  }\n\n  if (traversalCount <= 1) {\n    return false;\n  }\n\n  return traversalIndex < traversalCount - 1;\n}\n\ntype StandardQueryPassState = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias: string | undefined;\n  ctx: PredicateCompilerContext;\n  effectiveLimit: number | undefined;\n  fulltextPredicate: FulltextMatchPredicate | undefined;\n  fusion: HybridFusionOptions | undefined;\n  logicalPlan: LogicalPlan | undefined;\n  predicateIndex: PredicateIndex;\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n  shouldCollapseSelectiveTraversalRowset: boolean;\n  temporalFilterPass: TemporalFilterPass | undefined;\n  traversalCteLimit: number | undefined;\n  vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\nexport function runStandardQueryPassPipeline(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): StandardQueryPassState {\n  let state: StandardQueryPassState = {\n    ast,\n    collapsedTraversalCteAlias: undefined,\n    ctx,\n    effectiveLimit: undefined,\n    fulltextPredicate: undefined,\n    fusion: undefined,\n    logicalPlan: undefined,\n    predicateIndex: buildPredicateIndex(ast),\n    requiredColumnsByAlias: undefined,\n    shouldCollapseSelectiveTraversalRowset: false,\n    temporalFilterPass: undefined,\n    traversalCteLimit: undefined,\n    vectorPredicate: undefined,\n  };\n\n  const vectorPass = runCompilerPass(state, {\n    name: \"vector_predicate\",\n    execute(currentState): VectorSimilarityPredicate | undefined {\n      return runVectorPredicatePass(\n        currentState.ast,\n        currentState.ctx.dialect,\n        currentState.ctx.vectorStrategy,\n      ).vectorPredicate;\n    },\n    update(currentState, vectorPredicate): StandardQueryPassState {\n      return {\n        ...currentState,\n        vectorPredicate,\n      };\n    },\n  });\n  state = vectorPass.state;\n\n  const fulltextPass = runCompilerPass(state, {\n    name: \"fulltext_predicate\",\n    execute(currentState): FulltextMatchPredicate | undefined {\n      return runFulltextPredicatePass(\n        currentState.ast,\n        currentState.ctx.dialect,\n      ).fulltextPredicate;\n    },\n    update(currentState, fulltextPredicate): StandardQueryPassState {\n      return {\n        ...currentState,\n        fulltextPredicate,\n      };\n    },\n  });\n  state = fulltextPass.state;\n\n  assertRecordedQueryDoesNotUseCurrentIndexes(\n    state.ast,\n    state.vectorPredicate,\n    state.fulltextPredicate,\n  );\n\n  const fusionPass = runCompilerPass(state, {\n    name: \"fusion_config\",\n    execute(currentState): HybridFusionOptions | undefined {\n      return runFusionConfigPass(\n        currentState.ast,\n        currentState.vectorPredicate,\n        currentState.fulltextPredicate,\n      ).fusion;\n    },\n    update(currentState, fusion): StandardQueryPassState {\n      return {\n        ...currentState,\n        fusion,\n      };\n    },\n  });\n  state = fusionPass.state;\n\n  const temporalPass = runCompilerPass(state, {\n    name: \"temporal_filters\",\n    execute(currentState): TemporalFilterPass {\n      return createTemporalFilterPass(\n        currentState.ast,\n        ctx.readInstant,\n        ctx.recordedReadBinding,\n      );\n    },\n    update(currentState, temporalFilterPass): StandardQueryPassState {\n      return {\n        ...currentState,\n        temporalFilterPass,\n      };\n    },\n  });\n  state = temporalPass.state;\n\n  const columnPruningPass = runCompilerPass(state, {\n    name: \"column_pruning\",\n    execute(currentState): RequiredColumnsByAlias | undefined {\n      return isColumnPruningEnabled(currentState.ast) ?\n          collectRequiredColumnsByAlias(currentState.ast)\n        : undefined;\n    },\n    update(currentState, requiredColumnsByAlias): StandardQueryPassState {\n      return {\n        ...currentState,\n        requiredColumnsByAlias,\n      };\n    },\n  });\n  state = columnPruningPass.state;\n\n  const selectiveTraversalRowsetPass = runCompilerPass(state, {\n    name: \"selective_traversal_rowset\",\n    execute(currentState): Readonly<{\n      collapsedTraversalCteAlias: string | undefined;\n      shouldCollapseSelectiveTraversalRowset: boolean;\n    }> {\n      const shouldCollapseSelectiveTraversalRowset =\n        canCollapseSelectiveTraversalRowset(\n          currentState.ast,\n          currentState.vectorPredicate,\n          currentState.fulltextPredicate,\n        );\n      const lastTraversal = currentState.ast.traversals.at(-1);\n      const collapsedTraversalCteAlias =\n        shouldCollapseSelectiveTraversalRowset && lastTraversal !== undefined ?\n          `cte_${lastTraversal.nodeAlias}`\n        : undefined;\n\n      return {\n        collapsedTraversalCteAlias,\n        shouldCollapseSelectiveTraversalRowset,\n      };\n    },\n    update(\n      currentState,\n      { collapsedTraversalCteAlias, shouldCollapseSelectiveTraversalRowset },\n    ): StandardQueryPassState {\n      return {\n        ...currentState,\n        collapsedTraversalCteAlias,\n        shouldCollapseSelectiveTraversalRowset,\n      };\n    },\n  });\n  state = selectiveTraversalRowsetPass.state;\n\n  const traversalLimitPass = runCompilerPass(state, {\n    name: \"traversal_limit\",\n    execute(currentState): number | undefined {\n      return resolveTraversalCteLimit(\n        currentState.ast,\n        currentState.predicateIndex,\n      );\n    },\n    update(currentState, traversalCteLimit): StandardQueryPassState {\n      return {\n        ...currentState,\n        traversalCteLimit,\n      };\n    },\n  });\n  state = traversalLimitPass.state;\n\n  // Ranked predicates bound their candidate CTEs independently. The query limit\n  // applies to completed match rows after traversal fanout and result filtering.\n  state = {\n    ...state,\n    effectiveLimit: state.ast.limit,\n  };\n\n  const logicalPlanPass = runCompilerPass(state, {\n    name: \"logical_plan\",\n    execute(currentState): LogicalPlan {\n      const loweringInput = {\n        ast: currentState.ast,\n        dialect: currentState.ctx.dialect.name,\n        graphId,\n      };\n\n      return lowerStandardQueryToLogicalPlan({\n        ...loweringInput,\n        ...(currentState.collapsedTraversalCteAlias === undefined ?\n          {}\n        : {\n            collapsedTraversalCteAlias: currentState.collapsedTraversalCteAlias,\n          }),\n        ...(currentState.effectiveLimit === undefined ?\n          {}\n        : { effectiveLimit: currentState.effectiveLimit }),\n        ...(currentState.vectorPredicate === undefined ?\n          {}\n        : { vectorPredicate: currentState.vectorPredicate }),\n        ...(currentState.fulltextPredicate === undefined ?\n          {}\n        : { fulltextPredicate: currentState.fulltextPredicate }),\n      });\n    },\n    update(currentState, logicalPlan): StandardQueryPassState {\n      return {\n        ...currentState,\n        logicalPlan,\n      };\n    },\n  });\n  state = logicalPlanPass.state;\n\n  return state;\n}\n","/**\n * Recursive CTE Compilation\n *\n * Compiles variable-length path traversals using WITH RECURSIVE.\n * Handles cycle detection and depth limiting using dialect-specific operations.\n */\nimport {\n  CompilerInvariantError,\n  UnsupportedPredicateError,\n} from \"../../errors\";\nimport { IDENTITY_PATH_TOKEN_SEPARATOR } from \"../../utils/path\";\nimport { type FieldRef, type QueryAst, type SelectiveField } from \"../ast\";\nimport {\n  type DialectAdapter,\n  type DialectRecursiveQueryStrategy,\n} from \"../dialect\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport { compileOrderTerm, resolveNullOrdering } from \"../order\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { compileDatabaseExpression } from \"./database-expressions\";\nimport { emitRecursiveQuerySql } from \"./emitter\";\nimport {\n  compileIdentityClassCte,\n  planIdentityFrontierExpansion,\n} from \"./identity-traversal\";\nimport { compileInverseTraversalDuplicateGuard } from \"./inverse-traversal-guard\";\nimport { compileLimitOffsetClauses } from \"./limit-offset\";\nimport {\n  createTemporalFilterPass,\n  runCompilerPass,\n  runRecursiveTraversalSelectionPass,\n  type TemporalFilterPass,\n  type VariableLengthTraversal,\n} from \"./passes\";\nimport { type LogicalPlan, lowerRecursiveQueryToLogicalPlan } from \"./plan\";\nimport { compileKindFilter as sharedCompileKindFilter } from \"./predicate-utils\";\nimport {\n  assertRecursiveTraversalSupported,\n  compileFieldValue,\n  compileFieldValueFromColumn,\n  compilePredicateExpression,\n  type PredicateCompilerContext,\n} from \"./predicates\";\nimport { assertRecordedQueryAstDoesNotUseCurrentIndexes } from \"./recorded-current-index-guard\";\nimport {\n  markPredicateFieldsAsRequired,\n  visitExpressionFields,\n} from \"./standard-pass-pipeline\";\nimport { compileSelectivePropsExtraction } from \"./typed-json-extract\";\nimport {\n  addRequiredColumn,\n  EMPTY_REQUIRED_COLUMNS,\n  mapSelectiveSystemFieldToColumn,\n  markFieldRefAsRequired,\n  markSelectiveFieldAsRequired,\n  NODE_COLUMNS,\n  quoteIdentifier,\n  type RequiredColumnsByAlias,\n  shouldProjectColumn,\n} from \"./utils\";\n\n// ============================================================\n// Constants\n// ============================================================\n\n/**\n * Maximum depth for recursive CTE queries when maxDepth is unlimited (-1).\n *\n * Graphs with branching factor B produce O(B^depth) rows before cycle\n * detection can prune them. A default of 10 covers typical neighborhood,\n * shortest-path, and hierarchy use-cases without risking exponential blowup\n * on dense graphs. Users who need deeper traversals should pass\n * `.recursive({ maxHops: N })` explicitly (up to MAX_EXPLICIT_RECURSIVE_DEPTH).\n */\nexport const MAX_RECURSIVE_DEPTH = 10;\n\n/**\n * Maximum depth for explicit maxDepth traversals.\n *\n * Explicit traversal bounds are opt-in and safe to allow at a higher ceiling\n * for stress testing and long-path workloads.\n */\nexport const MAX_EXPLICIT_RECURSIVE_DEPTH = 1000;\n\nconst NO_ALWAYS_REQUIRED_COLUMNS = new Set<string>();\n\n/**\n * The per-step cycle/path token for a node table alias. For identity-expanded\n * traversals it is the composite `kind || SEP || id` so folded peers (same id,\n * different kind) are distinct tokens; otherwise it is the bare id, preserving\n * the exact pre-identity token and public path output.\n *\n * The separator is bound as a parameter (not `sql.raw`) so it needs no\n * dialect-specific `char()`/`chr()` builtin — both dialects concatenate bound\n * text with `||`. Composite tokens never reach the caller: result\n * materialization strips them back to bare ids with `stripIdentityPathTokens`.\n */\nfunction compilePathToken(tableAlias: string, composite: boolean): SqlFragment {\n  if (!composite) {\n    return sql.raw(`${tableAlias}.id`);\n  }\n  // Parenthesized so dialect path builders that splice this fragment into a\n  // larger `||` chain keep it one text operand — PostgreSQL's `text[] || x`\n  // would otherwise re-associate and coerce the separator as an array literal.\n  return sql`(${sql.raw(`${tableAlias}.kind`)} || ${IDENTITY_PATH_TOKEN_SEPARATOR} || ${sql.raw(`${tableAlias}.id`)})`;\n}\n\ntype RecursiveQueryPassState = Readonly<{\n  ast: QueryAst;\n  ctx: PredicateCompilerContext;\n  graphId: string;\n  logicalPlan: LogicalPlan | undefined;\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n  temporalFilterPass: TemporalFilterPass | undefined;\n  traversal: VariableLengthTraversal | undefined;\n}>;\n\nfunction runRecursiveQueryPassPipeline(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): RecursiveQueryPassState {\n  let state: RecursiveQueryPassState = {\n    ast,\n    ctx,\n    graphId,\n    logicalPlan: undefined,\n    requiredColumnsByAlias: undefined,\n    temporalFilterPass: undefined,\n    traversal: undefined,\n  };\n\n  const recursiveTraversalPass = runCompilerPass(state, {\n    name: \"recursive_traversal\",\n    execute(currentState): VariableLengthTraversal {\n      return runRecursiveTraversalSelectionPass(currentState.ast);\n    },\n    update(currentState, traversal): RecursiveQueryPassState {\n      return {\n        ...currentState,\n        traversal,\n      };\n    },\n  });\n  state = recursiveTraversalPass.state;\n\n  const temporalPass = runCompilerPass(state, {\n    name: \"temporal_filters\",\n    execute(currentState): TemporalFilterPass {\n      return createTemporalFilterPass(\n        currentState.ast,\n        currentState.ctx.readInstant,\n        currentState.ctx.recordedReadBinding,\n      );\n    },\n    update(currentState, temporalFilterPass): RecursiveQueryPassState {\n      return {\n        ...currentState,\n        temporalFilterPass,\n      };\n    },\n  });\n  state = temporalPass.state;\n\n  assertRecordedQueryAstDoesNotUseCurrentIndexes(state.ast);\n\n  const columnPruningPass = runCompilerPass(state, {\n    name: \"column_pruning\",\n    execute(currentState): RequiredColumnsByAlias | undefined {\n      const traversal = currentState.traversal;\n      if (traversal === undefined) {\n        throw new CompilerInvariantError(\n          \"Recursive traversal pass did not select traversal\",\n        );\n      }\n      return collectRequiredColumnsByAlias(currentState.ast, traversal);\n    },\n    update(currentState, requiredColumnsByAlias): RecursiveQueryPassState {\n      return {\n        ...currentState,\n        requiredColumnsByAlias,\n      };\n    },\n  });\n  state = columnPruningPass.state;\n\n  const logicalPlanPass = runCompilerPass(state, {\n    name: \"logical_plan\",\n    execute(currentState): LogicalPlan {\n      const loweringInput = {\n        ast: currentState.ast,\n        dialect: currentState.ctx.dialect.name,\n        graphId: currentState.graphId,\n        ...(currentState.traversal === undefined ?\n          {}\n        : { traversal: currentState.traversal }),\n      };\n      return lowerRecursiveQueryToLogicalPlan(loweringInput);\n    },\n    update(currentState, logicalPlan): RecursiveQueryPassState {\n      return {\n        ...currentState,\n        logicalPlan,\n      };\n    },\n  });\n  state = logicalPlanPass.state;\n\n  return state;\n}\n\n// ============================================================\n// Main Compiler\n// ============================================================\n\n/**\n * Compiles a variable-length query using recursive CTEs.\n *\n * @param ast - The query AST\n * @param graphId - The graph ID\n * @param ctx - Predicate compiler context\n * @returns `SqlFragment` for the recursive query\n */\nexport function compileVariableLengthQuery(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  assertRecursiveOutputSupported(ast);\n  assertRecursiveTraversalSupported(ctx, \"variable-length traversal\");\n  const strategy = ctx.dialect.capabilities.recursiveQueryStrategy;\n  const handler = RECURSIVE_QUERY_STRATEGY_HANDLERS[strategy];\n  return handler(ast, graphId, ctx);\n}\n\n/** Applies the shared output contract to single and composed recursion. */\nexport function assertRecursiveOutputSupported(ast: QueryAst): void {\n  if (\n    ast.groupBy !== undefined ||\n    ast.having !== undefined ||\n    (ast.aggregateOrderBy?.length ?? 0) > 0\n  )\n    throw new UnsupportedPredicateError(\n      \"Aggregating recursive traversals is not yet supported; project nodes as a relation before aggregating.\",\n    );\n  const materialized = new Set(\n    [\n      ast.start.alias,\n      ...ast.traversals.map((traversal) => traversal.nodeAlias),\n    ].flatMap((alias) => NODE_COLUMNS.map((column) => `${alias}_${column}`)),\n  );\n  for (const field of ast.projection.fields) materialized.add(field.outputName);\n  for (const field of ast.selectiveFields ?? [])\n    materialized.add(field.outputName);\n  for (const traversal of ast.traversals) {\n    for (const alias of [\n      traversal.variableLength?.depthAlias,\n      traversal.variableLength?.pathAlias,\n    ]) {\n      if (alias === undefined) continue;\n      if (materialized.has(alias)) {\n        throw new UnsupportedPredicateError(\n          `Recursive traversal output alias \"${alias}\" collides with another result column`,\n        );\n      }\n      materialized.add(alias);\n    }\n  }\n}\n\ntype RecursiveQueryStrategyHandler = (\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n) => SqlFragment;\n\nconst RECURSIVE_QUERY_STRATEGY_HANDLERS: Record<\n  DialectRecursiveQueryStrategy,\n  RecursiveQueryStrategyHandler\n> = {\n  recursive_cte: compileVariableLengthQueryWithRecursiveCteStrategy,\n};\n\n/** Compiles one traversal stage restricted to kind-qualified upstream seeds. */\nexport function compileRecursiveStage(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  seedQuery: SqlFragment,\n): SqlFragment {\n  assertRecursiveTraversalSupported(ctx, \"variable-length traversal stage\");\n  return compileVariableLengthQueryWithRecursiveCteStrategy(\n    ast,\n    graphId,\n    ctx,\n    seedQuery,\n  );\n}\n\nfunction compileVariableLengthQueryWithRecursiveCteStrategy(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  seedQuery?: SqlFragment,\n): SqlFragment {\n  const passState = runRecursiveQueryPassPipeline(ast, graphId, ctx);\n\n  const { dialect } = ctx;\n  const {\n    logicalPlan,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    traversal: vlTraversal,\n  } = passState;\n\n  if (temporalFilterPass === undefined) {\n    throw new CompilerInvariantError(\n      \"Temporal filter pass did not initialize temporal state\",\n    );\n  }\n  if (logicalPlan === undefined) {\n    throw new CompilerInvariantError(\n      \"Logical plan pass did not initialize plan state\",\n    );\n  }\n  if (vlTraversal === undefined) {\n    throw new CompilerInvariantError(\n      \"Recursive traversal pass did not select traversal\",\n    );\n  }\n\n  // Build the recursive CTE\n  const recursiveCte = compileRecursiveCte(\n    ast,\n    vlTraversal,\n    graphId,\n    ctx,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    seedQuery,\n  );\n\n  // A historical read reconstructs its class relation from outside the recursive\n  // term, so the ledger fixed point is evaluated once for the whole traversal\n  // rather than per expanded (frontier row, edge) pair. A current read emits no\n  // such relation: its step seeks the closure from the worktable row itself.\n  const identityClassCte = compileIdentityClassCte({\n    ast,\n    ctx,\n    graphId,\n    temporalFilterPass,\n  });\n\n  // Build projection\n  const projection = compileRecursiveProjection(ast, vlTraversal, ctx);\n\n  // Build final SELECT\n  const minDepth = vlTraversal.variableLength.minDepth;\n  const resultClauses: SqlFragment[] = [];\n  if (minDepth > 0) resultClauses.push(sql`depth >= ${minDepth}`);\n  if (vlTraversal.variableLength.stopExpansion?.emitStopNode === false)\n    resultClauses.push(sql`stop_reached = ${dialect.booleanLiteral(false)}`);\n  if (ast.resultPredicate !== undefined)\n    resultClauses.push(\n      compilePredicateExpression(ast.resultPredicate, {\n        ...ctx,\n        resolveFieldCteAlias: () => ctx.recursiveResultAlias,\n      }),\n    );\n  const depthFilter =\n    resultClauses.length > 0 ?\n      sql`WHERE ${sql.join(resultClauses, sql` AND `)}`\n    : sql.raw(\"\");\n\n  // Order by and limit/offset\n  const orderBy = compileRecursiveOrderBy(ast, ctx);\n  const limitOffset = compileLimitOffset(ast, dialect);\n\n  return emitRecursiveQuerySql({\n    depthFilter,\n    ...(limitOffset === undefined ? {} : { limitOffset }),\n    logicalPlan,\n    ...(orderBy === undefined ? {} : { orderBy }),\n    ...(identityClassCte === undefined ?\n      {}\n    : { precedingCtes: [identityClassCte] }),\n    projection,\n    recursiveCte,\n    ...(ctx.recursiveResultAlias === undefined ?\n      {}\n    : { resultAlias: ctx.recursiveResultAlias }),\n  });\n}\n\n/**\n * Checks if a query contains variable-length traversals.\n */\nexport function hasVariableLengthTraversal(ast: QueryAst): boolean {\n  return ast.traversals.some((t) => t.variableLength !== undefined);\n}\n\n// ============================================================\n// Recursive CTE Generation\n// ============================================================\n\n/**\n * Compiles the recursive CTE for variable-length traversal.\n */\nfunction compileRecursiveCte(\n  ast: QueryAst,\n  traversal: VariableLengthTraversal,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined,\n  temporalFilterPass: TemporalFilterPass,\n  seedQuery?: SqlFragment,\n): SqlFragment {\n  const { dialect } = ctx;\n  const startAlias = ast.start.alias;\n  const startKinds = ast.start.kinds;\n  const nodeAlias = traversal.nodeAlias;\n  const directEdgeKinds = [...new Set(traversal.edgeKinds)];\n  const inverseEdgeKinds =\n    traversal.inverseEdgeKinds === undefined ?\n      []\n    : [...new Set(traversal.inverseEdgeKinds)];\n  const forceWorktableOuterJoinOrder =\n    dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;\n  const nodeKinds = traversal.nodeKinds;\n  const previousNodeKinds = [...new Set([...startKinds, ...nodeKinds])];\n  const direction = traversal.direction;\n  const vl = traversal.variableLength;\n  const shouldEnforceCycleCheck = vl.cyclePolicy !== \"allow\";\n  const shouldTrackPath =\n    shouldEnforceCycleCheck ||\n    (vl.pathAlias !== undefined && vl.pathFormat !== \"qualified\");\n  const recursiveJoinRequiredColumns = new Set<string>([\"id\"]);\n  if (\n    previousNodeKinds.length > 1 ||\n    traversal.includeIdentityMembers === true\n  ) {\n    recursiveJoinRequiredColumns.add(\"kind\");\n  }\n  const requiredStartColumns =\n    requiredColumnsByAlias ?\n      (requiredColumnsByAlias.get(startAlias) ?? EMPTY_REQUIRED_COLUMNS)\n    : undefined;\n  const requiredNodeColumns =\n    requiredColumnsByAlias ?\n      (requiredColumnsByAlias.get(nodeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n    : undefined;\n  const startColumnsFromBase = compileNodeSelectColumnsFromTable(\n    \"n0\",\n    startAlias,\n    requiredStartColumns,\n    NO_ALWAYS_REQUIRED_COLUMNS,\n  );\n  const startColumnsFromRecursive = compileNodeSelectColumnsFromRecursiveRow(\n    startAlias,\n    requiredStartColumns,\n    NO_ALWAYS_REQUIRED_COLUMNS,\n  );\n  const nodeColumnsFromBase = compileNodeSelectColumnsFromTable(\n    \"n0\",\n    nodeAlias,\n    requiredNodeColumns,\n    recursiveJoinRequiredColumns,\n  );\n  const nodeColumnsFromRecursive = compileNodeSelectColumnsFromTable(\n    \"n\",\n    nodeAlias,\n    requiredNodeColumns,\n    recursiveJoinRequiredColumns,\n  );\n\n  const startKindFilter = compileKindFilter(startKinds, \"n0.kind\");\n  const nodeKindFilter = compileKindFilter(nodeKinds, \"n.kind\");\n\n  const startTemporalFilter = temporalFilterPass.forAlias(\"n0\");\n  const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n  const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n  // Start predicates (with cteColumnPrefix \"\" for raw n0 columns)\n  const startContext = { ...ctx, cteColumnPrefix: \"\" };\n  const startPredicates = compileNodePredicates(ast, startAlias, startContext);\n\n  // Edge predicates (with cteColumnPrefix \"e\" for e.props)\n  const edgeContext = { ...ctx, cteColumnPrefix: \"e\" };\n  const edgePredicates = compileEdgePredicates(\n    ast,\n    traversal.edgeAlias,\n    edgeContext,\n  );\n\n  // Target node predicates (with cteColumnPrefix \"n\" for n.props)\n  const targetContext = { ...ctx, cteColumnPrefix: \"n\" };\n  const targetNodePredicates = compileNodePredicates(\n    ast,\n    nodeAlias,\n    targetContext,\n  );\n  const stopExpression = traversal.variableLength.stopExpansion?.expression;\n  const compiledStopExpression =\n    stopExpression === undefined ? undefined : (\n      compilePredicateExpression(stopExpression, targetContext)\n    );\n  const compiledBaseStopExpression =\n    stopExpression === undefined ? undefined : (\n      compilePredicateExpression(stopExpression, {\n        ...ctx,\n        cteColumnPrefix: \"n0\",\n      })\n    );\n\n  // Max depth condition:\n  // - unlimited traversals are capped at MAX_RECURSIVE_DEPTH\n  // - explicit maxDepth traversals must not exceed MAX_EXPLICIT_RECURSIVE_DEPTH\n  if (vl.maxDepth > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n    throw new UnsupportedPredicateError(\n      `Recursive traversal maxHops(${vl.maxDepth}) exceeds maximum explicit depth of ${MAX_EXPLICIT_RECURSIVE_DEPTH}`,\n    );\n  }\n  const effectiveMaxDepth = vl.maxDepth > 0 ? vl.maxDepth : MAX_RECURSIVE_DEPTH;\n  const maxDepthCondition = sql`r.depth < ${effectiveMaxDepth}`;\n\n  // Under identity folding two folded peers share an id but differ in kind, so\n  // a bare-id path token treats a traversal that legitimately passes through\n  // both peers as a revisit — a spurious cycle. Scope the fix to identity\n  // traversals: their cycle-detection and path tokens become the composite\n  // (kind, id), leaving every other traversal's token (and public path output)\n  // byte-identical. See the `IdentityTraversalOption` JSDoc in\n  // src/query/builder/query-builder.ts for the option's public semantics.\n  const baseToken = compilePathToken(\n    \"n0\",\n    traversal.includeIdentityMembers === true,\n  );\n  const stepToken = compilePathToken(\n    \"n\",\n    traversal.includeIdentityMembers === true,\n  );\n  const cycleCheck =\n    shouldEnforceCycleCheck ?\n      dialect.cycleCheck(stepToken, sql.raw(\"r.path\"))\n    : undefined;\n  const initialPath =\n    shouldTrackPath ? dialect.initializePath(baseToken) : undefined;\n  const pathExtension =\n    shouldTrackPath ?\n      dialect.extendPath(sql.raw(\"r.path\"), stepToken)\n    : undefined;\n\n  // Base case WHERE clauses\n  const baseWhereClauses = [\n    sql`n0.graph_id = ${graphId}`,\n    startKindFilter,\n    startTemporalFilter,\n    ...startPredicates,\n  ];\n\n  if (seedQuery !== undefined) {\n    baseWhereClauses.push(\n      sql`EXISTS (SELECT 1 FROM (${seedQuery}) AS __tg_seed WHERE __tg_seed.kind = n0.kind AND __tg_seed.id = n0.id)`,\n    );\n  }\n\n  const previousIdColumn = sql`r.${sql.raw(nodeAlias)}_id`;\n  const previousKindColumn = sql`r.${sql.raw(nodeAlias)}_kind`;\n  const identityFrontierExpansion =\n    traversal.includeIdentityMembers === true ?\n      planIdentityFrontierExpansion({\n        ast,\n        ctx,\n        graphId,\n        previousId: previousIdColumn,\n        previousKind: previousKindColumn,\n        temporalFilterPass,\n      })\n    : undefined;\n\n  const recursiveBaseWhereClauses: SqlFragment[] = [\n    sql`e.graph_id = ${graphId}`,\n    nodeKindFilter,\n    edgeTemporalFilter,\n    nodeTemporalFilter,\n    maxDepthCondition,\n    ...(stopExpression === undefined ?\n      []\n    : [\n        sql`COALESCE(r.stop_reached, ${dialect.booleanLiteral(false)}) = ${dialect.booleanLiteral(false)}`,\n      ]),\n    // Conditions the frontier widening cannot state in a join condition —\n    // currently the member-visibility guard. Every branch of the recursive term\n    // carries them, because every branch reads the widened frontier.\n    ...(identityFrontierExpansion?.whereClauses ?? []),\n  ];\n  if (cycleCheck !== undefined) {\n    recursiveBaseWhereClauses.push(cycleCheck);\n  }\n  recursiveBaseWhereClauses.push(...edgePredicates, ...targetNodePredicates);\n\n  /**\n   * Connects a candidate edge to the row the worktable is expanding from. A\n   * widened frontier and a plain one join the edge the same way — on the\n   * worktable row's (kind, id) or on the class member's — so no traversal reaches\n   * an edge through a correlated membership test.\n   */\n  function compileWorktableJoinClauses(\n    branch: Readonly<{\n      joinField: \"from_id\" | \"to_id\";\n      joinKindField: \"from_kind\" | \"to_kind\";\n    }>,\n  ): SqlFragment[] {\n    const edgeId = sql`e.${sql.raw(branch.joinField)}`;\n    const edgeKind = sql`e.${sql.raw(branch.joinKindField)}`;\n    if (identityFrontierExpansion !== undefined) {\n      return [\n        sql`${edgeId} = ${identityFrontierExpansion.memberId}`,\n        sql`${edgeKind} = ${identityFrontierExpansion.memberKind}`,\n      ];\n    }\n    const clauses = [sql`${edgeId} = ${previousIdColumn}`];\n    if (previousNodeKinds.length > 1) {\n      clauses.push(sql`${edgeKind} = ${previousKindColumn}`);\n    }\n    return clauses;\n  }\n\n  function compileRecursiveBranch(\n    branch: Readonly<{\n      joinField: \"from_id\" | \"to_id\";\n      targetField: \"from_id\" | \"to_id\";\n      joinKindField: \"from_kind\" | \"to_kind\";\n      targetKindField: \"from_kind\" | \"to_kind\";\n      edgeKinds: readonly string[];\n      duplicateGuard?: SqlFragment | undefined;\n    }>,\n  ): SqlFragment {\n    const recursiveFilterClauses = [\n      ...recursiveBaseWhereClauses,\n      compileKindFilter(branch.edgeKinds, \"e.kind\"),\n      compileKindFilter(nodeKinds, `e.${branch.targetKindField}`),\n    ];\n    if (traversal.includeIdentityMembers !== true) {\n      recursiveFilterClauses.push(\n        compileKindFilter(previousNodeKinds, `e.${branch.joinKindField}`),\n      );\n    }\n\n    if (branch.duplicateGuard !== undefined) {\n      recursiveFilterClauses.push(branch.duplicateGuard);\n    }\n\n    const recursiveSelectColumns = [\n      ...startColumnsFromRecursive,\n      ...nodeColumnsFromRecursive,\n      sql`r.depth + 1 AS depth`,\n    ];\n    if (compiledStopExpression !== undefined) {\n      recursiveSelectColumns.push(\n        sql`COALESCE(${compiledStopExpression}, ${dialect.booleanLiteral(false)}) AS stop_reached`,\n      );\n    }\n    if (pathExtension !== undefined) {\n      recursiveSelectColumns.push(sql`${pathExtension} AS path`);\n    }\n    if (vl.pathFormat === \"qualified\") {\n      const qualifiedPath = dialect.appendTextJsonArray(sql`r.qualified_path`, [\n        sql`e.kind`,\n        sql`e.id`,\n        sql`${branch.joinField === \"from_id\" ? \"out\" : \"in\"}`,\n        sql`n.kind`,\n        sql`n.id`,\n      ]);\n      recursiveSelectColumns.push(sql`${qualifiedPath} AS qualified_path`);\n    }\n    const recursiveJoinClauses = compileWorktableJoinClauses(branch);\n    const frontierJoin = identityFrontierExpansion?.frontierJoin ?? sql``;\n\n    if (forceWorktableOuterJoinOrder) {\n      const recursiveWhereClauses = [\n        ...recursiveJoinClauses,\n        ...recursiveFilterClauses,\n      ];\n\n      return sql`\n        SELECT ${sql.join(recursiveSelectColumns, sql`, `)}\n        FROM recursive_cte r\n        ${frontierJoin}\n        CROSS JOIN ${ctx.schema.edgesTable} e\n        JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n          AND n.id = e.${sql.raw(branch.targetField)}\n          AND n.kind = e.${sql.raw(branch.targetKindField)}\n        WHERE ${sql.join(recursiveWhereClauses, sql` AND `)}\n      `;\n    }\n\n    return sql`\n      SELECT ${sql.join(recursiveSelectColumns, sql`, `)}\n      FROM recursive_cte r\n      ${frontierJoin}\n      JOIN ${ctx.schema.edgesTable} e ON ${sql.join(recursiveJoinClauses, sql` AND `)}\n      JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n        AND n.id = e.${sql.raw(branch.targetField)}\n        AND n.kind = e.${sql.raw(branch.targetKindField)}\n      WHERE ${sql.join(recursiveFilterClauses, sql` AND `)}\n    `;\n  }\n\n  const directJoinField = direction === \"out\" ? \"from_id\" : \"to_id\";\n  const directTargetField = direction === \"out\" ? \"to_id\" : \"from_id\";\n  const directJoinKindField = direction === \"out\" ? \"from_kind\" : \"to_kind\";\n  const directTargetKindField = direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n  const directBranch = compileRecursiveBranch({\n    joinField: directJoinField,\n    targetField: directTargetField,\n    joinKindField: directJoinKindField,\n    targetKindField: directTargetKindField,\n    edgeKinds: directEdgeKinds,\n  });\n\n  function compileInverseRecursiveBranch(): SqlFragment {\n    const inverseJoinField = direction === \"out\" ? \"to_id\" : \"from_id\";\n    const inverseTargetField = direction === \"out\" ? \"from_id\" : \"to_id\";\n    const inverseJoinKindField = direction === \"out\" ? \"to_kind\" : \"from_kind\";\n    const inverseTargetKindField =\n      direction === \"out\" ? \"from_kind\" : \"to_kind\";\n    const duplicateGuard = compileInverseTraversalDuplicateGuard(\n      directEdgeKinds,\n      inverseEdgeKinds,\n      (overlappingKinds) => compileKindFilter(overlappingKinds, \"e.kind\"),\n    );\n\n    const inverseBranch = compileRecursiveBranch({\n      joinField: inverseJoinField,\n      targetField: inverseTargetField,\n      joinKindField: inverseJoinKindField,\n      targetKindField: inverseTargetKindField,\n      edgeKinds: inverseEdgeKinds,\n      duplicateGuard,\n    });\n\n    return sql`\n      ${directBranch}\n      UNION ALL\n      ${inverseBranch}\n    `;\n  }\n\n  const recursiveBranchSql =\n    inverseEdgeKinds.length === 0 ?\n      directBranch\n    : compileInverseRecursiveBranch();\n  const baseSelectColumns = [\n    ...startColumnsFromBase,\n    ...nodeColumnsFromBase,\n    sql`0 AS depth`,\n  ];\n  if (compiledBaseStopExpression !== undefined) {\n    baseSelectColumns.push(\n      sql`COALESCE(${compiledBaseStopExpression}, ${dialect.booleanLiteral(false)}) AS stop_reached`,\n    );\n  }\n  if (initialPath !== undefined) {\n    baseSelectColumns.push(sql`${initialPath} AS path`);\n  }\n\n  if (vl.pathFormat === \"qualified\") {\n    baseSelectColumns.push(\n      sql`${dialect.textJsonArray([sql`n0.kind`, sql`n0.id`])} AS qualified_path`,\n    );\n  }\n\n  return sql`\n    recursive_cte AS (\n      -- Base case: starting nodes\n      SELECT ${sql.join(baseSelectColumns, sql`, `)}\n      FROM ${ctx.schema.nodesTable} n0\n      WHERE ${sql.join(baseWhereClauses, sql` AND `)}\n\n      UNION ALL\n\n      -- Recursive case: follow edges\n      ${recursiveBranchSql}\n    )\n  `;\n}\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n/**\n * Compiles a kind filter for IN clause.\n * Delegates to the shared compileKindFilter from predicate-utils\n * with a raw SQL column expression.\n */\nfunction compileKindFilter(\n  kinds: readonly string[],\n  columnExpr: string,\n): SqlFragment {\n  return sharedCompileKindFilter(sql.raw(columnExpr), kinds);\n}\n\n/**\n * Compiles node predicates for a specific alias.\n * Filters by alias and excludes edge predicates (targetType !== \"edge\").\n */\nfunction compileNodePredicates(\n  ast: QueryAst,\n  alias: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment[] {\n  return ast.predicates\n    .filter((p) => p.targetAlias === alias && p.targetType !== \"edge\")\n    .map((p) => compilePredicateExpression(p.expression, ctx));\n}\n\n/**\n * Compiles edge predicates for a specific edge alias.\n * Filters by alias and only includes edge predicates (targetType === \"edge\").\n */\nfunction compileEdgePredicates(\n  ast: QueryAst,\n  edgeAlias: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment[] {\n  return ast.predicates\n    .filter((p) => p.targetAlias === edgeAlias && p.targetType === \"edge\")\n    .map((p) => compilePredicateExpression(p.expression, ctx));\n}\n\nfunction collectRequiredColumnsByAlias(\n  ast: QueryAst,\n  traversal: VariableLengthTraversal,\n): RequiredColumnsByAlias | undefined {\n  const selectiveFields = ast.selectiveFields;\n  if (selectiveFields === undefined || selectiveFields.length === 0) {\n    return undefined;\n  }\n\n  const requiredColumnsByAlias = new Map<string, Set<string>>();\n  const previousNodeKinds = [\n    ...new Set([...ast.start.kinds, ...traversal.nodeKinds]),\n  ];\n\n  // Recursive expansion always needs node alias id for joins/cycle checks.\n  addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"id\");\n  if (previousNodeKinds.length > 1) {\n    addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"kind\");\n  }\n\n  for (const field of selectiveFields) {\n    markSelectiveFieldAsRequired(requiredColumnsByAlias, field);\n  }\n\n  const edgeAliases = new Set(ast.traversals.map((item) => item.edgeAlias));\n  for (const projected of ast.projection.fields) {\n    const source = projected.source;\n    if (source.__type === \"aggregate\") {\n      if (!edgeAliases.has(source.field.alias)) {\n        markFieldRefAsRequired(requiredColumnsByAlias, source.field);\n      }\n    } else if (source.__type === \"database_expression\") {\n      visitExpressionFields(source, (field) => {\n        if (!edgeAliases.has(field.alias)) {\n          markFieldRefAsRequired(requiredColumnsByAlias, field);\n        }\n      });\n    } else if (!edgeAliases.has(source.alias)) {\n      markFieldRefAsRequired(requiredColumnsByAlias, source);\n    }\n  }\n\n  if (ast.orderBy) {\n    for (const orderSpec of ast.orderBy) {\n      if (orderSpec.field.__type === \"field_ref\") {\n        markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n      } else {\n        visitExpressionFields(orderSpec.field, (field) => {\n          markFieldRefAsRequired(requiredColumnsByAlias, field);\n        });\n      }\n    }\n  }\n\n  if (ast.resultPredicate !== undefined)\n    markPredicateFieldsAsRequired(requiredColumnsByAlias, ast.resultPredicate);\n\n  return requiredColumnsByAlias;\n}\n\nfunction compileNodeSelectColumnsFromTable(\n  tableAlias: string,\n  alias: string,\n  requiredColumns: ReadonlySet<string> | undefined,\n  alwaysRequiredColumns: ReadonlySet<string>,\n): SqlFragment[] {\n  return NODE_COLUMNS.filter((column) =>\n    shouldProjectColumn(requiredColumns, column, alwaysRequiredColumns),\n  ).map(\n    (column) =>\n      sql`${sql.raw(tableAlias)}.${sql.raw(column)} AS ${sql.raw(`${alias}_${column}`)}`,\n  );\n}\n\nfunction compileNodeSelectColumnsFromRecursiveRow(\n  alias: string,\n  requiredColumns: ReadonlySet<string> | undefined,\n  alwaysRequiredColumns: ReadonlySet<string>,\n): SqlFragment[] {\n  return NODE_COLUMNS.filter((column) =>\n    shouldProjectColumn(requiredColumns, column, alwaysRequiredColumns),\n  ).map((column) => {\n    const projected = `${alias}_${column}`;\n    return sql`r.${sql.raw(projected)} AS ${sql.raw(projected)}`;\n  });\n}\n\n/**\n * Compiles projection for recursive query results.\n */\nfunction compileRecursiveProjection(\n  ast: QueryAst,\n  traversal: VariableLengthTraversal,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n    return compileRecursiveSelectiveProjection(\n      ast.selectiveFields,\n      ast,\n      traversal,\n      ctx,\n    );\n  }\n\n  const startAlias = ast.start.alias;\n  const nodeAlias = traversal.nodeAlias;\n  const vl = traversal.variableLength;\n\n  const explicitProjection = hasExplicitRecursiveProjection(ast);\n  const fields: SqlFragment[] =\n    explicitProjection ?\n      compileAdditionalRecursiveProjectionFields(\n        ast,\n        new Set(),\n        ctx,\n        undefined,\n        new Set([traversal.edgeAlias]),\n      )\n    : [startAlias, nodeAlias].flatMap((alias) =>\n        NODE_COLUMNS.map((column) => {\n          const name = `${alias}_${column}`;\n          return sql`${sql.raw(name)} AS ${quoteIdentifier(name)}`;\n        }),\n      );\n\n  if (vl.depthAlias !== undefined) {\n    fields.push(sql`depth AS ${quoteIdentifier(vl.depthAlias)}`);\n  }\n\n  if (vl.pathAlias !== undefined) {\n    fields.push(\n      sql`${sql.raw(vl.pathFormat === \"qualified\" ? \"qualified_path\" : \"path\")} AS ${quoteIdentifier(vl.pathAlias)}`,\n    );\n  }\n\n  if (!explicitProjection)\n    fields.push(\n      ...compileAdditionalRecursiveProjectionFields(\n        ast,\n        new Set(\n          [startAlias, nodeAlias].flatMap((alias) =>\n            NODE_COLUMNS.map((column) => `${alias}_${column}`),\n          ),\n        ),\n        ctx,\n        undefined,\n        new Set([traversal.edgeAlias]),\n      ),\n    );\n\n  return sql.join(fields, sql`, `);\n}\n\nfunction compileRecursiveSelectiveProjection(\n  fields: readonly SelectiveField[],\n  ast: QueryAst,\n  traversal: VariableLengthTraversal,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const dialect = ctx.dialect;\n  const allowedAliases = new Set([ast.start.alias, traversal.nodeAlias]);\n\n  const columns = fields.map((field) =>\n    compileRecursiveSelectiveField(field, allowedAliases, dialect),\n  );\n\n  columns.push(\n    ...compileAdditionalRecursiveProjectionFields(\n      ast,\n      new Set(fields.map((field) => field.outputName)),\n      ctx,\n      undefined,\n      new Set([traversal.edgeAlias]),\n    ),\n  );\n\n  // Include recursive depth/path columns when present\n  const vl = traversal.variableLength;\n  if (vl.depthAlias !== undefined) {\n    columns.push(sql`depth AS ${quoteIdentifier(vl.depthAlias)}`);\n  }\n  if (vl.pathAlias !== undefined) {\n    columns.push(\n      sql`${sql.raw(vl.pathFormat === \"qualified\" ? \"qualified_path\" : \"path\")} AS ${quoteIdentifier(vl.pathAlias)}`,\n    );\n  }\n\n  return sql.join(columns, sql`, `);\n}\n\n/** Explicit SQL projections choose their output shape; compatibility select() hydrates aliases. */\nexport function hasExplicitRecursiveProjection(ast: QueryAst): boolean {\n  return ast.projection.fields.some(\n    (field) => field.source.__type !== \"field_ref\",\n  );\n}\n\n/** Compiles a decoded node field consistently in single and composed recursion. */\nexport function compileRecursiveSelectiveField(\n  field: SelectiveField,\n  allowedAliases: ReadonlySet<string>,\n  dialect: DialectAdapter,\n  resultAlias?: string,\n): SqlFragment {\n  if (!allowedAliases.has(field.alias))\n    throw new UnsupportedPredicateError(\n      `Selective projection for recursive traversals does not support alias \"${field.alias}\"`,\n    );\n  const column = `${field.alias}_${field.isSystemField ? mapSelectiveSystemFieldToColumn(field.field) : \"props\"}`;\n  const reference =\n    resultAlias === undefined ?\n      sql.raw(column)\n    : sql`${sql.identifier(resultAlias)}.${sql.identifier(column)}`;\n  const value =\n    field.isSystemField ? reference : (\n      compileSelectivePropsExtraction(field, reference, dialect)\n    );\n  return sql`${value} AS ${quoteIdentifier(field.outputName)}`;\n}\n\n/** Emits envelope-only projection fields that selective decoding did not request. */\nexport function compileAdditionalRecursiveProjectionFields(\n  ast: QueryAst,\n  emittedOutputNames: ReadonlySet<string>,\n  ctx: PredicateCompilerContext,\n  resultAlias?: string,\n  edgeAliases: ReadonlySet<string> = new Set(),\n): SqlFragment[] {\n  return ast.projection.fields\n    .filter((field) => !emittedOutputNames.has(field.outputName))\n    .map((field) => {\n      const source = field.source;\n      const sourceAlias =\n        source.__type === \"aggregate\" ? source.field.alias\n        : source.__type === \"database_expression\" ? undefined\n        : source.alias;\n      if (source.__type === \"database_expression\") {\n        visitExpressionFields(source, (reference) => {\n          if (edgeAliases.has(reference.alias))\n            throw new UnsupportedPredicateError(\n              \"Scalar recursive-edge projection is not supported; request a qualified path instead.\",\n            );\n        });\n      }\n      if (sourceAlias !== undefined && edgeAliases.has(sourceAlias)) {\n        // Compatibility select() carries structural edge columns even when the\n        // callback never reads an edge. Only these synthetic columns are empty.\n        if (field.cteAlias !== undefined)\n          return sql`NULL AS ${quoteIdentifier(field.outputName)}`;\n        throw new UnsupportedPredicateError(\n          \"Scalar recursive-edge projection is not supported; request a qualified path instead.\",\n        );\n      }\n      if (source.__type === \"aggregate\") {\n        throw new UnsupportedPredicateError(\n          \"Aggregate projection is not supported for recursive traversals\",\n        );\n      }\n      const value =\n        source.__type === \"database_expression\" ?\n          compileRecursiveDatabaseExpression(\n            source,\n            ctx,\n            resultAlias,\n            \"recursive projection\",\n          )\n        : resultAlias === undefined ?\n          compileFieldValue(source, ctx.dialect, source.valueType)\n        : compileRecursiveResultField(source, ctx.dialect, resultAlias);\n      return sql`${value} AS ${quoteIdentifier(field.outputName)}`;\n    });\n}\n\nfunction compileRecursiveDatabaseExpression(\n  expression: DatabaseExpression,\n  ctx: PredicateCompilerContext,\n  resultAlias: string | undefined,\n  clause: string,\n): SqlFragment {\n  return compileDatabaseExpression(expression, {\n    dialect: ctx.dialect,\n    allowAggregates: false,\n    aggregateClause: clause,\n    ...(ctx.compileExpressionSubquery === undefined ?\n      {}\n    : { compileSubquery: ctx.compileExpressionSubquery }),\n    ...(ctx.compileExpressionOuterReference === undefined ?\n      {}\n    : { compileOuterReference: ctx.compileExpressionOuterReference }),\n    ...(resultAlias === undefined ?\n      {}\n    : {\n        compileFieldExpression(field, fieldExpression) {\n          return compileRecursiveResultField(\n            field,\n            ctx.dialect,\n            resultAlias,\n            fieldExpression.valueType,\n          );\n        },\n      }),\n  });\n}\n\nexport function compileRecursiveResultField(\n  field: FieldRef,\n  dialect: DialectAdapter,\n  resultAlias: string,\n  valueType = field.valueType,\n): SqlFragment {\n  const baseColumn =\n    field.path[0] === \"props\" ?\n      `${field.alias}_props`\n    : `${field.alias}_${field.path.join(\"_\")}`;\n  const column = sql`${sql.identifier(resultAlias)}.${sql.identifier(baseColumn)}`;\n  return compileFieldValueFromColumn(field, dialect, valueType, column);\n}\n\n/**\n * Compiles ORDER BY for recursive query.\n */\nexport function compileRecursiveOrderBy(\n  ast: QueryAst,\n  ctx: PredicateCompilerContext,\n  resultAlias?: string,\n): SqlFragment | undefined {\n  if (!ast.orderBy || ast.orderBy.length === 0) {\n    return undefined;\n  }\n\n  const parts: SqlFragment[] = [];\n\n  for (const orderSpec of ast.orderBy) {\n    const valueType = orderSpec.field.valueType;\n    if (valueType === \"array\" || valueType === \"object\") {\n      throw new UnsupportedPredicateError(\n        \"Ordering by JSON arrays or objects is not supported\",\n      );\n    }\n    const field =\n      orderSpec.field.__type === \"database_expression\" ?\n        compileRecursiveDatabaseExpression(\n          orderSpec.field,\n          ctx,\n          resultAlias,\n          \"recursive ORDER BY\",\n        )\n      : resultAlias === undefined ?\n        compileFieldValue(orderSpec.field, ctx.dialect, valueType)\n      : compileRecursiveResultField(\n          orderSpec.field,\n          ctx.dialect,\n          resultAlias,\n          valueType,\n        );\n    const nulls = resolveNullOrdering(orderSpec);\n    parts.push(compileOrderTerm(field, orderSpec.direction, nulls));\n  }\n\n  return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\n/**\n * Compiles LIMIT and OFFSET clauses.\n */\nfunction compileLimitOffset(\n  ast: QueryAst,\n  dialect: DialectAdapter,\n): SqlFragment | undefined {\n  const parts = compileLimitOffsetClauses(ast.limit, ast.offset, dialect);\n  return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\n}\n","import { requireDefined } from \"../../utils/presence\";\nimport type { OneStatementBatchableQuery } from \"./types\";\n\nexport type OneStatementBatchItem<Result = unknown> = ReturnType<\n  NonNullable<\n    OneStatementBatchableQuery<Result>[\"compileOneStatementBatchItem\"]\n  >\n>;\n\nexport type OneStatementSharing = Readonly<{\n  owner: object;\n  key: string;\n  combine: (\n    items: readonly OneStatementBatchItem[],\n  ) => OneStatementBatchItem<readonly unknown[]>;\n}>;\n\nexport type OneStatementBatchGroup = Readonly<{\n  indices: readonly number[];\n  item: OneStatementBatchItem<readonly unknown[]>;\n}>;\n\n// Evidence belongs to the exact compiled item, not a mutable read wrapper.\nconst sharing = new WeakMap<OneStatementBatchItem, OneStatementSharing>();\n\nexport function registerOneStatementSharing(\n  item: OneStatementBatchItem,\n  plan: OneStatementSharing,\n): void {\n  sharing.set(item, plan);\n}\n\nexport function groupOneStatementBatchItems(\n  items: readonly OneStatementBatchItem[],\n  enabled: boolean,\n): readonly OneStatementBatchGroup[] {\n  const groups: {\n    indices: number[];\n    sharing: OneStatementSharing | undefined;\n  }[] = [];\n  const owners = new Map<object, Map<string, number>>();\n  for (const [index, item] of items.entries()) {\n    const plan = enabled ? sharing.get(item) : undefined;\n    if (plan === undefined) {\n      groups.push({ indices: [index], sharing: undefined });\n      continue;\n    }\n    const keys = owners.get(plan.owner) ?? new Map<string, number>();\n    owners.set(plan.owner, keys);\n    const existing = keys.get(plan.key);\n    if (existing === undefined) {\n      keys.set(plan.key, groups.length);\n      groups.push({ indices: [index], sharing: plan });\n    } else {\n      requireDefined(groups[existing]).indices.push(index);\n    }\n  }\n  return groups.map((group) => {\n    const inputs = group.indices.map((index) => requireDefined(items[index]));\n    const first = requireDefined(inputs[0]);\n    return {\n      indices: group.indices,\n      item:\n        group.sharing !== undefined && inputs.length > 1 ?\n          group.sharing.combine(inputs)\n        : { ...first, mapRows: (rows) => [first.mapRows(rows)] },\n    };\n  });\n}\n","/**\n * Value decoding utilities for query execution.\n *\n * Selective projection queries return values extracted directly from JSON\n * columns. Some dialects return booleans/numbers as different JS types, and\n * arrays/objects may be returned as JSON text. This module normalizes those\n * values based on schema type information.\n */\n\nimport { type ValueType } from \"../ast\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\n\nexport function nullToUndefined(value: unknown): unknown {\n  return value === null ? undefined : value;\n}\n\nexport function decodeSelectedValue(\n  value: unknown,\n  typeInfo: FieldTypeInfo | undefined,\n): unknown {\n  const normalized = nullToUndefined(value);\n  if (normalized === undefined) return undefined;\n\n  if (typeInfo === undefined) {\n    return normalized;\n  }\n\n  return decodeByValueType(normalized, typeInfo.valueType);\n}\n\nfunction decodeByValueType(value: unknown, valueType: ValueType): unknown {\n  switch (valueType) {\n    case \"boolean\": {\n      if (typeof value === \"boolean\") return value;\n      if (typeof value === \"number\") return value !== 0;\n      if (typeof value === \"string\") {\n        if (value === \"0\") return false;\n        if (value === \"1\") return true;\n        if (value.toLowerCase() === \"true\") return true;\n        if (value.toLowerCase() === \"false\") return false;\n      }\n      return Boolean(value);\n    }\n    case \"number\": {\n      if (typeof value === \"number\") return value;\n      if (typeof value === \"string\") {\n        const parsed = Number(value);\n        return Number.isNaN(parsed) ? value : parsed;\n      }\n      return value;\n    }\n    case \"array\":\n    case \"object\":\n    case \"embedding\": {\n      if (typeof value !== \"string\") return value;\n      const trimmed = value.trim();\n      const looksJson = trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\");\n      if (!looksJson) return value;\n      try {\n        return JSON.parse(trimmed) as unknown;\n      } catch {\n        return value;\n      }\n    }\n    case \"string\":\n    case \"date\":\n    case \"unknown\": {\n      return value;\n    }\n    default: {\n      const _exhaustive: never = valueType;\n      void _exhaustive;\n      return value;\n    }\n  }\n}\n","import { backendDerivationRoot } from \"../backend/derive-backend\";\nimport {\n  normalizeRequiredRowTimestamp,\n  normalizeRowTimestamp,\n} from \"../backend/row-mappers\";\nimport type { GraphBackend, RowProps } from \"../backend/types\";\nimport type { AllNodeTypes, EdgeKinds, GraphDef } from \"../core/define-graph\";\nimport type { TemporalMode } from \"../core/types\";\nimport { ValidationError } from \"../errors\";\nimport type { ExecutableOneStatementRead } from \"../query/builder/types\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport type { SqlSchema } from \"../query/compiler/schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { compileTypedJsonExtract } from \"../query/compiler/typed-json-extract\";\nimport { getDialect } from \"../query/dialect\";\nimport { jsonPointer } from \"../query/json-pointer\";\nimport type { FieldTypeInfo } from \"../query/schema-introspector\";\nimport { createSchemaIntrospector } from \"../query/schema-introspector\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport type { KindRegistry } from \"../registry\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport type {\n  Edge,\n  GraphEdgeForKinds,\n  GraphNodeReference,\n  Node,\n} from \"./types\";\n\n/** Edge metadata fields accepted by bounded neighbor and subgraph reads. */\nexport type NeighborOrderField =\n  \"createdAt\" | \"id\" | \"updatedAt\" | \"validFrom\" | \"validTo\";\n\n/** Node property names accepted by adjacent-node ordering. */\nexport type NeighborNodeOrderField<G extends GraphDef> = {\n  [K in keyof G[\"nodes\"] & string]: Exclude<\n    keyof Node<G[\"nodes\"][K][\"type\"]>,\n    \"id\" | \"kind\" | \"meta\"\n  > &\n    string;\n}[keyof G[\"nodes\"] & string];\n\nexport type NeighborOrder<G extends GraphDef> =\n  | Readonly<{\n      by?: \"edge\";\n      field: NeighborOrderField;\n      direction?: \"asc\" | \"desc\";\n    }>\n  | Readonly<{\n      by: \"node\";\n      field: NeighborNodeOrderField<G>;\n      direction?: \"asc\" | \"desc\";\n    }>;\n\nconst NEIGHBOR_ORDER_FIELDS = [\n  \"createdAt\",\n  \"id\",\n  \"updatedAt\",\n  \"validFrom\",\n  \"validTo\",\n] as const satisfies readonly NeighborOrderField[];\nconst NEIGHBOR_ORDER_FIELD_SET: ReadonlySet<string> = new Set(\n  NEIGHBOR_ORDER_FIELDS,\n);\n\nfunction isNeighborOrderField(field: string): field is NeighborOrderField {\n  return NEIGHBOR_ORDER_FIELD_SET.has(field);\n}\n\n/** Per-edge-kind ordering and bound applied before traversal expands an edge. */\nexport type EdgeReadWindow = Readonly<{\n  limit: number;\n  /** Direction for this edge kind; defaults to the traversal direction. */\n  direction?: \"both\" | \"in\" | \"out\";\n  orderBy?: Readonly<{\n    field: NeighborOrderField;\n    direction?: \"asc\" | \"desc\";\n  }>;\n}>;\n\n/** Options for reading adjacent edge-node pairs without hydrating all targets. */\ntype NeighborReadOptionsBoundary<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n> = Readonly<{\n  edges?: readonly K[];\n  direction?: \"both\" | \"in\" | \"out\";\n  orderBy?: NeighborOrder<G>;\n  limit?: number;\n  temporalMode?: TemporalMode;\n  asOf?: string;\n}>;\n\nexport type NeighborReadOptions<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n> = NeighborReadOptionsBoundary<G, K> &\n  Required<Pick<NeighborReadOptionsBoundary<G, K>, \"edges\">>;\n\n/** One edge and the node it reaches from the requested source and direction. */\nexport type NeighborResult<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n> = Readonly<{\n  edge: GraphEdgeForKinds<G, K>;\n  node: Node<AllNodeTypes<G>>;\n}>;\n\ntype NeighborRow = Readonly<Record<string, unknown>>;\n\nfunction mapNeighborCountRows(rows: readonly NeighborRow[]): number {\n  return Number(rows[0]?.[\"count\"] ?? 0);\n}\n\ntype NeighborContext = Readonly<{\n  graphId: string;\n  backend: GraphBackend;\n  schema: SqlSchema;\n  defaultTemporalMode: TemporalMode;\n  registry: KindRegistry;\n}>;\n\nexport type NeighborRead<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n> = ExecutableOneStatementRead<readonly NeighborResult<G, K>[]>;\n\nexport function createNeighborRead<G extends GraphDef, K extends EdgeKinds<G>>(\n  ctx: NeighborContext,\n  source: GraphNodeReference<G>,\n  options: NeighborReadOptions<G, K>,\n): NeighborRead<G, K> {\n  validateOptions(ctx, options);\n  const query = buildNeighborQuery(ctx, source, options, false);\n  function mapRows(\n    rows: readonly NeighborRow[],\n  ): readonly NeighborResult<G, K>[] {\n    return rows.map((row) => ({\n      edge: mapEdge(row) as GraphEdgeForKinds<G, K>,\n      node: mapNode(row) as Node<AllNodeTypes<G>>,\n    }));\n  }\n  return {\n    execute: async () => {\n      if (options.edges.length === 0) return [];\n      return mapRows(\n        await ctx.backend.execute<NeighborRow>(asCompiledRowsSql(query)),\n      );\n    },\n    compileOneStatementBatchItem: () => ({\n      query: asCompiledRowsSql(query),\n      provenance: {\n        graphId: ctx.graphId,\n        executionTarget: backendDerivationRoot(ctx.backend),\n      },\n      outputNames: neighborOutputNames(),\n      orderBy: neighborBatchOrder(options.orderBy),\n      mapRows,\n    }),\n  };\n}\n\nexport async function readNeighbors<G extends GraphDef, K extends EdgeKinds<G>>(\n  ctx: NeighborContext,\n  source: GraphNodeReference<G>,\n  options: NeighborReadOptions<G, K>,\n): Promise<readonly NeighborResult<G, K>[]> {\n  return createNeighborRead(ctx, source, options).execute();\n}\n\nexport async function countNeighbors<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n>(\n  ctx: NeighborContext,\n  source: GraphNodeReference<G>,\n  options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n): Promise<number> {\n  return createNeighborCountRead(ctx, source, options).execute();\n}\n\nexport function createNeighborCountRead<\n  G extends GraphDef,\n  K extends EdgeKinds<G>,\n>(\n  ctx: NeighborContext,\n  source: GraphNodeReference<G>,\n  options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n): ExecutableOneStatementRead<number> {\n  validateEdgeReadBounds(options, \"countNeighbors\");\n  const query = buildNeighborQuery(ctx, source, options, true);\n  return {\n    execute: async () => {\n      if (options.edges.length === 0) return 0;\n      return mapNeighborCountRows(\n        await ctx.backend.execute<NeighborRow>(asCompiledRowsSql(query)),\n      );\n    },\n    compileOneStatementBatchItem: () => ({\n      query: asCompiledRowsSql(query),\n      provenance: {\n        graphId: ctx.graphId,\n        executionTarget: backendDerivationRoot(ctx.backend),\n      },\n      outputNames: [\"count\"],\n      orderBy: [],\n      mapRows: mapNeighborCountRows,\n    }),\n  };\n}\n\nfunction buildNeighborQuery<G extends GraphDef, K extends EdgeKinds<G>>(\n  ctx: NeighborContext,\n  source: GraphNodeReference<G>,\n  options: NeighborReadOptions<G, K>,\n  aggregate: boolean,\n): SqlFragment {\n  const direction = options.direction ?? \"out\";\n  const instant = currentReadInstant();\n  const temporalMode = options.temporalMode ?? ctx.defaultTemporalMode;\n  const edgeTemporal = compileTemporalFilter({\n    mode: temporalMode,\n    asOf: options.asOf,\n    tableAlias: \"e\",\n    currentTimestamp: instant,\n  });\n  const nodeTemporal = compileTemporalFilter({\n    mode: temporalMode,\n    asOf: options.asOf,\n    tableAlias: \"n\",\n    currentTimestamp: instant,\n  });\n  const endpoint = endpointClauses(direction, source);\n  const where = sql.join(\n    [\n      sql`e.graph_id = ${ctx.graphId}`,\n      sql`n.graph_id = ${ctx.graphId}`,\n      compileKindFilter(sql.raw(\"e.kind\"), options.edges),\n      edgeTemporal,\n      nodeTemporal,\n      endpoint.filter,\n    ],\n    sql` AND `,\n  );\n  if (aggregate) {\n    return sql`SELECT COUNT(DISTINCT e.id) AS count FROM ${ctx.schema.edgesTable} e JOIN ${ctx.schema.nodesTable} n ON ${endpoint.join} WHERE ${where}`;\n  }\n  const orderValue = buildOrderValue(ctx, options.orderBy);\n  const order = buildOrder(options.orderBy, orderValue);\n  const limit =\n    options.limit === undefined ? sql.empty() : sql` LIMIT ${options.limit}`;\n  return sql`SELECT ${neighborColumns()}, ${orderValue} AS typegraph_neighbor_order FROM ${ctx.schema.edgesTable} e JOIN ${ctx.schema.nodesTable} n ON ${endpoint.join} WHERE ${where} ORDER BY ${order}${limit}`;\n}\n\nfunction endpointClauses(\n  direction: \"both\" | \"in\" | \"out\",\n  source: Readonly<{ kind: string; id: string }>,\n): Readonly<{ join: SqlFragment; filter: SqlFragment }> {\n  const outgoingFilter = sql`e.from_kind = ${source.kind} AND e.from_id = ${source.id}`;\n  const incomingFilter = sql`e.to_kind = ${source.kind} AND e.to_id = ${source.id}`;\n  switch (direction) {\n    case \"out\": {\n      return {\n        filter: outgoingFilter,\n        join: sql`n.kind = e.to_kind AND n.id = e.to_id`,\n      };\n    }\n    case \"in\": {\n      return {\n        filter: incomingFilter,\n        join: sql`n.kind = e.from_kind AND n.id = e.from_id`,\n      };\n    }\n    case \"both\": {\n      return {\n        filter: sql`((${outgoingFilter}) OR (${incomingFilter}))`,\n        join: sql`((e.from_kind = ${source.kind} AND e.from_id = ${source.id} AND n.kind = e.to_kind AND n.id = e.to_id) OR (e.to_kind = ${source.kind} AND e.to_id = ${source.id} AND n.kind = e.from_kind AND n.id = e.from_id))`,\n      };\n    }\n  }\n}\n\nexport function edgeOrderColumnName(field: NeighborOrderField): string {\n  switch (field) {\n    case \"id\": {\n      return \"id\";\n    }\n    case \"createdAt\": {\n      return \"created_at\";\n    }\n    case \"updatedAt\": {\n      return \"updated_at\";\n    }\n    case \"validFrom\": {\n      return \"valid_from\";\n    }\n    case \"validTo\": {\n      return \"valid_to\";\n    }\n  }\n}\n\nfunction buildOrderValue(\n  ctx: NeighborContext,\n  orderBy: NeighborReadOptions<GraphDef, string>[\"orderBy\"],\n): SqlFragment {\n  if (orderBy?.by !== \"node\") {\n    return sql`e.${sql.raw(edgeOrderColumnName(orderBy?.field ?? \"id\"))}`;\n  }\n  return compileTypedJsonExtract({\n    column: sql.raw(\"n.props\"),\n    dialect: getDialect(ctx.backend.dialect),\n    fallback: \"text\",\n    pointer: jsonPointer([orderBy.field]),\n    valueType: resolveNodeOrderFieldType(ctx, orderBy.field)?.valueType,\n  });\n}\n\nfunction buildOrder(\n  orderBy: NeighborReadOptions<GraphDef, string>[\"orderBy\"],\n  value: SqlFragment,\n): SqlFragment {\n  const direction = orderBy?.direction ?? \"asc\";\n  return sql`CASE WHEN ${value} IS NULL THEN 1 ELSE 0 END ASC, ${value} ${sql.raw(direction.toUpperCase())}, e.id ASC`;\n}\n\nfunction neighborBatchOrder(\n  orderBy: NeighborReadOptions<GraphDef, string>[\"orderBy\"],\n): readonly Readonly<{\n  column: string;\n  direction: \"asc\" | \"desc\";\n  nulls: \"last\";\n}>[] {\n  return [\n    {\n      column: \"typegraph_neighbor_order\",\n      direction: orderBy?.direction ?? \"asc\",\n      nulls: \"last\",\n    },\n    { column: \"edge_id\", direction: \"asc\", nulls: \"last\" },\n  ];\n}\n\nfunction validateOptions(\n  ctx: NeighborContext,\n  options: NeighborReadOptions<GraphDef, string>,\n): void {\n  validateEdgeReadBounds(options, \"neighbors\");\n  if (options.orderBy?.by !== \"node\") return;\n  resolveNodeOrderFieldType(ctx, options.orderBy.field);\n}\n\nfunction resolveNodeOrderFieldType(\n  ctx: NeighborContext,\n  field: string,\n): FieldTypeInfo | undefined {\n  const nodeKinds = [...ctx.registry.nodeKinds.keys()];\n  const introspector = createSchemaIntrospector(ctx.registry.nodeKinds);\n  const declaringKinds = nodeKinds.filter(\n    (kind) => introspector.getFieldTypeInfo(kind, field) !== undefined,\n  );\n  if (declaringKinds.length === 0) {\n    throw new ValidationError(\"Unknown adjacent-node ordering field\", {\n      issues: [{ path: \"neighbors.orderBy.field\", message: \"Invalid field\" }],\n    });\n  }\n  return introspector.getSharedFieldTypeInfo(declaringKinds, field);\n}\n\nexport function validateEdgeReadBounds(\n  options: Readonly<{\n    limit?: number;\n    direction?: string;\n    orderBy?: Readonly<{ by?: string; field: string; direction?: string }>;\n  }>,\n  path: string,\n): void {\n  if (\n    options.limit !== undefined &&\n    (!Number.isSafeInteger(options.limit) || options.limit <= 0)\n  ) {\n    throw new ValidationError(\n      \"Neighbor limit must be a positive safe integer\",\n      {\n        issues: [{ path: `${path}.limit`, message: \"Invalid edge-read limit\" }],\n      },\n    );\n  }\n  if (\n    options.direction !== undefined &&\n    options.direction !== \"both\" &&\n    options.direction !== \"in\" &&\n    options.direction !== \"out\"\n  ) {\n    throw new ValidationError(\"Unknown edge traversal direction\", {\n      issues: [{ path: `${path}.direction`, message: \"Invalid direction\" }],\n    });\n  }\n  const field = options.orderBy?.field;\n  if (\n    field !== undefined &&\n    options.orderBy?.by !== \"node\" &&\n    !isNeighborOrderField(field)\n  ) {\n    throw new ValidationError(\"Unknown edge ordering field\", {\n      issues: [{ path: `${path}.orderBy.field`, message: \"Invalid field\" }],\n    });\n  }\n  const direction = options.orderBy?.direction;\n  if (direction !== undefined && direction !== \"asc\" && direction !== \"desc\") {\n    throw new ValidationError(\"Unknown edge ordering direction\", {\n      issues: [\n        { path: `${path}.orderBy.direction`, message: \"Invalid direction\" },\n      ],\n    });\n  }\n}\n\nfunction neighborColumns(): SqlFragment {\n  const edgeColumns = [\n    \"graph_id\",\n    \"id\",\n    \"kind\",\n    \"from_kind\",\n    \"from_id\",\n    \"to_kind\",\n    \"to_id\",\n    \"props\",\n    \"valid_from\",\n    \"valid_to\",\n    \"created_at\",\n    \"updated_at\",\n    \"deleted_at\",\n  ];\n  const nodeColumns = [\n    \"graph_id\",\n    \"id\",\n    \"kind\",\n    \"props\",\n    \"version\",\n    \"valid_from\",\n    \"valid_to\",\n    \"created_at\",\n    \"updated_at\",\n    \"deleted_at\",\n  ];\n  return sql.join(\n    [\n      ...edgeColumns.map(\n        (column) =>\n          sql`e.${sql.raw(column)} AS ${sql.identifier(`edge_${column}`)}`,\n      ),\n      ...nodeColumns.map(\n        (column) =>\n          sql`n.${sql.raw(column)} AS ${sql.identifier(`node_${column}`)}`,\n      ),\n    ],\n    sql`, `,\n  );\n}\n\nfunction neighborOutputNames(): readonly string[] {\n  return [\n    \"edge_graph_id\",\n    \"edge_id\",\n    \"edge_kind\",\n    \"edge_from_kind\",\n    \"edge_from_id\",\n    \"edge_to_kind\",\n    \"edge_to_id\",\n    \"edge_props\",\n    \"edge_valid_from\",\n    \"edge_valid_to\",\n    \"edge_created_at\",\n    \"edge_updated_at\",\n    \"edge_deleted_at\",\n    \"node_graph_id\",\n    \"node_id\",\n    \"node_kind\",\n    \"node_props\",\n    \"node_version\",\n    \"node_valid_from\",\n    \"node_valid_to\",\n    \"node_created_at\",\n    \"node_updated_at\",\n    \"node_deleted_at\",\n  ];\n}\n\nfunction mapEdge(row: NeighborRow): Edge {\n  return rowToEdge({\n    id: String(row[\"edge_id\"]),\n    kind: String(row[\"edge_kind\"]),\n    from_kind: String(row[\"edge_from_kind\"]),\n    from_id: String(row[\"edge_from_id\"]),\n    to_kind: String(row[\"edge_to_kind\"]),\n    to_id: String(row[\"edge_to_id\"]),\n    props: row[\"edge_props\"] as RowProps,\n    valid_from: normalizeRowTimestamp(\n      row[\"edge_valid_from\"],\n      \"edge_valid_from\",\n    ),\n    valid_to: normalizeRowTimestamp(row[\"edge_valid_to\"], \"edge_valid_to\"),\n    created_at: normalizeRequiredRowTimestamp(\n      row[\"edge_created_at\"],\n      \"edge_created_at\",\n    ),\n    updated_at: normalizeRequiredRowTimestamp(\n      row[\"edge_updated_at\"],\n      \"edge_updated_at\",\n    ),\n    deleted_at: normalizeRowTimestamp(\n      row[\"edge_deleted_at\"],\n      \"edge_deleted_at\",\n    ),\n  });\n}\n\nfunction mapNode(row: NeighborRow): Node {\n  return rowToNode({\n    id: String(row[\"node_id\"]),\n    kind: String(row[\"node_kind\"]),\n    props: row[\"node_props\"] as RowProps,\n    version: Number(row[\"node_version\"]),\n    valid_from: normalizeRowTimestamp(\n      row[\"node_valid_from\"],\n      \"node_valid_from\",\n    ),\n    valid_to: normalizeRowTimestamp(row[\"node_valid_to\"], \"node_valid_to\"),\n    created_at: normalizeRequiredRowTimestamp(\n      row[\"node_created_at\"],\n      \"node_created_at\",\n    ),\n    updated_at: normalizeRequiredRowTimestamp(\n      row[\"node_updated_at\"],\n      \"node_updated_at\",\n    ),\n    deleted_at: normalizeRowTimestamp(\n      row[\"node_deleted_at\"],\n      \"node_deleted_at\",\n    ),\n  });\n}\n","import {\n  assertRecursiveTraversal,\n  type RecursiveTraversalVerdict,\n} from \"../backend/capabilities/recursive-traversal\";\nimport { type RecordedInstant } from \"../core/temporal\";\nimport { type TemporalMode } from \"../core/types\";\nimport { type RecursiveCyclePolicy } from \"../query/ast\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport {\n  type RecordedReadBinding,\n  recordedReadSchemaFor,\n  type SqlSchema,\n} from \"../query/compiler/schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../query/dialect/types\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { type TraversalDirection } from \"./algorithms/types\";\nimport { edgeOrderColumnName, type EdgeReadWindow } from \"./neighbors\";\n\ntype BuildReachableCteOptions = Readonly<{\n  graphId: string;\n  edgeKinds: readonly string[];\n  maxHops: number;\n  direction: TraversalDirection;\n  cyclePolicy: RecursiveCyclePolicy;\n  includePath: boolean;\n  /**\n   * Temporal mode applied to both nodes and edges along the traversal.\n   * Callers that want the pre-temporal behavior (soft-delete only) should\n   * pass `\"includeEnded\"`.\n   */\n  temporalMode: TemporalMode;\n  currentTimestamp?: SqlFragment;\n  /** ISO-8601 timestamp used when `temporalMode === \"asOf\"`. */\n  asOf?: string;\n  /** Recorded/system-time timestamp for recorded-pinned reads. */\n  recordedAsOf?: RecordedInstant;\n  dialect: DialectAdapter;\n  /**\n   * The base (live-table) schema. The recorded-relation swap is derived here\n   * from `recordedAsOf`, so the table source and the recorded interval predicate\n   * cannot drift — callers pass their base schema and need not pre-resolve it.\n   */\n  schema: SqlSchema;\n  recordedReadBinding?: RecordedReadBinding;\n  /** Resolved verdict for the engine this CTE will run on. */\n  recursiveTraversal: RecursiveTraversalVerdict;\n  /** Operation label echoed in the refusal's `details.operation`. */\n  operation: string;\n  edgeWindows?: Readonly<Record<string, EdgeReadWindow | undefined>>;\n}> &\n  (\n    | Readonly<{ sourceId: string; sourceIds?: never }>\n    | Readonly<{ sourceId?: never; sourceIds: readonly string[] }>\n  );\n\nexport function buildReachableCte(\n  options: BuildReachableCteOptions,\n): SqlFragment {\n  assertRecursiveTraversal(options.recursiveTraversal, options.operation);\n  const trackPath = options.cyclePolicy === \"prevent\" || options.includePath;\n  const edgeKindFilter = compileKindFilter(\n    sql.raw(\"e.kind\"),\n    options.edgeKinds,\n  );\n  const currentTimestamp = options.currentTimestamp ?? currentReadInstant();\n  const nodeTemporalFilter = compileTemporalFilter({\n    mode: options.temporalMode,\n    asOf: options.asOf,\n    recordedAsOf: options.recordedAsOf,\n    tableAlias: \"n\",\n    currentTimestamp,\n    recordedReadBinding: options.recordedReadBinding,\n  });\n  const edgeTemporalFilter = compileTemporalFilter({\n    mode: options.temporalMode,\n    asOf: options.asOf,\n    recordedAsOf: options.recordedAsOf,\n    tableAlias: \"e\",\n    currentTimestamp,\n    recordedReadBinding: options.recordedReadBinding,\n  });\n  // Derive the read schema from the same `recordedAsOf` that drives the temporal\n  // filters above: when a recorded pin is set the node/edge sources become the\n  // recorded relations, matching the `recorded_from/to` interval predicate. One\n  // derivation means the table source and the predicate cannot disagree.\n  const schema = recordedReadSchemaFor(\n    options.schema,\n    options.recordedAsOf,\n    options.recordedReadBinding,\n    \"recorded-recursive-cte\",\n  );\n  const edgeWindows = Object.entries(options.edgeWindows ?? {}).filter(\n    (entry): entry is [string, EdgeReadWindow] => entry[1] !== undefined,\n  );\n\n  const initialPath =\n    trackPath ? options.dialect.initializePath(sql.raw(\"n.id\")) : undefined;\n  const pathExtension =\n    trackPath ?\n      options.dialect.extendPath(sql.raw(\"r.path\"), sql.raw(\"n.id\"))\n    : undefined;\n  const cycleCheck =\n    options.cyclePolicy === \"prevent\" ?\n      options.dialect.cycleCheck(sql.raw(\"n.id\"), sql.raw(\"r.path\"))\n    : undefined;\n\n  const baseColumns: SqlFragment[] = [sql`n.id`, sql`n.kind`, sql`0 AS depth`];\n  if (initialPath !== undefined) {\n    baseColumns.push(sql`${initialPath} AS path`);\n  }\n\n  if (options.sourceIds !== undefined) baseColumns.push(sql`n.id AS origin_id`);\n  const sourceFilter =\n    options.sourceIds === undefined ? sql`n.id = ${options.sourceId}`\n    : options.sourceIds.length === 0 ? sql`1 = 0`\n    : sql`n.id IN (${sql.join(\n        options.sourceIds.map((id) => sql`${id}`),\n        sql`, `,\n      )})`;\n  const baseCase = sql`SELECT ${sql.join(baseColumns, sql`, `)} FROM ${schema.nodesTable} n WHERE n.graph_id = ${options.graphId} AND ${sourceFilter} AND ${nodeTemporalFilter}`;\n\n  const recursiveColumns: SqlFragment[] = [\n    sql`n.id`,\n    sql`n.kind`,\n    sql`r.depth + 1 AS depth`,\n  ];\n  if (pathExtension !== undefined) {\n    recursiveColumns.push(sql`${pathExtension} AS path`);\n  }\n\n  if (options.sourceIds !== undefined) recursiveColumns.push(sql`r.origin_id`);\n\n  const recursiveWhere: SqlFragment[] = [\n    sql`e.graph_id = ${options.graphId}`,\n    edgeKindFilter,\n    edgeTemporalFilter,\n    nodeTemporalFilter,\n    sql`r.depth < ${options.maxHops}`,\n  ];\n  if (cycleCheck !== undefined) recursiveWhere.push(cycleCheck);\n\n  const forceWorktableOuterJoinOrder =\n    options.dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;\n\n  const usesOrientedEdges = edgeWindows.length > 0;\n  const recursiveCase = compileRecursiveBranch({\n    recursiveColumns,\n    whereClauses: recursiveWhere,\n    direction: usesOrientedEdges ? \"out\" : options.direction,\n    forceWorktableOuterJoinOrder,\n    schema,\n    edgesTable:\n      usesOrientedEdges ?\n        sql.identifier(\"typegraph_windowed_edges\")\n      : schema.edgesTable,\n    ...(usesOrientedEdges && {\n      joinField: \"typegraph_source_id\",\n      targetField: \"typegraph_target_id\",\n      targetKindField: \"typegraph_target_kind\",\n    }),\n  });\n\n  const windowedEdges =\n    usesOrientedEdges ?\n      buildWindowedEdgesCte(\n        schema.edgesTable,\n        options.direction,\n        options.edgeKinds.map((kind) => [kind, options.edgeWindows?.[kind]]),\n        sql.join(\n          [\n            sql`e.graph_id = ${options.graphId}`,\n            edgeKindFilter,\n            edgeTemporalFilter,\n          ],\n          sql` AND `,\n        ),\n      )\n    : undefined;\n  return windowedEdges === undefined ?\n      sql`WITH RECURSIVE reachable AS (${baseCase} UNION ALL ${recursiveCase})`\n    : sql`WITH RECURSIVE typegraph_windowed_edges AS (${windowedEdges}), reachable AS (${baseCase} UNION ALL ${recursiveCase})`;\n}\n\ntype CompileRecursiveBranchOptions = Readonly<{\n  recursiveColumns: readonly SqlFragment[];\n  whereClauses: readonly SqlFragment[];\n  direction: TraversalDirection;\n  forceWorktableOuterJoinOrder: boolean;\n  schema: SqlSchema;\n  edgesTable: SqlFragment;\n  joinField?: \"from_id\" | \"to_id\" | \"typegraph_source_id\";\n  targetField?: \"from_id\" | \"to_id\" | \"typegraph_target_id\";\n  targetKindField?: \"from_kind\" | \"to_kind\" | \"typegraph_target_kind\";\n}>;\n\nfunction compileRecursiveBranch(\n  options: CompileRecursiveBranchOptions,\n): SqlFragment {\n  const selectClause = sql`SELECT ${sql.join([...options.recursiveColumns], sql`, `)}`;\n\n  switch (options.direction) {\n    case \"out\": {\n      return buildDirectionalBranch({\n        selectClause,\n        whereClauses: options.whereClauses,\n        joinField: options.joinField ?? \"from_id\",\n        targetField: options.targetField ?? \"to_id\",\n        targetKindField: options.targetKindField ?? \"to_kind\",\n        forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n        schema: options.schema,\n        edgesTable: options.edgesTable,\n      });\n    }\n    case \"in\": {\n      return buildDirectionalBranch({\n        selectClause,\n        whereClauses: options.whereClauses,\n        joinField: \"to_id\",\n        targetField: \"from_id\",\n        targetKindField: \"from_kind\",\n        forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n        schema: options.schema,\n        edgesTable: options.edgesTable,\n      });\n    }\n    case \"both\": {\n      return buildBidirectionalBranch({\n        selectClause,\n        whereClauses: options.whereClauses,\n        forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n        schema: options.schema,\n        edgesTable: options.edgesTable,\n      });\n    }\n  }\n}\n\ntype DirectionalBranchOptions = Readonly<{\n  selectClause: SqlFragment;\n  whereClauses: readonly SqlFragment[];\n  joinField: \"from_id\" | \"to_id\" | \"typegraph_source_id\";\n  targetField: \"from_id\" | \"to_id\" | \"typegraph_target_id\";\n  targetKindField: \"from_kind\" | \"to_kind\" | \"typegraph_target_kind\";\n  forceWorktableOuterJoinOrder: boolean;\n  schema: SqlSchema;\n  edgesTable: SqlFragment;\n}>;\n\nfunction buildDirectionalBranch(\n  options: DirectionalBranchOptions,\n): SqlFragment {\n  const nodeJoin = sql`JOIN ${options.schema.nodesTable} n ON n.graph_id = e.graph_id AND n.id = e.${sql.raw(options.targetField)} AND n.kind = e.${sql.raw(options.targetKindField)}`;\n\n  if (options.forceWorktableOuterJoinOrder) {\n    const allWhere = [\n      ...options.whereClauses,\n      sql`e.${sql.raw(options.joinField)} = r.id`,\n    ];\n    return sql`${options.selectClause} FROM reachable r CROSS JOIN ${options.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n  }\n\n  return sql`${options.selectClause} FROM reachable r JOIN ${options.edgesTable} e ON e.${sql.raw(options.joinField)} = r.id ${nodeJoin} WHERE ${sql.join([...options.whereClauses], sql` AND `)}`;\n}\n\ntype BidirectionalBranchOptions = Readonly<{\n  selectClause: SqlFragment;\n  whereClauses: readonly SqlFragment[];\n  forceWorktableOuterJoinOrder: boolean;\n  schema: SqlSchema;\n  edgesTable: SqlFragment;\n}>;\n\nfunction buildBidirectionalBranch(\n  options: BidirectionalBranchOptions,\n): SqlFragment {\n  // PostgreSQL rejects multiple non-recursive terms, so both directions are\n  // folded into a single UNION ALL branch via an OR on the join condition.\n  const nodeJoin = sql`JOIN ${options.schema.nodesTable} n ON n.graph_id = e.graph_id AND ((e.to_id = r.id AND n.id = e.from_id AND n.kind = e.from_kind) OR (e.from_id = r.id AND n.id = e.to_id AND n.kind = e.to_kind))`;\n\n  if (options.forceWorktableOuterJoinOrder) {\n    const allWhere = [\n      ...options.whereClauses,\n      sql`(e.from_id = r.id OR e.to_id = r.id)`,\n    ];\n    return sql`${options.selectClause} FROM reachable r CROSS JOIN ${options.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n  }\n\n  return sql`${options.selectClause} FROM reachable r JOIN ${options.edgesTable} e ON (e.from_id = r.id OR e.to_id = r.id) ${nodeJoin} WHERE ${sql.join([...options.whereClauses], sql` AND `)}`;\n}\n\nexport function buildWindowedEdgesCte(\n  edgesTable: SqlFragment,\n  defaultDirection: TraversalDirection,\n  edgeKinds: readonly [string, EdgeReadWindow | undefined][],\n  where: SqlFragment,\n): SqlFragment {\n  const branches = edgeKinds.flatMap(([kind, window]) => {\n    const direction = window?.direction ?? defaultDirection;\n    const directions: readonly Exclude<TraversalDirection, \"both\">[] =\n      direction === \"both\" ? [\"out\", \"in\"] : [direction];\n    return directions.map((orientedDirection) => {\n      const sourceKind = orientedDirection === \"out\" ? \"from_kind\" : \"to_kind\";\n      const sourceId = orientedDirection === \"out\" ? \"from_id\" : \"to_id\";\n      const targetKind = orientedDirection === \"out\" ? \"to_kind\" : \"from_kind\";\n      const targetId = orientedDirection === \"out\" ? \"to_id\" : \"from_id\";\n      const column = edgeOrderColumnName(window?.orderBy?.field ?? \"id\");\n      const orderDirection = window?.orderBy?.direction ?? \"asc\";\n      const omitReverseSelfLoop =\n        direction === \"both\" && orientedDirection === \"in\" ?\n          sql` AND NOT (e.from_kind = e.to_kind AND e.from_id = e.to_id)`\n        : sql.empty();\n      const oriented = sql`SELECT e.*, e.${sql.raw(sourceKind)} AS typegraph_source_kind, e.${sql.raw(sourceId)} AS typegraph_source_id, e.${sql.raw(targetKind)} AS typegraph_target_kind, e.${sql.raw(targetId)} AS typegraph_target_id`;\n      if (window === undefined) {\n        return sql`${oriented}, 1 AS typegraphedgerank FROM ${edgesTable} e WHERE ${where} AND e.kind = ${kind}${omitReverseSelfLoop}`;\n      }\n      const rank = sql`ROW_NUMBER() OVER (PARTITION BY e.kind, e.${sql.raw(sourceKind)}, e.${sql.raw(sourceId)} ORDER BY CASE WHEN e.${sql.raw(column)} IS NULL THEN 1 ELSE 0 END ASC, e.${sql.raw(column)} ${sql.raw(orderDirection.toUpperCase())}, e.id ASC)`;\n      const ranked = sql`${oriented}, ${rank} AS typegraphedgerank FROM ${edgesTable} e WHERE ${where} AND e.kind = ${kind}${omitReverseSelfLoop}`;\n      return sql`SELECT * FROM (${ranked}) ranked WHERE ranked.typegraphedgerank <= ${window.limit}`;\n    });\n  });\n  return sql.join(branches, sql` UNION ALL `);\n}\n","/**\n * Subgraph Extraction\n *\n * Extracts a typed subgraph from a root node by traversing a set of edge kinds.\n * Both public read forms share one validation and projection plan. The direct\n * read uses the backend's tuned hydration strategy; the composable read emits\n * one statement so it can participate in batchOnce().\n */\nimport { resolveRecursiveTraversal } from \"../backend/capabilities/recursive-traversal\";\nimport { backendDerivationRoot } from \"../backend/derive-backend\";\nimport {\n  normalizeRequiredRowTimestamp,\n  normalizeRowTimestamp,\n} from \"../backend/row-mappers\";\nimport type { GraphBackend } from \"../backend/types\";\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../constants\";\nimport type {\n  AllNodeTypes,\n  EdgeKinds,\n  GraphDef,\n  NodeKinds,\n} from \"../core/define-graph\";\nimport { type RecordedInstant, resolveReadCoordinate } from \"../core/temporal\";\nimport type { KindEntity } from \"../core/types\";\nimport type {\n  AnyEdgeType,\n  NodeId,\n  NodeType,\n  TemporalMode,\n} from \"../core/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport type { RecursiveCyclePolicy } from \"../query/ast\";\nimport {\n  type OneStatementBatchItem,\n  registerOneStatementSharing,\n} from \"../query/builder/one-statement-sharing\";\nimport type { ExecutableOneStatementRead } from \"../query/builder/types\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../query/compiler/recursive\";\nimport {\n  DEFAULT_SQL_SCHEMA,\n  type RecordedReadBinding,\n  recordedReadSchemaFor,\n  type SqlSchema,\n} from \"../query/compiler/schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { compileTypedJsonExtract } from \"../query/compiler/typed-json-extract\";\nimport { quoteIdentifier } from \"../query/compiler/utils\";\nimport type { DialectAdapter } from \"../query/dialect/types\";\nimport { decodeSelectedValue } from \"../query/execution/value-decoder\";\nimport { jsonPointer } from \"../query/json-pointer\";\nimport {\n  createSchemaIntrospector,\n  type FieldTypeInfo,\n  type SchemaIntrospector,\n} from \"../query/schema-introspector\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, markForceCustomPlan } from \"../query/sql-intent\";\nimport { fnv1aBase36 } from \"../utils/hash\";\nimport { truncateToBytes } from \"../utils/identifier\";\nimport { hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { type EdgeReadWindow, validateEdgeReadBounds } from \"./neighbors\";\nimport { buildReachableCte, buildWindowedEdgesCte } from \"./recursive-cte\";\nimport { validateProjectionField } from \"./reserved-keys\";\nimport {\n  type EdgeRow,\n  type NodeRow,\n  rowToEdge,\n  rowToEdgeMeta,\n  rowToNode,\n  rowToNodeMeta,\n} from \"./row-mappers\";\nimport type { Edge, EdgeMeta, Node, NodeMeta } from \"./types\";\n\n// ============================================================\n// Constants\n// ============================================================\n\nconst DEFAULT_SUBGRAPH_MAX_DEPTH = 10;\n\n/**\n * Generates a short, deterministic column alias safe for PostgreSQL.\n *\n * Format: `sg_{n|e}_{truncatedKind}_{hash}`\n * The hash is computed from the full `kind + field` to prevent collisions\n * when truncation would make two different identifiers identical.\n *\n * PostgreSQL truncates identifiers at 63 *bytes*, not characters.\n * The kind portion is truncated by byte length to stay under the limit\n * even with multibyte characters.\n */\nfunction projectionAlias(\n  entityPrefix: KindEntity,\n  kind: string,\n  field: string,\n): string {\n  const prefix = entityPrefix === \"node\" ? \"sg_n\" : \"sg_e\";\n  const hash = fnv1aBase36(`${kind}\\0${field}`);\n  // prefix + \"_\" + kind_trunc + \"_\" + hash must fit in 63 bytes.\n  // prefix and hash are ASCII, so byte length === string length.\n  const fixedBytes = prefix.length + 1 + 1 + hash.length;\n  const maxKindBytes = MAX_PG_IDENTIFIER_LENGTH - fixedBytes;\n  const truncatedKind = truncateToBytes(kind, maxKindBytes);\n  return `${prefix}_${truncatedKind}_${hash}`;\n}\n\n/**\n * Normalizes a JSON column value to a string.\n * PostgreSQL JSONB columns return parsed objects; SQLite returns strings.\n */\nfunction normalizeProps(value: unknown): string {\n  return typeof value === \"string\" ? value : JSON.stringify(value ?? {});\n}\n\n// ============================================================\n// Type Utilities\n// ============================================================\n\n/**\n * Discriminated union of all Node runtime types in a graph.\n *\n * Unlike `AllNodeTypes<G>` which gives the union of *type definitions*,\n * `AnyNode<G>` gives the union of *runtime node instances*.\n */\nexport type AnyNode<G extends GraphDef> = {\n  [K in NodeKinds<G>]: Node<G[\"nodes\"][K][\"type\"]>;\n}[NodeKinds<G>];\n\n/**\n * Discriminated union of all Edge runtime types in a graph.\n */\nexport type AnyEdge<G extends GraphDef> = {\n  [K in EdgeKinds<G>]: Edge<G[\"edges\"][K][\"type\"]>;\n}[EdgeKinds<G>];\n\n/**\n * Discriminated union of Node runtime types narrowed to a subset of kinds.\n */\nexport type SubsetNode<G extends GraphDef, K extends NodeKinds<G>> = {\n  [Kind in K]: Node<G[\"nodes\"][Kind][\"type\"]>;\n}[K];\n\n/**\n * Discriminated union of Edge runtime types narrowed to a subset of kinds.\n */\nexport type SubsetEdge<G extends GraphDef, K extends EdgeKinds<G>> = {\n  [Kind in K]: Edge<G[\"edges\"][Kind][\"type\"]>;\n}[K];\n\ntype EmptyShape = Readonly<Record<never, never>>;\n\ntype NodeProjectionPropertyKey<N extends NodeType> = Exclude<\n  keyof Node<N>,\n  \"id\" | \"kind\" | \"meta\"\n> &\n  string;\n\ntype EdgeProjectionPropertyKey<E extends AnyEdgeType> = Exclude<\n  keyof Edge<E>,\n  \"id\" | \"kind\" | \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\" | \"meta\"\n> &\n  string;\n\ntype SubgraphNodeProjectionField<N extends NodeType = NodeType> =\n  NodeProjectionPropertyKey<N> | \"meta\";\n\ntype SubgraphEdgeProjectionField<E extends AnyEdgeType = AnyEdgeType> =\n  EdgeProjectionPropertyKey<E> | \"meta\";\n\ntype SubgraphNodeProjectionMap<\n  G extends GraphDef,\n  NK extends NodeKinds<G> = NodeKinds<G>,\n> = Readonly<{\n  [K in NodeKinds<G>]?: K extends NK ?\n    readonly SubgraphNodeProjectionField<G[\"nodes\"][K][\"type\"]>[]\n  : never;\n}>;\n\ntype SubgraphEdgeProjectionMap<\n  G extends GraphDef,\n  EK extends EdgeKinds<G> = EdgeKinds<G>,\n> = Readonly<{\n  [K in EdgeKinds<G>]?: K extends EK ?\n    readonly SubgraphEdgeProjectionField<G[\"edges\"][K][\"type\"]>[]\n  : never;\n}>;\n\nexport type SubgraphProject<\n  G extends GraphDef,\n  NK extends NodeKinds<G> = NodeKinds<G>,\n  EK extends EdgeKinds<G> = EdgeKinds<G>,\n> = Readonly<{\n  /**\n   * Node fields to keep per kind.\n   *\n   * Projected nodes always retain `kind` and `id`.\n   * Use `\"meta\"` to include the full metadata object; omit it to exclude metadata entirely.\n   * Only kinds present in `includeKinds` (or all node kinds when omitted) are valid keys.\n   */\n  nodes?: SubgraphNodeProjectionMap<G, NK>;\n  /**\n   * Edge fields to keep per kind.\n   *\n   * Projected edges always retain `id`, `kind`, `fromKind`, `fromId`,\n   * `toKind`, and `toId`.\n   * Use `\"meta\"` to include the full metadata object; omit it to exclude metadata entirely.\n   * Only edge kinds listed in `edges` are valid keys.\n   */\n  edges?: SubgraphEdgeProjectionMap<G, EK>;\n}>;\n\n/**\n * Identity function that preserves literal types for reusable projection configs.\n *\n * Without this helper, storing a projection in a typed variable widens the\n * field arrays to `string[]`, defeating compile-time narrowing on results.\n *\n * @example\n * ```ts\n * const project = defineSubgraphProject(graph)({\n *   nodes: { Task: [\"title\", \"meta\"] },\n *   edges: { uses_skill: [] },\n * });\n * const result = await store.subgraph(rootId, { edges: [\"uses_skill\"], project });\n * // result.nodes narrowed correctly — task.status is a type error\n * ```\n */\nexport function defineSubgraphProject<G extends GraphDef>(\n  _graph: G,\n): <const P extends SubgraphProject<G>>(project: P) => P {\n  return <const P extends SubgraphProject<G>>(project: P): P => project;\n}\n\ntype HasMeta<Selection extends readonly string[] | undefined> =\n  Selection extends readonly string[] ?\n    \"meta\" extends Selection[number] ?\n      true\n    : false\n  : false;\n\ntype SelectedNodeProps<\n  N extends NodeType,\n  Selection extends readonly string[] | undefined,\n> =\n  Selection extends readonly string[] ?\n    Pick<Node<N>, Extract<Selection[number], NodeProjectionPropertyKey<N>>>\n  : EmptyShape;\n\ntype SelectedEdgeProps<\n  E extends AnyEdgeType,\n  Selection extends readonly string[] | undefined,\n> =\n  Selection extends readonly string[] ?\n    Pick<Edge<E>, Extract<Selection[number], EdgeProjectionPropertyKey<E>>>\n  : EmptyShape;\n\ntype ProjectedNodeResult<\n  N extends NodeType,\n  Selection extends readonly string[] | undefined,\n> = Readonly<Pick<Node<N>, \"id\" | \"kind\">> &\n  Readonly<SelectedNodeProps<N, Selection>> &\n  (HasMeta<Selection> extends true ? Readonly<{ meta: NodeMeta }> : EmptyShape);\n\ntype ProjectedEdgeResult<\n  E extends AnyEdgeType,\n  Selection extends readonly string[] | undefined,\n> = Readonly<\n  Pick<Edge<E>, \"id\" | \"kind\" | \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\">\n> &\n  Readonly<SelectedEdgeProps<E, Selection>> &\n  (HasMeta<Selection> extends true ? Readonly<{ meta: EdgeMeta }> : EmptyShape);\n\ntype ProjectionSelection<\n  P,\n  Key extends \"nodes\" | \"edges\",\n  Kind extends string,\n> =\n  // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style -- mapped type needed for conditional inference on Key\n  P extends Readonly<{ [K in Key]?: infer Map }> ?\n    Map extends Readonly<Record<string, readonly string[] | undefined>> ?\n      Kind extends keyof Map ?\n        Map[Kind]\n      : undefined\n    : undefined\n  : undefined;\n\ntype SubgraphNodeResultForKind<\n  G extends GraphDef,\n  Kind extends NodeKinds<G>,\n  P,\n> =\n  ProjectionSelection<P, \"nodes\", Kind> extends readonly string[] ?\n    ProjectedNodeResult<\n      G[\"nodes\"][Kind][\"type\"],\n      ProjectionSelection<P, \"nodes\", Kind>\n    >\n  : Node<G[\"nodes\"][Kind][\"type\"]>;\n\ntype SubgraphEdgeResultForKind<\n  G extends GraphDef,\n  Kind extends EdgeKinds<G>,\n  P,\n> =\n  ProjectionSelection<P, \"edges\", Kind> extends readonly string[] ?\n    ProjectedEdgeResult<\n      G[\"edges\"][Kind][\"type\"],\n      ProjectionSelection<P, \"edges\", Kind>\n    >\n  : Edge<G[\"edges\"][Kind][\"type\"]>;\n\n// ============================================================\n// Options & Result Types\n// ============================================================\n\nexport type SubgraphOptions<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Readonly<{\n  /** Edge kinds to follow during traversal. Edges not listed are not traversed. */\n  edges: readonly EK[];\n  /** Maximum traversal depth from root (default: 10). */\n  maxDepth?: number;\n  /**\n   * Node kinds to include in the result. Nodes of other kinds are still\n   * traversed through but omitted from the output. When omitted, all\n   * reachable node kinds are included.\n   */\n  includeKinds?: readonly NK[];\n  /** Exclude the root node from the result (default: false). */\n  excludeRoot?: boolean;\n  /**\n   * Edge direction policy (default: \"out\").\n   * - \"out\": follow edges in their defined direction only\n   * - \"both\": follow edges in both directions (undirected traversal)\n   */\n  direction?: \"out\" | \"both\";\n  /** Cycle policy — reuse RecursiveCyclePolicy (default: \"prevent\"). */\n  cyclePolicy?: RecursiveCyclePolicy;\n  /**\n   * Temporal mode applied to both nodes and edges along the traversal and in\n   * the hydrated result. Defaults to `graph.defaults.temporalMode`.\n   */\n  temporalMode?: TemporalMode;\n  /** ISO-8601 timestamp used when `temporalMode === \"asOf\"`. */\n  asOf?: string;\n  /** @internal Recorded coordinates are supplied by StoreView only. */\n  recordedAsOf?: never;\n  /**\n   * Optional field-level projection per node/edge kind.\n   *\n   * Projected nodes keep `kind` and `id`; projected edges keep their structural\n   * endpoint fields. Kinds omitted from `project` remain fully hydrated.\n   * Projection applies to every returned entity, including the root node.\n   *\n   * Only kinds present in `includeKinds` (nodes) or `edges` (edges) are valid\n   * projection keys. Specifying a kind outside those sets is a compile-time error.\n   */\n  project?: P;\n  /**\n   * Per-edge-kind windows applied while traversing and hydrating. Each limit\n   * is partitioned by the current endpoint, so append-only edge histories can\n   * contribute only their newest N targets at every hop.\n   */\n  edgeWindows?: Readonly<Partial<Record<EK, EdgeReadWindow>>>;\n}>;\n\n/**\n * Subgraph options as seen by the internal executor: identical to the public\n * {@link SubgraphOptions} except the recorded/system-time pin is a branded\n * instant the StoreView seam supplies. The public surface keeps\n * `recordedAsOf?: never`;\n * recorded reads reach the executor only through `store.subgraphAtCoordinate`.\n */\nexport type InternalSubgraphOptions<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Omit<SubgraphOptions<G, EK, NK, P>, \"recordedAsOf\"> &\n  Readonly<{\n    recordedAsOf?: RecordedInstant;\n  }>;\n\n/**\n * Union of all node result types in a subgraph, respecting projection.\n */\nexport type SubgraphNodeResult<\n  G extends GraphDef,\n  NK extends NodeKinds<G> = NodeKinds<G>,\n  P = undefined,\n> = {\n  [Kind in NK]: SubgraphNodeResultForKind<G, Kind, P>;\n}[NK];\n\n/**\n * Union of all edge result types in a subgraph, respecting projection.\n */\nexport type SubgraphEdgeResult<\n  G extends GraphDef,\n  EK extends EdgeKinds<G> = EdgeKinds<G>,\n  P = undefined,\n> = {\n  [Kind in EK]: SubgraphEdgeResultForKind<G, Kind, P>;\n}[EK];\n\nexport type SubgraphResult<\n  G extends GraphDef,\n  NK extends NodeKinds<G> = NodeKinds<G>,\n  EK extends EdgeKinds<G> = EdgeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Readonly<{\n  /** The root node, or undefined if the root was not found or excluded. */\n  root: SubgraphNodeResult<G, NK, P> | undefined;\n  nodes: ReadonlyMap<string, SubgraphNodeResult<G, NK, P>>;\n  /** Forward adjacency: fromId → edgeKind → edges to targets. */\n  adjacency: ReadonlyMap<\n    string,\n    ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK, P>[]>\n  >;\n  /** Reverse adjacency: toId → edgeKind → edges from sources. */\n  reverseAdjacency: ReadonlyMap<\n    string,\n    ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK, P>[]>\n  >;\n}>;\n\n// ============================================================\n// Execution Context\n// ============================================================\n\ntype SubgraphContext = Readonly<{\n  graphId: string;\n  rootId: string;\n  edgeKinds: readonly string[];\n  maxDepth: number;\n  includeKinds: readonly string[] | undefined;\n  excludeRoot: boolean;\n  direction: \"out\" | \"both\";\n  cyclePolicy: RecursiveCyclePolicy;\n  temporalMode: TemporalMode;\n  currentTimestamp: SqlFragment;\n  asOf: string | undefined;\n  recordedAsOf: RecordedInstant | undefined;\n  dialect: DialectAdapter;\n  schema: SqlSchema;\n  recordedReadBinding: RecordedReadBinding | undefined;\n  backend: GraphBackend;\n  edgeWindows: Readonly<Record<string, EdgeReadWindow | undefined>> | undefined;\n}>;\n\ntype SubgraphNodeFetchRow = Readonly<\n  Omit<NodeRow, \"props\"> & { props: unknown } & Record<string, unknown>\n>;\n\ntype SubgraphEdgeFetchRow = Readonly<\n  Omit<EdgeRow, \"props\"> & { props: unknown } & Record<string, unknown>\n>;\n\ntype ProjectionPropertyFieldPlan = Readonly<{\n  field: string;\n  outputName: string;\n  typeInfo: FieldTypeInfo | undefined;\n}>;\n\ntype KindProjectionPlan = Readonly<{\n  includeMeta: boolean;\n  propertyFields: readonly ProjectionPropertyFieldPlan[];\n}>;\n\ntype ProjectionPlan = Readonly<{\n  fullKinds: readonly string[];\n  projectedKinds: ReadonlyMap<string, KindProjectionPlan>;\n}>;\n\ntype SubgraphExecutionParams<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined,\n> = Readonly<{\n  graph: G;\n  graphId: string;\n  rootId: NodeId<AllNodeTypes<G>>;\n  backend: GraphBackend;\n  dialect: DialectAdapter;\n  schema: SqlSchema | undefined;\n  recordedReadBinding: RecordedReadBinding | undefined;\n  options: InternalSubgraphOptions<G, EK, NK, P>;\n}>;\n\ntype SubgraphPlan = Readonly<{\n  baseSchema: SqlSchema;\n  ctx: SubgraphContext;\n  reachableCte: SqlFragment;\n  includedIdsCte: SqlFragment;\n  nodeProjectionPlan: ProjectionPlan;\n  edgeProjectionPlan: ProjectionPlan;\n}>;\n\ntype SubgraphSurface = \"subgraph\" | \"batchOnce.subgraph\";\n\nfunction buildSubgraphPlan<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined,\n>(\n  params: SubgraphExecutionParams<G, EK, NK, P>,\n  surface: SubgraphSurface,\n): SubgraphPlan {\n  const { options } = params;\n  validateSubgraphTraversalOptions(options);\n  const { valid: coordinate } = resolveReadCoordinate(\n    options.temporalMode ?? params.graph.defaults.temporalMode,\n    options.asOf,\n  );\n  validateEdgeWindows(options.edgeWindows, options.edges);\n  const baseSchema = params.schema ?? DEFAULT_SQL_SCHEMA;\n  const ctx: SubgraphContext = {\n    graphId: params.graphId,\n    rootId: params.rootId,\n    edgeKinds: [...options.edges],\n    maxDepth: options.maxDepth ?? DEFAULT_SUBGRAPH_MAX_DEPTH,\n    includeKinds:\n      options.includeKinds === undefined ?\n        undefined\n      : [...options.includeKinds],\n    excludeRoot: options.excludeRoot ?? false,\n    direction: options.direction ?? \"out\",\n    cyclePolicy: options.cyclePolicy ?? \"prevent\",\n    temporalMode: coordinate.mode,\n    currentTimestamp: currentReadInstant(),\n    asOf: coordinate.asOf,\n    // Recorded coordinates reach here only through the StoreView seam. The\n    // public API rejects them before either execution strategy is selected.\n    recordedAsOf: options.recordedAsOf,\n    dialect: params.dialect,\n    schema: recordedReadSchemaFor(\n      baseSchema,\n      options.recordedAsOf,\n      params.recordedReadBinding,\n      surface === \"subgraph\" ? \"recorded-subgraph\" : \"recorded-subgraph-query\",\n    ),\n    recordedReadBinding: params.recordedReadBinding,\n    backend: params.backend,\n    edgeWindows:\n      options.edgeWindows === undefined ?\n        undefined\n      : structuredClone(options.edgeWindows),\n  };\n  const introspector = getSubgraphSchemaIntrospector(params.graph);\n  const nodeProjectionPlan = buildProjectionPlan(\n    getIncludedNodeKinds(params.graph, options.includeKinds),\n    options.project?.nodes,\n    (kind, field) => introspector.getFieldTypeInfo(kind, field),\n    \"node\",\n  );\n  const edgeProjectionPlan = buildProjectionPlan(\n    dedupeStrings(options.edges),\n    options.project?.edges,\n    (kind, field) => introspector.getEdgeFieldTypeInfo(kind, field),\n    \"edge\",\n  );\n  const reachableCte = buildSubgraphReachableCte(ctx, baseSchema, surface);\n\n  return {\n    baseSchema,\n    ctx,\n    reachableCte,\n    includedIdsCte: buildIncludedIdsCte(ctx),\n    nodeProjectionPlan,\n    edgeProjectionPlan,\n  };\n}\n\nfunction buildSubgraphReachableCte(\n  ctx: SubgraphContext,\n  baseSchema: SqlSchema,\n  surface: SubgraphSurface,\n  sourceIds?: readonly string[],\n): SqlFragment {\n  return buildReachableCte({\n    graphId: ctx.graphId,\n    ...(sourceIds === undefined ? { sourceId: ctx.rootId } : { sourceIds }),\n    edgeKinds: ctx.edgeKinds,\n    maxHops: ctx.maxDepth,\n    direction: ctx.direction,\n    cyclePolicy: ctx.cyclePolicy,\n    includePath: false,\n    temporalMode: ctx.temporalMode,\n    currentTimestamp: ctx.currentTimestamp,\n    ...(ctx.asOf !== undefined && { asOf: ctx.asOf }),\n    ...(ctx.recordedAsOf !== undefined && { recordedAsOf: ctx.recordedAsOf }),\n    dialect: ctx.dialect,\n    // The recursive compiler derives the recorded relation from the pin.\n    schema: baseSchema,\n    ...(ctx.recordedReadBinding === undefined ?\n      {}\n    : { recordedReadBinding: ctx.recordedReadBinding }),\n    recursiveTraversal: resolveRecursiveTraversal(ctx.backend.capabilities),\n    operation: surface,\n    ...(ctx.edgeWindows === undefined ? {} : { edgeWindows: ctx.edgeWindows }),\n  });\n}\n\n// ============================================================\n// Public API\n// ============================================================\n\nexport async function executeSubgraph<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n>(\n  params: SubgraphExecutionParams<G, EK, NK, P>,\n): Promise<SubgraphResult<G, NK, EK, P>> {\n  const {\n    ctx,\n    reachableCte,\n    includedIdsCte,\n    nodeProjectionPlan,\n    edgeProjectionPlan,\n  } = buildSubgraphPlan(params, \"subgraph\");\n\n  // The node and edge fetches both need the traversal closure. Embedding\n  // the recursive CTE in each statement runs the BFS twice; on Postgres\n  // the closure ids are fetched ONCE and passed to both fetches as a\n  // single text[] parameter, filtered via a hashed semi-join\n  // (EXISTS over unnest — measured faster than `= ANY` on the same\n  // closure). SQLite keeps the embedded form: its in-process traversal\n  // is cheap, an id list would bind one parameter per id (bind-budget\n  // pressure), and per-count SQL texts would churn the prepared-statement\n  // cache.\n  let membership: SubgraphMembership;\n  const membershipStrategy =\n    ctx.dialect.capabilities.subgraphMembershipStrategy;\n  switch (membershipStrategy) {\n    case \"materialized-ids\": {\n      const includedIds = await fetchIncludedIds(\n        ctx,\n        reachableCte,\n        includedIdsCte,\n      );\n      const idsArray = textArrayParam(includedIds);\n      membership = {\n        prefix: sql``,\n        idFilter: (column) =>\n          sql`EXISTS (SELECT 1 FROM unnest(${idsArray}) AS tg_included(id) WHERE tg_included.id = ${column})`,\n        parameterDependentPlan: true,\n      };\n      break;\n    }\n    case \"inline-cte\": {\n      membership = {\n        prefix: sql`${reachableCte}${includedIdsCte} `,\n        // `column IN (subquery)` evaluates via a transient index — optimal\n        // as-is. (The materialized-ids strategy takes the parameterized\n        // array form above instead.)\n        idFilter: (column) => sql`${column} IN (SELECT id FROM included_ids)`,\n        parameterDependentPlan: false,\n      };\n      break;\n    }\n    default: {\n      membershipStrategy satisfies never;\n      throw new Error(\n        `Unsupported subgraph membership strategy: ${String(membershipStrategy)}`,\n      );\n    }\n  }\n\n  const [nodeRows, edgeRows] = await Promise.all([\n    fetchSubgraphNodes(ctx, membership, nodeProjectionPlan),\n    fetchSubgraphEdges(ctx, membership, edgeProjectionPlan),\n  ]);\n\n  return assembleSubgraphResult<G, NK, EK, P>(\n    ctx.rootId,\n    nodeRows.map((row) => mapSubgraphNodeRow(row, nodeProjectionPlan)),\n    edgeRows.map((row) => mapSubgraphEdgeRow(row, edgeProjectionPlan)),\n  );\n}\n\n/** A subgraph read that can execute alone or in `store.batchOnce()`. */\nexport type SubgraphRead<\n  G extends GraphDef,\n  NK extends NodeKinds<G>,\n  EK extends EdgeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = ExecutableOneStatementRead<SubgraphResult<G, NK, EK, P>>;\n\n/** Builds the one-statement form used by composable set-oriented reads. */\nexport function createSubgraphRead<\n  G extends GraphDef,\n  EK extends EdgeKinds<G>,\n  NK extends NodeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n>(params: SubgraphExecutionParams<G, EK, NK, P>): SubgraphRead<G, NK, EK, P> {\n  const plan = buildSubgraphPlan(params, \"batchOnce.subgraph\");\n  const {\n    ctx,\n    reachableCte,\n    includedIdsCte,\n    nodeProjectionPlan: nodePlan,\n    edgeProjectionPlan: edgePlan,\n  } = plan;\n  const query = buildOneStatementSubgraphQuery(\n    ctx,\n    reachableCte,\n    includedIdsCte,\n    nodePlan,\n    edgePlan,\n  );\n  function mapRows(\n    rows: readonly Record<string, unknown>[],\n  ): SubgraphResult<G, NK, EK, P> {\n    return mapOneStatementSubgraphRows(\n      ctx.rootId,\n      rows as readonly OneStatementSubgraphRow[],\n      nodePlan,\n      edgePlan,\n    );\n  }\n  return {\n    execute: async () =>\n      mapRows(\n        await params.backend.execute<OneStatementSubgraphRow>(\n          asCompiledRowsSql(query),\n        ),\n      ),\n    compileOneStatementBatchItem: () => {\n      const item: OneStatementBatchItem<SubgraphResult<G, NK, EK, P>> = {\n        query: asCompiledRowsSql(query),\n        provenance: {\n          graphId: params.graphId,\n          executionTarget: backendDerivationRoot(params.backend),\n        },\n        outputNames: oneStatementSubgraphOutputNames(nodePlan, edgePlan),\n        orderBy: [],\n        mapRows,\n      };\n      sharedSubgraphPlans.set(item, plan);\n      registerOneStatementSharing(item, {\n        owner: params.graph,\n        key: subgraphSharingKey(plan),\n        combine: combineSubgraphBatchItems,\n      });\n      return item;\n    },\n  };\n}\n\nconst sharedSubgraphPlans = new WeakMap<OneStatementBatchItem, SubgraphPlan>();\nconst SHARED_MEMBERSHIPS_COLUMN = \"typegraph_shared_memberships\";\n\nfunction projectionSharingKey(plan: ProjectionPlan): unknown {\n  return {\n    fullKinds: plan.fullKinds,\n    projectedKinds: [...plan.projectedKinds],\n  };\n}\n\nfunction subgraphSharingKey(plan: SubgraphPlan): string {\n  const { ctx } = plan;\n  return JSON.stringify({\n    graphId: ctx.graphId,\n    schema: ctx.schema,\n    edgeKinds: ctx.edgeKinds,\n    includeKinds: ctx.includeKinds,\n    excludeRoot: ctx.excludeRoot,\n    maxDepth: ctx.maxDepth,\n    direction: ctx.direction,\n    cyclePolicy: ctx.cyclePolicy,\n    temporalMode: ctx.temporalMode,\n    asOf: ctx.asOf,\n    recordedAsOf: ctx.recordedAsOf,\n    currentTimestamp: ctx.currentTimestamp.chunks,\n    edgeWindows: ctx.edgeWindows,\n    nodes: projectionSharingKey(plan.nodeProjectionPlan),\n    edges: projectionSharingKey(plan.edgeProjectionPlan),\n  });\n}\n\nfunction sharedEntityKey(row: Readonly<Record<string, unknown>>): string {\n  return JSON.stringify([row[\"typegraph_entity\"], row[\"kind\"], row[\"id\"]]);\n}\n\nfunction combineSubgraphBatchItems(\n  items: readonly OneStatementBatchItem[],\n): OneStatementBatchItem<readonly unknown[]> {\n  const first = requireDefined(items[0]);\n  const plans = items.map((item) =>\n    requireDefined(sharedSubgraphPlans.get(item)),\n  );\n  const {\n    ctx,\n    baseSchema,\n    nodeProjectionPlan: nodePlan,\n    edgeProjectionPlan: edgePlan,\n  } = requireDefined(plans[0]);\n  const roots = plans.map((plan) => plan.ctx.rootId);\n  const reachable = buildSubgraphReachableCte(\n    ctx,\n    baseSchema,\n    \"batchOnce.subgraph\",\n    dedupeStrings(roots),\n  );\n  const filters: SqlFragment[] = [];\n  if (ctx.includeKinds !== undefined && ctx.includeKinds.length > 0)\n    filters.push(compileKindFilter(sql.raw(\"kind\"), ctx.includeKinds));\n  if (ctx.excludeRoot) filters.push(sql`id != origin_id`);\n  const included = sql`, included_ids AS (SELECT DISTINCT origin_id, id FROM reachable ${filters.length === 0 ? sql.empty() : sql`WHERE ${sql.join(filters, sql` AND `)}`})`;\n  const requests = roots.map((root, index) => sql`(${index}, ${root})`);\n  const hydration = buildOneStatementSubgraphQuery(\n    ctx,\n    sql.empty(),\n    sql.empty(),\n    nodePlan,\n    edgePlan,\n    true,\n  );\n  const columns = first.outputNames;\n  const membershipPayload = ctx.dialect.orderedRowsJsonArray(\n    \"typegraph_shared_ordered_membership\",\n    [\"request_id\", \"typegraph_entity\", \"kind\", \"id\"],\n    \"typegraph_shared_ordinal\",\n  );\n  const hydratedColumns = columns.map(\n    (column) => sql`h.${sql.identifier(column)}`,\n  );\n  const membershipColumns = columns.map((column) =>\n    column === \"typegraph_entity\" ? sql`'membership'` : sql`NULL`,\n  );\n  const query = asCompiledRowsSql(sql`\n    ${reachable}${included},\n        typegraph_shared_requests(request_id, root_id) AS (VALUES ${sql.join(requests, sql`, `)}),\n        typegraph_shared_hydrated AS (${hydration}),\n        typegraph_shared_membership AS (\n          SELECT requests.request_id, h.typegraph_entity, h.kind, h.id\n          FROM typegraph_shared_hydrated h\n          JOIN included_ids included ON h.id = included.id\n          JOIN typegraph_shared_requests requests ON requests.root_id = included.origin_id\n          WHERE h.typegraph_entity = 'node'\n          UNION ALL\n          SELECT requests.request_id, h.typegraph_entity, h.kind, h.id\n          FROM typegraph_shared_hydrated h\n          JOIN included_ids source_membership ON h.from_id = source_membership.id\n          JOIN included_ids target_membership ON h.to_id = target_membership.id AND source_membership.origin_id = target_membership.origin_id\n          JOIN typegraph_shared_requests requests ON requests.root_id = source_membership.origin_id\n          WHERE h.typegraph_entity = 'edge'\n        ),\n        typegraph_shared_ordered_membership AS (\n          SELECT membership.*, request_id AS typegraph_shared_ordinal\n          FROM typegraph_shared_membership membership\n        )\n        SELECT ${sql.join(hydratedColumns, sql`, `)}, NULL AS ${sql.identifier(SHARED_MEMBERSHIPS_COLUMN)}\n        FROM typegraph_shared_hydrated h\n        UNION ALL\n        SELECT ${sql.join(membershipColumns, sql`, `)}, ${membershipPayload}\n  `);\n  return {\n    query,\n    provenance: first.provenance,\n    outputNames: [...columns, SHARED_MEMBERSHIPS_COLUMN],\n    orderBy: [],\n    mapRows: (rows) => mapSharedSubgraphRows(items, rows),\n  };\n}\n\nfunction mapSharedSubgraphRows(\n  items: readonly OneStatementBatchItem[],\n  rows: readonly Record<string, unknown>[],\n): readonly unknown[] {\n  const entities = new Map<string, Record<string, unknown>>();\n  const requestRows: Record<string, unknown>[][] = items.map(() => []);\n  const membershipRows = rows.filter(\n    (row) => row[\"typegraph_entity\"] === \"membership\",\n  );\n  for (const row of rows)\n    if (row[\"typegraph_entity\"] !== \"membership\")\n      entities.set(sharedEntityKey(row), row);\n  if (membershipRows.length !== 1)\n    throw new ConfigurationError(\n      \"Shared subgraph query returned an invalid membership envelope.\",\n    );\n  const encoded = requireDefined(membershipRows[0])[SHARED_MEMBERSHIPS_COLUMN];\n  const memberships: unknown =\n    typeof encoded === \"string\" ? JSON.parse(encoded) : encoded;\n  if (!Array.isArray(memberships))\n    throw new ConfigurationError(\n      \"Shared subgraph query returned invalid membership rows.\",\n    );\n  for (const membership of memberships) {\n    if (typeof membership !== \"object\" || membership === null)\n      throw new ConfigurationError(\n        \"Shared subgraph membership must be an object.\",\n      );\n    const row = membership as Record<string, unknown>;\n    const index = Number(row[\"request_id\"]);\n    if (!Number.isInteger(index) || index < 0 || index >= items.length)\n      throw new ConfigurationError(\n        \"Shared subgraph membership has an invalid request index.\",\n      );\n    const entity = requireDefined(\n      entities.get(sharedEntityKey(row)),\n      \"Shared subgraph membership refers to a missing entity.\",\n    );\n    requireDefined(requestRows[index]).push(entity);\n  }\n  // The envelope reuses hydrated rows; each public result must own nested props.\n  return items.map((item, index) =>\n    item.mapRows(structuredClone(requireDefined(requestRows[index]))),\n  );\n}\n\n// ============================================================\n// Projection Planning\n// ============================================================\n\ntype FieldTypeResolver = (\n  kind: string,\n  field: string,\n) => FieldTypeInfo | undefined;\n\nconst introspectorCache = new WeakMap<GraphDef, SchemaIntrospector>();\n\nfunction getSubgraphSchemaIntrospector<G extends GraphDef>(\n  graph: G,\n): SchemaIntrospector {\n  const cached = introspectorCache.get(graph);\n  if (cached !== undefined) return cached;\n\n  const nodeKinds = new Map(\n    Object.entries(graph.nodes).map(([kind, definition]) => [\n      kind,\n      { schema: definition.type.schema },\n    ]),\n  );\n  const edgeKinds = new Map(\n    Object.entries(graph.edges).map(([kind, definition]) => [\n      kind,\n      { schema: definition.type.schema },\n    ]),\n  );\n\n  const introspector = createSchemaIntrospector(nodeKinds, edgeKinds);\n  introspectorCache.set(graph, introspector);\n  return introspector;\n}\n\nfunction buildProjectionPlan(\n  kinds: readonly string[],\n  projectionMap:\n    Readonly<Record<string, readonly string[] | undefined>> | undefined,\n  resolveFieldType: FieldTypeResolver,\n  entityPrefix: KindEntity,\n): ProjectionPlan {\n  const projectedKinds = new Map<string, KindProjectionPlan>();\n  const fullKinds: string[] = [];\n\n  for (const kind of kinds) {\n    // Own-key read: `projectionMap` is the caller's `project.nodes` /\n    // `project.edges` record and `kind` is a graph kind name, so a kind named\n    // after an `Object.prototype` member (\"toString\") would otherwise read the\n    // inherited function as this kind's field selection instead of \"no\n    // projection declared\".\n    const selection =\n      projectionMap !== undefined && hasOwnKey(projectionMap, kind) ?\n        projectionMap[kind]\n      : undefined;\n    if (selection === undefined) {\n      fullKinds.push(kind);\n      continue;\n    }\n\n    projectedKinds.set(\n      kind,\n      buildKindProjectionPlan(kind, selection, resolveFieldType, entityPrefix),\n    );\n  }\n\n  return { fullKinds, projectedKinds };\n}\n\nfunction buildKindProjectionPlan(\n  kind: string,\n  selection: readonly string[],\n  resolveFieldType: FieldTypeResolver,\n  entityPrefix: KindEntity,\n): KindProjectionPlan {\n  const propertyFields = new Map<string, ProjectionPropertyFieldPlan>();\n  let includeMeta = false;\n\n  for (const field of selection) {\n    if (field === \"meta\") {\n      includeMeta = true;\n      continue;\n    }\n\n    validateProjectionField(field, entityPrefix, kind);\n\n    if (!propertyFields.has(field)) {\n      propertyFields.set(field, {\n        field,\n        outputName: projectionAlias(entityPrefix, kind, field),\n        typeInfo: resolveFieldType(kind, field),\n      });\n    }\n  }\n\n  return {\n    includeMeta,\n    propertyFields: [...propertyFields.values()],\n  };\n}\n\nfunction getIncludedNodeKinds<G extends GraphDef>(\n  graph: G,\n  includeKinds: readonly NodeKinds<G>[] | undefined,\n): readonly string[] {\n  if (includeKinds === undefined || includeKinds.length === 0) {\n    return Object.keys(graph.nodes);\n  }\n\n  return dedupeStrings(includeKinds);\n}\n\nfunction dedupeStrings(values: readonly string[]): readonly string[] {\n  return [...new Set(values)];\n}\n\n// ============================================================\n// SQL Generation\n// ============================================================\n\nfunction buildIncludedIdsCte(ctx: SubgraphContext): SqlFragment {\n  const filters: SqlFragment[] = [];\n\n  if (ctx.includeKinds !== undefined && ctx.includeKinds.length > 0) {\n    filters.push(compileKindFilter(sql.raw(\"kind\"), ctx.includeKinds));\n  }\n\n  if (ctx.excludeRoot) {\n    filters.push(sql`id != ${ctx.rootId}`);\n  }\n\n  const whereClause =\n    filters.length > 0 ? sql` WHERE ${sql.join(filters, sql` AND `)}` : sql``;\n\n  return sql`, included_ids AS (SELECT DISTINCT id FROM reachable${whereClause})`;\n}\n\nfunction buildSubgraphEdgeSource(\n  ctx: SubgraphContext,\n  edgeTemporalFilter: SqlFragment,\n): SqlFragment {\n  const windows = Object.entries(ctx.edgeWindows ?? {}).filter(\n    (entry): entry is [string, EdgeReadWindow] => entry[1] !== undefined,\n  );\n  if (windows.length === 0) return ctx.schema.edgesTable;\n\n  const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), ctx.edgeKinds);\n  const windowedEdges = buildWindowedEdgesCte(\n    ctx.schema.edgesTable,\n    ctx.direction,\n    ctx.edgeKinds.map((kind) => [kind, ctx.edgeWindows?.[kind]]),\n    sql.join(\n      [sql`e.graph_id = ${ctx.graphId}`, edgeKindFilter, edgeTemporalFilter],\n      sql` AND `,\n    ),\n  );\n  const physicalColumns = [\n    \"graph_id\",\n    \"id\",\n    \"kind\",\n    \"from_kind\",\n    \"from_id\",\n    \"to_kind\",\n    \"to_id\",\n    \"props\",\n    \"valid_from\",\n    \"valid_to\",\n    \"created_at\",\n    \"updated_at\",\n    \"deleted_at\",\n  ].map((column) => sql.raw(`windowed_edge.${column}`));\n\n  // Bidirectional windows can surface one physical edge through both\n  // orientations. Deduplicate the typed source rows before projection so\n  // UNION placeholder NULLs retain the opposite arm's database type.\n  return sql`(SELECT DISTINCT ${sql.join(physicalColumns, sql`, `)} FROM (${windowedEdges}) windowed_edge)`;\n}\n\n/**\n * How the node/edge fetches restrict rows to the traversal closure:\n * either a statement prefix re-declaring the recursive CTE with an\n * `included_ids` membership subquery (SQLite), or an empty prefix with a\n * pre-fetched id-array filter (Postgres).\n */\ntype SubgraphMembership = Readonly<{\n  prefix: SqlFragment;\n  idFilter: (column: SqlFragment) => SqlFragment;\n  /**\n   * True in id-array mode: the fetch plans depend on the array\n   * cardinality, so the statements must never fall onto a prepared\n   * generic plan (see markForceCustomPlan).\n   */\n  parameterDependentPlan: boolean;\n}>;\n\n/**\n * Binds a string list as ONE text parameter in Postgres array-literal\n * form, cast to text[]. A single parameter keeps the statement text\n * constant across id counts, and the fetch statements semi-join against\n * `unnest` of the array. (Drizzle would otherwise serialize a JS array\n * param as JSON text.)\n */\nfunction textArrayParam(values: readonly string[]): SqlFragment {\n  const elements = values.map(\n    (value) =>\n      `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', String.raw`\\\"`)}\"`,\n  );\n  return sql`${`{${elements.join(\",\")}}`}::text[]`;\n}\n\n/** Runs the traversal once and returns the closure's node ids. */\nasync function fetchIncludedIds(\n  ctx: SubgraphContext,\n  reachableCte: SqlFragment,\n  includedIdsCte: SqlFragment,\n): Promise<readonly string[]> {\n  const rows = await ctx.backend.execute<{ id: string }>(\n    asCompiledRowsSql(\n      sql`${reachableCte}${includedIdsCte} SELECT id FROM included_ids`,\n    ),\n  );\n  return rows.map((row) => row.id);\n}\n\ntype OneStatementSubgraphRow = SubgraphNodeFetchRow &\n  SubgraphEdgeFetchRow &\n  Readonly<{ typegraph_entity: \"edge\" | \"node\" }>;\n\nfunction projectionOutputNames(plan: ProjectionPlan): readonly string[] {\n  return [...plan.projectedKinds.values()].flatMap((kindPlan) =>\n    kindPlan.propertyFields.map((field) => field.outputName),\n  );\n}\n\nfunction oneStatementSubgraphOutputNames(\n  nodePlan: ProjectionPlan,\n  edgePlan: ProjectionPlan,\n): readonly string[] {\n  return [\n    \"typegraph_entity\",\n    \"id\",\n    \"kind\",\n    \"from_kind\",\n    \"from_id\",\n    \"to_kind\",\n    \"to_id\",\n    \"props\",\n    \"version\",\n    \"valid_from\",\n    \"valid_to\",\n    \"created_at\",\n    \"updated_at\",\n    \"deleted_at\",\n    ...projectionOutputNames(nodePlan),\n    ...projectionOutputNames(edgePlan),\n  ];\n}\n\nfunction nullProjectionColumns(plan: ProjectionPlan): readonly SqlFragment[] {\n  return projectionOutputNames(plan).map(\n    (outputName) => sql`NULL AS ${quoteIdentifier(outputName)}`,\n  );\n}\n\nfunction buildOneStatementSubgraphQuery(\n  ctx: SubgraphContext,\n  reachable: SqlFragment,\n  includedIds: SqlFragment,\n  nodePlan: ProjectionPlan,\n  edgePlan: ProjectionPlan,\n  sharedOrigins = false,\n): SqlFragment {\n  const instant = ctx.currentTimestamp;\n  const nodeTemporal = compileTemporalFilter({\n    mode: ctx.temporalMode,\n    asOf: ctx.asOf,\n    recordedAsOf: ctx.recordedAsOf,\n    tableAlias: \"n\",\n    currentTimestamp: instant,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const edgeTemporal = compileTemporalFilter({\n    mode: ctx.temporalMode,\n    asOf: ctx.asOf,\n    recordedAsOf: ctx.recordedAsOf,\n    tableAlias: \"e\",\n    currentTimestamp: instant,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const nodeColumns: SqlFragment[] = [\n    sql`'node' AS typegraph_entity`,\n    sql`n.id`,\n    sql`n.kind`,\n    sql`NULL AS from_kind`,\n    sql`NULL AS from_id`,\n    sql`NULL AS to_kind`,\n    sql`NULL AS to_id`,\n    buildFullPropsColumn(\"n\", nodePlan),\n    ...buildMetadataColumns(\"n\", nodePlan, [\n      \"version\",\n      \"valid_from\",\n      \"valid_to\",\n      \"created_at\",\n      \"updated_at\",\n      \"deleted_at\",\n    ]),\n    ...buildProjectedPropertyColumns(\"n\", nodePlan, ctx.dialect),\n    ...nullProjectionColumns(edgePlan),\n  ];\n  const edgeColumns: SqlFragment[] = [\n    sql`'edge' AS typegraph_entity`,\n    sql`e.id`,\n    sql`e.kind`,\n    sql`e.from_kind`,\n    sql`e.from_id`,\n    sql`e.to_kind`,\n    sql`e.to_id`,\n    buildFullPropsColumn(\"e\", edgePlan),\n    sql`NULL AS version`,\n    ...buildMetadataColumns(\"e\", edgePlan, [\n      \"valid_from\",\n      \"valid_to\",\n      \"created_at\",\n      \"updated_at\",\n      \"deleted_at\",\n    ]),\n    ...nullProjectionColumns(nodePlan),\n    ...buildProjectedPropertyColumns(\"e\", edgePlan, ctx.dialect),\n  ];\n  const edgeSource = buildSubgraphEdgeSource(ctx, edgeTemporal);\n  const edgeMembership =\n    sharedOrigins ?\n      sql`EXISTS (SELECT 1 FROM included_ids source_membership JOIN included_ids target_membership ON source_membership.origin_id = target_membership.origin_id WHERE source_membership.id = e.from_id AND target_membership.id = e.to_id)`\n    : sql`e.from_id IN (SELECT id FROM included_ids) AND e.to_id IN (SELECT id FROM included_ids)`;\n  return sql`${reachable}${includedIds} SELECT ${sql.join(nodeColumns, sql`, `)} FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND ${nodeTemporal} AND n.id IN (SELECT id FROM included_ids) UNION ALL SELECT ${sql.join(edgeColumns, sql`, `)} FROM ${edgeSource} e WHERE e.graph_id = ${ctx.graphId} AND ${compileKindFilter(sql.raw(\"e.kind\"), ctx.edgeKinds)} AND ${edgeTemporal} AND ${edgeMembership}`;\n}\n\nfunction mapOneStatementSubgraphRows<\n  G extends GraphDef,\n  NK extends NodeKinds<G>,\n  EK extends EdgeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined,\n>(\n  rootId: string,\n  rows: readonly OneStatementSubgraphRow[],\n  nodePlan: ProjectionPlan,\n  edgePlan: ProjectionPlan,\n): SubgraphResult<G, NK, EK, P> {\n  const nodes: Node[] = [];\n  const edges: Edge[] = [];\n  for (const row of rows) {\n    if (row.typegraph_entity === \"node\") {\n      nodes.push(mapSubgraphNodeRow(row, nodePlan));\n      continue;\n    }\n    edges.push(mapSubgraphEdgeRow(row, edgePlan));\n  }\n  return assembleSubgraphResult<G, NK, EK, P>(rootId, nodes, edges);\n}\n\nfunction assembleSubgraphResult<\n  G extends GraphDef,\n  NK extends NodeKinds<G>,\n  EK extends EdgeKinds<G>,\n  P extends SubgraphProject<G, NK, EK> | undefined,\n>(\n  rootId: string,\n  nodeValues: readonly Node[],\n  edgeValues: readonly Edge[],\n): SubgraphResult<G, NK, EK, P> {\n  const nodes = new Map<string, Node>();\n  for (const node of nodeValues) nodes.set(node.id, node);\n\n  const adjacency = new Map<string, Map<string, Edge[]>>();\n  const reverseAdjacency = new Map<string, Map<string, Edge[]>>();\n  for (const edge of edgeValues) {\n    insertAdjacencyEntry(adjacency, edge.fromId, edge.kind, edge);\n    insertAdjacencyEntry(reverseAdjacency, edge.toId, edge.kind, edge);\n  }\n  return {\n    root: nodes.get(rootId),\n    nodes,\n    adjacency,\n    reverseAdjacency,\n  } as unknown as SubgraphResult<G, NK, EK, P>;\n}\n\nasync function fetchSubgraphNodes(\n  ctx: SubgraphContext,\n  membership: SubgraphMembership,\n  projectionPlan: ProjectionPlan,\n): Promise<SubgraphNodeFetchRow[]> {\n  const nodeTemporalFilter = compileTemporalFilter({\n    mode: ctx.temporalMode,\n    asOf: ctx.asOf,\n    recordedAsOf: ctx.recordedAsOf,\n    tableAlias: \"n\",\n    currentTimestamp: ctx.currentTimestamp,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const columns: SqlFragment[] = [\n    sql`n.kind`,\n    sql`n.id`,\n    buildFullPropsColumn(\"n\", projectionPlan),\n    ...buildMetadataColumns(\"n\", projectionPlan, [\n      \"version\",\n      \"valid_from\",\n      \"valid_to\",\n      \"created_at\",\n      \"updated_at\",\n      \"deleted_at\",\n    ]),\n    ...buildProjectedPropertyColumns(\"n\", projectionPlan, ctx.dialect),\n  ];\n\n  const query = sql`${membership.prefix}SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND ${nodeTemporalFilter} AND ${membership.idFilter(sql.raw(\"n.id\"))}`;\n  if (membership.parameterDependentPlan) markForceCustomPlan(query);\n\n  return ctx.backend.execute<SubgraphNodeFetchRow>(\n    asCompiledRowsSql(query),\n  ) as Promise<SubgraphNodeFetchRow[]>;\n}\n\nasync function fetchSubgraphEdges(\n  ctx: SubgraphContext,\n  membership: SubgraphMembership,\n  projectionPlan: ProjectionPlan,\n): Promise<SubgraphEdgeFetchRow[]> {\n  const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), ctx.edgeKinds);\n  const edgeTemporalFilter = compileTemporalFilter({\n    mode: ctx.temporalMode,\n    asOf: ctx.asOf,\n    recordedAsOf: ctx.recordedAsOf,\n    tableAlias: \"e\",\n    currentTimestamp: ctx.currentTimestamp,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const columns: SqlFragment[] = [\n    sql`e.id`,\n    sql`e.kind`,\n    sql`e.from_kind`,\n    sql`e.from_id`,\n    sql`e.to_kind`,\n    sql`e.to_id`,\n    buildFullPropsColumn(\"e\", projectionPlan),\n    ...buildMetadataColumns(\"e\", projectionPlan, [\n      \"valid_from\",\n      \"valid_to\",\n      \"created_at\",\n      \"updated_at\",\n      \"deleted_at\",\n    ]),\n    ...buildProjectedPropertyColumns(\"e\", projectionPlan, ctx.dialect),\n  ];\n\n  const edgesSource = buildSubgraphEdgeSource(ctx, edgeTemporalFilter);\n  const query = sql`${membership.prefix}SELECT ${sql.join(columns, sql`, `)} FROM ${edgesSource} e WHERE e.graph_id = ${ctx.graphId} AND ${edgeKindFilter} AND ${edgeTemporalFilter} AND ${membership.idFilter(sql.raw(\"e.from_id\"))} AND ${membership.idFilter(sql.raw(\"e.to_id\"))}`;\n  if (membership.parameterDependentPlan) markForceCustomPlan(query);\n\n  return ctx.backend.execute<SubgraphEdgeFetchRow>(\n    asCompiledRowsSql(query),\n  ) as Promise<SubgraphEdgeFetchRow[]>;\n}\n\nfunction validateEdgeWindows(\n  windows: Readonly<Record<string, EdgeReadWindow | undefined>> | undefined,\n  selectedEdgeKinds: readonly string[],\n): void {\n  for (const [kind, window] of Object.entries(windows ?? {})) {\n    if (!selectedEdgeKinds.includes(kind)) {\n      throw new ValidationError(\n        \"Subgraph edge windows must name a traversed edge kind\",\n        {\n          issues: [\n            {\n              path: `edgeWindows.${kind}`,\n              message: \"Edge kind is not present in options.edges\",\n            },\n          ],\n        },\n      );\n    }\n    if (window !== undefined) {\n      validateEdgeReadBounds(window, `edgeWindows.${kind}`);\n    }\n  }\n}\n\nfunction validateSubgraphTraversalOptions(\n  options: Readonly<{\n    maxDepth?: number;\n    direction?: unknown;\n    cyclePolicy?: unknown;\n  }>,\n): void {\n  const maxDepth = options.maxDepth;\n  if (\n    maxDepth !== undefined &&\n    (!Number.isFinite(maxDepth) ||\n      !Number.isInteger(maxDepth) ||\n      maxDepth < 0 ||\n      maxDepth > MAX_EXPLICIT_RECURSIVE_DEPTH)\n  ) {\n    throw new ValidationError(\n      `Subgraph maxDepth must be an integer from 0 through ${MAX_EXPLICIT_RECURSIVE_DEPTH}`,\n      {\n        issues: [\n          {\n            path: \"maxDepth\",\n            message: `Received ${String(maxDepth)}`,\n            code: \"invalid_value\",\n          },\n        ],\n      },\n    );\n  }\n  if (\n    options.direction !== undefined &&\n    options.direction !== \"out\" &&\n    options.direction !== \"both\"\n  ) {\n    throw new ValidationError('Subgraph direction must be \"out\" or \"both\"', {\n      issues: [\n        {\n          path: \"direction\",\n          message: \"Received an unsupported direction\",\n          code: \"invalid_value\",\n        },\n      ],\n    });\n  }\n  if (\n    options.cyclePolicy !== undefined &&\n    options.cyclePolicy !== \"prevent\" &&\n    options.cyclePolicy !== \"allow\"\n  ) {\n    throw new ValidationError(\n      'Subgraph cyclePolicy must be \"prevent\" or \"allow\"',\n      {\n        issues: [\n          {\n            path: \"cyclePolicy\",\n            message: \"Received an unsupported cycle policy\",\n            code: \"invalid_value\",\n          },\n        ],\n      },\n    );\n  }\n}\n\nfunction buildMetadataColumns(\n  alias: \"n\" | \"e\",\n  plan: ProjectionPlan,\n  columns: readonly string[],\n): readonly SqlFragment[] {\n  if (plan.projectedKinds.size === 0) {\n    return columns.map((col) => sql`${sql.raw(`${alias}.${col}`)}`);\n  }\n\n  const metaKinds: string[] = [...plan.fullKinds];\n  for (const [kind, kindPlan] of plan.projectedKinds) {\n    if (kindPlan.includeMeta) metaKinds.push(kind);\n  }\n\n  if (metaKinds.length === 0) {\n    return columns.map((col) => sql`NULL AS ${sql.raw(col)}`);\n  }\n\n  // All kinds need meta — no CASE needed\n  if (metaKinds.length === plan.fullKinds.length + plan.projectedKinds.size) {\n    return columns.map((col) => sql`${sql.raw(`${alias}.${col}`)}`);\n  }\n\n  const filter = compileKindFilter(sql.raw(`${alias}.kind`), metaKinds);\n  return columns.map(\n    (col) =>\n      sql`CASE WHEN ${filter} THEN ${sql.raw(`${alias}.${col}`)} ELSE NULL END AS ${sql.raw(col)}`,\n  );\n}\n\nfunction buildFullPropsColumn(\n  alias: \"n\" | \"e\",\n  plan: ProjectionPlan,\n): SqlFragment {\n  if (plan.projectedKinds.size === 0) {\n    return sql`${sql.raw(`${alias}.props`)} AS props`;\n  }\n\n  if (plan.fullKinds.length === 0) {\n    return sql`NULL AS props`;\n  }\n\n  const filter = compileKindFilter(sql.raw(`${alias}.kind`), plan.fullKinds);\n  return sql`CASE WHEN ${filter} THEN ${sql.raw(`${alias}.props`)} ELSE NULL END AS props`;\n}\n\nfunction buildProjectedPropertyColumns(\n  alias: \"n\" | \"e\",\n  plan: ProjectionPlan,\n  dialect: DialectAdapter,\n): readonly SqlFragment[] {\n  const columns: SqlFragment[] = [];\n\n  for (const [kind, kindPlan] of plan.projectedKinds.entries()) {\n    for (const fieldPlan of kindPlan.propertyFields) {\n      const extracted = compileTypedJsonExtract({\n        column: sql.raw(`${alias}.props`),\n        dialect,\n        pointer: jsonPointer([fieldPlan.field]),\n        valueType: fieldPlan.typeInfo?.valueType,\n      });\n\n      columns.push(\n        sql`CASE WHEN ${sql.raw(alias)}.kind = ${kind} THEN ${extracted} ELSE NULL END AS ${quoteIdentifier(fieldPlan.outputName)}`,\n      );\n    }\n  }\n\n  return columns;\n}\n\n// ============================================================\n// Adjacency Index Builder\n// ============================================================\n\nfunction insertAdjacencyEntry(\n  index: Map<string, Map<string, Edge[]>>,\n  nodeId: string,\n  edgeKind: string,\n  edge: Edge,\n): void {\n  let kindMap = index.get(nodeId);\n  if (kindMap === undefined) {\n    kindMap = new Map();\n    index.set(nodeId, kindMap);\n  }\n  const edges = kindMap.get(edgeKind);\n  if (edges === undefined) {\n    kindMap.set(edgeKind, [edge]);\n  } else {\n    edges.push(edge);\n  }\n}\n\n// ============================================================\n// Result Mapping\n// ============================================================\n\nfunction applyProjectedFields(\n  target: Record<string, unknown>,\n  row: Readonly<Record<string, unknown>>,\n  kindPlan: KindProjectionPlan,\n): void {\n  for (const fieldPlan of kindPlan.propertyFields) {\n    target[fieldPlan.field] = decodeSelectedValue(\n      row[fieldPlan.outputName],\n      fieldPlan.typeInfo,\n    );\n  }\n}\n\nfunction normalizeSubgraphRowTimestamps<\n  T extends Readonly<{\n    valid_from: unknown;\n    valid_to: unknown;\n    created_at: unknown;\n    updated_at: unknown;\n    deleted_at: unknown;\n  }>,\n>(row: T) {\n  return {\n    ...row,\n    valid_from: normalizeRowTimestamp(row.valid_from, \"valid_from\"),\n    valid_to: normalizeRowTimestamp(row.valid_to, \"valid_to\"),\n    created_at: normalizeRequiredRowTimestamp(row.created_at, \"created_at\"),\n    updated_at: normalizeRequiredRowTimestamp(row.updated_at, \"updated_at\"),\n    deleted_at: normalizeRowTimestamp(row.deleted_at, \"deleted_at\"),\n  };\n}\n\nfunction mapSubgraphNodeRow(\n  row: SubgraphNodeFetchRow,\n  projectionPlan: ProjectionPlan,\n): Node {\n  const kindPlan = projectionPlan.projectedKinds.get(row.kind);\n  if (kindPlan === undefined) {\n    const normalizedRow = normalizeSubgraphRowTimestamps(row);\n    return rowToNode({\n      ...normalizedRow,\n      props: normalizeProps(normalizedRow.props),\n    });\n  }\n\n  const projectedNode: Record<string, unknown> = {\n    kind: row.kind,\n    id: row.id,\n  };\n\n  if (kindPlan.includeMeta) {\n    projectedNode[\"meta\"] = rowToNodeMeta(normalizeSubgraphRowTimestamps(row));\n  }\n\n  applyProjectedFields(projectedNode, row, kindPlan);\n  return projectedNode as Node;\n}\n\nfunction mapSubgraphEdgeRow(\n  row: SubgraphEdgeFetchRow,\n  projectionPlan: ProjectionPlan,\n): Edge {\n  const kindPlan = projectionPlan.projectedKinds.get(row.kind);\n  if (kindPlan === undefined) {\n    const normalizedRow = normalizeSubgraphRowTimestamps(row);\n    return rowToEdge({\n      ...normalizedRow,\n      props: normalizeProps(normalizedRow.props),\n    });\n  }\n\n  const projectedEdge: Record<string, unknown> = {\n    id: row.id,\n    kind: row.kind,\n    fromKind: row.from_kind,\n    fromId: row.from_id,\n    toKind: row.to_kind,\n    toId: row.to_id,\n  };\n\n  if (kindPlan.includeMeta) {\n    projectedEdge[\"meta\"] = rowToEdgeMeta(normalizeSubgraphRowTimestamps(row));\n  }\n\n  applyProjectedFields(projectedEdge, row, kindPlan);\n  return projectedEdge as Edge;\n}\n","import { UnsupportedPredicateError } from \"../../errors\";\nimport type {\n  FieldRef,\n  PredicateExpression,\n  QueryAst,\n  Traversal,\n} from \"../ast\";\nimport { visitExpressionFields } from \"./standard-pass-pipeline\";\n\n/** Refuses predicates that an independently compiled traversal stage cannot evaluate. */\nexport function assertTraversalStagePredicatesSupported(\n  ast: QueryAst,\n  traversal: Traversal,\n  index: number,\n): void {\n  const stageTargets = new Set([\n    traversal.edgeAlias,\n    traversal.nodeAlias,\n    ...(index === 0 ? [ast.start.alias] : []),\n  ]);\n\n  for (const predicate of ast.predicates) {\n    if (!stageTargets.has(predicate.targetAlias)) continue;\n    visitPredicateFields(predicate.expression, (field) => {\n      if (field.alias !== predicate.targetAlias) {\n        throw new UnsupportedPredicateError(\n          `Traversal stage predicate for alias \"${predicate.targetAlias}\" cannot evaluate cross-alias reference \"${field.alias}\"; use completed where() for comparisons between aliases.`,\n        );\n      }\n    });\n  }\n}\n\nfunction visitPredicateFields(\n  expression: PredicateExpression,\n  visit: (field: FieldRef) => void,\n): void {\n  switch (expression.__type) {\n    case \"comparison\": {\n      visit(expression.left);\n      if (\n        !Array.isArray(expression.right) &&\n        expression.right.__type === \"field_ref\"\n      )\n        visit(expression.right);\n      return;\n    }\n    case \"tuple_comparison\": {\n      for (const field of expression.fields) visit(field);\n      return;\n    }\n    case \"string_op\":\n    case \"null_check\":\n    case \"between\":\n    case \"array_op\":\n    case \"object_op\":\n    case \"in_subquery\":\n    case \"vector_similarity\":\n    case \"fulltext_match\": {\n      visit(expression.field);\n      return;\n    }\n    case \"aggregate_comparison\": {\n      visit(expression.aggregate.field);\n      return;\n    }\n    case \"and\":\n    case \"or\": {\n      for (const operand of expression.predicates)\n        visitPredicateFields(operand, visit);\n      return;\n    }\n    case \"not\": {\n      visitPredicateFields(expression.predicate, visit);\n      return;\n    }\n    case \"database_expression_predicate\": {\n      visitExpressionFields(expression.expression, visit);\n      return;\n    }\n    case \"exists\": {\n      return;\n    }\n  }\n}\n","import { UnsupportedPredicateError } from \"../../errors\";\nimport type {\n  PredicateExpression,\n  ProjectedField,\n  QueryAst,\n  Traversal,\n} from \"../ast\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { compileLimitOffsetClauses } from \"./limit-offset\";\nimport { getNodeKindsForAlias } from \"./predicate-utils\";\nimport {\n  compilePredicateExpression,\n  type PredicateCompilerContext,\n} from \"./predicates\";\nimport {\n  assertRecursiveOutputSupported,\n  compileAdditionalRecursiveProjectionFields,\n  compileRecursiveOrderBy,\n  compileRecursiveResultField,\n  compileRecursiveSelectiveField,\n  compileRecursiveStage,\n  compileVariableLengthQuery,\n  hasExplicitRecursiveProjection,\n} from \"./recursive\";\nimport { assertTraversalStagePredicatesSupported } from \"./traversal-stage-validation\";\nimport { EDGE_COLUMNS, NODE_COLUMNS } from \"./utils\";\n\nfunction stageAst(\n  ast: QueryAst,\n  traversal: Traversal,\n  index: number,\n): QueryAst {\n  const allowedPredicates = new Set([\n    traversal.edgeAlias,\n    traversal.nodeAlias,\n    ...(index === 0 ? [ast.start.alias] : []),\n  ]);\n  const {\n    aggregateOrderBy: _aggregateOrderBy,\n    groupBy: _groupBy,\n    having: _having,\n    limit: _limit,\n    offset: _offset,\n    orderBy: _orderBy,\n    resultPredicate: _resultPredicate,\n    selectiveFields: _selectiveFields,\n    fusion: _fusion,\n    ...stageBase\n  } = ast;\n  return {\n    ...stageBase,\n    start: {\n      alias: traversal.joinFromAlias,\n      kinds: getNodeKindsForAlias(ast, traversal.joinFromAlias),\n      includeSubClasses:\n        index === 0 && traversal.joinFromAlias === ast.start.alias ?\n          ast.start.includeSubClasses\n        : false,\n    },\n    traversals: [traversal],\n    predicates: ast.predicates.filter((predicate) =>\n      allowedPredicates.has(predicate.targetAlias),\n    ),\n    projection: { fields: [] },\n    ...(index === 0 && ast.fusion !== undefined ? { fusion: ast.fusion } : {}),\n  };\n}\n\nfunction sourceAst(ast: QueryAst): QueryAst {\n  const {\n    aggregateOrderBy: _aggregateOrderBy,\n    groupBy: _groupBy,\n    having: _having,\n    limit: _limit,\n    offset: _offset,\n    orderBy: _orderBy,\n    resultPredicate: _resultPredicate,\n    selectiveFields: _selectiveFields,\n    ...sourceBase\n  } = ast;\n  return {\n    ...sourceBase,\n    traversals: [],\n    predicates: ast.predicates.filter(\n      (predicate) => predicate.targetAlias === ast.start.alias,\n    ),\n    projection: {\n      fields: NODE_COLUMNS.map((column) => ({\n        outputName: `${ast.start.alias}_${column}`,\n        source: {\n          __type: \"field_ref\",\n          alias: ast.start.alias,\n          path: [column],\n        },\n      })),\n    },\n  };\n}\n\nfunction selectNodeColumns(alias: string, sourceAlias?: string): SqlFragment[] {\n  return NODE_COLUMNS.map((column) => {\n    const name = `${alias}_${column}`;\n    return sourceAlias === undefined ?\n        sql.identifier(name)\n      : sql`${sql.identifier(sourceAlias)}.${sql.identifier(name)} AS ${sql.identifier(name)}`;\n  });\n}\n\nfunction stageOutputColumns(\n  traversal: Traversal,\n  sourceAlias: string,\n): SqlFragment[] {\n  const columns = selectNodeColumns(traversal.nodeAlias, sourceAlias);\n  const variableLength = traversal.variableLength;\n  if (variableLength?.depthAlias !== undefined) {\n    columns.push(\n      sql`${sql.identifier(sourceAlias)}.${sql.identifier(variableLength.depthAlias)} AS ${sql.identifier(variableLength.depthAlias)}`,\n    );\n  }\n  if (variableLength?.pathAlias !== undefined) {\n    columns.push(\n      sql`${sql.identifier(sourceAlias)}.${sql.identifier(variableLength.pathAlias)} AS ${sql.identifier(variableLength.pathAlias)}`,\n    );\n  }\n  return columns;\n}\n\nfunction fixedStageOutputColumns(\n  traversal: Traversal,\n  sourceAlias: string,\n): SqlFragment[] {\n  return [\n    ...stageOutputColumns(traversal, sourceAlias),\n    ...EDGE_COLUMNS.map((column) => {\n      const name = `${traversal.edgeAlias}_${column}`;\n      return sql`${sql.identifier(sourceAlias)}.${sql.identifier(name)} AS ${sql.identifier(name)}`;\n    }),\n  ];\n}\n\nfunction fixedStageProjection(traversal: Traversal): readonly ProjectedField[] {\n  const fields = [\n    ...NODE_COLUMNS.map((column) => ({\n      alias: traversal.joinFromAlias,\n      column,\n    })),\n    ...NODE_COLUMNS.map((column) => ({\n      alias: traversal.nodeAlias,\n      column,\n    })),\n    ...EDGE_COLUMNS.map((column) => ({\n      alias: traversal.edgeAlias,\n      column,\n    })),\n  ];\n  return fields.map(({ alias, column }) => ({\n    outputName: `${alias}_${column}`,\n    source: {\n      __type: \"field_ref\",\n      alias,\n      path: [column],\n    },\n    ...(alias === traversal.edgeAlias ?\n      { cteAlias: `cte_${traversal.nodeAlias}` }\n    : {}),\n  }));\n}\n\nfunction outputColumnsForStage(\n  traversal: Traversal,\n  sourceAlias: string,\n): SqlFragment[] {\n  return traversal.variableLength === undefined ?\n      fixedStageOutputColumns(traversal, sourceAlias)\n    : stageOutputColumns(traversal, sourceAlias);\n}\n\nfunction compileStage(\n  ast: QueryAst,\n  traversal: Traversal,\n  index: number,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  seed?: SqlFragment,\n): SqlFragment {\n  assertTraversalStagePredicatesSupported(ast, traversal, index);\n  const isolated = stageAst(ast, traversal, index);\n  if (traversal.variableLength === undefined) {\n    const compiled = ctx.compileQuery(\n      {\n        ...isolated,\n        projection: { fields: fixedStageProjection(traversal) },\n      },\n      graphId,\n    );\n    if (seed === undefined) return compiled;\n    const stageAlias = \"__tg_fixed_stage\";\n    const seedAlias = \"__tg_fixed_seed\";\n    return sql`\n      SELECT * FROM (${compiled}) AS ${sql.identifier(stageAlias)}\n      WHERE EXISTS (\n        SELECT 1 FROM (${seed}) AS ${sql.identifier(seedAlias)}\n        WHERE ${sql.identifier(seedAlias)}.kind = ${sql.identifier(stageAlias)}.${sql.identifier(`${traversal.joinFromAlias}_kind`)}\n          AND ${sql.identifier(seedAlias)}.id = ${sql.identifier(stageAlias)}.${sql.identifier(`${traversal.joinFromAlias}_id`)}\n      )\n    `;\n  }\n  return seed === undefined ?\n      compileVariableLengthQuery(isolated, graphId, ctx)\n    : compileRecursiveStage(isolated, graphId, ctx, seed);\n}\n\nfunction compileFinalProjection(\n  ast: QueryAst,\n  traversals: readonly Traversal[],\n  ctx: PredicateCompilerContext,\n  resultAlias: string,\n): SqlFragment {\n  const dialect = ctx.dialect;\n  if (ast.selectiveFields !== undefined && ast.selectiveFields.length > 0) {\n    const nodeAliases = new Set([\n      ast.start.alias,\n      ...traversals.map((traversal) => traversal.nodeAlias),\n    ]);\n    const fixedEdgeAliases = new Set(\n      traversals\n        .filter((traversal) => traversal.variableLength === undefined)\n        .map((traversal) => traversal.edgeAlias),\n    );\n    const selectableAliases = new Set([...nodeAliases, ...fixedEdgeAliases]);\n    // Optional-node decoding tracks structural edge fields even when the edge\n    // was not selected. Recursive stages do not materialize those edge rows.\n    const emittedFields = ast.selectiveFields.filter((field) =>\n      selectableAliases.has(field.alias),\n    );\n    const columns = emittedFields.map((field) =>\n      compileRecursiveSelectiveField(\n        field,\n        selectableAliases,\n        dialect,\n        resultAlias,\n      ),\n    );\n    for (const traversal of traversals) {\n      const variableLength = traversal.variableLength;\n      if (variableLength?.depthAlias !== undefined) {\n        columns.push(\n          sql`${sql.identifier(resultAlias)}.${sql.identifier(variableLength.depthAlias)} AS ${sql.identifier(variableLength.depthAlias)}`,\n        );\n      }\n      if (variableLength?.pathAlias !== undefined) {\n        columns.push(\n          sql`${sql.identifier(resultAlias)}.${sql.identifier(variableLength.pathAlias)} AS ${sql.identifier(variableLength.pathAlias)}`,\n        );\n      }\n    }\n    columns.push(\n      ...compileAdditionalRecursiveProjectionFields(\n        ast,\n        new Set(emittedFields.map((field) => field.outputName)),\n        ctx,\n        resultAlias,\n        new Set(\n          traversals\n            .filter((traversal) => traversal.variableLength !== undefined)\n            .map((traversal) => traversal.edgeAlias),\n        ),\n      ),\n    );\n    return sql.join(columns, sql`, `);\n  }\n\n  const explicitProjection = hasExplicitRecursiveProjection(ast);\n  const nodeAliases = [\n    ast.start.alias,\n    ...traversals.map((traversal) => traversal.nodeAlias),\n  ];\n  const columns = [\n    ...(explicitProjection ?\n      []\n    : [\n        ...nodeAliases.flatMap((alias) =>\n          selectNodeColumns(alias, resultAlias),\n        ),\n        ...traversals\n          .filter((traversal) => traversal.variableLength === undefined)\n          .flatMap((traversal) =>\n            EDGE_COLUMNS.map((column) => {\n              const name = `${traversal.edgeAlias}_${column}`;\n              return sql`${sql.identifier(resultAlias)}.${sql.identifier(name)} AS ${sql.identifier(name)}`;\n            }),\n          ),\n      ]),\n    ...traversals.flatMap((traversal) =>\n      stageOutputColumns(traversal, resultAlias).slice(NODE_COLUMNS.length),\n    ),\n    ...compileAdditionalRecursiveProjectionFields(\n      ast,\n      new Set(\n        explicitProjection ?\n          []\n        : [\n            ...nodeAliases.flatMap((alias) =>\n              NODE_COLUMNS.map((column) => `${alias}_${column}`),\n            ),\n            ...traversals\n              .filter((traversal) => traversal.variableLength === undefined)\n              .flatMap((traversal) =>\n                EDGE_COLUMNS.map(\n                  (column) => `${traversal.edgeAlias}_${column}`,\n                ),\n              ),\n          ],\n      ),\n      ctx,\n      resultAlias,\n      new Set(\n        traversals\n          .filter((traversal) => traversal.variableLength !== undefined)\n          .map((traversal) => traversal.edgeAlias),\n      ),\n    ),\n  ];\n  return sql.join(columns, sql`, `);\n}\n\nfunction assertRecursiveResultPredicateSupported(\n  predicate: PredicateExpression,\n): void {\n  if (predicate.__type === \"database_expression_predicate\") return;\n  if (predicate.__type === \"not\") {\n    assertRecursiveResultPredicateSupported(predicate.predicate);\n    return;\n  }\n  if (predicate.__type === \"and\" || predicate.__type === \"or\") {\n    for (const operand of predicate.predicates)\n      assertRecursiveResultPredicateSupported(operand);\n    return;\n  }\n  throw new UnsupportedPredicateError(\n    \"Completed recursive match filters require database expressions so materialized output columns remain scope-safe.\",\n  );\n}\n\nexport function compileMultiStageRecursiveQuery(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const traversals = ast.traversals;\n  assertRecursiveOutputSupported(ast);\n  const materializedAliases = new Set([ast.start.alias]);\n  for (const traversal of traversals) {\n    if (!materializedAliases.has(traversal.joinFromAlias)) {\n      throw new UnsupportedPredicateError(\n        `Recursive traversal source alias \"${traversal.joinFromAlias}\" must refer to an earlier stage`,\n      );\n    }\n    materializedAliases.add(traversal.nodeAlias);\n  }\n  const edgeAliases = new Set(\n    traversals\n      .filter((traversal) => traversal.variableLength !== undefined)\n      .map((traversal) => traversal.edgeAlias),\n  );\n  const selectedEdgeField = ast.selectiveFields?.find((field) =>\n    edgeAliases.has(field.alias),\n  );\n  if (selectedEdgeField !== undefined) {\n    throw new UnsupportedPredicateError(\n      `Selective projection for recursive traversals does not support edge alias \"${selectedEdgeField.alias}\"`,\n    );\n  }\n  const ctes: SqlFragment[] = [];\n  let completedName = \"typegraph_recursive_stage_0\";\n  const firstTraversal = traversals[0];\n  if (firstTraversal === undefined) {\n    throw new UnsupportedPredicateError(\n      \"Recursive query has no traversal stages\",\n    );\n  }\n  if (firstTraversal.optional) {\n    assertTraversalStagePredicatesSupported(ast, firstTraversal, 0);\n    const sourceName = \"typegraph_recursive_source_0\";\n    const source = ctx.compileQuery(sourceAst(ast), graphId);\n    const seed = sql`SELECT DISTINCT ${sql.identifier(`${ast.start.alias}_kind`)} AS kind, ${sql.identifier(`${ast.start.alias}_id`)} AS id FROM ${sql.identifier(sourceName)}`;\n    const expansion = compileStage(ast, firstTraversal, 1, graphId, ctx, seed);\n    const expansionName = \"typegraph_recursive_expansion_0\";\n    ctes.push(\n      sql`${sql.identifier(sourceName)} AS (${source})`,\n      sql`${sql.identifier(expansionName)} AS (${expansion})`,\n      sql`\n        ${sql.identifier(completedName)} AS (\n          SELECT source.*, ${sql.join(outputColumnsForStage(firstTraversal, \"expanded\"), sql`, `)}\n          FROM ${sql.identifier(sourceName)} AS source\n          LEFT JOIN ${sql.identifier(expansionName)} AS expanded\n            ON expanded.${sql.identifier(`${ast.start.alias}_kind`)} = source.${sql.identifier(`${ast.start.alias}_kind`)}\n           AND expanded.${sql.identifier(`${ast.start.alias}_id`)} = source.${sql.identifier(`${ast.start.alias}_id`)}\n        )\n      `,\n    );\n  } else {\n    ctes.push(\n      sql`${sql.identifier(completedName)} AS (${compileStage(ast, firstTraversal, 0, graphId, ctx)})`,\n    );\n  }\n\n  for (let index = 1; index < traversals.length; index++) {\n    const traversal = traversals[index];\n    if (traversal === undefined) continue;\n    const expansionName = `typegraph_recursive_expansion_${index}`;\n    const nextCompletedName = `typegraph_recursive_stage_${index}`;\n    const seed = sql`SELECT DISTINCT ${sql.identifier(`${traversal.joinFromAlias}_kind`)} AS kind, ${sql.identifier(`${traversal.joinFromAlias}_id`)} AS id FROM ${sql.identifier(completedName)} WHERE ${sql.identifier(`${traversal.joinFromAlias}_id`)} IS NOT NULL`;\n    const expansion = compileStage(ast, traversal, index, graphId, ctx, seed);\n    ctes.push(sql`${sql.identifier(expansionName)} AS (${expansion})`);\n    const join = traversal.optional ? sql`LEFT JOIN` : sql`JOIN`;\n    ctes.push(sql`\n      ${sql.identifier(nextCompletedName)} AS (\n            SELECT previous.*, ${sql.join(outputColumnsForStage(traversal, \"expanded\"), sql`, `)}\n            FROM ${sql.identifier(completedName)} AS previous\n            ${join} ${sql.identifier(expansionName)} AS expanded\n              ON expanded.${sql.identifier(`${traversal.joinFromAlias}_kind`)} = previous.${sql.identifier(`${traversal.joinFromAlias}_kind`)}\n             AND expanded.${sql.identifier(`${traversal.joinFromAlias}_id`)} = previous.${sql.identifier(`${traversal.joinFromAlias}_id`)}\n          )\n    `);\n    completedName = nextCompletedName;\n  }\n\n  const resultAlias = ctx.recursiveResultAlias ?? \"typegraph_recursive_result\";\n  const clauses: SqlFragment[] = [];\n  if (ast.resultPredicate !== undefined) {\n    assertRecursiveResultPredicateSupported(ast.resultPredicate);\n    clauses.push(\n      sql`WHERE ${compilePredicateExpression(ast.resultPredicate, {\n        ...ctx,\n        resolveFieldCteAlias: () => resultAlias,\n        compileFieldExpression(field, expression) {\n          return compileRecursiveResultField(\n            field,\n            ctx.dialect,\n            resultAlias,\n            expression.valueType,\n          );\n        },\n      })}`,\n    );\n  }\n  const orderBy = compileRecursiveOrderBy(ast, ctx, resultAlias);\n  if (orderBy !== undefined) clauses.push(orderBy);\n  const range = compileLimitOffsetClauses(ast.limit, ast.offset, ctx.dialect);\n  clauses.push(...range);\n\n  return sql`\n    WITH ${sql.join(ctes, sql`, `)}\n        SELECT ${compileFinalProjection(ast, traversals, ctx, resultAlias)}\n        FROM ${sql.identifier(completedName)} AS ${sql.identifier(resultAlias)}\n        ${sql.join(clauses, sql` `)}\n  `;\n}\n","/**\n * Set Operation Compilation\n *\n * Compiles UNION, INTERSECT, and EXCEPT operations to SQL.\n *\n * Both dialects compile each leaf with the full query compiler and combine\n * the results with the requested operator. The only dialect-specific concern\n * is how each operand is wrapped so the compound statement stays valid:\n *\n * - PostgreSQL allows a complete SELECT (including its own WITH clause) to be\n *   parenthesized as a compound operand: `(SELECT ...) UNION (SELECT ...)`.\n * - SQLite forbids parentheses around compound operands, but it does allow a\n *   `WITH` clause inside a FROM-subquery, so each operand is wrapped as\n *   `SELECT * FROM (SELECT ...)`. This keeps every leaf's CTEs (traversals,\n *   vector/fulltext joins, recursive expansions) scoped to its own subquery\n *   and lets per-leaf ORDER BY/LIMIT/OFFSET live inside the wrap.\n *\n * Nested set operations are wrapped the same way, which preserves the AST's\n * grouping regardless of the dialect's native compound-operator associativity.\n */\nimport {\n  CompilerInvariantError,\n  ConfigurationError,\n  UnsupportedPredicateError,\n} from \"../../errors\";\nimport type { SetOperationType } from \"../ast\";\nimport {\n  type ComposableQuery,\n  type FieldRef,\n  type OrderSpec,\n  type ProjectedField,\n  type Projection,\n  type QueryAst,\n  type SetOperation,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport { type JsonPointer, jsonPointer } from \"../json-pointer\";\nimport { compileOrderTerm, resolveNullOrdering } from \"../order\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { emitSetOperationQuerySql } from \"./emitter\";\nimport { compileLimitOffsetClauses } from \"./limit-offset\";\nimport { runCompilerPass } from \"./passes\";\nimport { type LogicalPlan, lowerSetOperationToLogicalPlan } from \"./plan\";\n\n/**\n * Type for the query compiler function.\n */\nexport type QueryCompilerFunction = (\n  ast: QueryAst,\n  graphId: string,\n) => SqlFragment;\n\n/**\n * Operator mapping for set operations.\n */\nconst OPERATOR_MAP: Record<SetOperationType, string> = {\n  union: \"UNION\",\n  unionAll: \"UNION ALL\",\n  intersect: \"INTERSECT\",\n  except: \"EXCEPT\",\n};\n\n/** One closed operator vocabulary for graph and projected relation composition. */\nexport function setOperationKeyword(operator: SetOperationType): string {\n  if (!Object.hasOwn(OPERATOR_MAP, operator))\n    throw new UnsupportedPredicateError(\"Unsupported set-operation operator\");\n  return OPERATOR_MAP[operator];\n}\n\ntype SetOperationPassState = Readonly<{\n  dialect: DialectAdapter;\n  graphId: string;\n  logicalPlan: LogicalPlan | undefined;\n  op: SetOperation;\n}>;\n\ntype RecordedCoordinateKey = string;\n\nfunction queryRecordedCoordinateKey(ast: QueryAst): RecordedCoordinateKey {\n  return ast.recordedAsOf ?? \"live\";\n}\n\nfunction collectQueryRecordedCoordinateKeys(\n  query: ComposableQuery,\n  keys: Set<RecordedCoordinateKey>,\n): void {\n  if (\"__type\" in query) {\n    collectQueryRecordedCoordinateKeys(query.left, keys);\n    collectQueryRecordedCoordinateKeys(query.right, keys);\n    return;\n  }\n  keys.add(queryRecordedCoordinateKey(query));\n}\n\nfunction assertUniformSetOperationRecordedCoordinates(op: SetOperation): void {\n  const keys = new Set<RecordedCoordinateKey>();\n  collectQueryRecordedCoordinateKeys(op, keys);\n  if (keys.size <= 1) return;\n  throw new ConfigurationError(\n    \"Cannot combine queries with different recorded-time coordinates in a set \" +\n      \"operation: each operand reads either the live tables or the recorded \" +\n      \"relation at one instant, so mixing live with recorded (or two different \" +\n      \"recorded instants) is rejected. Valid-time differences are allowed.\",\n    { code: \"SET_OPERATION_RECORDED_COORDINATE_MISMATCH\" },\n    {\n      suggestion:\n        \"Build every operand from the same Store or recorded StoreView coordinate before calling union/intersect/except.\",\n    },\n  );\n}\n\nfunction runSetOperationPassPipeline(\n  op: SetOperation,\n  graphId: string,\n  dialect: DialectAdapter,\n  vectorStrategy: VectorStrategy | undefined,\n): SetOperationPassState {\n  let state: SetOperationPassState = {\n    dialect,\n    graphId,\n    logicalPlan: undefined,\n    op,\n  };\n\n  const logicalPlanPass = runCompilerPass(state, {\n    name: \"logical_plan\",\n    execute(currentState): LogicalPlan {\n      return lowerSetOperationToLogicalPlan({\n        dialect: currentState.dialect.name,\n        graphId: currentState.graphId,\n        op: currentState.op,\n        ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n      });\n    },\n    update(currentState, logicalPlan): SetOperationPassState {\n      return {\n        ...currentState,\n        logicalPlan,\n      };\n    },\n  });\n  state = logicalPlanPass.state;\n\n  return state;\n}\n\n// ============================================================\n// Main Entry Point\n// ============================================================\n\n/**\n * Compiles a set operation to SQL.\n *\n * Each leaf is compiled by the full query compiler, so set operations support\n * exactly the same query features as standalone queries (traversals, EXISTS/IN\n * subqueries, vector/fulltext predicates, GROUP BY/HAVING, and per-leaf\n * ORDER BY/LIMIT/OFFSET) on every dialect.\n *\n * @param op - The set operation AST\n * @param graphId - The graph ID\n * @param dialect - The dialect adapter\n * @param compileQuery - Function to compile regular (leaf) queries\n * @param vectorStrategy - The backend-configured vector strategy, if any, used\n *   to validate leaf vector predicates against the strategy's metric set\n * @returns `SqlFragment` for the set operation\n */\nexport function compileSetOperation(\n  op: SetOperation,\n  graphId: string,\n  dialect: DialectAdapter,\n  compileQuery: QueryCompilerFunction,\n  vectorStrategy?: VectorStrategy,\n): SqlFragment {\n  assertUniformSetOperationRecordedCoordinates(op);\n  const passState = runSetOperationPassPipeline(\n    op,\n    graphId,\n    dialect,\n    vectorStrategy,\n  );\n  const { logicalPlan } = passState;\n  if (logicalPlan === undefined) {\n    throw new CompilerInvariantError(\n      \"Logical plan pass did not initialize plan state\",\n    );\n  }\n\n  const coreSql = compileSetOperationCore(op, graphId, compileQuery, dialect);\n\n  const suffixClauses = buildSetOperationSuffixClauses(op, dialect);\n  return emitSetOperationQuerySql({\n    baseQuery: coreSql,\n    logicalPlan,\n    ...(suffixClauses.length === 0 ? {} : { suffixClauses }),\n  });\n}\n\n/**\n * Compiles a set operation node into a compound SELECT by wrapping each side\n * with the dialect's operand wrapper and joining them with the operator.\n */\nfunction compileSetOperationCore(\n  op: SetOperation,\n  graphId: string,\n  compileQuery: QueryCompilerFunction,\n  dialect: DialectAdapter,\n): SqlFragment {\n  const left = compileComposableQuery(op.left, graphId, compileQuery, dialect);\n  const right = compileComposableQuery(\n    op.right,\n    graphId,\n    compileQuery,\n    dialect,\n  );\n\n  const opSql = sql.raw(setOperationKeyword(op.operator));\n\n  return sql`${dialect.wrapSetOperationOperand(left)} ${opSql} ${dialect.wrapSetOperationOperand(right)}`;\n}\n\n/**\n * Compiles a composable query operand. Leaves are compiled by the full query\n * compiler; nested set operations recurse into a complete compound SELECT\n * (including their own ORDER BY/LIMIT/OFFSET) before the parent wraps them.\n */\nfunction compileComposableQuery(\n  query: ComposableQuery,\n  graphId: string,\n  compileQuery: QueryCompilerFunction,\n  dialect: DialectAdapter,\n): SqlFragment {\n  if (\"__type\" in query) {\n    return compileSetOperationCompound(query, graphId, compileQuery, dialect);\n  }\n  return compileQuery(query, graphId);\n}\n\n/**\n * Compiles a set operation into a complete compound SELECT, including its own\n * ORDER BY/LIMIT/OFFSET suffix clauses. Used for nested operands: a nested\n * compound carries suffix clauses that belong inside the operand, not on the\n * outer statement. The top-level entry (compileSetOperation) layers the\n * logical-plan emitter invariant on top of these same core + suffix clauses.\n */\nfunction compileSetOperationCompound(\n  op: SetOperation,\n  graphId: string,\n  compileQuery: QueryCompilerFunction,\n  dialect: DialectAdapter,\n): SqlFragment {\n  const core = compileSetOperationCore(op, graphId, compileQuery, dialect);\n  const suffixClauses = buildSetOperationSuffixClauses(op, dialect);\n  if (suffixClauses.length === 0) return core;\n  return sql.join([core, ...suffixClauses], sql` `);\n}\n\n// ============================================================\n// Suffix Clauses (ORDER BY / LIMIT / OFFSET)\n// ============================================================\n\n/**\n * Gets the leftmost leaf's projection from a set operation.\n * The leftmost leaf defines the output column names for the compound query.\n */\nfunction getLeftmostProjection(op: SetOperation): Projection {\n  let current: ComposableQuery = op.left;\n  while (\"__type\" in current) {\n    // current is a SetOperation, traverse left\n    current = current.left;\n  }\n  // current is now a QueryAst (the leftmost leaf)\n  return current.projection;\n}\n\n/**\n * Normalizes a FieldRef to a canonical key for comparison.\n *\n * Handles equivalent representations:\n * - path: [\"props\", \"name\"] (no jsonPointer) → \"alias:props:/name\"\n * - path: [\"props\"], jsonPointer: \"/name\" → \"alias:props:/name\"\n *\n * This matches the normalization logic in compileFieldValue/getFieldPointer.\n */\nfunction normalizeFieldRefKey(field: FieldRef): string {\n  // Derive JSON pointer from path if not explicitly set (same logic as predicates.ts getFieldPointer)\n  let pointer: JsonPointer | undefined = field.jsonPointer;\n  if (\n    pointer === undefined &&\n    field.path.length > 1 &&\n    field.path[0] === \"props\"\n  ) {\n    pointer = jsonPointer(field.path.slice(1));\n  }\n\n  // Normalize base path: for JSON fields, always use [\"props\"]\n  const basePath =\n    field.path.length > 0 && field.path[0] === \"props\" ?\n      \"props\"\n    : field.path.join(\".\");\n\n  return `${field.alias}:${basePath}:${pointer ?? \"\"}`;\n}\n\n/**\n * Matches a FieldRef from ORDER BY to a ProjectedField in the projection.\n * Returns the matching ProjectedField or undefined if no match.\n *\n * Uses normalized keys to handle equivalent field representations.\n */\nfunction matchFieldToProjection(\n  field: OrderSpec[\"field\"],\n  projection: Projection,\n): ProjectedField | undefined {\n  if (field.__type === \"database_expression\") {\n    return projection.fields.find((projected) => projected.source === field);\n  }\n  const targetKey = normalizeFieldRefKey(field);\n\n  for (const projected of projection.fields) {\n    const source = projected.source;\n\n    // Only match against FieldRef sources (not aggregates)\n    if (!(\"__type\" in source) || source.__type !== \"field_ref\") continue;\n\n    // Compare normalized keys\n    if (normalizeFieldRefKey(source) === targetKey) {\n      return projected;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Builds ORDER BY, LIMIT, OFFSET clauses for set operations.\n *\n * For set operations, ORDER BY must reference output column names from\n * the compound result, not internal CTE columns. This function:\n * 1. Maps each ORDER BY field to its output name from the leftmost projection\n * 2. Applies the requested NULLS FIRST/LAST placement\n * 3. Throws a descriptive error if an ORDER BY field isn't in the projection\n */\nfunction buildSetOperationSuffixClauses(\n  op: SetOperation,\n  dialect: DialectAdapter,\n): SqlFragment[] {\n  const clauses: SqlFragment[] = [];\n\n  // Handle ORDER BY if present\n  if (op.orderBy && op.orderBy.length > 0) {\n    const projection = getLeftmostProjection(op);\n\n    // Check for SELECT * (empty projection) - can't order by named columns\n    if (projection.fields.length === 0) {\n      throw new UnsupportedPredicateError(\n        \"Set operation ORDER BY requires explicit field projection. \" +\n          \"SELECT * does not provide stable output column names for ordering. \" +\n          \"Use .select() to specify which fields to project.\",\n      );\n    }\n\n    const orderParts: SqlFragment[] = [];\n\n    for (const orderSpec of op.orderBy) {\n      const projected = matchFieldToProjection(orderSpec.field, projection);\n\n      if (!projected) {\n        // Build a descriptive error message\n        const fieldDesc =\n          orderSpec.field.__type === \"database_expression\" ?\n            \"database expression\"\n          : orderSpec.field.jsonPointer ?\n            `${orderSpec.field.alias}.props${orderSpec.field.jsonPointer}`\n          : `${orderSpec.field.alias}.${orderSpec.field.path.join(\".\")}`;\n        const availableFields = projection.fields\n          .map((f) => f.outputName)\n          .join(\", \");\n        throw new UnsupportedPredicateError(\n          `Set operation ORDER BY field \"${fieldDesc}\" is not in the projection. ` +\n            `ORDER BY for UNION/INTERSECT/EXCEPT must reference projected columns. ` +\n            `Available columns: ${availableFields}`,\n        );\n      }\n\n      // Use output column name with proper quoting\n      const columnRef = sql.raw(dialect.quoteIdentifier(projected.outputName));\n      // Default: ASC → NULLS LAST, DESC → NULLS FIRST\n      const nulls = resolveNullOrdering(orderSpec);\n      orderParts.push(compileOrderTerm(columnRef, orderSpec.direction, nulls));\n    }\n\n    clauses.push(sql`ORDER BY ${sql.join(orderParts, sql`, `)}`);\n  }\n\n  clauses.push(...compileLimitOffsetClauses(op.limit, op.offset, dialect));\n\n  return clauses;\n}\n","import { requireDefined } from \"../../utils/presence\";\n/**\n * Query Compiler Module\n *\n * Main entry point for compiling query ASTs to SQL.\n * Re-exports individual compiler modules and provides the main compile functions.\n */\n\n// Re-export sub-modules\nexport {\n  type LogicalPlan,\n  type LogicalPlanNode,\n  lowerRecursiveQueryToLogicalPlan,\n  lowerSetOperationToLogicalPlan,\n  lowerStandardQueryToLogicalPlan,\n} from \"./plan\";\nexport {\n  compileAggregateExpr,\n  compileFieldColumn,\n  compileFieldValue,\n  compilePredicateExpression,\n  type PredicateCompilerContext,\n} from \"./predicates\";\nexport {\n  compileVariableLengthQuery,\n  hasVariableLengthTraversal,\n  MAX_EXPLICIT_RECURSIVE_DEPTH,\n  MAX_RECURSIVE_DEPTH,\n} from \"./recursive\";\nexport {\n  createSqlSchema,\n  DEFAULT_SQL_SCHEMA,\n  type ExternalRecordedReadSource,\n  recordedRelation,\n  type RecordedRelationOptions,\n  type ResolvedSqlTableNames,\n  type SqlSchema,\n  type SqlTableNames,\n} from \"./schema\";\nexport {\n  compileTemporalFilter,\n  extractTemporalOptions,\n  type TemporalFilterOptions,\n} from \"./temporal\";\nimport { type ReadInstantMode, withPinnedReadInstant } from \"./temporal\";\n\n// Re-export dialect helpers and types\nexport { getDialect } from \"../dialect\";\nexport { type DialectAdapter, type SqlDialect } from \"../dialect/types\";\n\nimport {\n  assumeRecursiveTraversalSupported,\n  type RecursiveTraversalVerdict,\n} from \"../../backend/capabilities/recursive-traversal\";\nimport { CompilerInvariantError, ConfigurationError } from \"../../errors\";\nimport {\n  type AggregateExpr,\n  type FulltextMatchPredicate,\n  type HybridFusionOptions,\n  type QueryAst,\n  type SelectiveField,\n  type SetOperation,\n  type VectorSimilarityPredicate,\n} from \"../ast\";\nimport { getDialect } from \"../dialect\";\nimport { type FulltextStrategy } from \"../dialect/fulltext-strategy\";\nimport {\n  type DialectAdapter,\n  type DialectStandardQueryStrategy,\n  type SqlDialect,\n} from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport {\n  annIndexScanTypes,\n  asCompiledSelectSql,\n  type CompiledSelectSql,\n  markAnnIndexScan,\n} from \"../sql-intent\";\nimport { compileDatabaseExpression } from \"./database-expressions\";\nimport { emitStandardQuerySql } from \"./emitter\";\nimport {\n  buildLateMaterializedOuterOrderBy,\n  buildLateMaterializedOuterProjection,\n  buildLateMaterializedTopKCte,\n  buildLimitOffsetClause,\n  buildStandardEmbeddingsCte,\n  buildStandardFromClause,\n  buildStandardFulltextCte,\n  buildStandardFulltextOrderBy,\n  buildStandardGroupBy,\n  buildStandardHaving,\n  buildStandardHybridCandidateCte,\n  buildStandardHybridRrfOrderBy,\n  buildStandardOrderBy,\n  buildStandardProjection,\n  buildStandardResultWhere,\n  buildStandardStartCte,\n  buildStandardTraversalCte,\n  buildStandardVectorOrderBy,\n  LATE_MAT_TOPK_CTE_ALIAS,\n  lateMaterializedPhysicalAlias,\n  lateMaterializedProjectedNodeAliases,\n} from \"./emitter\";\nimport {\n  type ExpressionAliasScope,\n  namespaceExpressionSubquery,\n} from \"./expression-subquery-scope\";\nimport { compileIdentityClassCte } from \"./identity-traversal\";\nimport { type TemporalFilterPass } from \"./passes\";\nimport { type LogicalPlan, type LogicalPlanNode } from \"./plan\";\nimport {\n  compileKindFilter,\n  compilePredicateClauses,\n  getHybridTargetAlias,\n  getNodeKindsForAlias,\n  getPredicatesForAlias,\n  type PredicateIndex,\n} from \"./predicate-utils\";\nimport { compileFieldValue, type PredicateCompilerContext } from \"./predicates\";\nimport {\n  compileVariableLengthQuery,\n  hasVariableLengthTraversal,\n} from \"./recursive\";\nimport { compileMultiStageRecursiveQuery } from \"./recursive-chain\";\nimport {\n  DEFAULT_SQL_SCHEMA,\n  type RecordedReadBinding,\n  recordedReadSchemaFor,\n  requireSqlSchema,\n  type SqlSchema,\n  type VectorSlotMap,\n} from \"./schema\";\nimport { compileSetOperation as compileSetOp } from \"./set-operations\";\nimport {\n  collectRequiredColumnsByAlias,\n  runStandardQueryPassPipeline,\n  shouldMaterializeTraversalCte,\n} from \"./standard-pass-pipeline\";\nimport {\n  findSelectivePropsFieldForFieldRef,\n  isAggregateExpr,\n  isIdFieldRef,\n  mapSelectiveSystemFieldToColumn,\n  quoteIdentifier,\n  type RequiredColumnsByAlias,\n} from \"./utils\";\n\n// ============================================================\n// Main Query Compiler\n// ============================================================\n\n/**\n * Options for query compilation.\n */\nexport type CompileQueryOptions = Readonly<{\n  /** SQL dialect (\"sqlite\" or \"postgres\"). Defaults to \"sqlite\". */\n  dialect?: SqlDialect | undefined;\n  /** SQL schema configuration from createSqlSchema(...). Defaults to standard names. */\n  schema?: SqlSchema | undefined;\n  /**\n   * Fulltext strategy override. When set, overrides the dialect's\n   * default fulltext strategy for `$fulltext.matches()` compilation.\n   * Callers typically read this from `resolveBackendFulltext(backend)` so\n   * a backend-declared strategy (e.g. ParadeDB) wins over the dialect\n   * default (tsvector), and `false` (a backend built with\n   * `fulltext: false`) compiles a `matches()` predicate to a typed\n   * refusal instead of the dialect default.\n   */\n  fulltextStrategy?: FulltextStrategy | false | undefined;\n  /**\n   * Vector strategy override. When set, `field.similarTo(...)`\n   * predicates compile against the strategy's per-`(kind, field)`\n   * tables and distance expression. Callers read it from\n   * `backend.vectorStrategy` so a backend-declared strategy (pgvector,\n   * libsql-native, sqlite-vec) drives the per-field relevance scan.\n   */\n  vectorStrategy?: VectorStrategy | undefined;\n  /**\n   * Whether the active backend supports SQL window functions such as\n   * `ROW_NUMBER()`. Defaults to true for direct compiler callers.\n   */\n  windowFunctions?: boolean | undefined;\n  /** Whether ordered scalar collection aggregates are supported. Defaults to true for direct compiler callers. */\n  orderedAggregates?: boolean | undefined;\n  /**\n   * Declared embedding slots `(kind, fieldPath) -> descriptor` used by\n   * the `field.similarTo(...)` CTE to know which kinds in an alias\n   * declare the field. Callers build it from the graph's node schemas.\n   */\n  vectorSlots?: VectorSlotMap | undefined;\n  /** Per-kind declared fulltext language (see buildFulltextLanguages). */\n  fulltextLanguages?: ReadonlyMap<string, string> | undefined;\n  /**\n   * Recorded read relation to use when the AST carries `recordedAsOf`.\n   * Supplying a recorded timestamp without this binding is rejected so the\n   * compiler never silently swaps to TypeGraph's built-in history tables when\n   * the store was only configured for live/valid-time reads.\n   */\n  recordedReadBinding?: RecordedReadBinding | undefined;\n  /**\n   * How the \"current\" valid-time read instant is emitted. Defaults to\n   * `\"literal\"` (a value frozen at compile time). The query builder's\n   * compiled template cache passes `\"placeholder\"` so the instant is a\n   * reserved execution-time slot, letting one compiled statement be reused\n   * across executions with a fresh \"now\" each call. See {@link ReadInstantMode}.\n   */\n  readInstant?: ReadInstantMode | undefined;\n  /** Equal-id behavior for historical identity traversal reconstruction. */\n  identitySameIdAcrossKinds?: \"fold\" | \"ignore\" | undefined;\n  /**\n   * Whether the active backend can compute a bounded transitive closure in\n   * one round trip. Defaults to {@link COMPILER_DEFAULT_RECURSIVE_TRAVERSAL}\n   * for direct compiler callers, mirroring `windowFunctions`.\n   */\n  recursiveTraversal?: RecursiveTraversalVerdict | undefined;\n}>;\n\n/**\n * Every key {@link CompileQueryOptions} declares, kept in sync with the type\n * by {@link Assert}<{@link Equal}> in `tests/compile-query-option-coverage.test.ts`\n * so a new option cannot be added to one without the other noticing.\n */\nexport const COMPILE_QUERY_OPTION_KEYS = [\n  \"dialect\",\n  \"schema\",\n  \"fulltextStrategy\",\n  \"vectorStrategy\",\n  \"windowFunctions\",\n  \"orderedAggregates\",\n  \"vectorSlots\",\n  \"fulltextLanguages\",\n  \"recordedReadBinding\",\n  \"readInstant\",\n  \"identitySameIdAcrossKinds\",\n  \"recursiveTraversal\",\n] as const;\n\n/**\n * The single sanctioned way to obtain a {@link RecursiveTraversalVerdict}\n * without a backend: `compileQuery`'s public entry point takes no backend at\n * all, so it has no capabilities to resolve a verdict from. This is the one\n * `assumeRecursiveTraversalSupported` call site in `src/**`.\n */\nexport const COMPILER_DEFAULT_RECURSIVE_TRAVERSAL =\n  assumeRecursiveTraversalSupported(\"compileQuery called without a backend\");\n\n/**\n * Compiles a query AST to SQL.\n *\n * This is the main entry point for query compilation. It dispatches to\n * the appropriate compiler based on the query type (standard, recursive,\n * or set operation).\n *\n * @param ast - The query AST to compile\n * @param graphId - The graph ID for filtering\n * @param options - Compilation options (dialect, schema)\n * @returns TypeGraph `SqlFragment` ready for backend execution\n *\n * @example\n * ```typescript\n * const ast = query.toAst();\n * const sql = compileQuery(ast, \"my_graph\", { dialect: \"postgres\" });\n * const results = await db.execute(sql);\n * ```\n *\n * @example\n * ```typescript\n * // With custom table names\n * const schema = createSqlSchema({ nodes: \"myapp_nodes\", edges: \"myapp_edges\" });\n * const sql = compileQuery(ast, \"my_graph\", { dialect: \"postgres\", schema });\n * ```\n */\nexport function compileQuery(\n  ast: QueryAst,\n  graphId: string,\n  options: CompileQueryOptions | SqlDialect = \"sqlite\",\n): CompiledSelectSql {\n  return compileQueryInExpressionContext(ast, graphId, options, {\n    aliasScopes: new Map(),\n    depth: 0,\n  });\n}\n\nfunction compileQueryInExpressionContext(\n  ast: QueryAst,\n  graphId: string,\n  options: CompileQueryOptions | SqlDialect,\n  expressionContext: Readonly<{\n    aliasScopes: ReadonlyMap<symbol, ExpressionAliasScope>;\n    depth: number;\n    recursiveResultAliases?: ReadonlyMap<symbol, string>;\n  }>,\n): CompiledSelectSql {\n  // Support legacy signature: compileQuery(ast, graphId, dialect)\n  const options_: CompileQueryOptions =\n    typeof options === \"string\" ? { dialect: options } : options;\n  const dialect = options_.dialect ?? \"sqlite\";\n  const baseSchema =\n    options_.schema === undefined ?\n      DEFAULT_SQL_SCHEMA\n    : requireSqlSchema(options_.schema, \"compileQuery schema\");\n  const schema = recordedReadSchemaFor(\n    baseSchema,\n    ast.recordedAsOf,\n    options_.recordedReadBinding,\n    \"recorded-query\",\n  );\n\n  const adapter = resolveDialectAdapter(dialect, options_.fulltextStrategy);\n  const expressionCompileDepth = expressionContext.depth;\n  const expressionAliasScopes = new Map(expressionContext.aliasScopes);\n  const recursiveResultAliases = new Map(\n    expressionContext.recursiveResultAliases,\n  );\n  const variableLength = hasVariableLengthTraversal(ast);\n  const loweredRecursive =\n    variableLength ? tryLowerSingleHopRecursiveTraversal(ast) : undefined;\n  const recursiveResultAlias =\n    variableLength && loweredRecursive === undefined ?\n      `__tg_recursive_result_${expressionCompileDepth}`\n    : undefined;\n  if (\n    ast.expressionScope !== undefined &&\n    !expressionAliasScopes.has(ast.expressionScope)\n  ) {\n    expressionAliasScopes.set(\n      ast.expressionScope,\n      new Map([\n        [ast.start.alias, ast.start.alias],\n        ...ast.traversals.flatMap(\n          (traversal) =>\n            [\n              [traversal.edgeAlias, traversal.nodeAlias],\n              [traversal.nodeAlias, traversal.nodeAlias],\n            ] as const,\n        ),\n      ]),\n    );\n  }\n  if (ast.expressionScope !== undefined && recursiveResultAlias !== undefined)\n    recursiveResultAliases.set(ast.expressionScope, recursiveResultAlias);\n  // Collects the ANN slot index types the emitter compiles engine-form\n  // branches for; a non-empty set brands the finished statement so the\n  // backend applies the pgvector iterative-scan GUCs around execution.\n  // (Sub-compiled correlated queries brand their own `SqlFragment` objects, which\n  // are embedded by text — an ANN branch inside a subquery therefore\n  // does not surface the brand; the inline vector predicate compiles at\n  // the top level, so this is theoretical today.)\n  const annIndexTypes = new Set<string>();\n  const ctx: PredicateCompilerContext = {\n    dialect: adapter,\n    schema,\n    annIndexTypes,\n    readInstant: options_.readInstant ?? \"literal\",\n    ...(options_.recordedReadBinding === undefined ?\n      {}\n    : { recordedReadBinding: options_.recordedReadBinding }),\n    identitySameIdAcrossKinds: options_.identitySameIdAcrossKinds ?? \"fold\",\n    compileQuery: (subAst, subGraphId) =>\n      compileQuery(\n        inheritRecordedAsOf(subAst, ast.recordedAsOf),\n        subGraphId,\n        propagateOptions(options_),\n      ),\n    compileExpressionSubquery(subAst) {\n      if (subAst.graphId === undefined)\n        throw new CompilerInvariantError(\n          \"Expression subquery is missing its graph identifier\",\n        );\n      const depth = expressionCompileDepth + 1;\n      const namespaced = namespaceExpressionSubquery(\n        subAst,\n        `__tg_sq_${depth}_`,\n      );\n      const scopes = new Map(expressionAliasScopes);\n      if (subAst.expressionScope !== undefined)\n        scopes.set(subAst.expressionScope, namespaced.aliases);\n      return compileQueryInExpressionContext(\n        namespaced.ast,\n        subAst.graphId,\n        propagateOptions(options_),\n        {\n          aliasScopes: scopes,\n          depth,\n          recursiveResultAliases,\n        },\n      );\n    },\n    compileExpressionOuterReference(\n      expression: DatabaseExpression,\n      outerScopeIdentity: symbol,\n    ) {\n      const aliases = expressionAliasScopes.get(outerScopeIdentity);\n      if (aliases === undefined || expression.node.kind !== \"field\")\n        throw new CompilerInvariantError(\n          \"Expression outer reference has no enclosing query scope\",\n        );\n      const recursiveResultAlias =\n        recursiveResultAliases.get(outerScopeIdentity);\n      const outerExpression =\n        recursiveResultAlias === undefined ? expression : (\n          {\n            ...expression,\n            node: {\n              ...expression.node,\n              field: {\n                ...expression.node.field,\n                alias:\n                  aliases.get(expression.node.field.alias) ??\n                  expression.node.field.alias,\n              },\n            },\n          }\n        );\n      return compileDatabaseExpression(outerExpression, {\n        dialect: adapter,\n        resolveFieldCteAlias: (field) =>\n          recursiveResultAlias ??\n          `cte_${aliases.get(field.alias) ?? field.alias}`,\n      });\n    },\n    ...(options_.vectorStrategy === undefined ?\n      {}\n    : { vectorStrategy: options_.vectorStrategy }),\n    windowFunctions: options_.windowFunctions ?? true,\n    orderedAggregates: options_.orderedAggregates ?? true,\n    recursiveTraversal:\n      options_.recursiveTraversal ?? COMPILER_DEFAULT_RECURSIVE_TRAVERSAL,\n    ...(recursiveResultAlias === undefined ? {} : { recursiveResultAlias }),\n    ...(options_.vectorSlots === undefined ?\n      {}\n    : { vectorSlots: options_.vectorSlots }),\n    ...(options_.fulltextLanguages === undefined ?\n      {}\n    : { fulltextLanguages: options_.fulltextLanguages }),\n  };\n\n  function finish(compiled: SqlFragment): CompiledSelectSql {\n    if (annIndexTypes.size > 0) {\n      markAnnIndexScan(compiled, [...annIndexTypes]);\n    }\n    return asCompiledSelectSql(compiled);\n  }\n\n  // Check for variable-length traversals\n  if (variableLength) {\n    if (loweredRecursive !== undefined) {\n      return finish(compileStandardQuery(loweredRecursive, graphId, ctx));\n    }\n    return finish(\n      ast.traversals.length > 1 || ast.traversals[0]?.optional === true ?\n        compileMultiStageRecursiveQuery(ast, graphId, ctx)\n      : compileVariableLengthQuery(ast, graphId, ctx),\n    );\n  }\n\n  // Standard query compilation\n  return finish(compileStandardQuery(ast, graphId, ctx));\n}\n\nfunction tryLowerSingleHopRecursiveTraversal(\n  ast: QueryAst,\n): QueryAst | undefined {\n  if (ast.traversals.length !== 1) {\n    return undefined;\n  }\n\n  const traversal = requireDefined(ast.traversals[0]);\n  const variableLength = traversal.variableLength;\n  if (!variableLength) {\n    return undefined;\n  }\n\n  if (variableLength.minDepth !== 1 || variableLength.maxDepth !== 1) {\n    return undefined;\n  }\n  if (\n    variableLength.pathAlias !== undefined ||\n    variableLength.depthAlias !== undefined ||\n    variableLength.stopExpansion !== undefined\n  ) {\n    return undefined;\n  }\n\n  const { variableLength: _vl, ...nonRecursiveTraversal } = traversal;\n\n  return {\n    ...ast,\n    traversals: [nonRecursiveTraversal],\n  };\n}\n\n/**\n * Compiles a set operation (UNION/INTERSECT/EXCEPT) to SQL.\n *\n * @param op - The set operation AST\n * @param graphId - The graph ID for filtering\n * @param options - Compilation options (dialect, schema)\n * @returns TypeGraph `SqlFragment`\n */\nexport function compileSetOperation(\n  op: SetOperation,\n  graphId: string,\n  options: CompileQueryOptions | SqlDialect = \"sqlite\",\n): CompiledSelectSql {\n  // Support legacy signature: compileSetOperation(op, graphId, dialect)\n  const options_: CompileQueryOptions =\n    typeof options === \"string\" ? { dialect: options } : options;\n  const dialect = options_.dialect ?? \"sqlite\";\n\n  const adapter = resolveDialectAdapter(dialect, options_.fulltextStrategy);\n  // Operand statements carry their own ANN brand, but the set-operation\n  // wrapper is a fresh `SqlFragment` object and the backend only inspects the\n  // object it executes — so operand brands are merged onto the final\n  // statement here, or a union with an approximate operand would skip\n  // the pgvector GUC wrapper.\n  const annIndexTypes = new Set<string>();\n  const compileOperand = (ast: QueryAst, gid: string): CompiledSelectSql => {\n    const compiled = compileQuery(ast, gid, propagateOptions(options_));\n    for (const indexType of annIndexScanTypes(compiled) ?? []) {\n      annIndexTypes.add(indexType);\n    }\n    return compiled;\n  };\n  // One statement, one \"current\" instant. Each operand compiles its own\n  // temporal filter, so without this pin an INTERSECT/EXCEPT could bind two\n  // clock samples microseconds apart and disagree about a row created between\n  // them.\n  const combined = withPinnedReadInstant(() =>\n    compileSetOp(op, graphId, adapter, compileOperand, options_.vectorStrategy),\n  );\n  if (annIndexTypes.size > 0) {\n    markAnnIndexScan(combined, [...annIndexTypes]);\n  }\n  return asCompiledSelectSql(combined);\n}\n\n/**\n * Builds the dialect adapter the compiler actually runs against,\n * applying a caller-supplied fulltext strategy override on top of the\n * dialect default. Returns the unmodified adapter when the override is\n * absent or identical to the dialect default — shipped backends always\n * set `fulltextStrategy`, so this short-circuit keeps the common path\n * from allocating a fresh adapter on every compile.\n *\n * `false` (a backend built with `fulltext: false`) is a third, distinct\n * signal from `undefined`: it declares no fulltext support at all, so a\n * `matches()` predicate hits the compiler's typed refusal instead of\n * falling back to the dialect's own default strategy and compiling SQL\n * against a table this backend never creates.\n */\nfunction resolveDialectAdapter(\n  dialect: SqlDialect,\n  fulltextStrategy: FulltextStrategy | false | undefined,\n): DialectAdapter {\n  const baseAdapter = getDialect(dialect);\n  if (fulltextStrategy === false) {\n    return {\n      ...baseAdapter,\n      capabilities: { ...baseAdapter.capabilities, supportsFulltext: false },\n      fulltext: undefined,\n    };\n  }\n  if (\n    fulltextStrategy === undefined ||\n    fulltextStrategy === baseAdapter.fulltext\n  ) {\n    return baseAdapter;\n  }\n  return { ...baseAdapter, fulltext: fulltextStrategy };\n}\n\n/**\n * Reconciles the enclosing query's recorded-time pin with an EXISTS/IN\n * subquery's so the whole statement reads one coordinate, never a silent mix\n * of recorded and live tables. Symmetric with the uniformity guard on set\n * operations ({@link assertUniformSetOperationRecordedCoordinates}):\n *\n * - **Recorded outer, unpinned subquery** — propagate the outer pin so the\n *   subquery reads the recorded relations as of the same instant (a subquery\n *   built from the live store carries none and would otherwise cross the axis\n *   and skip the current-index guard).\n * - **Recorded outer, differently-pinned subquery** — coordinate mismatch,\n *   rejected.\n * - **Live outer, recorded subquery** — also a mismatch: the subquery would\n *   read the recorded relations while the outer reads live tables. Rejected\n *   rather than silently honored, the same way the set-operation guard rejects\n *   a live ∪ recorded mix.\n */\nfunction inheritRecordedAsOf(\n  subAst: QueryAst,\n  recordedAsOf: string | undefined,\n): QueryAst {\n  if (recordedAsOf === undefined) {\n    if (subAst.recordedAsOf !== undefined) {\n      throw recordedSubqueryCoordinateMismatch(\n        \"Cannot nest a recorded-time subquery inside a live query without a recorded-time coordinate.\",\n      );\n    }\n    return subAst;\n  }\n  if (subAst.recordedAsOf === undefined) return { ...subAst, recordedAsOf };\n  if (subAst.recordedAsOf !== recordedAsOf) {\n    throw recordedSubqueryCoordinateMismatch(\n      \"Cannot nest a subquery with a different recorded-time coordinate than the enclosing query.\",\n    );\n  }\n  return subAst;\n}\n\nfunction recordedSubqueryCoordinateMismatch(\n  message: string,\n): ConfigurationError {\n  return new ConfigurationError(\n    message,\n    { code: \"SUBQUERY_TEMPORAL_COORDINATE_MISMATCH\" },\n    {\n      suggestion:\n        \"Build the subquery from the same Store or StoreView coordinate as the enclosing query.\",\n    },\n  );\n}\n\n/** Forwards compile options into recursive sub-compile calls. */\n/**\n * Forwards compile options into recursive sub-compile calls. Module-private\n * in every barrel — exported only so the T6 coverage test\n * (`tests/compile-query-option-coverage.test.ts`) can exercise it directly\n * against the same `CompileQueryOptions` keys the type declares.\n *\n * @internal\n */\nexport function propagateOptions(\n  options_: CompileQueryOptions,\n): CompileQueryOptions {\n  return {\n    dialect: options_.dialect ?? \"sqlite\",\n    ...(options_.schema === undefined ? {} : { schema: options_.schema }),\n    ...(options_.fulltextStrategy === undefined ?\n      {}\n    : { fulltextStrategy: options_.fulltextStrategy }),\n    ...(options_.vectorStrategy === undefined ?\n      {}\n    : { vectorStrategy: options_.vectorStrategy }),\n    windowFunctions: options_.windowFunctions ?? true,\n    orderedAggregates: options_.orderedAggregates ?? true,\n    recursiveTraversal:\n      options_.recursiveTraversal ?? COMPILER_DEFAULT_RECURSIVE_TRAVERSAL,\n    ...(options_.vectorSlots === undefined ?\n      {}\n    : { vectorSlots: options_.vectorSlots }),\n    ...(options_.fulltextLanguages === undefined ?\n      {}\n    : { fulltextLanguages: options_.fulltextLanguages }),\n    ...(options_.recordedReadBinding === undefined ?\n      {}\n    : { recordedReadBinding: options_.recordedReadBinding }),\n    ...(options_.readInstant === undefined ?\n      {}\n    : { readInstant: options_.readInstant }),\n    ...(options_.identitySameIdAcrossKinds === undefined ?\n      {}\n    : {\n        identitySameIdAcrossKinds: options_.identitySameIdAcrossKinds,\n      }),\n  };\n}\n\n// ============================================================\n// Standard Query Compilation\n// ============================================================\n\ntype CountAggregateFastPathPlan = Readonly<{\n  traversal: QueryAst[\"traversals\"][number];\n  /** Aggregate references `traversal.nodeAlias` (count of live target nodes). */\n  requiresNodeCount: boolean;\n  /** countDistinct over `traversal.nodeAlias`. */\n  requiresNodeCountDistinct: boolean;\n  /** Aggregate references `traversal.edgeAlias` (count of live edges). */\n  requiresEdgeCount: boolean;\n  /** countDistinct over `traversal.edgeAlias`. */\n  requiresEdgeCountDistinct: boolean;\n}>;\n\nfunction resolveCountAggregateFastPath(\n  ast: QueryAst,\n): CountAggregateFastPathPlan | undefined {\n  if (ast.traversals.length !== 1) {\n    return undefined;\n  }\n\n  if (ast.groupBy?.fields.length !== 1) {\n    return undefined;\n  }\n\n  if (ast.having !== undefined) {\n    return undefined;\n  }\n\n  if (\n    ast.orderBy?.some(\n      (orderSpec) =>\n        orderSpec.field.__type !== \"field_ref\" ||\n        orderSpec.field.alias !== ast.start.alias,\n    )\n  ) {\n    return undefined;\n  }\n\n  const traversal = requireDefined(ast.traversals[0]);\n  if ((traversal.inverseEdgeKinds?.length ?? 0) > 0) {\n    return undefined;\n  }\n\n  const groupField = requireDefined(ast.groupBy.fields[0]);\n  if (\n    groupField.__type !== \"field_ref\" ||\n    groupField.alias !== ast.start.alias ||\n    !isIdFieldRef(groupField)\n  ) {\n    return undefined;\n  }\n\n  let requiresNodeCount = false;\n  let requiresNodeCountDistinct = false;\n  let requiresEdgeCount = false;\n  let requiresEdgeCountDistinct = false;\n\n  for (const projectedField of ast.projection.fields) {\n    const source = projectedField.source;\n\n    if (source.__type === \"database_expression\") return undefined;\n\n    if (!isAggregateExpr(source)) {\n      if (source.alias !== ast.start.alias) {\n        return undefined;\n      }\n      continue;\n    }\n\n    if (!isIdFieldRef(source.field)) {\n      return undefined;\n    }\n\n    const isNodeTarget = source.field.alias === traversal.nodeAlias;\n    const isEdgeTarget = source.field.alias === traversal.edgeAlias;\n    if (!isNodeTarget && !isEdgeTarget) {\n      return undefined;\n    }\n\n    if (source.function === \"count\") {\n      if (isNodeTarget) requiresNodeCount = true;\n      else requiresEdgeCount = true;\n      continue;\n    }\n\n    if (source.function === \"countDistinct\") {\n      if (isNodeTarget) requiresNodeCountDistinct = true;\n      else requiresEdgeCountDistinct = true;\n      continue;\n    }\n\n    return undefined;\n  }\n\n  if (\n    !requiresNodeCount &&\n    !requiresNodeCountDistinct &&\n    !requiresEdgeCount &&\n    !requiresEdgeCountDistinct\n  ) {\n    return undefined;\n  }\n\n  return {\n    traversal,\n    requiresNodeCount,\n    requiresNodeCountDistinct,\n    requiresEdgeCount,\n    requiresEdgeCountDistinct,\n  };\n}\n\nfunction compileCountAggregateFastPath(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  logicalPlan: LogicalPlan,\n  requiredColumnsByAlias: RequiredColumnsByAlias | undefined,\n  predicateIndex: PredicateIndex,\n  temporalFilterPass: TemporalFilterPass,\n): SqlFragment | undefined {\n  if (\n    ast.traversals.some(\n      (traversal) => traversal.includeIdentityMembers === true,\n    )\n  ) {\n    return undefined;\n  }\n  // Preaggregated traversal counts cannot evaluate completed row predicates.\n  if (ast.resultPredicate !== undefined) return undefined;\n  const plan = resolveCountAggregateFastPath(ast);\n  if (!plan) {\n    return undefined;\n  }\n\n  const {\n    traversal,\n    requiresNodeCount,\n    requiresNodeCountDistinct,\n    requiresEdgeCount,\n    requiresEdgeCountDistinct,\n  } = plan;\n  const { dialect } = ctx;\n  const startAlias = ast.start.alias;\n  const previousAlias = traversal.joinFromAlias;\n  const previousAliasIdColumn = `${previousAlias}_id`;\n  const previousAliasKindColumn = `${previousAlias}_kind`;\n  const countCteAlias = `cte_${traversal.nodeAlias}_counts`;\n  const nodeCountColumn = `${traversal.nodeAlias}_count`;\n  const nodeCountDistinctColumn = `${traversal.nodeAlias}_count_distinct`;\n  const edgeCountColumn = `${traversal.edgeAlias}_count`;\n  const edgeCountDistinctColumn = `${traversal.edgeAlias}_count_distinct`;\n\n  const previousNodeKinds = getNodeKindsForAlias(ast, traversal.joinFromAlias);\n  const edgeKinds = [...new Set(traversal.edgeKinds)];\n  const nodeKinds = traversal.nodeKinds;\n\n  const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n  const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n  const nodePredicateContext: PredicateCompilerContext = {\n    ...ctx,\n    cteColumnPrefix: \"n\",\n  };\n  const nodePredicateClauses = compilePredicateClauses(\n    getPredicatesForAlias(predicateIndex, traversal.nodeAlias, \"node\"),\n    nodePredicateContext,\n  );\n\n  const edgePredicateContext: PredicateCompilerContext = {\n    ...ctx,\n    cteColumnPrefix: \"e\",\n  };\n  const edgePredicateClauses = compilePredicateClauses(\n    getPredicatesForAlias(predicateIndex, traversal.edgeAlias, \"edge\"),\n    edgePredicateContext,\n  );\n\n  const joinField = traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n  const targetField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n  const joinKindField = traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n  const targetKindField =\n    traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n  // The target-node join is only needed when an aggregate actually counts\n  // live target nodes. For edge-only counts (countEdges / countDistinctEdges)\n  // the edge row alone is sufficient: the edge's own deleted_at and valid_*\n  // columns already constrain \"live edge,\" and target-kind validation is\n  // enforced via the edge's to_kind filter (which the store's write path\n  // keeps consistent with the target node's kind at insert time).\n  const hasNodePredicates = nodePredicateClauses.length > 0;\n  const requiresNodeJoin =\n    requiresNodeCount || requiresNodeCountDistinct || hasNodePredicates;\n\n  // Join style depends on how the target-node join interacts with the\n  // aggregates:\n  //\n  // - INNER JOIN when the user applied a predicate to the target alias\n  //   (whereNode on the target). Predicates should constrain every\n  //   aggregate in the query — including countEdges — so they live in\n  //   WHERE and the JOIN filters edges whose targets fail to match.\n  //   With INNER JOIN, a group where every edge's target fails the\n  //   predicate produces no rows; GROUP BY omits it, and required\n  //   traversals correctly drop that start row.\n  //\n  // - LEFT JOIN when only temporal/deleted filters apply (no caller\n  //   predicates). This lets mixed aggregates differ: countEdges\n  //   counts all live edges (including edges to expired targets)\n  //   while count(target) only counts edges to live targets.\n  const useInnerJoin = hasNodePredicates;\n\n  const whereClauses = [\n    sql`e.graph_id = ${graphId}`,\n    compileKindFilter(sql.raw(\"e.kind\"), edgeKinds),\n    compileKindFilter(sql.raw(`e.${joinKindField}`), previousNodeKinds),\n    compileKindFilter(sql.raw(`e.${targetKindField}`), nodeKinds),\n    edgeTemporalFilter,\n    ...edgePredicateClauses,\n    // INNER JOIN mode: node-side filters in WHERE constrain every aggregate.\n    ...(requiresNodeJoin && useInnerJoin ?\n      [\n        compileKindFilter(sql.raw(\"n.kind\"), nodeKinds),\n        nodeTemporalFilter,\n        ...nodePredicateClauses,\n      ]\n    : []),\n  ];\n\n  const nodeJoinOnClauses =\n    requiresNodeJoin ?\n      useInnerJoin ?\n        // INNER JOIN: only the key conditions; filters live in WHERE.\n        [\n          sql`n.graph_id = e.graph_id`,\n          sql`n.id = e.${sql.raw(targetField)}`,\n          sql`n.kind = e.${sql.raw(targetKindField)}`,\n        ]\n        // LEFT JOIN: temporal/kind filters gate the join, so countEdges\n        // still sees the full edge set while count(target) excludes edges\n        // to expired targets (via COUNT ignoring NULLs).\n      : [\n          sql`n.graph_id = e.graph_id`,\n          sql`n.id = e.${sql.raw(targetField)}`,\n          sql`n.kind = e.${sql.raw(targetKindField)}`,\n          compileKindFilter(sql.raw(\"n.kind\"), nodeKinds),\n          nodeTemporalFilter,\n        ]\n    : [];\n\n  const aggregateColumns: SqlFragment[] = [];\n  if (requiresNodeCount) {\n    aggregateColumns.push(sql`COUNT(n.id) AS ${sql.raw(nodeCountColumn)}`);\n  }\n  if (requiresNodeCountDistinct) {\n    aggregateColumns.push(\n      sql`COUNT(DISTINCT n.id) AS ${sql.raw(nodeCountDistinctColumn)}`,\n    );\n  }\n  if (requiresEdgeCount) {\n    aggregateColumns.push(sql`COUNT(e.id) AS ${sql.raw(edgeCountColumn)}`);\n  }\n  if (requiresEdgeCountDistinct) {\n    aggregateColumns.push(\n      sql`COUNT(DISTINCT e.id) AS ${sql.raw(edgeCountDistinctColumn)}`,\n    );\n  }\n\n  // LIMIT push-down: when the outer SELECT applies LIMIT/OFFSET that do not\n  // depend on aggregate results, we can reduce the start CTE to just the\n  // required rows before aggregation. This turns an O(|start|) GROUP BY\n  // into an O(limit) GROUP BY.\n  //\n  // Safe when:\n  //   - The traversal is optional (LEFT JOIN outer). For INNER JOIN we can't\n  //     push down without potentially dropping rows the original query would\n  //     have kept.\n  //   - No ORDER BY of either kind. ORDER BY over the full result requires\n  //     the full result. `ast.orderBy` is FieldRef-based row ordering (the\n  //     fast path already restricts it to the start alias, but we still\n  //     need every row to sort correctly); `ast.aggregateOrderBy` is\n  //     output-alias-based ordering added via `ExecutableAggregateQuery\n  //     .orderBy()` — sorting by an aggregate value (e.g. `employeeCount`)\n  //     needs every start row counted first, so pushing LIMIT into the\n  //     start CTE before aggregation would pick an arbitrary subset of\n  //     rows to count rather than the true top-N.\n  //   - LIMIT is defined. OFFSET is carried with it.\n  const startCteLimit =\n    (\n      traversal.optional &&\n      ast.orderBy === undefined &&\n      ast.aggregateOrderBy === undefined &&\n      ast.limit !== undefined\n    ) ?\n      { limit: ast.limit, offset: ast.offset }\n    : undefined;\n\n  const startCte = buildStandardStartCte({\n    ast,\n    ctx,\n    graphId,\n    predicateIndex,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    ...(startCteLimit === undefined ? {} : { limitOffset: startCteLimit }),\n  });\n\n  const targetNodeJoinKeyword = useInnerJoin ? \"JOIN\" : \"LEFT JOIN\";\n  const targetNodeJoin =\n    requiresNodeJoin ?\n      sql`\n        ${sql.raw(targetNodeJoinKeyword)} ${ctx.schema.nodesTable} n ON ${sql.join(nodeJoinOnClauses, sql` AND `)}\n      `\n    : sql``;\n\n  const countCte = sql`\n    ${sql.raw(countCteAlias)} AS (\n      SELECT\n        cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)} AS ${sql.raw(previousAliasIdColumn)},\n        cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)} AS ${sql.raw(previousAliasKindColumn)},\n        ${sql.join(aggregateColumns, sql`, `)}\n      FROM cte_${sql.raw(previousAlias)}\n      JOIN ${ctx.schema.edgesTable} e ON cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)} = e.${sql.raw(joinField)}\n        AND cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)} = e.${sql.raw(joinKindField)}${targetNodeJoin}\n      WHERE ${sql.join(whereClauses, sql` AND `)}\n      GROUP BY\n        cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)},\n        cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)}\n    )\n  `;\n\n  function resolveCountColumn(source: AggregateExpr): string {\n    const isEdge = source.field.alias === traversal.edgeAlias;\n    if (source.function === \"countDistinct\") {\n      return isEdge ? edgeCountDistinctColumn : nodeCountDistinctColumn;\n    }\n    return isEdge ? edgeCountColumn : nodeCountColumn;\n  }\n\n  const projection = sql.join(\n    ast.projection.fields.map((projectedField) => {\n      const source = projectedField.source;\n\n      if (source.__type === \"database_expression\") {\n        throw new CompilerInvariantError(\n          \"Count aggregate fast path cannot compile database expressions\",\n        );\n      }\n\n      if (!isAggregateExpr(source)) {\n        const value = compileFieldValue(\n          source,\n          dialect,\n          source.valueType,\n          `cte_${source.alias}`,\n        );\n        return sql`${value} AS ${quoteIdentifier(projectedField.outputName)}`;\n      }\n\n      const projectedCountColumn = resolveCountColumn(source);\n      const countValue = sql`${sql.raw(countCteAlias)}.${sql.raw(projectedCountColumn)}`;\n      const aggregateValue =\n        traversal.optional ? sql`COALESCE(${countValue}, 0)` : countValue;\n\n      return sql`${aggregateValue} AS ${quoteIdentifier(projectedField.outputName)}`;\n    }),\n    sql`, `,\n  );\n\n  const joinType = traversal.optional ? \"LEFT JOIN\" : \"INNER JOIN\";\n  const fromClause = sql`\n    FROM cte_${sql.raw(startAlias)}\n    ${sql.raw(joinType)} ${sql.raw(countCteAlias)}\n      ON ${sql.raw(countCteAlias)}.${sql.raw(previousAliasIdColumn)} = cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)}\n      AND ${sql.raw(countCteAlias)}.${sql.raw(previousAliasKindColumn)} = cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)}\n  `;\n\n  // Also picks up `ast.aggregateOrderBy` (ORDER BY output-alias entries\n  // added via `ExecutableAggregateQuery.orderBy()`) with no extra handling\n  // here: the fast path's projection above always re-aliases every\n  // projected column to its final output name, so an alias reference\n  // resolves the same way it would on the general query path.\n  const orderBy = buildStandardOrderBy({ ast, dialect });\n  // When the LIMIT/OFFSET was pushed into the start CTE, the outer SELECT\n  // must not re-apply it — the start CTE already produced exactly the\n  // requested page, and the outer LEFT JOIN preserves its cardinality.\n  // Re-applying would double-offset and produce an empty page. Rewrite\n  // the logical plan to match: the emitter asserts plan shape aligns\n  // with emitted SQL, so dropping the clause and leaving the plan's\n  // `limit_offset` node behind would trip an invariant.\n  const emittedLogicalPlan =\n    startCteLimit === undefined ? logicalPlan : (\n      stripLimitOffsetFromPlan(logicalPlan)\n    );\n  const limitOffset =\n    startCteLimit === undefined ?\n      buildLimitOffsetClause({ limit: ast.limit, offset: ast.offset, dialect })\n    : undefined;\n\n  return emitStandardQuerySql({\n    ctes: [startCte, countCte],\n    fromClause,\n    ...(orderBy === undefined ? {} : { orderBy }),\n    ...(limitOffset === undefined ? {} : { limitOffset }),\n    logicalPlan: emittedLogicalPlan,\n    projection,\n  });\n}\n\n/**\n * Returns a copy of the logical plan with every `limit_offset` node\n * elided. Used when the count aggregate fast path pushes LIMIT/OFFSET\n * into the start CTE — the outer SELECT then carries no LIMIT/OFFSET,\n * so the logical plan must not either or the emitter invariant check\n * will disagree with the emitted SQL.\n */\nfunction stripLimitOffsetFromPlan(plan: LogicalPlan): LogicalPlan {\n  return { ...plan, root: stripLimitOffsetFromPlanNode(plan.root) };\n}\n\nfunction stripLimitOffsetFromPlanNode(node: LogicalPlanNode): LogicalPlanNode {\n  if (node.op === \"limit_offset\") {\n    return stripLimitOffsetFromPlanNode(node.input);\n  }\n  if (\"input\" in node) {\n    return { ...node, input: stripLimitOffsetFromPlanNode(node.input) };\n  }\n  return node;\n}\n\n/**\n * The identity-class relation (when the query needs one), the start\n * CTE, then one CTE per traversal — the candidate-set prefix shared by the flat\n * plan and the late-materialization plan (which feeds it a lean AST/column set\n * and no per-traversal limit).\n */\nfunction buildStandardStartAndTraversalCtes(\n  input: Readonly<{\n    ast: QueryAst;\n    carryForwardPreviousColumns: boolean;\n    ctx: PredicateCompilerContext;\n    graphId: string;\n    predicateIndex: PredicateIndex;\n    requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n    temporalFilterPass: TemporalFilterPass;\n    traversalLimit: number | undefined;\n  }>,\n): SqlFragment[] {\n  const {\n    ast,\n    carryForwardPreviousColumns,\n    ctx,\n    graphId,\n    predicateIndex,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    traversalLimit,\n  } = input;\n  const identityClassCte = compileIdentityClassCte({\n    ast,\n    ctx,\n    graphId,\n    temporalFilterPass,\n  });\n  const ctes: SqlFragment[] = [\n    ...(identityClassCte === undefined ? [] : [identityClassCte]),\n    buildStandardStartCte({\n      ast,\n      ctx,\n      graphId,\n      predicateIndex,\n      requiredColumnsByAlias,\n      temporalFilterPass,\n    }),\n  ];\n  for (let index = 0; index < ast.traversals.length; index++) {\n    ctes.push(\n      buildStandardTraversalCte({\n        ast,\n        carryForwardPreviousColumns,\n        ctx,\n        graphId,\n        materializeCte: shouldMaterializeTraversalCte(\n          ctx.dialect,\n          ast.traversals.length,\n          index,\n        ),\n        predicateIndex,\n        requiredColumnsByAlias,\n        temporalFilterPass,\n        traversalIndex: index,\n        traversalLimit,\n      }),\n    );\n  }\n  return ctes;\n}\n\ntype LateMaterializationPlan = Readonly<{\n  leanAst: QueryAst;\n  limit: number;\n  offset: number | undefined;\n}>;\n\n/**\n * A selective field that resolves to a node's identity (`id`/`kind`) — already\n * carried in the topK CTE, so it needs no deferred re-fetch.\n */\nfunction selectiveFieldIsIdentity(field: SelectiveField): boolean {\n  if (!field.isSystemField) {\n    return false;\n  }\n  const column = mapSelectiveSystemFieldToColumn(field.field);\n  return column === \"id\" || column === \"kind\";\n}\n\n/**\n * Decides whether a query is eligible for late materialization and, if so,\n * produces the lean AST whose CTEs carry only identity, ordering, and predicate\n * columns. Returns undefined (fall back to the flat plan) for anything outside\n * the v1 envelope — see the inline gates.\n */\nfunction resolveLateMaterializationPlan(\n  ast: QueryAst,\n): LateMaterializationPlan | undefined {\n  // Recorded-time reads swap `ctx.schema.nodesTable` to the recorded history\n  // relation (see `recordedReadSchemaFor`), where `(graph_id, kind, id)` is\n  // NOT unique — one row per recorded interval. The outer re-fetch joins on\n  // exactly that key with no temporal predicate, so it would match every\n  // historical version of each survivor (duplicate rows, stale props).\n  if (ast.recordedAsOf !== undefined) {\n    return undefined;\n  }\n\n  // v1 targets the selective `.select()` path. The non-selective path would\n  // have to carry the full `props` blob into the lean CTE to order by a prop,\n  // which defeats the deferral — left to a follow-up.\n  const selectiveFields = ast.selectiveFields;\n  if (selectiveFields === undefined || selectiveFields.length === 0) {\n    return undefined;\n  }\n\n  // The transform only pays off when rows past the LIMIT are discarded before\n  // their deferred columns are materialized — so both ORDER BY and a positive\n  // LIMIT must be present.\n  const orderBy = ast.orderBy;\n  if (orderBy === undefined || orderBy.length === 0) {\n    return undefined;\n  }\n  if (ast.limit === undefined || ast.limit <= 0) {\n    return undefined;\n  }\n\n  // Aggregation owns the count fast path / group-by shape, not this transform.\n  if (ast.groupBy !== undefined || ast.having !== undefined) {\n    return undefined;\n  }\n  if (ast.aggregateOrderBy !== undefined && ast.aggregateOrderBy.length > 0) {\n    return undefined;\n  }\n\n  // Optional (LEFT JOIN) traversals yield NULL-identity candidate rows that the\n  // outer identity re-join would drop. Out of v1 scope.\n  if (ast.traversals.some((traversal) => traversal.optional)) {\n    return undefined;\n  }\n\n  const nodeAliases = new Set<string>([\n    ast.start.alias,\n    ...ast.traversals.map((traversal) => traversal.nodeAlias),\n  ]);\n\n  // Every projected and ordered field must resolve to a node alias — edge\n  // fields live in the traversal CTE keyed differently, a follow-up.\n  for (const field of selectiveFields) {\n    if (!nodeAliases.has(field.alias)) {\n      return undefined;\n    }\n  }\n  for (const orderSpec of orderBy) {\n    if (\n      orderSpec.field.__type !== \"field_ref\" ||\n      !nodeAliases.has(orderSpec.field.alias)\n    ) {\n      return undefined;\n    }\n  }\n\n  // Sort-key props fields must stay in the lean CTE so the topK can order by\n  // them; everything else non-identity is deferred to the outer re-fetch.\n  const orderReferenced = new Set<SelectiveField>();\n  for (const orderSpec of orderBy) {\n    if (orderSpec.field.__type !== \"field_ref\") return undefined;\n    const matched = findSelectivePropsFieldForFieldRef(\n      selectiveFields,\n      orderSpec.field,\n    );\n    if (matched !== undefined) {\n      orderReferenced.add(matched);\n    }\n  }\n\n  // Worth doing only if some projected column is genuinely deferrable: a\n  // non-identity field that isn't already carried as a sort key.\n  const hasDeferredColumn = selectiveFields.some(\n    (field) => !selectiveFieldIsIdentity(field) && !orderReferenced.has(field),\n  );\n  if (!hasDeferredColumn) {\n    return undefined;\n  }\n\n  const prunedSelectiveFields = selectiveFields.filter(\n    (field) => field.isSystemField || orderReferenced.has(field),\n  );\n\n  return {\n    leanAst: { ...ast, selectiveFields: prunedSelectiveFields },\n    limit: ast.limit,\n    offset: ast.offset,\n  };\n}\n\n/**\n * The outer FROM clause: the topK CTE joined to the physical node table for each\n * projected alias, keyed on `(graph_id, kind, id)`. Sound only because that key\n * is the live nodes PK (one row per identity, the exact row the topK already\n * validated for temporal/soft-delete visibility). Recorded-time reads are gated\n * out in `resolveLateMaterializationPlan` — under a recorded pin `nodesTable`\n * is the history relation where this key matches every version.\n */\nfunction buildLateMaterializedOuterFromClause(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const topk = sql.raw(LATE_MAT_TOPK_CTE_ALIAS);\n  const joins = lateMaterializedProjectedNodeAliases(ast).map((alias) => {\n    const physical = sql.raw(lateMaterializedPhysicalAlias(alias));\n    return sql`JOIN ${ctx.schema.nodesTable} ${physical} ON ${physical}.graph_id = ${graphId} AND ${physical}.kind = ${topk}.${sql.raw(`${alias}_kind`)} AND ${physical}.id = ${topk}.${sql.raw(`${alias}_id`)}`;\n  });\n  return joins.length === 0 ?\n      sql`FROM ${topk}`\n    : sql`FROM ${topk} ${sql.join(joins, sql` `)}`;\n}\n\nfunction compileLateMaterializedQuery(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n  logicalPlan: LogicalPlan,\n  predicateIndex: PredicateIndex,\n  temporalFilterPass: TemporalFilterPass,\n  collapsedTraversalCteAlias: string | undefined,\n  shouldCollapseSelectiveTraversalRowset: boolean,\n): SqlFragment | undefined {\n  const plan = resolveLateMaterializationPlan(ast);\n  if (plan === undefined) {\n    return undefined;\n  }\n\n  const { leanAst, limit, offset } = plan;\n  const { dialect } = ctx;\n  const leanRequiredColumns = collectRequiredColumnsByAlias(leanAst, {\n    includeProjection: false,\n  });\n\n  const ctes = buildStandardStartAndTraversalCtes({\n    ast: leanAst,\n    carryForwardPreviousColumns: shouldCollapseSelectiveTraversalRowset,\n    ctx,\n    graphId,\n    predicateIndex,\n    requiredColumnsByAlias: leanRequiredColumns,\n    temporalFilterPass,\n    traversalLimit: undefined,\n  });\n  const where = buildStandardResultWhere({ ast: leanAst, ctx });\n  ctes.push(\n    buildLateMaterializedTopKCte({\n      ...(where === undefined ? {} : { where }),\n      ast: leanAst,\n      dialect,\n      fromClause: buildStandardFromClause({\n        ast: leanAst,\n        ...(collapsedTraversalCteAlias === undefined ?\n          {}\n        : { collapsedTraversalCteAlias }),\n      }),\n      limit,\n      offset,\n      ...(collapsedTraversalCteAlias === undefined ?\n        {}\n      : { collapsedTraversalCteAlias }),\n    }),\n  );\n\n  const orderBy = buildLateMaterializedOuterOrderBy(ast);\n  return emitStandardQuerySql({\n    ctes,\n    fromClause: buildLateMaterializedOuterFromClause(ast, graphId, ctx),\n    ...(orderBy === undefined ? {} : { orderBy }),\n    logicalPlan: stripLimitOffsetFromPlan(logicalPlan),\n    projection: buildLateMaterializedOuterProjection(ast, dialect),\n  });\n}\n\n/**\n * Compiles a standard (non-recursive) query to SQL using CTEs.\n */\ntype StandardQueryStrategyHandler = (\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n) => SqlFragment;\n\nconst STANDARD_QUERY_STRATEGY_HANDLERS: Record<\n  DialectStandardQueryStrategy,\n  StandardQueryStrategyHandler\n> = {\n  cte_project: compileStandardQueryWithCteStrategy,\n};\n\nfunction compileStandardQuery(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const strategy = ctx.dialect.capabilities.standardQueryStrategy;\n  const handler = STANDARD_QUERY_STRATEGY_HANDLERS[strategy];\n  return handler(ast, graphId, ctx);\n}\n\ntype SelectStandardOrderByInput = Readonly<{\n  ast: QueryAst;\n  collapsedTraversalCteAlias: string | undefined;\n  dialect: DialectAdapter;\n  fulltextPredicate: FulltextMatchPredicate | undefined;\n  fusion: HybridFusionOptions | undefined;\n  vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\nfunction selectStandardOrderBy(\n  input: SelectStandardOrderByInput,\n): SqlFragment | undefined {\n  const {\n    ast,\n    collapsedTraversalCteAlias,\n    dialect,\n    fulltextPredicate,\n    fusion,\n    vectorPredicate,\n  } = input;\n  if (vectorPredicate && fulltextPredicate) {\n    return buildStandardHybridRrfOrderBy({ ast, dialect, fusion });\n  }\n  if (vectorPredicate) {\n    return buildStandardVectorOrderBy({ ast, dialect });\n  }\n  if (fulltextPredicate) {\n    return buildStandardFulltextOrderBy({ ast, dialect });\n  }\n  return buildStandardOrderBy({\n    ast,\n    ...(collapsedTraversalCteAlias === undefined ?\n      {}\n    : { collapsedTraversalCteAlias }),\n    dialect,\n  });\n}\n\nfunction selectWindowFunctionOperation(\n  vectorPredicate: VectorSimilarityPredicate | undefined,\n  fulltextPredicate: FulltextMatchPredicate | undefined,\n): string {\n  if (vectorPredicate !== undefined && fulltextPredicate !== undefined) {\n    return \"hybrid relevance ranking\";\n  }\n  if (vectorPredicate !== undefined) return \"vector relevance ranking\";\n  return \"fulltext relevance ranking\";\n}\n\nfunction assertWindowFunctionsSupported(\n  ctx: PredicateCompilerContext,\n  operation: string,\n): void {\n  if (ctx.windowFunctions) return;\n\n  throw new ConfigurationError(\n    `${operation} requires SQL window functions, but this backend profile declares windowFunctions: false.`,\n    {\n      capability: \"windowFunctions\",\n      operation,\n      windowFunctions: false,\n    },\n    {\n      suggestion:\n        \"Use a backend profile that supports SQL window functions, or avoid this query shape.\",\n    },\n  );\n}\n\nfunction compileStandardQueryWithCteStrategy(\n  ast: QueryAst,\n  graphId: string,\n  ctx: PredicateCompilerContext,\n): SqlFragment {\n  const { dialect } = ctx;\n  const {\n    collapsedTraversalCteAlias,\n    effectiveLimit,\n    fulltextPredicate,\n    fusion,\n    logicalPlan,\n    predicateIndex,\n    requiredColumnsByAlias,\n    shouldCollapseSelectiveTraversalRowset,\n    temporalFilterPass,\n    traversalCteLimit,\n    vectorPredicate,\n  } = runStandardQueryPassPipeline(ast, graphId, ctx);\n\n  if (temporalFilterPass === undefined) {\n    throw new CompilerInvariantError(\n      \"Temporal filter pass did not initialize temporal state\",\n      { phase: \"standard-pass-pipeline\" },\n    );\n  }\n  if (logicalPlan === undefined) {\n    throw new CompilerInvariantError(\n      \"Logical plan pass did not initialize plan state\",\n      { phase: \"standard-pass-pipeline\" },\n    );\n  }\n\n  if (vectorPredicate !== undefined || fulltextPredicate !== undefined) {\n    assertWindowFunctionsSupported(\n      ctx,\n      selectWindowFunctionOperation(vectorPredicate, fulltextPredicate),\n    );\n  }\n\n  if (!vectorPredicate && !fulltextPredicate) {\n    const fastPathSql = compileCountAggregateFastPath(\n      ast,\n      graphId,\n      ctx,\n      logicalPlan,\n      requiredColumnsByAlias,\n      predicateIndex,\n      temporalFilterPass,\n    );\n    if (fastPathSql) {\n      return fastPathSql;\n    }\n\n    const lateMaterializedSql = compileLateMaterializedQuery(\n      ast,\n      graphId,\n      ctx,\n      logicalPlan,\n      predicateIndex,\n      temporalFilterPass,\n      collapsedTraversalCteAlias,\n      shouldCollapseSelectiveTraversalRowset,\n    );\n    if (lateMaterializedSql) {\n      return lateMaterializedSql;\n    }\n  }\n\n  // Start + traversal candidate CTEs\n  const ctes = buildStandardStartAndTraversalCtes({\n    ast,\n    carryForwardPreviousColumns: shouldCollapseSelectiveTraversalRowset,\n    ctx,\n    graphId,\n    predicateIndex,\n    requiredColumnsByAlias,\n    temporalFilterPass,\n    traversalLimit: traversalCteLimit,\n  });\n\n  // Add embeddings CTE if vector similarity is used\n  if (vectorPredicate) {\n    const nodeKinds = getNodeKindsForAlias(ast, vectorPredicate.field.alias);\n    ctes.push(\n      buildStandardEmbeddingsCte({\n        ctx,\n        graphId,\n        nodeKinds,\n        vectorPredicate,\n      }),\n    );\n  }\n\n  // Add fulltext CTE if a matches() predicate is used\n  if (fulltextPredicate) {\n    const nodeKinds = getNodeKindsForAlias(ast, fulltextPredicate.field.alias);\n    ctes.push(\n      buildStandardFulltextCte({\n        ctx,\n        fulltextPredicate,\n        graphId,\n        nodeKinds,\n      }),\n    );\n  }\n\n  if (getHybridTargetAlias(vectorPredicate, fulltextPredicate) !== undefined) {\n    ctes.push(buildStandardHybridCandidateCte());\n  }\n\n  // Build main SELECT\n  const projection = buildStandardProjection({\n    ast,\n    ...(collapsedTraversalCteAlias === undefined ?\n      {}\n    : { collapsedTraversalCteAlias }),\n    ctx,\n  });\n  const fromClause = buildStandardFromClause({\n    ast,\n    ...(collapsedTraversalCteAlias === undefined ?\n      {}\n    : { collapsedTraversalCteAlias }),\n    ...(vectorPredicate === undefined ? {} : { vectorPredicate }),\n    ...(fulltextPredicate === undefined ? {} : { fulltextPredicate }),\n  });\n  const where = buildStandardResultWhere({ ast, ctx });\n  const groupBy = buildStandardGroupBy({ ast, dialect });\n  const having = buildStandardHaving({ ast, ctx });\n\n  const orderBy = selectStandardOrderBy({\n    ast,\n    collapsedTraversalCteAlias,\n    dialect,\n    fulltextPredicate,\n    fusion,\n    vectorPredicate,\n  });\n\n  const limitOffset = buildLimitOffsetClause({\n    limit: effectiveLimit,\n    offset: ast.offset,\n    dialect,\n  });\n\n  return emitStandardQuerySql({\n    ctes,\n    fromClause,\n    ...(where === undefined ? {} : { where }),\n    ...(groupBy === undefined ? {} : { groupBy }),\n    ...(having === undefined ? {} : { having }),\n    ...(orderBy === undefined ? {} : { orderBy }),\n    ...(limitOffset === undefined ? {} : { limitOffset }),\n    logicalPlan,\n    projection,\n  });\n}\n","/**\n * Result mapping utilities for query execution.\n *\n * Transforms raw database rows into typed SelectContext and result objects.\n */\nimport {\n  normalizeRequiredRowTimestamp,\n  normalizeRowTimestamp,\n} from \"../../backend/row-mappers\";\nimport { type NodeType } from \"../../core/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { normalizePath } from \"../../utils\";\nimport { createDataKeyedBag } from \"../../utils/object\";\nimport { stripIdentityPathTokens } from \"../../utils/path\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { type Traversal } from \"../ast\";\nimport type {\n  AliasMap,\n  EdgeAliasMap,\n  QualifiedRecursivePath,\n  QueryBuilderState,\n  RecursiveAliasMap,\n  SelectableEdge,\n  SelectableNode,\n  SelectContext,\n} from \"../builder/types\";\nimport { type SqlDialect } from \"../dialect/types\";\n\n/**\n * A variable-length traversal's path column, plus whether its tokens carry the\n * identity-expansion `kind || SEP || id` wrapper the compiler emits for cycle\n * detection.\n */\ntype PathColumn = Readonly<{\n  alias: string;\n  identityExpanded: boolean;\n  format: \"ids\" | \"qualified\";\n  optional: boolean;\n}>;\n\nfunction collectPathColumns(state: QueryBuilderState): readonly PathColumn[] {\n  const columns: PathColumn[] = [];\n  for (const traversal of state.traversals) {\n    const pathAlias = traversal.variableLength?.pathAlias;\n    if (pathAlias !== undefined) {\n      columns.push({\n        alias: pathAlias,\n        identityExpanded: traversal.includeIdentityMembers === true,\n        format:\n          traversal.variableLength?.pathFormat === \"qualified\" ?\n            \"qualified\"\n          : \"ids\",\n        optional: traversal.optional,\n      });\n    }\n  }\n  return columns;\n}\n\n/**\n * Materializes path columns into the array of bare node IDs the public\n * traversal contract promises.\n *\n * SQLite returns pipe-delimited strings and PostgreSQL native arrays, so the\n * shape is normalized here. Identity-expanded traversals additionally carry\n * composite `kind || SEP || id` tokens (the compiler needs them so folded peers\n * stay distinct for cycle detection); those are stripped here so identity and\n * non-identity traversals produce identical path output on both dialects.\n *\n * This is the single seam where paths become caller-visible arrays — every\n * execution path (execute, prepared, paginated, selective) funnels through it,\n * so stripping exactly once here is safe.\n */\nexport function transformPathColumns(\n  rows: readonly Record<string, unknown>[],\n  state: QueryBuilderState,\n  _dialect: SqlDialect,\n): readonly Record<string, unknown>[] {\n  const pathColumns = collectPathColumns(state);\n  if (pathColumns.length === 0) return rows;\n\n  const result: Record<string, unknown>[] = [];\n  let changed = false;\n  for (const row of rows) {\n    let transformed: Record<string, unknown> | undefined;\n    for (const { alias, format, identityExpanded, optional } of pathColumns) {\n      const value = row[alias];\n      if (value === undefined) continue;\n      if (optional && value === null) {\n        transformed ??= { ...row };\n        transformed[alias] = undefined;\n        continue;\n      }\n      if (format === \"qualified\") {\n        const path = decodeQualifiedRecursivePath(value, alias);\n        transformed ??= { ...row };\n        transformed[alias] = path;\n        continue;\n      }\n      const normalized = normalizePath(value);\n      const path =\n        identityExpanded ? stripIdentityPathTokens(normalized) : normalized;\n      // normalizePath returns native arrays by reference, so an already-shaped\n      // path that needs no stripping leaves the row untouched.\n      if (path === value) continue;\n      transformed ??= { ...row };\n      transformed[alias] = path;\n    }\n    if (transformed === undefined) {\n      result.push(row);\n    } else {\n      changed = true;\n      result.push(transformed);\n    }\n  }\n  // Preserve reference identity when no rows were transformed\n  return changed ? result : rows;\n}\n\nfunction decodeQualifiedRecursivePath(\n  value: unknown,\n  alias: string,\n): QualifiedRecursivePath {\n  const parsed: unknown =\n    typeof value === \"string\" ? parseQualifiedPathJson(value, alias) : value;\n  if (\n    !Array.isArray(parsed) ||\n    parsed.length < 2 ||\n    (parsed.length - 2) % 5 !== 0\n  )\n    throw new ConfigurationError(\n      `Invalid qualified recursive path in column \"${alias}\"`,\n    );\n  if (!parsed.every((entry) => typeof entry === \"string\"))\n    throw new ConfigurationError(\n      `Invalid qualified recursive path in column \"${alias}\"`,\n    );\n  const tokens = parsed as readonly string[];\n  const path: QualifiedRecursivePath[number][] = [\n    {\n      type: \"node\",\n      kind: requireDefined(tokens[0]),\n      id: requireDefined(tokens[1]),\n    },\n  ];\n  for (let index = 2; index < tokens.length; index += 5) {\n    const direction = tokens[index + 2];\n    if (direction !== \"out\" && direction !== \"in\")\n      throw new ConfigurationError(\n        `Invalid qualified recursive path direction in column \"${alias}\"`,\n      );\n    path.push(\n      {\n        type: \"edge\",\n        kind: requireDefined(tokens[index]),\n        id: requireDefined(tokens[index + 1]),\n        direction,\n      },\n      {\n        type: \"node\",\n        kind: requireDefined(tokens[index + 3]),\n        id: requireDefined(tokens[index + 4]),\n      },\n    );\n  }\n  return path;\n}\n\nfunction parseQualifiedPathJson(value: string, alias: string): unknown {\n  try {\n    return JSON.parse(value);\n  } catch (error) {\n    throw new ConfigurationError(\n      `Invalid qualified recursive path JSON in column \"${alias}\"`,\n      { alias },\n      {\n        cause: error,\n      },\n    );\n  }\n}\n\n// Reserved keys that cannot be overwritten by user props\nconst RESERVED_NODE_KEYS: ReadonlySet<string> = new Set([\"id\", \"kind\", \"meta\"]);\nconst RESERVED_EDGE_KEYS: ReadonlySet<string> = new Set([\n  \"id\",\n  \"kind\",\n  \"fromId\",\n  \"toId\",\n  \"meta\",\n]);\n\n/**\n * The props to spread onto a selectable node/edge, with reserved keys dropped\n * so user props cannot collide with system fields (id, kind, meta, …).\n *\n * The accumulator is a {@link createDataKeyedBag} and the caller SPREADS the\n * result rather than assigning key-by-key onto the public object: `props` comes\n * straight off `JSON.parse` of the row's props column, which yields `__proto__`\n * as an ordinary own key, and `target[key] = value` would hand that key to\n * `Object.prototype`'s setter and drop the value. Spreading (a\n * `CreateDataProperty`, not a `Set`) carries it as an own key while leaving the\n * public result on `Object.prototype`, exactly as `rowToNode` already does.\n */\nfunction propsExcludingReserved(\n  props: Record<string, unknown>,\n  reservedKeys: ReadonlySet<string>,\n): Record<string, unknown> {\n  const kept = createDataKeyedBag<unknown>();\n  for (const [key, value] of Object.entries(props)) {\n    if (!reservedKeys.has(key)) {\n      kept[key] = value;\n    }\n  }\n  return kept;\n}\n\n/**\n * Builds a SelectableNode from row data for a given alias.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function buildSelectableNode(\n  row: Record<string, unknown>,\n  alias: string,\n): SelectableNode<NodeType> {\n  const id = row[`${alias}_id`] as string;\n  const kind = row[`${alias}_kind`] as string;\n  const propsRaw: unknown = row[`${alias}_props`];\n  const rawProps: Record<string, unknown> =\n    typeof propsRaw === \"string\" ?\n      (JSON.parse(propsRaw) as Record<string, unknown>)\n    : ((propsRaw as Record<string, unknown> | undefined) ?? {});\n\n  // Metadata columns - these are now always projected in CTEs\n  // Normalize null → undefined for optional fields\n  const version = row[`${alias}_version`] as number;\n  const validFrom = normalizeRowTimestamp(\n    row[`${alias}_valid_from`],\n    `${alias}_valid_from`,\n  );\n  const validTo = normalizeRowTimestamp(\n    row[`${alias}_valid_to`],\n    `${alias}_valid_to`,\n  );\n  const createdAt = normalizeRequiredRowTimestamp(\n    row[`${alias}_created_at`],\n    `${alias}_created_at`,\n  );\n  const updatedAt = normalizeRequiredRowTimestamp(\n    row[`${alias}_updated_at`],\n    `${alias}_updated_at`,\n  );\n  const deletedAt = normalizeRowTimestamp(\n    row[`${alias}_deleted_at`],\n    `${alias}_deleted_at`,\n  );\n\n  const result: Record<string, unknown> = {\n    id,\n    kind,\n    meta: {\n      version,\n      validFrom,\n      validTo,\n      createdAt,\n      updatedAt,\n      deletedAt,\n    },\n    ...propsExcludingReserved(rawProps, RESERVED_NODE_KEYS),\n  };\n\n  return result as SelectableNode<NodeType>;\n}\n\n/**\n * Builds a SelectableNode from row data, returning undefined when the node\n * doesn't exist (for optional traversals with LEFT JOIN).\n */\nfunction buildSelectableNodeOrUndefined(\n  row: Record<string, unknown>,\n  alias: string,\n): SelectableNode<NodeType> | undefined {\n  const id = row[`${alias}_id`] as string | null | undefined;\n  if (id === null || id === undefined) {\n    return undefined;\n  }\n  return buildSelectableNode(row, alias);\n}\n\n/**\n * Builds a SelectableEdge from row data for a given edge alias.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, fromId, toId, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n * Returns undefined if the edge doesn't exist (for optional traversals with LEFT JOIN).\n */\nfunction buildSelectableEdge(\n  row: Record<string, unknown>,\n  alias: string,\n): SelectableEdge | undefined {\n  const id = row[`${alias}_id`] as string | null | undefined;\n\n  // For optional traversals, edge may be null (LEFT JOIN)\n  if (id === null || id === undefined) {\n    return undefined;\n  }\n\n  const kind = row[`${alias}_kind`] as string;\n  const fromId = row[`${alias}_from_id`] as string;\n  const toId = row[`${alias}_to_id`] as string;\n\n  const propsRaw: unknown = row[`${alias}_props`];\n  const rawProps: Record<string, unknown> =\n    typeof propsRaw === \"string\" ?\n      (JSON.parse(propsRaw) as Record<string, unknown>)\n    : ((propsRaw as Record<string, unknown> | undefined) ?? {});\n\n  // Metadata columns - these are always projected in traversal CTEs\n  // Normalize null → undefined for optional fields\n  const validFrom = normalizeRowTimestamp(\n    row[`${alias}_valid_from`],\n    `${alias}_valid_from`,\n  );\n  const validTo = normalizeRowTimestamp(\n    row[`${alias}_valid_to`],\n    `${alias}_valid_to`,\n  );\n  const createdAt = normalizeRequiredRowTimestamp(\n    row[`${alias}_created_at`],\n    `${alias}_created_at`,\n  );\n  const updatedAt = normalizeRequiredRowTimestamp(\n    row[`${alias}_updated_at`],\n    `${alias}_updated_at`,\n  );\n  const deletedAt = normalizeRowTimestamp(\n    row[`${alias}_deleted_at`],\n    `${alias}_deleted_at`,\n  );\n\n  const result: Record<string, unknown> = {\n    id,\n    kind,\n    fromId,\n    toId,\n    meta: {\n      validFrom,\n      validTo,\n      createdAt,\n      updatedAt,\n      deletedAt,\n    },\n    ...propsExcludingReserved(rawProps, RESERVED_EDGE_KEYS),\n  };\n\n  return result as SelectableEdge;\n}\n\n/**\n * Builds a SelectContext from a raw database row.\n * Includes node aliases, edge aliases, and recursive metadata (depth/path).\n */\nexport function buildSelectContext<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n  RecursiveAliases extends RecursiveAliasMap = {},\n>(\n  row: Record<string, unknown>,\n  startAlias: string,\n  traversals: readonly Traversal[],\n): SelectContext<Aliases, EdgeAliases, RecursiveAliases> {\n  // Data-keyed: alias names chosen by the caller's query, which the kind-name\n  // pattern admits `__proto__` for. (The computed-key literal this replaced was\n  // itself safe — a computed key is a `CreateDataProperty` — but the traversal\n  // assignments below are not, so the whole bag is built the one right way.)\n  const context = createDataKeyedBag<\n    | SelectableNode<NodeType>\n    | SelectableEdge\n    | number\n    | readonly string[]\n    | undefined\n  >();\n  // Build the start node as initial context entry\n  context[startAlias] = buildSelectableNode(row, startAlias);\n\n  // Build traversal nodes and edges\n  for (const traversal of traversals) {\n    const nodeAlias = traversal.nodeAlias;\n    const edgeAlias = traversal.edgeAlias;\n\n    // Add node\n    context[nodeAlias] =\n      traversal.optional ?\n        buildSelectableNodeOrUndefined(row, nodeAlias)\n      : buildSelectableNode(row, nodeAlias);\n\n    // Add edge (may be undefined for optional traversals)\n    context[edgeAlias] = buildSelectableEdge(row, edgeAlias);\n\n    // Add recursive depth/path values\n    const vl = traversal.variableLength;\n    if (vl !== undefined) {\n      if (vl.depthAlias !== undefined) {\n        context[vl.depthAlias] =\n          traversal.optional && row[vl.depthAlias] === null ?\n            undefined\n          : (row[vl.depthAlias] as number);\n      }\n      if (vl.pathAlias !== undefined) {\n        context[vl.pathAlias] =\n          traversal.optional && row[vl.pathAlias] === null ?\n            undefined\n          : (row[vl.pathAlias] as readonly string[]);\n      }\n    }\n  }\n\n  // Spread at the boundary: the context is handed to the CALLER's `select`\n  // callback, and `select((ctx) => ctx)` returns it verbatim as the row. See\n  // `createDataKeyedBag` in ../../utils/object.ts — the spread is what keeps a\n  // `__proto__` alias an own key instead of reaching the prototype setter.\n  return { ...context } as SelectContext<\n    Aliases,\n    EdgeAliases,\n    RecursiveAliases\n  >;\n}\n\n/**\n * Maps raw database rows to typed results using a select function.\n */\nexport function mapResults<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n  R,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n  RA extends RecursiveAliasMap = {},\n>(\n  rows: readonly Record<string, unknown>[],\n  startAlias: string,\n  traversals: readonly Traversal[],\n  selectFunction: (context: SelectContext<Aliases, EdgeAliases, RA>) => R,\n): readonly R[] {\n  return rows.map((row) => {\n    const context = buildSelectContext<Aliases, EdgeAliases, RA>(\n      row,\n      startAlias,\n      traversals,\n    );\n    return selectFunction(context);\n  });\n}\n","import { ConfigurationError } from \"../../errors\";\nimport { type FieldRef, type OrderSpec, type SortDirection } from \"../ast\";\nimport { jsonPointer } from \"../json-pointer\";\nimport { fieldRef } from \"../predicates\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\n\nconst COMMON_SYSTEM_ORDER_FIELDS = new Map<\n  string,\n  NonNullable<FieldRef[\"valueType\"]>\n>([\n  [\"id\", \"string\"],\n  [\"kind\", \"string\"],\n  [\"valid_from\", \"string\"],\n  [\"valid_to\", \"string\"],\n  [\"created_at\", \"string\"],\n  [\"updated_at\", \"string\"],\n  [\"deleted_at\", \"string\"],\n]);\n\nconst EDGE_SYSTEM_ORDER_FIELDS = new Map<\n  string,\n  NonNullable<FieldRef[\"valueType\"]>\n>([\n  [\"from_id\", \"string\"],\n  [\"to_id\", \"string\"],\n]);\n\nconst DECLARED_PROPERTY_SHADOWABLE_SYSTEM_ORDER_FIELDS = new Set([\n  \"valid_from\",\n  \"valid_to\",\n  \"created_at\",\n  \"updated_at\",\n  \"deleted_at\",\n]);\nconst NULLABLE_SYSTEM_ORDER_FIELDS = new Set([\n  \"deleted_at\",\n  \"valid_from\",\n  \"valid_to\",\n]);\n\n/** Identifies physical system columns whose row-value comparisons are unsafe. */\nexport function isNullableSystemOrderField(field: string): boolean {\n  return NULLABLE_SYSTEM_ORDER_FIELDS.has(field);\n}\n\n/**\n * Resolves an orderable physical system column, or `undefined` when `field`\n * names a user property. Declared properties retain precedence over temporal\n * metadata with the same name, keeping `where*` and `orderBy` semantics\n * aligned. Structural identity fields remain unconditionally system-owned.\n * Both fluent builder stages consume this decision so they cannot drift.\n */\nexport function resolveSystemOrderField(\n  alias: string,\n  field: string,\n  isEdge: boolean,\n  hasDeclaredProperty: boolean,\n): FieldRef | undefined {\n  if (\n    hasDeclaredProperty &&\n    DECLARED_PROPERTY_SHADOWABLE_SYSTEM_ORDER_FIELDS.has(field)\n  ) {\n    return undefined;\n  }\n  const valueType =\n    COMMON_SYSTEM_ORDER_FIELDS.get(field) ??\n    (isEdge ? EDGE_SYSTEM_ORDER_FIELDS.get(field) : undefined);\n  return valueType === undefined ? undefined : (\n      fieldRef(alias, [field], {\n        nullable: isNullableSystemOrderField(field),\n        valueType,\n      })\n    );\n}\n\n/** Builds the shared system-column-or-property order expression. */\nexport function buildOrderSpec(\n  alias: string,\n  field: string,\n  direction: SortDirection,\n  systemField: FieldRef | undefined,\n  typeInfo: FieldTypeInfo | undefined,\n): OrderSpec {\n  return {\n    field:\n      systemField ??\n      fieldRef(alias, [\"props\"], {\n        jsonPointer: jsonPointer([field]),\n        valueType: typeInfo?.valueType,\n        elementType: typeInfo?.elementType,\n        ...(typeInfo === undefined ?\n          {}\n        : { nullable: typeInfo.nullable === true }),\n      }),\n    direction,\n  };\n}\n\n/** Refuses property operations that lack schema agreement across node kinds. */\nexport function assertSharedNodeField(\n  kindNames: readonly string[] | undefined,\n  field: string,\n  typeInfo: FieldTypeInfo | undefined,\n): void {\n  if (\n    kindNames !== undefined &&\n    kindNames.length > 1 &&\n    typeInfo === undefined\n  ) {\n    throw new ConfigurationError(\n      `Unknown or incompatible shared node field \"${field}\".`,\n    );\n  }\n}\n","/**\n * Cursor encoding/decoding for keyset pagination.\n *\n * Cursors are opaque URL-safe base64-encoded JSON containing:\n * - Column values at cursor position\n * - Direction indicator\n * - Version for forward compatibility\n */\n\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport { type FieldRef, type OrderSpec } from \"./ast\";\nimport { resolveJsonPointer } from \"./json-pointer\";\n\n// ============================================================\n// Types\n// ============================================================\n\nconst CURSOR_VERSION = 1;\n\n/**\n * Internal cursor data structure.\n */\nexport type CursorData = Readonly<{\n  /** Version for forward compatibility */\n  v: number;\n  /** Direction: 'f' = forward, 'b' = backward */\n  d: \"f\" | \"b\";\n  /** ORDER BY column values at cursor position */\n  vals: readonly unknown[];\n  /** Column identifiers for validation */\n  cols: readonly string[];\n}>;\n\n// ============================================================\n// Encoding / Decoding\n// ============================================================\n\n/**\n * Encodes cursor data to a URL-safe base64 string.\n */\nexport function encodeCursor(data: CursorData): string {\n  const json = JSON.stringify(data);\n  // Use URL-safe base64: replace + with -, / with _, remove padding\n  return btoa(json)\n    .replaceAll(\"+\", \"-\")\n    .replaceAll(\"/\", \"_\")\n    .replace(/=+$/, \"\");\n}\n\n/**\n * Decodes a cursor string to cursor data.\n *\n * @throws ValidationError if cursor is invalid or incompatible\n */\nexport function decodeCursor(cursor: string): CursorData {\n  try {\n    // Restore standard base64\n    let base64 = cursor.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n    // Add padding if needed\n    while (base64.length % 4) {\n      base64 += \"=\";\n    }\n    const json = atob(base64);\n    const raw = JSON.parse(json) as Record<string, unknown>;\n\n    if (typeof raw[\"v\"] !== \"number\" || raw[\"v\"] > CURSOR_VERSION) {\n      throw new ValidationError(\n        `Unsupported cursor version: ${String(raw[\"v\"])}. Maximum supported: ${CURSOR_VERSION}`,\n        {\n          issues: [\n            {\n              path: \"cursor\",\n              message: `Cursor version ${String(raw[\"v\"])} is not supported`,\n            },\n          ],\n        },\n        {\n          suggestion: `This cursor was created with a newer version. Re-fetch the data to get a compatible cursor.`,\n        },\n      );\n    }\n\n    if (raw[\"d\"] !== \"f\" && raw[\"d\"] !== \"b\") {\n      throw new ValidationError(\n        `Invalid cursor direction: ${String(raw[\"d\"])}`,\n        {\n          issues: [\n            {\n              path: \"cursor\",\n              message: `Direction must be \"f\" (forward) or \"b\" (backward)`,\n            },\n          ],\n        },\n      );\n    }\n\n    if (!Array.isArray(raw[\"vals\"]) || !Array.isArray(raw[\"cols\"])) {\n      throw new ValidationError(\"Invalid cursor structure\", {\n        issues: [\n          {\n            path: \"cursor\",\n            message: \"Cursor must contain vals and cols arrays\",\n          },\n        ],\n      });\n    }\n\n    if (raw[\"vals\"].length !== raw[\"cols\"].length) {\n      throw new ValidationError(\"Cursor column count mismatch\", {\n        issues: [\n          {\n            path: \"cursor\",\n            message: `vals (${raw[\"vals\"].length}) and cols (${raw[\"cols\"].length}) must have same length`,\n          },\n        ],\n      });\n    }\n\n    return {\n      v: raw[\"v\"],\n      d: raw[\"d\"],\n      vals: raw[\"vals\"] as readonly unknown[],\n      cols: raw[\"cols\"] as readonly string[],\n    };\n  } catch (error) {\n    if (error instanceof ValidationError) {\n      throw error;\n    }\n    throw new ValidationError(\n      \"Invalid cursor format\",\n      {\n        issues: [{ path: \"cursor\", message: \"Failed to decode cursor\" }],\n      },\n      { cause: error },\n    );\n  }\n}\n\n// ============================================================\n// Cursor Building\n// ============================================================\n\n/**\n * Builds a column identifier from an order spec.\n *\n * Format: \"alias.fieldName\" for property fields, \"alias.path[0]...\" for system fields.\n * Handles two field ref formats:\n * 1. New format: path=[\"props\"], jsonPointer=\"/name\"\n * 2. Legacy format: path=[\"props\", \"name\"]\n *\n * In both cases, outputs flattened format \"p.name\" to match the flattened API.\n */\nexport function buildColumnId(spec: OrderSpec): string {\n  const { alias, path, jsonPointer } = requireCursorField(spec.field);\n\n  // New format: path=[\"props\"] with jsonPointer=\"/fieldName\"\n  // jsonPointer is a branded string like \"/name\" or \"/nested/field\"\n  if (path.length === 1 && path[0] === \"props\" && jsonPointer) {\n    const parts = (jsonPointer as string).split(\"/\").filter(Boolean);\n    return `${alias}.${parts.join(\".\")}`;\n  }\n\n  // Legacy format: path=[\"props\", \"fieldName\", ...] without jsonPointer\n  if (path.length >= 2 && path[0] === \"props\") {\n    return `${alias}.${path.slice(1).join(\".\")}`;\n  }\n\n  // System fields (id, kind) or other paths\n  return `${alias}.${path.join(\".\")}`;\n}\n\n/**\n * Extracts the value for a cursor column from a result row.\n *\n * The row can be in two formats:\n * 1. Raw database row with flat column names\n * 2. Mapped result with alias-keyed nested data\n *\n * For mapped results, we navigate through the path and then jsonPointer.\n */\nexport function extractCursorValue(\n  row: Record<string, unknown>,\n  spec: OrderSpec,\n): unknown {\n  const { alias, path, jsonPointer } = requireCursorField(spec.field);\n\n  // Try alias-keyed format first (mapped results)\n  let current: unknown = row[alias];\n  if (current !== undefined) {\n    // Follow path first (e.g., [\"props\"])\n    for (const segment of path) {\n      if (current === null || current === undefined) return undefined;\n      if (typeof current !== \"object\") return undefined;\n\n      const record = current as Record<string, unknown>;\n      if (segment === \"props\" && !Object.hasOwn(record, segment)) {\n        continue;\n      }\n\n      current = record[segment];\n    }\n\n    // Then follow jsonPointer if present (e.g., \"/name\")\n    if (jsonPointer) {\n      return resolveJsonPointer(current, jsonPointer);\n    }\n\n    return current;\n  }\n\n  // Fallback: try direct path lookup for raw rows\n  current = row;\n  for (const segment of path) {\n    if (current === null || current === undefined) return undefined;\n    if (typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[segment];\n  }\n  return current;\n}\n\n/**\n * Builds a cursor from a result row and order specifications.\n *\n * @param row - The result row (mapped with alias-keyed data)\n * @param orderSpecs - The ORDER BY specifications\n * @param direction - Pagination direction\n * @returns Encoded cursor string\n */\nexport function buildCursorFromRow(\n  row: Record<string, unknown>,\n  orderSpecs: readonly OrderSpec[],\n  direction: \"f\" | \"b\",\n): string {\n  const vals = orderSpecs.map((spec) => extractCursorValue(row, spec));\n  const cols = orderSpecs.map((spec) => buildColumnId(spec));\n\n  return encodeCursor({\n    v: CURSOR_VERSION,\n    d: direction,\n    vals,\n    cols,\n  });\n}\n\n/** Builds a cursor when the ordered values were projected independently. */\nexport function buildCursorFromValues(\n  values: readonly unknown[],\n  orderSpecs: readonly OrderSpec[],\n  direction: \"f\" | \"b\",\n): string {\n  return encodeCursor({\n    v: CURSOR_VERSION,\n    d: direction,\n    vals: values,\n    cols: orderSpecs.map((spec) => buildColumnId(spec)),\n  });\n}\n\n/**\n * Validates that cursor columns match the query's ORDER BY columns.\n *\n * @throws ValidationError if columns don't match\n */\nexport function validateCursorColumns(\n  cursorData: CursorData,\n  orderSpecs: readonly OrderSpec[],\n): void {\n  const expectedCols = orderSpecs.map((spec) => buildColumnId(spec));\n\n  if (cursorData.cols.length !== expectedCols.length) {\n    throw new ValidationError(\n      `Cursor has ${cursorData.cols.length} columns but query has ${expectedCols.length} ORDER BY columns`,\n      {\n        issues: [\n          {\n            path: \"cursor\",\n            message: `Column count mismatch: cursor has ${cursorData.cols.length}, query has ${expectedCols.length}`,\n          },\n        ],\n      },\n      {\n        suggestion: `The cursor was created with a different ORDER BY. Re-fetch with consistent ordering.`,\n      },\n    );\n  }\n\n  for (const [index, expectedCol] of expectedCols.entries()) {\n    if (cursorData.cols[index] !== expectedCol) {\n      throw new ValidationError(\n        `Cursor column mismatch at position ${index}: expected \"${expectedCol}\", got \"${cursorData.cols[index]}\"`,\n        {\n          issues: [\n            {\n              path: \"cursor\",\n              message: `Column ${index}: expected \"${expectedCol}\", got \"${cursorData.cols[index]}\"`,\n            },\n          ],\n        },\n        {\n          suggestion: `The cursor was created with a different ORDER BY. Re-fetch with consistent ordering.`,\n        },\n      );\n    }\n  }\n}\n\n/** Cursor encoding currently requires identifiable fields, not computed values. */\nexport function requireCursorField(field: OrderSpec[\"field\"]): FieldRef {\n  if (field.__type !== \"field_ref\")\n    throw new ConfigurationError(\n      \"Cursor pagination does not support database-expression ordering.\",\n    );\n  return field;\n}\n","/**\n * Cursor-based pagination utilities.\n *\n * Provides pagination logic for ExecutableQuery including cursor predicate\n * building and result page construction.\n */\nimport {\n  DEFAULT_PAGINATION_LIMIT,\n  DEFAULT_STREAM_BATCH_SIZE,\n} from \"../../constants\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n  type FieldRef,\n  type LiteralValue,\n  type NodePredicate,\n  type OrderSpec,\n  type PredicateExpression,\n  type TupleComparisonPredicate,\n} from \"../ast\";\nimport { isNullableSystemOrderField } from \"../builder/order-by-field\";\nimport type {\n  AliasMap,\n  EdgeAliasMap,\n  PaginatedResult,\n  PaginateOptions,\n  SelectContext,\n  StreamOptions,\n} from \"../builder/types\";\nimport { requireCursorField } from \"../cursor\";\nimport {\n  buildCursorFromRow,\n  type CursorData,\n  decodeCursor,\n  validateCursorColumns,\n} from \"../cursor\";\nimport { resolveNullOrdering } from \"../order\";\n\n/**\n * Parses pagination options into internal format.\n */\nexport function parsePaginateOptions(options: PaginateOptions): {\n  isBackward: boolean;\n  limit: number;\n  cursor: string | undefined;\n  cursorData: CursorData | undefined;\n  orderBy: readonly OrderSpec[];\n} {\n  const isBackward = options.last !== undefined || options.before !== undefined;\n  const limit = options.first ?? options.last ?? DEFAULT_PAGINATION_LIMIT;\n  const cursor = options.after ?? options.before;\n\n  let cursorData: CursorData | undefined;\n  if (cursor) {\n    cursorData = decodeCursor(cursor);\n  }\n\n  return { isBackward, limit, cursor, cursorData, orderBy: [] };\n}\n\n/**\n * Validates cursor data against ORDER BY columns.\n */\nexport function validateCursor(\n  cursorData: CursorData | undefined,\n  orderBy: readonly OrderSpec[],\n): void {\n  if (cursorData) {\n    validateCursorColumns(cursorData, orderBy);\n  }\n}\n\n/**\n * Adjusts ORDER BY for backward pagination (reverses directions).\n */\nexport function adjustOrderByForDirection(\n  orderBy: readonly OrderSpec[],\n  direction: \"forward\" | \"backward\",\n): readonly OrderSpec[] {\n  if (direction === \"forward\") {\n    return orderBy;\n  }\n  return orderBy.map((spec) => ({\n    ...spec,\n    direction: spec.direction === \"asc\" ? (\"desc\" as const) : (\"asc\" as const),\n    nulls: resolveNullOrdering(spec) === \"first\" ? \"last\" : \"first\",\n  }));\n}\n\n/**\n * Builds a cursor predicate for keyset pagination.\n * Generates (col1 > val1) OR (col1 = val1 AND col2 > val2) OR ... pattern.\n */\nexport function buildCursorPredicate(\n  cursorData: CursorData,\n  orderBy: readonly OrderSpec[],\n  direction: \"forward\" | \"backward\",\n  targetAlias: string,\n): NodePredicate {\n  const values = cursorData.vals;\n\n  const tupleComparison = buildTupleComparisonPredicate(\n    values,\n    orderBy,\n    direction,\n  );\n  if (tupleComparison !== undefined) {\n    return { targetAlias, expression: tupleComparison };\n  }\n\n  // Build OR of progressively longer AND conditions\n  const orConditions: PredicateExpression[] = [];\n\n  for (let index = 0; index < orderBy.length; index++) {\n    const andConditions: PredicateExpression[] = [];\n\n    // All preceding columns must be equal\n    for (let index_ = 0; index_ < index; index_++) {\n      const spec = requireDefined(orderBy[index_]);\n      const value = values[index_];\n      andConditions.push(\n        buildEqualityPredicate(requireCursorField(spec.field), value),\n      );\n    }\n\n    // Current column uses comparison\n    const currentSpec = requireDefined(orderBy[index]);\n    const comparison = buildPositionPredicate(\n      requireCursorField(currentSpec.field),\n      currentSpec,\n      values[index],\n      direction === \"forward\" ? \"after\" : \"before\",\n    );\n    if (comparison === undefined) continue;\n    andConditions.push(comparison);\n\n    // Combine with AND\n    if (andConditions.length === 1) {\n      orConditions.push(requireDefined(andConditions[0]));\n    } else {\n      orConditions.push({ __type: \"and\", predicates: andConditions });\n    }\n  }\n\n  // Combine with OR\n  const expression: PredicateExpression =\n    orConditions.length === 0 ?\n      buildImpossiblePredicate(\n        requireCursorField(requireDefined(orderBy[0]).field),\n      )\n    : orConditions.length === 1 ? requireDefined(orConditions[0])\n    : { __type: \"or\", predicates: orConditions };\n\n  return {\n    targetAlias,\n    expression,\n  };\n}\n\n/** Uses row values only when SQL NULL semantics cannot change the ordering. */\nfunction buildTupleComparisonPredicate(\n  values: readonly unknown[],\n  orderBy: readonly OrderSpec[],\n  direction: \"forward\" | \"backward\",\n): TupleComparisonPredicate | undefined {\n  if (orderBy.length < 2 || values.length !== orderBy.length) return;\n  const [first] = orderBy;\n  if (first === undefined) return;\n  if (\n    orderBy.some(\n      (spec, index) =>\n        spec.direction !== first.direction ||\n        spec.nulls !== undefined ||\n        !isTupleComparableField(spec.field) ||\n        values[index] === null ||\n        values[index] === undefined,\n    )\n  ) {\n    return;\n  }\n  const fields = orderBy.map((spec) => requireCursorField(spec.field)) as [\n    FieldRef,\n    ...FieldRef[],\n  ];\n  const tupleValues = values.map((value) => ({\n    __type: \"literal\" as const,\n    value: value as string | number | boolean,\n  })) as [LiteralValue, ...LiteralValue[]];\n  const afterAscending =\n    (direction === \"forward\" && first.direction === \"asc\") ||\n    (direction === \"backward\" && first.direction === \"desc\");\n  return {\n    __type: \"tuple_comparison\",\n    fields,\n    op: afterAscending ? \"gt\" : \"lt\",\n    values: tupleValues,\n  };\n}\n\nfunction isTupleComparableField(field: OrderSpec[\"field\"]): boolean {\n  if (field.__type !== \"field_ref\") return false;\n  if (field.nullable === true) return false;\n  if (field.nullable === false) return isTupleScalarValueType(field.valueType);\n  // System identity and creation columns are physically NOT NULL. Existing\n  // manually assembled ASTs may predate the nullable marker, so retain this\n  // narrow compatibility path without making user properties eligible.\n  return (\n    field.path.length === 1 &&\n    isTupleScalarValueType(field.valueType) &&\n    !isNullableSystemOrderField(requireDefined(field.path[0])) &&\n    [\"id\", \"kind\", \"created_at\", \"updated_at\"].includes(\n      requireDefined(field.path[0]),\n    )\n  );\n}\n\nfunction isTupleScalarValueType(valueType: FieldRef[\"valueType\"]): boolean {\n  return (\n    valueType === \"boolean\" ||\n    valueType === \"date\" ||\n    valueType === \"number\" ||\n    valueType === \"string\"\n  );\n}\n\n/**\n * Builds an equality predicate for cursor pagination.\n */\nfunction buildEqualityPredicate(\n  field: FieldRef,\n  value: unknown,\n): PredicateExpression {\n  if (value === null || value === undefined) {\n    return { __type: \"null_check\", op: \"isNull\", field };\n  }\n  return {\n    __type: \"comparison\",\n    op: \"eq\",\n    left: field,\n    right: { __type: \"literal\", value: value as string | number | boolean },\n  };\n}\n\n/**\n * Builds a comparison predicate for cursor pagination.\n */\nfunction buildPositionPredicate(\n  field: FieldRef,\n  spec: OrderSpec,\n  value: unknown,\n  position: \"after\" | \"before\",\n): PredicateExpression | undefined {\n  const nulls = resolveNullOrdering(spec);\n  if (value === null || value === undefined) {\n    const nonNullValuesMatch =\n      (position === \"after\" && nulls === \"first\") ||\n      (position === \"before\" && nulls === \"last\");\n    return nonNullValuesMatch ?\n        { __type: \"null_check\", op: \"isNotNull\", field }\n      : undefined;\n  }\n\n  const isAscending = spec.direction === \"asc\";\n  const comparison: PredicateExpression = {\n    __type: \"comparison\",\n    op: isAscending === (position === \"after\") ? \"gt\" : \"lt\",\n    left: field,\n    right: { __type: \"literal\", value: value as string | number | boolean },\n  };\n  const nullValuesMatch =\n    (position === \"after\" && nulls === \"last\") ||\n    (position === \"before\" && nulls === \"first\");\n  return nullValuesMatch ?\n      {\n        __type: \"or\",\n        predicates: [comparison, { __type: \"null_check\", op: \"isNull\", field }],\n      }\n    : comparison;\n}\n\nfunction buildImpossiblePredicate(field: FieldRef): PredicateExpression {\n  return {\n    __type: \"and\",\n    predicates: [\n      { __type: \"null_check\", op: \"isNull\", field },\n      { __type: \"null_check\", op: \"isNotNull\", field },\n    ],\n  };\n}\n\n/**\n * Builds cursor string from a context row.\n */\nexport function buildCursorFromContext<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n>(\n  context: SelectContext<Aliases, EdgeAliases>,\n  orderBy: readonly OrderSpec[],\n  direction: \"f\" | \"b\",\n): string {\n  return buildCursorFromRow(context, orderBy, direction);\n}\n\n/**\n * Constructs a PaginatedResult from query results.\n */\nexport function buildPaginatedResult<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n  R,\n>(\n  data: readonly R[],\n  orderedRows: readonly Record<string, unknown>[],\n  orderBy: readonly OrderSpec[],\n  limit: number,\n  hasMore: boolean,\n  isBackward: boolean,\n  cursor: string | undefined,\n  buildContext: (\n    row: Record<string, unknown>,\n  ) => SelectContext<Aliases, EdgeAliases>,\n): PaginatedResult<R> {\n  return buildPaginatedResultFromRows(\n    data,\n    orderedRows,\n    hasMore,\n    isBackward,\n    cursor,\n    (row, direction) =>\n      buildCursorFromContext(buildContext(row), orderBy, direction),\n  );\n}\n\n/**\n * Constructs a paginated result from rows and a caller-owned cursor encoder.\n */\nexport function buildPaginatedResultFromRows<R, Row>(\n  data: readonly R[],\n  orderedRows: readonly Row[],\n  hasMore: boolean,\n  isBackward: boolean,\n  cursor: string | undefined,\n  buildCursor: (row: Row, direction: \"f\" | \"b\") => string,\n): PaginatedResult<R> {\n  const firstRow = orderedRows[0];\n  const lastRow = orderedRows.at(-1);\n  const previousCursor =\n    firstRow === undefined ? undefined : buildCursor(firstRow, \"b\");\n  const nextCursor =\n    lastRow === undefined ? undefined : buildCursor(lastRow, \"f\");\n\n  return {\n    data,\n    nextCursor: hasMore || isBackward ? nextCursor : undefined,\n    prevCursor:\n      cursor !== undefined || (isBackward && hasMore) ?\n        previousCursor\n      : undefined,\n    hasNextPage: isBackward ? cursor !== undefined : hasMore,\n    hasPrevPage: isBackward ? hasMore : cursor !== undefined,\n  };\n}\n\n/**\n * Creates an async iterable that streams results using cursor pagination.\n */\nexport async function* createStreamIterable<R>(\n  batchSize: number,\n  paginate: (options: PaginateOptions) => Promise<PaginatedResult<R>>,\n): AsyncGenerator<R> {\n  let cursor: string | undefined;\n  let hasMore = true;\n\n  while (hasMore) {\n    const options: PaginateOptions =\n      cursor ? { first: batchSize, after: cursor } : { first: batchSize };\n    const page = await paginate(options);\n\n    for (const item of page.data) {\n      yield item;\n    }\n\n    cursor = page.nextCursor;\n    hasMore = page.hasNextPage;\n  }\n}\n\n/**\n * Gets default stream options.\n */\nexport function getStreamBatchSize(options?: StreamOptions): number {\n  return options?.batchSize ?? DEFAULT_STREAM_BATCH_SIZE;\n}\n","export const SELECTABLE_ALIAS_MARKER = Symbol(\"selectable_alias_marker\");\n\nexport type SelectableAliasMarker = Readonly<{\n  alias: string;\n  kind: \"node\" | \"edge\";\n}>;\n\nfunction isSelectableAliasObject(\n  value: unknown,\n): value is SelectableAliasMarker {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    SELECTABLE_ALIAS_MARKER in value\n  );\n}\n\nexport function containsSelectableAliasObject(value: unknown): boolean {\n  const visited = new WeakSet<object>();\n\n  function walk(current: unknown): boolean {\n    if (isSelectableAliasObject(current)) return true;\n\n    if (typeof current !== \"object\" || current === null) return false;\n    if (visited.has(current)) return false;\n    visited.add(current);\n\n    if (Array.isArray(current)) {\n      for (const item of current) {\n        if (walk(item)) return true;\n      }\n      return false;\n    }\n\n    for (const value of Object.values(current)) {\n      if (walk(value)) return true;\n    }\n    return false;\n  }\n\n  return walk(value);\n}\n","/**\n * Field Tracking for Smart Select Optimization.\n *\n * Provides infrastructure for tracking which fields are accessed during\n * a select callback, enabling the query compiler to selectively project\n * only those fields instead of fetching the full props blob.\n */\nimport type { KindEntity } from \"../../core/types\";\nimport { EDGE_META_KEYS, NODE_META_KEYS } from \"../../system-fields\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { createDataKeyedBag, isInteropProbeKey } from \"../../utils/object\";\nimport { mergeEdgeKinds, type SelectiveField, type ValueType } from \"../ast\";\nimport { type QueryBuilderState } from \"../builder/types\";\nimport {\n  type FieldTypeInfo,\n  type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport { SELECTABLE_ALIAS_MARKER } from \"./selectable-alias\";\n\n// ============================================================\n// Types\n// ============================================================\n\ntype TrackingValueMode = \"falsy\" | \"truthy\" | \"max\";\n\ntype AccessedField = Readonly<{\n  alias: string;\n  field: string;\n  isSystemField: boolean;\n}>;\n\nexport type TrackingContextOptions = Readonly<{\n  schemaIntrospector: SchemaIntrospector;\n  mode: TrackingValueMode;\n  /**\n   * When \"absent\", optional traversal aliases are set to undefined to\n   * encourage exploring fallback branches (e.g., `ctx.friend ? ... : ...`).\n   */\n  optionalTraversalAliases: \"present\" | \"absent\";\n}>;\n\n// ============================================================\n// Constants\n// ============================================================\n\n/**\n * Names the tracking proxies answer with the inherited `Object.prototype`\n * member, so a select callback that stringifies or type-tests an alias object\n * during tracking behaves like it would against a real result object.\n *\n * A name on this list is a prototype member only while the schema does NOT\n * declare a field by that name — `z.object({ toString: z.string() })` is an\n * ordinary schema, and its field is ordinary data. Membership is therefore\n * decided by {@link SchemaIntrospector.hasDeclaredField}, the same own-key\n * question `hasOwnKey` answers everywhere else; a declared name never reaches\n * this list. Classifying it here instead left the field untracked, so the\n * selective projection never selected it and the guarded result proxy served\n * the inherited member in place of the stored value.\n */\nconst OBJECT_PROTOTYPE_PROPERTIES = new Set<string>([\n  \"__proto__\",\n  \"constructor\",\n  \"hasOwnProperty\",\n  \"isPrototypeOf\",\n  \"propertyIsEnumerable\",\n  \"toLocaleString\",\n  \"toString\",\n  \"valueOf\",\n]);\n\n// ============================================================\n// FieldAccessTracker\n// ============================================================\n\nexport class FieldAccessTracker {\n  requiresFullRow = false;\n\n  readonly #fields = new Map<string, AccessedField>();\n\n  record(alias: string, field: string, isSystemField: boolean): void {\n    const key = `${alias}\\u0000${field}`;\n    const existing = this.#fields.get(key);\n    // System fields (id, kind) are dedicated columns — not in the props JSON.\n    // Never downgrade a system field to a props field, as that would cause the\n    // compiler to emit props->>'id' (nonexistent) instead of the id column.\n    if (existing !== undefined && existing.isSystemField && !isSystemField) {\n      return;\n    }\n    this.#fields.set(key, { alias, field, isSystemField });\n  }\n\n  getAccessedFields(): readonly AccessedField[] {\n    return [...this.#fields.values()];\n  }\n}\n\n// ============================================================\n// Tracking Context Creation\n// ============================================================\n\nexport function createTrackingContext(\n  state: QueryBuilderState,\n  tracker: FieldAccessTracker,\n  options: TrackingContextOptions,\n): Record<string, unknown> {\n  // Data-keyed: alias names chosen by the caller's query. The tracking context\n  // must be keyed identically to the real one `buildSelectContext` produces —\n  // a tracking pass that drops an alias the execution pass keeps (or the\n  // reverse) is exactly the probe-vs-engine divergence to avoid.\n  const context = createDataKeyedBag<unknown>();\n  context[state.startAlias] = createNodeTrackingProxy(\n    state.startAlias,\n    state.startKinds,\n    tracker,\n    options,\n  );\n\n  for (const traversal of state.traversals) {\n    const edgeKindNames = mergeEdgeKinds(traversal);\n\n    const optionalAbsent =\n      options.optionalTraversalAliases === \"absent\" && traversal.optional;\n\n    context[traversal.nodeAlias] =\n      optionalAbsent ? undefined : (\n        createNodeTrackingProxy(\n          traversal.nodeAlias,\n          traversal.nodeKinds,\n          tracker,\n          options,\n        )\n      );\n\n    context[traversal.edgeAlias] =\n      optionalAbsent ? undefined : (\n        createEdgeTrackingProxy(\n          traversal.edgeAlias,\n          edgeKindNames,\n          tracker,\n          options,\n        )\n      );\n\n    // Provide placeholder values for recursive depth/path so the\n    // select callback can access them without crashing during tracking.\n    const vl = traversal.variableLength;\n    if (vl !== undefined) {\n      if (vl.depthAlias !== undefined) {\n        context[vl.depthAlias] = options.mode === \"falsy\" ? 0 : 1;\n      }\n      if (vl.pathAlias !== undefined) {\n        context[vl.pathAlias] =\n          options.mode === \"falsy\" ? []\n          : vl.pathFormat === \"qualified\" ?\n            [{ type: \"node\", kind: \"placeholder\", id: \"placeholder\" }]\n          : [\"placeholder\"];\n      }\n    }\n  }\n\n  // Spread at the boundary, for the same reason `buildSelectContext` does: this\n  // context is handed to the CALLER's `select` callback, on the tracking pass as\n  // much as on the execution pass. A callback that asks `ctx instanceof Object`\n  // must get the same answer from both, or the probe explores a branch the\n  // engine will not take.\n  return { ...context };\n}\n\nfunction createNodeTrackingProxy(\n  alias: string,\n  kindNames: readonly string[],\n  tracker: FieldAccessTracker,\n  options: TrackingContextOptions,\n): unknown {\n  return new Proxy(\n    { [SELECTABLE_ALIAS_MARKER]: true },\n    {\n      ownKeys: () => {\n        tracker.requiresFullRow = true;\n        return [];\n      },\n      get: (_, property: string | symbol) => {\n        if (typeof property === \"symbol\") return;\n        // The interop probes are exempted so an incidental `await` or\n        // `JSON.stringify` of the tracking context does not record a phantom\n        // field. Neither is on `Object.prototype`, but both earn the same rule\n        // as the members that are: a DECLARED field named `then` or `toJSON` is\n        // stored data, and exempting it would leave it untracked — the\n        // selective projection would omit the column the select callback just\n        // read, and the result mapper would have no own key to hand back.\n        if (\n          isInteropProbeKey(property) &&\n          !options.schemaIntrospector.hasDeclaredField(kindNames, property)\n        ) {\n          return;\n        }\n\n        if (\n          OBJECT_PROTOTYPE_PROPERTIES.has(property) &&\n          !options.schemaIntrospector.hasDeclaredField(kindNames, property)\n        ) {\n          if (property === \"constructor\") return Object;\n          if (property === \"__proto__\") return Object.prototype;\n          return Reflect.get(Object.prototype, property) as unknown;\n        }\n\n        if (property === \"id\" || property === \"kind\") {\n          tracker.record(alias, property, true);\n          return getPlaceholderForSystemField(property, options.mode);\n        }\n\n        if (property === \"meta\") {\n          for (const key of NODE_META_KEYS) {\n            tracker.record(alias, `meta.${key}`, true);\n          }\n          return buildNodeMetaPlaceholder(options.mode);\n        }\n\n        tracker.record(alias, property, false);\n        const typeInfo = options.schemaIntrospector.getSharedFieldTypeInfo(\n          kindNames,\n          property,\n        );\n        return getPlaceholderForTypeInfo(typeInfo, options.mode);\n      },\n    },\n  );\n}\n\nfunction createEdgeTrackingProxy(\n  alias: string,\n  edgeKindNames: readonly string[],\n  tracker: FieldAccessTracker,\n  options: TrackingContextOptions,\n): unknown {\n  return new Proxy(\n    { [SELECTABLE_ALIAS_MARKER]: true },\n    {\n      ownKeys: () => {\n        tracker.requiresFullRow = true;\n        return [];\n      },\n      get: (_, property: string | symbol) => {\n        if (typeof property === \"symbol\") return;\n        // See `createNodeTrackingProxy`: a DECLARED `then` / `toJSON` is stored\n        // data and must be tracked, not exempted.\n        if (\n          isInteropProbeKey(property) &&\n          !options.schemaIntrospector.hasDeclaredEdgeField(\n            edgeKindNames,\n            property,\n          )\n        ) {\n          return;\n        }\n\n        if (\n          OBJECT_PROTOTYPE_PROPERTIES.has(property) &&\n          !options.schemaIntrospector.hasDeclaredEdgeField(\n            edgeKindNames,\n            property,\n          )\n        ) {\n          if (property === \"constructor\") return Object;\n          if (property === \"__proto__\") return Object.prototype;\n          return Reflect.get(Object.prototype, property) as unknown;\n        }\n\n        if (\n          property === \"id\" ||\n          property === \"kind\" ||\n          property === \"fromId\" ||\n          property === \"toId\"\n        ) {\n          tracker.record(alias, property, true);\n          return getPlaceholderForSystemField(property, options.mode);\n        }\n\n        if (property === \"meta\") {\n          for (const key of EDGE_META_KEYS) {\n            tracker.record(alias, `meta.${key}`, true);\n          }\n          return buildEdgeMetaPlaceholder(options.mode);\n        }\n\n        tracker.record(alias, property, false);\n        const typeInfo = options.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n          edgeKindNames,\n          property,\n        );\n        return getPlaceholderForTypeInfo(typeInfo, options.mode);\n      },\n    },\n  );\n}\n\n// ============================================================\n// Selective Field Construction\n// ============================================================\n\ntype BuildSelectiveFieldsOptions = Readonly<{\n  state: QueryBuilderState;\n  schemaIntrospector: SchemaIntrospector;\n}>;\n\nexport function buildSelectiveFields(\n  accessedFields: readonly AccessedField[],\n  options?: BuildSelectiveFieldsOptions,\n): readonly SelectiveField[] {\n  const aliasInfo = options ? buildAliasKindMap(options.state) : undefined;\n\n  return accessedFields\n    .map((access) => {\n      const base: SelectiveField = {\n        alias: access.alias,\n        field: access.field,\n        outputName: `${access.alias}_${access.field}`,\n        isSystemField: access.isSystemField,\n      };\n\n      if (!options || access.isSystemField) {\n        return base;\n      }\n\n      const info = aliasInfo?.get(access.alias);\n      if (!info) {\n        return base;\n      }\n\n      const typeInfo =\n        info.kind === \"node\" ?\n          options.schemaIntrospector.getSharedFieldTypeInfo(\n            info.kindNames,\n            access.field,\n          )\n        : options.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n            info.kindNames,\n            access.field,\n          );\n\n      return {\n        ...base,\n        valueType: typeInfo?.valueType,\n      };\n    })\n    .toSorted((a, b) => {\n      const aliasCompare = compareStrings(a.alias, b.alias);\n      if (aliasCompare !== 0) return aliasCompare;\n      return compareStrings(a.field, b.field);\n    });\n}\n\ntype AliasKind = KindEntity;\n\ntype AliasKindInfo = Readonly<{\n  kind: AliasKind;\n  kindNames: readonly string[];\n}>;\n\nfunction buildAliasKindMap(\n  state: QueryBuilderState,\n): ReadonlyMap<string, AliasKindInfo> {\n  const map = new Map<string, AliasKindInfo>([\n    [\n      state.startAlias,\n      {\n        kind: \"node\",\n        kindNames: state.startKinds,\n      },\n    ],\n  ]);\n\n  for (const traversal of state.traversals) {\n    const edgeKindNames = mergeEdgeKinds(traversal);\n\n    map.set(traversal.nodeAlias, {\n      kind: \"node\",\n      kindNames: traversal.nodeKinds,\n    });\n    map.set(traversal.edgeAlias, {\n      kind: \"edge\",\n      kindNames: edgeKindNames,\n    });\n  }\n\n  return map;\n}\n\n// ============================================================\n// Placeholder Values\n// ============================================================\n\nfunction getPlaceholderForSystemField(\n  field: string,\n  mode: TrackingValueMode,\n): unknown {\n  if (\n    field === \"id\" ||\n    field === \"kind\" ||\n    field === \"fromId\" ||\n    field === \"toId\"\n  ) {\n    return mode === \"falsy\" ? \"\" : \"x\";\n  }\n  return undefined;\n}\n\nfunction buildNodeMetaPlaceholder(mode: TrackingValueMode): Readonly<{\n  version: number;\n  validFrom: string | undefined;\n  validTo: string | undefined;\n  createdAt: string;\n  updatedAt: string;\n  deletedAt: string | undefined;\n}> {\n  const empty = mode === \"falsy\";\n  return {\n    version: empty ? 0 : 1,\n    validFrom: empty ? undefined : \"2020-01-01T00:00:00.000Z\",\n    validTo: undefined,\n    createdAt: \"2020-01-01T00:00:00.000Z\",\n    updatedAt: \"2020-01-01T00:00:00.000Z\",\n    deletedAt: undefined,\n  };\n}\n\nfunction buildEdgeMetaPlaceholder(mode: TrackingValueMode): Readonly<{\n  validFrom: string | undefined;\n  validTo: string | undefined;\n  createdAt: string;\n  updatedAt: string;\n  deletedAt: string | undefined;\n}> {\n  const empty = mode === \"falsy\";\n  return {\n    validFrom: empty ? undefined : \"2020-01-01T00:00:00.000Z\",\n    validTo: undefined,\n    createdAt: \"2020-01-01T00:00:00.000Z\",\n    updatedAt: \"2020-01-01T00:00:00.000Z\",\n    deletedAt: undefined,\n  };\n}\n\nfunction getPlaceholderForTypeInfo(\n  typeInfo: FieldTypeInfo | undefined,\n  mode: TrackingValueMode,\n): unknown {\n  if (!typeInfo) {\n    return undefined;\n  }\n\n  return getPlaceholderForValueType(typeInfo.valueType, mode);\n}\n\nfunction getPlaceholderForValueType(\n  valueType: ValueType,\n  mode: TrackingValueMode,\n): unknown {\n  switch (valueType) {\n    case \"string\":\n    case \"date\": {\n      if (mode === \"falsy\") return \"\";\n      if (mode === \"max\") return \"active\";\n      return \"x\";\n    }\n    case \"number\": {\n      if (mode === \"falsy\") return 0;\n      if (mode === \"max\") return 100;\n      return 1;\n    }\n    case \"boolean\": {\n      return mode !== \"falsy\";\n    }\n    case \"array\":\n    case \"embedding\": {\n      return [];\n    }\n    case \"object\": {\n      return {};\n    }\n    case \"unknown\": {\n      return undefined;\n    }\n  }\n}\n","/**\n * Selective Result Mapping for Smart Select Optimization.\n *\n * Converts rows returned from a selective projection query into the\n * SelectContext expected by the select callback, while guarding against\n * missing fields and unsupported \"return whole node/edge\" selections.\n */\nimport {\n  normalizeRequiredRowTimestamp,\n  normalizeRowTimestamp,\n} from \"../../backend/row-mappers\";\nimport type { KindEntity } from \"../../core/types\";\nimport { compareStrings, hasOwnKey } from \"../../utils\";\nimport { createDataKeyedBag, isInteropProbeKey } from \"../../utils/object\";\nimport { mergeEdgeKinds, type SelectiveField, type Traversal } from \"../ast\";\nimport type {\n  AliasMap,\n  EdgeAliasMap,\n  QueryBuilderState,\n  SelectContext,\n} from \"../builder/types\";\nimport {\n  type FieldTypeInfo,\n  type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport {\n  containsSelectableAliasObject,\n  SELECTABLE_ALIAS_MARKER,\n  type SelectableAliasMarker,\n} from \"./selectable-alias\";\nimport { decodeSelectedValue, nullToUndefined } from \"./value-decoder\";\n\n// ============================================================\n// Errors\n// ============================================================\n\nexport class MissingSelectiveFieldError extends Error {\n  readonly alias: string;\n  readonly field: string;\n\n  constructor(alias: string, field: string) {\n    super(`Smart select missing field: ${alias}.${field}`);\n    this.alias = alias;\n    this.field = field;\n  }\n}\n\n// ============================================================\n// Internal Types\n// ============================================================\n\ntype AliasKind = KindEntity;\n\ntype SystemFieldPlan = Readonly<{\n  field: string;\n  outputName: string;\n}>;\n\ntype MetaFieldPlan = Readonly<{\n  metaKey: string;\n  outputName: string;\n}>;\n\ntype PropsFieldPlan = Readonly<{\n  field: string;\n  outputName: string;\n  typeInfo: FieldTypeInfo | undefined;\n}>;\n\ntype AliasPlan = Readonly<{\n  alias: string;\n  kind: AliasKind;\n  optional: boolean;\n  systemFields: readonly SystemFieldPlan[];\n  metaFields: readonly MetaFieldPlan[];\n  propsFields: readonly PropsFieldPlan[];\n  idOutputName: string | undefined;\n  metaOutputNames: ReadonlySet<string>;\n  propsOutputNames: ReadonlySet<string>;\n  systemOutputNames: ReadonlySet<string>;\n}>;\n\nfunction normalizeMetaValue(\n  value: unknown,\n  metaKey: string,\n  alias: string,\n): unknown {\n  if (metaKey === \"version\") return nullToUndefined(value);\n  const field = `${alias}_${metaKey}`;\n  if (metaKey === \"createdAt\" || metaKey === \"updatedAt\") {\n    return normalizeRequiredRowTimestamp(value, field);\n  }\n  return normalizeRowTimestamp(value, field);\n}\n\n// ============================================================\n// Marker for \"whole alias object\" detection\n// ============================================================\n\n// ============================================================\n// Public API\n// ============================================================\n\nexport function mapSelectiveResults<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n  R,\n>(\n  rows: readonly Record<string, unknown>[],\n  state: QueryBuilderState,\n  selectiveFields: readonly SelectiveField[],\n  schemaIntrospector: SchemaIntrospector,\n  selectFunction: (context: SelectContext<Aliases, EdgeAliases>) => R,\n): readonly R[] {\n  const plans = buildAliasPlans(state, selectiveFields, schemaIntrospector);\n\n  return rows.map((row) => {\n    const context = buildSelectiveContext<Aliases, EdgeAliases>(\n      row,\n      plans,\n      state.traversals,\n    );\n    const result = selectFunction(context);\n\n    // Returning whole alias objects is not supported by selective projection.\n    // If it happens, fall back to the full fetch path.\n    if (containsSelectableAliasObject(result)) {\n      throw new MissingSelectiveFieldError(\n        state.startAlias,\n        \"whole node/edge selection\",\n      );\n    }\n\n    return result;\n  });\n}\n\n// ============================================================\n// Plan Construction\n// ============================================================\n\nfunction buildAliasPlans(\n  state: QueryBuilderState,\n  selectiveFields: readonly SelectiveField[],\n  schemaIntrospector: SchemaIntrospector,\n): readonly AliasPlan[] {\n  const aliasInfo = new Map<\n    string,\n    Readonly<{\n      kind: AliasKind;\n      optional: boolean;\n      kindNames: readonly string[];\n    }>\n  >([\n    [\n      state.startAlias,\n      {\n        kind: \"node\",\n        optional: false,\n        kindNames: state.startKinds,\n      },\n    ],\n  ]);\n\n  for (const traversal of state.traversals) {\n    const edgeKindNames = mergeEdgeKinds(traversal);\n\n    aliasInfo.set(traversal.nodeAlias, {\n      kind: \"node\",\n      optional: traversal.optional,\n      kindNames: traversal.nodeKinds,\n    });\n    aliasInfo.set(traversal.edgeAlias, {\n      kind: \"edge\",\n      optional: traversal.optional,\n      kindNames: edgeKindNames,\n    });\n  }\n\n  const fieldsByAlias = new Map<string, SelectiveField[]>();\n  for (const field of selectiveFields) {\n    const existing = fieldsByAlias.get(field.alias) ?? [];\n    existing.push(field);\n    fieldsByAlias.set(field.alias, existing);\n  }\n\n  const plans: AliasPlan[] = [];\n\n  for (const [alias, info] of aliasInfo.entries()) {\n    const fields = fieldsByAlias.get(alias) ?? [];\n\n    const systemFields: SystemFieldPlan[] = [];\n    const metaFields: MetaFieldPlan[] = [];\n    const propsFields: PropsFieldPlan[] = [];\n\n    for (const field of fields) {\n      if (field.isSystemField) {\n        if (field.field.startsWith(\"meta.\")) {\n          metaFields.push({\n            metaKey: field.field.slice(5),\n            outputName: field.outputName,\n          });\n        } else {\n          systemFields.push({\n            field: field.field,\n            outputName: field.outputName,\n          });\n        }\n      } else {\n        const typeInfo =\n          info.kind === \"node\" ?\n            schemaIntrospector.getSharedFieldTypeInfo(\n              info.kindNames,\n              field.field,\n            )\n          : schemaIntrospector.getSharedEdgeFieldTypeInfo(\n              info.kindNames,\n              field.field,\n            );\n\n        propsFields.push({\n          field: field.field,\n          outputName: field.outputName,\n          typeInfo,\n        });\n      }\n    }\n\n    const idOutputName =\n      systemFields.find((f) => f.field === \"id\")?.outputName ?? undefined;\n\n    plans.push({\n      alias,\n      kind: info.kind,\n      optional: info.optional,\n      systemFields,\n      metaFields,\n      propsFields,\n      idOutputName,\n      metaOutputNames: new Set(metaFields.map((f) => f.outputName)),\n      propsOutputNames: new Set(propsFields.map((f) => f.outputName)),\n      systemOutputNames: new Set(systemFields.map((f) => f.outputName)),\n    });\n  }\n\n  // Keep plan iteration stable.\n  return plans.toSorted((a, b) => compareStrings(a.alias, b.alias));\n}\n\n// ============================================================\n// Context Building\n// ============================================================\n\nfunction buildSelectiveContext<\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n>(\n  row: Record<string, unknown>,\n  plans: readonly AliasPlan[],\n  traversals: readonly Traversal[],\n): SelectContext<Aliases, EdgeAliases> {\n  // Data-keyed: alias names chosen by the caller's query.\n  const context = createDataKeyedBag<unknown>();\n\n  for (const plan of plans) {\n    const value =\n      plan.optional && plan.idOutputName !== undefined ?\n        buildOptionalAliasValue(row, plan)\n      : buildRequiredAliasValue(row, plan);\n    context[plan.alias] = value;\n  }\n\n  // Extract recursive depth/path values from the row\n  for (const traversal of traversals) {\n    const vl = traversal.variableLength;\n    if (vl !== undefined) {\n      if (vl.depthAlias !== undefined) {\n        context[vl.depthAlias] =\n          traversal.optional && row[vl.depthAlias] === null ?\n            undefined\n          : row[vl.depthAlias];\n      }\n      if (vl.pathAlias !== undefined) {\n        context[vl.pathAlias] = row[vl.pathAlias];\n      }\n    }\n  }\n\n  // Spread at the boundary, for the same reason as the non-selective mapper:\n  // this context reaches the caller's `select` callback.\n  return { ...context } as SelectContext<Aliases, EdgeAliases>;\n}\n\nfunction buildOptionalAliasValue(\n  row: Record<string, unknown>,\n  plan: AliasPlan,\n): unknown {\n  if (plan.idOutputName === undefined) {\n    return undefined;\n  }\n  const idValue = row[plan.idOutputName];\n\n  if (idValue === null || idValue === undefined) {\n    return undefined;\n  }\n  return buildRequiredAliasValue(row, plan);\n}\n\nfunction buildRequiredAliasValue(\n  row: Record<string, unknown>,\n  plan: AliasPlan,\n): unknown {\n  // Data-keyed: the projected field names are schema property names, and the\n  // values behind them arrive as a `JSON.parse`d props bag — which yields\n  // `__proto__` as an ordinary own key. The null prototype stays INTERNAL:\n  // `createGuardedProxy` below spreads the finished bag onto an ordinary object\n  // before proxying it, so nothing a caller can observe carries it.\n  const base = createDataKeyedBag<unknown>();\n  // The marker is keyed by SYMBOL, not by data; the cast only reaches the\n  // symbol slot of a string-keyed record.\n  (base as Record<symbol, unknown>)[SELECTABLE_ALIAS_MARKER] = {\n    alias: plan.alias,\n    kind: plan.kind,\n  } satisfies SelectableAliasMarker;\n\n  for (const field of plan.systemFields) {\n    base[field.field] = nullToUndefined(row[field.outputName]);\n  }\n\n  if (plan.metaFields.length > 0) {\n    const meta = createDataKeyedBag<unknown>();\n    for (const field of plan.metaFields) {\n      meta[field.metaKey] = normalizeMetaValue(\n        row[field.outputName],\n        field.metaKey,\n        plan.alias,\n      );\n    }\n    base[\"meta\"] = createGuardedProxy(meta, `${plan.alias}.meta`);\n  }\n\n  for (const field of plan.propsFields) {\n    const decoded = decodeSelectedValue(row[field.outputName], field.typeInfo);\n    base[field.field] = decoded;\n  }\n\n  return createGuardedProxy(base, plan.alias);\n}\n\n/**\n * Wraps a projected alias (or its `meta`) in the missing-field guard, ON AN\n * ORDINARY OBJECT.\n *\n * The spread is the boundary spread `createDataKeyedBag` documents, applied\n * HERE rather than at each call site because a proxy's target is itself\n * caller-observable: the `get` trap below re-supplies `Object.prototype`'s\n * members explicitly, but `instanceof`, `Object.getPrototypeOf`, and every\n * other internal method fall through to the TARGET, which no `get` trap can\n * disguise. Proxying a null-prototype bag therefore made `ctx.p instanceof\n * Object` answer `false` under smart selection while the full mapper — which\n * builds ordinary object literals (see `buildSelectableNode`) — answered\n * `true`: a public behavior that depended on whether the optimizer engaged.\n *\n * Spreading is safe precisely where a key-by-key rebuild would not be: it\n * copies own properties (including the alias marker symbol) with\n * CreateDataProperty rather than Set, so a projected field named `__proto__`\n * survives as an own key while `Object.prototype` is restored.\n *\n * Callers must therefore hand over a COMPLETE bag — the copy is taken here and\n * later writes to the original are invisible.\n */\nfunction createGuardedProxy(\n  target: Record<string, unknown>,\n  debugPath: string,\n): unknown {\n  return new Proxy(\n    { ...target },\n    {\n      get: (object, property: string | symbol, receiver) => {\n        if (typeof property === \"symbol\") {\n          return Reflect.get(object, property, receiver) as unknown;\n        }\n\n        // Own keys FIRST — before any protocol-name exemption. The projected\n        // row's keys are data, so `in` here would answer for `Object.prototype`\n        // members the row does not carry, and a name-identity short-circuit\n        // ahead of this branch would answer for a field the row DOES carry.\n        // Smart selection must be indistinguishable from the full mapper, whose\n        // plain objects hand back an own `then` / `toJSON` like any other\n        // property; a schema may declare either name, and such a field survives\n        // validation and the JSON round-trip as ordinary data. The boundary\n        // spread above preserves that: it copies own properties with\n        // CreateDataProperty, so every projected field — `__proto__` included —\n        // is still an own key of the target this branch reads.\n        if (hasOwnKey(object, property)) {\n          return Reflect.get(object, property, receiver);\n        }\n\n        // Reached only once the row is known NOT to carry the key: resolve the\n        // language's own probes to `undefined` so a partially projected row is\n        // not mistaken for a thenable by `await` and `JSON.stringify` still\n        // works on it. Returning stored data above is safe for `then` because\n        // props decode from JSON and can never be callable — the thenable check\n        // ignores a non-callable `then`, exactly as it does on the full path.\n        if (isInteropProbeKey(property)) {\n          return;\n        }\n\n        // Deliberately `in`, NOT hasOwnKey: this branch's whole purpose is to\n        // reach inherited `Object.prototype` members (`toString`, `valueOf`, …) so\n        // a projected row still behaves like an object. Leave it alone.\n        if (property in Object.prototype) {\n          return Reflect.get(Object.prototype, property, receiver) as unknown;\n        }\n\n        throw new MissingSelectiveFieldError(debugPath, property);\n      },\n    },\n  );\n}\n","import type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport {\n  ConfigurationError,\n  SchemaChangedError,\n  ValidationError,\n} from \"../../errors\";\nimport type { QueryAst } from \"../ast\";\nimport { buildStandardOrderBy } from \"../compiler/emitter/standard-builders\";\nimport {\n  extractFulltextMatchPredicates,\n  extractVectorSimilarityPredicates,\n} from \"../compiler/predicates\";\nimport { getDialect } from \"../dialect\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { asCompiledSelectSql, type CompiledSelectSql } from \"../sql-intent\";\n\nexport type SchemaCheckedReadInput = Readonly<{\n  backend: GraphBackend | TransactionBackend;\n  ast: QueryAst;\n  graphId: string;\n  expectedVersion: number | undefined;\n  compile: () => CompiledSelectSql;\n  /** Non-null result column used to distinguish a real row from the envelope sentinel. */\n  rowIdentityColumn?: string;\n  /** Ordering over explicitly projected columns in the checked_rows envelope. */\n  resultOrderBy?: SqlFragment;\n}>;\n\n/** A version row survives even an empty data result; both reads share one SQL snapshot. */\nexport async function executeSchemaCheckedRead(\n  input: SchemaCheckedReadInput,\n): Promise<readonly Record<string, unknown>[]> {\n  const { backend, ast, graphId, expectedVersion } = input;\n  if (\n    expectedVersion !== undefined &&\n    (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0)\n  ) {\n    throw new ValidationError(\n      \"Expected schema version must be a non-negative safe integer\",\n      {\n        issues: [\n          { path: \"expectedSchemaVersion\", message: \"Invalid schema version\" },\n        ],\n      },\n    );\n  }\n  const table = backend.tableNames?.schemaVersions;\n  if (table === undefined) {\n    throw new ConfigurationError(\n      \"Checked reads require backend.tableNames.schemaVersions\",\n      { capability: \"schemaVersions\" },\n    );\n  }\n  if (\n    ast.traversals.some(\n      (traversal) => traversal.variableLength !== undefined,\n    ) ||\n    extractFulltextMatchPredicates(ast.predicates).length > 0 ||\n    extractVectorSimilarityPredicates(ast.predicates).length > 0\n  ) {\n    throw new ConfigurationError(\n      \"Checked reads support relational queries; recursive and relevance queries require a separate schema probe\",\n      { operation: \"executeChecked\" },\n    );\n  }\n  // Every full-projection column contains the alias/field separator \"_\".\n  // An envelope name without that separator cannot collide with data columns.\n  const marker = \"typegraphschemaversion\";\n  const dialect = getDialect(backend.dialect);\n  const orderBy =\n    input.resultOrderBy ??\n    buildStandardOrderBy({\n      ast,\n      dialect,\n      collapsedTraversalCteAlias: \"checked_rows\",\n    });\n  const query = asCompiledSelectSql(sql`\n    WITH checked_rows AS (${input.compile()}),\n    checked_version AS (\n      SELECT (SELECT version FROM ${sql.identifier(table)}\n        WHERE graph_id = ${graphId} AND is_active = ${dialect.booleanLiteral(true)}) AS version\n    )\n    SELECT checked_rows.*, checked_version.version AS ${sql.identifier(marker)}\n    FROM checked_version LEFT JOIN checked_rows ON 1 = 1\n    ${orderBy ?? sql.raw(\"\")}\n  `);\n  const rows = await backend.execute<Record<string, unknown>>(query);\n  const rawVersion = rows[0]?.[marker];\n  const actual =\n    rawVersion === null || rawVersion === undefined ?\n      undefined\n    : Number(rawVersion);\n  if (actual !== expectedVersion)\n    throw new SchemaChangedError({\n      graphId,\n      expected: expectedVersion,\n      actual,\n    });\n  // The start id is non-null for every real row. Only the left-join sentinel lacks it.\n  return rows\n    .filter(\n      (row) =>\n        row[input.rowIdentityColumn ?? `${ast.start.alias}_id`] !== null &&\n        row[input.rowIdentityColumn ?? `${ast.start.alias}_id`] !== undefined,\n    )\n    .map((row) => {\n      const { [marker]: _version, ...data } = row;\n      return data;\n    });\n}\n","/**\n * Compiled-SQL template cache keyed on the reserved read-instant placeholder.\n *\n * A \"current\" (live) query bakes its valid-time read instant into the compiled\n * SQL as a bound parameter. Recompiling the whole AST on every execution just\n * to refresh that one value — the behavior PR #246 introduced to fix a frozen\n * \"now\" — is pure waste: the SQL text is byte-identical across calls, only the\n * instant differs. This module compiles the statement ONCE in `\"placeholder\"`\n * mode (the read instant becomes {@link CURRENT_READ_INSTANT_PLACEHOLDER}\n * instead of a frozen value), caches the resulting `{ sql, params }`, and fills\n * a fresh instant into the placeholder on every execution via\n * {@link fillTemplateParams}.\n *\n * The fast path requires a backend that can both compile a TypeGraph `SqlFragment`\n * to text (`compileSql`) and execute pre-compiled text (`executeRaw`). Custom\n * or async backends without those members fall back to per-call recompilation,\n * exactly as before.\n */\nimport { ConfigurationError } from \"../../errors\";\nimport { nowIso } from \"../../utils/date\";\nimport { readOwnProperty } from \"../../utils/object\";\nimport { type ComposableQuery, type QueryAst } from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { CURRENT_READ_INSTANT_PLACEHOLDER } from \"../compiler/temporal\";\nimport { getDialect } from \"../dialect\";\nimport { bindSqlValue } from \"../dialect/profile\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport { isSqlPlaceholder, type SqlFragment } from \"../sql-fragment\";\nimport { type CompiledSelectSql, isRawExecutable } from \"../sql-intent\";\n\n/**\n * A compiled statement ready for `executeRaw`: SQL text plus a positional\n * parameter list that may still contain unfilled named placeholder objects\n * (the read instant, and any user `param()` refs on a prepared query).\n */\nexport type CompiledTemplate = Readonly<{\n  sql: string;\n  params: readonly unknown[];\n}>;\n\n/** Compiles a TypeGraph `SqlFragment` to `{ sql, params }` without executing. */\ntype CompileSqlFunction = (query: SqlFragment) => CompiledTemplate;\n\n/**\n * The receiver-free slice of a backend used to build a template.\n */\nexport type SqlCompilerBackend = Readonly<{ compileSql?: CompileSqlFunction }>;\n\n/** Whether a compiled template carries the reserved read-instant placeholder. */\nfunction templateHasReadInstant(template: CompiledTemplate): boolean {\n  return template.params.some(\n    (parameter) =>\n      isSqlPlaceholder(parameter) &&\n      parameter.name === CURRENT_READ_INSTANT_PLACEHOLDER,\n  );\n}\n\n/**\n * True when a query's compiled SQL must bind a fresh \"current\" instant per\n * execution — i.e. it reads valid-time \"current\" and is not pinned to a\n * recorded instant (a recorded pin replaces the wall clock with a fixed\n * instant).\n *\n * This is the *guard's* question, not \"does the statement contain a read\n * instant\". An `includeEnded` or `includeTombstones` read drops node validity,\n * but if it expands identity its class relation still binds the wall clock for\n * the assertion window — so such a statement can carry a read instant while\n * this returns false. That is safe rather than stale: placeholder-mode\n * compilation templatizes every read-instant emission through the one\n * placeholder seam, and {@link fillTemplateParams} fills a fresh value on each\n * execution whether or not the guard demanded one. `false` only relaxes the\n * \"the placeholder MUST be present\" check, which exists to refuse caching a\n * statement that froze \"now\" into a literal.\n */\nfunction queryAstNeedsCurrentReadInstant(ast: QueryAst): boolean {\n  return ast.temporalMode.mode === \"current\" && ast.recordedAsOf === undefined;\n}\n\n/** {@link queryAstNeedsCurrentReadInstant} lifted over a set operation's operands. */\nexport function composableNeedsCurrentReadInstant(\n  query: ComposableQuery,\n): boolean {\n  if (\"__type\" in query) {\n    return (\n      composableNeedsCurrentReadInstant(query.left) ||\n      composableNeedsCurrentReadInstant(query.right)\n    );\n  }\n  return queryAstNeedsCurrentReadInstant(query);\n}\n\ntype BuildReadInstantTemplateArguments = Readonly<{\n  /** Compiles the statement in `\"placeholder\"` read-instant mode. */\n  compile: () => CompiledSelectSql;\n  /**\n   * The backend, whose `compileSql` produces the cacheable text. When it (or\n   * its `compileSql`) is absent the backend has no raw-execution fast path, so\n   * there is no template to build.\n   */\n  backend: SqlCompilerBackend | undefined;\n  /**\n   * Whether the source query requires a fresh instant per execution (see\n   * {@link queryAstNeedsCurrentReadInstant}). Used as a correctness guard: a\n   * query that needs a read instant but whose compiled template carries no\n   * read-instant placeholder has frozen \"now\" into a literal, so it is NOT\n   * safe to cache — the caller must recompile per call instead.\n   */\n  needsReadInstant: boolean;\n}>;\n\n/**\n * Compiles the reusable placeholder template, or returns `undefined` when the\n * statement cannot be safely cached (or the backend has no raw-execution fast\n * path).\n *\n * The `needsReadInstant` guard enforces the lesson of the #246 freshness\n * regression: if the query needs a \"current\" instant yet the placeholder-mode\n * compilation did not templatize one, some read-instant emission escaped the\n * placeholder seam and would freeze into the cache. Every \"current\" query in\n * the builder's compile pipeline binds its instant through the one placeholder\n * seam, so this branch is unreachable by construction today; it exists to fail\n * safe — degrading to correct-but-uncached — if a future emission path forgets\n * the mode, rather than resting the invariant on a whole-compiler proof.\n */\nexport function buildReadInstantTemplate(\n  args: BuildReadInstantTemplateArguments,\n): CompiledTemplate | undefined {\n  const { backend } = args;\n  if (backend?.compileSql === undefined) return undefined;\n\n  const compiled = args.compile();\n  // A statement whose execution semantics ride on the compiled SQL OBJECT\n  // (pgvector ANN GUCs, force-custom-plan) loses them when flattened to raw\n  // text, so it can't take the executeRaw fast path — the caller falls back to\n  // backend.execute, which honors the brand. See isRawExecutable.\n  if (!isRawExecutable(compiled)) return undefined;\n\n  const template = backend.compileSql(compiled);\n  if (args.needsReadInstant && !templateHasReadInstant(template)) {\n    return undefined;\n  }\n  return template;\n}\n\n/**\n * Convenience over {@link buildReadInstantTemplate} for a standard (non\n * set-operation) query: compiles `ast` in placeholder mode via\n * {@link compileQuery} and derives {@link queryAstNeedsCurrentReadInstant}.\n * Set operations call {@link buildReadInstantTemplate} directly with their own\n * compile function and composable need-check.\n */\nexport function buildQueryTemplate(\n  ast: QueryAst,\n  graphId: string,\n  compileOptions: CompileQueryOptions,\n  backend: SqlCompilerBackend | undefined,\n): CompiledTemplate | undefined {\n  return buildReadInstantTemplate({\n    compile: () =>\n      compileQuery(ast, graphId, {\n        ...compileOptions,\n        readInstant: \"placeholder\",\n      }),\n    backend,\n    needsReadInstant: queryAstNeedsCurrentReadInstant(ast),\n  });\n}\n\nconst EMPTY_LIST_PARAMETERS: ReadonlyMap<string, unknown> = new Map();\n\n/**\n * Resolves a template's positional parameters for `executeRaw`, replacing\n * every {@link Placeholder} with a concrete value:\n *\n * - the reserved read-instant placeholder → a single fresh {@link nowIso}\n *   sampled once and shared by every occurrence, preserving the \"one instant\n *   per statement\" invariant the literal path guaranteed;\n * - a user `param()` placeholder → its binding, mapped the same way the\n *   compile path binds a literal (Date → ISO string; everything else through\n *   the dialect's `bindValue`);\n * - a list-valued `param()` placeholder (the whole right side of\n *   `in()`/`notIn()`) → the dialect's packed representation of the array, so\n *   the statement binds ONE value no matter how long the list is.\n */\nexport function fillTemplateParams(\n  params: readonly unknown[],\n  bindings: Readonly<Record<string, unknown>>,\n  dialect: SqlDialect,\n  listParameters: ReadonlyMap<string, unknown> = EMPTY_LIST_PARAMETERS,\n): unknown[] {\n  let readInstant: string | undefined;\n  return params.map((parameter) => {\n    if (!isSqlPlaceholder(parameter)) return parameter;\n\n    const name = parameter.name;\n    if (name === CURRENT_READ_INSTANT_PLACEHOLDER) {\n      readInstant ??= nowIso();\n      return readInstant;\n    }\n\n    // Own-key read: a parameter named after an `Object.prototype` member must\n    // read as an absent binding, not as the inherited member (the same guard\n    // `bindSqlValue`'s placeholder path applies).\n    const value = readOwnProperty(bindings, name);\n    if (value === undefined) {\n      throw new ConfigurationError(`Missing binding for parameter \"${name}\"`, {\n        parameterName: name,\n      });\n    }\n    if (listParameters.has(name)) {\n      assertListBinding(name, value);\n      return getDialect(dialect).packListValue(value);\n    }\n    return bindSqlValue(value, dialect);\n  });\n}\n\n/**\n * Narrows a binding destined for an `in()`/`notIn()` parameter to an array.\n * An empty array is valid — it compiles to an empty relation, matching the\n * literal `in([])` short circuit.\n */\nexport function assertListBinding(\n  name: string,\n  value: unknown,\n): asserts value is readonly unknown[] {\n  if (Array.isArray(value)) return;\n  throw new ConfigurationError(\n    `Parameter \"${name}\" must be an array for in()/notIn()`,\n    { parameterName: name, actualType: typeof value },\n  );\n}\n","/**\n * PreparedQuery — a pre-validated, parameterized query.\n *\n * Created via `ExecutableQuery.prepare()`. Builds and structurally validates\n * the query AST once at prepare time (so a malformed query fails fast, before\n * the first `execute()`).\n *\n * Fast path: when the backend can compile and run raw SQL (`compileSql` +\n * `executeRaw`) AND the statement is raw-executable, it is compiled ONCE\n * into a cached template whose\n * \"current\" read instant and user `param()` refs are reserved placeholders\n * (see {@link buildReadInstantTemplate}). Every `execute()` fills those\n * placeholders — a fresh instant plus the call's bindings — and runs the\n * cached SQL text directly, so a reused prepared query never recompiles and\n * never freezes \"now\" the way a cached literal instant would (the #246\n * regression).\n *\n * Fallback: substitutes parameter refs into the AST, compiles fresh per call,\n * and executes via the standard `backend.execute` path. Taken in two cases —\n * a backend without raw execution (custom/async), and a statement that is not\n * raw-executable because its execution semantics ride on the compiled SQL\n * OBJECT rather than its text (approximate vector search's iterative-scan\n * wrapper, `subgraph()`'s force-custom-plan fetches). The second applies even\n * on PostgreSQL with `executeRaw` available; `isRawExecutable` in\n * `sql-intent.ts` is the predicate that decides it.\n */\nimport { type GraphBackend } from \"../../backend/types\";\nimport { ConfigurationError, UnsupportedPredicateError } from \"../../errors\";\nimport { readOwnProperty } from \"../../utils/object\";\nimport {\n  type BetweenPredicate,\n  type ComparisonOp,\n  type ComparisonPredicate,\n  type ComposableQuery,\n  type LiteralValue,\n  type PredicateExpression,\n  type QueryAst,\n  type SelectiveField,\n  type StringPredicate,\n  type ValueType,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { resolveParameterValueType } from \"../compiler/predicates\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n  mapResults,\n  mapSelectiveResults,\n  MissingSelectiveFieldError,\n  transformPathColumns,\n} from \"../execution\";\nimport {\n  collectOperandExpressions,\n  type DatabaseExpression,\n  isCollectRecordOperand,\n  normalizeDatabaseLiteral,\n} from \"../expressions\";\nimport { isParameterRef } from \"../predicates\";\nimport { type SchemaIntrospector } from \"../schema-introspector\";\nimport {\n  assertListBinding,\n  buildQueryTemplate,\n  type CompiledTemplate,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n  type AliasMap,\n  type EdgeAliasMap,\n  type QueryBuilderState,\n  type SelectContext,\n} from \"./types\";\n\n// ============================================================\n// Parameter Substitution\n// ============================================================\n\nfunction toLiteral(value: unknown): LiteralValue {\n  if (value === null) {\n    throw new ConfigurationError(\n      \"Parameter value must not be null (use undefined-based patterns instead)\",\n      { parameterName: \"value\", valueType: \"null\" },\n    );\n  }\n  if (value instanceof Date) {\n    return { __type: \"literal\", value: value.toISOString(), valueType: \"date\" };\n  }\n  if (typeof value === \"string\") {\n    return { __type: \"literal\", value, valueType: \"string\" };\n  }\n  if (typeof value === \"number\") {\n    return { __type: \"literal\", value, valueType: \"number\" };\n  }\n  if (typeof value === \"boolean\") {\n    return { __type: \"literal\", value, valueType: \"boolean\" };\n  }\n  throw new ConfigurationError(\n    `Unsupported parameter value type: ${typeof value}`,\n    { parameterName: \"value\", actualType: typeof value },\n  );\n}\n\n/** Whether a comparison operator takes a list of values rather than a scalar. */\nfunction isListComparisonOp(op: ComparisonOp): boolean {\n  return op === \"in\" || op === \"notIn\";\n}\n\n/**\n * Expands a list-valued binding into the literal array the compiler's\n * non-parameterized `in`/`notIn` path expects. Used only on the fallback\n * (no `executeRaw`) path — the fast path keeps the list packed behind a\n * single placeholder.\n */\nfunction toLiteralList(parameterName: string, value: unknown): LiteralValue[] {\n  assertListBinding(parameterName, value);\n  return value.map((element) => toLiteral(element));\n}\n\n/**\n * Walks a predicate expression tree and replaces ParameterRef nodes\n * with LiteralValue nodes using the provided bindings.\n */\nfunction substitutePredicateExpression(\n  expr: PredicateExpression,\n  bindings: Readonly<Record<string, unknown>>,\n): PredicateExpression {\n  switch (expr.__type) {\n    case \"comparison\": {\n      if (isParameterRef(expr.right)) {\n        const value = resolveBinding(bindings, expr.right.name);\n        return {\n          ...expr,\n          right:\n            isListComparisonOp(expr.op) ?\n              toLiteralList(expr.right.name, value)\n            : toLiteral(value),\n        } satisfies ComparisonPredicate;\n      }\n      return expr;\n    }\n\n    case \"tuple_comparison\": {\n      return expr;\n    }\n\n    case \"string_op\": {\n      if (isParameterRef(expr.pattern)) {\n        const value = readOwnProperty(bindings, expr.pattern.name);\n        if (value === undefined) {\n          throw new ConfigurationError(\n            `Missing binding for parameter \"${expr.pattern.name}\"`,\n            { parameterName: expr.pattern.name },\n          );\n        }\n        if (typeof value !== \"string\") {\n          throw new ConfigurationError(\n            `Parameter \"${expr.pattern.name}\" must be a string for string operations`,\n            { parameterName: expr.pattern.name, actualType: typeof value },\n          );\n        }\n        return {\n          ...expr,\n          pattern: value,\n        } satisfies StringPredicate;\n      }\n      return expr;\n    }\n\n    case \"between\": {\n      const lowerIsParam = isParameterRef(expr.lower);\n      const upperIsParam = isParameterRef(expr.upper);\n      if (!lowerIsParam && !upperIsParam) return expr;\n\n      const lower =\n        lowerIsParam ?\n          toLiteral(resolveBinding(bindings, expr.lower.name))\n        : expr.lower;\n      const upper =\n        upperIsParam ?\n          toLiteral(resolveBinding(bindings, expr.upper.name))\n        : expr.upper;\n      return { ...expr, lower, upper } satisfies BetweenPredicate;\n    }\n\n    case \"and\": {\n      return {\n        ...expr,\n        predicates: expr.predicates.map((p) =>\n          substitutePredicateExpression(p, bindings),\n        ),\n      };\n    }\n\n    case \"or\": {\n      return {\n        ...expr,\n        predicates: expr.predicates.map((p) =>\n          substitutePredicateExpression(p, bindings),\n        ),\n      };\n    }\n\n    case \"not\": {\n      return {\n        ...expr,\n        predicate: substitutePredicateExpression(expr.predicate, bindings),\n      };\n    }\n\n    case \"database_expression_predicate\": {\n      return {\n        ...expr,\n        expression: substituteDatabaseExpression(expr.expression, bindings),\n      };\n    }\n\n    // These predicate types don't contain ParameterRef nodes\n    case \"null_check\":\n    case \"array_op\":\n    case \"object_op\":\n    case \"aggregate_comparison\":\n    case \"vector_similarity\":\n    case \"fulltext_match\": {\n      return expr;\n    }\n\n    case \"exists\": {\n      return {\n        ...expr,\n        subquery: substituteParameters(expr.subquery, bindings),\n      };\n    }\n\n    case \"in_subquery\": {\n      return {\n        ...expr,\n        subquery: substituteParameters(expr.subquery, bindings),\n      };\n    }\n  }\n}\n\nexport function substituteDatabaseExpression<T, Scope extends string>(\n  expression: DatabaseExpression<T, Scope>,\n  bindings: Readonly<Record<string, unknown>>,\n): DatabaseExpression<T, Scope> {\n  const node = expression.node;\n  function substitute(operand: DatabaseExpression): DatabaseExpression {\n    return substituteDatabaseExpression(operand, bindings);\n  }\n  switch (node.kind) {\n    case \"parameter\": {\n      const value = resolveBinding(bindings, node.name);\n      if (value === null) {\n        throw new ConfigurationError(\n          `Parameter \"${node.name}\" must not be null`,\n          { parameterName: node.name, valueType: \"null\" },\n        );\n      }\n      return {\n        ...expression,\n        node: {\n          kind: \"literal\",\n          value: normalizeDatabaseLiteral(value, `$parameter.${node.name}`),\n        },\n      };\n    }\n    case \"arithmetic\":\n    case \"comparison\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          left: substitute(node.left),\n          right: substitute(node.right),\n        },\n      };\n    }\n    case \"array_contains\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          array: substitute(node.array),\n          element: substitute(node.element),\n        },\n      };\n    }\n    case \"boolean\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          operands: node.operands.map((operand) =>\n            substitute(operand),\n          ) as readonly DatabaseExpression<boolean | undefined>[],\n        },\n      };\n    }\n    case \"not\":\n    case \"null_check\":\n    case \"numeric_conversion\": {\n      const operand = substitute(node.operand);\n      return {\n        ...expression,\n        node: { ...node, operand },\n      } as DatabaseExpression<T, Scope>;\n    }\n    case \"aggregate\": {\n      return node.operand === undefined ?\n          expression\n        : {\n            ...expression,\n            node: { ...node, operand: substitute(node.operand) },\n          };\n    }\n    case \"collect\": {\n      const operand = node.operand;\n      return {\n        ...expression,\n        node: {\n          ...node,\n          operand:\n            isCollectRecordOperand(operand) ?\n              {\n                kind: \"record\",\n                fields: Object.fromEntries(\n                  Object.entries(operand.fields).map(([name, value]) => [\n                    name,\n                    substitute(value),\n                  ]),\n                ),\n              }\n            : substitute(operand),\n          ...(node.filter === undefined ?\n            {}\n          : {\n              filter: substitute(node.filter) as typeof node.filter,\n            }),\n          orderBy: node.orderBy.map((order) => ({\n            ...order,\n            expression: substitute(order.expression) as typeof order.expression,\n          })),\n        },\n      };\n    }\n    case \"coalesce\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          operands: node.operands.map((operand) => substitute(operand)),\n        },\n      };\n    }\n    case \"conditional\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          condition: substitute(node.condition) as DatabaseExpression<\n            boolean | undefined\n          >,\n          // This is AST data, never a promise-like runtime object.\n          // eslint-disable-next-line unicorn/no-thenable\n          then: substitute(node.then),\n          otherwise: substitute(node.otherwise),\n        },\n      };\n    }\n    case \"outer_reference\": {\n      return {\n        ...expression,\n        node: { ...node, expression: substitute(node.expression) },\n      };\n    }\n    case \"exists_subquery\":\n    case \"scalar_subquery\": {\n      return {\n        ...expression,\n        node: {\n          ...node,\n          subquery: substituteParameters(node.subquery, bindings),\n        },\n      };\n    }\n    case \"field\":\n    case \"literal\": {\n      return expression;\n    }\n  }\n}\n\n// Own-key reads throughout this module: `bindings` is a caller-supplied\n// data-keyed bag and `name` is a `param()` name, so a raw read would answer a\n// parameter named after an `Object.prototype` member with the inherited member\n// — defeating the missing-binding check and binding a function into the\n// statement. `bindSqlValue`'s placeholder path already guards this way.\nfunction resolveBinding(\n  bindings: Readonly<Record<string, unknown>>,\n  name: string,\n): unknown {\n  const value = readOwnProperty(bindings, name);\n  if (value === undefined) {\n    throw new ConfigurationError(`Missing binding for parameter \"${name}\"`, {\n      parameterName: name,\n    });\n  }\n  return value;\n}\n\n/**\n * Substitutes all ParameterRef nodes in a QueryAst with concrete values.\n */\nfunction substituteParameters(\n  ast: QueryAst,\n  bindings: Readonly<Record<string, unknown>>,\n): QueryAst {\n  return {\n    ...ast,\n    traversals: ast.traversals.map((traversal) => {\n      const variableLength = traversal.variableLength;\n      if (variableLength?.stopExpansion === undefined) return traversal;\n      const stopExpansion = variableLength.stopExpansion;\n      return {\n        ...traversal,\n        variableLength: {\n          ...variableLength,\n          stopExpansion: {\n            ...stopExpansion,\n            expression: substitutePredicateExpression(\n              stopExpansion.expression,\n              bindings,\n            ),\n          },\n        },\n      };\n    }),\n    predicates: ast.predicates.map((pred) => ({\n      ...pred,\n      expression: substitutePredicateExpression(pred.expression, bindings),\n    })),\n    ...(ast.having !== undefined && {\n      having: substitutePredicateExpression(ast.having, bindings),\n    }),\n    ...(ast.resultPredicate !== undefined && {\n      resultPredicate: substitutePredicateExpression(\n        ast.resultPredicate,\n        bindings,\n      ),\n    }),\n    projection: {\n      ...ast.projection,\n      fields: ast.projection.fields.map((projection) =>\n        projection.source.__type === \"database_expression\" ?\n          {\n            ...projection,\n            source: substituteDatabaseExpression(projection.source, bindings),\n          }\n        : projection,\n      ),\n    },\n    ...(ast.groupBy !== undefined && {\n      groupBy: {\n        fields: ast.groupBy.fields.map((field) =>\n          field.__type === \"database_expression\" ?\n            substituteDatabaseExpression(field, bindings)\n          : field,\n        ),\n      },\n    }),\n    ...(ast.orderBy !== undefined && {\n      orderBy: ast.orderBy.map((order) => ({\n        ...order,\n        field:\n          order.field.__type === \"database_expression\" ?\n            substituteDatabaseExpression(order.field, bindings)\n          : order.field,\n      })),\n    }),\n  };\n}\n\n// ============================================================\n// PreparedQuery\n// ============================================================\n\ntype PreparedQueryConfig<R> = Readonly<{\n  ast: QueryAst;\n  unoptimizedAst: QueryAst;\n  backend: GraphBackend;\n  dialect: SqlDialect;\n  graphId: string;\n  compileOptions: CompileQueryOptions;\n  state: QueryBuilderState;\n  selectiveFields: readonly SelectiveField[] | undefined;\n  selectFn: (context: SelectContext<AliasMap, EdgeAliasMap>) => R;\n  schemaIntrospector: SchemaIntrospector;\n}>;\n\n/**\n * A pre-validated, parameterized query — see the module doc comment above for\n * how a reused prepared query runs a cached SQL template with a fresh read\n * instant filled per call.\n *\n * @example\n * ```typescript\n * const prepared = store.query()\n *   .from(\"Person\", \"p\")\n *   .whereNode(\"p\", (p) => p.name.eq(param(\"name\")))\n *   .select((ctx) => ctx.p)\n *   .prepare();\n *\n * // Execute with different bindings\n * const alice = await prepared.execute({ name: \"Alice\" });\n * const bob = await prepared.execute({ name: \"Bob\" });\n * ```\n */\nexport class PreparedQuery<R> {\n  readonly #ast: QueryAst;\n  readonly #unoptimizedAst: QueryAst;\n  readonly #backend: GraphBackend;\n  readonly #dialect: SqlDialect;\n  readonly #graphId: string;\n  readonly #compileOptions: CompileQueryOptions;\n  readonly #state: QueryBuilderState;\n  readonly #selectiveFields: readonly SelectiveField[] | undefined;\n  readonly #selectFn: (context: SelectContext<AliasMap, EdgeAliasMap>) => R;\n  readonly #schemaIntrospector: SchemaIntrospector;\n  readonly #parameterMetadata: ParameterMetadata;\n  #selectiveExecutionDisabled = false;\n  /**\n   * Per-AST cached placeholder template, keyed by AST reference so the\n   * optimized (`#ast`) and unoptimized (`#unoptimizedAst`) variants cache\n   * independently. A cached `undefined` records \"no fast-path template\" (the\n   * backend lacks `compileSql`, or the statement was not safely cacheable) so\n   * we don't rebuild it on every call.\n   */\n  readonly #templateCache = new Map<QueryAst, CompiledTemplate | undefined>();\n\n  constructor(config: PreparedQueryConfig<R>) {\n    this.#ast = config.ast;\n    this.#unoptimizedAst = config.unoptimizedAst;\n    this.#backend = config.backend;\n    this.#dialect = config.dialect;\n    this.#graphId = config.graphId;\n    this.#compileOptions = config.compileOptions;\n    this.#state = config.state;\n    this.#selectiveFields = config.selectiveFields;\n    this.#selectFn = config.selectFn;\n    this.#schemaIntrospector = config.schemaIntrospector;\n    this.#parameterMetadata = collectParameterMetadata(this.#ast);\n    assertDistinctParameterRoles(this.#parameterMetadata);\n  }\n\n  /**\n   * The cached placeholder template for `ast`, or `undefined` when no fast\n   * path applies. Compiled once (in placeholder mode) and reused across every\n   * `execute()`; the read instant is refreshed per call by\n   * {@link fillTemplateParams}, never frozen into the cache.\n   */\n  #template(ast: QueryAst): CompiledTemplate | undefined {\n    if (this.#templateCache.has(ast)) return this.#templateCache.get(ast);\n    const template = this.#buildTemplate(ast);\n    this.#templateCache.set(ast, template);\n    return template;\n  }\n\n  #buildTemplate(ast: QueryAst): CompiledTemplate | undefined {\n    return buildQueryTemplate(\n      ast,\n      this.#graphId,\n      this.#compileOptions,\n      this.#backend,\n    );\n  }\n\n  /** The set of parameter names required by this prepared query. */\n  get parameterNames(): ReadonlySet<string> {\n    return this.#parameterMetadata.names;\n  }\n\n  /**\n   * Executes the prepared query with the given parameter bindings.\n   *\n   * @param bindings - A record mapping parameter names to their values\n   * @returns The query results\n   */\n  async execute(\n    bindings: Readonly<Record<string, unknown>> = {},\n  ): Promise<readonly R[]> {\n    validateBindings(bindings, this.#parameterMetadata);\n\n    if (\n      this.#selectiveFields !== undefined &&\n      !this.#selectiveExecutionDisabled\n    ) {\n      try {\n        const rows = await this.#executeSelectiveRows(bindings);\n        return mapSelectiveResults<AliasMap, EdgeAliasMap, R>(\n          rows,\n          this.#state,\n          this.#selectiveFields,\n          this.#schemaIntrospector,\n          this.#selectFn,\n        );\n      } catch (error) {\n        if (error instanceof MissingSelectiveFieldError) {\n          // The compiled projection lacks a field the select callback can read.\n          // That is a property of the callback/projection pair, not of this\n          // call's bindings, so retrying the same projection on every execute\n          // would permanently double the statement count.\n          this.#selectiveExecutionDisabled = true;\n          return this.#executeUnoptimized(bindings);\n        }\n        if (error instanceof UnsupportedPredicateError) {\n          // This failure can depend on the bound values. Keep the optimized\n          // path available for a later execution with different bindings.\n          return this.#executeUnoptimized(bindings);\n        }\n        throw error;\n      }\n    }\n\n    return this.#executeUnoptimized(bindings);\n  }\n\n  async #executeSelectiveRows(\n    bindings: Readonly<Record<string, unknown>>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    return this.#executeRows(this.#ast, bindings);\n  }\n\n  async #executeUnoptimized(\n    bindings: Readonly<Record<string, unknown>>,\n  ): Promise<readonly R[]> {\n    const rows = await this.#executeUnoptimizedRows(bindings);\n    return mapResults<AliasMap, EdgeAliasMap, R>(\n      rows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    );\n  }\n\n  async #executeUnoptimizedRows(\n    bindings: Readonly<Record<string, unknown>>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    return this.#executeRows(this.#unoptimizedAst, bindings);\n  }\n\n  /**\n   * Runs one AST variant with the given bindings. Prefers the cached template\n   * + `executeRaw` fast path; falls back to substituting bindings into the AST\n   * and compiling fresh when the backend cannot execute raw SQL text.\n   */\n  async #executeRows(\n    ast: QueryAst,\n    bindings: Readonly<Record<string, unknown>>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    const executeRaw = this.#backend.executeRaw;\n    const template = executeRaw === undefined ? undefined : this.#template(ast);\n    if (template !== undefined && executeRaw !== undefined) {\n      const params = fillTemplateParams(\n        template.params,\n        bindings,\n        this.#dialect,\n        this.#parameterMetadata.listParameters,\n      );\n      const rawRows = await executeRaw<Record<string, unknown>>(\n        template.sql,\n        params,\n      );\n      return transformPathColumns(rawRows, this.#state, this.#dialect);\n    }\n\n    const concreteAst = substituteParameters(ast, bindings);\n    const compiled = compileQuery(\n      concreteAst,\n      this.#graphId,\n      this.#compileOptions,\n    );\n    const rawRows =\n      await this.#backend.execute<Record<string, unknown>>(compiled);\n    return transformPathColumns(rawRows, this.#state, this.#dialect);\n  }\n}\n\nexport type ParameterMetadata = Readonly<{\n  names: ReadonlySet<string>;\n  /** Parameters used in string_op predicates (must receive string values). */\n  stringOpParameters: ReadonlySet<string>;\n  /**\n   * Parameters used as the whole list of `in`/`notIn`, mapped to the element\n   * type their bindings must have. `undefined` means the schema declares\n   * nothing usable, so no element check applies.\n   */\n  listParameters: ReadonlyMap<string, ValueType | undefined>;\n  /** Parameters used in any position that binds a single scalar. */\n  scalarParameters: ReadonlySet<string>;\n  expressionParameters: ReadonlySet<string>;\n  expressionParameterTypes: ReadonlyMap<string, ValueType>;\n  /** Names bound in two `in`/`notIn` positions with different element types. */\n  conflictingElementTypes: ReadonlySet<string>;\n}>;\n\n/** The mutable form {@link collectParameterMetadataFromAst} fills. */\ntype ParameterMetadataAccumulator = Readonly<{\n  names: Set<string>;\n  stringOpParameters: Set<string>;\n  listParameters: Map<string, ValueType | undefined>;\n  scalarParameters: Set<string>;\n  expressionParameters: Set<string>;\n  expressionParameterTypes: Map<string, ValueType>;\n  /** Names bound in two `in`/`notIn` positions with different element types. */\n  conflictingElementTypes: Set<string>;\n}>;\n\nexport function collectParameterMetadata(\n  ast: QueryAst | readonly QueryAst[],\n  expressions: readonly DatabaseExpression[] = [],\n): ParameterMetadata {\n  const accumulator: ParameterMetadataAccumulator = {\n    names: new Set<string>(),\n    stringOpParameters: new Set<string>(),\n    listParameters: new Map<string, ValueType | undefined>(),\n    scalarParameters: new Set<string>(),\n    expressionParameters: new Set<string>(),\n    expressionParameterTypes: new Map<string, ValueType>(),\n    conflictingElementTypes: new Set<string>(),\n  };\n\n  const queries: readonly QueryAst[] =\n    Array.isArray(ast) ? ast : [ast as QueryAst];\n  for (const query of queries)\n    collectParameterMetadataFromAst(query, accumulator);\n  for (const expression of expressions)\n    collectParameterMetadataFromDatabaseExpression(expression, accumulator);\n\n  return accumulator;\n}\n\n/**\n * A name used both as a whole list and as a scalar cannot be satisfied by one\n * binding — the same value would have to be an array in one position and a\n * scalar in the other. Called at prepare time so the query fails before its\n * first execute() rather than on whichever binding happens to arrive.\n */\nfunction assertDistinctParameterRoles(metadata: ParameterMetadata): void {\n  if (metadata.conflictingElementTypes.size > 0) {\n    const names = [...metadata.conflictingElementTypes];\n    throw new ConfigurationError(\n      `Parameter${names.length === 1 ? \"\" : \"s\"} ${names.map((name) => `\"${name}\"`).join(\", \")} bound as an in()/notIn() list against fields of different types; one list cannot satisfy both`,\n      { conflictingParameters: names },\n    );\n  }\n\n  const conflicting = [...metadata.listParameters.keys()].filter((name) =>\n    metadata.scalarParameters.has(name),\n  );\n  if (conflicting.length === 0) return;\n\n  throw new ConfigurationError(\n    `Parameter${conflicting.length === 1 ? \"\" : \"s\"} ${conflicting.map((name) => `\"${name}\"`).join(\", \")} used both as an in()/notIn() list and as a scalar value`,\n    { conflictingParameters: conflicting },\n  );\n}\n\n/**\n * Records the element type a list parameter's bindings must have.\n *\n * A name reused across two `in()` positions keeps the declared type when only\n * one side declares one; two *different* declared types are irreconcilable —\n * one array cannot be both — so the name is flagged and `prepare()` rejects it.\n */\nfunction recordListElementType(\n  accumulator: ParameterMetadataAccumulator,\n  name: string,\n  elementType: ValueType | undefined,\n): void {\n  if (!accumulator.listParameters.has(name)) {\n    accumulator.listParameters.set(name, elementType);\n    return;\n  }\n  const existing = accumulator.listParameters.get(name);\n  if (existing === undefined) {\n    accumulator.listParameters.set(name, elementType);\n    return;\n  }\n  if (elementType !== undefined && elementType !== existing) {\n    accumulator.conflictingElementTypes.add(name);\n  }\n}\n\nexport function hasParameterReferences(ast: QueryAst): boolean {\n  return collectParameterMetadata(ast).names.size > 0;\n}\n\nexport function composableQueryHasParameterReferences(\n  query: ComposableQuery,\n): boolean {\n  if (\"__type\" in query) {\n    return (\n      composableQueryHasParameterReferences(query.left) ||\n      composableQueryHasParameterReferences(query.right)\n    );\n  }\n  return hasParameterReferences(query);\n}\n\nfunction collectParameterMetadataFromAst(\n  ast: QueryAst,\n  accumulator: ParameterMetadataAccumulator,\n): void {\n  for (const predicate of ast.predicates) {\n    collectParameterMetadataFromExpression(predicate.expression, accumulator);\n  }\n  if (ast.resultPredicate !== undefined) {\n    collectParameterMetadataFromExpression(ast.resultPredicate, accumulator);\n  }\n  for (const traversal of ast.traversals) {\n    const stopExpression = traversal.variableLength?.stopExpansion?.expression;\n    if (stopExpression !== undefined)\n      collectParameterMetadataFromExpression(stopExpression, accumulator);\n  }\n  if (ast.having !== undefined) {\n    collectParameterMetadataFromExpression(ast.having, accumulator);\n  }\n  for (const projection of ast.projection.fields) {\n    if (projection.source.__type === \"database_expression\") {\n      collectParameterMetadataFromDatabaseExpression(\n        projection.source,\n        accumulator,\n      );\n    }\n  }\n  for (const field of ast.groupBy?.fields ?? []) {\n    if (field.__type === \"database_expression\") {\n      collectParameterMetadataFromDatabaseExpression(field, accumulator);\n    }\n  }\n  for (const order of ast.orderBy ?? []) {\n    if (order.field.__type === \"database_expression\") {\n      collectParameterMetadataFromDatabaseExpression(order.field, accumulator);\n    }\n  }\n}\n\nfunction collectParameterMetadataFromDatabaseExpression(\n  expression: DatabaseExpression,\n  accumulator: ParameterMetadataAccumulator,\n): void {\n  const node = expression.node;\n  function collect(operand: DatabaseExpression): void {\n    collectParameterMetadataFromDatabaseExpression(operand, accumulator);\n  }\n  switch (node.kind) {\n    case \"parameter\": {\n      const existingType = accumulator.expressionParameterTypes.get(node.name);\n      if (existingType !== undefined && existingType !== expression.valueType)\n        throw new ConfigurationError(\n          `Parameter \"${node.name}\" is used with incompatible expression types`,\n          {\n            parameterName: node.name,\n            expectedType: existingType,\n            actualType: expression.valueType,\n          },\n        );\n      accumulator.names.add(node.name);\n      accumulator.scalarParameters.add(node.name);\n      accumulator.expressionParameters.add(node.name);\n      accumulator.expressionParameterTypes.set(node.name, expression.valueType);\n      return;\n    }\n    case \"arithmetic\":\n    case \"comparison\": {\n      collect(node.left);\n      collect(node.right);\n      return;\n    }\n    case \"array_contains\": {\n      collect(node.array);\n      collect(node.element);\n      return;\n    }\n    case \"boolean\":\n    case \"coalesce\": {\n      for (const operand of node.operands) collect(operand);\n      return;\n    }\n    case \"not\":\n    case \"null_check\":\n    case \"numeric_conversion\":\n    case \"outer_reference\": {\n      collect(node.kind === \"outer_reference\" ? node.expression : node.operand);\n      return;\n    }\n    case \"aggregate\": {\n      if (node.operand !== undefined) collect(node.operand);\n      return;\n    }\n    case \"collect\": {\n      for (const operand of collectOperandExpressions(node.operand))\n        collect(operand);\n      for (const order of node.orderBy) collect(order.expression);\n      if (node.filter !== undefined) collect(node.filter);\n      return;\n    }\n    case \"conditional\": {\n      collect(node.condition);\n      collect(node.then);\n      collect(node.otherwise);\n      return;\n    }\n    case \"exists_subquery\":\n    case \"scalar_subquery\": {\n      collectParameterMetadataFromAst(node.subquery, accumulator);\n      return;\n    }\n    case \"field\":\n    case \"literal\": {\n      return;\n    }\n  }\n}\n\nfunction collectParameterMetadataFromExpression(\n  expression: PredicateExpression,\n  accumulator: ParameterMetadataAccumulator,\n): void {\n  switch (expression.__type) {\n    case \"comparison\": {\n      if (isParameterRef(expression.right)) {\n        const name = expression.right.name;\n        accumulator.names.add(name);\n        if (isListComparisonOp(expression.op)) {\n          recordListElementType(\n            accumulator,\n            name,\n            resolveParameterValueType(expression.left, expression.right),\n          );\n        } else {\n          accumulator.scalarParameters.add(name);\n        }\n      }\n      return;\n    }\n    case \"string_op\": {\n      if (isParameterRef(expression.pattern)) {\n        accumulator.names.add(expression.pattern.name);\n        accumulator.scalarParameters.add(expression.pattern.name);\n        accumulator.stringOpParameters.add(expression.pattern.name);\n      }\n      return;\n    }\n    case \"between\": {\n      for (const bound of [expression.lower, expression.upper]) {\n        if (isParameterRef(bound)) {\n          accumulator.names.add(bound.name);\n          accumulator.scalarParameters.add(bound.name);\n        }\n      }\n      return;\n    }\n    case \"and\":\n    case \"or\": {\n      for (const predicate of expression.predicates) {\n        collectParameterMetadataFromExpression(predicate, accumulator);\n      }\n      return;\n    }\n    case \"not\": {\n      collectParameterMetadataFromExpression(expression.predicate, accumulator);\n      return;\n    }\n    case \"database_expression_predicate\": {\n      collectParameterMetadataFromDatabaseExpression(\n        expression.expression,\n        accumulator,\n      );\n      return;\n    }\n    case \"null_check\":\n    case \"tuple_comparison\":\n    case \"array_op\":\n    case \"object_op\":\n    case \"aggregate_comparison\":\n    case \"vector_similarity\":\n    case \"fulltext_match\": {\n      return;\n    }\n    case \"exists\":\n    case \"in_subquery\": {\n      collectParameterMetadataFromAst(expression.subquery, accumulator);\n      return;\n    }\n  }\n}\n\n/** Validates and substitutes every parameter used by a query AST. */\nexport function bindQueryParameters(\n  ast: QueryAst,\n  bindings: Readonly<Record<string, unknown>>,\n): QueryAst {\n  const metadata = collectParameterMetadata(ast);\n  assertDistinctParameterRoles(metadata);\n  validateBindings(bindings, metadata);\n  return substituteParameters(ast, bindings);\n}\n\n/** Validates a complete composed relation before its leaves bind their own subset. */\nexport function validateQueryBindings(\n  queries: readonly QueryAst[],\n  bindings: Readonly<Record<string, unknown>>,\n  expressions: readonly DatabaseExpression[] = [],\n): void {\n  const metadata = collectParameterMetadata(queries, expressions);\n  assertDistinctParameterRoles(metadata);\n  validateBindings(bindings, metadata);\n}\n\n/** The complete relation validates its bindings before individual leaves bind their subset. */\nexport function bindQueryParametersSubset(\n  ast: QueryAst,\n  bindings: Readonly<Record<string, unknown>>,\n): QueryAst {\n  const names = collectParameterMetadata(ast).names;\n  return bindQueryParameters(\n    ast,\n    Object.fromEntries(\n      [...names].map((name) => [name, readOwnProperty(bindings, name)]),\n    ),\n  );\n}\n\nfunction validateBindings(\n  bindings: Readonly<Record<string, unknown>>,\n  metadata: ParameterMetadata,\n): void {\n  const {\n    expressionParameters,\n    expressionParameterTypes,\n    names: expectedNames,\n    stringOpParameters,\n    listParameters,\n  } = metadata;\n\n  const missing: string[] = [];\n  for (const name of expectedNames) {\n    if (readOwnProperty(bindings, name) === undefined) {\n      missing.push(name);\n    }\n  }\n\n  if (missing.length > 0) {\n    throw new ConfigurationError(\n      `Missing bindings for parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.map((name) => `\"${name}\"`).join(\", \")}`,\n      { missingParameters: missing },\n    );\n  }\n\n  const unexpected = Object.keys(bindings).filter(\n    (name) => !expectedNames.has(name),\n  );\n  if (unexpected.length > 0) {\n    throw new ConfigurationError(\n      `Unexpected bindings provided: ${unexpected.map((name) => `\"${name}\"`).join(\", \")}`,\n      { unexpectedParameters: unexpected },\n    );\n  }\n\n  // Validate value types upfront so both the fast path (executeRaw) and the\n  // fallback path (AST substitution) reject the same invalid inputs.\n  for (const name of expectedNames) {\n    const value = readOwnProperty(bindings, name);\n    if (listParameters.has(name)) {\n      validateListBinding(name, value, listParameters.get(name));\n      continue;\n    }\n    if (expressionParameters.has(name)) {\n      normalizeDatabaseLiteral(value, `$parameter.${name}`);\n      const expectedType = expressionParameterTypes.get(name);\n      if (\n        expectedType !== undefined &&\n        expectedType !== \"unknown\" &&\n        !matchesExpressionType(value, expectedType)\n      ) {\n        throw new ConfigurationError(\n          `Expression parameter \"${name}\" must be a ${expectedType}`,\n          { parameterName: name, valueType: expectedType },\n        );\n      }\n      continue;\n    }\n    validateBindingValue(name, value, stringOpParameters.has(name));\n  }\n}\n\nfunction matchesExpressionType(value: unknown, valueType: ValueType): boolean {\n  if (valueType === \"array\") return Array.isArray(value);\n  if (valueType === \"object\") {\n    return typeof value === \"object\" && value !== null && !Array.isArray(value);\n  }\n  return matchesElementType(value, valueType);\n}\n\n/**\n * Validates a list-valued binding is an array of scalars of the field's type.\n *\n * The element-type check is what keeps the two backends in step. Without it\n * `[1, \"a\"]` against a number field passes — each element is individually a\n * legal scalar — and then PostgreSQL fails casting `\"a\"` to numeric while\n * SQLite's dynamic typing silently matches nothing for that element: the same\n * query, two behaviors. It also brings the parameterized form in line with the\n * literal one, which already refuses a mixed list when it compiles (\"Mixed\n * literal value types are not supported in predicates\") — the parameterized\n * form has no literals to inspect, so it reaches the same verdict from the\n * binding instead.\n *\n * The check rides the walk that was already validating every element, so it\n * costs a comparison per element rather than a second pass.\n */\nfunction validateListBinding(\n  name: string,\n  value: unknown,\n  elementType: ValueType | undefined,\n): void {\n  assertListBinding(name, value);\n  for (const element of value) {\n    validateBindingValue(name, element, false);\n    if (elementType === undefined) continue;\n    if (matchesElementType(element, elementType)) continue;\n    throw new ConfigurationError(\n      `Parameter \"${name}\" is bound against a ${elementType} field, so every ` +\n        `element must be a ${elementType}; got ${describeBindingType(element)}`,\n      { parameterName: name, valueType: elementType },\n    );\n  }\n}\n\n/** Whether `value` can be bound as `elementType` in an `in()`/`notIn()` list. */\nfunction matchesElementType(value: unknown, elementType: ValueType): boolean {\n  switch (elementType) {\n    case \"string\": {\n      return typeof value === \"string\";\n    }\n    case \"number\": {\n      return typeof value === \"number\";\n    }\n    case \"boolean\": {\n      return typeof value === \"boolean\";\n    }\n    case \"date\": {\n      // Either a Date or the ISO text TypeGraph stores. Arbitrary strings are\n      // not parsed here: the literal form does not validate them either, and\n      // guessing which formats PostgreSQL accepts would reject valid input.\n      return value instanceof Date || typeof value === \"string\";\n    }\n    // No element cast is emitted for these, so there is no divergence to\n    // prevent — `array`/`object` are rejected earlier, at compile time.\n    case \"array\":\n    case \"object\":\n    case \"embedding\":\n    case \"unknown\": {\n      return true;\n    }\n  }\n}\n\n/** A binding's type as it should read in an error message. */\nfunction describeBindingType(value: unknown): string {\n  if (value instanceof Date) return \"date\";\n  return typeof value;\n}\n\nfunction validateBindingValue(\n  name: string,\n  value: unknown,\n  isStringOp: boolean,\n): void {\n  if (value === null) {\n    throw new ConfigurationError(\n      \"Parameter value must not be null (use undefined-based patterns instead)\",\n      { parameterName: name, valueType: \"null\" },\n    );\n  }\n  if (isStringOp) {\n    if (typeof value !== \"string\") {\n      throw new ConfigurationError(\n        `Parameter \"${name}\" must be a string for string operations`,\n        { parameterName: name, actualType: typeof value },\n      );\n    }\n    return;\n  }\n  if (typeof value === \"number\") {\n    // JSON.stringify turns NaN and +/-Infinity into `null`, which the packed\n    // list form would bind as SQL NULL — silently poisoning the predicate\n    // (`NOT IN (NULL)` matches no row at all). The scalar form is no better:\n    // SQLite stores a bound NaN as NULL, so `eq(NaN)` quietly matches nothing.\n    // Neither is a value any comparison can mean, so reject both shapes here.\n    if (!Number.isFinite(value)) {\n      throw new ConfigurationError(\n        `Parameter \"${name}\" must be a finite number, got ${String(value)}`,\n        { parameterName: name, actualType: \"number\" },\n      );\n    }\n    return;\n  }\n  if (\n    value instanceof Date ||\n    typeof value === \"string\" ||\n    typeof value === \"boolean\"\n  ) {\n    return;\n  }\n  throw new ConfigurationError(\n    `Unsupported parameter value type: ${typeof value}`,\n    { parameterName: name, actualType: typeof value },\n  );\n}\n","/**\n * Aggregate and HAVING Helper Functions\n *\n * Provides factory functions for creating aggregate expressions (COUNT, SUM, etc.)\n * and HAVING clause predicates for use in GROUP BY queries.\n */\nimport {\n  type AggregateComparisonPredicate,\n  type AggregateExpr,\n  type ComparisonOp,\n  type FieldRef,\n} from \"../ast\";\nimport { jsonPointer } from \"../json-pointer\";\n\n// ============================================================\n// Aggregate Helpers\n// ============================================================\n\n/**\n * Creates a COUNT aggregate expression.\n *\n * @param alias - The node alias to count\n * @param field - Optional field to count (defaults to counting nodes by ID)\n *\n * @example\n * ```typescript\n * // COUNT all persons\n * count(\"p\")\n *\n * // COUNT persons with email field\n * count(\"p\", \"email\")\n * ```\n */\nexport function count<\n  const Alias extends string,\n  const Property extends string,\n>(\n  alias: Alias,\n  field?: Property,\n): AggregateExpr<\n  \"count\",\n  FieldRef<\n    unknown,\n    Alias,\n    readonly [\"id\"] | readonly [\"props\"],\n    readonly [Property]\n  >\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"count\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: field ? [\"props\"] : [\"id\"],\n      jsonPointer: field ? jsonPointer([field]) : undefined,\n      valueType: field ? undefined : \"string\",\n    },\n  };\n}\n\n/**\n * Creates a COUNT DISTINCT aggregate expression.\n *\n * @param alias - The node alias to count\n * @param field - Optional field to count distinct values of\n */\nexport function countDistinct<\n  const Alias extends string,\n  const Property extends string,\n>(\n  alias: Alias,\n  field?: Property,\n): AggregateExpr<\n  \"countDistinct\",\n  FieldRef<\n    unknown,\n    Alias,\n    readonly [\"id\"] | readonly [\"props\"],\n    readonly [Property]\n  >\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"countDistinct\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: field ? [\"props\"] : [\"id\"],\n      jsonPointer: field ? jsonPointer([field]) : undefined,\n      valueType: field ? undefined : \"string\",\n    },\n  };\n}\n\n/**\n * Creates a COUNT aggregate expression over an edge alias.\n *\n * Counts edges directly, without joining back to the target node table.\n * This has different semantics from `count(targetAlias)`:\n *\n * - `countEdges(edgeAlias)` — counts live edges, regardless of target-node\n *   temporal state. If a target node's `validTo` is in the past while its\n *   incident edges are still live, those edges are still counted.\n * - `count(targetAlias)` — counts edges whose target node is currently\n *   valid under the query's temporal mode.\n *\n * For the common case (\"how many follow relationships does this user\n * have?\") the edge-count semantics is what you want, and the compiler\n * can skip the target-node join entirely — measurably faster on\n * full-graph aggregates where the join dominates cost.\n *\n * @example\n * ```typescript\n * store\n *   .query()\n *   .from(\"User\", \"u\")\n *   .optionalTraverse(\"follows\", \"e\", { expand: \"none\" })\n *   .to(\"User\", \"target\")\n *   .groupByNode(\"u\")\n *   .aggregate({\n *     name: field(\"u\", \"name\"),\n *     // counts edges — skips the target-node join\n *     followCount: countEdges(\"e\"),\n *   })\n *   .execute();\n * ```\n */\nexport function countEdges<const Alias extends string>(\n  edgeAlias: Alias,\n): AggregateExpr<\"count\", FieldRef<unknown, Alias>> {\n  return count(edgeAlias);\n}\n\n/**\n * Creates a COUNT DISTINCT aggregate expression over an edge alias.\n * See {@link countEdges} for semantics.\n *\n * Distinct-on-edge-id is equivalent to `countEdges` when the query\n * surface produces each edge exactly once, but stays meaningful under\n * polymorphic expansions and ontology-driven edge fan-outs where the\n * same edge can appear multiple times in the join output.\n */\nexport function countDistinctEdges<const Alias extends string>(\n  edgeAlias: Alias,\n): AggregateExpr<\"countDistinct\", FieldRef<unknown, Alias>> {\n  return countDistinct(edgeAlias);\n}\n\n/**\n * Creates a SUM aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The numeric field to sum\n */\nexport function sum<const Alias extends string, const Property extends string>(\n  alias: Alias,\n  field: Property,\n): AggregateExpr<\n  \"sum\",\n  FieldRef<unknown, Alias, readonly [\"props\"], readonly [Property]>\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"sum\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: [\"props\"],\n      jsonPointer: jsonPointer([field]),\n      valueType: \"number\",\n    },\n  };\n}\n\n/**\n * Creates an AVG aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The numeric field to average\n */\nexport function avg<const Alias extends string, const Property extends string>(\n  alias: Alias,\n  field: Property,\n): AggregateExpr<\n  \"avg\",\n  FieldRef<unknown, Alias, readonly [\"props\"], readonly [Property]>\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"avg\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: [\"props\"],\n      jsonPointer: jsonPointer([field]),\n      valueType: \"number\",\n    },\n  };\n}\n\n/**\n * Creates a MIN aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The field to find minimum of\n */\nexport function min<const Alias extends string, const Property extends string>(\n  alias: Alias,\n  field: Property,\n): AggregateExpr<\n  \"min\",\n  FieldRef<unknown, Alias, readonly [\"props\"], readonly [Property]>\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"min\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: [\"props\"],\n      jsonPointer: jsonPointer([field]),\n    },\n  };\n}\n\n/**\n * Creates a MAX aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The field to find maximum of\n */\nexport function max<const Alias extends string, const Property extends string>(\n  alias: Alias,\n  field: Property,\n): AggregateExpr<\n  \"max\",\n  FieldRef<unknown, Alias, readonly [\"props\"], readonly [Property]>\n> {\n  return {\n    __type: \"aggregate\",\n    function: \"max\",\n    field: {\n      __type: \"field_ref\",\n      alias,\n      path: [\"props\"],\n      jsonPointer: jsonPointer([field]),\n    },\n  };\n}\n\n/**\n * Creates a field reference for use in aggregate.\n *\n * @param alias - The node alias\n * @param path - Path to the field. Use \"id\" for node ID, \"kind\" for node kind,\n *               or the property name directly (e.g., \"title\", \"year\").\n *\n * @example\n * ```typescript\n * field(\"p\", \"id\")      // Node ID\n * field(\"p\", \"kind\")    // Node kind\n * field(\"p\", \"title\")   // Property field\n * field(\"p\", \"nested\", \"field\")  // Nested property\n * ```\n */\nexport function field<\n  Value = unknown,\n  const Alias extends string = string,\n  const PropertyPath extends readonly string[] = readonly string[],\n>(\n  alias: Alias,\n  ...path: PropertyPath\n): FieldRef<\n  Value,\n  Alias,\n  readonly [\"id\"] | readonly [\"kind\"] | readonly [\"props\"],\n  PropertyPath\n> {\n  if (path.length === 0 || path[0] === \"id\") {\n    return {\n      __type: \"field_ref\",\n      alias,\n      path: [\"id\"],\n      valueType: \"string\",\n    };\n  }\n  if (path[0] === \"kind\") {\n    return {\n      __type: \"field_ref\",\n      alias,\n      path: [\"kind\"],\n      valueType: \"string\",\n    };\n  }\n  if (path[0] === \"props\") {\n    throw new Error(\n      `field(): Do not include \"props\" in the path. Use field(\"${alias}\", ${path\n        .slice(1)\n        .map((p) => `\"${p}\"`)\n        .join(\", \")}) instead.`,\n    );\n  }\n  return {\n    __type: \"field_ref\",\n    alias,\n    path: [\"props\"],\n    jsonPointer: jsonPointer(path),\n  };\n}\n\n// ============================================================\n// HAVING Helpers\n// ============================================================\n\n/**\n * Creates a HAVING predicate that compares an aggregate to a value.\n *\n * @param aggregate - The aggregate expression (count, sum, avg, etc.)\n * @param op - The comparison operator\n * @param value - The value to compare against\n *\n * @example\n * ```typescript\n * // HAVING COUNT(*) > 10\n * having(count(\"p\"), \"gt\", 10)\n *\n * // HAVING AVG(salary) >= 50000\n * having(avg(\"p\", \"salary\"), \"gte\", 50000)\n * ```\n */\nexport function having(\n  aggregate: AggregateExpr,\n  op: ComparisonOp,\n  value: number | string | boolean,\n): AggregateComparisonPredicate {\n  return {\n    __type: \"aggregate_comparison\",\n    op,\n    aggregate,\n    value: {\n      __type: \"literal\",\n      value,\n      valueType: typeof value === \"number\" ? \"number\" : \"string\",\n    },\n  };\n}\n\n/**\n * Creates a HAVING predicate: aggregate > value\n */\nexport function havingGt(\n  aggregate: AggregateExpr,\n  value: number,\n): AggregateComparisonPredicate {\n  return having(aggregate, \"gt\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate >= value\n */\nexport function havingGte(\n  aggregate: AggregateExpr,\n  value: number,\n): AggregateComparisonPredicate {\n  return having(aggregate, \"gte\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate < value\n */\nexport function havingLt(\n  aggregate: AggregateExpr,\n  value: number,\n): AggregateComparisonPredicate {\n  return having(aggregate, \"lt\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate <= value\n */\nexport function havingLte(\n  aggregate: AggregateExpr,\n  value: number,\n): AggregateComparisonPredicate {\n  return having(aggregate, \"lte\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate = value\n */\nexport function havingEq(\n  aggregate: AggregateExpr,\n  value: number,\n): AggregateComparisonPredicate {\n  return having(aggregate, \"eq\", value);\n}\n","import { ConfigurationError } from \"../../errors\";\nimport {\n  collectOperandExpressions,\n  type DatabaseExpression,\n} from \"../expressions\";\nimport type { QueryBuilderConfig } from \"./types\";\n\nconst scopes = new WeakMap<QueryBuilderConfig, symbol>();\n\n/** A builder chain shares a scope; a new query, including a subquery, gets its own. */\nexport function getExpressionScope(config: QueryBuilderConfig): symbol {\n  const existing = scopes.get(config);\n  if (existing !== undefined) return existing;\n  const scope = Symbol(\"query expression scope\");\n  scopes.set(config, scope);\n  return scope;\n}\n\n/** Refuses captured expressions from other query chains before SQL compilation. */\nexport function assertExpressionScope(\n  expression: DatabaseExpression,\n  scope: symbol,\n): void {\n  const node = expression.node;\n  switch (node.kind) {\n    case \"field\":\n    case \"outer_reference\":\n    case \"exists_subquery\":\n    case \"scalar_subquery\": {\n      if (expression.scopeIdentity !== scope)\n        throw new ConfigurationError(\n          \"Expression belongs to another query scope; use the subquery outer context for correlations.\",\n        );\n      return;\n    }\n    case \"literal\":\n    case \"parameter\": {\n      return;\n    }\n    case \"arithmetic\":\n    case \"comparison\": {\n      assertExpressionScope(node.left, scope);\n      assertExpressionScope(node.right, scope);\n      return;\n    }\n    case \"array_contains\": {\n      assertExpressionScope(node.array, scope);\n      assertExpressionScope(node.element, scope);\n      return;\n    }\n    case \"boolean\":\n    case \"coalesce\": {\n      for (const operand of node.operands)\n        assertExpressionScope(operand, scope);\n      return;\n    }\n    case \"not\":\n    case \"null_check\":\n    case \"numeric_conversion\": {\n      assertExpressionScope(node.operand, scope);\n      return;\n    }\n    case \"aggregate\": {\n      if (node.operand !== undefined)\n        assertExpressionScope(node.operand, scope);\n      return;\n    }\n    case \"collect\": {\n      for (const operand of collectOperandExpressions(node.operand))\n        assertExpressionScope(operand, scope);\n      for (const order of node.orderBy)\n        assertExpressionScope(order.expression, scope);\n      if (node.filter !== undefined) assertExpressionScope(node.filter, scope);\n      return;\n    }\n    case \"conditional\": {\n      assertExpressionScope(node.condition, scope);\n      assertExpressionScope(node.then, scope);\n      assertExpressionScope(node.otherwise, scope);\n    }\n  }\n}\n\n/** Recognizes expression values at dynamic builder boundaries. */\nexport function isDatabaseExpression(\n  value: unknown,\n): value is DatabaseExpression {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"__type\" in value &&\n    value.__type === \"database_expression\"\n  );\n}\n","/**\n * SQL Identifier Validation\n *\n * Validates aliases and identifiers to prevent SQL injection.\n */\nimport { ConfigurationError, ValidationError } from \"../../errors\";\nimport {\n  type HybridFusionOptions,\n  type PredicateExpression,\n  type SortDirection,\n} from \"../ast\";\nimport type { PaginateOptions, QueryBuilderState } from \"./types\";\n\n/**\n * Pattern for valid SQL identifiers (aliases).\n * Must start with a letter or underscore, followed by letters, digits, or underscores.\n * Maximum length of 63 characters (PostgreSQL limit).\n */\nconst SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/;\n\n/**\n * Reserved SQL keywords that cannot be used as aliases.\n */\nconst SQL_RESERVED_KEYWORDS = new Set([\n  \"select\",\n  \"from\",\n  \"where\",\n  \"and\",\n  \"or\",\n  \"not\",\n  \"in\",\n  \"is\",\n  \"null\",\n  \"true\",\n  \"false\",\n  \"as\",\n  \"on\",\n  \"join\",\n  \"left\",\n  \"right\",\n  \"inner\",\n  \"outer\",\n  \"cross\",\n  \"full\",\n  \"group\",\n  \"by\",\n  \"having\",\n  \"order\",\n  \"asc\",\n  \"desc\",\n  \"limit\",\n  \"offset\",\n  \"union\",\n  \"intersect\",\n  \"except\",\n  \"all\",\n  \"distinct\",\n  \"case\",\n  \"when\",\n  \"then\",\n  \"else\",\n  \"end\",\n  \"exists\",\n  \"between\",\n  \"like\",\n  \"ilike\",\n  \"insert\",\n  \"update\",\n  \"delete\",\n  \"create\",\n  \"drop\",\n  \"alter\",\n  \"table\",\n  \"index\",\n  \"view\",\n  \"with\",\n  \"recursive\",\n]);\n\n/**\n * Validates that an alias is a safe SQL identifier.\n *\n * @param alias - The alias to validate\n * @throws ValidationError if the alias is not a valid SQL identifier\n */\nexport function validateSqlIdentifier(alias: string): void {\n  if (!SQL_IDENTIFIER_PATTERN.test(alias)) {\n    throw new ValidationError(\n      `Invalid alias \"${alias}\": must start with a letter or underscore, ` +\n        `contain only letters, digits, and underscores, and be at most 63 characters`,\n      {\n        issues: [\n          {\n            path: \"alias\",\n            message: `\"${alias}\" is not a valid SQL identifier`,\n          },\n        ],\n      },\n      {\n        suggestion: `Use a simple identifier like \"p\", \"e\", \"node1\", or \"my_alias\".`,\n      },\n    );\n  }\n\n  if (alias.toLowerCase().startsWith(\"cte_\")) {\n    throw new ValidationError(\n      `Invalid alias \"${alias}\": aliases starting with \"cte_\" are reserved for internal use`,\n      {\n        issues: [\n          {\n            path: \"alias\",\n            message: `\"${alias}\" conflicts with internal CTE naming`,\n          },\n        ],\n      },\n      {\n        suggestion: `Choose an alias that does not start with \"cte_\".`,\n      },\n    );\n  }\n\n  if (SQL_RESERVED_KEYWORDS.has(alias.toLowerCase())) {\n    throw new ValidationError(\n      `Invalid alias \"${alias}\": \"${alias}\" is a reserved SQL keyword`,\n      {\n        issues: [\n          { path: \"alias\", message: `\"${alias}\" is a reserved SQL keyword` },\n        ],\n      },\n      {\n        suggestion: `Choose a different alias. Reserved words like SELECT, FROM, WHERE cannot be used.`,\n      },\n    );\n  }\n}\n\n/**\n * Walks a predicate expression and rejects placement under OR/NOT for\n * structural predicates (vector / fulltext) — those rewrite the query\n * shape and are incompatible with disjunction or negation. Both\n * predicate kinds use this same machinery; the `match` callback selects\n * which one is being validated.\n */\nfunction validateStructuralPredicatePlacement(\n  expression: PredicateExpression,\n  matchType: \"vector_similarity\" | \"fulltext_match\",\n  buildError: (path: string) => never,\n  inDisallowedBranch: boolean,\n  path: string,\n): void {\n  if (expression.__type === matchType) {\n    if (inDisallowedBranch) buildError(path);\n    return;\n  }\n  switch (expression.__type) {\n    case \"and\": {\n      for (const [index, child] of expression.predicates.entries()) {\n        validateStructuralPredicatePlacement(\n          child,\n          matchType,\n          buildError,\n          inDisallowedBranch,\n          `${path}.predicates[${index}]`,\n        );\n      }\n      return;\n    }\n    case \"or\": {\n      for (const [index, child] of expression.predicates.entries()) {\n        validateStructuralPredicatePlacement(\n          child,\n          matchType,\n          buildError,\n          true,\n          `${path}.predicates[${index}]`,\n        );\n      }\n      return;\n    }\n    case \"not\": {\n      validateStructuralPredicatePlacement(\n        expression.predicate,\n        matchType,\n        buildError,\n        true,\n        `${path}.predicate`,\n      );\n      return;\n    }\n    case \"comparison\":\n    case \"tuple_comparison\":\n    case \"string_op\":\n    case \"null_check\":\n    case \"between\":\n    case \"array_op\":\n    case \"object_op\":\n    case \"database_expression_predicate\":\n    case \"aggregate_comparison\":\n    case \"exists\":\n    case \"in_subquery\":\n    case \"vector_similarity\":\n    case \"fulltext_match\": {\n      return;\n    }\n  }\n}\n\nfunction throwInvalidVectorPredicatePlacement(path: string): never {\n  throw new ValidationError(\n    \"Vector similarity predicates cannot be nested under OR or NOT. \" +\n      \"Use top-level AND combinations instead.\",\n    {\n      issues: [\n        {\n          path,\n          message:\n            \"Vector similarity predicates are only supported at top-level \" +\n            \"or inside AND groups.\",\n        },\n      ],\n    },\n    {\n      suggestion:\n        \"Rewrite the predicate to keep vector similarity at top-level \" +\n        \"or combine with additional filters using AND.\",\n    },\n  );\n}\n\nfunction throwInvalidFulltextPredicatePlacement(path: string): never {\n  throw new ValidationError(\n    \"Fulltext match predicates (.matches()) cannot be nested under OR or NOT. \" +\n      \"Use top-level AND combinations instead.\",\n    {\n      issues: [\n        {\n          path,\n          message:\n            \"Fulltext match predicates are only supported at top-level \" +\n            \"or inside AND groups.\",\n        },\n      ],\n    },\n    {\n      suggestion:\n        \"Restructure your query so the fulltext match appears at the top level \" +\n        \"of a whereNode() or inside an .and() combination.\",\n    },\n  );\n}\n\nexport function validateVectorPredicatePlacement(\n  predicates: readonly { expression: PredicateExpression }[],\n): void {\n  for (const [index, predicate] of predicates.entries()) {\n    validateStructuralPredicatePlacement(\n      predicate.expression,\n      \"vector_similarity\",\n      throwInvalidVectorPredicatePlacement,\n      false,\n      `predicates[${index}].expression`,\n    );\n  }\n}\n\nexport function validateFulltextPredicatePlacement(\n  predicates: readonly { expression: PredicateExpression }[],\n): void {\n  for (const [index, predicate] of predicates.entries()) {\n    validateStructuralPredicatePlacement(\n      predicate.expression,\n      \"fulltext_match\",\n      throwInvalidFulltextPredicatePlacement,\n      false,\n      `predicates[${index}].expression`,\n    );\n  }\n}\n\n/**\n * Validates fusion options shared by `QueryBuilder.fuseWith()` and\n * `store.search.hybrid({ fusion })`. Rejects unsupported methods, and\n * non-finite / non-positive k, and negative / non-finite weights.\n */\nexport function validateHybridFusionOptions(\n  options: HybridFusionOptions,\n): void {\n  // Cast through string to survive callers that bypass the TS type\n  // (e.g. user-supplied JSON on the store.search.hybrid path).\n  const method = options.method as string | undefined;\n  if (method !== undefined && method !== \"rrf\") {\n    throw new ValidationError(`Unsupported fusion method: ${method}`, {\n      issues: [{ path: \"fusion.method\", message: `Only \"rrf\" is supported.` }],\n    });\n  }\n  const { k } = options;\n  if (k !== undefined && (!Number.isFinite(k) || k <= 0)) {\n    throw new ValidationError(\n      `Fusion k must be a positive finite number, got: ${String(k)}`,\n      {\n        issues: [{ path: \"fusion.k\", message: \"Must be a positive number.\" }],\n      },\n    );\n  }\n  const weights = options.weights;\n  if (weights !== undefined) {\n    for (const key of [\"vector\", \"fulltext\"] as const) {\n      const weight = weights[key];\n      if (weight !== undefined && (!Number.isFinite(weight) || weight < 0)) {\n        throw new ValidationError(\n          `Fusion weight for \"${key}\" must be a non-negative finite number, got: ${String(weight)}`,\n          {\n            issues: [\n              {\n                path: `fusion.weights.${key}`,\n                message: \"Must be a non-negative number.\",\n              },\n            ],\n          },\n        );\n      }\n    }\n  }\n}\n\n/** One owner for non-negative SQL result bounds on every builder. */\nexport function validateQueryRange(\n  value: number,\n  option: \"limit\" | \"offset\",\n): void {\n  if (!Number.isSafeInteger(value) || value < 0) {\n    throw new ValidationError(`${option} must be a non-negative safe integer`, {\n      issues: [\n        { path: option, message: `Invalid ${option}: ${String(value)}` },\n      ],\n    });\n  }\n}\n\n/** Validates the alias namespace and references once for every builder stage. */\nexport function validateQueryState(state: QueryBuilderState): void {\n  if (state.startAlias === \"\") return;\n  const aliases = new Set<string>();\n  const nodes = new Set<string>();\n  const edges = new Set<string>();\n  function addAlias(alias: string): void {\n    validateSqlIdentifier(alias);\n    if (aliases.has(alias))\n      throw new ValidationError(`Query alias \"${alias}\" is already in use`, {\n        issues: [\n          {\n            path: \"alias\",\n            message: \"Aliases must be unique across nodes, edges, and paths\",\n          },\n        ],\n      });\n    aliases.add(alias);\n  }\n  addAlias(state.startAlias);\n  nodes.add(state.startAlias);\n  for (const traversal of state.traversals) {\n    if (!nodes.has(traversal.joinFromAlias))\n      throw new ValidationError(\n        `Unknown traversal source alias \"${traversal.joinFromAlias}\"`,\n        {\n          issues: [\n            { path: \"from\", message: \"Expected an existing node alias\" },\n          ],\n        },\n      );\n    addAlias(traversal.edgeAlias);\n    edges.add(traversal.edgeAlias);\n    addAlias(traversal.nodeAlias);\n    nodes.add(traversal.nodeAlias);\n    for (const alias of [\n      traversal.variableLength?.depthAlias,\n      traversal.variableLength?.pathAlias,\n    ]) {\n      if (alias !== undefined) addAlias(alias);\n    }\n  }\n  for (const predicate of state.predicates) {\n    const expected = predicate.targetType === \"edge\" ? edges : nodes;\n    if (!expected.has(predicate.targetAlias))\n      throw new ValidationError(\n        `Unknown predicate alias \"${predicate.targetAlias}\"`,\n        {\n          issues: [\n            {\n              path: \"alias\",\n              message:\n                \"Expected an existing alias of the requested entity type\",\n            },\n          ],\n        },\n      );\n  }\n  for (const order of state.orderBy) {\n    if (order.field.__type === \"database_expression\") continue;\n    if (!nodes.has(order.field.alias) && !edges.has(order.field.alias))\n      throw new ValidationError(`Unknown order alias \"${order.field.alias}\"`, {\n        issues: [\n          {\n            path: \"orderBy\",\n            message: \"Expected an existing node or edge alias\",\n          },\n        ],\n      });\n  }\n}\n\nexport function validateQuerySource(\n  state: QueryBuilderState,\n  starting: boolean,\n): void {\n  if (starting ? state.startAlias !== \"\" : state.startAlias === \"\") {\n    throw new ValidationError(\n      starting ?\n        \"A query can have only one source; start a new query instead.\"\n      : \"Start the query with from() or fromDynamic() first.\",\n      {\n        issues: [\n          {\n            path: \"from\",\n            message: starting ? \"Source already defined\" : \"Source required\",\n          },\n        ],\n      },\n    );\n  }\n}\n\nexport function validateTraversalOptions(\n  direction: string,\n  expansion: string,\n): void {\n  if (direction !== \"in\" && direction !== \"out\")\n    throw new ValidationError(`Invalid traversal direction: ${direction}`, {\n      issues: [{ path: \"direction\", message: \"Use in or out\" }],\n    });\n  if (![\"none\", \"implying\", \"inverse\", \"all\"].includes(expansion))\n    throw new ValidationError(`Invalid traversal expansion: ${expansion}`, {\n      issues: [\n        { path: \"expand\", message: \"Use none, implying, inverse, or all\" },\n      ],\n    });\n}\n\n/** Cursor pagination owns its bounds; conflicting or invalid options must not be ignored. */\nexport function validatePaginationOptions(\n  state: QueryBuilderState,\n  options: PaginateOptions,\n): void {\n  if (state.limit !== undefined || state.offset !== undefined) {\n    throw new ValidationError(\n      \"Cursor pagination cannot honor query limit/offset; use first/after or last/before instead.\",\n      { issues: [{ path: \"paginate\", message: \"Conflicting result bounds\" }] },\n    );\n  }\n  const forward = options.first !== undefined || options.after !== undefined;\n  const backward = options.last !== undefined || options.before !== undefined;\n  if (forward && backward)\n    throw new ValidationError(\n      \"Use either first/after or last/before, not both pagination directions.\",\n      { issues: [{ path: \"paginate\", message: \"Conflicting directions\" }] },\n    );\n  for (const key of [\"first\", \"last\"] as const) {\n    const value = options[key];\n    if (\n      value !== undefined &&\n      (!Number.isSafeInteger(value) ||\n        value < 1 ||\n        value >= Number.MAX_SAFE_INTEGER)\n    ) {\n      throw new ValidationError(\n        `${key} must be a positive safe integer with room for a lookahead row`,\n        { issues: [{ path: key, message: \"Invalid page size\" }] },\n      );\n    }\n  }\n  for (const key of [\"after\", \"before\"] as const) {\n    if (options[key]?.length === 0)\n      throw new ValidationError(\"Pagination cursors must not be empty\", {\n        issues: [{ path: key, message: \"Empty cursor\" }],\n      });\n  }\n}\n\nexport function validateSortDirection(\n  value: unknown,\n): asserts value is SortDirection {\n  if (value !== \"asc\" && value !== \"desc\")\n    throw new ConfigurationError(\"Invalid order direction.\");\n}\n","/**\n * AST Builder utilities for query construction.\n *\n * Provides shared functions for building QueryAst objects from builder state.\n */\nimport { type QueryAst } from \"../ast\";\nimport { getExpressionScope } from \"./expression-scope\";\nimport type { QueryBuilderConfig, QueryBuilderState } from \"./types\";\nimport {\n  validateFulltextPredicatePlacement,\n  validateQuerySource,\n  validateQueryState,\n  validateVectorPredicatePlacement,\n} from \"./validation\";\n\n/**\n * Builds a QueryAst from builder config and state.\n *\n * This is shared by ExecutableQuery and ExecutableAggregateQuery to avoid\n * duplicating the AST construction logic.\n */\nexport function buildQueryAst(\n  config: QueryBuilderConfig,\n  state: QueryBuilderState,\n): QueryAst {\n  validateQuerySource(state, false);\n  validateQueryState(state);\n  validateVectorPredicatePlacement(state.predicates);\n  validateFulltextPredicatePlacement(state.predicates);\n\n  const temporalMode: { mode: typeof state.temporalMode; asOf?: string } = {\n    mode: state.temporalMode,\n  };\n  if (state.asOf !== undefined) {\n    temporalMode.asOf = state.asOf;\n  }\n\n  return {\n    graphId: config.graphId,\n    expressionScope: getExpressionScope(config),\n    start: {\n      alias: state.startAlias,\n      kinds: state.startKinds,\n      includeSubClasses: state.includeSubClasses,\n    },\n    traversals: state.traversals,\n    predicates: state.predicates,\n    ...(state.resultPredicate === undefined ?\n      {}\n    : { resultPredicate: state.resultPredicate }),\n    projection: {\n      fields: state.projection,\n    },\n    temporalMode,\n    ...(state.recordedAsOf !== undefined && {\n      recordedAsOf: state.recordedAsOf,\n    }),\n    ...(state.orderBy.length > 0 && { orderBy: state.orderBy }),\n    ...(state.limit !== undefined && { limit: state.limit }),\n    ...(state.offset !== undefined && { offset: state.offset }),\n    ...(state.groupBy !== undefined && { groupBy: state.groupBy }),\n    ...(state.having !== undefined && { having: state.having }),\n    ...(state.aggregateOrderBy.length > 0 && {\n      aggregateOrderBy: state.aggregateOrderBy,\n    }),\n    ...(state.fusion !== undefined && { fusion: state.fusion }),\n  };\n}\n","/**\n * Module-private builder context used by StoreView and recorded-time reads.\n *\n * These values are real query-builder mechanics, but not public builder API:\n * callers should pin coordinates through Store/StoreView and bind recorded\n * reads through Store options. A WeakMap keeps the public QueryBuilderConfig\n * free of internal-only fields while preserving clone-by-config behavior.\n */\nimport { type RuntimeKindTokenResolver } from \"../../core/runtime-kind\";\nimport { type ReadCoordinate } from \"../../core/temporal\";\nimport { type RecordedReadBinding } from \"../compiler/schema\";\nimport { type QueryBuilderConfig } from \"./types\";\n\nexport type QueryBuilderInternalContext = Readonly<{\n  recordedReadBinding?: RecordedReadBinding | undefined;\n  sealedCoordinate?: ReadCoordinate | undefined;\n  runtimeKindTokenResolver?: RuntimeKindTokenResolver | undefined;\n  /** Expected active schema version applied automatically by a checked scope. */\n  expectedSchemaVersion?: Readonly<{ value: number | undefined }>;\n}>;\n\nconst contexts = new WeakMap<QueryBuilderConfig, QueryBuilderInternalContext>();\n\nexport function registerQueryBuilderInternalContext(\n  config: QueryBuilderConfig,\n  context: QueryBuilderInternalContext,\n): void {\n  if (\n    context.recordedReadBinding === undefined &&\n    context.sealedCoordinate === undefined &&\n    context.runtimeKindTokenResolver === undefined &&\n    context.expectedSchemaVersion === undefined\n  ) {\n    return;\n  }\n  contexts.set(config, context);\n}\n\nexport function getQueryBuilderInternalContext(\n  config: QueryBuilderConfig,\n): QueryBuilderInternalContext {\n  return contexts.get(config) ?? {};\n}\n","/**\n * Shared `CompileQueryOptions` construction for the executable query,\n * aggregate query, and unionable query builders. Keeps one source of\n * truth for which config fields are propagated to the compiler.\n */\nimport { resolveBackendFulltext } from \"../../backend/capabilities/fulltext\";\nimport { resolveRecursiveTraversal } from \"../../backend/capabilities/recursive-traversal\";\nimport { resolveEmbeddingFields } from \"../../core/embedding\";\nimport { resolveDeclaredFulltextLanguage } from \"../../core/searchable\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport {\n  type CompileQueryOptions,\n  COMPILER_DEFAULT_RECURSIVE_TRAVERSAL,\n} from \"../compiler/index\";\nimport {\n  type VectorSlotDescriptor,\n  vectorSlotKey,\n  type VectorSlotMap,\n} from \"../compiler/schema\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { type QueryBuilderConfig } from \"./types\";\n\nexport function buildCompileOptions(\n  config: QueryBuilderConfig,\n): CompileQueryOptions {\n  const fulltextStrategy =\n    config.backend === undefined ?\n      undefined\n    : resolveBackendFulltext(config.backend);\n  const vectorStrategy = config.backend?.vectorStrategy;\n  const { recordedReadBinding } = getQueryBuilderInternalContext(config);\n  return {\n    dialect: config.dialect ?? \"sqlite\",\n    schema: config.schema,\n    windowFunctions: config.backend?.capabilities.windowFunctions ?? true,\n    orderedAggregates:\n      config.backend === undefined ?\n        false\n      : config.backend.capabilities.orderedAggregates === true,\n    recursiveTraversal:\n      config.backend === undefined ?\n        COMPILER_DEFAULT_RECURSIVE_TRAVERSAL\n      : resolveRecursiveTraversal(config.backend.capabilities),\n    identitySameIdAcrossKinds: config.identitySameIdAcrossKinds,\n    ...(fulltextStrategy === undefined ?\n      {}\n    : {\n        fulltextStrategy,\n        ...(fulltextStrategy === false ?\n          {}\n        : { fulltextLanguages: buildFulltextLanguages(config.registry) }),\n      }),\n    ...(vectorStrategy === undefined ?\n      {}\n    : { vectorStrategy, vectorSlots: buildVectorSlots(config.registry) }),\n    ...(recordedReadBinding === undefined ? {} : { recordedReadBinding }),\n  };\n}\n\n/**\n * Memoizes the {@link VectorSlotMap} per registry. A registry is immutable\n * for its lifetime, and `buildCompileOptions` runs on every query compile, so\n * caching avoids re-walking every node kind's schema (and re-allocating the\n * map) on each query — including the majority that contain no `similarTo()`.\n */\nconst vectorSlotsCache = new WeakMap<KindRegistry, VectorSlotMap>();\n\n/**\n * Memoizes each kind's DECLARED fulltext language per registry (the\n * winning-language rule the write path applies). The `$fulltext` CTE uses\n * it to parse queries with a CONSTANT regconfig when every kind in the\n * alias shares one declared language — the per-row\n * `websearch_to_tsquery(\"language\", ...)` form makes the tsquery\n * non-constant, so PostgreSQL's GIN index on `tsv` can never serve the\n * match.\n */\nconst fulltextLanguagesCache = new WeakMap<\n  KindRegistry,\n  ReadonlyMap<string, string>\n>();\n\nfunction buildFulltextLanguages(\n  registry: KindRegistry,\n): ReadonlyMap<string, string> {\n  const cached = fulltextLanguagesCache.get(registry);\n  if (cached !== undefined) return cached;\n\n  const languages = new Map<string, string>();\n  for (const [nodeKind, nodeType] of registry.nodeKinds) {\n    const language = resolveDeclaredFulltextLanguage(nodeType.schema);\n    if (language !== undefined) languages.set(nodeKind, language);\n  }\n  fulltextLanguagesCache.set(registry, languages);\n  return languages;\n}\n\n/**\n * Builds the compiler's {@link VectorSlotMap} from every registered node\n * kind's embedding fields. Used only when a vector strategy is present —\n * it tells the `field.similarTo(...)` CTE which `(kind, fieldPath)` pairs\n * back a per-field table, so the UNION ALL only scans kinds that declare\n * the field. Memoized per (immutable) registry.\n */\nfunction buildVectorSlots(registry: KindRegistry): VectorSlotMap {\n  const cached = vectorSlotsCache.get(registry);\n  if (cached !== undefined) return cached;\n\n  const slots = new Map<string, VectorSlotDescriptor>();\n  for (const [nodeKind, nodeType] of registry.nodeKinds) {\n    for (const field of resolveEmbeddingFields(nodeType.schema)) {\n      slots.set(vectorSlotKey(nodeKind, field.fieldPath), {\n        dimensions: field.dimensions,\n        metric: field.metric,\n        indexType: field.indexType,\n      });\n    }\n  }\n  vectorSlotsCache.set(registry, slots);\n  return slots;\n}\n","import { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { getDialect } from \"../dialect\";\nimport { compileOrderTerm } from \"../order\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { asCompiledRowsSql } from \"../sql-intent\";\nimport { groupOneStatementBatchItems } from \"./one-statement-sharing\";\nimport type {\n  EmbeddableOneStatementRead,\n  OneStatementBatchableQuery,\n  OneStatementBatchResults,\n} from \"./types\";\n\n/** Execution choices for a one-statement read batch. */\nexport type BatchOnceOptions = Readonly<{\n  /** Share hydration among compatible subgraphs. Recommended for overlapping, payload-heavy roots. Defaults to false. */\n  shareSubgraphs?: boolean;\n}>;\n\nconst ORDER_COLUMN = \"typegraphbatchordinal\";\nconst ORDER_KEY_PREFIX = \"typegraphbatchorder\";\n\n/** SQLite's default compound-select ceiling; kept as the portable request cap. */\nconst MAX_ONE_STATEMENT_BATCH_READS = 500;\n\nexport function oneStatementBatchOrderColumn(index: number): string {\n  return `${ORDER_KEY_PREFIX}${index}`;\n}\n\nfunction buildOrdinalOrder(\n  rowAlias: string,\n  orderBy: ReturnType<\n    NonNullable<\n      OneStatementBatchableQuery<unknown>[\"compileOneStatementBatchItem\"]\n    >\n  >[\"orderBy\"],\n): SqlFragment {\n  if (orderBy.length === 0) return sql.empty();\n  const row = sql.identifier(rowAlias);\n  const terms = orderBy.map((order) => {\n    const column = sql`${row}.${sql.identifier(order.column)}`;\n    return compileOrderTerm(column, order.direction, order.nulls);\n  });\n  return sql`ORDER BY ${sql.join(terms, sql`, `)}`;\n}\n\ntype BatchEnvelopeRow = Readonly<{\n  batch_index: number | string;\n  payload: unknown;\n}>;\n\n/** Executes independent relational reads through one database statement. */\nexport async function executeOneStatementBatch<\n  const Queries extends readonly EmbeddableOneStatementRead<unknown>[],\n>(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  queries: Queries,\n  options: BatchOnceOptions = {},\n): Promise<OneStatementBatchResults<Queries>> {\n  if (\n    options.shareSubgraphs !== undefined &&\n    typeof options.shareSubgraphs !== \"boolean\"\n  )\n    throw new ConfigurationError(\"batchOnce shareSubgraphs must be a boolean.\");\n  if (queries.length === 0) return [] as OneStatementBatchResults<Queries>;\n  if (queries.length > MAX_ONE_STATEMENT_BATCH_READS) {\n    throw new ConfigurationError(\n      `store.batchOnce() accepts at most ${MAX_ONE_STATEMENT_BATCH_READS} reads in one statement.`,\n      {\n        operation: \"batchOnce\",\n        reads: queries.length,\n        maxReads: MAX_ONE_STATEMENT_BATCH_READS,\n      },\n    );\n  }\n  if (!backend.capabilities.windowFunctions) {\n    throw new ConfigurationError(\n      \"store.batchOnce() requires backend window-function support.\",\n      {\n        operation: \"batchOnce\",\n        capability: \"windowFunctions\",\n        backend: backend.dialect,\n      },\n    );\n  }\n  const dialect = getDialect(backend.dialect);\n  const executionTarget = backendDerivationRoot(backend);\n  const items = queries.map((query) => {\n    const compile = query.compileOneStatementBatchItem;\n    if (compile === undefined) {\n      throw new ConfigurationError(\n        \"Read cannot be embedded in store.batchOnce().\",\n        { operation: \"batchOnce\" },\n        {\n          suggestion:\n            \"Pass a fluent relational query or a set-oriented read returned by the store's query helpers.\",\n        },\n      );\n    }\n    const item = compile.call(query);\n    if (item.provenance.graphId !== graphId) {\n      throw new ConfigurationError(\n        \"store.batchOnce() cannot combine reads from different graphs.\",\n        {\n          operation: \"batchOnce\",\n          expectedGraphId: graphId,\n          receivedGraphId: item.provenance.graphId,\n        },\n      );\n    }\n    if (item.provenance.executionTarget !== executionTarget) {\n      throw new ConfigurationError(\n        \"store.batchOnce() cannot rebind a read to a different database or transaction target.\",\n        { operation: \"batchOnce\", graphId },\n        {\n          suggestion:\n            \"Build fluent queries from the same Store or transaction context whose batchOnce() method executes them.\",\n        },\n      );\n    }\n    return item;\n  });\n  const ctes: SqlFragment[] = [];\n  const branches: SqlFragment[] = [];\n\n  for (const item of items) {\n    const reservedAlias = item.outputNames.find(\n      (outputName) =>\n        outputName === ORDER_COLUMN || outputName.startsWith(ORDER_KEY_PREFIX),\n    );\n    if (reservedAlias !== undefined) {\n      throw new ConfigurationError(\n        `Query output alias \"${reservedAlias}\" is reserved by store.batchOnce().`,\n        { operation: \"batchOnce\", alias: reservedAlias },\n      );\n    }\n  }\n  const groups = groupOneStatementBatchItems(\n    items,\n    options.shareSubgraphs === true,\n  );\n  for (const [index, { item }] of groups.entries()) {\n    const sourceName = `typegraph_batch_source_${index}`;\n    const rowsName = `typegraph_batch_rows_${index}`;\n    const ordinalOrder = buildOrdinalOrder(sourceName, item.orderBy);\n    ctes.push(\n      sql`${sql.identifier(sourceName)} AS (${item.query})`,\n      sql`${sql.identifier(rowsName)} AS (SELECT ${sql.identifier(sourceName)}.*, ROW_NUMBER() OVER (${ordinalOrder}) AS ${sql.identifier(ORDER_COLUMN)} FROM ${sql.identifier(sourceName)})`,\n    );\n    const payload = dialect.orderedRowsJsonArray(\n      rowsName,\n      [...item.outputNames, ...(item.hiddenOutputNames ?? [])],\n      ORDER_COLUMN,\n    );\n    branches.push(sql`SELECT ${index} AS batch_index, ${payload} AS payload`);\n  }\n\n  const statement = asCompiledRowsSql(\n    sql`WITH ${sql.join(ctes, sql`, `)} SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS typegraph_batch_envelope ORDER BY batch_index`,\n  );\n  const bindCount = statement.chunks.filter(\n    (chunk) => chunk.kind === \"parameter\",\n  ).length;\n  const bindBudget = backend.capabilities.maxBindParameters;\n  if (bindBudget !== undefined && bindCount > bindBudget) {\n    throw new ConfigurationError(\n      \"store.batchOnce() cannot fit the requested reads in one statement's bind-parameter budget.\",\n      { operation: \"batchOnce\", bindCount, bindBudget },\n      {\n        suggestion:\n          \"Split the reads into explicit batchOnce() calls or reduce their filters. batchOnce() never chunks or falls back to sequential execution.\",\n      },\n    );\n  }\n  const envelopes = await backend.execute<BatchEnvelopeRow>(statement);\n  const payloads = new Map<number, readonly Record<string, unknown>[]>();\n  for (const envelope of envelopes) {\n    payloads.set(Number(envelope.batch_index), parsePayload(envelope.payload));\n  }\n\n  const results: unknown[] = Array.from({ length: items.length });\n  for (const [index, group] of groups.entries()) {\n    const values = group.item.mapRows(payloads.get(index) ?? []);\n    for (const [offset, requestIndex] of group.indices.entries())\n      results[requestIndex] = values[offset];\n  }\n  return results as OneStatementBatchResults<Queries>;\n}\n\nfunction parsePayload(value: unknown): readonly Record<string, unknown>[] {\n  const parsed: unknown =\n    typeof value === \"string\" ? (JSON.parse(value) as unknown) : value;\n  if (!Array.isArray(parsed)) {\n    throw new ConfigurationError(\n      \"One-statement batch returned a non-array JSON payload.\",\n      { operation: \"batchOnce\" },\n    );\n  }\n  return parsed.map((row) => {\n    if (typeof row !== \"object\" || row === null || Array.isArray(row)) {\n      throw new ConfigurationError(\n        \"One-statement batch returned a non-object row.\",\n        { operation: \"batchOnce\" },\n      );\n    }\n    return row as Record<string, unknown>;\n  });\n}\n","import { ConfigurationError } from \"../../errors\";\n\nexport type OneStatementReadProvenance = Readonly<{\n  graphId: string;\n  executionTarget: object | undefined;\n}>;\n\n/** Owns graph/target compatibility for every set-operation construction path. */\nexport function assertCompatibleSetOperationProvenance(\n  expected: OneStatementReadProvenance,\n  candidate: OneStatementReadProvenance,\n): void {\n  if (candidate.graphId !== expected.graphId) {\n    throw new ConfigurationError(\n      \"Set operations cannot combine queries from different graphs.\",\n      {\n        expectedGraphId: expected.graphId,\n        receivedGraphId: candidate.graphId,\n      },\n    );\n  }\n  if (\n    expected.executionTarget !== undefined &&\n    candidate.executionTarget !== undefined &&\n    expected.executionTarget !== candidate.executionTarget\n  ) {\n    throw new ConfigurationError(\n      \"Set operations cannot combine queries from different execution targets.\",\n      { graphId: expected.graphId },\n    );\n  }\n}\n","/** Scalar SQL terminals preserve the relation without evaluating result selectors. */\nimport { ConfigurationError } from \"../../errors\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport type { QueryAst } from \"../ast\";\nimport { compileQuery } from \"../compiler\";\nimport { executeSchemaCheckedRead } from \"../execution/schema-checked-read\";\nimport { sql } from \"../sql-fragment\";\nimport { asCompiledSelectSql } from \"../sql-intent\";\nimport { count } from \"./aggregates\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { hasParameterReferences } from \"./prepared-query\";\nimport type { QueryBuilderConfig, QueryBuilderState } from \"./types\";\n\n/** COUNT operates on groups when grouping is present, otherwise on match rows. */\nfunction buildTerminalAst(\n  config: QueryBuilderConfig,\n  state: QueryBuilderState,\n): QueryAst {\n  const fields =\n    state.groupBy?.fields ??\n    (state.having === undefined ?\n      [\n        {\n          __type: \"field_ref\" as const,\n          alias: state.startAlias,\n          path: [\"id\"],\n          valueType: \"string\" as const,\n        },\n      ]\n    : [count(state.startAlias)]);\n  return buildQueryAst(config, {\n    ...state,\n    projection: fields.map((source, index) => ({\n      outputName: `terminal_field_${index}`,\n      source,\n    })),\n  });\n}\n\nexport async function executeQueryTerminal(\n  config: QueryBuilderConfig,\n  state: QueryBuilderState,\n  operation: \"count\" | \"exists\",\n): Promise<number> {\n  const backend = config.backend;\n  if (backend === undefined)\n    throw new ConfigurationError(\n      \"Query terminals require an execution backend.\",\n      { operation },\n    );\n  const ast = buildTerminalAst(config, state);\n  if (hasParameterReferences(ast))\n    throw new ConfigurationError(\n      \"Query terminals require bound values; param() references cannot be executed directly.\",\n      { operation },\n    );\n  const options = buildCompileOptions(config);\n  const relation = compileQuery(ast, config.graphId, options);\n  const column = \"typegraph_terminal_value\";\n  const statement = asCompiledSelectSql(\n    operation === \"count\" ?\n      sql`SELECT COUNT(*) AS ${sql.identifier(column)} FROM (${relation}) AS typegraph_terminal_rows`\n    : sql`SELECT CASE WHEN EXISTS (${relation}) THEN 1 ELSE 0 END AS ${sql.identifier(column)}`,\n  );\n  const checked = getQueryBuilderInternalContext(config).expectedSchemaVersion;\n  const { orderBy: _orderBy, ...unorderedAst } = ast;\n  const rowsPromise =\n    checked === undefined ?\n      backend.execute<Record<string, unknown>>(statement)\n    : executeSchemaCheckedRead({\n        backend,\n        ast: unorderedAst,\n        graphId: config.graphId,\n        expectedVersion: checked.value,\n        rowIdentityColumn: column,\n        compile: () => statement,\n      });\n  const rows = await (state.recordedAsOf === undefined ?\n    rowsPromise\n  : withRecordedRelationsPrecondition(rowsPromise, {\n      dialect: backend.dialect,\n      surface: `recorded-query-${operation}`,\n    }));\n  return Number(rows[0]?.[column] ?? 0);\n}\n","/**\n * ExecutableQuery - A query that can be executed, paginated, or streamed.\n */\nimport { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport {\n  type GraphBackend,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport { DEFAULT_PAGINATION_LIMIT } from \"../../constants\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n  ConfigurationError,\n  UnsupportedPredicateError,\n  ValidationError,\n} from \"../../errors\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport {\n  type FieldRef,\n  mergeEdgeKinds,\n  type OrderSpec,\n  type QueryAst,\n  type SelectiveField,\n  type SortDirection,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport {\n  buildCursorFromRow,\n  buildCursorFromValues,\n  type CursorData,\n  decodeCursor,\n  requireCursorField,\n  validateCursorColumns,\n} from \"../cursor\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n  adjustOrderByForDirection,\n  buildCursorPredicate,\n  buildPaginatedResult,\n  buildPaginatedResultFromRows,\n  buildSelectContext,\n  buildSelectiveFields,\n  containsSelectableAliasObject,\n  createStreamIterable,\n  createTrackingContext,\n  decodeSelectedValue,\n  executeSchemaCheckedRead,\n  FieldAccessTracker,\n  getStreamBatchSize,\n  mapResults,\n  mapSelectiveResults,\n  MissingSelectiveFieldError,\n  nullToUndefined,\n  transformPathColumns,\n} from \"../execution\";\nimport { parseJsonPointer } from \"../json-pointer\";\nimport { resolveNullOrdering } from \"../order\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { oneStatementBatchOrderColumn } from \"./one-statement-batch\";\nimport {\n  assertCompatibleSetOperationProvenance,\n  type OneStatementReadProvenance,\n} from \"./one-statement-provenance\";\nimport {\n  assertSharedNodeField,\n  buildOrderSpec,\n  resolveSystemOrderField,\n} from \"./order-by-field\";\nimport { hasParameterReferences, PreparedQuery } from \"./prepared-query\";\nimport {\n  buildQueryTemplate,\n  type CompiledTemplate,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport { executeQueryTerminal } from \"./terminal-query\";\nimport {\n  type AliasMap,\n  type CompiledOneStatementRead,\n  type EdgeAliasMap,\n  type NodeCandidateSelection,\n  type OneStatementBatchableQuery,\n  type PaginatedResult,\n  type PaginateOptions,\n  type QueryBuilderConfig,\n  type QueryBuilderState,\n  type RecursiveAliasMap,\n  type SelectContext,\n  type StreamOptions,\n} from \"./types\";\nimport { type UnionableQuery } from \"./unionable-query\";\nimport { validatePaginationOptions, validateQueryRange } from \"./validation\";\n\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\n// Forward declaration for UnionableQuery to avoid circular imports\ntype UnionableQueryConstructor = new (\n  config: QueryBuilderConfig,\n  state: {\n    left: QueryAst;\n    operator: \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n    right: QueryAst;\n    // Additional state for result transformation\n    startAlias: string;\n    traversals: QueryBuilderState[\"traversals\"];\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any select function type for set operations\n    selectFn: (context: SelectContext<any, any>) => unknown;\n  },\n) => unknown;\n\nlet UnionableQueryClass: UnionableQueryConstructor;\n\n/**\n * Sets the UnionableQuery class reference.\n * Called during module initialization to break circular dependency.\n */\nexport function setUnionableQueryClass(cls: UnionableQueryConstructor): void {\n  UnionableQueryClass = cls;\n}\n\n/**\n * A query that can be executed.\n */\nexport class ExecutableQuery<\n  G extends GraphDef,\n  Aliases extends AliasMap,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty object for initial empty edge alias map\n  EdgeAliases extends EdgeAliasMap = {},\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n  RecursiveAliases extends RecursiveAliasMap = {},\n  R = unknown,\n> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: QueryBuilderState;\n  readonly #selectFn: (\n    context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n  ) => R;\n  #cachedSelectiveFieldsForExecute:\n    readonly SelectiveField[] | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n  #cachedSelectiveFieldsForPagination:\n    readonly SelectiveField[] | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n  // The instance is immutable (every builder method returns a new instance),\n  // so the AST and its param-ref check are invariant — compute each once and\n  // reuse across execute()/paginate()/stream() instead of rebuilding per call.\n  #cachedAst: QueryAst | undefined;\n  #cachedHasParameterReferences: boolean | undefined;\n  // Per-instance compiled placeholder templates for the full and\n  // selective-field ASTs (NOT_COMPUTED = not yet built; undefined = no fast\n  // path). Reused across execute()/executeOn() calls so a repeated query\n  // compiles once; the read instant is filled fresh per call, never cached.\n  #fullTemplate: CompiledTemplate | typeof NOT_COMPUTED | undefined =\n    NOT_COMPUTED;\n  #selectiveTemplate: CompiledTemplate | typeof NOT_COMPUTED | undefined =\n    NOT_COMPUTED;\n\n  constructor(\n    config: QueryBuilderConfig,\n    state: QueryBuilderState,\n    selectFunction: (\n      context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n    ) => R,\n  ) {\n    this.#config = config;\n    this.#state = state;\n    this.#selectFn = selectFunction;\n  }\n\n  /**\n   * Builds the query AST (memoized — the instance is immutable).\n   */\n  toAst(): QueryAst {\n    return (this.#cachedAst ??= buildQueryAst(this.#config, this.#state));\n  }\n\n  /** Whether this query uses `param()` refs (memoized). */\n  #hasParameterReferences(): boolean {\n    return (this.#cachedHasParameterReferences ??= hasParameterReferences(\n      this.toAst(),\n    ));\n  }\n\n  /**\n   * Orders results.\n   */\n  orderBy<A extends (keyof Aliases | keyof EdgeAliases) & string>(\n    alias: A,\n    field: string,\n    direction: SortDirection = \"asc\",\n  ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n    const edgeTraversal = this.#state.traversals.find(\n      (traversal) => traversal.edgeAlias === alias,\n    );\n    const isEdge = edgeTraversal !== undefined;\n    const edgeKindNames =\n      edgeTraversal === undefined ? undefined : mergeEdgeKinds(edgeTraversal);\n    const nodeKindNames =\n      isEdge ? undefined\n      : alias === this.#state.startAlias ? this.#state.startKinds\n      : this.#state.traversals.find(\n          (traversal) => traversal.nodeAlias === alias,\n        )?.nodeKinds;\n    const hasDeclaredProperty =\n      edgeKindNames ?\n        this.#config.schemaIntrospector.hasDeclaredEdgeField(\n          edgeKindNames,\n          field,\n        )\n      : nodeKindNames !== undefined &&\n        this.#config.schemaIntrospector.hasDeclaredField(nodeKindNames, field);\n    const systemField = resolveSystemOrderField(\n      alias,\n      field,\n      isEdge,\n      hasDeclaredProperty,\n    );\n\n    let typeInfo: FieldTypeInfo | undefined;\n    if (systemField === undefined) {\n      if (edgeKindNames) {\n        typeInfo = this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n          edgeKindNames,\n          field,\n        );\n      } else {\n        typeInfo =\n          nodeKindNames ?\n            this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n              nodeKindNames,\n              field,\n            )\n          : undefined;\n        assertSharedNodeField(nodeKindNames, field, typeInfo);\n      }\n    }\n\n    const orderSpec = buildOrderSpec(\n      alias,\n      field,\n      direction,\n      systemField,\n      typeInfo,\n    );\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      orderBy: [...this.#state.orderBy, orderSpec],\n    };\n\n    return new ExecutableQuery(this.#config, newState, this.#selectFn);\n  }\n\n  /**\n   * Limits the number of results.\n   */\n  limit(\n    n: number,\n  ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n    validateQueryRange(n, \"limit\");\n    return new ExecutableQuery(\n      this.#config,\n      { ...this.#state, limit: n },\n      this.#selectFn,\n    );\n  }\n\n  /**\n   * Offsets the results.\n   */\n  offset(\n    n: number,\n  ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n    validateQueryRange(n, \"offset\");\n    return new ExecutableQuery(\n      this.#config,\n      { ...this.#state, offset: n },\n      this.#selectFn,\n    );\n  }\n\n  /**\n   * Applies a query fragment to transform this executable query.\n   *\n   * Useful for applying post-select transformations like ordering,\n   * limits, and offsets from reusable fragments.\n   *\n   * @example\n   * ```typescript\n   * const paginated = (q) => q.orderBy(\"u\", \"createdAt\", \"desc\").limit(10);\n   *\n   * const results = await query()\n   *   .from(\"User\", \"u\")\n   *   .select((ctx) => ctx.u)\n   *   .pipe(paginated)\n   *   .execute();\n   * ```\n   *\n   * @param fragment - A function that transforms the executable query\n   * @returns The transformed executable query\n   */\n  pipe<NewR = R>(\n    fragment: (\n      query: ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R>,\n    ) => ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, NewR>,\n  ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, NewR> {\n    return fragment(this);\n  }\n\n  /**\n   * Combines this query with another using UNION (removes duplicates).\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n  union(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleSetOperand(other);\n    return new UnionableQueryClass(this.#config, {\n      left: this.toAst(),\n      operator: \"union\",\n      right: other.toAst(),\n      // Pass state for result transformation\n      startAlias: this.#state.startAlias,\n      traversals: this.#state.traversals,\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n      selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n    }) as UnionableQuery<G, R>;\n  }\n\n  /**\n   * Combines this query with another using UNION ALL (keeps duplicates).\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n  unionAll(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleSetOperand(other);\n    return new UnionableQueryClass(this.#config, {\n      left: this.toAst(),\n      operator: \"unionAll\",\n      right: other.toAst(),\n      // Pass state for result transformation\n      startAlias: this.#state.startAlias,\n      traversals: this.#state.traversals,\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n      selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n    }) as UnionableQuery<G, R>;\n  }\n\n  /**\n   * Combines this query with another using INTERSECT.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n  intersect(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleSetOperand(other);\n    return new UnionableQueryClass(this.#config, {\n      left: this.toAst(),\n      operator: \"intersect\",\n      right: other.toAst(),\n      // Pass state for result transformation\n      startAlias: this.#state.startAlias,\n      traversals: this.#state.traversals,\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n      selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n    }) as UnionableQuery<G, R>;\n  }\n\n  /**\n   * Combines this query with another using EXCEPT.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n  except(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleSetOperand(other);\n    return new UnionableQueryClass(this.#config, {\n      left: this.toAst(),\n      operator: \"except\",\n      right: other.toAst(),\n      // Pass state for result transformation\n      startAlias: this.#state.startAlias,\n      traversals: this.#state.traversals,\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n      selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n    }) as UnionableQuery<G, R>;\n  }\n\n  /**\n   * Compiles the query and returns the SQL text and parameters.\n   *\n   * Requires a backend to be configured (the backend determines the SQL dialect).\n   * Use this for debugging, logging, or running the query with a custom executor.\n   */\n  toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n    if (!this.#config.backend?.compileSql) {\n      throw new Error(\n        \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n          \"Use store.query() to get a backend-aware query builder.\",\n      );\n    }\n    return this.#config.backend.compileSql(this.compile());\n  }\n\n  /**\n   * Compiles the query to TypeGraph's database-independent SQL fragment.\n   *\n   * Pass the result to a GraphBackend, or use toSQL() to render SQL text and\n   * parameters for the configured dialect.\n   */\n  compile(): CompiledSelectSql {\n    // Emits a directly-runnable statement with the read instant as a literal\n    // (a backend may execute the result directly), so this is not the\n    // reusable placeholder template execute() caches — see #templateFor.\n    const ast = this.toAst();\n    return compileQuery(ast, this.#config.graphId, this.#compileOptions());\n  }\n\n  /**\n   * Compiles only the root node identity for use by a set-based mutation.\n   * This deliberately ignores the JavaScript selector supplied to\n   * `.select(...)`: candidate identity is always the root id, so changing a\n   * result projection cannot make the mutation reference a missing column.\n   */\n  compileNodeCandidateIds(readInstant?: string): CompiledSelectSql {\n    const ast = this.toAst();\n    const idColumn = `${ast.start.alias}_id`;\n    return compileQuery(\n      {\n        ...ast,\n        ...(readInstant === undefined ?\n          {}\n        : {\n            temporalMode: {\n              mode: \"asOf\",\n              asOf: readInstant,\n            },\n          }),\n        projection: {\n          fields: [\n            {\n              outputName: idColumn,\n              source: {\n                __type: \"field_ref\",\n                alias: ast.start.alias,\n                path: [\"id\"],\n                valueType: \"string\",\n              },\n            },\n          ],\n        },\n      },\n      this.#config.graphId,\n      this.#compileOptions(),\n    );\n  }\n\n  /**\n   * Creates a prepared (pre-validated) query that can be executed multiple\n   * times with different parameter bindings. Builds and structurally\n   * validates the AST once (a malformed query fails fast, here, instead of on\n   * first use); the prepared query then compiles once into a reusable template\n   * and fills a fresh read instant per execute() — see PreparedQuery's class\n   * doc comment, which also covers the two cases that recompile per call\n   * instead (no `executeRaw`, or a statement whose semantics ride on the SQL\n   * object rather than its text).\n   *\n   * Use `param(\"name\")` in predicates to create parameterized slots,\n   * then pass values via `prepared.execute({ name: \"value\" })`.\n   *\n   * @example\n   * ```typescript\n   * import { param } from \"@nicia-ai/typegraph\";\n   *\n   * const prepared = store.query()\n   *   .from(\"Person\", \"p\")\n   *   .whereNode(\"p\", (p) => p.name.eq(param(\"name\")))\n   *   .select((ctx) => ctx.p)\n   *   .prepare();\n   *\n   * const alice = await prepared.execute({ name: \"Alice\" });\n   * const bob = await prepared.execute({ name: \"Bob\" });\n   * ```\n   *\n   * @throws Error if no backend is configured\n   */\n  prepare(): PreparedQuery<R> {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n      undefined\n    ) {\n      throw new ConfigurationError(\n        \"Prepared queries are unavailable inside withCheckedReads().\",\n        { operation: \"withCheckedReads.prepare\" },\n      );\n    }\n    if (!this.#config.backend) {\n      throw new Error(\n        \"Cannot prepare query: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n\n    // Build AST once\n    const baseAst = this.toAst();\n\n    // Attempt selective field optimization\n    const selectiveFields = this.#getSelectiveFieldsForExecute();\n    const ast =\n      selectiveFields === undefined ? baseAst : { ...baseAst, selectiveFields };\n    const unoptimizedAst = baseAst;\n\n    // Compile once here purely to fail fast on a malformed query. PreparedQuery\n    // caches its own reusable placeholder template (built lazily on first\n    // execute), so this validation compile is safe to discard — it only exists\n    // to surface a structural error at prepare() time rather than first use.\n    const compileOptions = this.#compileOptions();\n    compileQuery(ast, this.#config.graphId, compileOptions);\n    compileQuery(unoptimizedAst, this.#config.graphId, compileOptions);\n\n    return new PreparedQuery({\n      ast,\n      unoptimizedAst,\n      backend: this.#config.backend,\n      dialect: this.#config.dialect ?? \"sqlite\",\n      graphId: this.#config.graphId,\n      compileOptions: compileOptions,\n      state: this.#state,\n      selectiveFields,\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure needed for PreparedQuery which uses AliasMap\n      selectFn: this.#selectFn as (context: SelectContext<any, any>) => R,\n      schemaIntrospector: this.#config.schemaIntrospector,\n    });\n  }\n\n  /**\n   * Builds compile options from the config.\n   */\n  #compileOptions(): CompileQueryOptions {\n    return buildCompileOptions(this.#config);\n  }\n\n  #requireBackend(): GraphBackend {\n    const { backend } = this.#config;\n    if (backend === undefined) {\n      throw new Error(\n        \"Cannot execute query: no backend configured. \" +\n          \"Provide a backend when creating the QueryBuilder.\",\n      );\n    }\n    return backend;\n  }\n\n  #executeOnBackend<T>(\n    backend: GraphBackend | TransactionBackend,\n    promise: Promise<T>,\n    surface: string,\n  ): Promise<T> {\n    if (this.#state.recordedAsOf === undefined) return promise;\n    return withRecordedRelationsPrecondition(promise, {\n      dialect: backend.dialect,\n      surface,\n    });\n  }\n\n  #dialect(): SqlDialect {\n    return this.#config.dialect ?? \"sqlite\";\n  }\n\n  /**\n   * The cached placeholder template for one AST variant (`\"full\"` or\n   * `\"selective\"`), or `undefined` when no fast path applies. Built once per\n   * instance from the store backend's compiler; reusable across executions and\n   * across store/transaction backends of the same dialect, since SQL text and\n   * parameters depend only on the AST and dialect. The read instant is filled\n   * fresh per call by {@link fillTemplateParams}, never frozen into the cache.\n   */\n  #templateFor(\n    ast: QueryAst,\n    slot: \"full\" | \"selective\",\n  ): CompiledTemplate | undefined {\n    const cached =\n      slot === \"full\" ? this.#fullTemplate : this.#selectiveTemplate;\n    if (cached !== NOT_COMPUTED) return cached;\n    const built = this.#buildTemplate(ast);\n    if (slot === \"full\") this.#fullTemplate = built;\n    else this.#selectiveTemplate = built;\n    return built;\n  }\n\n  #buildTemplate(ast: QueryAst): CompiledTemplate | undefined {\n    return buildQueryTemplate(\n      ast,\n      this.#config.graphId,\n      this.#compileOptions(),\n      this.#config.backend,\n    );\n  }\n\n  /**\n   * Fetches raw rows for one AST variant, path-column-normalized. Prefers the\n   * cached template + `executeRaw` fast path; falls back to a fresh literal\n   * compile via `backend.execute` when the backend cannot run raw SQL text (in\n   * which case no template is built). Callers map the returned rows to typed\n   * results.\n   */\n  async #fetchRows(\n    backend: GraphBackend | TransactionBackend,\n    ast: QueryAst,\n    slot: \"full\" | \"selective\",\n    surface: string,\n  ): Promise<readonly Record<string, unknown>[]> {\n    const executeRaw = backend.executeRaw;\n    const template =\n      executeRaw === undefined ? undefined : this.#templateFor(ast, slot);\n    const rawRows = await this.#executeOnBackend(\n      backend,\n      template !== undefined && executeRaw !== undefined ?\n        executeRaw<Record<string, unknown>>(\n          template.sql,\n          fillTemplateParams(template.params, {}, this.#dialect()),\n        )\n      : backend.execute<Record<string, unknown>>(\n          compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n        ),\n      surface,\n    );\n    return transformPathColumns(rawRows, this.#state, this.#dialect());\n  }\n\n  /**\n   * Executes the query and returns typed results.\n   *\n   * Uses smart optimization to detect when only specific fields are accessed\n   * in the select callback. If the callback only accesses simple field\n   * references (no method calls or computations), generates optimized SQL\n   * that only extracts those fields instead of the full props blob.\n   *\n   * @throws Error if no backend is configured\n   */\n  async execute(): Promise<readonly R[]> {\n    if (!this.#config.backend) {\n      throw new Error(\n        \"Cannot execute query: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n    const backend = this.#config.backend;\n\n    // Guard: reject queries with param() refs — must use .prepare().execute({...})\n    const ast = this.toAst();\n    if (this.#hasParameterReferences()) {\n      throw new Error(\n        \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n      );\n    }\n\n    const checked = getQueryBuilderInternalContext(\n      this.#config,\n    ).expectedSchemaVersion;\n    if (checked !== undefined) return this.executeChecked(checked.value);\n\n    // Phase 1: Try optimized execution\n    const optimizedResult = await this.#tryOptimizedExecution();\n    if (optimizedResult !== undefined) {\n      return optimizedResult;\n    }\n\n    // Phase 2: Fall back to full fetch (cached template + executeRaw, or a\n    // fresh literal compile on backends without raw execution).\n    const rows = await this.#fetchRows(backend, ast, \"full\", \"recorded-query\");\n\n    // Cast: runtime context includes recursive aliases; type erasure in mapResults is safe\n    return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n      rows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    );\n  }\n\n  /** Returns the first mapped row, preserving an existing zero limit. */\n  async first(): Promise<R | undefined> {\n    const query = this.limit(Math.min(this.#state.limit ?? 1, 1));\n    if (query.#hasParameterReferences())\n      throw new ConfigurationError(\n        \"first() requires bound values, not param() references.\",\n        { operation: \"first\" },\n      );\n    const checked = getQueryBuilderInternalContext(\n      this.#config,\n    ).expectedSchemaVersion;\n    if (checked !== undefined) {\n      const rows = await query.executeChecked(checked.value);\n      return rows[0];\n    }\n    const rows = await query.#fetchRows(\n      query.#requireBackend(),\n      query.toAst(),\n      \"full\",\n      \"recorded-query-first\",\n    );\n    return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n      rows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    )[0];\n  }\n\n  /** Counts SQL match rows after grouping, offset, and limit, without running the selector. */\n  count(): Promise<number> {\n    return executeQueryTerminal(this.#config, this.#state, \"count\");\n  }\n\n  /** Tests whether the bounded SQL relation has a row, without running the selector. */\n  async exists(): Promise<boolean> {\n    return (\n      (await executeQueryTerminal(this.#config, this.#state, \"exists\")) > 0\n    );\n  }\n\n  /**\n   * Reads rows and the active schema version in one statement snapshot.\n   * Throws SchemaChangedError before invoking the selector on stale rows,\n   * including when the query has no matches. Reload the schema and rebuild\n   * the query before retrying. This does not pin subsequent request reads.\n   * Uses a full projection; relevance and recursive queries are refused.\n   */\n  async executeChecked(\n    expectedSchemaVersion: number | undefined,\n  ): Promise<readonly R[]> {\n    if (this.#hasParameterReferences()) {\n      throw new Error(\n        \"Checked reads require bound values, not param() references.\",\n      );\n    }\n    const ast = this.toAst();\n    const backend = this.#requireBackend();\n    const rows = await this.#executeOnBackend(\n      backend,\n      executeSchemaCheckedRead({\n        backend,\n        ast,\n        graphId: this.#config.graphId,\n        expectedVersion: expectedSchemaVersion,\n        compile: () =>\n          compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n      }),\n      \"recorded-checked-query\",\n    );\n    return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n      rows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    );\n  }\n\n  /**\n   * Executes the query against a provided backend.\n   *\n   * Used by `store.batch()` to run several queries in sequence against one\n   * target — a transaction on backends that have them, the backend itself\n   * otherwise. The full compile → execute → transform pipeline runs\n   * identically to `execute()`, but against the given backend.\n   *\n   * Costs one statement, or two when the selective-field path runs and its\n   * mapping then falls back: `#tryOptimizedExecutionOn` detects that only\n   * after its statement has executed, and the caller re-runs the full fetch.\n   * The fallback clears the fast path for this instance.\n   */\n  async executeOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly R[]> {\n    const ast = this.toAst();\n    // Guard: reject queries with param() refs — must use .prepare().execute({...})\n    if (this.#hasParameterReferences()) {\n      throw new Error(\n        \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n      );\n    }\n\n    const checked = getQueryBuilderInternalContext(\n      this.#config,\n    ).expectedSchemaVersion;\n    if (checked !== undefined) {\n      const rows = await executeSchemaCheckedRead({\n        backend,\n        ast,\n        graphId: this.#config.graphId,\n        expectedVersion: checked.value,\n        compile: () =>\n          compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n      });\n      return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n        rows,\n        this.#state.startAlias,\n        this.#state.traversals,\n        this.#selectFn,\n      );\n    }\n\n    // Try optimized execution with the provided backend\n    const optimizedResult = await this.#tryOptimizedExecutionOn(backend);\n    if (optimizedResult !== undefined) {\n      return optimizedResult;\n    }\n\n    // Fall back to full fetch (cached template + executeRaw on the provided\n    // backend, or a fresh literal compile when it can't run raw SQL).\n    const rows = await this.#fetchRows(\n      backend,\n      ast,\n      \"full\",\n      \"recorded-batch-query\",\n    );\n\n    return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n      rows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    );\n  }\n\n  /** @internal Set-operation and batch provenance validation. */\n  oneStatementBatchProvenance(): Readonly<{\n    graphId: string;\n    executionTarget: object | undefined;\n  }> {\n    return {\n      graphId: this.#config.graphId,\n      executionTarget:\n        this.#config.backend === undefined ?\n          undefined\n        : backendDerivationRoot(this.#config.backend),\n    };\n  }\n\n  /**\n   * Describes this query as a candidate source for a set-based node update.\n   * Candidate updates use the root node identity, so one concrete root kind is\n   * required even when the query traverses other kinds.\n   */\n  toNodeCandidateSelection(): NodeCandidateSelection {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n      undefined\n    ) {\n      throw new ConfigurationError(\n        \"Queries from withCheckedReads() cannot be used as updateWhere() candidates.\",\n        {\n          code: \"SET_UPDATE_CANDIDATE_CHECKED_READS_UNSUPPORTED\",\n          operation: \"updateWhere\",\n        },\n      );\n    }\n    const ast = this.toAst();\n    if (hasParameterReferences(ast)) {\n      throw new ConfigurationError(\n        \"Set-update candidate queries cannot contain param() references; use concrete predicate values.\",\n        {\n          code: \"SET_UPDATE_CANDIDATE_PARAMETERS_UNSUPPORTED\",\n          operation: \"updateWhere\",\n        },\n      );\n    }\n    if (ast.groupBy !== undefined || ast.having !== undefined) {\n      throw new ConfigurationError(\n        \"Set-update candidate queries cannot use groupBy() or having(); select node rows directly.\",\n        {\n          code: \"SET_UPDATE_CANDIDATE_GROUPING_UNSUPPORTED\",\n          operation: \"updateWhere\",\n        },\n      );\n    }\n    if (ast.start.kinds.length !== 1 || ast.start.includeSubClasses) {\n      throw new ConfigurationError(\n        \"A set-update candidate query must select one concrete node kind.\",\n        {\n          operation: \"updateWhere\",\n          candidateKinds: ast.start.kinds,\n          includeSubClasses: ast.start.includeSubClasses,\n        },\n      );\n    }\n    const kind = ast.start.kinds[0];\n    if (kind === undefined) {\n      throw new ConfigurationError(\n        \"A set-update candidate query must have a node source.\",\n        { operation: \"updateWhere\" },\n      );\n    }\n    return {\n      graphId: this.#config.graphId,\n      executionTarget:\n        this.#config.backend === undefined ?\n          undefined\n        : backendDerivationRoot(this.#config.backend),\n      kind,\n      idColumn: `${ast.start.alias}_id`,\n      temporalMode: ast.temporalMode.mode,\n      recordedAsOf: ast.recordedAsOf,\n    };\n  }\n\n  #assertCompatibleSetOperand(\n    other: Readonly<{\n      oneStatementBatchProvenance: () => OneStatementReadProvenance;\n    }>,\n  ): void {\n    const own = this.oneStatementBatchProvenance();\n    const candidate = other.oneStatementBatchProvenance();\n    assertCompatibleSetOperationProvenance(own, candidate);\n  }\n\n  /** @internal Embedding contract consumed by `store.batchOnce()`. */\n  compileOneStatementBatchItem?(): Readonly<{\n    query: CompiledSelectSql;\n    provenance: Readonly<{ graphId: string; executionTarget: object }>;\n    outputNames: readonly string[];\n    orderBy: readonly Readonly<{\n      column: string;\n      direction: \"asc\" | \"desc\";\n      nulls: \"first\" | \"last\";\n    }>[];\n    mapRows: (rows: readonly Record<string, unknown>[]) => readonly R[];\n  }> {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n      undefined\n    ) {\n      throw new ConfigurationError(\n        \"Queries from withCheckedReads() cannot be embedded in batchOnce().\",\n        { operation: \"withCheckedReads.batchOnce\" },\n      );\n    }\n    if (this.#hasParameterReferences()) {\n      throw new Error(\n        \"Query contains param() references. Bind prepared queries before batching.\",\n      );\n    }\n    const ast = this.toAst();\n    const batchOrderBy = (ast.orderBy ?? []).map((order, index) => ({\n      column: oneStatementBatchOrderColumn(index),\n      direction: order.direction,\n      nulls: resolveNullOrdering(order),\n    }));\n    const batchAst: QueryAst =\n      batchOrderBy.length === 0 ?\n        ast\n      : {\n          ...ast,\n          projection: {\n            fields: [\n              ...ast.projection.fields,\n              ...(ast.orderBy ?? []).map((order, index) => ({\n                outputName: oneStatementBatchOrderColumn(index),\n                source: order.field,\n              })),\n            ],\n          },\n        };\n    const recursiveOutputNames = batchAst.traversals.flatMap((traversal) => {\n      const variableLength = traversal.variableLength;\n      return variableLength === undefined ?\n          []\n        : [variableLength.depthAlias, variableLength.pathAlias].filter(\n            (name): name is string => name !== undefined,\n          );\n    });\n    return {\n      query: compileQuery(\n        batchAst,\n        this.#config.graphId,\n        this.#compileOptions(),\n      ),\n      provenance: {\n        graphId: this.#config.graphId,\n        executionTarget: backendDerivationRoot(\n          requireDefined(this.#config.backend),\n        ),\n      },\n      outputNames: [\n        ...ast.projection.fields.map((field) => field.outputName),\n        ...recursiveOutputNames.filter(\n          (name) =>\n            !ast.projection.fields.some((field) => field.outputName === name),\n        ),\n      ],\n      orderBy: batchOrderBy,\n      mapRows: (rows) =>\n        mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n          transformPathColumns(rows, this.#state, this.#dialect()),\n          this.#state.startAlias,\n          this.#state.traversals,\n          this.#selectFn,\n        ),\n    };\n  }\n\n  /**\n   * Attempts optimized execution by tracking which fields the select callback accesses.\n   *\n   * Returns undefined if optimization is not possible (callback uses method calls,\n   * computations, or returns whole nodes).\n   */\n  async #tryOptimizedExecution(): Promise<readonly R[] | undefined> {\n    const selectiveFields = this.#getSelectiveFieldsForExecute();\n    if (selectiveFields === undefined) {\n      return undefined;\n    }\n\n    // Cached template + executeRaw when available; the read instant is filled\n    // fresh per call, so a reused query never freezes \"now\" (the #246\n    // regression) yet compiles only once.\n    const baseAst = this.toAst();\n    const selectiveAst = { ...baseAst, selectiveFields };\n\n    const backend = this.#requireBackend();\n    const rows = await this.#fetchRows(\n      backend,\n      selectiveAst,\n      \"selective\",\n      \"recorded-query\",\n    );\n\n    try {\n      // RecursiveAliases are populated at runtime but erased in mapSelectiveResults' signature\n      return mapSelectiveResults<Aliases, EdgeAliases, R>(\n        rows,\n        this.#state,\n        selectiveFields,\n        this.#config.schemaIntrospector,\n        this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n      );\n    } catch (error) {\n      if (error instanceof MissingSelectiveFieldError) {\n        this.#cachedSelectiveFieldsForExecute = undefined;\n        return undefined;\n      }\n      if (error instanceof UnsupportedPredicateError) {\n        this.#cachedSelectiveFieldsForExecute = undefined;\n        return undefined;\n      }\n      throw error;\n    }\n  }\n\n  /**\n   * Attempts optimized execution against a provided backend.\n   * Mirror of #tryOptimizedExecution but delegates to the given backend.\n   */\n  async #tryOptimizedExecutionOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly R[] | undefined> {\n    const selectiveFields = this.#getSelectiveFieldsForExecute();\n    if (selectiveFields === undefined) {\n      return undefined;\n    }\n\n    // Cached template + executeRaw on the provided backend; see\n    // #tryOptimizedExecution.\n    const baseAst = this.toAst();\n    const selectiveAst = { ...baseAst, selectiveFields };\n\n    const rows = await this.#fetchRows(\n      backend,\n      selectiveAst,\n      \"selective\",\n      \"recorded-batch-query\",\n    );\n\n    try {\n      return mapSelectiveResults<Aliases, EdgeAliases, R>(\n        rows,\n        this.#state,\n        selectiveFields,\n        this.#config.schemaIntrospector,\n        this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n      );\n    } catch (error) {\n      if (error instanceof MissingSelectiveFieldError) {\n        this.#cachedSelectiveFieldsForExecute = undefined;\n        return undefined;\n      }\n      if (error instanceof UnsupportedPredicateError) {\n        this.#cachedSelectiveFieldsForExecute = undefined;\n        return undefined;\n      }\n      throw error;\n    }\n  }\n\n  #trackSelectFunctionAccesses(tracker: FieldAccessTracker): void {\n    const hasOptionalTraversal = this.#state.traversals.some(\n      (traversal) => traversal.optional,\n    );\n\n    const presentTrackingRuns = [\n      { mode: \"truthy\", optionalTraversalAliases: \"present\" },\n      { mode: \"max\", optionalTraversalAliases: \"present\" },\n      { mode: \"falsy\", optionalTraversalAliases: \"present\" },\n    ] as const;\n    const trackingRuns =\n      hasOptionalTraversal ?\n        [\n          ...presentTrackingRuns,\n          { mode: \"falsy\", optionalTraversalAliases: \"absent\" } as const,\n        ]\n      : presentTrackingRuns;\n\n    for (const run of trackingRuns) {\n      const trackingContext = createTrackingContext(this.#state, tracker, {\n        schemaIntrospector: this.#config.schemaIntrospector,\n        mode: run.mode,\n        optionalTraversalAliases: run.optionalTraversalAliases,\n      });\n\n      try {\n        // Execute the select callback against a lightweight tracking context.\n        const selected = this.#selectFn(\n          trackingContext as SelectContext<\n            Aliases,\n            EdgeAliases,\n            RecursiveAliases\n          >,\n        );\n        if (containsSelectableAliasObject(selected))\n          tracker.requiresFullRow = true;\n      } catch {\n        // Best-effort tracking: any runtime errors in the callback (e.g. calling\n        // a method on an undefined optional field) should simply disable or\n        // reduce optimization, never change correctness.\n      }\n    }\n  }\n\n  #getSelectiveFieldsForExecute(): readonly SelectiveField[] | undefined {\n    if (this.#cachedSelectiveFieldsForExecute === undefined) {\n      return undefined;\n    }\n\n    if (this.#cachedSelectiveFieldsForExecute !== NOT_COMPUTED) {\n      return this.#cachedSelectiveFieldsForExecute;\n    }\n\n    const tracker = new FieldAccessTracker();\n    this.#trackSelectFunctionAccesses(tracker);\n\n    const accessed = tracker.getAccessedFields();\n    if (tracker.requiresFullRow || accessed.length === 0) {\n      this.#cachedSelectiveFieldsForExecute = undefined;\n      return undefined;\n    }\n\n    const selectiveFields = this.#ensureOptionalTraversalIdsSelected(\n      buildSelectiveFields(accessed, {\n        state: this.#state,\n        schemaIntrospector: this.#config.schemaIntrospector,\n      }),\n    );\n    this.#cachedSelectiveFieldsForExecute = selectiveFields;\n    return selectiveFields;\n  }\n\n  #getSelectiveFieldsForPagination(): readonly SelectiveField[] | undefined {\n    if (this.#cachedSelectiveFieldsForPagination === undefined) {\n      return undefined;\n    }\n\n    if (this.#cachedSelectiveFieldsForPagination !== NOT_COMPUTED) {\n      return this.#cachedSelectiveFieldsForPagination;\n    }\n\n    const tracker = new FieldAccessTracker();\n    this.#trackSelectFunctionAccesses(tracker);\n    if (\n      tracker.requiresFullRow ||\n      !this.#recordOrderByFieldsForPagination(tracker)\n    ) {\n      this.#cachedSelectiveFieldsForPagination = undefined;\n      return undefined;\n    }\n\n    const selectiveFields = this.#ensureOptionalTraversalIdsSelected(\n      buildSelectiveFields(tracker.getAccessedFields(), {\n        state: this.#state,\n        schemaIntrospector: this.#config.schemaIntrospector,\n      }),\n    );\n    this.#cachedSelectiveFieldsForPagination = selectiveFields;\n    return selectiveFields;\n  }\n\n  #ensureOptionalTraversalIdsSelected(\n    selectiveFields: readonly SelectiveField[],\n  ): readonly SelectiveField[] {\n    const result = [...selectiveFields];\n    const keys = new Set(\n      result.map(\n        (field) =>\n          `${field.alias}\\u0000${field.field}\\u0000${String(field.isSystemField)}`,\n      ),\n    );\n\n    function add(alias: string): void {\n      const key = `${alias}\\u0000id\\u0000true`;\n      if (keys.has(key)) return;\n      keys.add(key);\n      result.push({\n        alias,\n        field: \"id\",\n        outputName: `${alias}_id`,\n        isSystemField: true,\n      });\n    }\n\n    for (const traversal of this.#state.traversals) {\n      if (!traversal.optional) continue;\n      add(traversal.nodeAlias);\n      if (traversal.variableLength === undefined) add(traversal.edgeAlias);\n    }\n\n    return result.toSorted((a, b) => {\n      const aliasCompare = compareStrings(a.alias, b.alias);\n      if (aliasCompare !== 0) return aliasCompare;\n      return compareStrings(a.field, b.field);\n    });\n  }\n\n  async #tryOptimizedPaginate(\n    cursorData: CursorData | undefined,\n    direction: \"forward\" | \"backward\",\n    pageLimit: number,\n    fetchLimit: number,\n    cursor: string | undefined,\n    isBackward: boolean,\n  ): Promise<PaginatedResult<R> | undefined> {\n    const selectiveFields = this.#getSelectiveFieldsForPagination();\n    if (selectiveFields === undefined) {\n      return undefined;\n    }\n\n    let rows: readonly Record<string, unknown>[];\n    try {\n      rows = await this.#executeWithCursor(cursorData, direction, fetchLimit, {\n        selectiveFields,\n      });\n    } catch (error) {\n      if (error instanceof UnsupportedPredicateError) {\n        this.#cachedSelectiveFieldsForPagination = undefined;\n        return undefined;\n      }\n      throw error;\n    }\n\n    const hasMore = rows.length > pageLimit;\n    const resultRows = hasMore ? rows.slice(0, pageLimit) : rows;\n    const paginationDialect = this.#config.dialect ?? \"sqlite\";\n    const orderedRows = transformPathColumns(\n      isBackward ? resultRows.toReversed() : resultRows,\n      this.#state,\n      paginationDialect,\n    );\n\n    let data: readonly R[];\n    try {\n      // RecursiveAliases are populated at runtime but erased in mapSelectiveResults' signature\n      data = mapSelectiveResults<Aliases, EdgeAliases, R>(\n        orderedRows,\n        this.#state,\n        selectiveFields,\n        this.#config.schemaIntrospector,\n        this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n      );\n    } catch (error) {\n      if (error instanceof MissingSelectiveFieldError) {\n        this.#cachedSelectiveFieldsForPagination = undefined;\n        return undefined;\n      }\n      if (error instanceof UnsupportedPredicateError) {\n        this.#cachedSelectiveFieldsForPagination = undefined;\n        return undefined;\n      }\n      throw error;\n    }\n\n    try {\n      return buildPaginatedResultFromRows(\n        data,\n        orderedRows,\n        hasMore,\n        isBackward,\n        cursor,\n        (row, cursorDirection) =>\n          this.#buildCursorFromSelectiveRow(\n            row,\n            selectiveFields,\n            cursorDirection,\n          ),\n      );\n    } catch (error) {\n      if (error instanceof MissingSelectiveFieldError) {\n        this.#cachedSelectiveFieldsForPagination = undefined;\n        return undefined;\n      }\n      if (error instanceof UnsupportedPredicateError) {\n        this.#cachedSelectiveFieldsForPagination = undefined;\n        return undefined;\n      }\n      throw error;\n    }\n  }\n\n  #recordOrderByFieldsForPagination(tracker: FieldAccessTracker): boolean {\n    for (const spec of this.#paginationOrderBy()) {\n      const field = spec.field;\n\n      // System field (e.g., id, kind) — path is [\"id\"] or [\"kind\"]\n      if (\n        field.path.length === 1 &&\n        field.path[0] !== \"props\" &&\n        field.jsonPointer === undefined\n      ) {\n        tracker.record(field.alias, requireDefined(field.path[0]), true);\n        continue;\n      }\n\n      // Props field — path is [\"props\"] with a JSON pointer\n      if (field.path.length !== 1 || field.path[0] !== \"props\") {\n        return false;\n      }\n\n      if (field.jsonPointer === undefined) {\n        return false;\n      }\n\n      const segments = parseJsonPointer(field.jsonPointer);\n      if (segments.length !== 1) {\n        return false;\n      }\n\n      tracker.record(field.alias, requireDefined(segments[0]), false);\n    }\n\n    return true;\n  }\n\n  #buildCursorFromSelectiveRow(\n    row: Record<string, unknown>,\n    selectiveFields: readonly SelectiveField[],\n    direction: \"f\" | \"b\",\n  ): string {\n    const contextRow = this.#buildCursorContextFromSelectiveRow(\n      row,\n      selectiveFields,\n    );\n    return buildCursorFromRow(contextRow, this.#paginationOrderBy(), direction);\n  }\n\n  #buildCursorContextFromSelectiveRow(\n    row: Record<string, unknown>,\n    selectiveFields: readonly SelectiveField[],\n  ): Record<string, unknown> {\n    const outputNameByAliasField = new Map<string, string>();\n    for (const field of selectiveFields) {\n      outputNameByAliasField.set(\n        `${field.alias}\\u0000${field.field}`,\n        field.outputName,\n      );\n    }\n\n    const optionalNodeAliases = new Set<string>();\n    for (const traversal of this.#state.traversals) {\n      if (traversal.optional) {\n        optionalNodeAliases.add(traversal.nodeAlias);\n      }\n    }\n\n    // Null-prototype: aliases and JSON-pointer segments are caller data, and a\n    // \"__proto__\" key on an ordinary object would WRITE INTO Object.prototype\n    // (global pollution) instead of creating an entry. See\n    // store/transaction-receipt.ts createCountBucket for the same rule.\n    const cursorContext: Record<string, unknown> = Object.create(\n      null,\n    ) as Record<string, unknown>;\n\n    for (const spec of this.#paginationOrderBy()) {\n      const alias = spec.field.alias;\n      const jsonPointer = spec.field.jsonPointer;\n\n      // System field order spec (e.g., path=[\"id\"], no jsonPointer)\n      if (jsonPointer === undefined) {\n        if (spec.field.path.length !== 1) {\n          throw new MissingSelectiveFieldError(alias, \"orderBy\");\n        }\n        const fieldName = requireDefined(spec.field.path[0]);\n        const outputName = outputNameByAliasField.get(\n          `${alias}\\u0000${fieldName}`,\n        );\n        if (outputName === undefined) {\n          throw new MissingSelectiveFieldError(alias, fieldName);\n        }\n\n        const aliasObject = this.#getOrCreateAliasObject(cursorContext, alias);\n        aliasObject[fieldName] = nullToUndefined(row[outputName]);\n        continue;\n      }\n\n      const segments = parseJsonPointer(jsonPointer);\n      if (segments.length === 0) {\n        throw new MissingSelectiveFieldError(alias, \"orderBy\");\n      }\n\n      const topField = requireDefined(segments[0]);\n      const outputName = outputNameByAliasField.get(\n        `${alias}\\u0000${topField}`,\n      );\n      if (outputName === undefined) {\n        throw new MissingSelectiveFieldError(alias, topField);\n      }\n\n      if (optionalNodeAliases.has(alias)) {\n        const idOutputName = outputNameByAliasField.get(`${alias}\\u0000id`);\n        if (idOutputName === undefined) {\n          throw new MissingSelectiveFieldError(alias, \"id\");\n        }\n        const idValue = row[idOutputName];\n        if (idValue === null || idValue === undefined) {\n          continue;\n        }\n      }\n\n      const aliasObject = this.#getOrCreateAliasObject(cursorContext, alias);\n\n      const kindNames = this.#getNodeKindNamesForAlias(alias);\n      const typeInfo =\n        kindNames ?\n          this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n            kindNames,\n            topField,\n          )\n        : undefined;\n\n      const decoded = decodeSelectedValue(row[outputName], typeInfo);\n\n      if (segments.length === 1) {\n        aliasObject[topField] = decoded;\n        continue;\n      }\n\n      let current = aliasObject;\n      for (let index = 0; index < segments.length - 1; index++) {\n        const segment = requireDefined(segments[index]);\n        const existing_ = current[segment];\n        if (typeof existing_ === \"object\" && existing_ !== null) {\n          current = existing_ as Record<string, unknown>;\n        } else {\n          const created: Record<string, unknown> = Object.create(\n            null,\n          ) as Record<string, unknown>;\n          current[segment] = created;\n          current = created;\n        }\n      }\n      current[requireDefined(segments.at(-1))] = decoded;\n    }\n\n    return cursorContext;\n  }\n\n  #getOrCreateAliasObject(\n    cursorContext: Record<string, unknown>,\n    alias: string,\n  ): Record<string, unknown> {\n    const existing = cursorContext[alias];\n    if (typeof existing === \"object\" && existing !== null) {\n      return existing as Record<string, unknown>;\n    }\n    const created: Record<string, unknown> = Object.create(null) as Record<\n      string,\n      unknown\n    >;\n    cursorContext[alias] = created;\n    return created;\n  }\n\n  #getNodeKindNamesForAlias(alias: string): readonly string[] | undefined {\n    if (alias === this.#state.startAlias) {\n      return this.#state.startKinds;\n    }\n    return this.#state.traversals.find((t) => t.nodeAlias === alias)?.nodeKinds;\n  }\n\n  /**\n   * The ORDER BY used for keyset pagination: the caller's ORDER BY plus a final\n   * identity tiebreaker on the start alias. Without a unique final key, a\n   * non-unique sort (e.g. `orderBy(\"p\", \"age\")` with many equal ages) makes the\n   * keyset predicate `age > lastAge` skip every not-yet-returned equal-age row,\n   * silently losing data across pages. For a multi-kind start, identity is\n   * `(kind, id)`; each missing component is appended after the caller's order.\n   * For a single-kind start, `id` alone remains sufficient. The emitted sort,\n   * cursor predicate, cursor encoding, and cursor validation all use this order,\n   * including the selective-field-optimized path.\n   */\n  #paginationOrderBy(): readonly (Omit<OrderSpec, \"field\"> & {\n    field: FieldRef;\n  })[] {\n    const orderBy = this.#state.orderBy.map((order) => ({\n      ...order,\n      field: requireCursorField(order.field),\n    }));\n    const startAlias = this.#state.startAlias;\n    function hasSystemOrder(fieldName: \"kind\" | \"id\"): boolean {\n      return orderBy.some(\n        (spec) =>\n          spec.field.alias === startAlias &&\n          spec.field.path.length === 1 &&\n          spec.field.path[0] === fieldName &&\n          spec.field.jsonPointer === undefined,\n      );\n    }\n    const missingKind =\n      this.#state.startKinds.length > 1 && !hasSystemOrder(\"kind\");\n    const missingId = !hasSystemOrder(\"id\");\n    if (!missingKind && !missingId) return orderBy;\n    function tiebreaker(fieldName: \"kind\" | \"id\"): OrderSpec & {\n      field: FieldRef;\n    } {\n      return {\n        field: {\n          __type: \"field_ref\",\n          alias: startAlias,\n          nullable: false,\n          path: [fieldName],\n          valueType: \"string\",\n        },\n        direction: \"asc\",\n      };\n    }\n    return [\n      ...orderBy,\n      ...(missingKind ? [tiebreaker(\"kind\")] : []),\n      ...(missingId ? [tiebreaker(\"id\")] : []),\n    ];\n  }\n\n  /**\n   * Executes a paginated query using cursor-based keyset pagination.\n   *\n   * Cursor pagination is efficient for large datasets as it avoids OFFSET.\n   * Requires ORDER BY to be specified for deterministic results.\n   *\n   * @param options - Pagination options (first/after for forward, last/before for backward)\n   * @throws ValidationError if ORDER BY is not specified\n   * @throws ValidationError if cursor columns don't match query ORDER BY columns\n   */\n  async paginate(options: PaginateOptions): Promise<PaginatedResult<R>> {\n    this.#refuseCheckedReadSurface(\"paginate\");\n    validatePaginationOptions(this.#state, options);\n    if (this.#hasParameterReferences())\n      throw new ConfigurationError(\n        \"Cursor pagination requires bound values, not param() references.\",\n        { operation: \"paginate\" },\n      );\n    if (!this.#config.backend) {\n      throw new Error(\n        \"Cannot execute query: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n\n    // Validate ORDER BY is present\n    if (this.#state.orderBy.length === 0) {\n      throw new ValidationError(\n        \"Cursor pagination requires ORDER BY. Add .orderBy() before .paginate()\",\n        {\n          issues: [\n            {\n              path: \"orderBy\",\n              message: \"ORDER BY is required for cursor pagination\",\n            },\n          ],\n        },\n        {\n          suggestion: `Add .orderBy(alias, field) before .paginate() to specify sort order.`,\n        },\n      );\n    }\n\n    // Determine pagination direction and parameters\n    const isBackward =\n      options.last !== undefined || options.before !== undefined;\n    const limit = options.first ?? options.last ?? DEFAULT_PAGINATION_LIMIT;\n    const cursor = options.after ?? options.before;\n\n    // Decode and validate cursor if provided\n    let cursorData: CursorData | undefined;\n    if (cursor) {\n      cursorData = decodeCursor(cursor);\n      validateCursorColumns(cursorData, this.#paginationOrderBy());\n    }\n\n    // Fetch limit + 1 to detect if there are more pages\n    const fetchLimit = limit + 1;\n\n    const direction = isBackward ? \"backward\" : \"forward\";\n    const optimized = await this.#tryOptimizedPaginate(\n      cursorData,\n      direction,\n      limit,\n      fetchLimit,\n      cursor,\n      isBackward,\n    );\n    if (optimized !== undefined) {\n      return optimized;\n    }\n\n    // Build and execute query with cursor condition\n    const rows = await this.#executeWithCursor(\n      cursorData,\n      direction,\n      fetchLimit,\n    );\n\n    // Detect if there are more items\n    const hasMore = rows.length > limit;\n    const resultRows = hasMore ? rows.slice(0, limit) : rows;\n\n    // For backward pagination, reverse the results to maintain natural order\n    const orderedRows = isBackward ? resultRows.toReversed() : resultRows;\n\n    // Map to typed results\n    const data = mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n      orderedRows,\n      this.#state.startAlias,\n      this.#state.traversals,\n      this.#selectFn,\n    );\n\n    // Build paginated result with cursors\n    return buildPaginatedResult(\n      data,\n      orderedRows,\n      this.#paginationOrderBy(),\n      limit,\n      hasMore,\n      isBackward,\n      cursor,\n      (row) =>\n        buildSelectContext<Aliases, EdgeAliases, RecursiveAliases>(\n          row,\n          this.#state.startAlias,\n          this.#state.traversals,\n        ),\n    );\n  }\n\n  /**\n   * Builds a cold cursor-page read that can execute independently or as one\n   * member of `store.batchOnce()`.\n   */\n  page(\n    options: PaginateOptions,\n  ): CompiledOneStatementRead<PaginatedResult<R>> &\n    Required<Pick<OneStatementBatchableQuery<PaginatedResult<R>>, \"execute\">> {\n    this.#refuseCheckedReadSurface(\"page\");\n    const pageOptions = { ...options };\n    validatePaginationOptions(this.#state, pageOptions);\n    if (this.#hasParameterReferences())\n      throw new ConfigurationError(\n        \"Cursor pagination requires bound values, not param() references.\",\n        { operation: \"page\" },\n      );\n    if (!this.#config.backend) {\n      throw new Error(\n        \"Cannot build page read: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n    if (this.#state.orderBy.length === 0) {\n      throw new ValidationError(\n        \"Cursor pagination requires ORDER BY. Add .orderBy() before .page()\",\n        {\n          issues: [\n            {\n              path: \"orderBy\",\n              message: \"ORDER BY is required for cursor pagination\",\n            },\n          ],\n        },\n        {\n          suggestion: `Add .orderBy(alias, field) before .page() to specify sort order.`,\n        },\n      );\n    }\n\n    const isBackward =\n      pageOptions.last !== undefined || pageOptions.before !== undefined;\n    const pageLimit =\n      pageOptions.first ?? pageOptions.last ?? DEFAULT_PAGINATION_LIMIT;\n    const cursor = pageOptions.after ?? pageOptions.before;\n    const paginationOrderBy = this.#paginationOrderBy();\n    const cursorData = cursor === undefined ? undefined : decodeCursor(cursor);\n    if (cursorData !== undefined)\n      validateCursorColumns(cursorData, paginationOrderBy);\n    const direction = isBackward ? \"backward\" : \"forward\";\n    const orderBy = adjustOrderByForDirection(paginationOrderBy, direction);\n    const predicates =\n      cursorData === undefined ?\n        this.#state.predicates\n      : [\n          ...this.#state.predicates,\n          buildCursorPredicate(\n            cursorData,\n            paginationOrderBy,\n            direction,\n            this.#state.startAlias,\n          ),\n        ];\n    const pagedQuery = new ExecutableQuery(\n      this.#config,\n      {\n        ...this.#state,\n        predicates,\n        orderBy,\n        limit: pageLimit + 1,\n        offset: undefined,\n      },\n      this.#selectFn,\n    );\n\n    return {\n      execute: () => this.paginate(pageOptions),\n      compileOneStatementBatchItem: () => {\n        const item = requireDefined(\n          pagedQuery.compileOneStatementBatchItem?.(),\n        );\n        const cursorOutputNames = orderBy.map((_spec, index) =>\n          oneStatementBatchOrderColumn(index),\n        );\n        function cursorFromRow(\n          row: Record<string, unknown>,\n          cursorDirection: \"f\" | \"b\",\n        ): string {\n          return buildCursorFromValues(\n            cursorOutputNames.map((outputName) => row[outputName]),\n            paginationOrderBy,\n            cursorDirection,\n          );\n        }\n        return {\n          ...item,\n          hiddenOutputNames: cursorOutputNames,\n          mapRows: (rows: readonly Record<string, unknown>[]) => {\n            const hasMore = rows.length > pageLimit;\n            const fetchedRows = hasMore ? rows.slice(0, pageLimit) : rows;\n            const orderedRows =\n              isBackward ? fetchedRows.toReversed() : fetchedRows;\n            const data = item.mapRows(orderedRows);\n            return buildPaginatedResultFromRows(\n              data,\n              orderedRows,\n              hasMore,\n              isBackward,\n              cursor,\n              (row, cursorDirection) => cursorFromRow(row, cursorDirection),\n            );\n          },\n        };\n      },\n    };\n  }\n\n  /**\n   * Returns an async iterator that streams results in batches.\n   *\n   * Uses cursor pagination internally for efficient memory usage.\n   * Requires ORDER BY to be specified for deterministic results.\n   *\n   * @param options - Stream options (batchSize defaults to 1000)\n   * @throws ValidationError if ORDER BY is not specified\n   */\n  stream(options?: StreamOptions): AsyncIterable<R> {\n    this.#refuseCheckedReadSurface(\"stream\");\n    // Validate ORDER BY is present\n    if (this.#state.orderBy.length === 0) {\n      throw new ValidationError(\n        \"Streaming requires ORDER BY. Add .orderBy() before .stream()\",\n        {\n          issues: [\n            { path: \"orderBy\", message: \"ORDER BY is required for streaming\" },\n          ],\n        },\n        {\n          suggestion: `Add .orderBy(alias, field) before .stream() to specify sort order.`,\n        },\n      );\n    }\n\n    const batchSize = getStreamBatchSize(options);\n    return createStreamIterable(batchSize, (paginateOptions) =>\n      this.paginate(paginateOptions),\n    );\n  }\n\n  #refuseCheckedReadSurface(surface: \"page\" | \"paginate\" | \"stream\"): void {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion ===\n      undefined\n    ) {\n      return;\n    }\n    throw new ConfigurationError(\n      `${surface === \"stream\" ? \"Streaming\" : \"Pagination\"} is unavailable inside withCheckedReads().`,\n      { operation: `withCheckedReads.${surface}` },\n    );\n  }\n\n  /**\n   * Executes a query with cursor conditions applied.\n   */\n  async #executeWithCursor(\n    cursorData: CursorData | undefined,\n    direction: \"forward\" | \"backward\",\n    limit: number,\n    options?: Readonly<{ selectiveFields?: readonly SelectiveField[] }>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    const ast = this.toAst();\n\n    const orderBy = adjustOrderByForDirection(\n      this.#paginationOrderBy(),\n      direction,\n    );\n\n    // Build cursor predicates if we have cursor data\n    let predicates = [...this.#state.predicates];\n    if (cursorData) {\n      const cursorPredicate = buildCursorPredicate(\n        cursorData,\n        this.#paginationOrderBy(),\n        direction,\n        this.#state.startAlias,\n      );\n      predicates = [...predicates, cursorPredicate];\n    }\n\n    // Apply modified ORDER BY, predicates, and limit to AST (discard offset)\n    const { offset: _discarded, ...astWithoutOffset } = ast;\n    const modifiedAst = {\n      ...astWithoutOffset,\n      predicates,\n      orderBy,\n      limit,\n      ...(options?.selectiveFields !== undefined && {\n        selectiveFields: options.selectiveFields,\n      }),\n    };\n\n    // Compile and execute\n    const compiled = compileQuery(\n      modifiedAst,\n      this.#config.graphId,\n      this.#compileOptions(),\n    );\n    const rawRows =\n      await this.#requireBackend().execute<Record<string, unknown>>(compiled);\n    const dialect = this.#config.dialect ?? \"sqlite\";\n    return transformPathColumns(rawRows, this.#state, dialect);\n  }\n}\n","import { ConfigurationError } from \"../../errors\";\nimport { isPortableCountDistinctValueType } from \"../aggregate-value-types\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport {\n  expressionContainsAggregate,\n  isAggregateExpression,\n  visitExpressionChildren,\n} from \"./expression-inspection\";\n\n/** SQL grouping needs every value outside an aggregate to be group-determined. */\nexport function validateRelationAggregation(\n  projection: readonly DatabaseExpression[],\n  groupBy: readonly DatabaseExpression[] = [],\n): void {\n  if (\n    groupBy.some(\n      (expression) => !isPortableCountDistinctValueType(expression.valueType),\n    )\n  )\n    throw new ConfigurationError(\n      \"Relation GROUP BY requires portable scalar expressions.\",\n    );\n  if (groupBy.some((expression) => expressionContainsAggregate(expression)))\n    throw new ConfigurationError(\n      \"Relation GROUP BY cannot contain aggregate expressions.\",\n    );\n  if (\n    groupBy.length === 0 &&\n    !projection.some((expression) => expressionContainsAggregate(expression))\n  )\n    return;\n\n  // Scope was validated at construction; the serializable node is the SQL expression's identity.\n  const grouped = new Set(\n    groupBy.map((expression) => JSON.stringify(expression.node)),\n  );\n  function validate(expression: DatabaseExpression): void {\n    if (\n      isAggregateExpression(expression) ||\n      grouped.has(JSON.stringify(expression.node))\n    )\n      return;\n    if (\n      expression.node.kind === \"field\" ||\n      expression.node.kind === \"outer_reference\"\n    )\n      throw new ConfigurationError(\n        \"Every projected field outside an aggregate must be determined by GROUP BY.\",\n      );\n    visitExpressionChildren(expression, (operand) => {\n      validate(operand);\n    });\n  }\n  for (const expression of projection) validate(expression);\n}\n","import { ConfigurationError } from \"../../errors\";\nimport type { QueryAst, SortDirection, ValueType } from \"../ast\";\nimport {\n  type DatabaseExpression,\n  haveCompatibleCollectionElements,\n} from \"../expressions\";\nimport { compileOrderTerm } from \"../order\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { asCompiledSelectSql, type CompiledSelectSql } from \"../sql-intent\";\nimport {\n  compileDatabaseExpression,\n  type DatabaseExpressionCompilerContext,\n} from \"./database-expressions\";\nimport { compileQuery, type CompileQueryOptions } from \"./index\";\nimport { compileLimitOffsetClauses } from \"./limit-offset\";\nimport { validateRelationAggregation } from \"./relation-aggregate-validation\";\nimport { setOperationKeyword } from \"./set-operations\";\nimport { withPinnedReadInstant } from \"./temporal\";\n\nexport type RelationColumn = Readonly<{\n  outputName: string;\n  valueType: ValueType;\n  elementValueType?: ValueType;\n  elementFields?: Readonly<Record<string, ValueType>>;\n  nullable: boolean;\n  /** Proven graph-node identity carried only from a direct graph field. */\n  identity?: Readonly<{\n    component: \"id\" | \"kind\";\n    alias: string;\n  }>;\n}>;\n\nexport type RelationOrder = Readonly<{\n  expression: DatabaseExpression;\n  direction: SortDirection;\n  nulls: \"first\" | \"last\";\n}>;\n\ntype RelationSource = Readonly<{\n  kind: \"source\";\n  query: QueryAst;\n  graphId: string;\n  options: CompileQueryOptions;\n}>;\n\ntype DerivedRelation = Readonly<{\n  kind: \"derived\";\n  source: RelationAst;\n  sourceColumns: readonly RelationColumn[];\n  projection: readonly Readonly<{\n    column: RelationColumn;\n    expression: DatabaseExpression;\n  }>[];\n  predicate?: DatabaseExpression<boolean | undefined>;\n  groupBy?: readonly DatabaseExpression[];\n  distinct: boolean;\n  orderBy: readonly RelationOrder[];\n  limit?: number;\n  offset?: number;\n}>;\n\ntype SetRelation = Readonly<{\n  kind: \"set\";\n  operator: \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n  left: RelationAst;\n  right: RelationAst;\n  columns: readonly RelationColumn[];\n}>;\n\nexport type TopPerPartitionRelation = Readonly<{\n  kind: \"topPerPartition\";\n  source: RelationAst;\n  columns: readonly RelationColumn[];\n  partitionBy: readonly DatabaseExpression[];\n  orderBy: readonly RelationOrder[];\n  limit: number;\n}>;\n\nexport type RelationAst =\n  DerivedRelation | RelationSource | SetRelation | TopPerPartitionRelation;\n\nfunction relationSources(relation: RelationAst): readonly RelationSource[] {\n  switch (relation.kind) {\n    case \"source\": {\n      return [relation];\n    }\n    case \"derived\": {\n      return relationSources(relation.source);\n    }\n    case \"topPerPartition\": {\n      return relationSources(relation.source);\n    }\n    case \"set\": {\n      return [\n        ...relationSources(relation.left),\n        ...relationSources(relation.right),\n      ];\n    }\n  }\n}\n\nconst SOURCE_ALIAS = \"typegraph_relation_source\";\n\nfunction expressionContext(\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  allowAggregates: boolean,\n  orderedAggregates: boolean,\n): DatabaseExpressionCompilerContext {\n  return {\n    allowAggregates,\n    aggregateClause:\n      allowAggregates ? \"relation projection\" : \"relation filter and ordering\",\n    dialect,\n    orderedAggregates,\n    compileFieldExpression(field) {\n      if (\n        field.alias !== \"relation\" ||\n        field.path.length !== 1 ||\n        field.path[0] === undefined\n      )\n        return;\n      return sql`${sql.identifier(SOURCE_ALIAS)}.${sql.identifier(field.path[0])}`;\n    },\n  };\n}\n\nfunction compileExpression(\n  expression: DatabaseExpression,\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  allowAggregates: boolean,\n  orderedAggregates: boolean,\n): SqlFragment {\n  return compileDatabaseExpression(\n    expression,\n    expressionContext(dialect, allowAggregates, orderedAggregates),\n  );\n}\n\nfunction compileOrder(\n  orderBy: readonly RelationOrder[],\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  orderedAggregates: boolean,\n): SqlFragment {\n  if (orderBy.length === 0) return sql.empty();\n  if (orderBy.some((order) => order.expression.elementValueType !== undefined))\n    throw new ConfigurationError(\n      \"Relation ordering requires scalar keys; collection-valued ordering is unsupported.\",\n    );\n  return sql` ORDER BY ${sql.join(\n    orderBy.map((order) =>\n      compileOrderTerm(\n        compileExpression(order.expression, dialect, false, orderedAggregates),\n        order.direction,\n        order.nulls,\n      ),\n    ),\n    sql`, `,\n  )}`;\n}\n\nfunction compileDerived(\n  relation: DerivedRelation,\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  orderedAggregates: boolean,\n): CompiledSelectSql {\n  validateRelationAggregation(\n    relation.projection.map(({ expression }) => expression),\n    relation.groupBy,\n  );\n  const source = compileRelation(relation.source, dialect);\n  const projection = sql.join(\n    relation.projection.map(\n      ({ column, expression }) =>\n        sql`${compileExpression(expression, dialect, true, orderedAggregates)} AS ${sql.identifier(column.outputName)}`,\n    ),\n    sql`, `,\n  );\n  const predicate =\n    relation.predicate === undefined ?\n      sql.empty()\n    : sql` WHERE ${compileExpression(relation.predicate, dialect, false, orderedAggregates)}`;\n  const groupBy =\n    relation.groupBy === undefined || relation.groupBy.length === 0 ?\n      sql.empty()\n    : sql` GROUP BY ${sql.join(\n        relation.groupBy.map((expression) =>\n          compileExpression(expression, dialect, false, orderedAggregates),\n        ),\n        sql`, `,\n      )}`;\n  return asCompiledSelectSql(\n    sql`SELECT ${relation.distinct ? sql.raw(\"DISTINCT \") : sql.empty()}${projection} FROM (${source}) AS ${sql.identifier(SOURCE_ALIAS)}${predicate}${groupBy}${compileOrder(relation.orderBy, dialect, orderedAggregates)} ${sql.join(compileLimitOffsetClauses(relation.limit, relation.offset, dialect), sql` `)}`,\n  );\n}\n\nfunction compileTopPerPartition(\n  relation: TopPerPartitionRelation,\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  orderedAggregates: boolean,\n): CompiledSelectSql {\n  const source = compileRelation(relation.source, dialect);\n  const partition = sql.join(\n    relation.partitionBy.map((expression) =>\n      compileExpression(expression, dialect, false, orderedAggregates),\n    ),\n    sql`, `,\n  );\n  const ordering = compileOrder(relation.orderBy, dialect, orderedAggregates);\n  const occupiedNames = new Set(\n    // SQLite resolves even quoted identifiers without case sensitivity.\n    relation.columns.map((column) => column.outputName.toLowerCase()),\n  );\n  let rankName = \"__tg_partition_rank\";\n  while (occupiedNames.has(rankName)) rankName += \"_\";\n  const selectedColumns = sql.join(\n    relation.columns.map(\n      (column) =>\n        sql`${sql.identifier(SOURCE_ALIAS)}.${sql.identifier(column.outputName)}`,\n    ),\n    sql`, `,\n  );\n  return asCompiledSelectSql(\n    sql`SELECT ${selectedColumns} FROM (SELECT ${sql.identifier(SOURCE_ALIAS)}.*, ROW_NUMBER() OVER (PARTITION BY ${partition}${ordering}) AS ${sql.identifier(rankName)} FROM (${source}) AS ${sql.identifier(SOURCE_ALIAS)}) AS ${sql.identifier(SOURCE_ALIAS)} WHERE ${sql.identifier(SOURCE_ALIAS)}.${sql.identifier(rankName)} <= ${relation.limit}`,\n  );\n}\n\n/** Compiles a structural relation tree without selecting a dialect strategy path. */\nfunction compileRelationInner(\n  relation: RelationAst,\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n  orderedAggregates: boolean,\n): CompiledSelectSql {\n  switch (relation.kind) {\n    case \"source\": {\n      return compileQuery(relation.query, relation.graphId, relation.options);\n    }\n    case \"derived\": {\n      return compileDerived(relation, dialect, orderedAggregates);\n    }\n    case \"topPerPartition\": {\n      return compileTopPerPartition(relation, dialect, orderedAggregates);\n    }\n    case \"set\": {\n      const left = compileRelation(relation.left, dialect);\n      const right = compileRelation(relation.right, dialect);\n      const columns = sql.join(\n        relation.columns.map(\n          (column) =>\n            sql`${sql.identifier(\"typegraph_relation_left\")}.${sql.identifier(column.outputName)}`,\n        ),\n        sql`, `,\n      );\n      const rightColumns = sql.join(\n        relation.columns.map(\n          (column) =>\n            sql`${sql.identifier(\"typegraph_relation_right\")}.${sql.identifier(column.outputName)}`,\n        ),\n        sql`, `,\n      );\n      const operator = setOperationKeyword(relation.operator);\n      return asCompiledSelectSql(\n        sql`SELECT ${columns} FROM (${left}) AS ${sql.identifier(\"typegraph_relation_left\")} ${sql.raw(operator)} SELECT ${rightColumns} FROM (${right}) AS ${sql.identifier(\"typegraph_relation_right\")}`,\n      );\n    }\n  }\n}\n\nexport function compileRelation(\n  relation: RelationAst,\n  dialect: DatabaseExpressionCompilerContext[\"dialect\"],\n): CompiledSelectSql {\n  const orderedAggregates = relationSources(relation).every(\n    (source) => source.options.orderedAggregates === true,\n  );\n  return withPinnedReadInstant(() =>\n    compileRelationInner(relation, dialect, orderedAggregates),\n  );\n}\n\nexport function assertCompatibleRelationColumns(\n  left: readonly RelationColumn[],\n  right: readonly RelationColumn[],\n): void {\n  if (left.length !== right.length)\n    throw new ConfigurationError(\n      \"Set-operation projections must have the same number of columns.\",\n    );\n  for (const [index, leftColumn] of left.entries()) {\n    const rightColumn = right[index];\n    if (\n      leftColumn.outputName !== rightColumn?.outputName ||\n      leftColumn.valueType !== rightColumn.valueType ||\n      !haveCompatibleCollectionElements(leftColumn, rightColumn) ||\n      leftColumn.nullable !== rightColumn.nullable\n    ) {\n      throw new ConfigurationError(\n        \"Set-operation projections must have identical ordered column names, types, collection element codecs, and nullability.\",\n        { index, left: leftColumn, right: rightColumn },\n      );\n    }\n  }\n}\n","import { ConfigurationError } from \"../../errors\";\nimport type { QueryAst } from \"../ast\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport { collectParameterMetadata } from \"./prepared-query\";\n\n/** Parameter expressions reused by a query and its typed preparation boundary. */\nexport type PreparedParameterDeclaration = Readonly<\n  Record<string, DatabaseExpression>\n>;\n\nexport type PreparedBindings<Parameters extends PreparedParameterDeclaration> =\n  {\n    readonly [Name in keyof Parameters]: Parameters[Name] extends (\n      DatabaseExpression<infer Value>\n    ) ?\n      Value\n    : never;\n  };\n\n/** Refuses declarations that would promise different bindings from the SQL relation. */\nexport function validatePreparedBindingsDeclaration(\n  parameters: PreparedParameterDeclaration,\n  queries: readonly QueryAst[],\n  expressions: readonly DatabaseExpression[] = [],\n): void {\n  const metadata = collectParameterMetadata(queries, expressions);\n  const names = Object.keys(parameters);\n  if (\n    Object.getOwnPropertySymbols(parameters).length > 0 ||\n    names.length !== metadata.names.size ||\n    names.some((name) => !metadata.names.has(name))\n  )\n    throw new ConfigurationError(\n      \"Prepared parameter declarations must name every query parameter exactly once.\",\n    );\n\n  for (const [name, expression] of Object.entries(parameters)) {\n    if (expression.node.kind !== \"parameter\" || expression.node.name !== name)\n      throw new ConfigurationError(\n        `Prepared declaration \"${name}\" must contain the parameter expression with that name.`,\n      );\n    const expectedType = metadata.expressionParameterTypes.get(name);\n    if (\n      expectedType === undefined ||\n      expectedType !== expression.valueType ||\n      expression.nullable\n    )\n      throw new ConfigurationError(\n        `Prepared declaration \"${name}\" must match its typed query parameter.`,\n      );\n    if (metadata.listParameters.has(name))\n      throw new ConfigurationError(\n        `Prepared declaration \"${name}\" cannot describe a legacy list parameter.`,\n      );\n  }\n}\n","import type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport type { CompiledSelectSql } from \"../sql-intent\";\n\n/** Keeps SQL-rendering capability checks shared by projection and relation execution. */\nexport function renderQuerySql(\n  backend: GraphBackend | TransactionBackend,\n  compile: () => CompiledSelectSql,\n): Readonly<{ sql: string; params: readonly unknown[] }> {\n  if (backend.compileSql === undefined)\n    throw new ConfigurationError(\"The backend cannot render SQL text.\");\n  return backend.compileSql(compile());\n}\n","import { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport {\n  ConfigurationError,\n  UnsupportedBackendCapabilityError,\n} from \"../../errors\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport { isPortableCountDistinctValueType } from \"../aggregate-value-types\";\nimport type { QueryAst, SortDirection } from \"../ast\";\nimport {\n  assertCompatibleRelationColumns,\n  compileRelation,\n  type RelationAst,\n  type RelationColumn,\n  type RelationOrder,\n  type TopPerPartitionRelation,\n} from \"../compiler/relations\";\nimport { getDialect } from \"../dialect\";\nimport {\n  createFieldExpression,\n  type DatabaseExpression,\n  expr,\n} from \"../expressions\";\nimport { resolveNullOrdering } from \"../order\";\nimport { sql } from \"../sql-fragment\";\nimport { asCompiledSelectSql } from \"../sql-intent\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { decodeExpressionValue } from \"./executable-projection-query\";\nimport {\n  assertExpressionScope,\n  isDatabaseExpression,\n} from \"./expression-scope\";\nimport {\n  type PreparedBindings,\n  type PreparedParameterDeclaration,\n  validatePreparedBindingsDeclaration,\n} from \"./prepared-bindings\";\nimport {\n  bindQueryParametersSubset,\n  collectParameterMetadata,\n  substituteDatabaseExpression,\n  validateQueryBindings,\n} from \"./prepared-query\";\nimport {\n  buildReadInstantTemplate,\n  type CompiledTemplate,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport { renderQuerySql } from \"./render-query-sql\";\nimport type { QueryBuilderConfig } from \"./types\";\nimport { validateQueryRange, validateSortDirection } from \"./validation\";\n\nexport type RelationProjection = Readonly<Record<string, DatabaseExpression>>;\nexport type RelationProjectionResult<Fields extends RelationProjection> = {\n  -readonly [Key in keyof Fields]: Fields[Key] extends (\n    DatabaseExpression<infer Value>\n  ) ?\n    Value\n  : never;\n};\n\nexport type RelationColumnContext<Fields extends RelationProjection> = {\n  readonly [Key in keyof Fields]: Fields[Key] extends (\n    DatabaseExpression<infer Value, infer Scope>\n  ) ?\n    DatabaseExpression<Value, Scope>\n  : never;\n};\n\n/**\n * A scalar ordering term used to choose winners within each partition.\n * Defaults to ascending with NULLS LAST; descending defaults to NULLS FIRST.\n * @public\n */\nexport type TopPerPartitionOrder = Readonly<{\n  expression: DatabaseExpression;\n  direction?: SortDirection;\n  nulls?: \"first\" | \"last\";\n}>;\n\n/**\n * Selects up to `limit` rows per partition using explicit scalar keys and ordering.\n * Include a stable final tie-breaker; tied rows do not expand the positive safe-integer limit.\n * @public\n */\nexport type TopPerPartitionOptions<Fields extends RelationProjection> =\n  Readonly<{\n    partitionBy: (\n      columns: RelationColumnContext<Fields>,\n    ) => readonly [DatabaseExpression, ...DatabaseExpression[]];\n    orderBy: (\n      columns: RelationColumnContext<Fields>,\n    ) => readonly [TopPerPartitionOrder, ...TopPerPartitionOrder[]];\n    limit: number;\n  }>;\n\nexport type RelationProvenance = Readonly<{\n  graphId: string;\n  executionTarget: object | undefined;\n  recordedAsOf: string | undefined;\n  checked: boolean;\n  temporalCoordinate: string;\n}>;\n\nexport type RelationDefinition<\n  Fields extends RelationProjection,\n  Result,\n> = Readonly<{\n  ast: RelationAst;\n  columns: readonly RelationColumn[];\n  fields: Fields;\n  config: QueryBuilderConfig;\n  provenance: RelationProvenance;\n  decodeRow: (row: Record<string, unknown>) => Result;\n  mapped?: boolean;\n}>;\n\ntype RelationState = Readonly<{\n  predicate?: DatabaseExpression<boolean | undefined>;\n  groupBy?: readonly DatabaseExpression[];\n  distinct: boolean;\n  orderBy: readonly RelationOrder[];\n  limit?: number;\n  offset?: number;\n}>;\n\nconst EMPTY_STATE: RelationState = { distinct: false, orderBy: [] };\n\n/** Sentinel distinguishing a template that was not built from one that cannot be built. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\nfunction relationScope(): symbol {\n  return Symbol(\"derived relation expression scope\");\n}\n\nfunction outputField(\n  outputName: string,\n  valueType: RelationColumn[\"valueType\"],\n) {\n  return {\n    __type: \"field_ref\",\n    alias: \"relation\",\n    path: [outputName],\n    valueType,\n  } as const;\n}\n\nfunction buildContext<Fields extends RelationProjection>(\n  columns: readonly RelationColumn[],\n  scopeIdentity: symbol,\n): RelationColumnContext<Fields> {\n  return Object.fromEntries(\n    columns.map((column) => [\n      column.outputName,\n      {\n        ...createFieldExpression(\n          outputField(column.outputName, column.valueType),\n          scopeIdentity,\n          column.nullable,\n        ),\n        ...(column.elementValueType === undefined ?\n          {}\n        : { elementValueType: column.elementValueType }),\n        ...(column.elementFields === undefined ?\n          {}\n        : { elementFields: column.elementFields }),\n      },\n    ]),\n  ) as RelationColumnContext<Fields>;\n}\n\nfunction relationColumns(\n  fields: RelationProjection,\n  options: Readonly<{\n    sourceColumns?: readonly RelationColumn[];\n    nodeAliases?: ReadonlySet<string>;\n  }> = {},\n): readonly RelationColumn[] {\n  return Object.entries(fields).map(([outputName, expression]) => {\n    const base = {\n      outputName,\n      valueType: expression.valueType,\n      ...(expression.elementValueType === undefined ?\n        {}\n      : { elementValueType: expression.elementValueType }),\n      ...(expression.elementFields === undefined ?\n        {}\n      : { elementFields: expression.elementFields }),\n      nullable: expression.nullable,\n    };\n    if (\n      expression.node.kind !== \"field\" ||\n      expression.node.field.path.length !== 1\n    )\n      return base;\n    const field = expression.node.field;\n    if (field.alias === \"relation\") {\n      const identity = options.sourceColumns?.find(\n        (column) => column.outputName === field.path[0],\n      )?.identity;\n      return identity === undefined ? base : { ...base, identity };\n    }\n    if (\n      options.nodeAliases?.has(field.alias) === true &&\n      (field.path[0] === \"id\" || field.path[0] === \"kind\")\n    )\n      return {\n        ...base,\n        identity: { alias: field.alias, component: field.path[0] },\n      };\n    return base;\n  });\n}\n\nfunction assertCompatibleProvenance(\n  left: RelationProvenance,\n  right: RelationProvenance,\n): void {\n  if (\n    left.graphId !== right.graphId ||\n    left.executionTarget !== right.executionTarget ||\n    left.recordedAsOf !== right.recordedAsOf ||\n    left.checked !== right.checked ||\n    left.temporalCoordinate !== right.temporalCoordinate\n  ) {\n    throw new ConfigurationError(\n      \"Relations can compose only when graph, execution target, temporal coordinate, and checked-read state match.\",\n    );\n  }\n}\n\nfunction relationQueries(relation: RelationAst): readonly QueryAst[] {\n  switch (relation.kind) {\n    case \"source\": {\n      return [relation.query];\n    }\n    case \"set\": {\n      return [\n        ...relationQueries(relation.left),\n        ...relationQueries(relation.right),\n      ];\n    }\n    case \"derived\": {\n      return relationQueries(relation.source);\n    }\n    case \"topPerPartition\": {\n      return relationQueries(relation.source);\n    }\n  }\n}\n\nfunction relationHasTopPerPartition(relation: RelationAst): boolean {\n  switch (relation.kind) {\n    case \"source\": {\n      return false;\n    }\n    case \"derived\": {\n      return relationHasTopPerPartition(relation.source);\n    }\n    case \"set\": {\n      return (\n        relationHasTopPerPartition(relation.left) ||\n        relationHasTopPerPartition(relation.right)\n      );\n    }\n    case \"topPerPartition\": {\n      return true;\n    }\n  }\n}\n\nfunction relationExpressions(\n  relation: RelationAst,\n): readonly DatabaseExpression[] {\n  switch (relation.kind) {\n    case \"source\": {\n      return [];\n    }\n    case \"set\": {\n      return [\n        ...relationExpressions(relation.left),\n        ...relationExpressions(relation.right),\n      ];\n    }\n    case \"derived\": {\n      return [\n        ...relationExpressions(relation.source),\n        ...relation.projection.map(({ expression }) => expression),\n        ...(relation.predicate === undefined ? [] : [relation.predicate]),\n        ...(relation.groupBy ?? []),\n        ...relation.orderBy.map(({ expression }) => expression),\n      ];\n    }\n    case \"topPerPartition\": {\n      return [\n        ...relationExpressions(relation.source),\n        ...relation.partitionBy,\n        ...relation.orderBy.map(({ expression }) => expression),\n      ];\n    }\n  }\n}\n\nfunction bindRelation(\n  relation: RelationAst,\n  bindings: Readonly<Record<string, unknown>>,\n): RelationAst {\n  switch (relation.kind) {\n    case \"source\": {\n      return {\n        ...relation,\n        query: bindQueryParametersSubset(relation.query, bindings),\n      };\n    }\n    case \"set\": {\n      return {\n        ...relation,\n        left: bindRelation(relation.left, bindings),\n        right: bindRelation(relation.right, bindings),\n      };\n    }\n    case \"derived\": {\n      return {\n        ...relation,\n        source: bindRelation(relation.source, bindings),\n        projection: relation.projection.map(({ column, expression }) => ({\n          column,\n          expression: substituteDatabaseExpression(expression, bindings),\n        })),\n        ...(relation.predicate === undefined ?\n          {}\n        : {\n            predicate: substituteDatabaseExpression(\n              relation.predicate,\n              bindings,\n            ),\n          }),\n        ...(relation.groupBy === undefined ?\n          {}\n        : {\n            groupBy: relation.groupBy.map((expression) =>\n              substituteDatabaseExpression(expression, bindings),\n            ),\n          }),\n        orderBy: relation.orderBy.map((order) => ({\n          ...order,\n          expression: substituteDatabaseExpression(order.expression, bindings),\n        })),\n      };\n    }\n    case \"topPerPartition\": {\n      return {\n        ...relation,\n        source: bindRelation(relation.source, bindings),\n        partitionBy: relation.partitionBy.map((expression) =>\n          substituteDatabaseExpression(expression, bindings),\n        ),\n        orderBy: relation.orderBy.map((order) => ({\n          ...order,\n          expression: substituteDatabaseExpression(order.expression, bindings),\n        })),\n      };\n    }\n  }\n}\n\nfunction bindState(\n  state: RelationState,\n  bindings: Readonly<Record<string, unknown>>,\n): RelationState {\n  return {\n    ...state,\n    ...(state.predicate === undefined ?\n      {}\n    : { predicate: substituteDatabaseExpression(state.predicate, bindings) }),\n    ...(state.groupBy === undefined ?\n      {}\n    : {\n        groupBy: state.groupBy.map((expression) =>\n          substituteDatabaseExpression(expression, bindings),\n        ),\n      }),\n    orderBy: state.orderBy.map((order) => ({\n      ...order,\n      expression: substituteDatabaseExpression(order.expression, bindings),\n    })),\n  };\n}\n\n/** Rewrites every source to emit its live read instant as a reusable placeholder. */\nfunction withPlaceholderReadInstants(relation: RelationAst): RelationAst {\n  switch (relation.kind) {\n    case \"source\": {\n      return {\n        ...relation,\n        options: { ...relation.options, readInstant: \"placeholder\" },\n      };\n    }\n    case \"set\": {\n      return {\n        ...relation,\n        left: withPlaceholderReadInstants(relation.left),\n        right: withPlaceholderReadInstants(relation.right),\n      };\n    }\n    case \"derived\": {\n      return {\n        ...relation,\n        source: withPlaceholderReadInstants(relation.source),\n      };\n    }\n    case \"topPerPartition\": {\n      return {\n        ...relation,\n        source: withPlaceholderReadInstants(relation.source),\n      };\n    }\n  }\n}\n\n/** Whether a relation contains a live source whose valid-time instant must remain fresh. */\nfunction relationNeedsCurrentReadInstant(relation: RelationAst): boolean {\n  return relationQueries(relation).some(\n    (query) =>\n      query.temporalMode.mode === \"current\" && query.recordedAsOf === undefined,\n  );\n}\n\nfunction assertPortableDistinctColumns(\n  columns: readonly RelationColumn[],\n  operation: string,\n): void {\n  const unsupported = columns.find(\n    (column) => !isPortableCountDistinctValueType(column.valueType),\n  );\n  if (unsupported !== undefined)\n    throw new ConfigurationError(\n      `${operation} requires portable scalar projected columns; \"${unsupported.outputName}\" has type ${unsupported.valueType}.`,\n    );\n}\n\nfunction assertPartitionScalarKey(\n  value: unknown,\n  scopeIdentity: symbol,\n  role: \"partition\" | \"ordering\",\n): asserts value is DatabaseExpression {\n  if (!isDatabaseExpression(value))\n    throw new ConfigurationError(\n      `topPerPartition() requires expression ${role} keys.`,\n    );\n  assertExpressionScope(value, scopeIdentity);\n  if (\n    !isPortableCountDistinctValueType(value.valueType) ||\n    value.elementValueType !== undefined\n  )\n    throw new ConfigurationError(\n      `topPerPartition() requires scalar ${role} keys.`,\n    );\n}\n\nfunction mergedSetColumns(\n  left: readonly RelationColumn[],\n  right: readonly RelationColumn[],\n): readonly RelationColumn[] {\n  const leftAliases = new Set(\n    left.flatMap((column) =>\n      column.identity === undefined ? [] : [column.identity.alias],\n    ),\n  );\n  const rightAliases = new Set(\n    right.flatMap((column) =>\n      column.identity === undefined ? [] : [column.identity.alias],\n    ),\n  );\n  const preservesIdentity =\n    leftAliases.size === 1 &&\n    rightAliases.size === 1 &&\n    left.every(\n      (column, index) =>\n        column.identity?.component === right[index]?.identity?.component,\n    );\n  if (preservesIdentity) return left;\n  return left.map(({ identity: _identity, ...column }) => column);\n}\n\nexport class ExecutableRelationQuery<\n  Fields extends RelationProjection,\n  Result = RelationProjectionResult<Fields>,\n> {\n  readonly #definition: RelationDefinition<Fields, Result>;\n  readonly #scopeIdentity: symbol;\n  readonly #state: RelationState;\n  readonly #context: RelationColumnContext<Fields>;\n  #template: CompiledTemplate | undefined | typeof NOT_COMPUTED = NOT_COMPUTED;\n  readonly #scalarTemplates = new Map<\n    \"count\" | \"exists\",\n    CompiledTemplate | undefined\n  >();\n\n  constructor(\n    definition: RelationDefinition<Fields, Result>,\n    state: RelationState = EMPTY_STATE,\n    scopeIdentity = relationScope(),\n  ) {\n    this.#definition = definition;\n    this.#state = state;\n    this.#scopeIdentity = scopeIdentity;\n    this.#context = buildContext<Fields>(definition.columns, scopeIdentity);\n  }\n\n  #copy(state: RelationState): ExecutableRelationQuery<Fields, Result> {\n    return new ExecutableRelationQuery(\n      this.#definition,\n      state,\n      this.#scopeIdentity,\n    );\n  }\n\n  #materialize(): RelationAst {\n    const projection = [\n      ...this.#definition.columns.map((column) => ({\n        column,\n        expression: this.#context[column.outputName as keyof Fields],\n      })),\n      ...this.#state.orderBy.map((order, index) => ({\n        column: {\n          outputName: `__tg_relation_order_${index}`,\n          valueType: order.expression.valueType,\n          nullable: order.expression.nullable,\n        },\n        expression: order.expression,\n      })),\n    ];\n    return {\n      kind: \"derived\",\n      source: this.#definition.ast,\n      sourceColumns: this.#definition.columns,\n      projection,\n      distinct: this.#state.distinct,\n      orderBy: this.#state.orderBy,\n      ...(this.#state.predicate === undefined ?\n        {}\n      : { predicate: this.#state.predicate }),\n      ...(this.#state.groupBy === undefined ?\n        {}\n      : { groupBy: this.#state.groupBy }),\n      ...(this.#state.limit === undefined ? {} : { limit: this.#state.limit }),\n      ...(this.#state.offset === undefined ?\n        {}\n      : { offset: this.#state.offset }),\n    };\n  }\n\n  /** Captures completed SQL stages for composition without exposing execution provenance. */\n  #materializedDefinition(): RelationDefinition<Fields, Result> {\n    return { ...this.#definition, ast: this.#materialize() };\n  }\n\n  where(\n    build: (\n      columns: RelationColumnContext<Fields>,\n    ) => DatabaseExpression<boolean | undefined>,\n  ): ExecutableRelationQuery<Fields, Result> {\n    const predicate = build(this.#context);\n    assertExpressionScope(predicate, this.#scopeIdentity);\n    if (predicate.valueType !== \"boolean\")\n      throw new ConfigurationError(\n        \"Relation filters require a Boolean expression.\",\n      );\n    const combined =\n      this.#state.predicate === undefined ?\n        predicate\n      : expr.and(this.#state.predicate, predicate);\n    return this.#copy({ ...this.#state, predicate: combined });\n  }\n\n  groupBy(\n    build: (\n      columns: RelationColumnContext<Fields>,\n    ) => readonly DatabaseExpression[],\n  ): ExecutableRelationQuery<Fields, Result> {\n    const groupBy = build(this.#context);\n    if (groupBy.length === 0)\n      throw new ConfigurationError(\n        \"groupBy() requires at least one expression.\",\n      );\n    for (const expression of groupBy)\n      assertExpressionScope(expression, this.#scopeIdentity);\n    return this.#copy({\n      ...this.#state,\n      groupBy: [...(this.#state.groupBy ?? []), ...groupBy],\n    });\n  }\n\n  project<const NextFields extends RelationProjection>(\n    build: (columns: RelationColumnContext<Fields>) => NextFields,\n  ): ExecutableRelationQuery<NextFields> {\n    return this.#project(build(this.#context));\n  }\n\n  aggregate<const NextFields extends RelationProjection>(\n    build: (columns: RelationColumnContext<Fields>) => NextFields,\n  ): ExecutableRelationQuery<NextFields> {\n    return this.#project(build(this.#context));\n  }\n\n  #project<NextFields extends RelationProjection>(\n    fields: NextFields,\n  ): ExecutableRelationQuery<NextFields> {\n    if (this.#definition.mapped === true)\n      throw new ConfigurationError(\n        \"A post-execution mapped relation cannot be projected or aggregated again.\",\n      );\n    const entries = Object.entries(fields);\n    if (entries.length === 0)\n      throw new ConfigurationError(\n        \"A relation projection requires at least one expression.\",\n      );\n    for (const [, expression] of entries)\n      assertExpressionScope(expression, this.#scopeIdentity);\n    // Grouping belongs to the new projection; all other modifiers describe its input rows.\n    const { groupBy: grouping, ...inputState } = this.#state;\n    const source = this.#copy(inputState).#materialize();\n    const columns = relationColumns(fields, {\n      sourceColumns: this.#definition.columns,\n    });\n    const ast: RelationAst = {\n      kind: \"derived\",\n      source,\n      sourceColumns: this.#definition.columns,\n      projection: columns.map((column, index) => {\n        const expression = entries[index]?.[1];\n        if (expression === undefined)\n          throw new ConfigurationError(\n            \"Relation projection metadata is incomplete.\",\n          );\n        return { column, expression };\n      }),\n      distinct: false,\n      orderBy: [],\n      ...(grouping === undefined ? {} : { groupBy: grouping }),\n    };\n    return createExecutableRelation({\n      ast,\n      columns,\n      fields,\n      config: this.#definition.config,\n      provenance: this.#definition.provenance,\n      decodeRow: (row) =>\n        Object.fromEntries(\n          entries.map(([outputName, expression]) => [\n            outputName,\n            decodeExpressionValue(row[outputName], expression),\n          ]),\n        ) as RelationProjectionResult<NextFields>,\n    });\n  }\n\n  orderBy(\n    build: (columns: RelationColumnContext<Fields>) => DatabaseExpression,\n    direction: SortDirection = \"asc\",\n    nulls: \"first\" | \"last\" = direction === \"asc\" ? \"last\" : \"first\",\n  ): ExecutableRelationQuery<Fields, Result> {\n    validateSortDirection(direction);\n    const expression = build(this.#context);\n    assertExpressionScope(expression, this.#scopeIdentity);\n    return this.#copy({\n      ...this.#state,\n      orderBy: [...this.#state.orderBy, { expression, direction, nulls }],\n    });\n  }\n\n  /**\n   * Selects up to N rows per partition after applying current input modifiers.\n   * Later filters remove winners without replacement. Add ordering after this stage\n   * to control result order. Requires backend window-function support.\n   * @public\n   */\n  topPerPartition(\n    options: TopPerPartitionOptions<Fields>,\n  ): ExecutableRelationQuery<Fields, Result> {\n    const runtimeOptions: unknown = options;\n    if (\n      runtimeOptions === undefined ||\n      runtimeOptions === null ||\n      typeof runtimeOptions !== \"object\" ||\n      Object.keys(options).some(\n        (key) => key !== \"partitionBy\" && key !== \"orderBy\" && key !== \"limit\",\n      ) ||\n      typeof options.partitionBy !== \"function\" ||\n      typeof options.orderBy !== \"function\"\n    )\n      throw new ConfigurationError(\n        \"topPerPartition() requires partitionBy, orderBy, and limit options only.\",\n      );\n    if (!Number.isSafeInteger(options.limit) || options.limit <= 0)\n      throw new ConfigurationError(\n        \"topPerPartition() limit must be a positive safe integer.\",\n      );\n    if (this.#definition.mapped === true || this.#state.groupBy !== undefined)\n      throw new ConfigurationError(\n        \"topPerPartition() cannot rank a post-execution mapped relation or pending groupBy().\",\n      );\n    const partitionBy = options.partitionBy(this.#context);\n    const requestedOrders = options.orderBy(this.#context);\n    if (\n      !Array.isArray(partitionBy) ||\n      partitionBy.length === 0 ||\n      !Array.isArray(requestedOrders) ||\n      requestedOrders.length === 0\n    )\n      throw new ConfigurationError(\n        \"topPerPartition() requires nonempty partition and ordering keys.\",\n      );\n    for (const expression of partitionBy) {\n      assertPartitionScalarKey(expression, this.#scopeIdentity, \"partition\");\n    }\n    const orderBy = requestedOrders.map((order) => {\n      const runtimeOrder: unknown = order;\n      if (\n        runtimeOrder === undefined ||\n        runtimeOrder === null ||\n        typeof runtimeOrder !== \"object\" ||\n        Object.keys(order).some(\n          (key) =>\n            key !== \"expression\" && key !== \"direction\" && key !== \"nulls\",\n        )\n      )\n        throw new ConfigurationError(\n          \"topPerPartition() has an invalid ordering option.\",\n        );\n      const { expression, direction = \"asc\", nulls } = order;\n      assertPartitionScalarKey(expression, this.#scopeIdentity, \"ordering\");\n      validateSortDirection(direction);\n      const runtimeNulls: unknown = nulls;\n      if (\n        runtimeNulls !== undefined &&\n        runtimeNulls !== \"first\" &&\n        runtimeNulls !== \"last\"\n      )\n        throw new ConfigurationError(\n          \"topPerPartition() has invalid null placement.\",\n        );\n      const nullPlacement = resolveNullOrdering({ direction, nulls });\n      return { expression, direction, nulls: nullPlacement };\n    });\n    const source = this.#materialize();\n    const ast: TopPerPartitionRelation = {\n      kind: \"topPerPartition\",\n      source,\n      columns: this.#definition.columns,\n      partitionBy: [...partitionBy],\n      orderBy,\n      limit: options.limit,\n    };\n    return createExecutableRelation({\n      ...this.#definition,\n      ast,\n    });\n  }\n\n  distinct(): ExecutableRelationQuery<Fields, Result> {\n    assertPortableDistinctColumns(this.#definition.columns, \"distinct()\");\n    const outputNames = new Set(\n      this.#definition.columns.map((column) => column.outputName),\n    );\n    if (\n      this.#state.orderBy.some(\n        (order) =>\n          order.expression.node.kind !== \"field\" ||\n          order.expression.node.field.alias !== \"relation\" ||\n          order.expression.node.field.path.length !== 1 ||\n          !outputNames.has(order.expression.node.field.path[0] ?? \"\"),\n      )\n    )\n      throw new ConfigurationError(\n        \"distinct() cannot preserve ordering by a graph expression that is absent from the explicit projection.\",\n      );\n    return this.#copy({ ...this.#state, distinct: true });\n  }\n\n  distinctNodes(\n    input: Readonly<{ kind: keyof Fields & string; id: keyof Fields & string }>,\n  ): ExecutableRelationQuery<Fields, Result> {\n    const { columns } = this.#definition;\n    const kind = columns.find((column) => column.outputName === input.kind);\n    const id = columns.find((column) => column.outputName === input.id);\n    const valid =\n      columns.length === 2 &&\n      kind?.identity?.component === \"kind\" &&\n      id?.identity?.component === \"id\" &&\n      kind.identity.alias === id.identity.alias &&\n      !kind.nullable &&\n      !id.nullable &&\n      kind.valueType === \"string\" &&\n      id.valueType === \"string\";\n    if (!valid)\n      throw new ConfigurationError(\n        \"distinctNodes() requires an identity-only projection of non-null kind and id fields from the same node alias.\",\n      );\n    return this.distinct();\n  }\n\n  limit(value: number): ExecutableRelationQuery<Fields, Result> {\n    validateQueryRange(value, \"limit\");\n    return this.#copy({ ...this.#state, limit: value });\n  }\n\n  offset(value: number): ExecutableRelationQuery<Fields, Result> {\n    validateQueryRange(value, \"offset\");\n    return this.#copy({ ...this.#state, offset: value });\n  }\n\n  map<Mapped>(\n    mapper: (row: Result) => Mapped,\n  ): ExecutableRelationQuery<Fields, Mapped> {\n    return new ExecutableRelationQuery(\n      {\n        ...this.#definition,\n        decodeRow: (row) => mapper(this.#definition.decodeRow(row)),\n        mapped: true,\n      },\n      this.#state,\n      this.#scopeIdentity,\n    );\n  }\n\n  union<Other extends CompatibleRelationProjection<Fields>>(\n    other: ExecutableRelationQuery<Other>,\n  ) {\n    return this.#set(\"union\", other);\n  }\n  unionAll<Other extends CompatibleRelationProjection<Fields>>(\n    other: ExecutableRelationQuery<Other>,\n  ) {\n    return this.#set(\"unionAll\", other);\n  }\n  intersect<Other extends CompatibleRelationProjection<Fields>>(\n    other: ExecutableRelationQuery<Other>,\n  ) {\n    return this.#set(\"intersect\", other);\n  }\n  except<Other extends CompatibleRelationProjection<Fields>>(\n    other: ExecutableRelationQuery<Other>,\n  ) {\n    return this.#set(\"except\", other);\n  }\n\n  #set<Other extends CompatibleRelationProjection<Fields>>(\n    operator: \"union\" | \"unionAll\" | \"intersect\" | \"except\",\n    other: ExecutableRelationQuery<Other>,\n  ): ExecutableRelationQuery<Fields, Result> {\n    const right = other.#materializedDefinition();\n    assertCompatibleRelationColumns(this.#definition.columns, right.columns);\n    assertCompatibleProvenance(this.#definition.provenance, right.provenance);\n    if (this.#definition.mapped === true || right.mapped === true)\n      throw new ConfigurationError(\n        \"Set operations cannot combine post-execution mapped relations.\",\n      );\n    if (operator !== \"unionAll\")\n      assertPortableDistinctColumns(this.#definition.columns, `${operator}()`);\n    const columns = mergedSetColumns(this.#definition.columns, right.columns);\n    return createExecutableRelation({\n      ...this.#definition,\n      columns,\n      ast: {\n        kind: \"set\",\n        operator,\n        left: this.#materialize(),\n        right: right.ast,\n        columns,\n      },\n    });\n  }\n\n  compile() {\n    return this.#compileForBackend(\n      this.#definition.config.backend,\n      this.#materialize(),\n    );\n  }\n\n  #compileForBackend(\n    backend: GraphBackend | TransactionBackend | undefined,\n    relation: RelationAst,\n  ) {\n    this.#assertWindowFunctionsSupported(backend, relation);\n    this.#assertRelationBound(relation);\n    return compileRelation(relation, getDialect(this.#dialect()));\n  }\n\n  toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n    return renderQuerySql(this.#requireBackend(), () => this.compile());\n  }\n\n  prepare(): Readonly<{\n    execute: (\n      bindings: Readonly<Record<string, unknown>>,\n    ) => Promise<readonly Result[]>;\n    bind: (\n      bindings: Readonly<Record<string, unknown>>,\n    ) => ExecutableRelationQuery<Fields, Result>;\n  }>;\n  prepare<const Parameters extends PreparedParameterDeclaration>(\n    parameters: Parameters,\n  ): Readonly<{\n    execute: (\n      bindings: PreparedBindings<Parameters>,\n    ) => Promise<readonly Result[]>;\n    bind: (\n      bindings: PreparedBindings<Parameters>,\n    ) => ExecutableRelationQuery<Fields, Result>;\n  }>;\n  prepare(parameters?: PreparedParameterDeclaration) {\n    const definition = this.#materializedDefinition();\n    const queries = relationQueries(definition.ast);\n    const expressions = relationExpressions(definition.ast);\n    if (parameters !== undefined)\n      validatePreparedBindingsDeclaration(parameters, queries, expressions);\n    const bind = (bindings: Readonly<Record<string, unknown>>) => {\n      validateQueryBindings(queries, bindings, expressions);\n      return new ExecutableRelationQuery(\n        {\n          ...this.#definition,\n          ast: bindRelation(this.#definition.ast, bindings),\n        },\n        bindState(this.#state, bindings),\n        this.#scopeIdentity,\n      );\n    };\n    return {\n      bind,\n      execute: async (bindings: Readonly<Record<string, unknown>>) => {\n        validateQueryBindings(queries, bindings, expressions);\n        const rows = await this.#fetchRows(\n          this.#requireBackend(),\n          definition.ast,\n          bindings,\n        );\n        return rows.map((row) => definition.decodeRow(row));\n      },\n    };\n  }\n\n  execute(): Promise<readonly Result[]> {\n    return this.executeOn(this.#requireBackend());\n  }\n\n  async executeOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly Result[]> {\n    if (this.#definition.provenance.checked)\n      throw new ConfigurationError(\n        \"Derived relations are unavailable inside withCheckedReads().\",\n      );\n    if (\n      backendDerivationRoot(backend) !==\n      this.#definition.provenance.executionTarget\n    )\n      throw new ConfigurationError(\n        \"A relation cannot execute on a different database or transaction target.\",\n      );\n    const rows = await this.#fetchRows(backend, this.#materialize());\n    return rows.map((row) => this.#definition.decodeRow(row));\n  }\n\n  async first(): Promise<Result | undefined> {\n    const rows = await this.limit(\n      Math.min(this.#state.limit ?? 1, 1),\n    ).execute();\n    return rows[0];\n  }\n  async count(): Promise<number> {\n    return this.#scalar(\"count\");\n  }\n  async exists(): Promise<boolean> {\n    return (await this.#scalar(\"exists\")) > 0;\n  }\n\n  async page(\n    options: Readonly<{ limit: number; offset?: number }>,\n  ): Promise<readonly Result[]> {\n    validateQueryRange(options.limit, \"limit\");\n    if (options.limit === 0)\n      throw new ConfigurationError(\n        \"Relation page limit must be greater than zero.\",\n      );\n    const relativeOffset = options.offset ?? 0;\n    validateQueryRange(relativeOffset, \"offset\");\n    this.#assertDeterministicPageShape();\n    const existingOffset = this.#state.offset ?? 0;\n    const combinedOffset = existingOffset + relativeOffset;\n    validateQueryRange(combinedOffset, \"offset\");\n    const remaining =\n      this.#state.limit === undefined ?\n        undefined\n      : Math.max(this.#state.limit - relativeOffset, 0);\n    const limit =\n      remaining === undefined ?\n        options.limit\n      : Math.min(options.limit, remaining);\n    if (limit === 0) return [];\n    return this.#copy({\n      ...this.#state,\n      limit,\n      offset: combinedOffset,\n    }).execute();\n  }\n\n  async *stream(\n    options: Readonly<{ pageSize?: number }> = {},\n  ): AsyncIterable<Result> {\n    const pageSize = options.pageSize ?? 100;\n    validateQueryRange(pageSize, \"limit\");\n    if (pageSize === 0)\n      throw new ConfigurationError(\n        \"Relation stream page size must be greater than zero.\",\n      );\n    this.#assertDeterministicPageShape();\n    const totalLimit = this.#state.limit;\n    for (\n      let offset = 0;\n      totalLimit === undefined || offset < totalLimit;\n      offset += pageSize\n    ) {\n      const rows = await this.page({ limit: pageSize, offset });\n      for (const row of rows) yield row;\n      if (\n        rows.length <\n        Math.min(\n          pageSize,\n          totalLimit === undefined ? pageSize : totalLimit - offset,\n        )\n      )\n        return;\n    }\n  }\n\n  #assertDeterministicPageShape(): void {\n    if (!this.#state.distinct)\n      throw new ConfigurationError(\n        \"Relation paging and streaming require distinct() over the whole projection.\",\n      );\n    assertPortableDistinctColumns(\n      this.#definition.columns,\n      \"Relation paging and streaming\",\n    );\n    const orderedNames = this.#state.orderBy.map((order) =>\n      (\n        order.expression.node.kind === \"field\" &&\n        order.expression.node.field.alias === \"relation\" &&\n        order.expression.node.field.path.length === 1\n      ) ?\n        order.expression.node.field.path[0]\n      : undefined,\n    );\n    const expected = this.#definition.columns.map(\n      (column) => column.outputName,\n    );\n    if (\n      orderedNames.length !== expected.length ||\n      new Set(orderedNames).size !== expected.length ||\n      expected.some((name) => !orderedNames.includes(name))\n    )\n      throw new ConfigurationError(\n        \"Relation paging and streaming require direct ordering by every projected column exactly once.\",\n      );\n  }\n\n  async #scalar(operation: \"count\" | \"exists\"): Promise<number> {\n    if (this.#definition.provenance.checked)\n      throw new ConfigurationError(\n        \"Derived relation terminals are unavailable inside withCheckedReads().\",\n      );\n    const backend = this.#requireBackend();\n    const relation = this.#materialize();\n    this.#assertWindowFunctionsSupported(backend, relation);\n    this.#assertRelationBound(relation);\n    const executeRaw = backend.executeRaw;\n    const template =\n      executeRaw === undefined ? undefined : (\n        this.#resolveScalarTemplate(relation, operation)\n      );\n    const operationPromise =\n      template !== undefined && executeRaw !== undefined ?\n        executeRaw<Record<string, unknown>>(\n          template.sql,\n          fillTemplateParams(template.params, {}, this.#dialect()),\n        )\n      : backend.execute<Record<string, unknown>>(\n          this.#compileScalar(relation, operation),\n        );\n    const rows =\n      this.#definition.provenance.recordedAsOf === undefined ?\n        await operationPromise\n      : await withRecordedRelationsPrecondition(operationPromise, {\n          dialect: backend.dialect,\n          surface: \"recorded-relation-terminal\",\n        });\n    return Number(rows[0]?.[\"__tg_scalar\"] ?? 0);\n  }\n\n  #compileScalar(\n    relation: RelationAst,\n    operation: \"count\" | \"exists\",\n    placeholderReadInstant = false,\n  ) {\n    const compiledRelation = compileRelation(\n      placeholderReadInstant ? withPlaceholderReadInstants(relation) : relation,\n      getDialect(this.#dialect()),\n    );\n    return asCompiledSelectSql(\n      operation === \"count\" ?\n        sql`SELECT COUNT(*) AS __tg_scalar FROM (${compiledRelation}) AS typegraph_relation_count`\n      : sql`SELECT CASE WHEN EXISTS (${compiledRelation}) THEN 1 ELSE 0 END AS __tg_scalar`,\n    );\n  }\n\n  #resolveScalarTemplate(\n    relation: RelationAst,\n    operation: \"count\" | \"exists\",\n  ): CompiledTemplate | undefined {\n    if (this.#scalarTemplates.has(operation))\n      return this.#scalarTemplates.get(operation);\n    const template = buildReadInstantTemplate({\n      compile: () => this.#compileScalar(relation, operation, true),\n      backend: this.#definition.config.backend,\n      needsReadInstant: relationNeedsCurrentReadInstant(relation),\n    });\n    this.#scalarTemplates.set(operation, template);\n    return template;\n  }\n\n  compileOneStatementBatchItem() {\n    if (this.#definition.provenance.checked)\n      throw new ConfigurationError(\n        \"Checked relations cannot be embedded in batchOnce().\",\n      );\n    if (this.#definition.provenance.recordedAsOf !== undefined)\n      throw new ConfigurationError(\n        \"Recorded relations cannot be embedded in batchOnce().\",\n      );\n    const backend = this.#requireBackend();\n    return {\n      query: this.compile(),\n      provenance: {\n        graphId: this.#definition.provenance.graphId,\n        executionTarget: backendDerivationRoot(backend),\n      },\n      outputNames: this.#definition.columns.map((column) => column.outputName),\n      orderBy: this.#state.orderBy.map((order, index) => ({\n        column: `__tg_relation_order_${index}`,\n        direction: order.direction,\n        nulls: order.nulls,\n      })),\n      mapRows: (rows: readonly Record<string, unknown>[]) =>\n        rows.map((row) => this.#definition.decodeRow(row)),\n    };\n  }\n\n  #requireBackend(): GraphBackend | TransactionBackend {\n    if (this.#definition.config.backend === undefined)\n      throw new ConfigurationError(\n        \"Relation execution requires a backend; use store.query().\",\n      );\n    return this.#definition.config.backend;\n  }\n\n  #dialect(): \"sqlite\" | \"postgres\" {\n    return this.#definition.config.dialect ?? \"sqlite\";\n  }\n\n  /** Resolves the per-instance placeholder template for this immutable relation. */\n  #resolveTemplate(relation: RelationAst): CompiledTemplate | undefined {\n    if (this.#template !== NOT_COMPUTED) return this.#template;\n    this.#template = buildReadInstantTemplate({\n      compile: () =>\n        compileRelation(\n          withPlaceholderReadInstants(relation),\n          getDialect(this.#dialect()),\n        ),\n      backend: this.#definition.config.backend,\n      needsReadInstant: relationNeedsCurrentReadInstant(relation),\n    });\n    return this.#template;\n  }\n\n  /**\n   * Executes either the cached raw template or a freshly compiled concrete\n   * relation. Binding substitution is deliberately confined to the fallback:\n   * the raw path retains user placeholders so one prepared relation serves\n   * every binding set and receives a fresh current-time instant per call.\n   */\n  async #fetchRows(\n    backend: GraphBackend | TransactionBackend,\n    relation: RelationAst,\n    bindings?: Readonly<Record<string, unknown>>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    this.#assertWindowFunctionsSupported(backend, relation);\n    const metadata = collectParameterMetadata(\n      relationQueries(relation),\n      relationExpressions(relation),\n    );\n    if (bindings === undefined) this.#assertRelationBound(relation, metadata);\n\n    const executeRaw = backend.executeRaw;\n    const template =\n      executeRaw === undefined ? undefined : this.#resolveTemplate(relation);\n    const operation =\n      template !== undefined && executeRaw !== undefined ?\n        executeRaw<Record<string, unknown>>(\n          template.sql,\n          fillTemplateParams(\n            template.params,\n            bindings ?? {},\n            this.#dialect(),\n            metadata.listParameters,\n          ),\n        )\n      : backend.execute<Record<string, unknown>>(\n          compileRelation(\n            bindings === undefined ? relation : (\n              bindRelation(relation, bindings)\n            ),\n            getDialect(this.#dialect()),\n          ),\n        );\n    return this.#definition.provenance.recordedAsOf === undefined ?\n        operation\n      : withRecordedRelationsPrecondition(operation, {\n          dialect: backend.dialect,\n          surface: \"recorded-relation\",\n        });\n  }\n\n  #assertRelationBound(\n    relation: RelationAst,\n    metadata = collectParameterMetadata(\n      relationQueries(relation),\n      relationExpressions(relation),\n    ),\n  ): void {\n    if (metadata.names.size === 0) return;\n    throw new ConfigurationError(\n      \"Relation contains unbound parameters; use prepare().execute(bindings).\",\n    );\n  }\n\n  #assertWindowFunctionsSupported(\n    backend: GraphBackend | TransactionBackend | undefined = this.#definition\n      .config.backend,\n    relation = this.#materialize(),\n  ): void {\n    if (\n      backend?.capabilities.windowFunctions === false &&\n      relationHasTopPerPartition(relation)\n    )\n      throw new UnsupportedBackendCapabilityError(\n        \"topPerPartition()\",\n        \"windowFunctions\",\n      );\n  }\n}\n\nexport type CompatibleRelationProjection<Fields extends RelationProjection> =\n  Readonly<{\n    [Key in keyof Fields]: DatabaseExpression<\n      RelationProjectionResult<Fields>[Key]\n    >;\n  }>;\n\nexport function createExecutableRelation<\n  Fields extends RelationProjection,\n  Result,\n>(\n  definition: RelationDefinition<Fields, Result>,\n): ExecutableRelationQuery<Fields, Result> {\n  return new ExecutableRelationQuery(definition);\n}\n\nexport function createProjectionRelation<\n  Fields extends RelationProjection,\n  Result,\n>(\n  input: Readonly<{\n    config: QueryBuilderConfig;\n    ast: QueryAst;\n    fields: Fields;\n    decodeRow: (row: Record<string, unknown>) => Result;\n    checked: boolean;\n    mapped?: boolean;\n  }>,\n): ExecutableRelationQuery<Fields, Result> {\n  const nodeAliases = new Set([\n    input.ast.start.alias,\n    ...input.ast.traversals.map((traversal) => traversal.nodeAlias),\n  ]);\n  const columns = relationColumns(input.fields, { nodeAliases });\n  const ordering = input.ast.orderBy ?? [];\n  const orderOutputNames = ordering.map(\n    (order) =>\n      input.ast.projection.fields.find(\n        (projected) =>\n          projected.source === order.field ||\n          (projected.source.__type === \"database_expression\" &&\n            order.field.__type === \"database_expression\" &&\n            projected.source.node.kind === \"field\" &&\n            order.field.node.kind === \"field\" &&\n            projected.source.node.field.alias ===\n              order.field.node.field.alias &&\n            projected.source.node.field.path.join(\"\\u0000\") ===\n              order.field.node.field.path.join(\"\\u0000\") &&\n            projected.source.node.field.jsonPointer ===\n              order.field.node.field.jsonPointer),\n      )?.outputName,\n  );\n  const {\n    limit: sourceLimit,\n    offset: sourceOffset,\n    orderBy: _sourceOrderBy,\n    ...unboundedSourceAst\n  } = input.ast;\n  const sourceAst: QueryAst = {\n    ...unboundedSourceAst,\n    projection: {\n      ...input.ast.projection,\n      fields: [\n        ...input.ast.projection.fields,\n        ...ordering.flatMap((order, index) =>\n          orderOutputNames[index] === undefined ?\n            [\n              {\n                outputName: `__tg_relation_source_order_${index}`,\n                source: order.field,\n              },\n            ]\n          : [],\n        ),\n      ],\n    },\n  };\n  const definition: RelationDefinition<Fields, Result> = {\n    ast: {\n      kind: \"source\",\n      query: sourceAst,\n      graphId: input.config.graphId,\n      options: buildCompileOptions(input.config),\n    },\n    columns,\n    fields: input.fields,\n    config: input.config,\n    provenance: {\n      graphId: input.config.graphId,\n      executionTarget:\n        input.config.backend === undefined ?\n          undefined\n        : backendDerivationRoot(input.config.backend),\n      recordedAsOf: input.ast.recordedAsOf,\n      checked: input.checked,\n      temporalCoordinate: JSON.stringify(input.ast.temporalMode),\n    },\n    decodeRow: input.decodeRow,\n    ...(input.mapped === undefined ? {} : { mapped: input.mapped }),\n  };\n  const scopeIdentity = relationScope();\n  const state: RelationState = {\n    distinct: false,\n    ...(sourceLimit === undefined ? {} : { limit: sourceLimit }),\n    ...(sourceOffset === undefined ? {} : { offset: sourceOffset }),\n    orderBy: ordering.map((order, index) => ({\n      expression: createFieldExpression(\n        outputField(\n          orderOutputNames[index] ?? `__tg_relation_source_order_${index}`,\n          order.field.valueType ?? \"unknown\",\n        ),\n        scopeIdentity,\n        true,\n      ),\n      direction: order.direction,\n      nulls: resolveNullOrdering(order),\n    })),\n  };\n  return new ExecutableRelationQuery(definition, state, scopeIdentity);\n}\n","import { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport type { QueryAst, SortDirection, ValueType } from \"../ast\";\nimport { compileQuery } from \"../compiler\";\nimport { executeSchemaCheckedRead } from \"../execution/schema-checked-read\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport { compileOrderTerm, resolveNullOrdering } from \"../order\";\nimport { sql } from \"../sql-fragment\";\nimport { asCompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { assertExpressionScope, getExpressionScope } from \"./expression-scope\";\nimport type { ExpressionProjectionEntries } from \"./expression-subqueries\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport {\n  bindQueryParameters,\n  collectParameterMetadata,\n  hasParameterReferences,\n  validateQueryBindings,\n} from \"./prepared-query\";\nimport {\n  buildQueryTemplate,\n  buildReadInstantTemplate,\n  type CompiledTemplate,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n  createProjectionRelation,\n  type ExecutableRelationQuery,\n} from \"./relation\";\nimport { renderQuerySql } from \"./render-query-sql\";\nimport type { QueryBuilderConfig, QueryBuilderState } from \"./types\";\nimport { validateQueryRange, validateSortDirection } from \"./validation\";\n\nexport type DatabaseProjection = Readonly<Record<string, DatabaseExpression>>;\nexport type ProjectionResult<Fields extends DatabaseProjection> = {\n  -readonly [Key in keyof Fields]: Fields[Key] extends (\n    DatabaseExpression<infer Value>\n  ) ?\n    Value\n  : never;\n};\n\n/** Sentinel distinguishing a template that was not built from one that cannot be built. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\n/** Explicit SQL results: construction never executes a JavaScript row selector. */\nexport class ExecutableProjectionQuery<\n  Fields extends DatabaseProjection,\n  Context,\n  Result = ProjectionResult<Fields>,\n> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: QueryBuilderState;\n  readonly #fields: Fields;\n  readonly #context: () => Context;\n  readonly #mapper: ((row: ProjectionResult<Fields>) => Result) | undefined;\n  #rowsTemplate: CompiledTemplate | undefined | typeof NOT_COMPUTED =\n    NOT_COMPUTED;\n  readonly #scalarTemplates = new Map<\n    \"count\" | \"exists\",\n    CompiledTemplate | undefined\n  >();\n\n  constructor(\n    config: QueryBuilderConfig,\n    state: QueryBuilderState,\n    fields: Fields,\n    context: () => Context,\n    mapper?: (row: ProjectionResult<Fields>) => Result,\n  ) {\n    this.#config = config;\n    this.#state = state;\n    this.#fields = fields;\n    this.#context = context;\n    this.#mapper = mapper;\n  }\n\n  #copy(\n    state: QueryBuilderState,\n  ): ExecutableProjectionQuery<Fields, Context, Result> {\n    return new ExecutableProjectionQuery(\n      this.#config,\n      state,\n      this.#fields,\n      this.#context,\n      this.#mapper,\n    );\n  }\n\n  limit(value: number): ExecutableProjectionQuery<Fields, Context, Result> {\n    validateQueryRange(value, \"limit\");\n    return this.#copy({ ...this.#state, limit: value });\n  }\n\n  offset(value: number): ExecutableProjectionQuery<Fields, Context, Result> {\n    validateQueryRange(value, \"offset\");\n    return this.#copy({ ...this.#state, offset: value });\n  }\n\n  orderBy(\n    build: (context: Context) => DatabaseExpression,\n    direction: SortDirection = \"asc\",\n  ): ExecutableProjectionQuery<Fields, Context, Result> {\n    validateSortDirection(direction);\n    const expression = build(this.#context());\n    assertExpressionScope(expression, this.getExpressionScopeIdentity());\n    return this.#copy({\n      ...this.#state,\n      orderBy: [...this.#state.orderBy, { field: expression, direction }],\n    });\n  }\n\n  map<Mapped>(\n    mapper: (row: Result) => Mapped,\n  ): ExecutableProjectionQuery<Fields, Context, Mapped> {\n    return new ExecutableProjectionQuery(\n      this.#config,\n      this.#state,\n      this.#fields,\n      this.#context,\n      (row) => mapper(this.#mapRow(row)),\n    );\n  }\n\n  toAst(): QueryAst {\n    return buildQueryAst(this.#config, this.#state);\n  }\n  getExpressionScopeIdentity(): symbol {\n    return getExpressionScope(this.#config);\n  }\n  getOneStatementReadProvenance() {\n    return {\n      graphId: this.#config.graphId,\n      executionTarget:\n        this.#config.backend === undefined ?\n          undefined\n        : backendDerivationRoot(this.#config.backend),\n    };\n  }\n  getExpressionProjection(): ExpressionProjectionEntries<Fields> {\n    if (this.#mapper !== undefined)\n      throw new ConfigurationError(\n        \"Subqueries consume SQL projections; apply map() after the enclosing query executes.\",\n      );\n    return Object.entries(this.#fields).map(([outputName, expression]) => ({\n      outputName,\n      expression,\n    })) as unknown as ExpressionProjectionEntries<Fields>;\n  }\n\n  /** Enters the shared relational composition surface for derived queries and set operations. */\n  asRelation(): ExecutableRelationQuery<Fields, Result> {\n    return createProjectionRelation({\n      config: this.#config,\n      ast: this.toAst(),\n      fields: this.#fields,\n      checked:\n        getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n        undefined,\n      mapped: this.#mapper !== undefined,\n      decodeRow: (row) => this.#decodeRow(row),\n    });\n  }\n\n  compile() {\n    return compileQuery(\n      this.toAst(),\n      this.#config.graphId,\n      buildCompileOptions(this.#config),\n    );\n  }\n  toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n    return renderQuerySql(this.#requireBackend(), () => this.compile());\n  }\n\n  execute(): Promise<readonly Result[]> {\n    return this.executeOn(this.#requireBackend());\n  }\n  /** Runs on an explicitly supplied target, including store.batch() transactions. */\n  async executeOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly Result[]> {\n    const rows = await this.#fetchRows(backend, this.toAst());\n    return rows.map((row) => this.#decodeRow(row));\n  }\n  async first(): Promise<Result | undefined> {\n    const rows = await this.limit(\n      Math.min(this.#state.limit ?? 1, 1),\n    ).execute();\n    return rows[0];\n  }\n  count(): Promise<number> {\n    return this.#scalarTerminal(\"count\");\n  }\n  async exists(): Promise<boolean> {\n    return (await this.#scalarTerminal(\"exists\")) > 0;\n  }\n\n  prepare(): Readonly<{\n    execute: (\n      bindings: Readonly<Record<string, unknown>>,\n    ) => Promise<readonly Result[]>;\n  }> {\n    const ast = this.toAst();\n    const backend = this.#requireBackend();\n    return {\n      execute: async (bindings) => {\n        validateQueryBindings([ast], bindings);\n        const rows = await this.#fetchRows(backend, ast, bindings);\n        return rows.map((row) => this.#decodeRow(row));\n      },\n    };\n  }\n\n  compileOneStatementBatchItem() {\n    const backend = this.#requireBackend();\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n      undefined\n    )\n      throw new ConfigurationError(\n        \"Checked projections cannot be embedded in batchOnce().\",\n      );\n    if (this.#state.recordedAsOf !== undefined)\n      throw new ConfigurationError(\n        \"Recorded projections cannot be embedded in batchOnce().\",\n      );\n    const ast = this.toAst();\n    this.#assertBound(ast);\n    const { ast: envelope, orderBy } = buildProjectionEnvelope(ast);\n    return {\n      query: compileQuery(\n        envelope,\n        this.#config.graphId,\n        buildCompileOptions(this.#config),\n      ),\n      provenance: {\n        graphId: this.#config.graphId,\n        executionTarget: backendDerivationRoot(backend),\n      },\n      outputNames: envelope.projection.fields.map((field) => field.outputName),\n      orderBy,\n      mapRows: (rows: readonly Record<string, unknown>[]) =>\n        rows.map((row) => this.#decodeRow(row)),\n    };\n  }\n\n  #requireBackend(): GraphBackend | TransactionBackend {\n    if (this.#config.backend === undefined)\n      throw new ConfigurationError(\n        \"Projection execution requires a backend; use store.query().\",\n      );\n    return this.#config.backend;\n  }\n  #assertBound(ast: QueryAst): void {\n    if (hasParameterReferences(ast))\n      throw new ConfigurationError(\n        \"Projection contains unbound parameters; use prepare().execute(bindings).\",\n      );\n  }\n  #recorded<T>(\n    operation: Promise<T>,\n    backend = this.#requireBackend(),\n  ): Promise<T> {\n    return this.#state.recordedAsOf === undefined ?\n        operation\n      : withRecordedRelationsPrecondition(operation, {\n          dialect: backend.dialect,\n          surface: \"recorded-projection\",\n        });\n  }\n  #fetchRows(\n    backend: GraphBackend | TransactionBackend,\n    ast: QueryAst,\n    bindings?: Readonly<Record<string, unknown>>,\n  ): Promise<readonly Record<string, unknown>[]> {\n    if (bindings === undefined) this.#assertBound(ast);\n    const checked = getQueryBuilderInternalContext(\n      this.#config,\n    ).expectedSchemaVersion;\n    if (checked === undefined) {\n      const executeRaw = backend.executeRaw;\n      const template =\n        executeRaw === undefined ? undefined : this.#resolveRowsTemplate(ast);\n      return this.#recorded(\n        template !== undefined && executeRaw !== undefined ?\n          executeRaw<Record<string, unknown>>(\n            template.sql,\n            fillTemplateParams(\n              template.params,\n              bindings ?? {},\n              this.#config.dialect ?? \"sqlite\",\n              collectParameterMetadata(ast).listParameters,\n            ),\n          )\n        : backend.execute<Record<string, unknown>>(\n            compileQuery(\n              bindings === undefined ? ast : bindQueryParameters(ast, bindings),\n              this.#config.graphId,\n              buildCompileOptions(this.#config),\n            ),\n          ),\n        backend,\n      );\n    }\n    const concreteAst =\n      bindings === undefined ? ast : bindQueryParameters(ast, bindings);\n    const compiled = compileQuery(\n      concreteAst,\n      this.#config.graphId,\n      buildCompileOptions(this.#config),\n    );\n    const { ast: envelope, orderBy } = buildProjectionEnvelope(concreteAst);\n    const ordered =\n      orderBy.length === 0 ?\n        compiled\n      : compileQuery(\n          envelope,\n          this.#config.graphId,\n          buildCompileOptions(this.#config),\n        );\n    const resultOrderBy =\n      orderBy.length === 0 ?\n        sql.empty()\n      : sql`ORDER BY ${sql.join(\n          orderBy.map((order) =>\n            compileOrderTerm(\n              sql`${sql.identifier(\"checked_rows\")}.${sql.identifier(order.column)}`,\n              order.direction,\n              order.nulls,\n            ),\n          ),\n          sql`, `,\n        )}`;\n    return this.#recorded(\n      executeSchemaCheckedRead({\n        backend,\n        ast: concreteAst,\n        graphId: this.#config.graphId,\n        expectedVersion: checked.value,\n        resultOrderBy,\n        rowIdentityColumn: \"__tg_projection_row\",\n        compile: () =>\n          asCompiledSelectSql(\n            sql`SELECT projected.*, 1 AS __tg_projection_row FROM (${ordered}) AS projected`,\n          ),\n      }),\n      backend,\n    );\n  }\n  /**\n   * Builds at most one reusable template for this immutable projection shape.\n   * The template belongs to the configured backend compiler, while execution\n   * may use a transaction derived from it; the fresh read instant is filled\n   * only when the supplied backend can execute raw SQL text.\n   */\n  #resolveRowsTemplate(ast: QueryAst): CompiledTemplate | undefined {\n    if (this.#rowsTemplate !== NOT_COMPUTED) return this.#rowsTemplate;\n    this.#rowsTemplate = buildQueryTemplate(\n      ast,\n      this.#config.graphId,\n      buildCompileOptions(this.#config),\n      this.#config.backend,\n    );\n    return this.#rowsTemplate;\n  }\n  async #scalarTerminal(operation: \"count\" | \"exists\"): Promise<number> {\n    const ast = this.toAst();\n    this.#assertBound(ast);\n    const backend = this.#requireBackend();\n    const checked = getQueryBuilderInternalContext(\n      this.#config,\n    ).expectedSchemaVersion;\n    const { orderBy: _orderBy, ...unordered } = ast;\n    const executeRaw = checked === undefined ? backend.executeRaw : undefined;\n    const template =\n      executeRaw === undefined ? undefined : (\n        this.#resolveScalarTemplate(ast, operation)\n      );\n    const rows = await this.#recorded(\n      checked === undefined ?\n        template !== undefined && executeRaw !== undefined ?\n          executeRaw<Record<string, unknown>>(\n            template.sql,\n            fillTemplateParams(\n              template.params,\n              {},\n              this.#config.dialect ?? \"sqlite\",\n            ),\n          )\n        : backend.execute<Record<string, unknown>>(\n            this.#compileScalar(ast, operation),\n          )\n      : executeSchemaCheckedRead({\n          backend,\n          ast: unordered,\n          graphId: this.#config.graphId,\n          expectedVersion: checked.value,\n          rowIdentityColumn: \"__tg_scalar\",\n          compile: () => this.#compileScalar(ast, operation),\n        }),\n    );\n    return Number(rows[0]?.[\"__tg_scalar\"] ?? 0);\n  }\n  #compileScalar(\n    ast: QueryAst,\n    operation: \"count\" | \"exists\",\n    readInstant: \"literal\" | \"placeholder\" = \"literal\",\n  ) {\n    const relation = compileQuery(ast, this.#config.graphId, {\n      ...buildCompileOptions(this.#config),\n      readInstant,\n    });\n    return asCompiledSelectSql(\n      operation === \"count\" ?\n        sql`SELECT COUNT(*) AS __tg_scalar FROM (${relation}) AS projected`\n      : sql`SELECT CASE WHEN EXISTS (${relation}) THEN 1 ELSE 0 END AS __tg_scalar`,\n    );\n  }\n  #resolveScalarTemplate(\n    ast: QueryAst,\n    operation: \"count\" | \"exists\",\n  ): CompiledTemplate | undefined {\n    if (this.#scalarTemplates.has(operation))\n      return this.#scalarTemplates.get(operation);\n    const template = buildReadInstantTemplate({\n      compile: () => this.#compileScalar(ast, operation, \"placeholder\"),\n      backend: this.#config.backend,\n      needsReadInstant:\n        ast.temporalMode.mode === \"current\" && ast.recordedAsOf === undefined,\n    });\n    this.#scalarTemplates.set(operation, template);\n    return template;\n  }\n  #decodeRow(row: Record<string, unknown>): Result {\n    const decoded = Object.fromEntries(\n      Object.entries(this.#fields).map(([key, expression]) => [\n        key,\n        decodeExpressionValue(row[key], expression),\n      ]),\n    ) as ProjectionResult<Fields>;\n    return this.#mapRow(decoded);\n  }\n  #mapRow(row: ProjectionResult<Fields>): Result {\n    return this.#mapper === undefined ?\n        (row as unknown as Result)\n      : this.#mapper(row);\n  }\n}\n\nexport function decodeExpressionValue(\n  value: unknown,\n  expression: DatabaseExpression,\n): unknown {\n  if (value === null || value === undefined) return undefined;\n  switch (expression.valueType) {\n    case \"boolean\":\n    case \"date\":\n    case \"number\":\n    case \"string\": {\n      return decodeScalarExpressionValue(value, expression.valueType);\n    }\n    case \"object\":\n    case \"embedding\": {\n      return typeof value === \"string\" ? (JSON.parse(value) as unknown) : value;\n    }\n    case \"array\": {\n      const parsed =\n        typeof value === \"string\" ? (JSON.parse(value) as unknown) : value;\n      if (!Array.isArray(parsed) || expression.elementValueType === undefined)\n        return parsed;\n      const elementValueType = expression.elementValueType;\n      const elementFields = expression.elementFields;\n      return parsed.map((element) => {\n        if (element === null || element === undefined) return;\n        return elementFields === undefined ?\n            decodeScalarExpressionValue(element, elementValueType)\n          : decodeRecordExpressionValue(element, elementFields);\n      });\n    }\n    case \"unknown\": {\n      return value;\n    }\n  }\n}\n\n/** Decode only the explicitly projected scalar fields, preserving records whose fields are all null. */\nfunction decodeRecordExpressionValue(\n  value: unknown,\n  fields: Readonly<Record<string, ValueType>>,\n): Readonly<Record<string, unknown>> {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value))\n    throw new ConfigurationError(\n      \"Expected a JSON object in a record collection.\",\n    );\n  const record = value as Readonly<Record<string, unknown>>;\n  return Object.fromEntries(\n    Object.entries(fields).map(([key, valueType]) => {\n      const field = record[key];\n      return [\n        key,\n        field === null || field === undefined ?\n          undefined\n        : decodeScalarExpressionValue(field, valueType),\n      ];\n    }),\n  );\n}\n\nfunction decodeScalarExpressionValue(\n  value: unknown,\n  valueType: ValueType,\n): unknown {\n  switch (valueType) {\n    case \"boolean\": {\n      return value === true || value === 1 || value === \"true\" || value === \"1\";\n    }\n    case \"number\": {\n      return Number(value);\n    }\n    case \"date\": {\n      return (\n        value instanceof Date ? value\n        : typeof value === \"string\" || typeof value === \"number\" ?\n          new Date(value)\n        : value\n      );\n    }\n    case \"string\": {\n      return value;\n    }\n    case \"array\":\n    case \"embedding\":\n    case \"object\":\n    case \"unknown\": {\n      return value;\n    }\n  }\n}\n\n/** Carries sort values through SQL envelopes without exposing them in decoded results. */\nfunction buildProjectionEnvelope(ast: QueryAst) {\n  const ordering = ast.orderBy ?? [];\n  const orderBy = ordering.map((order, index) => ({\n    column: `__tg_order_${index}`,\n    direction: order.direction,\n    nulls: resolveNullOrdering(order),\n  }));\n  return {\n    ast: {\n      ...ast,\n      projection: {\n        ...ast.projection,\n        fields: [\n          ...ast.projection.fields,\n          ...ordering.map((order, index) => ({\n            outputName: `__tg_order_${index}`,\n            source: order.field,\n          })),\n        ],\n      },\n    },\n    orderBy,\n  };\n}\n","/**\n * ExecutableAggregateQuery - A query with aggregate functions that can be executed.\n */\nimport { type z } from \"zod\";\n\nimport { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport type { GraphBackend, TransactionBackend } from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport { createDataKeyedBag } from \"../../utils/object\";\nimport {\n  type AggregateExpr,\n  type AggregateOrderSpec,\n  type FieldRef,\n  mergeEdgeKinds,\n  type QueryAst,\n  type SortDirection,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport type { DatabaseExpression } from \"../expressions\";\nimport { parseJsonPointer } from \"../json-pointer\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport type {\n  PreparedBindings,\n  PreparedParameterDeclaration,\n} from \"./prepared-bindings\";\nimport { hasParameterReferences } from \"./prepared-query\";\nimport {\n  buildQueryTemplate,\n  type CompiledTemplate,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n  createExecutableRelation,\n  type ExecutableRelationQuery,\n} from \"./relation\";\nimport { type QueryBuilderConfig, type QueryBuilderState } from \"./types\";\nimport { validateQueryRange, validateSortDirection } from \"./validation\";\n\n/** Sentinel distinguishing \"template not yet built\" from a built `undefined`. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\nexport type AggregateAliasMap = Readonly<\n  Record<\n    string,\n    Readonly<{\n      type: Readonly<{ schema: z.ZodType }>;\n      optional: boolean;\n    }>\n  >\n>;\n\ntype AliasValue<Aliases extends AggregateAliasMap, Alias extends string> =\n  Alias extends keyof Aliases ? Aliases[Alias] : never;\n\ntype AliasSchemaValue<\n  Aliases extends AggregateAliasMap,\n  Alias extends string,\n> = z.infer<AliasValue<Aliases, Alias>[\"type\"][\"schema\"]>;\n\ntype WithAliasOptionality<\n  Value,\n  Aliases extends AggregateAliasMap,\n  Alias extends string,\n> =\n  AliasValue<Aliases, Alias>[\"optional\"] extends true ? Value | undefined\n  : Value;\n\ntype PropertyValue<Value, Path extends readonly string[]> =\n  Path extends readonly [] ? Value\n  : Path extends (\n    readonly [\n      infer Head extends PropertyKey,\n      ...infer Tail extends readonly string[],\n    ]\n  ) ?\n    Head extends keyof Value ?\n      PropertyValue<Value[Head], Tail>\n    : unknown\n  : unknown;\n\ntype FieldResult<Field extends FieldRef, Aliases extends AggregateAliasMap> =\n  Field extends (\n    FieldRef<infer Declared, infer Alias, readonly string[], infer PropsPath>\n  ) ?\n    unknown extends Declared ?\n      PropsPath extends readonly [\"id\"] ? string\n      : PropsPath extends readonly [\"kind\"] ?\n        AliasValue<Aliases, Alias>[\"type\"] extends (\n          Readonly<{\n            kind: infer Kind;\n          }>\n        ) ?\n          Kind\n        : string\n      : WithAliasOptionality<\n          PropertyValue<AliasSchemaValue<Aliases, Alias>, PropsPath>,\n          Aliases,\n          Alias\n        >\n    : Declared\n  : never;\n\ntype AggregateFieldResult<\n  Expression extends AggregateExpr,\n  Aliases extends AggregateAliasMap,\n> =\n  Expression extends AggregateExpr<infer Function, infer Field> ?\n    Function extends \"count\" | \"countDistinct\" ? number\n    : Function extends \"sum\" | \"avg\" ? number | undefined\n    : Function extends \"min\" | \"max\" ?\n      unknown extends FieldResult<Field, Aliases> ? unknown\n      : Exclude<FieldResult<Field, Aliases>, undefined> extends (\n        string | number | Date\n      ) ?\n        Extract<FieldResult<Field, Aliases>, string | number | Date> | undefined\n      : never\n    : never\n  : never;\n\n/** Result type for aggregate queries, including SQL empty-set nullability. */\nexport type AggregateResult<\n  R extends Record<string, FieldRef | AggregateExpr>,\n  Aliases extends AggregateAliasMap = AggregateAliasMap,\n> = {\n  [K in keyof R]: R[K] extends AggregateExpr ?\n    AggregateFieldResult<R[K], Aliases>\n  : R[K] extends FieldRef ? FieldResult<R[K], Aliases>\n  : never;\n};\n\nexport type AggregateRelationFields<\n  R extends Record<string, FieldRef | AggregateExpr>,\n  Aliases extends AggregateAliasMap,\n> = { [K in keyof R]: DatabaseExpression<AggregateResult<R, Aliases>[K]> };\n\n/**\n * An aggregate query that can be executed.\n */\nexport class ExecutableAggregateQuery<\n  G extends GraphDef,\n  Aliases extends AggregateAliasMap,\n  R extends Record<string, FieldRef | AggregateExpr>,\n> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: QueryBuilderState;\n  readonly #fields: R;\n  // Per-instance compiled placeholder template, reused across execute() calls\n  // (see #resolveTemplate). NOT_COMPUTED = not yet built; undefined = no fast\n  // path.\n  #template: CompiledTemplate | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n\n  constructor(config: QueryBuilderConfig, state: QueryBuilderState, fields: R) {\n    this.#config = config;\n    this.#state = state;\n    this.#fields = fields;\n  }\n\n  /**\n   * Builds the query AST.\n   */\n  toAst(): QueryAst {\n    return buildQueryAst(this.#config, this.#state);\n  }\n\n  /**\n   * Orders results by a grouped field or aggregate alias.\n   *\n   * `key` is one of the output names passed to `.aggregate({...})` — either\n   * a grouped field (e.g. `genre`) or an aggregate alias (e.g. `bookCount`).\n   * Both are ordered the same way: by referencing the SELECT-list output\n   * column, since every `.aggregate()` field is projected with an alias.\n   *\n   * Chain multiple calls to sort by more than one key, in call order:\n   * `.orderBy(\"genre\").orderBy(\"bookCount\", \"desc\")` sorts by genre first,\n   * then by book count within each genre.\n   *\n   * @example\n   * ```typescript\n   * // Top 2 authors by book count\n   * store.query()\n   *   .from(\"Author\", \"a\")\n   *   .traverse(\"wrote\", \"e\")\n   *   .to(\"Book\", \"b\")\n   *   .groupByNode(\"a\")\n   *   .aggregate({ author: field(\"a\", \"name\"), bookCount: count(\"b\") })\n   *   .orderBy(\"bookCount\", \"desc\")\n   *   .limit(2)\n   *   .execute();\n   * ```\n   */\n  orderBy<K extends keyof R & string>(\n    key: K,\n    direction: SortDirection = \"asc\",\n  ): ExecutableAggregateQuery<G, Aliases, R> {\n    validateSortDirection(direction);\n    if (!Object.hasOwn(this.#fields, key))\n      throw new ConfigurationError(\n        `Aggregate orderBy() output \"${key}\" is not projected by this query.`,\n        { operation: \"aggregate.orderBy\", outputName: key },\n      );\n    const orderSpec: AggregateOrderSpec = { outputName: key, direction };\n    return new ExecutableAggregateQuery(\n      this.#config,\n      {\n        ...this.#state,\n        aggregateOrderBy: [...this.#state.aggregateOrderBy, orderSpec],\n      },\n      this.#fields,\n    );\n  }\n\n  /**\n   * Limits the number of results.\n   */\n  limit(n: number): ExecutableAggregateQuery<G, Aliases, R> {\n    validateQueryRange(n, \"limit\");\n    return new ExecutableAggregateQuery(\n      this.#config,\n      { ...this.#state, limit: n },\n      this.#fields,\n    );\n  }\n\n  /**\n   * Offsets the results.\n   */\n  offset(n: number): ExecutableAggregateQuery<G, Aliases, R> {\n    validateQueryRange(n, \"offset\");\n    return new ExecutableAggregateQuery(\n      this.#config,\n      { ...this.#state, offset: n },\n      this.#fields,\n    );\n  }\n\n  /**\n   * Compiles the query and returns the SQL text and parameters.\n   *\n   * Requires a backend to be configured (the backend determines the SQL dialect).\n   * Use this for debugging, logging, or running the query with a custom executor.\n   */\n  toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n    if (!this.#config.backend?.compileSql) {\n      throw new Error(\n        \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n          \"Use store.query() to get a backend-aware query builder.\",\n      );\n    }\n    return this.#config.backend.compileSql(this.compile());\n  }\n\n  /**\n   * Compiles the query to TypeGraph's database-independent SQL fragment.\n   */\n  compile(): CompiledSelectSql {\n    // Emits a directly-runnable statement with the read instant as a literal;\n    // this is not the reusable placeholder template execute() caches (see\n    // #resolveTemplate).\n    const ast = this.toAst();\n    return compileQuery(ast, this.#config.graphId, this.#compileOptions());\n  }\n\n  /** Adapts this compatibility aggregate builder to the shared relation API. */\n  asRelation(): ExecutableRelationQuery<\n    AggregateRelationFields<R, Aliases>,\n    AggregateResult<R, Aliases>\n  > {\n    const ast = this.toAst();\n    const { aggregateOrderBy, limit, offset, ...unorderedUnboundedAst } = ast;\n    const internalContext = getQueryBuilderInternalContext(this.#config);\n    const columns = Object.entries(this.#fields).map(\n      ([outputName, expression]) => ({\n        outputName,\n        valueType:\n          (\n            expression.__type === \"aggregate\" &&\n            (expression.function === \"count\" ||\n              expression.function === \"countDistinct\" ||\n              expression.function === \"sum\" ||\n              expression.function === \"avg\")\n          ) ?\n            (\"number\" as const)\n          : ((expression.__type === \"aggregate\" ?\n              expression.field.valueType\n            : expression.valueType) ?? \"unknown\"),\n        nullable: this.#aggregateOutputNullable(expression),\n      }),\n    );\n\n    let relation = createExecutableRelation<\n      AggregateRelationFields<R, Aliases>,\n      AggregateResult<R, Aliases>\n    >({\n      ast: {\n        kind: \"source\",\n        query: unorderedUnboundedAst,\n        graphId: this.#config.graphId,\n        options: this.#compileOptions(),\n      },\n      columns,\n      fields: {} as AggregateRelationFields<R, Aliases>,\n      config: this.#config,\n      provenance: {\n        graphId: this.#config.graphId,\n        executionTarget:\n          this.#config.backend === undefined ?\n            undefined\n          : backendDerivationRoot(this.#config.backend),\n        recordedAsOf: ast.recordedAsOf,\n        checked: internalContext.expectedSchemaVersion !== undefined,\n        temporalCoordinate: JSON.stringify(ast.temporalMode),\n      },\n      decodeRow: (row) => this.#mapRow(row),\n    });\n    for (const order of aggregateOrderBy ?? [])\n      relation = relation.orderBy(\n        (columns) => columns[order.outputName as keyof R],\n        order.direction,\n      );\n    if (limit !== undefined) relation = relation.limit(limit);\n    if (offset !== undefined) relation = relation.offset(offset);\n    return relation;\n  }\n\n  /** Runs on a target with the same database and transaction provenance. */\n  executeOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly AggregateResult<R, Aliases>[]> {\n    return this.asRelation().executeOn(backend);\n  }\n\n  first(): Promise<AggregateResult<R, Aliases> | undefined> {\n    return this.asRelation().first();\n  }\n\n  count(): Promise<number> {\n    return this.asRelation().count();\n  }\n\n  exists(): Promise<boolean> {\n    return this.asRelation().exists();\n  }\n\n  prepare(): Readonly<{\n    execute: (\n      bindings: Readonly<Record<string, unknown>>,\n    ) => Promise<readonly AggregateResult<R, Aliases>[]>;\n    bind: (\n      bindings: Readonly<Record<string, unknown>>,\n    ) => ExecutableRelationQuery<\n      AggregateRelationFields<R, Aliases>,\n      AggregateResult<R, Aliases>\n    >;\n  }>;\n  prepare<const Parameters extends PreparedParameterDeclaration>(\n    parameters: Parameters,\n  ): Readonly<{\n    execute: (\n      bindings: PreparedBindings<Parameters>,\n    ) => Promise<readonly AggregateResult<R, Aliases>[]>;\n    bind: (\n      bindings: PreparedBindings<Parameters>,\n    ) => ExecutableRelationQuery<\n      AggregateRelationFields<R, Aliases>,\n      AggregateResult<R, Aliases>\n    >;\n  }>;\n  prepare(parameters?: PreparedParameterDeclaration) {\n    const relation = this.asRelation();\n    return parameters === undefined ?\n        relation.prepare()\n      : relation.prepare(parameters);\n  }\n\n  /** @internal Embedding contract consumed by `store.batchOnce()`. */\n  compileOneStatementBatchItem() {\n    return this.asRelation().compileOneStatementBatchItem();\n  }\n\n  #aggregateOutputNullable(expression: FieldRef | AggregateExpr): boolean {\n    if (expression.__type === \"aggregate\")\n      return (\n        expression.function !== \"count\" &&\n        expression.function !== \"countDistinct\"\n      );\n\n    const traversal = this.#state.traversals.find(\n      (candidate) =>\n        candidate.nodeAlias === expression.alias ||\n        candidate.edgeAlias === expression.alias,\n    );\n    const aliasIsOptional = traversal?.optional ?? false;\n    if (expression.path[0] !== \"props\" || expression.jsonPointer === undefined)\n      return aliasIsOptional;\n\n    const segments = parseJsonPointer(expression.jsonPointer);\n    const [fieldName, ...nestedPath] = segments;\n    if (fieldName === undefined) return aliasIsOptional;\n    const kindNames =\n      traversal === undefined ? this.#state.startKinds\n      : traversal.edgeAlias === expression.alias ? mergeEdgeKinds(traversal)\n      : traversal.nodeKinds;\n    let typeInfo =\n      traversal?.edgeAlias === expression.alias ?\n        this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n          kindNames,\n          fieldName,\n        )\n      : this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n          kindNames,\n          fieldName,\n        );\n    let nullable = aliasIsOptional || (typeInfo?.nullable ?? true);\n    for (const segment of nestedPath) {\n      typeInfo = typeInfo?.shape?.[segment];\n      nullable ||= typeInfo?.nullable ?? true;\n    }\n    return nullable;\n  }\n\n  #compileOptions(): CompileQueryOptions {\n    return buildCompileOptions(this.#config);\n  }\n\n  /**\n   * The cached placeholder template for this aggregate query, or `undefined`\n   * when no fast path applies. Built once per instance; the read instant is\n   * filled fresh per execution by {@link fillTemplateParams}.\n   */\n  #resolveTemplate(ast: QueryAst): CompiledTemplate | undefined {\n    if (this.#template !== NOT_COMPUTED) return this.#template;\n    this.#template = buildQueryTemplate(\n      ast,\n      this.#config.graphId,\n      this.#compileOptions(),\n      this.#config.backend,\n    );\n    return this.#template;\n  }\n\n  /**\n   * Executes the query and returns typed results.\n   *\n   * @throws Error if no backend is configured\n   */\n  async execute(): Promise<readonly AggregateResult<R, Aliases>[]> {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion !==\n      undefined\n    ) {\n      throw new ConfigurationError(\n        \"Aggregate queries are unavailable inside withCheckedReads().\",\n        { operation: \"withCheckedReads.aggregate\" },\n      );\n    }\n    const backend = this.#config.backend;\n    if (!backend) {\n      throw new Error(\n        \"Cannot execute query: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n\n    const ast = this.toAst();\n    // Aggregate queries expose no `.prepare()`, so a param() ref can never be\n    // bound — reject it with clear guidance instead of a downstream \"missing\n    // binding\" error once it reaches the template's placeholder fill.\n    if (hasParameterReferences(ast)) {\n      throw new Error(\n        \"Aggregate queries do not support param() references; bind a concrete value instead.\",\n      );\n    }\n\n    const executeRaw = backend.executeRaw;\n    const template =\n      executeRaw === undefined ? undefined : this.#resolveTemplate(ast);\n    const rows =\n      template !== undefined && executeRaw !== undefined ?\n        await executeRaw<Record<string, unknown>>(\n          template.sql,\n          fillTemplateParams(\n            template.params,\n            {},\n            this.#config.dialect ?? \"sqlite\",\n          ),\n        )\n      : await backend.execute<Record<string, unknown>>(\n          compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n        );\n\n    return this.#mapResults(rows);\n  }\n\n  /**\n   * Maps raw database rows to typed results.\n   * Handles database-specific value conversions:\n   * - PostgreSQL returns bigint/numeric as strings → convert to numbers\n   * - SQLite returns JSON booleans as 0/1 numbers → convert to booleans\n   * - PostgreSQL returns JSON booleans as \"true\"/\"false\" strings → convert to booleans\n   */\n  #mapResults(\n    rows: readonly Record<string, unknown>[],\n  ): readonly AggregateResult<R, Aliases>[] {\n    return rows.map((row) => this.#mapRow(row));\n  }\n\n  #mapRow(row: Record<string, unknown>): AggregateResult<R, Aliases> {\n    // Data-keyed: the caller's aggregate/group aliases. An alias may be\n    // `__proto__` (it is a caller-supplied string), and `result[key] = value`\n    // on a `{}` literal would hand that key to `Object.prototype`'s setter\n    // and drop the value.\n    const result = createDataKeyedBag<unknown>();\n    for (const key of Object.keys(this.#fields)) {\n      const field = this.#fields[key];\n      if (!field) continue;\n      const value = row[key];\n\n      if (field.__type === \"aggregate\") {\n        result[key] = normalizeAggregateValue(field, value);\n        continue;\n      }\n\n      result[key] = normalizeFieldValue(field, value);\n    }\n    // SPREAD at the boundary. The null-prototype bag is an internal write-side\n    // protection, not something a caller asked for: returned as-is, an\n    // aggregate row had no `toString`, no `hasOwnProperty`, and answered\n    // `false` to `instanceof Object` — a public behavior regression against\n    // every other row this library returns. Spread copies own properties with\n    // CreateDataProperty rather than Set, so a `__proto__` ALIAS survives as\n    // an own key while `Object.prototype` is restored; the same pattern\n    // `rowToNode` and `buildSelectableNode` already use.\n    return { ...result } as AggregateResult<R, Aliases>;\n  }\n}\n\nfunction normalizeAggregateValue(\n  expression: AggregateExpr,\n  value: unknown,\n): unknown {\n  if (value === null) return undefined;\n\n  if (\n    expression.function === \"count\" ||\n    expression.function === \"countDistinct\" ||\n    expression.function === \"sum\" ||\n    expression.function === \"avg\" ||\n    expression.field.valueType === \"number\"\n  ) {\n    // PostgreSQL returns bigint/numeric aggregates as strings.\n    return typeof value === \"string\" ? Number(value) : value;\n  }\n\n  if (expression.field.valueType === \"boolean\") {\n    return normalizeBooleanValue(value);\n  }\n\n  if (expression.field.valueType === \"date\") {\n    return normalizeDateValue(value);\n  }\n\n  return value;\n}\n\nfunction normalizeDateValue(value: unknown): unknown {\n  if (value instanceof Date) return value;\n  if (typeof value === \"string\" || typeof value === \"number\") {\n    return new Date(value);\n  }\n  return value;\n}\n\n/**\n * Converts database-specific boolean encodings to JS booleans.\n *\n * - SQLite json_extract() returns 0/1 for JSON booleans\n * - PostgreSQL #>> returns \"true\"/\"false\" for JSON booleans\n */\nfunction normalizeBooleanValue(value: unknown): unknown {\n  if (value === null) return undefined;\n  if (value === true || value === false) return value;\n  if (value === 1) return true;\n  if (value === 0) return false;\n  if (value === \"true\") return true;\n  if (value === \"false\") return false;\n  if (value === \"1\") return true;\n  if (value === \"0\") return false;\n  return value;\n}\n\nfunction normalizeFieldValue(field: FieldRef, value: unknown): unknown {\n  if (value === null) return undefined;\n\n  if (field.valueType === \"boolean\") {\n    return normalizeBooleanValue(value);\n  }\n\n  if (field.valueType === \"date\") {\n    return normalizeDateValue(value);\n  }\n\n  return value;\n}\n","import { type z } from \"zod\";\n\nimport { RuntimeKindTokenError } from \"../errors\";\nimport { type EdgeType, type KindEntity, type NodeType } from \"./types\";\n\ndeclare const RUNTIME_KIND_TOKEN_BRAND: unique symbol;\n\n/** The schema identity a runtime-kind token is licensed against. */\nexport type RuntimeKindSchemaBinding = Readonly<{\n  graphId: string;\n  schemaVersion: number | undefined;\n  schemaHash: string | undefined;\n}>;\n\n/** Store-issued evidence for one persisted runtime node kind. */\nexport type RuntimeNodeKind<\n  K extends string = string,\n  S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n  entity: \"node\";\n  kind: K;\n  [RUNTIME_KIND_TOKEN_BRAND]: S;\n}>;\n\n/** Store-issued evidence for one persisted runtime edge kind. */\nexport type RuntimeEdgeKind<\n  K extends string = string,\n  S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n  entity: \"edge\";\n  kind: K;\n  [RUNTIME_KIND_TOKEN_BRAND]: S;\n}>;\n\n/** Node type recovered from validated runtime-kind evidence. */\nexport type RuntimeNodeTypeFor<T extends RuntimeNodeKind> =\n  T extends RuntimeNodeKind<infer K, infer S> ? NodeType<K, S> : never;\n\n/** Edge type recovered from validated runtime-kind evidence. */\nexport type RuntimeEdgeTypeFor<T extends RuntimeEdgeKind> =\n  T extends RuntimeEdgeKind<infer K, infer S> ?\n    EdgeType<\n      K,\n      S,\n      readonly NodeType[] | undefined,\n      readonly NodeType[] | undefined\n    >\n  : never;\n\ntype RuntimeKindToken = RuntimeNodeKind | RuntimeEdgeKind;\n\nexport type RuntimeKindInput = string | RuntimeKindToken;\nexport type RuntimeKindTokenResolver = (\n  token: unknown,\n  entity: KindEntity,\n) => string;\n\ntype RuntimeKindTokenMetadata = Readonly<{\n  owner: object;\n  binding: RuntimeKindSchemaBinding;\n  entity: KindEntity;\n  kind: string;\n}>;\n\nconst TOKEN_METADATA = new WeakMap<object, RuntimeKindTokenMetadata>();\n\nexport function createRuntimeKindToken<\n  const K extends string,\n  S extends z.ZodObject<z.ZodRawShape>,\n>(\n  owner: object,\n  binding: RuntimeKindSchemaBinding,\n  entity: \"node\",\n  kind: K,\n): RuntimeNodeKind<K, S>;\nexport function createRuntimeKindToken<\n  const K extends string,\n  S extends z.ZodObject<z.ZodRawShape>,\n>(\n  owner: object,\n  binding: RuntimeKindSchemaBinding,\n  entity: \"edge\",\n  kind: K,\n): RuntimeEdgeKind<K, S>;\nexport function createRuntimeKindToken(\n  owner: object,\n  binding: RuntimeKindSchemaBinding,\n  entity: KindEntity,\n  kind: string,\n): RuntimeKindToken {\n  const token = Object.freeze({ entity, kind }) as RuntimeKindToken;\n  TOKEN_METADATA.set(token, { owner, binding, entity, kind });\n  return token;\n}\n\n/** Resolves Store-issued evidence after checking its owner and schema fence. */\nexport function resolveRuntimeKindToken(\n  token: unknown,\n  expectedEntity: KindEntity,\n  owner: object | undefined,\n  binding: RuntimeKindSchemaBinding | undefined,\n): string {\n  const tokenObject =\n    typeof token === \"object\" && token !== null ? token : undefined;\n  const metadata =\n    tokenObject === undefined ? undefined : TOKEN_METADATA.get(tokenObject);\n  if (tokenObject === undefined || metadata === undefined) {\n    throw new RuntimeKindTokenError(\"invalid\", expectedEntity);\n  }\n  if (metadata.entity !== expectedEntity) {\n    throw new RuntimeKindTokenError(\"wrong-entity\", expectedEntity, {\n      actualEntity: metadata.entity,\n      kind: metadata.kind,\n    });\n  }\n  if (\n    !(\"kind\" in tokenObject) ||\n    typeof tokenObject.kind !== \"string\" ||\n    tokenObject.kind !== metadata.kind\n  ) {\n    throw new RuntimeKindTokenError(\"wrong-kind\", expectedEntity, {\n      kind: metadata.kind,\n    });\n  }\n  if (owner === undefined || metadata.owner !== owner) {\n    throw new RuntimeKindTokenError(\"wrong-store\", expectedEntity, {\n      kind: metadata.kind,\n      graphId: metadata.binding.graphId,\n    });\n  }\n  const bindingMatches =\n    binding?.graphId === metadata.binding.graphId &&\n    binding.schemaVersion === metadata.binding.schemaVersion &&\n    binding.schemaHash === metadata.binding.schemaHash;\n  if (!bindingMatches) {\n    throw new RuntimeKindTokenError(\"stale\", expectedEntity, {\n      kind: metadata.kind,\n      graphId: metadata.binding.graphId,\n      tokenSchemaVersion: metadata.binding.schemaVersion,\n      currentSchemaVersion: binding?.schemaVersion,\n      tokenSchemaHash: metadata.binding.schemaHash,\n      currentSchemaHash: binding?.schemaHash,\n    });\n  }\n  return metadata.kind;\n}\n\n/** One owner for string-or-token dispatch across every dynamic API. */\nexport function resolveRuntimeKindInput(\n  input: RuntimeKindInput,\n  entity: KindEntity,\n  resolver: RuntimeKindTokenResolver | undefined,\n): string {\n  if (typeof input === \"string\") return input;\n  if (resolver === undefined) {\n    return resolveRuntimeKindToken(input, entity, undefined, undefined);\n  }\n  return resolver(input, entity);\n}\n","/**\n * Dynamic query builder types.\n *\n * Backs `fromDynamic` / `traverseDynamic` / `optionalTraverseDynamic`\n * / `toDynamic` — the string-keyed sibling methods on `QueryBuilder`\n * and `TraversalBuilder` that admit runtime-declared kinds. Same SQL\n * compiler under the hood; only the alias-level surface types differ.\n *\n * Aliases declared via the dynamic methods carry `DynamicNodeType` /\n * `DynamicEdgeType` brands. `NodeAccessor<N>` / `EdgeAccessor<E>` /\n * `SelectableNode<N>` / `SelectableEdge<E>` branch on those brands so a\n * single query can mix typed and dynamic aliases — a typed alias keeps\n * `StringFieldAccessor`, etc., while a dynamic alias gets\n * `DynamicNodeAccessor` with a `.field(name)` discriminator.\n */\nimport {\n  type AnyEdgeType,\n  type KindEntity,\n  type NodeType,\n} from \"../../core/types\";\nimport { jsonPointer } from \"../json-pointer\";\nimport {\n  buildFieldBuilderForTypeInfo,\n  fieldRef,\n  type FulltextAccessor,\n} from \"../predicates\";\nimport {\n  type FieldTypeInfo,\n  type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport {\n  type ArrayFieldAccessor,\n  type BaseFieldAccessor,\n  type DateFieldAccessor,\n  type EmbeddingFieldAccessor,\n  type NumberFieldAccessor,\n  type ObjectFieldAccessor,\n  type SelectableEdgeMeta,\n  type SelectableNodeMeta,\n  type StringFieldAccessor,\n} from \"./types\";\n\ndeclare const DYNAMIC_NODE_BRAND: unique symbol;\ndeclare const DYNAMIC_EDGE_BRAND: unique symbol;\n\n/** A runtime-registered node kind whose collection lookup preserved `K`. */\nexport type DynamicNodeKind<K extends string = string> = K &\n  Readonly<{ [DYNAMIC_NODE_BRAND]: true }>;\n\nexport type DynamicNodeType<K extends string = string> = NodeType<\n  DynamicNodeKind<K>\n> &\n  Readonly<{ [DYNAMIC_NODE_BRAND]: true }>;\n\nexport type DynamicEdgeType = AnyEdgeType &\n  Readonly<{ [DYNAMIC_EDGE_BRAND]: true }>;\n\nexport type IsDynamicNodeType<N> =\n  N extends Readonly<{ [DYNAMIC_NODE_BRAND]: true }> ? true : false;\n\nexport type IsDynamicEdgeType<E> =\n  E extends Readonly<{ [DYNAMIC_EDGE_BRAND]: true }> ? true : false;\n\n/**\n * Type-discriminated field builder for runtime-typed properties.\n *\n * `BaseFieldAccessor` methods (`eq`, `isNull`, etc.) are available\n * directly. Type-specific methods (`gte`, `contains`, `similarTo`, …)\n * sit behind a discriminator method that asserts the field's type:\n *\n * ```ts\n * (n) => n.field(\"year\").number().gte(2020)\n * ```\n *\n * The discriminator validates against the registered Zod schema at\n * query-build time and throws `TypeError` on mismatch — the user can't\n * accidentally call `.between(...)` on a string field. The discriminator\n * is a type assertion *and* a runtime check.\n */\nexport type DynamicFieldBuilder = BaseFieldAccessor &\n  Readonly<{\n    string: () => StringFieldAccessor;\n    number: () => NumberFieldAccessor;\n    date: () => DateFieldAccessor;\n    array: () => ArrayFieldAccessor<unknown>;\n    object: () => ObjectFieldAccessor<Readonly<Record<string, unknown>>>;\n    embedding: () => EmbeddingFieldAccessor;\n  }>;\n\n/**\n * Predicate accessor for a runtime-kind alias.\n *\n * System fields keep their narrow types. Schema properties are reached\n * through `.field(name)` — `.field()` validates the property exists on\n * the registered Zod schema and throws if it doesn't.\n */\nexport type DynamicNodeAccessor = Readonly<{\n  id: StringFieldAccessor;\n  kind: StringFieldAccessor;\n  $fulltext: FulltextAccessor;\n  field: (name: string) => DynamicFieldBuilder;\n}>;\n\nexport type DynamicEdgeAccessor = Readonly<{\n  id: StringFieldAccessor;\n  kind: StringFieldAccessor;\n  fromId: StringFieldAccessor;\n  toId: StringFieldAccessor;\n  field: (name: string) => DynamicFieldBuilder;\n}>;\n\nexport type DynamicSelectableNode = Readonly<{\n  id: string;\n  kind: string;\n  meta: SelectableNodeMeta;\n}> &\n  Readonly<Record<string, unknown>>;\n\nexport type DynamicSelectableEdge = Readonly<{\n  id: string;\n  kind: string;\n  fromId: string;\n  toId: string;\n  meta: SelectableEdgeMeta;\n}> &\n  Readonly<Record<string, unknown>>;\n\n/**\n * Renders a kind-context string for error messages — `node kind \"Paper\"`\n * or `edge kinds \"knows\" | \"follows\"`.\n */\nfunction describeKindContext(\n  entity: KindEntity,\n  kindNames: readonly string[] | undefined,\n): string {\n  if (kindNames === undefined || kindNames.length === 0) {\n    return `${entity} (kind unresolved)`;\n  }\n  const list = kindNames.map((k) => `\"${k}\"`).join(\" | \");\n  return `${entity} kind${kindNames.length > 1 ? \"s\" : \"\"} ${list}`;\n}\n\n/**\n * Shared dynamic-field-builder factory. Returns a `DynamicFieldBuilder`\n * (typed as `BaseFieldAccessor` at the runtime boundary): the property\n * is validated against the registered Zod schema, and each\n * `.string()` / `.number()` / … discriminator throws `TypeError` on\n * type mismatch.\n *\n * Used by `QueryBuilder.#createNodeAccessor` for node aliases and by\n * `TraversalBuilder.#createEdgeAccessor` for edge aliases — they only\n * differ in which introspector method to call.\n */\nexport function createDynamicFieldBuilder(\n  introspector: SchemaIntrospector,\n  alias: string,\n  name: string,\n  kindNames: readonly string[] | undefined,\n  entity: KindEntity,\n): BaseFieldAccessor {\n  const typeInfo =\n    kindNames === undefined ? undefined\n    : entity === \"node\" ? introspector.getSharedFieldTypeInfo(kindNames, name)\n    : introspector.getSharedEdgeFieldTypeInfo(kindNames, name);\n\n  const where = describeKindContext(entity, kindNames);\n  if (typeInfo === undefined) {\n    throw new Error(`Property \"${name}\" is not declared on ${where}.`);\n  }\n\n  const ref = fieldRef(alias, [\"props\"], {\n    jsonPointer: jsonPointer([name]),\n    valueType: typeInfo.valueType,\n    elementType: typeInfo.elementType,\n  });\n  const base = buildFieldBuilderForTypeInfo(ref, typeInfo);\n\n  const expect = (asserted: FieldTypeInfo[\"valueType\"]): BaseFieldAccessor => {\n    if (typeInfo.valueType !== asserted) {\n      throw new TypeError(\n        `Property \"${name}\" on ${where} is ${typeInfo.valueType}, not ${asserted}.`,\n      );\n    }\n    return base;\n  };\n\n  return {\n    ...base,\n    string: () => expect(\"string\"),\n    number: () => expect(\"number\"),\n    date: () => expect(\"date\"),\n    array: () => expect(\"array\"),\n    object: () => expect(\"object\"),\n    embedding: () => expect(\"embedding\"),\n  } as BaseFieldAccessor;\n}\n","import type { z } from \"zod\";\n\nimport type { GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport type { FieldRef } from \"../ast\";\nimport { createFieldExpression, type DatabaseExpression } from \"../expressions\";\nimport { jsonPointer } from \"../json-pointer\";\nimport type { FieldTypeInfo } from \"../schema-introspector\";\nimport { getExpressionScope } from \"./expression-scope\";\nimport type { ExpressionSubqueryHelpers } from \"./expression-subqueries\";\nimport type { QueryBuilder } from \"./query-builder\";\nimport type {\n  AliasMap,\n  CommonPropertyKeys,\n  EdgeAliasMap,\n  EmptyAliasMap,\n  EmptyEdgeAliasMap,\n  EmptyRecursiveAliasMap,\n  NodePropsFor,\n  QueryBuilderConfig,\n  QueryBuilderState,\n  QueryCoordinateState,\n} from \"./types\";\n\ntype UndefinedWhenNullish<Value> =\n  Extract<Value, null | undefined> extends never ? never : undefined;\ntype UndefinedWhenOptional<Optional extends boolean> =\n  Optional extends true ? undefined : never;\ntype ExpressionObjectChildren<Value, Scope extends string> = {\n  readonly [\n    Key in Exclude<\n      CommonPropertyKeys<NonNullable<Value>>,\n      keyof DatabaseExpression | \"$get\"\n    >\n  ]-?: ExpressionValue<\n    NonNullable<Value>[Key] | UndefinedWhenNullish<Value>,\n    Scope\n  >;\n} & Readonly<{\n  $get: <Key extends CommonPropertyKeys<NonNullable<Value>>>(\n    key: Key,\n  ) => ExpressionValue<\n    NonNullable<Value>[Key] | UndefinedWhenNullish<Value>,\n    Scope\n  >;\n}>;\n\nexport type ExpressionValue<Value, Scope extends string> = DatabaseExpression<\n  Exclude<Value, null> | (null extends Value ? undefined : never),\n  Scope\n> &\n  (NonNullable<Value> extends Date | readonly unknown[] ? unknown\n  : NonNullable<Value> extends object ? ExpressionObjectChildren<Value, Scope>\n  : unknown);\n\ntype ExpressionMetadata<\n  Scope extends string,\n  Optional extends boolean = false,\n> = Readonly<{\n  validFrom: DatabaseExpression<string | undefined, Scope>;\n  validTo: DatabaseExpression<string | undefined, Scope>;\n  createdAt: DatabaseExpression<\n    string | UndefinedWhenOptional<Optional>,\n    Scope\n  >;\n  updatedAt: DatabaseExpression<\n    string | UndefinedWhenOptional<Optional>,\n    Scope\n  >;\n  deletedAt: DatabaseExpression<string | undefined, Scope>;\n}>;\n\ntype AliasExpressions<\n  Entry extends Readonly<{\n    type: Readonly<{ schema: z.ZodType; kind: string }>;\n    optional: boolean;\n  }>,\n  Scope extends string,\n> = {\n  readonly [\n    Property in CommonPropertyKeys<NodePropsFor<Entry[\"type\"]>>\n  ]-?: ExpressionValue<\n    | NodePropsFor<Entry[\"type\"]>[Property]\n    | (Entry[\"optional\"] extends true ? undefined : never),\n    Scope\n  >;\n} & Readonly<{\n  id: DatabaseExpression<\n    string | (Entry[\"optional\"] extends true ? undefined : never),\n    Scope\n  >;\n  kind: DatabaseExpression<\n    | Entry[\"type\"][\"kind\"]\n    | (Entry[\"optional\"] extends true ? undefined : never),\n    Scope\n  >;\n  $meta: ExpressionMetadata<Scope, Entry[\"optional\"]>;\n}>;\n\nexport type ExpressionAliasContext<\n  Aliases extends AliasMap,\n  Edges extends EdgeAliasMap,\n  Scope extends string = (keyof Aliases | keyof Edges) & string,\n> = {\n  readonly [Alias in keyof Aliases & string]: AliasExpressions<\n    Aliases[Alias],\n    Scope\n  >;\n} & {\n  readonly [Alias in keyof Edges & string]: AliasExpressions<\n    Edges[Alias],\n    Scope\n  > &\n    Readonly<{\n      fromId: DatabaseExpression<\n        string | (Edges[Alias][\"optional\"] extends true ? undefined : never),\n        Scope\n      >;\n      toId: DatabaseExpression<\n        string | (Edges[Alias][\"optional\"] extends true ? undefined : never),\n        Scope\n      >;\n    }>;\n};\n\nconst METADATA_COLUMNS: Readonly<Record<string, string>> = {\n  validFrom: \"valid_from\",\n  validTo: \"valid_to\",\n  createdAt: \"created_at\",\n  updatedAt: \"updated_at\",\n  deletedAt: \"deleted_at\",\n};\n\nconst DATABASE_EXPRESSION_KEYS: ReadonlySet<PropertyKey> = new Set([\n  \"__scope\",\n  \"__type\",\n  \"__value\",\n  \"elementValueType\",\n  \"elementFields\",\n  \"node\",\n  \"nullable\",\n  \"scopeIdentity\",\n  \"valueType\",\n]);\n\n/** Builds field expressions from schema evidence; no result callback is probed. */\nexport function createExpressionAliasContext<\n  Aliases extends AliasMap,\n  Edges extends EdgeAliasMap,\n  Scope extends string = (keyof Aliases | keyof Edges) & string,\n>(\n  config: QueryBuilderConfig,\n  state: QueryBuilderState,\n  transform: (expression: DatabaseExpression) => DatabaseExpression = (\n    expression,\n  ) => expression,\n): ExpressionAliasContext<Aliases, Edges, Scope> {\n  const scope = getExpressionScope(config);\n  function makeField(\n    alias: string,\n    path: readonly string[],\n    info: FieldTypeInfo,\n    nullable: boolean,\n    property: boolean,\n  ): DatabaseExpression {\n    const reference: FieldRef = {\n      __type: \"field_ref\",\n      alias,\n      path: property ? [\"props\"] : path,\n      ...(property ? { jsonPointer: jsonPointer(path) } : {}),\n      valueType: info.valueType,\n      elementType: info.elementType,\n      nullable: nullable || info.nullable === true,\n    };\n    const expression = transform(\n      createFieldExpression(\n        reference,\n        scope,\n        nullable || info.nullable === true,\n      ),\n    );\n    if (info.valueType !== \"object\") return expression;\n    return new Proxy(expression, {\n      get(target, key, receiver) {\n        if (key === \"$get\") {\n          return (property: string) => {\n            const child = info.shape?.[property] ?? info.recordValueType;\n            if (child === undefined)\n              throw new ConfigurationError(\n                `Unknown expression field \"${alias}.${[...path, property].join(\".\")}\"`,\n              );\n            return makeField(\n              alias,\n              [...path, property],\n              child,\n              nullable || info.nullable === true,\n              true,\n            );\n          };\n        }\n        if (\n          typeof key !== \"string\" ||\n          key in target ||\n          DATABASE_EXPRESSION_KEYS.has(key)\n        )\n          return Reflect.get(target, key, receiver) as unknown;\n        const child = info.shape?.[key] ?? info.recordValueType;\n        if (child === undefined)\n          throw new ConfigurationError(\n            `Unknown expression field \"${alias}.${[...path, key].join(\".\")}\"`,\n          );\n        return makeField(\n          alias,\n          [...path, key],\n          child,\n          nullable || info.nullable === true,\n          true,\n        );\n      },\n    });\n  }\n  function aliasContext(alias: string): object {\n    const edge = state.traversals.find(\n      (traversal) => traversal.edgeAlias === alias,\n    );\n    const node = state.traversals.find(\n      (traversal) => traversal.nodeAlias === alias,\n    );\n    const kinds =\n      edge?.edgeKinds ??\n      node?.nodeKinds ??\n      (alias === state.startAlias ? state.startKinds : undefined);\n    if (kinds === undefined)\n      throw new ConfigurationError(`Unknown expression alias \"${alias}\"`);\n    const optional = edge?.optional ?? node?.optional ?? false;\n    return new Proxy(\n      {},\n      {\n        get(_target, key) {\n          if (typeof key !== \"string\") return;\n          if (key === \"$meta\")\n            return new Proxy(\n              {},\n              {\n                get(_metadata, property) {\n                  if (\n                    typeof property !== \"string\" ||\n                    METADATA_COLUMNS[property] === undefined\n                  )\n                    return;\n                  return makeField(\n                    alias,\n                    [METADATA_COLUMNS[property]],\n                    { valueType: \"string\" },\n                    optional ||\n                      (property !== \"createdAt\" && property !== \"updatedAt\"),\n                    false,\n                  );\n                },\n              },\n            );\n          const system =\n            key === \"id\" || key === \"kind\" ? key\n            : edge !== undefined && key === \"fromId\" ? \"from_id\"\n            : edge !== undefined && key === \"toId\" ? \"to_id\"\n            : undefined;\n          if (system !== undefined)\n            return makeField(\n              alias,\n              [system],\n              { valueType: \"string\" },\n              optional,\n              false,\n            );\n          const info =\n            edge === undefined ?\n              config.schemaIntrospector.getSharedFieldTypeInfo(kinds, key)\n            : config.schemaIntrospector.getSharedEdgeFieldTypeInfo(kinds, key);\n          if (info === undefined)\n            throw new ConfigurationError(\n              `Unknown or incompatible expression field \"${alias}.${key}\"`,\n            );\n          return makeField(alias, [key], info, optional, true);\n        },\n      },\n    );\n  }\n  return new Proxy(\n    {},\n    {\n      get(_target, key) {\n        return typeof key === \"string\" ? aliasContext(key) : undefined;\n      },\n    },\n  ) as ExpressionAliasContext<Aliases, Edges, Scope>;\n}\n\nexport type QueryExpressionContext<\n  G extends GraphDef,\n  Aliases extends AliasMap,\n  Edges extends EdgeAliasMap,\n  Coordinate extends QueryCoordinateState,\n> = ExpressionAliasContext<Aliases, Edges> &\n  ExpressionSubqueryHelpers<\n    QueryBuilder<\n      G,\n      EmptyAliasMap,\n      EmptyEdgeAliasMap,\n      EmptyRecursiveAliasMap,\n      Coordinate\n    >,\n    ExpressionAliasContext<Aliases, Edges, never>,\n    (keyof Aliases | keyof Edges) & string\n  >;\n","import { ConfigurationError } from \"../../errors\";\nimport type { QueryAst } from \"../ast\";\nimport { isAggregateExpression } from \"../compiler/expression-inspection\";\nimport {\n  createExistsSubqueryExpression,\n  createScalarSubqueryExpression,\n  type DatabaseExpression,\n} from \"../expressions\";\nimport type { OneStatementReadProvenance } from \"./one-statement-provenance\";\nimport type { IsUnion } from \"./types\";\n\nexport type ExpressionProjectionEntry<T = unknown> = Readonly<{\n  outputName: string;\n  expression: DatabaseExpression<T>;\n}>;\n\ntype ExpressionValue<Expression> =\n  Expression extends DatabaseExpression<infer Value> ? Value : never;\n/** Preserves a one-field projection as a tuple so `$scalar()` can reject wider records. */\nexport type ExpressionProjectionEntries<\n  Fields extends Readonly<Record<string, DatabaseExpression>>,\n> =\n  keyof Fields extends never ? readonly []\n  : string extends keyof Fields ? readonly ExpressionProjectionEntry[]\n  : IsUnion<keyof Fields> extends true ? readonly ExpressionProjectionEntry[]\n  : readonly [ExpressionProjectionEntry<ExpressionValue<Fields[keyof Fields]>>];\n\nexport type ExpressionSubqueryRelation<\n  Projection extends readonly ExpressionProjectionEntry[],\n> = Readonly<{\n  getExpressionProjection: () => Projection;\n  getExpressionScopeIdentity: () => symbol;\n  getOneStatementReadProvenance: () => OneStatementReadProvenance;\n  toAst: () => QueryAst;\n}>;\n\ntype ProjectedExpressionSubqueryRelation = ExpressionSubqueryRelation<\n  readonly ExpressionProjectionEntry[]\n>;\n\ntype ScalarExpressionSubqueryRelation<T> = ExpressionSubqueryRelation<\n  readonly [ExpressionProjectionEntry<T>]\n>;\n\nexport type ExpressionSubqueryHelpers<\n  Builder,\n  OuterContext,\n  ParentScope extends string,\n> = Readonly<{\n  $exists: (\n    build: (\n      subquery: Builder,\n      outer: OuterContext,\n    ) => ProjectedExpressionSubqueryRelation,\n  ) => DatabaseExpression<boolean, ParentScope>;\n  $scalar: <T>(\n    build: (\n      subquery: Builder,\n      outer: OuterContext,\n    ) => ScalarExpressionSubqueryRelation<T>,\n  ) => DatabaseExpression<T | undefined, ParentScope>;\n}>;\n\nexport type CreateExpressionSubqueryHelpersInput<Builder, OuterContext> =\n  Readonly<{\n    parentScopeIdentity: symbol;\n    parentProvenance: OneStatementReadProvenance;\n    parentCoordinate: Pick<QueryAst, \"recordedAsOf\" | \"temporalMode\">;\n    createSubquery: () => Builder;\n    createOuterContext: (childScopeIdentity: symbol) => OuterContext;\n  }>;\n\n/** Creates the correlated subquery helpers exposed by an expression context. */\nexport function createExpressionSubqueryHelpers<\n  Builder,\n  OuterContext,\n  ParentScope extends string,\n>(\n  input: CreateExpressionSubqueryHelpersInput<Builder, OuterContext>,\n): ExpressionSubqueryHelpers<Builder, OuterContext, ParentScope> {\n  function buildRelation<\n    Projection extends readonly ExpressionProjectionEntry[],\n  >(\n    build: (\n      subquery: Builder,\n      outer: OuterContext,\n    ) => ExpressionSubqueryRelation<Projection>,\n  ): Readonly<{\n    ast: QueryAst;\n    projection: Projection;\n  }> {\n    const subquery = input.createSubquery();\n    if (!hasExpressionScope(subquery)) {\n      throw new ConfigurationError(\n        \"Expression subquery builders must expose their query scope.\",\n        { operation: \"expressionSubquery\" },\n      );\n    }\n    const childScopeIdentity = subquery.getExpressionScopeIdentity();\n    const relation = build(\n      subquery,\n      input.createOuterContext(childScopeIdentity),\n    );\n    const ast = relation.toAst();\n    assertRelationProvenance(relation, childScopeIdentity, input);\n    assertCoordinateMatches(ast, input.parentCoordinate);\n    return {\n      ast,\n      projection: relation.getExpressionProjection(),\n    };\n  }\n\n  function exists(\n    build: (\n      subquery: Builder,\n      outer: OuterContext,\n    ) => ProjectedExpressionSubqueryRelation,\n  ): DatabaseExpression<boolean, ParentScope> {\n    const { ast, projection } = buildRelation(build);\n    if (projection.length === 0) {\n      throw new ConfigurationError(\n        \"$exists() requires an explicit nonempty project() result.\",\n        { operation: \"$exists\" },\n      );\n    }\n    return createExistsSubqueryExpression<ParentScope>(\n      ast,\n      input.parentScopeIdentity,\n    );\n  }\n\n  function scalar<T>(\n    build: (\n      subquery: Builder,\n      outer: OuterContext,\n    ) => ScalarExpressionSubqueryRelation<T>,\n  ): DatabaseExpression<T | undefined, ParentScope> {\n    const { ast, projection } = buildRelation(build);\n    const projected = requireSingleProjection<T>(projection);\n    const ungroupedAggregate =\n      ast.groupBy === undefined && isAggregateExpression(projected.expression);\n    if (!ungroupedAggregate && (ast.limit === undefined || ast.limit > 1)) {\n      throw new ConfigurationError(\n        \"$scalar() requires limit(1) or an ungrouped aggregate subquery.\",\n        { operation: \"$scalar\" },\n      );\n    }\n    return createScalarSubqueryExpression<T, ParentScope>(\n      ast,\n      projected.expression,\n      input.parentScopeIdentity,\n    );\n  }\n\n  return { $exists: exists, $scalar: scalar };\n}\n\nfunction assertCoordinateMatches(\n  ast: QueryAst,\n  parent: Pick<QueryAst, \"recordedAsOf\" | \"temporalMode\">,\n): void {\n  if (\n    ast.temporalMode.mode !== parent.temporalMode.mode ||\n    ast.temporalMode.asOf !== parent.temporalMode.asOf ||\n    ast.recordedAsOf !== parent.recordedAsOf\n  ) {\n    throw new ConfigurationError(\n      \"Expression subqueries must use the enclosing query's temporal coordinate.\",\n      { operation: \"expressionSubquery\" },\n    );\n  }\n}\n\nfunction hasExpressionScope(\n  value: unknown,\n): value is Readonly<{ getExpressionScopeIdentity: () => symbol }> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"getExpressionScopeIdentity\" in value &&\n    typeof value.getExpressionScopeIdentity === \"function\"\n  );\n}\n\nfunction assertRelationProvenance<Builder, OuterContext>(\n  relation: ExpressionSubqueryRelation<readonly ExpressionProjectionEntry[]>,\n  childScopeIdentity: symbol,\n  input: CreateExpressionSubqueryHelpersInput<Builder, OuterContext>,\n): void {\n  if (relation.getExpressionScopeIdentity() !== childScopeIdentity) {\n    throw new ConfigurationError(\n      \"Expression subquery callbacks must return the relation built by their subquery argument.\",\n      { operation: \"expressionSubquery\" },\n    );\n  }\n  const provenance = relation.getOneStatementReadProvenance();\n  if (\n    provenance.graphId !== input.parentProvenance.graphId ||\n    provenance.executionTarget !== input.parentProvenance.executionTarget\n  ) {\n    throw new ConfigurationError(\n      \"Expression subqueries must use the enclosing query's graph and execution target.\",\n      { operation: \"expressionSubquery\" },\n    );\n  }\n}\n\nfunction requireSingleProjection<T>(\n  projection: readonly ExpressionProjectionEntry<T>[],\n): ExpressionProjectionEntry<T> {\n  if (projection.length !== 1 || projection[0] === undefined) {\n    throw new ConfigurationError(\n      \"$scalar() requires exactly one projected field.\",\n      { operation: \"$scalar\", projectionWidth: projection.length },\n    );\n  }\n  return projection[0];\n}\n","import { ConfigurationError } from \"../../errors\";\nimport type { FieldRef, PredicateExpression, Traversal } from \"../ast\";\nimport type { QueryBuilderState } from \"./types\";\n\nfunction assertStopFieldAlias(field: FieldRef, alias: string): void {\n  if (field.alias !== alias)\n    throw new ConfigurationError(\n      `stopExpansion() predicate must reference only recursive target alias \"${alias}\".`,\n    );\n}\n\nfunction assertSupportedStopPredicate(\n  expression: PredicateExpression,\n  alias: string,\n): void {\n  switch (expression.__type) {\n    case \"comparison\": {\n      assertStopFieldAlias(expression.left, alias);\n      if (\n        !Array.isArray(expression.right) &&\n        expression.right.__type === \"field_ref\"\n      )\n        assertStopFieldAlias(expression.right, alias);\n      return;\n    }\n    case \"tuple_comparison\": {\n      for (const field of expression.fields) assertStopFieldAlias(field, alias);\n      return;\n    }\n    case \"string_op\":\n    case \"null_check\":\n    case \"between\":\n    case \"array_op\":\n    case \"object_op\": {\n      assertStopFieldAlias(expression.field, alias);\n      return;\n    }\n    case \"and\":\n    case \"or\": {\n      for (const predicate of expression.predicates)\n        assertSupportedStopPredicate(predicate, alias);\n      return;\n    }\n    case \"not\": {\n      assertSupportedStopPredicate(expression.predicate, alias);\n      return;\n    }\n    case \"aggregate_comparison\":\n    case \"exists\":\n    case \"in_subquery\":\n    case \"vector_similarity\":\n    case \"fulltext_match\":\n    case \"database_expression_predicate\": {\n      throw new ConfigurationError(\n        \"stopExpansion() supports ordinary target-node predicates only.\",\n      );\n    }\n  }\n}\n\nexport function withRecursiveStopExpansion(\n  state: QueryBuilderState,\n  alias: string,\n  expression: PredicateExpression,\n  emitStopNode: boolean,\n): QueryBuilderState {\n  if (typeof emitStopNode !== \"boolean\")\n    throw new ConfigurationError(\n      \"stopExpansion() emitStopNode must be a boolean.\",\n    );\n  const traversal = state.traversals.find(\n    (traversal) =>\n      traversal.nodeAlias === alias && traversal.variableLength !== undefined,\n  );\n  const variableLength = traversal?.variableLength;\n  if (traversal === undefined || variableLength === undefined)\n    throw new ConfigurationError(\n      `stopExpansion() alias \"${alias}\" must be the target of a recursive traversal.`,\n    );\n  if (variableLength.stopExpansion !== undefined)\n    throw new ConfigurationError(\n      `stopExpansion() is already defined for recursive target alias \"${alias}\".`,\n    );\n  assertSupportedStopPredicate(expression, alias);\n  const updatedTraversal: Traversal = {\n    ...traversal,\n    variableLength: {\n      ...variableLength,\n      stopExpansion: { expression, emitStopNode },\n    },\n  };\n  return {\n    ...state,\n    traversals: state.traversals.map((candidate) =>\n      candidate === traversal ? updatedTraversal : candidate,\n    ),\n  };\n}\n","/**\n * TraversalBuilder - Intermediate builder for edge traversals.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { isEdgeTargetMap } from \"../../core/edge-endpoints\";\nimport {\n  resolveRuntimeKindInput,\n  type RuntimeNodeKind,\n  type RuntimeNodeTypeFor,\n} from \"../../core/runtime-kind\";\nimport { type AnyEdgeType, type NodeType } from \"../../core/types\";\nimport { EndpointError, KindNotFoundError } from \"../../errors\";\nimport { isInteropProbeKey } from \"../../utils/object\";\nimport {\n  type NodePredicate,\n  type RecursiveCyclePolicy,\n  type Traversal,\n  type TraversalDirection,\n} from \"../ast\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../compiler\";\nimport { jsonPointer } from \"../json-pointer\";\nimport {\n  arrayField,\n  baseField,\n  dateField,\n  fieldRef,\n  numberField,\n  objectField,\n  type Predicate,\n  stringField,\n} from \"../predicates\";\n// Type-only import to get the QueryBuilder type without runtime circular dependency\nimport {\n  createDynamicFieldBuilder,\n  type DynamicEdgeType,\n  type DynamicNodeType,\n} from \"./dynamic\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { type QueryBuilder } from \"./query-builder\";\nimport {\n  type AliasMap,\n  type BaseFieldAccessor,\n  type BuildRecursiveAliases,\n  type EdgeAccessor,\n  type EdgeAlias,\n  type EdgeAliasMap,\n  type EmptyEdgeAliasMap,\n  type EmptyRecursiveAliasMap,\n  type NodeAlias,\n  type QualifiedRecursivePathOption,\n  type QueryBuilderConfig,\n  type QueryBuilderState,\n  type QueryCoordinateState,\n  type RecursiveAliasMap,\n  type RecursiveTraversalOptions,\n  type UniqueAlias,\n  type ValidEdgeTargets,\n} from \"./types\";\nimport { validateSqlIdentifier } from \"./validation\";\n\n/**\n * Resolves the edge type for an edge alias based on its kind type parameter.\n *\n * For `traverse(...)`, `EK` is a literal like `\"authoredBy\"` and the\n * type comes from the typed graph. For string-keyed `traverseDynamic(...)`,\n * `EK` is widened to `string`, so this falls back to `DynamicEdgeType`.\n * Store-issued runtime-kind evidence overrides that fallback through the\n * `TraversalBuilder`'s `ET` parameter.\n */\ntype EdgeTypeForKey<G extends GraphDef, EK> =\n  string extends EK ? DynamicEdgeType\n  : EK extends keyof G[\"edges\"] & string ? G[\"edges\"][EK][\"type\"]\n  : DynamicEdgeType;\n\ntype DynamicNodeTypeFor<T> =\n  T extends RuntimeNodeKind ? RuntimeNodeTypeFor<T> : DynamicNodeType;\n\n// Forward declaration - actual import would cause circular dependency\ntype QueryBuilderConstructor = new (\n  config: QueryBuilderConfig,\n  state: QueryBuilderState,\n) => unknown;\n\n// This will be set by the main builder module to avoid circular imports\nlet QueryBuilderClass: QueryBuilderConstructor;\n\n/**\n * Sets the QueryBuilder class reference for use by TraversalBuilder.\n * Called during module initialization to break circular dependency.\n */\nexport function setQueryBuilderClass(cls: QueryBuilderConstructor): void {\n  QueryBuilderClass = cls;\n}\n\n/**\n * State for variable-length traversal configuration.\n */\ninterface VariableLengthState {\n  enabled: boolean;\n  minDepth: number;\n  maxDepth: number;\n  cyclePolicy: RecursiveCyclePolicy;\n  pathEnabled: boolean;\n  pathAlias?: string;\n  pathFormat?: \"qualified\";\n  depthEnabled: boolean;\n  depthAlias?: string;\n}\n\n/**\n * Default variable-length state (disabled).\n */\nconst DEFAULT_VARIABLE_LENGTH_STATE: VariableLengthState = {\n  enabled: false,\n  minDepth: 1,\n  maxDepth: -1,\n  cyclePolicy: \"prevent\",\n  pathEnabled: false,\n  depthEnabled: false,\n};\n\nfunction validateMaxHops(max: number): void {\n  if (!Number.isFinite(max) || !Number.isInteger(max)) {\n    throw new TypeError(\"maxHops must be a finite integer\");\n  }\n  if (max < 1) {\n    throw new Error(\"maxHops must be >= 1\");\n  }\n  if (max > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n    throw new Error(\n      `maxHops must be <= ${MAX_EXPLICIT_RECURSIVE_DEPTH}. ` +\n        `Use a smaller bound to prevent runaway recursive queries.`,\n    );\n  }\n}\n\nfunction validateMinHops(min: number): void {\n  if (!Number.isFinite(min) || !Number.isInteger(min)) {\n    throw new TypeError(\"minHops must be a finite integer\");\n  }\n  if (min < 0) {\n    throw new Error(\"minHops must be >= 0\");\n  }\n}\n\nfunction resolveAliasOption(\n  option: boolean | string | undefined,\n): string | undefined {\n  if (option === undefined || option === false) {\n    return;\n  }\n\n  if (option === true) {\n    return;\n  }\n\n  return typeof option === \"string\" ? option : undefined;\n}\n\nfunction resolvePathOption(option: unknown):\n  | Readonly<{\n      enabled: boolean;\n      alias?: string;\n      format?: \"qualified\";\n    }>\n  | undefined {\n  if (option === undefined) return;\n  if (option === false) return { enabled: false };\n  if (option === true) return { enabled: true };\n  if (typeof option === \"string\") return { enabled: true, alias: option };\n\n  if (typeof option !== \"object\" || option === null || Array.isArray(option)) {\n    throw new TypeError(\n      'path must be a boolean, an alias string, or { format: \"qualified\", alias?: string }',\n    );\n  }\n\n  const candidate = option as Readonly<{\n    alias?: unknown;\n    format?: unknown;\n  }>;\n  if (candidate.format !== \"qualified\") {\n    throw new TypeError('path.format must be \"qualified\"');\n  }\n  if (candidate.alias !== undefined && typeof candidate.alias !== \"string\") {\n    throw new TypeError(\"path.alias must be a string\");\n  }\n\n  return {\n    enabled: true,\n    format: \"qualified\",\n    ...(candidate.alias !== undefined && { alias: candidate.alias }),\n  };\n}\n\nfunction withoutPathMetadata(state: VariableLengthState): VariableLengthState {\n  const {\n    pathAlias: _pathAlias,\n    pathFormat: _pathFormat,\n    ...stateWithoutPathMetadata\n  } = state;\n  return stateWithoutPathMetadata;\n}\n\nfunction withoutDepthAlias(state: VariableLengthState): VariableLengthState {\n  const { depthAlias: _depthAlias, ...stateWithoutDepthAlias } = state;\n  return stateWithoutDepthAlias;\n}\n\n/**\n * Intermediate builder for traversal operations.\n *\n * Type parameters track the edge kind and direction to constrain\n * which node kinds are valid targets in the `to()` method.\n */\nexport class TraversalBuilder<\n  G extends GraphDef,\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap = EmptyEdgeAliasMap,\n  EK extends keyof G[\"edges\"] & string = keyof G[\"edges\"] & string,\n  EA extends string = string,\n  Dir extends TraversalDirection = \"out\",\n  Optional extends boolean = false,\n  DC extends boolean | string = false,\n  PC extends boolean | string | QualifiedRecursivePathOption = false,\n  RecAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n  CoordinateState extends QueryCoordinateState = \"open\",\n  ET extends AnyEdgeType = EdgeTypeForKey<G, EK>,\n> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: QueryBuilderState;\n  readonly #edgeKinds: readonly string[];\n  readonly #inverseEdgeKinds: readonly string[];\n  readonly #edgeAlias: EA;\n  readonly #direction: Dir;\n  readonly #fromAlias: string;\n  readonly #optional: Optional;\n  readonly #includeIdentityMembers: boolean;\n  readonly #variableLength: VariableLengthState;\n  readonly #pendingEdgePredicates: readonly NodePredicate[];\n\n  constructor(\n    config: QueryBuilderConfig,\n    state: QueryBuilderState,\n    edgeKinds: readonly string[],\n    edgeAlias: EA,\n    direction: Dir,\n    fromAlias: string,\n    inverseEdgeKinds: readonly string[] = [],\n    optional: Optional = false as Optional,\n    variableLength: VariableLengthState = DEFAULT_VARIABLE_LENGTH_STATE,\n    pendingEdgePredicates: readonly NodePredicate[] = [],\n    // Appended, never inserted: TraversalBuilder is public, so every\n    // pre-existing positional slot must keep its meaning.\n    includeIdentityMembers = false,\n  ) {\n    this.#config = config;\n    this.#state = state;\n    this.#edgeKinds = edgeKinds;\n    this.#inverseEdgeKinds = inverseEdgeKinds;\n    this.#edgeAlias = edgeAlias;\n    this.#direction = direction;\n    this.#fromAlias = fromAlias;\n    this.#optional = optional;\n    this.#includeIdentityMembers = includeIdentityMembers;\n    this.#variableLength = variableLength;\n    this.#pendingEdgePredicates = pendingEdgePredicates;\n  }\n\n  /**\n   * Enables variable-length (recursive) traversal.\n   * Defaults to MAX_RECURSIVE_DEPTH (10) hops with cycle prevention.\n   * Use `maxHops` to override (up to MAX_EXPLICIT_RECURSIVE_DEPTH).\n   */\n  recursive<const O extends RecursiveTraversalOptions = Record<string, never>>(\n    options?: O,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    Dir,\n    Optional,\n    O extends { depth: infer D extends boolean | string } ? D : DC,\n    O extends (\n      { path: infer P extends boolean | string | QualifiedRecursivePathOption }\n    ) ?\n      P\n    : PC,\n    RecAliases,\n    CoordinateState,\n    ET\n  > {\n    const minDepth = options?.minHops ?? this.#variableLength.minDepth;\n    const maxDepth = options?.maxHops ?? this.#variableLength.maxDepth;\n    validateMinHops(minDepth);\n    if (options?.maxHops !== undefined) {\n      validateMaxHops(maxDepth);\n    }\n    if (maxDepth > 0 && minDepth > maxDepth) {\n      throw new Error(\"minHops must be <= maxHops\");\n    }\n\n    const pathOption = resolvePathOption(options?.path);\n    const pathAlias = pathOption?.alias;\n    const depthAlias = resolveAliasOption(options?.depth);\n    if (pathAlias !== undefined) validateSqlIdentifier(pathAlias);\n    if (depthAlias !== undefined) validateSqlIdentifier(depthAlias);\n    const cyclePolicy =\n      options?.cyclePolicy ?? this.#variableLength.cyclePolicy;\n    const pathState =\n      pathOption === undefined ?\n        this.#variableLength\n      : withoutPathMetadata(this.#variableLength);\n    const variableLengthState =\n      options?.depth === undefined ? pathState : withoutDepthAlias(pathState);\n\n    return new TraversalBuilder<\n      G,\n      Aliases,\n      EdgeAliases,\n      EK,\n      EA,\n      Dir,\n      Optional,\n      O extends { depth: infer D extends boolean | string } ? D : DC,\n      O extends (\n        {\n          path: infer P extends boolean | string | QualifiedRecursivePathOption;\n        }\n      ) ?\n        P\n      : PC,\n      RecAliases,\n      CoordinateState,\n      ET\n    >(\n      this.#config,\n      this.#state,\n      this.#edgeKinds,\n      this.#edgeAlias,\n      this.#direction,\n      this.#fromAlias,\n      this.#inverseEdgeKinds,\n      this.#optional,\n      {\n        ...variableLengthState,\n        enabled: true,\n        minDepth,\n        maxDepth,\n        cyclePolicy,\n        ...(pathOption === undefined ?\n          {}\n        : {\n            pathEnabled: pathOption.enabled,\n            ...(pathAlias === undefined ? {} : { pathAlias }),\n            ...(pathOption.format === undefined ?\n              {}\n            : { pathFormat: pathOption.format }),\n          }),\n        ...(options?.depth !== undefined && {\n          depthEnabled: options.depth !== false,\n          ...(depthAlias === undefined ? {} : { depthAlias }),\n        }),\n      },\n      this.#pendingEdgePredicates,\n      this.#includeIdentityMembers,\n    );\n  }\n\n  /**\n   * Adds a WHERE clause for the edge being traversed.\n   *\n   * @param alias - The edge alias to filter on (must be the current edge alias)\n   * @param predicateFunction - A function that builds predicates using the edge accessor\n   */\n  whereEdge(\n    alias: EA,\n    predicateFunction: (edge: EdgeAccessor<ET>) => Predicate,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    Dir,\n    Optional,\n    DC,\n    PC,\n    RecAliases,\n    CoordinateState,\n    ET\n  > {\n    const accessor = this.#createEdgeAccessor(alias);\n    const predicate = predicateFunction(accessor as EdgeAccessor<ET>);\n\n    const newPredicate: NodePredicate = {\n      targetAlias: alias,\n      targetType: \"edge\",\n      expression: predicate.__expr,\n    };\n\n    return new TraversalBuilder<\n      G,\n      Aliases,\n      EdgeAliases,\n      EK,\n      EA,\n      Dir,\n      Optional,\n      DC,\n      PC,\n      RecAliases,\n      CoordinateState,\n      ET\n    >(\n      this.#config,\n      this.#state,\n      this.#edgeKinds,\n      this.#edgeAlias,\n      this.#direction,\n      this.#fromAlias,\n      this.#inverseEdgeKinds,\n      this.#optional,\n      this.#variableLength,\n      [...this.#pendingEdgePredicates, newPredicate],\n      this.#includeIdentityMembers,\n    );\n  }\n\n  /**\n   * Creates a type-safe accessor for edge properties.\n   */\n  #createEdgeAccessor(alias: string): EdgeAccessor<AnyEdgeType> {\n    const allEdgeKinds = [\n      ...this.#edgeKinds,\n      ...this.#inverseEdgeKinds.filter(\n        (kind) => !this.#edgeKinds.includes(kind),\n      ),\n    ];\n\n    // Pre-compute system field accessors\n    const idAccessor = stringField(\n      fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n    );\n    const kindAccessor = stringField(\n      fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n    );\n    const fromIdAccessor = stringField(\n      fieldRef(alias, [\"from_id\"], { valueType: \"string\" }),\n    );\n    const toIdAccessor = stringField(\n      fieldRef(alias, [\"to_id\"], { valueType: \"string\" }),\n    );\n\n    // Build field accessor for a schema property\n    const buildFieldAccessor = (propertyName: string): BaseFieldAccessor => {\n      const typeInfo =\n        this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n          allEdgeKinds,\n          propertyName,\n        );\n\n      const valueType = typeInfo?.valueType;\n      const elementType = typeInfo?.elementType;\n\n      const ref = fieldRef(alias, [\"props\"], {\n        jsonPointer: jsonPointer([propertyName]),\n        valueType,\n        elementType,\n      });\n\n      switch (valueType) {\n        case \"string\": {\n          return stringField(ref) as unknown as BaseFieldAccessor;\n        }\n        case \"number\": {\n          return numberField(ref) as unknown as BaseFieldAccessor;\n        }\n        case \"boolean\": {\n          return baseField(ref);\n        }\n        case \"date\": {\n          return dateField(ref) as unknown as BaseFieldAccessor;\n        }\n        case \"array\": {\n          return arrayField(ref) as unknown as BaseFieldAccessor;\n        }\n        case \"object\": {\n          return objectField(ref) as unknown as BaseFieldAccessor;\n        }\n        case \"embedding\":\n        case \"unknown\":\n        case undefined: {\n          // Embedding, unknown, or unresolved type - return base field\n          return baseField(ref);\n        }\n      }\n    };\n\n    if (this.#state.dynamicEdgeAliases.has(alias)) {\n      return {\n        id: idAccessor,\n        kind: kindAccessor,\n        fromId: fromIdAccessor,\n        toId: toIdAccessor,\n        field: (name: string) =>\n          createDynamicFieldBuilder(\n            this.#config.schemaIntrospector,\n            alias,\n            name,\n            allEdgeKinds,\n            \"edge\",\n          ),\n      } as unknown as EdgeAccessor<AnyEdgeType>;\n    }\n\n    // Use a Proxy to provide flattened property access\n    return new Proxy({} as EdgeAccessor<AnyEdgeType>, {\n      get: (_, property: string | symbol) => {\n        // Handle symbols and special properties to avoid infinite loops\n        if (typeof property === \"symbol\") return;\n\n        // System fields\n        if (property === \"id\") return idAccessor;\n        if (property === \"kind\") return kindAccessor;\n        if (property === \"fromId\") return fromIdAccessor;\n        if (property === \"toId\") return toIdAccessor;\n\n        // A DECLARED field wins over the interop exemption: `then` and `toJSON`\n        // are legal schema field names, so only an UNDECLARED probe resolves to\n        // `undefined`.\n        if (\n          isInteropProbeKey(property) &&\n          !this.#config.schemaIntrospector.hasDeclaredEdgeField(\n            allEdgeKinds,\n            property,\n          )\n        ) {\n          return;\n        }\n\n        // Schema properties\n        return buildFieldAccessor(property);\n      },\n    });\n  }\n\n  /**\n   * Specifies the target node kind.\n   *\n   * The kind must be a valid target for this edge based on the traversal direction:\n   * - \"out\" direction: kind must be in the edge's \"to\" array\n   * - \"in\" direction: kind must be in the edge's \"from\" array\n   *\n   * @param kind - The target node kind\n   * @param alias - A unique alias for this node (compile-time error if duplicate)\n   */\n  to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n    kind: K,\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: false },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<G[\"nodes\"][K][\"type\"], Optional>>,\n    EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n    RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n    CoordinateState\n  >;\n\n  to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n    kind: K,\n    alias: UniqueAlias<A, Aliases>,\n    options: { includeSubClasses: true },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n    EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n    RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n    CoordinateState\n  >;\n\n  to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n    kind: K,\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: boolean },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n    EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n    RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n    CoordinateState\n  > {\n    validateSqlIdentifier(alias);\n\n    const includeSubClasses = options?.includeSubClasses ?? false;\n    const kinds =\n      includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\n\n    const newState = this.#stateWithTraversal(alias, kinds);\n\n    // Cast is safe because the overloads provide compile-time type safety\n    // The runtime QueryBuilderClass is the correct implementation\n    return new QueryBuilderClass(this.#config, newState) as QueryBuilder<\n      G,\n      Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n      EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n      RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n      CoordinateState\n    >;\n  }\n\n  /**\n   * Runtime-kind sibling of `to`; accepts a kind name or Store-issued token.\n   * Throws `KindNotFoundError` if the kind is not registered.\n   */\n  toDynamic<T extends string | RuntimeNodeKind, A extends string>(\n    kind: T,\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: boolean },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<DynamicNodeTypeFor<T>, Optional>>,\n    EdgeAliases & Record<EA, EdgeAlias<ET, Optional>>,\n    RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n    CoordinateState\n  > {\n    validateSqlIdentifier(alias);\n    const kindName = resolveRuntimeKindInput(\n      kind,\n      \"node\",\n      getQueryBuilderInternalContext(this.#config).runtimeKindTokenResolver,\n    );\n    if (!this.#config.registry.hasNodeType(kindName)) {\n      throw new KindNotFoundError(kindName, \"node\", {\n        graphId: this.#config.graphId,\n      });\n    }\n    this.#assertValidEndpoint(kindName);\n\n    const includeSubClasses = options?.includeSubClasses ?? false;\n    const kinds =\n      includeSubClasses ?\n        this.#config.registry.expandSubClasses(kindName)\n      : [kindName];\n\n    const baseState = this.#stateWithTraversal(alias, kinds);\n    const newState: QueryBuilderState = {\n      ...baseState,\n      dynamicNodeAliases: new Set([...baseState.dynamicNodeAliases, alias]),\n    };\n\n    return new QueryBuilderClass(this.#config, newState) as QueryBuilder<\n      G,\n      Aliases & Record<A, NodeAlias<DynamicNodeTypeFor<T>, Optional>>,\n      EdgeAliases & Record<EA, EdgeAlias<ET, Optional>>,\n      RecAliases & BuildRecursiveAliases<DC, PC, A, Optional>,\n      CoordinateState\n    >;\n  }\n\n  /**\n   * Builds the next `QueryBuilderState` after appending a traversal\n   * targeting `alias` with `kinds`. Shared by `to` and `toDynamic`.\n   */\n  #stateWithTraversal(\n    alias: string,\n    kinds: readonly string[],\n  ): QueryBuilderState {\n    // The `direction` ternaries here and in the compiler's traversal emitters\n    // test for `\"out\"` and treat everything else as inbound. That is exhaustive\n    // because a query AST's `TraversalDirection` is `\"out\" | \"in\"`: the store's\n    // algorithm APIs have a three-valued union of the same name that includes\n    // `\"both\"`, but no public builder path can put it here, and an undirected\n    // query traversal is expressed with `inverseEdgeKinds` instead. Widening the\n    // AST union without revisiting these ternaries would silently compile\n    // `\"both\"` as inbound-only.\n    const traversalBase: Traversal = {\n      edgeAlias: this.#edgeAlias,\n      edgeKinds: this.#edgeKinds,\n      direction: this.#direction,\n      nodeAlias: alias,\n      nodeKinds: kinds,\n      joinFromAlias: this.#fromAlias,\n      joinEdgeField: this.#direction === \"out\" ? \"from_id\" : \"to_id\",\n      optional: this.#optional,\n      ...(this.#includeIdentityMembers ? { includeIdentityMembers: true } : {}),\n    };\n\n    const baseTraversal: Traversal =\n      this.#inverseEdgeKinds.length > 0 ?\n        { ...traversalBase, inverseEdgeKinds: this.#inverseEdgeKinds }\n      : traversalBase;\n\n    const traversal: Traversal =\n      this.#variableLength.enabled ?\n        {\n          ...baseTraversal,\n          variableLength: {\n            minDepth: this.#variableLength.minDepth,\n            maxDepth: this.#variableLength.maxDepth,\n            cyclePolicy: this.#variableLength.cyclePolicy,\n            ...(this.#variableLength.pathEnabled && {\n              pathAlias: this.#variableLength.pathAlias ?? `${alias}_path`,\n              ...(this.#variableLength.pathFormat === undefined ?\n                {}\n              : {\n                  pathFormat: this.#variableLength.pathFormat,\n                }),\n            }),\n            ...(this.#variableLength.depthEnabled && {\n              depthAlias: this.#variableLength.depthAlias ?? `${alias}_depth`,\n            }),\n          },\n        }\n      : baseTraversal;\n\n    return {\n      ...this.#state,\n      traversals: [...this.#state.traversals, traversal],\n      predicates: [...this.#state.predicates, ...this.#pendingEdgePredicates],\n      currentAlias: alias,\n    };\n  }\n\n  /**\n   * Asserts a runtime-declared target kind is a valid endpoint for the\n   * current traversal. Mirrors the compile-time `ValidEdgeTargets`\n   * constraint enforced by `to(...)` — without this check `toDynamic`\n   * would silently accept e.g. `traverseDynamic(\"authoredBy\") +\n   * toDynamic(\"Document\")` where authoredBy.to=[Author] and produce an\n   * empty result set.\n   *\n   * Permissive on unions: if the target is assignable to any valid\n   * endpoint across the edges being traversed, accept. Subclass\n   * relationships are honored via `registry.isAssignableTo`.\n   */\n  #assertValidEndpoint(targetKind: string): void {\n    const expectedKinds = new Set<string>();\n    const collectFromEdge = (edgeName: string, side: \"to\" | \"from\"): void => {\n      const edgeType = this.#config.registry.getEdgeType(edgeName);\n      const endpoints = edgeType?.[side];\n      if (!endpoints) return;\n      if (side === \"to\" && isEdgeTargetMap(endpoints)) {\n        for (const targets of Object.values(\n          endpoints,\n        ) as (readonly NodeType[])[]) {\n          for (const endpoint of targets) {\n            expectedKinds.add(endpoint.kind);\n          }\n        }\n      } else if (Array.isArray(endpoints)) {\n        for (const endpoint of endpoints as readonly NodeType[]) {\n          expectedKinds.add(endpoint.kind);\n        }\n      }\n    };\n    const forwardSide = this.#direction === \"out\" ? \"to\" : \"from\";\n    const inverseSide = this.#direction === \"out\" ? \"from\" : \"to\";\n    for (const edgeName of this.#edgeKinds) {\n      collectFromEdge(edgeName, forwardSide);\n    }\n    for (const edgeName of this.#inverseEdgeKinds) {\n      collectFromEdge(edgeName, inverseSide);\n    }\n\n    // No declared endpoints anywhere — edge kinds in the registry can\n    // legally have undefined `to` / `from`; nothing to validate against.\n    if (expectedKinds.size === 0) return;\n\n    for (const expected of expectedKinds) {\n      if (this.#config.registry.isAssignableTo(targetKind, expected)) return;\n    }\n\n    throw new EndpointError({\n      edgeKind: this.#edgeKinds[0] ?? \"(unknown)\",\n      endpoint: forwardSide,\n      actualKind: targetKind,\n      expectedKinds: [...expectedKinds],\n    });\n  }\n}\n","/**\n * QueryBuilder - The fluent query builder.\n */\nimport { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport {\n  type GraphDef,\n  type GraphIdentityConfig,\n} from \"../../core/define-graph\";\nimport {\n  resolveRuntimeKindInput,\n  type RuntimeEdgeKind,\n  type RuntimeEdgeTypeFor,\n  type RuntimeNodeKind,\n  type RuntimeNodeTypeFor,\n} from \"../../core/runtime-kind\";\nimport {\n  coordinateContext,\n  describeCoordinate,\n  resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport {\n  type EdgeType,\n  type NodeType,\n  type TemporalMode,\n} from \"../../core/types\";\nimport { ConfigurationError, KindNotFoundError } from \"../../errors\";\nimport { isInteropProbeKey } from \"../../utils/object\";\nimport {\n  type AggregateExpr,\n  type FieldRef,\n  type GroupBySpec,\n  type HybridFusionOptions,\n  mergeEdgeKinds,\n  type PredicateExpression,\n  type ProjectedField,\n  type SortDirection,\n  type TraversalDirection,\n  type TraversalExpansion,\n} from \"../ast\";\nimport { validateAggregateOperand } from \"../compiler/aggregate-validation\";\nimport {\n  createOuterReferenceExpression,\n  type DatabaseExpression,\n} from \"../expressions\";\nimport { jsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport {\n  buildFieldBuilderForTypeInfo,\n  createFulltextAccessor,\n  fieldRef,\n  type Predicate,\n  stringField,\n} from \"../predicates\";\nimport {\n  type FieldTypeInfo,\n  type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport {\n  createDynamicFieldBuilder,\n  type DynamicEdgeType,\n  type DynamicNodeType,\n} from \"./dynamic\";\nimport { ExecutableAggregateQuery } from \"./executable-aggregate-query\";\nimport {\n  type DatabaseProjection,\n  ExecutableProjectionQuery,\n} from \"./executable-projection-query\";\nimport { ExecutableQuery } from \"./executable-query\";\nimport {\n  createExpressionAliasContext,\n  type ExpressionAliasContext,\n  type QueryExpressionContext,\n} from \"./expression-context\";\nimport {\n  assertExpressionScope,\n  getExpressionScope,\n  isDatabaseExpression,\n} from \"./expression-scope\";\nimport { createExpressionSubqueryHelpers } from \"./expression-subqueries\";\nimport { registerQueryBuilderInternalContext } from \"./internal-context\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport {\n  assertSharedNodeField,\n  buildOrderSpec,\n  resolveSystemOrderField,\n} from \"./order-by-field\";\nimport { withRecursiveStopExpansion } from \"./recursive-stop\";\nimport { executeQueryTerminal } from \"./terminal-query\";\nimport { TraversalBuilder } from \"./traversal-builder\";\nimport {\n  type AliasMap,\n  type BaseFieldAccessor,\n  type EdgeAccessor,\n  type EdgeAlias,\n  type EdgeAliasMap,\n  type EmptyAliasMap,\n  type EmptyEdgeAliasMap,\n  type EmptyRecursiveAliasMap,\n  type NodeAccessor,\n  type NodeAlias,\n  type QueryBuilderConfig,\n  type QueryBuilderState,\n  type QueryCoordinateState,\n  type RecursiveAliasMap,\n  type SelectContext,\n  type UniqueAlias,\n} from \"./types\";\nimport {\n  validateHybridFusionOptions,\n  validateQueryRange,\n  validateQuerySource,\n  validateQueryState,\n  validateSortDirection,\n  validateSqlIdentifier,\n  validateTraversalOptions,\n} from \"./validation\";\n\nfunction resolveAggregateFieldTypeInfo(\n  introspector: SchemaIntrospector,\n  nodeKindNames: readonly string[] | undefined,\n  edgeKindNames: readonly string[] | undefined,\n  path: readonly string[],\n): FieldTypeInfo | undefined {\n  const [propertyName, ...nestedPath] = path;\n  if (propertyName === undefined) return undefined;\n\n  const rootTypeInfo =\n    nodeKindNames === undefined ?\n      edgeKindNames === undefined ?\n        undefined\n      : introspector.getSharedEdgeFieldTypeInfo(edgeKindNames, propertyName)\n    : introspector.getSharedFieldTypeInfo(nodeKindNames, propertyName);\n\n  function resolveNested(\n    current: FieldTypeInfo | undefined,\n    index: number,\n  ): FieldTypeInfo | undefined {\n    const segment = nestedPath[index];\n    return segment === undefined ? current : (\n        resolveNested(current?.shape?.[segment], index + 1)\n      );\n  }\n\n  return resolveNested(rootTypeInfo, 0);\n}\n\n/**\n * Identity-aware traversal option, available only on a graph that declares an\n * identity configuration. On any other graph the property is typed `never`, so\n * setting it is a compile error (and a runtime guard rejects it as well).\n *\n * When `includeIdentityMembers` is true, the traversal's source hop matches an\n * edge attached to *any* coordinate-visible member of the source node's\n * identity class, not just the source node itself. Semantics:\n *\n * - Results are physical rows: the nodes and edges returned are the ones\n *   actually stored, never a synthesized merge of the class.\n * - Identity-class membership is resolved at the query's own coordinate, so a\n *   traversal under `asOf`/`asOfRecorded` follows only the assertions that were\n *   in force at that instant; a retracted assertion stops conducting.\n * - Within a step, physical edge ids are deduplicated. The one exception is a\n *   self-inverse edge between two folded peers (same id, different kind), which\n *   legitimately matches in both directions and is kept.\n * - Under recursion, cycle detection keys on (kind, id) rather than id alone,\n *   so passing through two folded peers is not mistaken for a revisit. Path\n *   output is unaffected: it remains an array of bare node ids.\n */\nexport type IdentityTraversalOption<G extends GraphDef> =\n  G[\"identity\"] extends GraphIdentityConfig ?\n    Readonly<{ includeIdentityMembers?: boolean }>\n  : Readonly<{ includeIdentityMembers?: never }>;\n\ntype DynamicNodeTypeFor<T> =\n  T extends RuntimeNodeKind ? RuntimeNodeTypeFor<T> : DynamicNodeType;\n\ntype DynamicEdgeTypeFor<T> =\n  T extends RuntimeEdgeKind ? RuntimeEdgeTypeFor<T> : DynamicEdgeType;\n\n/**\n * Builds projected fields for a node alias (including all metadata columns).\n */\nfunction buildNodeFields(alias: string): ProjectedField[] {\n  return [\n    {\n      outputName: `${alias}_id`,\n      source: fieldRef(alias, [\"id\"]),\n    },\n    {\n      outputName: `${alias}_kind`,\n      source: fieldRef(alias, [\"kind\"]),\n    },\n    {\n      outputName: `${alias}_props`,\n      source: fieldRef(alias, [\"props\"]),\n    },\n    {\n      outputName: `${alias}_version`,\n      source: fieldRef(alias, [\"version\"]),\n    },\n    {\n      outputName: `${alias}_valid_from`,\n      source: fieldRef(alias, [\"valid_from\"]),\n    },\n    {\n      outputName: `${alias}_valid_to`,\n      source: fieldRef(alias, [\"valid_to\"]),\n    },\n    {\n      outputName: `${alias}_created_at`,\n      source: fieldRef(alias, [\"created_at\"]),\n    },\n    {\n      outputName: `${alias}_updated_at`,\n      source: fieldRef(alias, [\"updated_at\"]),\n    },\n    {\n      outputName: `${alias}_deleted_at`,\n      source: fieldRef(alias, [\"deleted_at\"]),\n    },\n  ];\n}\n\n/**\n * Builds projected fields for an edge alias (including all metadata columns).\n *\n * Edge columns are stored in the traversal's node CTE (e.g., cte_c contains e_id, e_kind, etc.).\n * The nodeCteAlias parameter specifies which CTE contains these columns.\n */\nfunction buildEdgeFields(\n  edgeAlias: string,\n  nodeCteAlias: string,\n): ProjectedField[] {\n  const cteAlias = `cte_${nodeCteAlias}`;\n  return [\n    {\n      outputName: `${edgeAlias}_id`,\n      source: fieldRef(edgeAlias, [\"id\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_kind`,\n      source: fieldRef(edgeAlias, [\"kind\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_from_id`,\n      source: fieldRef(edgeAlias, [\"from_id\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_to_id`,\n      source: fieldRef(edgeAlias, [\"to_id\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_props`,\n      source: fieldRef(edgeAlias, [\"props\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_valid_from`,\n      source: fieldRef(edgeAlias, [\"valid_from\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_valid_to`,\n      source: fieldRef(edgeAlias, [\"valid_to\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_created_at`,\n      source: fieldRef(edgeAlias, [\"created_at\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_updated_at`,\n      source: fieldRef(edgeAlias, [\"updated_at\"]),\n      cteAlias,\n    },\n    {\n      outputName: `${edgeAlias}_deleted_at`,\n      source: fieldRef(edgeAlias, [\"deleted_at\"]),\n      cteAlias,\n    },\n  ];\n}\n\ntype TemporalMethod<\n  G extends GraphDef,\n  Aliases extends AliasMap,\n  EdgeAliases extends EdgeAliasMap,\n  RecursiveAliases extends RecursiveAliasMap,\n  CoordinateState extends QueryCoordinateState,\n> =\n  CoordinateState extends \"open\" ?\n    (\n      mode: TemporalMode,\n      asOf?: string,\n    ) => QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, \"open\">\n  : never;\n\n/**\n * The fluent query builder.\n *\n * Type parameters accumulate as methods are chained:\n * - G: The graph definition\n * - Aliases: Map of alias names to their node kinds\n * - EdgeAliases: Map of alias names to their edge kinds (accumulated during traversals)\n */\nexport class QueryBuilder<\n  G extends GraphDef,\n  Aliases extends AliasMap = EmptyAliasMap,\n  EdgeAliases extends EdgeAliasMap = EmptyEdgeAliasMap,\n  RecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n  CoordinateState extends QueryCoordinateState = \"open\",\n> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: QueryBuilderState;\n  readonly temporal: TemporalMethod<\n    G,\n    Aliases,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  constructor(config: QueryBuilderConfig, state: QueryBuilderState) {\n    validateQueryState(state);\n    this.#config = config;\n    this.#state = state;\n    this.temporal = ((mode, asOf) =>\n      this.#setTemporal(mode, asOf)) as TemporalMethod<\n      G,\n      Aliases,\n      EdgeAliases,\n      RecursiveAliases,\n      CoordinateState\n    >;\n  }\n\n  /**\n   * Sets temporal mode.\n   *\n   * @param mode - The temporal mode to use\n   * @param asOf - Required timestamp for \"asOf\" mode (ISO 8601 string).\n   *   Rejected for every other mode — pinning an instant is only meaningful\n   *   in \"asOf\" mode, so `temporal(\"current\", t)` is a caller error, not a\n   *   silently-dropped argument.\n   * @throws ValidationError if mode is \"asOf\" but no timestamp is provided, or\n   *   if an asOf is supplied with a non-\"asOf\" mode.\n   */\n  #setTemporal(\n    mode: TemporalMode,\n    asOf?: string,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, \"open\"> {\n    const { sealedCoordinate } = getQueryBuilderInternalContext(this.#config);\n    if (sealedCoordinate !== undefined) {\n      const coordinate = sealedCoordinate;\n      throw new ConfigurationError(\n        `.temporal() is not available on a StoreView query — the view's ` +\n          `temporal coordinate (${describeCoordinate(coordinate)}) is sealed. ` +\n          `Re-coordinate on the live Store via store.query() or store.view(...).`,\n        {\n          code: \"STORE_VIEW_SEALED_QUERY\",\n          ...coordinateContext(coordinate),\n          requestedMode: mode,\n        },\n      );\n    }\n    const coordinate = resolveReadCoordinate(\n      mode,\n      asOf,\n      `Use .temporal(\"asOf\", \"2024-01-15T10:00:00.000Z\") or .temporal(\"current\") for current time.`,\n    );\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      temporalMode: coordinate.valid.mode,\n      asOf: coordinate.valid.asOf,\n    });\n  }\n\n  /**\n   * Starts a query from one kind or a nonempty explicit list of kinds.\n   * Lists scan exactly the requested kinds; duplicates are normalized.\n   * Properties used in predicates and expressions must be shared by all kinds.\n   *\n   * @param kind - The node kind to start from\n   * @param alias - A unique alias for this node (compile-time error if duplicate)\n   */\n  from<\n    const Kinds extends readonly [\n      keyof G[\"nodes\"] & string,\n      ...(keyof G[\"nodes\"] & string)[],\n    ],\n    A extends string,\n  >(\n    kinds: Kinds,\n    alias: UniqueAlias<A, Aliases>,\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<G[\"nodes\"][Kinds[number]][\"type\"]>>,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  from<K extends keyof G[\"nodes\"] & string, A extends string>(\n    kind: K,\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: false },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<G[\"nodes\"][K][\"type\"]>>,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  from<K extends keyof G[\"nodes\"] & string, A extends string>(\n    kind: K,\n    alias: UniqueAlias<A, Aliases>,\n    options: { includeSubClasses: true },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias>,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  from<K extends keyof G[\"nodes\"] & string, A extends string>(\n    kind: K | readonly K[],\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: boolean },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias>,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  > {\n    validateQuerySource(this.#state, true);\n    // Validate alias to prevent SQL injection\n    validateSqlIdentifier(alias);\n    const explicitKinds = typeof kind !== \"string\";\n    if (explicitKinds && options !== undefined) {\n      throw new ConfigurationError(\n        \"An explicit source kind list does not accept from() options.\",\n      );\n    }\n    const requestedKinds =\n      typeof kind === \"string\" ? [kind] : [...new Set(kind)];\n    if (requestedKinds.length === 0) {\n      throw new ConfigurationError(\n        \"from() requires a nonempty source kind list.\",\n      );\n    }\n    for (const requestedKind of requestedKinds) {\n      if (!this.#config.registry.hasNodeType(requestedKind)) {\n        throw new KindNotFoundError(requestedKind, \"node\", {\n          graphId: this.#config.graphId,\n        });\n      }\n    }\n    const includeSubClasses = options?.includeSubClasses ?? false;\n    const kinds =\n      typeof kind === \"string\" && includeSubClasses ?\n        this.#config.registry.expandSubClasses(kind)\n      : requestedKinds;\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      startAlias: alias,\n      currentAlias: alias,\n      startKinds: kinds,\n      includeSubClasses,\n    };\n\n    return new QueryBuilder(this.#config, newState);\n  }\n\n  /**\n   * Runtime-kind sibling of `from`; accepts a kind name or Store-issued token.\n   * Throws `KindNotFoundError` if the kind is not registered. String-keyed\n   * predicates use the `n.field(\"name\").number().gte(...)` discriminator.\n   */\n  fromDynamic<T extends string | RuntimeNodeKind, A extends string>(\n    kind: T,\n    alias: UniqueAlias<A, Aliases>,\n    options?: { includeSubClasses?: boolean },\n  ): QueryBuilder<\n    G,\n    Aliases & Record<A, NodeAlias<DynamicNodeTypeFor<T>>>,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  > {\n    validateQuerySource(this.#state, true);\n    validateSqlIdentifier(alias);\n    const kindName = resolveRuntimeKindInput(\n      kind,\n      \"node\",\n      getQueryBuilderInternalContext(this.#config).runtimeKindTokenResolver,\n    );\n    if (!this.#config.registry.hasNodeType(kindName)) {\n      throw new KindNotFoundError(kindName, \"node\", {\n        graphId: this.#config.graphId,\n      });\n    }\n\n    const includeSubClasses = options?.includeSubClasses ?? false;\n    const kinds =\n      includeSubClasses ?\n        this.#config.registry.expandSubClasses(kindName)\n      : [kindName];\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      startAlias: alias,\n      currentAlias: alias,\n      startKinds: kinds,\n      includeSubClasses,\n      dynamicNodeAliases: new Set([...this.#state.dynamicNodeAliases, alias]),\n    };\n\n    return new QueryBuilder(this.#config, newState);\n  }\n\n  /** Stops a recursive branch at a matching endpoint; stopping endpoints are emitted by default. */\n  stopExpansion<A extends keyof Aliases & string>(\n    alias: A,\n    build: (node: NodeAccessor<Aliases[A][\"type\"]>) => Predicate,\n    options: Readonly<{ emitStopNode?: boolean }> = {},\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    const accessor = this.#createNodeAccessor(alias);\n    const predicate = build(accessor as NodeAccessor<Aliases[A][\"type\"]>);\n    return new QueryBuilder(\n      this.#config,\n      withRecursiveStopExpansion(\n        this.#state,\n        alias,\n        predicate.__expr,\n        options.emitStopNode ?? true,\n      ),\n    );\n  }\n\n  /** Filters completed match rows, preserving optional and recursive expansion semantics. */\n  where(\n    build: (\n      context: QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>,\n    ) => DatabaseExpression<\n      boolean | undefined,\n      (keyof Aliases | keyof EdgeAliases) & string\n    >,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    validateQuerySource(this.#state, false);\n    const expression = build(this.#expressionContext());\n    if (!isDatabaseExpression(expression))\n      throw new ConfigurationError(\n        \"where() requires a Boolean database expression; ranked match helpers belong in whereNode().\",\n      );\n    const predicate = this.#expressionPredicate(expression);\n    const resultPredicate: PredicateExpression =\n      this.#state.resultPredicate === undefined ?\n        predicate\n      : {\n          __type: \"and\",\n          predicates: [this.#state.resultPredicate, predicate],\n        };\n    return new QueryBuilder(this.#config, { ...this.#state, resultPredicate });\n  }\n\n  /**\n   * Adds a WHERE clause for a node.\n   */\n  whereNode<A extends keyof Aliases & string>(\n    alias: A,\n    predicateFunction: (\n      n: NodeAccessor<Aliases[A][\"type\"]>,\n      expressions: QueryExpressionContext<\n        G,\n        Aliases,\n        EdgeAliases,\n        CoordinateState\n      >,\n    ) =>\n      | Predicate\n      | DatabaseExpression<\n          boolean | undefined,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    const accessor = this.#createNodeAccessor(alias);\n    const predicate = predicateFunction(\n      accessor as NodeAccessor<Aliases[A][\"type\"]>,\n      this.#expressionContext(),\n    );\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      predicates: [\n        ...this.#state.predicates,\n        {\n          targetAlias: alias,\n          expression: this.#expressionPredicate(predicate),\n        },\n      ],\n    };\n\n    return new QueryBuilder(this.#config, newState);\n  }\n\n  /**\n   * Adds a WHERE clause for an edge.\n   *\n   * @param alias - The edge alias to filter on\n   * @param predicateFunction - A function that builds predicates using the edge accessor\n   */\n  whereEdge<EA extends keyof EdgeAliases & string>(\n    alias: EA,\n    predicateFunction: (\n      edge: EdgeAccessor<EdgeAliases[EA][\"type\"]>,\n      expressions: QueryExpressionContext<\n        G,\n        Aliases,\n        EdgeAliases,\n        CoordinateState\n      >,\n    ) =>\n      | Predicate\n      | DatabaseExpression<\n          boolean | undefined,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    const accessor = this.#createEdgeAccessor(alias);\n    const predicate = predicateFunction(\n      accessor as EdgeAccessor<EdgeAliases[EA][\"type\"]>,\n      this.#expressionContext(),\n    );\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      predicates: [\n        ...this.#state.predicates,\n        {\n          targetAlias: alias,\n          targetType: \"edge\",\n          expression: this.#expressionPredicate(predicate),\n        },\n      ],\n    };\n\n    return new QueryBuilder(this.#config, newState);\n  }\n\n  /**\n   * Traverses an edge to another node (outgoing direction).\n   *\n   * By default, traverses from the current node (last traversal target, or start node).\n   * Use the `from` option to traverse from a different alias (fan-out pattern).\n   *\n   * @param options.expand - Ontology expansion mode for implying/inverse edges\n   * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n   */\n  traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options?: {\n      direction?: \"out\";\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    \"out\",\n    false,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  /**\n   * Traverses an edge to another node (incoming direction).\n   *\n   * By default, traverses from the current node (last traversal target, or start node).\n   * Use the `from` option to traverse from a different alias (fan-out pattern).\n   *\n   * @param options.direction - Set to \"in\" for incoming edge traversal\n   * @param options.expand - Ontology expansion mode for implying/inverse edges\n   * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n   */\n  traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options: {\n      direction: \"in\";\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    \"in\",\n    false,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options?: {\n      direction?: TraversalDirection;\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    TraversalDirection,\n    false,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  > {\n    // Validate edge alias to prevent SQL injection\n    validateSqlIdentifier(edgeAlias);\n\n    const direction = options?.direction ?? \"out\";\n    this.#assertIdentityTraversalAllowed(options);\n    const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n    validateQuerySource(this.#state, false);\n    validateTraversalOptions(direction, expansion);\n    const includeImplyingEdges =\n      expansion === \"implying\" || expansion === \"all\";\n    const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n    // Use explicit `from` if provided, otherwise chain from currentAlias\n    const fromAlias = options?.from ?? this.#state.currentAlias;\n\n    // Expand edge kinds if including implying edges\n    const edgeKinds = this.#expandTraversalEdgeKinds(\n      edgeKind,\n      includeImplyingEdges,\n    );\n    const inverseEdgeKinds =\n      includeInverseEdges ?\n        this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n      : [];\n\n    return new TraversalBuilder<\n      G,\n      Aliases,\n      EdgeAliases,\n      EK,\n      EA,\n      TraversalDirection,\n      false,\n      false,\n      false,\n      RecursiveAliases,\n      CoordinateState\n    >(\n      this.#config,\n      this.#state,\n      edgeKinds,\n      edgeAlias,\n      direction,\n      fromAlias,\n      inverseEdgeKinds,\n      false,\n      undefined, // variableLength — default\n      undefined, // pendingEdgePredicates — default\n      options?.includeIdentityMembers ?? false,\n    );\n  }\n\n  /**\n   * Runtime-kind sibling of `traverse`; accepts a kind name or Store-issued\n   * token. Throws `KindNotFoundError` if the edge kind is not registered.\n   */\n  traverseDynamic<T extends string | RuntimeEdgeKind, EA extends string>(\n    edgeKind: T,\n    edgeAlias: EA,\n    options?: {\n      direction?: TraversalDirection;\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeTypeFor<T>>>,\n    string,\n    EA,\n    TraversalDirection,\n    false,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState,\n    DynamicEdgeTypeFor<T>\n  > {\n    return this.#beginDynamicTraversal(edgeKind, edgeAlias, false, options);\n  }\n\n  /**\n   * Optionally traverses an edge to another node (LEFT JOIN semantics).\n   * If no matching edge/node exists, the result will include null values.\n   *\n   * By default, traverses from the current node (last traversal target, or start node).\n   * Use the `from` option to traverse from a different alias (fan-out pattern).\n   *\n   * @param options.direction - Direction of traversal: \"out\" (default) or \"in\"\n   * @param options.expand - Ontology expansion mode for implying/inverse edges\n   * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n   */\n  optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options?: {\n      direction?: \"out\";\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    \"out\",\n    true,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options: {\n      direction: \"in\";\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    \"in\",\n    true,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  >;\n\n  optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n    edgeKind: EK,\n    edgeAlias: EA,\n    options?: {\n      direction?: TraversalDirection;\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    EK,\n    EA,\n    TraversalDirection,\n    true,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState\n  > {\n    // Validate edge alias to prevent SQL injection\n    validateSqlIdentifier(edgeAlias);\n\n    const direction = options?.direction ?? \"out\";\n    this.#assertIdentityTraversalAllowed(options);\n    const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n    validateQuerySource(this.#state, false);\n    validateTraversalOptions(direction, expansion);\n    const includeImplyingEdges =\n      expansion === \"implying\" || expansion === \"all\";\n    const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n    // Use explicit `from` if provided, otherwise chain from currentAlias\n    const fromAlias = options?.from ?? this.#state.currentAlias;\n\n    // Expand edge kinds if including implying edges\n    const edgeKinds = this.#expandTraversalEdgeKinds(\n      edgeKind,\n      includeImplyingEdges,\n    );\n    const inverseEdgeKinds =\n      includeInverseEdges ?\n        this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n      : [];\n\n    return new TraversalBuilder<\n      G,\n      Aliases,\n      EdgeAliases,\n      EK,\n      EA,\n      TraversalDirection,\n      true,\n      false,\n      false,\n      RecursiveAliases,\n      CoordinateState\n    >(\n      this.#config,\n      this.#state,\n      edgeKinds,\n      edgeAlias,\n      direction,\n      fromAlias,\n      inverseEdgeKinds,\n      true,\n      undefined, // variableLength — default\n      undefined, // pendingEdgePredicates — default\n      options?.includeIdentityMembers ?? false,\n    );\n  }\n\n  /**\n   * Runtime-kind sibling of `optionalTraverse`; accepts a kind name or\n   * Store-issued token. LEFT JOIN semantics — non-matching rows produce a null\n   * edge alias instead of dropping. Throws `KindNotFoundError` if the edge kind\n   * is not registered.\n   */\n  optionalTraverseDynamic<\n    T extends string | RuntimeEdgeKind,\n    EA extends string,\n  >(\n    edgeKind: T,\n    edgeAlias: EA,\n    options?: {\n      direction?: TraversalDirection;\n      expand?: TraversalExpansion;\n      from?: keyof Aliases & string;\n    } & IdentityTraversalOption<G>,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeTypeFor<T>, true>>,\n    string,\n    EA,\n    TraversalDirection,\n    true,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState,\n    DynamicEdgeTypeFor<T>\n  > {\n    return this.#beginDynamicTraversal(edgeKind, edgeAlias, true, options);\n  }\n\n  /**\n   * Shared body for `traverseDynamic` and `optionalTraverseDynamic`.\n   * The only difference is the `optional` flag passed to the\n   * `TraversalBuilder` constructor.\n   */\n  #beginDynamicTraversal<\n    T extends string | RuntimeEdgeKind,\n    EA extends string,\n    Optional extends boolean,\n  >(\n    edgeKind: T,\n    edgeAlias: EA,\n    optional: Optional,\n    options:\n      | ({\n          direction?: TraversalDirection;\n          expand?: TraversalExpansion;\n          from?: keyof Aliases & string;\n          includeIdentityMembers?: boolean;\n        } & IdentityTraversalOption<G>)\n      | undefined,\n  ): TraversalBuilder<\n    G,\n    Aliases,\n    EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeTypeFor<T>, Optional>>,\n    string,\n    EA,\n    TraversalDirection,\n    Optional,\n    false,\n    false,\n    RecursiveAliases,\n    CoordinateState,\n    DynamicEdgeTypeFor<T>\n  > {\n    validateSqlIdentifier(edgeAlias);\n    const edgeKindName = resolveRuntimeKindInput(\n      edgeKind,\n      \"edge\",\n      getQueryBuilderInternalContext(this.#config).runtimeKindTokenResolver,\n    );\n    if (!this.#config.registry.hasEdgeType(edgeKindName)) {\n      throw new KindNotFoundError(edgeKindName, \"edge\", {\n        graphId: this.#config.graphId,\n      });\n    }\n\n    const direction = options?.direction ?? \"out\";\n    this.#assertIdentityTraversalAllowed(options);\n    const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n    validateQuerySource(this.#state, false);\n    validateTraversalOptions(direction, expansion);\n    const includeImplyingEdges =\n      expansion === \"implying\" || expansion === \"all\";\n    const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n    const fromAlias = options?.from ?? this.#state.currentAlias;\n\n    const edgeKinds = this.#expandTraversalEdgeKinds(\n      edgeKindName,\n      includeImplyingEdges,\n    );\n    const inverseEdgeKinds =\n      includeInverseEdges ?\n        this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n      : [];\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      dynamicEdgeAliases: new Set([\n        ...this.#state.dynamicEdgeAliases,\n        edgeAlias,\n      ]),\n    };\n\n    return new TraversalBuilder<\n      G,\n      Aliases,\n      EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeTypeFor<T>, Optional>>,\n      string,\n      EA,\n      TraversalDirection,\n      Optional,\n      false,\n      false,\n      RecursiveAliases,\n      CoordinateState,\n      DynamicEdgeTypeFor<T>\n    >(\n      this.#config,\n      newState,\n      edgeKinds,\n      edgeAlias,\n      direction,\n      fromAlias,\n      inverseEdgeKinds,\n      optional,\n      undefined, // variableLength — default\n      undefined, // pendingEdgePredicates — default\n      options?.includeIdentityMembers ?? false,\n    );\n  }\n\n  /** @internal Identifies this query's lexical expression scope. */\n  getExpressionScopeIdentity(): symbol {\n    return getExpressionScope(this.#config);\n  }\n\n  #expressionPredicate(\n    predicate: Predicate | DatabaseExpression<boolean | undefined>,\n  ): PredicateExpression {\n    if (\"__expr\" in predicate) return predicate.__expr;\n    assertExpressionScope(predicate, this.getExpressionScopeIdentity());\n    if (predicate.valueType !== \"boolean\")\n      throw new ConfigurationError(\n        \"A predicate requires a Boolean database expression.\",\n      );\n    return { __type: \"database_expression_predicate\", expression: predicate };\n  }\n\n  #expressionContext(): QueryExpressionContext<\n    G,\n    Aliases,\n    EdgeAliases,\n    CoordinateState\n  > {\n    const aliases = createExpressionAliasContext<Aliases, EdgeAliases>(\n      this.#config,\n      this.#state,\n    );\n    const helpers = createExpressionSubqueryHelpers<\n      QueryBuilder<\n        G,\n        EmptyAliasMap,\n        EmptyEdgeAliasMap,\n        EmptyRecursiveAliasMap,\n        CoordinateState\n      >,\n      ExpressionAliasContext<Aliases, EdgeAliases, never>,\n      (keyof Aliases | keyof EdgeAliases) & string\n    >({\n      parentScopeIdentity: this.getExpressionScopeIdentity(),\n      parentProvenance: {\n        graphId: this.#config.graphId,\n        executionTarget:\n          this.#config.backend === undefined ?\n            undefined\n          : backendDerivationRoot(this.#config.backend),\n      },\n      parentCoordinate: buildQueryAst(this.#config, this.#state),\n      createSubquery: () => {\n        const { resultPredicate: _resultPredicate, ...subqueryState } =\n          this.#state;\n        const config = { ...this.#config };\n        registerQueryBuilderInternalContext(\n          config,\n          getQueryBuilderInternalContext(this.#config),\n        );\n        return new QueryBuilder(config, {\n          ...subqueryState,\n          startAlias: \"\",\n          currentAlias: \"\",\n          startKinds: [],\n          traversals: [],\n          predicates: [],\n          projection: [],\n          orderBy: [],\n          aggregateOrderBy: [],\n          groupBy: undefined,\n          having: undefined,\n          limit: undefined,\n          offset: undefined,\n          fusion: undefined,\n          dynamicNodeAliases: new Set(),\n          dynamicEdgeAliases: new Set(),\n        });\n      },\n      createOuterContext: (childScope) =>\n        createExpressionAliasContext<Aliases, EdgeAliases, never>(\n          this.#config,\n          this.#state,\n          (expression) =>\n            createOuterReferenceExpression(expression, childScope),\n        ),\n    });\n    return new Proxy(helpers, {\n      get(target, key, receiver) {\n        if (key === \"$exists\" || key === \"$scalar\")\n          return Reflect.get(target, key, receiver);\n        return Reflect.get(aliases, key);\n      },\n    }) as QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>;\n  }\n\n  /** Projects database expressions; the callback runs once when building the query. */\n  project<\n    const Fields extends Readonly<\n      Record<\n        string,\n        DatabaseExpression<\n          unknown,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >\n      >\n    >,\n  >(\n    build: (\n      context: QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>,\n    ) => Fields,\n  ): ExecutableProjectionQuery<\n    Fields,\n    QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>\n  > {\n    return this.#project(build(this.#expressionContext()));\n  }\n\n  #project<Fields extends DatabaseProjection>(\n    fields: Fields,\n  ): ExecutableProjectionQuery<\n    Fields,\n    QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>\n  > {\n    if (Object.getOwnPropertySymbols(fields).length > 0)\n      throw new ConfigurationError(\"Projection output names must be strings.\");\n    const entries = Object.entries(fields);\n    if (entries.length === 0)\n      throw new ConfigurationError(\n        \"project() requires at least one database expression.\",\n      );\n    const projection = entries.map(([outputName, source]) => {\n      validateSqlIdentifier(outputName);\n      if (\n        outputName.startsWith(\"__tg_\") ||\n        outputName === \"typegraphschemaversion\"\n      )\n        throw new ConfigurationError(\"Projection output name is reserved.\");\n      if (!isDatabaseExpression(source))\n        throw new ConfigurationError(\n          \"project() accepts database expressions; use expr.literal() for constants.\",\n        );\n      assertExpressionScope(source, this.getExpressionScopeIdentity());\n      return { outputName, source };\n    });\n    return new ExecutableProjectionQuery(\n      this.#config,\n      { ...this.#state, projection },\n      fields,\n      () => this.#expressionContext(),\n    );\n  }\n\n  /** Counts match rows (or groups), preserving offset and limit. */\n  count(): Promise<number> {\n    return executeQueryTerminal(this.#config, this.#state, \"count\");\n  }\n\n  /** Tests whether the bounded relation contains a row. */\n  async exists(): Promise<boolean> {\n    return (\n      (await executeQueryTerminal(this.#config, this.#state, \"exists\")) > 0\n    );\n  }\n\n  /**\n   * Selects fields to return.\n   */\n  select<R>(\n    selectFunction: (\n      context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n    ) => R,\n  ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n    // For now, project all fields from all aliases\n    // A more sophisticated implementation would parse the selectFn\n\n    // Start node fields (including metadata)\n    const startFields = buildNodeFields(this.#state.startAlias);\n\n    // Traversal node and edge fields (including metadata)\n    // Edge fields are in the node's CTE, so we pass the node alias for CTE reference\n    const traversalFields = this.#state.traversals.flatMap((traversal) => [\n      ...buildEdgeFields(traversal.edgeAlias, traversal.nodeAlias),\n      ...buildNodeFields(traversal.nodeAlias),\n    ]);\n\n    const projection = [...startFields, ...traversalFields];\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      projection,\n    };\n\n    return new ExecutableQuery(this.#config, newState, selectFunction);\n  }\n\n  /**\n   * Selects fields including aggregates.\n   * Use with groupBy() for aggregate queries.\n   *\n   * @param fields - Object mapping output names to field refs or aggregate expressions\n   */\n  aggregate<\n    const Fields extends Readonly<\n      Record<\n        string,\n        DatabaseExpression<\n          unknown,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >\n      >\n    >,\n  >(\n    build: (\n      context: QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>,\n    ) => Fields,\n  ): ExecutableProjectionQuery<\n    Fields,\n    QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>\n  >;\n  aggregate<R extends Record<string, FieldRef | AggregateExpr>>(\n    fields: R,\n  ): ExecutableAggregateQuery<G, Aliases & EdgeAliases, R>;\n  aggregate<\n    R extends Record<string, FieldRef | AggregateExpr>,\n    Fields extends DatabaseProjection,\n  >(\n    fields:\n      | R\n      | ((\n          context: QueryExpressionContext<\n            G,\n            Aliases,\n            EdgeAliases,\n            CoordinateState\n          >,\n        ) => Fields),\n  ):\n    | ExecutableAggregateQuery<G, Aliases & EdgeAliases, R>\n    | ExecutableProjectionQuery<\n        Fields,\n        QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>\n      > {\n    if (typeof fields === \"function\")\n      return this.#project(fields(this.#expressionContext()));\n\n    const resolvedFields = Object.fromEntries(\n      Object.entries(fields).map(([outputName, source]) => {\n        const fieldRef = source.__type === \"aggregate\" ? source.field : source;\n\n        if (\n          fieldRef.path.length !== 1 ||\n          fieldRef.path[0] !== \"props\" ||\n          fieldRef.jsonPointer === undefined\n        ) {\n          return [outputName, source];\n        }\n\n        const segments = parseJsonPointer(fieldRef.jsonPointer);\n        if (segments.length === 0) {\n          return [outputName, source];\n        }\n\n        const nodeKindNames = this.#getKindNamesForAlias(fieldRef.alias);\n        const edgeKindNames = this.#getEdgeKindNamesForAlias(fieldRef.alias);\n        const typeInfo = resolveAggregateFieldTypeInfo(\n          this.#config.schemaIntrospector,\n          nodeKindNames,\n          edgeKindNames,\n          segments,\n        );\n\n        if (!typeInfo) {\n          if (source.__type === \"aggregate\") validateAggregateOperand(source);\n          return [outputName, source];\n        }\n\n        if (source.__type === \"aggregate\") {\n          validateAggregateOperand(source, typeInfo.valueType);\n        }\n\n        const resolvedField = {\n          ...fieldRef,\n          valueType: typeInfo.valueType,\n          elementType: typeInfo.elementType,\n        } satisfies FieldRef;\n\n        return source.__type === \"aggregate\" ?\n            [outputName, { ...source, field: resolvedField }]\n          : [outputName, resolvedField];\n      }),\n    ) as R;\n\n    const projection: ProjectedField[] = Object.entries(resolvedFields).map(\n      ([outputName, source]) => {\n        const sourceAlias =\n          source.__type === \"aggregate\" ? source.field.alias : source.alias;\n        const edgeTraversal = this.#state.traversals.find(\n          (traversal) => traversal.edgeAlias === sourceAlias,\n        );\n        return edgeTraversal === undefined ?\n            { outputName, source }\n          : {\n              outputName,\n              source,\n              cteAlias: `cte_${edgeTraversal.nodeAlias}`,\n            };\n      },\n    );\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      projection,\n    };\n\n    return new ExecutableAggregateQuery(this.#config, newState, resolvedFields);\n  }\n\n  /**\n   * Orders results.\n   */\n  orderBy(\n    build: (\n      context: QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>,\n    ) => DatabaseExpression<\n      unknown,\n      (keyof Aliases | keyof EdgeAliases) & string\n    >,\n    direction?: SortDirection,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState>;\n  orderBy<A extends (keyof Aliases | keyof EdgeAliases) & string>(\n    alias: A,\n    field: string,\n    direction?: SortDirection,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState>;\n  orderBy(\n    alias:\n      | ((\n          context: QueryExpressionContext<\n            G,\n            Aliases,\n            EdgeAliases,\n            CoordinateState\n          >,\n        ) => DatabaseExpression)\n      | ((keyof Aliases | keyof EdgeAliases) & string),\n    field?: string,\n    direction: SortDirection = \"asc\",\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    if (typeof alias === \"function\") {\n      const expression = alias(this.#expressionContext());\n      assertExpressionScope(expression, this.getExpressionScopeIdentity());\n      const sort = field ?? \"asc\";\n      validateSortDirection(sort);\n      return new QueryBuilder(this.#config, {\n        ...this.#state,\n        orderBy: [\n          ...this.#state.orderBy,\n          { field: expression, direction: sort },\n        ],\n      });\n    }\n    if (field === undefined)\n      throw new ConfigurationError(\"orderBy() requires a field.\");\n    validateSortDirection(direction);\n    const edgeKindNames = this.#getEdgeKindNamesForAlias(alias);\n    const isEdge = edgeKindNames !== undefined;\n    const nodeKindNames =\n      isEdge ? undefined : this.#getKindNamesForAlias(alias);\n    const hasDeclaredProperty =\n      isEdge ?\n        this.#config.schemaIntrospector.hasDeclaredEdgeField(\n          edgeKindNames,\n          field,\n        )\n      : nodeKindNames !== undefined &&\n        this.#config.schemaIntrospector.hasDeclaredField(nodeKindNames, field);\n    const systemField = resolveSystemOrderField(\n      alias,\n      field,\n      isEdge,\n      hasDeclaredProperty,\n    );\n    let typeInfo: FieldTypeInfo | undefined;\n    if (systemField === undefined) {\n      typeInfo =\n        isEdge ?\n          this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n            edgeKindNames,\n            field,\n          )\n        : nodeKindNames === undefined ? undefined\n        : this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n            nodeKindNames,\n            field,\n          );\n      assertSharedNodeField(nodeKindNames, field, typeInfo);\n    }\n    const orderSpec = buildOrderSpec(\n      alias,\n      field,\n      direction,\n      systemField,\n      typeInfo,\n    );\n\n    const newState: QueryBuilderState = {\n      ...this.#state,\n      orderBy: [...this.#state.orderBy, orderSpec],\n    };\n\n    return new QueryBuilder(this.#config, newState);\n  }\n\n  /**\n   * Limits the number of results.\n   */\n  limit(\n    n: number,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    validateQueryRange(n, \"limit\");\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      limit: n,\n    });\n  }\n\n  /**\n   * Offsets the results.\n   */\n  offset(\n    n: number,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    validateQueryRange(n, \"offset\");\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      offset: n,\n    });\n  }\n\n  /**\n   * Groups results by the specified field.\n   * Use with aggregate functions like COUNT, SUM, AVG in select().\n   *\n   * @param alias - The node alias to group by\n   * @param field - The field name to group by\n   */\n  groupBy(\n    build: (\n      context: QueryExpressionContext<G, Aliases, EdgeAliases, CoordinateState>,\n    ) =>\n      | DatabaseExpression<\n          unknown,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >\n      | readonly DatabaseExpression<\n          unknown,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >[],\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState>;\n  groupBy<A extends keyof Aliases & string>(\n    alias: A,\n    field: string,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState>;\n  groupBy(\n    alias:\n      | (keyof Aliases & string)\n      | ((\n          context: QueryExpressionContext<\n            G,\n            Aliases,\n            EdgeAliases,\n            CoordinateState\n          >,\n        ) => DatabaseExpression | readonly DatabaseExpression[]),\n    field?: string,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    if (typeof alias === \"function\") {\n      const value = alias(this.#expressionContext());\n      const fields: readonly DatabaseExpression[] =\n        Array.isArray(value) ? value : [value as DatabaseExpression];\n      if (fields.length === 0)\n        throw new ConfigurationError(\n          \"groupBy() requires at least one database expression.\",\n        );\n      for (const expression of fields)\n        assertExpressionScope(expression, this.getExpressionScopeIdentity());\n      return new QueryBuilder(this.#config, {\n        ...this.#state,\n        groupBy: {\n          fields: [...(this.#state.groupBy?.fields ?? []), ...fields],\n        },\n      });\n    }\n    if (field === undefined)\n      throw new ConfigurationError(\"groupBy() requires a field.\");\n    const kindNames = this.#getKindNamesForAlias(alias);\n    const typeInfo =\n      kindNames ?\n        this.#config.schemaIntrospector.getSharedFieldTypeInfo(kindNames, field)\n      : undefined;\n    assertSharedNodeField(kindNames, field, typeInfo);\n\n    const fieldRefValue: FieldRef = {\n      __type: \"field_ref\",\n      alias,\n      path: [\"props\"],\n      jsonPointer: jsonPointer([field]),\n      valueType: typeInfo?.valueType,\n      elementType: typeInfo?.elementType,\n    };\n\n    const existingFields = this.#state.groupBy?.fields ?? [];\n    const newGroupBy: GroupBySpec = {\n      fields: [...existingFields, fieldRefValue],\n    };\n\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      groupBy: newGroupBy,\n    });\n  }\n\n  /**\n   * Groups results by the node ID.\n   * Use when you want to group by a complete node rather than a specific field.\n   *\n   * @param alias - The node alias to group by (uses the node's ID)\n   */\n  groupByNode<A extends keyof Aliases & string>(\n    alias: A,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    const fieldRefValue: FieldRef = {\n      __type: \"field_ref\",\n      alias,\n      path: [\"id\"],\n      valueType: \"string\",\n    };\n\n    const existingFields = this.#state.groupBy?.fields ?? [];\n    const newGroupBy: GroupBySpec = {\n      fields: [...existingFields, fieldRefValue],\n    };\n\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      groupBy: newGroupBy,\n    });\n  }\n\n  /**\n   * Filters grouped results using aggregate conditions (HAVING clause).\n   * Use after groupBy() to filter based on aggregate values.\n   *\n   * @param predicate - A predicate expression to filter groups\n   */\n  having(\n    predicateOrBuild:\n      | PredicateExpression\n      | ((\n          context: QueryExpressionContext<\n            G,\n            Aliases,\n            EdgeAliases,\n            CoordinateState\n          >,\n        ) => DatabaseExpression<\n          boolean | undefined,\n          (keyof Aliases | keyof EdgeAliases) & string\n        >),\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    const predicate =\n      typeof predicateOrBuild === \"function\" ?\n        this.#expressionPredicate(predicateOrBuild(this.#expressionContext()))\n      : predicateOrBuild;\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      having:\n        this.#state.having === undefined ?\n          predicate\n        : { __type: \"and\", predicates: [this.#state.having, predicate] },\n    });\n  }\n\n  /**\n   * Sets fusion parameters for hybrid (vector + fulltext) queries.\n   *\n   * Applies only when the query contains both a `.similarTo()` and a\n   * `.$fulltext.matches()` predicate. Without this call, the default is\n   * RRF with k=60 and equal weights. A mismatch between `.fuseWith()`\n   * configuration and the predicates on the query is caught during\n   * compilation, not here.\n   *\n   * @example\n   * ```typescript\n   * store.query()\n   *   .from(\"Document\", \"d\")\n   *   .whereNode(\"d\", d =>\n   *     d.$fulltext.matches(\"renewable energy\", 50)\n   *       .and(d.embedding.similarTo(vec, 50))\n   *       .and(d.tenantId.eq(tenant))\n   *   )\n   *   .fuseWith({ k: 60, weights: { fulltext: 1.5 } })\n   *   .limit(10)\n   *   .execute();\n   * ```\n   */\n  fuseWith(\n    options: HybridFusionOptions,\n  ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n    validateHybridFusionOptions(options);\n    return new QueryBuilder(this.#config, {\n      ...this.#state,\n      fusion: options,\n    });\n  }\n\n  /**\n   * Applies a query fragment to transform this builder.\n   *\n   * Fragments are reusable query transformations that can add predicates,\n   * traversals, ordering, and other query operations. Use this for\n   * composing complex queries from simpler, reusable parts.\n   *\n   * @example\n   * ```typescript\n   * // Define a reusable fragment\n   * const activeUsers = createFragment<MyGraph>()((q) =>\n   *   q.whereNode(\"u\", ({ status }) => status.eq(\"active\"))\n   * );\n   *\n   * // Apply the fragment\n   * const results = await query()\n   *   .from(\"User\", \"u\")\n   *   .pipe(activeUsers)\n   *   .select((ctx) => ctx.u)\n   *   .execute();\n   * ```\n   *\n   * @param fragment - A function that transforms the builder\n   * @returns The transformed builder\n   */\n  pipe<\n    OutAliases extends AliasMap,\n    OutEdgeAliases extends EdgeAliasMap = EdgeAliases,\n    OutRecAliases extends RecursiveAliasMap = RecursiveAliases,\n  >(\n    fragment: (\n      builder: QueryBuilder<\n        G,\n        Aliases,\n        EdgeAliases,\n        RecursiveAliases,\n        CoordinateState\n      >,\n    ) => QueryBuilder<\n      G,\n      OutAliases,\n      OutEdgeAliases,\n      OutRecAliases,\n      CoordinateState\n    >,\n  ): QueryBuilder<\n    G,\n    OutAliases,\n    OutEdgeAliases,\n    OutRecAliases,\n    CoordinateState\n  > {\n    return fragment(this);\n  }\n\n  /**\n   * Gets all kind names for an alias.\n   */\n  #getKindNamesForAlias(alias: string): readonly string[] | undefined {\n    if (alias === this.#state.startAlias) {\n      return this.#state.startKinds;\n    }\n    for (const traversal of this.#state.traversals) {\n      if (traversal.nodeAlias === alias) {\n        return traversal.nodeKinds;\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * Determines the appropriate field builder based on Zod schema type.\n   */\n  #getFieldBuilderForProperty(\n    kindNames: readonly string[] | undefined,\n    property: string,\n    alias: string,\n  ): BaseFieldAccessor {\n    const typeInfo =\n      kindNames ?\n        this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n          kindNames,\n          property,\n        )\n      : undefined;\n\n    assertSharedNodeField(kindNames, property, typeInfo);\n    const ref = fieldRef(alias, [\"props\"], {\n      jsonPointer: jsonPointer([property]),\n      valueType: typeInfo?.valueType,\n      elementType: typeInfo?.elementType,\n    });\n\n    return this.#buildFieldBuilderForTypeInfo(ref, typeInfo);\n  }\n\n  #buildFieldBuilderForTypeInfo(\n    ref: ReturnType<typeof fieldRef>,\n    typeInfo: FieldTypeInfo | undefined,\n  ): BaseFieldAccessor {\n    return buildFieldBuilderForTypeInfo(ref, typeInfo);\n  }\n\n  #createNodeAccessor(alias: string): NodeAccessor<NodeType> {\n    const kindNames = this.#getKindNamesForAlias(alias);\n    const idAccessor = stringField(\n      fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n    );\n    const kindAccessor = stringField(\n      fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n    );\n    const fulltextAccessor = createFulltextAccessor(alias, () =>\n      this.#hasSearchableField(kindNames),\n    );\n\n    if (this.#state.dynamicNodeAliases.has(alias)) {\n      return {\n        id: idAccessor,\n        kind: kindAccessor,\n        $fulltext: fulltextAccessor,\n        field: (name: string) =>\n          createDynamicFieldBuilder(\n            this.#config.schemaIntrospector,\n            alias,\n            name,\n            kindNames,\n            \"node\",\n          ),\n      } as unknown as NodeAccessor<NodeType>;\n    }\n\n    // Use a Proxy to provide flattened property access\n    return new Proxy({} as NodeAccessor<NodeType>, {\n      get: (_, property: string | symbol) => {\n        // Handle symbols and special properties to avoid infinite loops\n        if (typeof property === \"symbol\") return;\n\n        // System fields\n        if (property === \"id\") return idAccessor;\n        if (property === \"kind\") return kindAccessor;\n        if (property === \"$fulltext\") return fulltextAccessor;\n\n        // A DECLARED field wins over the interop exemption: `toJSON` and `then`\n        // are legal schema field names, and the accessor type offers them, so\n        // resolving them to `undefined` here made a declared field\n        // unaddressable in a predicate. Only an UNDECLARED probe resolves to\n        // `undefined`, keeping the accessor safe to await or stringify.\n        if (\n          isInteropProbeKey(property) &&\n          !(\n            kindNames !== undefined &&\n            this.#config.schemaIntrospector.hasDeclaredField(\n              kindNames,\n              property,\n            )\n          )\n        ) {\n          return;\n        }\n\n        // Schema properties\n        return this.#getFieldBuilderForProperty(kindNames, property, alias);\n      },\n    });\n  }\n\n  #hasSearchableField(kindNames: readonly string[] | undefined): boolean {\n    if (!kindNames) return false;\n    return this.#config.schemaIntrospector.hasSearchableField(kindNames);\n  }\n\n  /**\n   * Guards `includeIdentityMembers` against a non-identity-enabled builder.\n   */\n  #assertIdentityTraversalAllowed(\n    options: Readonly<{ includeIdentityMembers?: boolean }> | undefined,\n  ): void {\n    if (!options?.includeIdentityMembers || this.#config.identityEnabled) {\n      return;\n    }\n    throw new ConfigurationError(\n      \"includeIdentityMembers requires an identity-enabled graph registry.\",\n      { code: \"IDENTITY_NOT_ENABLED\", graphId: this.#config.graphId },\n      {\n        suggestion:\n          \"Enable defineGraph(...).identity and build the registry from that graph.\",\n      },\n    );\n  }\n\n  #expandTraversalEdgeKinds(\n    edgeKind: string,\n    includeImplyingEdges: boolean,\n  ): readonly string[] {\n    return includeImplyingEdges ?\n        this.#config.registry.expandImplyingEdges(edgeKind)\n      : [edgeKind];\n  }\n\n  #expandInverseTraversalEdgeKinds(\n    edgeKinds: readonly string[],\n    includeImplyingEdges: boolean,\n  ): readonly string[] {\n    const inverseKinds = new Set<string>();\n\n    for (const kind of edgeKinds) {\n      const inverseKind = this.#config.registry.getInverseEdge(kind);\n      if (inverseKind === undefined) {\n        continue;\n      }\n\n      inverseKinds.add(inverseKind);\n\n      if (!includeImplyingEdges) {\n        continue;\n      }\n\n      for (const implyingKind of this.#config.registry.expandImplyingEdges(\n        inverseKind,\n      )) {\n        inverseKinds.add(implyingKind);\n      }\n    }\n\n    return [...inverseKinds];\n  }\n\n  /**\n   * Gets edge kind names for an edge alias.\n   */\n  #getEdgeKindNamesForAlias(alias: string): readonly string[] | undefined {\n    for (const traversal of this.#state.traversals) {\n      if (traversal.edgeAlias === alias) {\n        return mergeEdgeKinds(traversal);\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * Determines the appropriate field builder for an edge property based on Zod schema type.\n   */\n  #getFieldBuilderForEdgeProperty(\n    edgeKindNames: readonly string[] | undefined,\n    property: string,\n    alias: string,\n  ): BaseFieldAccessor {\n    const typeInfo =\n      edgeKindNames ?\n        this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n          edgeKindNames,\n          property,\n        )\n      : undefined;\n\n    const ref = fieldRef(alias, [\"props\"], {\n      jsonPointer: jsonPointer([property]),\n      valueType: typeInfo?.valueType,\n      elementType: typeInfo?.elementType,\n    });\n\n    return this.#buildFieldBuilderForTypeInfo(ref, typeInfo);\n  }\n\n  #createEdgeAccessor(alias: string): EdgeAccessor<EdgeType> {\n    const edgeKindNames = this.#getEdgeKindNamesForAlias(alias);\n    const idAccessor = stringField(\n      fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n    );\n    const kindAccessor = stringField(\n      fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n    );\n    const fromIdAccessor = stringField(\n      fieldRef(alias, [\"from_id\"], { valueType: \"string\" }),\n    );\n    const toIdAccessor = stringField(\n      fieldRef(alias, [\"to_id\"], { valueType: \"string\" }),\n    );\n\n    if (this.#state.dynamicEdgeAliases.has(alias)) {\n      return {\n        id: idAccessor,\n        kind: kindAccessor,\n        fromId: fromIdAccessor,\n        toId: toIdAccessor,\n        field: (name: string) =>\n          createDynamicFieldBuilder(\n            this.#config.schemaIntrospector,\n            alias,\n            name,\n            edgeKindNames,\n            \"edge\",\n          ),\n      } as unknown as EdgeAccessor<EdgeType>;\n    }\n\n    // Use a Proxy to provide flattened property access\n    return new Proxy({} as EdgeAccessor<EdgeType>, {\n      get: (_, property: string | symbol) => {\n        // Handle symbols and special properties to avoid infinite loops\n        if (typeof property === \"symbol\") return;\n\n        // System fields\n        if (property === \"id\") return idAccessor;\n        if (property === \"kind\") return kindAccessor;\n        if (property === \"fromId\") return fromIdAccessor;\n        if (property === \"toId\") return toIdAccessor;\n\n        // A DECLARED field wins over the interop exemption — see\n        // #createNodeAccessor.\n        if (\n          isInteropProbeKey(property) &&\n          !(\n            edgeKindNames !== undefined &&\n            this.#config.schemaIntrospector.hasDeclaredEdgeField(\n              edgeKindNames,\n              property,\n            )\n          )\n        ) {\n          return;\n        }\n\n        // Schema properties\n        return this.#getFieldBuilderForEdgeProperty(\n          edgeKindNames,\n          property,\n          alias,\n        );\n      },\n    });\n  }\n}\n","import { backendDerivationRoot } from \"../../backend/derive-backend\";\n/**\n * UnionableQuery - A query formed by combining multiple queries with set operations.\n */\nimport {\n  type GraphBackend,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport {\n  type ComposableQuery,\n  type QueryAst,\n  type SetOperation,\n  type SetOperationType,\n  type Traversal,\n} from \"../ast\";\nimport {\n  type CompileQueryOptions,\n  compileSetOperation,\n} from \"../compiler/index\";\nimport { mapResults } from \"../execution\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { assertCompatibleSetOperationProvenance } from \"./one-statement-provenance\";\nimport { composableQueryHasParameterReferences } from \"./prepared-query\";\nimport {\n  buildReadInstantTemplate,\n  type CompiledTemplate,\n  composableNeedsCurrentReadInstant,\n  fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n  type AliasMap,\n  type EdgeAliasMap,\n  type QueryBuilderConfig,\n  type SelectContext,\n} from \"./types\";\nimport { validateQueryRange } from \"./validation\";\n\nfunction executeOnBackend<T>(\n  backend: GraphBackend | TransactionBackend,\n  recordedAsOf: string | undefined,\n  promise: Promise<T>,\n  surface: string,\n): Promise<T> {\n  if (recordedAsOf === undefined) return promise;\n  return withRecordedRelationsPrecondition(promise, {\n    dialect: backend.dialect,\n    surface,\n  });\n}\n\nfunction recordedAsOfForComposableQuery(\n  query: ComposableQuery,\n): string | undefined {\n  if (\"__type\" in query) {\n    return (\n      recordedAsOfForComposableQuery(query.left) ??\n      recordedAsOfForComposableQuery(query.right)\n    );\n  }\n  return query.recordedAsOf;\n}\n\n// Forward declaration for ExecutableQuery to avoid circular imports\n// G and R are used for type compatibility with ExecutableQuery but not accessed in the interface body\ninterface ExecutableQueryLike<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used for type compatibility\n  G extends GraphDef,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used for type compatibility\n  R,\n> {\n  toAst(): QueryAst;\n  /** @internal Set-operation provenance validation. */\n  oneStatementBatchProvenance(): Readonly<{\n    graphId: string;\n    executionTarget: object | undefined;\n  }>;\n}\n\n/**\n * Internal state for unionable query.\n */\ntype UnionableQueryState = Readonly<{\n  left: ComposableQuery;\n  operator: SetOperationType;\n  right: ComposableQuery;\n  limit?: number;\n  offset?: number;\n  // For result transformation\n  startAlias?: string;\n  traversals?: readonly Traversal[];\n  selectFn?: (context: SelectContext<AliasMap, EdgeAliasMap>) => unknown;\n}>;\n\n/**\n * A query formed by combining multiple queries with set operations.\n * Supports chaining: q1.union(q2).intersect(q3)\n */\n/** Sentinel distinguishing \"template not yet built\" from a built `undefined`. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\nexport class UnionableQuery<G extends GraphDef, R> {\n  readonly #config: QueryBuilderConfig;\n  readonly #state: UnionableQueryState;\n  // Per-instance compiled placeholder template, reused across\n  // execute()/executeOn() calls; the read instant is filled fresh per call.\n  // NOT_COMPUTED = not yet built; undefined = no fast path.\n  #template: CompiledTemplate | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n\n  constructor(config: QueryBuilderConfig, state: UnionableQueryState) {\n    this.#config = config;\n    this.#state = state;\n  }\n\n  /**\n   * Combines with another query using UNION.\n   */\n  union(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleOperand(other);\n    return new UnionableQuery(this.#config, {\n      left: this.toAst(),\n      operator: \"union\",\n      right: other.toAst(),\n      // Preserve result transformation info (only include defined properties)\n      ...(this.#state.startAlias !== undefined && {\n        startAlias: this.#state.startAlias,\n      }),\n      ...(this.#state.traversals !== undefined && {\n        traversals: this.#state.traversals,\n      }),\n      ...(this.#state.selectFn !== undefined && {\n        selectFn: this.#state.selectFn,\n      }),\n    });\n  }\n\n  /**\n   * Combines with another query using UNION ALL.\n   */\n  unionAll(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleOperand(other);\n    return new UnionableQuery(this.#config, {\n      left: this.toAst(),\n      operator: \"unionAll\",\n      right: other.toAst(),\n      // Preserve result transformation info (only include defined properties)\n      ...(this.#state.startAlias !== undefined && {\n        startAlias: this.#state.startAlias,\n      }),\n      ...(this.#state.traversals !== undefined && {\n        traversals: this.#state.traversals,\n      }),\n      ...(this.#state.selectFn !== undefined && {\n        selectFn: this.#state.selectFn,\n      }),\n    });\n  }\n\n  /**\n   * Combines with another query using INTERSECT.\n   */\n  intersect(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleOperand(other);\n    return new UnionableQuery(this.#config, {\n      left: this.toAst(),\n      operator: \"intersect\",\n      right: other.toAst(),\n      // Preserve result transformation info (only include defined properties)\n      ...(this.#state.startAlias !== undefined && {\n        startAlias: this.#state.startAlias,\n      }),\n      ...(this.#state.traversals !== undefined && {\n        traversals: this.#state.traversals,\n      }),\n      ...(this.#state.selectFn !== undefined && {\n        selectFn: this.#state.selectFn,\n      }),\n    });\n  }\n\n  /**\n   * Combines with another query using EXCEPT.\n   */\n  except(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n    this.#assertCompatibleOperand(other);\n    return new UnionableQuery(this.#config, {\n      left: this.toAst(),\n      operator: \"except\",\n      right: other.toAst(),\n      // Preserve result transformation info (only include defined properties)\n      ...(this.#state.startAlias !== undefined && {\n        startAlias: this.#state.startAlias,\n      }),\n      ...(this.#state.traversals !== undefined && {\n        traversals: this.#state.traversals,\n      }),\n      ...(this.#state.selectFn !== undefined && {\n        selectFn: this.#state.selectFn,\n      }),\n    });\n  }\n\n  /**\n   * Limits the number of results from the combined query.\n   */\n  limit(n: number): UnionableQuery<G, R> {\n    validateQueryRange(n, \"limit\");\n    return new UnionableQuery(this.#config, { ...this.#state, limit: n });\n  }\n\n  /**\n   * Offsets the results from the combined query.\n   */\n  offset(n: number): UnionableQuery<G, R> {\n    validateQueryRange(n, \"offset\");\n    return new UnionableQuery(this.#config, { ...this.#state, offset: n });\n  }\n\n  /**\n   * Builds the set operation AST.\n   */\n  toAst(): SetOperation {\n    return {\n      __type: \"set_operation\",\n      operator: this.#state.operator,\n      left: this.#state.left,\n      right: this.#state.right,\n      ...(this.#state.limit !== undefined && { limit: this.#state.limit }),\n      ...(this.#state.offset !== undefined && { offset: this.#state.offset }),\n    };\n  }\n\n  /** @internal Set-operation and batch provenance validation. */\n  oneStatementBatchProvenance(): Readonly<{\n    graphId: string;\n    executionTarget: object | undefined;\n  }> {\n    return {\n      graphId: this.#config.graphId,\n      executionTarget:\n        this.#config.backend === undefined ?\n          undefined\n        : backendDerivationRoot(this.#config.backend),\n    };\n  }\n\n  #assertCompatibleOperand(other: ExecutableQueryLike<G, R>): void {\n    const own = this.oneStatementBatchProvenance();\n    const candidate = other.oneStatementBatchProvenance();\n    assertCompatibleSetOperationProvenance(own, candidate);\n  }\n\n  /**\n   * Compiles the query and returns the SQL text and parameters.\n   *\n   * Requires a backend to be configured (the backend determines the SQL dialect).\n   * Use this for debugging, logging, or running the query with a custom executor.\n   */\n  toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n    if (!this.#config.backend?.compileSql) {\n      throw new Error(\n        \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n          \"Use store.query() to get a backend-aware query builder.\",\n      );\n    }\n    return this.#config.backend.compileSql(this.compile());\n  }\n\n  /**\n   * Compiles the set operation to SQL.\n   */\n  compile(): CompiledSelectSql {\n    // Emits a directly-runnable statement with the read instant as a literal;\n    // this is not the reusable placeholder template execute() caches (see\n    // #resolveTemplate).\n    return compileSetOperation(\n      this.toAst(),\n      this.#config.graphId,\n      this.#compileOptions(),\n    );\n  }\n\n  #compileOptions(): CompileQueryOptions {\n    return buildCompileOptions(this.#config);\n  }\n\n  /**\n   * The cached placeholder template for this set operation, or `undefined`\n   * when no fast path applies. Built once per instance; every operand's read\n   * instant is the shared placeholder, filled fresh per execution by\n   * {@link fillTemplateParams}.\n   */\n  #resolveTemplate(ast: SetOperation): CompiledTemplate | undefined {\n    if (this.#template !== NOT_COMPUTED) return this.#template;\n    this.#template = buildReadInstantTemplate({\n      compile: () =>\n        compileSetOperation(ast, this.#config.graphId, {\n          ...this.#compileOptions(),\n          readInstant: \"placeholder\",\n        }),\n      backend: this.#config.backend,\n      needsReadInstant: composableNeedsCurrentReadInstant(ast),\n    });\n    return this.#template;\n  }\n\n  /**\n   * Fetches raw rows for the set operation: cached template + `executeRaw`\n   * when available, else a fresh literal compile via `backend.execute`.\n   */\n  async #fetchRows(\n    backend: GraphBackend | TransactionBackend,\n    ast: SetOperation,\n    surface: string,\n  ): Promise<readonly Record<string, unknown>[]> {\n    const executeRaw = backend.executeRaw;\n    const template =\n      executeRaw === undefined ? undefined : this.#resolveTemplate(ast);\n    return executeOnBackend(\n      backend,\n      recordedAsOfForComposableQuery(ast),\n      template !== undefined && executeRaw !== undefined ?\n        executeRaw<Record<string, unknown>>(\n          template.sql,\n          fillTemplateParams(\n            template.params,\n            {},\n            this.#config.dialect ?? \"sqlite\",\n          ),\n        )\n      : backend.execute<Record<string, unknown>>(\n          compileSetOperation(\n            ast,\n            this.#config.graphId,\n            this.#compileOptions(),\n          ),\n        ),\n      surface,\n    );\n  }\n\n  /** Applies the select-function transformation, if one is attached. */\n  #mapRows(rows: readonly Record<string, unknown>[]): readonly R[] {\n    if (this.#state.selectFn && this.#state.startAlias) {\n      return mapResults(\n        rows,\n        this.#state.startAlias,\n        this.#state.traversals ?? [],\n        this.#state.selectFn,\n      ) as readonly R[];\n    }\n    return rows as readonly R[];\n  }\n\n  /**\n   * Executes the combined query.\n   */\n  async execute(): Promise<readonly R[]> {\n    this.#refuseCheckedScope();\n    if (!this.#config.backend) {\n      throw new Error(\n        \"Cannot execute query: no backend configured. \" +\n          \"Use store.query() or pass a backend to createQueryBuilder().\",\n      );\n    }\n    const backend = this.#config.backend;\n\n    const ast = this.toAst();\n    if (composableQueryHasParameterReferences(ast)) {\n      throw new Error(\n        \"Combined queries do not support param() references; bind concrete values before combining queries.\",\n      );\n    }\n\n    return this.#mapRows(await this.#fetchRows(backend, ast, \"recorded-query\"));\n  }\n\n  /**\n   * Executes the combined query against a provided backend.\n   *\n   * Used by `store.batch()` to run several queries in sequence against one\n   * target — a transaction on backends that have them, the backend itself\n   * otherwise. A set operation compiles to one statement; whether that target\n   * is a shared connection is the adapter's business, not a function of\n   * transaction support.\n   */\n  async executeOn(\n    backend: GraphBackend | TransactionBackend,\n  ): Promise<readonly R[]> {\n    this.#refuseCheckedScope();\n    const ast = this.toAst();\n    if (composableQueryHasParameterReferences(ast)) {\n      throw new Error(\n        \"Combined queries do not support param() references; bind concrete values before combining queries.\",\n      );\n    }\n\n    return this.#mapRows(\n      await this.#fetchRows(backend, ast, \"recorded-batch-query\"),\n    );\n  }\n\n  /** @internal Embedding contract consumed by `store.batchOnce()`. */\n  compileOneStatementBatchItem?(): Readonly<{\n    query: CompiledSelectSql;\n    provenance: Readonly<{ graphId: string; executionTarget: object }>;\n    outputNames: readonly string[];\n    orderBy: readonly Readonly<{\n      column: string;\n      direction: \"asc\" | \"desc\";\n      nulls: \"first\" | \"last\";\n    }>[];\n    mapRows: (rows: readonly Record<string, unknown>[]) => readonly R[];\n  }> {\n    this.#refuseCheckedScope();\n    const ast = this.toAst();\n    if (composableQueryHasParameterReferences(ast)) {\n      throw new Error(\n        \"Query contains param() references. Bind prepared queries before batching.\",\n      );\n    }\n    return {\n      query: compileSetOperation(\n        ast,\n        this.#config.graphId,\n        this.#compileOptions(),\n      ),\n      provenance: {\n        graphId: this.#config.graphId,\n        executionTarget: backendDerivationRoot(\n          requireDefined(this.#config.backend),\n        ),\n      },\n      outputNames: projectionOutputNames(ast),\n      orderBy: [],\n      mapRows: (rows) => this.#mapRows(rows),\n    };\n  }\n\n  #refuseCheckedScope(): void {\n    if (\n      getQueryBuilderInternalContext(this.#config).expectedSchemaVersion ===\n      undefined\n    ) {\n      return;\n    }\n    throw new ConfigurationError(\n      \"Set operations are unavailable inside withCheckedReads().\",\n      { operation: \"withCheckedReads.setOperation\" },\n    );\n  }\n}\n\nfunction projectionOutputNames(query: ComposableQuery): readonly string[] {\n  if (\"__type\" in query) return projectionOutputNames(query.left);\n  return query.projection.fields.map((field) => field.outputName);\n}\n","/**\n * Query Fragment Composition\n *\n * Provides types and utilities for creating reusable query fragments\n * that can be composed together using the pipe() method.\n *\n * @example\n * ```typescript\n * // Define a reusable fragment\n * const activeUsers = createFragment<MyGraph>()((q) =>\n *   q.whereNode(\"u\", ({ status }) => status.eq(\"active\"))\n * );\n *\n * // Use in queries\n * const results = await query()\n *   .from(\"User\", \"u\")\n *   .pipe(activeUsers)\n *   .select((ctx) => ctx.u)\n *   .execute();\n * ```\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type TraversalDirection } from \"../ast\";\nimport { type QueryBuilder } from \"./query-builder\";\nimport { type TraversalBuilder } from \"./traversal-builder\";\nimport {\n  type AliasMap,\n  type EdgeAliasMap,\n  type EmptyAliasMap,\n  type EmptyEdgeAliasMap,\n  type EmptyRecursiveAliasMap,\n  type QueryCoordinateState,\n  type RecursiveAliasMap,\n} from \"./types\";\n\ntype MergeAliasMaps<Existing extends AliasMap, Added extends AliasMap> =\n  keyof Added extends never ? Existing : Existing & Added;\ntype MergeEdgeAliasMaps<\n  Existing extends EdgeAliasMap,\n  Added extends EdgeAliasMap,\n> = keyof Added extends never ? Existing : Existing & Added;\n\n// ============================================================\n// Fragment Types\n// ============================================================\n\n/**\n * A query fragment that transforms a QueryBuilder.\n *\n * Fragments are functions that take a builder and return a modified builder.\n * They can add predicates, traversals, ordering, and other query operations.\n *\n * @typeParam G - The graph definition\n * @typeParam InAliases - Input alias map (what the fragment requires)\n * @typeParam OutAliases - Output alias map (what the fragment produces)\n * @typeParam InEdgeAliases - Input edge alias map\n * @typeParam OutEdgeAliases - Output edge alias map\n * @typeParam InRecursiveAliases - Input recursive alias map\n * @typeParam OutRecursiveAliases - Output recursive alias map\n */\nexport type QueryFragment<\n  G extends GraphDef,\n  InAliases extends AliasMap = AliasMap,\n  OutAliases extends AliasMap = InAliases,\n  InEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n  OutEdgeAliases extends EdgeAliasMap = InEdgeAliases,\n  InRecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n  OutRecursiveAliases extends RecursiveAliasMap = InRecursiveAliases,\n> = <CoordinateState extends QueryCoordinateState>(\n  builder: QueryBuilder<\n    G,\n    InAliases,\n    InEdgeAliases,\n    InRecursiveAliases,\n    CoordinateState\n  >,\n) => QueryBuilder<\n  G,\n  OutAliases,\n  OutEdgeAliases,\n  OutRecursiveAliases,\n  CoordinateState\n>;\n\n/**\n * A flexible query fragment that works with any compatible builder.\n *\n * Use this when you want a fragment that only requires certain aliases\n * to exist, but doesn't care about other aliases that may be present.\n */\nexport type FlexibleQueryFragment<\n  G extends GraphDef,\n  RequiredAliases extends AliasMap = AliasMap,\n  AddedAliases extends AliasMap = EmptyAliasMap,\n  RequiredEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n  AddedEdgeAliases extends EdgeAliasMap = EmptyEdgeAliasMap,\n> = <\n  Aliases extends RequiredAliases,\n  EdgeAliases extends RequiredEdgeAliases,\n  RecursiveAliases extends RecursiveAliasMap,\n  CoordinateState extends QueryCoordinateState,\n>(\n  builder: QueryBuilder<\n    G,\n    Aliases,\n    EdgeAliases,\n    RecursiveAliases,\n    CoordinateState\n  >,\n) => QueryBuilder<\n  G,\n  MergeAliasMaps<Aliases, AddedAliases>,\n  MergeEdgeAliasMaps<EdgeAliases, AddedEdgeAliases>,\n  RecursiveAliases,\n  CoordinateState\n>;\n\n/**\n * A traversal fragment that transforms a TraversalBuilder.\n *\n * Use this for reusable traversal patterns including edge filtering,\n * recursive traversals, and path collection.\n */\nexport type TraversalFragment<\n  G extends GraphDef,\n  EK extends keyof G[\"edges\"] & string,\n  EA extends string,\n  InAliases extends AliasMap = AliasMap,\n  InEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n> = <\n  Dir extends TraversalDirection,\n  Optional extends boolean,\n  DC extends boolean | string,\n  PC extends boolean | string,\n  RecursiveAliases extends RecursiveAliasMap,\n  CoordinateState extends QueryCoordinateState,\n>(\n  builder: TraversalBuilder<\n    G,\n    InAliases,\n    InEdgeAliases,\n    EK,\n    EA,\n    Dir,\n    Optional,\n    DC,\n    PC,\n    RecursiveAliases,\n    CoordinateState\n  >,\n) => unknown;\n\n// ============================================================\n// Fragment Factory\n// ============================================================\n\n/**\n * Creates a typed query fragment factory for a specific graph.\n *\n * This is the recommended way to create reusable fragments with full type safety.\n * The factory returns a function that creates fragments bound to your graph type.\n *\n * @example\n * ```typescript\n * // Create a factory for your graph\n * const fragment = createFragment<MyGraph>();\n *\n * // Define a simple filter fragment\n * const activeOnly = fragment((q) =>\n *   q.whereNode(\"u\", ({ isActive }) => isActive.eq(true))\n * );\n *\n * // Define a traversal fragment\n * const withManager = fragment((q) =>\n *   q.traverse(\"reportsTo\", \"r\").to(\"User\", \"manager\")\n * );\n *\n * // Compose fragments\n * query()\n *   .from(\"User\", \"u\")\n *   .pipe(activeOnly)\n *   .pipe(withManager)\n *   .select((ctx) => ({ user: ctx.u, manager: ctx.manager }))\n * ```\n */\n/**\n * Identity function used by createFragment to return the fragment unchanged.\n * Defined at module scope to satisfy consistent-function-scoping lint rule.\n */\nfunction fragmentIdentity<\n  G extends GraphDef,\n  InAliases extends AliasMap,\n  OutAliases extends AliasMap,\n  InEdgeAliases extends EdgeAliasMap,\n  OutEdgeAliases extends EdgeAliasMap,\n  InRecursiveAliases extends RecursiveAliasMap,\n  OutRecursiveAliases extends RecursiveAliasMap,\n>(\n  fn: QueryFragment<\n    G,\n    InAliases,\n    OutAliases,\n    InEdgeAliases,\n    OutEdgeAliases,\n    InRecursiveAliases,\n    OutRecursiveAliases\n  >,\n): QueryFragment<\n  G,\n  InAliases,\n  OutAliases,\n  InEdgeAliases,\n  OutEdgeAliases,\n  InRecursiveAliases,\n  OutRecursiveAliases\n> {\n  return fn;\n}\n\nexport function createFragment<G extends GraphDef>(): <\n  InAliases extends AliasMap,\n  OutAliases extends AliasMap,\n  InEdgeAliases extends EdgeAliasMap,\n  OutEdgeAliases extends EdgeAliasMap,\n  InRecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n  OutRecursiveAliases extends RecursiveAliasMap = InRecursiveAliases,\n>(\n  fn: QueryFragment<\n    G,\n    InAliases,\n    OutAliases,\n    InEdgeAliases,\n    OutEdgeAliases,\n    InRecursiveAliases,\n    OutRecursiveAliases\n  >,\n) => QueryFragment<\n  G,\n  InAliases,\n  OutAliases,\n  InEdgeAliases,\n  OutEdgeAliases,\n  InRecursiveAliases,\n  OutRecursiveAliases\n> {\n  return fragmentIdentity;\n}\n\ntype ErasedFragment = (builder: unknown) => unknown;\n\n/**\n * Combines multiple fragments into a single fragment.\n *\n * Fragments are applied in order from left to right.\n *\n * @example\n * ```typescript\n * const combinedFragment = composeFragments(\n *   activeOnly,\n *   withManager,\n *   recentlyUpdated\n * );\n *\n * query()\n *   .from(\"User\", \"u\")\n *   .pipe(combinedFragment)\n *   .select(...)\n * ```\n */\nexport function composeFragments<\n  G extends GraphDef,\n  A1 extends AliasMap,\n  A2 extends AliasMap,\n  E1 extends EdgeAliasMap,\n  E2 extends EdgeAliasMap,\n  R1 extends RecursiveAliasMap,\n  R2 extends RecursiveAliasMap,\n>(\n  f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n): QueryFragment<G, A1, A2, E1, E2, R1, R2>;\n\nexport function composeFragments<\n  G extends GraphDef,\n  A1 extends AliasMap,\n  A2 extends AliasMap,\n  A3 extends AliasMap,\n  E1 extends EdgeAliasMap,\n  E2 extends EdgeAliasMap,\n  E3 extends EdgeAliasMap,\n  R1 extends RecursiveAliasMap,\n  R2 extends RecursiveAliasMap,\n  R3 extends RecursiveAliasMap,\n>(\n  f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n  f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n): QueryFragment<G, A1, A3, E1, E3, R1, R3>;\n\nexport function composeFragments<\n  G extends GraphDef,\n  A1 extends AliasMap,\n  A2 extends AliasMap,\n  A3 extends AliasMap,\n  A4 extends AliasMap,\n  E1 extends EdgeAliasMap,\n  E2 extends EdgeAliasMap,\n  E3 extends EdgeAliasMap,\n  E4 extends EdgeAliasMap,\n  R1 extends RecursiveAliasMap,\n  R2 extends RecursiveAliasMap,\n  R3 extends RecursiveAliasMap,\n  R4 extends RecursiveAliasMap,\n>(\n  f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n  f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n  f3: QueryFragment<G, A3, A4, E3, E4, R3, R4>,\n): QueryFragment<G, A1, A4, E1, E4, R1, R4>;\n\nexport function composeFragments<\n  G extends GraphDef,\n  A1 extends AliasMap,\n  A2 extends AliasMap,\n  A3 extends AliasMap,\n  A4 extends AliasMap,\n  A5 extends AliasMap,\n  E1 extends EdgeAliasMap,\n  E2 extends EdgeAliasMap,\n  E3 extends EdgeAliasMap,\n  E4 extends EdgeAliasMap,\n  E5 extends EdgeAliasMap,\n  R1 extends RecursiveAliasMap,\n  R2 extends RecursiveAliasMap,\n  R3 extends RecursiveAliasMap,\n  R4 extends RecursiveAliasMap,\n  R5 extends RecursiveAliasMap,\n>(\n  f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n  f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n  f3: QueryFragment<G, A3, A4, E3, E4, R3, R4>,\n  f4: QueryFragment<G, A4, A5, E4, E5, R4, R5>,\n): QueryFragment<G, A1, A5, E1, E5, R1, R5>;\n\nexport function composeFragments(...fragments: readonly unknown[]): unknown {\n  return (builder: unknown) => {\n    let result = builder;\n    for (const fragment of fragments) {\n      result = (fragment as ErasedFragment)(result);\n    }\n    return result;\n  };\n}\n\n// ============================================================\n// Common Fragment Patterns\n// ============================================================\n\n/**\n * Creates a fragment that adds ordering.\n *\n * @example\n * ```typescript\n * const byCreatedAt = orderByFragment<MyGraph, \"u\">(\"u\", \"createdAt\", \"desc\");\n * ```\n */\nexport function orderByFragment<G extends GraphDef, A extends string>(\n  alias: A,\n  field: string,\n  direction: \"asc\" | \"desc\" = \"asc\",\n): FlexibleQueryFragment<G> {\n  return (builder) => builder.orderBy(alias, field, direction);\n}\n\n/**\n * Creates a fragment that adds a limit.\n *\n * @example\n * ```typescript\n * const first10 = limitFragment<MyGraph>(10);\n * ```\n */\nexport function limitFragment<G extends GraphDef>(\n  n: number,\n): FlexibleQueryFragment<G> {\n  return (builder) => builder.limit(n);\n}\n\n/**\n * Creates a fragment that adds an offset.\n *\n * @example\n * ```typescript\n * const skip10 = offsetFragment<MyGraph>(10);\n * ```\n */\nexport function offsetFragment<G extends GraphDef>(\n  n: number,\n): FlexibleQueryFragment<G> {\n  return (builder) => builder.offset(n);\n}\n","/**\n * Query Builder Module\n *\n * Re-exports from the builder submodules for clean imports.\n * Also wires up circular dependencies between classes.\n */\n\n// Import classes for circular dependency wiring\nimport { setUnionableQueryClass } from \"./executable-query\";\nimport { QueryBuilder } from \"./query-builder\";\nimport { setQueryBuilderClass } from \"./traversal-builder\";\nimport { UnionableQuery } from \"./unionable-query\";\n\n// Wire up circular dependencies.\n// Type assertions are needed because the circular dependency resolution\n// requires passing classes that TypeScript can't verify at module init time.\nsetQueryBuilderClass(QueryBuilder);\nsetUnionableQueryClass(UnionableQuery);\n\n// Classes\nexport {\n  type AggregateResult,\n  ExecutableAggregateQuery,\n} from \"./executable-aggregate-query\";\nexport { ExecutableQuery } from \"./executable-query\";\nexport { executeOneStatementBatch } from \"./one-statement-batch\";\nexport { PreparedQuery } from \"./prepared-query\";\nexport { type IdentityTraversalOption, QueryBuilder } from \"./query-builder\";\nexport {\n  createExecutableRelation,\n  createProjectionRelation,\n  ExecutableRelationQuery,\n  type RelationColumnContext,\n  type RelationDefinition,\n  type RelationProjection,\n  type RelationProjectionResult,\n  type RelationProvenance,\n  type TopPerPartitionOptions,\n  type TopPerPartitionOrder,\n} from \"./relation\";\nexport { TraversalBuilder } from \"./traversal-builder\";\nexport { UnionableQuery } from \"./unionable-query\";\n\n// Aggregate helpers\nexport {\n  avg,\n  count,\n  countDistinct,\n  countDistinctEdges,\n  countEdges,\n  field,\n  having,\n  havingEq,\n  havingGt,\n  havingGte,\n  havingLt,\n  havingLte,\n  max,\n  min,\n  sum,\n} from \"./aggregates\";\n\n// Fragment composition\nexport {\n  composeFragments,\n  createFragment,\n  type FlexibleQueryFragment,\n  limitFragment,\n  offsetFragment,\n  orderByFragment,\n  type QueryFragment,\n  type TraversalFragment,\n} from \"./fragment\";\n\n// AST building utilities\nexport { buildQueryAst } from \"./ast-builder\";\n\n// Types\nexport {\n  type AliasMap,\n  type ArrayFieldAccessor,\n  type BaseFieldAccessor,\n  type BatchableQuery,\n  type BatchResults,\n  type BooleanFieldAccessor,\n  type CommonPropertyKeys,\n  type CompiledOneStatementRead,\n  type CreateQueryBuilderOptions,\n  type DateFieldAccessor,\n  type EdgeAccessor,\n  type EmbeddableOneStatementRead,\n  type EmbeddingFieldAccessor,\n  type EmptyAliasMap,\n  type EmptyEdgeAliasMap,\n  type EmptyRecursiveAliasMap,\n  type ExecutableOneStatementRead,\n  type FieldAccessor,\n  type NodeAccessor,\n  type NodeAlias,\n  type NodeCandidateQuery,\n  type NodeCandidateSelection,\n  type NodePropsFor,\n  type NumberFieldAccessor,\n  type ObjectFieldAccessor,\n  type OneStatementBatchableQuery,\n  type OneStatementBatchReads,\n  type OneStatementBatchResults,\n  type PaginatedResult,\n  type PaginateOptions,\n  type PropsAccessor,\n  type QualifiedRecursivePath,\n  type QualifiedRecursivePathEdge,\n  type QualifiedRecursivePathElement,\n  type QualifiedRecursivePathNode,\n  type QualifiedRecursivePathOption,\n  type QueryBuilderConfig,\n  type QueryBuilderState,\n  type QueryCoordinateState,\n  type RecursiveAlias,\n  type RecursiveAliasMap,\n  type RecursiveAliasValue,\n  type RecursiveTraversalOptions,\n  type SelectableEdge,\n  type SelectableEdgeMeta,\n  type SelectableNode,\n  type SelectableNodeMeta,\n  type SelectContext,\n  type StreamOptions,\n  type StringFieldAccessor,\n  type TraversalExpansion,\n  type UniqueAlias,\n  type ValidEdgeTargets,\n} from \"./types\";\n\n// Dynamic (string-keyed) builder types\nexport {\n  type DynamicEdgeAccessor,\n  type DynamicEdgeType,\n  type DynamicFieldBuilder,\n  type DynamicNodeAccessor,\n  type DynamicNodeKind,\n  type DynamicNodeType,\n  type DynamicSelectableEdge,\n  type DynamicSelectableNode,\n} from \"./dynamic\";\n\n// Validation utilities\nexport type { BatchOnceOptions } from \"./one-statement-batch\";\nexport { validateSqlIdentifier } from \"./validation\";\n","/**\n * Fluent query builder for TypeGraph.\n *\n * Provides a type-safe, chainable API for building queries.\n * Each method returns a new builder instance with expanded type information.\n *\n * This module re-exports from the builder submodules and provides the\n * createQueryBuilder factory function.\n */\nimport { type GraphDef } from \"../core/define-graph\";\nimport { ConfigurationError } from \"../errors\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n  type CreateQueryBuilderOptions,\n  type EmptyAliasMap,\n  type EmptyEdgeAliasMap,\n  type EmptyRecursiveAliasMap,\n  QueryBuilder,\n  type QueryBuilderConfig,\n  type QueryBuilderState,\n  type QueryCoordinateState,\n} from \"./builder/index\";\nimport {\n  type QueryBuilderInternalContext,\n  registerQueryBuilderInternalContext,\n} from \"./builder/internal-context\";\nimport { createSchemaIntrospector } from \"./schema-introspector\";\n\n// Re-export all classes\nexport {\n  ExecutableAggregateQuery,\n  ExecutableQuery,\n  executeOneStatementBatch,\n  QueryBuilder,\n} from \"./builder/index\";\n\n// Re-export aggregate helpers\nexport {\n  avg,\n  count,\n  countDistinct,\n  countDistinctEdges,\n  countEdges,\n  field,\n  having,\n  havingEq,\n  havingGt,\n  havingGte,\n  havingLt,\n  havingLte,\n  max,\n  min,\n  sum,\n} from \"./builder/index\";\n\n// Re-export types\nexport type {\n  AggregateResult,\n  AliasMap,\n  BatchableQuery,\n  BatchResults,\n  CommonPropertyKeys,\n  CompiledOneStatementRead,\n  DynamicEdgeAccessor,\n  DynamicEdgeType,\n  DynamicFieldBuilder,\n  DynamicNodeAccessor,\n  DynamicNodeKind,\n  DynamicNodeType,\n  DynamicSelectableEdge,\n  DynamicSelectableNode,\n  EdgeAccessor,\n  EmbeddableOneStatementRead,\n  EmptyAliasMap,\n  EmptyEdgeAliasMap,\n  EmptyRecursiveAliasMap,\n  ExecutableOneStatementRead,\n  FieldAccessor,\n  IdentityTraversalOption,\n  NodeAccessor,\n  NodeAlias,\n  NodeCandidateQuery,\n  NodeCandidateSelection,\n  NodePropsFor,\n  OneStatementBatchableQuery,\n  OneStatementBatchReads,\n  OneStatementBatchResults,\n  PaginatedResult,\n  PaginateOptions,\n  PropsAccessor,\n  QualifiedRecursivePath,\n  QualifiedRecursivePathEdge,\n  QualifiedRecursivePathElement,\n  QualifiedRecursivePathNode,\n  QualifiedRecursivePathOption,\n  QueryCoordinateState,\n  RecursiveTraversalOptions,\n  SelectableEdge,\n  SelectableNode,\n  SelectContext,\n  StreamOptions,\n  TraversalExpansion,\n} from \"./builder/index\";\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a new query builder for a graph.\n *\n * @param graphId - The graph identifier\n * @param registry - The kind registry for ontology lookups\n * @param options - Optional backend and dialect configuration\n * @returns A new QueryBuilder instance\n *\n * @example\n * ```typescript\n * // Without execution capability (compile only)\n * const builder = createQueryBuilder<MyGraph>(\"my_graph\", registry);\n *\n * // With execution capability\n * const builder = createQueryBuilder<MyGraph>(\"my_graph\", registry, {\n *   backend: myBackend,\n *   dialect: \"sqlite\",\n * });\n * ```\n */\ntype InternalCreateQueryBuilderOptions = CreateQueryBuilderOptions &\n  QueryBuilderInternalContext;\n\nexport type InitialQueryBuilder<\n  G extends GraphDef,\n  CoordinateState extends QueryCoordinateState = \"open\",\n> = QueryBuilder<\n  G,\n  EmptyAliasMap,\n  EmptyEdgeAliasMap,\n  EmptyRecursiveAliasMap,\n  CoordinateState\n>;\n\nexport function createQueryBuilder<G extends GraphDef>(\n  graphId: string,\n  registry: KindRegistry,\n  options?: CreateQueryBuilderOptions,\n): InitialQueryBuilder<G>;\nexport function createQueryBuilder<G extends GraphDef>(\n  graphId: string,\n  registry: KindRegistry,\n  options?: CreateQueryBuilderOptions,\n): InitialQueryBuilder<G> {\n  return createQueryBuilderWithContext<G>(graphId, registry, options);\n}\n\nexport function createInternalQueryBuilder<\n  G extends GraphDef,\n  CoordinateState extends QueryCoordinateState = \"open\",\n>(\n  graphId: string,\n  registry: KindRegistry,\n  options?: InternalCreateQueryBuilderOptions,\n): InitialQueryBuilder<G, CoordinateState> {\n  return createQueryBuilderWithContext<G, CoordinateState>(\n    graphId,\n    registry,\n    options,\n  );\n}\n\nfunction createQueryBuilderWithContext<\n  G extends GraphDef,\n  CoordinateState extends QueryCoordinateState = \"open\",\n>(\n  graphId: string,\n  registry: KindRegistry,\n  options?: InternalCreateQueryBuilderOptions,\n): InitialQueryBuilder<G, CoordinateState> {\n  const schemaIntrospector = createSchemaIntrospector(\n    registry.nodeKinds,\n    registry.edgeKinds,\n  );\n  if (options?.identityEnabled === true && registry.identity === undefined) {\n    throw new ConfigurationError(\n      \"Identity-aware query compilation requires an identity-enabled graph registry.\",\n      { code: \"IDENTITY_NOT_ENABLED\", graphId },\n      {\n        suggestion:\n          \"Build the registry from a graph whose defineGraph(...) config includes identity.\",\n      },\n    );\n  }\n  if (\n    options?.identitySameIdAcrossKinds !== undefined &&\n    registry.identity === undefined\n  ) {\n    throw new ConfigurationError(\n      \"identitySameIdAcrossKinds requires an identity-enabled graph registry.\",\n      { code: \"IDENTITY_NOT_ENABLED\", graphId },\n      {\n        suggestion:\n          \"Configure sameIdAcrossKinds on defineGraph(...).identity instead.\",\n      },\n    );\n  }\n\n  // Build config, only including optional properties if defined\n  const config: QueryBuilderConfig = {\n    graphId,\n    registry,\n    schemaIntrospector,\n    defaultTraversalExpansion: options?.defaultTraversalExpansion ?? \"inverse\",\n    identityEnabled:\n      options?.identityEnabled ?? registry.identity !== undefined,\n    identitySameIdAcrossKinds:\n      options?.identitySameIdAcrossKinds ??\n      registry.identity?.sameIdAcrossKinds ??\n      \"fold\",\n    ...(options?.backend !== undefined && { backend: options.backend }),\n    ...(options?.dialect !== undefined && { dialect: options.dialect }),\n    ...(options?.schema !== undefined && { schema: options.schema }),\n  };\n  registerQueryBuilderInternalContext(config, {\n    ...(options?.recordedReadBinding !== undefined && {\n      recordedReadBinding: options.recordedReadBinding,\n    }),\n    ...(options?.sealedCoordinate !== undefined && {\n      sealedCoordinate: options.sealedCoordinate,\n    }),\n    ...(options?.runtimeKindTokenResolver !== undefined && {\n      runtimeKindTokenResolver: options.runtimeKindTokenResolver,\n    }),\n    ...(options?.expectedSchemaVersion !== undefined && {\n      expectedSchemaVersion: options.expectedSchemaVersion,\n    }),\n  });\n\n  // A sealed coordinate (StoreView pin) seeds the temporal axis; `.temporal()`\n  // then refuses to override it.\n  const sealed = options?.sealedCoordinate?.valid;\n  const recorded = options?.sealedCoordinate?.recorded;\n\n  const initialState: QueryBuilderState = {\n    startAlias: \"\",\n    currentAlias: \"\",\n    startKinds: [],\n    includeSubClasses: false,\n    traversals: [],\n    predicates: [],\n    projection: [],\n    orderBy: [],\n    aggregateOrderBy: [],\n    limit: undefined,\n    offset: undefined,\n    temporalMode: sealed?.mode ?? \"current\",\n    asOf: sealed?.asOf,\n    recordedAsOf: recorded?.asOf,\n    groupBy: undefined,\n    having: undefined,\n    fusion: undefined,\n    dynamicNodeAliases: new Set(),\n    dynamicEdgeAliases: new Set(),\n  };\n\n  return new QueryBuilder(config, initialState) as InitialQueryBuilder<\n    G,\n    CoordinateState\n  >;\n}\n","/**\n * Rebuilds the fulltext index from existing node data.\n *\n * Iterates nodes via keyset pagination (ORDER BY id ASC, WHERE id > cursor)\n * so rebuild is stable even under shared created_at timestamps and light\n * concurrent writes. Each page runs in its own transaction; batch primitives\n * are used when the backend provides them, with per-row fallback otherwise.\n *\n * Rebuild is a maintenance operation. Concurrent deletes that happen\n * between page fetches can be missed by this pass — document as such.\n */\nimport { type z } from \"zod\";\n\nimport { resolveBackendFulltext } from \"../backend/capabilities/fulltext\";\nimport {\n  type GraphBackend,\n  type NodeRow,\n  rowPropsToObject,\n  runOptionallyInTransaction,\n  type TransactionBackend,\n} from \"../backend/types\";\nimport {\n  ConfigurationError,\n  UnsupportedBackendCapabilityError,\n  ValidationError,\n} from \"../errors\";\nimport { type KindRegistry } from \"../registry\";\nimport {\n  assertFulltextMember,\n  computeFulltextContent,\n  getSearchableFields,\n} from \"./fulltext-sync\";\n\n/**\n * Default page size. Fits under SQLite's ~32766 placeholder limit with\n * headroom: 6 params/row × 500 rows + 500-entry DELETE IN list ≈ 3500\n * placeholders. Bumping past ~5000 risks the ceiling on SQLite.\n */\nconst DEFAULT_PAGE_SIZE = 500;\n\n/**\n * Default cap on the length of `skippedIds` returned from rebuild. A\n * corrupted database could produce millions of skipped rows; surfacing\n * them all as a single in-memory array would turn a recovery tool into\n * an OOM. The total skipped *count* remains accurate; only the ID\n * listing is truncated. Operators who need the full list for recovery\n * can raise the cap via `maxSkippedIds`.\n */\nconst DEFAULT_MAX_SKIPPED_IDS = 10_000;\n\nexport type RebuildFulltextOptions = Readonly<{\n  /** Page size. Must be a positive integer. Default: 500. */\n  pageSize?: number;\n  /**\n   * Maximum number of skipped node IDs to include in the `skippedIds`\n   * array. Default: 10,000. Set higher to collect the full list when\n   * investigating systemic corruption; set lower when `processed` is\n   * all you care about. The `skipped` total is always accurate.\n   */\n  maxSkippedIds?: number;\n}>;\n\nexport type RebuildFulltextResult = Readonly<{\n  /** Node kinds that were rebuilt (those with at least one searchable field). */\n  kinds: readonly string[];\n  /** Total nodes scanned. */\n  processed: number;\n  /** Fulltext upsert operations executed. */\n  upserted: number;\n  /** Fulltext delete operations executed (soft-deleted or all-empty nodes). */\n  cleared: number;\n  /**\n   * Nodes skipped due to corrupt or non-object `props` (not counted in\n   * upserted/cleared).\n   */\n  skipped: number;\n  /**\n   * IDs of skipped nodes, capped at 10,000 entries so pathological\n   * corruption doesn't turn rebuild into an OOM. See `skippedTruncated`\n   * to tell whether the cap was hit. Empty when `skipped === 0`.\n   */\n  skippedIds: readonly string[];\n  /** True when `skipped > skippedIds.length` (the cap was reached). */\n  skippedTruncated: boolean;\n}>;\n\ntype RebuildContext = Readonly<{\n  graphId: string;\n  backend: GraphBackend;\n  registry: KindRegistry;\n}>;\n\n/** Anything the rebuild can read nodes from and write fulltext rows to. */\ntype FulltextRebuildTarget = GraphBackend | TransactionBackend;\n\n/**\n * How the rebuild frames its writes. The paging, content computation, and\n * accounting are identical whichever way a caller drives it; only the\n * transaction boundary differs, so that is the only thing injected.\n *\n * - The standalone `store.search.rebuildFulltext()` transacts per page, so\n *   a maintenance pass over a large graph never holds one long\n *   transaction and can resume where it stopped.\n * - The destructive `store.rebuildContribution()` runs every page inside\n *   the single transaction that also dropped, recreated, and will stamp\n *   the storage, because there the refill is not optional: publishing the\n *   marker over a half-filled table would advertise a healthy index that\n *   answers queries with nothing.\n */\ntype FulltextRebuildDriver = Readonly<{\n  /** Backend the paged node reads go through. */\n  read: FulltextRebuildTarget;\n  /** Runs one page's writes under whatever framing the caller wants. */\n  runPage: (\n    write: (target: FulltextRebuildTarget) => Promise<void>,\n  ) => Promise<void>;\n}>;\n\nfunction validatePageSize(value: number | undefined): number {\n  if (value === undefined) return DEFAULT_PAGE_SIZE;\n  if (!Number.isInteger(value) || value <= 0) {\n    throw new ValidationError(\n      `pageSize must be a positive integer, got: ${String(value)}`,\n      {\n        issues: [{ path: \"pageSize\", message: \"Must be a positive integer.\" }],\n      },\n    );\n  }\n  return value;\n}\n\nfunction validateMaxSkippedIds(value: number | undefined): number {\n  if (value === undefined) return DEFAULT_MAX_SKIPPED_IDS;\n  if (!Number.isInteger(value) || value < 0) {\n    throw new ValidationError(\n      `maxSkippedIds must be a non-negative integer, got: ${String(value)}`,\n      {\n        issues: [\n          {\n            path: \"maxSkippedIds\",\n            message: \"Must be a non-negative integer.\",\n          },\n        ],\n      },\n    );\n  }\n  return value;\n}\n\nfunction isPropsObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function rebuildFulltextIndex(\n  ctx: RebuildContext,\n  nodeKind: string | undefined,\n  options: RebuildFulltextOptions,\n): Promise<RebuildFulltextResult> {\n  const { backend } = ctx;\n  return runFulltextRebuild(\n    {\n      read: backend,\n      runPage: (write) => runOptionallyInTransaction(backend, write),\n    },\n    ctx,\n    nodeKind,\n    options,\n  );\n}\n\n/**\n * Reconstructs fulltext content entirely inside a transaction the caller\n * already owns, with no nested transaction of its own.\n *\n * Used by the destructive contribution rebuild, whose whole point is that\n * the drop, the recreate, this refill, and the marker stamp commit\n * together. `target` must be a transaction-scoped backend whose fulltext\n * methods are NOT gated on the durable marker: this runs while the\n * contribution is mid-rebuild, so a gate would refuse the very writes\n * that make it healthy again.\n */\nexport async function repopulateFulltextInTransaction(\n  ctx: Readonly<{ graphId: string; registry: KindRegistry }>,\n  target: TransactionBackend,\n  options: RebuildFulltextOptions = {},\n): Promise<RebuildFulltextResult> {\n  return runFulltextRebuild(\n    { read: target, runPage: (write) => write(target) },\n    ctx,\n    undefined,\n    options,\n  );\n}\n\nasync function runFulltextRebuild(\n  driver: FulltextRebuildDriver,\n  ctx: Readonly<{ graphId: string; registry: KindRegistry }>,\n  nodeKind: string | undefined,\n  options: RebuildFulltextOptions,\n): Promise<RebuildFulltextResult> {\n  const { registry } = ctx;\n  const backend = driver.read;\n\n  // `resolveBackendFulltext` is the one decision for \"is fulltext\n  // available on this backend\" — the same one the write path consults.\n  // A member missing past that point is a contract violation, asserted\n  // separately below rather than folded into this availability check.\n  if (resolveBackendFulltext(backend) === false) {\n    throw new UnsupportedBackendCapabilityError(\n      \"rebuildFulltext()\",\n      \"fulltext\",\n      { backend: backend.dialect, reason: \"fulltext_unsupported\" },\n      \"This backend declares no fulltext capability, so there is no \" +\n        \"fulltext index to rebuild. Use a backend with fulltext support.\",\n    );\n  }\n  assertFulltextMember(backend.upsertFulltext, \"upsertFulltext\", backend);\n  assertFulltextMember(backend.deleteFulltext, \"deleteFulltext\", backend);\n\n  const pageSize = validatePageSize(options.pageSize);\n  const maxSkippedIds = validateMaxSkippedIds(options.maxSkippedIds);\n\n  const targetKinds =\n    nodeKind === undefined ? [...registry.nodeKinds.keys()] : [nodeKind];\n\n  const rebuiltKinds: string[] = [];\n  let processed = 0;\n  let upserted = 0;\n  let cleared = 0;\n  let skipped = 0;\n  const skippedIds: string[] = [];\n\n  for (const kind of targetKinds) {\n    const nodeType = registry.getNodeType(kind);\n    if (!nodeType) {\n      throw new ConfigurationError(`Unknown node kind: ${kind}`, { kind });\n    }\n    if (getSearchableFields(nodeType.schema).length === 0) {\n      continue;\n    }\n\n    rebuiltKinds.push(kind);\n    let cursor: string | undefined;\n    for (;;) {\n      // Keyset pagination on id. Include soft-deleted nodes so their\n      // stale fulltext rows get cleaned up by this rebuild.\n      const rows = await backend.findNodesByKind({\n        graphId: ctx.graphId,\n        kind,\n        limit: pageSize,\n        excludeDeleted: false,\n        orderBy: \"id\",\n        ...(cursor === undefined ? {} : { after: cursor }),\n      });\n      if (rows.length === 0) break;\n\n      const pageResult = processPage(nodeType.schema, rows);\n      skipped += pageResult.skipped;\n      const remaining = maxSkippedIds - skippedIds.length;\n      if (remaining > 0 && pageResult.skippedIds.length > 0) {\n        skippedIds.push(...pageResult.skippedIds.slice(0, remaining));\n      }\n\n      const writePage = async (\n        target: FulltextRebuildTarget,\n      ): Promise<void> => {\n        if (pageResult.toUpsert.length > 0) {\n          if (target.upsertFulltextBatch) {\n            await target.upsertFulltextBatch({\n              graphId: ctx.graphId,\n              nodeKind: kind,\n              rows: pageResult.toUpsert,\n            });\n          } else if (target.upsertFulltext) {\n            for (const item of pageResult.toUpsert) {\n              await target.upsertFulltext({\n                graphId: ctx.graphId,\n                nodeKind: kind,\n                nodeId: item.nodeId,\n                content: item.content,\n                language: item.language,\n              });\n            }\n          } else {\n            assertFulltextMember(\n              target.upsertFulltext,\n              \"upsertFulltext\",\n              target,\n            );\n          }\n        }\n        if (pageResult.toDelete.length > 0) {\n          if (target.deleteFulltextBatch) {\n            await target.deleteFulltextBatch({\n              graphId: ctx.graphId,\n              nodeKind: kind,\n              nodeIds: pageResult.toDelete,\n            });\n          } else if (target.deleteFulltext) {\n            for (const nodeId of pageResult.toDelete) {\n              await target.deleteFulltext({\n                graphId: ctx.graphId,\n                nodeKind: kind,\n                nodeId,\n              });\n            }\n          } else {\n            assertFulltextMember(\n              target.deleteFulltext,\n              \"deleteFulltext\",\n              target,\n            );\n          }\n        }\n      };\n\n      // Framed by the driver: transacted per page for a standalone\n      // maintenance pass (so a partial failure mid-page doesn't leave the\n      // index half-rebuilt, and a backend without transactions still\n      // rebuilds rather than staying permanently stale), or run directly\n      // on the caller's transaction when the refill is one step of a\n      // larger atomic operation.\n      await driver.runPage(writePage);\n\n      processed += rows.length;\n      upserted += pageResult.toUpsert.length;\n      cleared += pageResult.toDelete.length;\n\n      const lastRow = rows.at(-1);\n      if (!lastRow) break;\n      cursor = lastRow.id;\n      if (rows.length < pageSize) break;\n    }\n  }\n\n  return {\n    kinds: rebuiltKinds,\n    processed,\n    upserted,\n    cleared,\n    skipped,\n    skippedIds,\n    skippedTruncated: skipped > skippedIds.length,\n  };\n}\n\ninterface PageResult {\n  toUpsert: { nodeId: string; content: string; language: string }[];\n  toDelete: string[];\n  skipped: number;\n  skippedIds: string[];\n}\n\nfunction processPage(schema: z.ZodType, rows: readonly NodeRow[]): PageResult {\n  const toUpsert: PageResult[\"toUpsert\"] = [];\n  const toDelete: string[] = [];\n  const skippedIds: string[] = [];\n  let skipped = 0;\n\n  for (const row of rows) {\n    if (row.deleted_at !== undefined) {\n      toDelete.push(row.id);\n      continue;\n    }\n    let parsed: unknown;\n    try {\n      parsed = rowPropsToObject(row.props);\n    } catch {\n      skipped += 1;\n      skippedIds.push(row.id);\n      continue;\n    }\n    if (!isPropsObject(parsed)) {\n      skipped += 1;\n      skippedIds.push(row.id);\n      continue;\n    }\n    const computed = computeFulltextContent(schema, parsed);\n    if (computed === undefined) {\n      toDelete.push(row.id);\n    } else {\n      toUpsert.push({\n        nodeId: row.id,\n        content: computed.content,\n        language: computed.language,\n      });\n    }\n  }\n\n  return { toUpsert, toDelete, skipped, skippedIds };\n}\n","/**\n * Store-level search helpers.\n *\n * `fulltextSearch` is a thin typed wrapper over `backend.fulltextSearch`.\n * `hybridSearch` runs a vector and a fulltext query in parallel and\n * fuses the two ranked lists with Reciprocal Rank Fusion. RRF is\n * rank-based, so it papers over score-scale differences between\n * pgvector/sqlite-vec (distance-derived) and tsvector/FTS5 (BM25-style).\n */\nimport { bindExtraIfReachable } from \"../backend/capabilities/bind\";\nimport { BATCH_POINT_READ } from \"../backend/capabilities/bundle-registry\";\nimport { resolveBackendFulltext } from \"../backend/capabilities/fulltext\";\nimport { type BundleVerdictOf } from \"../backend/capabilities/resolve\";\nimport {\n  type FulltextCapabilities,\n  type FulltextQueryMode,\n  type GraphBackend,\n  type VectorIndexType,\n  type VectorMetric,\n} from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { resolveDeclaredFulltextLanguage } from \"../core/searchable\";\nimport { type NodeType } from \"../core/types\";\nimport {\n  ConfigurationError,\n  UnsupportedBackendCapabilityError,\n} from \"../errors\";\nimport {\n  DEFAULT_RRF_K,\n  DEFAULT_RRF_WEIGHT,\n  type HybridFusionOptions,\n} from \"../query/ast\";\nimport { type QueryBuilder } from \"../query/builder/query-builder\";\nimport { type NodeAccessor } from \"../query/builder/types\";\nimport { validateHybridFusionOptions } from \"../query/builder/validation\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { assertVectorMinScore } from \"../query/dialect/vector-strategy\";\nimport { type Predicate } from \"../query/predicates\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { requireDefined } from \"../utils/presence\";\nimport { getEmbeddingFields } from \"./embedding-sync\";\nimport { rowToNode } from \"./row-mappers\";\nimport { type Node } from \"./types\";\n\n/**\n * A fulltext search hit. `N` defaults to the generic `Node`; the\n * `store.search.fulltext<K>(kind)` facade narrows it to the concrete\n * typed node for that kind so callers get `hit.node.title` without a cast.\n */\nexport type FulltextSearchHit<N = Node> = Readonly<{\n  node: N;\n  /** Backend-native relevance score; higher is better. */\n  score: number;\n  /** 1-based rank within the result set. */\n  rank: number;\n  /** Highlighted snippet (only present when `includeSnippets: true`). */\n  snippet?: string;\n}>;\n\nexport type VectorSearchHit<N = Node> = Readonly<{\n  node: N;\n  score: number;\n  rank: number;\n}>;\n\n/**\n * A hybrid search hit. Both sub-results (`vector`, `fulltext`) carry the\n * same narrowed node type as the top-level `node` for ergonomic access.\n */\nexport type HybridSearchHit<N = Node> = Readonly<{\n  node: N;\n  /** Fused RRF score (higher is better). */\n  score: number;\n  /** 1-based rank in the fused list. */\n  rank: number;\n  /** Sub-result from the vector half, if it ranked this node. */\n  vector?: VectorSearchHit<N>;\n  /** Sub-result from the fulltext half, if it ranked this node. */\n  fulltext?: FulltextSearchHit<N>;\n}>;\n\n/**\n * Scope options shared by every facade search leg.\n *\n * `where` and `includeSubClasses` compile into the search statement's\n * candidate set (a subquery produced by the store's own query compiler), so\n * filtering happens INSIDE the engine's top-k — never by post-filtering a\n * ranked list. `offset` is rank-relative pagination: the engine fetches\n * `limit + offset` ranked candidates and discards the leading page.\n */\nexport type SearchScopeOptions<N extends NodeType = NodeType> = Readonly<{\n  /**\n   * Predicate over the node's properties, compiled by the shared query\n   * compiler into the candidate subquery. Requires a query-capable store.\n   * The facade instantiates `N` to the searched kind's node type, so the\n   * accessor is fully typed at the call site; the base instantiation\n   * exposes the system accessors (`id`, `kind`) for standalone option\n   * values.\n   */\n  where?: (accessor: NodeAccessor<N>) => Predicate;\n  /** Rows to skip after ranking (rank-relative pagination). */\n  offset?: number;\n  /**\n   * Expand the searched kind to include its `subClassOf` descendants.\n   * Vector legs search each declaring kind's storage and merge by score;\n   * kinds that don't declare the embedding field are skipped (mirroring\n   * the query builder). Requires a query-capable store.\n   */\n  includeSubClasses?: boolean;\n}>;\n\nexport type FulltextSearchOptions<N extends NodeType = NodeType> =\n  SearchScopeOptions<N> &\n    Readonly<{\n      /** The user-supplied query string. */\n      query: string;\n      /** Max results. Required. */\n      limit: number;\n      /** Query parser mode. Default: \"websearch\". */\n      mode?: FulltextQueryMode;\n      /**\n       * Language override for query parsing. Default: the kind's\n       * declared language (the same config rows were indexed with),\n       * which keeps the parsed tsquery a plan-time constant on\n       * PostgreSQL so the GIN index can serve the match.\n       */\n      language?: string;\n      /** Minimum relevance score to include in results. */\n      minScore?: number;\n      /** Return a highlighted snippet alongside each hit. */\n      includeSnippets?: boolean;\n    }>;\n\nexport type HybridVectorOptions = Readonly<{\n  /** Field path of the embedding column on the node kind. */\n  fieldPath: string;\n  /** Query embedding to compare against. */\n  queryEmbedding: readonly number[];\n  /** Distance metric. Default: \"cosine\". */\n  metric?: VectorMetric;\n  /** How many candidates to retrieve from the vector side. Default: 4 * limit. */\n  k?: number;\n  /** Minimum similarity to include (units depend on metric). */\n  minScore?: number;\n  /**\n   * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n   * The vector side over-fetches `k` (default `4 * limit`) candidates;\n   * `efSearch` must be `>= k` for the index to surface that many\n   * neighbors, and ~2–4× `k` is the high-recall target. PostgreSQL\n   * requires an HNSW index and a transaction-capable driver, refusing the\n   * option with a typed error otherwise. Engines with no frontier knob at\n   * all (sqlite-vec, libSQL DiskANN) refuse it too, rather than searching\n   * as if it had not been passed. See `VectorSearchOptions.efSearch`.\n   */\n  efSearch?: number;\n}>;\n\n/**\n * Options for the standalone `store.search.vector` path. Mirrors the\n * vector half of `HybridSearchOptions` but flattens it because the\n * standalone path doesn't fuse against fulltext.\n */\nexport type VectorSearchOptions<N extends NodeType = NodeType> =\n  SearchScopeOptions<N> &\n    Readonly<{\n      /** Field path of the embedding column on the node kind. */\n      fieldPath: string;\n      /** Query embedding to compare against. */\n      queryEmbedding: readonly number[];\n      /** Max results. Required. */\n      limit: number;\n      /** Distance metric. Default: \"cosine\". */\n      metric?: VectorMetric;\n      /** Minimum similarity to include (units depend on metric). */\n      minScore?: number;\n      /**\n       * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n       * Sizes the dynamic candidate list the index scan maintains — higher\n       * trades latency for recall. The floor for the index to surface\n       * `limit` neighbors is `efSearch >= limit`; ~2–4× is the high-recall\n       * target on million-scale corpora. Lets a latency-sensitive\n       * interactive path and a recall-sensitive batch path share one\n       * connection pool, tuning per query rather than per session.\n       *\n       * PostgreSQL HNSW only: applied transaction-locally via `SET LOCAL`.\n       * Everywhere else the option is REFUSED with a typed error naming the\n       * state, never silently ignored — a non-HNSW slot or a driver that\n       * cannot hold a transaction (for example `drizzle-orm/neon-http`) on\n       * PostgreSQL, and any SQLite backend, since neither sqlite-vec's vec0\n       * KNN nor libSQL's `vector_top_k` has a per-search frontier to set.\n       * `backend.capabilities.vector.searchFrontierTuning` states which you\n       * have. Must be a positive integer; pgvector caps it at 1000.\n       */\n      efSearch?: number;\n    }>;\n\nexport type HybridFulltextOptions = Readonly<{\n  query: string;\n  /** How many candidates to retrieve from the fulltext side. Default: 4 * limit. */\n  k?: number;\n  mode?: FulltextQueryMode;\n  language?: string;\n  minScore?: number;\n  includeSnippets?: boolean;\n}>;\n\nexport type HybridSearchOptions<N extends NodeType = NodeType> =\n  SearchScopeOptions<N> &\n    Readonly<{\n      vector: HybridVectorOptions;\n      fulltext: HybridFulltextOptions;\n      fusion?: HybridFusionOptions;\n      /** Final number of fused results to return. Required. */\n      limit: number;\n    }>;\n\ntype StoreSearchContext = Readonly<{\n  graphId: string;\n  backend: GraphBackend;\n  registry: KindRegistry;\n  /**\n   * Builds a fresh query for candidate compilation (`store.query()`, the\n   * same seam collection `find({ where })` uses). Optional so a bare\n   * context still supports unscoped searches; `where` /\n   * `includeSubClasses` throw without it.\n   */\n  createQuery?: () => QueryBuilder<GraphDef>;\n  /**\n   * The threaded `batchPointRead` verdict — resolved once at `store.ts`,\n   * never re-resolved here. Optional at this boundary: `StoreSearchContext`\n   * is a contravariant (externally-authorable) position, so a new REQUIRED\n   * member here would be a breaking change (`scripts/api-surface-compat.ts`).\n   * Required after resolution instead, the same pattern\n   * `CompileQueryOptions.recursiveTraversal` uses — `store.ts`'s `search`\n   * getter always populates it, and every internal reader asserts it with\n   * `requireDefined`.\n   */\n  batchPointRead?: BundleVerdictOf<typeof BATCH_POINT_READ> | undefined;\n}>;\n\n/**\n * Internal alias for the candidate query. The compiled query prefixes its\n * output columns with the alias, so the id column is `\"_sc_id\"`.\n */\nconst SEARCH_CANDIDATE_ALIAS = \"_sc\";\n\n/**\n * Compiles the candidate subquery for one kind: the ids of nodes a search\n * statement may rank. Runs the store's own query compiler, so the\n * predicate, valid-time currency, tombstone exclusion, and graph scoping\n * are exactly the semantics of a `current` read — search can never return\n * (or lose top-k slots to) rows a `find()` would not see.\n *\n * Compiled ONLY when a `where` predicate exists: the unfiltered case\n * returns `undefined` so the backend supplies its flat, parameter-bound\n * current-read candidates (same semantics, far cheaper — the compiled\n * query's per-row SQL now() currency checks measurably dominated\n * unfiltered facade searches on SQLite and planned poorly on Postgres).\n */\nfunction buildKindCandidates(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  where: ((accessor: NodeAccessor<NodeType>) => Predicate) | undefined,\n): SqlFragment | undefined {\n  if (where === undefined) return undefined;\n  if (ctx.createQuery === undefined) {\n    throw new ConfigurationError(\n      \"search with a where predicate requires a query-capable store\",\n      { capability: \"search\", graphId: ctx.graphId },\n    );\n  }\n  const chain = ctx\n    .createQuery()\n    .from(nodeKind, SEARCH_CANDIDATE_ALIAS)\n    .whereNode(SEARCH_CANDIDATE_ALIAS, where);\n  const compiled = chain\n    .select(\n      (aliases: Record<string, unknown>) => aliases[SEARCH_CANDIDATE_ALIAS],\n    )\n    .compile();\n  return sql`SELECT ${sql.raw(`\"${SEARCH_CANDIDATE_ALIAS}_id\"`)} AS node_id FROM (${compiled}) AS tg_search_candidates`;\n}\n\n/**\n * The kinds one search call spans: the kind itself, plus its `subClassOf`\n * descendants when requested.\n */\nfunction resolveSearchKinds(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  includeSubClasses: boolean | undefined,\n): readonly string[] {\n  if (includeSubClasses !== true) return [nodeKind];\n  if (ctx.createQuery === undefined) {\n    throw new ConfigurationError(\n      \"search with includeSubClasses requires a query-capable store\",\n      { capability: \"search\", graphId: ctx.graphId },\n    );\n  }\n  return ctx.registry.expandSubClasses(nodeKind);\n}\n\nfunction assertSearchOffset(offset: number | undefined, label: string): void {\n  if (offset === undefined) return;\n  if (!Number.isInteger(offset) || offset < 0) {\n    throw new RangeError(\n      `${label} must be a non-negative integer, got: ${offset}`,\n    );\n  }\n}\n\n/**\n * The language a fulltext query should be parsed with for one kind: the\n * caller's explicit override, else the kind's DECLARED language (the one\n * its rows were written with). Passing the declared language keeps the\n * tsquery CONSTANT, so PostgreSQL's GIN index on `tsv` can serve the\n * match — the per-row `websearch_to_tsquery(\"language\", ...)` fallback\n * (used only when the kind declares no searchable fields) forces a scan.\n */\nfunction effectiveFulltextLanguage(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  override: string | undefined,\n): string | undefined {\n  if (override !== undefined) return override;\n  const nodeType = ctx.registry.getNodeType(nodeKind);\n  if (nodeType === undefined) return undefined;\n  return resolveDeclaredFulltextLanguage(nodeType.schema);\n}\n\n/** A ranked row tagged with the kind whose search leg produced it. */\ntype RankedSourceRow = Readonly<{\n  kind: string;\n  nodeId: string;\n  score: number;\n  snippet?: string;\n}>;\n\n/** Node ids are unique per kind, not globally — key hydration by both. */\nfunction searchNodeKey(kind: string, nodeId: string): string {\n  return `${kind}\\u0000${nodeId}`;\n}\n\n/**\n * Whether higher scores rank first for a metric. Cosine scores are\n * similarities (`1 - distance`); l2 / inner_product scores are the raw\n * distance expression, where lower is better (matching each strategy's\n * `ORDER BY distance ASC`).\n */\nfunction scoreDescending(metric: VectorMetric): boolean {\n  return metric === \"cosine\";\n}\n\n/**\n * Hydrates ranked rows spanning multiple kinds. One batched fetch per\n * kind, results keyed by {@link searchNodeKey}.\n */\nasync function fetchNodesForRows(\n  backend: GraphBackend,\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>,\n  graphId: string,\n  rows: readonly RankedSourceRow[],\n): Promise<Map<string, Node>> {\n  const idsByKind = new Map<string, Set<string>>();\n  for (const row of rows) {\n    const ids = idsByKind.get(row.kind) ?? new Set<string>();\n    ids.add(row.nodeId);\n    idsByKind.set(row.kind, ids);\n  }\n  const map = new Map<string, Node>();\n  await Promise.all(\n    [...idsByKind].map(async ([kind, ids]) => {\n      const kindMap = await fetchNodesByIds(\n        backend,\n        batchPointRead,\n        graphId,\n        kind,\n        [...ids],\n      );\n      for (const [id, node] of kindMap) {\n        map.set(searchNodeKey(kind, id), node);\n      }\n    }),\n  );\n  return map;\n}\n\n/**\n * Resolved storage identity of one embedding field on a concrete node\n * kind — the `(dimensions, metric, indexType)` the backend needs (in\n * addition to the runtime `metric` override) to address the field's\n * typed per-`(kind, field)` storage slot during search.\n */\ntype ResolvedSearchSlot = Readonly<{\n  dimensions: number;\n  metric: VectorMetric;\n  indexType: VectorIndexType;\n}>;\n\n/**\n * Resolves the `(dimensions, metric, indexType)` for a node kind's\n * embedding field from the registered node schema's `embedding()`\n * declaration. Throws a `ConfigurationError` when the kind has no such\n * embedding field so the caller gets a clear boundary error instead of a\n * downstream missing-table failure.\n */\nfunction tryResolveSearchSlot(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  fieldPath: string,\n): ResolvedSearchSlot | undefined {\n  const nodeType = ctx.registry.getNodeType(nodeKind);\n  if (nodeType === undefined) return undefined;\n  const fields = getEmbeddingFields(nodeType.schema);\n  const field = fields.find((entry) => entry.fieldPath === fieldPath);\n  if (field === undefined) return undefined;\n  return {\n    dimensions: field.dimensions,\n    metric: field.metric,\n    indexType: field.indexType,\n  };\n}\n\nfunction resolveSearchSlot(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  fieldPath: string,\n): ResolvedSearchSlot {\n  const slot = tryResolveSearchSlot(ctx, nodeKind, fieldPath);\n  if (slot !== undefined) return slot;\n  throw new ConfigurationError(\n    `Node kind \"${nodeKind}\" has no embedding field \"${fieldPath}\". ` +\n      `Declare it with embedding(dimensions) on the node schema.`,\n    { capability: \"vector\", graphId: ctx.graphId },\n  );\n}\n\nexport async function executeFulltextSearch<N = Node>(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  options: FulltextSearchOptions,\n): Promise<readonly FulltextSearchHit<N>[]> {\n  const { backend, graphId } = ctx;\n  refuseUnlessFulltextAvailable(backend, \"fulltextSearch\");\n  if (!backend.fulltextSearch) {\n    throw new ConfigurationError(\"Backend does not support fulltext search\", {\n      backend: backend.dialect,\n      capability: \"fulltext\",\n    });\n  }\n  if (!Number.isInteger(options.limit) || options.limit <= 0) {\n    throw new RangeError(\n      `fulltextSearch.limit must be a positive integer, got: ${options.limit}`,\n    );\n  }\n  assertSearchOffset(options.offset, \"fulltextSearch.offset\");\n  validateFulltextCallOptions(backend, {\n    mode: options.mode,\n    includeSnippets: options.includeSnippets,\n    language: options.language,\n  });\n\n  const kinds = resolveSearchKinds(ctx, nodeKind, options.includeSubClasses);\n  const offset = options.offset ?? 0;\n  const singleKind = kinds.length === 1;\n\n  const perKindRows = await Promise.all(\n    kinds.map(async (kind): Promise<readonly RankedSourceRow[]> => {\n      const candidates = buildKindCandidates(ctx, kind, options.where);\n      const language = effectiveFulltextLanguage(ctx, kind, options.language);\n      const rows = await requireDefined(backend.fulltextSearch)({\n        graphId,\n        nodeKind: kind,\n        query: options.query,\n        // A single kind pushes the page into SQL; multiple kinds fetch\n        // each kind's full page-covering prefix and re-slice after merge.\n        limit: singleKind ? options.limit : options.limit + offset,\n        ...(singleKind && offset > 0 ? { offset } : {}),\n        ...(candidates === undefined ? {} : { candidates }),\n        ...(options.mode ? { mode: options.mode } : {}),\n        ...(language === undefined ? {} : { language }),\n        ...(options.minScore === undefined ?\n          {}\n        : { minScore: options.minScore }),\n        ...(options.includeSnippets === undefined ?\n          {}\n        : { includeSnippets: options.includeSnippets }),\n      });\n      return rows.map((row) => ({\n        kind,\n        nodeId: row.nodeId,\n        score: row.score,\n        ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n      }));\n    }),\n  );\n\n  const merged =\n    singleKind ?\n      requireDefined(perKindRows[0])\n    : perKindRows\n        .flat()\n        .toSorted(\n          (a, b) =>\n            b.score - a.score ||\n            compareCodePoints(a.kind, b.kind) ||\n            compareCodePoints(a.nodeId, b.nodeId),\n        )\n        .slice(offset, offset + options.limit);\n  if (merged.length === 0) return [];\n\n  const nodeMap = await fetchNodesForRows(\n    backend,\n    requireDefined(ctx.batchPointRead),\n    graphId,\n    merged,\n  );\n\n  const hits: FulltextSearchHit<N>[] = [];\n  let rank = 1;\n  for (const row of merged) {\n    const node = nodeMap.get(searchNodeKey(row.kind, row.nodeId));\n    if (!node) continue;\n    hits.push({\n      node: node as N,\n      score: row.score,\n      rank,\n      ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n    });\n    rank += 1;\n  }\n  return hits;\n}\n\nexport async function executeVectorSearch<N = Node>(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  options: VectorSearchOptions,\n): Promise<readonly VectorSearchHit<N>[]> {\n  const { backend, graphId } = ctx;\n  if (!backend.vectorSearch) {\n    throw new ConfigurationError(\"Backend does not support vector search\", {\n      backend: backend.dialect,\n      capability: \"vector\",\n    });\n  }\n  if (!Number.isInteger(options.limit) || options.limit <= 0) {\n    throw new RangeError(\n      `vectorSearch.limit must be a positive integer, got: ${options.limit}`,\n    );\n  }\n  assertEfSearch(options.efSearch, \"vectorSearch.efSearch\");\n  assertSearchOffset(options.offset, \"vectorSearch.offset\");\n\n  const searchKinds = resolveVectorSearchKinds(\n    ctx,\n    nodeKind,\n    options.fieldPath,\n    options.includeSubClasses,\n    \"vectorSearch\",\n  );\n  for (const { slot } of searchKinds) {\n    assertVectorQueryCompatible(\n      backend,\n      slot,\n      { metric: options.metric, queryEmbedding: options.queryEmbedding },\n      \"vectorSearch\",\n    );\n    assertMinScore(\n      options.minScore,\n      options.metric ?? slot.metric,\n      \"vectorSearch.minScore\",\n    );\n  }\n  const offset = options.offset ?? 0;\n  const singleKind = searchKinds.length === 1;\n  const metric = options.metric ?? requireDefined(searchKinds[0]).slot.metric;\n\n  const perKindRows = await Promise.all(\n    searchKinds.map(\n      async ({ kind, slot }): Promise<readonly RankedSourceRow[]> => {\n        const candidates = buildKindCandidates(ctx, kind, options.where);\n        const rows = await requireDefined(backend.vectorSearch)({\n          graphId,\n          nodeKind: kind,\n          fieldPath: options.fieldPath,\n          queryEmbedding: options.queryEmbedding,\n          // Default to the field's DECLARED metric (the metric its index was\n          // built for); only an explicit caller override changes it.\n          // Defaulting to cosine here would mis-rank l2 / inner_product\n          // fields and bypass their ANN index.\n          metric,\n          dimensions: slot.dimensions,\n          indexType: slot.indexType,\n          // A single kind pushes the page into SQL; multiple kinds fetch\n          // each kind's full page-covering prefix and re-slice after merge.\n          limit: singleKind ? options.limit : options.limit + offset,\n          ...(singleKind && offset > 0 ? { offset } : {}),\n          ...(candidates === undefined ? {} : { candidates }),\n          ...(options.minScore === undefined ?\n            {}\n          : { minScore: options.minScore }),\n          ...(options.efSearch === undefined ?\n            {}\n          : { efSearch: options.efSearch }),\n        });\n        return rows.map((row) => ({\n          kind,\n          nodeId: row.nodeId,\n          score: row.score,\n        }));\n      },\n    ),\n  );\n\n  const merged =\n    singleKind ?\n      requireDefined(perKindRows[0])\n    : mergeVectorRows(perKindRows, metric).slice(\n        offset,\n        offset + options.limit,\n      );\n  if (merged.length === 0) return [];\n\n  const nodeMap = await fetchNodesForRows(\n    backend,\n    requireDefined(ctx.batchPointRead),\n    graphId,\n    merged,\n  );\n\n  const hits: VectorSearchHit<N>[] = [];\n  let rank = 1;\n  for (const row of merged) {\n    const node = nodeMap.get(searchNodeKey(row.kind, row.nodeId));\n    if (!node) continue;\n    hits.push({ node: node as N, score: row.score, rank });\n    rank += 1;\n  }\n  return hits;\n}\n\n/** One vector-search target: a kind and its resolved embedding slot. */\ntype VectorSearchKind = Readonly<{ kind: string; slot: ResolvedSearchSlot }>;\n\n/**\n * Resolves the kinds a vector search spans, keeping only kinds that\n * declare the embedding field (mirroring the query builder, which skips\n * non-declaring kinds instead of referencing a table that was never\n * created). Enforces one shared declared metric across the expansion:\n * scores from different metrics cannot be merged into one ranking, and a\n * per-call metric override cannot bridge the gap either (each kind's\n * storage is built for — and validated against — its declared metric), so\n * mixed declared metrics are unsupported for cross-kind ranking.\n */\nfunction resolveVectorSearchKinds(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  fieldPath: string,\n  includeSubClasses: boolean | undefined,\n  label: string,\n): readonly VectorSearchKind[] {\n  const kinds = resolveSearchKinds(ctx, nodeKind, includeSubClasses);\n  const resolved: VectorSearchKind[] = [];\n  for (const kind of kinds) {\n    const slot = tryResolveSearchSlot(ctx, kind, fieldPath);\n    if (slot !== undefined) resolved.push({ kind, slot });\n  }\n  // No declaring kind: surface the standard configuration error for the\n  // requested kind.\n  if (resolved.length === 0) resolveSearchSlot(ctx, nodeKind, fieldPath);\n  const metrics = new Set(resolved.map(({ slot }) => slot.metric));\n  if (metrics.size > 1) {\n    throw new ConfigurationError(\n      `${label}: kinds expanded from \"${nodeKind}\" declare different ` +\n        `metrics for \"${fieldPath}\" (${[...metrics].join(\", \")}). ` +\n        `Cross-kind vector ranking requires one shared declared metric — ` +\n        `search the kinds separately.`,\n      { capability: \"vector\", graphId: ctx.graphId },\n    );\n  }\n  return resolved;\n}\n\n/**\n * Merges per-kind ranked rows into one globally ordered list.\n *\n * Applied even to a single kind's rows, whose SQL already ordered them. The\n * vector source SQL breaks a score tie arbitrarily (no `node_id` tiebreak — a\n * second sort key would cost pgvector its ordered index scan), so trusting its\n * arrival order would make the rank a source of nondeterminism. The\n * single-statement hybrid path re-ranks the very same rows with\n * `ROW_NUMBER() OVER (ORDER BY score …, node_id)`; this is that window, in JS.\n * Ranks feed the fusion, so the two paths must assign them identically.\n */\nfunction mergeVectorRows(\n  perKindRows: readonly (readonly RankedSourceRow[])[],\n  metric: VectorMetric,\n): readonly RankedSourceRow[] {\n  const descending = scoreDescending(metric);\n  return perKindRows\n    .flat()\n    .toSorted(\n      (a, b) =>\n        (descending ? b.score - a.score : a.score - b.score) ||\n        compareCodePoints(a.kind, b.kind) ||\n        compareCodePoints(a.nodeId, b.nodeId),\n    );\n}\n\n/** {@link mergeVectorRows} for the fulltext leg, whose score always descends. */\nfunction mergeFulltextRows(\n  perKindRows: readonly (readonly RankedSourceRow[])[],\n): readonly RankedSourceRow[] {\n  return perKindRows\n    .flat()\n    .toSorted(\n      (a, b) =>\n        b.score - a.score ||\n        compareCodePoints(a.kind, b.kind) ||\n        compareCodePoints(a.nodeId, b.nodeId),\n    );\n}\n\nexport async function executeHybridSearch<N = Node>(\n  ctx: StoreSearchContext,\n  nodeKind: string,\n  options: HybridSearchOptions,\n): Promise<readonly HybridSearchHit<N>[]> {\n  const { backend, graphId } = ctx;\n  // Checked ahead of the vector gate so a fulltext-off backend refuses on\n  // the fulltext leg regardless of what the vector leg supports.\n  refuseUnlessFulltextAvailable(backend, \"hybridSearch\");\n  if (!backend.vectorSearch) {\n    throw new ConfigurationError(\"Backend does not support vector search\", {\n      backend: backend.dialect,\n      capability: \"vector\",\n    });\n  }\n  if (!backend.fulltextSearch) {\n    throw new ConfigurationError(\"Backend does not support fulltext search\", {\n      backend: backend.dialect,\n      capability: \"fulltext\",\n    });\n  }\n  if (!Number.isInteger(options.limit) || options.limit <= 0) {\n    throw new RangeError(\n      `hybridSearch.limit must be a positive integer, got: ${options.limit}`,\n    );\n  }\n\n  if (options.fusion !== undefined) {\n    validateHybridFusionOptions(options.fusion);\n  }\n  assertEfSearch(options.vector.efSearch, \"hybridSearch.vector.efSearch\");\n\n  validateFulltextCallOptions(backend, {\n    mode: options.fulltext.mode,\n    includeSnippets: options.fulltext.includeSnippets,\n    language: options.fulltext.language,\n  });\n\n  assertSearchOffset(options.offset, \"hybridSearch.offset\");\n\n  const fusionK = options.fusion?.k ?? DEFAULT_RRF_K;\n  const vectorWeight = options.fusion?.weights?.vector ?? DEFAULT_RRF_WEIGHT;\n  const fulltextWeight =\n    options.fusion?.weights?.fulltext ?? DEFAULT_RRF_WEIGHT;\n  const offset = options.offset ?? 0;\n  // Over-fetch covers the requested page: fused top-(limit+offset) needs\n  // deep-enough per-source prefixes.\n  const overFetchMultiplier = 4;\n  const pageLimit = options.limit + offset;\n  const vectorK = options.vector.k ?? pageLimit * overFetchMultiplier;\n  const fulltextK = options.fulltext.k ?? pageLimit * overFetchMultiplier;\n\n  // The fulltext half spans every expanded kind; the vector half only the\n  // kinds that declare the embedding field (mirroring the query builder's\n  // treatment of non-declaring kinds).\n  const fulltextKinds = resolveSearchKinds(\n    ctx,\n    nodeKind,\n    options.includeSubClasses,\n  );\n  const vectorKinds = resolveVectorSearchKinds(\n    ctx,\n    nodeKind,\n    options.vector.fieldPath,\n    options.includeSubClasses,\n    \"hybridSearch.vector\",\n  );\n  for (const { slot } of vectorKinds) {\n    assertVectorQueryCompatible(\n      backend,\n      slot,\n      {\n        metric: options.vector.metric,\n        queryEmbedding: options.vector.queryEmbedding,\n      },\n      \"hybridSearch.vector\",\n    );\n    assertMinScore(\n      options.vector.minScore,\n      options.vector.metric ?? slot.metric,\n      \"hybridSearch.vector.minScore\",\n    );\n  }\n  const vectorMetric =\n    options.vector.metric ?? requireDefined(vectorKinds[0]).slot.metric;\n\n  // One candidate subquery per kind, shared by both halves.\n  const candidatesByKind = new Map<string, SqlFragment | undefined>();\n  for (const kind of fulltextKinds) {\n    candidatesByKind.set(kind, buildKindCandidates(ctx, kind, options.where));\n  }\n  for (const { kind } of vectorKinds) {\n    if (!candidatesByKind.has(kind)) {\n      candidatesByKind.set(kind, buildKindCandidates(ctx, kind, options.where));\n    }\n  }\n\n  // Single-statement fast path: one kind, backend support. Both sources,\n  // fusion, liveness, and hydration compose into ONE statement (see\n  // `buildHybridSearchStatement`) — the multi-statement path below remains\n  // for kind expansions and backends without the member.\n  if (\n    backend.hybridSearch !== undefined &&\n    fulltextKinds.length === 1 &&\n    vectorKinds.length === 1 &&\n    fulltextKinds[0] === requireDefined(vectorKinds[0]).kind\n  ) {\n    const kind = fulltextKinds[0];\n    const { slot } = requireDefined(vectorKinds[0]);\n    const candidates = candidatesByKind.get(kind);\n    const hybridFulltextLanguage = effectiveFulltextLanguage(\n      ctx,\n      kind,\n      options.fulltext.language,\n    );\n    const rows = await backend.hybridSearch({\n      graphId,\n      nodeKind: kind,\n      vector: {\n        fieldPath: options.vector.fieldPath,\n        queryEmbedding: options.vector.queryEmbedding,\n        metric: vectorMetric,\n        dimensions: slot.dimensions,\n        indexType: slot.indexType,\n        k: vectorK,\n        ...(options.vector.minScore === undefined ?\n          {}\n        : { minScore: options.vector.minScore }),\n        ...(options.vector.efSearch === undefined ?\n          {}\n        : { efSearch: options.vector.efSearch }),\n      },\n      fulltext: {\n        query: options.fulltext.query,\n        k: fulltextK,\n        ...(options.fulltext.mode ? { mode: options.fulltext.mode } : {}),\n        ...(hybridFulltextLanguage === undefined ?\n          {}\n        : { language: hybridFulltextLanguage }),\n        ...(options.fulltext.minScore === undefined ?\n          {}\n        : { minScore: options.fulltext.minScore }),\n        ...(options.fulltext.includeSnippets === undefined ?\n          {}\n        : { includeSnippets: options.fulltext.includeSnippets }),\n      },\n      fusion: { k: fusionK, vectorWeight, fulltextWeight },\n      limit: options.limit,\n      ...(offset === 0 ? {} : { offset }),\n      ...(candidates === undefined ? {} : { candidates }),\n    });\n    return rows.map((row, index) => {\n      const typedNode = rowToNode(row.node) as N;\n      return {\n        node: typedNode,\n        score: row.fusedScore,\n        rank: index + 1,\n        ...(row.vectorRank !== undefined && row.vectorScore !== undefined ?\n          {\n            vector: {\n              node: typedNode,\n              score: row.vectorScore,\n              rank: row.vectorRank,\n            },\n          }\n        : {}),\n        ...(row.fulltextRank !== undefined && row.fulltextScore !== undefined ?\n          {\n            fulltext: {\n              node: typedNode,\n              score: row.fulltextScore,\n              rank: row.fulltextRank,\n              ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n            },\n          }\n        : {}),\n      };\n    });\n  }\n\n  const vectorPromise = Promise.all(\n    vectorKinds.map(\n      async ({ kind, slot }): Promise<readonly RankedSourceRow[]> => {\n        const candidates = candidatesByKind.get(kind);\n        const rows = await requireDefined(backend.vectorSearch)({\n          graphId,\n          nodeKind: kind,\n          fieldPath: options.vector.fieldPath,\n          queryEmbedding: options.vector.queryEmbedding,\n          // Default to the field's declared metric (see executeVectorSearch).\n          metric: vectorMetric,\n          dimensions: slot.dimensions,\n          indexType: slot.indexType,\n          limit: vectorK,\n          ...(candidates === undefined ? {} : { candidates }),\n          ...(options.vector.minScore === undefined ?\n            {}\n          : { minScore: options.vector.minScore }),\n          ...(options.vector.efSearch === undefined ?\n            {}\n          : { efSearch: options.vector.efSearch }),\n        });\n        return rows.map((row) => ({\n          kind,\n          nodeId: row.nodeId,\n          score: row.score,\n        }));\n      },\n    ),\n  ).then((perKind) => mergeVectorRows(perKind, vectorMetric).slice(0, vectorK));\n\n  const fulltextPromise = Promise.all(\n    fulltextKinds.map(async (kind): Promise<readonly RankedSourceRow[]> => {\n      const candidates = candidatesByKind.get(kind);\n      const language = effectiveFulltextLanguage(\n        ctx,\n        kind,\n        options.fulltext.language,\n      );\n      const rows = await requireDefined(backend.fulltextSearch)({\n        graphId,\n        nodeKind: kind,\n        query: options.fulltext.query,\n        limit: fulltextK,\n        ...(candidates === undefined ? {} : { candidates }),\n        ...(options.fulltext.mode ? { mode: options.fulltext.mode } : {}),\n        ...(language === undefined ? {} : { language }),\n        ...(options.fulltext.minScore === undefined ?\n          {}\n        : { minScore: options.fulltext.minScore }),\n        ...(options.fulltext.includeSnippets === undefined ?\n          {}\n        : { includeSnippets: options.fulltext.includeSnippets }),\n      });\n      return rows.map((row) => ({\n        kind,\n        nodeId: row.nodeId,\n        score: row.score,\n        ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n      }));\n    }),\n  ).then((perKind) => mergeFulltextRows(perKind).slice(0, fulltextK));\n\n  const [vectorRows, fulltextRows] = await Promise.all([\n    vectorPromise,\n    fulltextPromise,\n  ]);\n\n  // RRF fusion. The classic formula is score = Σ_src 1 / (k + rank_src).\n  // Per-source weights extend it to a weighted sum.\n  interface FusedEntry {\n    kind: string;\n    nodeId: string;\n    fusedScore: number;\n    vectorRank?: number;\n    vectorScore?: number;\n    fulltextRank?: number;\n    fulltextScore?: number;\n    fulltextSnippet?: string;\n  }\n  const fused = new Map<string, FusedEntry>();\n\n  for (const [index, row] of vectorRows.entries()) {\n    const rank = index + 1;\n    const contribution = vectorWeight / (fusionK + rank);\n    const key = searchNodeKey(row.kind, row.nodeId);\n    const entry = fused.get(key) ?? {\n      kind: row.kind,\n      nodeId: row.nodeId,\n      fusedScore: 0,\n    };\n    entry.fusedScore += contribution;\n    entry.vectorRank = rank;\n    entry.vectorScore = row.score;\n    fused.set(key, entry);\n  }\n\n  for (const [index, row] of fulltextRows.entries()) {\n    const rank = index + 1;\n    const contribution = fulltextWeight / (fusionK + rank);\n    const key = searchNodeKey(row.kind, row.nodeId);\n    const entry = fused.get(key) ?? {\n      kind: row.kind,\n      nodeId: row.nodeId,\n      fusedScore: 0,\n    };\n    entry.fusedScore += contribution;\n    entry.fulltextRank = rank;\n    entry.fulltextScore = row.score;\n    if (row.snippet !== undefined) {\n      entry.fulltextSnippet = row.snippet;\n    }\n    fused.set(key, entry);\n  }\n\n  // Code points, not code units: the single-statement path breaks the same tie\n  // with `ORDER BY fused_score DESC, node_id` under SQLite's BINARY collation\n  // or Postgres's forced `C` collation (see `buildHybridSearchStatement`). A\n  // fused-score tie at the page boundary must pick the same winner on both\n  // paths, and only code-point order agrees with byte order.\n  const ranked = [...fused.values()]\n    .toSorted(\n      (a, b) =>\n        b.fusedScore - a.fusedScore ||\n        compareCodePoints(a.kind, b.kind) ||\n        compareCodePoints(a.nodeId, b.nodeId),\n    )\n    .slice(offset, offset + options.limit);\n\n  const nodeMap = await fetchNodesForRows(\n    backend,\n    requireDefined(ctx.batchPointRead),\n    graphId,\n    ranked.map((entry) => ({\n      kind: entry.kind,\n      nodeId: entry.nodeId,\n      score: entry.fusedScore,\n    })),\n  );\n\n  const hits: HybridSearchHit<N>[] = [];\n  let rank = 1;\n  for (const entry of ranked) {\n    const node = nodeMap.get(searchNodeKey(entry.kind, entry.nodeId));\n    if (!node) continue;\n    const typedNode = node as N;\n    const hit: HybridSearchHit<N> = {\n      node: typedNode,\n      score: entry.fusedScore,\n      rank,\n      ...(entry.vectorRank !== undefined && entry.vectorScore !== undefined ?\n        {\n          vector: {\n            node: typedNode,\n            score: entry.vectorScore,\n            rank: entry.vectorRank,\n          },\n        }\n      : {}),\n      ...((\n        entry.fulltextRank !== undefined && entry.fulltextScore !== undefined\n      ) ?\n        {\n          fulltext: {\n            node: typedNode,\n            score: entry.fulltextScore,\n            rank: entry.fulltextRank,\n            ...(entry.fulltextSnippet === undefined ?\n              {}\n            : { snippet: entry.fulltextSnippet }),\n          },\n        }\n      : {}),\n    };\n    hits.push(hit);\n    rank += 1;\n  }\n  return hits;\n}\n\n/**\n * Validates the optional `efSearch` knob at the API boundary. Rejects\n * non-positive-integer values uniformly across backends — the\n * backend-specific ceiling (pgvector caps `hnsw.ef_search` at 1000) is\n * enforced on the Postgres path, and backends without an HNSW frontier\n * knob treat a valid value as a no-op.\n */\nfunction assertEfSearch(efSearch: number | undefined, label: string): void {\n  if (efSearch === undefined) return;\n  if (!Number.isInteger(efSearch) || efSearch <= 0) {\n    throw new RangeError(\n      `${label} must be a positive integer, got: ${efSearch}`,\n    );\n  }\n}\n\n/**\n * Validates the optional `minScore` filter at the API boundary, mirroring the\n * query-compiler vector pass. Rejects non-finite values for any metric and,\n * for cosine (where the score is `1 - distance` similarity), values outside\n * [-1, 1]. Without this a `NaN` minScore compiles to `distance <= (1 - NaN)`,\n * which matches nothing — a silent empty result instead of a clear error.\n */\nfunction assertMinScore(\n  minScore: number | undefined,\n  metric: VectorMetric,\n  label: string,\n): void {\n  if (minScore === undefined) return;\n  assertVectorMinScore(minScore, metric, label);\n}\n\n/**\n * Validates a vector search/hybrid call against the field's resolved slot:\n * an explicit `metric` override must match the field's declared metric (its\n * storage / ANN index is built for that metric), the declared metric must be\n * one the backend supports, and the query vector's length must match the\n * field's dimension. Rejects at the API boundary instead of surfacing an\n * opaque engine error from deep in `buildSearch`.\n */\nfunction assertVectorQueryCompatible(\n  backend: GraphBackend,\n  slot: ResolvedSearchSlot,\n  options: {\n    metric: VectorMetric | undefined;\n    queryEmbedding: readonly number[];\n  },\n  label: string,\n): void {\n  if (options.metric !== undefined && options.metric !== slot.metric) {\n    throw new ConfigurationError(\n      `${label}: metric \"${options.metric}\" does not match the field's declared metric \"${slot.metric}\". Vector storage is built for the declared metric — omit metric or pass \"${slot.metric}\".`,\n      { backend: backend.dialect, capability: \"vector\" },\n    );\n  }\n  const supported = backend.capabilities.vector?.metrics;\n  if (supported !== undefined && !supported.includes(slot.metric)) {\n    throw new ConfigurationError(\n      `${label}: backend \"${backend.dialect}\" does not support the \"${slot.metric}\" metric (supported: ${supported.join(\", \")}).`,\n      { backend: backend.dialect, capability: \"vector\" },\n    );\n  }\n  if (options.queryEmbedding.length !== slot.dimensions) {\n    throw new RangeError(\n      `${label}: queryEmbedding has ${options.queryEmbedding.length} dimensions, but \"${slot.dimensions}\" are declared for this field.`,\n    );\n  }\n}\n\n/**\n * The one gate every fulltext-touching store entry point consumes:\n * `resolveBackendFulltext` is the sole owner of \"is fulltext available on\n * this backend\", so `executeFulltextSearch` and `executeHybridSearch` both\n * refuse through it instead of re-deriving the decision from method\n * presence.\n */\nfunction refuseUnlessFulltextAvailable(\n  backend: GraphBackend,\n  operation: string,\n): void {\n  if (resolveBackendFulltext(backend) !== false) return;\n  throw new UnsupportedBackendCapabilityError(\n    operation,\n    \"fulltext\",\n    { backend: backend.dialect, reason: \"fulltext_unsupported\" },\n    \"This backend declares no fulltext capability: it was created with `fulltext: false`, or it omits `capabilities.fulltext`.\",\n  );\n}\n\ntype FulltextCallOptions = Readonly<{\n  mode: FulltextQueryMode | undefined;\n  includeSnippets: boolean | undefined;\n  language: string | undefined;\n}>;\n\n/**\n * Validates caller-supplied fulltext options against the active\n * `FulltextStrategy` (when present) or the declared `FulltextCapabilities`\n * projection (as a fallback). Strategy validation is authoritative:\n * `supportedModes` and `supportsLanguageOverride` reject options that the\n * capabilities projection would silently ignore (e.g. a `language`\n * override on the SQLite FTS5 strategy, whose tokenizer is fixed at\n * table-create time). Mode, snippets, and language are the fields\n * callers commonly get wrong; catching them here turns a downstream SQL\n * error — or worse, silent misbehavior — into a clear\n * `ConfigurationError` at the API boundary.\n */\nfunction validateFulltextCallOptions(\n  backend: GraphBackend,\n  options: FulltextCallOptions,\n): void {\n  const strategy = backend.fulltextStrategy;\n  const capabilities = backend.capabilities.fulltext;\n\n  if (options.mode !== undefined) {\n    validateFulltextMode(backend, strategy, capabilities, options.mode);\n  }\n  if (options.includeSnippets === true) {\n    validateFulltextSnippets(backend, strategy, capabilities);\n  }\n  if (options.language !== undefined) {\n    validateFulltextLanguageOption(\n      backend,\n      strategy,\n      capabilities,\n      options.language,\n    );\n  }\n}\n\nfunction validateFulltextMode(\n  backend: GraphBackend,\n  strategy: FulltextStrategy | undefined,\n  capabilities: FulltextCapabilities | undefined,\n  mode: FulltextQueryMode,\n): void {\n  if (strategy !== undefined) {\n    if (strategy.supportedModes.includes(mode)) return;\n    throw new ConfigurationError(\n      `Backend \"${backend.dialect}\" fulltext strategy \"${strategy.name}\" ` +\n        `does not support mode \"${mode}\". Supported modes: ${strategy.supportedModes.join(\", \")}`,\n      {\n        backend: backend.dialect,\n        strategy: strategy.name,\n        capability: `fulltext.modes.${mode}`,\n      },\n    );\n  }\n  if (mode === \"phrase\" && capabilities && !capabilities.phraseQueries) {\n    throw new ConfigurationError(\n      `Backend \"${backend.dialect}\" does not support phrase queries`,\n      { backend: backend.dialect, capability: \"fulltext.phraseQueries\" },\n    );\n  }\n}\n\nfunction validateFulltextSnippets(\n  backend: GraphBackend,\n  strategy: FulltextStrategy | undefined,\n  capabilities: FulltextCapabilities | undefined,\n): void {\n  const supportsSnippets =\n    strategy === undefined ?\n      capabilities?.highlighting !== false\n    : strategy.supportsSnippets;\n  if (supportsSnippets) return;\n  throw new ConfigurationError(\n    `Backend \"${backend.dialect}\" does not support snippet highlighting; ` +\n      `drop includeSnippets or switch to a backend where highlighting is supported`,\n    { backend: backend.dialect, capability: \"fulltext.highlighting\" },\n  );\n}\n\nfunction validateFulltextLanguageOption(\n  backend: GraphBackend,\n  strategy: FulltextStrategy | undefined,\n  capabilities: FulltextCapabilities | undefined,\n  language: string,\n): void {\n  if (strategy !== undefined && !strategy.supportsLanguageOverride) {\n    throw new ConfigurationError(\n      `Backend \"${backend.dialect}\" fulltext strategy \"${strategy.name}\" ` +\n        `does not honor a per-query \\`language\\` override ` +\n        `(its tokenizer is fixed at table-create time). ` +\n        `Drop the option, or pick a strategy that advertises \\`supportsLanguageOverride: true\\`.`,\n      {\n        backend: backend.dialect,\n        strategy: strategy.name,\n        capability: \"fulltext.languageOverride\",\n      },\n    );\n  }\n  if (capabilities !== undefined) {\n    warnIfLanguageNotAdvertised(backend.dialect, capabilities, language);\n  }\n}\n\n/**\n * Advisory language check — warn, don't throw. Postgres accepts any\n * installed regconfig at runtime, so a strict list would produce false\n * positives for extension-provided dictionaries.\n */\nfunction warnIfLanguageNotAdvertised(\n  dialect: string,\n  capabilities: FulltextCapabilities,\n  language: string,\n): void {\n  if (capabilities.languages.length === 0) return;\n  if (capabilities.languages.includes(language)) return;\n  if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n    return;\n  }\n  console.warn(\n    `[typegraph] fulltext language \"${language}\" is not in the advertised list ` +\n      `for dialect \"${dialect}\" (${capabilities.languages.join(\", \")}). ` +\n      `If your backend has this language installed this warning is safe to ignore.`,\n  );\n}\n\nasync function fetchNodesByIds(\n  backend: GraphBackend,\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>,\n  graphId: string,\n  nodeKind: string,\n  ids: readonly string[],\n): Promise<Map<string, Node>> {\n  if (ids.length === 0) return new Map();\n  const map = new Map<string, Node>();\n  const bound = bindExtraIfReachable(\n    backend,\n    batchPointRead.extras.getNodes,\n    BATCH_POINT_READ.id,\n  );\n  if (bound !== undefined) {\n    const rows = await bound.getNodes(graphId, nodeKind, ids);\n    for (const row of rows) {\n      // `getNodes` returns rows regardless of deleted_at. The search SQL\n      // already constrains top-k to live nodes; this skip is\n      // defense-in-depth for the window between the search statement and\n      // this hydration read (they are separate transactions, so a\n      // concurrent delete can land in between).\n      if (row.deleted_at !== undefined) continue;\n      map.set(row.id, rowToNode(row));\n    }\n    return map;\n  }\n  // Fallback: fetch one at a time. Slow, but only triggers on backends\n  // that haven't implemented the batched accessor.\n  for (const id of ids) {\n    const row = await backend.getNode(graphId, nodeKind, id);\n    if (row && row.deleted_at === undefined) map.set(row.id, rowToNode(row));\n  }\n  return map;\n}\n\nexport { type HybridFusionOptions } from \"../query/ast\";\n","/**\n * StoreSearch — store.search facade.\n *\n * Groups fulltext, vector, hybrid, and maintenance operations under one\n * namespace so the top-level Store API stays focused on CRUD + graph\n * traversal. The methods delegate to their respective execution\n * modules; this class exists to shape the surface and to gate kind\n * names through the registry — the kind argument is `string` so\n * graph-extension kinds (added via `store.evolve()`) work without a\n * type cast, with a runtime guard rejecting misspellings at the call\n * site.\n */\nimport { type BATCH_POINT_READ } from \"../backend/capabilities/bundle-registry\";\nimport {\n  batchPointReadVerdict,\n  type BundleVerdictOf,\n} from \"../backend/capabilities/resolve\";\nimport { type GraphBackend } from \"../backend/types\";\nimport { type GraphDef, type NodeKinds } from \"../core/define-graph\";\nimport { type NodeRegistration, type NodeType } from \"../core/types\";\nimport { KindNotFoundError } from \"../errors\";\nimport { type QueryBuilder } from \"../query/builder/query-builder\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n  rebuildFulltextIndex,\n  type RebuildFulltextOptions,\n  type RebuildFulltextResult,\n} from \"./fulltext-rebuild\";\nimport {\n  executeFulltextSearch,\n  executeHybridSearch,\n  executeVectorSearch,\n  type FulltextSearchHit,\n  type FulltextSearchOptions,\n  type HybridSearchHit,\n  type HybridSearchOptions,\n  type VectorSearchHit,\n  type VectorSearchOptions,\n} from \"./search\";\nimport { type Node } from \"./types\";\n\n/**\n * Resolves the hit's `node` type. Compile-time kinds keep their\n * narrowed `Node<N>`; kinds outside `G` (added via graph extension through\n * `store.evolve()`, or string variables the type system can't see)\n * widen to the base `Node` so callers don't need a cast.\n *\n * This is the same shape as `getNodeCollection` — the dynamic form\n * works for any registered kind, and the type narrows when (and only\n * when) the literal is statically known.\n */\ntype ResolveNode<G extends GraphDef, K extends string> =\n  K extends NodeKinds<G> ?\n    G[\"nodes\"][K] extends NodeRegistration<infer N extends NodeType> ?\n      Node<N>\n    : Node\n  : Node;\n\n/**\n * The registered `NodeType` behind a kind literal — the accessor-level\n * companion of {@link ResolveNode}, used to type `where` predicates.\n * Falls back to the base `NodeType` for dynamic (string) kinds.\n */\ntype ResolveNodeType<G extends GraphDef, K extends string> =\n  K extends NodeKinds<G> ?\n    G[\"nodes\"][K] extends NodeRegistration<infer N extends NodeType> ?\n      N\n    : NodeType\n  : NodeType;\n\ntype StoreSearchContext = Readonly<{\n  graphId: string;\n  backend: GraphBackend;\n  registry: KindRegistry;\n  createQuery?: () => QueryBuilder<GraphDef>;\n  /**\n   * The threaded `batchPointRead` verdict, resolved once per facade. Optional\n   * at this boundary for the same reason `search.ts`'s own\n   * `StoreSearchContext` is: a contravariant position, so a new required\n   * member would be a breaking change. The constructor resolves it when\n   * legacy callers omit it; `store.ts`'s `search` getter threads its\n   * already-resolved verdict through.\n   */\n  batchPointRead?: BundleVerdictOf<typeof BATCH_POINT_READ> | undefined;\n}>;\n\n/**\n * Search-related operations exposed via `store.search`.\n *\n * @example\n * ```typescript\n * // Fulltext only\n * const hits = await store.search.fulltext(\"Document\", {\n *   query: \"climate change\",\n *   limit: 10,\n *   includeSnippets: true,\n * });\n *\n * // Vector only — for extension kinds with embedding() modifiers,\n * // the auto-derived index serves this query.\n * const nearest = await store.search.vector(\"Document\", {\n *   fieldPath: \"embedding\",\n *   queryEmbedding: vec,\n *   limit: 10,\n * });\n *\n * // Hybrid: vector + fulltext, fused with RRF\n * const ranked = await store.search.hybrid(\"Document\", {\n *   limit: 10,\n *   vector: { fieldPath: \"embedding\", queryEmbedding: vec },\n *   fulltext: { query: \"climate change\" },\n * });\n *\n * // Rebuild after backfill / schema change\n * const stats = await store.search.rebuildFulltext();\n * ```\n *\n * Extension kinds added via `store.evolve(...)` work with all four\n * methods without a type cast — the kind argument is `string` and a\n * registry check rejects misspellings at the call site.\n */\nexport class StoreSearch<G extends GraphDef> {\n  readonly #context: StoreSearchContext;\n\n  constructor(context: StoreSearchContext) {\n    this.#context = {\n      ...context,\n      batchPointRead:\n        context.batchPointRead ?? batchPointReadVerdict(context.backend),\n    };\n  }\n\n  /**\n   * Runs a fulltext search against nodes of the given kind.\n   *\n   * Requires fields on the node schema declared with `searchable()`.\n   * The search hits the backend's fulltext index (tsvector + GIN on\n   * Postgres, FTS5 on SQLite — or whatever strategy the backend is\n   * configured with) and resolves the matching node IDs back to typed\n   * `Node` objects.\n   */\n  async fulltext<K extends string>(\n    nodeKind: K,\n    options: FulltextSearchOptions<ResolveNodeType<G, K>>,\n  ): Promise<readonly FulltextSearchHit<ResolveNode<G, K>>[]> {\n    this.#assertKindRegistered(nodeKind);\n    return executeFulltextSearch<ResolveNode<G, K>>(\n      this.#context,\n      nodeKind,\n      // Contravariance: the narrowed accessor callback is intentionally\n      // wider than the base instantiation the core helpers take.\n      options as unknown as FulltextSearchOptions,\n    );\n  }\n\n  /**\n   * Runs a vector similarity search against nodes of the given kind.\n   *\n   * Requires a field on the node schema declared with `embedding()`,\n   * either at compile time or via a graph extension (the auto-derived\n   * `VectorIndexDeclaration` flows through `materializeIndexes()` on\n   * the same path either way).\n   *\n   * Pure vector — no fulltext leg, no fusion. For combined\n   * vector+fulltext ranking, use `hybrid`.\n   */\n  async vector<K extends string>(\n    nodeKind: K,\n    options: VectorSearchOptions<ResolveNodeType<G, K>>,\n  ): Promise<readonly VectorSearchHit<ResolveNode<G, K>>[]> {\n    this.#assertKindRegistered(nodeKind);\n    return executeVectorSearch<ResolveNode<G, K>>(\n      this.#context,\n      nodeKind,\n      // Contravariance: the narrowed accessor callback is intentionally\n      // wider than the base instantiation the core helpers take.\n      options as unknown as VectorSearchOptions,\n    );\n  }\n\n  /**\n   * Runs a vector + fulltext hybrid search and fuses the results with\n   * Reciprocal Rank Fusion.\n   *\n   * RRF is rank-based, so it composes well across heterogeneous score\n   * scales (cosine similarity vs ts_rank_cd vs FTS5 BM25). Default\n   * over-fetch is 4× `limit` from each source — tune via `vector.k` /\n   * `fulltext.k` for higher-recall corpora.\n   */\n  async hybrid<K extends string>(\n    nodeKind: K,\n    options: HybridSearchOptions<ResolveNodeType<G, K>>,\n  ): Promise<readonly HybridSearchHit<ResolveNode<G, K>>[]> {\n    this.#assertKindRegistered(nodeKind);\n    return executeHybridSearch<ResolveNode<G, K>>(\n      this.#context,\n      nodeKind,\n      // Contravariance: the narrowed accessor callback is intentionally\n      // wider than the base instantiation the core helpers take.\n      options as unknown as HybridSearchOptions,\n    );\n  }\n\n  /**\n   * Rebuilds the fulltext index from existing node data.\n   *\n   * Use when:\n   * - A node kind gained a `searchable()` field after data was already\n   *   written and existing rows were never indexed.\n   * - The fulltext table was dropped / truncated.\n   * - `language` was changed on a `searchable()` field.\n   *\n   * Iterates nodes with keyset pagination (stable under shared\n   * timestamps and light concurrent writes), transacts per page, skips\n   * kinds with no searchable fields, and cleans up stale rows for\n   * soft-deleted nodes. Corrupt or non-object `props` are counted in\n   * `skipped` with their node IDs surfaced via `skippedIds` so operators\n   * can investigate. Concurrent hard-deletes between page fetches can\n   * be missed by a single pass — run during a maintenance window for\n   * full consistency.\n   */\n  async rebuildFulltext<K extends string>(\n    nodeKind?: K,\n    options: RebuildFulltextOptions = {},\n  ): Promise<RebuildFulltextResult> {\n    if (nodeKind !== undefined) this.#assertKindRegistered(nodeKind);\n    return rebuildFulltextIndex(\n      {\n        graphId: this.#context.graphId,\n        backend: this.#context.backend,\n        registry: this.#context.registry,\n      },\n      nodeKind,\n      options,\n    );\n  }\n\n  #assertKindRegistered(kind: string): void {\n    if (this.#context.registry.hasNodeType(kind)) return;\n    throw new KindNotFoundError(kind, \"node\", {\n      graphId: this.#context.graphId,\n      suggestion:\n        \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n    });\n  }\n}\n","/** Current-state population statistics and declared-schema validation. */\nimport { type z } from \"zod\";\n\nimport {\n  type GraphBackend,\n  type RowProps,\n  rowPropsToObject,\n} from \"../backend/types\";\nimport type { GraphDef } from \"../core/define-graph\";\nimport type { KindEntity } from \"../core/types\";\nimport {\n  SchemaMismatchError,\n  StaleVersionError,\n  TypeGraphError,\n  ValidationError,\n} from \"../errors\";\nimport type { SqlSchema } from \"../query/compiler/schema\";\nimport { compileTemporalFilter } from \"../query/compiler/temporal\";\nimport { decodeCursor, encodeCursor } from \"../query/cursor\";\nimport { getDialect } from \"../query/dialect\";\nimport {\n  encodeJsonPointerSegment,\n  type JsonPointer,\n} from \"../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { sortedReplacer } from \"../schema/canonical\";\nimport { serializeSchemaProperties } from \"../schema/serializer\";\nimport type { JsonSchema } from \"../schema/types\";\nimport { chunk } from \"../utils/array\";\nimport { nowIso } from \"../utils/date\";\nimport { sha256Hex } from \"../utils/hash\";\nimport type { SchemaIntrospection } from \"./introspect\";\n\nconst DEFAULT_VALIDATION_PAGE_SIZE = 100;\nconst MAX_VALIDATION_PAGE_SIZE = 1000;\n/**\n * Conservative width limit for each population query. PostgreSQL permits at\n * most 1,664 result columns and SQLite commonly permits 2,000.\n */\nconst STORE_ANALYSIS_RESULT_COLUMN_BUDGET = 512;\nconst POPULATION_FIXED_COLUMN_COUNT = 2;\nconst POPULATION_COLUMNS_PER_PATH = 2;\nconst POPULATION_PATH_BATCH_SIZE = Math.floor(\n  (STORE_ANALYSIS_RESULT_COLUMN_BUDGET - POPULATION_FIXED_COLUMN_COUNT) /\n    POPULATION_COLUMNS_PER_PATH,\n);\nconst VALIDATION_CURSOR_COLUMNS = [\n  \"typegraph.validateStore.entity\",\n  \"typegraph.validateStore.kind\",\n  \"typegraph.validateStore.schemaFence\",\n  \"typegraph.validateStore.afterId\",\n] as const;\n\nexport type StoreAnalysisSchemaCoordinate = Readonly<{\n  schemaVersion?: number;\n  schemaHash?: string;\n  /** Fingerprint of both the Store declarations and active schema row. */\n  schemaFence: string;\n}>;\n\nexport type PropertyPopulationStatistics = Readonly<{\n  /** RFC 6901 JSON pointer to a directly addressable declared property. */\n  path: string;\n  /** Rows in which the property exists, including explicit JSON null. */\n  presentCount: number;\n  /** Rows in which the property exists and is the JSON null literal. */\n  nullCount: number;\n  nonNullCount: number;\n  /** `nonNullCount / count`; zero for an empty kind. */\n  coverage: number;\n}>;\n\nexport type KindPopulationStatistics = Readonly<{\n  entity: KindEntity;\n  kind: string;\n  count: number;\n  properties: readonly PropertyPopulationStatistics[];\n}>;\n\nexport type StorePopulationStatistics = Readonly<{\n  /** Schema coordinate observed before and after the aggregate statements. */\n  snapshot: StoreAnalysisSchemaCoordinate;\n  nodes: readonly KindPopulationStatistics[];\n  edges: readonly KindPopulationStatistics[];\n}>;\n\nexport type StoreDescription = Readonly<{\n  schema: SchemaIntrospection;\n  statistics: StorePopulationStatistics;\n}>;\n\nexport type ValidateStoreOptions = Readonly<{\n  entity: KindEntity;\n  kind: string;\n  /** Number of records to scan. Default 100; maximum 1000. */\n  pageSize?: number;\n  /** Opaque keyset cursor returned by the preceding page. */\n  cursor?: string;\n}>;\n\nexport type StoreValidationFailure = Readonly<{\n  entity: KindEntity;\n  kind: string;\n  id: string;\n  /** RFC 6901 path; the empty string denotes a whole-record rule. */\n  path: string;\n  /** Top-level declared property, absent for a whole-record rule. */\n  property?: string;\n  code: string;\n  reason: string;\n}>;\n\nexport type StoreValidationPage = Readonly<{\n  /** Schema coordinate observed before and after this page scan. */\n  snapshot: StoreAnalysisSchemaCoordinate;\n  /** Number of records scanned, independent of the number of violations. */\n  scannedCount: number;\n  violations: readonly StoreValidationFailure[];\n  nextCursor?: string;\n}>;\n\nexport type StoreAnalysisCursorStaleErrorDetails = Readonly<{\n  entity: KindEntity;\n  kind: string;\n  expectedSchemaFence: string;\n  actualSchemaFence: string;\n}>;\n\n/** A validation cursor cannot be resumed after the active schema changes. */\nexport class StoreAnalysisCursorStaleError extends TypeGraphError {\n  declare readonly details: StoreAnalysisCursorStaleErrorDetails;\n\n  constructor(details: StoreAnalysisCursorStaleErrorDetails) {\n    super(\n      `The validation cursor for ${details.entity} kind \"${details.kind}\" is stale.`,\n      \"STORE_ANALYSIS_CURSOR_STALE\",\n      {\n        category: \"user\",\n        details,\n        suggestion:\n          \"Restart validateStore() without a cursor after the schema change.\",\n      },\n    );\n    this.name = \"StoreAnalysisCursorStaleError\";\n    this.details = details;\n  }\n}\n\ntype AnalysisContext<G extends GraphDef> = Readonly<{\n  graph: G;\n  graphId: string;\n  backend: Pick<GraphBackend, \"dialect\" | \"execute\" | \"getActiveSchema\">;\n  schema: SqlSchema;\n  introspect: () => SchemaIntrospection;\n}>;\n\ntype ValidationCursor = Readonly<{\n  entity: KindEntity;\n  kind: string;\n  schemaFence: string;\n  afterId: string;\n}>;\n\ntype ValidationRow = Readonly<{ id: string; props: RowProps }>;\ntype PopulationRow = Readonly<{\n  kind: string;\n  row_count: number | string | bigint;\n}> &\n  Readonly<Record<string, unknown>>;\ntype SchemaCoordinate = StoreAnalysisSchemaCoordinate;\ntype PopulationCounts = Readonly<{\n  presentCount: number;\n  nonNullCount: number;\n}>;\ntype KindPopulationAggregate = Readonly<{\n  count: number;\n  properties: ReadonlyMap<string, PopulationCounts>;\n}>;\n\n/**\n * Only ordinary nested `properties` members have an unambiguous portable SQL\n * address. `$ref`, unions, intersections, arrays, and conditionals remain in\n * the authoritative Zod validation pass rather than receiving fake coverage.\n */\nfunction declaredPropertyPaths(\n  schema: JsonSchema,\n  parent: readonly string[] = [],\n): readonly (readonly string[])[] {\n  const paths: (readonly string[])[] = [];\n  for (const [name, propertySchema] of Object.entries(\n    schema.properties ?? {},\n  )) {\n    const path = [...parent, name];\n    paths.push(path, ...declaredPropertyPaths(propertySchema, path));\n  }\n  return paths;\n}\n\nfunction pathToPointer(path: readonly PropertyKey[]): string {\n  return path\n    .map((segment) => `/${encodeJsonPointerSegment(String(segment))}`)\n    .join(\"\");\n}\n\nfunction normalizePageSize(pageSize: number | undefined): number {\n  const resolved = pageSize ?? DEFAULT_VALIDATION_PAGE_SIZE;\n  if (\n    !Number.isInteger(resolved) ||\n    resolved < 1 ||\n    resolved > MAX_VALIDATION_PAGE_SIZE\n  ) {\n    throw new ValidationError(\n      `validateStore pageSize must be an integer between 1 and ${MAX_VALIDATION_PAGE_SIZE}.`,\n      {\n        issues: [\n          {\n            path: \"pageSize\",\n            message: `Expected an integer between 1 and ${MAX_VALIDATION_PAGE_SIZE}`,\n          },\n        ],\n      },\n    );\n  }\n  return resolved;\n}\n\nfunction decodeValidationCursor(cursor: string): ValidationCursor {\n  const decoded = decodeCursor(cursor);\n  if (\n    decoded.d !== \"f\" ||\n    decoded.cols.length !== VALIDATION_CURSOR_COLUMNS.length ||\n    !decoded.cols.every(\n      (column, index) => column === VALIDATION_CURSOR_COLUMNS[index],\n    )\n  ) {\n    throw new ValidationError(\"Invalid validateStore cursor scope.\", {\n      issues: [\n        {\n          path: \"cursor\",\n          message: \"Cursor was not created by validateStore\",\n        },\n      ],\n    });\n  }\n  const [entity, kind, schemaFence, afterId] = decoded.vals;\n  if (\n    (entity !== \"node\" && entity !== \"edge\") ||\n    typeof kind !== \"string\" ||\n    typeof schemaFence !== \"string\" ||\n    typeof afterId !== \"string\"\n  ) {\n    throw new ValidationError(\"Invalid validateStore cursor payload.\", {\n      issues: [{ path: \"cursor\", message: \"Cursor payload is malformed\" }],\n    });\n  }\n  return { entity, kind, schemaFence, afterId };\n}\n\nfunction encodeValidationCursor(cursor: ValidationCursor): string {\n  return encodeCursor({\n    v: 1,\n    d: \"f\",\n    cols: VALIDATION_CURSOR_COLUMNS,\n    vals: [cursor.entity, cursor.kind, cursor.schemaFence, cursor.afterId],\n  });\n}\n\nasync function schemaCoordinateFor<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n): Promise<SchemaCoordinate> {\n  const active = await ctx.backend.getActiveSchema(ctx.graphId);\n  const declaration = ctx.introspect();\n  if (\n    declaration.schemaVersion !== undefined &&\n    active?.version !== declaration.schemaVersion\n  ) {\n    throw new StaleVersionError({\n      graphId: ctx.graphId,\n      expected: declaration.schemaVersion,\n      actual: active?.version ?? 0,\n    });\n  }\n  if (\n    declaration.schemaHash !== undefined &&\n    active !== undefined &&\n    active.schema_hash !== declaration.schemaHash\n  ) {\n    throw new SchemaMismatchError({\n      graphId: ctx.graphId,\n      expectedHash: declaration.schemaHash,\n      actualHash: active.schema_hash,\n    });\n  }\n  const declarationShape = {\n    graphId: declaration.graphId,\n    kinds: declaration.kinds.map((kind) => ({\n      name: kind.name,\n      properties: kind.properties,\n    })),\n    edges: declaration.edges.map((edge) => ({\n      name: edge.name,\n      from: edge.from,\n      to: edge.to,\n      properties: edge.properties,\n    })),\n  };\n  const schemaFence = await sha256Hex(\n    JSON.stringify(\n      {\n        active:\n          active === undefined ? undefined : (\n            [active.version, active.schema_hash]\n          ),\n        declaration: declarationShape,\n      },\n      sortedReplacer,\n    ),\n    16,\n  );\n  return {\n    ...(active === undefined ? {} : { schemaVersion: active.version }),\n    ...(active === undefined ? {} : { schemaHash: active.schema_hash }),\n    schemaFence,\n  };\n}\n\nfunction assertStableSchema(\n  before: SchemaCoordinate,\n  after: SchemaCoordinate,\n): void {\n  if (before.schemaFence === after.schemaFence) return;\n  throw new TypeGraphError(\n    \"The active schema changed while Store analysis was reading data.\",\n    \"STORE_ANALYSIS_SCHEMA_CHANGED\",\n    {\n      category: \"user\",\n      details: {\n        beforeSchemaFence: before.schemaFence,\n        afterSchemaFence: after.schemaFence,\n      },\n      suggestion: \"Retry the analysis against the new active schema.\",\n    },\n  );\n}\n\nfunction numberFromSql(value: unknown, label: string): number {\n  const converted = Number(value);\n  if (!Number.isSafeInteger(converted) || converted < 0) {\n    throw new TypeGraphError(\n      `Store analysis received an invalid ${label} aggregate.`,\n      \"STORE_ANALYSIS_INVALID_AGGREGATE\",\n      { category: \"system\", details: { label, value: String(value) } },\n    );\n  }\n  return converted;\n}\n\nfunction declaredPathsForEntity<G extends GraphDef>(\n  graph: G,\n  entity: KindEntity,\n): readonly string[] {\n  const paths = new Set<string>();\n  const schemas: readonly z.ZodType[] =\n    entity === \"node\" ?\n      Object.values(graph.nodes).map((registration) => registration.type.schema)\n    : Object.values(graph.edges).map(\n        (registration) => registration.type.schema,\n      );\n  for (const schema of schemas) {\n    for (const path of declaredPropertyPaths(\n      serializeSchemaProperties(schema),\n    )) {\n      paths.add(pathToPointer(path));\n    }\n  }\n  return [...paths].toSorted();\n}\n\nfunction populationSelect<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n  entity: KindEntity,\n  paths: readonly string[],\n  currentTimestamp: string,\n): SqlFragment {\n  const table =\n    entity === \"node\" ? ctx.schema.nodesTable : ctx.schema.edgesTable;\n  const dialect = getDialect(ctx.backend.dialect);\n  const temporal = compileTemporalFilter({\n    mode: \"current\",\n    currentTimestamp: sql`${currentTimestamp}`,\n  });\n  const aggregates = paths.flatMap((path, index) => {\n    const pointer = path as JsonPointer;\n    const presentAlias = sql.identifier(`p${index}_present`);\n    const nonNullAlias = sql.identifier(`p${index}_non_null`);\n    return [\n      sql`SUM(CASE WHEN ${dialect.jsonHasPath(sql`props`, pointer)} THEN 1 ELSE 0 END) AS ${presentAlias}`,\n      sql`SUM(CASE WHEN ${dialect.jsonPathIsNotNull(sql`props`, pointer)} THEN 1 ELSE 0 END) AS ${nonNullAlias}`,\n    ];\n  });\n  const aggregateColumns =\n    aggregates.length === 0 ? sql`` : sql`, ${sql.join(aggregates, sql`, `)}`;\n  return sql`SELECT kind, COUNT(*) AS row_count${aggregateColumns} FROM ${table} WHERE graph_id = ${ctx.graphId} AND ${temporal} GROUP BY kind ORDER BY kind`;\n}\n\nfunction pathBatches(paths: readonly string[]): readonly (readonly string[])[] {\n  if (paths.length === 0) return [[]];\n  return chunk(paths, POPULATION_PATH_BATCH_SIZE);\n}\n\nasync function readEntityPopulation<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n  entity: KindEntity,\n  paths: readonly string[],\n  currentTimestamp: string,\n): Promise<ReadonlyMap<string, KindPopulationAggregate>> {\n  const aggregates = new Map<\n    string,\n    { count: number; properties: Map<string, PopulationCounts> }\n  >();\n  const batches = pathBatches(paths);\n  for (const [batchIndex, batch] of batches.entries()) {\n    const rows = await ctx.backend.execute<PopulationRow>(\n      asCompiledRowsSql(populationSelect(ctx, entity, batch, currentTimestamp)),\n    );\n    for (const row of rows) {\n      const aggregate = aggregates.get(row.kind) ?? {\n        count: 0,\n        properties: new Map<string, PopulationCounts>(),\n      };\n      if (batchIndex === 0) {\n        aggregate.count = numberFromSql(row.row_count, \"count\");\n      }\n      for (const [pathIndex, path] of batch.entries()) {\n        aggregate.properties.set(path, {\n          presentCount: numberFromSql(\n            row[`p${pathIndex}_present`],\n            \"present count\",\n          ),\n          nonNullCount: numberFromSql(\n            row[`p${pathIndex}_non_null`],\n            \"non-null count\",\n          ),\n        });\n      }\n      aggregates.set(row.kind, aggregate);\n    }\n  }\n  return aggregates;\n}\n\nfunction populationForKind(\n  entity: KindEntity,\n  kind: string,\n  schema: z.ZodType,\n  populations: ReadonlyMap<string, KindPopulationAggregate>,\n): KindPopulationStatistics {\n  const population = populations.get(kind);\n  const count = population?.count ?? 0;\n  const declaredPaths = declaredPropertyPaths(serializeSchemaProperties(schema))\n    .map((path) => pathToPointer(path))\n    .toSorted();\n  return {\n    entity,\n    kind,\n    count,\n    properties: declaredPaths.map((path) => {\n      const counts = population?.properties.get(path);\n      const presentCount = counts?.presentCount ?? 0;\n      const nonNullCount = counts?.nonNullCount ?? 0;\n      return {\n        path,\n        presentCount,\n        nullCount: presentCount - nonNullCount,\n        nonNullCount,\n        coverage: count === 0 ? 0 : nonNullCount / count,\n      };\n    }),\n  };\n}\n\nfunction zodFailures(\n  entity: KindEntity,\n  kind: string,\n  schema: z.ZodType,\n  rows: readonly ValidationRow[],\n): readonly StoreValidationFailure[] {\n  const failures: StoreValidationFailure[] = [];\n  for (const row of rows) {\n    const parsed = schema.safeParse(rowPropsToObject(row.props));\n    if (parsed.success) continue;\n    for (const issue of parsed.error.issues) {\n      if (issue.code === \"unrecognized_keys\") continue;\n      const path: string[] = [];\n      for (const segment of issue.path) path.push(String(segment));\n      failures.push({\n        entity,\n        kind,\n        id: row.id,\n        path: pathToPointer(path),\n        ...(path[0] === undefined ? {} : { property: path[0] }),\n        code: issue.code,\n        reason: issue.message,\n      });\n    }\n  }\n  return failures;\n}\n\nasync function readValidationRows<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n  options: Pick<ValidateStoreOptions, \"entity\" | \"kind\">,\n  afterId: string | undefined,\n  limit: number,\n): Promise<readonly ValidationRow[]> {\n  const table =\n    options.entity === \"node\" ? ctx.schema.nodesTable : ctx.schema.edgesTable;\n  const temporal = compileTemporalFilter({\n    mode: \"current\",\n    currentTimestamp: sql`${nowIso()}`,\n  });\n  const keyset = afterId === undefined ? sql`` : sql` AND id > ${afterId}`;\n  const query = sql`SELECT id, props FROM ${table} WHERE graph_id = ${ctx.graphId} AND kind = ${options.kind} AND ${temporal}${keyset} ORDER BY id LIMIT ${limit}`;\n  return ctx.backend.execute<ValidationRow>(asCompiledRowsSql(query));\n}\n\nexport async function describeStore<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n): Promise<StoreDescription> {\n  const before = await schemaCoordinateFor(ctx);\n  const currentTimestamp = nowIso();\n  const nodePaths = declaredPathsForEntity(ctx.graph, \"node\");\n  const edgePaths = declaredPathsForEntity(ctx.graph, \"edge\");\n  const nodePopulations =\n    Object.keys(ctx.graph.nodes).length === 0 ?\n      new Map<string, KindPopulationAggregate>()\n    : await readEntityPopulation(ctx, \"node\", nodePaths, currentTimestamp);\n  const edgePopulations =\n    Object.keys(ctx.graph.edges).length === 0 ?\n      new Map<string, KindPopulationAggregate>()\n    : await readEntityPopulation(ctx, \"edge\", edgePaths, currentTimestamp);\n  const after = await schemaCoordinateFor(ctx);\n  assertStableSchema(before, after);\n  const nodes = Object.entries(ctx.graph.nodes).map(([kind, registration]) =>\n    populationForKind(\"node\", kind, registration.type.schema, nodePopulations),\n  );\n  const edges = Object.entries(ctx.graph.edges).map(([kind, registration]) =>\n    populationForKind(\"edge\", kind, registration.type.schema, edgePopulations),\n  );\n  return {\n    schema: ctx.introspect(),\n    statistics: { snapshot: before, nodes, edges },\n  };\n}\n\nexport async function validateStore<G extends GraphDef>(\n  ctx: AnalysisContext<G>,\n  options: ValidateStoreOptions,\n): Promise<StoreValidationPage> {\n  const pageSize = normalizePageSize(options.pageSize);\n  const cursor =\n    options.cursor === undefined ?\n      undefined\n    : decodeValidationCursor(options.cursor);\n  if (\n    cursor !== undefined &&\n    (cursor.entity !== options.entity || cursor.kind !== options.kind)\n  ) {\n    throw new ValidationError(\n      \"validateStore cursor scope does not match the request.\",\n      {\n        issues: [\n          {\n            path: \"cursor\",\n            message: `Expected ${options.entity} kind ${options.kind}`,\n          },\n        ],\n      },\n    );\n  }\n  const registration =\n    options.entity === \"node\" ?\n      ctx.graph.nodes[options.kind]\n    : ctx.graph.edges[options.kind];\n  if (registration === undefined) {\n    throw new ValidationError(\n      `Unknown ${options.entity} kind \"${options.kind}\".`,\n      {\n        issues: [{ path: \"kind\", message: `Unknown ${options.entity} kind` }],\n      },\n    );\n  }\n\n  const before = await schemaCoordinateFor(ctx);\n  if (cursor !== undefined && cursor.schemaFence !== before.schemaFence) {\n    throw new StoreAnalysisCursorStaleError({\n      entity: options.entity,\n      kind: options.kind,\n      expectedSchemaFence: cursor.schemaFence,\n      actualSchemaFence: before.schemaFence,\n    });\n  }\n  const fetched = await readValidationRows(\n    ctx,\n    options,\n    cursor?.afterId,\n    pageSize + 1,\n  );\n  const rows = fetched.slice(0, pageSize);\n  const after = await schemaCoordinateFor(ctx);\n  assertStableSchema(before, after);\n  const hasMore = fetched.length > rows.length;\n  const lastRow = rows.at(-1);\n  return {\n    snapshot: before,\n    scannedCount: rows.length,\n    violations: zodFailures(\n      options.entity,\n      options.kind,\n      registration.type.schema,\n      rows,\n    ),\n    ...(hasMore && lastRow !== undefined ?\n      {\n        nextCursor: encodeValidationCursor({\n          entity: options.entity,\n          kind: options.kind,\n          schemaFence: before.schemaFence,\n          afterId: lastRow.id,\n        }),\n      }\n    : {}),\n  };\n}\n","/**\n * Nominal brands that make the store's \"which backend does this work go\n * through?\" decision a compile-time choice instead of a convention.\n *\n * A history-enabled `Store` holds the same `GraphBackend` shape in two roles:\n *\n * - the **recorded-capture wrapper**, through which every public graph-entity\n *   write must flow so the write is captured, and\n * - the **bare backend**, used for raw SQL / DDL / bulk-materialization work\n *   that intentionally bypasses capture (the wrapper rejects raw DDL and writes\n *   no graph entities of its own).\n *\n * Routing a graph write through the bare backend silently loses history with no\n * error. The brands below turn that footgun into a type error: a function that\n * does bulk/DDL work declares `RawBackend`, a function that performs graph\n * writes declares `GraphWriteBackend`, and the two are not mutually assignable.\n *\n * The brand is erased at runtime — both values are ordinary `GraphBackend`s.\n * Only the `as*` tagging functions, called at the few seams where a role is\n * asserted, bridge a plain backend into a role; they are the greppable audit\n * surface for \"this path was deliberately routed to a capture role.\"\n *\n * This does not brand `TransactionBackend`: the collection-write entrypoint is\n * polymorphic over `GraphBackend | TransactionBackend`, and a raw backend is\n * structurally a `TransactionBackend`, so a brand there would be swallowed by\n * the union. The protection therefore covers the full-`GraphBackend` bulk/DDL\n * seams (where new capture-bypassing paths are actually added). Branding the\n * transaction surface is a deliberate follow-up, gated on a real bypass pattern.\n */\nimport { type GraphBackend } from \"./types\";\n\ndeclare const BackendRoleBrand: unique symbol;\n\n/**\n * The backend through which **graph-entity writes** (node/edge\n * create/update/delete) flow. When `history: true` this is the recorded-capture\n * wrapper; when history is off it is the bare backend. Either way, routing graph\n * writes here is what guarantees capture runs when it should.\n */\nexport type GraphWriteBackend = GraphBackend &\n  Readonly<{ [BackendRoleBrand]: \"graph-write\" }>;\n\n/**\n * A backend for raw SQL / DDL / bulk-materialization work that **intentionally\n * bypasses** recorded-time capture. Never route public graph-entity writes\n * here — that is the silent-history-loss footgun this brand exists to catch.\n */\nexport type RawBackend = GraphBackend & Readonly<{ [BackendRoleBrand]: \"raw\" }>;\n\n/** Tags a backend as the graph-write seam. Call only where capture is wired. */\nexport function asGraphWriteBackend(backend: GraphBackend): GraphWriteBackend {\n  return backend as GraphWriteBackend;\n}\n\n/** Tags a backend as the raw/DDL/bulk seam (capture-bypassing). */\nexport function asRawBackend(backend: GraphBackend): RawBackend {\n  return backend as RawBackend;\n}\n","/**\n * Bind parameters in the heterogeneous node upsert CTE outside its input\n * rows: two schema-fence predicates plus the lower bound and two timestamps\n * stamped by the data-modifying statement.\n */\nconst HETEROGENEOUS_NODE_UPSERT_BATCH_FIXED_BIND_COUNT = 5;\n\n/**\n * Each input row supplies its graph/id reference, both property documents, and\n * its caller-order ordinal.\n */\nconst HETEROGENEOUS_NODE_UPSERT_BATCH_ENTRY_BIND_COUNT = 6;\n\n/** Exact parameter count emitted by the heterogeneous node upsert CTE. */\nexport function heterogeneousNodeUpsertBatchBindParameterCount(\n  entryCount: number,\n): number | undefined {\n  if (!Number.isSafeInteger(entryCount) || entryCount < 1) return;\n  return (\n    HETEROGENEOUS_NODE_UPSERT_BATCH_FIXED_BIND_COUNT +\n    entryCount * HETEROGENEOUS_NODE_UPSERT_BATCH_ENTRY_BIND_COUNT\n  );\n}\n\n/**\n * Whether the one-statement PostgreSQL heterogeneous node upsert fits the\n * target's declared parameter budget. An absent limit explicitly admits that\n * the backend has no known ceiling.\n */\nexport function heterogeneousNodeUpsertBatchFitsBindBudget(\n  entryCount: number,\n  maxBindParameters: number | undefined,\n): boolean {\n  const parameterCount =\n    heterogeneousNodeUpsertBatchBindParameterCount(entryCount);\n  if (parameterCount === undefined) return false;\n  if (maxBindParameters === undefined) return true;\n  return parameterCount <= maxBindParameters;\n}\n","/**\n * Per-delta classification for `evolve()` modify-existing-kind support.\n *\n * Distinguishes additive / loosening changes (allowed without data\n * inspection) from tightening changes that require an empty-kind\n * probe, from genuinely incompatible changes that always reject.\n *\n * Pure function — no I/O. The caller (`store.evolve`) takes the\n * `requireEmpty` candidate list and runs the existence probes before\n * committing.\n */\nimport type { KindEntity } from \"../core/types\";\nimport { canonicalEqual } from \"../schema/canonical\";\nimport { hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { type IncompatibleChange, IncompatibleChangeError } from \"./errors\";\nimport {\n  type ExtensionArrayProperty,\n  type ExtensionEdgeDef,\n  type ExtensionEnumProperty,\n  type ExtensionNodeDef,\n  type ExtensionNumberProperty,\n  type ExtensionObjectProperty,\n  type ExtensionPropertyType,\n  type ExtensionStringProperty,\n  type ExtensionUniqueConstraint,\n  type GraphExtension,\n} from \"./extension-types\";\n\n/**\n * Result of classifying every delta between two graph-extension documents.\n *\n * `incompatible` collects rejections that the caller throws as a\n * single `IncompatibleChangeError`. `requireEmpty`\n * collects the names of kinds where at least one delta is\n * allowed-only-on-empty — the caller probes each kind's row count\n * and promotes the `requireEmpty` entries to `incompatible` when\n * the kind has rows.\n *\n * `entity` is tracked per-key so the probe dispatches to the right\n * backend primitive: `countNodesByKind` for `node`, `countEdgesByKind`\n * for `edge`. Without this, an edge-keyed `TIGHTEN_EDGE_ENDPOINTS`\n * delta would silently slip past the empty-kind gate (the node-\n * keyed count would always be 0 for an edge name).\n */\ntype ModificationClassification = Readonly<{\n  /** Deltas that always reject. */\n  incompatible: readonly IncompatibleChange[];\n  /**\n   * Deltas allowed only when the kind has zero rows. One entry per\n   * `(entity, kindName)`; each carries the per-delta detail to promote\n   * to `incompatible` if the empty-probe shows rows. Caller looks up\n   * by entry identity (frozen reference) — no string-key encoding.\n   */\n  requireEmpty: readonly RequireEmptyEntry[];\n}>;\n\nexport type RequireEmptyEntry = Readonly<{\n  entity: KindEntity;\n  kindName: string;\n  changes: readonly IncompatibleChange[];\n}>;\n\n/**\n * Classifies every delta between an existing and proposed graph-extension\n * document. Same-shape kinds produce no entries; new-kind additions\n * produce no entries (handled by the union spread upstream).\n *\n * The classification covers nodes and edges in scope; ontology and\n * indexes pass through unchanged because v1 evolve doesn't modify\n * them in-place (consumers add new ontology relations, runtime\n * indexes follow auto-derive on the underlying nodes).\n */\nexport function classifyModifications(\n  existing: GraphExtension,\n  next: GraphExtension,\n): ModificationClassification {\n  const incompatible: IncompatibleChange[] = [];\n  // Aggregate by (entity, kindName) using a temporary string-keyed Map\n  // — the encoding is private to this function. The Map's values are\n  // returned as a plain array; the caller never sees the key.\n  const requireEmptyMutable = new Map<\n    string,\n    { entity: KindEntity; kindName: string; changes: IncompatibleChange[] }\n  >();\n\n  const recordIncompatible = (entry: IncompatibleChange): void => {\n    incompatible.push(entry);\n  };\n  const recordRequireEmpty = (\n    entity: KindEntity,\n    entry: IncompatibleChange,\n  ): void => {\n    const key = `${entity}:${entry.kind}`;\n    const existingEntry = requireEmptyMutable.get(key);\n    if (existingEntry === undefined) {\n      requireEmptyMutable.set(key, {\n        entity,\n        kindName: entry.kind,\n        changes: [entry],\n      });\n    } else {\n      existingEntry.changes.push(entry);\n    }\n  };\n\n  // Own-key reads below: extension kind names match\n  // `/^[A-Za-z_][A-Za-z0-9_]*$/`, which admits `toString`, `constructor`, and\n  // `valueOf`. A raw read would answer such a name with the inherited\n  // `Object.prototype` member, so a brand-new kind would be classified as a\n  // MODIFICATION of an existing one and read its shape off a function.\n  for (const [name, nextNode] of Object.entries(next.nodes ?? {})) {\n    const existingNodes = existing.nodes;\n    const existingNode =\n      existingNodes !== undefined && hasOwnKey(existingNodes, name) ?\n        existingNodes[name]\n      : undefined;\n    if (existingNode === undefined) continue;\n    classifyNode(name, existingNode, nextNode, {\n      recordIncompatible,\n      recordRequireEmpty: (entry) => {\n        recordRequireEmpty(\"node\", entry);\n      },\n    });\n  }\n  for (const [name, nextEdge] of Object.entries(next.edges ?? {})) {\n    const existingEdges = existing.edges;\n    const existingEdge =\n      existingEdges !== undefined && hasOwnKey(existingEdges, name) ?\n        existingEdges[name]\n      : undefined;\n    if (existingEdge === undefined) continue;\n    classifyEdge(name, existingEdge, nextEdge, {\n      recordIncompatible,\n      recordRequireEmpty: (entry) => {\n        recordRequireEmpty(\"edge\", entry);\n      },\n    });\n  }\n\n  const requireEmpty: RequireEmptyEntry[] = [];\n  for (const value of requireEmptyMutable.values()) {\n    requireEmpty.push(\n      Object.freeze({\n        entity: value.entity,\n        kindName: value.kindName,\n        changes: Object.freeze([...value.changes]),\n      }),\n    );\n  }\n\n  return { incompatible, requireEmpty };\n}\n\n/**\n * Promotes the `requireEmpty` entries whose probe came back non-empty\n * to incompatible, returning a single `IncompatibleChangeError`\n * covering both the always-incompatible deltas and the promoted ones.\n * Returns `undefined` when nothing rejects (probe came back empty for\n * every entry and `incompatible` is empty).\n */\nexport function buildIncompatibleChangeError(\n  classification: ModificationClassification,\n  nonEmpty: ReadonlySet<RequireEmptyEntry>,\n  graphId: string,\n): IncompatibleChangeError | undefined {\n  const promoted: IncompatibleChange[] = [];\n  for (const entry of nonEmpty) {\n    promoted.push(...entry.changes);\n  }\n  const all = [...classification.incompatible, ...promoted];\n  if (all.length === 0) return undefined;\n  return new IncompatibleChangeError(all, graphId);\n}\n\n// ============================================================\n// Node classification\n// ============================================================\n\ntype Recorders = Readonly<{\n  recordIncompatible: (entry: IncompatibleChange) => void;\n  recordRequireEmpty: (entry: IncompatibleChange) => void;\n}>;\n\nfunction classifyNode(\n  kind: string,\n  existing: ExtensionNodeDef,\n  next: ExtensionNodeDef,\n  recorders: Recorders,\n): void {\n  classifyProperties(kind, existing.properties, next.properties, recorders);\n  classifyUnique(kind, existing.unique ?? [], next.unique ?? [], recorders);\n  // description / annotations — always allowed (no semantic effect).\n}\n\nfunction classifyEdge(\n  kind: string,\n  existing: ExtensionEdgeDef,\n  next: ExtensionEdgeDef,\n  recorders: Recorders,\n): void {\n  classifyProperties(\n    kind,\n    existing.properties ?? {},\n    next.properties ?? {},\n    recorders,\n  );\n  classifyEdgeEndpoints(kind, existing, next, recorders);\n}\n\nfunction getExtensionEdgePairs(edge: ExtensionEdgeDef): ReadonlySet<string> {\n  const pairs = new Set<string>();\n  if (Array.isArray(edge.to)) {\n    for (const f of edge.from) {\n      for (const t of edge.to) {\n        pairs.add(`${f}\\0${t}`);\n      }\n    }\n  } else {\n    for (const [sourceKind, targets] of Object.entries(edge.to)) {\n      for (const t of targets) {\n        pairs.add(`${sourceKind}\\0${t}`);\n      }\n    }\n  }\n  return pairs;\n}\n\nfunction classifyEdgeEndpoints(\n  kind: string,\n  existing: ExtensionEdgeDef,\n  next: ExtensionEdgeDef,\n  recorders: Recorders,\n): void {\n  // Adding pairs to from/to is broadening — always allowed.\n  // Removing endpoint pairs with no existing edges of that pair would be\n  // allowed in the spec, but TypeGraph doesn't have a per-(edge,\n  // endpoint-kind) row probe today; v1 stays conservative by treating\n  // endpoint-kind removal as allowed-on-empty for the whole edge kind.\n  const existingPairs = getExtensionEdgePairs(existing);\n  const nextPairs = getExtensionEdgePairs(next);\n\n  for (const pairKey of existingPairs) {\n    if (!nextPairs.has(pairKey)) {\n      const [from, to] = pairKey.split(\"\\0\");\n      recorders.recordRequireEmpty({\n        kind,\n        type: \"TIGHTEN_EDGE_ENDPOINTS\",\n        detail: `removed endpoint pair \"(${from} -> ${to})\"`,\n      });\n    }\n  }\n}\n\n// ============================================================\n// Properties\n// ============================================================\n\nfunction classifyProperties(\n  kind: string,\n  existing: Readonly<Record<string, ExtensionPropertyType>>,\n  next: Readonly<Record<string, ExtensionPropertyType>>,\n  recorders: Recorders,\n): void {\n  const existingNames = new Set(Object.keys(existing));\n  const nextNames = new Set(Object.keys(next));\n\n  // Removed properties — REMOVE_PROPERTY (always reject).\n  for (const name of existingNames) {\n    if (!nextNames.has(name)) {\n      recorders.recordIncompatible({\n        kind,\n        field: name,\n        type: \"REMOVE_PROPERTY\",\n      });\n    }\n  }\n\n  // Added properties — ADD_OPTIONAL (allowed) or ADD_REQUIRED\n  // (allowed-on-empty).\n  for (const name of nextNames) {\n    if (!existingNames.has(name)) {\n      const property = requireDefined(next[name]);\n      if (property.optional === true) continue;\n      recorders.recordRequireEmpty({\n        kind,\n        field: name,\n        type: \"ADD_REQUIRED_PROPERTY\",\n      });\n    }\n  }\n\n  // Modified properties — per-property classification.\n  for (const name of existingNames) {\n    if (!nextNames.has(name)) continue;\n    classifyProperty(\n      kind,\n      name,\n      requireDefined(existing[name]),\n      requireDefined(next[name]),\n      recorders,\n    );\n  }\n}\n\nfunction classifyProperty(\n  kind: string,\n  field: string,\n  existing: ExtensionPropertyType,\n  next: ExtensionPropertyType,\n  recorders: Recorders,\n): void {\n  // Type change — always reject.\n  if (existing.type !== next.type) {\n    recorders.recordIncompatible({\n      kind,\n      field,\n      type: \"TYPE_CHANGE\",\n      detail: `${existing.type} → ${next.type}`,\n    });\n    return;\n  }\n\n  // Optionality.\n  const wasOptional = existing.optional === true;\n  const isOptional = next.optional === true;\n  if (!wasOptional && isOptional) {\n    // LOOSEN_OPTIONALITY — allowed.\n  } else if (wasOptional && !isOptional) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_OPTIONALITY\",\n      detail: \"optional: true → false\",\n    });\n  }\n\n  // Searchable / embedding modifiers — always allowed (the materializer\n  // backfills indexes via materializeIndexes; vector regen is on the\n  // consumer per the design doc).\n\n  // Per-type constraint deltas.\n  switch (existing.type) {\n    case \"string\": {\n      classifyString(\n        kind,\n        field,\n        existing,\n        next as ExtensionStringProperty,\n        recorders,\n      );\n      break;\n    }\n    case \"number\": {\n      classifyNumber(\n        kind,\n        field,\n        existing,\n        next as ExtensionNumberProperty,\n        recorders,\n      );\n      break;\n    }\n    case \"enum\": {\n      classifyEnum(\n        kind,\n        field,\n        existing,\n        next as ExtensionEnumProperty,\n        recorders,\n      );\n      break;\n    }\n    case \"array\": {\n      classifyArray(\n        kind,\n        field,\n        existing,\n        next as ExtensionArrayProperty,\n        recorders,\n      );\n      break;\n    }\n    case \"object\": {\n      classifyObject(\n        kind,\n        field,\n        existing,\n        next as ExtensionObjectProperty,\n        recorders,\n      );\n      break;\n    }\n    case \"boolean\": {\n      // No classifiable deltas beyond optionality, already handled.\n      break;\n    }\n  }\n}\n\nfunction classifyString(\n  kind: string,\n  field: string,\n  existing: ExtensionStringProperty,\n  next: ExtensionStringProperty,\n  recorders: Recorders,\n): void {\n  // Length bounds: tighten requires empty, loosen allowed.\n  if (\n    existing.minLength !== next.minLength &&\n    next.minLength !== undefined &&\n    (existing.minLength === undefined || next.minLength > existing.minLength)\n  ) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_CONSTRAINT\",\n      detail: `minLength: ${existing.minLength ?? \"(none)\"} → ${next.minLength}`,\n    });\n  }\n  if (\n    existing.maxLength !== next.maxLength &&\n    next.maxLength !== undefined &&\n    (existing.maxLength === undefined || next.maxLength < existing.maxLength)\n  ) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_CONSTRAINT\",\n      detail: `maxLength: ${existing.maxLength ?? \"(none)\"} → ${next.maxLength}`,\n    });\n  }\n  // Pattern.\n  if (existing.pattern !== next.pattern) {\n    if (existing.pattern === undefined && next.pattern !== undefined) {\n      recorders.recordRequireEmpty({\n        kind,\n        field,\n        type: \"ADD_PATTERN\",\n        detail: next.pattern,\n      });\n    } else if (existing.pattern !== undefined && next.pattern === undefined) {\n      // DROP_PATTERN — allowed.\n    } else if (\n      existing.pattern !== undefined &&\n      next.pattern !== undefined &&\n      existing.pattern !== next.pattern\n    ) {\n      recorders.recordRequireEmpty({\n        kind,\n        field,\n        type: \"CHANGE_PATTERN\",\n        detail: `${existing.pattern} → ${next.pattern}`,\n      });\n    }\n  }\n  // Format.\n  if (existing.format !== next.format) {\n    if (existing.format === undefined && next.format !== undefined) {\n      recorders.recordRequireEmpty({\n        kind,\n        field,\n        type: \"ADD_FORMAT\",\n        detail: next.format,\n      });\n    } else if (existing.format !== undefined && next.format === undefined) {\n      // DROP_FORMAT — allowed.\n    } else {\n      recorders.recordRequireEmpty({\n        kind,\n        field,\n        type: \"CHANGE_FORMAT\",\n        detail: `${existing.format} → ${next.format}`,\n      });\n    }\n  }\n}\n\nfunction classifyNumber(\n  kind: string,\n  field: string,\n  existing: ExtensionNumberProperty,\n  next: ExtensionNumberProperty,\n  recorders: Recorders,\n): void {\n  if (\n    next.min !== undefined &&\n    (existing.min === undefined || next.min > existing.min)\n  ) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_CONSTRAINT\",\n      detail: `min: ${existing.min ?? \"(none)\"} → ${next.min}`,\n    });\n  }\n  if (\n    next.max !== undefined &&\n    (existing.max === undefined || next.max < existing.max)\n  ) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_CONSTRAINT\",\n      detail: `max: ${existing.max ?? \"(none)\"} → ${next.max}`,\n    });\n  }\n  if (existing.int !== next.int && next.int === true && existing.int !== true) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_INT\",\n      detail: \"int: false → true\",\n    });\n  }\n  // LOOSEN_INT — allowed.\n}\n\nfunction classifyEnum(\n  kind: string,\n  field: string,\n  existing: ExtensionEnumProperty,\n  next: ExtensionEnumProperty,\n  recorders: Recorders,\n): void {\n  const nextValues = new Set(next.values);\n  const removed = existing.values.filter((value) => !nextValues.has(value));\n  if (removed.length > 0) {\n    recorders.recordRequireEmpty({\n      kind,\n      field,\n      type: \"TIGHTEN_ENUM\",\n      detail: `removed values: ${removed.join(\", \")}`,\n    });\n  }\n  // Adding values — LOOSEN_ENUM, allowed.\n}\n\nfunction classifyArray(\n  kind: string,\n  field: string,\n  existing: ExtensionArrayProperty,\n  next: ExtensionArrayProperty,\n  recorders: Recorders,\n): void {\n  // v1: array.items deltas are nested-property deltas. Same-type\n  // recurse; different-type → TYPE_CHANGE.\n  if (existing.items.type !== next.items.type) {\n    recorders.recordIncompatible({\n      kind,\n      field: `${field}.items`,\n      type: \"TYPE_CHANGE\",\n      detail: `${existing.items.type} → ${next.items.type}`,\n    });\n    return;\n  }\n  classifyProperty(\n    kind,\n    `${field}.items`,\n    existing.items,\n    next.items,\n    recorders,\n  );\n}\n\nfunction classifyObject(\n  kind: string,\n  field: string,\n  existing: ExtensionObjectProperty,\n  next: ExtensionObjectProperty,\n  recorders: Recorders,\n): void {\n  // Recurse into the object's properties with field-prefixed names so\n  // the issue carries a useful path for the reviewer.\n  classifyProperties(kind, existing.properties, next.properties, {\n    recordIncompatible: (entry) => {\n      recorders.recordIncompatible({\n        ...entry,\n        field: `${field}.${entry.field ?? \"\"}`,\n      });\n    },\n    recordRequireEmpty: (entry) => {\n      recorders.recordRequireEmpty({\n        ...entry,\n        field: `${field}.${entry.field ?? \"\"}`,\n      });\n    },\n  });\n}\n\n// ============================================================\n// Unique constraints\n// ============================================================\n\nfunction classifyUnique(\n  kind: string,\n  existing: readonly ExtensionUniqueConstraint[],\n  next: readonly ExtensionUniqueConstraint[],\n  recorders: Recorders,\n): void {\n  const existingByName = new Map(\n    existing.map((constraint) => [constraint.name, constraint]),\n  );\n  const nextByName = new Map(\n    next.map((constraint) => [constraint.name, constraint]),\n  );\n  for (const [name, constraint] of nextByName) {\n    if (!existingByName.has(name)) {\n      // ADD_UNIQUE — allowed-on-empty (existing rule, kept).\n      recorders.recordRequireEmpty({\n        kind,\n        type: \"ADD_UNIQUE_ON_POPULATED\",\n        detail: `unique constraint \"${name}\" on [${constraint.fields.join(\", \")}]`,\n      });\n    }\n  }\n  // Dropped unique constraints — DROP_UNIQUE, allowed.\n  // Modified — DROP + ADD; the ADD is recorded above for any\n  // structurally-different constraint with a same name.\n  for (const [name, constraint] of existingByName) {\n    const newOne = nextByName.get(name);\n    if (newOne === undefined) continue;\n    // Different shape with same name → treat as modify; ADD half is\n    // allowed-on-empty. Use `canonicalEqual` so the comparison is\n    // key-order-stable; plain `JSON.stringify` would flag two\n    // structurally identical constraints with differently-ordered\n    // keys as reshaped.\n    const { name: _existingName, ...existingShape } = constraint;\n    const { name: _nextName, ...nextShape } = newOne;\n    if (!canonicalEqual(existingShape, nextShape)) {\n      recorders.recordRequireEmpty({\n        kind,\n        type: \"ADD_UNIQUE_ON_POPULATED\",\n        detail: `unique constraint \"${name}\" reshaped`,\n      });\n    }\n  }\n}\n","/** Pure preparation for a schema evolution; database-dependent guards run at apply time. */\nimport type { GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { classifyModifications } from \"../graph-extension/classify\";\nimport { IncompatibleChangeError } from \"../graph-extension/errors\";\nimport type { GraphExtension } from \"../graph-extension/extension-types\";\nimport { mergeGraphExtension } from \"../graph-extension/merge\";\nimport type { VectorSlot } from \"../query/dialect/vector-strategy\";\nimport { freezeDeep } from \"../utils/object\";\nimport { canonicalEqual } from \"./canonical\";\nimport { prepareNewSchemaVersion } from \"./new-schema-version\";\nimport type { SchemaHash, SchemaIdentity, SerializedSchema } from \"./types\";\n\n/** A planned schema delta, database-dependent check, or provisioning requirement. */\nexport type EvolutionRequirement =\n  | Readonly<{\n      kind: \"require-empty\";\n      entity: \"node\" | \"edge\";\n      kindName: string;\n    }>\n  | Readonly<{\n      /** A kind added by this delta; does not imply a pending removal or cleanup work. */\n      kind: \"new-kind\";\n      entity: \"node\" | \"edge\";\n      kindName: string;\n    }>\n  | Readonly<{\n      kind: \"vector-slot\";\n      nodeKind: string;\n      fieldPath: string;\n    }>\n  | Readonly<{\n      kind: \"identity\";\n      nodeKinds: readonly string[];\n    }>;\n\n/** Ordered requirements exposed by a change plan. */\nexport type EvolutionRequirements = readonly EvolutionRequirement[];\n\n/** Private instructions retained for the Store's apply-time checks. */\nexport type EvolutionPlanRequirements = Readonly<{\n  requireEmpty: readonly Extract<\n    EvolutionRequirement,\n    { kind: \"require-empty\" }\n  >[];\n  addedKinds: readonly Extract<EvolutionRequirement, { kind: \"new-kind\" }>[];\n  vectorSlots: readonly Extract<\n    EvolutionRequirement,\n    { kind: \"vector-slot\" }\n  >[];\n  identityAffectedKinds: readonly string[];\n}>;\n\ndeclare const evolutionPlanBrand: unique symbol;\n\ntype EvolutionPlanBase = Readonly<{\n  graphId: string;\n  baseline: SchemaIdentity;\n  result: SchemaIdentity;\n  /** Only this module can mint a plan accepted by withEvolvedTransaction. */\n  [evolutionPlanBrand]: true;\n}>;\n\n/**\n * A prepared schema change. Plans are module-bound, nonserializable values:\n * object spreads, clones, and reconstructed data cannot be applied.\n */\nexport type EvolutionPlan =\n  | (EvolutionPlanBase & Readonly<{ status: \"noop\" }>)\n  | (EvolutionPlanBase &\n      Readonly<{\n        status: \"change\";\n        requirements: EvolutionRequirements;\n      }>);\n\nexport type EvolutionPlanPayload<G extends GraphDef> = Readonly<{\n  baselineGraph: G;\n  mergedGraph: G;\n  requirements?: EvolutionPlanRequirements;\n  classification?: ReturnType<typeof classifyModifications>;\n  schemaDocument?: SerializedSchema;\n  vectorSlots?: readonly VectorSlot[];\n}>;\n\nconst PLAN_PAYLOADS = new WeakMap<\n  EvolutionPlan,\n  EvolutionPlanPayload<GraphDef>\n>();\n\nfunction mintEvolutionPlan(\n  fields:\n    | (Omit<EvolutionPlanBase, typeof evolutionPlanBrand> &\n        Readonly<{ status: \"noop\" }>)\n    | (Omit<EvolutionPlanBase, typeof evolutionPlanBrand> &\n        Readonly<{ status: \"change\"; requirements: EvolutionRequirements }>),\n): EvolutionPlan {\n  return Object.freeze(fields) as EvolutionPlan;\n}\n\nfunction newlyAddedKinds(\n  existing: GraphExtension,\n  next: GraphExtension,\n): EvolutionPlanRequirements[\"addedKinds\"] {\n  const nodes = Object.keys(next.nodes ?? {})\n    .filter((kindName) => !Object.hasOwn(existing.nodes ?? {}, kindName))\n    .map((kindName) =>\n      Object.freeze({\n        kind: \"new-kind\" as const,\n        entity: \"node\" as const,\n        kindName,\n      }),\n    );\n  const edges = Object.keys(next.edges ?? {})\n    .filter((kindName) => !Object.hasOwn(existing.edges ?? {}, kindName))\n    .map((kindName) =>\n      Object.freeze({\n        kind: \"new-kind\" as const,\n        entity: \"edge\" as const,\n        kindName,\n      }),\n    );\n  return Object.freeze([...nodes, ...edges]);\n}\n\nfunction newlyAddedVectorSlots(\n  existing: GraphExtension,\n  next: GraphExtension,\n): EvolutionPlanRequirements[\"vectorSlots\"] {\n  const slots: Extract<EvolutionRequirement, { kind: \"vector-slot\" }>[] = [];\n  for (const [kindName, node] of Object.entries(next.nodes ?? {})) {\n    const previous =\n      Object.hasOwn(existing.nodes ?? {}, kindName) ?\n        existing.nodes?.[kindName]\n      : undefined;\n    for (const [fieldName, property] of Object.entries(node.properties)) {\n      if (\n        property.embedding !== undefined &&\n        previous?.properties[fieldName]?.embedding === undefined\n      ) {\n        slots.push(\n          Object.freeze({\n            kind: \"vector-slot\",\n            nodeKind: kindName,\n            fieldPath: fieldName,\n          }),\n        );\n      }\n    }\n  }\n  return Object.freeze(slots);\n}\n\nfunction identityKindsRequiringPreflight<G extends GraphDef>(\n  baselineGraph: G,\n  mergedGraph: G,\n): readonly string[] {\n  if (baselineGraph.identity === undefined) return [];\n  if (\n    !canonicalEqual(\n      baselineGraph.extension?.ontology,\n      mergedGraph.extension?.ontology,\n    )\n  ) {\n    return Object.keys(mergedGraph.nodes);\n  }\n  // New kinds have no existing identity members. Kind removal cascades its\n  // assertions, and the apply-time pending-removal guard protects re-addition.\n  // An unrelated kind or scalar field therefore owes no identity scan.\n  return [];\n}\n\n/**\n * Prepare the semantic evolution once, against a named schema snapshot.\n * The caller owns snapshot freshness; this function performs no database I/O.\n */\nexport async function prepareEvolutionPlan<G extends GraphDef>(\n  params: Readonly<{\n    baselineGraph: G;\n    baselineVersion: number;\n    baselineHash: SchemaHash;\n    storedSchema: SerializedSchema;\n    extension: GraphExtension;\n  }>,\n): Promise<EvolutionPlan> {\n  const {\n    baselineGraph,\n    baselineVersion,\n    baselineHash,\n    storedSchema,\n    extension: callerExtension,\n  } = params;\n  const extension = freezeDeep(structuredClone(callerExtension));\n  const mergedGraph = mergeGraphExtension(baselineGraph, extension);\n  if (mergedGraph === baselineGraph) {\n    const baseline = Object.freeze({\n      version: baselineVersion,\n      hash: baselineHash,\n    });\n    const plan = mintEvolutionPlan({\n      status: \"noop\",\n      graphId: baselineGraph.id,\n      baseline,\n      result: baseline,\n    });\n    PLAN_PAYLOADS.set(\n      plan,\n      Object.freeze({ baselineGraph, mergedGraph: baselineGraph }),\n    );\n    return plan;\n  }\n\n  const existingExtension = baselineGraph.extension ?? Object.freeze({});\n  const classification = classifyModifications(existingExtension, extension);\n  if (classification.incompatible.length > 0) {\n    throw new IncompatibleChangeError(\n      classification.incompatible,\n      baselineGraph.id,\n    );\n  }\n  const prepared = await prepareNewSchemaVersion(\n    mergedGraph,\n    baselineVersion,\n    storedSchema,\n  );\n  const resultingVersion = prepared.version;\n  const schemaDocument = freezeDeep(prepared.schemaDocument);\n  const resultingHash = prepared.schemaHash;\n  const addedKinds = newlyAddedKinds(existingExtension, extension);\n  const groupedRequirements: EvolutionPlanRequirements = Object.freeze({\n    requireEmpty: Object.freeze(\n      classification.requireEmpty.map((entry) =>\n        Object.freeze({\n          kind: \"require-empty\" as const,\n          entity: entry.entity,\n          kindName: entry.kindName,\n        }),\n      ),\n    ),\n    addedKinds,\n    vectorSlots: newlyAddedVectorSlots(existingExtension, extension),\n    identityAffectedKinds: Object.freeze(\n      identityKindsRequiringPreflight(baselineGraph, mergedGraph),\n    ),\n  });\n  const requirements: EvolutionRequirements = Object.freeze([\n    ...groupedRequirements.requireEmpty,\n    ...groupedRequirements.addedKinds,\n    ...groupedRequirements.vectorSlots,\n    ...(groupedRequirements.identityAffectedKinds.length > 0 ?\n      [\n        Object.freeze({\n          kind: \"identity\" as const,\n          nodeKinds: groupedRequirements.identityAffectedKinds,\n        }),\n      ]\n    : []),\n  ]);\n  const plan = mintEvolutionPlan({\n    status: \"change\",\n    graphId: baselineGraph.id,\n    baseline: Object.freeze({ version: baselineVersion, hash: baselineHash }),\n    result: Object.freeze({ version: resultingVersion, hash: resultingHash }),\n    requirements,\n  });\n  PLAN_PAYLOADS.set(\n    plan,\n    Object.freeze({\n      baselineGraph,\n      mergedGraph,\n      requirements: groupedRequirements,\n      classification,\n      schemaDocument,\n      vectorSlots: freezeDeep(\n        resolveGraphVectorSlots(mergedGraph).filter((slot) =>\n          groupedRequirements.vectorSlots.some(\n            (required) =>\n              required.nodeKind === slot.nodeKind &&\n              required.fieldPath === slot.fieldPath,\n          ),\n        ),\n      ),\n    }),\n  );\n  return plan;\n}\n\n/** Refuse forged or modified objects before using private execution instructions. */\nexport function getEvolutionPlanPayload<G extends GraphDef>(\n  plan: EvolutionPlan,\n): EvolutionPlanPayload<G> | undefined {\n  return PLAN_PAYLOADS.get(plan) as EvolutionPlanPayload<G> | undefined;\n}\n","import { type GraphBackend } from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n  assertValidRecordedInstant,\n  type RecordedInstant,\n  resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport {\n  ConfigurationError,\n  UnsupportedBackendCapabilityError,\n} from \"../../errors\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../../query/compiler/recursive\";\nimport {\n  type RecordedReadBinding,\n  recordedReadSchemaFor,\n  type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n  type TemporalFilterOptions,\n} from \"../../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport type { AlgorithmCyclePolicy, TraversalDirection } from \"./types\";\n\nexport const DEFAULT_ALGORITHM_MAX_HOPS = 10;\nexport const DEFAULT_NEIGHBOR_DEPTH = 1;\n\nexport type AlgorithmContext = Readonly<{\n  graphId: string;\n  /** Graph definition — degree() enumerates declared edge endpoint kinds. */\n  graph: GraphDef;\n  /** Kind registry — expands declared endpoint kinds through subClassOf. */\n  registry: KindRegistry;\n  backend: GraphBackend;\n  dialect: DialectAdapter;\n  schema: SqlSchema;\n  recordedReadBinding: RecordedReadBinding | undefined;\n  defaultTemporalMode: TemporalMode;\n}>;\n\nexport type InternalTemporalOptions = Readonly<{\n  temporalMode?: TemporalMode;\n  asOf?: string;\n  recordedAsOf?: RecordedInstant;\n}>;\n\nexport type InternalTraversalOptions = InternalTemporalOptions &\n  Readonly<{\n    edges: readonly string[];\n    maxHops?: number;\n    direction?: TraversalDirection;\n    cyclePolicy?: AlgorithmCyclePolicy;\n    workingMemory?: string;\n    /**\n     * Numeric edge property supplying per-edge traversal weights. When set,\n     * the iterative operation compiles a shared weight expression and every\n     * edge expansion carries a `weight` column.\n     */\n    weightProperty?: string;\n    /** Weight substituted for edges missing `weightProperty`. */\n    defaultWeight?: number;\n  }>;\n\n/** Copies only explicitly supplied temporal overrides for option forwarding. */\nexport function pickTemporalOptions(\n  options: InternalTemporalOptions,\n): InternalTemporalOptions {\n  return {\n    ...(options.temporalMode === undefined ?\n      {}\n    : { temporalMode: options.temporalMode }),\n    ...(options.asOf === undefined ? {} : { asOf: options.asOf }),\n    ...(options.recordedAsOf === undefined ?\n      {}\n    : { recordedAsOf: options.recordedAsOf }),\n  };\n}\n\n/**\n * Resolves per-call temporal overrides against the graph's default mode into\n * a plain `{ temporalMode, asOf? }` object. Consumed by the working-table\n * iteration (`iterative-graph-operation.ts:848`), not `buildReachableCte` —\n * `reachable`/`canReach`/`neighbors`/`shortestPath` route through the\n * iterative working-table path and emit no recursive CTE. An `asOf` is\n * rejected unless the mode is `\"asOf\"` (via {@link resolveReadCoordinate}),\n * matching every other read path.\n */\nexport function resolveTemporalOptions(\n  ctx: AlgorithmContext,\n  options: InternalTemporalOptions,\n): Readonly<{\n  temporalMode: TemporalMode;\n  asOf?: string;\n  recordedAsOf?: RecordedInstant;\n}> {\n  const { valid } = resolveReadCoordinate(\n    options.temporalMode ?? ctx.defaultTemporalMode,\n    options.asOf,\n  );\n  // `recordedAsOf` normally arrives pre-validated through StoreView's\n  // withRecordedCoordinate, but it is absent from the public algorithm option\n  // types, so validate here too: a type-unsafe caller that smuggles a\n  // non-canonical anchor would otherwise be string-compared raw against\n  // recorded_from/recorded_to and return wrong rows on SQLite.\n  if (options.recordedAsOf !== undefined) {\n    assertValidRecordedInstant(options.recordedAsOf, \"recordedAsOf\");\n  }\n  return {\n    temporalMode: valid.mode,\n    ...(valid.asOf !== undefined && { asOf: valid.asOf }),\n    ...(options.recordedAsOf === undefined ?\n      {}\n    : { recordedAsOf: options.recordedAsOf }),\n  };\n}\n\nexport function resolveReadSchema(\n  ctx: AlgorithmContext,\n  options: InternalTemporalOptions,\n): SqlSchema {\n  return recordedReadSchemaFor(\n    ctx.schema,\n    options.recordedAsOf,\n    ctx.recordedReadBinding,\n    \"recorded-graph-algorithm\",\n  );\n}\n\n/**\n * Compiles the resolved temporal filter to SQL. `resolveTemporalOptions`\n * has already rejected an `asOf` paired with any non-`\"asOf\"` mode, so a\n * stray pin can never reach the filter; `current` resolves against the\n * dialect's current-timestamp expression.\n */\nexport function resolveTemporalFilter(\n  ctx: AlgorithmContext,\n  options: InternalTemporalOptions,\n  tableAlias?: string,\n): ReturnType<typeof compileTemporalFilter> {\n  const resolved = resolveTemporalOptions(ctx, options);\n  const filterOptions: TemporalFilterOptions = {\n    mode: resolved.temporalMode,\n    asOf: resolved.asOf,\n    recordedAsOf: resolved.recordedAsOf,\n    tableAlias,\n    currentTimestamp: currentReadInstant(),\n    recordedReadBinding: ctx.recordedReadBinding,\n  };\n  return compileTemporalFilter(filterOptions);\n}\n\nexport function resolveMaxHops(\n  rawMaxHops: number | undefined,\n  fallback: number,\n  optionName: \"maxHops\" | \"depth\",\n): number {\n  const value = rawMaxHops ?? fallback;\n\n  if (!Number.isFinite(value) || !Number.isInteger(value)) {\n    throw new ConfigurationError(\n      `Graph algorithm ${optionName} must be a finite integer, got ${String(value)}.`,\n      { option: optionName, value },\n    );\n  }\n\n  if (value < 1) {\n    throw new ConfigurationError(\n      `Graph algorithm ${optionName} must be at least 1, got ${value}.`,\n      { option: optionName, value },\n    );\n  }\n\n  if (value > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n    throw new ConfigurationError(\n      `Graph algorithm ${optionName} (${value}) exceeds the maximum of ${MAX_EXPLICIT_RECURSIVE_DEPTH}.`,\n      { option: optionName, value, limit: MAX_EXPLICIT_RECURSIVE_DEPTH },\n    );\n  }\n\n  return value;\n}\n\n/**\n * Validates an iterative algorithm's round budget. Unlike {@link\n * resolveMaxHops}, the budget is not a traversal depth bound — convergence\n * normally ends the run first — so it is not capped at the recursive-CTE\n * depth limit.\n */\nexport function resolveMaxIterations(\n  value: number | undefined,\n  fallback: number,\n  algorithm: string,\n): number {\n  const maxIterations = value ?? fallback;\n  assertPositiveSafeIntegerOption(maxIterations, algorithm, \"maxIterations\");\n  return maxIterations;\n}\n\n/** Validates an optional positive safe-integer algorithm option. */\nexport function assertPositiveSafeIntegerOption(\n  value: number | undefined,\n  algorithm: string,\n  optionName: string,\n): void {\n  if (value === undefined) return;\n  if (!Number.isSafeInteger(value) || value < 1) {\n    throw new ConfigurationError(\n      `${algorithm} ${optionName} must be a positive safe integer, got ${String(value)}.`,\n      { [optionName]: value },\n    );\n  }\n}\n\nexport function assertEdgeKinds(edges: readonly string[]): void {\n  if (edges.length === 0) {\n    throw new ConfigurationError(\n      `Graph algorithms require at least one edge kind in 'edges'.`,\n      { edges },\n    );\n  }\n}\n\nexport function assertGraphAnalyticsSupported(\n  ctx: AlgorithmContext,\n  algorithm: string,\n  options: Readonly<{ requiresWindowFunctions?: boolean }> = {},\n): void {\n  const graphAnalytics =\n    ctx.backend.capabilities.graphAnalytics?.supported === true;\n  const windowFunctions = ctx.backend.capabilities.windowFunctions;\n  if (\n    graphAnalytics &&\n    (options.requiresWindowFunctions !== true || windowFunctions)\n  ) {\n    return;\n  }\n\n  throw new UnsupportedBackendCapabilityError(\n    algorithm,\n    \"graphAnalytics\",\n    {\n      dialect: ctx.backend.dialect,\n      supported: graphAnalytics,\n      ...(options.requiresWindowFunctions === true ? { windowFunctions } : {}),\n    },\n    \"Use a built-in transactional SQLite/PostgreSQL backend, or declare graphAnalytics support on a compatible custom backend.\",\n  );\n}\n","import { compileKindFilter } from \"../../query/compiler/predicate-utils\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n  type AlgorithmContext,\n  type InternalTemporalOptions,\n  resolveReadSchema,\n  resolveTemporalFilter,\n} from \"./context\";\nimport type { TraversalDirection } from \"./types\";\n\ntype InternalDegreeOptions = InternalTemporalOptions &\n  Readonly<{\n    edges?: readonly string[];\n    direction?: TraversalDirection;\n  }>;\n\nexport async function executeDegree(\n  ctx: AlgorithmContext,\n  nodeId: string,\n  options: InternalDegreeOptions = {},\n): Promise<number> {\n  const direction = options.direction ?? \"both\";\n  const edgeKinds = options.edges ?? Object.keys(ctx.graph.edges);\n  // A graph that declares no edge kinds has no edges to count — provably zero\n  // without a round trip.\n  if (edgeKinds.length === 0) return 0;\n\n  const schema = resolveReadSchema(ctx, options);\n  const whereClauses: SqlFragment[] = [\n    sql`graph_id = ${ctx.graphId}`,\n    resolveTemporalFilter(ctx, options),\n    compileDirectionFilter(ctx, direction, nodeId, schema.nodesTable),\n  ];\n  if (options.edges !== undefined) {\n    whereClauses.push(compileKindFilter(sql.raw(\"kind\"), options.edges));\n  }\n\n  // COUNT(DISTINCT id) collapses self-loops (from === to === nodeId) to a\n  // single edge so they don't double-count under `\"both\"`.\n  const countExpr =\n    direction === \"both\" ? sql`COUNT(DISTINCT id)` : sql`COUNT(*)`;\n\n  const query = sql`SELECT ${countExpr} AS count FROM ${schema.edgesTable} WHERE ${sql.join(whereClauses, sql` AND `)}`;\n\n  const rows = await ctx.backend.execute<Readonly<{ count: number | string }>>(\n    asCompiledRowsSql(query),\n  );\n  return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * The counted node's own kind, as a scalar subquery.\n *\n * Every edge row stores the *actual* kind of each endpoint node — the write\n * path takes `from_kind` straight off the `from` node reference, and a node's\n * kind is immutable for the life of its id. So for any edge incident to\n * `nodeId`, the endpoint kind on `nodeId`'s side equals `nodeId`'s kind, and\n * nothing else. That makes this an equality the composite edge indexes seek on\n * directly, and it stays true no matter how the graph's endpoint declarations\n * evolve.\n *\n * (Enumerating the *declared* endpoint kinds instead — the shape this replaced\n * — held only for rows written under the current declaration. Narrow an edge's\n * `from: [Person]` to `from: [Employee]` and every `Person`-rooted edge already\n * on disk drops out of the filter, silently undercounting.)\n *\n * The subquery is uncorrelated, so both engines evaluate it once and treat the\n * result as a constant: Postgres hoists it to an InitPlan, SQLite runs it as a\n * one-shot scalar subquery. `LIMIT 1` is required in recorded-time mode, where\n * the resolved nodes relation holds one row per recorded version of the node.\n * An unknown `nodeId` yields NULL, and `from_kind = NULL` matches nothing —\n * degree 0, which is what a node that does not exist has.\n */\nfunction nodeKindSubquery(\n  ctx: AlgorithmContext,\n  nodeId: string,\n  nodesTable: SqlFragment,\n): SqlFragment {\n  return sql`(SELECT kind FROM ${nodesTable} WHERE graph_id = ${ctx.graphId} AND id = ${nodeId} LIMIT 1)`;\n}\n\n/**\n * Direction filter shaped for the default edge indexes: the endpoint-kind\n * equality comes first so `edges_from_idx (graph_id, from_kind, from_id, …)`\n * / `edges_to_idx (graph_id, to_kind, to_id, …)` can seek — a bare\n * `from_id = ?` scans the whole edge partition because both indexes lead\n * with the kind column.\n */\nfunction compileDirectionFilter(\n  ctx: AlgorithmContext,\n  direction: TraversalDirection,\n  nodeId: string,\n  nodesTable: SqlFragment,\n): SqlFragment {\n  const nodeKind = nodeKindSubquery(ctx, nodeId, nodesTable);\n  const fromSide = sql`(from_kind = ${nodeKind} AND from_id = ${nodeId})`;\n  const toSide = sql`(to_kind = ${nodeKind} AND to_id = ${nodeId})`;\n\n  switch (direction) {\n    case \"out\": {\n      return fromSide;\n    }\n    case \"in\": {\n      return toSide;\n    }\n    case \"both\": {\n      return sql`(${fromSide} OR ${toSide})`;\n    }\n  }\n}\n","import {\n  type GraphBackend,\n  INTERNAL_TEMPORARY_WRITES,\n  type InternalTransactionOptions,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport {\n  CompilerInvariantError,\n  ConfigurationError,\n  GraphAlgorithmConvergenceError,\n  UnsupportedBackendCapabilityError,\n} from \"../../errors\";\nimport {\n  compileKindFilter,\n  sqlValueList,\n} from \"../../query/compiler/predicate-utils\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n} from \"../../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { jsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport {\n  asCompiledRowsSql,\n  asCompiledTemporaryStatementSql,\n} from \"../../query/sql-intent\";\nimport { compareCodePoints, compareStrings } from \"../../utils/compare\";\nimport { generateId } from \"../../utils/id\";\nimport { isPresent } from \"../../utils/presence\";\nimport {\n  type PostgresReadWriteRefusedSqlState,\n  postgresReadWriteRefusedSqlState,\n  type PostgresTemporaryTableUnavailableSqlState,\n  postgresTemporaryTableUnavailableSqlState,\n} from \"../../utils/sql-errors\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport { resolveReadSchema, resolveTemporalOptions } from \"./context\";\nimport type { PathNode, TraversalDirection } from \"./types\";\n\ntype QueryBackend = Pick<GraphBackend, \"capabilities\" | \"execute\">;\ntype WorkingTableIdentifier = ReturnType<typeof sql.identifier>;\ntype CapturedFailure = Readonly<{ error: unknown }>;\n\nexport type IterativeGraphOperation = Readonly<{\n  backend: QueryBackend;\n  ctx: AlgorithmContext;\n  edgeKindChunks: readonly (readonly string[])[];\n  direction: TraversalDirection;\n  maxWorkingSetSize: number;\n  nodeTemporalFilter: ReturnType<typeof compileTemporalFilter>;\n  edgeTemporalFilter: ReturnType<typeof compileTemporalFilter>;\n  schema: ReturnType<typeof resolveReadSchema>;\n  /**\n   * Validated caller-requested transaction-scoped memory override for\n   * working-table rounds; `undefined` inherits the engine's configuration.\n   */\n  workingMemory: string | undefined;\n  /**\n   * Per-edge traversal weight over the expansion's edge alias `e`, compiled\n   * from the caller's `weightProperty`/`defaultWeight`. When set, every edge\n   * expansion carries it as a `weight` column; `undefined` for unweighted\n   * operations.\n   */\n  weightExpression: SqlFragment | undefined;\n}>;\n\nexport type NodeIdentityKey = string & {\n  readonly __nodeIdentityKey: unique symbol;\n};\n\nexport type NodeExpansion = Readonly<{\n  source: PathNode;\n  target: PathNode;\n  /** Edge weight; present exactly when the operation is weighted. */\n  weight?: number;\n}>;\n\ntype TemporaryStatementBackend = QueryBackend &\n  Pick<TransactionBackend, \"executeTemporaryStatement\"> &\n  Readonly<{\n    executeTemporaryStatement: NonNullable<\n      TransactionBackend[\"executeTemporaryStatement\"]\n    >;\n  }>;\n\nexport type IterativeGraphRunContext = Readonly<{\n  operation: IterativeGraphOperation;\n  backend: TemporaryStatementBackend;\n  workingTable: WorkingTableIdentifier;\n  graphId: string;\n  runId: string;\n  executeTemporary: (query: SqlFragment) => Promise<void>;\n}>;\n\nexport type IterativeGraphState = Readonly<{\n  workingTableSize: number;\n}>;\n\nexport function frontierIndexIdentifier(\n  context: IterativeGraphRunContext,\n): SqlFragment {\n  return sql.identifier(\n    `typegraph_iterative_${context.runId.replaceAll(\"-\", \"_\")}_frontier`,\n  );\n}\n\ntype WorkingTableCountRow = Readonly<{ count: number | string }>;\n\ntype WorkingTableNodeSeedColumn = Readonly<{\n  name: string;\n  value: SqlFragment;\n}>;\n\n/** Counts this run's working-table rows; drivers may deliver bigint text. */\nexport async function countWorkingTableRows(\n  context: IterativeGraphRunContext,\n): Promise<number> {\n  const rows = await context.backend.execute<WorkingTableCountRow>(\n    asCompiledRowsSql(sql`\n      SELECT COUNT(*) AS count\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n    `),\n  );\n  return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * Populates an iterative working table from the visible induced subgraph.\n * Explicit node-kind scopes are deterministic and split against the exact\n * statement budget; an omitted scope keeps the single full-graph statement.\n */\nexport async function seedWorkingTableFromNodes(\n  context: IterativeGraphRunContext,\n  nodeKinds: readonly string[] | undefined,\n  seedColumns: readonly WorkingTableNodeSeedColumn[],\n): Promise<void> {\n  if (nodeKinds?.length === 0) return;\n  const additionalColumns =\n    seedColumns.length === 0 ?\n      sql.empty()\n    : sql`, ${sql.join(\n        seedColumns.map((column) => sql.identifier(column.name)),\n        sql`, `,\n      )}`;\n  const additionalValues =\n    seedColumns.length === 0 ?\n      sql.empty()\n    : sql`, ${sql.join(\n        seedColumns.map((column) => column.value),\n        sql`, `,\n      )}`;\n  const compileSeedStatement = (nodeKindFilter: SqlFragment): SqlFragment => {\n    return sql`\n      INSERT INTO ${context.workingTable}\n        (graph_id, run_id, node_id, node_kind${additionalColumns})\n      SELECT ${context.graphId}, ${context.runId}, n.id, n.kind${additionalValues}\n      FROM ${context.operation.schema.nodesTable} n\n      WHERE n.graph_id = ${context.graphId}\n        AND ${nodeKindFilter}\n        AND ${context.operation.nodeTemporalFilter}\n    `;\n  };\n\n  const fixedStatement = compileSeedStatement(sql`TRUE`);\n  const parameterLimit =\n    context.operation.backend.capabilities.maxBindParameters ??\n    DEFAULT_MAX_BIND_PARAMETERS;\n  const fixedParameterCount = countBindParameters(fixedStatement);\n  // The full-graph seed carries no kind binds and only has to fit; a scoped\n  // seed also needs room for at least one kind bind before it can be chunked.\n  const kindBindBudget = parameterLimit - fixedParameterCount;\n  if (kindBindBudget < (nodeKinds === undefined ? 0 : 1)) {\n    throw new ConfigurationError(\n      \"An iterative graph operation cannot fit its node-kind initialization within the backend bind-parameter limit.\",\n      { fixedParameterCount, parameterLimit },\n    );\n  }\n\n  if (nodeKinds === undefined) {\n    await context.executeTemporary(fixedStatement);\n    return;\n  }\n\n  const normalizedKinds = [...new Set(nodeKinds)].toSorted((left, right) =>\n    compareCodePoints(left, right),\n  );\n  for (const kindChunk of chunkValues(normalizedKinds, kindBindBudget)) {\n    await context.executeTemporary(\n      compileSeedStatement(compileKindFilter(sql.raw(\"n.kind\"), kindChunk)),\n    );\n  }\n}\n\nfunction countBindParameters(fragment: SqlFragment): number {\n  return fragment.chunks.reduce(\n    (count, chunk) =>\n      count +\n      (chunk.kind === \"parameter\" || chunk.kind === \"placeholder\" ? 1 : 0),\n    0,\n  );\n}\n\nexport type IterativeGraphPlan<\n  State extends IterativeGraphState,\n  Result,\n> = Readonly<{\n  algorithm: string;\n  maxIterations: number;\n  createWorkingTable: (context: IterativeGraphRunContext) => SqlFragment;\n  initialize: (context: IterativeGraphRunContext) => Promise<State>;\n  runRound: (\n    context: IterativeGraphRunContext,\n    state: State,\n    iteration: number,\n  ) => Promise<State>;\n  hasConverged: (state: State) => boolean;\n  extractResult: (\n    context: IterativeGraphRunContext,\n    state: State,\n  ) => Promise<Result>;\n  /** Drops any plan-owned temporary relations before the working table. */\n  cleanup?: (context: IterativeGraphRunContext) => Promise<void>;\n}>;\n\ntype ExpansionRow = Readonly<{\n  source_id: string;\n  source_kind: string;\n  target_id: string;\n  target_kind: string;\n  /** Present when the operation is weighted; drivers may deliver text. */\n  weight?: number | string | null;\n}>;\n\ntype VisibleNodeRow = Readonly<{\n  id: string;\n  kind: string;\n}>;\n\nexport const DEFAULT_MAX_BIND_PARAMETERS = 999;\nconst RESERVED_TEMPORAL_BIND_PARAMETERS_PER_BRANCH = 12;\n/** Headroom for the weight expression's path and default-weight binds. */\nconst RESERVED_WEIGHT_BIND_PARAMETERS_PER_BRANCH = 4;\n/**\n * PostgreSQL initially estimates an un-analyzed temporary relation at one row.\n * Even a few dozen rows can distort join ordering on a dense edge expansion,\n * while ANALYZE remains a low-single-digit-millisecond operation at this size.\n * Keep the trigger below the 31-person smoke graph that exposed this cliff.\n */\nexport const WORKING_TABLE_ANALYZE_MINIMUM_ROWS = 16;\n/** Caps statistics drift for growing BFS-style working tables at under 4x. */\nexport const WORKING_TABLE_ANALYZE_GROWTH_FACTOR = 4;\n\n/**\n * Accepts only a plain integer with a binary unit suffix. The value reaches\n * the engine as a bound parameter, but a strict shape keeps the option from\n * ever smuggling arbitrary text into a settings statement and rejects\n * ambiguous inputs (fractions, spaces, unknown units) up front.\n */\nconst ITERATIVE_WORKING_MEMORY_PATTERN = /^(\\d+)(kB|MB|GB)$/;\n\nconst WORKING_MEMORY_KILOBYTES_PER_UNIT: Readonly<Record<string, number>> = {\n  kB: 1,\n  MB: 1024,\n  GB: 1024 * 1024,\n};\n\n/**\n * PostgreSQL's accepted `work_mem` range (in kB, its base unit). Values\n * outside it fail `set_config` mid-transaction with a raw engine error on\n * PostgreSQL while SQLite would silently accept them — so both backends\n * reject them up front with the same typed error instead.\n */\nconst MIN_WORKING_MEMORY_KILOBYTES = 64;\nconst MAX_WORKING_MEMORY_KILOBYTES = 2_147_483_647;\n\n/**\n * Validates an explicitly requested working-memory override. `undefined`\n * means the caller did not opt in: the operation inherits the engine's\n * configured setting and emits no override — `work_mem` is a threshold each\n * sort/hash operator (and each parallel worker) may allocate up to, not a\n * per-operation budget, so silently raising it for every algorithm call\n * could multiply memory use far past what a DBA provisioned.\n */\nfunction resolveWorkingMemory(\n  workingMemory: string | undefined,\n): string | undefined {\n  if (workingMemory === undefined) return undefined;\n  const match = ITERATIVE_WORKING_MEMORY_PATTERN.exec(workingMemory);\n  if (match === null) {\n    throw new ConfigurationError(\n      `Iterative graph operation workingMemory must be digits followed by kB, MB, or GB (for example \"64MB\"), got ${JSON.stringify(workingMemory)}.`,\n      { workingMemory },\n    );\n  }\n  const kilobytes =\n    Number(match[1]) * (WORKING_MEMORY_KILOBYTES_PER_UNIT[match[2] ?? \"\"] ?? 0);\n  if (\n    kilobytes < MIN_WORKING_MEMORY_KILOBYTES ||\n    kilobytes > MAX_WORKING_MEMORY_KILOBYTES\n  ) {\n    throw new ConfigurationError(\n      `Iterative graph operation workingMemory must be between ${MIN_WORKING_MEMORY_KILOBYTES}kB and ${MAX_WORKING_MEMORY_KILOBYTES}kB, got ${JSON.stringify(workingMemory)}.`,\n      { workingMemory, kilobytes },\n    );\n  }\n  return workingMemory;\n}\n\n/**\n * Opens the shared execution scope for iterative graph algorithms. The host\n * controls rounds and convergence; this scope supplies a snapshot-consistent,\n * bind-limit-aware SQL working relation for each round.\n *\n * The working relation is emitted as chunked `VALUES` rows rather than a\n * connection-local temporary table. That keeps the primitive portable to\n * backends such as D1 that cannot promise one pinned connection. Transactional\n * backends still run all rounds in one read-only snapshot.\n */\nexport async function withInlineIterativeGraphOperation<T>(\n  ctx: AlgorithmContext,\n  options: InternalTraversalOptions,\n  run: (operation: IterativeGraphOperation) => Promise<T>,\n): Promise<T> {\n  if (ctx.backend.capabilities.execution.interactiveTransactions) {\n    return ctx.backend.transaction(\n      async (backend) => run(createOperation(ctx, options, backend)),\n      {\n        isolationLevel: \"repeatable_read\",\n        accessMode: \"read_only\",\n      },\n    );\n  }\n  return run(createOperation(ctx, options, ctx.backend));\n}\n\n/**\n * Runs a compiler-defined iterative algorithm against a real temporary working\n * table. The primitive owns the read-only snapshot, iteration cap, convergence\n * check, and `finally` cleanup; the plan owns only table shape, round SQL, and\n * result extraction.\n */\nexport async function runIterativeGraphOperation<\n  State extends IterativeGraphState,\n  Result,\n>(\n  ctx: AlgorithmContext,\n  options: InternalTraversalOptions,\n  plan: IterativeGraphPlan<State, Result>,\n): Promise<Result> {\n  if (!ctx.backend.capabilities.execution.interactiveTransactions) {\n    throw new ConfigurationError(\n      \"Temporary-table graph iteration requires a transactional backend.\",\n      { dialect: ctx.backend.dialect },\n    );\n  }\n\n  const transactionOptions = {\n    isolationLevel: \"repeatable_read\",\n    accessMode: \"read_only\",\n    temporaryWrites: INTERNAL_TEMPORARY_WRITES,\n  } satisfies InternalTransactionOptions;\n\n  // A standby refuses the read-write access mode in the `BEGIN` itself, so on\n  // a replica the working-table seam below never executes. A failure raised\n  // before the callback started is that refusal and nothing else.\n  const rounds = { started: false };\n  try {\n    return await ctx.backend.transaction(async (backend) => {\n      rounds.started = true;\n      return runWorkingTableRounds(ctx, options, plan, backend);\n    }, transactionOptions);\n  } catch (error) {\n    if (rounds.started || ctx.backend.dialect !== \"postgres\") throw error;\n    const sqlState = postgresReadWriteRefusedSqlState(error);\n    if (sqlState === undefined) throw error;\n    throw temporaryTableCapabilityError(ctx, plan.algorithm, sqlState, error);\n  }\n}\n\n/**\n * The typed failure for a PostgreSQL execution environment that refuses the\n * transaction-local temporary tables its static `graphAnalytics` capability\n * advertises — a replica, or a role without the database `TEMP` privilege.\n */\nfunction temporaryTableCapabilityError(\n  ctx: AlgorithmContext,\n  algorithm: string,\n  sqlState:\n    | PostgresReadWriteRefusedSqlState\n    | PostgresTemporaryTableUnavailableSqlState,\n  cause: unknown,\n): UnsupportedBackendCapabilityError {\n  const error = new UnsupportedBackendCapabilityError(\n    algorithm,\n    \"graphAnalytics\",\n    {\n      dialect: ctx.backend.dialect,\n      supported: false,\n      requirement: \"transaction-local temporary tables\",\n      sqlState,\n    },\n    \"Run graph analytics on a writable PostgreSQL primary with a role that has the TEMP privilege.\",\n  );\n  // Match the non-enumerable Error.cause property created by the native\n  // Error constructor without widening the public capability-error API.\n  Object.defineProperty(error, \"cause\", {\n    configurable: true,\n    value: cause,\n    writable: true,\n  });\n  return error;\n}\n\n/** Runs the plan's rounds against a working table inside an open transaction. */\nasync function runWorkingTableRounds<State extends IterativeGraphState, Result>(\n  ctx: AlgorithmContext,\n  options: InternalTraversalOptions,\n  plan: IterativeGraphPlan<State, Result>,\n  backend: TransactionBackend,\n): Promise<Result> {\n  const temporaryBackend = requireTemporaryStatements(backend);\n  const runId = generateId();\n  const workingTable = sql.identifier(\n    `typegraph_iterative_${runId.replaceAll(\"-\", \"_\")}`,\n  );\n  const context: IterativeGraphRunContext = {\n    operation: createOperation(ctx, options, temporaryBackend),\n    backend: temporaryBackend,\n    workingTable,\n    graphId: ctx.graphId,\n    runId,\n    executeTemporary: async (query) => {\n      await temporaryBackend.executeTemporaryStatement(\n        asCompiledTemporaryStatementSql(query),\n      );\n    },\n  };\n\n  // Opt-in only: without an explicit workingMemory the rounds inherit\n  // the engine's configured setting. When requested, the override is\n  // transaction-scoped — `set_config(..., is_local => true)` reverts\n  // when this transaction ends, so the session/server setting is never\n  // touched. SQLite returns no statement here.\n  if (context.operation.workingMemory !== undefined) {\n    const workingMemoryStatement = ctx.dialect.setTransactionWorkingMemory(\n      context.operation.workingMemory,\n    );\n    if (workingMemoryStatement !== undefined) {\n      await context.executeTemporary(workingMemoryStatement);\n    }\n  }\n  try {\n    await context.executeTemporary(plan.createWorkingTable(context));\n  } catch (error) {\n    const sqlState =\n      ctx.backend.dialect === \"postgres\" ?\n        postgresTemporaryTableUnavailableSqlState(error)\n      : undefined;\n    if (sqlState === undefined) throw error;\n    throw temporaryTableCapabilityError(ctx, plan.algorithm, sqlState, error);\n  }\n  let operationFailure: CapturedFailure | undefined;\n  try {\n    let state = await plan.initialize(context);\n    let analyzedRowCount = await refreshWorkingTableStatistics(\n      context,\n      state.workingTableSize,\n    );\n    for (\n      let iteration = 1;\n      iteration <= plan.maxIterations && !plan.hasConverged(state);\n      iteration++\n    ) {\n      state = await plan.runRound(context, state, iteration);\n      // Statistics only pay off in a subsequent round: skip the refresh\n      // when the operation just converged or the iteration budget is\n      // spent — no further round will read the working table.\n      if (iteration < plan.maxIterations && !plan.hasConverged(state)) {\n        analyzedRowCount = await refreshWorkingTableStatistics(\n          context,\n          state.workingTableSize,\n          analyzedRowCount,\n        );\n      }\n    }\n    if (!plan.hasConverged(state)) {\n      throw new GraphAlgorithmConvergenceError(\n        plan.algorithm,\n        plan.maxIterations,\n      );\n    }\n    return await plan.extractResult(context, state);\n  } catch (error) {\n    operationFailure = { error };\n    throw error;\n  } finally {\n    await cleanupWorkingTables(context, plan.cleanup, operationFailure);\n  }\n}\n\nexport function shouldRefreshWorkingTableStatistics(\n  workingTableSize: number,\n  analyzedRowCount?: number,\n): boolean {\n  if (workingTableSize < WORKING_TABLE_ANALYZE_MINIMUM_ROWS) return false;\n  if (analyzedRowCount === undefined) return true;\n  return (\n    workingTableSize >= analyzedRowCount * WORKING_TABLE_ANALYZE_GROWTH_FACTOR\n  );\n}\n\nasync function refreshWorkingTableStatistics(\n  context: IterativeGraphRunContext,\n  workingTableSize: number,\n  analyzedRowCount?: number,\n): Promise<number | undefined> {\n  if (\n    !shouldRefreshWorkingTableStatistics(workingTableSize, analyzedRowCount)\n  ) {\n    return analyzedRowCount;\n  }\n  const statement = context.operation.ctx.dialect.analyzeTemporaryTable(\n    context.workingTable,\n  );\n  if (statement === undefined) return analyzedRowCount;\n  await context.executeTemporary(statement);\n  return workingTableSize;\n}\n\nasync function dropWorkingTable(\n  context: IterativeGraphRunContext,\n  hasPrimaryFailure: boolean,\n): Promise<void> {\n  try {\n    await context.executeTemporary(\n      sql`DROP TABLE IF EXISTS ${context.workingTable}`,\n    );\n  } catch (cleanupError) {\n    // A failed PostgreSQL statement aborts the transaction, so DROP is\n    // rejected too; rollback then owns cleanup. Preserve the algorithm's root\n    // error instead of masking it with \"transaction is aborted\".\n    if (!hasPrimaryFailure) throw cleanupError;\n  }\n}\n\nasync function cleanupWorkingTables(\n  context: IterativeGraphRunContext,\n  cleanup: IterativeGraphPlan<IterativeGraphState, unknown>[\"cleanup\"],\n  operationFailure: CapturedFailure | undefined,\n): Promise<void> {\n  let cleanupFailure: CapturedFailure | undefined;\n  try {\n    await cleanup?.(context);\n  } catch (error) {\n    // Preserve a failed operation over a secondary cleanup failure. When\n    // cleanup itself is the first failure, preserve it over a subsequent\n    // PostgreSQL \"transaction is aborted\" error from dropping the main table.\n    if (operationFailure === undefined) cleanupFailure = { error };\n  }\n\n  await dropWorkingTable(\n    context,\n    operationFailure !== undefined || cleanupFailure !== undefined,\n  );\n  if (cleanupFailure !== undefined) throw cleanupFailure.error;\n}\n\nexport async function fetchVisibleWorkingNodes(\n  operation: IterativeGraphOperation,\n  nodeIds: readonly string[],\n): Promise<readonly PathNode[]> {\n  const nodes = new Map<NodeIdentityKey, PathNode>();\n  for (const chunk of chunkValues(nodeIds, operation.maxWorkingSetSize)) {\n    const query = sql`SELECT n.id, n.kind FROM ${operation.schema.nodesTable} n WHERE n.graph_id = ${operation.ctx.graphId} AND n.id IN (${sqlValueList(chunk)}) AND ${operation.nodeTemporalFilter}`;\n    const rows = await operation.backend.execute<VisibleNodeRow>(\n      asCompiledRowsSql(query),\n    );\n    for (const row of rows) nodes.set(nodeIdentityKey(row), row);\n  }\n  return [...nodes.values()].toSorted((left, right) =>\n    compareNodeIdentity(left, right),\n  );\n}\n\n/**\n * Expands one working-set round and reduces all matching edges by target-node\n * identity before returning to the host loop. Callers choose the reduction:\n * BFS keeps one predecessor, label-min keeps the smallest propagated label,\n * and other fixpoint algorithms can define their own associative merge.\n */\nexport async function reduceExpandedWorkingSet<T>(\n  operation: IterativeGraphOperation,\n  workingSet: readonly PathNode[],\n  direction: TraversalDirection,\n  reduce: (current: T | undefined, expansion: NodeExpansion) => T | undefined,\n): Promise<ReadonlyMap<NodeIdentityKey, T>> {\n  const reduced = new Map<NodeIdentityKey, T>();\n  for (const edgeKinds of operation.edgeKindChunks) {\n    for (const chunk of chunkValues(workingSet, operation.maxWorkingSetSize)) {\n      const rows = await operation.backend.execute<ExpansionRow>(\n        asCompiledRowsSql(\n          compileExpansionQuery(operation, chunk, direction, edgeKinds),\n        ),\n      );\n      for (const row of rows) {\n        // A weighted operation compiles a weight column into every\n        // expansion, and weighted algorithms audit their weight domain\n        // before expanding — so a NULL weight here means either a plan\n        // skipped that audit, or (on a backend without snapshot isolation)\n        // a concurrent write invalidated a weight mid-run. Silently\n        // dropping the edge would return plausible-but-wrong results.\n        if (\n          operation.weightExpression !== undefined &&\n          !isPresent(row.weight)\n        ) {\n          throw new CompilerInvariantError(\n            \"Weighted graph expansion produced a NULL weight. Either the plan skipped its weight audit, or edge data changed concurrently during a run on a backend without snapshot isolation.\",\n            { source: row.source_id, target: row.target_id },\n          );\n        }\n        const expansion = {\n          source: { id: row.source_id, kind: row.source_kind },\n          target: { id: row.target_id, kind: row.target_kind },\n          ...(isPresent(row.weight) ? { weight: Number(row.weight) } : {}),\n        } satisfies NodeExpansion;\n        const targetKey = nodeIdentityKey(expansion.target);\n        const selected = reduce(reduced.get(targetKey), expansion);\n        if (selected !== undefined) reduced.set(targetKey, selected);\n      }\n    }\n  }\n  return reduced;\n}\n\nexport function nodeIdentityKey(node: PathNode): NodeIdentityKey {\n  return `${node.kind}\\u0000${node.id}` as NodeIdentityKey;\n}\n\n/**\n * Builds a node identity from a working-table row's nullable predecessor\n * columns. Drivers deliver SQL NULL in varying shapes, so only a string\n * pair counts as a real predecessor — the one owner of that predicate;\n * {@link nodeIdentityKeyFromRow} delegates to it rather than re-spelling the\n * same check.\n */\nexport function nodeIdentityFromRow(\n  id: unknown,\n  kind: unknown,\n): PathNode | undefined {\n  if (typeof id !== \"string\" || typeof kind !== \"string\") return undefined;\n  return { id, kind };\n}\n\n/**\n * Builds a node-identity key from a working-table row's nullable\n * predecessor columns. See {@link nodeIdentityFromRow} for the underlying\n * string-pair predicate.\n */\nexport function nodeIdentityKeyFromRow(\n  id: unknown,\n  kind: unknown,\n): NodeIdentityKey | undefined {\n  const node = nodeIdentityFromRow(id, kind);\n  return node === undefined ? undefined : nodeIdentityKey(node);\n}\n\nexport function compareNodeIdentity(left: PathNode, right: PathNode): number {\n  return (\n    compareCodePoints(left.id, right.id) ||\n    compareCodePoints(left.kind, right.kind)\n  );\n}\n\ntype DirectionFields = Readonly<{\n  joinField: \"from_id\" | \"to_id\";\n  joinKindField: \"from_kind\" | \"to_kind\";\n  targetField: \"from_id\" | \"to_id\";\n  targetKindField: \"from_kind\" | \"to_kind\";\n}>;\n\nconst OUTGOING_DIRECTION_FIELDS = {\n  joinField: \"from_id\",\n  joinKindField: \"from_kind\",\n  targetField: \"to_id\",\n  targetKindField: \"to_kind\",\n} as const satisfies DirectionFields;\n\nconst INCOMING_DIRECTION_FIELDS = {\n  joinField: \"to_id\",\n  joinKindField: \"to_kind\",\n  targetField: \"from_id\",\n  targetKindField: \"from_kind\",\n} as const satisfies DirectionFields;\n\nfunction fieldsForDirection(\n  direction: TraversalDirection,\n): readonly DirectionFields[] {\n  switch (direction) {\n    case \"out\": {\n      return [OUTGOING_DIRECTION_FIELDS];\n    }\n    case \"in\": {\n      return [INCOMING_DIRECTION_FIELDS];\n    }\n    case \"both\": {\n      return [OUTGOING_DIRECTION_FIELDS, INCOMING_DIRECTION_FIELDS];\n    }\n  }\n}\n\nfunction compileDirectionUnion(\n  direction: TraversalDirection,\n  compileDirection: (fields: DirectionFields) => SqlFragment,\n): SqlFragment {\n  return sql.join(\n    fieldsForDirection(direction).map((fields) => compileDirection(fields)),\n    sql` UNION ALL `,\n  );\n}\n\nfunction compileExpansionQuery(\n  operation: IterativeGraphOperation,\n  workingSet: readonly PathNode[],\n  direction: TraversalDirection,\n  edgeKinds: readonly string[],\n): ReturnType<typeof sql> {\n  const workingValues = sql.join(\n    workingSet.map((node) => sql`(${node.id}, ${node.kind})`),\n    sql`, `,\n  );\n  const workingCte = sql`WITH working_set(node_id, node_kind) AS (VALUES ${workingValues})`;\n\n  const expansion = compileDirectionUnion(direction, (fields) =>\n    compileDirectionalExpansion(\n      operation,\n      sql`working_set`,\n      sql`TRUE`,\n      edgeKinds,\n      fields.joinField,\n      fields.joinKindField,\n      fields.targetField,\n      fields.targetKindField,\n    ),\n  );\n  return sql`${workingCte} ${expansion}`;\n}\n\nexport function compileWorkingTableExpansion(\n  operation: IterativeGraphOperation,\n  workingTable: WorkingTableIdentifier,\n  sourceFilter: SqlFragment,\n  direction: TraversalDirection,\n  edgeKinds: readonly string[],\n): SqlFragment {\n  return compileDirectionUnion(direction, (fields) =>\n    compileDirectionalExpansion(\n      operation,\n      workingTable,\n      sourceFilter,\n      edgeKinds,\n      fields.joinField,\n      fields.joinKindField,\n      fields.targetField,\n      fields.targetKindField,\n    ),\n  );\n}\n\n/**\n * Expands a working-table frontier through visible edges without joining target\n * nodes. Callers that reduce duplicate targets first can defer the target-node\n * visibility join until after that reduction, avoiding repeated point lookups\n * for the same target on dense frontiers. `sourceProjection` lets callers\n * carry trusted working-row state through the expansion without re-joining it.\n */\nexport function compileWorkingTableEdgeExpansion(\n  operation: IterativeGraphOperation,\n  workingTable: WorkingTableIdentifier,\n  sourceFilter: SqlFragment,\n  direction: TraversalDirection,\n  edgeKinds: readonly string[],\n  sourceProjection?: SqlFragment,\n): SqlFragment {\n  return compileDirectionUnion(direction, (fields) =>\n    compileDirectionalEdgeExpansion(\n      operation,\n      workingTable,\n      sourceFilter,\n      edgeKinds,\n      fields.joinField,\n      fields.joinKindField,\n      fields.targetField,\n      fields.targetKindField,\n      sourceProjection,\n    ),\n  );\n}\n\nfunction compileDirectionalExpansion(\n  operation: IterativeGraphOperation,\n  workingRelation: SqlFragment | WorkingTableIdentifier,\n  sourceFilter: SqlFragment,\n  edgeKinds: readonly string[],\n  joinField: \"from_id\" | \"to_id\",\n  joinKindField: \"from_kind\" | \"to_kind\",\n  targetField: \"from_id\" | \"to_id\",\n  targetKindField: \"from_kind\" | \"to_kind\",\n): ReturnType<typeof sql> {\n  const edgeExpansion = compileDirectionalEdgeExpansion(\n    operation,\n    workingRelation,\n    sourceFilter,\n    edgeKinds,\n    joinField,\n    joinKindField,\n    targetField,\n    targetKindField,\n  );\n  const weightColumn =\n    operation.weightExpression === undefined ? sql`` : sql`, expanded.weight`;\n  return sql`SELECT expanded.source_id, expanded.source_kind, n.id AS target_id, n.kind AS target_kind${weightColumn} FROM (${edgeExpansion}) expanded JOIN ${operation.schema.nodesTable} n ON n.graph_id = ${operation.ctx.graphId} AND n.id = expanded.target_id AND n.kind = expanded.target_kind WHERE ${operation.nodeTemporalFilter}`;\n}\n\nfunction compileDirectionalEdgeExpansion(\n  operation: IterativeGraphOperation,\n  workingRelation: SqlFragment | WorkingTableIdentifier,\n  sourceFilter: SqlFragment,\n  edgeKinds: readonly string[],\n  joinField: \"from_id\" | \"to_id\",\n  joinKindField: \"from_kind\" | \"to_kind\",\n  targetField: \"from_id\" | \"to_id\",\n  targetKindField: \"from_kind\" | \"to_kind\",\n  sourceProjection?: SqlFragment,\n): ReturnType<typeof sql> {\n  const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), edgeKinds);\n  const weightColumn =\n    operation.weightExpression === undefined ?\n      sql``\n    : sql`, ${operation.weightExpression} AS weight`;\n  const sourceColumns =\n    sourceProjection === undefined ? sql`` : sql`, ${sourceProjection}`;\n  return sql`SELECT w.node_id AS source_id, w.node_kind AS source_kind${sourceColumns}, e.${sql.raw(targetField)} AS target_id, e.${sql.raw(targetKindField)} AS target_kind${weightColumn} FROM ${workingRelation} w JOIN ${operation.schema.edgesTable} e ON e.${sql.raw(joinField)} = w.node_id AND e.${sql.raw(joinKindField)} = w.node_kind AND e.graph_id = ${operation.ctx.graphId} WHERE ${sourceFilter} AND ${edgeKindFilter} AND ${operation.edgeTemporalFilter}`;\n}\n\nfunction chunkValues<T>(\n  values: readonly T[],\n  chunkSize: number,\n): readonly (readonly T[])[] {\n  const chunks: T[][] = [];\n  for (let offset = 0; offset < values.length; offset += chunkSize) {\n    chunks.push(values.slice(offset, offset + chunkSize));\n  }\n  return chunks;\n}\n\nfunction createOperation(\n  ctx: AlgorithmContext,\n  options: InternalTraversalOptions,\n  backend: QueryBackend | TransactionBackend,\n): IterativeGraphOperation {\n  const temporal = resolveTemporalOptions(ctx, options);\n  const currentTimestamp = currentReadInstant();\n  const nodeTemporalFilter = compileTemporalFilter({\n    mode: temporal.temporalMode,\n    ...(temporal.asOf === undefined ? {} : { asOf: temporal.asOf }),\n    ...(temporal.recordedAsOf === undefined ?\n      {}\n    : { recordedAsOf: temporal.recordedAsOf }),\n    tableAlias: \"n\",\n    currentTimestamp,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const edgeTemporalFilter = compileTemporalFilter({\n    mode: temporal.temporalMode,\n    ...(temporal.asOf === undefined ? {} : { asOf: temporal.asOf }),\n    ...(temporal.recordedAsOf === undefined ?\n      {}\n    : { recordedAsOf: temporal.recordedAsOf }),\n    tableAlias: \"e\",\n    currentTimestamp,\n    recordedReadBinding: ctx.recordedReadBinding,\n  });\n  const weightExpression =\n    options.weightProperty === undefined ?\n      undefined\n    : compileWeightExpression(\n        ctx.dialect,\n        options.weightProperty,\n        options.defaultWeight,\n      );\n  const direction = options.direction ?? \"out\";\n  const branchCount = direction === \"both\" ? 2 : 1;\n  const parameterLimit =\n    backend.capabilities.maxBindParameters ?? DEFAULT_MAX_BIND_PARAMETERS;\n  const reservedPerBranch =\n    RESERVED_TEMPORAL_BIND_PARAMETERS_PER_BRANCH +\n    (weightExpression === undefined ? 0 : (\n      RESERVED_WEIGHT_BIND_PARAMETERS_PER_BRANCH\n    ));\n  const fixedParameters = branchCount * reservedPerBranch;\n  const sharedBudget = parameterLimit - fixedParameters;\n  const maxEdgeKindsPerQuery = Math.floor(sharedBudget / (branchCount + 2));\n  if (maxEdgeKindsPerQuery < 1) {\n    throw new ConfigurationError(\n      \"An iterative graph operation cannot fit its fixed filters within the backend bind-parameter limit.\",\n      { parameterLimit, direction },\n    );\n  }\n  const edgeKindChunks = chunkValues(\n    [...new Set(options.edges)].toSorted((left, right) =>\n      compareStrings(left, right),\n    ),\n    maxEdgeKindsPerQuery,\n  );\n  const largestEdgeKindChunk = Math.max(\n    ...edgeKindChunks.map((chunk) => chunk.length),\n  );\n  const maxWorkingSetSize = Math.floor(\n    (parameterLimit -\n      branchCount * (largestEdgeKindChunk + reservedPerBranch)) /\n      2,\n  );\n  if (maxWorkingSetSize < 1) {\n    throw new ConfigurationError(\n      \"An iterative graph operation cannot fit one working-set node within the backend bind-parameter limit.\",\n      { parameterLimit, direction },\n    );\n  }\n\n  return {\n    backend,\n    ctx,\n    edgeKindChunks,\n    direction,\n    maxWorkingSetSize,\n    nodeTemporalFilter,\n    edgeTemporalFilter,\n    schema: resolveReadSchema(ctx, options),\n    workingMemory: resolveWorkingMemory(options.workingMemory),\n    weightExpression,\n  };\n}\n\n/**\n * Compiles the per-edge weight expression over the expansion's edge alias\n * `e`. The extraction is cast to DOUBLE PRECISION — a spelling both engines\n * accept — so weight arithmetic is IEEE 754 double on both backends.\n * PostgreSQL's `::numeric` extraction would use exact decimal arithmetic and\n * could produce different accumulated distances (and therefore different\n * paths) than SQLite's binary doubles.\n *\n * The weight audit runs before any expansion, so by the time this expression\n * evaluates, every selected edge's property is a JSON number (never text the\n * cast could mangle or reject) or absent with a configured default.\n */\nfunction compileWeightExpression(\n  dialect: DialectAdapter,\n  weightProperty: string,\n  defaultWeight: number | undefined,\n): SqlFragment {\n  const extracted = dialect.jsonExtractDouble(\n    sql.raw(\"e.props\"),\n    jsonPointer([weightProperty]),\n  );\n  return defaultWeight === undefined ? extracted : (\n      sql`COALESCE(${extracted}, ${defaultWeight})`\n    );\n}\n\n/**\n * Whether the backend can host working-table rounds: a pinned transactional\n * connection, temporary-statement support, and `INSERT … RETURNING` for the\n * folded frontier bookkeeping. Callers without it take the inline\n * chunked-`VALUES` fallback.\n */\nexport function supportsTemporaryIteration(ctx: AlgorithmContext): boolean {\n  return (\n    ctx.backend.capabilities.execution.interactiveTransactions &&\n    ctx.backend.capabilities.graphAnalytics?.supported !== false &&\n    ctx.backend.capabilities.returning !== false &&\n    ctx.backend.executeTemporaryStatement !== undefined\n  );\n}\n\nfunction requireTemporaryStatements(\n  backend: TransactionBackend,\n): TemporaryStatementBackend {\n  if (backend.executeTemporaryStatement === undefined) {\n    throw new ConfigurationError(\n      \"Iterative graph operations require temporary-statement support on the transaction backend.\",\n      { dialect: backend.dialect },\n      {\n        suggestion:\n          \"Use a built-in SQLite/PostgreSQL backend or implement executeTemporaryStatement on the custom backend.\",\n      },\n    );\n  }\n  return backend as TemporaryStatementBackend;\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { GraphAlgorithmConvergenceError } from \"../../errors\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n  type AlgorithmContext,\n  assertEdgeKinds,\n  assertGraphAnalyticsSupported,\n  type InternalTraversalOptions,\n  pickTemporalOptions,\n  resolveMaxIterations,\n} from \"./context\";\nimport {\n  compileWorkingTableEdgeExpansion,\n  countWorkingTableRows,\n  frontierIndexIdentifier,\n  type IterativeGraphRunContext,\n  type NodeIdentityKey,\n  nodeIdentityKey,\n  runIterativeGraphOperation,\n  seedWorkingTableFromNodes,\n} from \"./iterative-graph-operation\";\nimport type {\n  InternalLabelPropagationOptions,\n  LabelPropagationMembership,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n  changedCount: number;\n  workingTableSize: number;\n  /** Fixed-round completion reached (`onMaxIterations: \"return\"` only). */\n  completed: boolean;\n  /** A detected oscillation needs one parity round before completing. */\n  finishNextRound: boolean;\n}>;\ntype ChangedRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  label_id: string;\n  label_kind: string;\n}>;\ntype MembershipRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  label_id: string;\n  label_kind: string;\n}>;\n\ntype CompletionMode = \"return\" | \"throw\";\n\ntype RoundPolicy = Readonly<{\n  detector: OscillationDetector;\n  maxIterations: number;\n  onMaxIterations: CompletionMode;\n}>;\n\ntype OscillationDetector = ReturnType<typeof createOscillationDetector>;\n\nconst DEFAULT_LABEL_PROPAGATION_MAX_ITERATIONS = 1000;\n\n/** Runs exact synchronous CDLP in the shared temporary-table loop. */\nexport async function executeLabelPropagation<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  options: InternalLabelPropagationOptions<G>,\n): Promise<readonly LabelPropagationMembership[]> {\n  assertEdgeKinds(options.edges);\n  assertGraphAnalyticsSupported(ctx, \"labelPropagation\", {\n    requiresWindowFunctions: true,\n  });\n  const maxIterations = resolveMaxIterations(\n    options.maxIterations,\n    DEFAULT_LABEL_PROPAGATION_MAX_ITERATIONS,\n    \"labelPropagation\",\n  );\n  const policy: RoundPolicy = {\n    detector: createOscillationDetector(),\n    maxIterations,\n    onMaxIterations: options.onMaxIterations ?? \"throw\",\n  };\n  const traversalOptions: InternalTraversalOptions = {\n    edges: options.edges,\n    direction: \"both\",\n    ...pickTemporalOptions(options),\n    ...(options.workingMemory === undefined ?\n      {}\n    : { workingMemory: options.workingMemory }),\n  };\n\n  return runIterativeGraphOperation(ctx, traversalOptions, {\n    algorithm: \"labelPropagation\",\n    maxIterations,\n    createWorkingTable,\n    initialize: (context) =>\n      initializeWorkingTables(context, options.nodeKinds),\n    runRound: (context, state, iteration) =>\n      runLabelPropagationRound(context, state, iteration, policy),\n    hasConverged(state) {\n      return state.changedCount === 0 || state.completed;\n    },\n    extractResult: extractMemberships,\n    cleanup: dropNeighborTable,\n  });\n}\n\n/**\n * Detects period-two oscillation from the per-round change feed. The round\n * map is a delta over a lazily built shadow labeling (every node starts as\n * its own label, and `applyNextLabels` reports every change), so a round\n * whose changes exactly invert the previous round's proves the labeling two\n * rounds back has recurred — and a deterministic synchronous rule then\n * alternates between the two labelings forever. Longer cycles are not\n * detected here and fall through to the `maxIterations` budget. Memory grows\n * with the number of distinct nodes that ever changed label.\n */\nfunction createOscillationDetector() {\n  const shadowLabels = new Map<NodeIdentityKey, NodeIdentityKey>();\n  let previousRound:\n    | ReadonlyMap<NodeIdentityKey, Readonly<{ before: NodeIdentityKey }>>\n    | undefined;\n  return {\n    /** Records one applied round; true when the round inverts the previous. */\n    observeRound(changedRows: readonly ChangedRow[]): boolean {\n      const round = new Map<\n        NodeIdentityKey,\n        Readonly<{ before: NodeIdentityKey; after: NodeIdentityKey }>\n      >();\n      for (const row of changedRows) {\n        const node = nodeIdentityKey({ id: row.node_id, kind: row.node_kind });\n        const after = nodeIdentityKey({\n          id: row.label_id,\n          kind: row.label_kind,\n        });\n        const before = shadowLabels.get(node) ?? node;\n        round.set(node, { before, after });\n        shadowLabels.set(node, after);\n      }\n      const priorRound = previousRound;\n      previousRound = round;\n      if (priorRound?.size !== round.size) return false;\n      if (round.size === 0) return false;\n      for (const [node, change] of round) {\n        if (priorRound.get(node)?.before !== change.after) return false;\n      }\n      return true;\n    },\n  };\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n  return sql`\n    CREATE TEMP TABLE ${context.workingTable} (\n      graph_id TEXT NOT NULL,\n      run_id TEXT NOT NULL,\n      node_id TEXT NOT NULL,\n      node_kind TEXT NOT NULL,\n      label_id TEXT NOT NULL,\n      label_kind TEXT NOT NULL,\n      next_label_id TEXT NOT NULL,\n      next_label_kind TEXT NOT NULL,\n      changed_round INTEGER NOT NULL,\n      active_round INTEGER NOT NULL,\n      PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n    )\n  `;\n}\n\n// Single-letter discriminators before the run id keep the auxiliary relation\n// names aligned and clearly grouped per run; every name stays well inside\n// PostgreSQL's 63-byte identifier cap.\nfunction neighborTableIdentifier(context: IterativeGraphRunContext) {\n  return sql.identifier(\n    `typegraph_iterative_n_${context.runId.replaceAll(\"-\", \"_\")}`,\n  );\n}\n\nfunction activeIndexIdentifier(context: IterativeGraphRunContext) {\n  return sql.identifier(\n    `typegraph_iterative_a_${context.runId.replaceAll(\"-\", \"_\")}`,\n  );\n}\n\nasync function initializeWorkingTables(\n  context: IterativeGraphRunContext,\n  nodeKinds: readonly string[] | undefined,\n): Promise<IterationState> {\n  await seedWorkingTableFromNodes(context, nodeKinds, [\n    { name: \"label_id\", value: sql.raw(\"n.id\") },\n    { name: \"label_kind\", value: sql.raw(\"n.kind\") },\n    { name: \"next_label_id\", value: sql.raw(\"n.id\") },\n    { name: \"next_label_kind\", value: sql.raw(\"n.kind\") },\n    { name: \"changed_round\", value: sql.raw(\"0\") },\n    { name: \"active_round\", value: sql.raw(\"1\") },\n  ]);\n  await context.executeTemporary(sql`\n    CREATE INDEX ${frontierIndexIdentifier(context)}\n    ON ${context.workingTable} (graph_id, run_id, changed_round)\n  `);\n  await context.executeTemporary(sql`\n    CREATE INDEX ${activeIndexIdentifier(context)}\n    ON ${context.workingTable} (graph_id, run_id, active_round)\n  `);\n  const neighborTable = neighborTableIdentifier(context);\n  await context.executeTemporary(sql`\n    CREATE TEMP TABLE ${neighborTable} (\n      target_id TEXT NOT NULL,\n      target_kind TEXT NOT NULL,\n      neighbor_id TEXT NOT NULL,\n      neighbor_kind TEXT NOT NULL,\n      PRIMARY KEY (target_kind, target_id, neighbor_kind, neighbor_id)\n    )\n  `);\n  for (const edgeKinds of context.operation.edgeKindChunks) {\n    await materializeChunkNeighbors(context, edgeKinds);\n  }\n  const analyzeNeighbors =\n    context.operation.ctx.dialect.analyzeTemporaryTable(neighborTable);\n  if (analyzeNeighbors !== undefined) {\n    await context.executeTemporary(analyzeNeighbors);\n  }\n\n  const workingTableSize = await countWorkingTableRows(context);\n  return {\n    changedCount: workingTableSize,\n    workingTableSize,\n    completed: false,\n    finishNextRound: false,\n  };\n}\n\nasync function runLabelPropagationRound(\n  context: IterativeGraphRunContext,\n  state: IterationState,\n  iteration: number,\n  policy: RoundPolicy,\n): Promise<IterationState> {\n  // Every node owns a distinct initial label, so every non-isolated node votes\n  // in round one. Later rounds activate only neighbors of the changed frontier.\n  if (iteration > 1) {\n    await markActiveNeighbors(context, iteration);\n  }\n  await selectWinningLabels(context, iteration);\n  const changedRows = await applyNextLabels(context, iteration);\n  const next: IterationState = {\n    changedCount: changedRows.length,\n    workingTableSize: state.workingTableSize,\n    completed: false,\n    finishNextRound: false,\n  };\n  if (next.changedCount === 0) return next;\n  if (state.finishNextRound) return { ...next, completed: true };\n  if (policy.detector.observeRound(changedRows)) {\n    return resolveOscillation(next, iteration, policy);\n  }\n  if (\n    policy.onMaxIterations === \"return\" &&\n    iteration === policy.maxIterations\n  ) {\n    return { ...next, completed: true };\n  }\n  return next;\n}\n\n/**\n * The labeling two rounds back has recurred, so the synchronous rule now\n * alternates between two labelings forever. The fixed-round result is fully\n * determined by parity: an even remainder is this round's labeling, an odd\n * remainder is the next round's.\n */\nfunction resolveOscillation(\n  state: IterationState,\n  iteration: number,\n  policy: RoundPolicy,\n): IterationState {\n  if (policy.onMaxIterations === \"throw\") {\n    throw new GraphAlgorithmConvergenceError(\n      \"labelPropagation\",\n      policy.maxIterations,\n      { oscillating: true },\n    );\n  }\n  const remaining = policy.maxIterations - iteration;\n  if (remaining % 2 === 0) return { ...state, completed: true };\n  return { ...state, finishNextRound: true };\n}\n\n/** Marks exactly the nodes whose vote multiset may have changed this round. */\nasync function markActiveNeighbors(\n  context: IterativeGraphRunContext,\n  iteration: number,\n): Promise<void> {\n  const { workingTable, graphId, runId } = context;\n  const neighborTable = neighborTableIdentifier(context);\n  // The neighbor relation is symmetric — materialization inserts both\n  // orientations of every visible edge — so probing the primary-key prefix by\n  // target and reading the neighbor columns enumerates the same adjacency as\n  // a dedicated reverse index would, without paying for one.\n  await context.executeTemporary(sql`\n    WITH candidates AS (\n      SELECT DISTINCT neighbors.neighbor_id, neighbors.neighbor_kind\n      FROM ${workingTable} changed\n      JOIN ${neighborTable} neighbors\n        ON neighbors.target_id = changed.node_id\n        AND neighbors.target_kind = changed.node_kind\n      WHERE changed.graph_id = ${graphId}\n        AND changed.run_id = ${runId}\n        AND changed.changed_round = ${iteration - 1}\n    )\n    UPDATE ${workingTable} AS target\n    SET active_round = ${iteration}\n    FROM candidates\n    WHERE target.graph_id = ${graphId}\n      AND target.run_id = ${runId}\n      AND target.node_id = candidates.neighbor_id\n      AND target.node_kind = candidates.neighbor_kind\n  `);\n}\n\n/**\n * Materializes one bind-budget edge-kind chunk into the immutable neighbor\n * relation. The primary key collapses parallel edges and duplicate neighbors\n * across chunks; self-loops are excluded because a node is not its own\n * neighbor for CDLP.\n */\nasync function materializeChunkNeighbors(\n  context: IterativeGraphRunContext,\n  edgeKinds: readonly string[],\n): Promise<void> {\n  const { operation, workingTable, graphId, runId } = context;\n  const expansion = compileWorkingTableEdgeExpansion(\n    operation,\n    workingTable,\n    sql`\n      w.graph_id = ${graphId}\n      AND w.run_id = ${runId}\n    `,\n    \"both\",\n    edgeKinds,\n  );\n  const neighborTable = neighborTableIdentifier(context);\n  await context.executeTemporary(sql`\n    INSERT INTO ${neighborTable}\n      (target_id, target_kind, neighbor_id, neighbor_kind)\n    SELECT DISTINCT\n      expanded.source_id,\n      expanded.source_kind,\n      expanded.target_id,\n      expanded.target_kind\n    FROM (${expansion}) expanded\n    JOIN ${workingTable} scoped_neighbor\n      ON scoped_neighbor.graph_id = ${graphId}\n      AND scoped_neighbor.run_id = ${runId}\n      AND scoped_neighbor.node_id = expanded.target_id\n      AND scoped_neighbor.node_kind = expanded.target_kind\n    WHERE expanded.source_id <> expanded.target_id\n      OR expanded.source_kind <> expanded.target_kind\n    ON CONFLICT (target_kind, target_id, neighbor_kind, neighbor_id)\n    DO NOTHING\n  `);\n}\n\nasync function selectWinningLabels(\n  context: IterativeGraphRunContext,\n  iteration: number,\n): Promise<void> {\n  const { operation, workingTable, graphId, runId } = context;\n  const neighborTable = neighborTableIdentifier(context);\n  const targetId = operation.ctx.dialect.binaryText(sql`totals.target_id`);\n  const targetKind = operation.ctx.dialect.binaryText(sql`totals.target_kind`);\n  const labelId = operation.ctx.dialect.binaryText(sql`totals.label_id`);\n  const labelKind = operation.ctx.dialect.binaryText(sql`totals.label_kind`);\n  await context.executeTemporary(sql`\n    WITH totals AS (\n      SELECT\n        neighbors.target_id,\n        neighbors.target_kind,\n        neighbor.label_id,\n        neighbor.label_kind,\n        COUNT(*) AS total_votes\n      FROM ${neighborTable} neighbors\n      JOIN ${workingTable} active\n        ON active.graph_id = ${graphId}\n        AND active.run_id = ${runId}\n        AND active.active_round = ${iteration}\n        AND active.node_id = neighbors.target_id\n        AND active.node_kind = neighbors.target_kind\n      JOIN ${workingTable} neighbor\n        ON neighbor.graph_id = ${graphId}\n        AND neighbor.run_id = ${runId}\n        AND neighbor.node_id = neighbors.neighbor_id\n        AND neighbor.node_kind = neighbors.neighbor_kind\n      GROUP BY\n        target_id,\n        target_kind,\n        neighbor.label_id,\n        neighbor.label_kind\n    ), ranked AS (\n      SELECT\n        target_id,\n        target_kind,\n        label_id,\n        label_kind,\n        ROW_NUMBER() OVER (\n          PARTITION BY ${targetKind}, ${targetId}\n          ORDER BY total_votes DESC, ${labelId}, ${labelKind}\n        ) AS label_rank\n      FROM totals\n    )\n    UPDATE ${workingTable} AS target\n    SET next_label_id = ranked.label_id,\n        next_label_kind = ranked.label_kind\n    FROM ranked\n    WHERE target.graph_id = ${graphId}\n      AND target.run_id = ${runId}\n      AND target.active_round = ${iteration}\n      AND target.node_id = ranked.target_id\n      AND target.node_kind = ranked.target_kind\n      AND ranked.label_rank = 1\n      AND (\n        target.next_label_id <> ranked.label_id\n        OR target.next_label_kind <> ranked.label_kind\n      )\n  `);\n}\n\nfunction applyNextLabels(\n  context: IterativeGraphRunContext,\n  iteration: number,\n): Promise<readonly ChangedRow[]> {\n  // Only rows selectWinningLabels staged this round can diverge, and it stages\n  // active rows exclusively, so the active index bounds this scan by the\n  // frontier instead of the whole working table.\n  return context.backend.execute<ChangedRow>(\n    asCompiledRowsSql(sql`\n      UPDATE ${context.workingTable}\n      SET label_id = next_label_id,\n          label_kind = next_label_kind,\n          changed_round = ${iteration}\n      WHERE graph_id = ${context.graphId}\n        AND run_id = ${context.runId}\n        AND active_round = ${iteration}\n        AND (\n          label_id <> next_label_id OR label_kind <> next_label_kind\n        )\n      RETURNING node_id, node_kind, label_id, label_kind\n    `),\n  );\n}\n\nasync function extractMemberships(\n  context: IterativeGraphRunContext,\n): Promise<readonly LabelPropagationMembership[]> {\n  const { operation } = context;\n  const labelId = operation.ctx.dialect.binaryText(sql`label_id`);\n  const labelKind = operation.ctx.dialect.binaryText(sql`label_kind`);\n  const nodeId = operation.ctx.dialect.binaryText(sql`node_id`);\n  const nodeKind = operation.ctx.dialect.binaryText(sql`node_kind`);\n  const rows = await context.backend.execute<MembershipRow>(\n    asCompiledRowsSql(sql`\n      SELECT\n        node_id,\n        node_kind,\n        label_id,\n        label_kind\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n      ORDER BY ${labelId}, ${labelKind}, ${nodeId}, ${nodeKind}\n    `),\n  );\n\n  return rows.map((row) => ({\n    id: row.node_id,\n    kind: row.node_kind,\n    labelId: row.label_id,\n    labelKind: row.label_kind,\n  }));\n}\n\nasync function dropNeighborTable(\n  context: IterativeGraphRunContext,\n): Promise<void> {\n  await context.executeTemporary(\n    sql`DROP TABLE IF EXISTS ${neighborTableIdentifier(context)}`,\n  );\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n  type AlgorithmContext,\n  assertEdgeKinds,\n  assertGraphAnalyticsSupported,\n  assertPositiveSafeIntegerOption,\n  type InternalTraversalOptions,\n  pickTemporalOptions,\n  resolveMaxIterations,\n} from \"./context\";\nimport {\n  compareNodeIdentity,\n  compileWorkingTableEdgeExpansion,\n  countWorkingTableRows,\n  DEFAULT_MAX_BIND_PARAMETERS,\n  type IterativeGraphRunContext,\n  type NodeIdentityKey,\n  nodeIdentityKey,\n  runIterativeGraphOperation,\n  seedWorkingTableFromNodes,\n} from \"./iterative-graph-operation\";\nimport type {\n  InternalPageRankOptions,\n  InternalPersonalizedPageRankOptions,\n  PageRankScore,\n  PersonalizedPageRankSeed,\n  TraversalDirection,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n  activeScoreColumn: ScoreColumn;\n  maximumChange: number;\n  workingTableSize: number;\n}>;\n\ntype ScoreColumn = \"next_score\" | \"score\";\n\ntype ResolvedPageRankOptions = Readonly<{\n  dampingFactor: number;\n  tolerance: number;\n  maxIterations: number;\n  nodeKinds: readonly string[] | undefined;\n  topK: number | undefined;\n}>;\n\ntype PageRankAlgorithm = \"pageRank\" | \"personalizedPageRank\";\n\ntype NormalizedSeed = Readonly<{\n  id: string;\n  kind: string;\n  weight: number;\n}>;\n\ntype MetricRow = Readonly<{ value: number | string | null }>;\ntype IdentityRow = Readonly<{ node_id: string; node_kind: string }>;\ntype ScoreRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  score: number | string;\n}>;\n\nconst DEFAULT_DAMPING_FACTOR = 0.85;\nconst DEFAULT_TOLERANCE = 1e-8;\nconst DEFAULT_MAX_ITERATIONS = 1000;\n/** Each seed VALUES row binds its id, kind, and weight. */\nconst BIND_PARAMETERS_PER_SEED = 3;\n/** The seed UPDATE statement also binds the graph and run identifiers. */\nconst RESERVED_SEED_STATEMENT_BIND_PARAMETERS = 2;\n\n/** Computes global PageRank with a uniform teleport distribution. */\nexport async function executePageRank<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  options: InternalPageRankOptions<G>,\n): Promise<readonly PageRankScore[]> {\n  return executePageRankOperation(ctx, options, undefined);\n}\n\n/** Computes personalized PageRank with a weighted multi-seed teleport vector. */\nexport async function executePersonalizedPageRank<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  options: InternalPersonalizedPageRankOptions<G>,\n): Promise<readonly PageRankScore[]> {\n  return executePageRankOperation(ctx, options, normalizeSeeds(options.seeds));\n}\n\nfunction executePageRankOperation<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  options: InternalPageRankOptions<G>,\n  seeds: readonly NormalizedSeed[] | undefined,\n): Promise<readonly PageRankScore[]> {\n  const algorithm: PageRankAlgorithm =\n    seeds === undefined ? \"pageRank\" : \"personalizedPageRank\";\n  assertEdgeKinds(options.edges);\n  assertGraphAnalyticsSupported(ctx, algorithm);\n  const resolved = resolvePageRankOptions(options, algorithm);\n  const traversalOptions: InternalTraversalOptions = {\n    edges: options.edges,\n    direction: options.direction ?? \"out\",\n    ...pickTemporalOptions(options),\n    ...(options.workingMemory === undefined ?\n      {}\n    : { workingMemory: options.workingMemory }),\n  };\n\n  return runIterativeGraphOperation(ctx, traversalOptions, {\n    algorithm,\n    maxIterations: resolved.maxIterations,\n    createWorkingTable,\n    initialize: (context) =>\n      initializeWorkingTable(context, resolved.nodeKinds, seeds),\n    runRound: (context, state) =>\n      runPowerIterationRound(context, state, resolved.dampingFactor),\n    hasConverged(state) {\n      return state.maximumChange <= resolved.tolerance;\n    },\n    extractResult: (context, state) =>\n      extractScores(context, state, resolved.topK),\n  });\n}\n\nfunction resolvePageRankOptions<G extends GraphDef>(\n  options: InternalPageRankOptions<G>,\n  algorithm: PageRankAlgorithm,\n): ResolvedPageRankOptions {\n  const dampingFactor = options.dampingFactor ?? DEFAULT_DAMPING_FACTOR;\n  if (\n    !Number.isFinite(dampingFactor) ||\n    dampingFactor < 0 ||\n    dampingFactor >= 1\n  ) {\n    throw new ConfigurationError(\n      `PageRank dampingFactor must be finite and in [0, 1), got ${String(dampingFactor)}.`,\n      { dampingFactor },\n    );\n  }\n\n  const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;\n  if (!Number.isFinite(tolerance) || tolerance <= 0) {\n    throw new ConfigurationError(\n      `PageRank tolerance must be finite and greater than 0, got ${String(tolerance)}.`,\n      { tolerance },\n    );\n  }\n\n  assertPositiveSafeIntegerOption(options.topK, algorithm, \"topK\");\n\n  return {\n    dampingFactor,\n    tolerance,\n    maxIterations: resolveMaxIterations(\n      options.maxIterations,\n      DEFAULT_MAX_ITERATIONS,\n      algorithm,\n    ),\n    nodeKinds: options.nodeKinds,\n    topK: options.topK,\n  };\n}\n\nfunction normalizeSeeds<G extends GraphDef>(\n  seeds: readonly PersonalizedPageRankSeed<G>[],\n): readonly NormalizedSeed[] {\n  if (seeds.length === 0) {\n    throw new ConfigurationError(\n      \"Personalized PageRank requires at least one seed.\",\n      { seeds },\n    );\n  }\n\n  const combined = new Map<NodeIdentityKey, NormalizedSeed>();\n  for (const seed of seeds) {\n    // Node-identity keys join kind and id with a NUL separator, so an\n    // embedded NUL could alias two distinct seeds onto one key.\n    if (\n      typeof seed.id !== \"string\" ||\n      seed.id.length === 0 ||\n      seed.id.includes(\"\\u0000\") ||\n      typeof seed.kind !== \"string\" ||\n      seed.kind.length === 0 ||\n      seed.kind.includes(\"\\u0000\")\n    ) {\n      throw new ConfigurationError(\n        \"Personalized PageRank seed id and kind must be non-empty strings without NUL characters.\",\n        { seed },\n      );\n    }\n    const weight = seed.weight ?? 1;\n    if (!Number.isFinite(weight) || weight <= 0) {\n      throw new ConfigurationError(\n        `Personalized PageRank seed weight must be finite and greater than 0, got ${String(weight)}.`,\n        { seed },\n      );\n    }\n    const key = nodeIdentityKey(seed);\n    const previous = combined.get(key);\n    const combinedWeight = (previous?.weight ?? 0) + weight;\n    if (!Number.isFinite(combinedWeight)) {\n      throw new ConfigurationError(\n        \"Personalized PageRank seed weights overflowed while combining duplicate seeds.\",\n        { seed },\n      );\n    }\n    combined.set(key, { id: seed.id, kind: seed.kind, weight: combinedWeight });\n  }\n\n  const combinedSeeds = [...combined.values()];\n  let maximumWeight = 0;\n  for (const seed of combinedSeeds) {\n    maximumWeight = Math.max(maximumWeight, seed.weight);\n  }\n  const scaledTotal = combinedSeeds.reduce(\n    (total, seed) => total + seed.weight / maximumWeight,\n    0,\n  );\n  return combinedSeeds\n    .map((seed) => {\n      const weight = seed.weight / maximumWeight / scaledTotal;\n      if (weight === 0) {\n        throw new ConfigurationError(\n          \"Personalized PageRank seed weights differ too much to normalize without underflow.\",\n          { seed },\n        );\n      }\n      return { id: seed.id, kind: seed.kind, weight };\n    })\n    .toSorted((left, right) => compareNodeIdentity(left, right));\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n  return sql`\n    CREATE TEMP TABLE ${context.workingTable} (\n      graph_id TEXT NOT NULL,\n      run_id TEXT NOT NULL,\n      node_id TEXT NOT NULL,\n      node_kind TEXT NOT NULL,\n      score DOUBLE PRECISION NOT NULL,\n      next_score DOUBLE PRECISION NOT NULL,\n      personalization DOUBLE PRECISION NOT NULL,\n      out_weight DOUBLE PRECISION NOT NULL,\n      PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n    )\n  `;\n}\n\nasync function initializeWorkingTable(\n  context: IterativeGraphRunContext,\n  nodeKinds: readonly string[] | undefined,\n  seeds: readonly NormalizedSeed[] | undefined,\n): Promise<IterationState> {\n  const { operation, workingTable, graphId, runId } = context;\n  await seedWorkingTableFromNodes(context, nodeKinds, [\n    { name: \"score\", value: sql.raw(\"0.0\") },\n    { name: \"next_score\", value: sql.raw(\"0.0\") },\n    { name: \"personalization\", value: sql.raw(\"0.0\") },\n    { name: \"out_weight\", value: sql.raw(\"0.0\") },\n  ]);\n\n  const workingTableSize = await countWorkingTableRows(context);\n  if (workingTableSize === 0) {\n    if (seeds !== undefined) {\n      throw missingSeedError(seeds);\n    }\n    return {\n      activeScoreColumn: \"score\",\n      maximumChange: 0,\n      workingTableSize,\n    };\n  }\n\n  if (seeds === undefined) {\n    const uniformWeight = 1 / workingTableSize;\n    await context.executeTemporary(sql`\n      UPDATE ${workingTable}\n      SET score = ${uniformWeight},\n          personalization = ${uniformWeight}\n      WHERE graph_id = ${graphId} AND run_id = ${runId}\n    `);\n  } else {\n    await initializePersonalization(context, seeds);\n  }\n\n  for (const edgeKinds of operation.edgeKindChunks) {\n    await accumulateOutWeights(context, edgeKinds);\n  }\n  return {\n    activeScoreColumn: \"score\",\n    maximumChange: Number.POSITIVE_INFINITY,\n    workingTableSize,\n  };\n}\n\nasync function initializePersonalization(\n  context: IterativeGraphRunContext,\n  seeds: readonly NormalizedSeed[],\n): Promise<void> {\n  const parameterLimit =\n    context.operation.backend.capabilities.maxBindParameters ??\n    DEFAULT_MAX_BIND_PARAMETERS;\n  const seedChunkSize = Math.floor(\n    (parameterLimit - RESERVED_SEED_STATEMENT_BIND_PARAMETERS) /\n      BIND_PARAMETERS_PER_SEED,\n  );\n  if (seedChunkSize < 1) {\n    throw new ConfigurationError(\n      \"Personalized PageRank cannot fit one seed within the backend bind-parameter limit.\",\n      { parameterLimit },\n    );\n  }\n\n  for (let offset = 0; offset < seeds.length; offset += seedChunkSize) {\n    const chunk = seeds.slice(offset, offset + seedChunkSize);\n    const values = sql.join(\n      chunk.map(\n        (seed) =>\n          sql`(${seed.id}, ${seed.kind}, CAST(${seed.weight} AS DOUBLE PRECISION))`,\n      ),\n      sql`, `,\n    );\n    await context.executeTemporary(sql`\n      WITH seed_values(node_id, node_kind, weight) AS (VALUES ${values})\n      UPDATE ${context.workingTable} AS target\n      SET score = seed_values.weight,\n          personalization = seed_values.weight\n      FROM seed_values\n      WHERE target.graph_id = ${context.graphId}\n        AND target.run_id = ${context.runId}\n        AND target.node_id = seed_values.node_id\n        AND target.node_kind = seed_values.node_kind\n    `);\n  }\n\n  const matchedRows = await context.backend.execute<IdentityRow>(\n    asCompiledRowsSql(sql`\n      SELECT node_id, node_kind\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId}\n        AND run_id = ${context.runId}\n        AND personalization > 0\n    `),\n  );\n  const matched = new Set(\n    matchedRows.map((row) =>\n      nodeIdentityKey({ id: row.node_id, kind: row.node_kind }),\n    ),\n  );\n  const missing = seeds.filter((seed) => !matched.has(nodeIdentityKey(seed)));\n  if (missing.length > 0) throw missingSeedError(missing);\n}\n\nfunction missingSeedError(\n  seeds: readonly NormalizedSeed[],\n): ConfigurationError {\n  return new ConfigurationError(\n    \"Personalized PageRank seeds must identify visible nodes inside the selected induced subgraph.\",\n    { missingSeeds: seeds.map((seed) => ({ id: seed.id, kind: seed.kind })) },\n  );\n}\n\nasync function accumulateOutWeights(\n  context: IterativeGraphRunContext,\n  edgeKinds: readonly string[],\n): Promise<void> {\n  const { operation, workingTable, graphId, runId } = context;\n  const expansion = compileWorkingTableEdgeExpansion(\n    operation,\n    workingTable,\n    sql`w.graph_id = ${graphId} AND w.run_id = ${runId}`,\n    operation.direction,\n    edgeKinds,\n  );\n  const transitionWeight = compileTransitionWeight(operation.direction);\n\n  await context.executeTemporary(sql`\n    WITH scoped_edges AS (\n      SELECT\n        expanded.source_id,\n        expanded.source_kind,\n        ${transitionWeight} AS transition_weight\n      FROM (${expansion}) expanded\n      JOIN ${workingTable} scoped_target\n        ON scoped_target.graph_id = ${graphId}\n        AND scoped_target.run_id = ${runId}\n        AND scoped_target.node_id = expanded.target_id\n        AND scoped_target.node_kind = expanded.target_kind\n    ), degrees AS (\n      SELECT source_id, source_kind, SUM(transition_weight) AS out_weight\n      FROM scoped_edges\n      GROUP BY source_id, source_kind\n    )\n    UPDATE ${workingTable} AS target\n    SET out_weight = target.out_weight + degrees.out_weight\n    FROM degrees\n    WHERE target.graph_id = ${graphId}\n      AND target.run_id = ${runId}\n      AND target.node_id = degrees.source_id\n      AND target.node_kind = degrees.source_kind\n  `);\n}\n\nfunction compileTransitionWeight(direction: TraversalDirection): SqlFragment {\n  if (direction !== \"both\") return sql`1.0`;\n  // `both` emits one row per edge endpoint. A self-loop appears in both\n  // branches, so each incidence contributes one half and the physical edge\n  // retains total transition weight one. Parallel self-loops remain distinct.\n  return sql`\n    CASE\n      WHEN expanded.source_id = expanded.target_id\n       AND expanded.source_kind = expanded.target_kind\n      THEN 0.5\n      ELSE 1.0\n    END\n  `;\n}\n\nasync function runPowerIterationRound(\n  context: IterativeGraphRunContext,\n  state: IterationState,\n  dampingFactor: number,\n): Promise<IterationState> {\n  const sourceScoreColumn = state.activeScoreColumn;\n  const targetScoreColumn: ScoreColumn =\n    sourceScoreColumn === \"score\" ? \"next_score\" : \"score\";\n  await resetTargetScores(\n    context,\n    sourceScoreColumn,\n    targetScoreColumn,\n    dampingFactor,\n  );\n\n  for (const edgeKinds of context.operation.edgeKindChunks) {\n    await accumulateContributions(\n      context,\n      edgeKinds,\n      dampingFactor,\n      sourceScoreColumn,\n      targetScoreColumn,\n    );\n  }\n\n  const maximumChange = await readMaximumChange(\n    context,\n    sourceScoreColumn,\n    targetScoreColumn,\n  );\n  return {\n    activeScoreColumn: targetScoreColumn,\n    maximumChange,\n    workingTableSize: state.workingTableSize,\n  };\n}\n\nasync function resetTargetScores(\n  context: IterativeGraphRunContext,\n  sourceScoreColumn: ScoreColumn,\n  targetScoreColumn: ScoreColumn,\n  dampingFactor: number,\n): Promise<void> {\n  const sourceScore = sql.identifier(sourceScoreColumn);\n  const targetScore = sql.identifier(targetScoreColumn);\n  await context.executeTemporary(sql`\n    UPDATE ${context.workingTable}\n    SET ${targetScore} = personalization * (\n      ${1 - dampingFactor} + ${dampingFactor} * (\n        SELECT COALESCE(SUM(dangling.${sourceScore}), 0.0)\n        FROM ${context.workingTable} dangling\n        WHERE dangling.graph_id = ${context.graphId}\n          AND dangling.run_id = ${context.runId}\n          AND dangling.out_weight = 0.0\n      )\n    )\n    WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n  `);\n}\n\nasync function accumulateContributions(\n  context: IterativeGraphRunContext,\n  edgeKinds: readonly string[],\n  dampingFactor: number,\n  sourceScoreColumn: ScoreColumn,\n  targetScoreColumn: ScoreColumn,\n): Promise<void> {\n  const { operation, workingTable, graphId, runId } = context;\n  const sourceScore = sql.identifier(sourceScoreColumn);\n  const targetScore = sql.identifier(targetScoreColumn);\n  const expansion = compileWorkingTableEdgeExpansion(\n    operation,\n    workingTable,\n    sql`w.graph_id = ${graphId} AND w.run_id = ${runId}`,\n    operation.direction,\n    edgeKinds,\n    sql`w.${sourceScore} AS source_score, w.out_weight AS source_out_weight`,\n  );\n  const transitionWeight = compileTransitionWeight(operation.direction);\n\n  await context.executeTemporary(sql`\n    WITH scoped_edges AS (\n      SELECT\n        expanded.target_id,\n        expanded.target_kind,\n        expanded.source_score,\n        expanded.source_out_weight,\n        ${transitionWeight} AS transition_weight\n      FROM (${expansion}) expanded\n      JOIN ${workingTable} scoped_target\n        ON scoped_target.graph_id = ${graphId}\n        AND scoped_target.run_id = ${runId}\n        AND scoped_target.node_id = expanded.target_id\n        AND scoped_target.node_kind = expanded.target_kind\n      WHERE expanded.source_out_weight > 0.0\n    ), contributions AS (\n      SELECT\n        target_id,\n        target_kind,\n        SUM(source_score * transition_weight / source_out_weight) AS score\n      FROM scoped_edges\n      GROUP BY target_id, target_kind\n    )\n    UPDATE ${workingTable} AS target\n    SET ${targetScore} = target.${targetScore} + ${dampingFactor} * contributions.score\n    FROM contributions\n    WHERE target.graph_id = ${graphId}\n      AND target.run_id = ${runId}\n      AND target.node_id = contributions.target_id\n      AND target.node_kind = contributions.target_kind\n  `);\n}\n\nasync function readMaximumChange(\n  context: IterativeGraphRunContext,\n  sourceScoreColumn: ScoreColumn,\n  targetScoreColumn: ScoreColumn,\n): Promise<number> {\n  const sourceScore = sql.identifier(sourceScoreColumn);\n  const targetScore = sql.identifier(targetScoreColumn);\n  const rows = await context.backend.execute<MetricRow>(\n    asCompiledRowsSql(sql`\n      SELECT COALESCE(MAX(ABS(${targetScore} - ${sourceScore})), 0.0) AS value\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n    `),\n  );\n  return Number(rows[0]?.value ?? 0);\n}\n\nasync function extractScores(\n  context: IterativeGraphRunContext,\n  state: IterationState,\n  topK: number | undefined,\n): Promise<readonly PageRankScore[]> {\n  const score = sql.identifier(state.activeScoreColumn);\n  const nodeId = context.operation.ctx.dialect.binaryText(sql`node_id`);\n  const nodeKind = context.operation.ctx.dialect.binaryText(sql`node_kind`);\n  const limitClause = topK === undefined ? sql.empty() : sql`LIMIT ${topK}`;\n  const rows = await context.backend.execute<ScoreRow>(\n    asCompiledRowsSql(sql`\n      SELECT node_id, node_kind, ${score} AS score\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n      ORDER BY ${score} DESC, ${nodeId}, ${nodeKind}\n      ${limitClause}\n    `),\n  );\n  return rows.map((row) => ({\n    id: row.node_id,\n    kind: row.node_kind,\n    score: Number(row.score),\n  }));\n}\n","import { sql } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { requireDefined } from \"../../utils/presence\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport {\n  compareNodeIdentity,\n  compileWorkingTableEdgeExpansion,\n  compileWorkingTableExpansion,\n  fetchVisibleWorkingNodes,\n  type IterativeGraphOperation,\n  type IterativeGraphRunContext,\n  type NodeExpansion,\n  type NodeIdentityKey,\n  nodeIdentityKey,\n  nodeIdentityKeyFromRow,\n  reduceExpandedWorkingSet,\n  runIterativeGraphOperation,\n  supportsTemporaryIteration,\n  withInlineIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n  PathNode,\n  ReachableNode,\n  ShortestPathResult,\n  TraversalDirection,\n} from \"./types\";\n\ntype FrontierCandidate = Readonly<{\n  id: string;\n  kind: string;\n  parentId: string;\n  parentKind: string;\n}>;\n\ntype VisitedNode = Readonly<{\n  id: string;\n  kind: string;\n  depth: number;\n  parentKey: NodeIdentityKey | undefined;\n}>;\n\ntype WorkingRow = Readonly<{\n  side: WorkingSide;\n  node_id: string;\n  node_kind: string;\n  depth: number | string;\n  predecessor_id: unknown;\n  predecessor_kind: unknown;\n}>;\n\ntype InsertedRow = Readonly<{ node_id: string }>;\ntype SeededRow = Readonly<{ node_id: string; node_kind: string }>;\ntype InsertedFrontierRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  meeting_depth: unknown;\n}>;\ntype WorkingSide = \"forward\" | \"reverse\";\n\ntype MeetingNode = Readonly<{\n  id: string;\n  kind: string;\n  depth: number;\n}>;\n\ntype FrontierRound = Readonly<{\n  insertedCount: number;\n  meeting: MeetingNode | undefined;\n}>;\n\nexport async function findReachableNodes(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n  if (supportsTemporaryIteration(ctx)) {\n    return findReachableNodesInWorkingTable(ctx, sourceId, maxHops, options);\n  }\n  return findReachableNodesInline(ctx, sourceId, maxHops, options);\n}\n\nexport async function findShortestPath(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n  if (supportsTemporaryIteration(ctx)) {\n    return findShortestPathInWorkingTable(\n      ctx,\n      sourceId,\n      targetId,\n      maxHops,\n      options,\n    );\n  }\n  return findShortestPathInline(ctx, sourceId, targetId, maxHops, options);\n}\n\nasync function findReachableNodesInWorkingTable(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n  return runIterativeGraphOperation(ctx, options, {\n    algorithm: \"reachable\",\n    maxIterations: maxHops,\n    createWorkingTable,\n    async initialize(context) {\n      const seeded = await seedWorkingSide(context, sourceId, \"forward\");\n      return {\n        depth: 0,\n        frontierCount: seeded.length,\n        workingTableSize: seeded.length,\n      };\n    },\n    async runRound(context, state) {\n      const nextDepth = state.depth + 1;\n      const frontierCount = await expandReachableWorkingTableRound(\n        context,\n        \"forward\",\n        state.depth,\n        nextDepth,\n        context.operation.direction,\n      );\n      return {\n        depth: nextDepth,\n        frontierCount,\n        workingTableSize: state.workingTableSize + frontierCount,\n      };\n    },\n    hasConverged(state) {\n      return state.frontierCount === 0 || state.depth >= maxHops;\n    },\n    async extractResult(context) {\n      const rows = await readWorkingRows(context, \"forward\");\n      return rows\n        .map((row) => ({\n          id: row.node_id,\n          kind: row.node_kind,\n          depth: Number(row.depth),\n        }))\n        .toSorted(\n          (left, right) =>\n            left.depth - right.depth || compareNodeIdentity(left, right),\n        );\n    },\n  });\n}\n\nasync function findShortestPathInWorkingTable(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n  return runIterativeGraphOperation(ctx, options, {\n    algorithm: \"shortestPath\",\n    maxIterations: maxHops,\n    createWorkingTable,\n    async initialize(context) {\n      const forwardSeeds = await seedWorkingSide(context, sourceId, \"forward\");\n      const reverseSeeds = await seedWorkingSide(context, targetId, \"reverse\");\n      return {\n        forwardDepth: 0,\n        reverseDepth: 0,\n        forwardFrontierCount: forwardSeeds.length,\n        reverseFrontierCount: reverseSeeds.length,\n        meeting: findSeedMeeting(forwardSeeds, reverseSeeds),\n        workingTableSize: forwardSeeds.length + reverseSeeds.length,\n      };\n    },\n    async runRound(context, state) {\n      const expandForward =\n        state.forwardFrontierCount <= state.reverseFrontierCount;\n      const side = expandForward ? \"forward\" : \"reverse\";\n      const currentDepth =\n        expandForward ? state.forwardDepth : state.reverseDepth;\n      const nextDepth = currentDepth + 1;\n      const direction =\n        expandForward ?\n          context.operation.direction\n        : reverseDirection(context.operation.direction);\n      const round = await expandWorkingTableRound(\n        context,\n        side,\n        currentDepth,\n        nextDepth,\n        direction,\n        maxHops,\n      );\n\n      return {\n        forwardDepth: expandForward ? nextDepth : state.forwardDepth,\n        reverseDepth: expandForward ? state.reverseDepth : nextDepth,\n        forwardFrontierCount:\n          expandForward ? round.insertedCount : state.forwardFrontierCount,\n        reverseFrontierCount:\n          expandForward ? state.reverseFrontierCount : round.insertedCount,\n        meeting: round.meeting,\n        workingTableSize: state.workingTableSize + round.insertedCount,\n      };\n    },\n    hasConverged(state) {\n      return (\n        state.meeting !== undefined ||\n        state.forwardFrontierCount === 0 ||\n        state.reverseFrontierCount === 0 ||\n        state.forwardDepth + state.reverseDepth >= maxHops\n      );\n    },\n    async extractResult(context, state) {\n      if (state.meeting === undefined) return;\n      const rows = await readWorkingRows(context);\n      return buildShortestPath(\n        nodeIdentityKey(state.meeting),\n        createVisitedMapFromRows(rows, \"forward\"),\n        createVisitedMapFromRows(rows, \"reverse\"),\n      );\n    },\n  });\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext) {\n  return sql`\n    CREATE TEMP TABLE ${context.workingTable} (\n        graph_id TEXT NOT NULL,\n        run_id TEXT NOT NULL,\n        side TEXT NOT NULL,\n        node_id TEXT NOT NULL,\n        node_kind TEXT NOT NULL,\n        depth INTEGER NOT NULL,\n        predecessor_id TEXT,\n        predecessor_kind TEXT,\n        meeting_depth INTEGER,\n        PRIMARY KEY (graph_id, run_id, side, node_kind, node_id)\n      )\n  `;\n}\n\n/**\n * Seeds one traversal side and returns the seeded node identities from the\n * same statement, so the caller reads the frontier size (and, for\n * bidirectional search, the source-equals-target meeting) without a\n * follow-up COUNT round-trip.\n */\nasync function seedWorkingSide(\n  context: IterativeGraphRunContext,\n  nodeId: string,\n  side: WorkingSide,\n): Promise<readonly SeededRow[]> {\n  const { operation, workingTable, graphId, runId } = context;\n  return context.backend.execute<SeededRow>(\n    asCompiledRowsSql(sql`\n      INSERT INTO ${workingTable}\n        (graph_id, run_id, side, node_id, node_kind, depth,\n         predecessor_id, predecessor_kind)\n      SELECT ${graphId}, ${runId}, ${side}, n.id, n.kind, 0, NULL, NULL\n      FROM ${operation.schema.nodesTable} n\n      WHERE n.graph_id = ${graphId}\n        AND n.id = ${nodeId}\n        AND ${operation.nodeTemporalFilter}\n      ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n      RETURNING node_id, node_kind\n    `),\n  );\n}\n\n/**\n * Detects the depth-zero meeting for bidirectional search: a node seeded on\n * both sides (source equals target, possibly across kinds sharing that id).\n * Ties break by node id then kind in code-point order — deterministic\n * and identical on both backends, unlike the collation-dependent SQL probe\n * this replaced.\n */\nfunction findSeedMeeting(\n  forwardSeeds: readonly SeededRow[],\n  reverseSeeds: readonly SeededRow[],\n): MeetingNode | undefined {\n  const reverseKeys = new Set(\n    reverseSeeds.map((row) =>\n      nodeIdentityKey({ id: row.node_id, kind: row.node_kind }),\n    ),\n  );\n  let meeting: MeetingNode | undefined;\n  for (const row of forwardSeeds) {\n    const candidate = { id: row.node_id, kind: row.node_kind, depth: 0 };\n    if (!reverseKeys.has(nodeIdentityKey(candidate))) continue;\n    if (meeting === undefined || compareNodeIdentity(candidate, meeting) < 0) {\n      meeting = candidate;\n    }\n  }\n  return meeting;\n}\n\n/**\n * Expands one bidirectional round and detects meetings in the same\n * statement. Each inserted frontier row captures the opposite side's depth\n * for the same node identity (`meeting_depth`); a non-null value marks a\n * meeting. Only newly inserted rows can create a new meeting — both sides'\n * existing rows are immutable and any meeting among them would have\n * converged an earlier round — so the returned rows are a complete meeting\n * probe and the separate per-round meeting query is unnecessary.\n */\nasync function expandWorkingTableRound(\n  context: IterativeGraphRunContext,\n  side: WorkingSide,\n  currentDepth: number,\n  nextDepth: number,\n  direction: TraversalDirection,\n  maxHops: number,\n): Promise<FrontierRound> {\n  const oppositeSide: WorkingSide = side === \"forward\" ? \"reverse\" : \"forward\";\n  let insertedCount = 0;\n  let meeting: MeetingNode | undefined;\n  const { dialect } = context.operation.ctx;\n  const targetKind = dialect.binaryText(sql`expanded.target_kind`);\n  const targetId = dialect.binaryText(sql`expanded.target_id`);\n  const sourceId = dialect.binaryText(sql`expanded.source_id`);\n  const sourceKind = dialect.binaryText(sql`expanded.source_kind`);\n  for (const edgeKinds of context.operation.edgeKindChunks) {\n    const sourceFilter = sql`\n      w.graph_id = ${context.graphId}\n      AND w.run_id = ${context.runId}\n      AND w.side = ${side}\n      AND w.depth = ${currentDepth}\n    `;\n    const expansion = compileWorkingTableExpansion(\n      context.operation,\n      context.workingTable,\n      sourceFilter,\n      direction,\n      edgeKinds,\n    );\n    const rows = await context.backend.execute<InsertedFrontierRow>(\n      asCompiledRowsSql(sql`\n        INSERT INTO ${context.workingTable}\n          (graph_id, run_id, side, node_id, node_kind, depth,\n           predecessor_id, predecessor_kind, meeting_depth)\n        SELECT\n          ${context.graphId}, ${context.runId}, ${side},\n          ranked.target_id, ranked.target_kind, ${nextDepth},\n          ranked.source_id, ranked.source_kind,\n          (\n            SELECT opposite.depth\n            FROM ${context.workingTable} opposite\n            WHERE opposite.graph_id = ${context.graphId}\n              AND opposite.run_id = ${context.runId}\n              AND opposite.side = ${oppositeSide}\n              AND opposite.node_id = ranked.target_id\n              AND opposite.node_kind = ranked.target_kind\n          )\n        FROM (\n          SELECT expanded.*,\n            ROW_NUMBER() OVER (\n              PARTITION BY ${targetKind}, ${targetId}\n              ORDER BY ${sourceId}, ${sourceKind}\n            ) AS candidate_rank\n          FROM (${expansion}) expanded\n        ) ranked\n        WHERE ranked.candidate_rank = 1\n          AND NOT EXISTS (\n            SELECT 1\n            FROM ${context.workingTable} visited\n            WHERE visited.graph_id = ${context.graphId}\n              AND visited.run_id = ${context.runId}\n              AND visited.side = ${side}\n              AND visited.node_id = ranked.target_id\n              AND visited.node_kind = ranked.target_kind\n          )\n        ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n        RETURNING node_id, node_kind, meeting_depth\n      `),\n    );\n    insertedCount += rows.length;\n    meeting = selectRoundMeeting(meeting, rows, nextDepth, maxHops);\n  }\n  return { insertedCount, meeting };\n}\n\n/**\n * Folds one round's inserted rows into the best meeting so far: smallest\n * total depth within `maxHops`, ties broken by node id then kind in code-point\n * order. That tie-break is deterministic and identical on both\n * backends; the SQL probe it replaced ordered under the database collation,\n * so equal-depth meetings could previously pick a different node on a\n * PostgreSQL cluster with a linguistic default collation.\n */\nfunction selectRoundMeeting(\n  currentMeeting: MeetingNode | undefined,\n  rows: readonly InsertedFrontierRow[],\n  nextDepth: number,\n  maxHops: number,\n): MeetingNode | undefined {\n  let meeting = currentMeeting;\n  for (const row of rows) {\n    // Drivers may deliver the INTEGER column as number, text, or bigint\n    // (e.g. better-sqlite3 with defaultSafeIntegers); only its absence means\n    // \"no meeting\". Number() coerces every numeric shape.\n    if (row.meeting_depth === null || row.meeting_depth === undefined) {\n      continue;\n    }\n    const totalDepth = nextDepth + Number(row.meeting_depth);\n    if (totalDepth > maxHops) continue;\n    const candidate = {\n      id: row.node_id,\n      kind: row.node_kind,\n      depth: totalDepth,\n    };\n    if (\n      meeting === undefined ||\n      candidate.depth < meeting.depth ||\n      (candidate.depth === meeting.depth &&\n        compareNodeIdentity(candidate, meeting) < 0)\n    ) {\n      meeting = candidate;\n    }\n  }\n  return meeting;\n}\n\n/**\n * Reachability needs only minimum depth, not a reconstructable predecessor.\n * Reduce duplicate edge targets before checking target-node visibility so a\n * dense frontier performs one node lookup per candidate identity rather than\n * one lookup per incident edge.\n */\nasync function expandReachableWorkingTableRound(\n  context: IterativeGraphRunContext,\n  side: WorkingSide,\n  currentDepth: number,\n  nextDepth: number,\n  direction: TraversalDirection,\n): Promise<number> {\n  let insertedCount = 0;\n  for (const edgeKinds of context.operation.edgeKindChunks) {\n    const sourceFilter = sql`\n      w.graph_id = ${context.graphId}\n      AND w.run_id = ${context.runId}\n      AND w.side = ${side}\n      AND w.depth = ${currentDepth}\n    `;\n    const edgeExpansion = compileWorkingTableEdgeExpansion(\n      context.operation,\n      context.workingTable,\n      sourceFilter,\n      direction,\n      edgeKinds,\n    );\n    const rows = await context.backend.execute<InsertedRow>(\n      asCompiledRowsSql(sql`\n        INSERT INTO ${context.workingTable}\n          (graph_id, run_id, side, node_id, node_kind, depth,\n           predecessor_id, predecessor_kind)\n        SELECT\n          ${context.graphId}, ${context.runId}, ${side},\n          candidates.target_id, candidates.target_kind, ${nextDepth},\n          NULL, NULL\n        FROM (\n          SELECT DISTINCT expanded.target_id, expanded.target_kind\n          FROM (${edgeExpansion}) expanded\n        ) candidates\n        JOIN ${context.operation.schema.nodesTable} n\n          ON n.graph_id = ${context.graphId}\n          AND n.id = candidates.target_id\n          AND n.kind = candidates.target_kind\n        WHERE ${context.operation.nodeTemporalFilter}\n          AND NOT EXISTS (\n            SELECT 1\n            FROM ${context.workingTable} visited\n            WHERE visited.graph_id = ${context.graphId}\n              AND visited.run_id = ${context.runId}\n              AND visited.side = ${side}\n              AND visited.node_id = candidates.target_id\n              AND visited.node_kind = candidates.target_kind\n          )\n        ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n        RETURNING node_id\n      `),\n    );\n    insertedCount += rows.length;\n  }\n  return insertedCount;\n}\n\nasync function readWorkingRows(\n  context: IterativeGraphRunContext,\n  side?: WorkingSide,\n): Promise<readonly WorkingRow[]> {\n  const sideFilter = side === undefined ? sql`TRUE` : sql`side = ${side}`;\n  return context.backend.execute<WorkingRow>(\n    asCompiledRowsSql(sql`\n      SELECT side, node_id, node_kind, depth,\n        predecessor_id, predecessor_kind\n      FROM ${context.workingTable}\n      WHERE graph_id = ${context.graphId}\n        AND run_id = ${context.runId}\n        AND ${sideFilter}\n    `),\n  );\n}\n\nasync function findReachableNodesInline(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n  return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n    const sources = await fetchVisibleWorkingNodes(operation, [sourceId]);\n    if (sources.length === 0) return [];\n\n    const reached = new Map<NodeIdentityKey, ReachableNode>(\n      sources.map((source) => [\n        nodeIdentityKey(source),\n        { id: source.id, kind: source.kind, depth: 0 },\n      ]),\n    );\n    let workingSet: readonly PathNode[] = sources;\n\n    for (let depth = 1; depth <= maxHops && workingSet.length > 0; depth++) {\n      const candidates = await expandInlineWorkingSet(\n        operation,\n        workingSet,\n        operation.direction,\n        reached,\n      );\n      const nextWorkingSet = sortCandidates(candidates);\n      for (const candidate of nextWorkingSet) {\n        reached.set(nodeIdentityKey(candidate), {\n          id: candidate.id,\n          kind: candidate.kind,\n          depth,\n        });\n      }\n      workingSet = nextWorkingSet;\n    }\n\n    return [...reached.values()].toSorted(\n      (left, right) =>\n        left.depth - right.depth || compareNodeIdentity(left, right),\n    );\n  });\n}\n\nasync function findShortestPathInline(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  maxHops: number,\n  options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n  return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n    const visibleNodes = await fetchVisibleWorkingNodes(operation, [\n      sourceId,\n      targetId,\n    ]);\n    const sources = visibleNodes.filter((node) => node.id === sourceId);\n    const targets = visibleNodes.filter((node) => node.id === targetId);\n    if (sources.length === 0 || targets.length === 0) return;\n    if (sourceId === targetId)\n      return { nodes: [requireDefined(sources[0])], depth: 0 };\n\n    const forwardVisited = createVisitedMap(sources);\n    const reverseVisited = createVisitedMap(targets);\n    let forwardWorkingSet: readonly PathNode[] = sources;\n    let reverseWorkingSet: readonly PathNode[] = targets;\n    let forwardDepth = 0;\n    let reverseDepth = 0;\n\n    while (\n      forwardWorkingSet.length > 0 &&\n      reverseWorkingSet.length > 0 &&\n      forwardDepth + reverseDepth < maxHops\n    ) {\n      const expandForward =\n        forwardWorkingSet.length <= reverseWorkingSet.length;\n      const activeVisited = expandForward ? forwardVisited : reverseVisited;\n      const oppositeVisited = expandForward ? reverseVisited : forwardVisited;\n      const currentWorkingSet =\n        expandForward ? forwardWorkingSet : reverseWorkingSet;\n      const direction =\n        expandForward ?\n          operation.direction\n        : reverseDirection(operation.direction);\n      const candidates = await expandInlineWorkingSet(\n        operation,\n        currentWorkingSet,\n        direction,\n        activeVisited,\n      );\n      const nextDepth = (expandForward ? forwardDepth : reverseDepth) + 1;\n      const nextWorkingSet = sortCandidates(candidates);\n\n      for (const candidate of nextWorkingSet) {\n        activeVisited.set(nodeIdentityKey(candidate), {\n          id: candidate.id,\n          kind: candidate.kind,\n          depth: nextDepth,\n          parentKey: nodeIdentityKey({\n            id: candidate.parentId,\n            kind: candidate.parentKind,\n          }),\n        });\n      }\n\n      const meetingKey = findMeetingNodeKey(\n        nextWorkingSet,\n        activeVisited,\n        oppositeVisited,\n      );\n      if (meetingKey !== undefined) {\n        return buildShortestPath(meetingKey, forwardVisited, reverseVisited);\n      }\n\n      if (expandForward) {\n        forwardWorkingSet = nextWorkingSet;\n        forwardDepth = nextDepth;\n      } else {\n        reverseWorkingSet = nextWorkingSet;\n        reverseDepth = nextDepth;\n      }\n    }\n    return;\n  });\n}\n\nasync function expandInlineWorkingSet(\n  operation: IterativeGraphOperation,\n  workingSet: readonly PathNode[],\n  direction: TraversalDirection,\n  visited: ReadonlyMap<NodeIdentityKey, unknown>,\n): Promise<ReadonlyMap<NodeIdentityKey, FrontierCandidate>> {\n  return reduceExpandedWorkingSet(\n    operation,\n    workingSet,\n    direction,\n    (existing, expansion) => selectPredecessor(existing, expansion, visited),\n  );\n}\n\nfunction selectPredecessor(\n  existing: FrontierCandidate | undefined,\n  expansion: NodeExpansion,\n  visited: ReadonlyMap<NodeIdentityKey, unknown>,\n): FrontierCandidate | undefined {\n  if (visited.has(nodeIdentityKey(expansion.target))) return existing;\n  if (\n    existing !== undefined &&\n    compareNodeIdentity(expansion.source, {\n      id: existing.parentId,\n      kind: existing.parentKind,\n    }) >= 0\n  ) {\n    return existing;\n  }\n  return {\n    id: expansion.target.id,\n    kind: expansion.target.kind,\n    parentId: expansion.source.id,\n    parentKind: expansion.source.kind,\n  };\n}\n\nfunction sortCandidates(\n  candidates: ReadonlyMap<NodeIdentityKey, FrontierCandidate>,\n): readonly FrontierCandidate[] {\n  return [...candidates.values()].toSorted((left, right) =>\n    compareNodeIdentity(left, right),\n  );\n}\n\nfunction findMeetingNodeKey(\n  candidates: readonly FrontierCandidate[],\n  activeVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n  oppositeVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n): NodeIdentityKey | undefined {\n  let best:\n    | Readonly<{\n        key: NodeIdentityKey;\n        node: PathNode;\n        depth: number;\n      }>\n    | undefined;\n  for (const candidate of candidates) {\n    const key = nodeIdentityKey(candidate);\n    const active = activeVisited.get(key);\n    const opposite = oppositeVisited.get(key);\n    if (active === undefined || opposite === undefined) continue;\n    const meeting = {\n      key,\n      node: { id: candidate.id, kind: candidate.kind },\n      depth: active.depth + opposite.depth,\n    };\n    if (\n      best === undefined ||\n      meeting.depth < best.depth ||\n      (meeting.depth === best.depth &&\n        compareNodeIdentity(meeting.node, best.node) < 0)\n    ) {\n      best = meeting;\n    }\n  }\n  return best?.key;\n}\n\nfunction buildShortestPath(\n  meetingKey: NodeIdentityKey,\n  forwardVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n  reverseVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n): ShortestPathResult {\n  const forwardKeys: NodeIdentityKey[] = [];\n  let cursor: NodeIdentityKey | undefined = meetingKey;\n  while (cursor !== undefined) {\n    forwardKeys.push(cursor);\n    cursor = forwardVisited.get(cursor)?.parentKey;\n  }\n  forwardKeys.reverse();\n\n  const pathKeys = [...forwardKeys];\n  cursor = reverseVisited.get(meetingKey)?.parentKey;\n  while (cursor !== undefined) {\n    pathKeys.push(cursor);\n    cursor = reverseVisited.get(cursor)?.parentKey;\n  }\n\n  const nodes = pathKeys.map((key) => {\n    const node = forwardVisited.get(key) ?? reverseVisited.get(key);\n    return { id: node?.id ?? \"\", kind: node?.kind ?? \"\" };\n  });\n  return { nodes, depth: nodes.length - 1 };\n}\n\nfunction createVisitedMap(\n  nodes: readonly PathNode[],\n): Map<NodeIdentityKey, VisitedNode> {\n  return new Map(\n    nodes.map((node) => [\n      nodeIdentityKey(node),\n      { id: node.id, kind: node.kind, depth: 0, parentKey: undefined },\n    ]),\n  );\n}\n\nfunction createVisitedMapFromRows(\n  rows: readonly WorkingRow[],\n  side: WorkingSide,\n): Map<NodeIdentityKey, VisitedNode> {\n  return new Map(\n    rows\n      .filter((row) => row.side === side)\n      .map((row) => {\n        const parentKey = nodeIdentityKeyFromRow(\n          row.predecessor_id,\n          row.predecessor_kind,\n        );\n        const node = {\n          id: row.node_id,\n          kind: row.node_kind,\n          depth: Number(row.depth),\n          parentKey,\n        } satisfies VisitedNode;\n        return [nodeIdentityKey(node), node];\n      }),\n  );\n}\n\nfunction reverseDirection(direction: TraversalDirection): TraversalDirection {\n  switch (direction) {\n    case \"out\": {\n      return \"in\";\n    }\n    case \"in\": {\n      return \"out\";\n    }\n    case \"both\": {\n      return \"both\";\n    }\n  }\n}\n","import { findReachableNodes, findShortestPath } from \"./breadth-first\";\nimport {\n  type AlgorithmContext,\n  assertEdgeKinds,\n  DEFAULT_ALGORITHM_MAX_HOPS,\n  DEFAULT_NEIGHBOR_DEPTH,\n  type InternalTraversalOptions,\n  pickTemporalOptions,\n  resolveMaxHops,\n} from \"./context\";\nimport type { ReachableNode } from \"./types\";\n\ntype InternalReachableOptions = InternalTraversalOptions &\n  Readonly<{ excludeSource?: boolean }>;\n\ntype InternalNeighborsOptions = Omit<InternalTraversalOptions, \"maxHops\"> &\n  Readonly<{ depth?: number }>;\n\nexport async function executeReachable(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  options: InternalReachableOptions,\n): Promise<readonly ReachableNode[]> {\n  assertEdgeKinds(options.edges);\n  const maxHops = resolveMaxHops(\n    options.maxHops,\n    DEFAULT_ALGORITHM_MAX_HOPS,\n    \"maxHops\",\n  );\n\n  const reached = await findReachableNodes(ctx, sourceId, maxHops, options);\n  return options.excludeSource === true ?\n      reached.filter((node) => node.id !== sourceId)\n    : reached;\n}\n\nexport async function executeCanReach(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  options: InternalTraversalOptions,\n): Promise<boolean> {\n  assertEdgeKinds(options.edges);\n\n  const maxHops = resolveMaxHops(\n    options.maxHops,\n    DEFAULT_ALGORITHM_MAX_HOPS,\n    \"maxHops\",\n  );\n\n  return (\n    (await findShortestPath(ctx, sourceId, targetId, maxHops, options)) !==\n    undefined\n  );\n}\n\nexport async function executeNeighbors(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  options: InternalNeighborsOptions,\n): Promise<readonly ReachableNode[]> {\n  const depth = resolveMaxHops(options.depth, DEFAULT_NEIGHBOR_DEPTH, \"depth\");\n\n  return executeReachable(ctx, sourceId, {\n    edges: options.edges,\n    maxHops: depth,\n    direction: options.direction ?? \"out\",\n    cyclePolicy: options.cyclePolicy ?? \"prevent\",\n    ...pickTemporalOptions(options),\n    ...(options.workingMemory !== undefined && {\n      workingMemory: options.workingMemory,\n    }),\n    excludeSource: true,\n  });\n}\n","import { findShortestPath } from \"./breadth-first\";\nimport {\n  type AlgorithmContext,\n  assertEdgeKinds,\n  DEFAULT_ALGORITHM_MAX_HOPS,\n  type InternalTraversalOptions,\n  resolveMaxHops,\n} from \"./context\";\nimport type { ShortestPathResult } from \"./types\";\n\nexport async function executeShortestPath(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n  assertEdgeKinds(options.edges);\n  const maxHops = resolveMaxHops(\n    options.maxHops,\n    DEFAULT_ALGORITHM_MAX_HOPS,\n    \"maxHops\",\n  );\n  return findShortestPath(ctx, sourceId, targetId, maxHops, options);\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n  type AlgorithmContext,\n  assertEdgeKinds,\n  assertGraphAnalyticsSupported,\n  assertPositiveSafeIntegerOption,\n  type InternalTraversalOptions,\n  pickTemporalOptions,\n  resolveMaxIterations,\n} from \"./context\";\nimport {\n  compileWorkingTableEdgeExpansion,\n  countWorkingTableRows,\n  frontierIndexIdentifier,\n  type IterativeGraphRunContext,\n  runIterativeGraphOperation,\n  seedWorkingTableFromNodes,\n} from \"./iterative-graph-operation\";\nimport type {\n  InternalWeaklyConnectedComponentsOptions,\n  WeaklyConnectedComponentMembership,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n  changedCount: number;\n  workingTableSize: number;\n}>;\ntype ChangedRow = Readonly<{ node_id: string }>;\ntype MembershipRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  component_id: string;\n  component_kind: string;\n  component_size: number | string;\n}>;\n\nconst DEFAULT_WCC_MAX_ITERATIONS = 1000;\n\n/** Runs exact label-min weakly connected components in the shared SQL loop. */\nexport async function executeWeaklyConnectedComponents<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  options: InternalWeaklyConnectedComponentsOptions<G>,\n): Promise<readonly WeaklyConnectedComponentMembership[]> {\n  assertEdgeKinds(options.edges);\n  assertGraphAnalyticsSupported(ctx, \"weaklyConnectedComponents\", {\n    requiresWindowFunctions: true,\n  });\n  const maxIterations = resolveMaxIterations(\n    options.maxIterations,\n    DEFAULT_WCC_MAX_ITERATIONS,\n    \"weaklyConnectedComponents\",\n  );\n  assertPositiveSafeIntegerOption(\n    options.minComponentSize,\n    \"weaklyConnectedComponents\",\n    \"minComponentSize\",\n  );\n  const traversalOptions: InternalTraversalOptions = {\n    edges: options.edges,\n    direction: \"both\",\n    ...pickTemporalOptions(options),\n    ...(options.workingMemory === undefined ?\n      {}\n    : { workingMemory: options.workingMemory }),\n  };\n\n  return runIterativeGraphOperation(ctx, traversalOptions, {\n    algorithm: \"weaklyConnectedComponents\",\n    maxIterations,\n    createWorkingTable,\n    initialize: (context) => initializeWorkingTable(context, options.nodeKinds),\n    runRound: runLabelPropagationRound,\n    hasConverged(state) {\n      return state.changedCount === 0;\n    },\n    extractResult: (context) =>\n      extractMemberships(context, options.minComponentSize),\n  });\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n  return sql`\n    CREATE TEMP TABLE ${context.workingTable} (\n      graph_id TEXT NOT NULL,\n      run_id TEXT NOT NULL,\n      node_id TEXT NOT NULL,\n      node_kind TEXT NOT NULL,\n      label_id TEXT NOT NULL,\n      label_kind TEXT NOT NULL,\n      next_label_id TEXT NOT NULL,\n      next_label_kind TEXT NOT NULL,\n      improved_round INTEGER NOT NULL,\n      PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n    )\n  `;\n}\n\nasync function initializeWorkingTable(\n  context: IterativeGraphRunContext,\n  nodeKinds: readonly string[] | undefined,\n): Promise<IterationState> {\n  await seedWorkingTableFromNodes(context, nodeKinds, [\n    { name: \"label_id\", value: sql.raw(\"n.id\") },\n    { name: \"label_kind\", value: sql.raw(\"n.kind\") },\n    { name: \"next_label_id\", value: sql.raw(\"n.id\") },\n    { name: \"next_label_kind\", value: sql.raw(\"n.kind\") },\n    { name: \"improved_round\", value: sql.raw(\"0\") },\n  ]);\n  await context.executeTemporary(sql`\n    CREATE INDEX ${frontierIndexIdentifier(context)}\n    ON ${context.workingTable} (graph_id, run_id, improved_round)\n  `);\n\n  const workingTableSize = await countWorkingTableRows(context);\n  return { changedCount: workingTableSize, workingTableSize };\n}\n\nasync function runLabelPropagationRound(\n  context: IterativeGraphRunContext,\n  state: IterationState,\n  iteration: number,\n): Promise<IterationState> {\n  for (const edgeKinds of context.operation.edgeKindChunks) {\n    await propagateChunkLabels(context, edgeKinds, iteration);\n  }\n  const changedRows = await applyNextLabels(context, iteration);\n  return {\n    changedCount: changedRows.length,\n    workingTableSize: state.workingTableSize,\n  };\n}\n\n/**\n * Propagates the minimum neighbor label along one edge-kind chunk. The\n * expansion deliberately skips the target-node visibility join. The working\n * table was seeded through the same graph/kind/temporal filters inside the\n * same snapshot, WCC never inserts rows after seeding, source labels are\n * projected from the frontier, and each target is joined against the working\n * table below. Membership is therefore the visibility-and-scope proof, so a\n * per-edge `typegraph_nodes` lookup would only re-check what the frontier and\n * `scoped_target` already guarantee.\n */\nasync function propagateChunkLabels(\n  context: IterativeGraphRunContext,\n  edgeKinds: readonly string[],\n  iteration: number,\n): Promise<void> {\n  const { operation, workingTable, graphId, runId } = context;\n  const expansion = compileWorkingTableEdgeExpansion(\n    operation,\n    workingTable,\n    sql`\n      w.graph_id = ${graphId}\n      AND w.run_id = ${runId}\n      AND w.improved_round = ${iteration - 1}\n    `,\n    \"both\",\n    edgeKinds,\n    sql`w.label_id AS source_label_id, w.label_kind AS source_label_kind`,\n  );\n  const candidateId = operation.ctx.dialect.binaryText(sql`ranked.label_id`);\n  const candidateKind = operation.ctx.dialect.binaryText(\n    sql`ranked.label_kind`,\n  );\n  const currentId = operation.ctx.dialect.binaryText(sql`target.next_label_id`);\n  const currentKind = operation.ctx.dialect.binaryText(\n    sql`target.next_label_kind`,\n  );\n  const sourceId = operation.ctx.dialect.binaryText(sql`source.label_id`);\n  const sourceKind = operation.ctx.dialect.binaryText(sql`source.label_kind`);\n  const targetId = operation.ctx.dialect.binaryText(sql`source.target_id`);\n  const targetKind = operation.ctx.dialect.binaryText(sql`source.target_kind`);\n\n  await context.executeTemporary(sql`\n    WITH candidates AS (\n      SELECT\n        expanded.target_id,\n        expanded.target_kind,\n        expanded.source_label_id AS label_id,\n        expanded.source_label_kind AS label_kind\n      FROM (${expansion}) expanded\n      JOIN ${workingTable} scoped_target\n        ON scoped_target.graph_id = ${graphId}\n        AND scoped_target.run_id = ${runId}\n        AND scoped_target.node_id = expanded.target_id\n        AND scoped_target.node_kind = expanded.target_kind\n    ), ranked AS (\n      SELECT\n        target_id,\n        target_kind,\n        label_id,\n        label_kind,\n        ROW_NUMBER() OVER (\n          PARTITION BY ${targetKind}, ${targetId}\n          ORDER BY ${sourceId}, ${sourceKind}\n        ) AS candidate_rank\n      FROM candidates source\n    )\n    UPDATE ${workingTable} AS target\n    SET next_label_id = ranked.label_id,\n        next_label_kind = ranked.label_kind\n    FROM ranked\n    WHERE target.graph_id = ${graphId}\n      AND target.run_id = ${runId}\n      AND target.node_id = ranked.target_id\n      AND target.node_kind = ranked.target_kind\n      AND ranked.candidate_rank = 1\n      AND (\n        ${candidateId} < ${currentId}\n        OR (\n          ${candidateId} = ${currentId}\n          AND ${candidateKind} < ${currentKind}\n        )\n      )\n  `);\n}\n\nfunction applyNextLabels(\n  context: IterativeGraphRunContext,\n  iteration: number,\n): Promise<readonly ChangedRow[]> {\n  return context.backend.execute<ChangedRow>(\n    asCompiledRowsSql(sql`\n      UPDATE ${context.workingTable}\n      SET label_id = next_label_id,\n          label_kind = next_label_kind,\n          improved_round = ${iteration}\n      WHERE graph_id = ${context.graphId}\n        AND run_id = ${context.runId}\n        AND (\n          label_id <> next_label_id OR label_kind <> next_label_kind\n        )\n      RETURNING node_id\n    `),\n  );\n}\n\nasync function extractMemberships(\n  context: IterativeGraphRunContext,\n  minComponentSize: number | undefined,\n): Promise<readonly WeaklyConnectedComponentMembership[]> {\n  const { operation } = context;\n  const labelId = operation.ctx.dialect.binaryText(sql`label_id`);\n  const labelKind = operation.ctx.dialect.binaryText(sql`label_kind`);\n  const componentId = operation.ctx.dialect.binaryText(sql`component_id`);\n  const componentKind = operation.ctx.dialect.binaryText(sql`component_kind`);\n  const nodeId = operation.ctx.dialect.binaryText(sql`node_id`);\n  const nodeKind = operation.ctx.dialect.binaryText(sql`node_kind`);\n  const componentSizeFilter =\n    minComponentSize === undefined ?\n      sql.empty()\n    : sql`WHERE component_size >= ${minComponentSize}`;\n  const rows = await context.backend.execute<MembershipRow>(\n    asCompiledRowsSql(sql`\n      WITH memberships AS (\n        SELECT\n          node_id,\n          node_kind,\n          label_id AS component_id,\n          label_kind AS component_kind,\n          COUNT(*) OVER (\n            PARTITION BY ${labelKind}, ${labelId}\n          ) AS component_size\n        FROM ${context.workingTable}\n        WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n      )\n      SELECT node_id, node_kind, component_id, component_kind, component_size\n      FROM memberships\n      ${componentSizeFilter}\n      ORDER BY ${componentId}, ${componentKind}, ${nodeId}, ${nodeKind}\n    `),\n  );\n\n  return rows.map((row) => ({\n    id: row.node_id,\n    kind: row.node_kind,\n    componentId: row.component_id,\n    componentKind: row.component_kind,\n    size: Number(row.component_size),\n  }));\n}\n","import { resolveRecursiveTraversal } from \"../../backend/capabilities/recursive-traversal\";\nimport type { GraphDef } from \"../../core/define-graph\";\nimport {\n  ConfigurationError,\n  GraphAlgorithmConvergenceError,\n  InvalidEdgeWeightError,\n  type InvalidEdgeWeightReason,\n} from \"../../errors\";\nimport { compileKindFilter } from \"../../query/compiler/predicate-utils\";\nimport { jsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport { assertEdgeKinds, resolveMaxIterations } from \"./context\";\nimport {\n  compareNodeIdentity,\n  compileWorkingTableExpansion,\n  fetchVisibleWorkingNodes,\n  frontierIndexIdentifier,\n  type IterativeGraphOperation,\n  type IterativeGraphRunContext,\n  type NodeExpansion,\n  nodeIdentityFromRow,\n  type NodeIdentityKey,\n  nodeIdentityKey,\n  reduceExpandedWorkingSet,\n  runIterativeGraphOperation,\n  supportsTemporaryIteration,\n  withInlineIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n  InternalWeightedShortestPathOptions,\n  PathNode,\n  WeightedShortestPathResult,\n} from \"./types\";\n\nconst DEFAULT_WEIGHTED_SHORTEST_PATH_MAX_ITERATIONS = 1000;\n\nconst WEIGHTED_ALGORITHM_NAME = \"weightedShortestPath\";\n\n/**\n * Largest accepted edge weight (~9.7e289). Auditing weights to this bound\n * makes accumulated overflow impossible rather than merely unlikely: a path\n * gains one working-table row per hop, so it has at most 2^53 hops, and\n * 2^53 · MAX_EDGE_WEIGHT stays far below Number.MAX_VALUE even after\n * float-addition rounding (the 2^64 divisor leaves an ~2000x margin).\n * Without the bound, PostgreSQL's float8 addition would raise a raw 22003\n * overflow mid-round while SQLite silently saturated to Infinity.\n */\nconst MAX_EDGE_WEIGHT = Number.MAX_VALUE / 2 ** 64;\n\n/**\n * Smallest accepted nonzero weight magnitude: the smallest IEEE 754 double\n * (5e-324). PostgreSQL stores smaller nonzero JSON numbers exactly in jsonb\n * and raises a raw underflow when the traversal casts them to float8, so\n * the audit rejects them with the typed error instead. SQLite's JSON parser\n * has already rounded such text to 0 before SQL can observe it — an\n * engine-level difference the audit cannot detect there.\n */\nconst MIN_EDGE_WEIGHT = Number.MIN_VALUE;\n\n/** Traversal options with the weight source guaranteed present. */\ntype WeightedTraversalOptions = InternalTraversalOptions &\n  Readonly<{ weightProperty: string }>;\n\ntype WeightedState = Readonly<{\n  frontierCount: number;\n  workingTableSize: number;\n  /**\n   * Cheapest known distance to any node with the target id, tracked in JS\n   * from each round's RETURNING rows so the next round can prune with a\n   * plain bound parameter instead of per-candidate subqueries.\n   */\n  bestTargetDistance: number | undefined;\n}>;\n\ntype SeededRow = Readonly<{ node_id: string }>;\ntype ImprovedRow = Readonly<{ node_id: string; distance: number | string }>;\n\ntype FrontierRound = Readonly<{\n  frontierCount: number;\n  bestTargetDistance: number | undefined;\n}>;\n\ntype ChainRow = Readonly<{\n  node_id: string;\n  node_kind: string;\n  distance: number | string;\n  hops: number | string;\n}>;\n\ntype WeightAuditRow = Readonly<{\n  edge_id: string;\n  edge_kind: string;\n  weight_text: unknown;\n  is_number: unknown;\n  is_missing: unknown;\n}>;\n\n/**\n * A node settled by weighted relaxation: its best known distance from the\n * source, the hop count of the path achieving it, and the predecessor along\n * that path.\n */\ntype WeightedVisitedNode = Readonly<{\n  id: string;\n  kind: string;\n  distance: number;\n  hops: number;\n  parentKey: NodeIdentityKey | undefined;\n}>;\n\ntype WeightedCandidate = Readonly<{\n  id: string;\n  kind: string;\n  distance: number;\n  hops: number;\n  parentId: string;\n  parentKind: string;\n}>;\n\n/**\n * Finds the minimum-total-weight path from `sourceId` to `targetId` by\n * frontier-based label-correcting relaxation: each round relaxes the edges\n * out of the nodes improved in the previous round, keeping one best\n * `(distance, predecessor)` per node identity, until no distance improves.\n * Weights must be non-negative, which makes pruning against the best known\n * target distance safe: a candidate costing strictly more than a path\n * already reaching the target can never win, while equal-cost candidates\n * stay admitted so the result tie-break sees every equal-cost target.\n */\nexport async function executeWeightedShortestPath<G extends GraphDef>(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  options: InternalWeightedShortestPathOptions<G>,\n): Promise<WeightedShortestPathResult | undefined> {\n  assertEdgeKinds(options.edges);\n  assertWeightOptions(options.weightProperty, options.defaultWeight);\n  const maxIterations = resolveMaxIterations(\n    options.maxIterations,\n    DEFAULT_WEIGHTED_SHORTEST_PATH_MAX_ITERATIONS,\n    WEIGHTED_ALGORITHM_NAME,\n  );\n  // Structurally assignable — the internal options are the traversal options\n  // plus the algorithm-only `maxIterations`, which the substrate ignores.\n  const traversalOptions: WeightedTraversalOptions = options;\n\n  // Non-negative weights make distance 0 unbeatable, so a self path needs\n  // no relaxation rounds — only the weight audit (for deterministic data\n  // errors) and a visibility check on the node itself.\n  if (sourceId === targetId) {\n    return findWeightedSelfPath(ctx, sourceId, traversalOptions);\n  }\n\n  if (supportsTemporaryIteration(ctx)) {\n    return findWeightedShortestPathInWorkingTable(\n      ctx,\n      sourceId,\n      targetId,\n      maxIterations,\n      traversalOptions,\n    );\n  }\n  return findWeightedShortestPathInline(\n    ctx,\n    sourceId,\n    targetId,\n    maxIterations,\n    traversalOptions,\n  );\n}\n\nfunction assertWeightOptions(\n  weightProperty: string,\n  defaultWeight: number | undefined,\n): void {\n  if (typeof weightProperty !== \"string\" || weightProperty.length === 0) {\n    throw new ConfigurationError(\n      `${WEIGHTED_ALGORITHM_NAME} weightProperty must be a non-empty string.`,\n      { weightProperty },\n    );\n  }\n  // The same upper bound the audit applies to stored weights: a default\n  // above it would reopen the accumulated-overflow gap for missing-weight\n  // edges the audit deliberately lets through.\n  if (\n    defaultWeight !== undefined &&\n    (!Number.isFinite(defaultWeight) ||\n      defaultWeight < 0 ||\n      defaultWeight > MAX_EDGE_WEIGHT)\n  ) {\n    throw new ConfigurationError(\n      `${WEIGHTED_ALGORITHM_NAME} defaultWeight must be a non-negative number no greater than ${MAX_EDGE_WEIGHT}, got ${String(defaultWeight)}.`,\n      { defaultWeight, maximum: MAX_EDGE_WEIGHT },\n    );\n  }\n}\n\n/**\n * Fails fast on the first visible edge of the selected kinds whose weight\n * violates the weighted-traversal contract: a non-numeric value, a negative\n * number, or a missing value with no configured default. Runs inside the\n * operation's snapshot before any relaxation round, so a weighted call\n * either observes a fully valid weight domain or throws — the traversal's\n * own weight cast never sees a value it could silently mangle.\n *\n * The audit deliberately covers every visible edge of the selected kinds,\n * not just edges the traversal happens to reach: reachability-dependent\n * validation would make the error nondeterministic in the data.\n */\nasync function assertValidEdgeWeights(\n  operation: IterativeGraphOperation,\n  weightProperty: string,\n  defaultWeight: number | undefined,\n): Promise<void> {\n  const { dialect } = operation.ctx;\n  const pointer = jsonPointer([weightProperty]);\n  const propsColumn = sql.raw(\"e.props\");\n  // The inner projection extracts the JSON path once per edge; the outer\n  // violation predicate then works over plain projected columns. Composing\n  // the checks directly over `e.props` would re-parse the JSON payload for\n  // every predicate branch on the audit's full edge scan.\n  //\n  // Both type predicates are never-NULL by contract, so the multi-branch\n  // violation predicate below stays two-valued.\n  const isNumber = dialect.jsonPathIsNumber(propsColumn, pointer);\n  const isMissing = dialect.jsonPathIsNull(propsColumn, pointer);\n  const weightText = dialect.jsonExtractText(propsColumn, pointer);\n  // CASE keeps the numeric extraction unreachable for non-numeric values:\n  // PostgreSQL does not short-circuit OR/AND, and casting arbitrary text\n  // would error before the audit could produce its typed report. The\n  // extraction is jsonExtractNumber (PostgreSQL `numeric`), NOT the double\n  // extraction the traversal uses: a JSON number beyond the float8 range\n  // must reach the range check below instead of overflowing the cast.\n  const weightNumber = sql`CASE WHEN ${isNumber} THEN ${dialect.jsonExtractNumber(propsColumn, pointer)} END`;\n  const missingViolation =\n    defaultWeight === undefined ?\n      sql`audited.is_missing = 1`\n    : dialect.booleanLiteral(false);\n  const negativeViolation = sql`audited.is_number = 1 AND audited.weight_number < 0`;\n  // CAST the bounds to NUMERIC so PostgreSQL compares in the arbitrary-\n  // precision domain — a numeric-vs-float8 comparison would coerce the\n  // out-of-range value to float8 and overflow before comparing. The lower\n  // arm rejects sub-denormal magnitudes (float8 cast underflow on\n  // PostgreSQL); on SQLite they parsed to exactly 0 and the arm cannot\n  // fire, which is the declared engine caveat on MIN_EDGE_WEIGHT.\n  const outOfRangeViolation = sql`audited.is_number = 1 AND (ABS(audited.weight_number) > CAST(${MAX_EDGE_WEIGHT} AS NUMERIC) OR (audited.weight_number <> 0 AND ABS(audited.weight_number) < CAST(${MIN_EDGE_WEIGHT} AS NUMERIC)))`;\n\n  for (const edgeKinds of operation.edgeKindChunks) {\n    const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), edgeKinds);\n    const rows = await operation.backend.execute<WeightAuditRow>(\n      asCompiledRowsSql(sql`\n        SELECT audited.edge_id, audited.edge_kind, audited.weight_text,\n          audited.is_number, audited.is_missing\n        FROM (\n          SELECT e.id AS edge_id, e.kind AS edge_kind,\n            ${weightText} AS weight_text,\n            ${weightNumber} AS weight_number,\n            CASE WHEN ${isNumber} THEN 1 ELSE 0 END AS is_number,\n            CASE WHEN ${isMissing} THEN 1 ELSE 0 END AS is_missing\n          FROM ${operation.schema.edgesTable} e\n          WHERE e.graph_id = ${operation.ctx.graphId}\n            AND ${edgeKindFilter}\n            AND ${operation.edgeTemporalFilter}\n        ) audited\n        WHERE (${missingViolation})\n          OR (audited.is_missing = 0 AND audited.is_number = 0)\n          OR (${negativeViolation})\n          OR (${outOfRangeViolation})\n        ORDER BY ${dialect.binaryText(sql`audited.edge_id`)}\n        LIMIT 1\n      `),\n    );\n    const row = rows[0];\n    if (row !== undefined) {\n      throw createInvalidEdgeWeightError(row, weightProperty);\n    }\n  }\n}\n\nfunction createInvalidEdgeWeightError(\n  row: WeightAuditRow,\n  weightProperty: string,\n): InvalidEdgeWeightError {\n  const reason = resolveInvalidWeightReason(row);\n  const value =\n    reason === \"missing\" || row.weight_text === null ?\n      undefined\n    : formatWeightValue(row.weight_text);\n  return new InvalidEdgeWeightError({\n    edgeId: row.edge_id,\n    edgeKind: row.edge_kind,\n    property: weightProperty,\n    reason,\n    ...(value === undefined ? {} : { value }),\n  });\n}\n\nfunction resolveInvalidWeightReason(\n  row: WeightAuditRow,\n): InvalidEdgeWeightReason {\n  if (flagIsSet(row.is_missing)) return \"missing\";\n  if (!flagIsSet(row.is_number)) return \"non_numeric\";\n  // A numeric violation is either negative or outside the accepted\n  // magnitude range; the sign distinguishes them (Number() of an oversized\n  // magnitude yields ±Infinity, whose sign still holds).\n  return Number(row.weight_text) < 0 ? \"negative\" : \"out_of_range\";\n}\n\n/** Coerces a driver-shaped 0/1 flag (number, bigint, or boolean) to boolean. */\nfunction flagIsSet(value: unknown): boolean {\n  return Number(value) !== 0;\n}\n\n/** Renders an extracted weight value for the error message. */\nfunction formatWeightValue(value: unknown): string {\n  if (typeof value === \"string\") return value;\n  if (\n    typeof value === \"number\" ||\n    typeof value === \"bigint\" ||\n    typeof value === \"boolean\"\n  ) {\n    return String(value);\n  }\n  return JSON.stringify(value);\n}\n\n// ============================================================\n// Working-table execution\n// ============================================================\n\nasync function findWeightedShortestPathInWorkingTable(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  maxIterations: number,\n  options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n  return runIterativeGraphOperation<\n    WeightedState,\n    WeightedShortestPathResult | undefined\n  >(ctx, options, {\n    algorithm: WEIGHTED_ALGORITHM_NAME,\n    maxIterations,\n    createWorkingTable,\n    async initialize(context) {\n      await assertValidEdgeWeights(\n        context.operation,\n        options.weightProperty,\n        options.defaultWeight,\n      );\n      // A target no visible node carries can never be reached; converge\n      // immediately instead of relaxing the source's entire component.\n      if (!(await hasVisibleNode(context.operation, targetId))) {\n        return {\n          frontierCount: 0,\n          workingTableSize: 0,\n          bestTargetDistance: undefined,\n        };\n      }\n      // Each round scans only the previous round's frontier; without this\n      // index that filter re-scans the whole (growing) working table, since\n      // the identity primary key cannot serve an improved_round lookup.\n      await context.executeTemporary(sql`\n        CREATE INDEX ${frontierIndexIdentifier(context)}\n        ON ${context.workingTable} (graph_id, run_id, improved_round)\n      `);\n      const seeded = await seedDistances(context, sourceId);\n      return {\n        frontierCount: seeded.length,\n        workingTableSize: seeded.length,\n        // Seeds carry the source id, never the target's — the self-path\n        // case is short-circuited before this plan runs.\n        bestTargetDistance: undefined,\n      };\n    },\n    async runRound(context, state, iteration) {\n      const round = await relaxFrontierRound(\n        context,\n        targetId,\n        iteration,\n        state.bestTargetDistance,\n      );\n      return {\n        frontierCount: round.frontierCount,\n        // Overcounts by re-improved existing rows (RETURNING includes\n        // updates); acceptable because the size only paces the substrate's\n        // ANALYZE refresh, where too-early merely refreshes stats sooner.\n        workingTableSize: state.workingTableSize + round.frontierCount,\n        bestTargetDistance: round.bestTargetDistance,\n      };\n    },\n    hasConverged(state: WeightedState) {\n      return state.frontierCount === 0;\n    },\n    async extractResult(context) {\n      // Selects rather than refuses (§5.1.3 of the design): the working-table\n      // path is gated on temp tables/RETURNING, not recursive traversal, so\n      // an engine that can run every relaxation round but lacks the\n      // recursive CTE still gets a working extraction instead of a refusal\n      // that would take away an algorithm it can otherwise run in full.\n      const recursiveTraversal = resolveRecursiveTraversal(\n        ctx.backend.capabilities,\n      );\n      return recursiveTraversal.supported ?\n          extractPathFromWorkingTable(context, targetId, maxIterations)\n        : extractPathByPredecessorWalk(context, targetId, maxIterations);\n    },\n  });\n}\n\n/**\n * Point lookup: does any visible node carry this id (under any kind)?\n */\nasync function hasVisibleNode(\n  operation: IterativeGraphOperation,\n  nodeId: string,\n): Promise<boolean> {\n  const rows = await operation.backend.execute<Readonly<{ id: string }>>(\n    asCompiledRowsSql(sql`\n      SELECT n.id FROM ${operation.schema.nodesTable} n\n      WHERE n.graph_id = ${operation.ctx.graphId}\n        AND n.id = ${nodeId}\n        AND ${operation.nodeTemporalFilter}\n      LIMIT 1\n    `),\n  );\n  return rows.length > 0;\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n  // DOUBLE PRECISION is accepted by both engines: PostgreSQL's float8, and\n  // REAL affinity on SQLite — the same IEEE 754 double either way.\n  return sql`\n    CREATE TEMP TABLE ${context.workingTable} (\n      graph_id TEXT NOT NULL,\n      run_id TEXT NOT NULL,\n      node_id TEXT NOT NULL,\n      node_kind TEXT NOT NULL,\n      distance DOUBLE PRECISION NOT NULL,\n      hops INTEGER NOT NULL,\n      predecessor_id TEXT,\n      predecessor_kind TEXT,\n      improved_round INTEGER NOT NULL,\n      PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n    )\n  `;\n}\n\nasync function seedDistances(\n  context: IterativeGraphRunContext,\n  sourceId: string,\n): Promise<readonly SeededRow[]> {\n  const { operation, workingTable, graphId, runId } = context;\n  return context.backend.execute<SeededRow>(\n    asCompiledRowsSql(sql`\n      INSERT INTO ${workingTable}\n        (graph_id, run_id, node_id, node_kind, distance, hops,\n         predecessor_id, predecessor_kind, improved_round)\n      SELECT ${graphId}, ${runId}, n.id, n.kind, 0, 0, NULL, NULL, 0\n      FROM ${operation.schema.nodesTable} n\n      WHERE n.graph_id = ${graphId}\n        AND n.id = ${sourceId}\n        AND ${operation.nodeTemporalFilter}\n      ON CONFLICT (graph_id, run_id, node_kind, node_id) DO NOTHING\n      RETURNING node_id\n    `),\n  );\n}\n\n/**\n * Relaxes one round: expands the previous round's frontier through visible\n * edges, keeps the cheapest candidate per target identity (ties broken by\n * source id then kind in binary collation, so both backends pick the same\n * predecessor), and upserts only strict distance improvements.\n *\n * Candidates costing strictly more than `roundBound` — the cheapest path to\n * the target known at round start, tracked in JS from RETURNING rows — are\n * pruned. Sound because the audit guarantees non-negative weights: no\n * extension of such a candidate can beat the known path. Equal-cost\n * candidates stay admitted, because zero-weight edges can extend an\n * equal-cost node to another node with the target id, and the documented\n * smallest-identity target tie-break must see that node; strict-improvement\n * upserts keep the equal-cost plateau finite. A bound parameter keeps the\n * pruning O(1) per candidate and applies the same round-start state on both\n * execution paths, so they run identical round sequences.\n */\nasync function relaxFrontierRound(\n  context: IterativeGraphRunContext,\n  targetId: string,\n  iteration: number,\n  roundBound: number | undefined,\n): Promise<FrontierRound> {\n  const { operation, workingTable, graphId, runId } = context;\n  const { dialect } = operation.ctx;\n  let frontierCount = 0;\n  let bestTargetDistance = roundBound;\n  for (const edgeKinds of operation.edgeKindChunks) {\n    const sourceFilter = sql`\n      w.graph_id = ${graphId}\n      AND w.run_id = ${runId}\n      AND w.improved_round = ${iteration - 1}\n    `;\n    const expansion = compileWorkingTableExpansion(\n      operation,\n      workingTable,\n      sourceFilter,\n      operation.direction,\n      edgeKinds,\n    );\n    const rows = await context.backend.execute<ImprovedRow>(\n      asCompiledRowsSql(sql`\n        INSERT INTO ${workingTable}\n          (graph_id, run_id, node_id, node_kind, distance, hops,\n           predecessor_id, predecessor_kind, improved_round)\n        SELECT\n          ${graphId}, ${runId}, ranked.target_id, ranked.target_kind,\n          ranked.candidate_distance, ranked.candidate_hops,\n          ranked.source_id, ranked.source_kind, ${iteration}\n        FROM (\n          SELECT candidates.*,\n            ROW_NUMBER() OVER (\n              PARTITION BY ${dialect.binaryText(sql`candidates.target_kind`)},\n                ${dialect.binaryText(sql`candidates.target_id`)}\n              ORDER BY candidates.candidate_distance,\n                ${dialect.binaryText(sql`candidates.source_id`)},\n                ${dialect.binaryText(sql`candidates.source_kind`)}\n            ) AS candidate_rank\n          FROM (\n            SELECT expanded.source_id, expanded.source_kind,\n              expanded.target_id, expanded.target_kind,\n              frontier.distance + expanded.weight AS candidate_distance,\n              frontier.hops + 1 AS candidate_hops\n            FROM (${expansion}) expanded\n            JOIN ${workingTable} frontier\n              ON frontier.graph_id = ${graphId}\n              AND frontier.run_id = ${runId}\n              AND frontier.node_id = expanded.source_id\n              AND frontier.node_kind = expanded.source_kind\n          ) candidates\n          WHERE ${\n            roundBound === undefined ?\n              sql`TRUE`\n            : sql`candidates.candidate_distance <= ${roundBound}`\n          }\n        ) ranked\n        WHERE ranked.candidate_rank = 1\n        ON CONFLICT (graph_id, run_id, node_kind, node_id) DO UPDATE SET\n          distance = excluded.distance,\n          hops = excluded.hops,\n          predecessor_id = excluded.predecessor_id,\n          predecessor_kind = excluded.predecessor_kind,\n          improved_round = excluded.improved_round\n        WHERE excluded.distance < ${workingTable}.distance\n        RETURNING node_id, distance\n      `),\n    );\n    frontierCount += rows.length;\n    for (const row of rows) {\n      if (row.node_id !== targetId) continue;\n      const distance = Number(row.distance);\n      if (bestTargetDistance === undefined || distance < bestTargetDistance) {\n        bestTargetDistance = distance;\n      }\n    }\n  }\n  return { frontierCount, bestTargetDistance };\n}\n\n/**\n * Extracts the result path directly in SQL: pick the cheapest row carrying\n * the target id (ties by kind in binary collation, matching the inline\n * path's code-point tie-break since the id is fixed), then walk predecessor\n * pointers through a recursive CTE. Transfer and JS memory stay\n * proportional to the path length instead of the visited set. The\n * `position` guard bounds recursion at the round budget — predecessor\n * chains cannot cycle, but a recursive CTE should never rely on that alone.\n */\nasync function extractPathFromWorkingTable(\n  context: IterativeGraphRunContext,\n  targetId: string,\n  maxIterations: number,\n): Promise<WeightedShortestPathResult | undefined> {\n  const { workingTable, graphId, runId } = context;\n  const rows = await context.backend.execute<ChainRow>(\n    asCompiledRowsSql(sql`\n      WITH RECURSIVE chain AS (\n        SELECT best.node_id, best.node_kind, best.distance, best.hops,\n          best.predecessor_id, best.predecessor_kind, 0 AS position\n        FROM (${selectCheapestTargetRowSql(context, targetId)}) best\n        UNION ALL\n        SELECT w.node_id, w.node_kind, w.distance, w.hops,\n          w.predecessor_id, w.predecessor_kind, c.position + 1\n        FROM chain c\n        JOIN ${workingTable} w\n          ON w.graph_id = ${graphId}\n          AND w.run_id = ${runId}\n          AND w.node_id = c.predecessor_id\n          AND w.node_kind = c.predecessor_kind\n        WHERE c.position <= ${maxIterations}\n      )\n      SELECT node_id, node_kind, distance, hops\n      FROM chain\n      ORDER BY position DESC\n    `),\n  );\n  // position DESC orders source-first, target-last.\n  const target = rows.at(-1);\n  if (target === undefined) return undefined;\n  return {\n    nodes: rows.map((row) => ({ id: row.node_id, kind: row.node_kind })),\n    depth: Number(target.hops),\n    totalWeight: Number(target.distance),\n  };\n}\n\n/**\n * The one owner of the \"cheapest row carrying the target id\" decision (ties\n * broken by kind in binary collation, matching the id's fixed value): the\n * recursive extractor above and the predecessor-walk fallback below both\n * anchor on this fragment, so their tie-break cannot drift apart the way a\n * second inline copy of this `ORDER BY` would let it.\n */\nfunction selectCheapestTargetRowSql(\n  context: IterativeGraphRunContext,\n  targetId: string,\n): SqlFragment {\n  const { operation, workingTable, graphId, runId } = context;\n  const { dialect } = operation.ctx;\n  return sql`\n    SELECT node_id, node_kind, distance, hops,\n      predecessor_id, predecessor_kind\n    FROM ${workingTable}\n    WHERE graph_id = ${graphId}\n      AND run_id = ${runId}\n      AND node_id = ${targetId}\n    ORDER BY distance ASC, ${dialect.binaryText(sql`node_kind`)}\n    LIMIT 1\n  `;\n}\n\n/** @internal — the working-table row a predecessor walk reads. */\nexport type PredecessorChainRow = ChainRow &\n  Readonly<{ predecessor_id: unknown; predecessor_kind: unknown }>;\n\n/**\n * @internal — exported so the bound/termination axes are unit-testable\n * (precedent: `shouldRefreshWorkingTableStatistics`).\n *\n * Walks predecessor pointers target-first, starting at `first`, reproducing\n * the recursive CTE's own bound and termination exactly (ruling M-13,\n * behavior preservation):\n *\n * - **Termination**: a row's predecessor columns normalize to `undefined`\n *   through {@link nodeIdentityFromRow} exactly when the CTE's join on\n *   `predecessor_id`/`predecessor_kind` would fail on SQL NULL — the seeded\n *   source row ends the chain this way. The same predicate also ends the\n *   chain when a read returns no row, mirroring a join that yields nothing.\n * - **Bound**: the loop runs `position` from `0` through `maxIterations`\n *   inclusive — the same range as the CTE's recursive arm, gated on\n *   `position <= maxIterations` — and stops silently, without throwing, past\n *   it. The chain can therefore hold at most `maxIterations + 2` rows: `first`\n *   plus one row per loop iteration. The truncation this produces on an\n *   over-length chain is pre-existing contract, reproduced deliberately, not\n *   a new defect: it is unreachable through the public API, because\n *   `runWorkingTableRounds` (`iterative-graph-operation.ts:471-493`) raises\n *   `GraphAlgorithmConvergenceError` before extraction runs at all unless the\n *   plan converged, and a converged plan has at most `maxIterations - 1`\n *   hops (a node improved in round *i* has hops at most *i*, and convergence\n *   needs one round with an empty frontier). Follow-up **F11** asks whether\n *   either implementation should truncate at all — this function does not\n *   answer that question, only reproduces the existing one.\n */\nexport async function collectPredecessorChain(\n  first: PredecessorChainRow,\n  readPredecessor: (\n    predecessor: PathNode,\n  ) => Promise<PredecessorChainRow | undefined>,\n  maxIterations: number,\n): Promise<readonly PredecessorChainRow[]> {\n  const chain: PredecessorChainRow[] = [first];\n  let current = first;\n  for (let position = 0; position <= maxIterations; position++) {\n    const predecessor = nodeIdentityFromRow(\n      current.predecessor_id,\n      current.predecessor_kind,\n    );\n    if (predecessor === undefined) break;\n    const predecessorRow = await readPredecessor(predecessor);\n    if (predecessorRow === undefined) break;\n    chain.push(predecessorRow);\n    current = predecessorRow;\n  }\n  return chain;\n}\n\n/**\n * The predecessor-walk fallback for engines with temporary tables and\n * `RETURNING` but no recursive traversal (the recursive CTE `chain` above):\n * issues the shared selection once, then walks predecessor pointers with one\n * primary-key point read per hop instead of one recursive statement. Costs\n * `path length + 1` statements rather than 1, which is the applied-not-\n * refused answer for an engine that can run every relaxation round but\n * cannot run the final recursive read (§5.1.3 of the design).\n */\nasync function extractPathByPredecessorWalk(\n  context: IterativeGraphRunContext,\n  targetId: string,\n  maxIterations: number,\n): Promise<WeightedShortestPathResult | undefined> {\n  const rows = await context.backend.execute<PredecessorChainRow>(\n    asCompiledRowsSql(selectCheapestTargetRowSql(context, targetId)),\n  );\n  const first = rows[0];\n  if (first === undefined) return undefined;\n\n  const { workingTable, graphId, runId } = context;\n  const chain = await collectPredecessorChain(\n    first,\n    async (predecessor) => {\n      const predecessorRows =\n        await context.backend.execute<PredecessorChainRow>(\n          asCompiledRowsSql(sql`\n            SELECT node_id, node_kind, distance, hops,\n              predecessor_id, predecessor_kind\n            FROM ${workingTable}\n            WHERE graph_id = ${graphId} AND run_id = ${runId}\n              AND node_kind = ${predecessor.kind} AND node_id = ${predecessor.id}\n          `),\n        );\n      return predecessorRows[0];\n    },\n    maxIterations,\n  );\n\n  return {\n    nodes: chain\n      .map((row) => ({ id: row.node_id, kind: row.node_kind }))\n      .toReversed(),\n    depth: Number(first.hops),\n    totalWeight: Number(first.distance),\n  };\n}\n\n/**\n * Zero-weight self path: audits the weight domain (so data errors surface\n * identically to a full traversal) and checks the node's visibility, with\n * no relaxation rounds. Multiple kinds sharing the id resolve to the\n * smallest node identity, matching the traversal tie-break.\n */\nasync function findWeightedSelfPath(\n  ctx: AlgorithmContext,\n  nodeId: string,\n  options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n  return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n    await assertValidEdgeWeights(\n      operation,\n      options.weightProperty,\n      options.defaultWeight,\n    );\n    const nodes = await fetchVisibleWorkingNodes(operation, [nodeId]);\n    const node = nodes.toSorted((left, right) =>\n      compareNodeIdentity(left, right),\n    )[0];\n    if (node === undefined) return;\n    return { nodes: [node], depth: 0, totalWeight: 0 };\n  });\n}\n\n// ============================================================\n// Inline execution (backends without temporary-table support)\n// ============================================================\n\nasync function findWeightedShortestPathInline(\n  ctx: AlgorithmContext,\n  sourceId: string,\n  targetId: string,\n  maxIterations: number,\n  options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n  return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n    await assertValidEdgeWeights(\n      operation,\n      options.weightProperty,\n      options.defaultWeight,\n    );\n    const endpoints = await fetchVisibleWorkingNodes(operation, [\n      sourceId,\n      targetId,\n    ]);\n    const sources = endpoints.filter((node) => node.id === sourceId);\n    // A target no visible node carries can never be reached; skip relaxing\n    // the source's entire component.\n    if (\n      sources.length === 0 ||\n      !endpoints.some((node) => node.id === targetId)\n    ) {\n      return;\n    }\n\n    const settled = new Map<NodeIdentityKey, WeightedVisitedNode>(\n      sources.map((source) => [\n        nodeIdentityKey(source),\n        {\n          id: source.id,\n          kind: source.kind,\n          distance: 0,\n          hops: 0,\n          parentKey: undefined,\n        },\n      ]),\n    );\n    let bestTargetDistance: number | undefined;\n    let frontier: readonly PathNode[] = sources;\n    let rounds = 0;\n\n    while (frontier.length > 0) {\n      if (rounds >= maxIterations) {\n        throw new GraphAlgorithmConvergenceError(\n          WEIGHTED_ALGORITHM_NAME,\n          maxIterations,\n        );\n      }\n      rounds++;\n\n      const candidates = await reduceExpandedWorkingSet<WeightedCandidate>(\n        operation,\n        frontier,\n        operation.direction,\n        (existing, expansion) =>\n          reduceWeightedCandidate(existing, expansion, settled),\n      );\n\n      // Prune against the best target distance as of the round start, the\n      // same state the working-table round's pre-statement snapshot sees, so\n      // both execution paths run identical round sequences.\n      const roundBound = bestTargetDistance;\n      const improved: PathNode[] = [];\n      for (const [candidateKey, candidate] of candidates) {\n        const existing = settled.get(candidateKey);\n        if (existing !== undefined && existing.distance <= candidate.distance) {\n          continue;\n        }\n        // Mirrors the working-table prune: only strictly-worse candidates\n        // are dropped. Equal-cost ones stay admitted so zero-weight edges\n        // from the equal-cost plateau can still reach a smaller-identity\n        // node carrying the target id.\n        if (roundBound !== undefined && candidate.distance > roundBound) {\n          continue;\n        }\n        settled.set(candidateKey, {\n          id: candidate.id,\n          kind: candidate.kind,\n          distance: candidate.distance,\n          hops: candidate.hops,\n          parentKey: nodeIdentityKey({\n            id: candidate.parentId,\n            kind: candidate.parentKind,\n          }),\n        });\n        improved.push({ id: candidate.id, kind: candidate.kind });\n        if (\n          candidate.id === targetId &&\n          (bestTargetDistance === undefined ||\n            candidate.distance < bestTargetDistance)\n        ) {\n          bestTargetDistance = candidate.distance;\n        }\n      }\n      frontier = improved.toSorted((left, right) =>\n        compareNodeIdentity(left, right),\n      );\n    }\n\n    return buildWeightedPathResult(settled, targetId);\n  });\n}\n\n/**\n * Keeps the cheapest candidate per target identity; ties break by source id\n * then kind, mirroring the working-table round's ROW_NUMBER ordering.\n */\nfunction reduceWeightedCandidate(\n  existing: WeightedCandidate | undefined,\n  expansion: NodeExpansion,\n  settled: ReadonlyMap<NodeIdentityKey, WeightedVisitedNode>,\n): WeightedCandidate | undefined {\n  // Unreachable on a weighted run — the substrate rejects NULL weights with\n  // an invariant error — but the field is optional, so narrow it.\n  const weight = expansion.weight;\n  if (weight === undefined) return existing;\n  const sourceEntry = settled.get(nodeIdentityKey(expansion.source));\n  if (sourceEntry === undefined) return existing;\n  const candidateDistance = sourceEntry.distance + weight;\n  if (\n    existing !== undefined &&\n    (existing.distance < candidateDistance ||\n      (existing.distance === candidateDistance &&\n        compareNodeIdentity(\n          { id: existing.parentId, kind: existing.parentKind },\n          expansion.source,\n        ) <= 0))\n  ) {\n    return existing;\n  }\n  return {\n    id: expansion.target.id,\n    kind: expansion.target.kind,\n    distance: candidateDistance,\n    hops: sourceEntry.hops + 1,\n    parentId: expansion.source.id,\n    parentKind: expansion.source.kind,\n  };\n}\n\n// ============================================================\n// Shared result construction\n// ============================================================\n\n/**\n * Selects the cheapest settled node matching the target id (ties by node id\n * then kind) and reconstructs the path by walking predecessors back to the\n * source. Returns `undefined` when the target was never settled.\n */\nfunction buildWeightedPathResult(\n  visited: ReadonlyMap<NodeIdentityKey, WeightedVisitedNode>,\n  targetId: string,\n): WeightedShortestPathResult | undefined {\n  let target: WeightedVisitedNode | undefined;\n  for (const node of visited.values()) {\n    if (node.id !== targetId) continue;\n    if (\n      target === undefined ||\n      node.distance < target.distance ||\n      (node.distance === target.distance &&\n        compareNodeIdentity(node, target) < 0)\n    ) {\n      target = node;\n    }\n  }\n  if (target === undefined) return undefined;\n\n  const reversedNodes: PathNode[] = [];\n  let cursor: WeightedVisitedNode | undefined = target;\n  while (cursor !== undefined) {\n    reversedNodes.push({ id: cursor.id, kind: cursor.kind });\n    cursor =\n      cursor.parentKey === undefined ?\n        undefined\n      : visited.get(cursor.parentKey);\n  }\n\n  return {\n    nodes: reversedNodes.toReversed(),\n    depth: target.hops,\n    totalWeight: target.distance,\n  };\n}\n","import { type GraphBackend } from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type TemporalMode } from \"../../core/types\";\nimport {\n  createSqlSchema,\n  type RecordedReadBinding,\n  type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { assertNoRecordedCoordinate } from \"../recorded-coordinate-guard\";\nimport { type AlgorithmContext } from \"./context\";\nimport { executeDegree } from \"./degree\";\nimport { executeLabelPropagation } from \"./label-propagation\";\nimport { executePageRank, executePersonalizedPageRank } from \"./page-rank\";\nimport {\n  executeCanReach,\n  executeNeighbors,\n  executeReachable,\n} from \"./reachable\";\nimport { executeShortestPath } from \"./shortest-path\";\nimport type {\n  BaseTraversalOptions,\n  DegreeOptions,\n  InternalBaseTraversalOptions,\n  InternalDegreeOptions,\n  InternalLabelPropagationOptions,\n  InternalNeighborsOptions,\n  InternalPageRankOptions,\n  InternalPersonalizedPageRankOptions,\n  InternalReachableOptions,\n  InternalShortestPathOptions,\n  InternalWeaklyConnectedComponentsOptions,\n  InternalWeightedShortestPathOptions,\n  LabelPropagationMembership,\n  LabelPropagationOptions,\n  NeighborsOptions,\n  PageRankOptions,\n  PageRankScore,\n  PersonalizedPageRankOptions,\n  ReachableNode,\n  ReachableOptions,\n  ShortestPathOptions,\n  ShortestPathResult,\n  WeaklyConnectedComponentMembership,\n  WeaklyConnectedComponentsOptions,\n  WeightedShortestPathOptions,\n  WeightedShortestPathResult,\n} from \"./types\";\nimport { executeWeaklyConnectedComponents } from \"./weakly-connected-components\";\nimport { executeWeightedShortestPath } from \"./weighted-shortest-path\";\n\n/**\n * Raw node id or any object with an `id: string` field. Covers `Node`,\n * `NodeRef`, and the lightweight `ReachableNode` / `PathNode` shapes\n * returned by the algorithms themselves.\n *\n * Deliberately kind-agnostic: graph algorithms don't constrain the source\n * node's kind — you can start a traversal from any node reachable via the\n * given edge kinds. `NodeRef<N>` exists for the edge-endpoint case where\n * kind *is* load-bearing; using it here would paint a constraint onto a\n * contract that doesn't need one and would reject common patterns like\n * passing `ReachableNode` / cache entries / `{ id }` records straight\n * through.\n */\nexport type NodeIdentifier = string | Readonly<{ id: string }>;\n\nfunction resolveNodeId(value: NodeIdentifier): string {\n  return typeof value === \"string\" ? value : value.id;\n}\n\nexport type GraphAlgorithms<G extends GraphDef> = Readonly<{\n  /**\n   * Finds the shortest directed path from `from` to `to` using the given\n   * edge kinds. Returns `undefined` when no path exists within `maxHops`.\n   *\n   * @example\n   * ```typescript\n   * const path = await store.algorithms.shortestPath(alice, bob, {\n   *   edges: [\"knows\"],\n   *   maxHops: 6,\n   * });\n   * if (path) {\n   *   console.log(`${path.depth} hops via`, path.nodes.map((n) => n.id));\n   * }\n   * ```\n   */\n  shortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: ShortestPathOptions<G>,\n  ) => Promise<ShortestPathResult | undefined>;\n\n  /**\n   * Finds the minimum-total-weight path from `from` to `to`, weighting each\n   * traversed edge by the numeric `weightProperty` stored on it. Returns\n   * `undefined` when no path exists. Weights must be non-negative; a\n   * negative, non-numeric, or (without `defaultWeight`) missing weight on\n   * any visible edge of the selected kinds throws `InvalidEdgeWeightError`\n   * before traversal starts.\n   *\n   * @example\n   * ```typescript\n   * const path = await store.algorithms.weightedShortestPath(alice, bob, {\n   *   edges: [\"knows\"],\n   *   weightProperty: \"interactionCost\",\n   *   direction: \"both\",\n   * });\n   * if (path) {\n   *   console.log(`total weight ${path.totalWeight} over ${path.depth} hops`);\n   * }\n   * ```\n   */\n  weightedShortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: WeightedShortestPathOptions<G>,\n  ) => Promise<WeightedShortestPathResult | undefined>;\n\n  /**\n   * Returns every node reachable from `from` within `maxHops` edges of the\n   * allowed kinds. Each node carries its minimum discovered depth.\n   */\n  reachable: (\n    from: NodeIdentifier,\n    options: ReachableOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n\n  /**\n   * Fast boolean check: is `to` reachable from `from` within `maxHops`\n   * edges? Uses bidirectional BFS and stops when the frontiers meet.\n   */\n  canReach: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: BaseTraversalOptions<G>,\n  ) => Promise<boolean>;\n\n  /**\n   * Returns the k-hop neighborhood of a node. The source is always\n   * excluded. `depth` defaults to 1, matching the common \"immediate\n   * neighbors\" interpretation.\n   */\n  neighbors: (\n    node: NodeIdentifier,\n    options: NeighborsOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n\n  /**\n   * Counts active edges incident to `node`.\n   *\n   * With `direction: \"both\"` (default), self-loops contribute once.\n   */\n  degree: (node: NodeIdentifier, options?: DegreeOptions<G>) => Promise<number>;\n\n  /**\n   * Runs deterministic synchronous label propagation over an undirected\n   * projection of the selected edge kinds.\n   */\n  labelPropagation: (\n    options: LabelPropagationOptions<G>,\n  ) => Promise<readonly LabelPropagationMembership[]>;\n\n  /**\n   * Computes exact weakly connected components over the selected edge kinds.\n   *\n   * Iterative: runs multiple SQL rounds in one snapshot and requires\n   * `backend.capabilities.graphAnalytics.supported`.\n   */\n  weaklyConnectedComponents: (\n    options: WeaklyConnectedComponentsOptions<G>,\n  ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n\n  /**\n   * Computes global PageRank over the visible induced graph. Scores sum to\n   * approximately one and are returned from highest to lowest.\n   */\n  pageRank: (options: PageRankOptions<G>) => Promise<readonly PageRankScore[]>;\n\n  /**\n   * Computes PageRank with teleport mass distributed across weighted seeds.\n   */\n  personalizedPageRank: (\n    options: PersonalizedPageRankOptions<G>,\n  ) => Promise<readonly PageRankScore[]>;\n}>;\n\nexport type InternalGraphAlgorithms<G extends GraphDef> = Readonly<{\n  shortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: InternalShortestPathOptions<G>,\n  ) => Promise<ShortestPathResult | undefined>;\n  weightedShortestPath: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: InternalWeightedShortestPathOptions<G>,\n  ) => Promise<WeightedShortestPathResult | undefined>;\n  reachable: (\n    from: NodeIdentifier,\n    options: InternalReachableOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n  canReach: (\n    from: NodeIdentifier,\n    to: NodeIdentifier,\n    options: InternalBaseTraversalOptions<G>,\n  ) => Promise<boolean>;\n  neighbors: (\n    node: NodeIdentifier,\n    options: InternalNeighborsOptions<G>,\n  ) => Promise<readonly ReachableNode[]>;\n  degree: (\n    node: NodeIdentifier,\n    options?: InternalDegreeOptions<G>,\n  ) => Promise<number>;\n  labelPropagation: (\n    options: InternalLabelPropagationOptions<G>,\n  ) => Promise<readonly LabelPropagationMembership[]>;\n  weaklyConnectedComponents: (\n    options: InternalWeaklyConnectedComponentsOptions<G>,\n  ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n  pageRank: (\n    options: InternalPageRankOptions<G>,\n  ) => Promise<readonly PageRankScore[]>;\n  personalizedPageRank: (\n    options: InternalPersonalizedPageRankOptions<G>,\n  ) => Promise<readonly PageRankScore[]>;\n}>;\n\nexport type CreateGraphAlgorithmsParams = Readonly<{\n  graphId: string;\n  graph: GraphDef;\n  registry: KindRegistry;\n  backend: GraphBackend;\n  schema: SqlSchema | undefined;\n  recordedReadBinding: RecordedReadBinding | undefined;\n  defaultTemporalMode: TemporalMode;\n  allowRecordedAsOf?: boolean;\n}>;\n\nfunction assertRecordedAsOfInternalOnly(\n  options: unknown,\n  method: string,\n  allowRecordedAsOf: boolean,\n): void {\n  if (allowRecordedAsOf) return;\n  assertNoRecordedCoordinate(options, {\n    code: \"ALGORITHM_RECORDED_ASOF_INTERNAL_ONLY\",\n    message: `recordedAsOf is only available through store.asOfRecorded(...).${method}(...).`,\n    context: { method },\n    suggestion:\n      \"Use store.asOfRecorded(recordedAt) or a recorded StoreView instead of passing recordedAsOf directly.\",\n  });\n}\n\nexport function createGraphAlgorithms<G extends GraphDef>(\n  params: CreateGraphAlgorithmsParams,\n): InternalGraphAlgorithms<G> {\n  const allowRecordedAsOf = params.allowRecordedAsOf === true;\n  const ctx: AlgorithmContext = {\n    graphId: params.graphId,\n    graph: params.graph,\n    registry: params.registry,\n    backend: params.backend,\n    dialect: getDialect(params.backend.dialect),\n    schema: params.schema ?? createSqlSchema(params.backend.tableNames),\n    recordedReadBinding: params.recordedReadBinding,\n    defaultTemporalMode: params.defaultTemporalMode,\n  };\n\n  return {\n    shortestPath(from, to, options) {\n      assertRecordedAsOfInternalOnly(\n        options,\n        \"shortestPath\",\n        allowRecordedAsOf,\n      );\n      return executeShortestPath(\n        ctx,\n        resolveNodeId(from),\n        resolveNodeId(to),\n        options,\n      );\n    },\n    weightedShortestPath(from, to, options) {\n      assertRecordedAsOfInternalOnly(\n        options,\n        \"weightedShortestPath\",\n        allowRecordedAsOf,\n      );\n      return executeWeightedShortestPath(\n        ctx,\n        resolveNodeId(from),\n        resolveNodeId(to),\n        options,\n      );\n    },\n    reachable(from, options) {\n      assertRecordedAsOfInternalOnly(options, \"reachable\", allowRecordedAsOf);\n      return executeReachable(ctx, resolveNodeId(from), options);\n    },\n    canReach(from, to, options) {\n      assertRecordedAsOfInternalOnly(options, \"canReach\", allowRecordedAsOf);\n      return executeCanReach(\n        ctx,\n        resolveNodeId(from),\n        resolveNodeId(to),\n        options,\n      );\n    },\n    neighbors(node, options) {\n      assertRecordedAsOfInternalOnly(options, \"neighbors\", allowRecordedAsOf);\n      return executeNeighbors(ctx, resolveNodeId(node), options);\n    },\n    degree(node, options) {\n      assertRecordedAsOfInternalOnly(options, \"degree\", allowRecordedAsOf);\n      return executeDegree(ctx, resolveNodeId(node), options ?? {});\n    },\n    labelPropagation(options) {\n      assertRecordedAsOfInternalOnly(\n        options,\n        \"labelPropagation\",\n        allowRecordedAsOf,\n      );\n      return executeLabelPropagation(ctx, options);\n    },\n    weaklyConnectedComponents(options) {\n      assertRecordedAsOfInternalOnly(\n        options,\n        \"weaklyConnectedComponents\",\n        allowRecordedAsOf,\n      );\n      return executeWeaklyConnectedComponents(ctx, options);\n    },\n    pageRank(options) {\n      assertRecordedAsOfInternalOnly(options, \"pageRank\", allowRecordedAsOf);\n      return executePageRank(ctx, options);\n    },\n    personalizedPageRank(options) {\n      assertRecordedAsOfInternalOnly(\n        options,\n        \"personalizedPageRank\",\n        allowRecordedAsOf,\n      );\n      return executePersonalizedPageRank(ctx, options);\n    },\n  };\n}\n\nexport type {\n  AlgorithmCyclePolicy,\n  BaseTraversalOptions,\n  DegreeOptions,\n  InternalBaseTraversalOptions,\n  InternalDegreeOptions,\n  InternalLabelPropagationOptions,\n  InternalNeighborsOptions,\n  InternalPageRankOptions,\n  InternalPersonalizedPageRankOptions,\n  InternalReachableOptions,\n  InternalShortestPathOptions,\n  InternalTemporalAlgorithmOptions,\n  InternalWeaklyConnectedComponentsOptions,\n  InternalWeightedShortestPathOptions,\n  LabelPropagationMembership,\n  LabelPropagationOptions,\n  NeighborsOptions,\n  PageRankOptions,\n  PageRankScore,\n  PathNode,\n  PersonalizedPageRankOptions,\n  PersonalizedPageRankSeed,\n  ReachableNode,\n  ReachableOptions,\n  ShortestPathOptions,\n  ShortestPathResult,\n  TemporalAlgorithmOptions,\n  TraversalDirection,\n  WeaklyConnectedComponentMembership,\n  WeaklyConnectedComponentsOptions,\n  WeightedShortestPathOptions,\n  WeightedShortestPathResult,\n} from \"./types\";\n","/**\n * The read-only fence diagnostic: which claim axes are ALREADY contended.\n *\n * A claim relation refuses a second claimant from the first post-upgrade write\n * onward, but it repairs nothing that is already there. A database that carried\n * two live siblings sharing a scoped key, or two live `cardinality: \"one\"` edges\n * from one source, keeps carrying them — the next write that touches such an\n * axis is refused with the ordinary typed error naming the incumbent, and until\n * then nothing says so out loud. This module is what says so.\n *\n * It reports; it never repairs. Choosing which of two live claimants keeps the\n * axis is a data-loss decision that belongs to the operator, not to a\n * diagnostic.\n *\n * Every axis and key it names is built by the SAME function the fence writes\n * with — {@link uniquenessClaimTarget}, {@link disjointnessClaimAxis},\n * {@link edgeCardinalityClaimTarget} — so a report row names the row a writer\n * would actually contend for. A second spelling here would produce a report\n * about axes the fence does not use.\n */\nimport type {\n  ConstraintFenceViolationRows,\n  ContendedEdgeRow,\n  ContendedUniqueRow,\n  DisjointOverlapRow,\n  EdgeCardinalityDeclaration,\n  GraphBackend,\n  ReadConstraintFenceViolationsParams,\n} from \"../../backend/types\";\nimport { subClassComponent } from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { compareStrings } from \"../../utils/compare\";\nimport {\n  type ClaimOwner,\n  type ClaimTarget,\n  compareClaimTargets,\n  DISJOINT_CONSTRAINT_NAME,\n  disjointnessClaimAxis,\n  isSameClaimOwner,\n  uniquenessClaimTarget,\n} from \"./axis\";\nimport { edgeCardinalityClaimTarget } from \"./edge-claims\";\n\n/**\n * One claim axis more than one live claimant holds.\n *\n * Discriminated on the family because the two claim relations record their\n * holders differently: a `uniques` axis is held by an OWNER PAIR (ids are\n * unique only per kind), an edge-claim axis by an edge id. `target` is the\n * claim row itself, so a reader can go straight to the row a writer contends\n * for rather than reconstructing it from the family's own vocabulary.\n */\nexport type ConstraintFenceViolation =\n  | Readonly<{\n      family: \"nodeUniqueness\" | \"nodeDisjointness\";\n      target: ClaimTarget;\n      owners: readonly ClaimOwner[];\n    }>\n  | Readonly<{\n      family: \"edgeCardinality\";\n      target: ClaimTarget;\n      edgeIds: readonly string[];\n    }>;\n\n/** What the audit needs to know: the graph, its registry, and where to read. */\nexport type VerifyConstraintFencesContext = Readonly<{\n  graph: GraphDef;\n  registry: KindRegistry;\n  graphId: string;\n  backend: GraphBackend;\n}>;\n\n/**\n * One `(constraint name, axis)` a declared uniqueness constraint claims at, and\n * the kinds whose claim rows fold onto it.\n *\n * The covered set is what maps a row written at a LEGACY axis — its own\n * concrete kind, which is where every pre-upgrade row sits — onto the axis this\n * version writes at. Without it the report would group a pre-upgrade duplicate\n * into two groups of one and find nothing.\n */\ntype UniquenessAxisGroup = Readonly<{\n  constraintName: string;\n  axis: string;\n  coveredKinds: ReadonlySet<string>;\n}>;\n\n/** The uniqueness axes the graph's own declarations produce. */\nfunction uniquenessAxisGroups(\n  graph: GraphDef,\n  registry: KindRegistry,\n): readonly UniquenessAxisGroup[] {\n  const groups = new Map<string, UniquenessAxisGroup>();\n  for (const [kind, registration] of Object.entries(graph.nodes)) {\n    for (const constraint of registration.unique ?? []) {\n      const target = uniquenessClaimTarget(kind, constraint.scope, registry);\n      const coveredKinds =\n        constraint.scope === \"kind\" ?\n          [kind]\n        : subClassComponent(kind, registry);\n      const identity = `${constraint.name}\\u0000${target.axis}`;\n      const existing = groups.get(identity);\n      groups.set(identity, {\n        constraintName: constraint.name,\n        axis: target.axis,\n        coveredKinds: new Set([\n          ...(existing?.coveredKinds ?? []),\n          ...coveredKinds,\n        ]),\n      });\n    }\n  }\n  return [...groups.values()];\n}\n\n/**\n * WHICH axis a live `uniques` row is read at.\n *\n * A row whose `node_kind` no declared group covers is left at its own\n * `node_kind`: the relation's primary key already makes it the only row there,\n * so it can contend with nothing and is reported by no group.\n *\n * A row covered by more than one group — possible only when one constraint name\n * is declared at two different scopes over one hierarchy — folds onto the\n * WIDEST of them, then onto the lowest axis. Widest, because that is where the\n * strictest fence sits: merging is what can reveal a contention, so the tie is\n * broken toward reporting rather than toward silence.\n */\nfunction uniquenessAxisFor(\n  row: ContendedUniqueRow,\n  groups: readonly UniquenessAxisGroup[],\n): string {\n  const covering = groups\n    .filter(\n      (group) =>\n        group.constraintName === row.constraintName &&\n        group.coveredKinds.has(row.nodeKind),\n    )\n    .toSorted(\n      (left, right) =>\n        right.coveredKinds.size - left.coveredKinds.size ||\n        compareStrings(left.axis, right.axis),\n    );\n  return covering[0]?.axis ?? row.nodeKind;\n}\n\n/** Owners in one deterministic order, so two runs report one shape. */\nfunction sortedOwners(owners: readonly ClaimOwner[]): readonly ClaimOwner[] {\n  return owners.toSorted(\n    (left, right) =>\n      compareStrings(left.concreteKind, right.concreteKind) ||\n      compareStrings(left.nodeId, right.nodeId),\n  );\n}\n\n/** A claim target keyed as one map entry, for grouping rows onto axes. */\nfunction targetIdentity(target: ClaimTarget): string {\n  return [\n    target.relation,\n    target.axis,\n    target.constraintName ?? \"\",\n    target.key,\n  ].join(\"\\u0000\");\n}\n\n/**\n * Live `uniques` rows folded onto their axes, reported where an axis carries\n * more than one DISTINCT owner.\n *\n * Distinctness is {@link isSameClaimOwner}, not id equality and not row count:\n * one node legitimately holds rows at two axes at once (a claim written before\n * the axis moved plus the one written after), and counting rows would report\n * that as a violation of a constraint it does not violate.\n */\nfunction uniquenessViolations(\n  rows: readonly ContendedUniqueRow[],\n  groups: readonly UniquenessAxisGroup[],\n  graphId: string,\n): readonly ConstraintFenceViolation[] {\n  const byAxis = new Map<\n    string,\n    Readonly<{ target: ClaimTarget; owners: ClaimOwner[] }>\n  >();\n  for (const row of rows) {\n    const target: ClaimTarget = {\n      relation: \"uniques\",\n      graphId,\n      axis: uniquenessAxisFor(row, groups),\n      constraintName: row.constraintName,\n      key: row.key,\n    };\n    const identity = targetIdentity(target);\n    const entry = byAxis.get(identity) ?? { target, owners: [] };\n    const owner: ClaimOwner = {\n      concreteKind: row.concreteKind,\n      nodeId: row.nodeId,\n    };\n    if (!entry.owners.some((held) => isSameClaimOwner(held, owner)))\n      entry.owners.push(owner);\n    byAxis.set(identity, entry);\n  }\n  return [...byAxis.values()]\n    .filter((entry) => entry.owners.length > 1)\n    .map((entry) => ({\n      family: \"nodeUniqueness\" as const,\n      target: entry.target,\n      owners: sortedOwners(entry.owners),\n    }));\n}\n\n/**\n * Each id live under both kinds of a declared disjoint pair, at the pair axis\n * the claim uses and keyed — as the claim is — on the id itself.\n */\nfunction disjointnessViolations(\n  overlaps: readonly DisjointOverlapRow[],\n  registry: KindRegistry,\n  graphId: string,\n): readonly ConstraintFenceViolation[] {\n  return overlaps.map((overlap) => ({\n    family: \"nodeDisjointness\" as const,\n    target: {\n      relation: \"uniques\" as const,\n      graphId,\n      axis: disjointnessClaimAxis(overlap.kinds[0], overlap.kinds[1], registry),\n      constraintName: DISJOINT_CONSTRAINT_NAME,\n      key: overlap.nodeId,\n    },\n    owners: sortedOwners([\n      { concreteKind: overlap.kinds[0], nodeId: overlap.nodeId },\n      { concreteKind: overlap.kinds[1], nodeId: overlap.nodeId },\n    ]),\n  }));\n}\n\n/**\n * Live edges folded onto the cardinality axis each one would claim, reported\n * where an axis carries more than one holder.\n */\nfunction edgeCardinalityViolations(\n  rows: readonly ContendedEdgeRow[],\n  graphId: string,\n): readonly ConstraintFenceViolation[] {\n  const byAxis = new Map<\n    string,\n    Readonly<{ target: ClaimTarget; edgeIds: string[] }>\n  >();\n  for (const row of rows) {\n    const target = edgeCardinalityClaimTarget({ ...row, graphId });\n    const identity = targetIdentity(target);\n    const entry = byAxis.get(identity) ?? { target, edgeIds: [] };\n    entry.edgeIds.push(row.edgeId);\n    byAxis.set(identity, entry);\n  }\n  return [...byAxis.values()]\n    .filter((entry) => entry.edgeIds.length > 1)\n    .map((entry) => ({\n      family: \"edgeCardinality\" as const,\n      target: entry.target,\n      edgeIds: entry.edgeIds.toSorted((left, right) =>\n        compareStrings(left, right),\n      ),\n    }));\n}\n\n/** The declarations the audit reads, one list per family. */\nfunction fenceDeclarations(\n  graph: GraphDef,\n  registry: KindRegistry,\n  graphId: string,\n): ReadConstraintFenceViolationsParams {\n  const uniqueConstraintNames = new Set(\n    Object.values(graph.nodes).flatMap((registration) =>\n      (registration.unique ?? []).map((constraint) => constraint.name),\n    ),\n  );\n  const edgeCardinalities = Object.entries(graph.edges).flatMap(\n    ([edgeKind, registration]): readonly EdgeCardinalityDeclaration[] => {\n      const cardinality = registration.cardinality ?? \"many\";\n      return cardinality === \"many\" ? [] : [{ edgeKind, cardinality }];\n    },\n  );\n  return {\n    graphId,\n    uniqueConstraintNames: [...uniqueConstraintNames],\n    disjointKindPairs: registry.disjointKindPairs(),\n    edgeCardinalities,\n  };\n}\n\n/**\n * THE fence audit. Reads only; reports every claim axis whose population\n * already carries more than one live claimant.\n *\n * @throws ConfigurationError (`CONSTRAINT_FENCE_AUDIT_UNSUPPORTED`) when the\n *   backend cannot run the audit. Returning an empty report would be\n *   indistinguishable from a clean database, which is the one answer a\n *   diagnostic must never fabricate.\n */\nexport async function verifyConstraintFences(\n  context: VerifyConstraintFencesContext,\n): Promise<readonly ConstraintFenceViolation[]> {\n  const audit = context.backend.readConstraintFenceViolations;\n  if (audit === undefined) {\n    throw new ConfigurationError(\n      \"This backend cannot audit constraint fences: it does not implement \" +\n        \"`readConstraintFenceViolations`.\",\n      { code: \"CONSTRAINT_FENCE_AUDIT_UNSUPPORTED\" },\n      {\n        suggestion:\n          \"Run the audit through a backend built by `createSqliteBackend` or \" +\n          \"`createPostgresBackend`, or implement the member.\",\n      },\n    );\n  }\n  const declarations = fenceDeclarations(\n    context.graph,\n    context.registry,\n    context.graphId,\n  );\n  const rows: ConstraintFenceViolationRows = await audit(declarations);\n  const groups = uniquenessAxisGroups(context.graph, context.registry);\n  return [\n    ...uniquenessViolations(rows.contendedUniqueRows, groups, context.graphId),\n    ...disjointnessViolations(\n      rows.disjointOverlaps,\n      context.registry,\n      context.graphId,\n    ),\n    ...edgeCardinalityViolations(rows.contendedEdgeRows, context.graphId),\n  ].toSorted((left, right) => compareClaimTargets(left.target, right.target));\n}\n","import { EDGE_IDENTITY_MISMATCH_CODE, ValidationError } from \"../../errors\";\n\n/** The immutable identity a collection-scoped edge write expects to own. */\nexport type EdgeIdentityExpectation = Readonly<{\n  kind: string;\n  fromKind?: string;\n  fromId?: string;\n  toKind?: string;\n  toId?: string;\n}>;\n\nexport type EdgeIdentity = Readonly<{\n  kind: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n}>;\n\nexport function edgeIdentityFromRow(row: {\n  kind: string;\n  from_kind: string;\n  from_id: string;\n  to_kind: string;\n  to_id: string;\n}): EdgeIdentity {\n  return {\n    kind: row.kind,\n    fromKind: row.from_kind,\n    fromId: row.from_id,\n    toKind: row.to_kind,\n    toId: row.to_id,\n  };\n}\n\n/**\n * The single owner of edge-id ownership validation.\n *\n * Edge ids are graph-global, while public collections are kind-scoped and an\n * edge's endpoints are immutable. Every collection write calls this predicate\n * before it consumes a row.\n *\n * This check alone does NOT close the window between reading a row and writing\n * it: a re-read is a separate statement, and until the write commits, another\n * session's `hardDelete(id)` + recreate can re-point that id (PostgreSQL READ\n * COMMITTED re-resolves it; SQLite's `BEGIN IMMEDIATE` does not). What closes\n * the window is that the write statement carries the same expected kind in its\n * own `WHERE` (see {@link UpdateEdgeParams}'s `kind`), so this predicate and\n * the write agree on which row they mean by construction rather than by\n * repetition. A row that fails the predicate here is refused before any write;\n * a row that changes afterwards makes the write match nothing, and the caller\n * hears the same refusal from\n * {@link file://./edge-write-fences.ts withUnmatchedEdgeUpdateRefusal}.\n */\nexport function assertEdgeIdentityMatches(\n  id: string,\n  expected: EdgeIdentityExpectation,\n  actual: EdgeIdentity,\n  operation: \"update\" | \"delete\" | \"hardDelete\",\n): void {\n  const mismatches = [\n    expected.kind === actual.kind ? undefined : \"kind\",\n    expected.fromKind === undefined || expected.fromKind === actual.fromKind ?\n      undefined\n    : \"from.kind\",\n    expected.fromId === undefined || expected.fromId === actual.fromId ?\n      undefined\n    : \"from.id\",\n    expected.toKind === undefined || expected.toKind === actual.toKind ?\n      undefined\n    : \"to.kind\",\n    expected.toId === undefined || expected.toId === actual.toId ?\n      undefined\n    : \"to.id\",\n  ].filter((path): path is string => path !== undefined);\n  if (mismatches.length === 0) return;\n\n  throw new ValidationError(\n    `Edge \"${id}\" belongs to ${actual.kind} ` +\n      `(${actual.fromKind}/${actual.fromId} -> ${actual.toKind}/${actual.toId}), ` +\n      `not ${expected.kind}` +\n      (expected.fromKind === undefined ?\n        \".\"\n      : ` (${expected.fromKind}/${expected.fromId} -> ${expected.toKind}/${expected.toId}).`),\n    {\n      entityType: \"edge\",\n      kind: expected.kind,\n      operation,\n      id,\n      issues: mismatches.map((path) => ({\n        path,\n        message: \"The edge id resolves to a different immutable identity\",\n        code: EDGE_IDENTITY_MISMATCH_CODE,\n      })),\n    },\n    {\n      suggestion:\n        \"Use the edge collection and endpoints that created this id, or choose a new id.\",\n    },\n  );\n}\n","import {\n  isCanonicalIsoDate,\n  preservesImmutableLowerBound,\n  statedBoundMatchesStored,\n} from \"../../utils/date\";\nimport { validityEndAfterMutation } from \"../validity-end\";\n\n/**\n * Coalesce dirty-check shared by `upsertById` / `bulkUpsertById`.\n *\n * A store created with `coalesceUnchangedUpserts` skips the write for an upsert\n * whose validated props already equal the row's stored props (see\n * {@link file://../types.ts BaseStoreOptions.coalesceUnchangedUpserts}).\n */\n\n/**\n * Result of the dirty check: the props the update WOULD persist (input merged\n * over the current props and run through the kind's Zod schema), and whether\n * they equal the current props (so the write can be skipped). `validatedProps`\n * doubles as the batch-local running value a later same-id item is compared\n * against in the bulk path.\n */\nexport type UpsertDirtyCheck = Readonly<{\n  validatedProps: Record<string, unknown>;\n  unchanged: boolean;\n}>;\n\n/**\n * The seam collections call to run the dirty check. Present only when the store\n * enabled coalescing; its absence is the off switch. `existingProps` is the\n * PARSED current props — the prefetched row's, or the batch-local running value\n * for a repeated id.\n */\nexport type UpsertDirtyCheckFunction = (\n  kind: string,\n  id: string,\n  existingProps: Record<string, unknown>,\n  inputProps: Record<string, unknown>,\n) => UpsertDirtyCheck;\n\n/**\n * The ids that appear more than once in one bulk-upsert batch.\n *\n * A repeated id is the only case where a queued write's batch-local running\n * value is ever read, and computing a queued CREATE's running value costs a Zod\n * parse the insert will repeat. Batches with all-distinct ids — the common case —\n * skip that parse entirely.\n */\nexport function findRepeatedUpsertIds(\n  items: readonly Readonly<{ id: string }>[],\n): Set<string> {\n  const seen = new Set<string>();\n  const repeated = new Set<string>();\n  for (const item of items) {\n    if (seen.has(item.id)) repeated.add(item.id);\n    seen.add(item.id);\n  }\n  return repeated;\n}\n\n/**\n * A validity window as a row carries it, in the column names a backend returns —\n * so a prefetched row is comparable without being reshaped.\n *\n * `undefined` is a known open-left bound. A private symbol is an UNKNOWN\n * prediction for a queued create whose backend will choose the lower bound.\n * Keeping those distinct prevents a later explicit open-left request from\n * coalescing against an earlier, not-yet-stamped create.\n */\nconst UNKNOWN_VALIDITY_LOWER_BOUND = Symbol(\"unknownValidityLowerBound\");\n\nexport type UpsertWindow = Readonly<{\n  valid_from: string | typeof UNKNOWN_VALIDITY_LOWER_BOUND | undefined;\n  valid_to: string | undefined;\n}>;\n\n/** The window bounds an upsert item may request. */\ntype RequestedWindow = Readonly<{\n  validFrom?: string | null;\n  validTo?: string;\n  clearValidTo?: true;\n  onImmutableLowerBound?: \"preserve\" | \"refuse\";\n}>;\n\n/** A window to compare against — a row, or an {@link UpsertWindow}. */\ntype CurrentWindow = Readonly<{\n  valid_from?: string | typeof UNKNOWN_VALIDITY_LOWER_BOUND | undefined;\n  valid_to?: string | undefined;\n}>;\n\n/**\n * Whether one requested window endpoint differs from the stored one, compared as\n * instants rather than as driver text. An omitted request never changes anything.\n *\n * A NON-CANONICAL request always counts as a change, so it reaches the write path\n * that rejects it. Coalescing must not decide whether malformed input is\n * reported: a bound the write path refuses has to be refused whether or not this\n * store happens to coalesce, or the flag silently turns a `ValidationError` into\n * a no-op. That covers the unparseable string and the merely non-canonical one\n * alike — `\"2100-06-01T00:00:00Z\"` names the same instant as the stored\n * `\"2100-06-01T00:00:00.000Z\"` and is still refused by every write path, because\n * a variable-width bound mis-sorts against an `asOf` coordinate.\n *\n * Counting it as a change is also what lets the comparison canonicalize the\n * STORED side only ({@link statedBoundMatchesStored}): past this guard the\n * requested value is known canonical, or explicitly open-left for `validFrom`.\n * The upper bound retains its separate set/clear protocol: null must reach the\n * write path for rejection even when the stored upper bound is absent.\n */\nfunction windowFieldChanges(\n  field: \"validFrom\" | \"validTo\",\n  requested: string | null | undefined,\n  stored: string | typeof UNKNOWN_VALIDITY_LOWER_BOUND | undefined,\n): boolean {\n  if (requested === undefined) {\n    return false;\n  }\n  if (\n    stored === UNKNOWN_VALIDITY_LOWER_BOUND ||\n    (requested === null ?\n      field !== \"validFrom\"\n    : !isCanonicalIsoDate(requested))\n  ) {\n    return true;\n  }\n  return !statedBoundMatchesStored(requested, stored);\n}\n\n/** Whether the requested lower bound prevents an unchanged upsert from coalescing. */\nfunction lowerBoundRequiresWrite(\n  requested: RequestedWindow | undefined,\n  stored: string | typeof UNKNOWN_VALIDITY_LOWER_BOUND | undefined,\n): boolean {\n  const requestedValidFrom = requested?.validFrom;\n  if (!preservesImmutableLowerBound(requested?.onImmutableLowerBound)) {\n    return windowFieldChanges(\"validFrom\", requestedValidFrom, stored);\n  }\n  return (\n    requestedValidFrom !== undefined &&\n    requestedValidFrom !== null &&\n    !isCanonicalIsoDate(requestedValidFrom)\n  );\n}\n\n/**\n * Whether an upsert item's requested window differs from the one its target\n * already holds.\n *\n * THE window comparison: `upsertById` and both `bulkUpsertById` paths call this\n * one function, so a re-stated window coalesces identically whether it arrives\n * alone or inside a batch. Comparing as INSTANTS is what keeps one backend from\n * writing where the other coalesces — the stored value arrives as the driver\n * rendered it, and the dialects do not render a timestamp the same way (SQLite\n * returns the written text; a Postgres driver renders `timestamptz` its own way,\n * and one that hands back a zoned string rather than a `Date` hands back text\n * that is equivalent to the canonical form without being identical to it).\n */\nexport function upsertWindowChanges(\n  requested: RequestedWindow | undefined,\n  current: CurrentWindow,\n): boolean {\n  return (\n    lowerBoundRequiresWrite(requested, current.valid_from) ||\n    (requested?.clearValidTo === true &&\n      validityEndAfterMutation(requested, current.valid_to) !==\n        current.valid_to) ||\n    (requested?.clearValidTo === true && requested.validTo !== undefined) ||\n    windowFieldChanges(\"validTo\", requested?.validTo, current.valid_to)\n  );\n}\n\n/**\n * The window a queued upsert CREATE — or a resurrection, which asserts a\n * COMPLETE window — leaves the row holding, for a later item with the same id in\n * the same batch to compare against.\n *\n * An explicit `null` predicts a known open-left row (`undefined`). Omission\n * leaves the lower bound unknown: the backend can stamp its instant or\n * choose no bound for a born-ended write. A later item stating any bound must\n * therefore reach the write path, which compares against the actual row.\n */\nexport function windowAfterUpsertCreate(\n  requested: RequestedWindow,\n): UpsertWindow {\n  return {\n    valid_from:\n      requested.validFrom === null ?\n        undefined\n      : (requested.validFrom ?? UNKNOWN_VALIDITY_LOWER_BOUND),\n    valid_to: validityEndAfterMutation(requested, undefined),\n  };\n}\n\n/**\n * The window a queued upsert UPDATE over a live row leaves it holding: the lower\n * bound is history and never moves (only a resurrection rewrites `valid_from`),\n * and the upper bound moves only when the item names one.\n */\nexport function windowAfterUpsertUpdate(\n  current: UpsertWindow,\n  requested: RequestedWindow,\n): UpsertWindow {\n  return {\n    valid_from: current.valid_from,\n    valid_to: validityEndAfterMutation(requested, current.valid_to),\n  };\n}\n\n/**\n * Whether a single upsert may be coalesced: coalescing is enabled\n * (`runDirtyCheck` present), the row is live, no explicit temporal override was\n * requested, and the props are unchanged. The dirty check runs last (only when\n * the cheap preconditions pass).\n *\n * A throw from the dirty check is treated as \"do not coalesce\". The check\n * validates the input, so it can throw a `ValidationError`; that must not fail\n * HERE, ahead of the operation hooks. Falling through to the normal write path\n * re-validates inside the hooked pipeline, which raises the error with correct\n * `onError` wiring (matching flag-off) — the error is re-raised there, not\n * swallowed.\n */\nexport function shouldCoalesceUpsert(\n  existing: Readonly<{\n    deleted_at: string | undefined;\n    valid_from?: string | typeof UNKNOWN_VALIDITY_LOWER_BOUND | undefined;\n    valid_to?: string | undefined;\n  }>,\n  options:\n    | Readonly<{\n        validFrom?: string | null;\n        validTo?: string;\n        clearValidTo?: true;\n      }>\n    | undefined,\n  runDirtyCheck: (() => UpsertDirtyCheck) | undefined,\n): boolean {\n  // An explicit temporal override blocks coalescing ONLY when it would\n  // change the stored window: merge commits pass the staged survivor's window\n  // on every canonical write, and a graph merge passes an inherited row's\n  // reconciled end-of-validity, so a row written back with the window it\n  // already holds (identical props AND identical window) must still coalesce\n  // instead of rewriting version, history, and revision state.\n  const windowChanges = upsertWindowChanges(options, existing);\n  if (\n    runDirtyCheck === undefined ||\n    existing.deleted_at !== undefined ||\n    windowChanges\n  ) {\n    return false;\n  }\n  try {\n    return runDirtyCheck().unchanged;\n  } catch {\n    return false;\n  }\n}\n","/**\n * EdgeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific edge type.\n */\nimport { type z } from \"zod\";\n\nimport { endpointSetReadMembers } from \"../../backend/capabilities/bind\";\nimport {\n  type BATCH_POINT_READ,\n  type ENDPOINT_SET_READ,\n} from \"../../backend/capabilities/bundle-registry\";\nimport { type BundleVerdictOf } from \"../../backend/capabilities/resolve\";\nimport {\n  type EdgeEndpointSide,\n  type EdgeRow as BackendEdgeRow,\n  type FindEdgesByKindParams,\n  type GraphBackend,\n  rowPropsToObject,\n  runOptionallyInTransaction,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type TemporalMode } from \"../../core/types\";\nimport {\n  ConfigurationError,\n  UnsupportedPredicateError,\n  ValidationError,\n} from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport type { BatchableQuery } from \"../../query/builder/types\";\nimport { groupBy } from \"../../utils/array\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { encodeTupleKey } from \"../../utils/tuple-key\";\nimport { getEdgeRowsByIds } from \"../edge-fetch\";\nimport {\n  assertEdgeIdentityMatches,\n  type EdgeIdentity,\n  type EdgeIdentityExpectation,\n  edgeIdentityFromRow,\n} from \"../operations/edge-identity\";\nimport {\n  type ResolvedMutationSetAttempt,\n  runResolvedMutationSetConverging,\n} from \"../resolved-mutation-set\";\nimport { type EdgeRow } from \"../row-mappers\";\nimport {\n  type CreateEdgeInput,\n  type Edge,\n  type EdgeBulkFindEndpointOptions,\n  type EdgeCollection,\n  type EdgeFindByEndpointsOptions,\n  type EdgeGetOrCreateByEndpointsOptions,\n  type EdgeGetOrCreateByEndpointsResult,\n  type GetOrCreateAction,\n  type IfExistsMode,\n  type NodeRef,\n  type QueryOptions,\n  type ValidityEndMutation,\n} from \"../types\";\nimport {\n  assertClearValidToSupported,\n  assertValidityEndMutation,\n} from \"../validity-end\";\nimport {\n  findRepeatedUpsertIds,\n  type UpsertDirtyCheck,\n  type UpsertDirtyCheckFunction,\n  type UpsertWindow,\n  upsertWindowChanges,\n  windowAfterUpsertCreate,\n  windowAfterUpsertUpdate,\n} from \"./coalesce\";\nimport {\n  resolveTemporalReadParams,\n  type TemporalReadParams,\n} from \"./temporal-read-params\";\n\n/**\n * Narrows unparameterized Edge to Edge<E>.\n * Safe: props are validated by Zod at creation/update boundaries.\n */\nfunction narrowEdge<E extends AnyEdgeType>(edge: Edge): Edge<E> {\n  return edge as Edge<E>;\n}\n\n/**\n * Narrows a readonly Edge array to Edge<E>[].\n */\nfunction narrowEdges<E extends AnyEdgeType>(edges: readonly Edge[]): Edge<E>[] {\n  return edges as Edge<E>[];\n}\n\n/**\n * Config for creating an EdgeCollection.\n */\nexport type EdgeCollectionConfig = Readonly<{\n  graphId: string;\n  kind: string;\n  backend: GraphBackend | TransactionBackend;\n  /** Threaded `batchPointRead` verdict — never re-resolved here. */\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  /** Threaded endpoint-set read verdict, resolved against the graph backend. */\n  endpointSetRead: BundleVerdictOf<typeof ENDPOINT_SET_READ>;\n  defaultTemporalMode: TemporalMode;\n  rowToEdge: (row: EdgeRow) => Edge;\n  /** See EdgeOperations.maybeRefreshStatisticsAfterBulk. */\n  maybeRefreshStatisticsAfterBulk?:\n    ((rowCount: number) => Promise<void>) | undefined;\n  executeCreate: (\n    input: CreateEdgeInput,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Edge>;\n  executeCreateNoReturnBatch: (\n    inputs: readonly CreateEdgeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeCreateBatch: (\n    inputs: readonly CreateEdgeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Edge[]>;\n  executeUpdate: (\n    input: {\n      id: string;\n      identity: EdgeIdentityExpectation;\n      props: Partial<Record<string, unknown>>;\n      validTo?: string;\n      clearValidTo?: true;\n    },\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Edge>;\n  executeUpsertUpdateBatch: (\n    entries: readonly EdgeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Edge[]>;\n  executeResolvedMutationSet: (\n    creates: readonly CreateEdgeInput[],\n    updates: readonly EdgeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<\n    ResolvedMutationSetAttempt<\n      Readonly<{ created: readonly Edge[]; updated: readonly Edge[] }>\n    >\n  >;\n  /** See EdgeOperations.upsertDirtyCheck. */\n  upsertDirtyCheck?: UpsertDirtyCheckFunction;\n  executeDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeDeleteBatch: (\n    kind: string,\n    ids: readonly string[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeHardDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  temporalRowMatcher: (options?: QueryOptions) => (row: EdgeRow) => boolean;\n  createQuery?: () => QueryBuilder<GraphDef>;\n  executeGetOrCreateByEndpoints: (\n    kind: string,\n    fromKind: string,\n    fromId: string,\n    toKind: string,\n    toId: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      ifExists?: IfExistsMode;\n      validFrom?: string | null;\n      validTo?: string;\n      clearValidTo?: true;\n      onImmutableLowerBound?: \"preserve\" | \"refuse\";\n    }>,\n  ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>>;\n  executeBulkGetOrCreateByEndpoints: (\n    kind: string,\n    items: readonly Readonly<{\n      fromKind: string;\n      fromId: string;\n      toKind: string;\n      toId: string;\n      props: Record<string, unknown>;\n      validFrom?: string | null;\n      validTo?: string;\n      clearValidTo?: true;\n      onImmutableLowerBound?: \"preserve\" | \"refuse\";\n    }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      ifExists?: IfExistsMode;\n    }>,\n  ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]>;\n  executeFindByEndpoints: (\n    kind: string,\n    fromKind: string,\n    fromId: string,\n    toKind: string,\n    toId: string,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      props?: Record<string, unknown>;\n      excludeDeleted?: boolean;\n      temporalMode?: TemporalMode;\n      asOf?: string;\n    }>,\n  ) => Promise<Edge | undefined>;\n}>;\n\nfunction buildCreateEdgeInput(\n  kind: string,\n  from: NodeRef,\n  to: NodeRef,\n  props: Record<string, unknown>,\n  options?: Readonly<{\n    id?: string;\n    validFrom?: string | null;\n    validTo?: string;\n  }>,\n): CreateEdgeInput {\n  const input: {\n    kind: string;\n    id?: string;\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    props: Record<string, unknown>;\n    validFrom?: string | null;\n    validTo?: string;\n  } = {\n    kind,\n    fromKind: from.kind,\n    fromId: from.id,\n    toKind: to.kind,\n    toId: to.id,\n    props,\n  };\n  if (options?.id !== undefined) input.id = options.id;\n  if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  return input;\n}\n\n/** The scalar endpoint predicate of a `findFrom` / `findTo` read. */\ntype EdgeEndpointPredicate =\n  | Readonly<{ fromKind: string; fromId: string }>\n  | Readonly<{ toKind: string; toId: string }>;\n\ntype EdgeUpdateInput = Readonly<{\n  id: string;\n  identity: EdgeIdentityExpectation;\n  props: Partial<Record<string, unknown>>;\n  validTo?: string;\n  clearValidTo?: true;\n}>;\n\n/**\n * Update input for the internal upsert path, which owns the WHOLE validity\n * window: a resurrecting upsert rewrites both endpoints, so it must be able to\n * carry `validFrom` as well as `validTo`. Dropping `validFrom` here would leave\n * the backend defaulting the lower bound to the resurrection instant while the\n * caller's (possibly already past) `validTo` stayed — an inverted window that\n * no read coordinate can observe.\n *\n * The public `update()` API cannot reach this member: its options type exposes\n * `validTo` only, and it builds its input through {@link buildUpdateEdgeInput}.\n * `bulkUpsertById` and endpoint-matched upserts route through this input because\n * both may accept `validFrom`; only the endpoint surface currently exposes the\n * create/resurrection-only policy.\n */\nexport type UpsertUpdateEdgeInput = EdgeUpdateInput &\n  Readonly<{\n    validFrom?: string | null;\n    onImmutableLowerBound?: \"preserve\" | \"refuse\";\n  }>;\n\nexport type EdgeUpsertUpdateBatchEntry = Readonly<{\n  input: UpsertUpdateEdgeInput;\n  clearDeleted: boolean;\n  existing?: BackendEdgeRow;\n}>;\n\nfunction buildUpdateEdgeInput(\n  kind: string,\n  id: string,\n  props: Record<string, unknown>,\n  options?: ValidityEndMutation,\n): EdgeUpdateInput {\n  const input: {\n    id: string;\n    identity: EdgeIdentityExpectation;\n    props: Partial<Record<string, unknown>>;\n    validTo?: string;\n    clearValidTo?: true;\n  } = { id, identity: { kind }, props };\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  if (options?.clearValidTo === true) input.clearValidTo = true;\n  return input;\n}\n\n/** Builds an {@link UpsertUpdateEdgeInput} — see that type for why upsert alone carries `validFrom`. */\nfunction buildUpsertUpdateEdgeInput(\n  kind: string,\n  id: string,\n  from: NodeRef,\n  to: NodeRef,\n  props: Record<string, unknown>,\n  options?: Readonly<{\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n  }>,\n): UpsertUpdateEdgeInput {\n  const input: {\n    id: string;\n    identity: EdgeIdentityExpectation;\n    props: Partial<Record<string, unknown>>;\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n  } = {\n    id,\n    identity: {\n      kind,\n      fromKind: from.kind,\n      fromId: from.id,\n      toKind: to.kind,\n      toId: to.id,\n    },\n    props,\n  };\n  if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  if (options?.clearValidTo === true) input.clearValidTo = true;\n  return input;\n}\n\n/**\n * Composite bucket key for an endpoint. Node ids are unique per kind, not\n * globally, so the kind is part of the key — the same key shape the endpoint\n * predicate itself uses (`from_kind` + `from_id`).\n */\nfunction endpointKey(endpointKind: string, id: string): string {\n  return encodeTupleKey([endpointKind, id]);\n}\n\n/**\n * Buckets endpoint refs into one id list per kind, preserving input order.\n * Repeated ids are left in place — the backend dedupes an endpoint set before\n * splitting it into bind-budget chunks, which is the only place duplicates\n * could do harm.\n */\nfunction groupEndpointIdsByKind(\n  references: readonly NodeRef[],\n): Map<string, string[]> {\n  const referencesByKind = groupBy(references, (ref) => ref.kind);\n  return new Map(\n    [...referencesByKind].map(([endpointKind, group]) => [\n      endpointKind,\n      group.map((ref) => ref.id),\n    ]),\n  );\n}\n\n/**\n * Validates the caller-facing fan-out cap. This runs in the collection rather\n * than only in the backend because the cap is not always pushed into SQL: on a\n * backend without window functions it is applied in JS, where an invalid value\n * would silently truncate instead of failing.\n */\nfunction assertLimitPerInput(\n  kind: string,\n  limitPerInput: number | undefined,\n): void {\n  if (limitPerInput === undefined) return;\n  if (Number.isInteger(limitPerInput) && limitPerInput > 0) return;\n  throw new ValidationError(\n    \"bulk endpoint reads require limitPerInput to be a positive integer\",\n    {\n      entityType: \"edge\",\n      kind,\n      issues: [\n        {\n          path: \"limitPerInput\",\n          message: `Expected a positive integer, received ${String(limitPerInput)}`,\n          code: \"invalid_value\",\n        },\n      ],\n    },\n  );\n}\n\nfunction mapBulkEdgeInputs(\n  kind: string,\n  items: readonly Readonly<{\n    from: NodeRef;\n    to: NodeRef;\n    props?: Record<string, unknown>;\n    id?: string;\n    validFrom?: string | null;\n    validTo?: string;\n  }>[],\n): CreateEdgeInput[] {\n  return items.map((item) =>\n    buildCreateEdgeInput(kind, item.from, item.to, item.props ?? {}, item),\n  );\n}\n\n/**\n * Creates an EdgeCollection for a specific edge type.\n */\nexport function createEdgeCollection<\n  G extends GraphDef,\n  K extends keyof G[\"edges\"] & string,\n>(config: EdgeCollectionConfig): EdgeCollection<G[\"edges\"][K][\"type\"]> {\n  type E = G[\"edges\"][K][\"type\"];\n\n  const {\n    graphId,\n    kind,\n    backend,\n    batchPointRead,\n    defaultTemporalMode,\n    rowToEdge,\n    executeCreate: executeEdgeCreate,\n    executeCreateNoReturnBatch: executeEdgeCreateNoReturnBatch,\n    executeCreateBatch: executeEdgeCreateBatch,\n    executeUpdate: executeEdgeUpdate,\n    executeUpsertUpdateBatch: executeEdgeUpsertUpdateBatch,\n    executeResolvedMutationSet: executeEdgeResolvedMutationSet,\n    executeDelete: executeEdgeDelete,\n    executeDeleteBatch: executeEdgeDeleteBatch,\n    executeHardDelete: executeEdgeHardDelete,\n    temporalRowMatcher,\n  } = config;\n\n  const mapRows = (rows: readonly EdgeRow[]): Edge<E>[] =>\n    rows.map((row) => narrowEdge<E>(rowToEdge(row)));\n\n  /**\n   * Builds the `findEdgesByKind` params for an endpoint lookup, resolving\n   * the temporal mode the same way `find` / `getById` do: the per-call\n   * `options` win, falling back to the graph's default mode. Keeps\n   * `findFrom` / `findTo` honoring the temporal model instead of silently\n   * returning every non-deleted edge.\n   *\n   * The scalar and set forms of the endpoint predicate share this builder, so\n   * `bulkFindFrom` / `bulkFindTo` cannot resolve a different coordinate than\n   * the singleton reads they widen.\n   */\n  function buildEndpointFindParams(\n    endpoint: EdgeEndpointPredicate,\n    temporal: TemporalReadParams,\n  ): FindEdgesByKindParams {\n    return { graphId, kind, ...endpoint, ...temporal };\n  }\n\n  async function findEdgesFrom(\n    from: NodeRef,\n    target: GraphBackend | TransactionBackend,\n    options?: QueryOptions,\n  ): Promise<Edge<E>[]> {\n    const rows = await target.findEdgesByKind(\n      buildEndpointFindParams(\n        { fromKind: from.kind, fromId: from.id },\n        resolveTemporalReadParams(options, defaultTemporalMode),\n      ),\n    );\n    return mapRows(rows);\n  }\n\n  async function findEdgesTo(\n    to: NodeRef,\n    target: GraphBackend | TransactionBackend,\n    options?: QueryOptions,\n  ): Promise<Edge<E>[]> {\n    const rows = await target.findEdgesByKind(\n      buildEndpointFindParams(\n        { toKind: to.kind, toId: to.id },\n        resolveTemporalReadParams(options, defaultTemporalMode),\n      ),\n    );\n    return mapRows(rows);\n  }\n\n  /**\n   * Shared implementation of `bulkFindFrom` / `bulkFindTo`: `findEdgesFrom` /\n   * `findEdgesTo` with the endpoint equality widened to set membership.\n   *\n   * The edge relation's system index is keyed\n   * `(graph_id, from_kind, from_id, kind, ...)`, so the id set is issued per\n   * endpoint KIND — a set within one kind is a prefix seek, while mixing kinds\n   * would force a scan. Inputs of a single kind therefore cost one statement\n   * per bind-budget chunk rather than one statement per endpoint.\n   */\n  async function findEdgesByEndpointSet(\n    side: EdgeEndpointSide,\n    references: readonly NodeRef[],\n    options?: EdgeBulkFindEndpointOptions,\n  ): Promise<Edge<E>[][]> {\n    if (references.length === 0) return [];\n\n    const method = side === \"from\" ? \"bulkFindFrom\" : \"bulkFindTo\";\n    const endpointReadBinding = endpointSetReadMembers(\n      backend,\n      config.endpointSetRead,\n    );\n    const endpointRead = endpointReadBinding.findEdgesByEndpointSet;\n    if (endpointRead === undefined) {\n      throw new ConfigurationError(\n        `store.edges.${kind}.${method}() requires a backend that can read a set of ` +\n          `endpoints with set-oriented statements, and this backend does not implement ` +\n          `findEdgesByEndpointSet.`,\n        {\n          code: \"ENDPOINT_SET_READ_UNSUPPORTED\",\n          backend: backend.dialect,\n          capability: \"findEdgesByEndpointSet\",\n          kind,\n          operation: method,\n        },\n        {\n          suggestion:\n            `Falling back to one findFrom/findTo per endpoint is deliberately NOT done here: ` +\n            `a caller reaching for a bulk endpoint read is asking for a set-oriented read, and ` +\n            `silently issuing N singleton statements is the cost surprise this method exists ` +\n            `to avoid. Loop over ` +\n            `findFrom/findTo explicitly if that trade is acceptable.`,\n        },\n      );\n    }\n\n    const limitPerInput = options?.limitPerInput;\n    assertLimitPerInput(kind, limitPerInput);\n\n    // Resolve the read coordinate ONCE. `current` mode materializes an `asOf`\n    // of \"now\", so resolving per endpoint kind would let a mixed-kind read\n    // straddle a validity boundary and return an internally inconsistent\n    // answer from a single logical read.\n    const temporal = resolveTemporalReadParams(options, defaultTemporalMode);\n\n    // The per-endpoint cap is pushed into SQL when the engine has window\n    // functions; otherwise the rows arrive uncapped and the JS slice below\n    // (which every path applies) keeps the same leading edges.\n    const limitPerEndpoint =\n      limitPerInput !== undefined && backend.capabilities.windowFunctions ?\n        { limitPerEndpoint: limitPerInput }\n      : {};\n\n    const edgesByEndpoint = new Map<string, Edge<E>[]>();\n    for (const [endpointKind, endpointIds] of groupEndpointIdsByKind(\n      references,\n    )) {\n      const rows = await endpointRead({\n        graphId,\n        kind,\n        side,\n        endpointKind,\n        endpointIds,\n        ...limitPerEndpoint,\n        ...temporal,\n      });\n      for (const edge of mapRows(rows)) {\n        const key =\n          side === \"from\" ?\n            endpointKey(edge.fromKind, edge.fromId)\n          : endpointKey(edge.toKind, edge.toId);\n        const bucket = edgesByEndpoint.get(key);\n        if (bucket === undefined) edgesByEndpoint.set(key, [edge]);\n        else bucket.push(edge);\n      }\n    }\n\n    // Each input position gets its own array: repeated inputs share an\n    // endpoint bucket, and callers must not see one input's mutation in\n    // another's.\n    return references.map((ref) => {\n      const bucket = edgesByEndpoint.get(endpointKey(ref.kind, ref.id)) ?? [];\n      return limitPerInput === undefined ?\n          [...bucket]\n        : bucket.slice(0, limitPerInput);\n    });\n  }\n\n  function buildFindByEndpointsOptions(\n    options?: EdgeFindByEndpointsOptions<E>,\n    temporal?: QueryOptions,\n  ): Readonly<{\n    matchOn?: readonly string[];\n    props?: Record<string, unknown>;\n    excludeDeleted?: boolean;\n    temporalMode?: TemporalMode;\n    asOf?: string;\n  }> {\n    const result: {\n      matchOn?: readonly string[];\n      props?: Record<string, unknown>;\n      excludeDeleted?: boolean;\n      temporalMode?: TemporalMode;\n      asOf?: string;\n    } = { ...resolveTemporalReadParams(temporal, defaultTemporalMode) };\n    if (options?.matchOn !== undefined)\n      result.matchOn = options.matchOn as readonly string[];\n    if (options?.props !== undefined) result.props = options.props;\n    return result;\n  }\n\n  return {\n    async create(\n      from: NodeRef,\n      to: NodeRef,\n      props?: z.input<E[\"schema\"]>,\n      options?: Readonly<{\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>,\n    ): Promise<Edge<E>> {\n      const result = await executeEdgeCreate(\n        buildCreateEdgeInput(kind, from, to, props ?? {}, options),\n        backend,\n      );\n      return narrowEdge<E>(result);\n    },\n\n    async getById(\n      id: string,\n      options?: QueryOptions,\n    ): Promise<Edge<E> | undefined> {\n      const row = await backend.getEdge(graphId, id);\n      if (!row) return undefined;\n      if (row.kind !== kind) return undefined; // Edge is a different type\n      if (!temporalRowMatcher(options)(row)) return undefined;\n      return narrowEdge<E>(rowToEdge(row));\n    },\n\n    async getByIds(\n      ids: readonly string[],\n      options?: QueryOptions,\n    ): Promise<readonly (Edge<E> | undefined)[]> {\n      if (ids.length === 0) return [];\n\n      const rowsById = await getEdgeRowsByIds(\n        backend,\n        batchPointRead,\n        graphId,\n        ids,\n      );\n      // Resolve the coordinate once so the whole batch observes one instant.\n      const matches = temporalRowMatcher(options);\n      return ids.map((id) => {\n        const row = rowsById.get(id);\n        if (!row) return;\n        if (row.kind !== kind) return;\n        if (!matches(row)) return;\n        return narrowEdge<E>(rowToEdge(row));\n      });\n    },\n\n    async update(\n      id: string,\n      props: Partial<z.input<E[\"schema\"]>>,\n      options?: ValidityEndMutation,\n    ): Promise<Edge<E>> {\n      const result = await executeEdgeUpdate(\n        buildUpdateEdgeInput(kind, id, props, options),\n        backend,\n      );\n      return narrowEdge<E>(result);\n    },\n\n    async findFrom(from: NodeRef, options?: QueryOptions): Promise<Edge<E>[]> {\n      return findEdgesFrom(from, backend, options);\n    },\n\n    async findTo(to: NodeRef, options?: QueryOptions): Promise<Edge<E>[]> {\n      return findEdgesTo(to, backend, options);\n    },\n\n    async bulkFindFrom(\n      froms: readonly NodeRef[],\n      options?: EdgeBulkFindEndpointOptions,\n    ): Promise<readonly Edge<E>[][]> {\n      return findEdgesByEndpointSet(\"from\", froms, options);\n    },\n\n    async bulkFindTo(\n      tos: readonly NodeRef[],\n      options?: EdgeBulkFindEndpointOptions,\n    ): Promise<readonly Edge<E>[][]> {\n      return findEdgesByEndpointSet(\"to\", tos, options);\n    },\n\n    batchFindFrom(\n      from: NodeRef,\n      options?: QueryOptions,\n    ): BatchableQuery<Edge<E>> {\n      return { executeOn: (target) => findEdgesFrom(from, target, options) };\n    },\n\n    batchFindTo(to: NodeRef, options?: QueryOptions): BatchableQuery<Edge<E>> {\n      return { executeOn: (target) => findEdgesTo(to, target, options) };\n    },\n\n    batchFindByEndpoints(\n      from: NodeRef,\n      to: NodeRef,\n      options?: EdgeFindByEndpointsOptions<E>,\n      temporal?: QueryOptions,\n    ): BatchableQuery<Edge<E>> {\n      return {\n        executeOn: async (target) => {\n          const result = await config.executeFindByEndpoints(\n            kind,\n            from.kind,\n            from.id,\n            to.kind,\n            to.id,\n            target,\n            buildFindByEndpointsOptions(options, temporal),\n          );\n          return result === undefined ? [] : [narrowEdge<E>(result)];\n        },\n      };\n    },\n\n    async delete(id: string): Promise<void> {\n      await executeEdgeDelete(kind, id, backend);\n    },\n\n    async hardDelete(id: string): Promise<void> {\n      await executeEdgeHardDelete(kind, id, backend);\n    },\n\n    async find(\n      filter?: Readonly<{\n        from?: NodeRef;\n        to?: NodeRef;\n        limit?: number;\n        offset?: number;\n      }>,\n      temporal?: QueryOptions,\n    ): Promise<Edge<E>[]> {\n      const untypedFilter = filter as Readonly<{ where?: unknown }> | undefined;\n      if (untypedFilter?.where !== undefined) {\n        throw new UnsupportedPredicateError(\n          `store.edges.${kind}.find({ where }) is not supported. ` +\n            `Use store.query().traverse(...).whereEdge(...) for edge property filters.`,\n          { kind, operation: \"find\" },\n        );\n      }\n\n      const params: {\n        graphId: string;\n        kind: string;\n        fromKind?: string;\n        fromId?: string;\n        toKind?: string;\n        toId?: string;\n        limit?: number;\n        offset?: number;\n      } & TemporalReadParams = {\n        graphId,\n        kind,\n        ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n      };\n      if (filter?.from?.kind !== undefined) params.fromKind = filter.from.kind;\n      if (filter?.from?.id !== undefined) params.fromId = filter.from.id;\n      if (filter?.to?.kind !== undefined) params.toKind = filter.to.kind;\n      if (filter?.to?.id !== undefined) params.toId = filter.to.id;\n      if (filter?.limit !== undefined) params.limit = filter.limit;\n      if (filter?.offset !== undefined) params.offset = filter.offset;\n\n      const rows = await backend.findEdgesByKind(params);\n      return mapRows(rows);\n    },\n\n    async count(\n      filter?: Readonly<{\n        from?: NodeRef;\n        to?: NodeRef;\n      }>,\n      temporal?: QueryOptions,\n    ): Promise<number> {\n      const params: {\n        graphId: string;\n        kind: string;\n        fromKind?: string;\n        fromId?: string;\n        toKind?: string;\n        toId?: string;\n      } & TemporalReadParams = {\n        graphId,\n        kind,\n        ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n      };\n      if (filter?.from?.kind !== undefined) params.fromKind = filter.from.kind;\n      if (filter?.from?.id !== undefined) params.fromId = filter.from.id;\n      if (filter?.to?.kind !== undefined) params.toKind = filter.to.kind;\n      if (filter?.to?.id !== undefined) params.toId = filter.to.id;\n\n      return backend.countEdgesByKind(params);\n    },\n\n    async bulkCreate(\n      items: readonly Readonly<{\n        from: NodeRef;\n        to: NodeRef;\n        props?: z.input<E[\"schema\"]>;\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>[],\n    ): Promise<Edge<E>[]> {\n      const batchInputs = mapBulkEdgeInputs(kind, items);\n      const results = await executeEdgeCreateBatch(batchInputs, backend);\n      await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n      return narrowEdges<E>(results);\n    },\n\n    async bulkUpsertById(\n      items: readonly Readonly<{\n        id: string;\n        from: NodeRef;\n        to: NodeRef;\n        props?: z.input<E[\"schema\"]>;\n        validFrom?: string | null;\n        validTo?: string;\n        clearValidTo?: true;\n      }>[],\n    ): Promise<Edge<E>[]> {\n      if (items.length === 0) return [];\n\n      for (const item of items) {\n        assertValidityEndMutation(item, {\n          entityType: \"edge\",\n          kind,\n          id: item.id,\n        });\n        if (item.clearValidTo === true) {\n          assertClearValidToSupported(backend, \"edge\");\n        }\n      }\n\n      const upsertAll = async (\n        target: GraphBackend | TransactionBackend,\n      ): Promise<{ results: Edge<E>[]; mutations: number }> => {\n        const ids = items.map((item) => item.id);\n        const existingMap = await getEdgeRowsByIds(\n          target,\n          batchPointRead,\n          graphId,\n          ids,\n        );\n\n        // Coalesced items are written straight to results (the existing or\n        // last-written edge) and skipped from the write batch; see the node\n        // collection and BaseStoreOptions.coalesceUnchangedUpserts.\n        const results: Edge<E>[] = Array.from({ length: items.length });\n\n        // Bucket items into creates and updates\n        const toCreate: { index: number; input: CreateEdgeInput }[] = [];\n        const toUpdate: {\n          index: number;\n          input: UpsertUpdateEdgeInput;\n          clearDeleted: boolean;\n          existing?: BackendEdgeRow;\n        }[] = [];\n\n        // Batch-local running state per id so a repeated id coalesces against\n        // the props AND validity window earlier items in this batch would write,\n        // preserving last-write-wins — and so a repeated id whose edge does not\n        // exist yet queues ONE create plus an update over it rather than two\n        // creates the create batch rejects as \"already exists\". See the node\n        // collection for the full rationale, including why `props` may be\n        // undefined while `window` is always computed.\n        const pending = new Map<\n          string,\n          {\n            identity: EdgeIdentity;\n            props: Record<string, unknown> | undefined;\n            window: UpsertWindow;\n            sourceIndex: number;\n          }\n        >();\n        const deferred: { index: number; sourceIndex: number }[] = [];\n\n        // See the node collection: only a coalescing store reads a running\n        // value, so only it needs the repeated-id set.\n        const repeatedIds =\n          config.upsertDirtyCheck === undefined ?\n            new Set<string>()\n          : findRepeatedUpsertIds(items);\n\n        /** See the node collection's runDirtyCheck. */\n        function runDirtyCheck(\n          edgeKind: string,\n          id: string,\n          currentProps: Record<string, unknown>,\n          inputProps: Record<string, unknown>,\n        ): UpsertDirtyCheck | undefined {\n          if (config.upsertDirtyCheck === undefined) return undefined;\n          try {\n            return config.upsertDirtyCheck(\n              edgeKind,\n              id,\n              currentProps,\n              inputProps,\n            );\n          } catch {\n            return undefined;\n          }\n        }\n\n        let itemIndex = 0;\n        for (const item of items) {\n          const pendingEntry = pending.get(item.id);\n          const original = existingMap.get(item.id);\n          const inputProps = item.props ?? {};\n\n          if (pendingEntry === undefined && original === undefined) {\n            toCreate.push({\n              index: itemIndex,\n              input: buildCreateEdgeInput(\n                kind,\n                item.from,\n                item.to,\n                inputProps,\n                item,\n              ),\n            });\n            // A create merges over nothing, so the dirty check run against an\n            // EMPTY base is exactly the validated props the insert will store —\n            // needed only when a later copy of this id will compare against it.\n            pending.set(item.id, {\n              identity: {\n                kind,\n                fromKind: item.from.kind,\n                fromId: item.from.id,\n                toKind: item.to.kind,\n                toId: item.to.id,\n              },\n              props:\n                repeatedIds.has(item.id) ?\n                  runDirtyCheck(kind, item.id, {}, inputProps)?.validatedProps\n                : undefined,\n              window: windowAfterUpsertCreate(item),\n              sourceIndex: itemIndex,\n            });\n            itemIndex++;\n            continue;\n          }\n\n          const deletedAt =\n            pendingEntry === undefined ?\n              requireDefined(original).deleted_at\n            : undefined;\n\n          const expectedIdentity: EdgeIdentityExpectation = {\n            kind,\n            fromKind: item.from.kind,\n            fromId: item.from.id,\n            toKind: item.to.kind,\n            toId: item.to.id,\n          };\n          const actualIdentity =\n            pendingEntry === undefined ?\n              edgeIdentityFromRow(requireDefined(original))\n            : pendingEntry.identity;\n          assertEdgeIdentityMatches(\n            item.id,\n            expectedIdentity,\n            actualIdentity,\n            \"update\",\n          );\n\n          const currentProps =\n            pendingEntry === undefined ?\n              rowPropsToObject(requireDefined(original).props)\n            : pendingEntry.props;\n          // The fetched edge carries the authoritative kind (an id may resolve\n          // to a different edge kind than this collection); a queued create is\n          // this collection's kind by construction.\n          const dirty =\n            currentProps === undefined ? undefined : (\n              runDirtyCheck(\n                original?.kind ?? kind,\n                item.id,\n                currentProps,\n                inputProps,\n              )\n            );\n\n          // The window the edge holds going into this item: the prefetched row's,\n          // or the one the batch's last queued write for this id leaves behind.\n          const currentWindow: UpsertWindow =\n            pendingEntry === undefined ?\n              {\n                valid_from: requireDefined(original).valid_from,\n                valid_to: requireDefined(original).valid_to,\n              }\n            : pendingEntry.window;\n\n          // An explicit window blocks coalescing ONLY when it would change the\n          // window already held: merge commits pass the staged survivor's window\n          // on every edge write, so a target edge staged back at itself\n          // (identical props AND identical window) must still coalesce instead of\n          // rewriting history and revision state. The comparison is\n          // shouldCoalesceUpsert's own, which reads both sides as INSTANTS —\n          // comparing the driver's text directly (what this path used to do) let\n          // an identical re-stated window coalesce on one dialect and write on\n          // another.\n          const coalesce =\n            dirty?.unchanged === true &&\n            deletedAt === undefined &&\n            !upsertWindowChanges(item, currentWindow);\n\n          if (coalesce) {\n            if (pendingEntry === undefined) {\n              results[itemIndex] = narrowEdge<E>(\n                rowToEdge(requireDefined(original)),\n              );\n            } else {\n              deferred.push({\n                index: itemIndex,\n                sourceIndex: pendingEntry.sourceIndex,\n              });\n            }\n          } else {\n            toUpdate.push({\n              index: itemIndex,\n              input: buildUpsertUpdateEdgeInput(\n                kind,\n                item.id,\n                item.from,\n                item.to,\n                inputProps,\n                item,\n              ),\n              clearDeleted: deletedAt !== undefined,\n              ...(pendingEntry === undefined && original !== undefined ?\n                { existing: original }\n              : {}),\n            });\n            pending.set(item.id, {\n              identity: actualIdentity,\n              props: dirty?.validatedProps,\n              // A resurrection rewrites both bounds only when it NAMES the lower\n              // one (buildUpdateEdge's clearDeleted leg); omitting `validFrom`\n              // keeps the stored window, exactly like a live-row update.\n              window:\n                deletedAt !== undefined && item.validFrom !== undefined ?\n                  windowAfterUpsertCreate(item)\n                : windowAfterUpsertUpdate(currentWindow, item),\n              sourceIndex: itemIndex,\n            });\n          }\n          itemIndex++;\n        }\n\n        const createInputs = toCreate.map((entry) => entry.input);\n        const updateEntries = toUpdate.map((entry) => ({\n          input: entry.input,\n          clearDeleted: entry.clearDeleted,\n          ...(entry.existing === undefined ? {} : { existing: entry.existing }),\n        }));\n        const mutationAttempt = await executeEdgeResolvedMutationSet(\n          createInputs,\n          updateEntries,\n          target,\n        );\n        if (mutationAttempt.outcome === \"unsupported\") {\n          if (toCreate.length > 0) {\n            const created = await executeEdgeCreateBatch(createInputs, target);\n            for (const [index, entry] of toCreate.entries()) {\n              results[entry.index] = narrowEdge<E>(\n                requireDefined(created[index]),\n              );\n            }\n          }\n\n          if (toUpdate.length > 0) {\n            const updated = await executeEdgeUpsertUpdateBatch(\n              updateEntries,\n              target,\n            );\n            for (const [updateIndex, entry] of toUpdate.entries()) {\n              const result = requireDefined(updated[updateIndex]);\n              results[entry.index] = narrowEdge<E>(result);\n            }\n          }\n        } else {\n          const mutationSet = mutationAttempt.value;\n          for (const [index, entry] of toCreate.entries()) {\n            results[entry.index] = narrowEdge<E>(\n              requireDefined(mutationSet.created[index]),\n            );\n          }\n          for (const [index, entry] of toUpdate.entries()) {\n            results[entry.index] = narrowEdge<E>(\n              requireDefined(mutationSet.updated[index]),\n            );\n          }\n        }\n\n        // Items that coalesced against an in-batch write take that write's\n        // result (now filled). Its sourceIndex is always a write slot — a\n        // queued create or a queued update, both filled above.\n        for (const { index, sourceIndex } of deferred) {\n          results[index] = requireDefined(results[sourceIndex]);\n        }\n\n        return { results, mutations: toCreate.length + toUpdate.length };\n      };\n\n      // INVARIANT: the prefetch that feeds every coalesce decision and the\n      // writes those decisions elect run against ONE target — so an item is\n      // skipped only on evidence taken inside the transaction that would have\n      // written it, never on an autocommit read taken before it (the defect\n      // `upsertById` had on the node side).\n      //\n      // `runOptionallyInTransaction` is the one owner of \"open a transaction if\n      // this backend has one\": already inside `store.transaction(...)` the\n      // target IS the caller's transaction and no nested one opens, and on a\n      // backend without interactive transactions there is nothing to open, so\n      // the decision is exactly as fenced as that backend's writes are — which\n      // is to say not at all, matching the atomicity it already cannot offer.\n      const { results, mutations } = await runResolvedMutationSetConverging(\n        \"edge\",\n        backend,\n        () =>\n          runOptionallyInTransaction(backend, (target) => upsertAll(target)),\n      );\n      // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n      // autocommit bulk write. Coalesced items wrote nothing, so only real\n      // mutations count toward the threshold. A no-op inside a caller\n      // transaction (the hook is intentionally undefined there).\n      await config.maybeRefreshStatisticsAfterBulk?.(mutations);\n      return results;\n    },\n\n    async bulkInsert(\n      items: readonly Readonly<{\n        from: NodeRef;\n        to: NodeRef;\n        props?: z.input<E[\"schema\"]>;\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>[],\n    ): Promise<void> {\n      const batchInputs = mapBulkEdgeInputs(kind, items);\n      await executeEdgeCreateNoReturnBatch(batchInputs, backend);\n      await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n    },\n\n    async bulkDelete(ids: readonly string[]): Promise<void> {\n      if (ids.length === 0) return;\n      await executeEdgeDeleteBatch(kind, ids, backend);\n    },\n\n    async findByEndpoints(\n      from: NodeRef,\n      to: NodeRef,\n      options?: EdgeFindByEndpointsOptions<E>,\n      temporal?: QueryOptions,\n    ): Promise<Edge<E> | undefined> {\n      const result = await config.executeFindByEndpoints(\n        kind,\n        from.kind,\n        from.id,\n        to.kind,\n        to.id,\n        backend,\n        buildFindByEndpointsOptions(options, temporal),\n      );\n      return result === undefined ? undefined : narrowEdge<E>(result);\n    },\n\n    async getOrCreateByEndpoints(\n      from: NodeRef,\n      to: NodeRef,\n      props: z.input<E[\"schema\"]>,\n      options?: EdgeGetOrCreateByEndpointsOptions<E>,\n    ): Promise<EdgeGetOrCreateByEndpointsResult<E>> {\n      assertValidityEndMutation(options ?? {}, {\n        entityType: \"edge\",\n        kind,\n      });\n      const getOrCreateOptions = {\n        ...(options?.matchOn !== undefined && {\n          matchOn: options.matchOn as readonly string[],\n        }),\n        ...(options?.ifExists !== undefined && {\n          ifExists: options.ifExists,\n        }),\n        ...(options?.validFrom !== undefined && {\n          validFrom: options.validFrom,\n        }),\n        ...(options?.validTo !== undefined && { validTo: options.validTo }),\n        ...(options?.clearValidTo === true && { clearValidTo: true as const }),\n        ...(options?.onImmutableLowerBound !== undefined && {\n          onImmutableLowerBound: options.onImmutableLowerBound,\n        }),\n      };\n\n      const result = await config.executeGetOrCreateByEndpoints(\n        kind,\n        from.kind,\n        from.id,\n        to.kind,\n        to.id,\n        props,\n        backend,\n        getOrCreateOptions,\n      );\n      return { edge: narrowEdge<E>(result.edge), action: result.action };\n    },\n\n    async bulkGetOrCreateByEndpoints(\n      items: readonly Readonly<{\n        from: NodeRef;\n        to: NodeRef;\n        props: z.input<E[\"schema\"]>;\n        validFrom?: string | null;\n        validTo?: string;\n        clearValidTo?: true;\n        onImmutableLowerBound?: \"preserve\" | \"refuse\";\n      }>[],\n      options?: Pick<\n        EdgeGetOrCreateByEndpointsOptions<E>,\n        \"matchOn\" | \"ifExists\"\n      >,\n    ): Promise<EdgeGetOrCreateByEndpointsResult<E>[]> {\n      if (items.length === 0) return [];\n\n      for (const item of items) {\n        assertValidityEndMutation(item, {\n          entityType: \"edge\",\n          kind,\n        });\n      }\n\n      const mappedItems = items.map((item) => ({\n        fromKind: item.from.kind,\n        fromId: item.from.id,\n        toKind: item.to.kind,\n        toId: item.to.id,\n        props: item.props,\n        ...(item.validFrom !== undefined && { validFrom: item.validFrom }),\n        ...(item.validTo !== undefined && { validTo: item.validTo }),\n        ...(item.clearValidTo === true && { clearValidTo: true as const }),\n        ...(item.onImmutableLowerBound !== undefined && {\n          onImmutableLowerBound: item.onImmutableLowerBound,\n        }),\n      }));\n\n      const getOrCreateOptions = {\n        ...(options?.matchOn !== undefined && {\n          matchOn: options.matchOn as readonly string[],\n        }),\n        ...(options?.ifExists !== undefined && {\n          ifExists: options.ifExists,\n        }),\n      };\n\n      const getOrCreateAll = async (\n        target: GraphBackend | TransactionBackend,\n      ): Promise<EdgeGetOrCreateByEndpointsResult<E>[]> => {\n        const results = await config.executeBulkGetOrCreateByEndpoints(\n          kind,\n          mappedItems,\n          target,\n          getOrCreateOptions,\n        );\n        return results.map((result) => ({\n          edge: narrowEdge<E>(result.edge),\n          action: result.action,\n        }));\n      };\n\n      // The operation owns its transaction boundary. This lets exact-root\n      // atomic convergence dispatch before a derived transaction target hides\n      // the bundled backend proof; the portable implementation still enters\n      // `runWritePlan` and receives the same all-or-nothing boundary.\n      return getOrCreateAll(backend);\n    },\n  };\n}\n","/**\n * NodeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific node type.\n */\nimport { type z } from \"zod\";\n\nimport { bindExtraIfReachable } from \"../../backend/capabilities/bind\";\nimport { BATCH_POINT_READ } from \"../../backend/capabilities/bundle-registry\";\nimport { type BundleVerdictOf } from \"../../backend/capabilities/resolve\";\nimport { backendDerivationRoot } from \"../../backend/derive-backend\";\nimport {\n  type GraphBackend,\n  type NodeRow as BackendNodeRow,\n  rowPropsToObject,\n  runOptionallyInTransaction,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n  type NodeId,\n  type NodeType,\n  type TemporalMode,\n} from \"../../core/types\";\nimport {\n  ConfigurationError,\n  ENTITY_ALREADY_EXISTS_CODE,\n  NodeNotFoundError,\n  ValidationError,\n} from \"../../errors\";\nimport type { DynamicNodeAccessor, NodeAccessor } from \"../../query/builder\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport { type Predicate } from \"../../query/predicates\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport {\n  asCompiledSelectSql,\n  type CompiledSelectSql,\n} from \"../../query/sql-intent\";\nimport { nowIso } from \"../../utils/date\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport {\n  type ResolvedMutationSetAttempt,\n  runResolvedMutationSetConverging,\n} from \"../resolved-mutation-set\";\nimport { type NodeRow } from \"../row-mappers\";\nimport {\n  type CreateNodeInput,\n  type GetOrCreateAction,\n  type Node,\n  type NodeBulkFindByIndexOptions,\n  type NodeCollection,\n  type NodeGetOrCreateByConstraintOptions,\n  type NodeGetOrCreateByConstraintResult,\n  type QueryOptions,\n  type UpdateNodeInput,\n  type ValidityEndMutation,\n} from \"../types\";\nimport {\n  assertClearValidToSupported,\n  assertValidityEndMutation,\n} from \"../validity-end\";\nimport {\n  findRepeatedUpsertIds,\n  shouldCoalesceUpsert,\n  type UpsertDirtyCheck,\n  type UpsertDirtyCheckFunction,\n  type UpsertWindow,\n  upsertWindowChanges,\n  windowAfterUpsertCreate,\n  windowAfterUpsertUpdate,\n} from \"./coalesce\";\nimport {\n  resolveTemporalReadParams,\n  type TemporalReadParams,\n} from \"./temporal-read-params\";\n\nfunction isNodeReplacementPartitionMovement(error: unknown): boolean {\n  return (\n    error instanceof NodeNotFoundError ||\n    (error instanceof ValidationError &&\n      error.details.issues.some(\n        (issue) => issue.code === ENTITY_ALREADY_EXISTS_CODE,\n      ))\n  );\n}\n\ntype OnImmutableLowerBound = \"preserve\" | \"refuse\";\n\ntype NodeUpsertOptions = Readonly<{\n  validFrom?: string | null;\n  onImmutableLowerBound?: OnImmutableLowerBound;\n}> &\n  ValidityEndMutation;\n\nexport type NodeSetUpdateRequest =\n  | Readonly<{ operation: \"updateWhere\" }>\n  | Readonly<{\n      operation: \"compareAndSet\";\n      expected: Record<string, unknown>;\n    }>;\n\n/**\n * Narrows unparameterized Node to Node<N>.\n * Safe: props are validated by Zod at creation/update boundaries.\n */\nfunction narrowNode<N extends NodeType>(node: Node): Node<N> {\n  return node as Node<N>;\n}\n\n/**\n * Narrows a readonly Node array to Node<N>[].\n */\nfunction narrowNodes<N extends NodeType>(nodes: readonly Node[]): Node<N>[] {\n  return nodes as Node<N>[];\n}\n\n/** Adapts a schema-shaped typed callback to the runtime dynamic accessor. */\ntype NodeCollectionPredicateAccessor<N extends NodeType> =\n  string extends N[\"kind\"] ? DynamicNodeAccessor : NodeAccessor<N>;\n\n/** Supports both dynamic `.field(name)` and a typed property named `field`. */\nfunction createFieldMember(\n  accessor: DynamicNodeAccessor,\n): DynamicNodeAccessor[\"field\"] {\n  const selectField = (name: string) => accessor.field(name);\n  return new Proxy(selectField, {\n    get(target, property, receiver) {\n      if (Reflect.has(target, property)) {\n        const ownProperty: unknown = Reflect.get(target, property, receiver);\n        return ownProperty;\n      }\n      return (\n        accessor.field(\"field\") as unknown as Readonly<\n          Record<PropertyKey, unknown>\n        >\n      )[property];\n    },\n  });\n}\n\nfunction evaluateNodePredicate<N extends NodeType>(\n  accessor: DynamicNodeAccessor,\n  predicate: (accessor: NodeCollectionPredicateAccessor<N>) => Predicate,\n): Predicate {\n  const collectionAccessor = new Proxy(\n    {} as NodeCollectionPredicateAccessor<N>,\n    {\n      get(_target, property) {\n        if (typeof property === \"symbol\") return;\n        // No interop exemption for `then` / `toJSON`. This accessor's contract\n        // is that EVERY name is a field — the typed signature offers the\n        // schema's fields, including ones legally named after a protocol hook,\n        // and refusing those names made a declared field unaddressable. The\n        // exemption is also unnecessary here: a field builder is an object,\n        // never a function, so `await` sees a non-callable `then` and\n        // `JSON.stringify` a non-callable `toJSON`, and neither is invoked.\n        if (\n          property === \"id\" ||\n          property === \"kind\" ||\n          property === \"$fulltext\"\n        ) {\n          return accessor[property];\n        }\n        if (property === \"field\") return createFieldMember(accessor);\n        return accessor.field(property);\n      },\n    },\n  );\n  return predicate(collectionAccessor);\n}\n\n/**\n * Update input for the internal upsert path, which owns the WHOLE validity\n * window: a resurrecting upsert rewrites both endpoints, so it must be able to\n * carry `validFrom` as well as `validTo`. Dropping `validFrom` here would leave\n * a stated lower bound unreachable by the only node write that stores one: a\n * resurrection rewrites `valid_from` whether or not the caller named it, so the\n * caller's bound would be replaced by the instant that write stamps rather than\n * honored. It would no longer INVERT the window — a resurrection stating only a\n * historical `validTo` stores no lower bound at all — which is why the sibling\n * note on `UpsertUpdateEdgeInput` still reads in terms of inversion and this one\n * does not: an edge resurrection RETAINS its stored bound.\n *\n * The public `update()` API cannot reach this member: its options type exposes\n * `validTo` only, and it builds its input through {@link buildUpdateInput}. Only\n * `upsertById` / `bulkUpsertById`, which accept `validFrom` by contract, route\n * through {@link buildUpsertUpdateInput}.\n */\nexport type UpsertUpdateNodeInput = UpdateNodeInput &\n  Readonly<{\n    validFrom?: string | null;\n    onImmutableLowerBound?: OnImmutableLowerBound;\n  }>;\n\nexport type NodeUpsertUpdateBatchEntry = Readonly<{\n  input: UpsertUpdateNodeInput;\n  clearDeleted: boolean;\n  existing?: BackendNodeRow;\n  /** Complete props already validated by the replacement API owner. */\n  replacementProps?: Record<string, unknown>;\n}>;\n\n/**\n * Config for creating a NodeCollection.\n */\nexport type NodeCollectionConfig = Readonly<{\n  graphId: string;\n  kind: string;\n  backend: GraphBackend | TransactionBackend;\n  /** Threaded `batchPointRead` verdict — never re-resolved here. */\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  defaultTemporalMode: TemporalMode;\n  rowToNode: (row: NodeRow) => Node;\n  /** See NodeOperations.maybeRefreshStatisticsAfterBulk. */\n  maybeRefreshStatisticsAfterBulk?:\n    ((rowCount: number) => Promise<void>) | undefined;\n  executeCreate: (\n    input: CreateNodeInput,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Node>;\n  executeCreateNoReturnBatch: (\n    inputs: readonly CreateNodeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeCreateBatch: (\n    inputs: readonly CreateNodeInput[],\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{ propsPreValidated?: true }>,\n  ) => Promise<readonly Node[]>;\n  executeUpdate: (\n    input: UpsertUpdateNodeInput,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{ clearDeleted?: boolean }>,\n  ) => Promise<Node>;\n  executeNodeSetUpdate: (\n    kind: string,\n    patch: Record<string, unknown>,\n    candidateIds: CompiledSelectSql,\n    candidateIdColumn: string,\n    backend: GraphBackend | TransactionBackend,\n    request: NodeSetUpdateRequest,\n  ) => Promise<Readonly<{ affectedCount: number }>>;\n  executeUpsertUpdateBatch: (\n    entries: readonly NodeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Node[]>;\n  executeResolvedMutationSet: (\n    creates: readonly CreateNodeInput[],\n    updates: readonly NodeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<\n    ResolvedMutationSetAttempt<\n      Readonly<{ created: readonly Node[]; updated: readonly Node[] }>\n    >\n  >;\n  prepareReplacement: (\n    kind: string,\n    props: Record<string, unknown>,\n  ) => Record<string, unknown>;\n  executeReplacementBatch: (\n    kind: string,\n    items: readonly Readonly<{\n      id: string;\n      props: Record<string, unknown>;\n    }>[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<ResolvedMutationSetAttempt<readonly Node[]>>;\n  /** See NodeOperations.upsertDirtyCheck. */\n  upsertDirtyCheck?: UpsertDirtyCheckFunction;\n  executeDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeDeleteBatch: (\n    kind: string,\n    ids: readonly string[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeHardDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  temporalRowMatcher: (options?: QueryOptions) => (row: NodeRow) => boolean;\n  createQuery?: () => QueryBuilder<GraphDef>;\n  executeGetOrCreateByConstraint: (\n    kind: string,\n    constraintName: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeGetOrCreateByConstraintOptions,\n  ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>>;\n  executeBulkGetOrCreateByConstraint: (\n    kind: string,\n    constraintName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeGetOrCreateByConstraintOptions,\n  ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]>;\n  executeFindByConstraint: (\n    kind: string,\n    constraintName: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Node | undefined>;\n  executeBulkFindByConstraint: (\n    kind: string,\n    constraintName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<(Node | undefined)[]>;\n  executeBulkFindByIndex: (\n    kind: string,\n    indexName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeBulkFindByIndexOptions,\n  ) => Promise<Node[][]>;\n}>;\n\nfunction buildCreateInput(\n  kind: string,\n  props: Record<string, unknown>,\n  options?: Readonly<{\n    id?: string;\n    validFrom?: string | null;\n    validTo?: string;\n  }>,\n): CreateNodeInput {\n  const input: {\n    kind: string;\n    id?: string;\n    props: Record<string, unknown>;\n    validFrom?: string | null;\n    validTo?: string;\n  } = { kind, props };\n  if (options?.id !== undefined) input.id = options.id;\n  if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  return input;\n}\n\nfunction buildUpdateInput(\n  kind: string,\n  id: string,\n  props: Record<string, unknown>,\n  options?: ValidityEndMutation,\n): UpdateNodeInput {\n  const input: {\n    kind: string;\n    id: string;\n    props: Partial<Record<string, unknown>>;\n    validTo?: string;\n    clearValidTo?: true;\n  } = { kind, id, props };\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  if (options?.clearValidTo === true) input.clearValidTo = true;\n  return input as UpdateNodeInput;\n}\n\n/** Builds an {@link UpsertUpdateNodeInput} — see that type for why upsert alone carries `validFrom`. */\nfunction buildUpsertUpdateInput(\n  kind: string,\n  id: string,\n  props: Record<string, unknown>,\n  options?: Readonly<{\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: OnImmutableLowerBound;\n  }>,\n): UpsertUpdateNodeInput {\n  const input: {\n    kind: string;\n    id: string;\n    props: Partial<Record<string, unknown>>;\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: OnImmutableLowerBound;\n  } = { kind, id, props };\n  if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n  if (options?.validTo !== undefined) input.validTo = options.validTo;\n  if (options?.clearValidTo === true) input.clearValidTo = true;\n  if (options?.onImmutableLowerBound !== undefined) {\n    input.onImmutableLowerBound = options.onImmutableLowerBound;\n  }\n  return input as UpsertUpdateNodeInput;\n}\n\nfunction mapBulkNodeInputs(\n  kind: string,\n  items: readonly Readonly<{\n    props: Record<string, unknown>;\n    id?: string;\n    validFrom?: string | null;\n    validTo?: string;\n  }>[],\n): CreateNodeInput[] {\n  return items.map((item) => buildCreateInput(kind, item.props, item));\n}\n\n/**\n * Creates a NodeCollection for a specific node type.\n */\nexport function createNodeCollection<\n  G extends GraphDef,\n  K extends keyof G[\"nodes\"] & string,\n>(config: NodeCollectionConfig): NodeCollection<G[\"nodes\"][K][\"type\"]> {\n  type N = G[\"nodes\"][K][\"type\"];\n\n  const {\n    graphId,\n    kind,\n    backend,\n    batchPointRead,\n    defaultTemporalMode,\n    rowToNode,\n    executeCreate: executeNodeCreate,\n    executeCreateNoReturnBatch: executeNodeCreateNoReturnBatch,\n    executeCreateBatch: executeNodeCreateBatch,\n    executeUpdate: executeNodeUpdate,\n    executeNodeSetUpdate,\n    executeUpsertUpdateBatch: executeNodeUpsertUpdateBatch,\n    executeResolvedMutationSet: executeNodeResolvedMutationSet,\n    prepareReplacement,\n    executeReplacementBatch: executeNodeReplacementBatch,\n    executeDelete: executeNodeDelete,\n    executeDeleteBatch: executeNodeDeleteBatch,\n    executeHardDelete: executeNodeHardDelete,\n    temporalRowMatcher,\n    createQuery,\n    executeGetOrCreateByConstraint,\n    executeBulkGetOrCreateByConstraint,\n    executeFindByConstraint,\n    executeBulkFindByConstraint,\n    executeBulkFindByIndex,\n  } = config;\n\n  return {\n    async create(\n      props: z.input<N[\"schema\"]>,\n      options?: Readonly<{\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>,\n    ): Promise<Node<N>> {\n      return this.createFromRecord(props, options);\n    },\n\n    async createFromRecord(\n      data: Record<string, unknown>,\n      options?: Readonly<{\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>,\n    ): Promise<Node<N>> {\n      const result = await executeNodeCreate(\n        buildCreateInput(kind, data, options),\n        backend,\n      );\n      return narrowNode<N>(result);\n    },\n\n    async getById(\n      id: NodeId<N>,\n      options?: QueryOptions,\n    ): Promise<Node<N> | undefined> {\n      const row = await backend.getNode(graphId, kind, id);\n      if (!row) return undefined;\n      if (!temporalRowMatcher(options)(row)) return undefined;\n      return narrowNode<N>(rowToNode(row));\n    },\n\n    async getByIds(\n      ids: readonly NodeId<N>[],\n      options?: QueryOptions,\n    ): Promise<readonly (Node<N> | undefined)[]> {\n      if (ids.length === 0) return [];\n\n      const rowsById = await getNodeRowsByIds(\n        backend,\n        batchPointRead,\n        graphId,\n        kind,\n        ids,\n      );\n      // Resolve the coordinate once so the whole batch observes one instant.\n      const matches = temporalRowMatcher(options);\n      return ids.map((id) => {\n        const row = rowsById.get(id);\n        if (!row) return;\n        if (!matches(row)) return;\n        return narrowNode<N>(rowToNode(row));\n      });\n    },\n\n    async update(\n      id: NodeId<N>,\n      props: Partial<z.input<N[\"schema\"]>>,\n      options?: ValidityEndMutation,\n    ): Promise<Node<N>> {\n      const result = await executeNodeUpdate(\n        buildUpdateInput(kind, id, props, options),\n        backend,\n      );\n      return narrowNode<N>(result);\n    },\n\n    async compareAndSet(id, params): Promise<boolean> {\n      if (createQuery === undefined) {\n        throw new ConfigurationError(\n          `store.nodes.${kind}.compareAndSet() requires a query-capable store`,\n          { kind, operation: \"compareAndSet\" },\n        );\n      }\n      const rootAlias = \"compare_and_set_candidate\";\n      const candidateIdColumn = `${rootAlias}_id`;\n      const candidateIds = createQuery()\n        .fromDynamic(kind, rootAlias)\n        .whereNode(rootAlias, (accessor) => accessor.id.eq(id))\n        .select((ctx: Record<string, { id: unknown }>) => ctx[rootAlias]?.id)\n        .compile();\n      const result = await executeNodeSetUpdate(\n        kind,\n        params.patch,\n        candidateIds,\n        candidateIdColumn,\n        backend,\n        { operation: \"compareAndSet\", expected: params.expected },\n      );\n      return result.affectedCount === 1;\n    },\n\n    async updateWhere(params): Promise<Readonly<{ affectedCount: number }>> {\n      if (createQuery === undefined) {\n        throw new ConfigurationError(\n          `store.nodes.${kind}.updateWhere() requires a query-capable store`,\n          { kind, operation: \"updateWhere\" },\n        );\n      }\n      const exists = params.exists ?? [];\n      if (\n        params.where === undefined &&\n        exists.length === 0 &&\n        params.candidates === undefined &&\n        !params.all\n      ) {\n        throw new ConfigurationError(\n          `store.nodes.${kind}.updateWhere() requires candidates, where, exists, or explicit all: true`,\n          { kind, operation: \"updateWhere\" },\n        );\n      }\n\n      const rootAlias = \"update_candidate\";\n      const readInstant = nowIso();\n      const candidateIdColumn = `${rootAlias}_id`;\n      const compiledBranches: CompiledSelectSql[] = [];\n\n      const candidateQuery = params.candidates;\n      if (candidateQuery !== undefined) {\n        const selection = candidateQuery.toNodeCandidateSelection();\n        const expectedTarget = backendDerivationRoot(backend);\n        if (selection.graphId !== graphId) {\n          throw new ConfigurationError(\n            \"updateWhere() candidates must belong to the same graph as the collection.\",\n            {\n              kind,\n              operation: \"updateWhere\",\n              expectedGraphId: graphId,\n              receivedGraphId: selection.graphId,\n            },\n          );\n        }\n        if (\n          selection.executionTarget === undefined ||\n          selection.executionTarget !== expectedTarget\n        ) {\n          throw new ConfigurationError(\n            \"updateWhere() candidates must be created by this Store or transaction.\",\n            { kind, operation: \"updateWhere\" },\n          );\n        }\n        if (selection.kind !== kind) {\n          throw new ConfigurationError(\n            \"updateWhere() candidates must select the collection's node kind.\",\n            {\n              kind,\n              operation: \"updateWhere\",\n              candidateKind: selection.kind,\n            },\n          );\n        }\n        if (\n          selection.temporalMode !== \"current\" ||\n          selection.recordedAsOf !== undefined\n        ) {\n          throw new ConfigurationError(\n            \"updateWhere() candidates must use the current temporal coordinate.\",\n            { kind, operation: \"updateWhere\" },\n          );\n        }\n        const compiledCandidateQuery =\n          candidateQuery.compileNodeCandidateIds(readInstant);\n        compiledBranches.push(\n          asCompiledSelectSql(\n            sql`SELECT ${sql.identifier(selection.idColumn)} AS ${sql.identifier(candidateIdColumn)} FROM (${compiledCandidateQuery}) AS ${sql.identifier(\"update_selected_candidates\")}`,\n          ),\n        );\n      }\n\n      let base = createQuery()\n        .fromDynamic(kind, rootAlias)\n        .temporal(\"asOf\", readInstant);\n      const where = params.where;\n      if (where !== undefined) {\n        base = base.whereNode(rootAlias, (accessor) =>\n          evaluateNodePredicate<N>(accessor, where),\n        );\n      }\n      for (const [index, relation] of exists.entries()) {\n        const edgeAlias = `update_edge_${index}`;\n        const relatedAlias = `update_related_${index}`;\n        const relationRoot = createQuery()\n          .fromDynamic(kind, rootAlias)\n          .temporal(\"asOf\", readInstant);\n        let traversal = relationRoot.traverseDynamic(\n          relation.edgeKind,\n          edgeAlias,\n          {\n            direction: relation.direction,\n            expand: \"none\",\n          },\n        );\n        if (relation.whereEdge !== undefined) {\n          traversal = traversal.whereEdge(edgeAlias, relation.whereEdge);\n        }\n        let related = traversal.toDynamic(relation.relatedKind, relatedAlias);\n        if (relation.whereRelated !== undefined) {\n          related = related.whereNode(relatedAlias, relation.whereRelated);\n        }\n        compiledBranches.push(\n          related\n            .select(\n              (ctx: Record<string, { id: unknown }>) => ctx[rootAlias]?.id,\n            )\n            .compile(),\n        );\n      }\n      // A candidate selection is already constrained to this collection's\n      // kind and the current temporal coordinate (validated above). When it is\n      // the only selection predicate, adding the unfiltered kind scan and\n      // intersecting it back in is redundant. The candidate branch remains the\n      // first branch so relation predicates still intersect with it below.\n      if (candidateQuery === undefined || where !== undefined) {\n        compiledBranches.unshift(\n          base\n            .select(\n              (ctx: Record<string, { id: unknown }>) => ctx[rootAlias]?.id,\n            )\n            .compile(),\n        );\n      }\n      const projectCandidateId = (\n        branch: CompiledSelectSql,\n        index: number,\n      ): SqlFragment => sql`\n        SELECT ${sql.identifier(candidateIdColumn)}\n        FROM (${branch}) AS ${sql.identifier(`update_branch_${index}`)}\n      `;\n      let combinedCandidates = projectCandidateId(\n        requireDefined(compiledBranches[0]),\n        0,\n      );\n      for (let index = 1; index < compiledBranches.length; index++) {\n        combinedCandidates = sql`${combinedCandidates} INTERSECT ${projectCandidateId(\n          requireDefined(compiledBranches[index]),\n          index,\n        )}`;\n      }\n      const compiledCandidates = asCompiledSelectSql(combinedCandidates);\n\n      const result = await executeNodeSetUpdate(\n        kind,\n        params.patch,\n        compiledCandidates,\n        candidateIdColumn,\n        backend,\n        { operation: \"updateWhere\" },\n      );\n      await config.maybeRefreshStatisticsAfterBulk?.(result.affectedCount);\n      return result;\n    },\n\n    async delete(id: NodeId<N>): Promise<void> {\n      await executeNodeDelete(kind, id, backend);\n    },\n\n    async hardDelete(id: NodeId<N>): Promise<void> {\n      await executeNodeHardDelete(kind, id, backend);\n    },\n\n    async find(\n      filter?: Readonly<{\n        where?: (accessor: never) => unknown;\n        limit?: number;\n        offset?: number;\n      }>,\n      temporal?: QueryOptions,\n    ): Promise<Node<N>[]> {\n      if (filter?.where !== undefined && createQuery === undefined) {\n        throw new ConfigurationError(\n          `store.nodes.${kind}.find({ where }) requires a query-capable store`,\n          { kind, operation: \"find\" },\n        );\n      }\n      if (filter?.where !== undefined && createQuery !== undefined) {\n        // Resolve the coordinate through the same helper as the non-where\n        // branch and count(), so find({ where }) and find(filter) observe\n        // identical rows. `current` / `asOf` both resolve to a concrete instant\n        // the backend find path compares against; pin the query to that same\n        // instant — `current` would otherwise compile against the DB clock and\n        // ignore the resolved asOf. includeEnded / includeTombstones carry no\n        // instant. Routing through resolveTemporalReadParams also makes a\n        // missing asOf in asOf mode throw here, matching the non-where branch.\n        const { temporalMode, asOf } = resolveTemporalReadParams(\n          temporal,\n          defaultTemporalMode,\n        );\n        let query = createQuery()\n          .from(kind, \"_n\")\n          .temporal(asOf === undefined ? temporalMode : \"asOf\", asOf)\n          .whereNode(\"_n\", filter.where as never)\n          .select((ctx: Record<string, unknown>) => ctx[\"_n\"]);\n        if (filter.limit !== undefined) query = query.limit(filter.limit);\n        if (filter.offset !== undefined) query = query.offset(filter.offset);\n        const results = await query.execute();\n        return results as Node<N>[];\n      }\n\n      const params: {\n        graphId: string;\n        kind: string;\n        limit?: number;\n        offset?: number;\n      } & TemporalReadParams = {\n        graphId,\n        kind,\n        ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n      };\n      if (filter?.limit !== undefined) params.limit = filter.limit;\n      if (filter?.offset !== undefined) params.offset = filter.offset;\n\n      const rows = await backend.findNodesByKind(params);\n      return rows.map((row) => narrowNode<N>(rowToNode(row)));\n    },\n\n    async count(temporal?: QueryOptions): Promise<number> {\n      const params: {\n        graphId: string;\n        kind: string;\n      } & TemporalReadParams = {\n        graphId,\n        kind,\n        ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n      };\n      return backend.countNodesByKind(params);\n    },\n\n    async upsertById(\n      id: string,\n      props: z.input<N[\"schema\"]>,\n      options?: NodeUpsertOptions,\n    ): Promise<Node<N>> {\n      return this.upsertByIdFromRecord(id, props, options);\n    },\n\n    async upsertByIdFromRecord(\n      id: string,\n      data: Record<string, unknown>,\n      options?: NodeUpsertOptions,\n    ): Promise<Node<N>> {\n      assertValidityEndMutation(options ?? {}, {\n        entityType: \"node\",\n        kind,\n        id,\n      });\n      if (options?.clearValidTo === true) {\n        assertClearValidToSupported(backend, \"node\");\n      }\n      const existing = await backend.getNode(graphId, kind, id);\n\n      // Coalesce a value-identical replay: skip the write entirely (no\n      // updateNode, no recorded capture, no revision advance, no hooks) and\n      // resolve with the existing node. See\n      // BaseStoreOptions.coalesceUnchangedUpserts.\n      const coalesces = (row: NonNullable<typeof existing>): boolean => {\n        const runDirtyCheck =\n          config.upsertDirtyCheck &&\n          (() =>\n            requireDefined(config.upsertDirtyCheck)(\n              kind,\n              id,\n              rowPropsToObject(row.props),\n              data,\n            ));\n        return shouldCoalesceUpsert(row, options, runDirtyCheck);\n      };\n\n      // INVARIANT: a coalescing upsert's decision to SKIP is both taken and\n      // executed inside one transaction. The read that justifies the skip and\n      // the skip itself are the same transaction; the skip IS that\n      // transaction's empty commit, and nothing after the commit writes, so\n      // there is no window between deciding and acting for a competitor to\n      // occupy.\n      //\n      // Coalescing must be an optimization, never a semantic: with the flag\n      // off, `executeNodeUpdate` opens a transaction, re-reads, and merges the\n      // caller's props over whatever it finds, so a writer that commits between\n      // the autocommit read above and the write still has the caller's props\n      // applied on top. Deciding \"skip\" from that earlier read gave a DIFFERENT\n      // answer — the caller was told its props were stored while the store held\n      // the other writer's — so the flag changed the outcome instead of the\n      // cost. Deciding inside the transaction restores the equivalence: a\n      // \"write\" verdict falls through to the ordinary path, whose own\n      // in-transaction re-read merges over the current row.\n      //\n      // Note the shape difference from a plain re-read: the verdict is computed\n      // where `target` is live, not after the transaction closed. Committing\n      // and THEN deciding would narrow the window rather than close it, which\n      // is what the bulk paths avoid by deciding inside `upsertAll`.\n      //\n      // Only a coalescing store that is ABOUT to skip pays the second read; a\n      // store without the flag, or one whose props differ, keeps the single\n      // read and the single write it always had. On SQLite the transaction is\n      // `BEGIN IMMEDIATE`, which excludes every other writer for its duration;\n      // on a backend without transactions there is nothing to open and the\n      // decision is as fenced as that backend's writes are — which is to say\n      // not at all, matching the atomicity it already cannot offer.\n      type UpsertVerdict =\n        | Readonly<{ verdict: \"skip\"; row: NodeRow }>\n        | Readonly<{ verdict: \"write\"; row: NodeRow | undefined }>;\n\n      const decision: UpsertVerdict =\n        existing !== undefined && coalesces(existing) ?\n          await runOptionallyInTransaction(\n            backend,\n            async (target): Promise<UpsertVerdict> => {\n              const confirmed = await target.getNode(graphId, kind, id);\n              return confirmed !== undefined && coalesces(confirmed) ?\n                  { verdict: \"skip\", row: confirmed }\n                : { verdict: \"write\", row: confirmed };\n            },\n          )\n        : { verdict: \"write\", row: existing };\n\n      if (decision.verdict === \"skip\") {\n        return narrowNode<N>(rowToNode(decision.row));\n      }\n\n      if (decision.row !== undefined) {\n        const result = await executeNodeUpdate(\n          buildUpsertUpdateInput(kind, id, data, options),\n          backend,\n          { clearDeleted: decision.row.deleted_at !== undefined },\n        );\n        return narrowNode<N>(result);\n      }\n\n      const result = await executeNodeCreate(\n        buildCreateInput(kind, data, { ...options, id }),\n        backend,\n      );\n      return narrowNode<N>(result);\n    },\n\n    async bulkCreate(\n      items: readonly Readonly<{\n        props: z.input<N[\"schema\"]>;\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>[],\n    ): Promise<Node<N>[]> {\n      const batchInputs = mapBulkNodeInputs(kind, items);\n      const results = await executeNodeCreateBatch(batchInputs, backend);\n      await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n      return narrowNodes<N>(results);\n    },\n\n    async bulkReplaceById(\n      items: readonly Readonly<{\n        id: string;\n        props: z.input<N[\"schema\"]>;\n      }>[],\n    ): Promise<Node<N>[]> {\n      if (items.length === 0) return [];\n      const seenIds = new Set<string>();\n      for (const item of items) {\n        if (seenIds.has(item.id)) {\n          throw new ValidationError(\n            `bulkReplaceById requires distinct node ids; received \"${item.id}\" more than once.`,\n            {\n              entityType: \"node\",\n              kind,\n              operation: \"update\",\n              id: item.id,\n              issues: [],\n            },\n          );\n        }\n        seenIds.add(item.id);\n      }\n      const prepared = items.map((item) => ({\n        id: item.id,\n        props: prepareReplacement(kind, item.props),\n      }));\n      const attempt = await executeNodeReplacementBatch(\n        kind,\n        prepared,\n        backend,\n      );\n      if (attempt.outcome === \"applied\") {\n        await config.maybeRefreshStatisticsAfterBulk?.(attempt.value.length);\n        return narrowNodes<N>(attempt.value);\n      }\n      const results = await runResolvedMutationSetConverging(\n        \"node\",\n        backend,\n        () =>\n          runOptionallyInTransaction(backend, async (target) => {\n            const rows = await getNodeRowsByIds(\n              target,\n              batchPointRead,\n              graphId,\n              kind,\n              prepared.map((item) => item.id),\n            );\n            const results = new Map<string, Node<N>>();\n            const creates = prepared.filter((item) => !rows.has(item.id));\n            const updates = prepared.filter((item) => rows.has(item.id));\n            if (creates.length > 0) {\n              const created = await executeNodeCreateBatch(\n                creates.map((item) =>\n                  buildCreateInput(kind, item.props, { id: item.id }),\n                ),\n                target,\n                { propsPreValidated: true },\n              );\n              for (const row of created)\n                results.set(row.id, narrowNode<N>(row));\n            }\n            if (updates.length > 0) {\n              const updated = await executeNodeUpsertUpdateBatch(\n                updates.map((item) => {\n                  const existing = requireDefined(rows.get(item.id));\n                  return {\n                    input: buildUpsertUpdateInput(kind, item.id, item.props),\n                    clearDeleted: existing.deleted_at !== undefined,\n                    existing,\n                    replacementProps: item.props,\n                  };\n                }),\n                target,\n              );\n              for (const row of updated)\n                results.set(row.id, narrowNode<N>(row));\n            }\n            return prepared.map((item) => requireDefined(results.get(item.id)));\n          }),\n        { isMovement: isNodeReplacementPartitionMovement },\n      );\n      await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n      return results;\n    },\n\n    async bulkUpsertById(\n      items: readonly Readonly<{\n        id: string;\n        props: z.input<N[\"schema\"]>;\n        validFrom?: string | null;\n        validTo?: string;\n        clearValidTo?: true;\n        onImmutableLowerBound?: OnImmutableLowerBound;\n      }>[],\n    ): Promise<Node<N>[]> {\n      if (items.length === 0) return [];\n\n      for (const item of items) {\n        assertValidityEndMutation(item, {\n          entityType: \"node\",\n          kind,\n          id: item.id,\n        });\n        if (item.clearValidTo === true) {\n          assertClearValidToSupported(backend, \"node\");\n        }\n      }\n\n      const upsertAll = async (\n        target: GraphBackend | TransactionBackend,\n      ): Promise<{ results: Node<N>[]; mutations: number }> => {\n        const ids = items.map((item) => item.id);\n        // Full existing rows: the coalesce dirty-check needs their stored\n        // props, not just deleted_at.\n        const existingMap = new Map<string, BackendNodeRow>();\n\n        const boundGetNodes = bindExtraIfReachable(\n          target,\n          batchPointRead.extras.getNodes,\n          BATCH_POINT_READ.id,\n        );\n        if (boundGetNodes === undefined) {\n          const rows = await Promise.all(\n            ids.map((id) => target.getNode(graphId, kind, id)),\n          );\n          for (const row of rows) {\n            if (row !== undefined) existingMap.set(row.id, row);\n          }\n        } else {\n          const rows = await boundGetNodes.getNodes(graphId, kind, ids);\n          for (const row of rows) {\n            existingMap.set(row.id, row);\n          }\n        }\n\n        // Coalesced items are written straight to results (the existing or\n        // last-written node) and skipped from the write batch; see the\n        // single-upsert path and BaseStoreOptions.coalesceUnchangedUpserts.\n        const results: Node<N>[] = Array.from({ length: items.length });\n\n        // Bucket items into creates and updates\n        const toCreate: { index: number; input: CreateNodeInput }[] = [];\n        const toUpdate: {\n          index: number;\n          input: UpsertUpdateNodeInput;\n          clearDeleted: boolean;\n          existing?: BackendNodeRow;\n        }[] = [];\n\n        // Batch-local running state per id: the props AND validity window the\n        // row would hold after the writes queued so far, and the item index that\n        // queued that write. A later same-id item coalesces against this running\n        // value, not the once-prefetched row — otherwise [{x:B},{x:A}] on a row\n        // holding A would coalesce the second item against the stale prefetched\n        // A and drop the first item's write, breaking last-write-wins. The same\n        // staleness applies to the window: a copy re-stating the bound the\n        // prefetched row held, after an earlier copy already moved it, must\n        // write it back rather than coalesce.\n        //\n        // A QUEUED CREATE is registered here too. Leaving it out queued a SECOND\n        // create for a repeated id whose row does not exist yet, and the create\n        // batch rejected it as \"already exists\". Registered, the later copy\n        // takes the update path against the queued create — creates run before\n        // updates, so the row is there by then — producing exactly the row that\n        // sequential `upsertById` calls produce.\n        //\n        // `props` is the running value the dirty check compares against. It is\n        // undefined when no value could be computed (coalescing off, or the\n        // check rejected the input): presence of the ENTRY is what routes a\n        // later copy away from a second create, while the props only decide\n        // coalescing, and an unknown running value simply never coalesces.\n        // `window` is always computed — unlike the props it costs no Zod parse.\n        const pending = new Map<\n          string,\n          {\n            props: Record<string, unknown> | undefined;\n            window: UpsertWindow;\n            sourceIndex: number;\n          }\n        >();\n        // A coalesced item that matched an in-batch write resolves to that\n        // write's result (filled once the writes run), not a fabricated row.\n        const deferred: { index: number; sourceIndex: number }[] = [];\n\n        // A running value exists only to be dirty-checked, so a store without\n        // coalescing never needs to know which ids repeat.\n        const repeatedIds =\n          config.upsertDirtyCheck === undefined ?\n            new Set<string>()\n          : findRepeatedUpsertIds(items);\n\n        /**\n         * The dirty check for one item, or undefined when coalescing is off or\n         * the check rejected the input — a validation error must surface from\n         * the hooked write path, which re-validates and rejects the batch\n         * (matching flag-off), not from here.\n         */\n        function runDirtyCheck(\n          id: string,\n          currentProps: Record<string, unknown>,\n          inputProps: Record<string, unknown>,\n        ): UpsertDirtyCheck | undefined {\n          if (config.upsertDirtyCheck === undefined) return undefined;\n          try {\n            return config.upsertDirtyCheck(kind, id, currentProps, inputProps);\n          } catch {\n            return undefined;\n          }\n        }\n\n        let itemIndex = 0;\n        for (const item of items) {\n          const pendingEntry = pending.get(item.id);\n          const original = existingMap.get(item.id);\n\n          if (pendingEntry === undefined && original === undefined) {\n            toCreate.push({\n              index: itemIndex,\n              input: buildCreateInput(kind, item.props, item),\n            });\n            // A create merges over nothing, so the dirty check run against an\n            // EMPTY base is exactly the validated props the insert will store —\n            // the running value a later copy of this id compares against, and\n            // needed only when there IS a later copy.\n            pending.set(item.id, {\n              props:\n                repeatedIds.has(item.id) ?\n                  runDirtyCheck(item.id, {}, item.props)?.validatedProps\n                : undefined,\n              window: windowAfterUpsertCreate(item),\n              sourceIndex: itemIndex,\n            });\n            itemIndex++;\n            continue;\n          }\n\n          // A prior in-batch write left the row live; only the prefetched row\n          // (no prior write) can be soft-deleted and trigger a resurrection.\n          const deletedAt =\n            pendingEntry === undefined ?\n              requireDefined(original).deleted_at\n            : undefined;\n\n          const currentProps =\n            pendingEntry === undefined ?\n              rowPropsToObject(requireDefined(original).props)\n            : pendingEntry.props;\n          const dirty =\n            currentProps === undefined ? undefined : (\n              runDirtyCheck(item.id, currentProps, item.props)\n            );\n\n          // The window the row holds going into this item: the prefetched row's,\n          // or the one the batch's last queued write for this id leaves behind.\n          const currentWindow: UpsertWindow =\n            pendingEntry === undefined ?\n              {\n                valid_from: requireDefined(original).valid_from,\n                valid_to: requireDefined(original).valid_to,\n              }\n            : pendingEntry.window;\n\n          // An explicit window blocks coalescing ONLY when it would change the\n          // window already held — the same rule, through the same comparison,\n          // that shouldCoalesceUpsert applies to a single upsert. Blocking on the\n          // mere PRESENCE of a bound (what this path used to do) rewrote version,\n          // history, and revision state for every re-stated row a caller happened\n          // to hand its own current window.\n          const coalesce =\n            dirty?.unchanged === true &&\n            deletedAt === undefined &&\n            !upsertWindowChanges(item, currentWindow);\n\n          if (coalesce) {\n            if (pendingEntry === undefined) {\n              results[itemIndex] = narrowNode<N>(\n                rowToNode(requireDefined(original)),\n              );\n            } else {\n              deferred.push({\n                index: itemIndex,\n                sourceIndex: pendingEntry.sourceIndex,\n              });\n            }\n          } else {\n            toUpdate.push({\n              index: itemIndex,\n              input: buildUpsertUpdateInput(kind, item.id, item.props, item),\n              clearDeleted: deletedAt !== undefined,\n              ...(pendingEntry === undefined && original !== undefined ?\n                { existing: original }\n              : {}),\n            });\n            pending.set(item.id, {\n              props: dirty?.validatedProps,\n              // A resurrecting update rewrites BOTH bounds (buildUpdateNode's\n              // clearDeleted leg stamps `valid_from` and reopens `valid_to`);\n              // a live-row update moves only `valid_to`.\n              window:\n                deletedAt === undefined ?\n                  windowAfterUpsertUpdate(currentWindow, item)\n                : windowAfterUpsertCreate(item),\n              sourceIndex: itemIndex,\n            });\n          }\n          itemIndex++;\n        }\n\n        const createInputs = toCreate.map((entry) => entry.input);\n        const updateEntries = toUpdate.map((entry) => ({\n          input: entry.input,\n          clearDeleted: entry.clearDeleted,\n          ...(entry.existing === undefined ? {} : { existing: entry.existing }),\n        }));\n        const mutationAttempt = await executeNodeResolvedMutationSet(\n          createInputs,\n          updateEntries,\n          target,\n        );\n        if (mutationAttempt.outcome === \"unsupported\") {\n          if (toCreate.length > 0) {\n            const created = await executeNodeCreateBatch(createInputs, target);\n            for (const [index, entry] of toCreate.entries()) {\n              results[entry.index] = narrowNode<N>(\n                requireDefined(created[index]),\n              );\n            }\n          }\n\n          if (toUpdate.length > 0) {\n            const updated = await executeNodeUpsertUpdateBatch(\n              updateEntries,\n              target,\n            );\n            for (const [updateIndex, entry] of toUpdate.entries()) {\n              const result = requireDefined(updated[updateIndex]);\n              results[entry.index] = narrowNode<N>(result);\n            }\n          }\n        } else {\n          const mutationSet = mutationAttempt.value;\n          for (const [index, entry] of toCreate.entries()) {\n            results[entry.index] = narrowNode<N>(\n              requireDefined(mutationSet.created[index]),\n            );\n          }\n          for (const [index, entry] of toUpdate.entries()) {\n            results[entry.index] = narrowNode<N>(\n              requireDefined(mutationSet.updated[index]),\n            );\n          }\n        }\n\n        // Items that coalesced against an in-batch write take that write's\n        // result (now filled). Its sourceIndex is always a write slot — a\n        // queued create or a queued update, both filled above.\n        for (const { index, sourceIndex } of deferred) {\n          results[index] = requireDefined(results[sourceIndex]);\n        }\n\n        return { results, mutations: toCreate.length + toUpdate.length };\n      };\n\n      const { results, mutations } = await runResolvedMutationSetConverging(\n        \"node\",\n        backend,\n        () =>\n          runOptionallyInTransaction(backend, (target) => upsertAll(target)),\n      );\n      // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n      // autocommit bulk write. Coalesced items wrote nothing, so only real\n      // mutations count toward the threshold. A no-op inside a caller\n      // transaction (the hook is intentionally undefined there).\n      await config.maybeRefreshStatisticsAfterBulk?.(mutations);\n      return results;\n    },\n\n    async bulkInsert(\n      items: readonly Readonly<{\n        props: z.input<N[\"schema\"]>;\n        id?: string;\n        validFrom?: string | null;\n        validTo?: string;\n      }>[],\n    ): Promise<void> {\n      const batchInputs = mapBulkNodeInputs(kind, items);\n\n      await executeNodeCreateNoReturnBatch(batchInputs, backend);\n      await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n    },\n\n    async bulkDelete(ids: readonly NodeId<N>[]): Promise<void> {\n      if (ids.length === 0) return;\n      await executeNodeDeleteBatch(kind, ids, backend);\n    },\n\n    async findByConstraint(\n      constraintName: string,\n      props: z.input<N[\"schema\"]>,\n    ): Promise<Node<N> | undefined> {\n      const result = await executeFindByConstraint(\n        kind,\n        constraintName,\n        props,\n        backend,\n      );\n      return result === undefined ? undefined : narrowNode<N>(result);\n    },\n\n    async bulkFindByConstraint(\n      constraintName: string,\n      items: readonly Readonly<{\n        props: z.input<N[\"schema\"]>;\n      }>[],\n    ): Promise<(Node<N> | undefined)[]> {\n      if (items.length === 0) return [];\n\n      const mappedItems = items.map((item) => ({\n        props: item.props,\n      }));\n\n      const results = await executeBulkFindByConstraint(\n        kind,\n        constraintName,\n        mappedItems,\n        backend,\n      );\n      return results.map((result) =>\n        result === undefined ? undefined : narrowNode<N>(result),\n      );\n    },\n\n    async bulkFindByIndex(\n      indexName: string,\n      items: readonly Readonly<{\n        props: Partial<z.input<N[\"schema\"]>>;\n      }>[],\n      options?: NodeBulkFindByIndexOptions,\n    ): Promise<readonly Node<N>[][]> {\n      if (items.length === 0) return [];\n\n      const mappedItems = items.map((item) => ({\n        props: item.props,\n      }));\n\n      const results = await executeBulkFindByIndex(\n        kind,\n        indexName,\n        mappedItems,\n        backend,\n        options,\n      );\n      return results.map((bucket) => narrowNodes<N>(bucket));\n    },\n\n    async getOrCreateByConstraint(\n      constraintName: string,\n      props: z.input<N[\"schema\"]>,\n      options?: NodeGetOrCreateByConstraintOptions,\n    ): Promise<NodeGetOrCreateByConstraintResult<N>> {\n      // No enclosing transaction: the found path is a pure read and must not\n      // pay for one, and each write leg (create / upsert) opens its own\n      // hooked transaction — nesting them here would fire their hooks before\n      // this wrapper's COMMIT. Race convergence lives in\n      // executeGetOrCreateByConstraint (re-probe on a create collision).\n      const result = await executeGetOrCreateByConstraint(\n        kind,\n        constraintName,\n        props,\n        backend,\n        options,\n      );\n      return result as NodeGetOrCreateByConstraintResult<N>;\n    },\n\n    async bulkGetOrCreateByConstraint(\n      constraintName: string,\n      items: readonly Readonly<{\n        props: z.input<N[\"schema\"]>;\n      }>[],\n      options?: NodeGetOrCreateByConstraintOptions,\n    ): Promise<NodeGetOrCreateByConstraintResult<N>[]> {\n      if (items.length === 0) return [];\n\n      const mappedItems = items.map((item) => ({\n        props: item.props,\n      }));\n\n      const getOrCreateAll = async (\n        target: GraphBackend | TransactionBackend,\n      ): Promise<NodeGetOrCreateByConstraintResult<N>[]> => {\n        const results = await executeBulkGetOrCreateByConstraint(\n          kind,\n          constraintName,\n          mappedItems,\n          target,\n          options,\n        );\n        return results as NodeGetOrCreateByConstraintResult<N>[];\n      };\n\n      if (\n        backend.capabilities.execution.interactiveTransactions &&\n        \"transaction\" in backend\n      ) {\n        return backend.transaction(async (txBackend) =>\n          getOrCreateAll(txBackend),\n        );\n      }\n      return getOrCreateAll(backend);\n    },\n  };\n}\n","/**\n * Collection Factory for Store\n *\n * Creates typed node and edge collection proxies for both\n * Store and TransactionContext to reduce code duplication.\n */\nimport {\n  type BATCH_POINT_READ,\n  type ENDPOINT_SET_READ,\n} from \"../backend/capabilities/bundle-registry\";\nimport { type BundleVerdictOf } from \"../backend/capabilities/resolve\";\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { type TemporalMode } from \"../core/types\";\nimport { KindNotFoundError } from \"../errors\";\nimport { type QueryBuilder } from \"../query/builder\";\nimport type { CompiledSelectSql } from \"../query/sql-intent\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { createEdgeCollection, createNodeCollection } from \"./collections\";\nimport { type UpsertDirtyCheckFunction } from \"./collections/coalesce\";\nimport { type EdgeUpsertUpdateBatchEntry } from \"./collections/edge-collection\";\nimport {\n  type NodeSetUpdateRequest,\n  type NodeUpsertUpdateBatchEntry,\n  type UpsertUpdateNodeInput,\n} from \"./collections/node-collection\";\nimport type { ResolvedMutationSetAttempt } from \"./resolved-mutation-set\";\nimport { type EdgeRow, type NodeRow } from \"./row-mappers\";\nimport {\n  type CreateEdgeInput,\n  type CreateNodeInput,\n  type Edge,\n  type GetOrCreateAction,\n  type GraphEdgeCollections,\n  type GraphNodeCollections,\n  type IfExistsMode,\n  type Node,\n  type NodeBulkFindByIndexOptions,\n  type NodeGetOrCreateByConstraintOptions,\n  type QueryOptions,\n} from \"./types\";\n\n/**\n * Operation functions passed to collections.\n */\nexport type NodeOperations = Readonly<{\n  defaultTemporalMode: TemporalMode;\n  rowToNode: (row: NodeRow) => Node;\n  /**\n   * Store-provided hook run after an autocommit bulk write completes;\n   * refreshes planner statistics when the row count crosses the\n   * configured threshold. Absent on transaction-scoped collections.\n   */\n  maybeRefreshStatisticsAfterBulk?:\n    ((rowCount: number) => Promise<void>) | undefined;\n  executeCreate: (\n    input: CreateNodeInput,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Node>;\n  executeCreateBatch: (\n    inputs: readonly CreateNodeInput[],\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{ propsPreValidated?: true }>,\n  ) => Promise<readonly Node[]>;\n  executeCreateNoReturnBatch: (\n    inputs: readonly CreateNodeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeUpdate: (\n    input: UpsertUpdateNodeInput,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{ clearDeleted?: boolean }>,\n  ) => Promise<Node>;\n  executeNodeSetUpdate: (\n    kind: string,\n    patch: Record<string, unknown>,\n    candidateIds: CompiledSelectSql,\n    candidateIdColumn: string,\n    backend: GraphBackend | TransactionBackend,\n    request: NodeSetUpdateRequest,\n  ) => Promise<Readonly<{ affectedCount: number }>>;\n  executeUpsertUpdateBatch: (\n    entries: readonly NodeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Node[]>;\n  executeResolvedMutationSet: (\n    creates: readonly CreateNodeInput[],\n    updates: readonly NodeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<\n    ResolvedMutationSetAttempt<\n      Readonly<{ created: readonly Node[]; updated: readonly Node[] }>\n    >\n  >;\n  prepareReplacement: (\n    kind: string,\n    props: Record<string, unknown>,\n  ) => Record<string, unknown>;\n  executeReplacementBatch: (\n    kind: string,\n    items: readonly Readonly<{\n      id: string;\n      props: Record<string, unknown>;\n    }>[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<ResolvedMutationSetAttempt<readonly Node[]>>;\n  /**\n   * Coalesce dirty-check for `upsertById` / `bulkUpsertById`. Present only when\n   * the store was created with `coalesceUnchangedUpserts: true`; its absence is\n   * the off switch. Given the current (parsed) props, returns the props the\n   * upsert would persist and whether they are unchanged; the collection owns\n   * the other preconditions.\n   */\n  upsertDirtyCheck?: UpsertDirtyCheckFunction;\n  executeDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeDeleteBatch: (\n    kind: string,\n    ids: readonly string[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeHardDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  temporalRowMatcher: (options?: QueryOptions) => (row: NodeRow) => boolean;\n  createQuery?: () => QueryBuilder<GraphDef>;\n  executeGetOrCreateByConstraint: (\n    kind: string,\n    constraintName: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeGetOrCreateByConstraintOptions,\n  ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>>;\n  executeBulkGetOrCreateByConstraint: (\n    kind: string,\n    constraintName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeGetOrCreateByConstraintOptions,\n  ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]>;\n  executeFindByConstraint: (\n    kind: string,\n    constraintName: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Node | undefined>;\n  executeBulkFindByConstraint: (\n    kind: string,\n    constraintName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<(Node | undefined)[]>;\n  executeBulkFindByIndex: (\n    kind: string,\n    indexName: string,\n    items: readonly Readonly<{ props: Record<string, unknown> }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: NodeBulkFindByIndexOptions,\n  ) => Promise<Node[][]>;\n}>;\n\nexport type EdgeOperations = Readonly<{\n  defaultTemporalMode: TemporalMode;\n  rowToEdge: (row: EdgeRow) => Edge;\n  /**\n   * Store-provided hook run after an autocommit bulk write completes;\n   * refreshes planner statistics when the row count crosses the\n   * configured threshold. Absent on transaction-scoped collections.\n   */\n  maybeRefreshStatisticsAfterBulk?:\n    ((rowCount: number) => Promise<void>) | undefined;\n  executeCreate: (\n    input: CreateEdgeInput,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Edge>;\n  executeCreateBatch: (\n    inputs: readonly CreateEdgeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Edge[]>;\n  executeCreateNoReturnBatch: (\n    inputs: readonly CreateEdgeInput[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeUpdate: (\n    input: {\n      id: string;\n      identity: Readonly<{\n        kind: string;\n        fromKind?: string;\n        fromId?: string;\n        toKind?: string;\n        toId?: string;\n      }>;\n      props: Partial<Record<string, unknown>>;\n      validTo?: string;\n      clearValidTo?: true;\n    },\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<Edge>;\n  executeUpsertUpdateBatch: (\n    entries: readonly EdgeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<readonly Edge[]>;\n  executeResolvedMutationSet: (\n    creates: readonly CreateEdgeInput[],\n    updates: readonly EdgeUpsertUpdateBatchEntry[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<\n    ResolvedMutationSetAttempt<\n      Readonly<{ created: readonly Edge[]; updated: readonly Edge[] }>\n    >\n  >;\n  /**\n   * Coalesce dirty-check for `bulkUpsertById` (props only — endpoints are the\n   * edge's identity). Present only when the store was created with\n   * `coalesceUnchangedUpserts: true`; its absence is the off switch.\n   */\n  upsertDirtyCheck?: UpsertDirtyCheckFunction;\n  executeDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeDeleteBatch: (\n    kind: string,\n    ids: readonly string[],\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  executeHardDelete: (\n    kind: string,\n    id: string,\n    backend: GraphBackend | TransactionBackend,\n  ) => Promise<void>;\n  temporalRowMatcher: (options?: QueryOptions) => (row: EdgeRow) => boolean;\n  createQuery?: () => QueryBuilder<GraphDef>;\n  executeGetOrCreateByEndpoints: (\n    kind: string,\n    fromKind: string,\n    fromId: string,\n    toKind: string,\n    toId: string,\n    props: Record<string, unknown>,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      ifExists?: IfExistsMode;\n      validFrom?: string | null;\n      validTo?: string;\n      clearValidTo?: true;\n      onImmutableLowerBound?: \"preserve\" | \"refuse\";\n    }>,\n  ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>>;\n  executeBulkGetOrCreateByEndpoints: (\n    kind: string,\n    items: readonly Readonly<{\n      fromKind: string;\n      fromId: string;\n      toKind: string;\n      toId: string;\n      props: Record<string, unknown>;\n      validFrom?: string | null;\n      validTo?: string;\n      clearValidTo?: true;\n      onImmutableLowerBound?: \"preserve\" | \"refuse\";\n    }>[],\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      ifExists?: IfExistsMode;\n    }>,\n  ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]>;\n  executeFindByEndpoints: (\n    kind: string,\n    fromKind: string,\n    fromId: string,\n    toKind: string,\n    toId: string,\n    backend: GraphBackend | TransactionBackend,\n    options?: Readonly<{\n      matchOn?: readonly string[];\n      props?: Record<string, unknown>;\n    }>,\n  ) => Promise<Edge | undefined>;\n}>;\n\n/**\n * Creates a typed node collections proxy.\n *\n * The proxy dynamically creates NodeCollection instances for each node kind\n * when accessed.\n */\nexport function createNodeCollectionsProxy<G extends GraphDef>(\n  graph: G,\n  graphId: string,\n  registry: KindRegistry,\n  backend: GraphBackend | TransactionBackend,\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>,\n  operations: NodeOperations,\n): GraphNodeCollections<G> {\n  const collectionCache = new Map<string, unknown>();\n\n  // The proxy dynamically returns typed collections for each key.\n  // Type assertions are necessary because the proxy pattern doesn't preserve\n  // the relationship between keys and their specific node types at compile time.\n  return new Proxy({} as unknown as GraphNodeCollections<G>, {\n    get: (_, kind: string) => {\n      if (!Object.hasOwn(graph.nodes, kind)) {\n        throw new KindNotFoundError(kind, \"node\");\n      }\n\n      const cached = collectionCache.get(kind);\n      if (cached !== undefined) {\n        return cached;\n      }\n\n      const collection = createNodeCollection({\n        graphId,\n        kind,\n        backend,\n        batchPointRead,\n        ...operations,\n      });\n      collectionCache.set(kind, collection);\n      return collection;\n    },\n  });\n}\n\n/**\n * Creates a typed edge collections proxy.\n *\n * The proxy dynamically creates EdgeCollection instances for each edge kind\n * when accessed.\n */\nexport function createEdgeCollectionsProxy<G extends GraphDef>(\n  graph: G,\n  graphId: string,\n  registry: KindRegistry,\n  backend: GraphBackend | TransactionBackend,\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>,\n  endpointSetRead: BundleVerdictOf<typeof ENDPOINT_SET_READ>,\n  operations: EdgeOperations,\n): GraphEdgeCollections<G> {\n  const collectionCache = new Map<string, unknown>();\n\n  // The proxy dynamically returns typed collections for each key.\n  // Type assertions are necessary because the proxy pattern doesn't preserve\n  // the relationship between keys and their specific edge types at compile time.\n  return new Proxy({} as unknown as GraphEdgeCollections<G>, {\n    get: (_, kind: string) => {\n      if (!Object.hasOwn(graph.edges, kind)) {\n        throw new KindNotFoundError(kind, \"edge\");\n      }\n\n      const cached = collectionCache.get(kind);\n      if (cached !== undefined) {\n        return cached;\n      }\n\n      const collection = createEdgeCollection({\n        graphId,\n        kind,\n        backend,\n        batchPointRead,\n        endpointSetRead,\n        ...operations,\n      });\n      collectionCache.set(kind, collection);\n      return collection;\n    },\n  });\n}\n","import type { SchemaVersionRow } from \"../backend/types\";\nimport {\n  ConfigurationError,\n  SchemaContentConflictError,\n  StaleVersionError,\n} from \"../errors\";\nimport type { EvolutionPlan } from \"../schema/evolution-plan\";\nimport type { SchemaIdentity } from \"../schema/types\";\nimport { type StoreRef, type TransactionOutcome } from \"./types\";\n\n/** Selects the snapshot used to plan without taking a schema write fence. */\nexport type PlanEvolutionOptions = Readonly<{\n  /** Defaults to a fresh, read-only active-schema lookup. */\n  source?: \"database\" | \"cached\";\n}>;\n\n/** Read-only reconciliation after the caller has committed its transaction. */\nexport type RefreshSchemaOptions<TStore> = Readonly<{\n  ref?: StoreRef<TStore>;\n  /** Minimum committed version expected; a matching cached snapshot needs no SQL. */\n  minVersion?: number;\n}>;\n\n/** Options for applying a precomputed evolution plan on a caller transaction. */\nexport type EvolvedTransactionOptions = Readonly<{\n  /** Finite exclusive schema-fence acquisition budget for change plans, in milliseconds. */\n  waitBudgetMs?: number;\n}>;\n\n/** Schema metadata is provisional until the caller commits the outer transaction. */\nexport type EvolvedTransactionOutcome<T> = Readonly<{\n  result: TransactionOutcome<T>[\"result\"];\n  receipt: TransactionOutcome<T>[\"receipt\"] &\n    Readonly<{ schema: SchemaIdentity }>;\n}>;\n\ninterface AdoptedScopeState {\n  depth: number;\n  exclusive: boolean;\n}\n\nconst ACTIVE_ADOPTED_TRANSACTIONS = new WeakMap<object, AdoptedScopeState>();\n\n/** Prevent schema-lock upgrades through a nested adopted callback. */\nexport async function withAdoptedTransactionScope<T>(\n  nativeTransaction: unknown,\n  callback: () => Promise<T>,\n  exclusive = false,\n): Promise<T> {\n  if (typeof nativeTransaction !== \"object\" || nativeTransaction === null) {\n    return callback();\n  }\n  const activeScope = ACTIVE_ADOPTED_TRANSACTIONS.get(nativeTransaction);\n  if (\n    activeScope?.exclusive === true ||\n    (exclusive && activeScope !== undefined)\n  ) {\n    throw new ConfigurationError(\n      \"An adopted callback is already active on this transaction.\",\n      {\n        code: \"ADOPTED_TRANSACTION_ALREADY_ACTIVE\",\n      },\n    );\n  }\n  if (activeScope === undefined) {\n    ACTIVE_ADOPTED_TRANSACTIONS.set(nativeTransaction, { depth: 1, exclusive });\n  } else {\n    activeScope.depth += 1;\n  }\n  try {\n    return await callback();\n  } finally {\n    const scope = ACTIVE_ADOPTED_TRANSACTIONS.get(nativeTransaction);\n    if (scope !== undefined) {\n      scope.depth -= 1;\n      if (scope.depth === 0)\n        ACTIVE_ADOPTED_TRANSACTIONS.delete(nativeTransaction);\n    }\n  }\n}\n\n/** Refuses options that an evolution operation cannot honor. */\nexport function assertEvolutionOptions(\n  options: object | undefined,\n  allowedKeys: readonly string[],\n): void {\n  const unknownOptions = Object.keys(options ?? {}).filter(\n    (key) => !allowedKeys.includes(key),\n  );\n  if (unknownOptions.length > 0) {\n    throw new ConfigurationError(\"Unsupported schema evolution options.\", {\n      code: \"EVOLUTION_OPTIONS_UNSUPPORTED\",\n      options: unknownOptions,\n    });\n  }\n}\n\n/** Checks the fenced active schema against the snapshot that minted a plan. */\nexport function assertEvolutionPlanBaseline(\n  plan: EvolutionPlan,\n  active: SchemaVersionRow | undefined,\n): void {\n  if (active?.version !== plan.baseline.version) {\n    throw new StaleVersionError({\n      graphId: plan.graphId,\n      expected: plan.baseline.version,\n      actual: active?.version ?? 0,\n    });\n  }\n  if (active.schema_hash !== plan.baseline.hash) {\n    throw new SchemaContentConflictError({\n      graphId: plan.graphId,\n      version: active.version,\n      existingHash: active.schema_hash,\n      incomingHash: plan.baseline.hash,\n    });\n  }\n}\n","// This overlay only guards existing operation members; it does not narrow the port.\n// eslint-disable-next-line no-restricted-syntax -- preserves session/resource derivation for a callback-owned backend\nimport { deriveBackend } from \"../backend/derive-backend\";\nimport { GRAPH_BACKEND_PROJECTION_KEYS } from \"../backend/graph-backend-keys\";\nimport type { GraphBackend, TransactionBackend } from \"../backend/types\";\nimport { TransactionClosedError } from \"../errors\";\nimport { createDataKeyedBag } from \"../utils/object\";\nimport { inheritRecordedTransactionBindings } from \"./recorded-capture\";\n\n/** A callback-owned backend whose operations refuse execution after sealing. */\nexport type ScopedExecutionBackend<\n  T extends GraphBackend | TransactionBackend,\n> = Readonly<{\n  backend: T;\n  seal: () => void;\n}>;\n\nconst NESTED_OPERATION_PORTS = new Set<PropertyKey>([\n  \"commands\",\n  \"catalog\",\n  \"lineage\",\n  \"recordedTime\",\n]);\n\n/**\n * Decorates an adopted session before any callback views are constructed.\n * A deferred operation keeps this backend, so its execution checks the scope\n * even if its query or collection was built while the callback was active.\n */\nexport function scopeBackendExecution<\n  T extends GraphBackend | TransactionBackend,\n>(sourceBackend: T): ScopedExecutionBackend<T> {\n  let active = true;\n\n  function assertActive(): void {\n    if (!active) throw new TransactionClosedError();\n  }\n\n  function guardOperationPort(port: object): object {\n    const members = createDataKeyedBag<unknown>() as Record<\n      PropertyKey,\n      unknown\n    >;\n    for (const key of Reflect.ownKeys(port)) {\n      const value: unknown = Reflect.get(port, key, port);\n      members[key] =\n        typeof value === \"function\" ?\n          (...args: readonly unknown[]) => {\n            assertActive();\n            return Reflect.apply(value, undefined, args) as unknown;\n          }\n        : value;\n    }\n    return members;\n  }\n\n  const guardedMembers = createDataKeyedBag<unknown>() as Record<\n    PropertyKey,\n    unknown\n  >;\n  for (const key of new Set<PropertyKey>([\n    ...GRAPH_BACKEND_PROJECTION_KEYS,\n    ...Reflect.ownKeys(sourceBackend),\n  ])) {\n    if (!Reflect.has(sourceBackend, key)) continue;\n    const value: unknown = Reflect.get(sourceBackend, key, sourceBackend);\n    if (typeof value === \"function\") {\n      guardedMembers[key] = (...args: readonly unknown[]) => {\n        assertActive();\n        return Reflect.apply(value, undefined, args) as unknown;\n      };\n    } else if (\n      NESTED_OPERATION_PORTS.has(key) &&\n      typeof value === \"object\" &&\n      value !== null\n    ) {\n      guardedMembers[key] = guardOperationPort(value);\n    }\n  }\n\n  const backend = deriveBackend(sourceBackend, guardedMembers as T);\n  inheritRecordedTransactionBindings(sourceBackend, backend, assertActive);\n  return {\n    backend,\n    seal: () => {\n      active = false;\n    },\n  };\n}\n","import type { CLAIMS } from \"../backend/capabilities/bundle-registry\";\nimport { projectBackend } from \"../backend/derive-backend\";\nimport { type GraphBackend } from \"../backend/types\";\nimport { type Assert, type ContainsAll } from \"../utils/type-assert\";\n\n/**\n * Members that are safe to expose through a history-enabled adapter Store.\n *\n * Graph entity writes remain because the source is the capture-wrapped\n * backend. Direct raw SQL, native import, graph clearing, and nested backend\n * transactions stay internal because each can mutate live rows without a\n * corresponding capture flush.\n */\nconst HISTORY_STORE_BACKEND_KEYS = [\n  \"assertRuntimeContributionsInitialized\",\n  \"assertVectorSlotInitialized\",\n  \"assertVectorSlotsInitialized\",\n  \"bootstrapTables\",\n  \"capabilities\",\n  \"catalog\",\n  \"lineage\",\n  \"recordedTime\",\n  \"checkUnique\",\n  \"checkUniqueBatch\",\n  // The edge cardinality fence. Both members write only the claim relation —\n  // a reservation whose holder is a graph row, never a graph row itself — so\n  // neither can bypass a capture flush, and a history-enabled store that could\n  // not reach them would write constrained edges unfenced.\n  \"claimEdgeCardinality\",\n  \"claimEdgeCardinalityGuarded\",\n  \"claimEdgeCardinalityBatch\",\n  \"claimIndexMaterialization\",\n  \"close\",\n  \"commitSchemaVersion\",\n  \"commitSchemaVersionIfKindsEmpty\",\n  \"lockSchemaVersionForWrite\",\n  \"lockSchemaVersionAndGraphWrite\",\n  \"compileSql\",\n  \"countEdgesByKind\",\n  \"countEdgesFrom\",\n  \"countNodesByKind\",\n  \"createVectorIndex\",\n  \"deleteEdge\",\n  \"deleteEdgesBatch\",\n  \"deleteEmbedding\",\n  \"deleteEmbeddingBatch\",\n  \"deleteFulltext\",\n  \"deleteFulltextBatch\",\n  \"deleteNode\",\n  \"deleteUnique\",\n  \"hardDeleteUniquesByNodeIds\",\n  \"deleteVectorSlotContribution\",\n  \"dialect\",\n  \"dropVectorIndex\",\n  \"fenceSql\",\n  \"adoptBaseSchema\",\n  \"assertBaseSchemaCurrent\",\n  \"edgeExistsBetween\",\n  \"ensureContributionMaterializationsTable\",\n  // Installs a database-global extension — and `ensureTrigramExtension` is the\n  // same operation under its deprecated `pg_trgm`-only name, so the two are\n  // classified together or not at all. Like the `ensure*Table` members they sit\n  // beside, they create storage-level scaffolding and write no graph row, so\n  // neither can bypass a capture flush.\n  \"ensureExtension\",\n  \"ensureEdgeMatchIdentityStorage\",\n  \"ensureFulltextTable\",\n  \"ensureIndexMaterializationsTable\",\n  \"ensureKindRemovalsTable\",\n  \"ensureReconciliationMarkersTable\",\n  \"ensureRevisionOriginsTable\",\n  \"ensureRuntimeContributions\",\n  \"ensureTrigramExtension\",\n  \"ensureVectorSlotContribution\",\n  \"ensureVectorSlotContributions\",\n  \"execute\",\n  \"executeTemporaryStatement\",\n  \"findEdgesByKind\",\n  \"findEdgesByEndpointSet\",\n  \"findEdgesByHeterogeneousEndpointSet\",\n  \"findEdgesConnectedTo\",\n  \"findNodesByKind\",\n  \"fulltextSearch\",\n  \"fulltextStrategy\",\n  \"getActiveSchema\",\n  \"getAllKindRemovals\",\n  \"getContributionMaterialization\",\n  \"getEdge\",\n  \"getEdges\",\n  \"getIndexMaterialization\",\n  \"getIndexMaterializations\",\n  \"getNode\",\n  \"getNodes\",\n  \"getPendingKindRemovals\",\n  \"getReconciliationMarker\",\n  \"getSchemaVersion\",\n  \"hardDeleteEdge\",\n  \"hardDeleteEdgesBatch\",\n  \"hardDeleteNode\",\n  // Reaps the claims a removed kind's nodes own. Like the sibling\n  // `hardDeleteUniquesByNodeIds` beside it, it clears sidecar rows whose\n  // entity rows are already gone, so it cannot bypass a capture flush.\n  \"hardDeleteUniquesByConcreteKind\",\n  \"hardDeleteUniquesByNodeIds\",\n  \"hybridSearch\",\n  \"insertEdge\",\n  \"commands\",\n  \"insertEdgeNoReturn\",\n  \"insertEdgesBatch\",\n  \"insertEdgesBatchReturning\",\n  \"insertEdgesDurableBatchReturning\",\n  \"insertNode\",\n  \"insertNodeIfAbsent\",\n  \"insertNodeIfAbsentWithSchemaFence\",\n  \"insertNodeWithSchemaFence\",\n  \"insertNodeNoReturn\",\n  \"insertNodesBatch\",\n  \"insertNodesBatchReturning\",\n  \"insertUnique\",\n  \"insertUniqueBatch\",\n  \"probeContributions\",\n  // Housekeeping for the relation above: drops claim rows whose holders are\n  // already gone. Writes no graph row.\n  \"purgeEdgeClaims\",\n  // Read-only fence audit. Writes nothing at all, so it can bypass no capture\n  // flush, and a history-enabled store that could not reach it would have no\n  // way to report which declared constraint its data already violates.\n  \"readConstraintFenceViolations\",\n  \"recordContributionMaterialization\",\n  \"recordIndexMaterialization\",\n  \"recordKindRemoval\",\n  \"refreshStatistics\",\n  \"releaseIndexMaterializationClaim\",\n  \"setActiveVersion\",\n  \"setReconciliationMarker\",\n  \"tableNames\",\n  \"updateEdge\",\n  \"updateNode\",\n  \"upsertHeterogeneousNodes\",\n  \"updateResolvedNodesBatch\",\n  \"compareAndSetNode\",\n  \"updateNodeSet\",\n  \"upsertEmbedding\",\n  \"upsertEmbeddingBatch\",\n  \"upsertFulltext\",\n  \"upsertFulltextBatch\",\n  \"vectorSearch\",\n  \"vectorStrategy\",\n  \"verifyContributions\",\n] as const satisfies readonly (keyof GraphBackend)[];\n\ntype HistoryStoreBackendMember = (typeof HISTORY_STORE_BACKEND_KEYS)[number];\n\n// I13: every `claims` core member is exposed through the history-store\n// projection, or a history-enabled Store could silently lose access to a\n// member `claimSupport` binds — unfencing exactly the constrained edge\n// writes the claim relation exists to fence.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _historyStoreContainsClaimsCore = Assert<\n  ContainsAll<\n    typeof HISTORY_STORE_BACKEND_KEYS,\n    (typeof CLAIMS)[\"core\"][number]\n  >\n>;\n\ntype UnsafeHistoryStoreBackendMember =\n  | \"clearGraph\"\n  | \"commitSchemaVersionWithPreflight\"\n  | \"instantiateGraphTemplate\"\n  | \"executeDdl\"\n  | \"executeRaw\"\n  | \"executeStatement\"\n  | \"ensureIdentityTables\"\n  | \"identityTableDdl\"\n  | \"rebuildContribution\"\n  | \"recordedTableDdl\"\n  | \"repairContributions\"\n  | \"registerGraphTemplate\"\n  | \"schemaWriteTransaction\"\n  | \"transaction\"\n  | \"trustedImport\";\n\ntype UnclassifiedHistoryStoreBackendMember = Exclude<\n  keyof GraphBackend,\n  HistoryStoreBackendMember | UnsafeHistoryStoreBackendMember\n>;\n\nexport type HistoryStoreBackend =\n  UnclassifiedHistoryStoreBackendMember extends never ?\n    Readonly<Pick<GraphBackend, HistoryStoreBackendMember>>\n  : never;\n\n/** @internal */\nexport function createHistoryStoreBackendProjection(\n  backend: GraphBackend,\n): HistoryStoreBackend {\n  return Object.freeze(projectBackend(backend, HISTORY_STORE_BACKEND_KEYS));\n}\n","/**\n * `store.introspect()` — unified read of the merged schema.\n *\n * Returns a coherent snapshot of \"what does my schema look like right\n * now\" suitable for schema-management UIs, codegen, and IDE plugins.\n * The previous surface was fragmented across `registry.hasNodeType`,\n * `store.deprecatedKinds`, and direct graph poking; `introspect()`\n * unifies them with explicit `origin` markers distinguishing\n * compile-time from runtime declarations.\n *\n * Pure read — no I/O. Built from the in-memory `GraphDef` and the\n * persisted-but-already-merged `extension`. `schemaVersion` /\n * `schemaHash` are populated when the loader cached them at\n * construction time and `undefined` otherwise; consumers needing a\n * fresh read should call `backend.getActiveSchema(graphId)` directly.\n */\nimport {\n  type AllEdgeTypes,\n  type AllNodeTypes,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport { projectTargetKinds } from \"../core/edge-endpoints\";\nimport { canonicalAnnotations } from \"../core/json-value\";\nimport {\n  type Cardinality,\n  type Collation,\n  type EdgeType,\n  type EndpointExistence,\n  type GraphAnnotations,\n  type KindAnnotations,\n  type NodeRegistration,\n  type NodeType,\n  type UniquenessScope,\n} from \"../core/types\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport {\n  buildGraphExtensionOntologyKeySet,\n  compileTimeOntologyKey,\n  extensionKindNames,\n} from \"../graph-extension/ontology-keys\";\nimport { getTypeName } from \"../ontology/types\";\nimport { serializeSchemaProperties } from \"../schema/serializer\";\nimport { type JsonSchema } from \"../schema/types\";\n\nexport type SchemaIntrospection = Readonly<{\n  graphId: string;\n  /** Active schema version on the backend, when known to the caller. */\n  schemaVersion: number | undefined;\n  /** Hash of the active schema document, when known to the caller. */\n  schemaHash: string | undefined;\n  /** Consumer-owned graph-scoped JSON metadata. */\n  annotations: GraphAnnotations | undefined;\n  kinds: readonly KindIntrospection[];\n  edges: readonly EdgeIntrospection[];\n  ontology: readonly OntologyIntrospection[];\n  deprecatedKinds: ReadonlySet<string>;\n  /**\n   * The persisted graph extension, or `undefined` when the store has\n   * no extensions. Round-trips: passing this value to\n   * `defineGraphExtension` and `evolve` against an empty graph yields\n   * a graph with the same extension kinds.\n   */\n  extension: GraphExtension | undefined;\n}>;\n\nexport type KindIntrospection = Readonly<{\n  name: string;\n  origin: \"compile-time\" | \"runtime\";\n  description: string | undefined;\n  annotations: KindAnnotations | undefined;\n  deprecated: boolean;\n  /**\n   * JSON-Schema view of the kind's properties. For extension kinds the\n   * lower-level `ExtensionPropertyType` shape (with first-class\n   * `searchable` / `embedding` modifiers) is reachable via\n   * `introspection.extension.nodes[name].properties`.\n   */\n  properties: JsonSchema;\n  unique: readonly UniqueIntrospection[];\n}>;\n\nexport type EdgeIntrospection = Readonly<{\n  name: string;\n  origin: \"compile-time\" | \"runtime\";\n  description: string | undefined;\n  from: readonly string[];\n  to: readonly string[];\n  cardinality: Cardinality;\n  endpointExistence: EndpointExistence;\n  properties: JsonSchema;\n  annotations: KindAnnotations | undefined;\n  deprecated: boolean;\n}>;\n\nexport type OntologyIntrospection = Readonly<{\n  metaEdge: string;\n  from: string;\n  to: string;\n  origin: \"compile-time\" | \"runtime\";\n}>;\n\nexport type UniqueIntrospection = Readonly<{\n  name: string;\n  fields: readonly string[];\n  scope: UniquenessScope;\n  collation: Collation;\n}>;\n\ntype IntrospectContext = Readonly<{\n  graphId: string;\n  schemaVersion: number | undefined;\n  schemaHash: string | undefined;\n}>;\n\nexport function introspectSchema<G extends GraphDef>(\n  graph: G,\n  context: IntrospectContext,\n): SchemaIntrospection {\n  const extension = graph.extension;\n  const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n    extensionKindNames(extension);\n  const deprecated = graph.deprecatedKinds;\n\n  const kinds: KindIntrospection[] = [];\n  for (const [name, registration] of Object.entries(graph.nodes)) {\n    const reg = registration as NodeRegistration<NodeType>;\n    kinds.push({\n      name,\n      origin: runtimeNodeNames.has(name) ? \"runtime\" : \"compile-time\",\n      description: reg.type.description,\n      annotations: reg.type.annotations,\n      deprecated: deprecated.has(name),\n      properties: serializeSchemaProperties(reg.type.schema),\n      unique: (reg.unique ?? []).map((constraint) => ({\n        name: constraint.name,\n        fields: [...constraint.fields],\n        scope: constraint.scope,\n        collation: constraint.collation,\n      })),\n    });\n  }\n\n  const edges: EdgeIntrospection[] = [];\n  for (const [name, registration] of Object.entries(graph.edges)) {\n    const reg = registration;\n    const edgeType = reg.type as AllEdgeTypes<G> & EdgeType;\n    edges.push({\n      name,\n      origin: runtimeEdgeNames.has(name) ? \"runtime\" : \"compile-time\",\n      description: edgeType.description,\n      from: reg.from.map((entry) => (entry as AllNodeTypes<G> & NodeType).kind),\n      to: projectTargetKinds(reg.to),\n      cardinality: reg.cardinality ?? \"many\",\n      endpointExistence: reg.endpointExistence ?? \"notDeleted\",\n      properties: serializeSchemaProperties(edgeType.schema),\n      annotations: edgeType.annotations,\n      deprecated: deprecated.has(name),\n    });\n  }\n\n  const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(extension);\n  const ontology: OntologyIntrospection[] = graph.ontology.map((relation) => ({\n    metaEdge: relation.metaEdge.name,\n    from: getTypeName(relation.from),\n    to: getTypeName(relation.to),\n    origin:\n      runtimeOntologyKeys.has(compileTimeOntologyKey(relation)) ? \"runtime\" : (\n        \"compile-time\"\n      ),\n  }));\n\n  return {\n    graphId: context.graphId,\n    annotations: canonicalAnnotations(graph.annotations),\n    schemaVersion: context.schemaVersion,\n    schemaHash: context.schemaHash,\n    kinds,\n    edges,\n    ontology,\n    deprecatedKinds: new Set(deprecated),\n    extension,\n  };\n}\n","/**\n * Shared building blocks for schema-management and materialization verbs.\n * Each status-backed operation lazily bootstraps its per-deployment table;\n * this module centralizes focused bootstrap dispatch plus the bucketed\n * orchestration used by index materialization.\n */\nimport { type GraphBackend } from \"../backend/types\";\n\n/**\n * Idempotently ensure a per-verb status table exists, preferring the\n * focused `ensure*Table` primitive when available and falling back to\n * the full `bootstrapTables` for legacy backends.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent callers (e.g. two replicas of the same `schema_doc` both\n * starting up) deadlock on Postgres SHARE locks. Restricting the\n * ensure-step to a single table eliminates the cross-table lock cycle.\n * Backends still own any dialect-specific same-table race handling; the\n * PostgreSQL focused ensures retry their catalog uniqueness race.\n */\nexport async function ensureFocusedStatusTable(\n  backend: GraphBackend,\n  ensureFocused: (() => Promise<void>) | undefined,\n): Promise<void> {\n  if (ensureFocused !== undefined) {\n    await ensureFocused();\n    return;\n  }\n  await backend.bootstrapTables?.();\n}\n\n/**\n * Bucketed orchestration for index-materialization runners.\n *\n * `stopOnError === true` runs sequentially in input order and\n * short-circuits after the first `failed` entry (returning the partial\n * results). Otherwise items are grouped by `bucketKey` and the groups run\n * concurrently with each group sequential — the shape Postgres requires\n * for `CREATE INDEX CONCURRENTLY` (one in-flight build per relation).\n * Results always come back in input order regardless of how the buckets\n * resolved.\n */\nexport async function runBucketedMaterialization<\n  TItem,\n  TEntry extends { status: string },\n>(\n  items: readonly TItem[],\n  options: Readonly<{ stopOnError?: boolean }>,\n  bucketKey: (item: TItem) => string,\n  runOne: (item: TItem) => Promise<TEntry>,\n): Promise<readonly TEntry[]> {\n  if (options.stopOnError === true) {\n    const results: TEntry[] = [];\n    for (const item of items) {\n      const entry = await runOne(item);\n      results.push(entry);\n      if (entry.status === \"failed\") break;\n    }\n    return results;\n  }\n\n  const buckets = new Map<string, [number, TItem][]>();\n  for (const [index, item] of items.entries()) {\n    const key = bucketKey(item);\n    const bucket = buckets.get(key);\n    if (bucket === undefined) buckets.set(key, [[index, item]]);\n    else bucket.push([index, item]);\n  }\n\n  const results: TEntry[] = Array.from({ length: items.length });\n  await Promise.all(\n    [...buckets.values()].map(async (group) => {\n      for (const [index, item] of group) {\n        results[index] = await runOne(item);\n      }\n    }),\n  );\n  return results;\n}\n","/**\n * Index materialization — runs declared index DDL against the live\n * database and tracks per-deployment status in\n * `typegraph_index_materializations`.\n *\n * Reads `IndexDeclaration[]` from `GraphDef.indexes`, generates DDL via\n * `generateIndexDDL`, executes via `backend.executeDdl` (Postgres path\n * uses `CREATE INDEX CONCURRENTLY`, which cannot run inside a\n * transaction — `executeDdl` runs at the top-level backend, never inside\n * `transaction(...)`), and upserts a status row per index.\n *\n * Caveats baked in to the algorithm:\n *\n * - SQL index names are physical, database-global identifiers.\n *   Cross-graph collisions (two graphs declaring the same name with\n *   different shapes) surface as a `failed` result with reason\n *   \"signature drift\", because the existing recorded signature won't\n *   match the new one.\n * - On Postgres, `CREATE INDEX CONCURRENTLY IF NOT EXISTS` does NOT\n *   prove the existing physical index has the same shape as ours —\n *   only that something with that name exists. Drift detection here\n *   relies on TypeGraph's recorded signature, not on PG metadata.\n * - Failed `CONCURRENTLY` builds leave invalid indexes behind\n *   (`pg_index.indisvalid = false`). Relational rebuilds self-heal: the\n *   claim-holding materializer drops an invalid leftover with the\n *   declaration's name before rebuilding (see the backend's\n *   `catalog.dropInvalidIndex`, called from materializeWithClaim).\n *   Vector per-field index leftovers remain operator-repair.\n * - Two materializers racing the SAME index name serialize through a\n *   durable claim in the status table (see materializeWithClaim) —\n *   concurrent same-name expression-index CIC builds deadlock on\n *   Postgres (no safe-snapshot exemption).\n */\nimport { type RawBackend } from \"../backend/branded\";\nimport {\n  type BackendCatalogProbes,\n  requireCatalog,\n} from \"../backend/capabilities/catalog\";\nimport {\n  isOptimisticRetryTier,\n  OPTIMISTIC_RETRY_ATTEMPTS,\n  runRetriedUnit,\n} from \"../backend/capabilities/retried-unit\";\nimport {\n  type CreateVectorIndexParams,\n  type GraphBackend,\n  type IndexMaterializationRow,\n  type RecordIndexMaterializationParams,\n} from \"../backend/types\";\nimport { type GraphDef, isKnownKind } from \"../core/define-graph\";\nimport type { IndexEntity } from \"../core/types\";\nimport { ConfigurationError, KindNotFoundError } from \"../errors\";\nimport { generateIndexDDL } from \"../indexes/ddl\";\nimport {\n  generateSystemIndexDDL,\n  resolveSystemIndexNames,\n  resolveSystemIndexTableName,\n  SYSTEM_INDEX_DECLARATIONS,\n  type SystemIndexDeclaration,\n  systemIndexName,\n} from \"../indexes/system\";\nimport {\n  type IndexDeclaration,\n  type RelationalIndexDeclaration,\n  type VectorIndexDeclaration,\n} from \"../indexes/types\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport { sortedReplacer } from \"../schema/canonical\";\nimport { serializeIndexDeclaration } from \"../schema/serializer\";\nimport { nowIso } from \"../utils/date\";\nimport { delay } from \"../utils/delay\";\nimport { sha256Hex } from \"../utils/hash\";\nimport { requireDefined } from \"../utils/presence\";\nimport { isPostgresConcurrentDdlRaceError } from \"../utils/sql-errors\";\nimport {\n  ensureFocusedStatusTable,\n  runBucketedMaterialization,\n} from \"./materialize-shared\";\n\n/**\n * Cross-caller build claim timing (Postgres).\n *\n * A claim older than the lease is stale (its holder crashed mid-build) and\n * may be taken over; the lease is generous because CREATE INDEX\n * CONCURRENTLY on a large relation legitimately runs for minutes, and a\n * premature takeover would recreate exactly the same-index CIC race the\n * claim exists to prevent. Losers retry the claim on an interval —\n * re-claiming after the winner releases converges through the normal\n * already-materialized check — and give up shortly after the lease bound.\n */\nconst CLAIM_LEASE_MS = 15 * 60_000;\nconst CLAIM_RETRY_DELAY_MS = 200;\nconst CLAIM_WAIT_TIMEOUT_MS = CLAIM_LEASE_MS + 60_000;\nconst TRIGRAM_EXTENSION_DDL = \"CREATE EXTENSION IF NOT EXISTS pg_trgm;\";\n\n/**\n * Whether the backend implements the FULL cross-caller build-claim\n * protocol. One predicate for both decisions that depend on it — build\n * serialization and the post-create statistics refresh — so a backend\n * implementing only half the surface can never refresh without\n * serializing (the combination that reopens the same-index CIC deadlock).\n */\nfunction hasIndexBuildClaimProtocol(backend: GraphBackend): boolean {\n  return (\n    backend.claimIndexMaterialization !== undefined &&\n    backend.releaseIndexMaterializationClaim !== undefined\n  );\n}\n\n/**\n * Installs `pg_trgm`, preferring the most capable seam the backend offers.\n *\n * All three branches make the SAME request and differ only in what happens to\n * the loser of a concurrent install:\n *\n *  1. `ensureExtension` — the general seam: the backend owns the fence for\n *     every extension the library installs;\n *  2. `ensureTrigramExtension` — the `pg_trgm`-only spelling a 0.47 backend may\n *     implement instead, consulted so such a backend keeps its fence;\n *  3. bare `executeDdl` with this function's own one-shot retry, which is all\n *     a backend offering neither can do.\n *\n * A backend with none of them keeps failing loudly on `requireDefined`.\n */\nasync function ensureTrigramExtension(backend: GraphBackend): Promise<void> {\n  if (backend.ensureExtension !== undefined) {\n    await backend.ensureExtension(\"pg_trgm\");\n    return;\n  }\n  // Consulting the deprecated seam IS this branch's purpose: a backend written\n  // against 0.47 implements only this one, and skipping it would drop such a\n  // backend to the bare statement below and lose the fence it does have.\n  /* eslint-disable @typescript-eslint/no-deprecated */\n  if (backend.ensureTrigramExtension !== undefined) {\n    await backend.ensureTrigramExtension();\n    return;\n  }\n  /* eslint-enable @typescript-eslint/no-deprecated */\n\n  const executeDdl = requireDefined(backend.executeDdl);\n  try {\n    await executeDdl(TRIGRAM_EXTENSION_DDL);\n  } catch (error) {\n    if (!isPostgresConcurrentDdlRaceError(error)) throw error;\n    await executeDdl(TRIGRAM_EXTENSION_DDL);\n  }\n}\n\nexport type MaterializeIndexesOptions = Readonly<{\n  /** Restrict to indexes whose `kind` is in this set. */\n  kinds?: readonly string[];\n  /** Stop on the first failure. Default: false (best-effort). */\n  stopOnError?: boolean;\n  /**\n   * Refresh planner statistics (ANALYZE) after at least one index was\n   * created. A fresh index can be ignored by the planner until statistics\n   * exist. Default: true. Applied on non-concurrent builders (SQLite) and\n   * on concurrent builders that serialize same-index builds via the\n   * cross-caller claim primitive (the bundled Postgres backend); a custom\n   * concurrent backend without the primitive skips the refresh — see\n   * refreshStatisticsAfterCreation — and should call\n   * `store.refreshStatistics()` after materializing.\n   */\n  refreshStatistics?: boolean;\n}>;\n\n/**\n * Per-index outcome from `materializeIndexes()`.\n *\n * Status values:\n * - `created`: DDL ran successfully and a new physical index now exists.\n * - `alreadyMaterialized`: status table shows a prior successful\n *   materialization with the same signature; no DDL ran.\n * - `failed`: the DDL or status write failed; `error` carries the\n *   captured exception. Best-effort mode continues to the next index;\n *   `stopOnError: true` halts.\n * - `skipped`: the backend can't materialize this index variant in its\n *   current configuration (e.g. vector indexes against SQLite without\n *   sqlite-vec, or `indexType: \"none\"` declared on an embedding). The\n *   declaration is recognized but intentionally not acted on. Status\n *   table is NOT updated for skipped entries.\n */\nexport type MaterializeIndexesEntry = Readonly<{\n  indexName: string;\n  entity: IndexEntity;\n  kind: string;\n  status: \"created\" | \"alreadyMaterialized\" | \"failed\" | \"skipped\";\n  error?: Error;\n  /**\n   * Human-readable reason. Required for `skipped`; optional otherwise.\n   */\n  reason?: string;\n}>;\n\nexport type MaterializeIndexesResult = Readonly<{\n  results: readonly MaterializeIndexesEntry[];\n}>;\n\ntype MaterializeIndexesContext = Readonly<{\n  graph: GraphDef;\n  graphId: string;\n  // Index DDL runs at the top-level backend (CREATE INDEX CONCURRENTLY cannot\n  // run in a transaction) and writes no graph entities — it is the raw seam,\n  // not the capture wrapper. Passing the graph-write backend here is an error.\n  backend: RawBackend;\n  schemaVersion: number;\n}>;\n\nexport async function materializeIndexes(\n  context: MaterializeIndexesContext,\n  options: MaterializeIndexesOptions = {},\n): Promise<MaterializeIndexesResult> {\n  const { graph, graphId, backend, schemaVersion } = context;\n\n  assertBackendSupportsIndexMaterialization(\n    backend,\n    \"store.materializeIndexes()\",\n  );\n\n  const declared = graph.indexes ?? [];\n  const kindFilter =\n    options.kinds === undefined ? undefined : new Set(options.kinds);\n\n  if (kindFilter !== undefined) {\n    for (const name of kindFilter) {\n      if (!isKnownKind(graph, name)) {\n        throw new KindNotFoundError(\n          name,\n          Object.hasOwn(graph.edges, name) ? \"edge\" : \"node\",\n          {\n            graphId,\n            suggestion:\n              \"Only kinds declared on the graph (compile-time or runtime) can be passed to materializeIndexes.\",\n          },\n        );\n      }\n    }\n  }\n\n  const candidates = declared.filter((index) =>\n    kindFilter === undefined ? true : kindFilter.has(index.kind),\n  );\n\n  // Short-circuit before any I/O when there's nothing to do. The\n  // ensure-step below issues a CREATE TABLE statement — paying that\n  // cost only to return an empty result is wasteful, especially on\n  // repeated `evolve(sameExt, { eager: {} })` calls.\n  if (candidates.length === 0) {\n    return { results: [] };\n  }\n\n  await ensureFocusedStatusTable(\n    backend,\n    backend.ensureIndexMaterializationsTable,\n  );\n\n  const catalog = requireCatalog(backend, \"store.materializeIndexes()\");\n  const dialect = backend.dialect;\n  const tableNames = backend.tableNames;\n  const ddlOptions = {\n    ifNotExists: true,\n    concurrent: catalog.indexBehavior.concurrentBuilds,\n    ...(tableNames?.nodes === undefined ?\n      {}\n    : { nodesTableName: tableNames.nodes }),\n    ...(tableNames?.edges === undefined ?\n      {}\n    : { edgesTableName: tableNames.edges }),\n  } as const;\n\n  // Bulk-preload existing materialization rows for every candidate's\n  // status key in one round-trip. With 30 declared indexes this drops 30\n  // sequential SELECTs to one. Backends without the bulk primitive fall\n  // back to per-key lookups inside `materializeOne`.\n  const statusKeys = candidates.map((declaration) =>\n    statusKeyFor(declaration, graphId),\n  );\n  const existingByStatusKey = await preloadMaterializations(\n    backend,\n    statusKeys,\n  );\n\n  // Bulk-preload INVALID index leftovers (interrupted CONCURRENTLY builds)\n  // for the relational candidates in one `pg_index` query. On a warm start\n  // `settleAgainstExisting` would otherwise fire one leftover check per\n  // already-materialized index — the same N-round-trip cost the status\n  // preload above just eliminated. Vector entries are excluded: their\n  // per-field physical index leftovers are operator-repair, and\n  // `settleAgainstExisting` only consults this set for non-vector\n  // declarations. Physical names are the declaration names.\n  const relationalPhysicalNames = candidates\n    .filter((declaration) => declaration.entity !== \"vector\")\n    .map((declaration) => declaration.name);\n  const invalidLeftovers = await preloadInvalidIndexLeftovers(\n    catalog,\n    relationalPhysicalNames,\n  );\n\n  // System index names are reserved: a colliding relational declaration's\n  // `CREATE INDEX IF NOT EXISTS` would silently no-op against the\n  // (differently shaped) system index while recording a false success.\n  // The schema factories reject the same collision at table-definition\n  // time; this covers declarations that never pass through them.\n  const reservedSystemNames = resolveSystemIndexNames(backend.tableNames);\n\n  const materializeEntry = (\n    declaration: IndexDeclaration,\n  ): Promise<MaterializeIndexesEntry> => {\n    if (\n      declaration.entity !== \"vector\" &&\n      reservedSystemNames.has(declaration.name)\n    ) {\n      return Promise.resolve(\n        entry(\n          declaration,\n          \"failed\",\n          new Error(\n            `Index name \"${declaration.name}\" collides with a TypeGraph ` +\n              `system index. Rename the declaration — a same-named CREATE ` +\n              `INDEX IF NOT EXISTS would silently no-op against the system ` +\n              `index instead of creating the declared one.`,\n          ),\n        ),\n      );\n    }\n    return declaration.entity === \"vector\" ?\n        materializeVectorIndex(\n          declaration,\n          backend,\n          catalog,\n          graphId,\n          schemaVersion,\n          existingByStatusKey,\n          invalidLeftovers,\n        )\n      : materializeRelationalIndex(\n          declaration,\n          backend,\n          catalog,\n          dialect,\n          ddlOptions,\n          graphId,\n          schemaVersion,\n          existingByStatusKey,\n          invalidLeftovers,\n        );\n  };\n\n  // Postgres restricts `CREATE INDEX CONCURRENTLY` to one in-flight\n  // build per relation, so declarations group by target relation and\n  // each group runs sequentially while the groups run in parallel.\n  // Typical schemas land in three buckets (nodes, edges, vector\n  // embeddings), giving a ~3× round-trip win over fully sequential\n  // without ever issuing two CONCURRENTLY builds against the same\n  // relation. SQLite ignores the grouping (writes serialize at the\n  // engine level either way).\n  const results = await runBucketedMaterialization(\n    candidates,\n    options,\n    (declaration) => parallelBucketKey(declaration),\n    (declaration) => materializeEntry(declaration),\n  );\n  await refreshStatisticsAfterCreation(\n    backend,\n    results,\n    options,\n    ddlOptions.concurrent,\n  );\n  return { results };\n}\n\n/**\n * Runs ANALYZE once when at least one index was freshly created (unless the\n * caller opted out): the planner can keep seq-scanning past a brand-new\n * index until statistics for it exist.\n *\n * On backends that build with CREATE INDEX CONCURRENTLY, the refresh runs\n * only when the backend also exposes the cross-caller claim primitive\n * (the bundled Postgres backend does): the claim serializes same-index\n * CIC builds, which used to deadlock under the refresh's timing shift\n * (expression-index CIC gets no safe-snapshot exemption). A custom\n * concurrent backend without the primitive keeps the conservative skip\n * and refreshes manually via `store.refreshStatistics()`.\n *\n * Best-effort: by this point the indexes exist and their status rows are\n * recorded, so a failed statistics refresh must not convert that success\n * into a failure — it degrades to a warning.\n */\nasync function refreshStatisticsAfterCreation(\n  backend: RawBackend,\n  results: readonly MaterializeIndexesEntry[],\n  options: MaterializeIndexesOptions,\n  usesConcurrentBuilds: boolean,\n): Promise<void> {\n  if (options.refreshStatistics === false) return;\n  // Concurrent (Postgres) builds were excluded while two callers racing\n  // the SAME expression-index CIC could deadlock — the refresh's timing\n  // shift made that latent race fire reliably. With the cross-caller\n  // claim protocol serializing same-index builds, backends that expose\n  // the claim primitive refresh automatically again; a custom concurrent\n  // backend without the primitive keeps the conservative skip.\n  if (usesConcurrentBuilds && !hasIndexBuildClaimProtocol(backend)) return;\n  if (!results.some((entry) => entry.status === \"created\")) return;\n  try {\n    await backend.refreshStatistics();\n  } catch (error) {\n    if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n      return;\n    }\n    console.warn(\n      \"[typegraph] materializeIndexes created its indexes but the follow-up \" +\n        \"statistics refresh failed; run store.refreshStatistics() to give \" +\n        \"the planner fresh statistics.\",\n      error,\n    );\n  }\n}\n\nfunction parallelBucketKey(declaration: IndexDeclaration): IndexEntity {\n  // Vector indexes now target typed per-`(kind, field)` tables rather\n  // than one shared table, so distinct vector declarations could in\n  // principle build concurrently. They still share one bucket (keyed by\n  // the `\"vector\"` entity) — serializing them is conservative but\n  // correct, and keeps Postgres CIC's \"one in-flight build per relation\"\n  // rule trivially satisfied without tracking per-table identity here.\n  // Relational node and edge indexes split into their own entity buckets.\n  return declaration.entity;\n}\n\nasync function materializeRelationalIndex(\n  declaration: RelationalIndexDeclaration,\n  backend: GraphBackend,\n  catalog: BackendCatalogProbes,\n  dialect: SqlDialect,\n  ddlOptions: Readonly<{\n    ifNotExists: boolean;\n    concurrent: boolean;\n    nodesTableName?: string;\n    edgesTableName?: string;\n  }>,\n  graphId: string,\n  schemaVersion: number,\n  existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>,\n  invalidLeftovers: ReadonlySet<string>,\n): Promise<MaterializeIndexesEntry> {\n  // GIN-family methods are PostgreSQL expression GINs; SQLite has no\n  // equivalent (its substring-search story is FTS5 fulltext), so the\n  // declaration is recognized and intentionally not acted on — same\n  // contract as vector indexes on engines without vector support.\n  if (\n    declaration.method !== undefined &&\n    !catalog.indexBehavior.supportsGinFamily\n  ) {\n    return {\n      indexName: declaration.name,\n      entity: declaration.entity,\n      kind: declaration.kind,\n      status: \"skipped\",\n      reason:\n        `Index method \"${declaration.method}\" requires PostgreSQL ` +\n        `(expression GIN${declaration.method === \"trigram\" ? \" + pg_trgm\" : \"\"}); ` +\n        \"SQLite serves substring search via FTS5 fulltext instead.\",\n    };\n  }\n\n  const ddl = generateIndexDDL(declaration, dialect, ddlOptions);\n  const targetTable =\n    declaration.entity === \"node\" ?\n      (ddlOptions.nodesTableName ?? \"typegraph_nodes\")\n    : (ddlOptions.edgesTableName ?? \"typegraph_edges\");\n  const signature = await computeIndexSignature(\n    dialect,\n    targetTable,\n    declaration,\n  );\n  return materializeOne(declaration, backend, catalog, graphId, schemaVersion, {\n    statusKey: declaration.name,\n    signature,\n    driftLabel: \"Index\",\n    run: async () => {\n      if (declaration.method === \"trigram\") {\n        // gin_trgm_ops lives in the pg_trgm extension (contrib — present\n        // on stock Postgres and the hosted variants). Idempotent, and a\n        // permission failure surfaces as this index's `failed` entry.\n        //\n        // The install needs a fence this claim cannot give it: the extension\n        // is database-global while this claim is per-index, so two\n        // materializers building DIFFERENT trigram indexes both reach it and\n        // race on the catalog row — the loser's 23505 would be a spurious\n        // `failed` entry (#446). The backend seam owns that fence (#475); a\n        // backend offering neither seam keeps issuing it bare, so the index is\n        // still materialized, just with this function's own retry rather than\n        // the backend's serialization.\n        await ensureTrigramExtension(backend);\n      }\n      await requireDefined(backend.executeDdl)(ddl);\n    },\n    existingByStatusKey,\n    physicalRebuildPreload: invalidLeftovers,\n  });\n}\n\nasync function materializeVectorIndex(\n  declaration: VectorIndexDeclaration,\n  backend: GraphBackend,\n  catalog: BackendCatalogProbes,\n  graphId: string,\n  schemaVersion: number,\n  existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>,\n  invalidLeftovers: ReadonlySet<string>,\n): Promise<MaterializeIndexesEntry> {\n  // `indexType: \"none\"` is a declarative opt-out — the declaration\n  // carries shape metadata (dimensions, metric) for tooling but the\n  // operator has signaled \"no automatic index\". Surface as `skipped`.\n  if (declaration.indexType === \"none\") {\n    return skippedEntry(\n      declaration,\n      \"indexType: 'none' opts out of automatic materialization\",\n    );\n  }\n\n  // Capability check: backends declare vector support via\n  // `capabilities.vector` (derived from the active `VectorStrategy`) and\n  // expose that strategy as `backend.vectorStrategy`. When either is\n  // absent the backend can't act on the declaration — surface as\n  // skipped. The `vectorStrategy` check also narrows it to defined for\n  // the per-field table-name resolution below.\n  const vectorCapability = backend.capabilities.vector;\n  if (\n    vectorCapability?.supported !== true ||\n    backend.createVectorIndex === undefined ||\n    backend.vectorStrategy === undefined\n  ) {\n    return skippedEntry(\n      declaration,\n      `Backend (${backend.dialect}) does not support vector indexes in its current configuration`,\n    );\n  }\n  // Capability check (per index type): backends advertise the specific\n  // index implementations they support (e.g. SQLite + sqlite-vec\n  // accepts vectors but no HNSW/IVFFlat — the brute-force scan IS the\n  // \"index\"). Surface unsupported types as skipped so consumers see a\n  // clear \"this backend can't materialize this declaration\" signal\n  // instead of a silent no-op masquerading as `created`.\n  if (!vectorCapability.indexTypes.includes(declaration.indexType)) {\n    return skippedEntry(\n      declaration,\n      `Backend (${backend.dialect}) does not support index type \"${declaration.indexType}\" for vector indexes; supported: ${vectorCapability.indexTypes.join(\", \") || \"(none)\"}`,\n    );\n  }\n\n  // Hash against the strategy's typed per-`(kind, field)` physical table\n  // — the storage this declaration's index actually targets. Folding the\n  // resolved table name into the signature keeps drift detection honest:\n  // if the strategy (and thus the physical table) changes, the recorded\n  // signature mismatches and re-materialization is forced.\n  const embeddingsTable = backend.vectorStrategy.tableName(\n    graphId,\n    declaration.kind,\n    declaration.fieldPath,\n  );\n  const signature = await computeIndexSignature(\n    backend.dialect,\n    embeddingsTable,\n    declaration,\n  );\n  const params: CreateVectorIndexParams = {\n    graphId,\n    nodeKind: declaration.kind,\n    fieldPath: declaration.fieldPath,\n    dimensions: declaration.dimensions,\n    metric: declaration.metric,\n    indexType: declaration.indexType,\n    indexParams: {\n      m: declaration.indexParams.m,\n      efConstruction: declaration.indexParams.efConstruction,\n      ...(declaration.indexParams.lists === undefined ?\n        {}\n      : { lists: declaration.indexParams.lists }),\n    },\n    concurrent: catalog.indexBehavior.concurrentBuilds,\n  };\n  return materializeOne(declaration, backend, catalog, graphId, schemaVersion, {\n    // Compound status-table key for vector entries. Pgvector creates\n    // one physical index per (graphId, kind, field) — so the\n    // per-deployment status table needs to disambiguate entries that\n    // SHARE a declaration name but belong to different graphs.\n    // Applied uniformly to auto-derived AND explicit declarations.\n    statusKey: vectorStatusKey(graphId, declaration.name),\n    signature,\n    driftLabel: \"Vector index\",\n    run: () => requireDefined(backend.createVectorIndex)(params),\n    existingByStatusKey,\n    physicalRebuildPreload: invalidLeftovers,\n  });\n}\n\n/**\n * The identity a materialization run needs from its declaration: the\n * physical/status name plus the `(entity, kind)` pair recorded on the\n * status row. Relational and vector declarations satisfy it structurally;\n * system indexes construct it from `SYSTEM_INDEX_DECLARATIONS`.\n */\ntype MaterializableIndexIdentity = Readonly<{\n  name: string;\n  entity: IndexEntity;\n  kind: string;\n}>;\n\n/**\n * Shared \"check existing → run → record\" frame for relational, vector,\n * and system materialization. All paths track a per-deployment status row\n * keyed by `statusKey`, short-circuit on a matching signature, surface\n * signature drift as a recorded failure, and execute `run()` on first\n * materialization. Differences live entirely in the `MaterializeAction`\n * the caller passes.\n */\nasync function materializeOne(\n  declaration: MaterializableIndexIdentity,\n  backend: GraphBackend,\n  catalog: BackendCatalogProbes,\n  graphId: string,\n  schemaVersion: number,\n  action: Readonly<{\n    statusKey: string;\n    signature: string;\n    driftLabel: string;\n    run: () => Promise<void>;\n    existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>;\n    /**\n     * Physical index names whose catalog state requires a rebuild despite\n     * a matching success row. Relational: INVALID `CONCURRENTLY`\n     * leftovers. System: leftovers plus physically absent indexes —\n     * name-presence identifies a system index, so absence is proof the\n     * recorded success is stale (dump/restore, manual drop).\n     */\n    physicalRebuildPreload: ReadonlySet<string>;\n    /**\n     * Fresh per-name variant of `physicalRebuildPreload` for the\n     * post-claim re-check (the preload is stale after waiting on another\n     * builder's claim). Defaults to the Postgres invalid-leftover query.\n     */\n    freshNeedsPhysicalRebuild?: (physicalIndexName: string) => Promise<boolean>;\n    /**\n     * Allow the physical-rebuild check to trigger even on backends\n     * without the claim protocol (SQLite). Sound only when the rebuild is\n     * a plain idempotent CREATE (system indexes); relational leftover\n     * healing requires the claim and keeps the default `false`.\n     */\n    rebuildWithoutClaim?: boolean;\n  }>,\n): Promise<MaterializeIndexesEntry> {\n  // Narrowed by callsite — guaranteed defined when this is reached\n  // (validated in `materializeIndexes`).\n  const recordIndexMaterialization = requireDefined(\n    backend.recordIndexMaterialization,\n  );\n\n  const { statusKey, signature, driftLabel, run, existingByStatusKey } = action;\n  const statusOverride =\n    statusKey === declaration.name ? undefined : { statusName: statusKey };\n\n  // Pre-claim physical check reads the bulk-preloaded set (one catalog\n  // query for all candidates), not one round-trip per index.\n  const settled = await settleAgainstExisting(\n    existingByStatusKey.get(statusKey),\n    declaration,\n    backend,\n    graphId,\n    schemaVersion,\n    {\n      statusKey,\n      signature,\n      driftLabel,\n      needsPhysicalRebuild: (physicalIndexName) =>\n        action.physicalRebuildPreload.has(physicalIndexName),\n      ...(action.rebuildWithoutClaim === undefined ?\n        {}\n      : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n    },\n  );\n  if (settled !== undefined) return settled;\n\n  // Backends whose concurrent builds can deadlock across callers expose a\n  // claim primitive; one caller builds, the rest wait and converge through\n  // the already-materialized check on re-claim.\n  if (hasIndexBuildClaimProtocol(backend)) {\n    return materializeWithClaim(\n      declaration,\n      backend,\n      catalog,\n      graphId,\n      schemaVersion,\n      {\n        statusKey,\n        signature,\n        driftLabel,\n        run,\n        ...(action.freshNeedsPhysicalRebuild === undefined ?\n          {}\n        : { freshNeedsPhysicalRebuild: action.freshNeedsPhysicalRebuild }),\n        ...(action.rebuildWithoutClaim === undefined ?\n          {}\n        : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n      },\n    );\n  }\n\n  try {\n    await run();\n    const attemptedAt = nowIso();\n    await recordIndexMaterialization(\n      buildAttempt({\n        declaration,\n        graphId,\n        signature,\n        schemaVersion,\n        materializedAt: attemptedAt,\n        error: undefined,\n        attemptedAt,\n        ...statusOverride,\n      }),\n    );\n    return entry(declaration, \"created\");\n  } catch (error_) {\n    const error = error_ instanceof Error ? error_ : new Error(String(error_));\n    await recordIndexMaterialization(\n      buildAttempt({\n        declaration,\n        graphId,\n        signature,\n        schemaVersion,\n        materializedAt: undefined,\n        error,\n        ...statusOverride,\n      }),\n    );\n    return entry(declaration, \"failed\", error);\n  }\n}\n\n/**\n * Applies the existing-status decision: `alreadyMaterialized` on a prior\n * success with a matching signature, a recorded `failed` on signature\n * drift, and `undefined` when a build is needed. Shared by the pre-claim\n * check (against the bulk-preloaded rows) and the post-claim re-check\n * (against a fresh read — the preload is stale after waiting on a claim).\n */\nasync function settleAgainstExisting(\n  existing: IndexMaterializationRow | undefined,\n  declaration: MaterializableIndexIdentity,\n  backend: GraphBackend,\n  graphId: string,\n  schemaVersion: number,\n  action: Readonly<{\n    statusKey: string;\n    signature: string;\n    driftLabel: string;\n    /**\n     * Whether the physical index behind this name is unusable and must be\n     * rebuilt despite the recorded success (INVALID leftover; for system\n     * indexes also physically absent). The pre-claim caller reads a\n     * bulk-preloaded set (one query for all candidates); the post-claim\n     * caller reads fresh (the preload is stale after waiting on another\n     * builder's claim).\n     */\n    needsPhysicalRebuild: (\n      physicalIndexName: string,\n    ) => boolean | Promise<boolean>;\n    /** See `materializeOne`'s action field of the same name. */\n    rebuildWithoutClaim?: boolean;\n  }>,\n): Promise<MaterializeIndexesEntry | undefined> {\n  if (existing?.materializedAt === undefined) return undefined;\n  const { statusKey, signature, driftLabel, needsPhysicalRebuild } = action;\n  if (existing.signature === signature) {\n    // A recorded success is only trustworthy while the physical index is\n    // usable: a run interrupted after `CREATE ... IF NOT EXISTS` silently\n    // kept an invalid leftover (or a pre-claim-protocol run recorded\n    // success over one), and a dump/restore or manual drop can leave a\n    // success row for an index that no longer exists. Fall through to the\n    // build path — under the claim it drops any leftover and rebuilds;\n    // `rebuildWithoutClaim` callers re-run their plain idempotent CREATE.\n    if (\n      declaration.entity !== \"vector\" &&\n      (hasIndexBuildClaimProtocol(backend) ||\n        action.rebuildWithoutClaim === true) &&\n      (await needsPhysicalRebuild(declaration.name))\n    ) {\n      return undefined;\n    }\n    return entry(declaration, \"alreadyMaterialized\");\n  }\n  const error = new Error(\n    `${driftLabel} \"${declaration.name}\" already materialized with a different signature (recorded by graph \"${existing.graphId}\" at version ${existing.schemaVersion}). Drop the index manually and retry, or rename the new declaration.`,\n  );\n  await requireDefined(backend.recordIndexMaterialization)(\n    buildAttempt({\n      declaration,\n      graphId,\n      signature,\n      schemaVersion,\n      materializedAt: undefined,\n      error,\n      ...(statusKey === declaration.name ? {} : { statusName: statusKey }),\n    }),\n  );\n  return entry(declaration, \"failed\", error);\n}\n\n/**\n * Drops `physicalIndexName` through `catalog.dropInvalidIndex` — a no-op\n * for a valid or absent index on every engine, since that member re-probes\n * `indisvalid` itself before ever issuing `DROP INDEX CONCURRENTLY` — but\n * ONLY when this backend carries `executeDdl`.\n *\n * Every current caller reaches this only after\n * `assertBackendSupportsIndexMaterialization` has already confirmed\n * `executeDdl` is present on the SAME backend, so the guard below is\n * currently unreachable through the public `materializeIndexes` /\n * `materializeSystemIndexes` surface — restored anyway (mirroring the\n * deleted `dropInvalidIndexLeftover` helper this replaced, which carried\n * the identical check) because `catalog.dropInvalidIndex` has its own,\n * independent DDL path: nothing about the catalog member itself requires a\n * backend that implements it to also implement `executeDdl`. A caller\n * reaching this function with a backend narrowed to omit `executeDdl`\n * (`projectBackendWithout([\"executeDdl\"])`, say) must never have that\n * narrowing bypassed through the catalog's own back door.\n */\nexport async function dropInvalidIndexLeftover(\n  backend: GraphBackend,\n  catalog: BackendCatalogProbes,\n  physicalIndexName: string,\n): Promise<void> {\n  if (backend.executeDdl === undefined) return;\n  await catalog.dropInvalidIndex(physicalIndexName);\n}\n\n/**\n * Runs `run` — ONE write of the claim protocol, either the claim upsert\n * itself or the success record that follows a build — directly, or as one\n * retried unit of `backend`'s own optimistic-retry budget when its tier\n * requires it (`isOptimisticRetryTier`). Unlike a store-owned write plan,\n * neither call opens its own transaction — the claim and the record are\n * each already a single, autocommitted statement — so the gate is the tier\n * alone, with no transaction-mode check: `resolveWriteTransactionMode`\n * describes a distinction (opened vs. adopted transaction) that does not\n * apply to a root-level autocommit write.\n *\n * The claim loop's OWN wait/retry on a losing claim (below) is unaffected:\n * that loop keeps polling for a claim already held by another caller, which\n * is a different condition from this backend's own write conflicting at\n * commit.\n */\nfunction runAsIndexMaterializationUnit<T>(\n  backend: GraphBackend,\n  operation: string,\n  run: () => Promise<T>,\n): Promise<T> {\n  if (!isOptimisticRetryTier(backend)) return run();\n  return runRetriedUnit(\n    { operation, attempts: OPTIMISTIC_RETRY_ATTEMPTS, target: backend },\n    run,\n  );\n}\n\n/**\n * Builds one index under the cross-caller claim protocol.\n *\n * Claim → re-check → build → record → release. Losers retry the claim on\n * an interval: once the winner records its result and releases, the next\n * claim succeeds and the fresh status re-check settles them as\n * `alreadyMaterialized` (or surfaces the winner's drift failure) without\n * ever issuing a second same-index CONCURRENTLY build — the shape that\n * deadlocks on Postgres (expression-index CIC gets no safe-snapshot\n * exemption). A crashed holder's claim expires after the lease; the\n * takeover drops the invalid leftover its interrupted build left behind\n * (relational indexes — the declaration name IS the physical name) before\n * rebuilding.\n */\nasync function materializeWithClaim(\n  declaration: MaterializableIndexIdentity,\n  backend: GraphBackend,\n  catalog: BackendCatalogProbes,\n  graphId: string,\n  schemaVersion: number,\n  action: Readonly<{\n    statusKey: string;\n    signature: string;\n    driftLabel: string;\n    run: () => Promise<void>;\n    freshNeedsPhysicalRebuild?: (physicalIndexName: string) => Promise<boolean>;\n    rebuildWithoutClaim?: boolean;\n  }>,\n): Promise<MaterializeIndexesEntry> {\n  const { statusKey, signature, driftLabel, run } = action;\n  const statusOverride =\n    statusKey === declaration.name ? undefined : { statusName: statusKey };\n  const recordIndexMaterialization = requireDefined(\n    backend.recordIndexMaterialization,\n  );\n  const token = `${statusKey}:${nowIso()}:${Math.floor(performance.now() * 1000)}`;\n  const deadline = Date.now() + CLAIM_WAIT_TIMEOUT_MS;\n\n  for (;;) {\n    const claimed = await runAsIndexMaterializationUnit(\n      backend,\n      \"claimIndexMaterialization\",\n      () =>\n        requireDefined(backend.claimIndexMaterialization)({\n          indexName: statusKey,\n          graphId,\n          entity: declaration.entity,\n          kind: declaration.kind,\n          signature,\n          schemaVersion,\n          token,\n          leaseMs: CLAIM_LEASE_MS,\n        }),\n    );\n\n    if (!claimed) {\n      if (Date.now() >= deadline) {\n        return entry(\n          declaration,\n          \"failed\",\n          new Error(\n            `Timed out waiting for a concurrent materializer's claim on \"${statusKey}\" (waited ${String(CLAIM_WAIT_TIMEOUT_MS)}ms). If its holder crashed, retry after the lease expires.`,\n          ),\n        );\n      }\n      await delay(CLAIM_RETRY_DELAY_MS);\n      continue;\n    }\n\n    try {\n      // Fresh re-check: the bulk preload happened before (possibly) waiting\n      // on another caller's build.\n      const fresh = await requireDefined(backend.getIndexMaterialization)(\n        statusKey,\n      );\n      const settled = await settleAgainstExisting(\n        fresh,\n        declaration,\n        backend,\n        graphId,\n        schemaVersion,\n        {\n          statusKey,\n          signature,\n          driftLabel,\n          // Post-claim the bulk preload is stale (we may have waited on\n          // another builder's claim), so re-check this index fresh.\n          needsPhysicalRebuild:\n            action.freshNeedsPhysicalRebuild ??\n            ((physicalIndexName) =>\n              hasInvalidIndexLeftover(catalog, physicalIndexName)),\n          ...(action.rebuildWithoutClaim === undefined ?\n            {}\n          : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n        },\n      );\n      if (settled !== undefined) return settled;\n\n      if (declaration.entity !== \"vector\") {\n        await dropInvalidIndexLeftover(backend, catalog, declaration.name);\n      }\n\n      try {\n        await run();\n        const attemptedAt = nowIso();\n        await runAsIndexMaterializationUnit(\n          backend,\n          \"recordIndexMaterialization\",\n          () =>\n            recordIndexMaterialization(\n              buildAttempt({\n                declaration,\n                graphId,\n                signature,\n                schemaVersion,\n                materializedAt: attemptedAt,\n                error: undefined,\n                attemptedAt,\n                ...statusOverride,\n              }),\n            ),\n        );\n        return entry(declaration, \"created\");\n      } catch (error_) {\n        const error =\n          error_ instanceof Error ? error_ : new Error(String(error_));\n        await runAsIndexMaterializationUnit(\n          backend,\n          \"recordIndexMaterialization\",\n          () =>\n            recordIndexMaterialization(\n              buildAttempt({\n                declaration,\n                graphId,\n                signature,\n                schemaVersion,\n                materializedAt: undefined,\n                error,\n                ...statusOverride,\n              }),\n            ),\n        );\n        return entry(declaration, \"failed\", error);\n      }\n    } finally {\n      // A claim-release failure must not mask the build's own outcome — a\n      // successful build must not surface as a thrown rejection, and one\n      // bucket's release error must not abort its siblings. The claim carries\n      // a lease (CLAIM_LEASE_MS) and self-expires, so a missed release is\n      // reclaimed by the next materializer; warn and move on.\n      try {\n        await runAsIndexMaterializationUnit(\n          backend,\n          \"releaseIndexMaterializationClaim\",\n          () =>\n            requireDefined(backend.releaseIndexMaterializationClaim)({\n              indexName: statusKey,\n              token,\n            }),\n        );\n      } catch (releaseError) {\n        console.warn(\n          `typegraph: failed to release the index materialization claim for ` +\n            `\"${statusKey}\"; it will expire on its lease and be reclaimed ` +\n            `automatically.`,\n          releaseError,\n        );\n      }\n    }\n  }\n}\n\n/**\n * Whether an index with this name exists but is INVALID (an interrupted\n * CONCURRENTLY build's leftover). False for absent or valid indexes and\n * on engines whose `indexBehavior.hasInvalidIndexState` is `false`.\n */\nasync function hasInvalidIndexLeftover(\n  catalog: BackendCatalogProbes,\n  physicalIndexName: string,\n): Promise<boolean> {\n  if (!catalog.indexBehavior.hasInvalidIndexState) return false;\n  const [state] = await catalog.indexStates([physicalIndexName]);\n  return state?.invalid === true;\n}\n\n/**\n * Bulk variant of `hasInvalidIndexLeftover`: the set of INVALID leftover\n * index names among `physicalIndexNames`, resolved in ONE catalog round\n * trip. Empty set on engines whose `indexBehavior.hasInvalidIndexState` is\n * `false`, or on empty input.\n *\n * A warm start (every index already materialized with a matching signature)\n * would otherwise fire `hasInvalidIndexLeftover` once per already-materialized\n * relational index inside `settleAgainstExisting` — N catalog round trips.\n * Preloading the whole set collapses that to one, mirroring how\n * `preloadMaterializations` batches the status reads it sits beside.\n */\nasync function preloadInvalidIndexLeftovers(\n  catalog: BackendCatalogProbes,\n  physicalIndexNames: readonly string[],\n): Promise<ReadonlySet<string>> {\n  if (\n    !catalog.indexBehavior.hasInvalidIndexState ||\n    physicalIndexNames.length === 0\n  ) {\n    return new Set();\n  }\n  const { invalid } = await preloadPhysicalIndexStates(\n    catalog,\n    physicalIndexNames,\n  );\n  return invalid;\n}\n\n/**\n * The subset of `tableNames` that exist as tables (not views or other\n * relations) in the engine catalog, in one round trip via\n * `BackendCatalogProbes.tablesExist`.\n */\nasync function preloadExistingTables(\n  catalog: BackendCatalogProbes,\n  tableNames: readonly string[],\n): Promise<ReadonlySet<string>> {\n  if (tableNames.length === 0) return new Set();\n  const states = await catalog.tablesExist(tableNames);\n  return new Set(\n    states.filter((state) => state.exists).map((state) => state.name),\n  );\n}\n\ntype PhysicalIndexStates = Readonly<{\n  /** Names that exist as usable indexes in the engine catalog. */\n  valid: ReadonlySet<string>;\n  /** Postgres INVALID leftovers from interrupted CONCURRENTLY builds. */\n  invalid: ReadonlySet<string>;\n}>;\n\n/**\n * Partitions `physicalIndexNames` by their catalog state in ONE round trip\n * via `BackendCatalogProbes.indexStates`: `valid` (usable index exists) and\n * `invalid` (Postgres CONCURRENTLY leftover needing the healing build path).\n * An absent name lands in neither set. SQLite has no invalid state, so its\n * `invalid` set is always empty. This single probe serves both the\n * relational runner's leftover preload and the system runner's\n * name-presence fast path.\n */\nasync function preloadPhysicalIndexStates(\n  catalog: BackendCatalogProbes,\n  physicalIndexNames: readonly string[],\n): Promise<PhysicalIndexStates> {\n  const valid = new Set<string>();\n  const invalid = new Set<string>();\n  if (physicalIndexNames.length === 0) return { valid, invalid };\n  const states = await catalog.indexStates(physicalIndexNames);\n  for (const state of states) {\n    if (!state.exists) continue;\n    (state.invalid ? invalid : valid).add(state.name);\n  }\n  return { valid, invalid };\n}\n\nfunction entry(\n  declaration: MaterializableIndexIdentity,\n  status: MaterializeIndexesEntry[\"status\"],\n  error?: Error,\n): MaterializeIndexesEntry {\n  return {\n    indexName: declaration.name,\n    entity: declaration.entity,\n    kind: declaration.kind,\n    status,\n    ...(error === undefined ? {} : { error }),\n  };\n}\n\nfunction skippedEntry(\n  declaration: VectorIndexDeclaration,\n  reason: string,\n): MaterializeIndexesEntry {\n  return {\n    indexName: declaration.name,\n    entity: \"vector\",\n    kind: declaration.kind,\n    status: \"skipped\",\n    reason,\n  };\n}\n\n/**\n * Compose the per-deployment status-table key for a vector index.\n * Pgvector physical indexes are partial-by-graph_id (one per graph),\n * so the status table needs graph-scoped identity to disambiguate\n * two graphs reusing the same declaration name. The `::` separator\n * keeps the compound visually unambiguous when inspecting the table.\n */\nexport function vectorStatusKey(\n  graphId: string,\n  declarationName: string,\n): string {\n  return `${graphId}::${declarationName}`;\n}\n\nfunction statusKeyFor(declaration: IndexDeclaration, graphId: string): string {\n  return declaration.entity === \"vector\" ?\n      vectorStatusKey(graphId, declaration.name)\n    : declaration.name;\n}\n\n/**\n * Bulk-load the recorded materialization rows for `statusKeys` into a\n * Map keyed by status key. Backends that implement\n * `getIndexMaterializations` return everything in one round-trip;\n * legacy backends fall back to per-key parallel `getIndexMaterialization`\n * calls. Missing rows are simply absent from the map.\n */\nasync function preloadMaterializations(\n  backend: GraphBackend,\n  statusKeys: readonly string[],\n): Promise<ReadonlyMap<string, IndexMaterializationRow>> {\n  const map = new Map<string, IndexMaterializationRow>();\n  if (statusKeys.length === 0) return map;\n  if (backend.getIndexMaterializations !== undefined) {\n    const rows = await backend.getIndexMaterializations(statusKeys);\n    for (const row of rows) map.set(row.indexName, row);\n    return map;\n  }\n  const getOne = requireDefined(backend.getIndexMaterialization);\n  const rows = await Promise.all(statusKeys.map((key) => getOne(key)));\n  for (const [index, row] of rows.entries()) {\n    if (row !== undefined) map.set(requireDefined(statusKeys[index]), row);\n  }\n  return map;\n}\n\nfunction buildAttempt(\n  args: Readonly<{\n    declaration: MaterializableIndexIdentity;\n    graphId: string;\n    signature: string;\n    schemaVersion: number;\n    materializedAt: string | undefined;\n    error: Error | undefined;\n    attemptedAt?: string;\n    /**\n     * Override the status-table identity. Used by vector entries to\n     * inject the graph-scoped compound key (`vectorStatusKey`).\n     * Relational entries default to the declaration name because\n     * physical CREATE INDEX names are already database-global.\n     */\n    statusName?: string;\n  }>,\n): RecordIndexMaterializationParams {\n  return {\n    indexName: args.statusName ?? args.declaration.name,\n    graphId: args.graphId,\n    entity: args.declaration.entity,\n    kind: args.declaration.kind,\n    signature: args.signature,\n    schemaVersion: args.schemaVersion,\n    attemptedAt: args.attemptedAt ?? nowIso(),\n    materializedAt: args.materializedAt,\n    error: args.error?.message,\n  };\n}\n\n// ============================================================\n// System indexes\n// ============================================================\n\nexport type MaterializeSystemIndexesOptions = Readonly<{\n  /** Stop on the first failure. Default: false (best-effort). */\n  stopOnError?: boolean;\n  /** Refresh planner statistics after a creation. Default: true. */\n  refreshStatistics?: boolean;\n}>;\n\ntype SystemIndexCandidate = Readonly<{\n  declaration: SystemIndexDeclaration;\n  physicalTable: string;\n  name: string;\n}>;\n\n/**\n * Materializes TypeGraph's own base-relation indexes\n * (`SYSTEM_INDEX_DECLARATIONS`) against the live database.\n *\n * Bootstrap DDL runs only on first boot, so a system index added in a new\n * library version never reaches an already-initialized database on its\n * own — this runner is the upgrade path. It rides the same per-deployment\n * status table, drift signatures, invalid-leftover healing, and Postgres\n * `CREATE INDEX CONCURRENTLY` cross-caller claim protocol as\n * graph-declared indexes; on a database whose indexes all exist, a warm\n * call costs three concurrent reads (status, index-catalog, and\n * table-catalog preloads) after the idempotent status-table ensure, and runs no\n * DDL after the first recorded success.\n *\n * Graph-independent: the declarations don't depend on `GraphDef`. The\n * `graphId` is recorded on status rows for observability only (\"who\n * materialized this\"), matching relational rows' semantics.\n *\n * Unlike expression indexes, a system index is fully identified by its\n * physical name, so a candidate that already exists in the engine catalog\n * (valid, with no recorded status row) settles as `alreadyMaterialized`\n * from one bulk catalog read — no claim, no DDL, no status write. Status\n * rows are recorded only for genuine builds and failures, which keeps the\n * common boot (fresh bootstrap or wiped status table) at three concurrent\n * reads. A status row that exists with a mismatching signature still\n * surfaces as drift, exactly like graph-declared indexes.\n */\n/**\n * Whether the backend carries every primitive index materialization\n * requires (DDL execution + status reads/writes). The strict runners\n * throw `ConfigurationError` exactly when this is false; the boot path\n * (`createStoreWithSchema`) consults the same predicate to skip instead\n * — one definition so the two contracts cannot drift apart.\n */\nexport function backendSupportsIndexMaterialization(\n  backend: GraphBackend,\n): boolean {\n  return (\n    backend.executeDdl !== undefined &&\n    backend.getIndexMaterialization !== undefined &&\n    backend.recordIndexMaterialization !== undefined\n  );\n}\n\n/**\n * Strict-side counterpart of {@link backendSupportsIndexMaterialization}:\n * the runners' throw-guard, derived from the same predicate the boot\n * path's skip-guard consults.\n */\nfunction assertBackendSupportsIndexMaterialization(\n  backend: GraphBackend,\n  surface: string,\n): void {\n  if (backendSupportsIndexMaterialization(backend)) return;\n  throw new ConfigurationError(\n    `${surface} requires a backend with \\`executeDdl\\` and the index ` +\n      \"materialization status primitives (`getIndexMaterialization`, \" +\n      \"`recordIndexMaterialization`). The bundled SQLite and Postgres \" +\n      \"backends provide them; a custom backend must implement all three.\",\n    { code: \"MATERIALIZE_BACKEND_UNSUPPORTED\" },\n  );\n}\n\nexport async function materializeSystemIndexes(\n  context: Readonly<{\n    backend: RawBackend;\n    graphId: string;\n    schemaVersion: number;\n  }>,\n  options: MaterializeSystemIndexesOptions = {},\n): Promise<MaterializeIndexesResult> {\n  const { backend, graphId, schemaVersion } = context;\n\n  assertBackendSupportsIndexMaterialization(\n    backend,\n    \"store.materializeSystemIndexes()\",\n  );\n\n  await ensureFocusedStatusTable(\n    backend,\n    backend.ensureIndexMaterializationsTable,\n  );\n\n  const catalog = requireCatalog(backend, \"store.materializeSystemIndexes()\");\n  const concurrent = catalog.indexBehavior.concurrentBuilds;\n  const candidates: readonly SystemIndexCandidate[] =\n    SYSTEM_INDEX_DECLARATIONS.map((declaration) => {\n      const physicalTable = resolveSystemIndexTableName(\n        declaration.table,\n        backend.tableNames,\n      );\n      return {\n        declaration,\n        physicalTable,\n        name: systemIndexName(physicalTable, declaration.suffix),\n      };\n    });\n\n  // The three preloads are mutually independent reads (status table +\n  // two catalog probes); running them concurrently keeps the warm boot at\n  // one round-trip latency after the ensure step.\n  const statusKeys = candidates.map((candidate) => candidate.name);\n  const targetTables = [\n    ...new Set(candidates.map((candidate) => candidate.physicalTable)),\n  ];\n  const [existingByStatusKey, physicalStates, existingTables] =\n    await Promise.all([\n      preloadMaterializations(backend, statusKeys),\n      preloadPhysicalIndexStates(catalog, statusKeys),\n      preloadExistingTables(catalog, targetTables),\n    ]);\n  const { valid: physicallyPresent } = physicalStates;\n  // Physical state is authoritative for system indexes: absent or INVALID\n  // must rebuild even under a matching success row (dump/restore, manual\n  // drop). One set serves every candidate's pre-claim check.\n  const physicalRebuildPreload: ReadonlySet<string> = new Set(\n    statusKeys.filter((name) => !physicallyPresent.has(name)),\n  );\n\n  const materializeEntry = async (\n    candidate: SystemIndexCandidate,\n  ): Promise<MaterializeIndexesEntry> => {\n    const identity: MaterializableIndexIdentity = {\n      name: candidate.name,\n      entity: \"system\",\n      kind: candidate.declaration.table,\n    };\n    // Legacy databases can predate optional relations (the recorded\n    // tables ship with history support; `operation-backend-core` guards\n    // its clears the same way). Their indexes are skipped, not failed —\n    // the relation appearing later (bootstrap on a fresh database always\n    // creates it) brings the indexes with it.\n    if (!existingTables.has(candidate.physicalTable)) {\n      return {\n        indexName: candidate.name,\n        entity: \"system\",\n        kind: candidate.declaration.table,\n        status: \"skipped\",\n        reason: `Relation \"${candidate.physicalTable}\" does not exist in this database`,\n      };\n    }\n\n    const existing = existingByStatusKey.get(candidate.name);\n\n    // A status row owned by another entity means a graph-declared index\n    // was materialized under this name. Refuse WITHOUT writing: driving\n    // this through the drift path would record a system-signature failure\n    // over the graph-declared index's row and permanently brick it.\n    if (existing !== undefined && existing.entity !== \"system\") {\n      return entry(\n        identity,\n        \"failed\",\n        new Error(\n          `System index name \"${candidate.name}\" is already recorded by a ` +\n            `${existing.entity} index declaration (graph \"${existing.graphId}\"). ` +\n            `Rename the graph-declared index — \"typegraph_\"-prefixed names ` +\n            `belong to TypeGraph's system indexes.`,\n        ),\n      );\n    }\n\n    // Name-presence fast path: valid physical index, no status row — the\n    // normal steady state, since bootstrap DDL creates system indexes\n    // without recording status rows. Trusting name-presence is sound\n    // ONLY here: system index names are library-owned with a stable\n    // name→shape contract (reshaping requires a rename), whereas a\n    // graph-declared index name could collide with a foreign index whose\n    // shape only the recorded signature can vouch for. Known limitation\n    // of that contract: a declaration reshaped in place (violating the\n    // rename rule) is NOT detected on bootstrap-created databases, since\n    // there is no recorded signature to drift against — the rename rule\n    // is enforced by review and the parity tests, not at runtime. A row\n    // with a mismatching signature must NOT take the fast path — that is\n    // drift, and the frame below records it as a failure.\n    if (existing === undefined && physicallyPresent.has(candidate.name)) {\n      return entry(identity, \"alreadyMaterialized\");\n    }\n    const signature = await computeSystemIndexSignature(\n      backend.dialect,\n      candidate.physicalTable,\n      candidate.declaration,\n    );\n    const ddl = generateSystemIndexDDL(\n      candidate.declaration,\n      candidate.physicalTable,\n      { concurrent },\n    );\n    return materializeOne(identity, backend, catalog, graphId, schemaVersion, {\n      statusKey: candidate.name,\n      signature,\n      driftLabel: \"System index\",\n      run: () => requireDefined(backend.executeDdl)(ddl),\n      existingByStatusKey,\n      physicalRebuildPreload,\n      freshNeedsPhysicalRebuild: async (physicalIndexName) => {\n        const fresh = await preloadPhysicalIndexStates(catalog, [\n          physicalIndexName,\n        ]);\n        return !fresh.valid.has(physicalIndexName);\n      },\n      rebuildWithoutClaim: true,\n    });\n  };\n\n  // Same shape as the relational runner: one CONCURRENTLY build per\n  // relation, so buckets key on the physical table.\n  const results = await runBucketedMaterialization(\n    candidates,\n    options,\n    (candidate) => candidate.physicalTable,\n    (candidate) => materializeEntry(candidate),\n  );\n  await refreshStatisticsAfterCreation(backend, results, options, concurrent);\n  return { results };\n}\n\n/**\n * Canonical hash of `{ dialect, targetTableName, declaration }` for a\n * system-index declaration — same drift contract as\n * `computeIndexSignature`: changing a declaration's shape under the same\n * suffix mismatches the recorded signature and surfaces as a `failed`\n * entry until the operator drops the old physical index (rename instead).\n */\nasync function computeSystemIndexSignature(\n  dialect: SqlDialect,\n  targetTableName: string,\n  declaration: SystemIndexDeclaration,\n): Promise<string> {\n  const json = JSON.stringify(\n    { dialect, targetTableName, declaration },\n    sortedReplacer,\n  );\n  return sha256Hex(json, 16);\n}\n\n/**\n * Canonical hash of `{ dialect, targetTableName, declaration }`.\n *\n * Includes the physical target table name because custom backends can\n * remap `typegraph_nodes` / `typegraph_edges` — a declaration-only\n * signature would falsely report \"already materialized\" after a table\n * rename. Excludes execution flags (`CONCURRENTLY`, `IF NOT EXISTS`)\n * because those are runtime modifiers, not shape.\n *\n * `declaration` is canonicalized via `serializeIndexDeclaration` before\n * hashing — `defineGraph` accepts pre-built `IndexDeclaration`s directly\n * (bypassing `defineNodeIndex`'s own canonicalization), so a raw\n * declaration with e.g. a present-but-empty `keySystemColumns: []` would\n * otherwise hash differently from the same declaration with the field\n * omitted, spuriously forcing re-materialization for no real shape change.\n */\nexport async function computeIndexSignature(\n  dialect: SqlDialect,\n  targetTableName: string,\n  declaration: IndexDeclaration,\n): Promise<string> {\n  const hashable = {\n    dialect,\n    targetTableName,\n    declaration: serializeIndexDeclaration(declaration),\n  };\n  const json = JSON.stringify(hashable, sortedReplacer);\n  return sha256Hex(json, 16);\n}\n","/**\n * Data-cleanup phase for `store.removeKinds()`.\n *\n * The removeKinds verb commits the new schema atomically (millisecond\n * budget); the data deletion happens here, scoped per-deployment via\n * the `typegraph_kind_removals` status table. Splitting the verbs\n * mirrors how `materializeIndexes` complements `evolve`: schema\n * commits are atomic and fast, while data work is bounded by row count and\n * deferrable. Candidates run sequentially because they share one graph lock.\n */\nimport { type RawBackend } from \"../backend/branded\";\nimport { resolveBackendFulltext } from \"../backend/capabilities/fulltext\";\nimport {\n  type GraphBackend,\n  type KindRemovalRow,\n  type RecordKindRemovalParams,\n  type SchemaVersionRow,\n  type SchemaWriteTransactionBackend,\n  type TransactionBackend,\n} from \"../backend/types\";\nimport type { KindEntity } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { createSqlSchema, type SqlSchema } from \"../query/compiler/schema\";\nimport type {\n  VectorSlot,\n  VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledStatementSql } from \"../query/sql-intent\";\nimport { parseSerializedSchema } from \"../schema/manager\";\nimport type { SerializedSchema } from \"../schema/types\";\nimport { nowIso } from \"../utils/date\";\nimport { hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport {\n  buildHardDeleteEdgeClaimsByEdgeKind,\n  buildHardDeleteEdgeClaimsByNodeKind,\n  buildHardDeleteUniquesByConcreteKind,\n} from \"./claims/removal-sql\";\nimport { ensureFocusedStatusTable } from \"./materialize-shared\";\nimport { closeRecordedHardDeletedKind } from \"./recorded-capture\";\n\nconst ENTITY_KINDS: readonly KindEntity[] = [\"node\", \"edge\"];\n\n/**\n * Build the \"pending\" `recordKindRemoval` payload shared by\n * `Store.removeKinds` (the original commit-time write) and\n * `materializeRemovals` reconciliation (the catch-up write for kinds\n * that crashed before their queue row landed). Centralizes the\n * `removedAt: undefined, error: undefined` constants so a future\n * status-table column expansion has one site to update.\n */\nexport function buildPendingKindRemoval(\n  args: Readonly<{\n    graphId: string;\n    kindName: string;\n    entity: KindEntity;\n    schemaVersion: number;\n    attemptedAt: string;\n  }>,\n): RecordKindRemovalParams {\n  return { ...args, removedAt: undefined, error: undefined };\n}\n\nexport type MaterializeRemovalsOptions = Readonly<{\n  /** Restrict to specific kind names. */\n  kinds?: readonly string[];\n  /** Halt on first failure. Default: false (best-effort). */\n  stopOnError?: boolean;\n}>;\n\n/**\n * Outcome of one queued kind removal, discriminated on `status`.\n *\n * A union rather than one shape with optional fields, so each outcome carries\n * exactly its own payload: `\"failed\"` always has an `error`, `\"skipped\"`\n * always has a `reason`, and `\"removed\"` has neither. The flat form permitted\n * impossible states — a `\"skipped\"` with no reason, or a `\"removed\"` carrying\n * `reason: \"kind-is-live\"` — and narrowing on `status` still left both fields\n * optional at the use site.\n */\nexport type MaterializeRemovalsEntry =\n  | Readonly<{ kind: string; entity: KindEntity; status: \"removed\" }>\n  | Readonly<{\n      kind: string;\n      entity: KindEntity;\n      status: \"failed\";\n      error: Error;\n    }>\n  | Readonly<{\n      kind: string;\n      entity: KindEntity;\n      status: \"skipped\";\n      /**\n       * `\"kind-is-live\"`: the active schema declares this kind again — it was\n       * dropped, then re-added — so deleting its rows would destroy live\n       * data. The queue row stays pending, so a later removal of the same\n       * kind still reclaims it.\n       *\n       * Reported rather than silent: an empty `results` array would otherwise\n       * be indistinguishable from \"nothing was pending\", leaving the queue at\n       * a non-zero depth with nothing explaining why.\n       */\n      reason: \"kind-is-live\";\n    }>;\n\n/**\n * Outcome of reclaiming one per-`(graphId, kind, field)` vector table that\n * was orphaned when its embedding field was dropped from a *surviving*\n * kind's schema. Distinct from {@link MaterializeRemovalsEntry} (whole\n * kinds) because the unit is a single embedding field, not a kind.\n */\nexport type ReclaimedVectorFieldEntry = Readonly<{\n  kind: string;\n  fieldPath: string;\n  status: \"reclaimed\" | \"failed\";\n  error?: Error;\n}>;\n\nexport type MaterializeRemovalsResult = Readonly<{\n  results: readonly MaterializeRemovalsEntry[];\n  /**\n   * Embedding fields removed from a *surviving* kind whose per-field vector\n   * table this pass dropped (or confirmed already absent). Empty when the\n   * backend has no vector strategy or no embedding field has ever been\n   * dropped. Re-derived from immutable schema history each call, so it lists\n   * the same removed fields on repeat passes — the underlying drop is\n   * idempotent (`DROP ... IF EXISTS`). See {@link reclaimRemovedVectorFieldTables}.\n   */\n  reclaimedVectorFields: readonly ReclaimedVectorFieldEntry[];\n}>;\n\ntype MaterializeRemovalsContext = Readonly<{\n  graphId: string;\n  // Bulk kind-removal deletes live rows directly and closes recorded intervals\n  // by kind — it deliberately bypasses the per-row capture wrapper, so it takes\n  // the raw seam. Passing the graph-write backend here is a type error.\n  backend: RawBackend;\n  captureRecordedRemovals?: boolean;\n  // The store's resolved SQL schema, so recorded-interval closes target the\n  // same relations recorded reads do (honoring a custom `schema` option, not\n  // just `backend.tableNames`). Falls back to the backend's table names.\n  recordedSchema?: SqlSchema;\n}>;\n\ntype MaterializeOneContext = Readonly<{\n  backend: GraphBackend;\n  graphId: string;\n  nodesTable: string;\n  edgesTable: string;\n  // Undefined when the backend has no active fulltext strategy — the table\n  // was never created, so the removed-kind cleanup below skips it.\n  fulltextTable: string | undefined;\n  uniquesTable: string;\n  edgeClaimsTable: string;\n  captureRecordedRemovals: boolean;\n  // Resolved once per removal pass (not per kind) and threaded into each\n  // recorded-interval close. Undefined when recorded capture is off.\n  recordedSchema: SqlSchema | undefined;\n}>;\n\nexport async function materializeRemovals(\n  context: MaterializeRemovalsContext,\n  options: MaterializeRemovalsOptions = {},\n): Promise<MaterializeRemovalsResult> {\n  const { backend, graphId } = context;\n\n  if (\n    backend.recordKindRemoval === undefined ||\n    backend.getPendingKindRemovals === undefined\n  ) {\n    throw new ConfigurationError(\n      \"store.materializeRemovals() requires a backend with kind-removal \" +\n        \"primitives (recordKindRemoval, getPendingKindRemovals). \" +\n        \"The bundled SQLite and Postgres backends provide them.\",\n      { code: \"MATERIALIZE_REMOVALS_BACKEND_UNSUPPORTED\" },\n    );\n  }\n\n  await ensureFocusedStatusTable(backend, backend.ensureKindRemovalsTable);\n\n  // Recovery path: `removeKinds()` commits the schema-version diff\n  // (kind dropped from `nodes`/`edges`) BEFORE recording the cleanup\n  // queue rows. If the queue write fails between those two steps the\n  // schema is durable but the queue is missing rows — and a retry of\n  // `removeKinds()` short-circuits on the no-op path because the kind\n  // is already absent. Atomicity isn't an option (the schema-commit\n  // path takes dialect-specific advisory locks that can't be extended\n  // across the status-table write), so reconcile here against schema\n  // history: walk every transition, find kinds whose removal isn't\n  // reflected in the queue, and re-record them.\n  await reconcilePendingRemovals(context);\n\n  // Independent of pending kind removals: a per-field vector table is\n  // orphaned the moment its embedding field is dropped from a *surviving*\n  // kind (an `evolve` that removes the field, with no kind removal at all).\n  // The add-only `materializeIndexes` path never reclaims it and the\n  // candidate loop below only handles whole kinds, so reclaim here before\n  // the no-candidates short-circuit.\n  // One read of the active schema, shared by the vector-reclaim candidate scan\n  // and the live-kind candidate scan below. Both are optimizations only: each\n  // destructive path repeats its liveness check under the schema-write lock.\n  const activeRow = await backend.getActiveSchema(graphId);\n  const activeSchema =\n    activeRow === undefined ? undefined : (\n      parseSerializedSchema(activeRow.schema_doc)\n    );\n\n  const reclaimedVectorFields = await reclaimRemovedVectorFieldTables(\n    context,\n    activeRow,\n  );\n\n  const pending = await backend.getPendingKindRemovals(graphId);\n\n  // Never delete the rows of a kind the ACTIVE schema still declares.\n  //\n  // A pending removal only records that a kind was absent at some version. It\n  // does not mean the kind is absent *now*: a drop at v3 followed by a re-add\n  // at v4 leaves the v3 removal queued (and `reconcilePendingRemovals` keeps\n  // re-deriving it from history, since that walk compares each consecutive\n  // pair of documents and is blind to what happened later). Cleanup is an\n  // unconditional `DELETE ... WHERE kind = ?`, so acting on that row would\n  // destroy live data belonging to a kind applications are actively writing.\n  //\n  // Skipped rather than completed: the kind genuinely has not been cleaned up,\n  // and leaving the row pending means a later removal of the same kind is\n  // still reclaimed. Self-healing rather than sticky.\n  //\n  // This first read is an optimization only. `materializeOne` repeats the\n  // liveness check while holding the schema-write lock and performs every row,\n  // vector-table, and marker deletion in that same transaction. A re-add must\n  // therefore commit either before the locked check (and be skipped) or after\n  // cleanup commits.\n  //\n  // The decline is REPORTED (`status: \"skipped\"`), not silent. Queue depth is\n  // the health signal for this subsystem, and a silent skip gives it a\n  // legitimate non-zero steady state that no output explains — an operator\n  // could not tell \"nothing pending\" from \"declined on purpose\".\n  //\n  // `reclaimRemovedVectorFieldTables` above independently keys its candidate\n  // scan on the same active schema and repeats the field check under the same\n  // lock before dropping storage — see the note there.\n  const liveKinds = liveKindNamesFrom(activeSchema);\n\n  const kindFilter =\n    options.kinds === undefined ? undefined : new Set(options.kinds);\n  const selected = pending.filter(\n    (row) => kindFilter === undefined || kindFilter.has(row.kindName),\n  );\n  const candidates = selected.filter(\n    (row) => !liveKinds[row.entity].has(row.kindName),\n  );\n  const skipped: readonly MaterializeRemovalsEntry[] = selected\n    .filter((row) => liveKinds[row.entity].has(row.kindName))\n    .map((row) => ({\n      kind: row.kindName,\n      entity: row.entity,\n      status: \"skipped\" as const,\n      reason: \"kind-is-live\" as const,\n    }));\n\n  if (candidates.length === 0) {\n    return { results: skipped, reclaimedVectorFields };\n  }\n\n  const tableNames = backend.tableNames;\n  const nodesTable = tableNames?.nodes ?? \"typegraph_nodes\";\n  const edgesTable = tableNames?.edges ?? \"typegraph_edges\";\n  const fulltextTable =\n    resolveBackendFulltext(backend) === false ? undefined : (\n      (tableNames?.fulltext ?? \"typegraph_node_fulltext\")\n    );\n  const uniquesTable = tableNames?.uniques ?? \"typegraph_node_uniques\";\n  const edgeClaimsTable = tableNames?.edgeClaims ?? \"typegraph_edge_claims\";\n\n  const captureRecordedRemovals = context.captureRecordedRemovals === true;\n  const ctx = {\n    backend,\n    graphId,\n    nodesTable,\n    edgesTable,\n    fulltextTable,\n    uniquesTable,\n    edgeClaimsTable,\n    captureRecordedRemovals,\n    recordedSchema:\n      captureRecordedRemovals ?\n        (context.recordedSchema ?? createSqlSchema(backend.tableNames))\n      : undefined,\n  } as const;\n\n  // Every candidate takes the same per-graph schema-write lock. Running them\n  // concurrently only consumes pool connections while all but one wait, so\n  // process candidates sequentially. Best-effort mode continues after failed\n  // entries; `stopOnError` short-circuits after the first failure.\n  const materialized: MaterializeRemovalsEntry[] = [];\n  for (const candidate of candidates) {\n    const entry = await materializeOne(candidate, ctx);\n    materialized.push(entry);\n    if (options.stopOnError === true && entry.status === \"failed\") break;\n  }\n  return { results: [...materialized, ...skipped], reclaimedVectorFields };\n}\n\n/**\n * Walks the schema-version history backward from the active version\n * and re-records any kind-removal whose queue row is missing entirely.\n *\n * Handles the full crash-window recovery: a `removeKinds()` call that\n * commits the schema diff but fails before recording the queue row\n * can be followed by any number of additional schema transitions\n * (evolve, deprecate, further removes) — the lost queue row is still\n * recoverable from schema history because the kind diff at that\n * specific transition is permanent metadata.\n *\n * Uses `getAllKindRemovals` to distinguish \"row missing entirely\" (the\n * crash window — needs recovery) from \"row already completed\" (a\n * successful prior cleanup — re-recording would churn\n * `last_attempted_at` even though COALESCE preserves the success).\n * Backends without that primitive fall back to the pending-only set,\n * which keeps reconciliation correct (the COALESCE rule preserves the\n * completed state) but does churn `last_attempted_at` on already-\n * completed rows. The bundled SQLite and Postgres backends implement\n * `getAllKindRemovals`.\n */\nasync function reconcilePendingRemovals(\n  context: MaterializeRemovalsContext,\n): Promise<void> {\n  const { backend, graphId } = context;\n  const recordKindRemoval = backend.recordKindRemoval;\n  if (recordKindRemoval === undefined) return;\n\n  const activeRow = await backend.getActiveSchema(graphId);\n  if (activeRow === undefined || activeRow.version <= 1) return;\n\n  // Watermark short-circuit: when a previous reconciliation pass\n  // verified history through some version M, only walk transitions\n  // newer than M. Without the watermark this loop walked from active\n  // down to version 1 on every call — N round-trips + N Zod parses\n  // per call — and re-verified already-good history every time.\n  // Backends without the marker primitives fall back to walking from\n  // version 1 (the legacy behavior) so existing custom backends\n  // keep working.\n  //\n  // Bootstrap the marker table BEFORE the read — DBs that pre-date\n  // this slice would otherwise SELECT from a missing table and throw\n  // before they got the chance to create it.\n  if (backend.ensureReconciliationMarkersTable !== undefined) {\n    await backend.ensureReconciliationMarkersTable();\n  }\n  const marker =\n    backend.getReconciliationMarker === undefined ?\n      undefined\n    : await backend.getReconciliationMarker(graphId);\n  if (marker !== undefined && marker >= activeRow.version) return;\n\n  // Existence map: a (entity, kindName, schemaVersion) is recorded if\n  // a row exists in any state (pending or completed). The rows we want\n  // to reconcile are the ones missing from this set entirely.\n  const allRemovals = await (backend.getAllKindRemovals === undefined ?\n    requireDefined(backend.getPendingKindRemovals)(graphId)\n  : backend.getAllKindRemovals(graphId));\n  const recorded = new Set(\n    allRemovals.map((row) =>\n      kindRemovalKey(row.entity, row.kindName, row.schemaVersion),\n    ),\n  );\n\n  const reconciliations: {\n    kindName: string;\n    entity: KindEntity;\n    schemaVersion: number;\n  }[] = [];\n\n  // Walk backward through transitions, stopping at the watermark.\n  // At each pair (priorRow, currentRow) we compute \"kinds removed at\n  // currentRow.version\" and check the existence map — any missing\n  // entry needs an idempotent upsert. The marker bounds the walk so\n  // long-running deployments with hundreds of schema versions skip\n  // the bulk of the round-trips after their first reconciliation.\n  const stopAtVersion = marker ?? 1;\n  let currentRow = activeRow;\n  let currentSchema = parseSerializedSchema(activeRow.schema_doc);\n  while (currentRow.version > stopAtVersion) {\n    const priorRow = await backend.getSchemaVersion(\n      graphId,\n      currentRow.version - 1,\n    );\n    if (priorRow === undefined) break;\n    const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n\n    for (const entity of ENTITY_KINDS) {\n      const priorEntries = priorSchema[entity === \"node\" ? \"nodes\" : \"edges\"];\n      const currentEntries =\n        currentSchema[entity === \"node\" ? \"nodes\" : \"edges\"];\n      for (const kindName of Object.keys(priorEntries)) {\n        if (hasOwnKey(currentEntries, kindName)) continue;\n        if (\n          recorded.has(kindRemovalKey(entity, kindName, currentRow.version))\n        ) {\n          continue;\n        }\n        reconciliations.push({\n          kindName,\n          entity,\n          schemaVersion: currentRow.version,\n        });\n      }\n    }\n\n    currentRow = priorRow;\n    currentSchema = priorSchema;\n  }\n\n  if (reconciliations.length > 0) {\n    const attemptedAt = nowIso();\n    await Promise.all(\n      reconciliations.map((entry) =>\n        recordKindRemoval(\n          buildPendingKindRemoval({\n            graphId,\n            kindName: entry.kindName,\n            entity: entry.entity,\n            schemaVersion: entry.schemaVersion,\n            attemptedAt,\n          }),\n        ),\n      ),\n    );\n  }\n\n  // Persist the new high-water mark so the next call walks only\n  // versions newer than this one. Done after the reconciliation\n  // upserts succeed — a crash before this point leaves the marker\n  // unchanged, so the next call re-walks (idempotent — recorded\n  // rows skip via the existence-map check above).\n  if (backend.setReconciliationMarker !== undefined) {\n    await backend.setReconciliationMarker(graphId, activeRow.version);\n  }\n}\n\n/**\n * Node and edge kind names the active schema declares, by entity.\n *\n * Used to refuse cleanup for a kind that has since been re-added. Returns\n * empty sets when no schema is committed — nothing is live, so nothing is\n * protected, and the pending rows proceed as before.\n */\nfunction liveKindNamesFrom(\n  schema: SerializedSchema | undefined,\n): Readonly<Record<KindEntity, ReadonlySet<string>>> {\n  if (schema === undefined) {\n    return { node: new Set<string>(), edge: new Set<string>() };\n  }\n  return {\n    node: new Set(Object.keys(schema.nodes)),\n    edge: new Set(Object.keys(schema.edges)),\n  };\n}\n\nfunction kindRemovalKey(\n  entity: KindEntity,\n  kindName: string,\n  version: number,\n): string {\n  return `${entity}|${kindName}|${version}`;\n}\n\nasync function materializeOne(\n  row: KindRemovalRow,\n  ctx: MaterializeOneContext,\n): Promise<MaterializeRemovalsEntry> {\n  const recordKindRemoval = requireDefined(ctx.backend.recordKindRemoval);\n  const schemaWriteTransaction = ctx.backend.schemaWriteTransaction;\n  if (schemaWriteTransaction === undefined) {\n    throw new ConfigurationError(\n      \"store.materializeRemovals() requires a backend that can hold the \" +\n        \"schema-write lock across the live-kind check and cleanup.\",\n      { code: \"MATERIALIZE_REMOVALS_SCHEMA_FENCE_UNSUPPORTED\" },\n    );\n  }\n  try {\n    const outcome = await schemaWriteTransaction(\n      ctx.graphId,\n      async (target): Promise<\"removed\" | \"skipped\"> => {\n        const activeRow = await target.getActiveSchema(ctx.graphId);\n        const activeSchema =\n          activeRow === undefined ? undefined : (\n            parseSerializedSchema(activeRow.schema_doc)\n          );\n        if (liveKindNamesFrom(activeSchema)[row.entity].has(row.kindName)) {\n          return \"skipped\";\n        }\n\n        await closeRecordedAndDeleteLiveRows(ctx, row, target);\n        await dropEmbeddingTableStorage(ctx, row, target);\n        return \"removed\";\n      },\n    );\n\n    if (outcome === \"skipped\") {\n      return {\n        kind: row.kindName,\n        entity: row.entity,\n        status: \"skipped\",\n        reason: \"kind-is-live\",\n      };\n    }\n\n    const removedAt = nowIso();\n    await recordKindRemoval({\n      graphId: ctx.graphId,\n      kindName: row.kindName,\n      entity: row.entity,\n      schemaVersion: row.schemaVersion,\n      attemptedAt: removedAt,\n      removedAt,\n      error: undefined,\n    });\n    return {\n      kind: row.kindName,\n      entity: row.entity,\n      status: \"removed\",\n    };\n  } catch (error_) {\n    const error = error_ instanceof Error ? error_ : new Error(String(error_));\n    await recordKindRemoval({\n      graphId: ctx.graphId,\n      kindName: row.kindName,\n      entity: row.entity,\n      schemaVersion: row.schemaVersion,\n      attemptedAt: nowIso(),\n      removedAt: undefined,\n      error: error.message,\n    });\n    return {\n      kind: row.kindName,\n      entity: row.entity,\n      status: \"failed\",\n      error,\n    };\n  }\n}\n\n/**\n * Closes recorded-time intervals for a hard-removed kind and deletes the live\n * rows in one transaction. Without the shared transaction, a crash after the\n * recorded close but before the live deletes leaves broad live reads able to see\n * rows whose kind the active schema has removed.\n *\n * Tolerates absent recorded relations exactly as `clear()` and\n * `refreshStatistics()` do: a history-enabled store whose recorded tables\n * predate recorded-time history (bring-your-own-pool, no DDL re-run) skips only\n * the close, then still deletes the live rows. A transaction-bound catalog\n * preflight avoids issuing a statement that would abort PostgreSQL and avoids\n * raw transaction framing, which Durable Object SQLite forbids. A no-op close\n * when recorded-removal capture is off.\n */\nasync function closeRecordedAndDeleteLiveRows(\n  ctx: MaterializeOneContext,\n  row: KindRemovalRow,\n  target: SchemaWriteTransactionBackend,\n): Promise<void> {\n  // Same tolerance `clearGraph` gives the relation: a database bootstrapped\n  // before edge claims existed has no such table, and reaping a removed kind's\n  // housekeeping rows must not be the operation that fails on it.\n  const reapsEdgeClaims = await target.tableExists(ctx.edgeClaimsTable);\n  const deleteStatements = buildRemovedKindLiveDeleteStatements(\n    ctx,\n    row,\n    reapsEdgeClaims,\n  );\n  if (!ctx.captureRecordedRemovals || ctx.recordedSchema === undefined) {\n    await executeDeleteStatements(target, deleteStatements);\n    return;\n  }\n\n  const recordedSchema = ctx.recordedSchema;\n  const requiredRecordedTables = [\n    recordedSchema.tables.recordedClock,\n    recordedSchema.tables.recordedEdges,\n    ...(row.entity === \"node\" ? [recordedSchema.tables.recordedNodes] : []),\n  ];\n  const recordedTablesExist = await Promise.all(\n    requiredRecordedTables.map((tableName) => target.tableExists(tableName)),\n  );\n  if (recordedTablesExist.some((exists) => !exists)) {\n    await executeDeleteStatements(target, deleteStatements);\n    return;\n  }\n\n  await closeRecordedHardDeletedKind(\n    target,\n    recordedSchema,\n    ctx.graphId,\n    { entity: row.entity, kind: row.kindName },\n    false,\n  );\n  await executeDeleteStatements(target, deleteStatements);\n}\n\n/**\n * The live rows a removed kind leaves behind, as statements.\n *\n * Neither claim family is spelled here — edge claims come from the two\n * ownership builders in `operations/edge-claims`, one for edges of a removed\n * edge kind and one for edges connected to a removed node kind.\n * The uniqueness claims are NOT spelled here: which claims a kind owns is one\n * predicate with one owner, `buildHardDeleteUniquesByConcreteKind`, and this is\n * its second consumer. Filtering on `node_kind` — the claim AXIS — instead would\n * leak a claim whose axis is a sibling kind, delete a surviving sibling's claim\n * when the removed kind IS the axis, and never match a claim whose axis is not a\n * kind at all.\n */\nfunction buildRemovedKindLiveDeleteStatements(\n  ctx: MaterializeOneContext,\n  row: KindRemovalRow,\n  reapsEdgeClaims: boolean,\n): readonly SqlFragment[] {\n  const graphLit = literal(ctx.graphId);\n  const kindLit = literal(row.kindName);\n  if (row.entity === \"node\") {\n    return [\n      // Must precede the edge delete: ownership is discovered by selecting the\n      // connected edge ids, which no longer exist afterward.\n      ...(reapsEdgeClaims ?\n        [\n          buildHardDeleteEdgeClaimsByNodeKind(\n            ctx.edgeClaimsTable,\n            ctx.edgesTable,\n            { graphId: ctx.graphId, nodeKind: row.kindName },\n          ),\n        ]\n      : []),\n      sql.raw(\n        `DELETE FROM ${quote(ctx.nodesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n      ),\n      sql.raw(\n        `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND (from_kind = ${kindLit} OR to_kind = ${kindLit})`,\n      ),\n      // Omitted when the backend has no active fulltext strategy — the\n      // table was never created, so there is nothing to reap.\n      ...(ctx.fulltextTable === undefined ?\n        []\n      : [\n          sql.raw(\n            `DELETE FROM ${quote(ctx.fulltextTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n          ),\n        ]),\n      buildHardDeleteUniquesByConcreteKind(ctx.uniquesTable, {\n        graphId: ctx.graphId,\n        concreteKind: row.kindName,\n      }),\n    ];\n  }\n  return [\n    sql.raw(\n      `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n    ),\n    // Housekeeping, on the same one-owner terms as the uniqueness reap: the\n    // rows this kind's edges held are takeable the moment those edges are gone,\n    // but nothing would ever reap them, so the relation would grow by one row\n    // per removed constrained kind forever.\n    ...(reapsEdgeClaims ?\n      [\n        buildHardDeleteEdgeClaimsByEdgeKind(ctx.edgeClaimsTable, {\n          graphId: ctx.graphId,\n          edgeKind: row.kindName,\n        }),\n      ]\n    : []),\n  ];\n}\n\nasync function executeDeleteStatements(\n  target: SchemaWriteTransactionBackend,\n  statements: readonly SqlFragment[],\n): Promise<void> {\n  for (const statement of statements) {\n    await target.executeStatement(asCompiledStatementSql(statement));\n  }\n}\n\n/**\n * Builds the embedding-storage cleanup for a removed node kind.\n *\n * With per-`(graphId, kind, field)` storage there is no single shared\n * embeddings table to filter by `node_kind`; each embedding field of the\n * removed kind has its own typed, graph-scoped table. We resolve those fields\n * from the schema version that still *had* the kind (`schemaVersion - 1`) and\n * drop each per-field table via the strategy — the same teardown the\n * removed-*field* reclamation uses — so the kind's table and any ANN index it\n * owns are fully reclaimed (a stale empty table would otherwise collide with a\n * re-added kind at a different dimension).\n *\n * Backends without a vector strategy, or schema history that can't be\n * read, yield no cleanup — there is no embedding storage to reclaim.\n */\nasync function dropEmbeddingTableStorage(\n  ctx: Readonly<{\n    backend: GraphBackend;\n    graphId: string;\n  }>,\n  row: KindRemovalRow,\n  target: SchemaWriteTransactionBackend,\n): Promise<void> {\n  const vectorStrategy = ctx.backend.vectorStrategy;\n  if (vectorStrategy === undefined) return;\n\n  const executeDdl = target.executeSchemaDdl;\n  const deleteContribution = target.deleteSchemaVectorSlotContribution;\n  const slots = await resolveRemovedKindEmbeddingSlots(target, row);\n  for (const slot of slots) {\n    await dropVectorSlotStorage(vectorStrategy, executeDdl, slot);\n    await deleteContribution(slot);\n  }\n}\n\n/**\n * Drops a per-field vector slot's storage via the strategy (table + any ANN\n * index it owns), tolerating an already-absent table — a declared field whose\n * per-field table was never materialized (no write, no index build) has nothing\n * to reclaim. The caller supplies the schema transaction's DDL executor so the\n * storage drop and marker deletion commit or roll back together. Shared by\n * removed-kind cleanup and removed-field reclamation so both reclaim storage\n * the same way.\n */\nasync function dropVectorSlotStorage(\n  strategy: VectorStrategy,\n  executeDdl: (statement: string) => Promise<void>,\n  slot: VectorSlot,\n): Promise<void> {\n  try {\n    for (const ddl of strategy.buildDropStorage(slot)) {\n      await executeDdl(ddl);\n    }\n  } catch (error) {\n    if (!isMissingTableError(error)) throw error;\n  }\n}\n\n/**\n * Resolves the embedding field paths a removed node kind declared, read\n * from the persisted vector index declarations in the schema version\n * just before the removal (`schemaVersion - 1`). Returns `[]` when the\n * prior version is unavailable or declared no embedding fields for the\n * kind.\n */\nasync function resolveRemovedKindEmbeddingSlots(\n  backend: GraphBackend | TransactionBackend,\n  row: KindRemovalRow,\n): Promise<readonly VectorSlot[]> {\n  const priorVersion = row.schemaVersion - 1;\n  if (priorVersion < 1) return [];\n  const priorRow = await backend.getSchemaVersion(row.graphId, priorVersion);\n  if (priorRow === undefined) return [];\n\n  const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n  const slots = new Map<string, VectorSlot>();\n  for (const declaration of priorSchema.indexes ?? []) {\n    if (declaration.entity === \"vector\" && declaration.kind === row.kindName) {\n      slots.set(declaration.fieldPath, {\n        graphId: row.graphId,\n        nodeKind: row.kindName,\n        fieldPath: declaration.fieldPath,\n        dimensions: declaration.dimensions,\n        metric: declaration.metric,\n        indexType: declaration.indexType,\n      });\n    }\n  }\n  return [...slots.values()];\n}\n\n/** Stable key for a `(kind, fieldPath)` embedding-field pair. */\nfunction vectorFieldKey(kind: string, fieldPath: string): string {\n  return `${kind}\\u0000${fieldPath}`;\n}\n\nfunction vectorFieldKeysFrom(schema: SerializedSchema): ReadonlySet<string> {\n  const keys = new Set<string>();\n  for (const declaration of schema.indexes ?? []) {\n    if (declaration.entity === \"vector\") {\n      keys.add(vectorFieldKey(declaration.kind, declaration.fieldPath));\n    }\n  }\n  return keys;\n}\n\n/**\n * The historical declaration of a vector field, carrying everything\n * {@link VectorStrategy.buildDropStorage} needs to tear the storage down —\n * notably `indexType`, which libSQL reads to also drop its DiskANN index.\n */\ntype HistoricalVectorField = Readonly<{\n  kind: string;\n  fieldPath: string;\n  slot: VectorSlot;\n}>;\n\n/**\n * Reclaims per-`(graphId, kind, field)` vector tables orphaned by embedding-\n * field removals on *surviving* kinds.\n *\n * Per-field storage means every embedding field owns a typed table. When a\n * field is dropped from a kind that still exists (an `evolve` that removes the\n * embedding), nothing reclaims that table: the add-only `materializeIndexes`\n * path ignores removals and the kind-scoped cleanup above only fires for whole\n * removed kinds. Left alone the table lingers with dead rows that no query\n * reads again, and — worse — a later re-add of the field at a different\n * dimension would collide with the stale table.\n *\n * The orphan set is derived from schema history: every vector field ever\n * declared, minus the ones still declared in the *active* schema, restricted\n * to kinds that still exist (removed-kind fields are the kind path's job).\n * The initial active-schema read only finds candidates. Each candidate is\n * rechecked while holding the schema-write lock, and its DDL plus durable\n * marker deletion run in that same transaction. A re-add therefore commits\n * either before the locked check (and is skipped) or after cleanup commits.\n * `buildDropStorage` emits `DROP ... IF EXISTS`, so the pass is idempotent and\n * a never-materialized field is a clean no-op; deriving from full history each\n * call also reclaims tables orphaned before this shipped.\n *\n * Backends without a vector strategy have no per-field tables to reclaim and\n * yield an empty result.\n */\nasync function reclaimRemovedVectorFieldTables(\n  context: MaterializeRemovalsContext,\n  activeRow: SchemaVersionRow | undefined,\n): Promise<readonly ReclaimedVectorFieldEntry[]> {\n  const { backend, graphId } = context;\n  const vectorStrategy = backend.vectorStrategy;\n  if (vectorStrategy === undefined) return [];\n  if (activeRow === undefined) return [];\n\n  // The orphan set is a pure function of (graphId, active version) over\n  // immutable schema history and the drops are idempotent, so re-walking the\n  // whole history on every materializeRemovals call is wasted O(versions) work.\n  // Memoize per (backend, graphId:version); an evolve bumps the version and\n  // invalidates. Only fully-successful passes are cached (a failed drop must be\n  // retried), and the cache is in-process so a fresh backend re-walks once.\n  const cacheKey = `${graphId}\\u0000${activeRow.version}`;\n  let perBackend = reclaimCache.get(backend);\n  const cached = perBackend?.get(cacheKey);\n  if (cached !== undefined) return cached;\n\n  const activeSchema = parseSerializedSchema(activeRow.schema_doc);\n\n  const activeVectorFields = vectorFieldKeysFrom(activeSchema);\n  const survivingKinds = new Set(Object.keys(activeSchema.nodes));\n\n  // Walk history backward, keeping the most-recent declaration of each\n  // vector field (first seen wins) so `buildDropStorage` gets a faithful\n  // `indexType`/`dimensions`.\n  const historical = new Map<string, HistoricalVectorField>();\n  for (let version = activeRow.version - 1; version >= 1; version -= 1) {\n    const priorRow = await backend.getSchemaVersion(graphId, version);\n    if (priorRow === undefined) continue;\n    const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n    for (const declaration of priorSchema.indexes ?? []) {\n      if (declaration.entity !== \"vector\") continue;\n      const key = vectorFieldKey(declaration.kind, declaration.fieldPath);\n      if (historical.has(key)) continue;\n      historical.set(key, {\n        kind: declaration.kind,\n        fieldPath: declaration.fieldPath,\n        slot: {\n          graphId,\n          nodeKind: declaration.kind,\n          fieldPath: declaration.fieldPath,\n          dimensions: declaration.dimensions,\n          metric: declaration.metric,\n          indexType: declaration.indexType,\n        },\n      });\n    }\n  }\n\n  // Both clauses key on the ACTIVE schema to keep the candidate set narrow:\n  // `survivingKinds` requires the kind to be live now, so a re-added kind with\n  // its field re-declared is not an orphan, and a still-removed kind is left\n  // to the candidate loop in `materializeRemovals` instead.\n  //\n  // This scan is not the safety boundary: a schema commit can land after it.\n  // The per-field transaction below re-reads the same authority under the\n  // schema-write lock before issuing DDL.\n  const orphans = [...historical.values()].filter(\n    (field) =>\n      !activeVectorFields.has(vectorFieldKey(field.kind, field.fieldPath)) &&\n      survivingKinds.has(field.kind),\n  );\n\n  const results: ReclaimedVectorFieldEntry[] = [];\n  let skippedAfterLockedRecheck = false;\n  const schemaWriteTransaction = backend.schemaWriteTransaction;\n  if (orphans.length > 0 && schemaWriteTransaction === undefined) {\n    throw new ConfigurationError(\n      \"store.materializeRemovals() requires a backend that can hold the \" +\n        \"schema-write lock across the vector-field liveness check and cleanup.\",\n      { code: \"MATERIALIZE_REMOVALS_SCHEMA_FENCE_UNSUPPORTED\" },\n    );\n  }\n  for (const field of orphans) {\n    try {\n      const reclaimed = await requireDefined(schemaWriteTransaction)(\n        graphId,\n        async (target): Promise<boolean> => {\n          const lockedActiveRow = await target.getActiveSchema(graphId);\n          if (lockedActiveRow === undefined) return false;\n          const lockedActiveSchema = parseSerializedSchema(\n            lockedActiveRow.schema_doc,\n          );\n          const lockedVectorFields = vectorFieldKeysFrom(lockedActiveSchema);\n          if (\n            lockedVectorFields.has(\n              vectorFieldKey(field.kind, field.fieldPath),\n            ) ||\n            !Object.hasOwn(lockedActiveSchema.nodes, field.kind)\n          ) {\n            return false;\n          }\n\n          await dropVectorSlotStorage(\n            vectorStrategy,\n            target.executeSchemaDdl,\n            field.slot,\n          );\n          await target.deleteSchemaVectorSlotContribution(field.slot);\n          return true;\n        },\n      );\n      if (!reclaimed) {\n        skippedAfterLockedRecheck = true;\n        continue;\n      }\n      results.push({\n        kind: field.kind,\n        fieldPath: field.fieldPath,\n        status: \"reclaimed\",\n      });\n    } catch (error) {\n      results.push({\n        kind: field.kind,\n        fieldPath: field.fieldPath,\n        status: \"failed\",\n        error: error instanceof Error ? error : new Error(String(error)),\n      });\n    }\n  }\n\n  // Cache only a fully-successful pass — a failed drop must be retried.\n  if (\n    !skippedAfterLockedRecheck &&\n    results.every((entry) => entry.status === \"reclaimed\")\n  ) {\n    if (perBackend === undefined) {\n      perBackend = new Map();\n      reclaimCache.set(backend, perBackend);\n    }\n    perBackend.set(cacheKey, results);\n  }\n  return results;\n}\n\n/**\n * In-process memo for {@link reclaimRemovedVectorFieldTables}, keyed by backend\n * then `graphId:activeVersion`. See that function for why version-keying is\n * sound (the orphan set is a pure function of immutable history + the version).\n */\nconst reclaimCache = new WeakMap<\n  GraphBackend,\n  Map<string, readonly ReclaimedVectorFieldEntry[]>\n>();\n\n// The DELETE statements built here are dialect-neutral and use no\n// SQLite/Postgres-specific syntax. They use single-quote string literals for\n// graph_id / kind names. Both\n// values come from the schema — never untrusted user input — but we\n// still escape single quotes defensively to avoid surprises if a\n// future kind-name validator narrows beyond `[A-Za-z_][A-Za-z0-9_]*`.\nfunction quote(identifier: string): string {\n  return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction literal(value: string): string {\n  return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","/**\n * The write-side half of an edge's identity fence: what a kind-predicated\n * UPDATE means when it matched nothing, and the internal signal that verdict\n * produces.\n *\n * ## Why this is not in `edge-identity.ts`\n *\n * That module is the pure predicate — it compares an expectation against a row\n * and throws, and it imports nothing but the error types. The diagnosis below\n * is a different job: it READS the backend, classifies a\n * `DatabaseOperationError` raised by a write, and re-derives the predicate's\n * verdict against what it finds. Putting it there would give the identity\n * predicate a backend dependency and a write-error dependency it does not have\n * today, on the module every edge read path already imports.\n *\n * ## Why it is caller-applied, not part of the session\n *\n * The store and interchange import interpret a zero-row edge UPDATE\n * DIFFERENTLY, and both readings are deliberate: the store re-reads and either\n * converges on the row that is actually there or refuses with a typed error,\n * while import records a per-row conflict and continues to the next row. A\n * fused write unit owns the row, its fences and its sidecars — not one recovery\n * policy for every caller. So `session.reviseEdge` issues the write and lets\n * the backend's error propagate, and this wrapper is applied by the caller that\n * wants the store's reading of it.\n */\nimport { type EdgeRow, type GraphReadBackend } from \"../../backend/types\";\nimport { DatabaseOperationError, EdgeNotFoundError } from \"../../errors\";\nimport {\n  assertEdgeIdentityMatches,\n  type EdgeIdentityExpectation,\n  edgeIdentityFromRow,\n} from \"./edge-identity\";\n\n/**\n * Internal signal: the edge is still there and still this edge, but the\n * validity bound the update asserted no longer holds.\n *\n * Never returned to a caller. The store's converge-and-retry loop is the only\n * code that catches it, and it does so to re-read and re-judge rather than to\n * report anything.\n */\nexport class EdgeUpdateTargetMoved extends Error {\n  constructor(kind: string, id: string) {\n    super(\n      `The ${kind} edge \"${id}\" was replaced between this update's read and ` +\n        `its write; re-resolving it. This is internal and is never returned ` +\n        `to a caller.`,\n    );\n    this.name = \"EdgeUpdateTargetMoved\";\n  }\n}\n\nfunction isEdgeUpdateNoRowError(\n  error: unknown,\n): error is DatabaseOperationError {\n  return (\n    error instanceof DatabaseOperationError &&\n    error.details.operation === \"update\" &&\n    error.details.entity === \"edge\" &&\n    error.details.reason === \"no_row_returned\"\n  );\n}\n\n/**\n * Reports a kind-predicated edge UPDATE that matched nothing.\n *\n * With the expected kind in the statement's `WHERE`, \"no row returned\" is no\n * longer only \"the row vanished\" — it is also \"the id now resolves to a\n * different edge\" (or \"the row was tombstoned\", for a non-resurrecting\n * update). Only this failure path pays the extra read, and it re-derives the\n * SAME verdict the pre-write check would have reached, through the same single\n * owner ({@link assertEdgeIdentityMatches}), so the caller cannot tell which of\n * the two raised it.\n *\n * `assertedValidFrom` is the write's own fence, read through\n * `assertsStoredLowerBound` by the caller that stated it — never re-derived\n * here from the params, which this wrapper deliberately never sees.\n */\nexport async function withUnmatchedEdgeUpdateRefusal(\n  graphId: string,\n  target: Pick<GraphReadBackend, \"getEdge\">,\n  id: string,\n  expected: EdgeIdentityExpectation,\n  assertedValidFrom: boolean,\n  write: () => Promise<EdgeRow>,\n): Promise<EdgeRow> {\n  try {\n    return await write();\n  } catch (error) {\n    if (!isEdgeUpdateNoRowError(error)) throw error;\n    const current = await target.getEdge(graphId, id);\n    if (current !== undefined) {\n      assertEdgeIdentityMatches(\n        id,\n        expected,\n        edgeIdentityFromRow(current),\n        \"update\",\n      );\n      // Identity still matches, so the predicate that stopped matching was the\n      // validity bound this update asserted — the row was replaced by an\n      // incarnation whose window the verdict never saw. That is not \"no such\n      // edge\", and reporting it as one would be a lie about a row that is\n      // sitting right there; it is a stale target, and the caller above\n      // converges on the row that is actually present.\n      if (assertedValidFrom && current.deleted_at === undefined) {\n        throw new EdgeUpdateTargetMoved(expected.kind, id);\n      }\n    }\n    // The row is gone, or still this edge but tombstoned by a concurrent\n    // delete (a non-resurrecting UPDATE carries `deleted_at IS NULL`). Either\n    // way the edge this update was for no longer exists to update.\n    throw new EdgeNotFoundError(expected.kind, id);\n  }\n}\n","/**\n * Edge Operations for Store\n *\n * Handles edge CRUD operations: create, update, delete.\n *\n * ## Invariants this module owns\n *\n * **An edge write lands only on a row satisfying every identity component it\n * ASSERTED.** Each write issued on behalf of a kind-scoped collection —\n * `update`, soft `delete`, `hardDelete`, the batch soft delete — carries the\n * identity it asserted INSIDE the write statement's own `WHERE` (see\n * {@link UpdateEdgeParams}'s `kind` / `fromKind` / `fromId` / `toKind` /\n * `toId`). The identity the operation checked and the row the statement mutates\n * are therefore resolved by one predicate in one statement, on every backend\n * and at every isolation level: nothing another session does between the check\n * and the write can re-point that id at a row failing an assertion this write\n * made. An assertion that does not match affects zero rows, and the caller\n * hears the same `EDGE_IDENTITY_MISMATCH` / not-found refusal it would have\n * heard from the check.\n *\n * The scope of the claim is exactly \"what it asserted\", and no wider. An upsert\n * that resolved an edge BY its endpoints asserts them and predicates on them,\n * so a same-kind `hardDelete` + recreate pointing somewhere else is refused.\n * A plain `update` on a kind-scoped collection asserts only kind — it resolved\n * the edge by id and never looked at where it points — so a same-kind recreate\n * with different endpoints is a row it is content to write, and predicating on\n * endpoints it never checked would refuse legitimate writes instead. The node\n * delete cascade asserts nothing at all: it removes every connected edge\n * whatever its kind, and is deliberately left identity-blind.\n *\n * **A declared constraint's probe and the write it guards commit under one\n * per-graph mutual exclusion, on every backend.** Cardinality (`one` /\n * `unique` / `oneActive`) is enforced by an application probe that no database\n * key backs — the edges table's only uniqueness is its `(graph_id, id)` primary\n * key — and `getOrCreateByEndpoints` converges on a match key no key backs\n * either. Those writes therefore take the per-graph write fence for the whole\n * probe-and-write transaction (see\n * {@link file://./write-transaction.ts runInWriteTransaction}'s\n * `fencesConstraintProbe`), which SQLite already supplies through\n * `BEGIN IMMEDIATE` and PostgreSQL supplies through the per-graph advisory\n * lock — previously taken only when history or revision tracking was on, and so\n * absent from a default PostgreSQL store. An UNCONSTRAINED edge write\n * (cardinality `many`, no convergence probe) states that it needs no fence and\n * pays for none.\n *\n * **A write asserts every component its verdict READ.** The identity claim\n * above is one instance of a wider rule, and the rule is what keeps this module\n * honest: `performEdgeUpdate` probes the row, decides from what it finds, and\n * then writes, so anything the decision consumed and the statement does not\n * restate is a decision that can land on a row it was never computed for.\n * Enumerated, with where each is asserted:\n *\n *  - `kind` and the four endpoint components — asserted, per the paragraph\n *    above, exactly to the extent the caller claimed them.\n *  - `deleted_at` (live vs tombstoned, which selects the leg) — asserted as\n *    `deleted_at IS NULL` on the in-place leg. Deliberately NOT asserted on the\n *    resurrecting leg: `buildUpdateEdge`'s `clearDeleted` branch carries no\n *    tombstone predicate, so an upsert whose peer revived the row first still\n *    applies its window instead of failing. That is a convergence choice, not\n *    an oversight — the losing writer owns the properties either way.\n *  - `valid_from` — asserted via `expectedValidFrom` WHEN the window verdict\n *    read it ({@link ValidityWindowVerdict}), which is when the caller stated a\n *    `validFrom` to compare or a lone `validTo` to invert against the row's\n *    bound. A caller that states no window reads no bound and is fenced by\n *    nothing extra, on the same \"only what it asserted\" principle as endpoints.\n *  - `props` — read as the merge base for the caller's partial update, and NOT\n *    assertable: an edge props blob is TEXT on SQLite and `jsonb` on\n *    PostgreSQL, and neither comparison is stable under key reordering. Bounded\n *    instead by {@link performEdgeUpdateConverging}, which re-reads and\n *    re-merges whenever the bound assertion catches a replaced row.\n *  - `valid_to` when deciding whether an ended/deleted edge re-enters the active\n *    `oneActive` population — asserted only for that decision; other\n *    cardinalities do not turn an unconditional clear into a stale-value CAS.\n */\nimport {\n  AtomicEdgeBatchCardinalityRefusalError,\n  AtomicEdgeBatchEndpointRefusalError,\n  AtomicEdgeConvergenceTombstoneRefusalError,\n  type AtomicEdgeDeleteBatchExecutor,\n  AtomicEdgeDeleteIdentityRefusalError,\n  type AtomicEdgeResolvedUpdateBatchExecutor,\n} from \"../../backend/capabilities/atomic-mutation-program\";\nimport { isBundledRootAutocommitEligible } from \"../../backend/capabilities/autocommit-single-statement\";\nimport { bindExtraIfReachable } from \"../../backend/capabilities/bind\";\nimport {\n  BATCH_POINT_READ,\n  type STATEMENT_EXECUTION,\n  type UNIQUE_SIDECAR_BATCH,\n} from \"../../backend/capabilities/bundle-registry\";\nimport {\n  type BundleVerdictOf,\n  type ClaimsVerdictThunk,\n} from \"../../backend/capabilities/resolve\";\nimport { isSchemaFencedInsertEligible } from \"../../backend/capabilities/schema-fenced-insert\";\nimport {\n  assertGraphCommandConvergenceIsolation,\n  executeAuthoritativeGraphCommand,\n} from \"../../backend/command-contract\";\nimport { assertEdgeMatchIdentityBackendSupport } from \"../../backend/edge-match-identity\";\nimport {\n  type ClaimEdgeCardinalityParams,\n  type EdgeConvergeCreateCommand,\n  type EdgeCreateCommand,\n  type EdgeRow as BackendEdgeRow,\n  type GraphBackend,\n  type GraphReadBackend,\n  type InsertEdgeParams,\n  rowPropsToObject,\n  runOptionallyInTransaction,\n  type TransactionBackend,\n} from \"../../backend/types\";\nimport { validateEdgeEndpoints } from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n  type Cardinality,\n  type KindEntity,\n  type TemporalMode,\n} from \"../../core/types\";\nimport {\n  CardinalityError,\n  CompilerInvariantError,\n  ConfigurationError,\n  DatabaseOperationError,\n  EdgeMatchIdentityConflictError,\n  EdgeNotFoundError,\n  EndpointNotFoundError,\n  KindNotFoundError,\n  ValidationError,\n} from \"../../errors\";\nimport { validateEdgeProps } from \"../../errors/validation\";\nimport { type SqlSchema } from \"../../query/compiler/schema\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { canonicalEqual } from \"../../schema/canonical\";\nimport { chunk } from \"../../utils/array\";\nimport {\n  assertOrderedValidityWindow,\n  assertWritableValidityWindow,\n  preservesImmutableLowerBound,\n  validateOptionalCanonicalIsoDate,\n  validateStatedValidityLowerBound,\n} from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport { hasOwnKey, readOwnProperty } from \"../../utils/object\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { encodeTupleKey } from \"../../utils/tuple-key\";\nimport { compareClaimTargets } from \"../claims/axis\";\nimport {\n  claimEdgeCardinality,\n  edgeCardinalityClaim,\n  edgeCardinalityClaimMode,\n  edgeCardinalityClaimRefusal,\n  edgeCardinalityClaimTarget,\n} from \"../claims/edge-claims\";\nimport {\n  shouldCoalesceUpsert,\n  type UpsertDirtyCheck,\n} from \"../collections/coalesce\";\nimport {\n  type EdgeUpsertUpdateBatchEntry,\n  type UpsertUpdateEdgeInput,\n} from \"../collections/edge-collection\";\nimport {\n  checkCardinalityConstraint,\n  type ConstraintContext,\n  type ConstraintFenceReason,\n  edgeWriteNeedsConstraintFence,\n} from \"../constraints\";\nimport { classifyDurableEdgeBatchOutcomes } from \"../durable-edge-batch\";\nimport { getEdgeRowsByIds } from \"../edge-fetch\";\nimport {\n  buildEdgeMatchKey,\n  canonicalPersistedJsonValue,\n  edgeMatchIdentityUpdateRefusal,\n  normalizePersistedEdgeMatchProps,\n  resolveEdgeMatchIdentityStorage,\n} from \"../edge-match-key\";\nimport { type GraphWriteLock } from \"../recorded-capture/clock\";\nimport {\n  appliedResolvedMutationSet,\n  type ResolvedMutationSetAttempt,\n  ResolvedMutationSetMoved,\n  unsupportedResolvedMutationSet,\n} from \"../resolved-mutation-set\";\nimport { type EdgeRow, rowToEdge } from \"../row-mappers\";\nimport {\n  type CreateEdgeInput,\n  type Edge,\n  type GetOrCreateAction,\n  type IfExistsMode,\n  type OperationHookContext,\n} from \"../types\";\nimport {\n  assertClearValidToSupported,\n  assertValidityEndMutation,\n  validityEndAfterMutation,\n} from \"../validity-end\";\nimport { withAlreadyExistsTranslation } from \"./already-exists\";\nimport {\n  assertAtomicDeleteSchemaFenceMatched,\n  type AtomicEdgeBatchExecutor,\n  resolveAtomicEdgeBatchExecutor,\n  resolveAtomicEdgeConvergenceExecutor,\n  resolveAtomicEdgeDeleteBatchExecutor,\n  resolveAtomicEdgeResolvedMutationSetExecutor,\n  resolveAtomicEdgeResolvedUpdateBatchExecutor,\n} from \"./atomic-mutation-program\";\nimport {\n  AutocommitWriteRequiresTransaction,\n  canFuseSchemaFenceInFirstWrite,\n  isAutocommitSingleStatementWrite,\n} from \"./autocommit-single-statement\";\nimport { createEdgeBatchValidationBackend } from \"./edge-batch-validation\";\nimport {\n  assertEdgeIdentityMatches,\n  type EdgeIdentityExpectation,\n  edgeIdentityFromRow,\n} from \"./edge-identity\";\nimport {\n  EdgeUpdateTargetMoved,\n  withUnmatchedEdgeUpdateRefusal,\n} from \"./edge-write-fences\";\nimport { type EdgeUpdateWork } from \"./edge-write-pipeline\";\nimport {\n  atomicResolvedUpdateAttemptBudget,\n  type OverlaidSessionMint,\n  runAtomicProgramWithHooks,\n  runAutocommitSingleStatementWritePlan,\n  runHookedWritePlan,\n  runWritePlan,\n  writeResultAlwaysChanges,\n} from \"./write-executor\";\nimport {\n  assertsStoredWindowState,\n  type EdgeUpdateFences,\n} from \"./write-fences\";\nimport { edgeWritePlan } from \"./write-plan\";\nimport {\n  type EdgeInsertWork,\n  type EdgeWriteSession,\n  nestedManagedWriteTarget,\n  unfencedTarget,\n  type WriteTarget,\n} from \"./write-session\";\nimport {\n  diagnoseFusedSchemaFenceNoRow,\n  hasLeasedSchemaFence,\n  lockSchemaVersionForStoreWrite,\n  memoizeLeasedSchemaFence,\n  type WriteTransactionMode,\n} from \"./write-transaction\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Context for edge operations.\n */\nexport type EdgeOperationContext<G extends GraphDef> = Readonly<{\n  graph: G;\n  graphId: string;\n  schemaVersion: number | undefined;\n  historyEnabled: boolean;\n  revisionTrackingEnabled: boolean;\n  coalesceUnchangedUpsertsEnabled: boolean;\n  revisionSchema: SqlSchema;\n  registry: KindRegistry;\n  /**\n   * The `claims` bundle's memoized, at-most-once verdict thunk (ruling B7\n   * refinement 2) — threaded through to `createEdgeWriteContext` by\n   * `runWritePlan`'s session mint, and called at the write-session sites that\n   * issue or release an edge-cardinality claim.\n   */\n  claimsVerdict: ClaimsVerdictThunk;\n  /** Threaded from `store.ts`'s `#batchPointRead` — never re-resolved here. */\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  /**\n   * Threaded from `store.ts`'s `#uniqueSidecarBatch` — the edge side never\n   * consults it (uniqueness sidecars are a node-only concern), but the field\n   * is structurally required: `runWritePlan` mints ONE shared write session\n   * from this context for both node and edge write contexts, and the\n   * session's `WriteSessionContext` parameter carries the field.\n   */\n  uniqueSidecarBatch: BundleVerdictOf<typeof UNIQUE_SIDECAR_BATCH>;\n  /** Threaded from `store.ts`; exact transaction targets bind separately. */\n  statementExecution: BundleVerdictOf<typeof STATEMENT_EXECUTION>;\n  createOperationContext: (\n    operation: \"create\" | \"update\" | \"delete\",\n    entity: KindEntity,\n    kind: string,\n    id: string,\n  ) => OperationHookContext;\n  withOperationHooks: <T>(\n    ctx: OperationHookContext,\n    fn: () => Promise<T>,\n    didWrite?: (result: T) => boolean,\n  ) => Promise<T>;\n}>;\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n// Own-key membership, matching `store.getEdgePropsSchema` and the collections\n// proxy: kind names are arbitrary identifiers, so a `toString`-named kind that\n// is NOT registered would otherwise read the inherited function as its\n// registration and fail with a `TypeError` off `registration.type` instead of\n// the `KindNotFoundError` this guard exists to raise.\nfunction getEdgeRegistration<G extends GraphDef>(graph: G, kind: string) {\n  if (!hasOwnKey(graph.edges, kind)) throw new KindNotFoundError(kind, \"edge\");\n  const registration = graph.edges[kind];\n  if (registration === undefined) throw new KindNotFoundError(kind, \"edge\");\n  return registration;\n}\n\ntype EdgeCreatePrepared = Readonly<{\n  insertParams: InsertEdgeParams;\n  cardinality: Cardinality;\n}>;\n\n/**\n * One prepared create as the session's insert unit: the row params and the\n * cardinality claim the row owes.\n *\n * ONE owner, shared by the single create and both batch shapes. The claim is a\n * pure function of the cardinality this preparation resolved, so deciding it\n * here keeps the decision beside the verdict it follows from; the session issues\n * it, because a claim write is a backend member only the seam may spell.\n */\nfunction edgeInsertWork(prepared: EdgeCreatePrepared): EdgeInsertWork {\n  const claim = edgeCardinalityClaim(\n    prepared.cardinality,\n    prepared.insertParams,\n  );\n  return {\n    params: prepared.insertParams,\n    claim,\n  };\n}\n\nfunction buildInsertEdgeParams(\n  graphId: string,\n  id: string,\n  kind: string,\n  fromKind: string,\n  fromId: string,\n  toKind: string,\n  toId: string,\n  props: Record<string, unknown>,\n  validFrom: string | null | undefined,\n  validTo: string | undefined,\n  matchIdentity?: Readonly<{ name: string; key: string }>,\n): InsertEdgeParams {\n  const insertParams: {\n    graphId: string;\n    id: string;\n    kind: string;\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    props: Record<string, unknown>;\n    validFrom?: string | null;\n    validTo?: string;\n    matchIdentity?: Readonly<{ name: string; key: string }>;\n  } = {\n    graphId,\n    id,\n    kind,\n    fromKind,\n    fromId,\n    toKind,\n    toId,\n    props,\n  };\n  if (validFrom !== undefined) insertParams.validFrom = validFrom;\n  if (validTo !== undefined) insertParams.validTo = validTo;\n  if (matchIdentity !== undefined) insertParams.matchIdentity = matchIdentity;\n  return insertParams;\n}\n\nasync function validateAndPrepareEdgeCreate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: CreateEdgeInput,\n  id: string,\n  backend: WriteTarget,\n  options?: Readonly<{\n    validateEndpoints?: boolean;\n    validateCardinality?: boolean;\n  }>,\n): Promise<EdgeCreatePrepared> {\n  const kind = input.kind;\n  const fromKind = input.fromKind;\n  const toKind = input.toKind;\n\n  // Validate kind exists and get registration\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  const edgeKind = registration.type;\n  assertEdgeMatchIdentityBackendSupport(\n    registration.matchIdentity,\n    backend.capabilities,\n    kind,\n  );\n\n  // Validate endpoint types\n  const endpointError = validateEdgeEndpoints(\n    kind,\n    fromKind,\n    toKind,\n    registration,\n    ctx.registry,\n  );\n  if (endpointError) throw endpointError;\n\n  if (options?.validateEndpoints ?? true) {\n    await assertLiveEdgeEndpoints(\n      ctx,\n      kind,\n      fromKind,\n      input.fromId,\n      toKind,\n      input.toId,\n      backend,\n    );\n  }\n\n  // Validate props with full context\n  const validatedProps = validateEdgeProps(edgeKind.schema, input.props, {\n    kind,\n    operation: \"create\",\n  });\n  const matchIdentity = resolveEdgeMatchIdentityStorage(\n    registration.matchIdentity,\n    {\n      fromKind,\n      fromId: input.fromId,\n      toKind,\n      toId: input.toId,\n      props: validatedProps,\n    },\n    { graphId: ctx.graphId, edgeKind: kind },\n  );\n\n  // Validate temporal fields\n  const validFrom = validateStatedValidityLowerBound(\n    input.validFrom,\n    \"validFrom\",\n  );\n  const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n  // A stated pair must be ordered, and on an insert that is the COMPLETE rule.\n  // A lone historical validTo is NOT an error — it means \"born already ended\"\n  // (see assertWritableValidityWindow), and the insert stores no lower bound for\n  // it rather than one past the stated end, so there is no effective bound left\n  // for this layer to judge. Both create paths (single and batch) prepare\n  // through here, so this is the only insert-side check needed.\n  assertOrderedValidityWindow(`edge \"${id}\"`, validFrom, validTo);\n\n  // Check cardinality constraints\n  const cardinality = registration.cardinality ?? \"many\";\n  const constraintContext: ConstraintContext = {\n    graphId: ctx.graphId,\n    registry: ctx.registry,\n    backend,\n  };\n  if (options?.validateCardinality ?? true) {\n    await checkCardinalityConstraint(\n      constraintContext,\n      kind,\n      cardinality,\n      fromKind,\n      input.fromId,\n      toKind,\n      input.toId,\n      validTo,\n    );\n  }\n\n  return {\n    cardinality,\n    insertParams: buildInsertEdgeParams(\n      ctx.graphId,\n      id,\n      kind,\n      fromKind,\n      input.fromId,\n      toKind,\n      input.toId,\n      validatedProps,\n      validFrom,\n      validTo,\n      matchIdentity,\n    ),\n  };\n}\n\n/**\n * Gives endpoint refusals their public ordering: source wins when both inputs\n * are unavailable. The fused INSERT uses this only after its predicate\n * produced no row, so it never spends the reads on a successful create.\n */\nasync function assertLiveEdgeEndpoints<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  edgeKindName: string,\n  fromKind: string,\n  fromId: string,\n  toKind: string,\n  toId: string,\n  backend: WriteTarget,\n): Promise<void> {\n  const fromNode = await backend.getNode(ctx.graphId, fromKind, fromId);\n  assertEndpointRowLive(edgeKindName, \"from\", fromKind, fromId, fromNode);\n\n  const toNode = await backend.getNode(ctx.graphId, toKind, toId);\n  assertEndpointRowLive(edgeKindName, \"to\", toKind, toId, toNode);\n}\n\n/** The single owner of an edge endpoint row's live/refusal verdict. */\nfunction assertEndpointRowLive(\n  edgeKind: string,\n  endpoint: \"from\" | \"to\",\n  nodeKind: string,\n  nodeId: string,\n  row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n): void {\n  if (!row || row.deleted_at) {\n    throw new EndpointNotFoundError({\n      edgeKind,\n      endpoint,\n      nodeKind,\n      nodeId,\n    });\n  }\n}\n\n// ============================================================\n// Edge Operations\n// ============================================================\n\n/**\n * The cardinality an edge create must honor, resolved from the graph def.\n * Also the input to {@link edgeWriteNeedsConstraintFence}, so \"does this create\n * probe anything\" and \"what does it probe\" are read from one place.\n *\n * A kind this graph does not define answers `many`. Choosing the fence must not\n * become the thing that REPORTS an unknown kind: the write path raises\n * `KindNotFoundError` from inside the hooked transaction, where a caller's\n * `onError` hook observes it, and this runs before that transaction opens.\n */\nfunction edgeCardinality<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n): Cardinality {\n  if (!hasOwnKey(ctx.graph.edges, kind)) return \"many\";\n  return getEdgeRegistration(ctx.graph, kind).cardinality ?? \"many\";\n}\n\n/**\n * The convergence key a `getOrCreateByEndpoints` create leg must find ABSENT\n * inside its own fenced transaction before it inserts.\n *\n * `getOrCreateByEndpoints` promises at most one edge per match key, and no\n * database key backs that promise — the edges table is unique on\n * `(graph_id, id)` only, and the match key can include `matchOn` prop values.\n * The only way the promise survives two concurrent callers is for the lookup\n * that decides \"create\" and the INSERT it authorizes to happen under one\n * per-graph mutual exclusion, so the create leg re-runs the lookup here, inside\n * the fence, and returns the incumbent rather than inserting a duplicate.\n */\ntype EdgeConvergenceGuard = Readonly<{\n  matchOn: readonly string[];\n  props: Record<string, unknown>;\n}>;\n\ntype EdgeCreateInternalResult =\n  | Readonly<{ outcome: \"created\"; edge: Edge | undefined }>\n  | Readonly<{ outcome: \"found\"; edge: Edge; row: BackendEdgeRow }>;\n\nfunction createdEdgeResult(edge: Edge | undefined): EdgeCreateInternalResult {\n  return { outcome: \"created\", edge };\n}\n\nfunction foundEdgeResult(row: BackendEdgeRow): EdgeCreateInternalResult {\n  return { outcome: \"found\", edge: rowToEdge(row), row };\n}\n\nfunction edgeCreateDidWrite(result: EdgeCreateInternalResult): boolean {\n  return result.outcome === \"created\";\n}\n\n/** A dispatcher-selected edge no longer carries the requested match key. */\nclass EdgeMatchKeyMoved extends Error {\n  constructor(kind: string, id: string) {\n    super(\n      `The ${kind} edge \"${id}\" no longer has the requested match key; ` +\n        \"re-resolving it. This is internal and is never returned to a caller.\",\n    );\n    this.name = \"EdgeMatchKeyMoved\";\n  }\n}\n\n/**\n * Reads the transaction target's candidate rows. Both portable convergence\n * paths use this one lookup so they keep identical live-over-tombstone\n * selection.\n */\nasync function findConvergenceMatch(\n  target: Pick<GraphReadBackend, \"findEdgesByKind\">,\n  graphId: string,\n  kind: string,\n  input: Pick<CreateEdgeInput, \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\">,\n  convergeOn: EdgeConvergenceGuard,\n): Promise<BackendEdgeRow | undefined> {\n  const candidateRows = await target.findEdgesByKind({\n    graphId,\n    kind,\n    fromKind: input.fromKind,\n    fromId: input.fromId,\n    toKind: input.toKind,\n    toId: input.toId,\n    excludeDeleted: false,\n    temporalMode: \"includeTombstones\",\n  });\n  const { liveRow, deletedRow } = findMatchingEdge(\n    candidateRows,\n    convergeOn.matchOn,\n    convergeOn.props,\n  );\n  const matchedRow = liveRow ?? deletedRow;\n  return matchedRow;\n}\n\n/**\n * A durable direct create with the incumbent's explicit id is intentionally\n * omitted by the identity upsert's `DO UPDATE ... WHERE` clause. That keeps a\n * same-id incumbent distinguishable from a newly inserted row, but the\n * resulting empty RETURNING set is otherwise indistinguishable from a failed\n * endpoint predicate. Re-read the id only in that refusal case and preserve\n * the public durable-identity conflict contract (including tombstones).\n */\nasync function durableIdentityIdConflict(\n  target: Pick<GraphReadBackend, \"getEdge\">,\n  graphId: string,\n  id: string,\n  identity: Readonly<{ name: string; key: string }>,\n  kind: string,\n): Promise<EdgeMatchIdentityConflictError | undefined> {\n  const row = await target.getEdge(graphId, id);\n  if (\n    row?.kind === kind &&\n    row.match_identity_name === identity.name &&\n    row.match_identity_key === identity.key\n  ) {\n    return new EdgeMatchIdentityConflictError({\n      attempted: [{ id, identityName: identity.name, kind }],\n    });\n  }\n  return undefined;\n}\n\n/**\n * Executes an edge create operation.\n */\nasync function executeEdgeCreateInternal<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: CreateEdgeInput,\n  backend: GraphBackend | TransactionBackend,\n  options?: Readonly<{\n    returnRow?: boolean;\n    convergeOn?: EdgeConvergenceGuard;\n    /** Batch callers deliberately skip per-item operation hooks. */\n    skipHooks?: boolean;\n  }>,\n): Promise<EdgeCreateInternalResult> {\n  const kind = input.kind;\n  const id = input.id ?? generateId();\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  // Refuse on the caller-visible backend before a write plan can replace it\n  // with a transaction target whose capability declaration came from the\n  // underlying adapter. A derived backend is allowed to narrow capabilities;\n  // opening its delegated transaction must not silently widen them again.\n  assertEdgeMatchIdentityBackendSupport(\n    registration.matchIdentity,\n    backend.capabilities,\n    kind,\n  );\n  const opContext = ctx.createOperationContext(\"create\", \"edge\", kind, id);\n  const shouldReturnRow = options?.returnRow ?? true;\n  const convergeOn = options?.convergeOn;\n  const durableConvergence =\n    convergeOn !== undefined && registration.matchIdentity !== undefined;\n  const autocommitBackend =\n    isBundledRootAutocommitEligible(backend) ? backend : undefined;\n  const candidate =\n    hasOwnKey(ctx.graph.edges, kind) ?\n      ({\n        backend,\n        schemaVersion: ctx.schemaVersion,\n        historyEnabled: ctx.historyEnabled,\n        revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n        kindRegistered: true,\n        convergesDynamically: convergeOn !== undefined && !durableConvergence,\n        cardinality: edgeCardinality(ctx, kind),\n      } as const)\n    : undefined;\n  const schemaFenceInFirstWrite =\n    candidate !== undefined &&\n    canFuseSchemaFenceInFirstWrite({ kind: \"edge\", candidate });\n  const autocommitSingleStatement =\n    autocommitBackend !== undefined &&\n    candidate !== undefined &&\n    isAutocommitSingleStatementWrite({ kind: \"edge\", candidate });\n  const plan = edgeWritePlan(\n    convergeOn === undefined || durableConvergence ?\n      edgeWriteNeedsConstraintFence(edgeCardinality(ctx, kind))\n    : \"edgeMatchKeyConvergence\",\n  );\n\n  const rowWork = async (\n    session: EdgeWriteSession,\n    target: WriteTarget,\n    _overlaidSession: OverlaidSessionMint<\"edge\">,\n    lock: GraphWriteLock,\n    transactionMode: WriteTransactionMode,\n  ): Promise<EdgeCreateInternalResult> => {\n    // See node create's matching receiver check: a custom transaction\n    // wrapper may replace the marked outer backend with an unmarked target.\n    // Fall back to the ordinary fence before any row work in that case.\n    const targetBackend = unfencedTarget(target);\n    const fuseSchemaFenceInFirstWrite =\n      schemaFenceInFirstWrite &&\n      isSchemaFencedInsertEligible(targetBackend) &&\n      !hasLeasedSchemaFence(ctx, targetBackend);\n    if (schemaFenceInFirstWrite && !fuseSchemaFenceInFirstWrite) {\n      await lockSchemaVersionForStoreWrite(ctx, targetBackend);\n    }\n    const diagnoseFusedCreateNoRow = async (\n      validateCardinality: boolean,\n    ): Promise<EdgeCreatePrepared> => {\n      if (fuseSchemaFenceInFirstWrite) {\n        await diagnoseFusedSchemaFenceNoRow(ctx, targetBackend);\n        const directInteractiveAutocommit =\n          autocommitSingleStatement &&\n          transactionMode === \"none\" &&\n          targetBackend.capabilities.execution.interactiveTransactions;\n        if (directInteractiveAutocommit) {\n          throw new AutocommitWriteRequiresTransaction();\n        }\n        if (transactionMode !== \"none\") {\n          // Transaction-backed fallback probes need the portable schema fence;\n          // the transaction already supplies atomicity.\n          await lockSchemaVersionForStoreWrite(ctx, targetBackend);\n        }\n        const prepared = await validateAndPrepareEdgeCreate(\n          ctx,\n          input,\n          id,\n          target,\n          { validateEndpoints: true, validateCardinality },\n        );\n        if (transactionMode === \"none\") {\n          // A noninteractive root has no safe plain-write fallback. Probe\n          // endpoints first for the typed missing-endpoint error, then fail\n          // closed at the schema fence before any unfenced INSERT.\n          await lockSchemaVersionForStoreWrite(ctx, targetBackend);\n        }\n        return prepared;\n      }\n      return validateAndPrepareEdgeCreate(ctx, input, id, target, {\n        validateEndpoints: true,\n        validateCardinality,\n      });\n    };\n\n    const declaredCardinality = edgeCardinality(ctx, kind);\n    const usesGuardedCardinalityClaim =\n      declaredCardinality !== \"many\" &&\n      edgeCardinalityClaimMode(target, ctx.claimsVerdict()).kind === \"guarded\";\n    const usesFusedCardinalityInsert = usesGuardedCardinalityClaim;\n    // A constrained convergence has to see an incumbent match before it\n    // derives a cardinality refusal. Otherwise a stale root dispatcher turns a\n    // matching winner into an avoidable failed create attempt, rather than the\n    // promised `found` result. Guarded claims own their own refusal at the row\n    // write; every other constrained create validates after the convergence\n    // lookup has ruled out an incumbent match.\n    const delaysCardinalityProbe =\n      convergeOn !== undefined && !usesGuardedCardinalityClaim;\n    // The convergence command (or its fallback) runs under this transaction's\n    // graph fence. Once it reports no match, endpoint existence is the only\n    // remaining pre-insert read, so let the existing endpoint-predicate INSERT\n    // remove those two RTTs even though this create leg carries a convergence\n    // guard.\n    const canFuseEndpointCheck =\n      declaredCardinality === \"many\" || usesGuardedCardinalityClaim;\n    const durableIdentityArbitratedCreate =\n      registration.matchIdentity !== undefined;\n    let prepared = await validateAndPrepareEdgeCreate(ctx, input, id, target, {\n      validateEndpoints: convergeOn === undefined && !canFuseEndpointCheck,\n      validateCardinality:\n        !durableIdentityArbitratedCreate &&\n        !usesGuardedCardinalityClaim &&\n        !delaysCardinalityProbe,\n    });\n\n    // A converging create owns both the match-key read and the endpoint\n    // predicate in one semantic backend command. A matched row becomes the\n    // explicit `found` result consumed by the hook/revision decision and the\n    // outer convergence loop. No caller re-derives that decision, and no\n    // expected found result travels through error hooks or a cache-backed root\n    // re-read.\n    //\n    // Keep the old fenced lookup as an explicit fallback for dynamic matching\n    // on a backend that does not implement this command yet. Durable identity\n    // cannot take that fallback: its write plan delegates arbitration to the\n    // database key and therefore owns no graph lock. A port that declares the\n    // durable capability but refuses its command must fail closed instead of\n    // racing a lookup with an uncoordinated insert.\n    // A durable identity is the database's arbiter for every create shape,\n    // including constrained kinds. Cardinality claims are a separate\n    // application-owned axis; the graph fence already held by this plan\n    // makes the probe and the durable command one serialized decision. Do not\n    // skip the identity command merely because this row also owes a claim:\n    // doing so lets a missing identity index turn a constrained create into a\n    // successful duplicate.\n    if (convergeOn !== undefined || durableIdentityArbitratedCreate) {\n      if (\n        durableIdentityArbitratedCreate &&\n        convergeOn !== undefined &&\n        declaredCardinality !== \"many\"\n      ) {\n        // A get-or-create that already has its endpoint/match winner must\n        // resolve that winner before the cardinality probe: cardinality is a\n        // create-only decision, and rejecting the found leg would regress\n        // resurrection/found semantics. The graph fence makes this lookup and\n        // the following durable command one serialized decision.\n        const matchedRow = await findConvergenceMatch(\n          target,\n          ctx.graphId,\n          kind,\n          input,\n          convergeOn,\n        );\n        if (matchedRow !== undefined) {\n          return foundEdgeResult(matchedRow);\n        }\n        prepared = await validateAndPrepareEdgeCreate(ctx, input, id, target, {\n          validateEndpoints: !canFuseEndpointCheck,\n          validateCardinality: true,\n        });\n      }\n      const work = edgeInsertWork(prepared);\n      const durableMatchIdentity = work.params.matchIdentity;\n      if (work.claim === undefined || durableMatchIdentity !== undefined) {\n        const command: EdgeConvergeCreateCommand = {\n          kind: \"edge.converge-create\",\n          plan: {\n            entity: \"edge\",\n            params: work.params,\n            ...(fuseSchemaFenceInFirstWrite ?\n              {\n                schemaFence: {\n                  graphId: ctx.graphId,\n                  expectedVersion: requireDefined(ctx.schemaVersion),\n                },\n              }\n            : {}),\n          },\n          match:\n            durableMatchIdentity === undefined ?\n              { kind: \"dynamic\", ...requireDefined(convergeOn) }\n            : { kind: \"durable\", identity: durableMatchIdentity },\n        };\n        const result =\n          lock.coordination === undefined && command.match.kind === \"dynamic\" ?\n            {\n              outcome: \"unsupported\" as const,\n              entity: \"edge\" as const,\n              dimensions: [\"convergence\"] as const,\n            }\n          : await withAlreadyExistsTranslation(\"edge\", () =>\n              executeAuthoritativeGraphCommand(\n                target.commands,\n                command,\n                lock.coordination ?? \"none\",\n              ),\n            );\n        if (result.outcome === \"created\") {\n          // Durable identity and cardinality are separate authorities. The\n          // converge command owns the former; retain the latter's claim row\n          // in the same transaction after the edge exists. If claiming\n          // refuses, the surrounding write frame rolls the command back.\n          if (durableMatchIdentity !== undefined && work.claim !== undefined) {\n            await claimEdgeCardinality(target, ctx.claimsVerdict(), work.claim);\n          }\n          return createdEdgeResult(rowToEdge(result.row));\n        }\n        if (result.outcome === \"found\") {\n          if (command.match.kind === \"dynamic\") {\n            assertEdgeMatchKey(\n              result.row,\n              command.match.matchOn,\n              command.match.props,\n            );\n          }\n          if (convergeOn === undefined) {\n            if (command.match.kind !== \"durable\") {\n              throw new CompilerInvariantError(\n                \"A direct durable edge create constructed a dynamic convergence command.\",\n                { kind, id },\n              );\n            }\n            throw new EdgeMatchIdentityConflictError({\n              attempted: [\n                {\n                  id,\n                  identityName: command.match.identity.name,\n                  kind,\n                },\n              ],\n            });\n          }\n          return foundEdgeResult(result.row);\n        }\n        if (result.outcome === \"unsupported\") {\n          if (command.match.kind === \"durable\") {\n            throw new ConfigurationError(\n              \"Backend declares durable edge match identity support but refuses the convergence command.\",\n              {\n                code: \"DURABLE_EDGE_MATCH_IDENTITY_COMMAND_UNSUPPORTED\",\n                capability: \"durableEdgeMatchIdentity\",\n                graphId: ctx.graphId,\n                edgeKind: kind,\n              },\n              {\n                suggestion:\n                  \"Implement edge.converge-create atomically or declare durableEdgeMatchIdentity as unsupported.\",\n              },\n            );\n          }\n          const matchedRow = await findConvergenceMatch(\n            target,\n            ctx.graphId,\n            kind,\n            input,\n            requireDefined(convergeOn),\n          );\n          if (matchedRow !== undefined) {\n            return foundEdgeResult(matchedRow);\n          }\n        }\n        if (\n          result.outcome === \"rejected\" &&\n          command.match.kind === \"durable\" &&\n          convergeOn === undefined\n        ) {\n          const identityConflict = await durableIdentityIdConflict(\n            target,\n            ctx.graphId,\n            id,\n            command.match.identity,\n            kind,\n          );\n          if (identityConflict !== undefined) {\n            // The same-id incumbent probe has already established the\n            // durable-arbiter refusal. Preserve the established endpoint\n            // validation ordering, but do not enter the fallback path: once\n            // endpoints pass, the typed conflict is already authoritative.\n            await diagnoseFusedSchemaFenceNoRow(ctx, targetBackend);\n            await validateAndPrepareEdgeCreate(ctx, input, id, target, {\n              validateEndpoints: true,\n              validateCardinality: false,\n            });\n            throw identityConflict;\n          }\n        }\n        // A rejected fused statement returned no row because an endpoint\n        // predicate or schema fence did not hold. This is deliberately not a\n        // create refusal by itself: the ordinary fused write/diagnostic path\n        // below owns the typed errors and permits a concurrently revived\n        // endpoint.\n      } else if (convergeOn !== undefined) {\n        // The current one-statement convergence builder does not own a\n        // cardinality claim. Do the portable lookup before its cardinality\n        // verdict instead of issuing a command known to return unsupported.\n        const matchedRow = await findConvergenceMatch(\n          target,\n          ctx.graphId,\n          kind,\n          input,\n          convergeOn,\n        );\n        if (matchedRow !== undefined) {\n          return foundEdgeResult(matchedRow);\n        }\n      }\n\n      if (delaysCardinalityProbe) {\n        // Re-establish endpoint liveness on the portable path. When the next\n        // row write can fuse that predicate, it remains in the INSERT instead.\n        prepared = await validateAndPrepareEdgeCreate(ctx, input, id, target, {\n          validateEndpoints: !canFuseEndpointCheck,\n          validateCardinality: true,\n        });\n      }\n    }\n\n    // A plain, generated-id `many` edge owes no cardinality claim and no\n    // sidecar. Its only pre-insert database reads were endpoint existence\n    // probes, so first-party backends can make their live-node predicates\n    // part of the INSERT ... SELECT itself. Do not infer an endpoint error\n    // from an empty RETURNING result: retry the ordinary ordered validation\n    // below, which preserves source-before-target typed refusals and handles\n    // a concurrent endpoint revival before we report anything.\n    if (canFuseEndpointCheck) {\n      const fusedWork = edgeInsertWork(prepared);\n      const fusedCommand: EdgeCreateCommand = {\n        kind: \"edge.create\",\n        plan: {\n          entity: \"edge\",\n          params: fusedWork.params,\n          ...(fuseSchemaFenceInFirstWrite ?\n            {\n              schemaFence: {\n                graphId: ctx.graphId,\n                expectedVersion: requireDefined(ctx.schemaVersion),\n              },\n            }\n          : {}),\n          ...(usesFusedCardinalityInsert && fusedWork.claim !== undefined ?\n            { cardinalityClaim: fusedWork.claim }\n          : {}),\n        },\n      };\n      const fusedResult = await withAlreadyExistsTranslation(\"edge\", () =>\n        session.createEdgeWithPlan(fusedCommand),\n      );\n      if (fusedResult.outcome === \"created\") {\n        if (fuseSchemaFenceInFirstWrite) {\n          memoizeLeasedSchemaFence(ctx, targetBackend);\n        }\n        return createdEdgeResult(rowToEdge(fusedResult.row));\n      }\n\n      // A fused refusal has no row, so the ordered fallback owns the full\n      // portable cardinality diagnostic regardless of claim mode.\n      prepared = await diagnoseFusedCreateNoRow(true);\n    }\n\n    // An edge create has no existence probe at all — its id is either\n    // caller-supplied or freshly generated — so the engine's refusal is the ONLY\n    // report that the id is taken. Translated here, that report is the same\n    // already-exists error a node create raises. The translation spans the fused\n    // unit — the claim and the row — which is inert for the claim half: a\n    // contended claim raises a `CardinalityError`, never a duplicate-key insert\n    // report.\n    //\n    // The claim is DECIDED here (a pure function of the cardinality this\n    // preparation resolved) and ISSUED by the session, before the row it gates:\n    // the probe above read a population no key fences, so the claim row is what\n    // stops a concurrent writer that read the same population from also\n    // committing, and a refusal there has written no edge row.\n    const work = edgeInsertWork(prepared);\n    const row = await withAlreadyExistsTranslation(\"edge\", async () => {\n      if (shouldReturnRow) return session.createEdge(work);\n      await session.createEdgeNoReturn(work);\n      return;\n    });\n\n    return createdEdgeResult(row === undefined ? undefined : rowToEdge(row));\n  };\n\n  if (autocommitSingleStatement) {\n    return runAutocommitSingleStatementWritePlan(\n      ctx,\n      opContext,\n      plan,\n      autocommitBackend,\n      rowWork,\n      {\n        schemaFenceInFirstWrite,\n        didWrite: edgeCreateDidWrite,\n      },\n    );\n  }\n  if (options?.skipHooks === true) {\n    return runWritePlan(ctx, plan, backend, rowWork, {\n      schemaFenceInFirstWrite,\n      didWrite: edgeCreateDidWrite,\n    });\n  }\n  return runHookedWritePlan(ctx, opContext, plan, backend, rowWork, {\n    schemaFenceInFirstWrite,\n    didWrite: edgeCreateDidWrite,\n  });\n}\n\n/**\n * Executes an edge create operation and returns the created edge.\n */\nexport async function executeEdgeCreate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: CreateEdgeInput,\n  backend: GraphBackend | TransactionBackend,\n): Promise<Edge> {\n  const result = await executeEdgeCreateInternal(ctx, input, backend, {\n    returnRow: true,\n  });\n  if (result.outcome !== \"created\") {\n    throw new CompilerInvariantError(\n      \"A direct edge create unexpectedly returned a convergence incumbent.\",\n      { kind: input.kind, id: input.id },\n    );\n  }\n  if (result.edge === undefined) {\n    throw new DatabaseOperationError(\n      \"Edge create failed: expected created edge row\",\n      { operation: \"insert\", entity: \"edge\" },\n    );\n  }\n  return result.edge;\n}\n\n/**\n * Executes an edge create operation without returning the created edge payload.\n */\nexport async function executeEdgeCreateNoReturn<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: CreateEdgeInput,\n  backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n  await executeEdgeCreateInternal(ctx, input, backend, { returnRow: false });\n}\n\n/**\n * Batch-primes an edge batch's endpoint validation cache with one\n * `getNodes` round trip per distinct (kind) referenced across every\n * from/to endpoint in the batch, instead of a `getNode` probe per edge.\n * Mirrors `primeBatchValidationCaches`'s node-existence priming.\n */\ntype BoundBatchNodeRead = (\n  kind: string,\n  ids: readonly string[],\n) => ReturnType<NonNullable<GraphBackend[\"getNodes\"]>>;\n\nfunction bindBatchNodeRead<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  backend: WriteTarget,\n): BoundBatchNodeRead | undefined {\n  const bound = bindExtraIfReachable(\n    backend,\n    ctx.batchPointRead.extras.getNodes,\n    BATCH_POINT_READ.id,\n  );\n  if (bound === undefined) return;\n  return (kind, ids) => bound.getNodes(ctx.graphId, kind, ids);\n}\n\nasync function primeEdgeBatchValidationCache<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: WriteTarget,\n  seedEndpointRow: (\n    graphId: string,\n    kind: string,\n    id: string,\n    row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n  ) => void,\n): Promise<void> {\n  const readNodes = bindBatchNodeRead(ctx, backend);\n  if (readNodes === undefined) return;\n\n  const idsByKind = collectEdgeEndpointIdsByKind(inputs);\n\n  for (const [kind, ids] of idsByKind) {\n    const orderedIds = [...ids];\n    const rows = await readNodes(kind, orderedIds);\n    const rowsById = new Map(rows.map((row) => [row.id, row]));\n    for (const id of orderedIds) {\n      seedEndpointRow(ctx.graphId, kind, id, rowsById.get(id));\n    }\n  }\n}\n\n/**\n * Shared batch preparation for edge creates: primes the endpoint\n * validation cache with one `getNodes` call per referenced kind, then\n * validates every input against the primed cache in order (so later\n * inputs see earlier ones' pending cardinality/uniqueness registrations).\n * Shared between the non-returning and RETURNING batch paths so both get\n * the same batched-prefetch treatment.\n */\nasync function prepareEdgeBatchCreates<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: WriteTarget,\n): Promise<{\n  preparedCreates: EdgeCreatePrepared[];\n  batchInsertWork: EdgeInsertWork[];\n}> {\n  const {\n    backend: validationBackend,\n    registerPendingEdgeForCardinality,\n    seedEndpointRow,\n  } = createEdgeBatchValidationBackend(backend);\n\n  await primeEdgeBatchValidationCache(ctx, inputs, backend, seedEndpointRow);\n\n  const preparedCreates: EdgeCreatePrepared[] = [];\n  for (const input of inputs) {\n    const id = input.id ?? generateId();\n    const prepared = await validateAndPrepareEdgeCreate(\n      ctx,\n      input,\n      id,\n      validationBackend,\n    );\n    preparedCreates.push(prepared);\n    registerPendingEdgeForCardinality(\n      prepared.insertParams,\n      prepared.cardinality,\n    );\n  }\n\n  // The batch's insert UNITS: each row's params paired with the claim it owes.\n  // The session issues ONE sorted claim statement for the group — after this\n  // preparation loop, never inside it, so no claim is taken for a row the loop\n  // may still refuse, and every batch takes its claim row locks in\n  // `compareClaimTargets` order rather than input order.\n  const batchInsertWork = preparedCreates.map((prepared) =>\n    edgeInsertWork(prepared),\n  );\n\n  return { preparedCreates, batchInsertWork };\n}\n\n/**\n * Prepares the closed input to the native edge batch program without issuing\n * reads. The SQL program owns endpoint, schema-fence, durable-identity and\n * cardinality enforcement at the authoritative write boundary. The only\n * client-side constraint decision is the closed input's own duplicate axes,\n * which need no database state and must refuse before dispatch.\n */\ntype AtomicEdgeBatchPreparation = Readonly<{\n  claims: readonly ClaimEdgeCardinalityParams[];\n  preparedCreates: readonly EdgeCreatePrepared[];\n}>;\n\nasync function prepareAtomicEdgeBatchCreates<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: WriteTarget,\n): Promise<AtomicEdgeBatchPreparation> {\n  const preparedCreates: EdgeCreatePrepared[] = [];\n  const claims: ClaimEdgeCardinalityParams[] = [];\n  const claimedTargets = new Set<string>();\n  for (const input of inputs) {\n    const prepared = await validateAndPrepareEdgeCreate(\n      ctx,\n      input,\n      input.id ?? generateId(),\n      backend,\n      { validateEndpoints: false, validateCardinality: false },\n    );\n    preparedCreates.push(prepared);\n    const claim = edgeInsertWork(prepared).claim;\n    if (claim === undefined) continue;\n    const target = edgeCardinalityClaimTarget(claim);\n    const targetKey = `${target.axis}\\u0000${target.key}`;\n    if (claimedTargets.has(targetKey)) {\n      throw edgeCardinalityClaimRefusal(claim);\n    }\n    claimedTargets.add(targetKey);\n    claims.push(claim);\n  }\n  return {\n    claims: claims.toSorted((left, right) =>\n      compareClaimTargets(\n        edgeCardinalityClaimTarget(left),\n        edgeCardinalityClaimTarget(right),\n      ),\n    ),\n    preparedCreates,\n  };\n}\n\n/**\n * Diagnoses an atomic-program refusal in public input order. The native SQL\n * deliberately turns a missing endpoint into a statement error so every\n * chunk rolls back; these reads recover the precise source-before-target\n * refusal only on that exceptional path.\n */\ntype EdgeEndpointInput = Readonly<{\n  kind: string;\n  fromKind: string;\n  fromId: string;\n  toKind: string;\n  toId: string;\n}>;\n\n/** Bounds concurrent scalar custom-backend reads on an exceptional path. */\nconst ATOMIC_EDGE_SCALAR_DIAGNOSTIC_WINDOW_SIZE = 32;\n\nfunction edgeEndpointRowKey(kind: string, id: string): string {\n  return encodeTupleKey([kind, id]);\n}\n\nfunction collectEdgeEndpointIdsByKind(\n  inputs: readonly Pick<\n    EdgeEndpointInput,\n    \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\"\n  >[],\n): ReadonlyMap<string, ReadonlySet<string>> {\n  const idsByKind = new Map<string, Set<string>>();\n  for (const input of inputs) {\n    for (const [kind, id] of [\n      [input.fromKind, input.fromId],\n      [input.toKind, input.toId],\n    ] as const) {\n      const ids = idsByKind.get(kind) ?? new Set<string>();\n      ids.add(id);\n      idsByKind.set(kind, ids);\n    }\n  }\n  return idsByKind;\n}\n\n/**\n * Reads every endpoint a bundled batch named in one set-oriented request per\n * kind. A custom backend without the batch-point-read extra gets\n * bounded-concurrency scalar windows that still cover the complete input:\n * refusal diagnosis must never trade semantic coverage for fan-out control.\n */\nasync function readAtomicEdgeBatchEndpointRows<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly EdgeEndpointInput[],\n  backend: WriteTarget,\n  readNodes: BoundBatchNodeRead | undefined,\n): Promise<\n  Readonly<{\n    rowsByEndpoint: ReadonlyMap<\n      string,\n      Awaited<ReturnType<GraphBackend[\"getNode\"]>>\n    >;\n  }>\n> {\n  const idsByKind = collectEdgeEndpointIdsByKind(inputs);\n\n  const rowsByEndpoint = new Map<\n    string,\n    Awaited<ReturnType<GraphBackend[\"getNode\"]>>\n  >();\n  await Promise.all(\n    [...idsByKind].map(async ([kind, ids]) => {\n      const orderedIds = [...ids];\n      if (readNodes !== undefined) {\n        const rows = await readNodes(kind, orderedIds);\n        const rowsById = new Map(rows.map((row) => [row.id, row]));\n        for (const id of orderedIds) {\n          rowsByEndpoint.set(edgeEndpointRowKey(kind, id), rowsById.get(id));\n        }\n        return;\n      }\n      const rows = await Promise.all(\n        orderedIds.map((id) => backend.getNode(ctx.graphId, kind, id)),\n      );\n      for (const [index, id] of orderedIds.entries()) {\n        rowsByEndpoint.set(edgeEndpointRowKey(kind, id), rows[index]);\n      }\n    }),\n  );\n  return { rowsByEndpoint };\n}\n\nfunction assertEndpointRowsLive(\n  inputs: readonly EdgeEndpointInput[],\n  rowsByEndpoint: ReadonlyMap<\n    string,\n    Awaited<ReturnType<GraphBackend[\"getNode\"]>>\n  >,\n): void {\n  for (const input of inputs) {\n    assertEndpointRowLive(\n      input.kind,\n      \"from\",\n      input.fromKind,\n      input.fromId,\n      rowsByEndpoint.get(edgeEndpointRowKey(input.fromKind, input.fromId)),\n    );\n    assertEndpointRowLive(\n      input.kind,\n      \"to\",\n      input.toKind,\n      input.toId,\n      rowsByEndpoint.get(edgeEndpointRowKey(input.toKind, input.toId)),\n    );\n  }\n}\n\nasync function assertAtomicEdgeBatchEndpoints<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly EdgeEndpointInput[],\n  backend: WriteTarget,\n): Promise<void> {\n  const readNodes = bindBatchNodeRead(ctx, backend);\n  const windows =\n    readNodes === undefined ?\n      chunk(inputs, ATOMIC_EDGE_SCALAR_DIAGNOSTIC_WINDOW_SIZE)\n    : [inputs];\n  for (const window of windows) {\n    const { rowsByEndpoint } = await readAtomicEdgeBatchEndpointRows(\n      ctx,\n      window,\n      backend,\n      readNodes,\n    );\n    assertEndpointRowsLive(window, rowsByEndpoint);\n  }\n}\n\n/** Owns the typed terminal when a rolled-back endpoint refusal went stale. */\nasync function diagnoseAtomicEdgeBatchEndpointRefusal<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly EdgeEndpointInput[],\n  backend: WriteTarget,\n  cause: unknown,\n): Promise<never> {\n  await assertAtomicEdgeBatchEndpoints(ctx, inputs, backend);\n  throw new DatabaseOperationError(\n    \"Atomic edge batch refused endpoint liveness, but no current missing \" +\n      \"endpoint could be diagnosed. Endpoint state may have changed after \" +\n      \"the atomic program rolled back.\",\n    { operation: \"insert\", entity: \"edge\" },\n    { cause },\n  );\n}\n\nasync function assertAtomicEdgeBatchCardinality<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: WriteTarget,\n): Promise<void> {\n  const constraintContext: ConstraintContext = {\n    graphId: ctx.graphId,\n    registry: ctx.registry,\n    backend,\n  };\n  for (const window of chunk(\n    inputs,\n    ATOMIC_EDGE_SCALAR_DIAGNOSTIC_WINDOW_SIZE,\n  )) {\n    const errors = await Promise.all(\n      window.map(async (input) => {\n        try {\n          await checkCardinalityConstraint(\n            constraintContext,\n            input.kind,\n            edgeCardinality(ctx, input.kind),\n            input.fromKind,\n            input.fromId,\n            input.toKind,\n            input.toId,\n            input.validTo,\n          );\n          return;\n        } catch (error) {\n          return error;\n        }\n      }),\n    );\n    for (const error of errors) {\n      if (error !== undefined) throw error;\n    }\n  }\n}\n\nasync function runAtomicEdgeBatchProgram<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  preparation: AtomicEdgeBatchPreparation,\n  backend: GraphBackend | TransactionBackend,\n  atomicExecutor: AtomicEdgeBatchExecutor,\n  resultMode: \"count\",\n): Promise<number>;\nasync function runAtomicEdgeBatchProgram<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  preparation: AtomicEdgeBatchPreparation,\n  backend: GraphBackend | TransactionBackend,\n  atomicExecutor: AtomicEdgeBatchExecutor,\n  resultMode: \"rows\",\n): Promise<readonly BackendEdgeRow[]>;\n/** Owns native refusal diagnosis and result completeness for both batch APIs. */\nasync function runAtomicEdgeBatchProgram<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  preparation: AtomicEdgeBatchPreparation,\n  backend: GraphBackend | TransactionBackend,\n  atomicExecutor: AtomicEdgeBatchExecutor,\n  resultMode: \"count\" | \"rows\",\n): Promise<number | readonly BackendEdgeRow[]> {\n  const params = preparation.preparedCreates.map(\n    (prepared) => prepared.insertParams,\n  );\n  const schemaFence = {\n    graphId: ctx.graphId,\n    expectedVersion: requireDefined(ctx.schemaVersion),\n  };\n  const result = await withAlreadyExistsTranslation(\"edge\", async () => {\n    try {\n      if (resultMode === \"count\") {\n        return await atomicExecutor({\n          claims: preparation.claims,\n          params,\n          resultMode,\n          schemaFence,\n        });\n      }\n      return await atomicExecutor({\n        claims: preparation.claims,\n        params,\n        resultMode,\n        schemaFence,\n      });\n    } catch (error) {\n      if (error instanceof AtomicEdgeBatchEndpointRefusalError) {\n        await diagnoseAtomicEdgeBatchEndpointRefusal(\n          ctx,\n          inputs,\n          backend,\n          error.cause,\n        );\n      }\n      if (error instanceof AtomicEdgeBatchCardinalityRefusalError) {\n        await assertAtomicEdgeBatchCardinality(ctx, inputs, backend);\n        throw new DatabaseOperationError(\n          \"Atomic edge batch refused a cardinality claim, but no current \" +\n            \"competing edge could be diagnosed.\",\n          {\n            operation: \"insert\",\n            entity: \"edge\",\n          },\n          { cause: error.cause },\n        );\n      }\n      throw error;\n    }\n  });\n  const insertedCount = typeof result === \"number\" ? result : result.length;\n  if (insertedCount === 0) {\n    await diagnoseFusedSchemaFenceNoRow(ctx, backend);\n    await assertAtomicEdgeBatchEndpoints(ctx, inputs, backend);\n  }\n  if (insertedCount !== inputs.length) {\n    throw new DatabaseOperationError(\n      `Atomic edge batch insert returned ${insertedCount} rows, expected ${inputs.length}`,\n      {\n        operation: \"insert\",\n        entity: \"edge\",\n        attempted: params.map((item) => ({ kind: item.kind, id: item.id })),\n      },\n    );\n  }\n  memoizeLeasedSchemaFence(ctx, backend);\n  return result;\n}\n\n/** Identity-conflicted rows are omitted by the authoritative batch RETURNING. */\nfunction assertDurableBatchRows(\n  work: readonly EdgeInsertWork[],\n  rows: readonly BackendEdgeRow[],\n): void {\n  const outcomes = classifyDurableEdgeBatchOutcomes(\n    work.map((item) => item.params),\n    rows,\n  );\n  const attempted = work.flatMap((item, index) => {\n    if (requireDefined(outcomes[index]) === \"conflict\") {\n      return [\n        {\n          id: item.params.id,\n          identityName: requireDefined(item.params.matchIdentity).name,\n          kind: item.params.kind,\n        },\n      ];\n    }\n    return [];\n  });\n  if (attempted.length > 0) {\n    throw new EdgeMatchIdentityConflictError({ attempted });\n  }\n}\n\n/**\n * Executes batched edge creates without returning inserted edge payloads.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateNoReturnBatch<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n  if (inputs.length === 0) {\n    return;\n  }\n\n  const atomicExecutor = resolveAtomicEdgeBatchExecutor({\n    backend,\n    graph: ctx.graph,\n    inputs,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n  });\n  if (atomicExecutor !== undefined) {\n    const preparation = await prepareAtomicEdgeBatchCreates(\n      ctx,\n      inputs,\n      backend,\n    );\n    await runAtomicEdgeBatchProgram(\n      ctx,\n      inputs,\n      preparation,\n      backend,\n      atomicExecutor,\n      \"count\",\n    );\n    return;\n  }\n\n  await runWritePlan(\n    ctx,\n    edgeWritePlan(batchFencesConstraintProbe(ctx, inputs)),\n    backend,\n    async (session, target) => {\n      const { batchInsertWork } = await prepareEdgeBatchCreates(\n        ctx,\n        inputs,\n        target,\n      );\n      const durableWork = batchInsertWork.filter(\n        (item) => item.params.matchIdentity !== undefined,\n      );\n      if (durableWork.length > 0) {\n        if (\n          durableWork.length !== batchInsertWork.length ||\n          target.insertEdgesDurableBatchReturning === undefined\n        ) {\n          for (const input of inputs) {\n            await executeEdgeCreateInternal(\n              ctx,\n              input,\n              nestedManagedWriteTarget(target),\n              {\n                returnRow: false,\n                skipHooks: true,\n              },\n            );\n          }\n          return;\n        }\n        const rows = await withAlreadyExistsTranslation(\"edge\", () =>\n          requireDefined(session.createEdgesDurable)(batchInsertWork),\n        );\n        assertDurableBatchRows(batchInsertWork, rows);\n        return;\n      }\n      await withAlreadyExistsTranslation(\"edge\", () =>\n        session.createEdgesNoReturn(batchInsertWork),\n      );\n    },\n  );\n}\n\n/**\n * Executes batched edge creates and returns the inserted edge payloads.\n *\n * Uses batch validation caching and a single multi-row INSERT with RETURNING\n * when the backend supports it. Falls back to sequential inserts otherwise.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateBatch<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n  backend: GraphBackend | TransactionBackend,\n): Promise<readonly Edge[]> {\n  if (inputs.length === 0) {\n    return [];\n  }\n\n  const atomicExecutor = resolveAtomicEdgeBatchExecutor({\n    backend,\n    graph: ctx.graph,\n    inputs,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n  });\n  if (atomicExecutor !== undefined) {\n    const preparation = await prepareAtomicEdgeBatchCreates(\n      ctx,\n      inputs,\n      backend,\n    );\n    const rows = await runAtomicEdgeBatchProgram(\n      ctx,\n      inputs,\n      preparation,\n      backend,\n      atomicExecutor,\n      \"rows\",\n    );\n    return rows.map((row) => rowToEdge(row));\n  }\n\n  return runWritePlan(\n    ctx,\n    edgeWritePlan(batchFencesConstraintProbe(ctx, inputs)),\n    backend,\n    async (session, target) => {\n      const { batchInsertWork } = await prepareEdgeBatchCreates(\n        ctx,\n        inputs,\n        target,\n      );\n\n      const durableWork = batchInsertWork.filter(\n        (item) => item.params.matchIdentity !== undefined,\n      );\n      if (durableWork.length > 0) {\n        if (\n          durableWork.length !== batchInsertWork.length ||\n          target.insertEdgesDurableBatchReturning === undefined\n        ) {\n          const fallbackRows: Edge[] = [];\n          for (const input of inputs) {\n            const result = await executeEdgeCreateInternal(\n              ctx,\n              input,\n              nestedManagedWriteTarget(target),\n              { returnRow: true, skipHooks: true },\n            );\n            if (result.outcome !== \"created\") {\n              throw new CompilerInvariantError(\n                \"A bulk direct edge create unexpectedly returned a convergence incumbent.\",\n                { kind: input.kind, id: input.id },\n              );\n            }\n            if (result.edge === undefined) {\n              throw new DatabaseOperationError(\n                \"Edge create failed: expected created edge row\",\n                { operation: \"insert\", entity: \"edge\" },\n              );\n            }\n            fallbackRows.push(result.edge);\n          }\n          return fallbackRows;\n        }\n        const rows = await withAlreadyExistsTranslation(\"edge\", () =>\n          requireDefined(session.createEdgesDurable)(batchInsertWork),\n        );\n        assertDurableBatchRows(batchInsertWork, rows);\n        return rows.map((row) => rowToEdge(row));\n      }\n\n      const rows = await withAlreadyExistsTranslation(\"edge\", () =>\n        session.createEdges(batchInsertWork),\n      );\n\n      return rows.map((row) => rowToEdge(row));\n    },\n  );\n}\n\n/**\n * A batch fences when ANY item in it does: the batch shares one transaction, so\n * one constrained item makes the whole transaction a constrained write. A batch\n * of purely `many` edges still takes no lock.\n */\nfunction batchFencesConstraintProbe<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  inputs: readonly CreateEdgeInput[],\n): ConstraintFenceReason | undefined {\n  for (const input of inputs) {\n    const reason = edgeWriteNeedsConstraintFence(\n      edgeCardinality(ctx, input.kind),\n    );\n    if (reason !== undefined) return reason;\n  }\n  return undefined;\n}\n\n/**\n * The exact props an edge update would persist: the caller's partial input\n * merged over the current props and run through the edge kind's Zod schema.\n * Operates on PARSED props so the write path and the coalesce dirty-check\n * (which may compare against a batch-local running value, never a row) share\n * one validation. Endpoints are the edge's identity and are not part of an\n * upsert-by-id update, so only props are involved.\n */\nfunction computeEdgeUpdate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n  id: string,\n  existingProps: Record<string, unknown>,\n  inputProps: Partial<Record<string, unknown>>,\n): Record<string, unknown> {\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  const validatedProps = validateEdgeProps(\n    registration.type.schema,\n    { ...existingProps, ...inputProps },\n    { kind, operation: \"update\", id },\n  );\n  const identityRefusal = edgeMatchIdentityUpdateRefusal({\n    identity: registration.matchIdentity,\n    kind,\n    id,\n    beforeProps: existingProps,\n    afterProps: validatedProps,\n  });\n  if (identityRefusal !== undefined) throw identityRefusal;\n  return validatedProps;\n}\n\n/**\n * Row-based wrapper over {@link computeEdgeUpdate} for the write path.\n */\nfunction resolveEdgeUpdateProps<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  existing: Pick<EdgeRow, \"kind\" | \"id\" | \"props\">,\n  inputProps: Partial<Record<string, unknown>>,\n): Readonly<{\n  existingProps: Record<string, unknown>;\n  validatedProps: Record<string, unknown>;\n}> {\n  const existingProps = rowPropsToObject(existing.props);\n  const validatedProps = computeEdgeUpdate(\n    ctx,\n    existing.kind,\n    existing.id,\n    existingProps,\n    inputProps,\n  );\n  return { existingProps, validatedProps };\n}\n\n/**\n * The edge coalesce dirty-check: returns the props an upsert would persist and\n * whether they equal `existingProps`. `existingProps` is the PARSED current\n * props — the edge's, or the batch-local running value for a repeated id.\n */\nexport function edgeUpsertDirtyCheck<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n  id: string,\n  existingProps: Record<string, unknown>,\n  inputProps: Record<string, unknown>,\n): UpsertDirtyCheck {\n  const validatedProps = computeEdgeUpdate(\n    ctx,\n    kind,\n    id,\n    existingProps,\n    inputProps,\n  );\n  return {\n    validatedProps,\n    unchanged: canonicalEqual(validatedProps, existingProps),\n  };\n}\n\n/**\n * Shared edge-update body: re-reads the edge inside the transaction, merges\n * and validates props, and writes. A plain update requires a live edge; a\n * resurrecting upsert (`clearDeleted`) may target a tombstoned one.\n */\nasync function performEdgeUpdate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: UpsertUpdateEdgeInput,\n  session: EdgeWriteSession,\n  target: WriteTarget,\n  options?: Readonly<{\n    clearDeleted?: boolean;\n    matchOn?: readonly string[];\n    matchProps?: Record<string, unknown>;\n  }>,\n  resolvedExisting?: BackendEdgeRow,\n): Promise<Edge> {\n  const id = input.id;\n\n  assertValidityEndMutation(input, {\n    entityType: \"edge\",\n    kind: input.identity.kind,\n    id,\n  });\n\n  const existing = resolvedExisting ?? (await target.getEdge(ctx.graphId, id));\n  if (!existing || (!options?.clearDeleted && existing.deleted_at)) {\n    throw new EdgeNotFoundError(input.identity.kind, id);\n  }\n  assertEdgeIdentityMatches(\n    id,\n    input.identity,\n    edgeIdentityFromRow(existing),\n    \"update\",\n  );\n  if (options?.matchOn !== undefined && options.matchProps !== undefined) {\n    assertEdgeMatchKey(existing, options.matchOn, options.matchProps);\n  }\n\n  const { validatedProps } = resolveEdgeUpdateProps(ctx, existing, input.props);\n\n  const statedValidFrom = validateStatedValidityLowerBound(\n    input.validFrom,\n    \"validFrom\",\n  );\n  const preservesLiveLowerBound =\n    options?.clearDeleted !== true &&\n    preservesImmutableLowerBound(input.onImmutableLowerBound);\n  const appliedValidFrom =\n    preservesLiveLowerBound ? undefined : statedValidFrom;\n  const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n  const effectiveValidTo =\n    options?.clearDeleted === true && appliedValidFrom !== undefined ?\n      validTo\n    : validityEndAfterMutation(\n        input.clearValidTo === true ? { clearValidTo: true }\n        : validTo === undefined ? {}\n        : { validTo },\n        existing.valid_to,\n      );\n  const cardinality = edgeCardinality(ctx, input.identity.kind);\n  const reentersLivePopulation =\n    options?.clearDeleted === true && existing.deleted_at !== undefined;\n  // `let` earns its place: the claim is decided inside the re-entry branch and\n  // consumed by the work record built after it, and there is no expression form\n  // that keeps the branch's two other statements (probe, then decide) together.\n  let reentryClaim: ClaimEdgeCardinalityParams | undefined;\n  const reentersActivePopulation =\n    cardinality === \"oneActive\" &&\n    effectiveValidTo === undefined &&\n    (existing.deleted_at !== undefined || existing.valid_to !== undefined);\n  if (reentersLivePopulation || reentersActivePopulation) {\n    await checkCardinalityConstraint(\n      {\n        graphId: ctx.graphId,\n        registry: ctx.registry,\n        backend: target,\n      },\n      input.identity.kind,\n      cardinality,\n      existing.from_kind,\n      existing.from_id,\n      existing.to_kind,\n      existing.to_id,\n      effectiveValidTo,\n    );\n    // Re-entry re-admits this edge to the population its cardinality\n    // constrains, so it claims the axis exactly as a create does — BEFORE the\n    // update that re-admits it, because the probe above read a population no key\n    // fences. Both legs claim: a resurrect (`clearDeleted`) and a reopened\n    // `oneActive` window (#469) put the same row back into the same counted\n    // population, and a fence that covered only the first would leave the second\n    // unfenced. Decided here, ISSUED by the step that owns the row write, so the\n    // pair cannot be separated.\n    reentryClaim = edgeCardinalityClaim(cardinality, {\n      graphId: ctx.graphId,\n      id,\n      kind: input.identity.kind,\n      fromKind: existing.from_kind,\n      fromId: existing.from_id,\n      toKind: existing.to_kind,\n      toId: existing.to_id,\n      ...(effectiveValidTo === undefined ? {} : { validTo: effectiveValidTo }),\n    });\n  }\n  // The row's stored lower bound is the effective one on EVERY edge update,\n  // in-place or resurrecting: an edge RETAINS `valid_from` unless the\n  // resurrection names a new one (see UpdateEdgeParams), so a lone `validTo`\n  // is always measured against the bound the row already carries. This is the\n  // ordering hole the edge write path used to have; nodes have always been\n  // checked here, and the two now agree.\n  //\n  // Resurrecting an edge straight into the ENDED state stays available — that is\n  // what `getOrCreateByEndpoints` does to an ended employment, counting it\n  // against cardinality as inactive — but the end it names must not precede the\n  // window it is ending. Reviving a row into a window that closed before the row\n  // began means restating the start, so pass `validFrom` alongside `validTo`.\n  //\n  // A stated `validFrom` is STORED only on the resurrecting leg, which\n  // `buildUpdateEdge` selects on `clearDeleted` ALONE — its UPDATE carries no\n  // `deleted_at` predicate, so the leg is taken (and the bound applied) even\n  // where a concurrent writer revived the row between the caller's probe and\n  // this re-read. A plain in-place update stores no lower bound at all, so one\n  // that differs from the bound the row holds is refused rather than accepted\n  // and dropped.\n  const windowVerdict = assertWritableValidityWindow(\n    `edge \"${id}\"`,\n    appliedValidFrom,\n    {\n      effectiveValidFrom: existing.valid_from,\n      appliesStatedValidFrom: options?.clearDeleted === true,\n      // Unlike the node side, an edge RETAINS `valid_from` through a\n      // resurrection that does not name a new one, so the effective bound is the\n      // row's stored one on BOTH legs and there is no carve-out to make.\n      effectiveBoundIsStored: true,\n    },\n    validTo,\n  );\n\n  // The write's FENCES: everything the statement asserts because a verdict\n  // above READ it, separated from the props this update intends to change.\n  //\n  // `kind` makes the UPDATE self-verifying: the re-read above computed the\n  // merged props and the effective window, and the same predicate that\n  // validated its identity is carried into the statement, so the row this\n  // writes is provably the row that was judged.\n  //\n  // Every component `input.identity` ASSERTS is carried, not just kind: an\n  // upsert that resolved this edge by its endpoints asserted them, and a\n  // same-kind recreate with different endpoints would satisfy a kind-only\n  // predicate. The expectation object is the single source for both the\n  // pre-write check and the statement, so the two cannot assert different\n  // things.\n  //\n  // The lower bound is carried on exactly the same terms: present only when\n  // the verdict consulted it, because a component the caller made no claim\n  // about must not become a predicate that refuses legitimate writes. The\n  // window END follows the same rule: only a reopen that judged the row's\n  // stored `valid_to` asserts it.\n  const fences: EdgeUpdateFences = {\n    validityLowerBound: windowVerdict.storedLowerBoundFence,\n    validityUpperBound:\n      reentersActivePopulation && existing.valid_to !== undefined ?\n        { expectedValidTo: existing.valid_to }\n      : {},\n    edgeIdentity: input.identity,\n  };\n\n  // `appliedValidFrom` reaches the backend only through a resurrecting write\n  // (see UpdateEdgeParams): a live edge's lower bound is history and stays put.\n  const work: EdgeUpdateWork = {\n    id,\n    props: validatedProps,\n    ...(appliedValidFrom !== undefined && { validFrom: appliedValidFrom }),\n    // `validTo` and `clearValidTo` are mutually exclusive in the params, so the\n    // work states exactly one of them.\n    ...(input.clearValidTo === true ? { clearValidTo: true as const }\n    : validTo === undefined ? {}\n    : { validTo }),\n    ...(options?.clearDeleted === true && { clearDeleted: true }),\n    ...(reentryClaim === undefined ? {} : { claim: reentryClaim }),\n  };\n\n  const row = await withUnmatchedEdgeUpdateRefusal(\n    ctx.graphId,\n    target,\n    id,\n    input.identity,\n    // \"Did this write assert any window state?\" is one predicate with one\n    // owner, consulted here and by the fence appliers that carry it, rather\n    // than re-derived from the params the diagnosis never sees.\n    assertsStoredWindowState(fences),\n    () => session.reviseEdge(work, fences),\n  );\n\n  return rowToEdge(row);\n}\n\n/**\n * How many probe-and-write rounds an edge update gets before it stops trying to\n * converge. See {@link NODE_UPDATE_ATTEMPTS}' counterpart reasoning: one retry\n * absorbs a single concurrent recreate, and the bound stops a peer that keeps\n * replacing the row from livelocking this writer.\n */\nconst EDGE_UPDATE_ATTEMPTS = 2;\n\n/**\n * Runs {@link performEdgeUpdate} and CONVERGES on the row that is actually\n * there when the asserted validity bound stopped matching.\n *\n * The retry re-reads, re-merges the caller's partial props over the CURRENT\n * props, and re-judges the window against the CURRENT bound — so a stated\n * window that no longer fits is refused with the same typed `ValidationError`\n * the first attempt would have raised, and one that still fits is applied to\n * the row that really exists. Refusing instead would make the fence a behavior\n * regression for every writer that loses a benign race.\n *\n * Only the bound-mismatch case retries. A vanished row, a tombstoned row, and\n * an id that now resolves to a different edge are all terminal verdicts that\n * {@link withUnmatchedEdgeUpdateRefusal} has already turned into the typed\n * errors this operation has always thrown.\n */\nasync function performEdgeUpdateConverging<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: UpsertUpdateEdgeInput,\n  session: EdgeWriteSession,\n  target: WriteTarget,\n  options?: Readonly<{\n    clearDeleted?: boolean;\n    matchOn?: readonly string[];\n    matchProps?: Record<string, unknown>;\n  }>,\n  resolvedExisting?: BackendEdgeRow,\n): Promise<Edge> {\n  for (let attempt = 1; attempt <= EDGE_UPDATE_ATTEMPTS; attempt += 1) {\n    try {\n      return await performEdgeUpdate(\n        ctx,\n        input,\n        session,\n        target,\n        options,\n        attempt === 1 ? resolvedExisting : undefined,\n      );\n    } catch (error) {\n      if (!(error instanceof EdgeUpdateTargetMoved)) throw error;\n      if (attempt === EDGE_UPDATE_ATTEMPTS) {\n        throw new DatabaseOperationError(\n          `Edge update for \"${input.id}\" could not be applied to a stable row after ${EDGE_UPDATE_ATTEMPTS} attempts: the row was replaced between each read and its write. A concurrent writer is replacing this edge faster than it can be read; serialize the writers, or retry.`,\n          { operation: \"update\", entity: \"edge\" },\n          { cause: error },\n        );\n      }\n    }\n  }\n  // Unreachable: the loop either returns or throws on its last attempt.\n  throw new EdgeNotFoundError(input.identity.kind, input.id);\n}\n\nfunction resolveAtomicEdgeUpdateExecutor<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  entries: readonly EdgeUpsertUpdateBatchEntry[],\n  backend: GraphBackend | TransactionBackend,\n): AtomicEdgeResolvedUpdateBatchExecutor | undefined {\n  const first = entries[0];\n  if (first === undefined) return;\n  const distinctIds = new Set(entries.map((entry) => entry.input.id));\n  if (\n    distinctIds.size !== entries.length ||\n    entries.some(\n      (entry) =>\n        entry.clearDeleted ||\n        entry.input.validFrom !== undefined ||\n        entry.input.validTo !== undefined ||\n        entry.input.clearValidTo === true,\n    )\n  ) {\n    return;\n  }\n  return resolveAtomicEdgeResolvedUpdateBatchExecutor({\n    backend,\n    graph: ctx.graph,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n    kind: first.input.identity.kind,\n    entryCount: entries.length,\n  });\n}\n\n/** Executes an edge update operation. */\nexport async function executeEdgeUpdate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: {\n    id: string;\n    identity: EdgeIdentityExpectation;\n    props: Partial<Record<string, unknown>>;\n    validTo?: string;\n    clearValidTo?: true;\n  },\n  backend: GraphBackend | TransactionBackend,\n): Promise<Edge> {\n  const id = input.id;\n\n  // Read outside execution: the hook context needs the edge kind, and an\n  // absent edge must not fire hooks or submit a write. Eligible plain updates\n  // bind this preimage to one guarded atomic program. The portable body\n  // re-reads inside its transaction, so a concurrent delete between this gate\n  // and the write lock is still handled correctly.\n  const gate = await backend.getEdge(ctx.graphId, id);\n  if (!gate || gate.deleted_at) {\n    throw new EdgeNotFoundError(input.identity.kind, id);\n  }\n  assertEdgeIdentityMatches(\n    id,\n    input.identity,\n    edgeIdentityFromRow(gate),\n    \"update\",\n  );\n\n  const opContext = ctx.createOperationContext(\"update\", \"edge\", gate.kind, id);\n\n  if (input.clearValidTo === true) {\n    assertClearValidToSupported(backend, \"edge\");\n  }\n  const atomicEntry = {\n    input,\n    clearDeleted: false,\n    existing: gate,\n  } satisfies EdgeUpsertUpdateBatchEntry;\n  const atomicExecutor = resolveAtomicEdgeUpdateExecutor(\n    ctx,\n    [atomicEntry],\n    backend,\n  );\n  if (atomicExecutor !== undefined) {\n    return runAtomicProgramWithHooks(\n      ctx,\n      opContext,\n      async () => {\n        const edges = await executeAtomicEdgeResolvedUpdates(\n          ctx,\n          [atomicEntry],\n          backend,\n          atomicExecutor,\n        );\n        return requireDefined(edges[0]);\n      },\n      writeResultAlwaysChanges,\n    );\n  }\n  return runHookedWritePlan(\n    ctx,\n    opContext,\n    // An in-place props update on a live edge re-derives no constraint verdict.\n    // Clearing an `oneActive` edge's end DOES: it re-admits the row to the\n    // counted active population.\n    edgeWritePlan(\n      (\n        input.clearValidTo === true &&\n          edgeCardinality(ctx, gate.kind) === \"oneActive\"\n      ) ?\n        edgeWriteNeedsConstraintFence(\"oneActive\")\n      : undefined,\n    ),\n    backend,\n    (session, target) =>\n      performEdgeUpdateConverging(ctx, input, session, target),\n    { didWrite: writeResultAlwaysChanges },\n  );\n}\n\ntype EdgeUpsertUpdateOutcome = Readonly<{\n  edge: Edge;\n  wrote: boolean;\n}>;\n\n/**\n * Executes the endpoint-aware edge upsert update and reports whether it wrote.\n *\n * The ordinary id-upsert callers need only the edge, while endpoint\n * get-or-create also owes callers an honest action (`found` when an identical\n * replay was coalesced, `updated` only when an UPDATE ran). Keeping the verdict\n * here makes the dirty-check read and the write it may elide share the same\n * transaction and graph-write fence.\n */\nasync function executeEdgeUpsertUpdateWithOutcome<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: UpsertUpdateEdgeInput,\n  backend: GraphBackend | TransactionBackend,\n  options?: Readonly<{\n    clearDeleted?: boolean;\n    coalesceUnchanged?: boolean;\n    coalesceCandidate?: BackendEdgeRow;\n    matchOn?: readonly string[];\n    matchProps?: Record<string, unknown>;\n  }>,\n): Promise<EdgeUpsertUpdateOutcome> {\n  if (input.clearValidTo === true) {\n    assertClearValidToSupported(backend, \"edge\");\n  }\n  return runWritePlan(\n    ctx,\n    // An in-place props update re-derives no constraint verdict: endpoints\n    // are immutable, so cardinality cannot change under it. A coalescing upsert\n    // converges on a match key no database key backs; a resurrect or a cleared\n    // end re-admits the row to the counted population its cardinality\n    // constrains.\n    edgeWritePlan(\n      options?.coalesceUnchanged === true ? \"edgeMatchKeyConvergence\"\n      : input.clearValidTo === true || options?.clearDeleted === true ?\n        edgeWriteNeedsConstraintFence(edgeCardinality(ctx, input.identity.kind))\n      : undefined,\n    ),\n    backend,\n    async (session, target) => {\n      if (options?.coalesceUnchanged === true && !options.clearDeleted) {\n        const existing =\n          options.matchOn !== undefined && options.matchProps !== undefined ?\n            await target.getEdge(ctx.graphId, input.id)\n          : (options.coalesceCandidate ??\n            (await target.getEdge(ctx.graphId, input.id)));\n        if (existing !== undefined && existing.deleted_at === undefined) {\n          assertEdgeIdentityMatches(\n            input.id,\n            input.identity,\n            edgeIdentityFromRow(existing),\n            \"update\",\n          );\n          if (\n            options.matchOn !== undefined &&\n            options.matchProps !== undefined\n          ) {\n            assertEdgeMatchKey(existing, options.matchOn, options.matchProps);\n          }\n          const runDirtyCheck = () =>\n            edgeUpsertDirtyCheck(\n              ctx,\n              existing.kind,\n              existing.id,\n              rowPropsToObject(existing.props),\n              input.props,\n            );\n          if (shouldCoalesceUpsert(existing, input, runDirtyCheck)) {\n            return { edge: rowToEdge(existing), wrote: false };\n          }\n        }\n      }\n\n      const edge = await performEdgeUpdateConverging(\n        ctx,\n        input,\n        session,\n        target,\n        options,\n      );\n      return { edge, wrote: true };\n    },\n    {\n      didWrite: (outcome) => outcome.wrote,\n    },\n  );\n}\n\n/**\n * Executes an edge update for upsert — bypasses the soft-delete check\n * and optionally clears `deleted_at`.\n */\nexport async function executeEdgeUpsertUpdate<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  input: UpsertUpdateEdgeInput,\n  backend: GraphBackend | TransactionBackend,\n  options?: Readonly<{\n    clearDeleted?: boolean;\n    matchOn?: readonly string[];\n    matchProps?: Record<string, unknown>;\n  }>,\n): Promise<Edge> {\n  const outcome = await executeEdgeUpsertUpdateWithOutcome(\n    ctx,\n    input,\n    backend,\n    options,\n  );\n  return outcome.edge;\n}\n\n/**\n * Executes an already-resolved set of edge upsert updates under one write plan.\n * The collection owns ordering and repeated-id resolution; this boundary keeps\n * the complete set under one graph fence and one write session.\n */\nexport async function executeEdgeResolvedMutationSet<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  creates: readonly CreateEdgeInput[],\n  updates: readonly EdgeUpsertUpdateBatchEntry[],\n  backend: GraphBackend | TransactionBackend,\n): Promise<\n  ResolvedMutationSetAttempt<\n    Readonly<{ created: readonly Edge[]; updated: readonly Edge[] }>\n  >\n> {\n  if (creates.length === 0 || updates.length === 0) {\n    return unsupportedResolvedMutationSet();\n  }\n  const firstUpdate = requireDefined(updates[0]);\n  const executor = resolveAtomicEdgeResolvedMutationSetExecutor({\n    backend,\n    graph: ctx.graph,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n    kind: firstUpdate.input.identity.kind,\n    creates,\n    updateCount: updates.length,\n  });\n  if (executor === undefined) return unsupportedResolvedMutationSet();\n  const ids = new Set([\n    ...creates.map((input) => requireDefined(input.id)),\n    ...updates.map((entry) => entry.input.id),\n  ]);\n  if (ids.size !== creates.length + updates.length) {\n    return unsupportedResolvedMutationSet();\n  }\n  if (\n    updates.some(\n      (entry) =>\n        entry.clearDeleted ||\n        entry.existing === undefined ||\n        entry.input.validFrom !== undefined ||\n        entry.input.validTo !== undefined ||\n        entry.input.clearValidTo === true,\n    )\n  ) {\n    return unsupportedResolvedMutationSet();\n  }\n\n  // The eligibility owner above excludes every edge kind that can owe a\n  // cardinality claim. Preparation normalizes that proven shape; a claim here\n  // is contradictory evidence between the classifier and claim planner, not a\n  // late unsupported verdict that may silently enter another execution path.\n  const preparation = await prepareAtomicEdgeBatchCreates(\n    ctx,\n    creates,\n    backend,\n  );\n  if (preparation.claims.length > 0) {\n    throw new CompilerInvariantError(\n      \"An eligible resolved edge mutation set produced unsupported cardinality claims.\",\n    );\n  }\n  const createParams = preparation.preparedCreates.map(\n    (prepared) => prepared.insertParams,\n  );\n  const resolvedUpdates = updates.map((entry) => {\n    const existing = requireDefined(entry.existing);\n    assertEdgeIdentityMatches(\n      entry.input.id,\n      entry.input.identity,\n      edgeIdentityFromRow(existing),\n      \"update\",\n    );\n    const { validatedProps } = resolveEdgeUpdateProps(\n      ctx,\n      existing,\n      entry.input.props,\n    );\n    return { existing, props: validatedProps };\n  });\n  const result = await withAlreadyExistsTranslation(\"edge\", async () => {\n    try {\n      return await executor({\n        kind: \"resolved-set\",\n        creates: createParams,\n        updates: resolvedUpdates,\n        schemaFence: {\n          graphId: ctx.graphId,\n          expectedVersion: requireDefined(ctx.schemaVersion),\n        },\n      });\n    } catch (error) {\n      if (error instanceof AtomicEdgeBatchEndpointRefusalError) {\n        await diagnoseAtomicEdgeBatchEndpointRefusal(\n          ctx,\n          creates,\n          backend,\n          error.cause,\n        );\n      }\n      throw error;\n    }\n  });\n  if (result.created.length === 0 && result.updated.length === 0) {\n    await diagnoseFusedSchemaFenceNoRow(ctx, backend);\n    throw new ResolvedMutationSetMoved(\"edge\", executor);\n  }\n  if (\n    result.created.length !== creates.length ||\n    result.updated.length !== updates.length\n  ) {\n    throw new CompilerInvariantError(\n      \"Atomic resolved edge mutation set returned a partial result.\",\n    );\n  }\n  memoizeLeasedSchemaFence(ctx, backend);\n  const createdById = new Map(result.created.map((row) => [row.id, row]));\n  const updatedById = new Map(result.updated.map((row) => [row.id, row]));\n  return appliedResolvedMutationSet({\n    created: creates.map((input) =>\n      rowToEdge(requireDefined(createdById.get(requireDefined(input.id)))),\n    ),\n    updated: updates.map((entry) =>\n      rowToEdge(requireDefined(updatedById.get(entry.input.id))),\n    ),\n  });\n}\n\nexport async function executeEdgeUpsertUpdateBatch<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  entries: readonly EdgeUpsertUpdateBatchEntry[],\n  backend: GraphBackend | TransactionBackend,\n): Promise<readonly Edge[]> {\n  if (entries.length === 0) return [];\n  for (const entry of entries) {\n    if (entry.input.clearValidTo === true) {\n      assertClearValidToSupported(backend, \"edge\");\n    }\n  }\n\n  const first = requireDefined(entries[0]);\n  const distinctIds = new Set(entries.map((entry) => entry.input.id));\n  const atomicExecutor = resolveAtomicEdgeUpdateExecutor(ctx, entries, backend);\n  if (atomicExecutor !== undefined) {\n    return executeAtomicEdgeResolvedUpdates(\n      ctx,\n      entries,\n      backend,\n      atomicExecutor,\n    );\n  }\n\n  const needsConstraintFence = entries.some(\n    (entry) => entry.clearDeleted || entry.input.clearValidTo === true,\n  );\n  return runWritePlan(\n    ctx,\n    edgeWritePlan(\n      needsConstraintFence ?\n        edgeWriteNeedsConstraintFence(\n          edgeCardinality(ctx, first.input.identity.kind),\n        )\n      : undefined,\n    ),\n    backend,\n    async (session, target) => {\n      const resolvedRows =\n        (\n          target.capabilities.execution.interactiveTransactions &&\n          distinctIds.size === entries.length\n        ) ?\n          await getEdgeRowsByIds(target, ctx.batchPointRead, ctx.graphId, [\n            ...distinctIds,\n          ])\n        : undefined;\n      const edges: Edge[] = [];\n      for (const entry of entries) {\n        edges.push(\n          await performEdgeUpdateConverging(\n            ctx,\n            entry.input,\n            session,\n            target,\n            entry.clearDeleted ? { clearDeleted: true } : undefined,\n            resolvedRows?.get(entry.input.id),\n          ),\n        );\n      }\n      return edges;\n    },\n    { didWrite: writeResultAlwaysChanges },\n  );\n}\n\nasync function executeAtomicEdgeResolvedUpdates<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  entries: readonly EdgeUpsertUpdateBatchEntry[],\n  backend: GraphBackend | TransactionBackend,\n  atomicExecutor: AtomicEdgeResolvedUpdateBatchExecutor,\n): Promise<readonly Edge[]> {\n  const maxAttempts = atomicResolvedUpdateAttemptBudget(\n    entries.length,\n    EDGE_UPDATE_ATTEMPTS,\n  );\n  const first = requireDefined(entries[0]);\n  const distinctIds = new Set(entries.map((entry) => entry.input.id));\n  const supplied = entries.flatMap((entry) =>\n    entry.existing === undefined ? [] : [entry.existing],\n  );\n  const fetched =\n    supplied.length === entries.length ?\n      undefined\n    : await getEdgeRowsByIds(backend, ctx.batchPointRead, ctx.graphId, [\n        ...distinctIds,\n      ]);\n  let existing = fetched === undefined ? supplied : [...fetched.values()];\n  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n    const byId = new Map(existing.map((row) => [row.id, row]));\n    const missing = entries.find((entry) => {\n      const row = byId.get(entry.input.id);\n      return row === undefined || row.deleted_at !== undefined;\n    });\n    if (missing !== undefined) {\n      // This update-only partition was resolved from live rows. Once a\n      // refreshed preimage is absent or tombstoned, the requested update\n      // target no longer exists; do not reinterpret it as a create or fall\n      // through to a transactionless portable write.\n      throw new EdgeNotFoundError(first.input.identity.kind, missing.input.id);\n    }\n    const resolved = entries.map((entry) => {\n      const row = requireDefined(byId.get(entry.input.id));\n      assertEdgeIdentityMatches(\n        entry.input.id,\n        entry.input.identity,\n        edgeIdentityFromRow(row),\n        \"update\",\n      );\n      const { validatedProps } = resolveEdgeUpdateProps(\n        ctx,\n        row,\n        entry.input.props,\n      );\n      return { existing: row, props: validatedProps };\n    });\n    const rows = await atomicExecutor({\n      entries: resolved,\n      schemaFence: {\n        graphId: ctx.graphId,\n        expectedVersion: requireDefined(ctx.schemaVersion),\n      },\n    });\n    if (rows.length === entries.length) {\n      memoizeLeasedSchemaFence(ctx, backend);\n      const returned = new Map(rows.map((row) => [row.id, row]));\n      return entries.map((entry) =>\n        rowToEdge(requireDefined(returned.get(entry.input.id))),\n      );\n    }\n    if (rows.length > 0) {\n      throw new CompilerInvariantError(\n        \"Atomic resolved edge update returned a partial result.\",\n        { expected: entries.length, actual: rows.length },\n      );\n    }\n    await diagnoseFusedSchemaFenceNoRow(ctx, backend);\n    if (attempt === maxAttempts) {\n      throw new DatabaseOperationError(\n        `Atomic edge update could not be applied to stable rows after ${maxAttempts} attempts.`,\n        {\n          operation: \"update\",\n          entity: \"edge\",\n          attempted: entries.map((entry) => ({\n            kind: entry.input.identity.kind,\n            id: entry.input.id,\n          })),\n        },\n      );\n    }\n    const refreshed = await getEdgeRowsByIds(\n      backend,\n      ctx.batchPointRead,\n      ctx.graphId,\n      [...distinctIds],\n    );\n    existing = [...refreshed.values()];\n  }\n  throw new CompilerInvariantError(\n    \"Atomic resolved edge update exhausted its retry loop.\",\n  );\n}\n\n/**\n * Executes an edge delete operation.\n */\nexport async function executeEdgeDelete<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  expectedKind: string,\n  id: string,\n  backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n  // Gate outside execution so an absent/tombstoned edge never fires hooks or\n  // submits a write; the gate row also supplies and verifies the hook kind.\n  // Eligible deletes then carry that kind into one atomic program. Other\n  // shapes retain the ordinary transaction path.\n  const gate = await backend.getEdge(ctx.graphId, id);\n  if (!gate) return;\n  assertEdgeIdentityMatches(\n    id,\n    { kind: expectedKind },\n    edgeIdentityFromRow(gate),\n    \"delete\",\n  );\n  if (gate.deleted_at) return;\n\n  const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n  const atomicExecutor = resolveAtomicEdgeDeleteBatchExecutor({\n    backend,\n    graph: ctx.graph,\n    expectedKind,\n    ids: [id],\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n  });\n  if (atomicExecutor !== undefined) {\n    await runAtomicProgramWithHooks(\n      ctx,\n      opContext,\n      () =>\n        executeAtomicEdgeDeletes(\n          ctx,\n          expectedKind,\n          [id],\n          backend,\n          atomicExecutor,\n        ),\n      (affectedCount) => affectedCount > 0,\n    );\n    return;\n  }\n\n  return runHookedWritePlan(\n    ctx,\n    opContext,\n    // A soft delete decides nothing a concurrent write could invalidate.\n    edgeWritePlan(undefined),\n    backend,\n    async (session) => {\n      // No in-transaction re-read: the statement carries the expected kind and\n      // `deleted_at IS NULL`, so it is its own recheck. A concurrent writer that\n      // tombstones this edge, or hard-deletes it and recreates the id under\n      // another kind, leaves the DELETE matching zero rows — the same no-op the\n      // re-read produced, one round trip cheaper and without the window between\n      // a lock-free `getEdge` and a `(graph_id, id)`-keyed write that PostgreSQL\n      // READ COMMITTED left open.\n      await session.retireEdge({ id, kind: expectedKind });\n    },\n  );\n}\n\n/**\n * Soft-deletes a batch without per-item operation hooks.\n *\n * The edge kind is checked from the authoritative row inside the transaction;\n * accepting an ID owned by another collection would violate collection\n * isolation even though edge IDs are graph-global.\n */\nexport async function executeEdgeDeleteBatch<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  expectedKind: string,\n  ids: readonly string[],\n  backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n  const atomicExecutor = resolveAtomicEdgeDeleteBatchExecutor({\n    backend,\n    graph: ctx.graph,\n    expectedKind,\n    ids,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n  });\n  if (atomicExecutor !== undefined) {\n    await executeAtomicEdgeDeletes(\n      ctx,\n      expectedKind,\n      ids,\n      backend,\n      atomicExecutor,\n    );\n    return;\n  }\n\n  await runWritePlan(\n    ctx,\n    edgeWritePlan(undefined),\n    backend,\n    async (session, target) => {\n      const rowsById = await getEdgeRowsByIds(\n        target,\n        ctx.batchPointRead,\n        ctx.graphId,\n        ids,\n      );\n      const retirements: { id: string; kind: string }[] = [];\n      const scheduledIds = new Set<string>();\n      for (const id of ids) {\n        const current = rowsById.get(id);\n        if (!current) continue;\n        assertEdgeIdentityMatches(\n          id,\n          { kind: expectedKind },\n          edgeIdentityFromRow(current),\n          \"delete\",\n        );\n        if (current.deleted_at) continue;\n        if (scheduledIds.has(id)) continue;\n        scheduledIds.add(id);\n        retirements.push({ id, kind: expectedKind });\n      }\n      // Resolution and execution share the same transaction target. The batch\n      // read is the identity gate; update operations cannot change an edge's\n      // kind or id, so the id-keyed batch update applies exactly that closed\n      // set while preserving the former absent/tombstoned skip semantics.\n      await session.retireEdges(retirements);\n      return retirements.length;\n    },\n    { didWrite: (affectedCount) => affectedCount > 0 },\n  );\n}\n\nasync function executeAtomicEdgeDeletes<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  expectedKind: string,\n  ids: readonly string[],\n  backend: GraphBackend | TransactionBackend,\n  atomicExecutor: AtomicEdgeDeleteBatchExecutor,\n): Promise<number> {\n  try {\n    const result = await atomicExecutor({\n      graphId: ctx.graphId,\n      expectedKind,\n      ids,\n      schemaFence: {\n        graphId: ctx.graphId,\n        expectedVersion: requireDefined(ctx.schemaVersion),\n      },\n    });\n    await assertAtomicDeleteSchemaFenceMatched(\n      result.schemaFenceMatched,\n      ctx,\n      backend,\n      \"edge\",\n    );\n    return result.affectedCount;\n  } catch (error) {\n    if (!(error instanceof AtomicEdgeDeleteIdentityRefusalError)) throw error;\n    const rowsById = await getEdgeRowsByIds(\n      backend,\n      ctx.batchPointRead,\n      ctx.graphId,\n      ids,\n    );\n    for (const id of ids) {\n      const current = rowsById.get(id);\n      if (current === undefined) continue;\n      assertEdgeIdentityMatches(\n        id,\n        { kind: expectedKind },\n        edgeIdentityFromRow(current),\n        \"delete\",\n      );\n    }\n    throw new DatabaseOperationError(\n      \"Atomic edge delete refused an identity mismatch, but no current \" +\n        \"foreign collection row could be diagnosed. The row identity may \" +\n        \"have changed concurrently after the atomic program aborted.\",\n      { operation: \"delete\", entity: \"edge\" },\n      { cause: error.cause },\n    );\n  }\n}\n\n/**\n * Executes an edge hard delete operation (permanent removal).\n *\n * Unlike soft delete, this permanently removes the edge from the database.\n */\nexport async function executeEdgeHardDelete<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  expectedKind: string,\n  id: string,\n  backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n  // Gate outside the transaction so an absent edge never opens an empty one;\n  // hooks wrap the transaction (see executeEdgeDelete).\n  const gate = await backend.getEdge(ctx.graphId, id);\n  if (!gate) return;\n  assertEdgeIdentityMatches(\n    id,\n    { kind: expectedKind },\n    edgeIdentityFromRow(gate),\n    \"hardDelete\",\n  );\n\n  const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n  return runHookedWritePlan(\n    ctx,\n    opContext,\n    edgeWritePlan(undefined),\n    backend,\n    async (session) => {\n      // No in-transaction re-read: see executeEdgeDelete. The DELETE carries the\n      // expected kind, so an id concurrently re-pointed at another kind's edge\n      // matches zero rows instead of destroying that other edge.\n      await session.purgeEdge({\n        id,\n        kind: expectedKind,\n        // Housekeeping, not a fence: this edge's claim is already takeable — its\n        // liveness predicate reads a row that no longer exists — so dropping the\n        // row only keeps the relation from growing by one row per hard-deleted\n        // constrained edge. An unconstrained kind holds no claim and pays no\n        // statement for one, the same rule its create follows.\n        holdsCardinalityClaim: edgeCardinality(ctx, expectedKind) !== \"many\",\n      });\n    },\n  );\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\n/**\n * Validates that all `matchOn` fields exist in the edge schema shape.\n * Throws a ValidationError for invalid fields.\n */\nfunction validateMatchOnFields(\n  schema: { shape?: Record<string, unknown> },\n  matchOn: readonly string[],\n  edgeKind: string,\n): void {\n  if (matchOn.length === 0) return;\n  const shape = schema.shape;\n  if (shape === undefined) {\n    throw new ValidationError(\n      `Edge kind \"${edgeKind}\" has no schema shape to validate matchOn fields against`,\n      {\n        kind: edgeKind,\n        operation: \"create\",\n        issues: matchOn.map((field) => ({\n          path: field,\n          message: `Field \"${field}\" does not exist in edge schema`,\n        })),\n      },\n    );\n  }\n\n  const invalidFields = matchOn.filter((field) => !hasOwnKey(shape, field));\n  if (invalidFields.length > 0) {\n    throw new ValidationError(\n      `Invalid matchOn fields for edge kind \"${edgeKind}\": ${invalidFields.join(\", \")}`,\n      {\n        kind: edgeKind,\n        operation: \"create\",\n        issues: invalidFields.map((field) => ({\n          path: field,\n          message: `Field \"${field}\" does not exist in edge schema`,\n        })),\n      },\n    );\n  }\n}\n\n/** Resolves the one match-field set an edge kind is allowed to converge on. */\nfunction resolveEdgeMatchFields(\n  edgeKind: string,\n  declared: readonly string[] | undefined,\n  requested: readonly string[] | undefined,\n): readonly string[] {\n  if (declared === undefined) return requested ?? [];\n  if (requested === undefined) return declared;\n  const canonicalRequested = [...requested].toSorted();\n  if (\n    canonicalRequested.length === declared.length &&\n    canonicalRequested.every((field, index) => field === declared[index])\n  ) {\n    return declared;\n  }\n  throw new ConfigurationError(\n    `Edge kind \"${edgeKind}\" declares match identity fields [${declared.join(\", \")}], but getOrCreateByEndpoints requested [${canonicalRequested.join(\", \")}].`,\n    { edgeKind, declared, requested: canonicalRequested },\n  );\n}\n\n/**\n * Endpoint-only key for grouping findEdgesByKind queries.\n */\nfunction buildEndpointPairKey(\n  fromKind: string,\n  fromId: string,\n  toKind: string,\n  toId: string,\n): string {\n  return encodeTupleKey([fromKind, fromId, toKind, toId]);\n}\n\ntype EdgeMatch = Readonly<{\n  liveRow: BackendEdgeRow | undefined;\n  deletedRow: BackendEdgeRow | undefined;\n}>;\n\n/**\n * Finds the best matching edge from candidate rows.\n * Partitions into live vs deleted; prefers live.\n */\nfunction findMatchingEdge(\n  rows: readonly BackendEdgeRow[],\n  matchOn: readonly string[],\n  inputProps: Record<string, unknown>,\n): EdgeMatch {\n  let liveRow: BackendEdgeRow | undefined;\n  let deletedRow: BackendEdgeRow | undefined;\n\n  for (const row of rows) {\n    if (matchOn.length > 0) {\n      const rowProps = rowPropsToObject(row.props);\n      const matches = matchOn.every(\n        (field) =>\n          canonicalPersistedJsonValue(readOwnProperty(rowProps, field)) ===\n          canonicalPersistedJsonValue(readOwnProperty(inputProps, field)),\n      );\n      if (!matches) continue;\n    }\n\n    if (row.deleted_at === undefined) {\n      liveRow ??= row;\n    } else {\n      deletedRow ??= row;\n    }\n\n    if (liveRow !== undefined) break;\n  }\n\n  return { liveRow, deletedRow };\n}\n\n/** Rechecks a dispatcher-selected row against the authoritative match key. */\nfunction assertEdgeMatchKey(\n  row: BackendEdgeRow,\n  matchOn: readonly string[],\n  matchProps: Record<string, unknown>,\n): void {\n  const match = findMatchingEdge([row], matchOn, matchProps);\n  if (match.liveRow === undefined && match.deletedRow === undefined) {\n    throw new EdgeMatchKeyMoved(row.kind, row.id);\n  }\n}\n\n/**\n * Executes a single findByEndpoints operation.\n *\n * Looks up an edge by endpoints and optional matchOn fields, honoring the\n * temporal coordinate in `options` (mode / asOf / excludeDeleted) the same way\n * `findFrom` / `findTo` do. Returns the matching edge, or undefined. By default\n * soft-deleted and out-of-window edges are excluded; under `includeTombstones`\n * (excludeDeleted = false) a soft-deleted edge can be returned.\n */\nexport async function executeEdgeFindByEndpoints<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n  fromKind: string,\n  fromId: string,\n  toKind: string,\n  toId: string,\n  backend: GraphReadBackend,\n  options?: Readonly<{\n    matchOn?: readonly string[];\n    props?: Record<string, unknown>;\n    excludeDeleted?: boolean;\n    temporalMode?: TemporalMode;\n    asOf?: string;\n  }>,\n): Promise<Edge | undefined> {\n  const matchOn = options?.matchOn ?? [];\n  const matchProps = normalizePersistedEdgeMatchProps(options?.props ?? {});\n\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  const edgeKind = registration.type;\n\n  if (matchOn.length > 0) {\n    validateMatchOnFields(edgeKind.schema, matchOn, kind);\n  }\n\n  const candidateRows = await backend.findEdgesByKind({\n    graphId: ctx.graphId,\n    kind,\n    fromKind,\n    fromId,\n    toKind,\n    toId,\n    excludeDeleted: options?.excludeDeleted ?? true,\n    ...(options?.temporalMode !== undefined && {\n      temporalMode: options.temporalMode,\n    }),\n    ...(options?.asOf !== undefined && { asOf: options.asOf }),\n  });\n\n  if (candidateRows.length === 0) return undefined;\n\n  if (matchOn.length === 0) return rowToEdge(requireDefined(candidateRows[0]));\n\n  const { liveRow } = findMatchingEdge(candidateRows, matchOn, matchProps);\n  return liveRow === undefined ? undefined : rowToEdge(liveRow);\n}\n\nfunction defersEndpointWindowOrdering(\n  ifExists: IfExistsMode,\n  onImmutableLowerBound: \"preserve\" | \"refuse\" | undefined,\n): boolean {\n  return (\n    ifExists === \"update\" && preservesImmutableLowerBound(onImmutableLowerBound)\n  );\n}\n\n/** Refuses a clear request on the endpoint mode whose matched-row contract is read-only. */\nfunction assertEndpointClearCanApply(\n  ifExists: IfExistsMode,\n  clearValidTo: true | undefined,\n  kind: string,\n): void {\n  if (ifExists !== \"return\" || clearValidTo !== true) return;\n  throw new ConfigurationError(\n    `clearValidTo requires ifExists: \"update\" for getOrCreateByEndpoints on edge kind \"${kind}\"; ifExists: \"return\" never mutates a matching edge.`,\n    {\n      code: \"CLEAR_VALID_TO_REQUIRES_UPDATE\",\n      kind,\n      ifExists,\n    },\n  );\n}\n\n/**\n * Executes a single getOrCreateByEndpoints operation.\n */\nexport async function executeEdgeGetOrCreateByEndpoints<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n  fromKind: string,\n  fromId: string,\n  toKind: string,\n  toId: string,\n  props: Record<string, unknown>,\n  backend: GraphBackend | TransactionBackend,\n  options?: Readonly<{\n    matchOn?: readonly string[];\n    ifExists?: IfExistsMode;\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: \"preserve\" | \"refuse\";\n  }>,\n): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>> {\n  const ifExists = options?.ifExists ?? \"return\";\n\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  const edgeKind = registration.type;\n  const matchOn = resolveEdgeMatchFields(\n    kind,\n    registration.matchIdentity?.fields,\n    options?.matchOn,\n  );\n\n  assertValidityEndMutation(options ?? {}, { entityType: \"edge\", kind });\n  if (options?.clearValidTo === true) {\n    assertClearValidToSupported(backend, \"edge\");\n  }\n\n  // Validate props\n  const validatedProps = validateEdgeProps(edgeKind.schema, props, {\n    kind,\n    operation: \"create\",\n  });\n  const matchProps = normalizePersistedEdgeMatchProps(validatedProps);\n\n  // Validate matchOn fields\n  validateMatchOnFields(edgeKind.schema, matchOn, kind);\n\n  // Canonical form is validated before the read probe so malformed input is\n  // always refused. Strict writes and return-mode calls also judge the stated\n  // pair here. A preserve-mode update defers ordering until its write leg has\n  // resolved whether it will create/resurrect (and apply the stated start) or\n  // update a live row (and retain the stored start).\n  const validFrom = validateStatedValidityLowerBound(\n    options?.validFrom,\n    \"validFrom\",\n  );\n  const validTo = validateOptionalCanonicalIsoDate(options?.validTo, \"validTo\");\n  if (!defersEndpointWindowOrdering(ifExists, options?.onImmutableLowerBound)) {\n    assertOrderedValidityWindow(\n      `${kind} edge between ${fromKind} \"${fromId}\" and ${toKind} \"${toId}\"`,\n      validFrom,\n      validTo,\n    );\n  }\n\n  const findCandidates = async (\n    target: GraphBackend | TransactionBackend,\n  ): Promise<readonly BackendEdgeRow[]> =>\n    target.findEdgesByKind({\n      graphId: ctx.graphId,\n      kind,\n      fromKind,\n      fromId,\n      toKind,\n      toId,\n      excludeDeleted: false,\n      temporalMode: \"includeTombstones\",\n    });\n\n  async function findCandidatesInTransaction(): Promise<\n    readonly BackendEdgeRow[]\n  > {\n    return runOptionallyInTransaction(\n      backend,\n      (target) => findCandidates(target),\n      { transaction: { accessMode: \"read_only\" } },\n    );\n  }\n\n  // The return-mode probe is also the dispatcher read for a create. Retain its\n  // result, including whether it came from a transaction, so a stale positive\n  // disproved by the authoritative read does not repeat either lookup before\n  // the create transaction performs its own convergence check.\n  let initialCandidateRead:\n    | Readonly<{\n        rows: readonly BackendEdgeRow[];\n        authoritative: boolean;\n      }>\n    | undefined;\n\n  // A root read is only a dispatcher hint. Confirm a positive result through\n  // the transaction target before returning it; a cache may replay a stale\n  // positive just as it may replay a stale empty result.\n  if (ifExists === \"return\" && registration.matchIdentity === undefined) {\n    const probeRows = await findCandidates(backend);\n    const { liveRow: probedLiveRow, deletedRow: probedDeletedRow } =\n      findMatchingEdge(probeRows, matchOn, matchProps);\n    if (probedLiveRow !== undefined) {\n      const currentRows = await findCandidatesInTransaction();\n      const { liveRow: currentLiveRow } = findMatchingEdge(\n        currentRows,\n        matchOn,\n        matchProps,\n      );\n      if (currentLiveRow !== undefined) {\n        assertEndpointClearCanApply(ifExists, options?.clearValidTo, kind);\n        return { edge: rowToEdge(currentLiveRow), action: \"found\" };\n      }\n      initialCandidateRead = {\n        rows: currentRows,\n        authoritative: true,\n      };\n    } else if (probedDeletedRow === undefined) {\n      initialCandidateRead = {\n        rows: probeRows,\n        authoritative: false,\n      };\n    }\n  }\n\n  // No enclosing transaction: each write leg opens its own (hooked, for the\n  // create leg) transaction. An outer transaction here would make the nested\n  // operation run directly inside it and fire its success hooks before THIS\n  // wrapper's COMMIT — the durability contract hooks promise would be false.\n  //\n  // The lookup below is therefore only a DISPATCHER: it chooses a leg, and the\n  // two legs that DERIVE a verdict re-derive it under the per-graph fence their\n  // transaction holds. The create leg runs the convergence command inside\n  // that transaction (`convergeOn`) and aborts rather than inserting a second\n  // edge for a match key a competitor just claimed; the resurrect leg re-checks\n  // cardinality in-transaction. The `found` leg writes nothing and derives\n  // nothing, and the `updated` leg writes to an id it resolved here — its\n  // in-transaction re-read and its endpoint-predicated UPDATE are what make\n  // that write land on the row this lookup meant, not a re-derivation of the\n  // dispatcher's choice.\n  async function resolveMatchedRow(\n    matchedRow: BackendEdgeRow,\n    isDeleted: boolean,\n  ): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>> {\n    if (!isDeleted) {\n      if (ifExists === \"return\") {\n        assertEndpointClearCanApply(ifExists, options?.clearValidTo, kind);\n        return { edge: rowToEdge(matchedRow), action: \"found\" };\n      }\n      const outcome = await executeEdgeUpsertUpdateWithOutcome(\n        ctx,\n        {\n          id: matchedRow.id,\n          identity: { kind, fromKind, fromId, toKind, toId },\n          props: validatedProps,\n          ...(validFrom !== undefined && { validFrom }),\n          ...(validTo !== undefined && { validTo }),\n          ...(options?.clearValidTo === true && {\n            clearValidTo: true as const,\n          }),\n          ...(options?.onImmutableLowerBound !== undefined && {\n            onImmutableLowerBound: options.onImmutableLowerBound,\n          }),\n        },\n        backend,\n        {\n          coalesceUnchanged:\n            ctx.coalesceUnchangedUpsertsEnabled &&\n            shouldCoalesceUpsert(matchedRow, options, () =>\n              edgeUpsertDirtyCheck(\n                ctx,\n                matchedRow.kind,\n                matchedRow.id,\n                rowPropsToObject(matchedRow.props),\n                validatedProps,\n              ),\n            ),\n          matchOn,\n          matchProps,\n        },\n      );\n      return {\n        edge: outcome.edge,\n        action: outcome.wrote ? \"updated\" : \"found\",\n      };\n    }\n\n    const edge = await executeEdgeUpsertUpdate(\n      ctx,\n      {\n        id: matchedRow.id,\n        identity: { kind, fromKind, toKind, fromId, toId },\n        props: validatedProps,\n        ...(validFrom !== undefined && { validFrom }),\n        ...(validTo !== undefined && { validTo }),\n        ...(options?.clearValidTo === true && { clearValidTo: true as const }),\n        ...(options?.onImmutableLowerBound !== undefined && {\n          onImmutableLowerBound: options.onImmutableLowerBound,\n        }),\n      },\n      backend,\n      { clearDeleted: true, matchOn, matchProps },\n    );\n    return { edge, action: \"resurrected\" };\n  }\n\n  async function attempt(\n    forceTransactionRead: boolean,\n  ): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>> {\n    if (registration.matchIdentity !== undefined && !forceTransactionRead) {\n      const createResult = await executeEdgeCreateInternal(\n        ctx,\n        {\n          kind,\n          fromKind,\n          fromId,\n          toKind,\n          toId,\n          props: validatedProps,\n          ...(validFrom !== undefined && { validFrom }),\n          ...(validTo !== undefined && { validTo }),\n        },\n        backend,\n        {\n          returnRow: true,\n          convergeOn: { matchOn, props: matchProps },\n        },\n      );\n      if (createResult.outcome === \"found\") {\n        return resolveMatchedRow(\n          createResult.row,\n          createResult.row.deleted_at !== undefined,\n        );\n      }\n      if (createResult.edge === undefined) {\n        throw new DatabaseOperationError(\n          \"Durable edge convergence returned no row.\",\n          { operation: \"insert\", entity: \"edge\" },\n        );\n      }\n      return { edge: createResult.edge, action: \"created\" };\n    }\n\n    const retainedRead = initialCandidateRead;\n    initialCandidateRead = undefined;\n    const candidateRead =\n      retainedRead ??\n      (forceTransactionRead ?\n        {\n          rows: await findCandidatesInTransaction(),\n          authoritative: true,\n        }\n      : {\n          rows: await findCandidates(backend),\n          authoritative: false,\n        });\n\n    let { liveRow, deletedRow } = findMatchingEdge(\n      candidateRead.rows,\n      matchOn,\n      matchProps,\n    );\n\n    // A root match is a dispatcher hint only. Use the transaction-scoped row\n    // before selecting an update/resurrection id, since cached root reads may\n    // be stale in either direction.\n    if (\n      !candidateRead.authoritative &&\n      (liveRow !== undefined || deletedRow !== undefined)\n    ) {\n      const currentRows = await findCandidatesInTransaction();\n      ({ liveRow, deletedRow } = findMatchingEdge(\n        currentRows,\n        matchOn,\n        matchProps,\n      ));\n    }\n\n    // No match → create new edge\n    if (liveRow === undefined && deletedRow === undefined) {\n      const input: CreateEdgeInput = {\n        kind,\n        fromKind,\n        fromId,\n        toKind,\n        toId,\n        props: validatedProps,\n        ...(validFrom !== undefined && { validFrom }),\n        ...(validTo !== undefined && { validTo }),\n      };\n      const createResult = await executeEdgeCreateInternal(\n        ctx,\n        input,\n        backend,\n        {\n          returnRow: true,\n          convergeOn: { matchOn, props: matchProps },\n        },\n      );\n      if (createResult.outcome === \"found\") {\n        return resolveMatchedRow(\n          createResult.row,\n          createResult.row.deleted_at !== undefined,\n        );\n      }\n      if (createResult.edge === undefined) {\n        throw new DatabaseOperationError(\n          \"Edge create failed: expected created edge row\",\n          { operation: \"insert\", entity: \"edge\" },\n        );\n      }\n      return { edge: createResult.edge, action: \"created\" };\n    }\n\n    if (liveRow !== undefined) return resolveMatchedRow(liveRow, false);\n    if (deletedRow === undefined) {\n      throw new Error(\"Expected deletedRow to be defined\");\n    }\n    return resolveMatchedRow(deletedRow, true);\n  }\n\n  // Convergence loop. Under the fence a losing writer learns about the winner\n  // from its own in-transaction convergence command rather than from a\n  // constraint violation, so the ordinary path uses the row the transaction\n  // just observed. The `CardinalityError` arm remains the\n  // backstop for the paths the fence cannot cover — a competitor whose write is\n  // not a `getOrCreateByEndpoints` at all.\n  //\n  // ATTEMPT_LIMIT bounds a pathological ping-pong (a competitor that creates\n  // and hard-deletes the same match key repeatedly) rather than spinning.\n  const ATTEMPT_LIMIT = 3;\n  let forceTransactionRead = false;\n  for (let remaining = ATTEMPT_LIMIT; remaining > 0; remaining -= 1) {\n    try {\n      return await attempt(forceTransactionRead);\n    } catch (error) {\n      if (\n        error instanceof EdgeMatchKeyMoved ||\n        error instanceof EdgeNotFoundError\n      ) {\n        if (remaining === 1) {\n          throw new DatabaseOperationError(\n            `getOrCreateByEndpoints for ${kind} between ${fromKind} \"${fromId}\" ` +\n              `and ${toKind} \"${toId}\" could not resolve a stable matching edge ` +\n              `after ${String(ATTEMPT_LIMIT)} attempts; a concurrent writer ` +\n              \"keeps changing or deleting it. Retry the operation.\",\n            { operation: \"insert\", entity: \"edge\" },\n            { cause: error },\n          );\n        }\n        forceTransactionRead = true;\n        continue;\n      }\n      if (error instanceof EdgeMatchIdentityConflictError) {\n        if (remaining === 1) {\n          throw new DatabaseOperationError(\n            `getOrCreateByEndpoints for ${kind} between ${fromKind} \"${fromId}\" ` +\n              `and ${toKind} \"${toId}\" could not resolve the durable identity ` +\n              `owner after ${String(ATTEMPT_LIMIT)} attempts. Retry the operation.`,\n            { operation: \"insert\", entity: \"edge\" },\n            { cause: error },\n          );\n        }\n        forceTransactionRead = true;\n        continue;\n      }\n      if (error instanceof CardinalityError && remaining > 1) continue;\n      throw error;\n    }\n  }\n  // Unreachable: the loop either returns or throws on its final iteration.\n  throw new DatabaseOperationError(\n    \"getOrCreateByEndpoints convergence loop exited without a verdict\",\n    { operation: \"insert\", entity: \"edge\" },\n  );\n}\n\n/**\n * Executes a bulk getOrCreateByEndpoints operation.\n */\nexport async function executeEdgeBulkGetOrCreateByEndpoints<G extends GraphDef>(\n  ctx: EdgeOperationContext<G>,\n  kind: string,\n  items: readonly Readonly<{\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    props: Record<string, unknown>;\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: \"preserve\" | \"refuse\";\n  }>[],\n  backend: GraphBackend | TransactionBackend,\n  options?: Readonly<{\n    matchOn?: readonly string[];\n    ifExists?: IfExistsMode;\n  }>,\n): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]> {\n  if (items.length === 0) return [];\n\n  const ifExists = options?.ifExists ?? \"return\";\n\n  const registration = getEdgeRegistration(ctx.graph, kind);\n  const edgeKind = registration.type;\n  assertEdgeMatchIdentityBackendSupport(\n    registration.matchIdentity,\n    backend.capabilities,\n    kind,\n  );\n  const matchOn = resolveEdgeMatchFields(\n    kind,\n    registration.matchIdentity?.fields,\n    options?.matchOn,\n  );\n\n  // Validate matchOn fields once\n  validateMatchOnFields(edgeKind.schema, matchOn, kind);\n\n  // Step 1: Validate all props and compute composite keys\n  const validated: {\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    validatedProps: Record<string, unknown>;\n    matchProps: Record<string, unknown>;\n    compositeKey: string;\n    endpointKey: string;\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: \"preserve\" | \"refuse\";\n  }[] = [];\n\n  for (const item of items) {\n    assertValidityEndMutation(item, { entityType: \"edge\", kind });\n    if (item.clearValidTo === true) {\n      assertClearValidToSupported(backend, \"edge\");\n    }\n    const validatedProps = validateEdgeProps(edgeKind.schema, item.props, {\n      kind,\n      operation: \"create\",\n    });\n    const matchProps = normalizePersistedEdgeMatchProps(validatedProps);\n    const validFrom = validateStatedValidityLowerBound(\n      item.validFrom,\n      \"validFrom\",\n    );\n    const validTo = validateOptionalCanonicalIsoDate(item.validTo, \"validTo\");\n    // As in the single-item path, canonical form is always judged up front.\n    // Preserve-mode updates defer ordering until the target row is resolved.\n    if (!defersEndpointWindowOrdering(ifExists, item.onImmutableLowerBound)) {\n      assertOrderedValidityWindow(\n        `${kind} edge between ${item.fromKind} \"${item.fromId}\" and ${item.toKind} \"${item.toId}\"`,\n        validFrom,\n        validTo,\n      );\n    }\n\n    const compositeKey = buildEdgeMatchKey({\n      fromKind: item.fromKind,\n      fromId: item.fromId,\n      toKind: item.toKind,\n      toId: item.toId,\n      props: matchProps,\n      matchOn,\n    });\n    const endpointKey = buildEndpointPairKey(\n      item.fromKind,\n      item.fromId,\n      item.toKind,\n      item.toId,\n    );\n\n    validated.push({\n      fromKind: item.fromKind,\n      fromId: item.fromId,\n      toKind: item.toKind,\n      toId: item.toId,\n      validatedProps,\n      matchProps,\n      compositeKey,\n      endpointKey,\n      ...(validFrom !== undefined && { validFrom }),\n      ...(validTo !== undefined && { validTo }),\n      ...(item.clearValidTo === true && { clearValidTo: true as const }),\n      ...(item.onImmutableLowerBound !== undefined && {\n        onImmutableLowerBound: item.onImmutableLowerBound,\n      }),\n    });\n  }\n\n  interface Result {\n    readonly edge: Edge;\n    readonly action: GetOrCreateAction;\n  }\n\n  // Durable many-cardinality batches have a database arbiter for their match\n  // key. Dispatch this closed program before the collection can wrap the call\n  // in a caller transaction; otherwise the exact-root proof is hidden behind\n  // a derived transaction target and the operation falls back to the old\n  // read/transaction/one-row-at-a-time path.\n  const atomicConvergenceExecutor = resolveAtomicEdgeConvergenceExecutor({\n    backend,\n    graph: ctx.graph,\n    schemaVersion: ctx.schemaVersion,\n    historyEnabled: ctx.historyEnabled,\n    revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n    kind,\n    matchOn,\n    inputs: items,\n    uniqueEntryCount: new Set(validated.map((entry) => entry.compositeKey))\n      .size,\n    ifExists,\n  });\n  if (atomicConvergenceExecutor !== undefined) {\n    const nativeEntries: {\n      index: number;\n      compositeKey: string;\n      params: InsertEdgeParams;\n      match: { kind: \"durable\"; identity: { name: string; key: string } };\n    }[] = [];\n    const firstByCompositeKey = new Set<string>();\n    for (const [index, entry] of validated.entries()) {\n      if (firstByCompositeKey.has(entry.compositeKey)) continue;\n      firstByCompositeKey.add(entry.compositeKey);\n      const endpointError = validateEdgeEndpoints(\n        kind,\n        entry.fromKind,\n        entry.toKind,\n        registration,\n        ctx.registry,\n      );\n      if (endpointError) throw endpointError;\n      const matchIdentity = resolveEdgeMatchIdentityStorage(\n        registration.matchIdentity,\n        {\n          fromKind: entry.fromKind,\n          fromId: entry.fromId,\n          toKind: entry.toKind,\n          toId: entry.toId,\n          props: entry.validatedProps,\n        },\n        { graphId: ctx.graphId, edgeKind: kind },\n      );\n      if (matchIdentity === undefined) {\n        throw new CompilerInvariantError(\n          \"Atomic edge convergence requires durable match identity storage.\",\n          { kind, index },\n        );\n      }\n      const params = buildInsertEdgeParams(\n        ctx.graphId,\n        generateId(),\n        kind,\n        entry.fromKind,\n        entry.fromId,\n        entry.toKind,\n        entry.toId,\n        entry.validatedProps,\n        undefined,\n        undefined,\n        matchIdentity,\n      );\n      nativeEntries.push({\n        index,\n        compositeKey: entry.compositeKey,\n        params,\n        match: { kind: \"durable\", identity: matchIdentity },\n      });\n    }\n\n    const schemaFence = {\n      graphId: ctx.graphId,\n      expectedVersion: requireDefined(ctx.schemaVersion),\n    };\n    let nativeResults:\n      | readonly {\n          readonly row: BackendEdgeRow;\n          readonly outcome: \"created\" | \"found\";\n        }[]\n      | undefined;\n    try {\n      nativeResults = await atomicConvergenceExecutor({\n        kind: \"durable-convergence\",\n        entries: nativeEntries.map((entry) => ({\n          params: entry.params,\n          match: entry.match,\n        })),\n        schemaFence,\n      });\n    } catch (error) {\n      if (error instanceof AtomicEdgeBatchEndpointRefusalError) {\n        await diagnoseAtomicEdgeBatchEndpointRefusal(\n          ctx,\n          nativeEntries.map((entry) => entry.params),\n          backend,\n          error.cause,\n        );\n      }\n      if (error instanceof AtomicEdgeConvergenceTombstoneRefusalError) {\n        nativeResults = undefined;\n      } else {\n        throw error;\n      }\n    }\n    if (nativeResults !== undefined) {\n      if (nativeResults.length !== nativeEntries.length) {\n        await diagnoseFusedSchemaFenceNoRow(ctx, backend);\n        throw new DatabaseOperationError(\n          `Atomic edge convergence returned ${nativeResults.length} results, expected ${nativeEntries.length}.`,\n          { operation: \"insert\", entity: \"edge\" },\n        );\n      }\n      const results: Result[] = Array.from({ length: items.length });\n      const resultByCompositeKey = new Map<string, Result>();\n      for (const [nativeIndex, nativeResult] of nativeResults.entries()) {\n        const nativeEntry = requireDefined(nativeEntries[nativeIndex]);\n        const result = {\n          edge: rowToEdge(nativeResult.row),\n          action: nativeResult.outcome,\n        } satisfies Result;\n        results[nativeEntry.index] = result;\n        resultByCompositeKey.set(nativeEntry.compositeKey, result);\n      }\n      for (const [index, entry] of validated.entries()) {\n        if (results[index] !== undefined) continue;\n        const result = resultByCompositeKey.get(entry.compositeKey);\n        if (result === undefined) {\n          throw new CompilerInvariantError(\n            \"Atomic edge convergence omitted an input result.\",\n            { index, compositeKey: entry.compositeKey },\n          );\n        }\n        results[index] = { edge: result.edge, action: \"found\" };\n      }\n      return results;\n    }\n    // The native program rolled back before any logical write. A\n    // transaction-capable fallback below owns schema-aware resurrection;\n    // transactionless roots refuse because they cannot preserve whole-call\n    // atomicity while running that merge in application code.\n  }\n\n  // Step 2: Group by unique endpoint pair\n  const uniqueEndpoints = new Map<\n    string,\n    { fromKind: string; fromId: string; toKind: string; toId: string }\n  >();\n  for (const entry of validated) {\n    if (!uniqueEndpoints.has(entry.endpointKey)) {\n      uniqueEndpoints.set(entry.endpointKey, {\n        fromKind: entry.fromKind,\n        fromId: entry.fromId,\n        toKind: entry.toKind,\n        toId: entry.toId,\n      });\n    }\n  }\n\n  // Fetch all candidate rows, grouped by endpoint pair. Shared by the\n  // outside-transaction probe (reading the root backend) and the\n  // transactional body (re-reading through the transaction target).\n  async function fetchRowsByEndpoint(\n    reader: GraphReadBackend,\n  ): Promise<ReadonlyMap<string, readonly BackendEdgeRow[]>> {\n    const rowsByEndpoint = new Map<string, readonly BackendEdgeRow[]>();\n    const setRead = reader.findEdgesByHeterogeneousEndpointSet;\n    if (setRead !== undefined) {\n      for (const endpointKey of uniqueEndpoints.keys()) {\n        rowsByEndpoint.set(endpointKey, []);\n      }\n      const sourceEndpoints = new Map<\n        string,\n        Readonly<{\n          kind: string;\n          id: string;\n          opposite: Readonly<{ kind: string; id: string }>;\n        }>\n      >();\n      for (const endpoint of uniqueEndpoints.values()) {\n        sourceEndpoints.set(\n          buildEndpointPairKey(\n            endpoint.fromKind,\n            endpoint.fromId,\n            endpoint.toKind,\n            endpoint.toId,\n          ),\n          {\n            kind: endpoint.fromKind,\n            id: endpoint.fromId,\n            opposite: { kind: endpoint.toKind, id: endpoint.toId },\n          },\n        );\n      }\n      const rows = await setRead({\n        graphId: ctx.graphId,\n        side: \"from\",\n        endpoints: [...sourceEndpoints.values()],\n        edgeKinds: [kind],\n        excludeDeleted: false,\n        temporalMode: \"includeTombstones\",\n      });\n      const mutableRows = new Map<string, BackendEdgeRow[]>();\n      for (const row of rows) {\n        const endpointKey = buildEndpointPairKey(\n          row.from_kind,\n          row.from_id,\n          row.to_kind,\n          row.to_id,\n        );\n        if (!uniqueEndpoints.has(endpointKey)) continue;\n        const bucket = mutableRows.get(endpointKey) ?? [];\n        bucket.push(row);\n        mutableRows.set(endpointKey, bucket);\n      }\n      for (const [endpointKey, endpointRows] of mutableRows) {\n        rowsByEndpoint.set(endpointKey, endpointRows);\n      }\n      return rowsByEndpoint;\n    }\n    for (const [endpointKey, endpoint] of uniqueEndpoints) {\n      const rows = await reader.findEdgesByKind({\n        graphId: ctx.graphId,\n        kind,\n        fromKind: endpoint.fromKind,\n        fromId: endpoint.fromId,\n        toKind: endpoint.toKind,\n        toId: endpoint.toId,\n        excludeDeleted: false,\n        temporalMode: \"includeTombstones\",\n      });\n      rowsByEndpoint.set(endpointKey, rows);\n    }\n    return rowsByEndpoint;\n  }\n\n  interface CreateEntry {\n    index: number;\n    input: CreateEdgeInput;\n  }\n  interface FetchEntry {\n    index: number;\n    row: BackendEdgeRow;\n    isDeleted: boolean;\n    validatedProps: Record<string, unknown>;\n    fromKind: string;\n    fromId: string;\n    toKind: string;\n    toId: string;\n    /**\n     * STORED only on a RESURRECTION, which rewrites both endpoints. It is\n     * forwarded on the live-update leg too, where the write guard refuses a\n     * bound that differs from the one the row already holds.\n     */\n    validFrom?: string | null;\n    validTo?: string;\n    clearValidTo?: true;\n    onImmutableLowerBound?: \"preserve\" | \"refuse\";\n  }\n  interface DuplicateEntry {\n    index: number;\n    sourceIndex: number;\n  }\n  // Step 3: Partition into toCreate, toFetch, and duplicates\n  function partitionEntries(\n    rowsByEndpoint: ReadonlyMap<string, readonly BackendEdgeRow[]>,\n  ): Readonly<{\n    toCreate: CreateEntry[];\n    toFetch: FetchEntry[];\n    duplicateOf: DuplicateEntry[];\n  }> {\n    const toCreate: CreateEntry[] = [];\n    const toFetch: FetchEntry[] = [];\n    const duplicateOf: DuplicateEntry[] = [];\n    const seenKeys = new Map<string, number>();\n\n    for (const [index, entry] of validated.entries()) {\n      // Check within-batch duplicate\n      const previousIndex = seenKeys.get(entry.compositeKey);\n      if (previousIndex !== undefined) {\n        // A duplicate is a found/no-write result, so there is no stored target\n        // window against which preserve mode can defer this decision. Keep the\n        // existing return-mode contract: its stated pair must be ordered.\n        if (preservesImmutableLowerBound(entry.onImmutableLowerBound)) {\n          assertOrderedValidityWindow(\n            `${kind} edge between ${entry.fromKind} \"${entry.fromId}\" and ${entry.toKind} \"${entry.toId}\"`,\n            entry.validFrom,\n            entry.validTo,\n          );\n        }\n        duplicateOf.push({ index, sourceIndex: previousIndex });\n        continue;\n      }\n      seenKeys.set(entry.compositeKey, index);\n\n      const candidateRows = rowsByEndpoint.get(entry.endpointKey) ?? [];\n      const { liveRow, deletedRow } = findMatchingEdge(\n        candidateRows,\n        matchOn,\n        entry.matchProps,\n      );\n\n      if (liveRow === undefined && deletedRow === undefined) {\n        toCreate.push({\n          index,\n          input: {\n            kind,\n            fromKind: entry.fromKind,\n            fromId: entry.fromId,\n            toKind: entry.toKind,\n            toId: entry.toId,\n            props: entry.validatedProps,\n            ...(entry.validFrom !== undefined && {\n              validFrom: entry.validFrom,\n            }),\n            ...(entry.validTo !== undefined && { validTo: entry.validTo }),\n          },\n        });\n      } else {\n        // At least one of liveRow/deletedRow is defined (both-undefined handled above)\n        const bestRow = liveRow ?? deletedRow;\n        if (bestRow === undefined) {\n          throw new Error(\"Expected at least one of liveRow or deletedRow\");\n        }\n        toFetch.push({\n          index,\n          row: bestRow,\n          isDeleted: liveRow === undefined,\n          validatedProps: entry.validatedProps,\n          fromKind: entry.fromKind,\n          fromId: entry.fromId,\n          toKind: entry.toKind,\n          toId: entry.toId,\n          ...(entry.validFrom !== undefined && {\n            validFrom: entry.validFrom,\n          }),\n          ...(entry.validTo !== undefined && { validTo: entry.validTo }),\n          ...(entry.clearValidTo === true && {\n            clearValidTo: true as const,\n          }),\n          ...(entry.onImmutableLowerBound !== undefined && {\n            onImmutableLowerBound: entry.onImmutableLowerBound,\n          }),\n        });\n      }\n    }\n\n    return { toCreate, toFetch, duplicateOf };\n  }\n\n  function restoreAllFoundResults(\n    partition: ReturnType<typeof partitionEntries>,\n  ): Result[] | undefined {\n    if (\n      partition.toCreate.length > 0 ||\n      partition.toFetch.some((entry) => entry.isDeleted)\n    ) {\n      return;\n    }\n\n    const found: Result[] = Array.from({ length: items.length });\n    for (const entry of partition.toFetch) {\n      assertEndpointClearCanApply(ifExists, entry.clearValidTo, kind);\n      found[entry.index] = { edge: rowToEdge(entry.row), action: \"found\" };\n    }\n    for (const { index, sourceIndex } of partition.duplicateOf) {\n      found[index] = {\n        edge: requireDefined(found[sourceIndex]).edge,\n        action: \"found\",\n      };\n    }\n    return found;\n  }\n\n  // An all-live `ifExists: \"return\"` result is a read-only observation: it\n  // writes nothing and therefore needs no write fence or transaction-owned\n  // create-vs-fetch decision. A caching transport can return a stale positive,\n  // but that has the same semantics as any other read through that transport;\n  // only a partition that may write is re-derived inside the fenced session.\n  if (ifExists === \"return\") {\n    const found = restoreAllFoundResults(\n      partitionEntries(await fetchRowsByEndpoint(backend)),\n    );\n    if (found !== undefined) return found;\n  }\n\n  // The partition that decides create-vs-fetch is re-derived from `target`\n  // INSIDE the fenced transaction, so the batch's lookup and its writes commit\n  // under one per-graph mutual exclusion — the bulk analogue of the single-item\n  // path's `convergeOn` guard, and the reason the bulk path needs no in-loop\n  // race handling of its own.\n  function runBatch(): Promise<\n    Readonly<{ results: Result[]; writes: number }>\n  > {\n    return runWritePlan(\n      ctx,\n      // A bulk getOrCreate always converges on a match key no database key\n      // backs, whatever its cardinality — the same reason the single-item path\n      // fences unconditionally.\n      edgeWritePlan(\"edgeMatchKeyConvergence\"),\n      backend,\n      async (session, target, _overlaidSession, lock) => {\n        // ## The one widening the migration cannot remove\n        //\n        // The nested legs are whole managed writes of their own: each opens its\n        // OWN plan against THIS transaction target, which is why they take the\n        // raw union rather than the session this frame minted. Re-entering the\n        // executor is not decoration — the nested frame re-takes the schema\n        // fence and, on a revision-tracking store, advances the revision clock —\n        // so inlining their row work here to avoid the widening would change\n        // emitted statements and revision numbers, which the no-behavior-change\n        // invariant forbids. Every other escape is gone; this one is the\n        // ratchet's stated floor, not migration debt.\n        const rawTarget = nestedManagedWriteTarget(target);\n        const { toCreate, toFetch, duplicateOf } = partitionEntries(\n          await fetchRowsByEndpoint(target),\n        );\n        const results: Result[] = Array.from({ length: items.length });\n        let writes = 0;\n\n        // Step 4: Execute creates in batch\n        if (toCreate.length > 0) {\n          // The batch insertion path deliberately remains one multi-row write,\n          // rather than expanding into one convergence command per item. It\n          // still derives create-vs-found from the fenced snapshot, so enforce\n          // the same freshness contract as the single-item command before the\n          // first create. Existing-only batches never reach this gate.\n          if (lock.coordination !== undefined) {\n            assertGraphCommandConvergenceIsolation(\n              target.commands,\n              lock.coordination,\n            );\n          }\n          const createInputs = toCreate.map((entry) => entry.input);\n          const createdEdges = await executeEdgeCreateBatch(\n            ctx,\n            createInputs,\n            rawTarget,\n          );\n          for (const [batchIndex, entry] of toCreate.entries()) {\n            results[entry.index] = {\n              edge: requireDefined(createdEdges[batchIndex]),\n              action: \"created\",\n            };\n          }\n          writes += toCreate.length;\n        }\n\n        // Step 5: Handle existing edges (update/skip/resurrect). The batch\n        // helper owns the same update/resurrection semantics as the single\n        // entry path, including validity-window checks and cardinality\n        // fencing. It can also select the native resolved-update program for\n        // a live, no-window batch. Coalescing is intentionally kept on the\n        // outcome path below: the batch helper has no per-entry dirty-check\n        // candidate, so routing that shape through it would turn a found\n        // replay into an update.\n        const updateEntries = toFetch.map(\n          (entry) =>\n            ({\n              input: {\n                id: entry.row.id,\n                identity: {\n                  kind,\n                  fromKind: entry.fromKind,\n                  fromId: entry.fromId,\n                  toKind: entry.toKind,\n                  toId: entry.toId,\n                },\n                props: entry.validatedProps,\n                ...(entry.validFrom !== undefined && {\n                  validFrom: entry.validFrom,\n                }),\n                ...(entry.validTo !== undefined && { validTo: entry.validTo }),\n                ...(entry.clearValidTo === true && {\n                  clearValidTo: true as const,\n                }),\n                ...(entry.onImmutableLowerBound !== undefined && {\n                  onImmutableLowerBound: entry.onImmutableLowerBound,\n                }),\n              },\n              clearDeleted: entry.isDeleted,\n              existing: entry.row,\n            }) satisfies EdgeUpsertUpdateBatchEntry,\n        );\n\n        const batchEntryIndexes =\n          ifExists === \"update\" ?\n            toFetch.map((_entry, index) => index)\n          : toFetch.flatMap((entry, index) => (entry.isDeleted ? [index] : []));\n        const canBatchUpdates =\n          !ctx.coalesceUnchangedUpsertsEnabled && batchEntryIndexes.length > 0;\n        if (canBatchUpdates) {\n          const updated = await executeEdgeUpsertUpdateBatch(\n            ctx,\n            batchEntryIndexes.map((index) =>\n              requireDefined(updateEntries[index]),\n            ),\n            rawTarget,\n          );\n          for (const [updateIndex, entryIndex] of batchEntryIndexes.entries()) {\n            const entry = requireDefined(toFetch[entryIndex]);\n            const edge = requireDefined(updated[updateIndex]);\n            results[entry.index] = {\n              edge,\n              action: entry.isDeleted ? \"resurrected\" : \"updated\",\n            };\n            writes += 1;\n          }\n\n          // The write batch contains only rows that need mutation. A live\n          // `ifExists: \"return\"` match deliberately stays out of that batch,\n          // but it still owns a result slot in the caller's input order.\n          // Complete those read-only outcomes here, at the same seam that\n          // correlates the mutated postimages, before duplicate resolution\n          // consumes any source result.\n          if (ifExists === \"return\") {\n            for (const entry of toFetch) {\n              if (entry.isDeleted) continue;\n              assertEndpointClearCanApply(ifExists, entry.clearValidTo, kind);\n              results[entry.index] = {\n                edge: rowToEdge(entry.row),\n                action: \"found\",\n              };\n            }\n          }\n        } else {\n          for (const [entryIndex, entry] of toFetch.entries()) {\n            const input = requireDefined(updateEntries[entryIndex]).input;\n            if (entry.isDeleted) {\n              // As in the single-item path: a resurrection forwards\n              // `validFrom` so a stated lower bound restates the revived row's\n              // whole window, and its cardinality re-check runs inside the\n              // resurrecting write.\n              const edge = await executeEdgeUpsertUpdate(\n                ctx,\n                input,\n                rawTarget,\n                { clearDeleted: true },\n              );\n              results[entry.index] = { edge, action: \"resurrected\" };\n              writes += 1;\n            } else if (ifExists === \"update\") {\n              // As in the single-item path: `validFrom` is forwarded so the\n              // shared write guard refuses a bound the in-place update cannot\n              // store, rather than dropping it here.\n              const outcome = await executeEdgeUpsertUpdateWithOutcome(\n                ctx,\n                input,\n                rawTarget,\n                {\n                  coalesceUnchanged: ctx.coalesceUnchangedUpsertsEnabled,\n                  coalesceCandidate: entry.row,\n                },\n              );\n              results[entry.index] = {\n                edge: outcome.edge,\n                action: outcome.wrote ? \"updated\" : \"found\",\n              };\n              if (outcome.wrote) writes += 1;\n            } else {\n              assertEndpointClearCanApply(ifExists, entry.clearValidTo, kind);\n              results[entry.index] = {\n                edge: rowToEdge(entry.row),\n                action: \"found\",\n              };\n            }\n          }\n        }\n\n        // Step 6: Resolve within-batch duplicates\n        for (const { index, sourceIndex } of duplicateOf) {\n          const sourceResult = requireDefined(results[sourceIndex]);\n          if (sourceResult.action === \"found\") {\n            assertEndpointClearCanApply(\n              ifExists,\n              items[index]?.clearValidTo,\n              kind,\n            );\n          }\n          results[index] = { edge: sourceResult.edge, action: \"found\" };\n        }\n\n        return { results, writes };\n      },\n      { didWrite: (outcome) => outcome.writes > 0 },\n    );\n  }\n\n  async function runBatchResults(): Promise<Result[]> {\n    const outcome = await runBatch();\n    return outcome.results;\n  }\n\n  // The single-item path's `CardinalityError` retry, which this path lacked: a\n  // competing winner failed the WHOLE batch instead of converging. With the\n  // fence the batch's own lookup sees the winner, so this is the backstop for\n  // the paths the fence cannot cover (a non-transactional backend, or a\n  // competitor that is not a `getOrCreateByEndpoints`) — one retry, matching\n  // the single-item path rather than inventing a second policy.\n  try {\n    return await runBatchResults();\n  } catch (error) {\n    if (!(error instanceof CardinalityError)) throw error;\n    return runBatchResults();\n  }\n}\n","import { deriveBackend, projectGraphBackend } from \"../backend/derive-backend\";\nimport {\n  type EdgeRow,\n  type GraphBackend,\n  type NodeRow,\n} from \"../backend/types\";\nimport {\n  parseRecordedInstant,\n  type ReadCoordinate,\n  type RecordedInstantParts,\n} from \"../core/temporal\";\nimport {\n  type AnyEdgeType,\n  type EdgeId,\n  type NodeId,\n  type NodeType,\n} from \"../core/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport { sqlValueList } from \"../query/compiler/predicate-utils\";\nimport {\n  type RecordedReadBinding,\n  recordedReadSqlSchema,\n  requireRecordedReadBinding,\n  type SqlSchema,\n} from \"../query/compiler/schema\";\nimport {\n  compileTemporalFilter,\n  currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { decodeCursor, encodeCursor } from \"../query/cursor\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, type CompiledRowsSql } from \"../query/sql-intent\";\nimport { chunk } from \"../utils/array\";\nimport { requireDefined } from \"../utils/presence\";\nimport { withRecordedRelationsPrecondition } from \"../utils/sql-errors\";\nimport { recordedBindParamBudget } from \"./recorded-capture/relations\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport {\n  type Edge,\n  type Node,\n  type RecordedScanOptions,\n  type RecordedScanPage,\n} from \"./types\";\n\nconst RECORDED_POINT_READ_FIXED_BIND_PARAMS = 8;\nconst RECORDED_SCAN_LIMIT = 1000;\n\ntype RecordedReadServiceParams = Readonly<{\n  graphId: string;\n  backend: GraphBackend;\n  recordedReadBinding: RecordedReadBinding | undefined;\n  mapRecordedNodeRow: (row: Record<string, unknown>) => NodeRow;\n  mapRecordedEdgeRow: (row: Record<string, unknown>) => EdgeRow;\n}>;\n\ntype RecordedGetByIdsParams<T extends Readonly<{ id: string }>> = Readonly<{\n  entity: \"node\" | \"edge\";\n  table: SqlFragment;\n  alias: string;\n  kind: string;\n  ids: readonly string[];\n  coordinate: ReadCoordinate;\n  toEntity: (row: Record<string, unknown>) => T;\n}>;\n\ntype RecordedScanParams<T extends Readonly<{ id: string }>> = Readonly<{\n  entity: \"node\" | \"edge\";\n  table: SqlFragment;\n  alias: string;\n  kind: string;\n  coordinate: ReadCoordinate;\n  options: RecordedScanOptions | undefined;\n  toEntity: (row: Record<string, unknown>) => T;\n}>;\n\nexport type RecordedReadService = Readonly<{\n  backendForCoordinate: (\n    coordinate: ReadCoordinate,\n    surface: string,\n  ) => GraphBackend;\n  nodeGetById: <N extends NodeType>(\n    kind: string,\n    id: NodeId<N>,\n    coordinate: ReadCoordinate,\n  ) => Promise<Node<N> | undefined>;\n  nodeGetByIds: <N extends NodeType>(\n    kind: string,\n    ids: readonly NodeId<N>[],\n    coordinate: ReadCoordinate,\n  ) => Promise<readonly (Node<N> | undefined)[]>;\n  nodeScan: <N extends NodeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ) => Promise<RecordedScanPage<Node<N>>>;\n  edgeGetById: <E extends AnyEdgeType>(\n    kind: string,\n    id: EdgeId<E>,\n    coordinate: ReadCoordinate,\n  ) => Promise<Edge<E> | undefined>;\n  edgeGetByIds: <E extends AnyEdgeType>(\n    kind: string,\n    ids: readonly EdgeId<E>[],\n    coordinate: ReadCoordinate,\n  ) => Promise<readonly (Edge<E> | undefined)[]>;\n  edgeScan: <E extends AnyEdgeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ) => Promise<RecordedScanPage<Edge<E>>>;\n}>;\n\n/**\n * Per-chunk id count for a recorded point read: the backend's real\n * bound-parameter ceiling less the statement's fixed binds, so Postgres point\n * reads page thousands of ids per round-trip instead of a dialect-blind 900.\n */\nfunction recordedPointReadIdChunk(backend: GraphBackend): number {\n  const budget = recordedBindParamBudget(backend);\n  return Math.max(1, budget - RECORDED_POINT_READ_FIXED_BIND_PARAMS);\n}\n\nfunction recordedRelationErrorDetails(\n  backend: Pick<GraphBackend, \"dialect\">,\n  surface: string,\n): Readonly<{ dialect: GraphBackend[\"dialect\"]; surface: string }> {\n  return { dialect: backend.dialect, surface };\n}\n\nfunction withRelationsPrecondition<T>(\n  backend: Pick<GraphBackend, \"dialect\">,\n  promise: Promise<T>,\n  surface: string,\n): Promise<T> {\n  return withRecordedRelationsPrecondition(\n    promise,\n    recordedRelationErrorDetails(backend, surface),\n  );\n}\n\nfunction createRecordedReadBackend(\n  backend: GraphBackend,\n  surface: string,\n): GraphBackend {\n  // A public AdapterStore backend is frozen. Decorate a fresh allowlist\n  // projection so Proxy invariants do not prevent the execute guards from\n  // replacing non-configurable function properties.\n  const projectedBackend = projectGraphBackend(backend);\n  return deriveBackend(projectedBackend, {\n    execute: <T>(query: CompiledRowsSql): Promise<readonly T[]> =>\n      withRelationsPrecondition(backend, backend.execute<T>(query), surface),\n    ...(backend.executeRaw === undefined ?\n      {}\n    : {\n        executeRaw: <T>(\n          sqlText: string,\n          params: readonly unknown[],\n        ): Promise<readonly T[]> =>\n          withRelationsPrecondition(\n            backend,\n            requireDefined(backend.executeRaw)<T>(sqlText, params),\n            surface,\n          ),\n      }),\n  });\n}\n\n/**\n * The recorded revision a point read or scan reconstructs at, parsed once\n * from the coordinate's `recorded.asOf` — the single place a missing\n * recorded pin is refused, consulted by {@link createRecordedReadService}'s\n * callers before they resolve the recorded schema. The temporal filter below\n * re-derives the same instant through {@link compileTemporalFilter}'s own\n * parse rather than repeating the refusal here, since by the time it runs\n * this function has already guaranteed the coordinate carries one.\n */\nfunction requireRecordedRevision(\n  coordinate: ReadCoordinate,\n): RecordedInstantParts {\n  const recordedAsOf = coordinate.recorded?.asOf;\n  if (recordedAsOf === undefined) {\n    throw new ConfigurationError(\n      \"Recorded point reads require a recorded-time coordinate.\",\n      { code: \"RECORDED_POINT_READ_MISSING_COORDINATE\" },\n    );\n  }\n  return parseRecordedInstant(recordedAsOf, \"coordinate.recorded.asOf\");\n}\n\nfunction recordedTemporalFilter(\n  coordinate: ReadCoordinate,\n  tableAlias: string,\n  recordedReadBinding: RecordedReadBinding,\n): SqlFragment {\n  return compileTemporalFilter({\n    mode: coordinate.valid.mode,\n    asOf: coordinate.valid.asOf,\n    recordedAsOf: coordinate.recorded?.asOf,\n    tableAlias,\n    currentTimestamp: currentReadInstant(),\n    recordedReadBinding,\n  });\n}\n\n/**\n * The ORDER BY a recorded point read applies, letting `recordedGetByIds`\n * detect an overlapping-interval anomaly deterministically. Meaningful only\n * for a binding whose source carries the `recorded_from`/`recorded_to`\n * interval (`binding.carriesInterval`) — a TypeGraph-relation-backed source\n * returns every revision of a matching row, and `recorded_from` is what\n * separates them; a binding without that interval already scopes its source\n * to exactly one revision, so there is no such column to order by and no\n * anomaly the ordering could surface — `recordedGetByIds`'s per-id duplicate\n * check still catches a genuine violation regardless of row order.\n */\nfunction recordedPointReadOrderBy(\n  binding: RecordedReadBinding,\n  aliasSql: SqlFragment,\n): SqlFragment {\n  return binding.carriesInterval ?\n      sql`ORDER BY ${aliasSql}.recorded_from`\n    : sql``;\n}\n\n/**\n * The ORDER BY a recorded scan applies. `id ASC` drives pagination and\n * dedup on every binding; the `recorded_from ASC` tiebreaker exists only to\n * make a same-id anomaly's row order deterministic under a binding whose\n * source carries the recorded-time interval — see\n * {@link recordedPointReadOrderBy}.\n */\nfunction recordedScanOrderBy(\n  binding: RecordedReadBinding,\n  aliasSql: SqlFragment,\n): SqlFragment {\n  return binding.carriesInterval ?\n      sql`ORDER BY ${aliasSql}.id ASC, ${aliasSql}.recorded_from ASC`\n    : sql`ORDER BY ${aliasSql}.id ASC`;\n}\n\nfunction recordedRelationInvariantError(\n  params: Readonly<{\n    graphId: string;\n    entity: \"node\" | \"edge\";\n    kind: string;\n    id: string;\n    coordinate: ReadCoordinate;\n  }>,\n): ConfigurationError {\n  return new ConfigurationError(\n    \"Recorded relation invariant violation: more than one recorded row matched the requested read.\",\n    {\n      code: \"RECORDED_RELATION_INVARIANT_VIOLATION\",\n      graphId: params.graphId,\n      entity: params.entity,\n      kind: params.kind,\n      id: params.id,\n      validMode: params.coordinate.valid.mode,\n      validAsOf: params.coordinate.valid.asOf,\n      recordedAsOf: params.coordinate.recorded?.asOf,\n    },\n    {\n      suggestion:\n        \"Repair overlapping recorded_from/recorded_to intervals for this entity before using recorded-time reads.\",\n    },\n  );\n}\n\nfunction validateRecordedScanLimit(limit: number | undefined): number {\n  if (limit === undefined) return RECORDED_SCAN_LIMIT;\n  if (!Number.isInteger(limit) || limit <= 0 || limit > RECORDED_SCAN_LIMIT) {\n    throw new ValidationError(\n      `Recorded scan limit must be an integer between 1 and ${RECORDED_SCAN_LIMIT}, got: ${String(limit)}`,\n      {\n        issues: [\n          {\n            path: \"limit\",\n            message: `Must be an integer between 1 and ${RECORDED_SCAN_LIMIT}.`,\n          },\n        ],\n      },\n    );\n  }\n  return limit;\n}\n\nfunction recordedScanCursorScope(\n  graphId: string,\n  entity: \"node\" | \"edge\",\n  kind: string,\n  coordinate: ReadCoordinate,\n): string {\n  return JSON.stringify([\n    \"recorded-scan\",\n    graphId,\n    entity,\n    kind,\n    coordinate.valid.mode,\n    coordinate.valid.asOf,\n    coordinate.recorded?.asOf,\n  ]);\n}\n\nfunction invalidRecordedScanCursor(): ValidationError {\n  return new ValidationError(\n    \"Recorded scan cursor does not match this graph, collection, or temporal coordinate.\",\n    {\n      issues: [\n        {\n          path: \"after\",\n          message:\n            \"Use a cursor returned by the same recorded collection scan.\",\n        },\n      ],\n    },\n  );\n}\n\nfunction decodeRecordedScanCursor(\n  cursor: string,\n  expectedScope: string,\n): string {\n  const decoded = decodeCursor(cursor);\n  if (\n    decoded.d !== \"f\" ||\n    decoded.cols.length !== 1 ||\n    decoded.cols[0] !== expectedScope ||\n    decoded.vals.length !== 1 ||\n    typeof decoded.vals[0] !== \"string\"\n  ) {\n    throw invalidRecordedScanCursor();\n  }\n  return decoded.vals[0];\n}\n\nfunction encodeRecordedScanCursor(id: string, scope: string): string {\n  return encodeCursor({ v: 1, d: \"f\", vals: [id], cols: [scope] });\n}\n\nexport function createRecordedReadService(\n  params: RecordedReadServiceParams,\n): RecordedReadService {\n  const {\n    graphId,\n    backend,\n    recordedReadBinding,\n    mapRecordedNodeRow,\n    mapRecordedEdgeRow,\n  } = params;\n\n  /**\n   * Resolves the recorded relation schema for `revision` — built fresh per\n   * coordinate since {@link RecordedReadSource.source} takes the revision\n   * (an engine-native binding could fold it into the source expression\n   * itself), and refuses the same way every recorded read refuses a missing\n   * binding.\n   */\n  function schemaForRecordedRead(\n    surface: string,\n    revision: RecordedInstantParts,\n  ): SqlSchema {\n    return recordedReadSqlSchema(\n      requireRecordedReadBinding(recordedReadBinding, surface),\n      revision,\n    );\n  }\n\n  async function recordedGetByIds<T extends Readonly<{ id: string }>>(\n    read: RecordedGetByIdsParams<T>,\n  ): Promise<readonly (T | undefined)[]> {\n    const { table, alias, kind, ids, coordinate, toEntity, entity } = read;\n    if (ids.length === 0) return [];\n\n    const uniqueIds = [...new Set(ids)];\n    const aliasSql = sql.raw(alias);\n    const binding = requireRecordedReadBinding(\n      recordedReadBinding,\n      \"recorded-point-read\",\n    );\n    const temporalFilter = recordedTemporalFilter(coordinate, alias, binding);\n    const orderBy = recordedPointReadOrderBy(binding, aliasSql);\n    const chunkResults = await withRelationsPrecondition(\n      backend,\n      Promise.all(\n        chunk(uniqueIds, recordedPointReadIdChunk(backend)).map((idChunk) =>\n          backend.execute<Record<string, unknown>>(\n            asCompiledRowsSql(sql`\n              SELECT * FROM ${table} ${aliasSql}\n              WHERE ${aliasSql}.graph_id = ${graphId}\n                AND ${aliasSql}.kind = ${kind}\n                AND ${aliasSql}.id IN (${sqlValueList(idChunk)})\n                AND ${temporalFilter}\n              ${orderBy}\n            `),\n          ),\n        ),\n      ),\n      \"recorded-point-read\",\n    );\n\n    const byId = new Map<string, T>();\n    for (const rows of chunkResults) {\n      for (const row of rows) {\n        const entityRow = toEntity(row);\n        if (byId.has(entityRow.id)) {\n          throw recordedRelationInvariantError({\n            graphId,\n            entity,\n            kind,\n            id: entityRow.id,\n            coordinate,\n          });\n        }\n        byId.set(entityRow.id, entityRow);\n      }\n    }\n    return ids.map((id) => byId.get(id));\n  }\n\n  async function recordedScan<T extends Readonly<{ id: string }>>(\n    scan: RecordedScanParams<T>,\n  ): Promise<RecordedScanPage<T>> {\n    const { table, alias, kind, coordinate, options, toEntity, entity } = scan;\n    const limit = validateRecordedScanLimit(options?.limit);\n    const scope = recordedScanCursorScope(graphId, entity, kind, coordinate);\n    const after =\n      options?.after === undefined ?\n        undefined\n      : decodeRecordedScanCursor(options.after, scope);\n    const aliasSql = sql.raw(alias);\n    const binding = requireRecordedReadBinding(\n      recordedReadBinding,\n      \"recorded-scan\",\n    );\n    const temporalFilter = recordedTemporalFilter(coordinate, alias, binding);\n    const orderBy = recordedScanOrderBy(binding, aliasSql);\n    const rows = await withRelationsPrecondition(\n      backend,\n      backend.execute<Record<string, unknown>>(\n        asCompiledRowsSql(sql`\n          SELECT * FROM ${table} ${aliasSql}\n          WHERE ${aliasSql}.graph_id = ${graphId}\n            AND ${aliasSql}.kind = ${kind}\n            ${after === undefined ? sql.raw(\"\") : sql`AND ${aliasSql}.id > ${after}`}\n            AND ${temporalFilter}\n          ${orderBy}\n          LIMIT ${limit + 1}\n        `),\n      ),\n      \"recorded-scan\",\n    );\n    const entities = rows.map((row) => toEntity(row));\n    for (let index = 1; index < entities.length; index += 1) {\n      const previous = requireDefined(entities[index - 1]);\n      const current = requireDefined(entities[index]);\n      if (previous.id !== current.id) continue;\n      throw recordedRelationInvariantError({\n        graphId,\n        entity,\n        kind,\n        id: current.id,\n        coordinate,\n      });\n    }\n\n    const hasNextPage = entities.length > limit;\n    const data = hasNextPage ? entities.slice(0, limit) : entities;\n    return {\n      data,\n      nextCursor:\n        hasNextPage ?\n          encodeRecordedScanCursor(requireDefined(data.at(-1)).id, scope)\n        : undefined,\n      hasNextPage,\n    };\n  }\n\n  function nodeGetByIds<N extends NodeType>(\n    kind: string,\n    ids: readonly NodeId<N>[],\n    coordinate: ReadCoordinate,\n  ): Promise<readonly (Node<N> | undefined)[]> {\n    const schema = schemaForRecordedRead(\n      \"recorded-point-read\",\n      requireRecordedRevision(coordinate),\n    );\n    return recordedGetByIds({\n      entity: \"node\",\n      table: schema.nodesTable,\n      alias: \"n\",\n      kind,\n      ids,\n      coordinate,\n      toEntity: (row) => rowToNode(mapRecordedNodeRow(row)) as Node<N>,\n    });\n  }\n\n  function edgeGetByIds<E extends AnyEdgeType>(\n    kind: string,\n    ids: readonly EdgeId<E>[],\n    coordinate: ReadCoordinate,\n  ): Promise<readonly (Edge<E> | undefined)[]> {\n    const schema = schemaForRecordedRead(\n      \"recorded-point-read\",\n      requireRecordedRevision(coordinate),\n    );\n    return recordedGetByIds({\n      entity: \"edge\",\n      table: schema.edgesTable,\n      alias: \"e\",\n      kind,\n      ids,\n      coordinate,\n      toEntity: (row) => rowToEdge(mapRecordedEdgeRow(row)) as Edge<E>,\n    });\n  }\n\n  function nodeScan<N extends NodeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ): Promise<RecordedScanPage<Node<N>>> {\n    const schema = schemaForRecordedRead(\n      \"recorded-scan\",\n      requireRecordedRevision(coordinate),\n    );\n    return recordedScan({\n      entity: \"node\",\n      table: schema.nodesTable,\n      alias: \"n\",\n      kind,\n      coordinate,\n      options,\n      toEntity: (row) => rowToNode(mapRecordedNodeRow(row)) as Node<N>,\n    });\n  }\n\n  function edgeScan<E extends AnyEdgeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ): Promise<RecordedScanPage<Edge<E>>> {\n    const schema = schemaForRecordedRead(\n      \"recorded-scan\",\n      requireRecordedRevision(coordinate),\n    );\n    return recordedScan({\n      entity: \"edge\",\n      table: schema.edgesTable,\n      alias: \"e\",\n      kind,\n      coordinate,\n      options,\n      toEntity: (row) => rowToEdge(mapRecordedEdgeRow(row)) as Edge<E>,\n    });\n  }\n\n  return {\n    backendForCoordinate(\n      coordinate: ReadCoordinate,\n      surface: string,\n    ): GraphBackend {\n      if (coordinate.recorded === undefined) return backend;\n      requireRecordedReadBinding(recordedReadBinding, surface);\n      return createRecordedReadBackend(backend, surface);\n    },\n\n    async nodeGetById<N extends NodeType>(\n      kind: string,\n      id: NodeId<N>,\n      coordinate: ReadCoordinate,\n    ): Promise<Node<N> | undefined> {\n      const results = await nodeGetByIds(kind, [id], coordinate);\n      return results[0];\n    },\n\n    nodeGetByIds,\n    nodeScan,\n\n    async edgeGetById<E extends AnyEdgeType>(\n      kind: string,\n      id: EdgeId<E>,\n      coordinate: ReadCoordinate,\n    ): Promise<Edge<E> | undefined> {\n      const results = await edgeGetByIds(kind, [id], coordinate);\n      return results[0];\n    },\n\n    edgeGetByIds,\n    edgeScan,\n  };\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport {\n  type IdentityFacade,\n  type IdentityReadFacade,\n  type IdentityWriteSummary,\n} from \"../identity/types\";\nimport { type Assert, type Equal } from \"../utils/type-assert\";\nimport type {\n  IDENTITY_READ_NAMES,\n  IDENTITY_WRITE_NAMES,\n} from \"./collection-surface\";\nimport { EDGE_WRITE_NAMES, NODE_WRITE_NAMES } from \"./collection-surface\";\nimport type {\n  EdgeWrites,\n  GraphEdgeCollections,\n  GraphNodeCollections,\n  NodeWrites,\n  TransactionReceipt,\n} from \"./types\";\n\ntype NodeWriteMethodName = (typeof NODE_WRITE_NAMES)[number];\ntype EdgeWriteMethodName = (typeof EDGE_WRITE_NAMES)[number];\n\n// If these fail, the receipt wrapper drifted away from the collection write\n// surface that defines NodeWrites / EdgeWrites.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _receiptNodeSurfaceIsComplete = Assert<\n  Equal<NodeWriteMethodName, keyof NodeWrites<NodeType, string>>\n>;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _receiptEdgeSurfaceIsComplete = Assert<\n  Equal<EdgeWriteMethodName, keyof EdgeWrites<AnyEdgeType, NodeType, NodeType>>\n>;\n// wrapTransactionIdentity re-implements the facade method by method, so a new\n// IdentityFacade method that nobody adds here would silently bypass both the\n// receipt counters and the sealing guard.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _receiptIdentitySurfaceIsComplete = Assert<\n  Equal<\n    | (typeof IDENTITY_READ_NAMES)[number]\n    | (typeof IDENTITY_WRITE_NAMES)[number],\n    keyof IdentityFacade<GraphDef>\n  >\n>;\n// And the read/write split itself: a method the read facade exposes must be\n// classified as a read, so StoreView's read-only identity surface stays honest.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _identityReadSplitIsHonest = Assert<\n  Equal<\n    (typeof IDENTITY_READ_NAMES)[number],\n    keyof IdentityReadFacade<GraphDef>\n  >\n>;\n\n/** The receipt's identity counter buckets, minus the derived total. */\ntype IdentityWriteCounterName = Exclude<keyof IdentityWriteSummary, \"total\">;\n\nexport type TransactionReceiptRecorder = Readonly<{\n  recordNode: (kind: string, count: number) => void;\n  recordEdge: (kind: string, count: number) => void;\n  recordIdentity: (kind: IdentityWriteCounterName, count: number) => void;\n  snapshot: (recorded?: TransactionReceipt[\"recorded\"]) => TransactionReceipt;\n  /**\n   * Seals the recorder: every subsequent write through a collection wrapped with\n   * it (see {@link wrapTransactionCollections}) throws. Used to fail loud when a\n   * transaction context is retained and written through *after* its callback\n   * returned — where the receipt is already snapshotted and the write would\n   * otherwise persist uncounted.\n   */\n  seal: () => void;\n  /**\n   * Throws {@link ConfigurationError} once {@link seal} has been called. Invoked\n   * at the top of every wrapped write method, before the live write runs, so a\n   * post-seal write never reaches the backend.\n   */\n  assertWritable: () => void;\n}>;\n\ntype WrappedMethod = (...args: unknown[]) => Promise<unknown>;\n\ntype WriteIntentCounter = (args: readonly unknown[]) => number;\n\nfunction inputLength(value: unknown): number {\n  return Array.isArray(value) ? value.length : 0;\n}\n\nfunction countSingleWrite(): number {\n  return 1;\n}\n\nfunction countBulkInputAt(index: number): WriteIntentCounter {\n  return (args) => inputLength(args[index]);\n}\n\n// `satisfies Record<...MethodName, ...>` forces a per-method decision: a new\n// write method fails to compile here until its intent count is chosen, so a\n// future bulk method cannot silently fall back to counting 1 per call.\nconst NODE_WRITE_INTENT_COUNTERS = {\n  create: countSingleWrite,\n  createFromRecord: countSingleWrite,\n  update: countSingleWrite,\n  compareAndSet: countSingleWrite,\n  updateWhere: countSingleWrite,\n  delete: countSingleWrite,\n  hardDelete: countSingleWrite,\n  upsertById: countSingleWrite,\n  upsertByIdFromRecord: countSingleWrite,\n  bulkCreate: countBulkInputAt(0),\n  bulkReplaceById: countBulkInputAt(0),\n  bulkUpsertById: countBulkInputAt(0),\n  bulkInsert: countBulkInputAt(0),\n  bulkDelete: countBulkInputAt(0),\n  getOrCreateByConstraint: countSingleWrite,\n  bulkGetOrCreateByConstraint: countBulkInputAt(1),\n} as const satisfies Record<NodeWriteMethodName, WriteIntentCounter>;\n\nconst EDGE_WRITE_INTENT_COUNTERS = {\n  create: countSingleWrite,\n  update: countSingleWrite,\n  delete: countSingleWrite,\n  hardDelete: countSingleWrite,\n  bulkCreate: countBulkInputAt(0),\n  bulkUpsertById: countBulkInputAt(0),\n  bulkInsert: countBulkInputAt(0),\n  bulkDelete: countBulkInputAt(0),\n  getOrCreateByEndpoints: countSingleWrite,\n  bulkGetOrCreateByEndpoints: countBulkInputAt(0),\n} as const satisfies Record<EdgeWriteMethodName, WriteIntentCounter>;\n\n// Null-prototype buckets: kind names are arbitrary identifiers, so\n// `constructor`, `toString`, or `__proto__` are valid kinds. On a plain `{}`\n// they would read inherited Object.prototype members (corrupting the count)\n// or trigger the `__proto__` setter (dropping it).\nfunction createCountBucket(): Record<string, number> {\n  return Object.create(null) as Record<string, number>;\n}\n\nfunction increment(\n  counts: Record<string, number>,\n  kind: string,\n  count: number,\n): void {\n  if (count === 0) return;\n  counts[kind] = (counts[kind] ?? 0) + count;\n}\n\n/**\n * One receipt's running counts. Each recorder owns exactly one: the outer\n * transaction's receipt, or the sub-receipt of one `tx.measure` scope. Scope\n * attribution is structural — a scope is a *second* recorder wrapping the outer\n * collections again (see `attachMeasure` in store.ts) — so no recorder ever\n * needs to know about another's scopes.\n */\ninterface WriteCounters {\n  readonly nodes: Record<string, number>;\n  readonly edges: Record<string, number>;\n  readonly identity: { -readonly [K in keyof IdentityWriteSummary]: number };\n  total: number;\n}\n\nexport function createTransactionReceiptRecorder(): TransactionReceiptRecorder {\n  const counters: WriteCounters = {\n    nodes: createCountBucket(),\n    edges: createCountBucket(),\n    identity: {\n      sameAssertions: 0,\n      differentAssertions: 0,\n      retractions: 0,\n      total: 0,\n    },\n    total: 0,\n  };\n  let sealed = false;\n\n  return {\n    recordNode(kind, count): void {\n      increment(counters.nodes, kind, count);\n      counters.total += count;\n    },\n\n    recordEdge(kind, count): void {\n      increment(counters.edges, kind, count);\n      counters.total += count;\n    },\n\n    recordIdentity(kind, count): void {\n      counters.identity[kind] += count;\n      counters.identity.total += count;\n      counters.total += count;\n    },\n\n    snapshot(recorded): TransactionReceipt {\n      // Spread, not `Object.assign` onto a fresh null-prototype bucket. Both\n      // keep a prototype-colliding kind name readable, but the receipt is\n      // RETURNED to the caller, and a spread is the boundary copy that also\n      // restores `Object.prototype` (see `createDataKeyedBag`'s \"Spread it at\n      // the boundary\"): it copies own properties with CreateDataProperty rather\n      // than Set, so a `__proto__` kind survives as an own key while\n      // `receipt.writes.nodes instanceof Object` still answers `true` — as\n      // `identity` on the next line always did.\n      return Object.freeze({\n        writes: Object.freeze({\n          nodes: Object.freeze({ ...counters.nodes }),\n          edges: Object.freeze({ ...counters.edges }),\n          identity: Object.freeze({ ...counters.identity }),\n          total: counters.total,\n        }),\n        ...(recorded === undefined ? {} : { recorded }),\n      });\n    },\n\n    seal(): void {\n      sealed = true;\n    },\n\n    assertWritable(): void {\n      if (sealed) {\n        throw new ConfigurationError(\n          \"Transaction context is sealed: a write happened through the receipt-tracked collections after the transaction callback returned.\",\n          {},\n          {\n            suggestion:\n              \"Perform all writes inside the transactionWithReceipt / withRecordedTransaction callback; do not reuse the transaction context after it returns.\",\n          },\n        );\n      }\n    },\n  };\n}\n\nexport function wrapTransactionIdentity<G extends GraphDef>(\n  identity: IdentityFacade<G>,\n  recorder: TransactionReceiptRecorder,\n): IdentityFacade<G> {\n  return {\n    representativeOf: (ref) => identity.representativeOf(ref),\n    membersOf: (ref) => identity.membersOf(ref),\n    nodesOf: (ref) => identity.nodesOf(ref),\n    areSame: (a, b) => identity.areSame(a, b),\n    areDifferent: (a, b) => identity.areDifferent(a, b),\n    assertionsOf: (ref) => identity.assertionsOf(ref),\n    async assertSame(a, b) {\n      recorder.assertWritable();\n      const result = await identity.assertSame(a, b);\n      recorder.recordIdentity(\"sameAssertions\", 1);\n      return result;\n    },\n    async assertDifferent(a, b) {\n      recorder.assertWritable();\n      const result = await identity.assertDifferent(a, b);\n      recorder.recordIdentity(\"differentAssertions\", 1);\n      return result;\n    },\n    async bulkAssertSame(pairs) {\n      recorder.assertWritable();\n      // Pin the intent count before awaiting: the caller may mutate the input\n      // array while the write is in flight (matches the node/edge wrappers).\n      const count = pairs.length;\n      const result = await identity.bulkAssertSame(pairs);\n      recorder.recordIdentity(\"sameAssertions\", count);\n      return result;\n    },\n    async bulkAssertDifferent(pairs) {\n      recorder.assertWritable();\n      const count = pairs.length;\n      const result = await identity.bulkAssertDifferent(pairs);\n      recorder.recordIdentity(\"differentAssertions\", count);\n      return result;\n    },\n    async retractAssertion(id) {\n      recorder.assertWritable();\n      const result = await identity.retractAssertion(id);\n      recorder.recordIdentity(\"retractions\", 1);\n      return result;\n    },\n    async retractSameAssertion(a, b) {\n      recorder.assertWritable();\n      const result = await identity.retractSameAssertion(a, b);\n      recorder.recordIdentity(\"retractions\", 1);\n      return result;\n    },\n    async retractDifferentAssertion(a, b) {\n      recorder.assertWritable();\n      const result = await identity.retractDifferentAssertion(a, b);\n      recorder.recordIdentity(\"retractions\", 1);\n      return result;\n    },\n    async bulkRetractAssertions(ids) {\n      recorder.assertWritable();\n      const count = ids.length;\n      const result = await identity.bulkRetractAssertions(ids);\n      recorder.recordIdentity(\"retractions\", count);\n      return result;\n    },\n  };\n}\n\nfunction isWrappedMethod(value: unknown): value is WrappedMethod {\n  return typeof value === \"function\";\n}\n\nfunction isObject(value: unknown): value is object {\n  return typeof value === \"object\" && Boolean(value);\n}\n\n/**\n * Which methods on a node/edge collection count as writes, and how each\n * counts its intent. Bundled into one value per entity kind (below) rather\n * than passed as separate `methodNames`/`counters` parameters, so a call\n * site can only pick \"the node surface\" or \"the edge surface\" as a unit —\n * it cannot independently mismatch a method-name set against the wrong\n * counter table.\n */\ntype WriteIntentSurface<M extends string> = Readonly<{\n  methodNames: ReadonlySet<string>;\n  counters: Record<M, WriteIntentCounter>;\n}>;\n\nconst NODE_WRITE_SURFACE: WriteIntentSurface<NodeWriteMethodName> = {\n  methodNames: new Set(NODE_WRITE_NAMES),\n  counters: NODE_WRITE_INTENT_COUNTERS,\n};\n\nconst EDGE_WRITE_SURFACE: WriteIntentSurface<EdgeWriteMethodName> = {\n  methodNames: new Set(EDGE_WRITE_NAMES),\n  counters: EDGE_WRITE_INTENT_COUNTERS,\n};\n\n/**\n * Proxies `target`, memoizing the wrapped value for each string-keyed\n * property after first access. `shouldWrap` gates which properties run\n * through `wrap`; everything else (including symbol keys) passes through\n * via `Reflect.get` untouched. Shared by `wrapWriteCollection` (wraps write\n * methods on one collection) and `wrapCollections` (wraps every collection\n * in a kind-keyed map) — both are \"lazily transform and cache one property\n * of an object\" with a different `shouldWrap`/`wrap` pair.\n */\nfunction memoizedProxyGet<T extends object>(\n  target: T,\n  shouldWrap: (property: string) => boolean,\n  wrap: (value: unknown, property: string) => unknown,\n): T {\n  const cache = new Map<string, unknown>();\n\n  return new Proxy(target, {\n    get(proxyTarget, property, receiver) {\n      if (typeof property !== \"string\" || !shouldWrap(property)) {\n        return Reflect.get(proxyTarget, property, receiver);\n      }\n\n      const cached = cache.get(property);\n      if (cached !== undefined) return cached;\n\n      const value = Reflect.get(proxyTarget, property, receiver);\n      const wrapped = wrap(value, property);\n      cache.set(property, wrapped);\n      return wrapped;\n    },\n  });\n}\n\n/**\n * Wraps one node/edge collection so every write method on it (per\n * `surface.methodNames`) fails loud once the recorder is sealed, then counts\n * its intent through `record` on resolution.\n */\nfunction wrapWriteCollection<T extends object, M extends string>(\n  collection: T,\n  kind: string,\n  surface: WriteIntentSurface<M>,\n  record: (kind: string, count: number) => void,\n  assertWritable: () => void,\n): T {\n  return memoizedProxyGet(\n    collection,\n    (property) => surface.methodNames.has(property),\n    (value, property) => {\n      if (!isWrappedMethod(value)) return value;\n\n      const method = property as M;\n      const wrapped: WrappedMethod = async (...args) => {\n        // Reject before the live write: a context retained past its callback\n        // must not persist a row the already-snapshotted receipt cannot count.\n        assertWritable();\n        // Pin the intent count at call time: a caller may mutate a bulk input\n        // array while the write is in flight, and the backend has already\n        // snapshotted the items. Recording still waits for resolution so a\n        // rejected write counts 0.\n        const count = surface.counters[method](args);\n        const result = await Reflect.apply(value, collection, args);\n        record(kind, count);\n        return result;\n      };\n      return wrapped;\n    },\n  );\n}\n\n/**\n * Wraps a kind-keyed collection map (`GraphNodeCollections<G>` /\n * `GraphEdgeCollections<G>`), lazily wrapping each collection with\n * `wrapOne` on first access.\n */\nfunction wrapCollections<T extends object>(\n  collections: T,\n  wrapOne: (collection: object, kind: string) => unknown,\n): T {\n  return memoizedProxyGet(\n    collections,\n    () => true,\n    (collection, kind) =>\n      isObject(collection) ? wrapOne(collection, kind) : collection,\n  );\n}\n\nexport function wrapTransactionCollections<G extends GraphDef>(\n  nodes: GraphNodeCollections<G>,\n  edges: GraphEdgeCollections<G>,\n  recorder: TransactionReceiptRecorder,\n): Readonly<{\n  nodes: GraphNodeCollections<G>;\n  edges: GraphEdgeCollections<G>;\n}> {\n  return {\n    nodes: wrapCollections(nodes, (collection, kind) =>\n      wrapWriteCollection(\n        collection,\n        kind,\n        NODE_WRITE_SURFACE,\n        recorder.recordNode,\n        recorder.assertWritable,\n      ),\n    ),\n    edges: wrapCollections(edges, (collection, kind) =>\n      wrapWriteCollection(\n        collection,\n        kind,\n        EDGE_WRITE_SURFACE,\n        recorder.recordEdge,\n        recorder.assertWritable,\n      ),\n    ),\n  };\n}\n","/**\n * Main Store implementation for TypeGraph.\n *\n * The Store is the primary interface for interacting with a TypeGraph.\n * It coordinates:\n * - Node and edge CRUD operations\n * - Constraint validation\n * - Schema management\n * - Transaction handling\n */\nimport type { z } from \"zod\";\n\nimport {\n  asGraphWriteBackend,\n  asRawBackend,\n  type GraphWriteBackend,\n  type RawBackend,\n} from \"../backend/branded\";\nimport { bindExtra, bindExtraIfReachable } from \"../backend/capabilities/bind\";\nimport type {\n  ENDPOINT_SET_READ,\n  RECORDED_REVISION_ORIGINS,\n  STATEMENT_EXECUTION,\n  UNIQUE_SIDECAR_BATCH,\n} from \"../backend/capabilities/bundle-registry\";\nimport {\n  BATCH_POINT_READ,\n  CONTRIBUTION_HEALTH,\n} from \"../backend/capabilities/bundle-registry\";\nimport {\n  type RecordedTimeSession,\n  requireRecordedTime,\n} from \"../backend/capabilities/recorded-time\";\nimport {\n  isEngineNativeRecordedReadBinding,\n  type RecordedTimeOwnership,\n  resolveRecordedTimeOwnership,\n} from \"../backend/capabilities/recorded-time-ownership\";\nimport {\n  batchPointReadVerdict,\n  type BundleVerdictOf,\n  type ClaimsVerdictThunk,\n  contributionHealthVerdict,\n  createClaimsVerdictThunk,\n  endpointSetReadVerdict,\n  recordedRevisionOriginsVerdict,\n  requireExtras,\n  statementExecutionVerdict,\n  uniqueSidecarBatchVerdict,\n} from \"../backend/capabilities/resolve\";\nimport {\n  type RetriedUnitAttempt,\n  runRetriedUnit,\n} from \"../backend/capabilities/retried-unit\";\nimport {\n  refuseUnfencedClockAllocation,\n  refuseUnfencedOperationalIdentity,\n  resolveWriteFencePlan,\n} from \"../backend/capabilities/write-fence\";\nimport { deriveBackend, projectGraphBackend } from \"../backend/derive-backend\";\nimport {\n  heterogeneousNodeUpsertBatchBindParameterCount,\n  heterogeneousNodeUpsertBatchFitsBindBudget,\n} from \"../backend/heterogeneous-node-upsert-batch\";\nimport {\n  createEdgeRowMapper,\n  createNodeRowMapper,\n  POSTGRES_ROW_MAPPER_CONFIG,\n  SQLITE_ROW_MAPPER_CONFIG,\n} from \"../backend/row-mappers\";\nimport { countSchemaKindRows } from \"../backend/schema-kind-emptiness\";\nimport {\n  type AdapterBackend,\n  type BackendCapabilities,\n  type ContributionDiagnostic,\n  type ContributionProbeResult,\n  type ContributionRebuildResult,\n  type ContributionRebuildScope,\n  type ContributionRepairResult,\n  createTransactionReadBackend,\n  type FindEdgesByHeterogeneousEndpointSetParams,\n  type GraphBackend,\n  runOptionallyInTransaction,\n  type SchemaCommitPreflightBackend,\n  type SchemaVersionRow,\n  type TransactionBackend,\n  type TransactionOptions,\n} from \"../backend/types\";\nimport {\n  type AllNodeTypes,\n  type EdgeKinds,\n  type GraphDef,\n  type GraphIdentityConfig,\n  isKnownKind,\n  type NodeKinds,\n} from \"../core/define-graph\";\nimport {\n  resolveEmbeddingFields,\n  resolveGraphVectorSlots,\n} from \"../core/embedding\";\nimport {\n  createRuntimeKindToken,\n  resolveRuntimeKindInput,\n  resolveRuntimeKindToken,\n  type RuntimeEdgeKind,\n  type RuntimeKindInput,\n  type RuntimeKindSchemaBinding,\n  type RuntimeNodeKind,\n} from \"../core/runtime-kind\";\nimport {\n  asRecordedInstant,\n  createEngineRecordedInstant,\n  type ReadCoordinate,\n  type RecordedInstant,\n  recordedInstantWallTime,\n  resolveReadCoordinate,\n  withRecordedCoordinate,\n} from \"../core/temporal\";\nimport type {\n  AnyEdgeType,\n  EdgeId,\n  KindEntity,\n  NodeId,\n  NodeType,\n} from \"../core/types\";\nimport {\n  ConfigurationError,\n  ContributionRebuildUnsupportedError,\n  EagerMaterializationError,\n  KindNotFoundError,\n  MigrationError,\n  RuntimeKindTokenError,\n  UnsupportedBackendCapabilityError,\n  ValidationError,\n} from \"../errors\";\nimport { validateNodeProps } from \"../errors/validation\";\nimport {\n  buildIncompatibleChangeError,\n  classifyModifications,\n} from \"../graph-extension/classify\";\nimport { IncompatibleChangeError } from \"../graph-extension/errors\";\nimport {\n  type ExtensionEdgeDef,\n  type ExtensionEdgeProperties,\n  type ExtensionNodeDef,\n  type ExtensionObjectSchema,\n  type GraphExtension,\n} from \"../graph-extension/extension-types\";\nimport { mergeGraphExtension } from \"../graph-extension/merge\";\nimport { planRemovals, stripGraphExtension } from \"../graph-extension/remove\";\nimport { refuseEngineNativeRecordedIdentityRead } from \"../identity/historical-sql\";\nimport {\n  ensureIdentitySchemaStorage,\n  identityKindCascadeNeeded,\n  identitySchemaCommitPreflight,\n  inspectAdoptedIdentityStorage,\n} from \"../identity/schema-transition\";\nimport {\n  applyIdentityChangesForContext,\n  assertAffectedIdentityClassesConsistent,\n  createIdentityFacade,\n  createIdentityReadFacade,\n  detachIdentityForNode,\n  foldIdentityForCreatedNodes,\n  type IdentityImportSummary,\n  type IdentityRebuildContext,\n  type IdentityServiceContext,\n  type IdentityTransferAssertion,\n  importIdentityAssertionsIntoTarget,\n  liveNodeKindsSharingIds,\n  loadAssertionsByIds,\n  loadCurrentStructuralClasses,\n  lockIdentityGraph,\n  readIdentityAssertionPageAtTarget,\n  readIdentityAssertionsForInterchange,\n  rebuildIdentityClosureForContext,\n  refKey,\n  removeIdentityKindsForContext,\n  requireNodeValidityEndCompatible,\n  toTransferAssertion,\n  validateIdentityForContext,\n} from \"../identity/service\";\nimport { type IdentityTarget } from \"../identity/sql-target\";\nimport type {\n  IdentityFacade,\n  IdentityNode,\n  IdentityReadFacade,\n} from \"../identity/types\";\nimport { type VectorIndexDeclaration } from \"../indexes/types\";\nimport {\n  META_EDGE_DISJOINT_WITH,\n  META_EDGE_EQUIVALENT_TO,\n  META_EDGE_SAME_AS,\n  META_EDGE_SUB_CLASS_OF,\n} from \"../ontology/constants\";\nimport type { TraversalExpansion } from \"../query/ast\";\nimport {\n  type BatchableQuery,\n  type BatchResults,\n  type CompiledOneStatementRead,\n  createInternalQueryBuilder,\n  executeOneStatementBatch,\n  type InitialQueryBuilder,\n  type OneStatementBatchReads,\n  type OneStatementBatchResults,\n  type QueryCoordinateState,\n} from \"../query/builder\";\nimport type { BatchOnceOptions } from \"../query/builder/one-statement-batch\";\nimport {\n  createEngineRecordedReadBinding,\n  createRecordedReadBinding,\n  createSqlSchema,\n  type RecordedReadBinding,\n  recordedReadSchemaFor,\n  requireExternalRecordedReadSource,\n  requireSqlSchema,\n  type SqlSchema,\n} from \"../query/compiler/schema\";\nimport { withPinnedReadInstant } from \"../query/compiler/temporal\";\nimport { getDialect } from \"../query/dialect\";\nimport type { SqlDialect } from \"../query/dialect/types\";\nimport { type VectorSlot } from \"../query/dialect/vector-strategy\";\nimport { renderSql } from \"../query/sql-fragment\";\nimport { type CompiledRowsSql } from \"../query/sql-intent\";\nimport { buildKindRegistry, type KindRegistry } from \"../registry\";\nimport { canonicalEqual } from \"../schema/canonical\";\nimport {\n  type EvolutionPlan,\n  type EvolutionPlanRequirements,\n  getEvolutionPlanPayload,\n  prepareEvolutionPlan,\n} from \"../schema/evolution-plan\";\nimport {\n  applyDeprecatedKinds,\n  commitNewSchemaVersion,\n  commitNewSchemaVersionIfKindsEmpty,\n  commitNewSchemaVersionWithPreflight,\n  ensureSchema as ensureSchemaImpl,\n  getSchemaChanges,\n  loadActiveSchemaWithBootstrap,\n  loadAndMergeGraphExtensionDocument,\n  loadAndVerifyGraph,\n  parseSerializedSchema,\n  requiresMigration as requiresMigrationImpl,\n  type SchemaManagerOptions,\n  type SchemaValidationResult,\n} from \"../schema/manager\";\nimport { type SchemaDiff } from \"../schema/migration\";\nimport { serializeSchema } from \"../schema/serializer\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { nowIso, validityWindowContainsInstant } from \"../utils/date\";\nimport { generateId } from \"../utils/id\";\nimport { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n  createGraphAlgorithms,\n  type GraphAlgorithms,\n  type InternalGraphAlgorithms,\n} from \"./algorithms\";\nimport { applyResolvedNodeClaims } from \"./claims/resolved-node-claims\";\nimport {\n  type ConstraintFenceViolation,\n  verifyConstraintFences as verifyConstraintFencesImpl,\n} from \"./claims/verify\";\nimport {\n  createEdgeCollectionsProxy,\n  createNodeCollectionsProxy,\n  type EdgeOperations,\n  type NodeOperations,\n} from \"./collection-factory\";\nimport { resolveTemporalReadParams } from \"./collections/temporal-read-params\";\nimport {\n  assertEvolutionOptions,\n  assertEvolutionPlanBaseline,\n  type EvolvedTransactionOptions,\n  type EvolvedTransactionOutcome,\n  type PlanEvolutionOptions,\n  type RefreshSchemaOptions,\n  withAdoptedTransactionScope,\n} from \"./evolution\";\nimport { scopeBackendExecution } from \"./execution-lifetime\";\nimport { repopulateFulltextInTransaction } from \"./fulltext-rebuild\";\nimport { getSearchableFields } from \"./fulltext-sync\";\nimport {\n  createHistoryStoreBackendProjection,\n  type HistoryStoreBackend,\n} from \"./history-store-backend\";\nimport { introspectSchema, type SchemaIntrospection } from \"./introspect\";\nimport {\n  backendSupportsIndexMaterialization,\n  computeIndexSignature,\n  materializeIndexes as materializeIndexesImpl,\n  type MaterializeIndexesOptions,\n  type MaterializeIndexesResult,\n  materializeSystemIndexes as materializeSystemIndexesImpl,\n  type MaterializeSystemIndexesOptions,\n  vectorStatusKey,\n} from \"./materialize-indexes\";\nimport {\n  buildPendingKindRemoval,\n  materializeRemovals as materializeRemovalsImpl,\n  type MaterializeRemovalsOptions,\n  type MaterializeRemovalsResult,\n} from \"./materialize-removals\";\nimport { ensureFocusedStatusTable } from \"./materialize-shared\";\nimport {\n  countNeighbors as countNeighborsImpl,\n  createNeighborCountRead,\n  createNeighborRead,\n  type NeighborReadOptions,\n  type NeighborResult,\n  readNeighbors,\n} from \"./neighbors\";\nimport {\n  type EdgeOperationContext,\n  edgeUpsertDirtyCheck,\n  executeEdgeBulkGetOrCreateByEndpoints,\n  executeEdgeCreate,\n  executeEdgeCreateBatch,\n  executeEdgeCreateNoReturnBatch,\n  executeEdgeDelete,\n  executeEdgeDeleteBatch,\n  executeEdgeFindByEndpoints,\n  executeEdgeGetOrCreateByEndpoints,\n  executeEdgeHardDelete,\n  executeEdgeResolvedMutationSet,\n  executeEdgeUpdate,\n  executeEdgeUpsertUpdateBatch,\n  executeNodeBulkFindByConstraint,\n  executeNodeBulkFindByIndex,\n  executeNodeBulkGetOrCreateByConstraint,\n  executeNodeCreate,\n  executeNodeCreateBatch,\n  executeNodeCreateNoReturnBatch,\n  executeNodeDelete,\n  executeNodeDeleteBatch,\n  executeNodeFindByConstraint,\n  executeNodeGetOrCreateByConstraint,\n  executeNodeHardDelete,\n  executeNodeReplacementBatch,\n  executeNodeResolvedMutationSet,\n  executeNodeSetUpdate,\n  executeNodeUpdate,\n  executeNodeUpsertUpdateBatch,\n  lockSchemaVersionForStoreWrite,\n  type NodeOperationContext,\n  nodeUpsertDirtyCheck,\n  prepareNodeReplacement,\n} from \"./operations\";\nimport {\n  batchRefusalDetails,\n  batchRefusalSuffix,\n  diagnoseFusedSchemaFenceNoRow,\n  resolveBatchWriteVerdict,\n  runInWriteTransaction,\n  withPreAcquiredTransactionSchemaFenceLease,\n  withTransactionSchemaFenceLease,\n  withWriteTransactionSession,\n  type WriteTransactionContext,\n} from \"./operations/write-transaction\";\nimport {\n  advanceRevisionClock,\n  assertCurrentRecordedSchema,\n  assertRecordedCaptureTransactionIsolation,\n  assertRevisionTrackableBackend,\n  createMutationWitness,\n  createRecordedBackend,\n  createRecordedTransactionScope,\n  ensureRevisionOrigin,\n  ensureRevisionOriginsRelation,\n  forceRecordedGraphRevision,\n  lockRecordedGraphWrite,\n  mintsOriginNamespacedAnchor,\n  readRecordedClock,\n  recordedCaptureRequiresCallbackTransactionError,\n  type RecordedFlushInstants,\n  registerRecordedIdentityMutationWitness,\n  resetRevisionOrigin,\n  throwHistoryUnsafeSqlAccess,\n  throwRevisionTrackingUnsafeSqlAccess,\n  withRecordedFlushObserver,\n  withRecordedNodeMutationTarget,\n  withRecordedRelationsPrecondition,\n} from \"./recorded-capture\";\nimport { assertNoRecordedCoordinate } from \"./recorded-coordinate-guard\";\nimport {\n  createRecordedReadService,\n  type RecordedReadService,\n} from \"./recorded-read-service\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport {\n  bindEvolvedTransactionStore,\n  bindTransactionStore,\n  runInTransactionContext,\n  STORE_RUNTIME,\n  type StoreRuntime,\n} from \"./runtime-port\";\nimport { StoreSearch } from \"./search-facade\";\nimport {\n  describeStore,\n  type StoreDescription,\n  type StoreValidationPage,\n  validateStore as validateStoreImpl,\n  type ValidateStoreOptions,\n} from \"./store-analysis\";\nimport {\n  RecordedStoreView,\n  StoreView,\n  type StoreViewCoordinate,\n} from \"./store-view\";\nimport {\n  createSubgraphRead,\n  executeSubgraph,\n  type InternalSubgraphOptions,\n  type SubgraphOptions,\n  type SubgraphProject,\n  type SubgraphRead,\n  type SubgraphResult,\n} from \"./subgraph\";\nimport {\n  createTransactionReceiptRecorder,\n  type TransactionReceiptRecorder,\n  wrapTransactionCollections,\n  wrapTransactionIdentity,\n} from \"./transaction-receipt\";\nimport {\n  type AdapterTransactionContext,\n  AUTO_REFRESH_STATISTICS_ROW_THRESHOLD,\n  type BulkFindEdgesFromParams,\n  type BulkFindEdgesFromResult,\n  type BulkFindEdgesToParams,\n  type BulkFindEdgesToResult,\n  type BulkFindRuntimeEdgesFromParams,\n  type BulkFindRuntimeEdgesFromResult,\n  type BulkOperationHookContext,\n  type DynamicEdgeCollection,\n  type DynamicNodeCollection,\n  type Edge,\n  type EdgeBulkFindEndpointOptions,\n  type GraphEdgeCollections,\n  type GraphEdgeForKinds,\n  type GraphNodeCollections,\n  type GraphNodeReference,\n  type HeterogeneousNodeUpsertInput,\n  type HeterogeneousNodeUpsertResult,\n  type HistoryStoreOptions,\n  type HistoryTransactionContext,\n  type HookContext,\n  type LiveStoreOptions,\n  type MeasurableAdapterTransactionContext,\n  type MeasurableHistoryTransactionContext,\n  type MeasurableTransactionContext,\n  type Node,\n  type OperationHookContext,\n  type QueryHookContext,\n  type QueryOptions,\n  type RecordedHeterogeneousNodeWriteBatch,\n  type RecordedReadStoreOptions,\n  type RecordedRevisionRequest,\n  type RecordedScanOptions,\n  type RecordedScanPage,\n  type RuntimeEdgeCollection,\n  type RuntimeNodeCollection,\n  type ScopedMeasure,\n  type StoreHooks,\n  type StoreOptions,\n  type StoreRef,\n  TRANSACTION_RUNTIME,\n  type TransactionContext,\n  type TransactionOutcome,\n  type UnboundLiveStoreOptions,\n  type WorkingCopyOptions,\n} from \"./types\";\n\ntype StoreSchemaMetadata = Readonly<{\n  schemaVersion: number | undefined;\n  schemaHash: string | undefined;\n}>;\n\nconst UNKNOWN_SCHEMA_METADATA: StoreSchemaMetadata = Object.freeze({\n  schemaVersion: undefined,\n  schemaHash: undefined,\n});\n\ntype CaughtUpVerb =\n  | \"evolve\"\n  | \"materialize\"\n  | \"deprecate\"\n  | \"undeprecate\"\n  | \"remove\"\n  | \"reembed\"\n  | \"repair\"\n  | \"rebuild\";\n\n/** Default page size for the {@link Store.reembedVectorField} re-embed loop. */\nconst DEFAULT_REEMBED_BATCH_SIZE = 200;\n\nconst CAUGHT_UP_VERB_DETAILS: Readonly<\n  Record<CaughtUpVerb, Readonly<{ phrase: string; code: string }>>\n> = {\n  evolve: { phrase: \"evolve\", code: \"EVOLVE_BEFORE_INITIALIZE\" },\n  materialize: {\n    phrase: \"materialize indexes on\",\n    code: \"MATERIALIZE_BEFORE_INITIALIZE\",\n  },\n  remove: { phrase: \"remove kinds on\", code: \"REMOVE_BEFORE_INITIALIZE\" },\n  deprecate: {\n    phrase: \"deprecate kinds on\",\n    code: \"DEPRECATE_BEFORE_INITIALIZE\",\n  },\n  undeprecate: {\n    phrase: \"undeprecate kinds on\",\n    code: \"DEPRECATE_BEFORE_INITIALIZE\",\n  },\n  reembed: {\n    phrase: \"re-embed a vector field on\",\n    code: \"REEMBED_BEFORE_INITIALIZE\",\n  },\n  repair: {\n    phrase: \"repair contributions for\",\n    code: \"REPAIR_CONTRIBUTIONS_BEFORE_INITIALIZE\",\n  },\n  rebuild: {\n    phrase: \"rebuild a contribution for\",\n    code: \"REBUILD_CONTRIBUTION_BEFORE_INITIALIZE\",\n  },\n};\n\nconst ROW_MAPPER_CONFIGS = {\n  postgres: POSTGRES_ROW_MAPPER_CONFIG,\n  sqlite: SQLITE_ROW_MAPPER_CONFIG,\n} satisfies Record<SqlDialect, typeof POSTGRES_ROW_MAPPER_CONFIG>;\n\nfunction rowMapperConfigFor(backend: GraphBackend | TransactionBackend) {\n  return ROW_MAPPER_CONFIGS[backend.dialect];\n}\n\n// ============================================================\n// Store Class\n// ============================================================\n\n/**\n * The Store provides typed access to a TypeGraph database.\n *\n * @example\n * ```typescript\n * const store = createStore(myGraph, backend);\n *\n * // Create nodes using collection API\n * const person = await store.nodes.Person.create({\n *   name: \"Alice\",\n *   email: \"alice@example.com\",\n * });\n *\n * const company = await store.nodes.Company.create({\n *   name: \"Acme\",\n *   industry: \"Technology\",\n * });\n *\n * // Create edges\n * await store.edges.worksAt.create(\n *   { kind: \"Person\", id: person.id },\n *   { kind: \"Company\", id: company.id },\n *   { role: \"Engineer\" }\n * );\n *\n * // Query with the fluent API\n * const results = await store.query()\n *   .from(\"Person\", \"p\")\n *   .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n *   .select((ctx) => ctx.p)\n *   .execute();\n * ```\n */\n\n/**\n * Optional embedder for {@link Store.reembedVectorField}. Receives a batch of\n * the kind's nodes and returns a map of `nodeId → new embedding vector` (omit\n * an id to leave that node without an embedding). Called once per page; the\n * page size is `batchSize`.\n */\nexport type ReembedFunction = (\n  nodes: readonly Node[],\n) =>\n  | Promise<ReadonlyMap<string, readonly number[]>>\n  | ReadonlyMap<string, readonly number[]>;\n\n/** Options for {@link Store.reembedVectorField}. */\nexport type ReembedVectorFieldOptions = Readonly<{\n  /**\n   * When supplied, drives a batched re-embed loop after recreating storage:\n   * pages the kind's nodes, calls `embed(batch)`, and upserts the returned\n   * vectors. When omitted, storage is recreated empty and the caller\n   * re-embeds via normal `update()` / `upsertEmbedding` writes.\n   */\n  embed?: ReembedFunction;\n  /** Re-embed page size. Default 200. */\n  batchSize?: number;\n}>;\n\n/** Result of {@link Store.reembedVectorField}. */\nexport type ReembedVectorFieldResult = Readonly<{\n  /** Whether the per-field storage was dropped and recreated. */\n  recreated: boolean;\n  /** Number of nodes whose embedding was re-written (0 without `embed`). */\n  reembedded: number;\n}>;\n\n/** Options for {@link Store.rebuildContribution}. */\nexport type RebuildContributionOptions = Readonly<{\n  /**\n   * Page size for the content reconstruction pass. Default 500.\n   *\n   * Every page runs inside the rebuild's single transaction, so this\n   * trades statement count against per-statement size rather than\n   * bounding how long the transaction is held — that is set by the graph.\n   */\n  pageSize?: number;\n}>;\n\n/** One place for the hooks' error normalization. */\nfunction asError(error: unknown): Error {\n  return error instanceof Error ? error : new Error(String(error));\n}\n\n/** The `(hook context, operation body)` wrapper shape operation contexts carry. */\ntype OperationHookRunner = <T>(\n  ctx: OperationHookContext,\n  fn: () => Promise<T>,\n  didWrite?: (result: T) => boolean,\n) => Promise<T>;\n\ntype BulkOperationHookRunner = <T extends Readonly<{ affectedCount: number }>>(\n  ctx: BulkOperationHookContext,\n  fn: () => Promise<T>,\n) => Promise<T>;\n\n/** A committed-inside-the-transaction operation awaiting the outer COMMIT. */\ntype PendingOperationOutcome =\n  | Readonly<{\n      type: \"operation\";\n      ctx: OperationHookContext;\n      durationMs: number;\n      outcome: \"written\" | \"unchanged\" | \"unknown\";\n    }>\n  | Readonly<{\n      type: \"bulkOperation\";\n      ctx: BulkOperationHookContext;\n      affectedCount: number;\n      durationMs: number;\n    }>;\n\ntype TransactionRunResult<T> = Readonly<{\n  result: T;\n  recordedByGraph: RecordedFlushInstants | undefined;\n  /** The committed attempt's own receipt recorder, when one was requested. */\n  recorder: TransactionReceiptRecorder | undefined;\n  /**\n   * The committed attempt's own buffered operation outcomes, awaiting the\n   * `onOperationEnd`/`onBulkOperationEnd` flush. Returned rather than\n   * flushed inside the attempt so that flush runs OUTSIDE `runRetriedUnit`:\n   * a hook it calls is user code that can throw for reasons that have\n   * nothing to do with the transaction, and by the time this value exists\n   * the backend has already committed — a throwing hook must propagate once,\n   * never be mistaken for a conflict and replay a transaction that already\n   * durably succeeded.\n   */\n  pending: readonly PendingOperationOutcome[];\n}>;\n\n/**\n * The flush result for a `withRecordedTransaction` on a store without history\n * capture: no recorded rows were closed, so no graph maps to an instant. Shared\n * (rather than allocated per call) — a `ReadonlyMap` is never mutated.\n */\nconst EMPTY_RECORDED_FLUSH_INSTANTS: RecordedFlushInstants = new Map();\n\nfunction transactionOutcome<T>(\n  result: T,\n  recorder: TransactionReceiptRecorder,\n  recordedByGraph: RecordedFlushInstants | undefined,\n  graphId: string,\n): TransactionOutcome<T> {\n  const recorded = recordedByGraph?.get(graphId);\n  return {\n    result,\n    receipt: recorder.snapshot(\n      recorded === undefined ? undefined : asRecordedInstant(recorded),\n    ),\n  };\n}\n\n/** Clones an internal context without evaluating accessor properties. */\nfunction overlayPropertyDescriptors<\n  TBase extends object,\n  TOverlay extends object,\n>(base: TBase, overlay: TOverlay): TBase & TOverlay {\n  return Object.defineProperties(Object.create(Reflect.getPrototypeOf(base)), {\n    ...Object.getOwnPropertyDescriptors(base),\n    ...Object.getOwnPropertyDescriptors(overlay),\n  }) as TBase & TOverlay;\n}\n\n/** Keeps suppressed/JavaScript raw-SQL access fail-loud without advertising it. */\nfunction defineUnavailableSqlGuard(context: object, guard: () => never): void {\n  Object.defineProperty(context, \"sql\", {\n    configurable: false,\n    enumerable: true,\n    get: guard,\n  });\n}\n\n/**\n * The identity surface a store carries, present only when the graph declared\n * `identity: { ... }`. Conditional *presence* (not a `never`-typed property) is\n * the encoding used everywhere identity is exposed — `tx.identity` and the\n * read-only views included — so an identity-disabled graph simply has no\n * `identity` member to reach for.\n */\ntype StoreIdentityAccess<G extends GraphDef> =\n  G[\"identity\"] extends GraphIdentityConfig ?\n    Readonly<{ identity: IdentityFacade<G> }>\n  : Readonly<Record<never, never>>;\n\n/** The same conditional presence for the read-only pinned views. */\nexport type ViewIdentityAccess<G extends GraphDef> =\n  G[\"identity\"] extends GraphIdentityConfig ?\n    Readonly<{ identity: IdentityReadFacade<G> }>\n  : Readonly<Record<never, never>>;\n\nexport type NodeCollectionLookup = <const K extends string>(\n  kind: K,\n) => DynamicNodeCollection<K> | undefined;\n\nexport interface RequiredNodeCollectionLookup {\n  <T extends RuntimeNodeKind>(token: T): RuntimeNodeCollection<T>;\n  <const K extends string>(kind: K): DynamicNodeCollection<K>;\n}\n\nexport interface EdgeCollectionLookup<G extends GraphDef = GraphDef> {\n  <K extends EdgeKinds<G>>(\n    kind: K,\n  ): DynamicEdgeCollection<G[\"edges\"][K][\"type\"]> | undefined;\n  (kind: string): DynamicEdgeCollection | undefined;\n}\n\nexport interface RequiredEdgeCollectionLookup<G extends GraphDef = GraphDef> {\n  <T extends RuntimeEdgeKind>(token: T): RuntimeEdgeCollection<T>;\n  <K extends EdgeKinds<G>>(\n    kind: K,\n  ): DynamicEdgeCollection<G[\"edges\"][K][\"type\"]>;\n  (kind: string): DynamicEdgeCollection;\n}\n\ntype CheckedReadScopeBoundary<G extends GraphDef> = Readonly<{\n  query?: () => InitialQueryBuilder<G, \"open\">;\n}>;\n\n/** Read scope whose fluent-query executions all verify one schema version. */\nexport type CheckedReadScope<G extends GraphDef> = CheckedReadScopeBoundary<G> &\n  Required<Pick<CheckedReadScopeBoundary<G>, \"query\">>;\n\ntype StoreCore<G extends GraphDef> = Readonly<{\n  [STORE_RUNTIME]: StoreRuntime<G>;\n  graph: G;\n  graphId: string;\n  capabilities: BackendCapabilities;\n  registry: KindRegistry;\n  historyEnabled: boolean;\n  revisionTrackingEnabled: boolean;\n  revisionSchema: SqlSchema;\n  recordedReadBound: boolean;\n  recordedTimeOwnership: RecordedTimeOwnership;\n  workingCopyOptions: WorkingCopyOptions;\n  nodes: GraphNodeCollections<G>;\n  edges: GraphEdgeCollections<G>;\n  algorithms: GraphAlgorithms<G>;\n  search: StoreSearch<G>;\n  runtimeNodeKind: <const K extends string, const D extends ExtensionNodeDef>(\n    kind: K,\n    definition: D,\n  ) => RuntimeNodeKind<K, ExtensionObjectSchema<D[\"properties\"]>>;\n  runtimeEdgeKind: <const K extends string, const D extends ExtensionEdgeDef>(\n    kind: K,\n    definition: D,\n  ) => RuntimeEdgeKind<K, ExtensionObjectSchema<ExtensionEdgeProperties<D>>>;\n  getNodeCollection: NodeCollectionLookup;\n  getNodeCollectionOrThrow: RequiredNodeCollectionLookup;\n  getEdgeCollection: EdgeCollectionLookup<G>;\n  getEdgeCollectionOrThrow: RequiredEdgeCollectionLookup<G>;\n  getNodePropsSchema: (kind: string) => z.ZodObject<z.ZodRawShape> | undefined;\n  getNodePropsSchemaOrThrow: (kind: string) => z.ZodObject<z.ZodRawShape>;\n  getEdgePropsSchema: (kind: string) => z.ZodObject<z.ZodRawShape> | undefined;\n  getEdgePropsSchemaOrThrow: (kind: string) => z.ZodObject<z.ZodRawShape>;\n  introspect: () => SchemaIntrospection;\n  /** Describe the schema and current population with bounded aggregate statements. */\n  describe: () => Promise<StoreDescription>;\n  /** Page declared-schema violations without treating undeclared fields as invalid. */\n  validateStore: (\n    options: ValidateStoreOptions,\n  ) => Promise<StoreValidationPage>;\n  schemaChanges: () => Promise<SchemaDiff | undefined>;\n  requiresMigration: () => Promise<boolean>;\n  query: () => InitialQueryBuilder<G, \"open\">;\n  withCheckedReads?: <T>(\n    expectedSchemaVersion: number | undefined,\n    fn: (reads: CheckedReadScope<G>) => Promise<T>,\n  ) => Promise<T>;\n  asOf: (asOf: string) => StoreView<G>;\n  asOfRecorded: (recordedAsOf: RecordedInstant) => RecordedStoreView<G>;\n  recordedNow: () => Promise<RecordedInstant | undefined>;\n  revisionNow: () => Promise<RecordedInstant | undefined>;\n  revisionOriginNow: () => Promise<string>;\n  view: (coordinate: StoreViewCoordinate) => StoreView<G>;\n  snapshot: () => StoreView<G>;\n  batch: <\n    const Queries extends readonly [\n      BatchableQuery<unknown>,\n      BatchableQuery<unknown>,\n      ...BatchableQuery<unknown>[],\n    ],\n  >(\n    ...queries: Queries\n  ) => Promise<BatchResults<Queries>>;\n  batchOnce?: <const Queries extends OneStatementBatchReads>(\n    build: (read: BatchReadBuilder<G>) => Queries,\n    options?: BatchOnceOptions,\n  ) => Promise<OneStatementBatchResults<Queries>>;\n  neighbors?: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: NeighborReadOptions<G, K>,\n  ) => Promise<readonly NeighborResult<G, K>[]>;\n  countNeighbors?: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n  ) => Promise<number>;\n  bulkFindEdgesFrom: <const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesFromParams<G, K>,\n    options?: EdgeBulkFindEndpointOptions,\n  ) => Promise<readonly BulkFindEdgesFromResult<G, K>[]>;\n  bulkFindEdgesTo: <const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesToParams<G, K>,\n    options?: EdgeBulkFindEndpointOptions,\n  ) => Promise<readonly BulkFindEdgesToResult<G, K>[]>;\n  bulkFindRuntimeEdgesFrom: <\n    NT extends RuntimeNodeKind,\n    ET extends RuntimeEdgeKind,\n  >(\n    params: BulkFindRuntimeEdgesFromParams<NT, ET>,\n    options?: EdgeBulkFindEndpointOptions,\n  ) => Promise<readonly BulkFindRuntimeEdgesFromResult<NT, ET>[]>;\n  subgraph: <\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: SubgraphOptions<G, EK, NK, P>,\n  ) => Promise<SubgraphResult<G, NK, EK, P>>;\n  clear: () => Promise<void>;\n  refreshStatistics: () => Promise<void>;\n  materializeIndexes: (\n    options?: MaterializeIndexesOptions,\n  ) => Promise<MaterializeIndexesResult>;\n  materializeSystemIndexes: (\n    options?: MaterializeSystemIndexesOptions,\n  ) => Promise<MaterializeIndexesResult>;\n  reembedVectorField: (\n    kind: string,\n    fieldPath: string,\n    options?: ReembedVectorFieldOptions,\n  ) => Promise<ReembedVectorFieldResult>;\n  verifyContributions: () => Promise<readonly ContributionDiagnostic[]>;\n  verifyConstraintFences: () => Promise<readonly ConstraintFenceViolation[]>;\n  repairContributions: () => Promise<ContributionRepairResult>;\n  probeContributions: () => Promise<ContributionProbeResult>;\n  rebuildContribution: (\n    scope: ContributionRebuildScope,\n    options?: RebuildContributionOptions,\n  ) => Promise<ContributionRebuildResult>;\n  materializeRemovals: (\n    options?: MaterializeRemovalsOptions,\n  ) => Promise<MaterializeRemovalsResult>;\n  close: () => Promise<void>;\n}> &\n  StoreIdentityAccess<G>;\n\n/**\n * Options for {@link Store.transaction} and {@link Store.transactionWithReceipt}.\n * `retry` is TypeGraph's own option: it is read here and never forwarded to\n * the backend, which only ever sees the {@link TransactionOptions} fields.\n *\n * Without `retry`, the callback runs once; a transaction conflict the backend\n * reports (a serialization failure or deadlock) surfaces as\n * `TransactionConflictError` with `attempts: 1` instead of the raw driver\n * error. With `retry`, such a conflict re-runs the WHOLE callback from the\n * top — up to `attempts` times total — so the callback must tolerate being\n * invoked more than once: await all of its own work before returning, read\n * and write only values it creates fresh on each call (never something a\n * previous, rolled-back try left in memory), and perform no effect outside\n * its own transaction. Every hook the callback's operations fire carries the\n * 1-based attempt number that produced it; a rolled-back attempt's completed\n * operations report no `onOperationEnd` and no `onError` of their own —\n * only the attempt that actually commits (or the last one, once `attempts`\n * is exhausted) is reported.\n */\nexport type StoreTransactionOptions = TransactionOptions &\n  Readonly<{\n    /**\n     * Opts the callback into replay on a transaction conflict. The total\n     * number of tries, including the first. Exhausting it throws\n     * `TransactionConflictError`.\n     */\n    retry?: Readonly<{ attempts: number }>;\n  }>;\n\ntype StoreTransactions<G extends GraphDef> = Readonly<{\n  transaction: <T>(\n    fn: (tx: TransactionContext<G>) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<T>;\n  transactionWithReceipt: <T>(\n    fn: (tx: MeasurableTransactionContext<G>) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<TransactionOutcome<T>>;\n}>;\n\n/** Builds cold reads that {@link Store.batchOnce} can compose in one statement. */\nexport type BatchReadBuilder<G extends GraphDef> = Readonly<{\n  neighbors: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: NeighborReadOptions<G, K>,\n  ) => CompiledOneStatementRead<readonly NeighborResult<G, K>[]>;\n  countNeighbors: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n  ) => CompiledOneStatementRead<number>;\n  subgraph: <\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: SubgraphOptions<G, EK, NK, P>,\n  ) => CompiledOneStatementRead<SubgraphResult<G, NK, EK, P>>;\n}>;\n\ntype TransactionReadMethods<G extends GraphDef> = Readonly<{\n  query: () => InitialQueryBuilder<G, \"open\">;\n  describe: () => Promise<StoreDescription>;\n  validateStore: (\n    options: ValidateStoreOptions,\n  ) => Promise<StoreValidationPage>;\n  batchOnce: <const Queries extends OneStatementBatchReads>(\n    build: (read: BatchReadBuilder<G>) => Queries,\n    options?: BatchOnceOptions,\n  ) => Promise<OneStatementBatchResults<Queries>>;\n  neighbors: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: NeighborReadOptions<G, K>,\n  ) => Promise<readonly NeighborResult<G, K>[]>;\n  countNeighbors: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n  ) => Promise<number>;\n  subgraph: <\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: SubgraphOptions<G, EK, NK, P>,\n  ) => Promise<SubgraphResult<G, NK, EK, P>>;\n}>;\n\ntype AddedStoreReadsBoundary<G extends GraphDef> = Readonly<{\n  withCheckedReads?: <T>(\n    expectedSchemaVersion: number | undefined,\n    fn: (reads: CheckedReadScope<G>) => Promise<T>,\n  ) => Promise<T>;\n  batchOnce?: <const Queries extends OneStatementBatchReads>(\n    build: (read: BatchReadBuilder<G>) => Queries,\n    options?: BatchOnceOptions,\n  ) => Promise<OneStatementBatchResults<Queries>>;\n  neighbors?: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: NeighborReadOptions<G, K>,\n  ) => Promise<readonly NeighborResult<G, K>[]>;\n  countNeighbors?: <const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n  ) => Promise<number>;\n}>;\n\ntype AddedStoreReadKey = keyof AddedStoreReadsBoundary<GraphDef>;\n\ntype AddedStoreReads<G extends GraphDef> = AddedStoreReadsBoundary<G> &\n  Required<Pick<AddedStoreReadsBoundary<G>, AddedStoreReadKey>>;\n\ntype ResolvedStoreCore<G extends GraphDef> = StoreCore<G> & AddedStoreReads<G>;\n\n/** Schema planning, reconciliation, and lifecycle operations shared by Stores. */\nexport interface StoreEvolution<\n  G extends GraphDef,\n  TStore extends StoreCore<G>,\n> {\n  /**\n   * Prepares an immutable plan without acquiring a schema write fence.\n   * The default source reads the active schema; cached planning reuses this Store's snapshot.\n   * Apply the module-issued token through a compatible AdapterStore's withEvolvedTransaction().\n   */\n  readonly planEvolution: (\n    extension: GraphExtension,\n    options?: PlanEvolutionOptions,\n  ) => Promise<EvolutionPlan>;\n  /**\n   * Reconciles this Store with committed schema metadata without writes or provisioning.\n   * Call after outer commit. A cache matching minVersion skips SQL; otherwise a read\n   * accepts that version or newer. Updates ref when supplied and returns the reconciled Store.\n   */\n  readonly refreshSchema: <TRefStore extends StoreCore<G> = TStore>(\n    options?: RefreshSchemaOptions<\n      TStore extends TRefStore ? TRefStore : never\n    >,\n  ) => Promise<TStore>;\n\n  /** Commits an extension in a TypeGraph-owned transaction and returns the evolved Store. */\n  readonly evolve: <TRefStore extends StoreCore<G> = TStore>(\n    extension: GraphExtension,\n    options?: Readonly<{\n      ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n      eager?: MaterializeIndexesOptions;\n    }>,\n  ) => Promise<TStore>;\n  /** Marks kinds deprecated for introspection without restricting reads or writes; returns the updated Store. */\n  readonly deprecateKinds: <TRefStore extends StoreCore<G> = TStore>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n    }>,\n  ) => Promise<TStore>;\n  /** Clears kind deprecation markers and returns the updated Store. */\n  readonly undeprecateKinds: <TRefStore extends StoreCore<G> = TStore>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n    }>,\n  ) => Promise<TStore>;\n  /** Removes runtime kinds from the schema, queues physical cleanup, and returns the updated Store. */\n  readonly removeKinds: <TRefStore extends StoreCore<G> = TStore>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n      eager?: MaterializeRemovalsOptions;\n    }>,\n  ) => Promise<TStore>;\n}\n\nfunction syncStoreReplacementRef<\n  G extends GraphDef,\n  TRefStore extends StoreCore<G>,\n>(ref: StoreRef<TRefStore> | undefined, replacement: StoreCore<G>): void {\n  if (ref === undefined) return;\n  // StoreEvolution admits only refs whose value is a supertype of the returned\n  // Store flavor. Runtime implementations use one broader class for every\n  // overload, so the compiler cannot recover that public conditional here.\n  ref.current = replacement as unknown as TRefStore;\n}\n\n/**\n * The default TypeGraph Store contract. It contains the complete graph API and\n * graph-owned transactions while keeping adapter-native handles, backend\n * internals, and caller-owned transaction adoption out of the public surface.\n */\nexport type Store<G extends GraphDef> = ResolvedStoreCore<G> &\n  StoreTransactions<G> &\n  StoreEvolution<G, Store<G>>;\n\n/**\n * An opaque, in-memory snapshot of a store's reconciled schema: the merged\n * compile-time + runtime-committed graph plus the committed schema version and\n * hash it reflects. Produced by {@link AdapterStore.reconciledSchema} after a\n * verified open, cached once per isolate/process, and handed to\n * {@link createAdapterStore} via `{ reconciled }` (or used implicitly by\n * {@link AdapterStore.withBackend}) to build request-scoped stores against\n * fresh connections with **zero** database round-trips. Reads and writes are\n * validated against the reconciled graph, so runtime-committed kinds seen at\n * the reconcile are honored without re-querying.\n *\n * Treat it as opaque and immutable — do not construct or mutate it. Its\n * `version` is the value to compare against {@link getCommittedSchemaVersion}\n * to detect a schema commit from another process and refresh the snapshot.\n */\nexport type ReconciledSchema<G extends GraphDef> = Readonly<{\n  graph: G;\n  version: number | undefined;\n  hash: string | undefined;\n}>;\n\n/** Construction option carrying a cached {@link ReconciledSchema}. */\ntype ReconciledOption<G extends GraphDef> = Readonly<{\n  reconciled?: ReconciledSchema<G>;\n}>;\n\n/**\n * The reconciliation surface shared by every adapter store flavor: read the\n * cached {@link ReconciledSchema} and rebind to a fresh connection with no\n * verify round-trip. `Self` is the receiver's own surface so `withBackend`\n * preserves the store flavor (live / history / recorded-read).\n *\n * Declared as an `interface` (not a `type`): the surface aliases intersect it\n * with `Self` bound to themselves, which a `type` alias rejects as a circular\n * self-reference (TS2456) but an interface resolves lazily — the same idiom as\n * {@link StoreEvolution}.\n */\ninterface AdapterStoreReconciliation<\n  G extends GraphDef,\n  TNativeTransaction,\n  Self,\n> {\n  /**\n   * An opaque snapshot of this store's reconciled schema. Cache it after a\n   * verified open and pass it to {@link createAdapterStore} `{ reconciled }`\n   * to build per-request stores with zero database round-trips.\n   */\n  readonly reconciledSchema: ReconciledSchema<G>;\n  /**\n   * Build an equivalent store bound to a fresh backend/connection, reusing\n   * this store's already-reconciled schema — no verify round-trip. The\n   * per-request primitive for serverless deployments that open a new\n   * connection per request; the returned store validates writes against the\n   * same reconciled graph as the receiver.\n   */\n  readonly withBackend: (backend: AdapterBackend<TNativeTransaction>) => Self;\n}\n\n/**\n * A Store with explicit adapter interoperability. Adapter entrypoints return\n * this surface so native transaction handles remain precisely typed without\n * leaking into the default Store contract.\n */\nexport type AdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n> = ResolvedStoreCore<G> &\n  StoreEvolution<G, AdapterStore<G, TNativeTransaction>> &\n  AdapterStoreTransactions<G, TNativeTransaction> &\n  AdapterStoreReconciliation<\n    G,\n    TNativeTransaction,\n    AdapterStore<G, TNativeTransaction>\n  > &\n  Readonly<{ backend: GraphBackend }>;\n\ntype AdapterStoreTransactions<\n  G extends GraphDef,\n  TNativeTransaction,\n> = Readonly<{\n  transaction: <T>(\n    fn: (tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<T>;\n  transactionWithReceipt: <T>(\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<TransactionOutcome<T>>;\n  withTransaction: (\n    externalTransaction: TNativeTransaction,\n  ) => AdapterTransactionContext<G, TNativeTransaction>;\n  withEvolvedTransaction: <T>(\n    externalTransaction: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: EvolvedTransactionOptions,\n  ) => Promise<EvolvedTransactionOutcome<T>>;\n  withRecordedTransaction: <T>(\n    externalTransaction: TNativeTransaction,\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n  ) => Promise<TransactionOutcome<T>>;\n}>;\n\nasync function commitEvolvedSchemaWhenRequiredKindsAreEmpty<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  currentVersion: number,\n  classification: ReturnType<typeof classifyModifications>,\n  storedSchema: SerializedSchema,\n): Promise<SchemaVersionRow> {\n  const result = await commitNewSchemaVersionIfKindsEmpty(\n    backend,\n    graph,\n    currentVersion,\n    classification.requireEmpty.map((entry) => ({\n      entity: entry.entity,\n      kind: entry.kindName,\n      rows: \"nonDeleted\" as const,\n    })),\n    storedSchema,\n  );\n  if (result.status === \"committed\") return result.row;\n\n  const populatedKeys = new Set(\n    result.kinds.map((entry) => `${entry.entity}:${entry.kind}`),\n  );\n  const nonEmpty = new Set(\n    classification.requireEmpty.filter((entry) =>\n      populatedKeys.has(`${entry.entity}:${entry.kindName}`),\n    ),\n  );\n  const error = buildIncompatibleChangeError(\n    classification,\n    nonEmpty,\n    graph.id,\n  );\n  if (error !== undefined) throw error;\n\n  throw new ConfigurationError(\n    \"Schema emptiness guard reported populated kinds that were not part of \" +\n      \"the compatibility classification.\",\n    {\n      graphId: graph.id,\n      populatedKinds: result.kinds.map((entry) => entry.kind),\n    },\n  );\n}\n\nasync function assertEvolvedSchemaRequiredKindsEmpty(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  classification: ReturnType<typeof classifyModifications>,\n): Promise<void> {\n  const counts = await Promise.all(\n    classification.requireEmpty.map(async (entry) => ({\n      entry,\n      count: await countSchemaKindRows(backend, graphId, {\n        entity: entry.entity,\n        kind: entry.kindName,\n        rows: \"nonDeleted\",\n      }),\n    })),\n  );\n  const nonEmpty = new Set(\n    counts.filter(({ count }) => count > 0).map(({ entry }) => entry),\n  );\n  const error = buildIncompatibleChangeError(classification, nonEmpty, graphId);\n  if (error !== undefined) throw error;\n}\n\nconst IDENTITY_FACADES = new WeakMap<object, unknown>();\n\n/**\n * Keeps a live upsert patch to exactly the keys the caller supplied, while\n * retaining field-level Zod normalization from the complete create parse.\n * Defaults only exist in `parsedCreateProps` because a caller omitted a key,\n * so they cannot leak into the live-row merge.\n */\nfunction callerSuppliedParsedNodeProps(\n  inputProps: Readonly<Record<string, unknown>>,\n  parsedCreateProps: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n  const updateProps = createDataKeyedBag<unknown>();\n  for (const property of Object.keys(inputProps)) {\n    if (hasOwnKey(parsedCreateProps, property)) {\n      updateProps[property] = parsedCreateProps[property];\n    }\n  }\n  return updateProps;\n}\n\nclass StoreImplementation<G extends GraphDef, TNativeTransaction = unknown> {\n  readonly [STORE_RUNTIME]: StoreRuntime<G>;\n  readonly #graph: G;\n  #evolutionPlanningSnapshot:\n    | Readonly<{\n        activeRow: SchemaVersionRow;\n        storedSchema: SerializedSchema;\n        baseline: G;\n      }>\n    | undefined;\n  /**\n   * Bare backend for DDL, vector-storage, and bulk-materialization work that must\n   * bypass recorded capture. Graph-entity writes use `#backend` instead.\n   */\n  readonly #baseBackend: RawBackend;\n  readonly #backend: GraphWriteBackend;\n  /**\n   * The `claims` bundle's memoized, at-most-once verdict thunk (ruling B7\n   * refinement 2), minted from `#backend` — the same object every claimed\n   * write actually executes through — once, here, and threaded into every\n   * node/edge operation context this Store builds. Never resolved eagerly:\n   * only the thunk's own first call may reach the bidirectional cross-check's\n   * throw.\n   */\n  readonly #claimsVerdict: ClaimsVerdictThunk;\n  /**\n   * Resolved EAGERLY, once, immediately after `#claimsVerdict` — unlike\n   * `claims`, no pilot bundle below has a `crossCheck`, so `resolveBundle`\n   * cannot throw on construction and the thunk's lazy-resolution rationale\n   * does not apply (ruling B8 spec item 2). `batchPointRead` and\n   * `uniqueSidecarBatch` resolve against `#backend`, the object every graph\n   * write and read actually executes through.\n   */\n  readonly #batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  readonly #endpointSetRead: BundleVerdictOf<typeof ENDPOINT_SET_READ>;\n  readonly #uniqueSidecarBatch: BundleVerdictOf<typeof UNIQUE_SIDECAR_BATCH>;\n  /** Root verdict minted once; transaction targets bind its member separately. */\n  readonly #statementExecution: BundleVerdictOf<typeof STATEMENT_EXECUTION>;\n  /**\n   * The contribution-health methods and `ensureRevisionOrigin` read\n   * `#baseBackend`, not `#backend` (recorded capture never wraps them), so\n   * their verdicts are resolved against `#baseBackend` too.\n   */\n  readonly #contributionHealth: BundleVerdictOf<typeof CONTRIBUTION_HEALTH>;\n  readonly #recordedRevisionOrigins: BundleVerdictOf<\n    typeof RECORDED_REVISION_ORIGINS\n  >;\n  readonly #adapterBackend: AdapterBackend<TNativeTransaction> | undefined;\n  readonly #recordedTimeOwnership: RecordedTimeOwnership;\n  readonly #requestedHistory: boolean;\n  readonly #captureEnabled: boolean;\n  readonly #engineNativeHistory: boolean;\n  readonly #revisionTrackingEnabled: boolean;\n  readonly #recordedReadBinding: RecordedReadBinding | undefined;\n  readonly #registry: KindRegistry;\n  readonly #hooks: StoreHooks;\n  readonly #schema: StoreOptions[\"schema\"];\n  readonly #recordedReads: RecordedReadService;\n  #schemaMetadata: StoreSchemaMetadata;\n  readonly #runtimeKindOwner = Object.freeze({});\n  readonly #defaultTraversalExpansion: TraversalExpansion;\n  // Stored verbatim so `evolve()` can construct the next Store with\n  // identical options. Reconstructing from the individual private\n  // fields would silently drop any future StoreOptions field a\n  // maintainer adds without also threading it through evolve.\n  readonly #options: StoreOptions | undefined;\n  #nodeCollections: GraphNodeCollections<G> | undefined;\n  #edgeCollections: GraphEdgeCollections<G> | undefined;\n  #algorithms: GraphAlgorithms<G> | undefined;\n  #search: StoreSearch<G> | undefined;\n  constructor(\n    graph: G,\n    backend: GraphBackend,\n    options?: StoreOptions,\n    schemaMetadata?: StoreSchemaMetadata,\n    adapterBackend?: AdapterBackend<TNativeTransaction>,\n  ) {\n    this.#graph = graph;\n    const statementExecution = statementExecutionVerdict(backend);\n    if (\n      graph.identity !== undefined &&\n      (!backend.capabilities.execution.interactiveTransactions ||\n        !statementExecution.supported)\n    ) {\n      const identityVerdict = resolveBatchWriteVerdict(backend, {\n        needs: \"identity\",\n      });\n      throw new ConfigurationError(\n        \"Operational Identity requires an atomic transactional backend with statement execution support.\" +\n          batchRefusalSuffix(identityVerdict),\n        {\n          code: \"IDENTITY_REQUIRES_ATOMIC_BACKEND\",\n          interactiveTransactions:\n            backend.capabilities.execution.interactiveTransactions,\n          statementExecution: statementExecution.supported,\n          ...batchRefusalDetails(identityVerdict),\n        },\n        {\n          suggestion:\n            \"Use a transactional SQLite or PostgreSQL driver; Cloudflare D1 and neon-http cannot host identity closure maintenance.\",\n        },\n      );\n    }\n    // A separate throw, not a widened condition on the gate above, so the\n    // message can be the migration guide (OQ-B) rather than a generic\n    // \"atomic backend\" refusal.\n    if (graph.identity !== undefined) {\n      const identityFencePlan = resolveWriteFencePlan(backend);\n      if (identityFencePlan.kind === \"unfenced\") {\n        refuseUnfencedOperationalIdentity(backend.dialect);\n      }\n    }\n    this.#baseBackend = asRawBackend(backend);\n    this.#adapterBackend = adapterBackend;\n    this.#recordedTimeOwnership = resolveRecordedTimeOwnership(backend);\n    const requestedHistory = options?.history === true;\n    const requestedRevisionTracking = options?.revisionTracking === true;\n    if (\n      this.#recordedTimeOwnership === \"engine-native\" &&\n      requestedRevisionTracking\n    ) {\n      // Engine-native has no TypeGraph clock for `revisionTracking: true` to\n      // advance — the engine's own revision IS the tracking, and it only\n      // ever surfaces through `history: true`, whether or not `history` was\n      // also requested. Refusing only the without-history combination once\n      // let `{ history: true, revisionTracking: true }` construct\n      // successfully while silently forcing `revisionTrackingEnabled` back\n      // to false — an accepted option this backend cannot honor at all, not\n      // one it can honor only some of the time.\n      throw new ConfigurationError(\n        \"revisionTracking: true is not supported under engine-native recorded time.\",\n        { code: \"ENGINE_NATIVE_REVISION_TRACKING_UNSUPPORTED\" },\n        {\n          suggestion:\n            \"Pass { history: true } instead — the engine's own recordedTime.revisionNow is the only revision this backend can track, and it is available under history: true whether or not revisionTracking is also requested.\",\n        },\n      );\n    }\n    if (\n      this.#recordedTimeOwnership === \"engine-native\" &&\n      options?.recordedRead !== undefined\n    ) {\n      // An externally bound recorded relation is a TypeGraph-relations\n      // concept: engine-native has no recorded relation of its own for a\n      // caller to populate, and its own recorded reads are sourced from\n      // `recordedTime.source` instead.\n      throw new ConfigurationError(\n        \"recordedRead is not supported under engine-native recorded time.\",\n        { code: \"ENGINE_NATIVE_RECORDED_READ_UNSUPPORTED\" },\n        {\n          suggestion:\n            \"Use { history: true } to read this backend's own engine-native recorded time, or omit recordedRead.\",\n        },\n      );\n    }\n    // `#requestedHistory` is the caller's own request — `options.history ===\n    // true` — regardless of which ownership form honors it; the public\n    // `historyEnabled` getter answers this, matching `HistoryStore<G>`'s\n    // static `historyEnabled: true` for either ownership. `#captureEnabled`\n    // means TypeGraph itself performs capture — recorded relations, a\n    // TypeGraph clock, the write-fence/schema-lock machinery capture needs —\n    // and stays scoped to `typegraph-relations` ownership: it is the flag a\n    // reader of a recorded relation's own columns must consult instead\n    // (`storeCaptureEnabled`, `src/store/runtime-port.ts`), never the public\n    // getter, or an engine-native store fools it into reading relations the\n    // engine never populates. Engine-native `history: true` gets NONE of\n    // TypeGraph's capture: the engine tracks history on its own, so\n    // `#engineNativeHistory` is a parallel, much narrower flag consulted only\n    // where the receipt/read wiring genuinely differs from TypeGraph-owned\n    // capture (construction below, recordedNow/revisionNow, and the two\n    // transaction-commit sites).\n    this.#requestedHistory = requestedHistory;\n    this.#captureEnabled =\n      requestedHistory && this.#recordedTimeOwnership === \"typegraph-relations\";\n    this.#engineNativeHistory =\n      requestedHistory && this.#recordedTimeOwnership === \"engine-native\";\n    this.#revisionTrackingEnabled =\n      this.#recordedTimeOwnership === \"engine-native\" ?\n        false\n      : this.#captureEnabled || requestedRevisionTracking;\n    if (this.#revisionTrackingEnabled) {\n      // Keyed on the resource `lockRecordedClock` fences: the\n      // TypeGraph-owned clock row, which `history` and `revisionTracking`\n      // both reach here — unreachable under engine-native, whose\n      // `#revisionTrackingEnabled` is forced false above.\n      const clockFencePlan = resolveWriteFencePlan(backend);\n      if (clockFencePlan.kind === \"unfenced\") {\n        refuseUnfencedClockAllocation(backend.dialect);\n      }\n      assertRevisionTrackableBackend(backend);\n    }\n    // Resolve the schema before wrapping so recorded-time capture targets the\n    // same relations recorded reads do (the explicit `schema` option, not just\n    // `backend.tableNames`).\n    const explicitSchema =\n      options?.schema === undefined ?\n        undefined\n      : requireSqlSchema(options.schema, \"store schema\");\n    const resolvedSchema =\n      explicitSchema ??\n      (backend.tableNames ? createSqlSchema(backend.tableNames) : undefined);\n    const readSchema = resolvedSchema ?? createSqlSchema(backend.tableNames);\n    if (this.#captureEnabled && options?.recordedRead !== undefined) {\n      throw new ConfigurationError(\n        \"recordedRead cannot be combined with history: true.\",\n        { code: \"RECORDED_READ_CONFLICTS_WITH_HISTORY\" },\n        {\n          suggestion:\n            \"Use { history: true } for TypeGraph-managed capture, or omit history and pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n        },\n      );\n    }\n    const externalRecordedRead = requireExternalRecordedReadSource(\n      options?.recordedRead,\n    );\n    this.#recordedReadBinding =\n      this.#captureEnabled ? createRecordedReadBinding(readSchema)\n      : this.#engineNativeHistory ?\n        createEngineRecordedReadBinding(\n          requireRecordedTime(backend, \"store construction\"),\n          readSchema,\n        )\n      : externalRecordedRead;\n    this.#backend =\n      this.#captureEnabled ?\n        asGraphWriteBackend(createRecordedBackend(backend, resolvedSchema))\n      : asGraphWriteBackend(backend);\n    this.#claimsVerdict = createClaimsVerdictThunk(this.#backend);\n    this.#batchPointRead = batchPointReadVerdict(this.#backend);\n    this.#endpointSetRead = endpointSetReadVerdict(this.#backend);\n    this.#uniqueSidecarBatch = uniqueSidecarBatchVerdict(this.#backend);\n    this.#statementExecution = statementExecution;\n    this.#contributionHealth = contributionHealthVerdict(this.#baseBackend);\n    this.#recordedRevisionOrigins = recordedRevisionOriginsVerdict(\n      this.#baseBackend,\n    );\n    this.#schema = resolvedSchema;\n    const rowMapperConfig = rowMapperConfigFor(this.#backend);\n    this.#recordedReads = createRecordedReadService({\n      graphId: graph.id,\n      backend: this.#backend,\n      recordedReadBinding: this.#recordedReadBinding,\n      mapRecordedNodeRow: createNodeRowMapper(rowMapperConfig),\n      mapRecordedEdgeRow: createEdgeRowMapper(rowMapperConfig),\n    });\n    this.#registry = buildKindRegistry(graph);\n    this.#hooks = options?.hooks ?? {};\n    this.#defaultTraversalExpansion =\n      options?.queryDefaults?.traversalExpansion ?? \"inverse\";\n    this.#options = options;\n    this.#schemaMetadata = schemaMetadata ?? UNKNOWN_SCHEMA_METADATA;\n    this[STORE_RUNTIME] = {\n      backend: this.#backend,\n      evolutionPlanningTarget: (plan) => this.#evolutionPlanningTarget(plan),\n      captureEnabled: this.#captureEnabled,\n      uniqueSidecarBatch: this.#uniqueSidecarBatch,\n      // The query path's own construction, not a second spelling of it: a\n      // caller that could only rebuild this object could not observe the one\n      // the queries actually run on.\n      queryBackend: (target) =>\n        this.#createHookedQueryBackend(target ?? this[STORE_RUNTIME].backend),\n      sealedQuery: (coordinate) => this.sealedQuery(coordinate),\n      recordedNodeGetById: (kind, id, coordinate) =>\n        this.recordedNodeGetById(kind, id, coordinate),\n      recordedNodeGetByIds: (kind, ids, coordinate) =>\n        this.recordedNodeGetByIds(kind, ids, coordinate),\n      recordedNodeScan: (kind, coordinate, options) =>\n        this.recordedNodeScan(kind, coordinate, options),\n      recordedEdgeGetById: (kind, id, coordinate) =>\n        this.recordedEdgeGetById(kind, id, coordinate),\n      recordedEdgeGetByIds: (kind, ids, coordinate) =>\n        this.recordedEdgeGetByIds(kind, ids, coordinate),\n      recordedEdgeScan: (kind, coordinate, options) =>\n        this.recordedEdgeScan(kind, coordinate, options),\n      subgraphAtCoordinate: (rootId, subgraphOptions) =>\n        this.subgraphAtCoordinate(rootId, subgraphOptions),\n      algorithmsAtCoordinate: (coordinate) =>\n        this.algorithmsAtCoordinate(coordinate),\n      identityAtCoordinate: (coordinate) =>\n        this.identityAtCoordinate(coordinate),\n      rebuildIdentityClosure: () => this.rebuildIdentityClosure(),\n      validateIdentity: () => this.validateIdentity(),\n      applyResolvedNodeUniqueness: async (target, writes, apply) => {\n        const upserts = writes.upserts.map((upsert) => {\n          if (!hasOwnKey(this.#graph.nodes, upsert.kind)) {\n            throw new KindNotFoundError(upsert.kind, \"node\", {\n              graphId: this.graphId,\n            });\n          }\n          const registration = this.#graph.nodes[upsert.kind];\n          if (registration === undefined) {\n            throw new KindNotFoundError(upsert.kind, \"node\", {\n              graphId: this.graphId,\n            });\n          }\n          return {\n            ...upsert,\n            constraints: registration.unique ?? [],\n          };\n        });\n        // Which kinds a release is worth CLEARING for: the clear exists so the\n        // set's upserts can take keys the set is giving back, and only a\n        // uniqueness declaration produces a key another node could take.\n        const constrainedKinds = new Set(\n          Object.entries(this.#graph.nodes)\n            .filter(\n              ([, registration]) => (registration.unique ?? []).length > 0,\n            )\n            .map(([kind]) => kind),\n        );\n        const releases = writes.releases.filter((release) => {\n          if (!Object.hasOwn(this.#graph.nodes, release.kind)) {\n            throw new KindNotFoundError(release.kind, \"node\", {\n              graphId: this.graphId,\n            });\n          }\n          return constrainedKinds.has(release.kind);\n        });\n        if (\n          upserts.every((upsert) => upsert.constraints.length === 0) &&\n          releases.length === 0\n        ) {\n          // Nothing is cleared, so nothing needs rebuilding, so the write set\n          // owes no set-wide preflight either. A kind with no uniqueness\n          // declaration may still owe DISJOINTNESS claims, and those are taken\n          // and released by the individual writes inside `apply()` exactly as\n          // they are outside a merge — this branch is what keeps that true.\n          return apply();\n        }\n        // The per-graph write lock, before any claim or sidecar work: the\n        // rebuild below writes claim rows, and the lock is what the claim\n        // discipline requires ahead of them. It is reentrant and memoized per\n        // transaction, so a merge that already took it pays no round trip.\n        const lock = await lockRecordedGraphWrite(target, this.graphId);\n        return applyResolvedNodeClaims(\n          {\n            graphId: this.graphId,\n            registry: this.#registry,\n            lock,\n            claimsVerdict: this.#claimsVerdict,\n            uniqueSidecarBatch: this.#uniqueSidecarBatch,\n          },\n          target,\n          upserts,\n          releases,\n          apply,\n        );\n      },\n      liveNodesSharingIds: async (ids, target) => {\n        const backend = target ?? this.#baseBackend;\n        const liveKindsById = await liveNodeKindsSharingIds(\n          this.#identityContext(backend),\n          backend,\n          ids,\n        );\n        const peers: Readonly<{ kind: string; id: string }>[] = [];\n        for (const [id, kinds] of liveKindsById) {\n          for (const kind of kinds) peers.push({ kind, id });\n        }\n        return peers;\n      },\n      identityAssertionRowsByIds: async (ids, target) => {\n        // An identity-disabled graph has no assertions table to read from.\n        if (this.#graph.identity === undefined) return new Map();\n        const backend = target ?? this.#baseBackend;\n        const ctx = this.#identityContext(backend);\n        const rows = await loadAssertionsByIds(\n          backend,\n          ctx.schema,\n          this.graphId,\n          ids,\n        );\n        return new Map(\n          [...rows].map(([id, row]) => [id, toTransferAssertion(row)]),\n        );\n      },\n      structuralIdentityClasses: async (references, target) => {\n        // An identity-disabled graph has no closure table to read from.\n        if (this.#graph.identity === undefined) return new Map();\n        const backend = target ?? this.#baseBackend;\n        const ctx = this.#identityContext(backend);\n        return loadCurrentStructuralClasses(\n          backend,\n          ctx.schema,\n          this.graphId,\n          references,\n        );\n      },\n      readCurrentIdentityAssertions: (mode, options) =>\n        this.readCurrentIdentityAssertions(mode, options),\n      identityAssertionsAtTarget: (target, mode) =>\n        this.identityAssertionsAtTarget(target, mode),\n      readIdentityAssertionPageAtTarget: (target, mode, options) =>\n        this.readIdentityAssertionPageAtTarget(target, mode, options),\n      lockIdentityImportTarget: (target) =>\n        this.lockIdentityImportTarget(target),\n      foldImportedIdentityNodes: (target, references) =>\n        this.foldImportedIdentityNodes(target, references),\n      importIdentityAssertionsAtTarget: (target, assertions, mode) =>\n        this.importIdentityAssertionsAtTarget(target, assertions, mode),\n      applyIdentityMergeAtTarget: (target, retractions, assertions) =>\n        this.applyIdentityMergeAtTarget(target, retractions, assertions),\n      assertIdentityClassesConsistentAtTarget: (target, seeds) =>\n        this.assertIdentityClassesConsistentAtTarget(target, seeds),\n    };\n    Object.defineProperty(this, STORE_RUNTIME, {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n    });\n  }\n\n  // === Accessors ===\n\n  /** The graph definition */\n  get graph(): G {\n    return this.#graph;\n  }\n\n  /** The graph ID */\n  get graphId(): string {\n    return this.#graph.id;\n  }\n\n  /** Runtime features available through this store's configured backend. */\n  get capabilities(): BackendCapabilities {\n    return this.#baseBackend.capabilities;\n  }\n\n  /** The kind registry for ontology lookups */\n  get registry(): KindRegistry {\n    return this.#registry;\n  }\n\n  /**\n   * The TypeGraph Identity Profile facade. Reachable through the public\n   * {@link Store} surface only on graphs that declared `identity: { ... }`;\n   * the runtime guard below catches widened or JavaScript callers.\n   *\n   * The facade is memoized per store, so it must not close over any state a\n   * lifecycle operation can move — see `#identityContext`.\n   */\n  get identity(): IdentityFacade<G> {\n    this.#requireIdentityEnabled(\n      'Add identity: { sameIdAcrossKinds: \"fold\" } to defineGraph(...).',\n    );\n    const existing = IDENTITY_FACADES.get(this);\n    if (existing !== undefined) return existing as IdentityFacade<G>;\n    const facade = createIdentityFacade(this.#identityContext(this.#backend));\n    IDENTITY_FACADES.set(this, facade);\n    return facade;\n  }\n\n  /**\n   * Refuses an identity operation on a graph that never declared\n   * `identity: { ... }`, where none of the identity tables exist.\n   */\n  #requireIdentityEnabled(suggestion?: string): void {\n    if (this.#graph.identity !== undefined) return;\n    throw new ConfigurationError(\n      \"Identity is not enabled for this graph.\",\n      { code: \"IDENTITY_NOT_ENABLED\", graphId: this.graphId },\n      suggestion === undefined ? undefined : { suggestion },\n    );\n  }\n\n  /** @internal Builds the identity read facade for a pinned StoreView. */\n  identityAtCoordinate(coordinate: ReadCoordinate): IdentityReadFacade<G> {\n    this.#requireIdentityEnabled();\n    // A recorded-time identity read must reconstruct from the SAME recorded\n    // relation the coordinate's node/edge reads use — binding-aware, so an\n    // externally bound recorded relation with divergent table names resolves\n    // its recorded identity assertions instead of TypeGraph's default-named\n    // (empty) tables. Mirror the node recorded-read routing: the\n    // relations-precondition backend overlay plus the recorded schema view.\n    const recordedAsOf = coordinate.recorded?.asOf;\n    if (\n      recordedAsOf !== undefined &&\n      isEngineNativeRecordedReadBinding(this.#recordedReadBinding)\n    ) {\n      refuseEngineNativeRecordedIdentityRead(\"identityAtCoordinate\");\n    }\n    const backend =\n      recordedAsOf === undefined ?\n        this.#backend\n      : this.#recordedReads.backendForCoordinate(\n          coordinate,\n          \"recorded-identity\",\n        );\n    const schema = recordedReadSchemaFor(\n      this.#sqlSchema(),\n      recordedAsOf,\n      this.#recordedReadBinding,\n      \"recorded-identity\",\n    );\n    return createIdentityReadFacade({\n      ...this.#identityContext(backend),\n      schema,\n      coordinate,\n    });\n  }\n\n  /** Rebuilds derived current identity closure without advancing revision. */\n  async rebuildIdentityClosure(): Promise<void> {\n    this.#requireIdentityEnabled();\n    await rebuildIdentityClosureWithSchemaFence(\n      this.#identityContext(this.#baseBackend),\n      {\n        graphId: this.graphId,\n        schemaVersion: this.#schemaMetadata.schemaVersion,\n        historyEnabled: this.#captureEnabled,\n        revisionTrackingEnabled: this.#revisionTrackingEnabled,\n        revisionSchema: this.#sqlSchema(),\n        statementExecution: this.#statementExecution,\n      },\n    );\n  }\n\n  /**\n   * @internal Validates/rebuilds identity under schema-transition locks.\n   *\n   * `provisionDerivedRelations` carries the DDL `ensureIdentitySchemaStorage`\n   * deliberately did not run outside this transaction, so an evolution that\n   * fails leaves no half-published derived relation behind.\n   */\n  async identitySchemaPreflight(\n    target: SchemaCommitPreflightBackend,\n    provisionDerivedRelations: readonly string[],\n  ): Promise<void> {\n    await identitySchemaCommitPreflight(this.#identityContext(this.#backend), {\n      enablement: false,\n      provisionDerivedRelations,\n    })(target);\n  }\n\n  /** @internal Read-only startup integrity verification. */\n  async validateIdentity(): Promise<void> {\n    if (this.#graph.identity === undefined) return;\n    // Assertion/disjointness integrity AND closure-vs-components agreement are\n    // both enforced here: validateIdentityForContext now also asserts the\n    // materialized closure matches the computed components (throws\n    // IDENTITY_SCHEMA_CONTRADICTION with a rebuildIdentityClosure suggestion).\n    await validateIdentityForContext(this.#identityContext(this.#baseBackend));\n  }\n\n  /** @internal Cascades removed kinds in the schema-commit transaction. */\n  async removeIdentityKindsInSchemaPreflight(\n    target: TransactionBackend,\n    kinds: readonly string[],\n    options?: Readonly<{ repairClosure?: boolean }>,\n  ): Promise<void> {\n    if (!this.#captureEnabled) {\n      await removeIdentityKindsForContext(\n        this.#identityContext(target),\n        kinds,\n        options,\n      );\n      return;\n    }\n    const scope = createRecordedTransactionScope(\n      target,\n      this.#batchPointRead,\n      this.#sqlSchema(),\n      target.dialect === \"sqlite\",\n    );\n    await removeIdentityKindsForContext(\n      this.#identityContext(scope.backend),\n      kinds,\n      options,\n    );\n    await scope.flush();\n  }\n\n  /**\n   * @internal Reads the graph's identity assertions in transfer shape, honoring\n   * this store's SQL binding. Used by interchange export, base-version\n   * fingerprinting, and merge staging/diff.\n   */\n  readCurrentIdentityAssertions(\n    mode: \"state\" | \"archival\",\n    options?: Readonly<{\n      nodeKinds?: readonly string[];\n      includeDeleted?: boolean;\n    }>,\n  ): Promise<readonly IdentityTransferAssertion[]> {\n    if (this.#graph.identity === undefined) return Promise.resolve([]);\n    return readIdentityAssertionsForInterchange(\n      this.#identityContext(this.#baseBackend),\n      mode,\n      options,\n    );\n  }\n\n  /** @internal Reads identity truth through an already-bound transaction. */\n  identityAssertionsAtTarget(\n    target: GraphBackend | TransactionBackend,\n    mode: \"state\" | \"archival\" = \"state\",\n  ): Promise<readonly IdentityTransferAssertion[]> {\n    if (this.#graph.identity === undefined) return Promise.resolve([]);\n    return readIdentityAssertionsForInterchange(\n      this.#identityContext(target),\n      mode,\n    );\n  }\n\n  /** @internal Reads one bounded identity-assertion page at a bound target. */\n  readIdentityAssertionPageAtTarget(\n    target: GraphBackend | TransactionBackend,\n    mode: \"state\" | \"archival\",\n    options: Readonly<{\n      nodeKinds?: readonly string[];\n      includeDeleted?: boolean;\n      after?: string;\n      limit: number;\n    }>,\n  ): ReturnType<typeof readIdentityAssertionPageAtTarget> {\n    if (this.#graph.identity === undefined) {\n      return Promise.resolve({ assertions: [], done: true });\n    }\n    return readIdentityAssertionPageAtTarget(\n      this.#identityContext(target),\n      target,\n      mode,\n      options,\n    );\n  }\n\n  /** @internal Acquires the enabled graph's identity lock for an import. */\n  lockIdentityImportTarget(target: IdentityTarget): Promise<void> {\n    return this.#graph.identity === undefined ?\n        Promise.resolve()\n      : lockIdentityGraph(target, this.graphId);\n  }\n\n  /** @internal Restores same-id folding after the ops-layer import bypass. */\n  foldImportedIdentityNodes(\n    target: IdentityTarget,\n    references: readonly Readonly<{ kind: string; id: string }>[],\n  ): Promise<void> {\n    if (this.#graph.identity === undefined || references.length === 0) {\n      return Promise.resolve();\n    }\n    return foldIdentityForCreatedNodes(\n      {\n        graphId: this.graphId,\n        registry: this.#registry,\n        sameIdAcrossKinds: this.#graph.identity.sameIdAcrossKinds,\n        schema: this.#sqlSchema(),\n      },\n      target,\n      references,\n    );\n  }\n\n  /** @internal Applies identity interchange rows inside an import transaction. */\n  importIdentityAssertionsAtTarget(\n    target: IdentityTarget,\n    assertions: readonly IdentityTransferAssertion[],\n    mode: \"state\" | \"archival\",\n  ): Promise<IdentityImportSummary> {\n    if (assertions.length === 0) {\n      return Promise.resolve({ created: 0, skipped: 0 });\n    }\n    if (this.#graph.identity === undefined) {\n      throw new ConfigurationError(\n        \"Cannot import identity assertions into an identity-disabled graph.\",\n        { code: \"IDENTITY_IMPORT_REQUIRES_PROFILE\", graphId: this.graphId },\n      );\n    }\n    return importIdentityAssertionsIntoTarget(\n      // The slice the coordinator reads — graph, registry, schema, folding\n      // mode — none of which depend on the target. The target it writes\n      // through is the parameter beside it, which is why this method can take\n      // the narrow statement projection an import frame is able to offer.\n      this.#identityContext(this.#baseBackend),\n      target,\n      assertions,\n      mode,\n    );\n  }\n\n  /**\n   * @internal Post-write identity validation for a graph-merge commit: proves\n   * the identity classes the merge touched carry no contradiction in the state\n   * the merge just wrote, inside the merge's own transaction.\n   */\n  assertIdentityClassesConsistentAtTarget(\n    target: GraphBackend | TransactionBackend,\n    seeds: readonly Readonly<{ kind: string; id: string }>[],\n  ): Promise<void> {\n    if (this.#graph.identity === undefined || seeds.length === 0) {\n      return Promise.resolve();\n    }\n    return assertAffectedIdentityClassesConsistent(\n      this.#identityContext(target),\n      target,\n      seeds,\n    );\n  }\n\n  /** @internal Mechanical graph-merge apply through the mutation coordinator. */\n  applyIdentityMergeAtTarget(\n    target: GraphBackend | TransactionBackend,\n    retractions: readonly IdentityTransferAssertion[],\n    assertions: readonly IdentityTransferAssertion[],\n  ): Promise<Readonly<{ created: number; retracted: number }>> {\n    if (retractions.length === 0 && assertions.length === 0) {\n      return Promise.resolve({ created: 0, retracted: 0 });\n    }\n    if (this.#graph.identity === undefined) {\n      throw new ConfigurationError(\n        \"Cannot apply identity merge changes to an identity-disabled graph.\",\n        { code: \"IDENTITY_MERGE_REQUIRES_PROFILE\", graphId: this.graphId },\n      );\n    }\n    return applyIdentityChangesForContext(\n      this.#identityContext(target),\n      retractions,\n      assertions,\n    );\n  }\n\n  /**\n   * An opaque, in-memory snapshot of this store's reconciled schema — the\n   * merged compile-time + runtime-committed graph plus the committed version\n   * it reflects. Cache it after a verified open and hand it to\n   * {@link createAdapterStore} via `{ reconciled }` (or call\n   * {@link AdapterStoreImplementation.withBackend}) to build request-scoped\n   * stores against fresh connections with zero database round-trips. Refresh\n   * it when {@link getCommittedSchemaVersion} reports a moved version.\n   */\n  get reconciledSchema(): ReconciledSchema<G> {\n    return Object.freeze({\n      graph: this.#graph,\n      version: this.#schemaMetadata.schemaVersion,\n      hash: this.#schemaMetadata.schemaHash,\n    });\n  }\n\n  /**\n   * Reconstruction inputs for a connection rebind: the merged graph, the\n   * verbatim construction options, and the reconciled schema metadata. Lets an\n   * adapter subclass rebuild an equivalent store against a fresh backend\n   * without a verify round-trip.\n   *\n   * @internal\n   */\n  protected reconstructionState(): Readonly<{\n    graph: G;\n    options: StoreOptions | undefined;\n    schemaMetadata: StoreSchemaMetadata;\n  }> {\n    return {\n      graph: this.#graph,\n      options: this.#options,\n      schemaMetadata: this.#schemaMetadata,\n    };\n  }\n\n  /**\n   * Whether this store was constructed with `history: true` — under EITHER\n   * recorded-time ownership form. Matches `HistoryStore<G>`'s static\n   * `historyEnabled: true`: a store this is true for always answers\n   * `asOfRecorded` and stamps recorded receipts, whether TypeGraph's own\n   * capture runs underneath (`typegraph-relations` ownership) or the\n   * engine tracks history on its own (`engine-native` ownership, where\n   * TypeGraph's recorded relations are never populated). A decision that\n   * specifically needs \"does TypeGraph's own capture run\" — a reader of a\n   * recorded relation's own columns — must consult `storeCaptureEnabled`\n   * (`src/store/runtime-port.ts`) instead; this getter would answer `true`\n   * for an engine-native store too and lead it to read relations the engine\n   * never populates.\n   *\n   * @internal\n   */\n  get historyEnabled(): boolean {\n    return this.#requestedHistory;\n  }\n\n  /**\n   * Whether this Store advances a durable revision anchor for graph writes.\n   *\n   * @internal\n   */\n  get revisionTrackingEnabled(): boolean {\n    return this.#revisionTrackingEnabled;\n  }\n\n  /**\n   * SQL schema that owns the durable revision clock relation.\n   *\n   * @internal\n   */\n  get revisionSchema(): SqlSchema {\n    return this.#sqlSchema();\n  }\n\n  /**\n   * Whether this store has a recorded read relation bound for reconstruction.\n   *\n   * @internal\n   */\n  get recordedReadBound(): boolean {\n    return this.#recordedReadBinding !== undefined;\n  }\n\n  /**\n   * Who allocates recorded-time revisions for this store: TypeGraph's own\n   * capture relations and clock, or this backend's engine through\n   * `recordedTime`. See {@link resolveRecordedTimeOwnership}.\n   *\n   * @internal\n   */\n  get recordedTimeOwnership(): RecordedTimeOwnership {\n    return this.#recordedTimeOwnership;\n  }\n\n  /**\n   * The behavioral subset of this store's construction options a\n   * working-copy strategy inherits: hooks, upsert coalescing, the SQL\n   * schema, the auto-refresh-statistics threshold, query defaults, and an\n   * externally-bound recorded-read relation. Read off the verbatim options\n   * this store was constructed with (the same field `evolve()` reconstructs\n   * from), never re-derived from private state, so this is the one place a\n   * strategy reaches for them.\n   *\n   * Excludes `history`/`revisionTracking` — those are the working-copy\n   * strategy's own decision, not something to inherit blindly.\n   *\n   * Public: this is the getter a custom `WorkingCopyStrategy` author is meant\n   * to call (see `forkedWorkingCopyStrategy` in `graph-merge`), not an\n   * internal implementation detail like its `historyEnabled`/\n   * `revisionTrackingEnabled`/`revisionSchema` siblings.\n   */\n  get workingCopyOptions(): WorkingCopyOptions {\n    const {\n      history: _history,\n      revisionTracking: _revisionTracking,\n      ...rest\n    } = this.#options ?? {};\n    return Object.freeze(rest);\n  }\n\n  // === Collections ===\n\n  /**\n   * Node collections for ergonomic CRUD operations.\n   *\n   * @example\n   * ```typescript\n   * // Create a node\n   * const person = await store.nodes.Person.create({ name: \"Alice\" });\n   *\n   * // Get by ID\n   * const fetched = await store.nodes.Person.getById(person.id);\n   *\n   * // Find all\n   * const people = await store.nodes.Person.find({ limit: 10 });\n   * ```\n   */\n  get nodes(): GraphNodeCollections<G> {\n    if (this.#nodeCollections === undefined) {\n      this.#nodeCollections = createNodeCollectionsProxy(\n        this.#graph,\n        this.graphId,\n        this.#registry,\n        this.#backend,\n        this.#batchPointRead,\n        this.#nodeOperations,\n      );\n    }\n\n    return this.#nodeCollections;\n  }\n\n  /**\n   * Edge collections for ergonomic CRUD operations.\n   *\n   * @example\n   * ```typescript\n   * // Create an edge\n   * const edge = await store.edges.worksAt.create(\n   *   { kind: \"Person\", id: person.id },\n   *   { kind: \"Company\", id: company.id },\n   *   { role: \"Engineer\" }\n   * );\n   *\n   * // Find edges from a node\n   * const edges = await store.edges.worksAt.findFrom({ kind: \"Person\", id: person.id });\n   * ```\n   */\n  get edges(): GraphEdgeCollections<G> {\n    if (this.#edgeCollections === undefined) {\n      this.#edgeCollections = createEdgeCollectionsProxy(\n        this.#graph,\n        this.graphId,\n        this.#registry,\n        this.#backend,\n        this.#batchPointRead,\n        this.#endpointSetRead,\n        this.#edgeOperations,\n      );\n    }\n\n    return this.#edgeCollections;\n  }\n\n  // === Graph Algorithms ===\n\n  /**\n   * Tier 1 graph algorithms: shortest path, reachability, neighborhoods, and\n   * degree centrality.\n   *\n   * Traversal calls use the iterative graph-operation substrate: a set-based\n   * breadth-first frontier backed by a temporary working table, or a chunked\n   * inline relation when the backend cannot pin a transactional connection.\n   * `degree` uses a single count query. The facade is built lazily on first\n   * access and cached for the lifetime of the store.\n   *\n   * @example\n   * ```typescript\n   * const path = await store.algorithms.shortestPath(alice, bob, {\n   *   edges: [\"knows\"],\n   * });\n   *\n   * const friends = await store.algorithms.neighbors(alice, {\n   *   edges: [\"knows\"],\n   *   depth: 2,\n   * });\n   * ```\n   */\n  get algorithms(): GraphAlgorithms<G> {\n    if (this.#algorithms === undefined) {\n      this.#algorithms = createGraphAlgorithms<G>({\n        graphId: this.graphId,\n        graph: this.#graph,\n        registry: this.#registry,\n        backend: this.#backend,\n        schema: this.#schema,\n        recordedReadBinding: this.#recordedReadBinding,\n        defaultTemporalMode: this.#graph.defaults.temporalMode,\n      });\n    }\n    return this.#algorithms;\n  }\n\n  // === Dynamic Collection Access ===\n\n  #runtimeKindBinding(): RuntimeKindSchemaBinding {\n    return {\n      graphId: this.graphId,\n      schemaVersion: this.#schemaMetadata.schemaVersion,\n      schemaHash: this.#schemaMetadata.schemaHash,\n    };\n  }\n\n  #assertRuntimeKindDefinition(\n    entity: KindEntity,\n    kind: string,\n    evidence: ExtensionNodeDef | ExtensionEdgeDef,\n  ): void {\n    if (\n      this.#schemaMetadata.schemaVersion === undefined ||\n      this.#schemaMetadata.schemaHash === undefined\n    ) {\n      throw new RuntimeKindTokenError(\"unreconciled\", entity, {\n        graphId: this.graphId,\n        kind,\n      });\n    }\n    const registered =\n      entity === \"node\" ?\n        this.#graph.extension?.nodes?.[kind]\n      : this.#graph.extension?.edges?.[kind];\n    if (registered === undefined || !canonicalEqual(registered, evidence)) {\n      throw new RuntimeKindTokenError(\"schema-mismatch\", entity, {\n        graphId: this.graphId,\n        kind,\n      });\n    }\n  }\n\n  runtimeNodeKind<const K extends string, const D extends ExtensionNodeDef>(\n    kind: K,\n    definition: D,\n  ): RuntimeNodeKind<K, ExtensionObjectSchema<D[\"properties\"]>> {\n    this.#assertRuntimeKindDefinition(\"node\", kind, definition);\n    return createRuntimeKindToken<K, ExtensionObjectSchema<D[\"properties\"]>>(\n      this.#runtimeKindOwner,\n      this.#runtimeKindBinding(),\n      \"node\",\n      kind,\n    );\n  }\n\n  runtimeEdgeKind<const K extends string, const D extends ExtensionEdgeDef>(\n    kind: K,\n    definition: D,\n  ): RuntimeEdgeKind<K, ExtensionObjectSchema<ExtensionEdgeProperties<D>>> {\n    this.#assertRuntimeKindDefinition(\"edge\", kind, definition);\n    return createRuntimeKindToken<\n      K,\n      ExtensionObjectSchema<ExtensionEdgeProperties<D>>\n    >(this.#runtimeKindOwner, this.#runtimeKindBinding(), \"edge\", kind);\n  }\n\n  #resolveRuntimeKind(input: RuntimeKindInput, entity: KindEntity): string {\n    return resolveRuntimeKindInput(input, entity, (token, expectedEntity) =>\n      this.#resolveRuntimeKindToken(token, expectedEntity),\n    );\n  }\n\n  #resolveRuntimeKindToken(token: unknown, entity: KindEntity): string {\n    return resolveRuntimeKindToken(\n      token,\n      entity,\n      this.#runtimeKindOwner,\n      this.#runtimeKindBinding(),\n    );\n  }\n\n  /**\n   * Resolves `kind` against `collections` (either `this.nodes` or a\n   * transaction-scoped — and possibly receipt-wrapped — node collection map),\n   * or `undefined` when the kind is not registered in this graph. Shared by\n   * `getNodeCollection` and both transaction contexts' `getNodeCollection` so\n   * a receipt-wrapped transaction counts writes made through the dynamic\n   * lookup exactly like `this.#graph.nodes` membership is checked everywhere\n   * else.\n   */\n  #resolveDynamicNodeCollection<const K extends string>(\n    collections: GraphNodeCollections<G>,\n    kind: K,\n  ): DynamicNodeCollection<K> | undefined {\n    if (!Object.hasOwn(this.#graph.nodes, kind)) return undefined;\n    return collections[\n      kind as keyof G[\"nodes\"] & string\n    ] as unknown as DynamicNodeCollection<K>;\n  }\n\n  /**\n   * Returns the node collection for the given kind, or undefined if the kind\n   * is not registered in this graph.\n   *\n   * Use this for runtime string-keyed access when the kind is not known at\n   * compile time (e.g., iterating all kinds, resolving from edge metadata,\n   * dynamic admin UIs). For the post-evolve \"I just added this kind, give\n   * me the collection\" pattern, prefer `getNodeCollectionOrThrow` — it\n   * throws `KindNotFoundError` instead of forcing a null-check.\n   */\n  getNodeCollection<const K extends string>(\n    kind: K,\n  ): DynamicNodeCollection<K> | undefined {\n    return this.#resolveDynamicNodeCollection(this.nodes, kind);\n  }\n\n  /**\n   * Returns the node collection for the given kind. Throws\n   * `KindNotFoundError` when the kind is not registered.\n   *\n   * The dominant graph-extension-kind access pattern: `await store.evolve(...)`\n   * returns the Store for the resulting schema, the caller immediately\n   * operates on the new kind, and the null-check the optional variant requires\n   * is busywork.\n   */\n  getNodeCollectionOrThrow<T extends RuntimeNodeKind>(\n    token: T,\n  ): RuntimeNodeCollection<T>;\n  getNodeCollectionOrThrow<const K extends string>(\n    kind: K,\n  ): DynamicNodeCollection<K>;\n  getNodeCollectionOrThrow(kindOrToken: string | RuntimeNodeKind): unknown {\n    const kind = this.#resolveRuntimeKind(kindOrToken, \"node\");\n    const collection = this.#resolveDynamicNodeCollection(this.nodes, kind);\n    if (collection === undefined) {\n      throw new KindNotFoundError(kind, \"node\", {\n        graphId: this.graphId,\n      });\n    }\n    return collection;\n  }\n\n  /**\n   * Returns the edge collection for the given kind, or undefined if the kind\n   * is not registered in this graph.\n   *\n   * Use this for runtime string-keyed access when the kind is not known at\n   * compile time. For post-evolve access, prefer `getEdgeCollectionOrThrow`.\n   */\n  getEdgeCollection<K extends EdgeKinds<G>>(\n    kind: K,\n  ): DynamicEdgeCollection<G[\"edges\"][K][\"type\"]> | undefined;\n  getEdgeCollection(kind: string): DynamicEdgeCollection | undefined;\n  getEdgeCollection(kind: string): unknown {\n    return this.#resolveDynamicEdgeCollection(this.edges, kind);\n  }\n\n  /** Returns a runtime-validated collection; throws when the kind is absent. */\n  getEdgeCollectionOrThrow<T extends RuntimeEdgeKind>(\n    token: T,\n  ): RuntimeEdgeCollection<T>;\n  getEdgeCollectionOrThrow<K extends EdgeKinds<G>>(\n    kind: K,\n  ): DynamicEdgeCollection<G[\"edges\"][K][\"type\"]>;\n  getEdgeCollectionOrThrow(kind: string): DynamicEdgeCollection;\n  getEdgeCollectionOrThrow(kindOrToken: string | RuntimeEdgeKind): unknown {\n    return this.#requireDynamicEdgeCollection(this.edges, kindOrToken);\n  }\n\n  #requireDynamicEdgeCollection(\n    collections: GraphEdgeCollections<G>,\n    kindOrToken: string | RuntimeEdgeKind,\n  ): DynamicEdgeCollection {\n    const kind = this.#resolveRuntimeKind(kindOrToken, \"edge\");\n    const collection = this.#resolveDynamicEdgeCollection(collections, kind);\n    if (collection === undefined) {\n      throw new KindNotFoundError(kind, \"edge\", { graphId: this.graphId });\n    }\n    return collection;\n  }\n\n  #resolveDynamicEdgeCollection(\n    collections: GraphEdgeCollections<G>,\n    kind: string,\n  ): DynamicEdgeCollection | undefined {\n    if (!Object.hasOwn(this.#graph.edges, kind)) return undefined;\n    return collections[\n      kind as EdgeKinds<G>\n    ] as unknown as DynamicEdgeCollection;\n  }\n\n  /** Resolve through the supplied context's wrappers, preserving transaction and receipt ownership. */\n  #edgeCollectionAccess(collections: GraphEdgeCollections<G>): Readonly<{\n    getEdgeCollection: EdgeCollectionLookup<G>;\n    getEdgeCollectionOrThrow: RequiredEdgeCollectionLookup<G>;\n  }> {\n    const getEdgeCollection = (\n      kind: string,\n    ): DynamicEdgeCollection | undefined =>\n      this.#resolveDynamicEdgeCollection(collections, kind);\n    const getEdgeCollectionOrThrow = (\n      kindOrToken: string | RuntimeEdgeKind,\n    ): DynamicEdgeCollection =>\n      this.#requireDynamicEdgeCollection(collections, kindOrToken);\n    // Lookup erases endpoint evidence, not the selected edge's property schema.\n    return {\n      getEdgeCollection: getEdgeCollection as EdgeCollectionLookup<G>,\n      getEdgeCollectionOrThrow:\n        getEdgeCollectionOrThrow as RequiredEdgeCollectionLookup<G>,\n    };\n  }\n\n  // === Dynamic Props Schema Access ===\n\n  /**\n   * Returns the Zod props schema for the given node kind, or `undefined`\n   * if the kind is not registered. Identity-preserving: returns the\n   * exact instance used by `.create()` / `.update()`, so a `parse()`\n   * surfaces the same underlying Zod issues that `ValidationError`\n   * wraps (operation-level checks like uniqueness and endpoints stay\n   * in `collection.create`).\n   */\n  getNodePropsSchema(kind: string): z.ZodObject<z.ZodRawShape> | undefined {\n    if (!Object.hasOwn(this.#graph.nodes, kind)) return undefined;\n    return requireDefined(this.#graph.nodes[kind]).type.schema;\n  }\n\n  /**\n   * Returns the Zod props schema for the given node kind. Throws\n   * `KindNotFoundError` when the kind is not registered.\n   */\n  getNodePropsSchemaOrThrow(kind: string): z.ZodObject<z.ZodRawShape> {\n    const schema = this.getNodePropsSchema(kind);\n    if (schema === undefined) {\n      throw new KindNotFoundError(kind, \"node\", {\n        graphId: this.graphId,\n      });\n    }\n    return schema;\n  }\n\n  /**\n   * Returns the Zod props schema for the given edge kind, or `undefined`\n   * if the kind is not registered. Symmetric with `getNodePropsSchema`.\n   */\n  getEdgePropsSchema(kind: string): z.ZodObject<z.ZodRawShape> | undefined {\n    if (!Object.hasOwn(this.#graph.edges, kind)) return undefined;\n    return requireDefined(this.#graph.edges[kind]).type.schema;\n  }\n\n  /**\n   * Returns the Zod props schema for the given edge kind. Throws\n   * `KindNotFoundError` when the kind is not registered.\n   */\n  getEdgePropsSchemaOrThrow(kind: string): z.ZodObject<z.ZodRawShape> {\n    const schema = this.getEdgePropsSchema(kind);\n    if (schema === undefined) {\n      throw new KindNotFoundError(kind, \"edge\", {\n        graphId: this.graphId,\n      });\n    }\n    return schema;\n  }\n\n  /**\n   * Returns a unified read of the merged schema — every compile-time\n   * and graph-extension kind, every edge, every ontology relation,\n   * with explicit `origin: \"compile-time\" | \"runtime\"` markers — plus\n   * the persisted `extension` for round-tripping.\n   *\n   * Pure synchronous read built from the in-memory graph and the\n   * already-merged graph-extension document. `schemaVersion` and `schemaHash`\n   * are populated when the loader cached them at construction or after\n   * `evolve` returns; consumers needing a fresh read should call\n   * `backend.getActiveSchema(graphId)`.\n   *\n   * The return shape is the canonical schema-introspection surface:\n   * the prior standalone `store.deprecatedKinds` accessor is replaced\n   * by `introspect().deprecatedKinds`.\n   */\n  introspect(): SchemaIntrospection {\n    return introspectSchema(this.#graph, {\n      graphId: this.graphId,\n      schemaVersion: this.#schemaMetadata.schemaVersion,\n      schemaHash: this.#schemaMetadata.schemaHash,\n    });\n  }\n\n  /**\n   * Describes the merged schema and current population statistics. Bounded SQL\n   * aggregates compute the data observation, bracketed by active-schema reads.\n   */\n  async describe(): Promise<StoreDescription> {\n    return describeStore(this.#analysisContext());\n  }\n\n  /**\n   * Keyset-pages current records and reports rules they violate under the\n   * current kind schema. Undeclared properties remain valid semi-structured\n   * state. Cursors are schema-fenced; data changes remain live between pages.\n   */\n  async validateStore(\n    options: ValidateStoreOptions,\n  ): Promise<StoreValidationPage> {\n    return validateStoreImpl(this.#analysisContext(), options);\n  }\n\n  #analysisContext(\n    backend: Pick<\n      GraphBackend,\n      \"dialect\" | \"execute\" | \"getActiveSchema\"\n    > = this.#baseBackend,\n  ) {\n    return {\n      graph: this.#graph,\n      graphId: this.graphId,\n      backend,\n      schema: this.#sqlSchema(),\n      introspect: () => this.introspect(),\n    };\n  }\n\n  /**\n   * Pre-flights this store's graph against the committed schema — one SELECT,\n   * no DDL, no writes. Returns the structured diff, or `undefined` when no\n   * schema has been committed for this graph yet.\n   *\n   * Pass the diff to `classifySchemaChanges` for the\n   * `identical | additive | incompatible` decision, so a caller can choose\n   * between \"proceed\" and \"ask the user\" *before* attempting a commit.\n   */\n  async schemaChanges(): Promise<SchemaDiff | undefined> {\n    return getSchemaChanges(this.#backend, this.#graph);\n  }\n\n  /**\n   * Whether committing this store's graph would require a schema migration —\n   * a SELECT-only pre-flight. Also `true` when no schema has been committed\n   * yet, since that needs the privileged bootstrap too.\n   *\n   * Lets a least-privilege runtime detect \"this needs the privileged path\"\n   * and route accordingly, instead of discovering the migration wall partway\n   * through a user's request.\n   */\n  async requiresMigration(): Promise<boolean> {\n    return requiresMigrationImpl(this.#backend, this.#graph);\n  }\n\n  /**\n   * Node operations bound to this store instance.\n   */\n  get #nodeOperations(): NodeOperations {\n    return this.#buildNodeOperations(this.#createNodeOperationContext());\n  }\n\n  /**\n   * Refreshes planner statistics after an autocommit bulk write that\n   * reached the configured row threshold. A refresh failure must never\n   * fail the (already committed) write — it degrades to a warning.\n   */\n  async #maybeRefreshStatisticsAfterBulk(rowCount: number): Promise<void> {\n    const configured = this.#options?.autoRefreshStatistics;\n    if (configured === false) return;\n    const threshold = configured ?? AUTO_REFRESH_STATISTICS_ROW_THRESHOLD;\n    if (rowCount < threshold) return;\n    try {\n      await this.refreshStatistics();\n    } catch (error) {\n      console.warn(\n        \"typegraph: statistics refresh after bulk write failed; run \" +\n          \"store.refreshStatistics() to avoid stale planner statistics.\",\n        error,\n      );\n    }\n  }\n\n  #buildNodeOperations(ctx: NodeOperationContext<G>): NodeOperations {\n    return {\n      defaultTemporalMode: this.#graph.defaults.temporalMode,\n      rowToNode: (row) => rowToNode(row),\n      maybeRefreshStatisticsAfterBulk: (rowCount) =>\n        this.#maybeRefreshStatisticsAfterBulk(rowCount),\n      executeCreate: (input, backend) => executeNodeCreate(ctx, input, backend),\n      executeCreateBatch: (inputs, backend, options) =>\n        executeNodeCreateBatch(ctx, inputs, backend, options),\n      executeCreateNoReturnBatch: (inputs, backend) =>\n        executeNodeCreateNoReturnBatch(ctx, inputs, backend),\n      executeUpdate: (input, backend, options) =>\n        executeNodeUpdate(ctx, { ...input, id: input.id }, backend, options),\n      executeNodeSetUpdate: (\n        kind,\n        patch,\n        candidateIds,\n        candidateIdColumn,\n        backend,\n        options,\n      ) =>\n        executeNodeSetUpdate(\n          ctx,\n          kind,\n          patch,\n          candidateIds,\n          candidateIdColumn,\n          backend,\n          options,\n        ),\n      executeUpsertUpdateBatch: (entries, backend) =>\n        executeNodeUpsertUpdateBatch(ctx, entries, backend),\n      executeResolvedMutationSet: (creates, updates, backend) =>\n        executeNodeResolvedMutationSet(ctx, creates, updates, backend),\n      prepareReplacement: (kind, props) =>\n        prepareNodeReplacement(ctx, kind, props),\n      executeReplacementBatch: (kind, items, backend) =>\n        executeNodeReplacementBatch(ctx, kind, items, backend),\n      // Present only when opted in; its absence is the coalesce off switch.\n      ...(ctx.coalesceUnchangedUpsertsEnabled && {\n        upsertDirtyCheck: (kind, id, existingProps, inputProps) =>\n          nodeUpsertDirtyCheck(ctx, kind, id, existingProps, inputProps),\n      }),\n      executeDelete: (kind, id, backend) =>\n        executeNodeDelete(ctx, kind, id, backend),\n      executeDeleteBatch: (kind, ids, backend) =>\n        executeNodeDeleteBatch(ctx, kind, ids, backend),\n      executeHardDelete: (kind, id, backend) =>\n        executeNodeHardDelete(ctx, kind, id, backend),\n      temporalRowMatcher: (options) => this.#temporalRowMatcher(options),\n      createQuery: () => this.query(),\n      executeGetOrCreateByConstraint: (\n        kind,\n        constraintName,\n        props,\n        backend,\n        options,\n      ) =>\n        executeNodeGetOrCreateByConstraint(\n          ctx,\n          kind,\n          constraintName,\n          props,\n          backend,\n          options,\n        ),\n      executeBulkGetOrCreateByConstraint: (\n        kind,\n        constraintName,\n        items,\n        backend,\n        options,\n      ) =>\n        executeNodeBulkGetOrCreateByConstraint(\n          ctx,\n          kind,\n          constraintName,\n          items,\n          backend,\n          options,\n        ),\n      executeFindByConstraint: (kind, constraintName, props, backend) =>\n        executeNodeFindByConstraint(ctx, kind, constraintName, props, backend),\n      executeBulkFindByConstraint: (kind, constraintName, items, backend) =>\n        executeNodeBulkFindByConstraint(\n          ctx,\n          kind,\n          constraintName,\n          items,\n          backend,\n        ),\n      executeBulkFindByIndex: (kind, indexName, items, backend, options) =>\n        executeNodeBulkFindByIndex(\n          ctx,\n          kind,\n          indexName,\n          items,\n          backend,\n          options,\n        ),\n    };\n  }\n\n  /**\n   * Edge operations bound to this store instance.\n   */\n  get #edgeOperations(): EdgeOperations {\n    return this.#buildEdgeOperations(this.#createEdgeOperationContext());\n  }\n\n  #buildEdgeOperations(ctx: EdgeOperationContext<G>): EdgeOperations {\n    return {\n      defaultTemporalMode: this.#graph.defaults.temporalMode,\n      rowToEdge: (row) => rowToEdge(row),\n      maybeRefreshStatisticsAfterBulk: (rowCount) =>\n        this.#maybeRefreshStatisticsAfterBulk(rowCount),\n      executeCreate: (input, backend) => executeEdgeCreate(ctx, input, backend),\n      executeCreateBatch: (inputs, backend) =>\n        executeEdgeCreateBatch(ctx, inputs, backend),\n      executeCreateNoReturnBatch: (inputs, backend) =>\n        executeEdgeCreateNoReturnBatch(ctx, inputs, backend),\n      executeUpdate: (input, backend) => executeEdgeUpdate(ctx, input, backend),\n      executeUpsertUpdateBatch: (entries, backend) =>\n        executeEdgeUpsertUpdateBatch(ctx, entries, backend),\n      executeResolvedMutationSet: (creates, updates, backend) =>\n        executeEdgeResolvedMutationSet(ctx, creates, updates, backend),\n      // Present only when opted in; its absence is the coalesce off switch.\n      ...(ctx.coalesceUnchangedUpsertsEnabled && {\n        upsertDirtyCheck: (kind, id, existingProps, inputProps) =>\n          edgeUpsertDirtyCheck(ctx, kind, id, existingProps, inputProps),\n      }),\n      executeDelete: (kind, id, backend) =>\n        executeEdgeDelete(ctx, kind, id, backend),\n      executeDeleteBatch: (kind, ids, backend) =>\n        executeEdgeDeleteBatch(ctx, kind, ids, backend),\n      executeHardDelete: (kind, id, backend) =>\n        executeEdgeHardDelete(ctx, kind, id, backend),\n      temporalRowMatcher: (options) => this.#temporalRowMatcher(options),\n      createQuery: () => this.query(),\n      executeGetOrCreateByEndpoints: (\n        kind,\n        fromKind,\n        fromId,\n        toKind,\n        toId,\n        props,\n        backend,\n        options,\n      ) =>\n        executeEdgeGetOrCreateByEndpoints(\n          ctx,\n          kind,\n          fromKind,\n          fromId,\n          toKind,\n          toId,\n          props,\n          backend,\n          options,\n        ),\n      executeBulkGetOrCreateByEndpoints: (kind, items, backend, options) =>\n        executeEdgeBulkGetOrCreateByEndpoints(\n          ctx,\n          kind,\n          items,\n          backend,\n          options,\n        ),\n      executeFindByEndpoints: (\n        kind,\n        fromKind,\n        fromId,\n        toKind,\n        toId,\n        backend,\n        options,\n      ) =>\n        executeEdgeFindByEndpoints(\n          ctx,\n          kind,\n          fromKind,\n          fromId,\n          toKind,\n          toId,\n          backend,\n          options,\n        ),\n    };\n  }\n\n  // === Query Builder ===\n\n  /**\n   * Creates a query builder for this store.\n   *\n   * @example\n   * ```typescript\n   * const results = await store.query()\n   *   .from(\"Person\", \"p\")\n   *   .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n   *   .select((ctx) => ctx.p)\n   *   .execute();\n   * ```\n   */\n  query(): InitialQueryBuilder<G, \"open\"> {\n    return this.#createQueryForBackend(this.#backend);\n  }\n\n  /**\n   * Runs a read block whose fluent queries automatically use\n   * `executeChecked(expectedSchemaVersion)` when `.execute()` is called.\n   * A schema mismatch aborts the block with `SchemaChangedError`, so callers\n   * can put one reload-and-retry boundary around the whole block.\n   */\n  withCheckedReads<T>(\n    expectedSchemaVersion: number | undefined,\n    fn: (reads: CheckedReadScope<G>) => Promise<T>,\n  ): Promise<T> {\n    const reads: CheckedReadScope<G> = {\n      query: () =>\n        this.#createQueryForBackend(this.#backend, undefined, 1, {\n          value: expectedSchemaVersion,\n        }),\n    };\n    return fn(reads);\n  }\n\n  /**\n   * Internal seam for {@link StoreView.query}: a query builder pinned to a\n   * view's {@link ReadCoordinate} with its temporal axis sealed\n   * (`.temporal()` throws). Not part of the stable public API — construct a\n   * view via {@link Store.view} / {@link Store.asOf} and call `.query()`.\n   */\n  sealedQuery(coordinate: ReadCoordinate): InitialQueryBuilder<G, \"sealed\"> {\n    return this.#createQueryForBackend(\n      this.#recordedReads.backendForCoordinate(coordinate, \"recorded-query\"),\n      coordinate,\n    );\n  }\n\n  #sqlSchema(): SqlSchema {\n    return this.#schema ?? createSqlSchema(this.#backend.tableNames);\n  }\n\n  /**\n   * Internal seam for {@link RecordedStoreView}: reconstruct a node point read\n   * from the recorded-time relation while preserving live getById ordering and\n   * duplicate-input behavior.\n   *\n   * @internal\n   */\n  async recordedNodeGetById<N extends NodeType>(\n    kind: string,\n    id: NodeId<N>,\n    coordinate: ReadCoordinate,\n  ): Promise<Node<N> | undefined> {\n    return this.#recordedReads.nodeGetById(kind, id, coordinate);\n  }\n\n  /**\n   * Internal seam for {@link RecordedStoreView}: reconstruct node point reads\n   * from the recorded-time relation while preserving input order.\n   *\n   * @internal\n   */\n  async recordedNodeGetByIds<N extends NodeType>(\n    kind: string,\n    ids: readonly NodeId<N>[],\n    coordinate: ReadCoordinate,\n  ): Promise<readonly (Node<N> | undefined)[]> {\n    return this.#recordedReads.nodeGetByIds(kind, ids, coordinate);\n  }\n\n  /** @internal Bounded recorded-time node enumeration for RecordedStoreView. */\n  async recordedNodeScan<N extends NodeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ): Promise<RecordedScanPage<Node<N>>> {\n    return this.#recordedReads.nodeScan(kind, coordinate, options);\n  }\n\n  /**\n   * Internal seam for {@link RecordedStoreView}: reconstruct an edge point read\n   * from the recorded-time relation while preserving live getById behavior.\n   *\n   * @internal\n   */\n  async recordedEdgeGetById<E extends AnyEdgeType>(\n    kind: string,\n    id: EdgeId<E>,\n    coordinate: ReadCoordinate,\n  ): Promise<Edge<E> | undefined> {\n    return this.#recordedReads.edgeGetById(kind, id, coordinate);\n  }\n\n  /**\n   * Internal seam for {@link RecordedStoreView}: reconstruct edge point reads\n   * from the recorded-time relation while preserving input order.\n   *\n   * @internal\n   */\n  async recordedEdgeGetByIds<E extends AnyEdgeType>(\n    kind: string,\n    ids: readonly EdgeId<E>[],\n    coordinate: ReadCoordinate,\n  ): Promise<readonly (Edge<E> | undefined)[]> {\n    return this.#recordedReads.edgeGetByIds(kind, ids, coordinate);\n  }\n\n  /** @internal Bounded recorded-time edge enumeration for RecordedStoreView. */\n  async recordedEdgeScan<E extends AnyEdgeType>(\n    kind: string,\n    coordinate: ReadCoordinate,\n    options?: RecordedScanOptions,\n  ): Promise<RecordedScanPage<Edge<E>>> {\n    return this.#recordedReads.edgeScan(kind, coordinate, options);\n  }\n\n  // === Temporal Views ===\n\n  /**\n   * Returns a read-only {@link StoreView} pinned to a valid-time instant.\n   *\n   * The view routes every supported read — `nodes` / `edges` collections,\n   * `query()`, `subgraph()`, and the graph algorithms — through the\n   * `asOf` coordinate, so they observe the graph as it was valid at `T`.\n   * Writes stay on the live `Store`. Mirrors Datomic's `(d/as-of db t)`.\n   *\n   * @example\n   * ```typescript\n   * const past = store.asOf(\"2026-01-01T00:00:00.000Z\");\n   * const alice = await past.nodes.Person.getById(aliceId);\n   * const names = await past\n   *   .query()\n   *   .from(\"Person\", \"p\")\n   *   .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n   *   .select((ctx) => ctx.p.name)\n   *   .execute();\n   * ```\n   *\n   * @param asOf - ISO-8601 timestamp to pin the valid-time coordinate to.\n   */\n  asOf(asOf: string): StoreView<G> {\n    return new StoreView(this, { mode: \"asOf\", asOf });\n  }\n\n  /**\n   * Returns a narrow read-only view pinned to a recorded/system-time instant.\n   *\n   * Direct `store.asOfRecorded(T)` is diagonal bitemporal sugar: it reads the\n   * recorded-time relation at the anchor's logical revision and uses the\n   * anchor's wall-time component for the valid-time axis. Use\n   * `store.asOf(validT).asOfRecorded(recordedT)` when the valid and recorded\n   * axes should differ.\n   *\n   * The returned view exposes only reconstructing-safe reads: query,\n   * subgraph, graph algorithms, and collection point reads.\n   *\n   * Prefer `await store.recordedNow()` over a wall-clock timestamp. The anchor\n   * carries both the graph's strict logical revision and a non-decreasing\n   * physical wall-time high-water mark, so several commits in one millisecond\n   * remain independently addressable without manufacturing timestamp\n   * increments.\n   */\n  asOfRecorded(recordedAsOf: RecordedInstant): RecordedStoreView<G> {\n    const validCoordinate = resolveReadCoordinate(\n      \"asOf\",\n      recordedInstantWallTime(recordedAsOf),\n      \"Use await store.recordedNow() as the anchor, or asRecordedInstant(value) only for an instant previously read from recordedNow().\",\n    );\n    return new RecordedStoreView(\n      this,\n      withRecordedCoordinate(validCoordinate, recordedAsOf),\n    );\n  }\n\n  /**\n   * Returns the latest recorded-time instant captured for this graph — the\n   * recorded high-water mark. After guarding the `undefined` case,\n   * `store.asOfRecorded(checkpoint)` reconstructs everything committed so far, a\n   * deterministic anchor that avoids guessing with the wall clock. Its logical\n   * revision is strictly monotonic per graph while its timestamp is a\n   * non-decreasing physical wall-time high-water mark. Capture each anchor right\n   * after the writes it should cover.\n   *\n   * Returns `undefined` until the first write has been captured, so on a\n   * brand-new graph guard the composition — `asOfRecorded(undefined)` rejects\n   * (an instant is required) rather than reconstructing an empty view. Read the\n   * value first and only pass it to `asOfRecorded` once it is defined.\n   *\n   * **Graph-global, not caller-scoped.** This is the single high-water mark for\n   * the whole graph, advanced by every committed capture from any writer — not\n   * a per-write or per-caller value. An advance between two reads means\n   * \"something committed to this graph in between,\" *not* \"the write this caller\n   * just made landed.\" Do not use a `recordedNow()` advance as a \"did my write\n   * succeed?\" signal: under any concurrent writer to the same graph it both\n   * misses dropped writes and misfires on no-op writes. Confirm a specific write\n   * by observing the write itself (its return value, or `store.transaction(...)`\n   * success), not the global clock.\n   */\n  async recordedNow(): Promise<RecordedInstant | undefined> {\n    if (this.#engineNativeHistory) {\n      return this.#engineRecordedInstant(this.#backend);\n    }\n    if (!this.#captureEnabled) {\n      throw new ConfigurationError(\n        \"recordedNow() requires a store created with { history: true }.\",\n        { code: \"RECORDED_NOW_REQUIRES_HISTORY\" },\n        {\n          suggestion:\n            \"Create the store with createStore(graph, backend, { history: true }) to enable recorded-time capture.\",\n        },\n      );\n    }\n    const recordedAt = await withRecordedRelationsPrecondition(\n      readRecordedClock(this.#backend, this.#sqlSchema(), this.graphId),\n      { dialect: this.#backend.dialect, surface: \"recorded-now\" },\n    );\n    // The clock high-water mark is already a canonical recorded instant; brand\n    // it so `asOfRecorded` accepts it without the caller re-wrapping.\n    return recordedAt === undefined ? undefined : asRecordedInstant(recordedAt);\n  }\n\n  /**\n   * Reads `session`'s own recorded-time revision and mints the `e1:`\n   * {@link RecordedInstant} for it — the ONE place that calls\n   * `recordedTime.revisionNow`, consulted by {@link recordedNow} and\n   * {@link revisionNow} (both on the root backend, so they read the current\n   * COMMITTED revision) and by the two transaction-commit sites that stamp\n   * `TransactionReceipt.recorded` (on the still-open committing transaction\n   * handle, so they read that transaction's PENDING revision — see\n   * `EngineRecordedTimeMembers.revisionNow`'s own doc comment for why that\n   * is the correct value to stamp into a receipt). One owner for \"what\n   * instant does this transaction get,\" beside `flush()`'s own\n   * TypeGraph-capture answer.\n   */\n  async #engineRecordedInstant(\n    session: RecordedTimeSession,\n  ): Promise<RecordedInstant> {\n    const recordedTime = requireRecordedTime(\n      this.#baseBackend,\n      \"engine-native recorded time\",\n    );\n    const revision = await recordedTime.revisionNow(session);\n    return createEngineRecordedInstant(revision.revision, revision.recordedAt);\n  }\n\n  /**\n   * Returns the durable graph revision used by graph branching. It is undefined\n   * until the first successful tracked write, which is itself a stable initial\n   * anchor. Unlike {@link recordedNow}, this is also available on a live Store\n   * created with `{ revisionTracking: true }`.\n   *\n   * Under engine-native ownership, `revisionTrackingEnabled` is always\n   * false (the engine anchor applies instead), but a `history: true` store\n   * still answers from `recordedTime.revisionNow` on the root backend —\n   * the same source `recordedNow()` uses — so this and `recordedNow()`\n   * report the same value there, unlike under TypeGraph-owned tracking\n   * where `revisionTracking: true` without `history` gives this a value\n   * `recordedNow()` refuses to give.\n   *\n   * @internal\n   */\n  async revisionNow(): Promise<RecordedInstant | undefined> {\n    if (this.#engineNativeHistory) {\n      return this.#engineRecordedInstant(this.#backend);\n    }\n    if (!this.#revisionTrackingEnabled) return undefined;\n    return readRecordedClock(this.#backend, this.#sqlSchema(), this.graphId);\n  }\n\n  /**\n   * Returns the durable random namespace for this graph's revision clock. A\n   * tracked base token combines it with {@link revisionNow}, preventing a\n   * branch from one independent store from matching a coincident timestamp in\n   * another store.\n   *\n   * Reads the origin row fresh on every call rather than caching it on this\n   * `Store` instance: two `Store` objects can legitimately observe the same\n   * graph (a second live `Store` opened over the same backend/graphId), and\n   * only one of them runs `clear()`'s origin rotation at a time. A cached\n   * copy on the OTHER instance would keep answering with the pre-rotation\n   * nonce until that instance happened to be recreated — `computeBaseVersion`\n   * would then mint a stale anchor from it, and every merge into that\n   * instance would fail at commit for no reason visible to the caller.\n   * `ensureRevisionOrigin`'s own `INSERT … ON CONFLICT DO NOTHING` already\n   * makes concurrent first-time minting safe without a per-Store memo.\n   *\n   * @internal\n   */\n  async revisionOriginNow(): Promise<string> {\n    if (!this.#revisionTrackingEnabled) {\n      throw new ConfigurationError(\n        \"revisionOriginNow() requires revisionTracking: true or history: true.\",\n        { code: \"REVISION_ORIGIN_REQUIRES_TRACKING\" },\n      );\n    }\n    return ensureRevisionOrigin(\n      this.#baseBackend,\n      this.#recordedRevisionOrigins,\n      this.#sqlSchema(),\n      this.graphId,\n    );\n  }\n\n  /**\n   * Returns a read-only {@link StoreView} pinned to an arbitrary public\n   * temporal mode. Use {@link Store.asOf} for the common valid-time case;\n   * reach for `view` to pin `\"current\"`, `\"includeEnded\"`, or\n   * `\"includeTombstones\"`.\n   *\n   * @example\n   * ```typescript\n   * const withTombstones = store.view({ mode: \"includeTombstones\" });\n   * const everyEverVersion = await withTombstones.nodes.Person.find();\n   * ```\n   *\n   * @param coordinate - The `(mode, asOf)` coordinate to pin. `asOf` is\n   *   required when `mode` is `\"asOf\"` and rejected for every other mode.\n   */\n  view(coordinate: StoreViewCoordinate): StoreView<G> {\n    return new StoreView(this, coordinate);\n  }\n\n  /**\n   * Returns a read-only {@link StoreView} pinned to the current instant,\n   * captured once at construction — a stable point-in-time snapshot. Unlike\n   * `store.view({ mode: \"current\" })` (which tracks \"now\" live and can read\n   * different surfaces against slightly different clocks), a snapshot pins one\n   * `asOf` timestamp, so every surface observes the same instant. Sugar for\n   * `store.asOf(new Date().toISOString())`; mirrors Datomic's `(d/db conn)`.\n   *\n   * @example\n   * ```typescript\n   * const snap = store.snapshot();\n   * // Every read on `snap` sees the graph as of one fixed instant.\n   * const a = await snap.nodes.Person.find();\n   * const r = await snap.reachable(rootId, { edges: [\"knows\"] });\n   * ```\n   */\n  snapshot(): StoreView<G> {\n    return this.asOf(nowIso());\n  }\n\n  // === Search ===\n\n  /**\n   * Search-related operations (fulltext, hybrid, and rebuild).\n   *\n   * All search methods live under this facade to keep the top-level\n   * Store API focused on CRUD + graph traversal. The facade is\n   * lazy-initialized and cached for the lifetime of the store.\n   *\n   * @example\n   * ```typescript\n   * // Fulltext\n   * const hits = await store.search.fulltext(\"Document\", {\n   *   query: \"climate warming\",\n   *   limit: 10,\n   *   includeSnippets: true,\n   * });\n   *\n   * // Hybrid (vector + fulltext fused with RRF)\n   * const ranked = await store.search.hybrid(\"Document\", {\n   *   limit: 10,\n   *   vector: { fieldPath: \"embedding\", queryEmbedding: vec },\n   *   fulltext: { query: \"climate warming\" },\n   * });\n   *\n   * // Rebuild index after schema change\n   * const stats = await store.search.rebuildFulltext();\n   * ```\n   */\n  get search(): StoreSearch<G> {\n    if (this.#search === undefined) {\n      this.#search = new StoreSearch<G>({\n        graphId: this.graphId,\n        backend: this.#backend,\n        registry: this.#registry,\n        createQuery: () => this.query(),\n        batchPointRead: this.#batchPointRead,\n      });\n    }\n    return this.#search;\n  }\n\n  // === Batch Query Execution ===\n\n  /**\n   * Runs several queries in sequence, returning a typed tuple. The portable\n   * guarantee is N serialized query executions — never one round trip.\n   *\n   * **Cost.** At least one statement per query, sometimes two: a query whose\n   * selective-field mapping falls back re-runs as a full fetch, and that\n   * fallback is detected *after* the selective statement has already\n   * executed. It clears the fast path, so a reused query instance pays the\n   * double only once — but the builder is immutable, so a query rebuilt per\n   * request pays it every request.\n   *\n   * With `backend.capabilities.execution.interactiveTransactions` the queries share one\n   * transaction; how that reaches the wire is the adapter's business. A SQL\n   * backend frames them with `begin`/`commit`, putting a networked one at\n   * N+2 round trips *at best*, while Durable Objects use an ambient storage\n   * transaction with no framing statements. Without transactions there is no\n   * framing. Connection reuse is a separate question from transaction\n   * support: the no-transaction path passes the same backend object, so an\n   * adapter may reuse one client there too. The portable guarantee is only\n   * that at most one query is in flight at a time.\n   *\n   * **Not a snapshot by default.** PostgreSQL defaults to read-committed\n   * isolation, so a later query can observe a commit the earlier ones did not.\n   * When multiple reads need one stable snapshot, use `tx.query()` or the\n   * transaction's set-oriented reads inside `store.transaction(fn, {\n   * isolationLevel: \"repeatable_read\" })`. `tx.batchOnce()` is one statement\n   * regardless of isolation level. Transaction reads require a backend with\n   * interactive transactions, and a history-enabled store on PostgreSQL\n   * additionally requires `accessMode: \"read_only\"` for a read-only transaction.\n   *\n   * **Will not fix an N+1.** Serializing N queries does not reduce their\n   * number. The alternatives are set-oriented or chunked rather than\n   * fixed-cost: `.traverse()` compiles a whole chain to one statement;\n   * `store.subgraph()` costs 2 statements on SQLite and 3 on PostgreSQL\n   * however large the result; `getByIds()` issues one statement per\n   * bind-limit chunk, falling back to one per distinct id where the backend\n   * exposes no batch read; `bulkFindByIndex()` costs one probe plus that same\n   * chunked hydration.\n   *\n   * **Versus `Promise.all`.** Workload- and adapter-dependent in both\n   * directions. `Promise.all` overlaps its queries against a pool with idle\n   * capacity, but it does not necessarily hold N connections, and against a\n   * single client or a saturated pool it queues. `batch()` keeps at most one\n   * query in flight, so it pays the sum of their latencies — but it can still\n   * come out ahead where connection acquisition dominates. Measure rather\n   * than assume.\n   *\n   * Read-only — use `bulkCreate`, `bulkInsert`, etc. for write batching.\n   *\n   * @example\n   * ```typescript\n   * const [people, companies] = await store.batch(\n   *   store.query()\n   *     .from(\"Person\", \"p\")\n   *     .select((ctx) => ({ id: ctx.p.id, name: ctx.p.name })),\n   *   store.query()\n   *     .from(\"Company\", \"c\")\n   *     .select((ctx) => ({ id: ctx.c.id, name: ctx.c.name }))\n   *     .orderBy(\"c\", \"name\", \"asc\")\n   *     .limit(5),\n   * );\n   * // people:    readonly { id: string; name: string }[]\n   * // companies: readonly { id: string; name: string }[]\n   * ```\n   *\n   * @param queries - Two or more executable queries (from `.select()` or set operations)\n   * @returns A tuple with per-query typed results, preserving input order\n   */\n  async batch<\n    const Queries extends readonly [\n      BatchableQuery<unknown>,\n      BatchableQuery<unknown>,\n      ...BatchableQuery<unknown>[],\n    ],\n  >(...queries: Queries): Promise<BatchResults<Queries>> {\n    // batch() is read-only, so it routes through the uncaptured backend. Going\n    // through the capture wrapper would open a recorded-capture transaction\n    // scope — which demands executeStatement on the transaction target — for a\n    // path that performs no writes and needs no capture.\n    return runOptionallyInTransaction(this.#baseBackend, async (target) => {\n      const queryBackend = this.#createHookedQueryBackend(target);\n      const results: unknown[] = [];\n      for (const query of queries) {\n        const result = await query.executeOn(queryBackend);\n        results.push(result);\n      }\n      return results as BatchResults<Queries>;\n    });\n  }\n\n  /**\n   * Executes independent relational queries as exactly one SQL statement and\n   * returns their typed results in input order. An empty input executes zero\n   * statements.\n   *\n   * Each read is embedded as a CTE and its rows are returned through a JSON\n   * envelope. Unlike {@link batch}, this method opens no transaction and has\n   * no sequential fallback: one call means one statement on every supported\n   * backend. Fluent queries and the reads built by the callback are composable\n   * here.\n   */\n  async batchOnce<const Queries extends OneStatementBatchReads>(\n    build: (read: BatchReadBuilder<G>) => Queries,\n    options?: BatchOnceOptions,\n  ): Promise<OneStatementBatchResults<Queries>> {\n    return this.#batchOnceForBackend(this.#baseBackend, 1, build, options);\n  }\n\n  #createBatchReadBuilder(\n    backend: GraphBackend | TransactionBackend,\n    attempt: number,\n  ): BatchReadBuilder<G> {\n    return {\n      neighbors: (source, options) => {\n        this.#assertNeighborKinds(source, options.edges);\n        return createNeighborRead(\n          this.#neighborContext(backend, attempt),\n          source,\n          options,\n        );\n      },\n      countNeighbors: (source, options) => {\n        this.#assertNeighborKinds(source, options.edges);\n        return createNeighborCountRead(\n          this.#neighborContext(backend, attempt),\n          source,\n          options,\n        );\n      },\n      subgraph: (rootId, options) =>\n        this.#createSubgraphRead(rootId, options, backend, attempt),\n    };\n  }\n\n  async #batchOnceForBackend<const Queries extends OneStatementBatchReads>(\n    backend: GraphBackend | TransactionBackend,\n    attempt: number,\n    build: (read: BatchReadBuilder<G>) => Queries,\n    options?: BatchOnceOptions,\n  ): Promise<OneStatementBatchResults<Queries>> {\n    return withPinnedReadInstant(() =>\n      executeOneStatementBatch(\n        this.#createHookedQueryBackend(backend, attempt),\n        this.graphId,\n        build(this.#createBatchReadBuilder(backend, attempt)),\n        options,\n      ),\n    );\n  }\n\n  /** Reads hydrated adjacent nodes and their connecting edges in one statement. */\n  async neighbors<const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: NeighborReadOptions<G, K>,\n  ): Promise<readonly NeighborResult<G, K>[]> {\n    this.#assertNeighborKinds(source, options.edges);\n    return readNeighbors(this.#neighborContext(), source, options);\n  }\n\n  /** Counts visible relationships to adjacent nodes without hydrating them. */\n  async countNeighbors<const K extends EdgeKinds<G>>(\n    source: GraphNodeReference<G>,\n    options: Omit<NeighborReadOptions<G, K>, \"limit\" | \"orderBy\">,\n  ): Promise<number> {\n    this.#assertNeighborKinds(source, options.edges);\n    return countNeighborsImpl(this.#neighborContext(), source, options);\n  }\n\n  #neighborContext(\n    backend: GraphBackend | TransactionBackend = this.#backend,\n    attempt = 1,\n  ): Parameters<typeof readNeighbors<G, EdgeKinds<G>>>[0] {\n    return {\n      graphId: this.graphId,\n      backend: this.#createHookedQueryBackend(backend, attempt),\n      schema: this.#sqlSchema(),\n      defaultTemporalMode: this.#graph.defaults.temporalMode,\n      registry: this.#registry,\n    };\n  }\n\n  #assertNeighborKinds(\n    source: GraphNodeReference<G>,\n    edgeKinds: readonly EdgeKinds<G>[],\n  ): void {\n    if (!Object.hasOwn(this.#graph.nodes, source.kind)) {\n      throw new KindNotFoundError(source.kind, \"node\", {\n        graphId: this.graphId,\n      });\n    }\n    for (const edgeKind of edgeKinds) {\n      if (!Object.hasOwn(this.#graph.edges, edgeKind)) {\n        throw new KindNotFoundError(edgeKind, \"edge\", {\n          graphId: this.graphId,\n        });\n      }\n    }\n  }\n\n  /**\n   * Reads several edge kinds from heterogeneous source nodes with round trips\n   * independent of the number of licensed edge/source-kind combinations.\n   *\n   * Results are flattened in source-group/id order. Repeated sources receive\n   * independent edge arrays, and sources with no matching edges remain present\n   * with an empty array. Inputs that exceed the backend bind budget are split\n   * into source chunks without splitting one source across statements.\n   */\n  async bulkFindEdgesFrom<const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesFromParams<G, K>,\n    options?: EdgeBulkFindEndpointOptions,\n  ): Promise<readonly BulkFindEdgesFromResult<G, K>[]> {\n    return this.#bulkFindEdgesByEndpoint(\"from\", params, options);\n  }\n\n  /** Reverse-direction mirror of bulkFindEdgesFrom, grouped by target. */\n  async bulkFindEdgesTo<const K extends EdgeKinds<G>>(\n    params: BulkFindEdgesToParams<G, K>,\n    options?: EdgeBulkFindEndpointOptions,\n  ): Promise<readonly BulkFindEdgesToResult<G, K>[]> {\n    const results = await this.#bulkFindEdgesByEndpoint(\n      \"to\",\n      { sources: params.targets, edgeKinds: params.edgeKinds },\n      options,\n    );\n    return results.map(({ source, edges }) => ({ target: source, edges }));\n  }\n\n  async #bulkFindEdgesByEndpoint<const K extends EdgeKinds<G>>(\n    side: \"from\" | \"to\",\n    params: BulkFindEdgesFromParams<G, K>,\n    options?: EdgeBulkFindEndpointOptions,\n  ): Promise<readonly BulkFindEdgesFromResult<G, K>[]> {\n    const operation = side === \"from\" ? \"bulkFindEdgesFrom\" : \"bulkFindEdgesTo\";\n    const sources: readonly GraphNodeReference<G>[] = params.sources.flatMap(\n      (group) => {\n        if (!Object.hasOwn(this.#graph.nodes, group.kind)) {\n          throw new KindNotFoundError(group.kind, \"node\", {\n            graphId: this.graphId,\n          });\n        }\n        return group.ids.map((id) => ({ kind: group.kind, id }));\n      },\n    );\n    for (const edgeKind of params.edgeKinds) {\n      if (!Object.hasOwn(this.#graph.edges, edgeKind)) {\n        throw new KindNotFoundError(edgeKind, \"edge\", {\n          graphId: this.graphId,\n        });\n      }\n    }\n\n    if (sources.length === 0 || params.edgeKinds.length === 0) {\n      return sources.map((source) => ({ source, edges: [] }));\n    }\n\n    const readEndpointSet =\n      this.#baseBackend.findEdgesByHeterogeneousEndpointSet;\n    if (readEndpointSet === undefined) {\n      throw new ConfigurationError(\n        `store.${operation}() requires a backend that can read heterogeneous endpoint and edge-kind sets in set-oriented statements.`,\n        {\n          backend: this.#baseBackend.dialect,\n          capability: \"findEdgesByHeterogeneousEndpointSet\",\n          operation,\n        },\n        {\n          suggestion: `Use per-edge-kind ${side === \"from\" ? \"bulkFindFrom\" : \"bulkFindTo\"} calls explicitly if that round-trip tradeoff is acceptable.`,\n        },\n      );\n    }\n\n    const limitPerInput = options?.limitPerInput;\n    if (\n      limitPerInput !== undefined &&\n      (!Number.isInteger(limitPerInput) || limitPerInput <= 0)\n    ) {\n      throw new ValidationError(\n        \"bulk endpoint reads require limitPerInput to be a positive integer\",\n        {\n          entityType: \"edge\",\n          kind: params.edgeKinds.join(\",\"),\n          issues: [\n            {\n              path: \"limitPerInput\",\n              message: `Expected a positive integer, received ${String(limitPerInput)}`,\n              code: \"invalid_value\",\n            },\n          ],\n        },\n      );\n    }\n\n    const temporal = resolveTemporalReadParams(\n      options,\n      this.#graph.defaults.temporalMode,\n    );\n    const endpoints: FindEdgesByHeterogeneousEndpointSetParams[\"endpoints\"] =\n      sources;\n    const rows = await readEndpointSet({\n      graphId: this.graphId,\n      side,\n      endpoints,\n      edgeKinds: params.edgeKinds,\n      ...(limitPerInput !== undefined &&\n        this.#baseBackend.capabilities.windowFunctions && {\n          limitPerEndpoint: limitPerInput,\n        }),\n      ...temporal,\n    });\n\n    const edgesBySource = new Map<string, GraphEdgeForKinds<G, K>[]>();\n    for (const row of rows) {\n      const edge = rowToEdge(row) as GraphEdgeForKinds<G, K>;\n      const key =\n        side === \"from\" ?\n          `${edge.fromKind}\\0${edge.fromId}`\n        : `${edge.toKind}\\0${edge.toId}`;\n      const bucket = edgesBySource.get(key);\n      if (bucket === undefined) edgesBySource.set(key, [edge]);\n      else bucket.push(edge);\n    }\n\n    return sources.map((source) => {\n      const bucket = edgesBySource.get(`${source.kind}\\0${source.id}`) ?? [];\n      const edges =\n        limitPerInput === undefined ?\n          [...bucket]\n        : bucket.slice(0, limitPerInput);\n      return { source, edges };\n    });\n  }\n\n  /**\n   * Token-validated sibling of `bulkFindEdgesFrom` for persisted runtime kinds.\n   * Validation and type recovery happen here; execution delegates to the same\n   * set-oriented backend path as the compile-time API.\n   */\n  async bulkFindRuntimeEdgesFrom<\n    NT extends RuntimeNodeKind,\n    ET extends RuntimeEdgeKind,\n  >(\n    params: BulkFindRuntimeEdgesFromParams<NT, ET>,\n    options?: EdgeBulkFindEndpointOptions,\n  ): Promise<readonly BulkFindRuntimeEdgesFromResult<NT, ET>[]> {\n    const sources = params.sources.map((group) => ({\n      kind: this.#resolveRuntimeKind(group.kind, \"node\"),\n      ids: group.ids,\n    }));\n    const edgeKinds = params.edgeKinds.map((token) =>\n      this.#resolveRuntimeKind(token, \"edge\"),\n    );\n    const result = await this.bulkFindEdgesFrom(\n      {\n        sources,\n        edgeKinds,\n      } as unknown as BulkFindEdgesFromParams<G, EdgeKinds<G>>,\n      options,\n    );\n    return result as unknown as readonly BulkFindRuntimeEdgesFromResult<\n      NT,\n      ET\n    >[];\n  }\n\n  // === Subgraph Extraction ===\n\n  /**\n   * Extracts a typed subgraph by traversing from a root node.\n   *\n   * Performs a BFS traversal from `rootId` following the specified edge kinds,\n   * returning an indexed result with adjacency maps for immediate traversal.\n   *\n   * @example\n   * ```typescript\n   * const sg = await store.subgraph(run.id, {\n   *   edges: [\"has_task\", \"runs_agent\", \"uses_skill\"],\n   *   maxDepth: 4,\n   * });\n   *\n   * // Root node (the traversal starting point)\n   * console.log(sg.root?.kind);\n   *\n   * // Lookup by ID\n   * const task = sg.nodes.get(taskId);\n   *\n   * // Forward adjacency: edges of a kind from a node\n   * const taskEdges = sg.adjacency.get(run.id)?.get(\"has_task\") ?? [];\n   *\n   * // Reverse adjacency: edges of a kind pointing to a node\n   * const parentEdges = sg.reverseAdjacency.get(taskId)?.get(\"has_task\") ?? [];\n   * ```\n   */\n  async subgraph<\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: SubgraphOptions<G, EK, NK, P>,\n  ): Promise<SubgraphResult<G, NK, EK, P>> {\n    // The public surface is valid-time only (`recordedAsOf` is typed `never`).\n    // Guard JS callers who bypass the type so a leaked recorded pin can't\n    // silently switch this read onto the recorded relation; recorded subgraph\n    // reads come through subgraphAtCoordinate (store.asOfRecorded(...).subgraph).\n    this.#assertPublicSubgraphOptions(options);\n    // After the guard, the public read is just the coordinate path with no\n    // recorded pin — delegate so the executeSubgraph wiring lives in one place.\n    return this.subgraphAtCoordinate(rootId, options);\n  }\n\n  #createSubgraphRead<\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: SubgraphOptions<G, EK, NK, P>,\n    backend: GraphBackend | TransactionBackend = this.#baseBackend,\n    attempt = 1,\n  ): SubgraphRead<G, NK, EK, P> {\n    this.#assertPublicSubgraphOptions(options);\n    return createSubgraphRead({\n      graph: this.#graph,\n      graphId: this.graphId,\n      rootId,\n      backend: this.#createHookedQueryBackend(backend, attempt),\n      dialect: getDialect(backend.dialect),\n      schema: this.#schema,\n      recordedReadBinding: this.#recordedReadBinding,\n      options,\n    });\n  }\n\n  #assertPublicSubgraphOptions(options: unknown): void {\n    assertNoRecordedCoordinate(options, {\n      code: \"SUBGRAPH_RECORDED_ASOF_INTERNAL_ONLY\",\n      message:\n        \"recordedAsOf is only available through store.asOfRecorded(...).subgraph(...).\",\n      suggestion:\n        \"Use store.asOfRecorded(recordedAt).subgraph(rootId, options) instead of passing recordedAsOf directly.\",\n    });\n  }\n\n  /**\n   * Internal seam for {@link StoreView} / {@link RecordedStoreView}: runs a\n   * subgraph with a coordinate already flattened into the options (including a\n   * recorded/system-time pin). Trusted caller — the public {@link Store.subgraph}\n   * is the guarded entry point.\n   *\n   * @internal\n   */\n  subgraphAtCoordinate<\n    const EK extends EdgeKinds<G>,\n    const NK extends NodeKinds<G> = NodeKinds<G>,\n    const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n  >(\n    rootId: NodeId<AllNodeTypes<G>>,\n    options: InternalSubgraphOptions<G, EK, NK, P>,\n  ): Promise<SubgraphResult<G, NK, EK, P>> {\n    const coordinate = resolveReadCoordinate(\n      options.temporalMode ?? this.#graph.defaults.temporalMode,\n      options.asOf,\n    );\n    const readCoordinate =\n      options.recordedAsOf === undefined ?\n        coordinate\n      : withRecordedCoordinate(coordinate, options.recordedAsOf);\n    return executeSubgraph({\n      graph: this.#graph,\n      graphId: this.graphId,\n      rootId,\n      backend: this.#recordedReads.backendForCoordinate(\n        readCoordinate,\n        \"recorded-subgraph\",\n      ),\n      dialect: getDialect(this.#backend.dialect),\n      schema: this.#schema,\n      recordedReadBinding: this.#recordedReadBinding,\n      options,\n    });\n  }\n\n  /**\n   * Internal seam for StoreView graph algorithms at a pinned coordinate.\n   *\n   * @internal\n   */\n  algorithmsAtCoordinate(\n    coordinate: ReadCoordinate,\n  ): InternalGraphAlgorithms<G> {\n    return createGraphAlgorithms<G>({\n      graphId: this.graphId,\n      graph: this.#graph,\n      registry: this.#registry,\n      backend: this.#recordedReads.backendForCoordinate(\n        coordinate,\n        \"recorded-graph-algorithm\",\n      ),\n      schema: this.#schema,\n      recordedReadBinding: this.#recordedReadBinding,\n      defaultTemporalMode: this.#graph.defaults.temporalMode,\n      allowRecordedAsOf: coordinate.recorded !== undefined,\n    });\n  }\n\n  // === Transactions ===\n\n  /**\n   * Executes a function within a transaction.\n   *\n   * The transaction context provides the same collection API as the Store:\n   * - `tx.nodes.Person.create(...)` - Create a node\n   * - `tx.edges.worksAt.create(...)` - Create an edge\n   * - `tx.backend` - a read-only backend projection bound to this transaction\n   *\n   * {@link AdapterStore} transaction callbacks additionally expose `tx.sql`,\n   * the adapter-native handle bound to the same atomic boundary. Branch on\n   * `tx.sqlAvailability`: `\"available\"` carries the handle and `\"unavailable\"`\n   * carries `undefined`. History and revision-tracking contexts make `tx.sql`\n   * unusable in their public types; reflective or type-suppressed runtime\n   * access throws because raw SQL would bypass capture or the revision anchor.\n   * Use typed collections or {@link AdapterStore.withRecordedTransaction} in\n   * those modes.\n   *\n   * @example\n   * ```typescript\n   * await store.transaction(async (tx) => {\n   *   const person = await tx.nodes.Person.create({ name: \"Alice\" });\n   *   const company = await tx.nodes.Company.create({ name: \"Acme\" });\n   *   await tx.edges.worksAt.create(\n   *     { kind: \"Person\", id: person.id },\n   *     { kind: \"Company\", id: company.id },\n   *     { role: \"Engineer\" }\n   *   );\n   * });\n   * ```\n   *\n   * @example Cross-store write via `tx.sql` (graph-owned boundary):\n   * ```typescript\n   * await store.transaction(async (tx) => {\n   *   await tx.nodes.Document.update(documentId, props);\n   *   if (tx.sqlAvailability !== \"available\") {\n   *     throw new Error(\"This operation requires a SQL-backed transaction\");\n   *   }\n   *   // Narrowing makes the precisely typed native handle available.\n   *   const sqlTx = tx.sql as NodePgDatabase;\n   *   await sqlTx.insert(documentVersions).values(versionRow);\n   * });\n   * ```\n   *\n   * **`tx.sql` shares the one pinned connection — await it, don't overlap it.**\n   * TypeGraph serializes the statements *its own* collections issue, so a\n   * `Promise.all` of graph writes is safe. A statement you issue through\n   * `tx.sql` bypasses that queue: run it concurrently with a graph write (or\n   * with another `tx.sql` statement) and two queries race on the one\n   * transaction connection — the exact overlap Postgres removes in `pg@9`.\n   * Await each `tx.sql` statement before starting the next write. TypeGraph\n   * cannot police this: it never sees the raw handle's traffic, so it also\n   * cannot drain a raw statement still in flight when the transaction commits.\n   *\n   * **Backends without transactions.** When `backend.capabilities.execution.interactiveTransactions`\n   * is `false` (Cloudflare D1, `drizzle-orm/neon-http`), this method refuses\n   * before invoking the callback. A callback-shaped API that silently applies\n   * writes one by one is not a transaction and would make the atomicity\n   * contract depend on backend selection. Use the Store's ordinary write\n   * methods for deliberately non-atomic work, or provide a backend with real\n   * transaction support:\n   *\n   * ```typescript\n   * if (backend.capabilities.execution.interactiveTransactions) {\n   *   await store.transaction(async (tx) => { ... });\n   * }\n   * ```\n   *\n   * @param fn The callback run inside the transaction boundary. See\n   *   {@link StoreTransactionOptions} for what `options.retry` requires of it.\n   * @param options Optional {@link StoreTransactionOptions}. Every field but\n   *   `retry` is forwarded to the backend verbatim (e.g.\n   *   `isolationLevel: \"serializable\"` on Postgres — backends without\n   *   isolation-level support ignore it). On non-transactional backends, the\n   *   method refuses before invoking `fn`. A concurrent schema commit can make\n   *   a snapshot-isolated PostgreSQL write fail with the database's normal\n   *   serialization error; without `retry` that surfaces as\n   *   `TransactionConflictError` after one try. Stores created with\n   *   `{ history: true }` require read-committed semantics for recorded-clock\n   *   capture.\n   */\n  transaction<T>(\n    this: AdapterHistoryStore<G, TNativeTransaction>,\n    fn: (\n      tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ): Promise<T>;\n\n  transaction<T>(\n    fn: (tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ): Promise<T>;\n\n  async transaction<T>(\n    fn:\n      | ((tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>)\n      | ((\n          tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n    options?: StoreTransactionOptions,\n  ): Promise<T> {\n    const invoke = fn as (\n      tx: AdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>;\n    const { result } = await this.#runTransaction(\n      invoke,\n      options,\n      undefined,\n      \"store.transaction()\",\n    );\n    return result;\n  }\n\n  /**\n   * Runs a transaction exactly like {@link transaction} and additionally\n   * returns a {@link TransactionOutcome} whose receipt summarizes the\n   * completed write intents on the transaction-scoped collection surface.\n   *\n   * A dedicated method (rather than an option on `transaction()`) keeps the\n   * return type tied to static dispatch: forwarding options through wrappers\n   * can never change what a call returns. See {@link TransactionReceipt} for\n   * exact count semantics.\n   *\n   * The receipt does not count writes that bypass the `tx.nodes.*` /\n   * `tx.edges.*` collections, such as direct backend writes, raw SQL, or\n   * import helpers. The adopted-commit sibling\n   * {@link AdapterStore.withRecordedTransaction} also returns a\n   * {@link TransactionOutcome}; only `withTransaction` (whose commit belongs\n   * entirely to the caller with no flush point) produces no receipt. On\n   * non-transactional backends, this method refuses before invoking the\n   * callback, so it cannot produce a receipt. Use ordinary Store writes when\n   * deliberately performing non-atomic work.\n   *\n   * For stores created with `{ history: true }`, `receipt.recorded` is the\n   * recorded commit instant this transaction allocated for the store's\n   * graph, or `undefined` when nothing was captured or requested.\n   *\n   * The callback receives a {@link MeasurableTransactionContext}: call\n   * `tx.measure((scoped) => ...)` to scope a sub-receipt to the writes made\n   * through the `scoped` context (e.g. to attribute writes to user code the\n   * caller invokes, excluding its own bookkeeping written through `tx`). See\n   * {@link MeasurableTransactionContext} for semantics.\n   *\n   * @example\n   * ```typescript\n   * const outcome = await store.transactionWithReceipt(async (tx) => {\n   *   const alice = await tx.nodes.Person.create({ name: \"Alice\" });\n   *   return alice.id;\n   * });\n   * outcome.result; // Alice's id\n   * outcome.receipt.writes; // { nodes: { Person: 1 }, edges: {}, total: 1 }\n   * ```\n   */\n  transactionWithReceipt<T>(\n    this: AdapterHistoryStore<G, TNativeTransaction>,\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ): Promise<TransactionOutcome<T>>;\n\n  transactionWithReceipt<T>(\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ): Promise<TransactionOutcome<T>>;\n\n  async transactionWithReceipt<T>(\n    fn:\n      | ((\n          tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>)\n      | ((\n          tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n    options?: StoreTransactionOptions,\n  ): Promise<TransactionOutcome<T>> {\n    const invoke = fn as (\n      tx: AdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>;\n    // The receipt recorder is attempt-scoped (a rolled-back attempt's counts\n    // must never survive into the one that commits), so `#runTransaction`\n    // builds a fresh one per attempt from this factory and hands back the\n    // committed attempt's own recorder.\n    const { result, recordedByGraph, recorder } = await this.#runTransaction(\n      invoke,\n      options,\n      createTransactionReceiptRecorder,\n      \"store.transactionWithReceipt()\",\n    );\n    return transactionOutcome(\n      result,\n      requireDefined(\n        recorder,\n        \"store.transactionWithReceipt(): the committed attempt produced no receipt recorder\",\n      ),\n      recordedByGraph,\n      this.graphId,\n    );\n  }\n\n  async #runTransaction<T>(\n    invoke: (\n      tx: AdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options: StoreTransactionOptions | undefined,\n    createReceiptRecorder: (() => TransactionReceiptRecorder) | undefined,\n    operation: \"store.transaction()\" | \"store.transactionWithReceipt()\",\n  ): Promise<TransactionRunResult<T>> {\n    if (!this.#backend.capabilities.execution.interactiveTransactions) {\n      const transactionVerdict = resolveBatchWriteVerdict(this.#backend, {\n        needs: \"interactive-callback\",\n      });\n      throw new UnsupportedBackendCapabilityError(\n        operation,\n        \"execution.interactiveTransactions\",\n        {\n          graphId: this.graphId,\n          dialect: this.#backend.dialect,\n          ...batchRefusalDetails(transactionVerdict),\n        },\n        \"Use a backend with transaction support, or call ordinary Store \" +\n          \"write methods when non-atomic work is intentional.\",\n        batchRefusalSuffix(transactionVerdict),\n      );\n    }\n\n    // `retry` is TypeGraph's own option and is never part of what the\n    // backend sees; every other field forwards verbatim. This is the one\n    // place that strips it.\n    const { retry, ...backendOptions } = options ?? {};\n    const attempts = retry?.attempts ?? 1;\n\n    // #134/#135: no gate here. The backend's transaction() wraps the\n    // tx-scoped fulltext methods so the durable-marker assert fires at\n    // point of use (a cached SELECT, never DDL). A transaction that\n    // never touches fulltext requires no fulltext initialization.\n    //\n    // A schema-version fence is acquired and validated at every managed write\n    // when this Store came from schema reconciliation. A TypeGraph-owned Store\n    // transaction on a bundled backend is the narrow exception: its first\n    // managed write acquires the fence and leases that success to later\n    // managed writes. Such a callback has neither a nested transaction runner\n    // nor a native SQL handle, so no savepoint can predate that acquisition;\n    // adapter-native and caller-adopted transactions retain the per-write\n    // check because their raw SQL can roll back a savepoint and release a\n    // PostgreSQL row lock acquired after it.\n    // Snapshot-isolated transactions retain their normal serialization-failure\n    // semantics rather than validating a stale version after a concurrent\n    // commit. The separate recorded graph lock is still taken at each write\n    // boundary; callers that need read-before-write serialization for graph\n    // data acquire that lock explicitly.\n    //\n    // Operation hooks inside the callback run BUFFERED: an operation nested\n    // in this transaction completes only when the transaction commits, so its\n    // onOperationEnd is held back until after COMMIT — and converted into\n    // onError when the transaction fails — keeping \"success\" synonymous with\n    // \"durable\" even for tx-scoped collection operations.\n    //\n    // Everything below is the ATTEMPT: `runRetriedUnit` may invoke it more\n    // than once, and every value it touches — the pending buffer, the hook\n    // runners, the receipt recorder, the flush observer — is built fresh on\n    // each call, so a rolled-back attempt leaves nothing for the next one to\n    // read. A retryable failure with attempts left discards this attempt's\n    // buffer without reporting it; a final failure (exhausted budget, or a\n    // failure the retry owner does not recognize) reports it through\n    // `onError` exactly as a non-retried transaction always has, using the\n    // same object `runRetriedUnit` itself will raise. The committed attempt's\n    // buffer is returned rather than flushed here — the flush runs once the\n    // backend transaction has already committed, so it belongs to the caller\n    // of `runRetriedUnit`, past any point a hook's own failure could be\n    // mistaken for a conflict on the transaction that just succeeded.\n    const runAttempt: RetriedUnitAttempt<TransactionRunResult<T>> = async (\n      frame,\n    ) => {\n      const pending: PendingOperationOutcome[] = [];\n      const runHooks = this.#createBufferedHookRunner(pending);\n      const runBulkHooks = this.#createBufferedBulkHookRunner(pending);\n      const receiptRecorder = createReceiptRecorder?.();\n      let recordedByGraph: RecordedFlushInstants | undefined;\n      const transactionOptions =\n        receiptRecorder !== undefined && this.#captureEnabled ?\n          withRecordedFlushObserver(backendOptions, (instants) => {\n            recordedByGraph = instants;\n          })\n        : backendOptions;\n      try {\n        const run = async (\n          txBackend: TransactionBackend,\n          nativeTransaction: TNativeTransaction | undefined,\n        ): Promise<T> => {\n          // A receipt was requested AND this store is engine-native: wrap the\n          // committing session so every write member this transaction body\n          // calls is observed at the point it either changed a row or did\n          // not (`write-touch.ts`'s per-member decision — the same one\n          // TypeGraph-owned capture reads, not a second guess at it), rather\n          // than inferring \"did this transaction write\" from a\n          // collection-level write-INTENT count — that counts a call, not\n          // its effect, so a delete of a missing row or a coalesced no-op\n          // upsert would otherwise still stamp `recorded`. No receipt\n          // requested, or not engine-native: nothing to observe, so no\n          // wrapping. `writeTarget` is the single object\n          // every write in this attempt runs through — capture's decorator\n          // installs the same way, and the schema-fence lease / write-session\n          // maps below key on object identity, so leasing and wrapping must\n          // share the identical target or a write issued through the wrapper\n          // resolves a session/lease the raw `txBackend` registered under.\n          const mutationWitness =\n            this.#engineNativeHistory && receiptRecorder !== undefined ?\n              createMutationWitness()\n            : undefined;\n          const writeTarget =\n            mutationWitness === undefined ? txBackend : (\n              mutationWitness.wrap(txBackend)\n            );\n          if (mutationWitness !== undefined) {\n            // Identity assertions run through a wholly separate seam\n            // (`withRecordedIdentityMutationTarget`) that `wrap`'s overlay\n            // does not cover — register the witness's sink against both\n            // object identities `writeTarget` can be reached through, the\n            // same binding capture uses for its own session-backed sink.\n            registerRecordedIdentityMutationWitness(\n              writeTarget,\n              txBackend,\n              mutationWitness.sink,\n            );\n          }\n          const invokeTransaction = (): Promise<T> =>\n            runInTransactionContext(\n              this.#buildTransactionContext(\n                writeTarget,\n                nativeTransaction,\n                runHooks,\n                receiptRecorder,\n                runBulkHooks,\n                frame.attempt,\n                backendOptions.accessMode !== \"read_only\",\n              ),\n              invoke,\n            );\n          const invokeWithSchemaFenceLease = (): Promise<T> =>\n            this.#adapterBackend === undefined ?\n              withTransactionSchemaFenceLease(\n                {\n                  graphId: this.graphId,\n                  schemaVersion: this.#schemaMetadata.schemaVersion,\n                },\n                writeTarget,\n                invokeTransaction,\n              )\n            : invokeTransaction();\n          const output = await withWriteTransactionSession(\n            writeTarget,\n            {\n              graphId: this.graphId,\n              schemaVersion: this.#schemaMetadata.schemaVersion,\n              historyEnabled: this.#captureEnabled,\n              revisionTrackingEnabled: this.#revisionTrackingEnabled,\n              revisionSchema: this.#sqlSchema(),\n            },\n            invokeWithSchemaFenceLease,\n          );\n          // The engine-native counterpart to capture's flush observer: read\n          // inside the transaction (before its outer COMMIT), on the SAME\n          // committing session `txBackend` is, so `recordedTime.revisionNow`\n          // answers with the PENDING revision this transaction's writes will\n          // land at once it commits, not the last one already committed\n          // before it opened. Exactly once — never once per graph, since an\n          // engine-native store answers for exactly one. Only when the\n          // mutation witness actually saw a write — `TransactionReceipt.recorded`\n          // is undefined for a read-only or no-op engine-native transaction.\n          // TypeGraph-owned capture can instead stamp an explicitly requested\n          // revision without an entity mutation, so a plain `store.transaction()`\n          // or an empty-body `transactionWithReceipt()` neither takes the\n          // extra round trip nor stamps an instant nothing earned.\n          if (mutationWitness?.mutated === true) {\n            recordedByGraph = new Map([\n              [this.graphId, await this.#engineRecordedInstant(txBackend)],\n            ]);\n          }\n          return output;\n        };\n        const result =\n          this.#captureEnabled || this.#adapterBackend === undefined ?\n            await this.#backend.transaction(\n              (txBackend) => run(txBackend, undefined),\n              transactionOptions,\n            )\n          : await this.#adapterBackend.transactionWithNative(\n              (txBackend, nativeTransaction) =>\n                run(txBackend, nativeTransaction),\n              transactionOptions,\n            );\n        // The COMMIT above already succeeded: flushing `onOperationEnd` is\n        // done by the caller of `runRetriedUnit`, not here, so a hook that\n        // throws can never be mistaken for a conflict on an attempt that\n        // already durably committed. See `TransactionRunResult.pending`.\n        return { result, recordedByGraph, recorder: receiptRecorder, pending };\n      } catch (error) {\n        // `frame.willRetry`/`frame.reportedFailure` are the same decision\n        // `runRetriedUnit` itself will apply to this very error — never a\n        // second, independently computed verdict — so the object reported to\n        // `onError` here is always the one the eventual caller also sees.\n        if (!frame.willRetry(error)) {\n          const failure = asError(frame.reportedFailure(error));\n          for (const outcome of pending) {\n            this.#reportError(outcome.ctx, failure);\n          }\n        }\n        throw error;\n      }\n    };\n\n    const runResult = await runRetriedUnit(\n      { operation, attempts, target: this.#backend },\n      runAttempt,\n    );\n    for (const outcome of runResult.pending) {\n      if (outcome.type === \"bulkOperation\") {\n        this.#hooks.onBulkOperationEnd?.(outcome.ctx, {\n          affectedCount: outcome.affectedCount,\n          durationMs: outcome.durationMs,\n        });\n      } else {\n        this.#hooks.onOperationEnd?.(outcome.ctx, {\n          durationMs: outcome.durationMs,\n          outcome: outcome.outcome,\n        });\n      }\n    }\n    return runResult;\n  }\n\n  /**\n   * Adopts a caller-owned, already-open Drizzle transaction so the graph\n   * store and the caller's relational writes commit or roll back as one\n   * Postgres/SQLite transaction (#134).\n   *\n   * Use this when the **relational layer owns the transaction**: the\n   * caller has opened a transaction and needs TypeGraph writes enlisted\n   * on the *same* connection. Unlike {@link transaction}, this opens no\n   * transaction — the caller's transaction is the single commit/rollback\n   * boundary.\n   *\n   * Do not call a managed write on this root Store from inside the caller's\n   * `db.transaction(...)` callback. On a single-connection PostgreSQL handle,\n   * a root-store write opens its own `BEGIN` / `COMMIT`; PostgreSQL accepts the\n   * nested `BEGIN` with a warning, then that `COMMIT` closes the caller's\n   * transaction. Build this adopted context from the callback's `externalTx`\n   * and use its collections for every graph write instead. History-enabled\n   * stores use {@link withRecordedTransaction}, which adopts the same handle\n   * and flushes capture before the caller commits.\n   *\n   * `withTransaction` is driver-agnostic; how the caller opens the\n   * transaction is not. **Async drivers** (node-postgres,\n   * `neon-serverless` Pool, libsql) use `db.transaction(async …)`.\n   * **Synchronous `better-sqlite3`** cannot — its driver rejects an\n   * `async` transaction callback (`Transaction function cannot return a\n   * promise`) and the async continuation would run outside the\n   * rolled-back transaction — so the caller opens the transaction with\n   * explicit `BEGIN`/`COMMIT`/`ROLLBACK` on the single connection\n   * instead. See the \"Cross-Store Transactions\" recipe for both shapes.\n   *\n   * The returned context reuses this store's already-resolved\n   * schema/registry: it runs **no** schema bootstrap, `evolve`, or\n   * migration, and emits **no DDL** inside the caller's transaction.\n   * Fulltext operations assert the durable materialization marker (a\n   * cached SELECT) and throw {@link StoreNotInitializedError} on a\n   * missing/stale/failed marker rather than migrating mid-transaction —\n   * so boot the parent store via `createAdapterStoreWithSchema` once at\n   * startup.\n   *\n   * @example\n   * ```typescript\n   * // Async driver (Postgres / libsql):\n   * await db.transaction(async (sqlTx) => {\n   *   const connector = await createConnectorRow(sqlTx, input); // Drizzle\n   *   const txStore = store.withTransaction(sqlTx);\n   *   await txStore.nodes.ArtifactSource.create({              // TypeGraph\n   *     connectorId: connector.id,\n   *   });\n   * }); // one COMMIT / ROLLBACK across both layers\n   * ```\n   *\n   * **The caller owns the connection — don't overlap writes on it.** The graph\n   * store and your Drizzle writes share the one connection the caller's\n   * transaction pinned. TypeGraph serializes the statements *its* collections\n   * issue, but your raw Drizzle statements (and any graph write run alongside\n   * them) are yours to sequence: a `Promise.all` mixing the two races two\n   * queries on that connection — the overlap Postgres removes in `pg@9`. Await\n   * each write before starting the next.\n   *\n   * Not available when the store was created with `{ history: true }`: a\n   * caller-owned transaction context would let writes happen after capture has\n   * lost its flush point. {@link AdapterHistoryStore} omits this method, while\n   * the runtime guard still throws `ConfigurationError` if the public contract\n   * is bypassed\n   * (`RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`) if the check is\n   * suppressed. Use {@link AdapterStore.withRecordedTransaction} on a history-enabled\n   * store, which adopts the same external transaction but flushes recorded-time\n   * capture before the caller commits.\n   *\n   * @throws {ConfigurationError} when the store has history capture enabled\n   *   (use {@link AdapterStore.withRecordedTransaction} instead), or when the backend\n   *   cannot adopt an external transaction — either it is not a Drizzle\n   *   Postgres/SQLite backend, or `backend.capabilities.execution.interactiveTransactions` is `false`\n   *   (`drizzle-orm/neon-http`, Cloudflare D1, SQLite\n   *   `transactionMode: \"none\"`). A non-atomic fallback is deliberately\n   *   not offered here: the caller's relational write *would* still\n   *   commit, defeating the purpose of cross-store atomicity.\n   * @throws {StoreNotInitializedError} at point of use, when a fulltext\n   *   operation on the returned context observes a missing/stale/failed\n   *   durable materialization marker (parent store not booted via\n   *   `createAdapterStoreWithSchema`). Rolls back the caller's transaction\n   *   without emitting any DDL.\n   */\n  withTransaction(\n    externalTx: TNativeTransaction,\n  ): AdapterTransactionContext<G, TNativeTransaction> {\n    if (this.#captureEnabled) {\n      throw recordedCaptureRequiresCallbackTransactionError();\n    }\n    const adopt = this.#adapterBackend?.adoptTransaction;\n    if (adopt === undefined) {\n      throw new ConfigurationError(\n        \"This backend cannot adopt an external transaction for cross-store \" +\n          \"atomicity. adoptTransaction is provided only by the Drizzle \" +\n          \"Postgres/SQLite backends with transaction support. Check \" +\n          \"backend.capabilities.execution.interactiveTransactions, or run the relational and \" +\n          \"graph writes as separate transactions with manual compensation.\",\n        { capability: \"adoptTransaction\" },\n      );\n    }\n    // The caller already owns the boundary, so `externalTx` *is* the\n    // bound handle — surface it as `tx.sql` for symmetry with the\n    // graph-owned `transaction()` path.\n    return this.#buildTransactionContext(adopt(externalTx), externalTx);\n  }\n\n  /**\n   * Adopts a caller-owned transaction while giving recorded-time capture a\n   * flush point before the caller commits. Required when `history: true` is\n   * enabled because returning a long-lived transaction context would let writes\n   * happen after TypeGraph has lost the chance to close/open recorded rows.\n   *\n   * Capture flushes once, when `fn` resolves. The flush seals the capture\n   * session, so a graph write made through the transaction context *after* `fn`\n   * returns (e.g. retaining `tx` and writing once more before the caller's\n   * COMMIT) throws rather than committing uncaptured — the post-flush write\n   * cannot silently diverge history from live state. This sealing behavior is\n   * unchanged by the receipt return.\n   *\n   * Returns a {@link TransactionOutcome} — the adopted path is the only way to\n   * get exactly-once cursors and graph writes atomically on a history store, so\n   * it surfaces the same receipt `transactionWithReceipt` does: `receipt.writes`\n   * for drop detection (a non-delete change that wrote nothing) and\n   * `receipt.recorded` as the per-transaction replay anchor. Destructure\n   * `{ result, receipt }`:\n   *\n   * ```typescript\n   * const { result, receipt } = await store.withRecordedTransaction(\n   *   externalTx,\n   *   async (tx) => tx.nodes.Document.update(documentId, props),\n   * );\n   * ```\n   *\n   * `receipt.recorded` is the recorded commit instant this transaction allocated\n   * for the store's graph at the flush point (when `fn` resolved), and is\n   * `undefined` when nothing was captured or requested — a read-only `fn`, or a\n   * non-history store (where the receipt still counts write intents but there is\n   * no recorded time). To attribute writes when `fn` invokes user code that also\n   * bookkeeps, use `tx.measure((scoped) => ...)` and have that code write\n   * through the `scoped` context (see {@link MeasurableTransactionContext}).\n   *\n   * Write your own relational tables through the **external transaction handle\n   * you passed in** (`externalTx`) — it *is* the pinned connection. `tx.sql` is\n   * unavailable here (it is a fail-loud guard under history capture, since raw\n   * SQL bypasses recorded-time capture, and `AdapterHistoryTransactionContext` types it\n   * `sql?: never`). Writing through `externalTx` is the sanctioned way to get\n   * cross-store atomicity on a history-enabled store:\n   *\n   * ```typescript\n   * // Async driver (Postgres / libsql):\n   * await db.transaction(async (pgTx) => {\n   *   const { receipt } = await store.withRecordedTransaction(pgTx, async (tx) => {\n   *     await tx.nodes.Document.update(documentId, props); // graph write\n   *   });\n   *   await pgTx.insert(streamCursors).values(cursorRow);  // your own table\n   * }); // one COMMIT / ROLLBACK across both layers\n   * ```\n   *\n   * The graph writes and your `externalTx` statements share the caller's one\n   * pinned connection. TypeGraph serializes the statements its collections\n   * issue; sequence your own raw statements (and don't `Promise.all` them with\n   * graph writes) so two queries never race on that connection.\n   */\n  withRecordedTransaction<T>(\n    this: AdapterHistoryStore<G, TNativeTransaction>,\n    externalTx: TNativeTransaction,\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n  ): Promise<TransactionOutcome<T>>;\n\n  withRecordedTransaction<T>(\n    externalTx: TNativeTransaction,\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n  ): Promise<TransactionOutcome<T>>;\n\n  async withRecordedTransaction<T>(\n    externalTx: TNativeTransaction,\n    fn:\n      | ((\n          tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>)\n      | ((\n          tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n  ): Promise<TransactionOutcome<T>> {\n    const adopt = this.#adapterBackend?.adoptTransaction;\n    if (adopt === undefined) {\n      throw new ConfigurationError(\n        \"This backend cannot adopt an external transaction for recorded-time capture.\",\n        { capability: \"adoptTransaction\" },\n        {\n          suggestion:\n            \"Use a Drizzle PostgreSQL/SQLite backend that can adopt this transaction, use store.transaction(...) on a backend with transaction support, or call ordinary Store writes when non-atomic work is intentional.\",\n        },\n      );\n    }\n    return withAdoptedTransactionScope(externalTx, () =>\n      this.#runAdoptedRecordedTransaction(adopt(externalTx), externalTx, fn),\n    );\n  }\n\n  async #runAdoptedRecordedTransaction<T>(\n    txBackend: TransactionBackend,\n    externalTx: TNativeTransaction,\n    fn:\n      | ((\n          tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>)\n      | ((\n          tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n    originalStore?: StoreImplementation<G, TNativeTransaction>,\n  ): Promise<TransactionOutcome<T>> {\n    if (this.#captureEnabled) {\n      await assertRecordedCaptureTransactionIsolation(txBackend);\n      await lockSchemaVersionForStoreWrite(\n        {\n          graphId: this.graphId,\n          schemaVersion: this.#schemaMetadata.schemaVersion,\n        },\n        txBackend,\n      );\n    }\n    // A uniform `flush → RecordedFlushInstants` shape on both branches keeps the\n    // outcome-building path identical; the non-history branch has no recorded\n    // rows to close, so it flushes to an empty instant map.\n    const scope =\n      this.#captureEnabled ?\n        createRecordedTransactionScope(\n          txBackend,\n          this.#batchPointRead,\n          this.#sqlSchema(),\n        )\n      : {\n          backend: txBackend,\n          flush: (): Promise<RecordedFlushInstants> =>\n            Promise.resolve(EMPTY_RECORDED_FLUSH_INSTANTS),\n        };\n    if (this.#captureEnabled) {\n      await lockRecordedGraphWrite(scope.backend, this.graphId);\n    }\n    const receiptRecorder = createTransactionReceiptRecorder();\n    // See the matching comment at the other engine-native receipt site\n    // (`runAttempt` above): the witness observes real per-member mutations\n    // on the adopted session, not write intents, so a delete of a missing\n    // row or a coalesced no-op upsert through this context leaves\n    // `receipt.recorded` undefined.\n    const mutationWitness =\n      this.#engineNativeHistory ? createMutationWitness() : undefined;\n    const writeTarget =\n      mutationWitness === undefined ?\n        scope.backend\n      : mutationWitness.wrap(scope.backend);\n    if (mutationWitness !== undefined) {\n      // Same registration as the other engine-native receipt site: identity\n      // assertions bypass `wrap`'s overlay entirely, so the witness's sink\n      // needs its own binding to see one.\n      registerRecordedIdentityMutationWitness(\n        writeTarget,\n        scope.backend,\n        mutationWitness.sink,\n      );\n    }\n    const invoke = fn as (\n      tx: AdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>;\n    const executionScope =\n      originalStore === undefined ? undefined : (\n        scopeBackendExecution(writeTarget)\n      );\n    const contextBackend = executionScope?.backend ?? writeTarget;\n    const context = this.#buildTransactionContext(\n      contextBackend,\n      externalTx,\n      undefined,\n      receiptRecorder,\n    );\n    if (originalStore !== undefined) {\n      bindEvolvedTransactionStore(context, originalStore, this);\n    }\n    const finish = async (): Promise<TransactionOutcome<T>> => {\n      const result = await runInTransactionContext(\n        context,\n        async (activeContext) => {\n          try {\n            return await invoke(activeContext);\n          } finally {\n            executionScope?.seal();\n          }\n        },\n      );\n      // Flush allocates the recorded commit instant for this transaction's graph\n      // under TypeGraph-owned capture; under engine-native it is\n      // `recordedTime.revisionNow` read on this SAME adopted session, still\n      // inside the caller's transaction — so it answers with the PENDING\n      // revision this transaction's writes will land at once it commits, not\n      // the last one already committed before it opened. The engine-native\n      // counterpart to `flush()`, called once for this store's one graph, and\n      // only when the mutation witness actually saw a write (TypeGraph-owned\n      // capture may also answer an explicit revision request without a touched\n      // entity. Either way\n      // `transactionOutcome` reads this store's instant out of the returned map\n      // (undefined when nothing was captured or requested) into `receipt.recorded`.\n      const recordedByGraph =\n        mutationWitness?.mutated === true ?\n          new Map([\n            [this.graphId, await this.#engineRecordedInstant(txBackend)],\n          ])\n        : await scope.flush();\n      // Seal the context so a write through a retained `tx` after this returns\n      // fails loud instead of persisting a row the snapshotted receipt can't\n      // count. Under history capture the capture session already sealed on flush\n      // (its guard throws before the live write); this covers the non-history\n      // path, which has no capture session.\n      if (!this.#captureEnabled) receiptRecorder.seal();\n      return transactionOutcome(\n        result,\n        receiptRecorder,\n        recordedByGraph,\n        this.graphId,\n      );\n    };\n    // The schema fence above was acquired before the caller callback. That\n    // makes reuse safe for this history-capture scope: a callback-created\n    // savepoint is necessarily later than the lock, so rolling back to it\n    // cannot release the lock. Seed the lease on the actual derived capture\n    // target, which is what collection writes receive. A savepoint created\n    // before entering this method through the raw external handle is outside\n    // the recorded-capture callback contract and is not covered by this\n    // lease. Seed every exact target a managed mutation can resolve to,\n    // including the raw identity target and the evolved execution-lifetime\n    // target. Adapter/native and non-history adopted paths retain their\n    // per-write fence behavior.\n    return this.#captureEnabled ?\n        withPreAcquiredTransactionSchemaFenceLease(\n          {\n            graphId: this.graphId,\n            schemaVersion: this.#schemaMetadata.schemaVersion,\n          },\n          [txBackend, scope.backend, writeTarget, contextBackend],\n          finish,\n        )\n      : finish();\n  }\n\n  /**\n   * Decorates a receipt-enabled transaction `context` with `measure`.\n   * Attribution is structural: `measure` wraps the context's *own* (already\n   * outer-recording) collections a second time with a fresh scope recorder, so a\n   * write through the scoped context counts in the scope and — via the inner\n   * wrapper it delegates to — the outer receipt, while a write through the outer\n   * `context` never reaches the scope recorder. This makes overlapping/concurrent\n   * measures safe by construction (each holds its own scope recorder) and lets\n   * scopes nest: the scoped context is itself decorated, so `scoped.measure(...)`\n   * chains one more wrapper. The scoped context's dynamic collection lookups resolve\n   * against the scope-wrapped map too, so dynamic-kind writes are attributed like\n   * `scoped.nodes.<Kind>`. The scope receipt's `recorded` is always undefined —\n   * the recorded instant is a whole-transaction flush concern.\n   */\n  #attachMeasure(\n    context: AdapterTransactionContext<G, TNativeTransaction>,\n  ): MeasurableAdapterTransactionContext<G, TNativeTransaction> {\n    const measure: ScopedMeasure<\n      MeasurableAdapterTransactionContext<G, TNativeTransaction>\n    > = async (fn) => {\n      const scopeRecorder = createTransactionReceiptRecorder();\n      const { nodes, edges } = wrapTransactionCollections(\n        context.nodes,\n        context.edges,\n        scopeRecorder,\n      );\n      const identity =\n        this.#graph.identity === undefined ?\n          undefined\n        : wrapTransactionIdentity(\n            (\n              context as unknown as TransactionContext<G> & {\n                identity: IdentityFacade<G>;\n              }\n            ).identity,\n            scopeRecorder,\n          );\n      const scoped = this.#attachMeasure(\n        overlayPropertyDescriptors(context, {\n          nodes,\n          edges,\n          ...(identity === undefined ? {} : { identity }),\n          ...this.#edgeCollectionAccess(edges),\n          getNodeCollection: <const K extends string>(kind: K) =>\n            this.#resolveDynamicNodeCollection(nodes, kind),\n        }),\n      );\n      const result = await fn(scoped);\n      return { result, receipt: scopeRecorder.snapshot() };\n    };\n    return overlayPropertyDescriptors(context, { measure });\n  }\n\n  /** Builds graph reads that execute through one already-open transaction. */\n  #createTransactionReadSurface(\n    txBackend: TransactionBackend,\n    attempt: number,\n  ): TransactionReadMethods<G> {\n    return {\n      query: () => this.#createQueryForBackend(txBackend, undefined, attempt),\n      describe: () => describeStore(this.#analysisContext(txBackend)),\n      validateStore: (options) =>\n        validateStoreImpl(this.#analysisContext(txBackend), options),\n      batchOnce: (build, options) =>\n        this.#batchOnceForBackend(txBackend, attempt, build, options),\n      neighbors: (source, options) => {\n        this.#assertNeighborKinds(source, options.edges);\n        return readNeighbors(\n          this.#neighborContext(txBackend, attempt),\n          source,\n          options,\n        );\n      },\n      countNeighbors: (source, options) => {\n        this.#assertNeighborKinds(source, options.edges);\n        return countNeighborsImpl(\n          this.#neighborContext(txBackend, attempt),\n          source,\n          options,\n        );\n      },\n      subgraph: (rootId, options) =>\n        this.#createSubgraphRead(rootId, options, txBackend, attempt).execute(),\n    };\n  }\n\n  /** One CTE-backed upsert envelope for plain history-store node kinds. */\n  async #writeNodeUpsertBatch<\n    const Entries extends readonly HeterogeneousNodeUpsertInput<G>[],\n  >(\n    txBackend: TransactionBackend,\n    entries: Entries,\n    receiptRecorder: TransactionReceiptRecorder | undefined,\n  ): Promise<HeterogeneousNodeUpsertResult<G, Entries>> {\n    if (entries.length === 0)\n      return [] as HeterogeneousNodeUpsertResult<G, Entries>;\n    if (!this.#captureEnabled) {\n      throw new UnsupportedBackendCapabilityError(\n        \"tx.writeNodeUpsertBatch()\",\n        \"recorded heterogeneous node upserts\",\n        { history: this.#captureEnabled },\n      );\n    }\n    if (this.#coalescesUnchangedUpserts()) {\n      throw new ConfigurationError(\n        \"writeNodeUpsertBatch does not support coalesceUnchangedUpserts.\",\n        { code: \"HETEROGENEOUS_NODE_BATCH_UNSUPPORTED_COALESCING\" },\n      );\n    }\n    if (this.#graph.identity !== undefined) {\n      throw new ConfigurationError(\n        \"writeNodeUpsertBatch does not support graphs with operational identity.\",\n        { code: \"HETEROGENEOUS_NODE_BATCH_UNSUPPORTED_IDENTITY\" },\n      );\n    }\n    const schemaVersion = this.#schemaMetadata.schemaVersion;\n    if (schemaVersion === undefined) {\n      throw new ConfigurationError(\n        \"writeNodeUpsertBatch requires an initialized schema-fenced Store.\",\n        { code: \"HETEROGENEOUS_NODE_BATCH_SCHEMA_UNAVAILABLE\" },\n      );\n    }\n    const seen = new Set<string>();\n    const validated = entries.map((entry) => {\n      if (\n        \"validFrom\" in entry ||\n        \"validTo\" in entry ||\n        \"clearValidTo\" in entry ||\n        \"onImmutableLowerBound\" in entry\n      ) {\n        throw new ConfigurationError(\n          \"writeNodeUpsertBatch does not support temporal write options.\",\n          { code: \"HETEROGENEOUS_NODE_BATCH_UNSUPPORTED_TEMPORAL_OPTIONS\" },\n        );\n      }\n      if (!hasOwnKey(this.#graph.nodes, entry.kind)) {\n        throw new KindNotFoundError(entry.kind, \"node\", {\n          graphId: this.graphId,\n        });\n      }\n      const registration = this.#graph.nodes[entry.kind];\n      if (registration === undefined) {\n        throw new KindNotFoundError(entry.kind, \"node\", {\n          graphId: this.graphId,\n        });\n      }\n      if (\n        (registration.unique?.length ?? 0) > 0 ||\n        this.#registry.getDisjointKinds(entry.kind).length > 0 ||\n        resolveEmbeddingFields(registration.type.schema).length > 0 ||\n        getSearchableFields(registration.type.schema).length > 0\n      ) {\n        throw new ConfigurationError(\n          \"writeNodeUpsertBatch only supports plain node kinds without identity claims or projections.\",\n          {\n            code: \"HETEROGENEOUS_NODE_BATCH_UNSUPPORTED_KIND\",\n            kind: entry.kind,\n          },\n        );\n      }\n      const key = `${entry.kind}\\u0000${entry.id}`;\n      if (seen.has(key)) {\n        throw new ValidationError(\n          `writeNodeUpsertBatch received duplicate node id \"${entry.id}\" for kind \"${entry.kind}\".`,\n          { entityType: \"node\", kind: entry.kind, id: entry.id, issues: [] },\n        );\n      }\n      seen.add(key);\n      const props = validateNodeProps(registration.type.schema, entry.props, {\n        kind: entry.kind,\n        id: entry.id,\n        operation: \"create\",\n      });\n      return {\n        kind: entry.kind,\n        id: entry.id,\n        props,\n        updateProps: callerSuppliedParsedNodeProps(entry.props, props),\n      };\n    });\n    if (\n      !heterogeneousNodeUpsertBatchFitsBindBudget(\n        validated.length,\n        txBackend.capabilities.maxBindParameters,\n      )\n    ) {\n      const maxBindParameters = txBackend.capabilities.maxBindParameters;\n      const parameterCount = heterogeneousNodeUpsertBatchBindParameterCount(\n        validated.length,\n      );\n      throw new ConfigurationError(\n        `writeNodeUpsertBatch uses ${parameterCount} bound parameters, exceeding this backend's limit of ${maxBindParameters}.`,\n        {\n          capability: \"maxBindParameters\",\n          maxBindParameters,\n          parameterCount,\n        },\n        {\n          suggestion:\n            \"Split the operation into smaller batches before retrying.\",\n        },\n      );\n    }\n    receiptRecorder?.assertWritable();\n    if (txBackend.upsertHeterogeneousNodes === undefined) {\n      throw new UnsupportedBackendCapabilityError(\n        \"tx.writeNodeUpsertBatch()\",\n        \"exact-session heterogeneous node upsert program\",\n        { dialect: txBackend.dialect },\n      );\n    }\n    const rows = await withRecordedNodeMutationTarget(\n      txBackend,\n      this.graphId,\n      (target) => {\n        const upsert = target.upsertHeterogeneousNodes;\n        if (upsert === undefined) {\n          throw new UnsupportedBackendCapabilityError(\n            \"tx.writeNodeUpsertBatch()\",\n            \"exact-session heterogeneous node upsert program\",\n            { dialect: target.dialect },\n          );\n        }\n        return upsert({\n          entries: validated,\n          schemaFence: {\n            graphId: this.graphId,\n            expectedVersion: schemaVersion,\n          },\n        });\n      },\n    );\n    if (rows.length !== validated.length) {\n      await diagnoseFusedSchemaFenceNoRow(\n        { graphId: this.graphId, schemaVersion },\n        txBackend,\n      );\n      throw new ConfigurationError(\n        \"writeNodeUpsertBatch did not observe its active schema fence.\",\n        { code: \"HETEROGENEOUS_NODE_BATCH_STALE_SCHEMA\" },\n      );\n    }\n    for (const row of rows) receiptRecorder?.recordNode(row.kind, 1);\n    return rows.map((row) =>\n      rowToNode(row),\n    ) as unknown as HeterogeneousNodeUpsertResult<G, Entries>;\n  }\n\n  /**\n   * Builds the transaction context bound to a transaction-scoped backend.\n   * Collections, fluent queries, and set-oriented reads all use that same\n   * backend. Shared verbatim by {@link transaction}\n   * (TypeGraph opens the tx) and {@link withTransaction} (#134 — the\n   * caller opened it) so both surfaces resolve collections, query\n   * factories, and the reused graph/registry identically. When history capture\n   * is disabled, `sql` is the raw Drizzle handle bound to the same transaction\n   * (#140); when history capture is enabled it is replaced with a fail-loud\n   * guard because raw graph writes would bypass recorded-time capture.\n   */\n  #buildTransactionContext(\n    txBackend: TransactionBackend,\n    sql?: TNativeTransaction,\n    runHooks: OperationHookRunner = this.#immediateHookRunner(),\n    receiptRecorder?: TransactionReceiptRecorder,\n    runBulkHooks: BulkOperationHookRunner = this.#immediateBulkHookRunner(),\n    // 1 outside a retried `store.transaction`; the retry owner's attempt\n    // factory is the only caller that supplies anything else.\n    attempt = 1,\n    recordedRevisionRequestAllowed = true,\n  ): AdapterTransactionContext<G, TNativeTransaction> {\n    // No statistics auto-refresh inside a caller-provided transaction:\n    // ANALYZE from another connection cannot see the uncommitted rows,\n    // so it would only reset the counter without fixing the estimates.\n    const txNodeOperations: NodeOperations = {\n      ...this.#buildNodeOperations(\n        this.#createNodeOperationContext(runHooks, runBulkHooks, attempt),\n      ),\n      createQuery: () =>\n        this.#createQueryForBackend(txBackend, undefined, attempt),\n      maybeRefreshStatisticsAfterBulk: undefined,\n    };\n    const txEdgeOperations: EdgeOperations = {\n      ...this.#buildEdgeOperations(\n        this.#createEdgeOperationContext(runHooks, attempt),\n      ),\n      createQuery: () =>\n        this.#createQueryForBackend(txBackend, undefined, attempt),\n      maybeRefreshStatisticsAfterBulk: undefined,\n    };\n\n    const runNodeOperationHooks = <T>(\n      operation: \"create\" | \"update\" | \"delete\",\n      kind: string,\n      id: string,\n      fn: () => Promise<T>,\n    ): Promise<T> =>\n      runHooks(\n        this.#createOperationContext(operation, \"node\", kind, id, attempt),\n        fn,\n      );\n\n    let nodes = createNodeCollectionsProxy(\n      this.#graph,\n      this.graphId,\n      this.#registry,\n      txBackend,\n      this.#batchPointRead,\n      txNodeOperations,\n    );\n\n    let edges = createEdgeCollectionsProxy(\n      this.#graph,\n      this.graphId,\n      this.#registry,\n      txBackend,\n      this.#batchPointRead,\n      this.#endpointSetRead,\n      txEdgeOperations,\n    );\n\n    if (receiptRecorder !== undefined) {\n      ({ nodes, edges } = wrapTransactionCollections(\n        nodes,\n        edges,\n        receiptRecorder,\n      ));\n    }\n\n    const identity =\n      this.#graph.identity === undefined ?\n        undefined\n      : createIdentityFacade(this.#identityContext(txBackend));\n    const receiptIdentity =\n      identity === undefined || receiptRecorder === undefined ?\n        identity\n      : wrapTransactionIdentity(identity, receiptRecorder);\n\n    const getNodeCollection = <const K extends string>(\n      kind: K,\n    ): DynamicNodeCollection<K> | undefined =>\n      this.#resolveDynamicNodeCollection(nodes, kind);\n\n    // Honest capability discriminant for `tx.sql`. Capture/revision tracking\n    // take precedence because they replace `tx.sql` with a fail-loud guard even\n    // though the transaction itself is real; only a genuinely absent handle is\n    // \"unavailable\" (this method runs on transactional backends — the\n    // non-transactional fallback context is built in #runTransaction).\n    const base = {\n      nodes,\n      edges,\n      writeNodeUpsertBatch: <\n        const Entries extends readonly HeterogeneousNodeUpsertInput<G>[],\n      >(\n        entries: Entries,\n      ) => this.#writeNodeUpsertBatch(txBackend, entries, receiptRecorder),\n      ...this.#createTransactionReadSurface(txBackend, attempt),\n      ...(receiptIdentity === undefined ? {} : { identity: receiptIdentity }),\n      backend: createTransactionReadBackend(txBackend),\n      [TRANSACTION_RUNTIME]: { backend: txBackend, runNodeOperationHooks },\n      getNodeCollection,\n      ...this.#edgeCollectionAccess(edges),\n      ...(this.#captureEnabled || this.#engineNativeHistory ?\n        {\n          requestRecordedRevision: (): void => {\n            if (!recordedRevisionRequestAllowed) {\n              throw new UnsupportedBackendCapabilityError(\n                \"tx.requestRecordedRevision()\",\n                \"write transaction access\",\n                { graphId: this.graphId, accessMode: \"read_only\" },\n                'Remove accessMode: \"read_only\" when the transaction must allocate a recorded revision.',\n              );\n            }\n            if (this.#engineNativeHistory) {\n              throw new UnsupportedBackendCapabilityError(\n                \"tx.requestRecordedRevision()\",\n                \"TypeGraph-owned recorded-time capture\",\n                { graphId: this.graphId, dialect: this.#backend.dialect },\n                \"Use a backend with TypeGraph-owned history capture; engine-native revision allocation is controlled by the database engine.\",\n              );\n            }\n            if (!forceRecordedGraphRevision(txBackend, this.graphId)) {\n              throw new ConfigurationError(\n                \"The history transaction is not bound to a recorded-time capture session.\",\n                { graphId: this.graphId },\n              );\n            }\n          },\n        }\n      : {}),\n    };\n\n    let withSql: AdapterTransactionContext<G, TNativeTransaction>;\n    if (this.#captureEnabled) {\n      withSql = {\n        ...base,\n        sqlAvailability: \"history\",\n      };\n      defineUnavailableSqlGuard(withSql, () => throwHistoryUnsafeSqlAccess());\n    } else if (this.#revisionTrackingEnabled) {\n      withSql = {\n        ...base,\n        sqlAvailability: \"revisionTracking\",\n      };\n      defineUnavailableSqlGuard(withSql, () =>\n        throwRevisionTrackingUnsafeSqlAccess(),\n      );\n    } else if (sql === undefined) {\n      withSql = { ...base, sqlAvailability: \"unavailable\" };\n    } else {\n      withSql = { ...base, sql, sqlAvailability: \"available\" };\n    }\n    Object.defineProperty(withSql, TRANSACTION_RUNTIME, {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n    });\n\n    bindTransactionStore(withSql, this);\n\n    // Scoped write measurement (`tx.measure`) is only meaningful with a recorder\n    // to scope; the plain `transaction()` path stays free of a `measure` the\n    // caller has no receiver for.\n    return receiptRecorder === undefined ? withSql : (\n        this.#attachMeasure(withSql)\n      );\n  }\n\n  #identityContext(\n    backend: GraphBackend | TransactionBackend,\n  ): IdentityServiceContext<G> {\n    // `store.identity` memoizes its facade for the life of the store, so the\n    // context it captures must resolve the schema version at mutation time\n    // rather than snapshotting it here: `clear()` resets this store to the\n    // unversioned lifecycle, and a captured version would make every later\n    // identity write fail as stale against active version 0.\n    const currentSchemaVersion = (): number | undefined =>\n      this.#schemaMetadata.schemaVersion;\n    return {\n      graph: this.#graph,\n      graphId: this.graphId,\n      get schemaVersion(): number | undefined {\n        return currentSchemaVersion();\n      },\n      registry: this.#registry,\n      backend,\n      schema: this.#sqlSchema(),\n      historyEnabled: this.#captureEnabled,\n      revisionTrackingEnabled: this.#revisionTrackingEnabled,\n      sameIdAcrossKinds: this.#graph.identity?.sameIdAcrossKinds ?? \"ignore\",\n      loadNodes: async (references, coordinate) => {\n        const idsByKind = new Map<string, Set<string>>();\n        for (const reference of references) {\n          const ids = idsByKind.get(reference.kind) ?? new Set<string>();\n          ids.add(reference.id);\n          idsByKind.set(reference.kind, ids);\n        }\n        const loadedByReference = new Map<string, IdentityNode<G>>();\n        await Promise.all(\n          [...idsByKind].map(async ([kind, idSet]) => {\n            const ids = [...idSet];\n            // Only a recorded pin needs the recorded relation. Valid-time\n            // views also carry a coordinate, but their members were already\n            // selected as coordinate-visible, and valid time is a lens over\n            // the live rows — hydrating through the recorded reader would\n            // throw RECORDED_POINT_READ_MISSING_COORDINATE.\n            if (coordinate?.recorded !== undefined) {\n              const nodes = await this.recordedNodeGetByIds(\n                kind,\n                ids.map((id) => id as NodeId<NodeType>),\n                coordinate,\n              );\n              for (const [index, node] of nodes.entries()) {\n                if (node !== undefined) {\n                  loadedByReference.set(\n                    refKey({ kind, id: requireDefined(ids[index]) }),\n                    node as IdentityNode<G>,\n                  );\n                }\n              }\n              return;\n            }\n            const boundGetNodes = bindExtraIfReachable(\n              backend,\n              this.#batchPointRead.extras.getNodes,\n              BATCH_POINT_READ.id,\n            );\n            const rows =\n              boundGetNodes === undefined ?\n                await Promise.all(\n                  ids.map((id) => backend.getNode(this.graphId, kind, id)),\n                )\n              : await boundGetNodes.getNodes(this.graphId, kind, ids);\n            // Identity visibility treats every row as visible under\n            // includeTombstones, so a soft-deleted member the coordinate\n            // surfaced must hydrate rather than silently vanish between\n            // membersOf and nodesOf.\n            const includeTombstoned =\n              coordinate?.valid.mode === \"includeTombstones\";\n            for (const row of rows) {\n              if (row === undefined) continue;\n              if (!includeTombstoned && row.deleted_at !== undefined) continue;\n              loadedByReference.set(\n                refKey({ kind, id: row.id }),\n                rowToNode(row) as IdentityNode<G>,\n              );\n            }\n          }),\n        );\n        return references.map((reference) =>\n          loadedByReference.get(refKey(reference)),\n        );\n      },\n    };\n  }\n\n  // === Graph Lifecycle ===\n\n  /**\n   * Hard-deletes all data for this graph from the database.\n   *\n   * Removes all nodes, edges, uniqueness entries, embeddings, and schema versions\n   * for this graph's ID. No hooks, no per-row logic. Wrapped in a transaction\n   * when the backend supports it.\n   *\n   * The store is usable after clearing — new data can be created immediately.\n   */\n  async clear(): Promise<void> {\n    // Both origin-namespaced `base@V` anchor forms — the TypeGraph revision\n    // anchor and the engine anchor — share one `typegraph_revision_origins`\n    // row per graph, so any store able to mint either form must rotate it\n    // here; `mintsOriginNamespacedAnchor` is the one spelling of that\n    // decision (it follows `computeBaseVersion`'s anchor precedence). Gating\n    // on `#revisionTrackingEnabled` alone left an engine-anchored store's\n    // origin untouched, so a branch forked before the clear could satisfy\n    // the base-version precondition again once the graph was repopulated to\n    // the same engine revision.\n    const mintsAnchorOrigin = mintsOriginNamespacedAnchor(\n      this,\n      this.#recordedRevisionOrigins.supported,\n    );\n    if (mintsAnchorOrigin) {\n      // `ensureRevisionOriginsTable` is schema DDL, never projected onto an\n      // open `transaction()` handle (unlike ordinary row writes) — it must\n      // run on the ROOT backend, before `doClear` opens its transaction, so\n      // the row-only `resetRevisionOrigin` below can rely on the table\n      // already existing inside it. Idempotent (`CREATE TABLE IF NOT\n      // EXISTS`, issued once per backend object). On every bundled backend\n      // the table is already part of the full base-schema DDL a fresh\n      // backend installs at construction, so the statement is idempotent and\n      // never provisions anything new there; it exists for a backend whose\n      // `ensureRevisionOriginsTable` provisions the relation lazily instead.\n      await ensureRevisionOriginsRelation(\n        this.#baseBackend,\n        this.#recordedRevisionOrigins,\n      );\n    }\n    const doClear = async (\n      target: GraphBackend | TransactionBackend,\n    ): Promise<void> => {\n      if (this.#revisionTrackingEnabled) {\n        await lockRecordedGraphWrite(target, this.graphId);\n      }\n      if (this.#graph.identity !== undefined) {\n        await lockIdentityGraph(target, this.graphId);\n      }\n      const previousRevision =\n        this.#revisionTrackingEnabled && !this.#captureEnabled ?\n          await readRecordedClock(target, this.#sqlSchema(), this.graphId)\n        : undefined;\n      await target.clearGraph(this.graphId);\n      if (mintsAnchorOrigin) {\n        // Rotate the durable per-graph revision-origin nonce in the SAME\n        // transaction as `clearGraph`, for either origin-namespaced anchor\n        // form this store can mint. `clearGraph` deletes the recorded-clock\n        // row (and, under history, every recorded relation row) but never\n        // touches the origin row — without this, a graph repopulated after\n        // clear() to look the same (the same revision COUNT for a tracked\n        // store, or a coincidentally-matching engine revision for an\n        // engine-anchored one) would restore the anchor's origin half\n        // unchanged, and a pre-clear branch would silently pass the\n        // base-version precondition again. See `resetRevisionOrigin`'s own\n        // doc for why this must be the origin row, not the revision, that\n        // fences the epoch.\n        await resetRevisionOrigin(target, this.#sqlSchema(), this.graphId);\n      }\n      // Live (non-capturing) revision tracking immediately reseeds the\n      // clock so a pre-clear branch cannot match a now-empty graph purely\n      // by revision number, ahead of the origin rotation above ever being\n      // exercised for a token minted from this exact clock value. History\n      // capture intentionally preserves its long-standing\n      // `recordedNow() === undefined` clear contract and leaves the clock\n      // unseeded; the rotated origin above is what fences a pre-clear\n      // history branch once the graph is repopulated, not the clock value.\n      if (this.#revisionTrackingEnabled && !this.#captureEnabled) {\n        await advanceRevisionClock(\n          target,\n          this.#sqlSchema(),\n          this.graphId,\n          this.#baseBackend.capabilities.execution.interactiveTransactions,\n          previousRevision,\n        );\n      }\n    };\n\n    await (this.#baseBackend.capabilities.execution.interactiveTransactions ?\n      this.#baseBackend.transaction(async (tx) => doClear(tx))\n    : doClear(this.#baseBackend));\n\n    // `revisionOriginNow()` and `computeBaseVersion` both read the origin\n    // row fresh on every call (no per-Store memo survives this method), so\n    // there is nothing here to invalidate.\n\n    // `clearGraph` is graph-agnostic and can't reach the strategy-owned\n    // per-`(kind, field)` vector tables, so reset them here — otherwise cleared\n    // embeddings leak and a reused node id would resurface a stale vector.\n    await this.#clearVectorStorage();\n\n    // The committed schema rows were deleted with the graph. This Store now\n    // has the same raw, unversioned lifecycle semantics as `createStore(...)`;\n    // retaining the old version would make its documented post-clear writes\n    // fail as stale against active version 0.\n    this.#schemaMetadata = UNKNOWN_SCHEMA_METADATA;\n\n    // Reset lazy-initialized collection caches\n    this.#nodeCollections = undefined;\n    this.#edgeCollections = undefined;\n    this.#algorithms = undefined;\n    this.#search = undefined;\n  }\n\n  /**\n   * Resets every declared embedding field's per-field storage for this graph by\n   * dropping and recreating it empty. Drop+recreate (rather than DELETE) mirrors\n   * `reembedVectorField` and keeps the backend's storage-ensure latch valid: the\n   * table still exists after clear, so a later write finds it. Enumerated from\n   * the in-memory registry (not the DB schema, which `clearGraph` just wiped).\n   */\n  async #clearVectorStorage(): Promise<void> {\n    const backend = this.#baseBackend;\n    const strategy = backend.vectorStrategy;\n    if (strategy === undefined || backend.executeDdl === undefined) return;\n\n    for (const [nodeKind, nodeType] of this.#registry.nodeKinds) {\n      for (const field of resolveEmbeddingFields(nodeType.schema)) {\n        const slot: VectorSlot = {\n          graphId: this.graphId,\n          nodeKind,\n          fieldPath: field.fieldPath,\n          dimensions: field.dimensions,\n          metric: field.metric,\n          indexType: field.indexType,\n        };\n        for (const ddl of strategy.buildDropStorage(slot)) {\n          await backend.executeDdl(ddl);\n        }\n        for (const contribution of strategy.ownedTables(slot)) {\n          for (const ddl of contribution.createDdl) {\n            await backend.executeDdl(ddl);\n          }\n        }\n      }\n    }\n  }\n\n  // === Lifecycle ===\n\n  /**\n   * Refreshes the backend's query-planner statistics.\n   *\n   * Call this once after a large initial import or bulk backfill. The\n   * planner uses table statistics to choose between TypeGraph's\n   * multi-column indexes; without fresh stats a forward traversal can\n   * pick a reverse index and run an order of magnitude slower than\n   * needed. Autovacuum / background statistics will catch up\n   * eventually, but calling this explicitly after a bulk load gives\n   * you correct latencies immediately.\n   *\n   * Implementations:\n   * - SQLite runs `ANALYZE`, populating `sqlite_stat1`\n   * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n   *\n   * Costs a few tens of milliseconds at the sizes this library is\n   * designed for. Safe to call at any time.\n   *\n   * @example\n   * ```typescript\n   * // After a bulk import\n   * for (const batch of batches) {\n   *   await store.nodes.Document.bulkCreate(batch);\n   * }\n   * await store.refreshStatistics();\n   * ```\n   */\n  async refreshStatistics(): Promise<void> {\n    await this.#backend.refreshStatistics();\n  }\n\n  #evolutionPlanningTarget(\n    plan: EvolutionPlan,\n  ): StoreImplementation<G, TNativeTransaction> {\n    const payload = getEvolutionPlanPayload<G>(plan);\n    if (payload === undefined || plan.graphId !== this.graphId) {\n      throw new ConfigurationError(\n        \"Evolution plans must be created by this module for the same graph.\",\n        {\n          code: \"EVOLUTION_PLAN_OWNER_MISMATCH\",\n          graphId: this.graphId,\n        },\n      );\n    }\n    return this.#cloneWithGraph(payload.mergedGraph, undefined, {\n      schemaVersion: plan.result.version,\n      schemaHash: plan.result.hash,\n    });\n  }\n\n  async withEvolvedTransaction<T>(\n    this: AdapterHistoryStore<G, TNativeTransaction>,\n    externalTx: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: EvolvedTransactionOptions,\n  ): Promise<EvolvedTransactionOutcome<T>>;\n  async withEvolvedTransaction<T>(\n    externalTx: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn: (\n      tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: EvolvedTransactionOptions,\n  ): Promise<EvolvedTransactionOutcome<T>>;\n  async withEvolvedTransaction<T>(\n    externalTx: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn:\n      | ((\n          tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>)\n      | ((\n          tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n    options?: EvolvedTransactionOptions,\n  ): Promise<EvolvedTransactionOutcome<T>> {\n    return withAdoptedTransactionScope(\n      externalTx,\n      () => this.#applyEvolvedTransaction(externalTx, plan, fn, options),\n      true,\n    );\n  }\n\n  async #applyEvolvedTransaction<T>(\n    externalTx: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn:\n      | ((\n          tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>)\n      | ((\n          tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n        ) => Promise<T>),\n    options?: EvolvedTransactionOptions,\n  ): Promise<EvolvedTransactionOutcome<T>> {\n    const candidate = this.#evolutionPlanningTarget(plan);\n    const payload = requireDefined(getEvolutionPlanPayload<G>(plan));\n    assertEvolutionOptions(options, [\"waitBudgetMs\"]);\n    const waitBudgetMs = options?.waitBudgetMs ?? 5000;\n    if (!Number.isSafeInteger(waitBudgetMs) || waitBudgetMs <= 0) {\n      throw new ConfigurationError(\n        \"waitBudgetMs must be a positive safe integer.\",\n        {\n          code: \"INVALID_SCHEMA_FENCE_BUDGET\",\n          waitBudgetMs,\n        },\n      );\n    }\n    if (plan.status === \"noop\") {\n      if (options?.waitBudgetMs !== undefined) {\n        throw new ConfigurationError(\n          \"No-op plans use ordinary adoption and do not acquire an exclusive schema fence.\",\n          { code: \"EVOLUTION_NOOP_FENCE_BUDGET_UNSUPPORTED\" },\n        );\n      }\n      const adopt = this.#adapterBackend?.adoptTransaction;\n      if (adopt === undefined)\n        throw new UnsupportedBackendCapabilityError(\n          \"store.withEvolvedTransaction()\",\n          \"adoptTransaction\",\n          { graphId: this.graphId },\n        );\n      const target = adopt(externalTx);\n      await lockSchemaVersionForStoreWrite(\n        {\n          graphId: this.graphId,\n          schemaVersion: plan.baseline.version,\n        },\n        target,\n      );\n      assertEvolutionPlanBaseline(\n        plan,\n        await target.getActiveSchema(this.graphId),\n      );\n      const outcome = await candidate.#runAdoptedRecordedTransaction(\n        target,\n        externalTx,\n        fn,\n        this,\n      );\n      return {\n        ...outcome,\n        receipt: {\n          ...outcome.receipt,\n          schema: {\n            version: plan.baseline.version,\n            hash: plan.baseline.hash,\n          },\n        },\n      };\n    }\n    const requirements: EvolutionPlanRequirements = requireDefined(\n      payload.requirements,\n    );\n    // Permission policy is explicit and checked before the mutating fence.\n    // Database permissions remain authoritative on opted-in connections.\n    if (\n      (requirements.vectorSlots.length > 0 ||\n        requirements.identityAffectedKinds.length > 0) &&\n      this.#adapterBackend?.schemaProvisioning !== \"transactional\"\n    ) {\n      throw new UnsupportedBackendCapabilityError(\n        \"store.withEvolvedTransaction()\",\n        \"transactional schema provisioning\",\n        { graphId: this.graphId, requirements: plan.requirements },\n        \"Use an adapter configured with schemaProvisioning: 'transactional' on a privileged connection, or apply the extension through bootstrap and replan.\",\n      );\n    }\n    if (\n      requirements.vectorSlots.length > 0 &&\n      (this.#backend.capabilities.vector?.supported !== true ||\n        this.#backend.ensureVectorSlotContributions === undefined)\n    ) {\n      throw new UnsupportedBackendCapabilityError(\n        \"store.withEvolvedTransaction()\",\n        \"transactional vector provisioning\",\n        {\n          graphId: this.graphId,\n          slots: requirements.vectorSlots,\n        },\n      );\n    }\n    const adopt = this.#adapterBackend?.adoptSchemaWriteTransaction;\n    if (adopt === undefined)\n      throw new UnsupportedBackendCapabilityError(\n        \"store.withEvolvedTransaction()\",\n        \"adoptSchemaWriteTransaction\",\n        { graphId: this.graphId },\n      );\n    // Live evolution needs the same session-observed isolation as recorded\n    // capture: its emptiness and freshness decisions cannot use an old snapshot.\n    const ordinaryAdopt = requireDefined(\n      this.#adapterBackend?.adoptTransaction,\n    );\n    await assertRecordedCaptureTransactionIsolation(ordinaryAdopt(externalTx));\n    const adopted = await adopt(externalTx, this.graphId, { waitBudgetMs });\n    const active = adopted.activeSchema;\n    assertEvolutionPlanBaseline(plan, active);\n    await this.#assertNoPendingRemovalFor(\n      payload.mergedGraph,\n      payload.baselineGraph,\n      adopted.backend,\n    );\n    await assertEvolvedSchemaRequiredKindsEmpty(\n      adopted.backend,\n      this.graphId,\n      requireDefined(payload.classification),\n    );\n    if (requirements.vectorSlots.length > 0) {\n      const provision = adopted.backend.ensureVectorSlotContributions;\n      if (provision === undefined) {\n        throw new UnsupportedBackendCapabilityError(\n          \"store.withEvolvedTransaction()\",\n          \"transactional vector provisioning\",\n          { graphId: this.graphId },\n        );\n      }\n      await provision(requireDefined(payload.vectorSlots), {\n        onDrift: \"throw\",\n      });\n    }\n    if (requirements.identityAffectedKinds.length > 0) {\n      const storage = await inspectAdoptedIdentityStorage(\n        adopted.backend,\n        this.#sqlSchema(),\n        {\n          graphId: this.graphId,\n          identityTableDdl: this.#baseBackend.identityTableDdl,\n        },\n      );\n      await candidate.identitySchemaPreflight(\n        adopted.backend,\n        storage.provisionInCommit,\n      );\n    }\n    const committed = await adopted.backend.commitSchemaVersion({\n      graphId: this.graphId,\n      expected: { kind: \"active\", version: plan.baseline.version },\n      version: plan.result.version,\n      schemaHash: plan.result.hash,\n      schemaDoc: requireDefined(payload.schemaDocument),\n    });\n    const outcome = await candidate.#runAdoptedRecordedTransaction(\n      adopted.backend,\n      externalTx,\n      fn,\n      this,\n    );\n    return {\n      ...outcome,\n      receipt: {\n        ...outcome.receipt,\n        schema: {\n          version: committed.version,\n          hash: committed.schema_hash,\n        },\n      },\n    };\n  }\n\n  /** Prepares immutable schema instructions without acquiring a write fence. */\n  async planEvolution(\n    extension: GraphExtension,\n    options?: PlanEvolutionOptions,\n  ): Promise<EvolutionPlan> {\n    assertEvolutionOptions(options, [\"source\"]);\n    if (\n      options?.source !== undefined &&\n      ![\"database\", \"cached\"].includes(options.source)\n    ) {\n      throw new ConfigurationError(\"Unknown evolution planning source.\", {\n        code: \"INVALID_EVOLUTION_PLANNING_SOURCE\",\n        source: options.source,\n      });\n    }\n    if (options?.source !== \"cached\") {\n      const activeRow = await this.#backend.getActiveSchema(this.graphId);\n      if (activeRow === undefined) {\n        throw new ConfigurationError(\n          \"Planning requires an initialized schema.\",\n          {\n            code: \"EVOLUTION_SCHEMA_REQUIRED\",\n            graphId: this.graphId,\n          },\n        );\n      }\n      const storedSchema = parseSerializedSchema(activeRow.schema_doc);\n      this.#evolutionPlanningSnapshot = {\n        activeRow,\n        storedSchema,\n        baseline: this.#catchUpToStored(storedSchema),\n      };\n    }\n    const snapshot = this.#evolutionPlanningSnapshot;\n    if (snapshot === undefined) {\n      throw new ConfigurationError(\n        \"No schema planning snapshot is cached. Plan from the database first.\",\n        {\n          code: \"EVOLUTION_SNAPSHOT_REQUIRED\",\n          graphId: this.graphId,\n        },\n      );\n    }\n    const plan = await prepareEvolutionPlan({\n      baselineGraph: snapshot.baseline,\n      baselineVersion: snapshot.activeRow.version,\n      baselineHash: snapshot.activeRow.schema_hash,\n      storedSchema: snapshot.storedSchema,\n      extension,\n    });\n    return plan;\n  }\n\n  /** Reloads schema metadata after outer commit without applying or provisioning it. */\n  async refreshSchema<TRefStore extends StoreCore<G>>(\n    options?: RefreshSchemaOptions<TRefStore>,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    assertEvolutionOptions(options, [\"ref\", \"minVersion\"]);\n    const minVersion = options?.minVersion;\n    if (\n      minVersion !== undefined &&\n      (!Number.isSafeInteger(minVersion) || minVersion < 1)\n    ) {\n      throw new ConfigurationError(\n        \"minVersion must be a positive safe integer.\",\n        {\n          code: \"INVALID_MIN_SCHEMA_VERSION\",\n          minVersion,\n        },\n      );\n    }\n    if (\n      minVersion !== undefined &&\n      this.#schemaMetadata.schemaVersion === minVersion\n    ) {\n      syncStoreReplacementRef(options?.ref, this);\n      return this;\n    }\n    // Reconciliation is read-only: missing bootstrap storage must never cause DDL.\n    const active = await this.#backend.getActiveSchema(this.graphId);\n    if (\n      active === undefined ||\n      (minVersion !== undefined && active.version < minVersion)\n    ) {\n      throw new ConfigurationError(\n        \"The minimum committed schema version is not visible.\",\n        {\n          code: \"SCHEMA_REFRESH_VERSION_UNAVAILABLE\",\n          graphId: this.graphId,\n          minVersion,\n          actualVersion: active?.version,\n        },\n      );\n    }\n    if (\n      active.version === this.#schemaMetadata.schemaVersion &&\n      active.schema_hash === this.#schemaMetadata.schemaHash\n    ) {\n      syncStoreReplacementRef(options?.ref, this);\n      return this;\n    }\n    return this.#cloneWithGraph(\n      this.#catchUpToStored(parseSerializedSchema(active.schema_doc)),\n      options?.ref,\n      schemaMetadataFromRow(active),\n    );\n  }\n\n  /**\n   * Evolves the graph at runtime by merging a graph extension into the\n   * current schema, atomically committing a new schema version, and\n   * returning the `Store` for the merged graph.\n   *\n   * The `Store` is immutable — its registry, collections, and operation\n   * contexts close over the graph at construction time. After `evolve()`\n   * resolves, callers must use the returned Store (or the re-pointed\n   * `ref.current`) for every subsequent operation in the same request. A\n   * Store captured before the schema commit remains pinned to the old version,\n   * and its next managed write is rejected by the schema fence.\n   *\n   * **Cost for purely additive extensions is proportional to schema\n   * document size, not row count.** The commit is a single CAS write.\n   * Tightening changes against existing graph-extension-declared kinds run\n   * row-count probes for those affected kinds so populated kinds can\n   * be rejected without a backfill.\n   *\n   * **Concurrent evolve recovery.** On `StaleVersionError`, refetch the\n   * current active schema (or dereference your `StoreRef`),\n   * reconstruct your `Store`, and re-call `evolve(extension)` against\n   * the new store. Re-validation may now surface deterministic errors\n   * (e.g., another caller just added a kind that collides with yours,\n   * or redeclared one of yours with a different shape). Don't loop\n   * blindly — surface the error.\n   *\n   * @param extension - Graph extension produced by\n   *   `defineGraphExtension(...)`.\n   * @param options.ref - Optional handle whose `current` is overwritten with\n   *   the replacement before a successful call resolves. Code awaiting this\n   *   call can use the returned Store or `ref.current` immediately. A\n   *   previously captured Store is not mutated.\n   *\n   * @throws {GraphExtensionValidationError} when the extension is\n   *   structurally invalid.\n   * @throws {KindCollisionError} when an extension kind shadows a\n   *   compile-time kind (code `KIND_COLLISION`).\n   * @throws {IncompatibleChangeError} when a redeclared kind narrows\n   *   in a way the existing rows can't satisfy\n   *   (code `INCOMPATIBLE_CHANGE`).\n   * @throws {GraphExtensionUnresolvedEndpointError} when an edge\n   *   endpoint references a kind that exists in neither the extension\n   *   nor the host graph\n   *   (code `GRAPH_EXTENSION_UNRESOLVED_ENDPOINT`).\n   * @throws {StaleVersionError} when another writer has advanced the\n   *   schema since this store was constructed; recovery as above.\n   * @throws {SchemaContentConflictError} when a row already exists at\n   *   the target version with a different content hash.\n   */\n  async evolve<TRefStore extends StoreCore<G>>(\n    extension: GraphExtension,\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n      /**\n       * When set, automatically run `materializeIndexes()` on the new\n       * Store after the schema commit succeeds. Pass `{}` for default\n       * behavior (all declared indexes, best-effort) or a populated\n       * options object for finer control. Omit to defer materialization\n       * to a later `materializeIndexes()` call.\n       *\n       * The schema-version write is NOT rolled back if materialization\n       * produces failed entries — failure surfaces as\n       * `EagerMaterializationError` thrown AFTER the new Store is\n       * constructed and `ref.current` is updated, so the caller can\n       * recover via the ref handle.\n       */\n      eager?: MaterializeIndexesOptions;\n    }>,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    // Catch up to the persisted state first (extension AND deprecated\n    // set). Without this, a stale store applying an extension on top\n    // of an out-of-date baseline would make ensureSchema diff against\n    // the persisted schema and either treat missing-locally kinds as\n    // removed (breaking MigrationError) or silently drop another\n    // writer's deprecation flags. The CAS guard inside\n    // commitSchemaVersion still serializes the actual commit. If the\n    // stored extension redefines a local extension kind with a\n    // different shape, classifyModifications throws\n    // IncompatibleChangeError here — surfacing the divergence rather\n    // than overwriting.\n    const { activeRow, storedSchema, baseline } =\n      await this.#loadCaughtUp(\"evolve\");\n\n    // Merge first so the \"I evolved with the same extension again\"\n    // hot path short-circuits before we walk every property in\n    // `classifyModifications`. The merge itself canonicalEqual-checks\n    // and returns the input graph unchanged for no-op re-evolves.\n    const merged = mergeGraphExtension(baseline, extension);\n\n    // No-op evolve (extension already applied to the persisted state):\n    // skip the schema commit. We compare against `baseline` (the\n    // caught-up graph), not `this.#graph` (the local one). When\n    // another writer has just committed the same extension, the local\n    // store is stale — `baseline !== this.#graph` — but the merge is\n    // still a structural no-op, so re-committing would only churn the\n    // schema version. When the local store is also fresh\n    // (`baseline === this.#graph`) we return `this` so repeated\n    // `evolve(sameExt)` calls keep warm registry,\n    // collection, and query caches; otherwise we return a clone\n    // wrapping the caught-up baseline so `introspect()` reflects the\n    // persisted version. Eager still runs in either case because the\n    // contract is \"schema committed AND indexes materialized\" — the\n    // local DB may have unmaterialized indexes even when the local\n    // graph hasn't changed (restart-parity flow, prior failed\n    // materialize).\n    if (merged === baseline) {\n      if (baseline === this.#graph) {\n        syncStoreReplacementRef(options?.ref, this);\n        if (options?.eager !== undefined) {\n          await this.#runEagerOrThrow(this, options.eager);\n        }\n        return this;\n      }\n      const caughtUp = this.#cloneWithGraph(\n        baseline,\n        options?.ref,\n        schemaMetadataFromRow(activeRow),\n      );\n      if (options?.eager !== undefined) {\n        await this.#runEagerOrThrow(caughtUp, options.eager);\n      }\n      return caughtUp;\n    }\n\n    // Classification gates the schema commit. Same-shape re-evolves\n    // already short-circuited above; here we know there's at least\n    // one delta. Additive changes produce `allowed` deltas (no entry);\n    // tightening changes produce `requireEmpty` entries that we\n    // promote to incompatible only when the kind has rows; genuinely\n    // incompatible changes (REMOVE_PROPERTY, TYPE_CHANGE) are\n    // rejected unconditionally.\n    // A kind cannot be re-added while its cleanup is still queued. The rows\n    // of the previous incarnation are still in the base relations, and reads\n    // filter only by (graph_id, kind) — there is no schema-generation\n    // boundary — so re-adding makes them visible again alongside whatever the\n    // new incarnation writes. Worse, `materializeRemovals` then declines the\n    // queued row (the kind is live), so those rows are never reclaimed.\n    //\n    // The documented cycle is remove -> materializeRemovals -> re-add, which\n    // this leaves untouched. Blocking here rather than at cleanup time keeps\n    // the diagnosis where the caller can act on it.\n    await this.#assertNoPendingRemovalFor(merged, baseline);\n\n    const baselineDocument = baseline.extension ?? Object.freeze({});\n    const classification = classifyModifications(baselineDocument, extension);\n    if (classification.incompatible.length > 0) {\n      throw new IncompatibleChangeError(\n        classification.incompatible,\n        this.graphId,\n      );\n    }\n    const identityCandidate =\n      merged.identity === undefined ?\n        undefined\n      : this.#cloneWithGraph(merged, undefined);\n\n    // Commit via `commitNewSchemaVersion` directly (the row-returning\n    // sibling of `migrateSchema`). The classification step above is the\n    // authoritative compatibility gate — `ensureSchema`'s\n    // `isBackwardsCompatible` check would over-restrict ADD-required-\n    // on-empty / TIGHTEN-on-empty modifications that the classifier\n    // already approved.\n    // Check the identity relations BEFORE the schema-commit transaction: a\n    // missing ledger is refused here rather than surfacing as a raw \"no such\n    // table\" from inside the commit. Any DERIVED relation the transition still\n    // owes comes back as DDL and is issued inside the commit transaction\n    // below, so an evolution that fails or is refused leaves nothing behind.\n    const identityProvisioning =\n      identityCandidate === undefined ? undefined : (\n        await ensureIdentitySchemaStorage(\n          this.#baseBackend,\n          this.#sqlSchema(),\n          {\n            graphId: this.graphId,\n            enablement: false,\n            // The evolved graph's registry — the one the candidate's own\n            // preflight rebuilds through, so the predicate and the fill agree\n            // on which assertions count.\n            registry: buildKindRegistry(merged),\n          },\n        )\n      );\n    const committed =\n      identityCandidate === undefined ?\n        classification.requireEmpty.length > 0 ?\n          await commitEvolvedSchemaWhenRequiredKindsAreEmpty(\n            this.#backend,\n            merged,\n            activeRow.version,\n            classification,\n            storedSchema,\n          )\n        : await commitNewSchemaVersion(\n            this.#backend,\n            merged,\n            activeRow.version,\n            storedSchema,\n          )\n      : await commitNewSchemaVersionWithPreflight(\n          this.#backend,\n          merged,\n          activeRow.version,\n          async (target) => {\n            await assertEvolvedSchemaRequiredKindsEmpty(\n              target,\n              this.graphId,\n              classification,\n            );\n            await identityCandidate.identitySchemaPreflight(\n              target,\n              identityProvisioning?.provisionInCommit ?? [],\n            );\n          },\n          storedSchema,\n        );\n    // Provision per-field vector tables + durable markers for any embedding\n    // fields this evolution introduced (idempotent for fields that already\n    // existed). `evolve()` is a privileged migrator path — it commits schema\n    // versions and runs index DDL in eager mode — so emitting the table DDL\n    // here mirrors how `createStoreWithSchema` provisions at first boot, and\n    // keeps a runtime write to a freshly-added embedding field from hitting\n    // an unmaterialized slot. The shared fulltext table needs no such step\n    // (one table for all kinds); vectors are per-`(kind, field)`.\n    await materializeVectorContributions(this.#backend, merged);\n    const evolved = this.#cloneWithGraph(\n      merged,\n      options?.ref,\n      schemaMetadataFromRow(committed),\n    );\n    if (options?.eager !== undefined) {\n      await this.#runEagerOrThrow(evolved, options.eager);\n    }\n    return evolved;\n  }\n\n  async #runEagerOrThrow(\n    store: StoreImplementation<G, TNativeTransaction>,\n    eager: MaterializeIndexesOptions,\n  ): Promise<void> {\n    const result = await store.materializeIndexes(eager);\n    if (result.results.some((entry) => entry.status === \"failed\")) {\n      throw new EagerMaterializationError(result, this.graphId);\n    }\n  }\n\n  /**\n   * Marks the named node and edge kinds as soft-deprecated. Surfaces in\n   * `store.introspect().deprecatedKinds` for introspection (codegen,\n   * UI tooling, lints) but does not gate reads, writes, or queries —\n   * deprecation is a signal, not a removal.\n   *\n   * Atomically commits a new schema version through the same primitive\n   * `evolve()` uses, so concurrent deprecate/evolve calls produce\n   * `StaleVersionError | SchemaContentConflictError` race losers that\n   * the caller refetches and retries. Idempotent: re-deprecating a\n   * kind that's already marked is a no-op (no version bump).\n   *\n   * @param names - Node or edge kind names to mark as deprecated.\n   * @param options.ref - Optional handle to be re-pointed to the replacement\n   *   Store before a successful call resolves, mirroring `evolve()`.\n   *\n   * @throws {ConfigurationError} on `DEPRECATE_BEFORE_INITIALIZE` (no\n   *   schema yet) or `DEPRECATE_UNKNOWN_KIND` (name not on the graph).\n   * @throws {StaleVersionError} when another writer has advanced the\n   *   schema since this store was constructed; refetch and retry per\n   *   the same recipe `evolve()` documents.\n   * @throws {SchemaContentConflictError} when a row already exists at\n   *   the target version with a different content hash.\n   */\n  async deprecateKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{ ref?: StoreRef<TRefStore> }>,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    return this.#updateDeprecatedKinds(\"add\", names, options);\n  }\n\n  /**\n   * Reverses `deprecateKinds(...)` for the named kinds. Same race +\n   * idempotency semantics: removing a name that isn't currently\n   * deprecated is a no-op for that name (the call as a whole is a\n   * no-op only if every name was already absent).\n   *\n   * @param names - Node or edge kind names to remove from the\n   *   deprecated set.\n   * @param options.ref - Optional handle to be re-pointed to the replacement\n   *   Store before a successful call resolves.\n   *\n   * @throws {ConfigurationError} on `DEPRECATE_BEFORE_INITIALIZE`.\n   * @throws {StaleVersionError} on a CAS race with another writer.\n   * @throws {SchemaContentConflictError} on a same-version content\n   *   conflict.\n   */\n  async undeprecateKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{ ref?: StoreRef<TRefStore> }>,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    return this.#updateDeprecatedKinds(\"remove\", names, options);\n  }\n\n  /**\n   * Runs `CREATE INDEX` DDL for the indexes declared on this graph and\n   * records per-deployment status in `typegraph_index_materializations`.\n   * The status table is per-database (two replicas of the same\n   * `schema_doc` are still two different databases for DDL purposes),\n   * so the same call against two replicas materializes independently.\n   *\n   * Idempotent. Re-running the verb against an already-materialized\n   * index is a no-op (`status: \"alreadyMaterialized\"`). Postgres uses\n   * `CREATE INDEX CONCURRENTLY` so live tables never take an\n   * `AccessExclusiveLock`. SQLite is single-writer regardless.\n   *\n   * Best-effort by default: a failed index records `status: \"failed\"`\n   * with the error and the loop continues. Pass `{ stopOnError: true }`\n   * to halt on the first failure.\n   *\n   * @param options.kinds - Restrict to indexes whose `kind` is in this\n   *   set. Throws `ConfigurationError` (`code:\n   *   \"MATERIALIZE_UNKNOWN_KIND\"`) if any name doesn't match a known\n   *   compile-time or extension kind.\n   * @param options.stopOnError - Halt on first failure. Default false.\n   *\n   * @throws {ConfigurationError} `MATERIALIZE_BACKEND_UNSUPPORTED` if\n   *   the backend lacks `executeDdl`, `getIndexMaterialization`, or\n   *   `recordIndexMaterialization`; `MATERIALIZE_UNKNOWN_KIND` for an\n   *   unknown kind name; `MATERIALIZE_BEFORE_INITIALIZE` if the store\n   *   has no schema yet.\n   */\n  async materializeIndexes(\n    options?: MaterializeIndexesOptions,\n  ): Promise<MaterializeIndexesResult> {\n    const { activeRow, baseline } = await this.#loadCaughtUp(\"materialize\");\n    return materializeIndexesImpl(\n      {\n        graph: baseline,\n        graphId: this.graphId,\n        backend: this.#baseBackend,\n        schemaVersion: activeRow.version,\n      },\n      options ?? {},\n    );\n  }\n\n  /**\n   * Materializes TypeGraph's own base-relation indexes\n   * (`SYSTEM_INDEX_DECLARATIONS`) against the live database.\n   *\n   * Bootstrap DDL runs only on first boot, so a system index shipped in a\n   * newer library version never reaches an already-initialized database on\n   * its own. `createStoreWithSchema` runs this automatically; deployments\n   * that boot with plain `createStore` / `createVerifiedStore` (zero-DDL by\n   * contract) adopt new system indexes by calling this once under a role\n   * that may run DDL. Same status-table, drift-signature, and Postgres\n   * `CREATE INDEX CONCURRENTLY` claim semantics as `materializeIndexes`.\n   */\n  async materializeSystemIndexes(\n    options?: MaterializeSystemIndexesOptions,\n  ): Promise<MaterializeIndexesResult> {\n    const { activeRow } = await this.#loadCaughtUp(\"materialize\");\n    return materializeSystemIndexesImpl(\n      {\n        backend: this.#baseBackend,\n        graphId: this.graphId,\n        schemaVersion: activeRow.version,\n      },\n      options ?? {},\n    );\n  }\n\n  /**\n   * Recreate a vector field's per-field storage at its current declared\n   * dimension, then optionally re-embed existing rows.\n   *\n   * Use this after changing a field's `embedding(N)` to `embedding(M)` (e.g. a\n   * new embedding model): the stored N-dim vectors are invalid under the new\n   * dimension and must be recomputed, not converted. This drops and recreates\n   * the per-`(graphId, kind, field)` table at the new dimension — a brief\n   * window where the field returns no vector hits — resets its materialization\n   * marker, then, when `options.embed` is supplied, pages the kind's nodes,\n   * calls `embed(batch)`, and upserts the returned vectors. Without `embed`,\n   * storage is recreated empty and the caller re-embeds via normal\n   * `update()` / `upsertEmbedding` writes.\n   *\n   * @throws {ConfigurationError} when the backend has no vector strategy or\n   *   cannot execute DDL, or `(kind, fieldPath)` is not a declared embedding.\n   */\n  async reembedVectorField(\n    kind: string,\n    fieldPath: string,\n    options?: ReembedVectorFieldOptions,\n  ): Promise<ReembedVectorFieldResult> {\n    // Validate up front, before any drop/recreate side effects.\n    if (\n      options?.batchSize !== undefined &&\n      (!Number.isInteger(options.batchSize) || options.batchSize <= 0)\n    ) {\n      throw new RangeError(\n        `reembedVectorField batchSize must be a positive integer, got: ${options.batchSize}`,\n      );\n    }\n    const { activeRow, baseline } = await this.#loadCaughtUp(\"reembed\");\n    const backend = this.#baseBackend;\n    const strategy = backend.vectorStrategy;\n    if (strategy === undefined || backend.executeDdl === undefined) {\n      throw new ConfigurationError(\n        \"reembedVectorField requires a backend with a vector strategy and executeDdl.\",\n        {\n          backend: backend.dialect,\n          capability: \"vector\",\n          operation: \"reembed\",\n        },\n      );\n    }\n    const declaration = (baseline.indexes ?? []).find(\n      (candidate): candidate is VectorIndexDeclaration =>\n        candidate.entity === \"vector\" &&\n        candidate.kind === kind &&\n        candidate.fieldPath === fieldPath,\n    );\n    if (declaration === undefined) {\n      throw new ConfigurationError(\n        `No embedding field \"${kind}.${fieldPath}\" is declared in the active schema.`,\n        { kind, fieldPath, operation: \"reembed\" },\n      );\n    }\n\n    const slot: VectorSlot = {\n      graphId: this.graphId,\n      nodeKind: kind,\n      fieldPath,\n      dimensions: declaration.dimensions,\n      metric: declaration.metric,\n      indexType: declaration.indexType,\n    };\n\n    // Recreate storage at the new dimension: drop, then re-create the per-\n    // field table the strategy owns (libSQL/sqlite-vec also (re)create their\n    // index/vtable here; pgvector's index is built via createVectorIndex\n    // below). `ensureVectorSlotContribution({ force: true })` re-runs the\n    // table DDL AND re-stamps the durable contribution marker at the new\n    // signature, bypassing the drift-guard — this is the sanctioned shape\n    // change. Without the marker reset, the post-reembed runtime assert would\n    // see a stale marker and refuse every write. Backends without the marker\n    // method (custom, pre-#135) fall back to raw recreate DDL.\n    for (const ddl of strategy.buildDropStorage(slot)) {\n      await backend.executeDdl(ddl);\n    }\n    if (backend.ensureVectorSlotContribution === undefined) {\n      for (const contribution of strategy.ownedTables(slot)) {\n        for (const ddl of contribution.createDdl) {\n          await backend.executeDdl(ddl);\n        }\n      }\n    } else {\n      await backend.ensureVectorSlotContribution(slot, { force: true });\n    }\n\n    // Whether this backend would actually materialize an ANN index for the\n    // declared slot — brute-force-only (\"none\") slots and index types the\n    // backend doesn't advertise are skipped. Gates both the index (re)build\n    // and the materialization-marker reset below so they stay in lockstep.\n    const declaredIndexMaterializes =\n      declaration.indexType !== \"none\" &&\n      backend.capabilities.vector?.indexTypes.includes(\n        declaration.indexType,\n      ) === true;\n\n    // (Re)build the ANN index with the field's DECLARED tuning. The table was\n    // just recreated above, so createVectorIndex's own ensure is a safe no-op\n    // even if the latch is stale.\n    if (declaredIndexMaterializes && backend.createVectorIndex !== undefined) {\n      await backend.createVectorIndex({\n        graphId: this.graphId,\n        nodeKind: kind,\n        fieldPath,\n        dimensions: declaration.dimensions,\n        metric: declaration.metric,\n        indexType: declaration.indexType,\n        indexParams: {\n          m: declaration.indexParams.m,\n          efConstruction: declaration.indexParams.efConstruction,\n          ...(declaration.indexParams.lists === undefined ?\n            {}\n          : { lists: declaration.indexParams.lists }),\n        },\n      });\n    }\n\n    // Reset the index-materialization marker so a later materializeIndexes()\n    // sees the new-dimension signature as already materialized, not as drift.\n    if (\n      declaredIndexMaterializes &&\n      backend.recordIndexMaterialization !== undefined\n    ) {\n      const tableName = strategy.tableName(this.graphId, kind, fieldPath);\n      const signature = await computeIndexSignature(\n        backend.dialect,\n        tableName,\n        declaration,\n      );\n      const now = nowIso();\n      await backend.recordIndexMaterialization({\n        indexName: vectorStatusKey(this.graphId, declaration.name),\n        graphId: this.graphId,\n        entity: \"vector\",\n        kind,\n        signature,\n        schemaVersion: activeRow.version,\n        attemptedAt: now,\n        materializedAt: now,\n        error: undefined,\n      });\n    }\n\n    if (options?.embed === undefined) {\n      return { recreated: true, reembedded: 0 };\n    }\n\n    if (backend.upsertEmbedding === undefined) {\n      throw new ConfigurationError(\n        \"reembedVectorField with an `embed` callback requires a backend that supports upsertEmbedding.\",\n        {\n          backend: backend.dialect,\n          capability: \"vector\",\n          operation: \"reembed\",\n        },\n      );\n    }\n\n    // Re-embed: page the kind's nodes, compute vectors, upsert. Offset paging\n    // is stable because upserts target the per-field table, not the nodes table.\n    const upsertEmbedding = backend.upsertEmbedding;\n    const batchSize = options.batchSize ?? DEFAULT_REEMBED_BATCH_SIZE;\n    const collection = this.getNodeCollectionOrThrow(kind);\n    let reembedded = 0;\n    let offset = 0;\n    for (;;) {\n      const batch = (await collection.find({\n        limit: batchSize,\n        offset,\n      })) as readonly Node[];\n      if (batch.length === 0) break;\n      const vectors = await options.embed(batch);\n      for (const node of batch) {\n        const embedding = vectors.get(node.id);\n        if (embedding === undefined) continue;\n        await upsertEmbedding({\n          graphId: this.graphId,\n          nodeKind: kind,\n          nodeId: node.id,\n          fieldPath,\n          embedding,\n          dimensions: declaration.dimensions,\n          metric: declaration.metric,\n          indexType: declaration.indexType,\n        });\n        reembedded += 1;\n      }\n      offset += batch.length;\n      if (batch.length < batchSize) break;\n    }\n    return { recreated: true, reembedded };\n  }\n\n  /**\n   * Diagnostic: compare each contribution currently expected by this graph\n   * and the backend strategies with its durable marker and the physical\n   * catalog. Reports detected unusable contributions, including a recorded\n   * failed materialization whose absent table agrees with the marker.\n   * Contributions with neither marker nor table and retired marker rows are\n   * omitted, so an empty array is not proof that storage was initialized.\n   *\n   * Opening a store never probes the catalog — `ensureRuntimeContributions`\n   * and the runtime asserts short-circuit on a per-instance signature cache\n   * and then on the marker row alone, which is the right default for a hot\n   * path. The cost is that a database whose contribution tables were dropped\n   * out of band (a partial restore, a hand-run `DROP`, a schema-scoped\n   * restore that missed them) opens completely clean and then fails at the\n   * first read or write that depends on the affected slot. This is the\n   * explicit, operator-invoked check for that state; it is not, and should not\n   * become, a boot step.\n   *\n   * Purely read-only: one existence query per distinct contribution table\n   * plus one marker read per graph, no DDL and no writes, so it is safe to\n   * run under a least-privilege runtime role and safe to run on a live\n   * store. Each entry carries identity resolved from the active contribution\n   * declaration and matching the marker contract, so callers can route to a\n   * repair without reconstructing any internal naming contract.\n   *\n   * Route on `state`, NOT on whether the entry is a vector slot: the\n   * repairs differ per state and the wrong one destroys data.\n   * {@link Store.reembedVectorField} drops and recreates storage, so\n   * applying it to a `missing-marker` — table intact, only the marker\n   * wrong — discards every embedding to fix bookkeeping. See\n   * {@link ContributionDiagnostic} and the per-state repair tables in the\n   * troubleshooting guide.\n   *\n   * Vector slots are enumerated from the graph's declared embedding fields\n   * and are considered only when the backend advertises vector support; a\n   * backend without it never materialized them, so there is nothing to\n   * compare. Current fulltext contributions are always considered. For a\n   * readiness check, first construct the Store through a verified attach so\n   * initialization is established independently.\n   *\n   * @throws {ConfigurationError} when the backend cannot probe its own\n   *   catalog. Reporting \"no problems found\" on a backend that never\n   *   looked would be the one answer this diagnostic must never give.\n   */\n  async verifyContributions(): Promise<readonly ContributionDiagnostic[]> {\n    const backend = this.#baseBackend;\n    requireExtras(\n      CONTRIBUTION_HEALTH,\n      this.#contributionHealth,\n      \"contribution verify\",\n      () => {\n        throw new ConfigurationError(\n          \"verifyContributions requires a backend that can probe its catalog \" +\n            \"for contribution tables.\",\n          {\n            backend: backend.dialect,\n            capability: \"contributions\",\n            operation: \"verify\",\n          },\n        );\n      },\n    );\n    const { verifyContributions: verify } = bindExtra(\n      backend,\n      this.#contributionHealth.extras.verifyContributions,\n      CONTRIBUTION_HEALTH.id,\n    );\n    const vectorSlots =\n      backend.capabilities.vector?.supported === true ?\n        resolveGraphVectorSlots(this.#graph)\n      : [];\n    return verify(this.graphId, vectorSlots);\n  }\n\n  /**\n   * Read-only diagnostic: every claim axis this graph's data ALREADY contends\n   * for — a scoped unique key two live nodes hold, an id live under both kinds\n   * of a `disjointWith` pair, or a declared edge cardinality two live edges\n   * exceed.\n   *\n   * The claim relations refuse a second claimant from the first write after\n   * upgrade onward, but they repair nothing that predates them: a database that\n   * carried a violation keeps carrying it until a write touches that axis, and\n   * is then refused with the ordinary typed error naming the incumbent. This is\n   * how an operator sees that state before a user does.\n   *\n   * Reports; never repairs. Which of two live claimants keeps the axis is a\n   * data-loss decision that belongs to the operator.\n   *\n   * Declarations are resolved from the active persisted schema, not this\n   * Store's construction-time graph snapshot. A Store left stale by another\n   * instance's `evolve()` therefore audits the constraints that currently\n   * govern the database instead of returning a false clean report.\n   *\n   * @throws {ConfigurationError} `CONSTRAINT_FENCE_AUDIT_UNSUPPORTED` when the\n   *   backend cannot run the audit — an empty report from a backend that never\n   *   looked is indistinguishable from a clean database.\n   */\n  async verifyConstraintFences(): Promise<readonly ConstraintFenceViolation[]> {\n    const activeRow = await this.#baseBackend.getActiveSchema(this.graphId);\n    const graph =\n      activeRow === undefined ?\n        this.#graph\n      : this.#catchUpToStored(parseSerializedSchema(activeRow.schema_doc));\n    const registry =\n      graph === this.#graph ? this.#registry : buildKindRegistry(graph);\n    return verifyConstraintFencesImpl({\n      graph,\n      registry,\n      graphId: this.graphId,\n      backend: this.#baseBackend,\n    });\n  }\n\n  /**\n   * Non-destructively repairs contribution states whose physical storage can\n   * be preserved: `missing-marker` and `failed-materialization`.\n   * `orphaned-marker` and `stale` findings are returned as\n   * `requires-rebuild`; this method never drops contribution tables or\n   * fabricates the data needed to rebuild them.\n   *\n   * The repair re-audits inside the backend and resolves every declaration\n   * from the committed schema. Callers do not supply diagnostics, physical\n   * names, or DDL. A stale Store is caught up to the active persisted graph\n   * before its vector slots are enumerated, so repair does not use declarations\n   * from the Store's stale in-memory graph snapshot.\n   *\n   * @throws {ConfigurationError} when no schema has been initialized or the\n   *   backend cannot probe and repair strategy-owned contributions.\n   */\n  async repairContributions(): Promise<ContributionRepairResult> {\n    const backend = this.#baseBackend;\n    requireExtras(\n      CONTRIBUTION_HEALTH,\n      this.#contributionHealth,\n      \"contribution repair\",\n      () => {\n        throw new ConfigurationError(\n          \"repairContributions requires a backend that can probe and repair \" +\n            \"strategy-owned contribution tables.\",\n          {\n            backend: backend.dialect,\n            capability: \"contributions\",\n            operation: \"repair\",\n          },\n        );\n      },\n    );\n    const { repairContributions: repair } = bindExtra(\n      backend,\n      this.#contributionHealth.extras.repairContributions,\n      CONTRIBUTION_HEALTH.id,\n    );\n\n    const { baseline } = await this.#loadCaughtUp(\"repair\");\n    const vectorSlots =\n      backend.capabilities.vector?.supported === true ?\n        resolveGraphVectorSlots(baseline)\n      : [];\n    return repair(this.graphId, vectorSlots);\n  }\n\n  /**\n   * Read-only readiness check for the search projections: are dependent reads\n   * and writes coherent with the graph right now, or are they about to hit a\n   * degraded index?\n   *\n   * The read-only half of {@link Store.repairContributions}, and the\n   * bottom rung of the contribution health ladder — probe (read) →\n   * `repairContributions()` (incremental, non-destructive) →\n   * {@link Store.rebuildContribution} (destructive full reset). It shares\n   * the detection logic of the other two exactly: a second implementation\n   * would be free to disagree with the one the hot-path gate consults,\n   * and a health check that disagrees with the gate is worse than none.\n   *\n   * Writes nothing — no DDL, no marker writes, no effect on the\n   * per-instance caches the hot path relies on — so it is safe on a read\n   * path, on a replica, and under a least-privilege role. That is the\n   * whole reason it exists: the alternative for a caller who wants to\n   * know whether search is ready was to run `repairContributions()`, a\n   * write with repair side effects, and hope.\n   *\n   * One entry per search projection that this graph actually declares\n   * contributions for. A projection with none is omitted rather than\n   * reported `ready`, so an empty `entries` array means \"nothing to\n   * assess\" — never \"assessed and healthy\". Use\n   * {@link Store.verifyContributions} for the structured per-table\n   * diagnostics behind a `degraded` entry.\n   *\n   * @throws {ConfigurationError} when the backend provisions\n   *   contributions but cannot probe its own catalog. Answering `ready`\n   *   without having looked is the one answer this method must never\n   *   give. A backend with no contribution machinery at all has nothing\n   *   to assess and resolves to empty entries instead.\n   */\n  async probeContributions(): Promise<ContributionProbeResult> {\n    const backend = this.#baseBackend;\n    const probeVerdict = this.#contributionHealth.extras.probeContributions;\n    if (!probeVerdict.present) {\n      if (backend.capabilities.contributions?.supported !== true) {\n        return { entries: [] };\n      }\n      throw new ConfigurationError(\n        \"probeContributions requires a backend that can probe its catalog \" +\n          \"for contribution tables.\",\n        {\n          backend: backend.dialect,\n          capability: \"contributions\",\n          operation: \"probe\",\n        },\n      );\n    }\n    const { probeContributions: probe } = bindExtra(\n      backend,\n      probeVerdict,\n      CONTRIBUTION_HEALTH.id,\n    );\n\n    // The graph snapshot this Store holds, deliberately not a catch-up\n    // read: the probe must stay read-only, and `#loadCaughtUp` commits\n    // schema work. A Store whose in-memory graph has fallen behind\n    // reports on the slots it believes are declared, which is the same\n    // set its own reads and writes will use.\n    const vectorSlots =\n      backend.capabilities.vector?.supported === true ?\n        resolveGraphVectorSlots(this.#graph)\n      : [];\n    const entries = await probe(this.graphId, vectorSlots);\n    const revision = await this.revisionNow();\n    return {\n      ...(revision === undefined ? {} : { graphRevision: revision }),\n      entries,\n    };\n  }\n\n  /**\n   * Destructively rebuilds one search projection for THIS graph: clears the\n   * graph's rows from the projection's storage, recreates that storage from\n   * the current DDL when recreating it is safe, reconstructs the content\n   * from the node rows, and stamps the durable marker at the current\n   * signature.\n   *\n   * **Scoped to this graph.** The fulltext table is one physical table\n   * holding every graph's rows, keyed by `graph_id`, and this method is\n   * fenced per graph — so it removes only this graph's rows\n   * (`DELETE ... WHERE graph_id`, the same statement `clear()` uses) and\n   * escalates to dropping and recreating the table only when no other graph\n   * has rows in it. That drop is the one repair for storage provisioned at a\n   * shape the current DDL no longer produces; when another graph's content\n   * is in the way it is refused\n   * ({@link ContributionRebuildUnsupportedError}, reason\n   * `shared-storage-in-use`) rather than taken, because fulltext content is\n   * reconstructed from a graph's own nodes through its own schema and no\n   * other process can put back what the drop would destroy.\n   *\n   * The top rung of the health ladder, and the repair\n   * {@link Store.repairContributions} deliberately refuses to perform.\n   * Never reachable from that method — a `stale` contribution's table\n   * exists at the *old* shape, so the ordinary ensure path's idempotent\n   * `CREATE ... IF NOT EXISTS` no-ops and re-stamping the marker there\n   * would leave it blessing a table whose shape is wrong, which is\n   * exactly what the drift guard exists to prevent. Only a recreate makes\n   * the ensure meaningful, and destroying content is a decision stated at\n   * the call site rather than reached through a flag named `force`.\n   *\n   * **This destroys this graph's index content.** For `\"fulltext\"` nothing\n   * is permanently lost: the searchable content is derived from node\n   * properties TypeGraph already stores, so the refill reconstructs it in\n   * the same transaction. Nodes whose stored `props` cannot be read as an\n   * object are counted in `skipped` and are absent from the rebuilt index —\n   * `store.search.rebuildFulltext()` reports their ids individually.\n   *\n   * Atomic: the clear (or drop), recreate, refill, and stamp all run inside\n   * one transaction under the same per-graph fence as a schema commit, plus\n   * a database-scoped advisory lock serializing this contribution's DDL\n   * across graphs, so an interrupted rebuild leaves the contribution exactly\n   * as it was rather than attested-but-empty.\n   *\n   * The cost differs by path, and only one of them is a maintenance-window\n   * operation. A rebuild that drops and recreates the shared table takes\n   * `ACCESS EXCLUSIVE` on it before deciding to — the verdict \"no other\n   * graph has rows here\" is only sound under the exclusion the drop needs —\n   * so on PostgreSQL every graph's fulltext writers wait for the whole\n   * refill. That was already true of the drop itself, which holds the same\n   * lock to commit; the exclusion now merely starts a few statements\n   * earlier. The graph-scoped path takes no table lock at all: its\n   * `DELETE ... WHERE graph_id` is transactional and touches only this\n   * graph's rows, so it never makes another graph's writers wait.\n   * `store.search.rebuildFulltext()` remains the incremental, resumable way\n   * to refresh content when the storage shape is fine.\n   *\n   * @throws {ContributionRebuildUnsupportedError} for `\"vector\"`, always:\n   *   TypeGraph stores the vectors callers supply and never the inputs\n   *   that produced them, so embeddings exist only in the storage a\n   *   rebuild would drop and there is nothing to reconstruct them from.\n   *   `store.reembedVectorField(kind, fieldPath, { embed })` is the\n   *   sanctioned destructive path — it takes the callback that can\n   *   regenerate what the drop destroys. Also thrown when the active\n   *   strategy declares no teardown DDL, when the backend has no\n   *   transactional schema fence to make the sequence atomic, and when the\n   *   recorded shape is stale but the storage that would have to be\n   *   recreated holds another graph's rows (`shared-storage-in-use`). Every\n   *   one of these refuses before anything is dropped or deleted.\n   * @throws {ConfigurationError} when the backend cannot rebuild\n   *   strategy-owned contributions at all.\n   */\n  async rebuildContribution(\n    scope: ContributionRebuildScope,\n    options?: RebuildContributionOptions,\n  ): Promise<ContributionRebuildResult> {\n    const backend = this.#baseBackend;\n    requireExtras(\n      CONTRIBUTION_HEALTH,\n      this.#contributionHealth,\n      \"contribution rebuild\",\n      () => {\n        throw new ConfigurationError(\n          \"rebuildContribution requires a backend that can drop, recreate, \" +\n            \"and re-stamp strategy-owned contribution tables.\",\n          {\n            backend: backend.dialect,\n            capability: \"contributions\",\n            operation: \"rebuild\",\n          },\n        );\n      },\n    );\n    const { rebuildContribution: rebuild } = bindExtra(\n      backend,\n      this.#contributionHealth.extras.rebuildContribution,\n      CONTRIBUTION_HEALTH.id,\n    );\n\n    // Catch up first: a rebuild recreates storage from the CURRENT\n    // declarations, so running it against a stale in-memory graph would\n    // provision the shape this Store remembers rather than the one the\n    // committed schema asks for.\n    await this.#loadCaughtUp(\"rebuild\");\n    const registry = this.#registry;\n    const graphId = this.graphId;\n    return rebuild(graphId, scope, async (target) => {\n      // This callback only knows how to reconstruct fulltext content, and\n      // the port's contract is that implementations refuse `\"vector\"`\n      // before reaching it. Restate that here rather than trusting it: a\n      // backend that accepted the scope anyway would have this write\n      // fulltext rows over storage it had just dropped for another\n      // projection, which is worse than the refusal it skipped.\n      if (scope !== \"fulltext\") {\n        throw new ContributionRebuildUnsupportedError(\n          \"vector-source-unavailable\",\n          { graphId, contribution: scope, backend: backend.dialect },\n        );\n      }\n      const result = await repopulateFulltextInTransaction(\n        { graphId, registry },\n        target,\n        options?.pageSize === undefined ? {} : { pageSize: options.pageSize },\n      );\n      return {\n        processed: result.processed,\n        repopulated: result.upserted,\n        skipped: result.skipped,\n      };\n    });\n  }\n\n  /**\n   * Removes extension kinds from the schema with cascading edge and\n   * ontology cleanup. Two-phase by design:\n   *\n   *   1. **Schema commit (this method).** Validates the removal,\n   *      rebuilds the persisted extension without the named kinds\n   *      (and without extension edges that lose their last endpoint),\n   *      CAS-commits the new schema version, and queues\n   *      per-deployment data-cleanup status. Millisecond budget.\n   *   2. **Data cleanup (`materializeRemovals`).** Deletes the orphan\n   *      rows from the nodes/edges tables. Bounded by row count.\n   *\n   * Pass `{ eager: {} }` to run the data-cleanup pass inline with\n   * default options, or `{ eager: { ... } }` to scope it; otherwise\n   * call `materializeRemovals()` later.\n   *\n   * Idempotent: removing a name that doesn't exist is a no-op (no\n   * version bump). Removing an extension kind referenced by a compile-\n   * time edge or ontology relation throws `KindHasReferentsError`.\n   * Removing a compile-time kind throws `RemoveCompileTimeKindError` —\n   * compile-time kinds are removed by recompiling and redeploying.\n   *\n   * @throws {RemoveCompileTimeKindError} when `names` includes a\n   *   compile-time kind.\n   * @throws {KindHasReferentsError} when an extension kind being\n   *   removed is referenced by a compile-time declaration.\n   * @throws {StaleVersionError} on a CAS race with another writer.\n   * @throws {SchemaContentConflictError} on a same-version content\n   *   conflict.\n   */\n  async removeKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n      eager?: MaterializeRemovalsOptions;\n    }>,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    const { activeRow, storedSchema, baseline } =\n      await this.#loadCaughtUp(\"remove\");\n    const plan = planRemovals(baseline, names);\n\n    // True no-op: every name was either absent or already removed.\n    // Mirrors the (un)deprecateKinds same-set short-circuit.\n    if (\n      plan.removedNodeKinds.length === 0 &&\n      plan.removedEdgeKinds.length === 0\n    ) {\n      if (baseline === this.#graph) {\n        syncStoreReplacementRef(options?.ref, this);\n        return this;\n      }\n      return this.#cloneWithGraph(\n        baseline,\n        options?.ref,\n        schemaMetadataFromRow(activeRow),\n      );\n    }\n\n    // Build the post-removal graph: rebuild from the new\n    // extension by re-applying the merge against the host\n    // graph's compile-time slice. Take the host's compile-time\n    // graph (the `Store<G>`'s original `#graph` minus extension\n    // kinds) and merge the planned extension on top of it.\n    const compileTimeGraph = stripGraphExtension(this.#graph);\n    const merged =\n      plan.document === undefined ?\n        compileTimeGraph\n      : mergeGraphExtension(compileTimeGraph, plan.document);\n    const finalGraph = applyDeprecatedKinds(merged, baseline.deprecatedKinds);\n\n    // Atomic schema commit via the lower-level `migrateSchema`\n    // primitive — `ensureSchema`'s breaking-change check would\n    // reject the kind removal as a destructive diff. The removal IS\n    // destructive by design; that's why removeKinds is a separate\n    // verb. Concurrent commits surface as `StaleVersionError` from\n    // `commitSchemaVersion` (CAS check).\n    const identityCascade = await this.#identityRemovalPreflight(\n      finalGraph,\n      plan.removedNodeKinds,\n    );\n    const committedRow =\n      identityCascade === undefined ?\n        await commitNewSchemaVersion(\n          this.#backend,\n          finalGraph,\n          activeRow.version,\n          storedSchema,\n        )\n      : await commitNewSchemaVersionWithPreflight(\n          this.#backend,\n          finalGraph,\n          activeRow.version,\n          identityCascade,\n          storedSchema,\n        );\n\n    // Queue per-deployment data-cleanup status — one row per removed\n    // kind. The status table is best-effort: if recordKindRemoval\n    // throws, the schema commit is already done and the rows just\n    // become invisible (queries against the kind go through the new\n    // store). Operators reconcile via materializeRemovals later.\n    const recordKindRemoval = this.#backend.recordKindRemoval;\n    if (recordKindRemoval !== undefined) {\n      await ensureFocusedStatusTable(\n        this.#backend,\n        this.#backend.ensureKindRemovalsTable,\n      );\n      const attemptedAt = nowIso();\n      const newSchemaVersion = committedRow.version;\n      const queue = (kindName: string, entity: KindEntity): Promise<void> =>\n        recordKindRemoval(\n          buildPendingKindRemoval({\n            graphId: this.graphId,\n            kindName,\n            entity,\n            schemaVersion: newSchemaVersion,\n            attemptedAt,\n          }),\n        );\n      // Independent rows on independent primary keys — issue in parallel.\n      // For typical cascades (one kind + a few edges) this drops the\n      // schema-commit budget by 30-100ms on Postgres.\n      await Promise.all([\n        ...plan.removedNodeKinds.map((name) => queue(name, \"node\")),\n        ...plan.removedEdgeKinds.map((name) => queue(name, \"edge\")),\n      ]);\n    }\n\n    const evolved = this.#cloneWithGraph(\n      finalGraph,\n      options?.ref,\n      schemaMetadataFromRow(committedRow),\n    );\n    if (options?.eager !== undefined) {\n      // Scope to just the kinds removed by THIS call (other pending\n      // removals from prior calls aren't this caller's concern).\n      const kinds = [...plan.removedNodeKinds, ...plan.removedEdgeKinds];\n      await evolved.materializeRemovals({\n        ...options.eager,\n        kinds: options.eager.kinds ?? kinds,\n      });\n    }\n    return evolved;\n  }\n\n  /**\n   * The identity cascade `removeKinds()` commits with, or `undefined` when the\n   * removal cannot touch the assertion ledger.\n   *\n   * Identity being switched OFF is not that case: disabling identity retains\n   * the assertion rows, so a graph with no profile can still hold assertions\n   * naming the kinds being removed. Those rows are cascaded too — otherwise\n   * they survive as current orphans that a later re-enablement filters out of\n   * the closure while raw ledger reads and merge staging still see them. What\n   * the profile's absence does remove is the closure contract, so the repair\n   * pass is skipped and the ledger cleanup runs alone — and a graph that has no\n   * such rows keeps committing through the plain schema-commit primitive.\n   */\n  async #identityRemovalPreflight(\n    finalGraph: G,\n    removedNodeKinds: readonly string[],\n  ): Promise<((target: TransactionBackend) => Promise<void>) | undefined> {\n    if (removedNodeKinds.length === 0) return undefined;\n    const repairClosure = finalGraph.identity !== undefined;\n    if (\n      !repairClosure &&\n      !(await identityKindCascadeNeeded(\n        this.#backend,\n        this.#sqlSchema(),\n        this.graphId,\n        removedNodeKinds,\n      ))\n    ) {\n      return undefined;\n    }\n    const candidate = this.#cloneWithGraph(finalGraph, undefined);\n    return async (target: TransactionBackend) =>\n      candidate.removeIdentityKindsInSchemaPreflight(target, removedNodeKinds, {\n        repairClosure,\n      });\n  }\n\n  /**\n   * Runs the data-cleanup phase for any kinds removed via\n   * `removeKinds()` whose data has not yet been deleted on this\n   * deployment. Safe to call repeatedly; idempotent.\n   */\n  async materializeRemovals(\n    options?: MaterializeRemovalsOptions,\n  ): Promise<MaterializeRemovalsResult> {\n    return materializeRemovalsImpl(\n      {\n        graphId: this.graphId,\n        backend: this.#baseBackend,\n        captureRecordedRemovals: this.#captureEnabled,\n        ...(this.#captureEnabled && { recordedSchema: this.#sqlSchema() }),\n      },\n      options ?? {},\n    );\n  }\n\n  async #updateDeprecatedKinds<TRefStore extends StoreCore<G>>(\n    direction: \"add\" | \"remove\",\n    names: readonly string[],\n    options: Readonly<{ ref?: StoreRef<TRefStore> }> | undefined,\n  ): Promise<StoreImplementation<G, TNativeTransaction>> {\n    const verb = direction === \"add\" ? \"deprecate\" : \"undeprecate\";\n    const { activeRow, storedSchema, baseline } =\n      await this.#loadCaughtUp(verb);\n    const nextSet = new Set(baseline.deprecatedKinds);\n\n    if (direction === \"add\") {\n      for (const name of names) {\n        if (!isKnownKind(baseline, name)) {\n          // Deprecate accepts either node OR edge kinds — the runtime\n          // kind type is reported as \"node\" here for the error\n          // message default; consumers branch on `kindName` not\n          // `entity` for this code path.\n          throw new KindNotFoundError(\n            name,\n            isKnownEdgeKind(baseline, name) ? \"edge\" : \"node\",\n            {\n              graphId: this.graphId,\n              suggestion:\n                \"Only kinds declared on the graph (compile-time or runtime) can be deprecated.\",\n            },\n          );\n        }\n        nextSet.add(name);\n      }\n    } else {\n      for (const name of names) nextSet.delete(name);\n    }\n\n    if (setsEqual(nextSet, baseline.deprecatedKinds)) {\n      // True no-op only when the catch-up didn't change anything\n      // either. Otherwise the caller's `this` reference is stale\n      // relative to the persisted state — return a clone of the\n      // caught-up baseline so they pick up another writer's\n      // extension kinds and deprecation flags.\n      if (baseline === this.#graph) {\n        syncStoreReplacementRef(options?.ref, this);\n        return this;\n      }\n      return this.#cloneWithGraph(\n        baseline,\n        options?.ref,\n        schemaMetadataFromRow(activeRow),\n      );\n    }\n\n    const merged = applyDeprecatedKinds(baseline, nextSet);\n    const result = await ensureSchemaImpl(this.#backend, merged, {\n      preloaded: { activeRow, storedSchema },\n      autoMigrate: true,\n    });\n    // Use the committed row from the migration result when available,\n    // skipping the post-commit `getActiveSchema` round-trip. The\n    // `unchanged` / `pending` / `breaking` branches don't write a new\n    // version, so the existing `activeRow` metadata is still authoritative.\n    const metadata =\n      result.status === \"migrated\" || result.status === \"initialized\" ?\n        schemaMetadataFromRow(result.committedRow)\n      : schemaMetadataFromRow(activeRow);\n    return this.#cloneWithGraph(merged, options?.ref, metadata);\n  }\n\n  #catchUpToStored(storedSchema: SerializedSchema): G {\n    // Strip the local extension slice before re-applying the persisted\n    // extension. Otherwise a stale store whose `this.#graph` carries\n    // extension kinds another writer has since removed would resurrect\n    // them: `unionDocuments` unions local extension nodes/edges back in,\n    // and the absent-from-stored kinds win the spread. Stripping first\n    // makes the merge a function of the persisted document alone, so\n    // removeKinds on one store cannot be silently undone by a stale peer.\n    const compileTimeGraph = stripGraphExtension(this.#graph);\n    const withGraphExtension =\n      storedSchema.extension === undefined ?\n        compileTimeGraph\n      : mergeGraphExtension(compileTimeGraph, storedSchema.extension);\n    return applyDeprecatedKinds(\n      withGraphExtension,\n      storedSchema.deprecatedKinds,\n    );\n  }\n\n  /**\n   * Loads the active schema row, parses it, and catches the in-memory\n   * graph up to the persisted state — the shared preamble for\n   * `evolve`, `materializeIndexes`, and `(un)deprecateKinds`.\n   *\n   * Throws `ConfigurationError` with a verb-specific code when the\n   * graph has not been initialized yet. The catch-up step replays the\n   * persisted graph-extension document and deprecation set on top of the\n   * compile-time graph so we diff against the same baseline another\n   * writer would; the CAS guard inside `commitSchemaVersion` still\n   * serializes the actual commit.\n   */\n  async #loadCaughtUp(verb: CaughtUpVerb): Promise<{\n    activeRow: SchemaVersionRow;\n    storedSchema: SerializedSchema;\n    baseline: G;\n  }> {\n    const activeRow = await loadActiveSchemaWithBootstrap(\n      this.#backend,\n      this.graphId,\n    );\n    if (activeRow === undefined) {\n      const { phrase, code } = CAUGHT_UP_VERB_DETAILS[verb];\n      throw new ConfigurationError(\n        `Cannot ${phrase} graph \"${this.graphId}\": no schema has been initialized. Call createStoreWithSchema first.`,\n        { code },\n      );\n    }\n    const storedSchema = parseSerializedSchema(activeRow.schema_doc);\n    const baseline = this.#catchUpToStored(storedSchema);\n    return { activeRow, storedSchema, baseline };\n  }\n\n  /**\n   * Refuses an evolve that re-adds a kind whose data cleanup is still pending.\n   *\n   * Returns silently on backends without the removal queue: they cannot have\n   * a pending row, so there is nothing to conflict with.\n   */\n  async #assertNoPendingRemovalFor(\n    merged: G,\n    baseline: G,\n    target?: TransactionBackend,\n  ): Promise<void> {\n    const backend = target ?? this.#backend;\n    const getPendingKindRemovals = backend.getPendingKindRemovals;\n    if (getPendingKindRemovals === undefined) return;\n\n    // Own keys only: `baseline` is rebuilt from the PARSED stored schema, so a kind\n    // named after an `Object.prototype` member would otherwise always look\n    // still-present and skip the pending-removal refusal this guard exists for.\n    const addedNodes = Object.keys(merged.nodes).filter(\n      (kind) => !hasOwnKey(baseline.nodes, kind),\n    );\n    const addedEdges = Object.keys(merged.edges).filter(\n      (kind) => !hasOwnKey(baseline.edges, kind),\n    );\n    if (addedNodes.length === 0 && addedEdges.length === 0) return;\n\n    if (target === undefined) {\n      await ensureFocusedStatusTable(\n        this.#backend,\n        this.#backend.ensureKindRemovalsTable,\n      );\n    }\n    const pending = await getPendingKindRemovals(this.graphId);\n    if (pending.length === 0) return;\n\n    const blocked = pending.filter((row) =>\n      row.entity === \"node\" ?\n        addedNodes.includes(row.kindName)\n      : addedEdges.includes(row.kindName),\n    );\n    if (blocked.length === 0) return;\n\n    const named = blocked\n      .map((row) => `${row.entity} \"${row.kindName}\"`)\n      .join(\", \");\n    throw new ConfigurationError(\n      `Cannot re-add ${named} for graph \"${this.graphId}\": the previous ` +\n        `removal's data cleanup has not run, so the old rows are still in ` +\n        `the database and would become visible again alongside the new ` +\n        `ones. Run store.materializeRemovals() first, then evolve.`,\n      {\n        code: \"KIND_READD_BLOCKED_BY_PENDING_REMOVAL\",\n        graphId: this.graphId,\n        kinds: blocked.map((row) => row.kindName),\n      },\n    );\n  }\n\n  #cloneWithGraph<TRefStore extends StoreCore<G>>(\n    graph: G,\n    ref: StoreRef<TRefStore> | undefined,\n    schemaMetadata: StoreSchemaMetadata = this.#schemaMetadata,\n  ): StoreImplementation<G, TNativeTransaction> {\n    const next: StoreImplementation<G, TNativeTransaction> =\n      this.#adapterBackend === undefined ?\n        new StoreImplementation<G, TNativeTransaction>(\n          graph,\n          this.#baseBackend,\n          this.#options,\n          schemaMetadata,\n        )\n      : new AdapterStoreImplementation(\n          graph,\n          this.#adapterBackend,\n          this.#options,\n          schemaMetadata,\n        );\n    syncStoreReplacementRef(ref, next);\n    return next;\n  }\n\n  /**\n   * Closes the store and releases underlying resources.\n   *\n   * Note: When using the Drizzle adapter, this method does not close the database\n   * connection itself, as Drizzle delegates connection management to the user.\n   * You should close the underlying database connection (e.g., better-sqlite3 or pg pool)\n   * using their respective APIs.\n   */\n  async close(): Promise<void> {\n    await this.#backend.close();\n  }\n\n  // === Internal: Operation Contexts ===\n\n  #immediateHookRunner(): OperationHookRunner {\n    return <T>(\n      ctx: OperationHookContext,\n      fn: () => Promise<T>,\n      didWrite?: (result: T) => boolean,\n    ) => this.#withOperationHooks(ctx, fn, didWrite);\n  }\n\n  #immediateBulkHookRunner(): BulkOperationHookRunner {\n    return <T extends Readonly<{ affectedCount: number }>>(\n      ctx: BulkOperationHookContext,\n      fn: () => Promise<T>,\n    ) => this.#withBulkOperationHooks(ctx, fn);\n  }\n\n  #createNodeOperationContext(\n    runHooks: OperationHookRunner = this.#immediateHookRunner(),\n    runBulkHooks: BulkOperationHookRunner = this.#immediateBulkHookRunner(),\n    attempt = 1,\n  ): NodeOperationContext<G> {\n    const identityConfig = this.#graph.identity;\n    return {\n      graph: this.#graph,\n      graphId: this.graphId,\n      schemaVersion: this.#schemaMetadata.schemaVersion,\n      historyEnabled: this.#captureEnabled,\n      revisionTrackingEnabled: this.#revisionTrackingEnabled,\n      coalesceUnchangedUpsertsEnabled: this.#coalescesUnchangedUpserts(),\n      revisionSchema: this.#sqlSchema(),\n      statementExecution: this.#statementExecution,\n      registry: this.#registry,\n      claimsVerdict: this.#claimsVerdict,\n      batchPointRead: this.#batchPointRead,\n      uniqueSidecarBatch: this.#uniqueSidecarBatch,\n      ...(identityConfig === undefined ?\n        {}\n      : {\n          identity: {\n            lock: (target: IdentityTarget) =>\n              lockIdentityGraph(target, this.graphId),\n            foldCreated: (\n              target: IdentityTarget,\n              references: readonly Readonly<{ kind: string; id: string }>[],\n            ) =>\n              foldIdentityForCreatedNodes(\n                {\n                  graphId: this.graphId,\n                  registry: this.#registry,\n                  sameIdAcrossKinds: identityConfig.sameIdAcrossKinds,\n                  schema: this.#sqlSchema(),\n                },\n                target,\n                references,\n              ),\n            detachDeleted: (\n              target: IdentityTarget,\n              ref: Readonly<{ kind: string; id: string }>,\n              mode: \"soft\" | \"hard\",\n            ) =>\n              detachIdentityForNode(\n                {\n                  graphId: this.graphId,\n                  sameIdAcrossKinds: identityConfig.sameIdAcrossKinds,\n                  schema: this.#sqlSchema(),\n                },\n                target,\n                ref,\n                mode,\n              ),\n            requireValidityEndCompatible: (\n              target: IdentityTarget,\n              ref: Readonly<{ kind: string; id: string }>,\n              validTo: string,\n            ) =>\n              requireNodeValidityEndCompatible(\n                {\n                  graphId: this.graphId,\n                  schema: this.#sqlSchema(),\n                },\n                target,\n                ref,\n                validTo,\n              ),\n          },\n        }),\n      createOperationContext: (operation, entity, kind, id) =>\n        this.#createOperationContext(operation, entity, kind, id, attempt),\n      withOperationHooks: runHooks,\n      createBulkOperationContext: (operation, kind) => ({\n        ...this.#createHookContext(attempt),\n        operation,\n        entity: \"node\",\n        kind,\n      }),\n      withBulkOperationHooks: runBulkHooks,\n    };\n  }\n\n  #createEdgeOperationContext(\n    runHooks: OperationHookRunner = this.#immediateHookRunner(),\n    attempt = 1,\n  ): EdgeOperationContext<G> {\n    return {\n      graph: this.#graph,\n      graphId: this.graphId,\n      schemaVersion: this.#schemaMetadata.schemaVersion,\n      historyEnabled: this.#captureEnabled,\n      revisionTrackingEnabled: this.#revisionTrackingEnabled,\n      coalesceUnchangedUpsertsEnabled: this.#coalescesUnchangedUpserts(),\n      revisionSchema: this.#sqlSchema(),\n      registry: this.#registry,\n      claimsVerdict: this.#claimsVerdict,\n      batchPointRead: this.#batchPointRead,\n      uniqueSidecarBatch: this.#uniqueSidecarBatch,\n      statementExecution: this.#statementExecution,\n      createOperationContext: (operation, entity, kind, id) =>\n        this.#createOperationContext(operation, entity, kind, id, attempt),\n      withOperationHooks: runHooks,\n    };\n  }\n\n  /** The single owner of the store-wide unchanged-upsert enablement decision. */\n  #coalescesUnchangedUpserts(): boolean {\n    return this.#options?.coalesceUnchangedUpserts === true;\n  }\n\n  // === Internal: Hook Helpers ===\n\n  /**\n   * Decorates the query execution port so hooks observe each statement the\n   * query builder submits to the backend. A selective-projection retry\n   * therefore emits two independent start/end pairs with their actual SQL.\n   *\n   * Decoration goes through {@link deriveBackend}, which carries the\n   * projection's serialized-resource ownership: the hooked backend still\n   * executes on the source's connection, so it must answer the same \"shares one\n   * serialized connection\" question as its source.\n   */\n  #createHookedQueryBackend(\n    backend: GraphBackend | TransactionBackend,\n    attempt = 1,\n  ): GraphBackend {\n    if (\n      this.#hooks.onQueryStart === undefined &&\n      this.#hooks.onQueryEnd === undefined &&\n      this.#hooks.onError === undefined\n    ) {\n      return backend as GraphBackend;\n    }\n\n    const executeRaw = backend.executeRaw;\n    const compileSql = backend.compileSql;\n    // Store backends may be frozen. Decorate an allowlist projection so\n    // execute/executeRaw can be replaced without mutating the source.\n    const projected = projectGraphBackend(backend as GraphBackend);\n\n    return deriveBackend(projected, {\n      execute: <T>(query: CompiledRowsSql): Promise<readonly T[]> => {\n        const compiled =\n          compileSql === undefined ?\n            renderSql(query, backend.dialect)\n          : compileSql(query);\n        return this.#withQueryHooks(\n          compiled.sql,\n          compiled.params,\n          () => backend.execute<T>(query),\n          attempt,\n        );\n      },\n      ...(executeRaw === undefined ?\n        {}\n      : {\n          executeRaw: <T>(\n            sqlText: string,\n            params: readonly unknown[],\n          ): Promise<readonly T[]> =>\n            this.#withQueryHooks(\n              sqlText,\n              params,\n              () => executeRaw<T>(sqlText, params),\n              attempt,\n            ),\n        }),\n    });\n  }\n\n  async #withQueryHooks<T>(\n    sql: string,\n    params: readonly unknown[],\n    execute: () => Promise<readonly T[]>,\n    attempt = 1,\n  ): Promise<readonly T[]> {\n    const ctx: QueryHookContext = {\n      ...this.#createHookContext(attempt),\n      sql,\n      params,\n    };\n    this.#hooks.onQueryStart?.(ctx);\n    const startTime = Date.now();\n    try {\n      const rows = await execute();\n      this.#hooks.onQueryEnd?.(ctx, {\n        rowCount: rows.length,\n        durationMs: Date.now() - startTime,\n      });\n      return rows;\n    } catch (error) {\n      this.#reportError(ctx, asError(error));\n      throw error;\n    }\n  }\n\n  /**\n   * `attempt` is 1 everywhere outside a retried `store.transaction`; its\n   * attempt factory is the only caller that threads its own attempt number\n   * through, so a listener can tell a replay from a fresh operation.\n   */\n  #createHookContext(attempt = 1): HookContext {\n    return {\n      operationId: generateId(),\n      graphId: this.graphId,\n      startedAt: new Date(),\n      attempt,\n    };\n  }\n\n  #createOperationContext(\n    operation: \"create\" | \"update\" | \"delete\",\n    entity: KindEntity,\n    kind: string,\n    id: string,\n    attempt = 1,\n  ): OperationHookContext {\n    return {\n      ...this.#createHookContext(attempt),\n      operation,\n      entity,\n      kind,\n      id,\n    };\n  }\n\n  async #withOperationHooks<T>(\n    ctx: OperationHookContext,\n    fn: () => Promise<T>,\n    didWrite?: (result: T) => boolean,\n  ): Promise<T> {\n    this.#hooks.onOperationStart?.(ctx);\n    const startTime = Date.now();\n    try {\n      const result = await fn();\n      this.#hooks.onOperationEnd?.(ctx, {\n        durationMs: Date.now() - startTime,\n        outcome:\n          didWrite === undefined ? \"unknown\"\n          : didWrite(result) ? \"written\"\n          : \"unchanged\",\n      });\n      return result;\n    } catch (error) {\n      this.#reportError(ctx, asError(error));\n      throw error;\n    }\n  }\n\n  async #withBulkOperationHooks<T extends Readonly<{ affectedCount: number }>>(\n    ctx: BulkOperationHookContext,\n    fn: () => Promise<T>,\n  ): Promise<T> {\n    this.#hooks.onBulkOperationStart?.(ctx);\n    const startTime = Date.now();\n    try {\n      const result = await fn();\n      this.#hooks.onBulkOperationEnd?.(ctx, {\n        affectedCount: result.affectedCount,\n        durationMs: Date.now() - startTime,\n      });\n      return result;\n    } catch (error) {\n      this.#reportError(ctx, asError(error));\n      throw error;\n    }\n  }\n\n  /**\n   * THE one caller of `hooks.onError`. A hook that throws while being told\n   * about a failure must not replace that failure: the error being reported\n   * is what the caller — and, for a unit nested in a retried transaction,\n   * the retry owner classifying it — receives, so the hook's own exception\n   * is discarded here (see `StoreHooks.onError`).\n   */\n  #reportError(ctx: HookContext, error: Error): void {\n    try {\n      this.#hooks.onError?.(ctx, error);\n    } catch {\n      // Discarded on purpose; see `StoreHooks.onError`.\n    }\n  }\n\n  /**\n   * A hook runner for operations that execute INSIDE an explicit\n   * `store.transaction`: `onOperationStart` (and a failed operation's\n   * `onError`) fire immediately — the attempt and the failure are real when\n   * they happen — but a successful operation's `onOperationEnd` is only\n   * BUFFERED. `transaction()` flushes the buffer after the backend COMMIT\n   * succeeds, or converts every buffered success into `onError` when the\n   * transaction fails, so `onOperationEnd` always means durably committed\n   * even for operations nested in a caller-controlled transaction.\n   */\n  #createBufferedHookRunner(\n    pending: PendingOperationOutcome[],\n  ): OperationHookRunner {\n    return async <T>(\n      ctx: OperationHookContext,\n      fn: () => Promise<T>,\n      didWrite?: (result: T) => boolean,\n    ): Promise<T> => {\n      this.#hooks.onOperationStart?.(ctx);\n      const startTime = Date.now();\n      try {\n        const result = await fn();\n        pending.push({\n          type: \"operation\",\n          ctx,\n          durationMs: Date.now() - startTime,\n          outcome:\n            didWrite === undefined ? \"unknown\"\n            : didWrite(result) ? \"written\"\n            : \"unchanged\",\n        });\n        return result;\n      } catch (error) {\n        this.#reportError(ctx, asError(error));\n        throw error;\n      }\n    };\n  }\n\n  /** Buffered counterpart for set-based operations inside `transaction()`. */\n  #createBufferedBulkHookRunner(\n    pending: PendingOperationOutcome[],\n  ): BulkOperationHookRunner {\n    return async <T extends Readonly<{ affectedCount: number }>>(\n      ctx: BulkOperationHookContext,\n      fn: () => Promise<T>,\n    ): Promise<T> => {\n      this.#hooks.onBulkOperationStart?.(ctx);\n      const startTime = Date.now();\n      try {\n        const result = await fn();\n        pending.push({\n          type: \"bulkOperation\",\n          ctx,\n          affectedCount: result.affectedCount,\n          durationMs: Date.now() - startTime,\n        });\n        return result;\n      } catch (error) {\n        this.#reportError(ctx, asError(error));\n        throw error;\n      }\n    };\n  }\n\n  // === Internal: Temporal Filtering ===\n\n  #temporalRowMatcher(options?: QueryOptions): (\n    row: Readonly<{\n      deleted_at: string | undefined;\n      valid_from: string | undefined;\n      valid_to: string | undefined;\n    }>,\n  ) => boolean {\n    // Resolve the coordinate ONCE (via the shared resolveTemporalReadParams, so\n    // the in-memory getById/getByIds filter cannot drift from the SQL-side\n    // filter, and a non-canonical asOf is rejected here too). Returning a\n    // predicate lets getByIds pin one instant for the whole batch instead of\n    // recomputing nowIso() — and re-validating — per row.\n    const { temporalMode, asOf } = resolveTemporalReadParams(\n      options,\n      this.#graph.defaults.temporalMode,\n    );\n\n    return (row) => {\n      switch (temporalMode) {\n        case \"current\":\n        case \"asOf\": {\n          // resolveTemporalReadParams always resolves an instant for these modes.\n          if (row.deleted_at || asOf === undefined) return false;\n          return validityWindowContainsInstant(\n            row.valid_from,\n            row.valid_to,\n            asOf,\n          );\n        }\n        case \"includeEnded\": {\n          return !row.deleted_at;\n        }\n        case \"includeTombstones\": {\n          return true;\n        }\n      }\n    };\n  }\n\n  #createQueryForBackend<CoordinateState extends QueryCoordinateState = \"open\">(\n    backend: GraphBackend | TransactionBackend,\n    sealedCoordinate?: ReadCoordinate,\n    attempt = 1,\n    expectedSchemaVersion?: Readonly<{ value: number | undefined }>,\n  ): InitialQueryBuilder<G, CoordinateState> {\n    const queryBackend = this.#createHookedQueryBackend(backend, attempt);\n    return createInternalQueryBuilder<G, CoordinateState>(\n      this.graphId,\n      this.#registry,\n      {\n        // TransactionBackend omits transaction/close, but query execution only needs\n        // the read-path/query capabilities shared with GraphBackend.\n        backend: queryBackend,\n        dialect: backend.dialect,\n        defaultTraversalExpansion: this.#defaultTraversalExpansion,\n        runtimeKindTokenResolver: (token, entity) =>\n          this.#resolveRuntimeKindToken(token, entity),\n        ...(this.#schema !== undefined && { schema: this.#schema }),\n        ...(this.#recordedReadBinding !== undefined && {\n          recordedReadBinding: this.#recordedReadBinding,\n        }),\n        ...(sealedCoordinate !== undefined && { sealedCoordinate }),\n        ...(expectedSchemaVersion !== undefined && { expectedSchemaVersion }),\n      },\n    );\n  }\n}\n\n/** Runtime implementation for the explicit adapter-interoperability surface. */\nclass AdapterStoreImplementation<\n  G extends GraphDef,\n  TNativeTransaction,\n> extends StoreImplementation<G, TNativeTransaction> {\n  readonly backend: GraphBackend | HistoryStoreBackend;\n\n  constructor(\n    graph: G,\n    backend: AdapterBackend<TNativeTransaction>,\n    options?: StoreOptions,\n    schemaMetadata?: StoreSchemaMetadata,\n  ) {\n    super(graph, backend, options, schemaMetadata, backend);\n    // Projections remain mutable while they serve as internal overlay targets;\n    // freeze only the final object exposed at this public boundary.\n    this.backend =\n      options?.history === true ?\n        createHistoryStoreBackendProjection(this[STORE_RUNTIME].backend)\n      : Object.freeze(projectGraphBackend(this[STORE_RUNTIME].backend));\n  }\n\n  /**\n   * Rebind this store's already-reconciled schema onto a fresh backend/\n   * connection, returning a new equivalent store with **no** verify round-trip.\n   * The connection is captured at construction and never mutated, so this\n   * returns a new instance rather than rebinding in place — the serverless\n   * per-request primitive: verify once per isolate, then `withBackend` the\n   * per-request connection.\n   */\n  withBackend(\n    backend: AdapterBackend<TNativeTransaction>,\n  ): AdapterStoreImplementation<G, TNativeTransaction> {\n    const state = this.reconstructionState();\n    return new AdapterStoreImplementation(\n      state.graph,\n      backend,\n      state.options,\n      state.schemaMetadata,\n    );\n  }\n\n  override async evolve<TRefStore extends StoreCore<G>>(\n    extension: GraphExtension,\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n      eager?: MaterializeIndexesOptions;\n    }>,\n  ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n    return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n      super.evolve(\n        extension,\n        options?.eager === undefined ?\n          { ref: replacementRef }\n        : { eager: options.eager, ref: replacementRef },\n      ),\n    );\n  }\n\n  override async deprecateKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n    }>,\n  ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n    return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n      super.deprecateKinds(names, { ref: replacementRef }),\n    );\n  }\n\n  override async undeprecateKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n    }>,\n  ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n    return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n      super.undeprecateKinds(names, { ref: replacementRef }),\n    );\n  }\n\n  override async removeKinds<TRefStore extends StoreCore<G>>(\n    names: readonly string[],\n    options?: Readonly<{\n      ref?: StoreRef<TRefStore>;\n      eager?: MaterializeRemovalsOptions;\n    }>,\n  ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n    return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n      super.removeKinds(\n        names,\n        options?.eager === undefined ?\n          { ref: replacementRef }\n        : { eager: options.eager, ref: replacementRef },\n      ),\n    );\n  }\n\n  async #withAdapterReplacement<TRefStore extends StoreCore<G>>(\n    ref: StoreRef<TRefStore> | undefined,\n    operation: (ref: StoreRef<Store<G>>) => Promise<Store<G>>,\n  ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n    const tracked = createTrackedReplacementRef<G>(this);\n    try {\n      await operation(tracked.ref);\n    } catch (error) {\n      if (tracked.wasReplaced()) {\n        const replacement = requireAdapterStoreImplementation<\n          G,\n          TNativeTransaction\n        >(tracked.ref.current);\n        syncAdapterReplacementRef(ref, replacement);\n      }\n      throw error;\n    }\n    const replacement = requireAdapterStoreImplementation<\n      G,\n      TNativeTransaction\n    >(tracked.ref.current);\n    syncAdapterReplacementRef(ref, replacement);\n    return replacement;\n  }\n}\n\nfunction createTrackedReplacementRef<G extends GraphDef>(\n  initial: Store<G>,\n): Readonly<{\n  ref: StoreRef<Store<G>>;\n  wasReplaced: () => boolean;\n}> {\n  let current = initial;\n  let replaced = false;\n  return {\n    ref: {\n      get current(): Store<G> {\n        return current;\n      },\n      set current(next: Store<G>) {\n        current = next;\n        replaced = true;\n      },\n    },\n    wasReplaced: () => replaced,\n  };\n}\n\nfunction syncAdapterReplacementRef<\n  G extends GraphDef,\n  TNativeTransaction,\n  TRefStore extends StoreCore<G>,\n>(\n  ref: StoreRef<TRefStore> | undefined,\n  replacement: AdapterStoreImplementation<G, TNativeTransaction>,\n): void {\n  if (ref === undefined) return;\n  // Public StoreEvolution only accepts refs whose value is a supertype of the\n  // returned Store flavor. This implementation class is deliberately broader\n  // because one runtime class backs live, recorded-read, and history overloads.\n  ref.current = replacement as unknown as TRefStore;\n}\n\nfunction requireAdapterStoreImplementation<\n  G extends GraphDef,\n  TNativeTransaction,\n>(store: Store<G>): AdapterStoreImplementation<G, TNativeTransaction> {\n  if (isAdapterStoreImplementation<G, TNativeTransaction>(store)) return store;\n  throw new ConfigurationError(\n    \"Adapter store replacement lost its adapter capabilities.\",\n    { code: \"ADAPTER_STORE_REPLACEMENT_INVARIANT\" },\n  );\n}\n\nfunction isAdapterStoreImplementation<G extends GraphDef, TNativeTransaction>(\n  store: Store<G>,\n): store is AdapterStoreImplementation<G, TNativeTransaction> {\n  return store instanceof AdapterStoreImplementation;\n}\n\nfunction asAdapterStoreSurface<G extends GraphDef, TNativeTransaction>(\n  store: AdapterStoreImplementation<G, TNativeTransaction>,\n):\n  | AdapterStore<G, TNativeTransaction>\n  | AdapterHistoryStore<G, TNativeTransaction>\n  | AdapterRecordedReadStore<G, TNativeTransaction> {\n  // One runtime implementation backs the three option-discriminated overloads.\n  // It constructs the matching backend projection and replacement flavor, but\n  // TypeScript cannot derive that structural union from constructor options.\n  return store as unknown as\n    | AdapterStore<G, TNativeTransaction>\n    | AdapterHistoryStore<G, TNativeTransaction>\n    | AdapterRecordedReadStore<G, TNativeTransaction>;\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\nexport type AdapterHistoryTransactionContext<\n  G extends GraphDef,\n  TNativeTransaction,\n> = Omit<\n  AdapterTransactionContext<G, TNativeTransaction>,\n  \"sql\" | \"sqlAvailability\"\n> &\n  RecordedRevisionRequest &\n  RecordedHeterogeneousNodeWriteBatch<G> &\n  Readonly<{\n    sqlAvailability: \"history\";\n  }>;\n\n/**\n * The {@link AdapterHistoryTransactionContext} handed to a `withRecordedTransaction`\n * callback, extended with {@link ScopedMeasure}. Its `measure` scopes to a child\n * {@link MeasurableAdapterHistoryTransactionContext} (so nested scopes keep the\n * history-safe absent-`sql` / backend typing). Assignable to\n * {@link MeasurableTransactionContext} (and hence to {@link TransactionContext}),\n * so a projector helper typed against either still accepts it.\n */\nexport type MeasurableAdapterHistoryTransactionContext<\n  G extends GraphDef,\n  TNativeTransaction,\n> = AdapterHistoryTransactionContext<G, TNativeTransaction> &\n  Readonly<{\n    measure: ScopedMeasure<\n      MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>\n    >;\n  }>;\n\nexport type AdapterRecordedReadStore<\n  G extends GraphDef,\n  TNativeTransaction,\n> = ResolvedStoreCore<G> &\n  StoreEvolution<G, AdapterRecordedReadStore<G, TNativeTransaction>> &\n  AdapterStoreTransactions<G, TNativeTransaction> &\n  AdapterStoreReconciliation<\n    G,\n    TNativeTransaction,\n    AdapterRecordedReadStore<G, TNativeTransaction>\n  > &\n  Readonly<{\n    backend: GraphBackend;\n    recordedReadBound: true;\n  }>;\n\nexport type RecordedReadStore<G extends GraphDef> = ResolvedStoreCore<G> &\n  StoreTransactions<G> &\n  StoreEvolution<G, RecordedReadStore<G>> &\n  Readonly<{ recordedReadBound: true }>;\n\nexport type HistoryStore<G extends GraphDef> = ResolvedStoreCore<G> &\n  StoreEvolution<G, HistoryStore<G>> &\n  Readonly<{\n    transaction: <T>(\n      fn: (tx: HistoryTransactionContext<G>) => Promise<T>,\n      options?: StoreTransactionOptions,\n    ) => Promise<T>;\n    transactionWithReceipt: <T>(\n      fn: (tx: MeasurableHistoryTransactionContext<G>) => Promise<T>,\n      options?: StoreTransactionOptions,\n    ) => Promise<TransactionOutcome<T>>;\n    historyEnabled: true;\n    recordedReadBound: true;\n  }>;\n\nexport type AdapterHistoryStore<\n  G extends GraphDef,\n  TNativeTransaction,\n> = ResolvedStoreCore<G> &\n  StoreEvolution<G, AdapterHistoryStore<G, TNativeTransaction>> &\n  AdapterHistoryStoreTransactions<G, TNativeTransaction> &\n  AdapterStoreReconciliation<\n    G,\n    TNativeTransaction,\n    AdapterHistoryStore<G, TNativeTransaction>\n  > &\n  Readonly<{\n    backend: HistoryStoreBackend;\n    historyEnabled: true;\n    recordedReadBound: true;\n  }>;\n\ntype AdapterHistoryStoreTransactions<\n  G extends GraphDef,\n  TNativeTransaction,\n> = Readonly<{\n  transaction: <T>(\n    fn: (\n      tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<T>;\n  transactionWithReceipt: <T>(\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: StoreTransactionOptions,\n  ) => Promise<TransactionOutcome<T>>;\n  withEvolvedTransaction: <T>(\n    externalTransaction: TNativeTransaction,\n    plan: EvolutionPlan,\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n    options?: EvolvedTransactionOptions,\n  ) => Promise<EvolvedTransactionOutcome<T>>;\n  withRecordedTransaction: <T>(\n    externalTransaction: TNativeTransaction,\n    fn: (\n      tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n    ) => Promise<T>,\n  ) => Promise<TransactionOutcome<T>>;\n}>;\n\n/**\n * Creates a new Store instance.\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Optional store configuration including observability hooks\n * @returns A new Store instance\n *\n * @example\n * ```typescript\n * // Basic usage\n * const store = createStore(graph, backend);\n *\n * // With observability hooks\n * const store = createStore(graph, backend, {\n *   hooks: {\n *     onOperationStart: (ctx) => {\n *       console.log(`Starting ${ctx.operation} on ${ctx.entity}:${ctx.kind}`);\n *     },\n *     onOperationEnd: (ctx, result) => {\n *       console.log(`Completed in ${result.durationMs}ms`);\n *     },\n *     onError: (ctx, error) => {\n *       console.error(`Operation ${ctx.operationId} failed:`, error);\n *     },\n *   },\n * });\n * ```\n */\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: HistoryStoreOptions,\n): HistoryStore<G>;\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: RecordedReadStoreOptions,\n): RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: UnboundLiveStoreOptions,\n): Store<G>;\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: LiveStoreOptions | undefined,\n): Store<G> | RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: StoreOptions | undefined,\n): Store<G> | HistoryStore<G> | RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: StoreOptions,\n): Store<G> | HistoryStore<G> | RecordedReadStore<G> {\n  return new StoreImplementation<G>(graph, backend, options);\n}\n\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: HistoryStoreOptions & ReconciledOption<G>,\n): AdapterHistoryStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: RecordedReadStoreOptions & ReconciledOption<G>,\n): AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: UnboundLiveStoreOptions & ReconciledOption<G>,\n): AdapterStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: (LiveStoreOptions & ReconciledOption<G>) | undefined,\n):\n  | AdapterStore<G, TNativeTransaction>\n  | AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: (StoreOptions & ReconciledOption<G>) | undefined,\n):\n  | AdapterStore<G, TNativeTransaction>\n  | AdapterHistoryStore<G, TNativeTransaction>\n  | AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: StoreOptions & ReconciledOption<G>,\n):\n  | AdapterStore<G, TNativeTransaction>\n  | AdapterHistoryStore<G, TNativeTransaction>\n  | AdapterRecordedReadStore<G, TNativeTransaction> {\n  const reconciled = options?.reconciled;\n  if (reconciled !== undefined && reconciled.graph.id !== graph.id) {\n    // Same-shaped graphs are structurally interchangeable to TypeScript, so a\n    // snapshot from a different graph would silently reroute reads/writes to\n    // the wrong graph ID. Reject it — this is a zero-query check.\n    throw new ConfigurationError(\n      `Reconciled snapshot is for graph \"${reconciled.graph.id}\", not \"${graph.id}\".`,\n      { code: \"RECONCILED_GRAPH_MISMATCH\" },\n      {\n        suggestion:\n          \"Pass the ReconciledSchema produced from the same graph you are building the store with; snapshots are not interchangeable across graphs.\",\n      },\n    );\n  }\n  const storeOptions = stripReconciledOption(options);\n  // A reconciled snapshot is a pre-computed (graph, schemaMetadata) — the\n  // zero-round-trip equivalent of `prepareVerifiedStore`. Resolve the inputs,\n  // then take the single construction path. The merged graph is a superset of\n  // the compile-time `graph`, so runtime-committed kinds validate.\n  const resolvedGraph = reconciled?.graph ?? graph;\n  const schemaMetadata =\n    reconciled === undefined ? undefined : reconciledSchemaMetadata(reconciled);\n  return asAdapterStoreSurface(\n    new AdapterStoreImplementation(\n      resolvedGraph,\n      backend,\n      storeOptions,\n      schemaMetadata,\n    ),\n  );\n}\n\nfunction isKnownEdgeKind(graph: GraphDef, name: string): boolean {\n  return Object.hasOwn(graph.edges, name);\n}\n\nfunction setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n  if (a.size !== b.size) return false;\n  for (const value of a) if (!b.has(value)) return false;\n  return true;\n}\n\nfunction schemaMetadataFromRow(\n  row: SchemaVersionRow | undefined,\n): StoreSchemaMetadata {\n  if (row === undefined) return UNKNOWN_SCHEMA_METADATA;\n  return Object.freeze({\n    schemaVersion: row.version,\n    schemaHash: row.schema_hash,\n  });\n}\n\nfunction reconciledSchemaMetadata(\n  reconciled: ReconciledSchema<GraphDef>,\n): StoreSchemaMetadata {\n  return Object.freeze({\n    schemaVersion: reconciled.version,\n    schemaHash: reconciled.hash,\n  });\n}\n\n/**\n * Splits the construction-time `reconciled` snapshot off the persisted store\n * options. The store keeps its options verbatim to reconstruct the next store\n * on `evolve()`, so the snapshot — a one-shot construction source — must never\n * be carried forward.\n */\nfunction stripReconciledOption<G extends GraphDef>(\n  options: (StoreOptions & ReconciledOption<G>) | undefined,\n): StoreOptions | undefined {\n  if (options === undefined || !(\"reconciled\" in options)) return options;\n  const { reconciled: _reconciled, ...rest } = options;\n  return rest;\n}\n\nfunction schemaMetadataForResult(\n  activeRow: SchemaVersionRow | undefined,\n  result: SchemaValidationResult,\n): StoreSchemaMetadata {\n  if (result.status === \"initialized\" || result.status === \"migrated\") {\n    return schemaMetadataFromRow(result.committedRow);\n  }\n  return schemaMetadataFromRow(activeRow);\n}\n\n/**\n * Prefer the #129 contribution path; fall back to the pre-#129\n * `ensureFulltextTable` for backends that predate it. Idempotent and\n * cheap on a warm re-call (per-instance cache + recorded-signature\n * short-circuit).\n */\nasync function materializeRuntimeContributions(\n  backend: GraphBackend,\n  graphId: string,\n): Promise<void> {\n  if (backend.ensureRuntimeContributions) {\n    await backend.ensureRuntimeContributions(graphId);\n    return;\n  }\n  await backend.ensureFulltextTable?.(graphId);\n}\n\n/**\n * Privileged boot step: materialize every embedding `(kind, field)` slot's\n * per-field vector table + durable marker, enumerated from the graph via\n * {@link resolveGraphVectorSlots}. The vector counterpart of\n * {@link materializeRuntimeContributions} (fulltext) — runs once under the\n * privileged role inside `createStoreWithSchema` so a least-privilege runtime\n * can assert the markers (a cached SELECT) and write embeddings without\n * holding `CREATE` on the schema. No-op on backends without vector support\n * (both vector contribution methods absent, or `capabilities.vector`\n * unsupported) and for graphs that declare no embedding fields. Built-in\n * backends use the batch method; the singular loop is the compatibility path.\n *\n * `onDrift: \"skip\"`: a slot already provisioned at a DIFFERENT shape (the\n * declared dimension changed since the table was created) is warned about\n * and left untouched rather than refused — boot must stay reachable so the\n * operator can run `store.reembedVectorField(kind, fieldPath)`, the\n * sanctioned recreate-and-restamp path. Until then, writes to that slot\n * fail with a typed `stale` StoreNotInitializedError.\n */\nasync function materializeVectorContributions(\n  backend: GraphBackend,\n  graph: GraphDef,\n): Promise<void> {\n  if (backend.capabilities.vector?.supported !== true) return;\n  const slots = resolveGraphVectorSlots(graph);\n  const ensureVectorSlotContributions = backend.ensureVectorSlotContributions;\n  if (ensureVectorSlotContributions !== undefined) {\n    await ensureVectorSlotContributions(slots, { onDrift: \"skip\" });\n    return;\n  }\n  const ensureVectorSlotContribution = backend.ensureVectorSlotContribution;\n  if (ensureVectorSlotContribution === undefined) return;\n  for (const slot of slots) {\n    await ensureVectorSlotContribution(slot, { onDrift: \"skip\" });\n  }\n}\n\n// ============================================================\n// Async Factory with Schema Management\n// ============================================================\n\n// Re-export schema manager types\nexport type {\n  SchemaManagerOptions,\n  SchemaValidationResult,\n} from \"../schema/manager\";\n\n/**\n * Creates a store and ensures the schema is initialized/migrated.\n *\n * This is the recommended way to create a store in production.\n * It automatically:\n * - Creates base tables on a fresh database (if the backend supports bootstrapTables)\n * - Initializes the schema on first run (version 1)\n * - Auto-migrates safe changes (additive changes)\n * - Throws MigrationError for breaking changes\n * - Fences managed writes against concurrent schema-version commits; a stale Store\n *   fails before writing instead of landing rows against a replaced schema\n *   (official transactional backends only; unsupported custom backends fail\n *   closed on their first managed write)\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Store and schema options\n * @returns A tuple of [store, validationResult]\n *\n * @example\n * ```typescript\n * const [store, result] = await createStoreWithSchema(graph, backend);\n *\n * if (result.status === \"initialized\") {\n *   console.log(\"Schema initialized at version\", result.version);\n * } else if (result.status === \"migrated\") {\n *   console.log(`Migrated from v${result.fromVersion} to v${result.toVersion}`);\n * } else if (result.status === \"pending\") {\n *   console.log(`Safe changes pending at version ${result.version}`);\n * }\n * ```\n */\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: HistoryStoreOptions & SchemaManagerOptions,\n): Promise<[HistoryStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: RecordedReadStoreOptions & SchemaManagerOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: UnboundLiveStoreOptions & SchemaManagerOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: (LiveStoreOptions & SchemaManagerOptions) | undefined,\n): Promise<[Store<G> | RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n  [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: StoreOptions & SchemaManagerOptions,\n): Promise<\n  [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n> {\n  const prepared = await prepareStoreWithSchema(graph, backend, options);\n  return [\n    new StoreImplementation(\n      prepared.graph,\n      backend,\n      options,\n      prepared.schemaMetadata,\n    ),\n    prepared.result,\n  ];\n}\n\ntype PreparedStore<G extends GraphDef> = Readonly<{\n  graph: G;\n  result: SchemaValidationResult;\n  schemaMetadata: StoreSchemaMetadata;\n}>;\n\nasync function assertHistorySchemaOnOpen(\n  backend: GraphBackend,\n  graph: GraphDef,\n  options: StoreOptions | undefined,\n): Promise<void> {\n  if (options?.history !== true) return;\n  // Only a TypeGraph-owned store reads or writes the recorded relations\n  // this check verifies; an engine-native backend has none, and gating on\n  // `history` alone would refuse it with RECORDED_SCHEMA_INCOMPATIBLE for a\n  // table shape it was never going to touch.\n  if (resolveRecordedTimeOwnership(backend) !== \"typegraph-relations\") return;\n  const schema =\n    options.schema === undefined ?\n      createSqlSchema(backend.tableNames)\n    : requireSqlSchema(options.schema, \"store schema\");\n  await assertCurrentRecordedSchema(\n    backend,\n    schema,\n    graph.identity !== undefined,\n  );\n}\n\nconst IDENTITY_ONTOLOGY_META_EDGES: ReadonlySet<string> = new Set([\n  META_EDGE_DISJOINT_WITH,\n  META_EDGE_EQUIVALENT_TO,\n  META_EDGE_SAME_AS,\n  META_EDGE_SUB_CLASS_OF,\n]);\n\nfunction identityOntologyChanged(\n  before: SerializedSchema,\n  after: SerializedSchema,\n): boolean {\n  function relevantRelations(schema: SerializedSchema): readonly string[] {\n    return schema.ontology.relations\n      .filter((relation) => IDENTITY_ONTOLOGY_META_EDGES.has(relation.metaEdge))\n      .map((relation) =>\n        JSON.stringify([relation.metaEdge, relation.from, relation.to]),\n      )\n      .toSorted();\n  }\n  return (\n    JSON.stringify(relevantRelations(before)) !==\n    JSON.stringify(relevantRelations(after))\n  );\n}\n\n/** Which identity semantic change is waiting on an unapplied migration. */\ntype IdentitySchemaGate = \"enablement\" | \"profile\" | \"ontology\";\n\nconst IDENTITY_GATE_CODES = {\n  enablement: \"IDENTITY_ENABLEMENT_PENDING\",\n  profile: \"IDENTITY_PROFILE_MIGRATION_PENDING\",\n  ontology: \"IDENTITY_SCHEMA_MIGRATION_PENDING\",\n} as const;\n\n/**\n * Runs the schema gate, but lets the identity-specific refusal win over the\n * generic `MigrationError` when the identity change is the *only* breaking\n * change in the diff.\n *\n * A `sameIdAcrossKinds` flip is classified breaking (it rewrites every\n * `areSame` / `membersOf` answer), so the generic gate would otherwise be the\n * only thing a caller ever sees and the documented `IDENTITY_*` codes would be\n * unreachable. When the diff carries other breaking changes too, the generic\n * error wins: it enumerates all of them, which the identity error cannot.\n */\nasync function ensureSchemaWithIdentityPrecedence<G extends GraphDef>(\n  backend: GraphBackend,\n  graph: G,\n  options: StoreOptions & SchemaManagerOptions,\n  gate: IdentitySchemaGate | undefined,\n): Promise<SchemaValidationResult> {\n  try {\n    return await ensureSchemaImpl(backend, graph, options);\n  } catch (error) {\n    if (gate === undefined || !isIdentityOnlyBreakingChange(error)) throw error;\n    throw identityMigrationRequiredError(graph.id, gate, {\n      blockedBy: \"breaking-change\",\n      cause: error,\n    });\n  }\n}\n\nfunction isIdentityOnlyBreakingChange(error: unknown): boolean {\n  if (!(error instanceof MigrationError)) return false;\n  const diff = \"diff\" in error.details ? error.details.diff : undefined;\n  if (diff?.identity?.severity !== \"breaking\") return false;\n  return ![\n    ...diff.nodes,\n    ...diff.edges,\n    ...diff.ontology,\n    ...diff.indexes,\n  ].some((change) => change.severity === \"breaking\");\n}\n\nfunction identityMigrationRequiredError(\n  graphId: string,\n  gate: IdentitySchemaGate,\n  context: Readonly<{\n    blockedBy: \"breaking-change\" | \"auto-migrate-disabled\";\n    pendingVersion?: number;\n    cause?: unknown;\n  }>,\n): ConfigurationError {\n  const blocker =\n    context.blockedBy === \"breaking-change\" ?\n      \"but the change is breaking and has not been applied.\"\n    : \"but autoMigrate is disabled and the change is pending.\";\n  return new ConfigurationError(\n    `Changing Operational Identity semantics requires the schema migration to commit, ${blocker}`,\n    {\n      code: IDENTITY_GATE_CODES[gate],\n      graphId,\n      ...(context.pendingVersion === undefined ?\n        {}\n      : { pendingVersion: context.pendingVersion }),\n    },\n    {\n      cause: context.cause,\n      suggestion:\n        \"Apply the migration explicitly with migrateSchema(backend, graph, activeVersion) — it commits the new version and rebuilds the identity closure in the same transaction — or, for a change that is not breaking, enable autoMigrate.\",\n    },\n  );\n}\n\n/** One fenced, revision-neutral entry for public and startup identity repair. */\nfunction rebuildIdentityClosureWithSchemaFence<G extends GraphDef>(\n  identityContext: IdentityRebuildContext<G>,\n  writeContext: WriteTransactionContext,\n): Promise<void> {\n  return runInWriteTransaction(\n    writeContext,\n    identityContext.backend,\n    async (target) =>\n      rebuildIdentityClosureForContext({ ...identityContext, backend: target }),\n    { didWrite: () => false },\n  );\n}\n\nasync function prepareStoreWithSchema<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<PreparedStore<G>> {\n  // Fold any persisted graph extension into the graph BEFORE\n  // constructing the Store. The prefetched row + parsed schema thread\n  // through to ensureSchema so each Store boot pays for one DB round\n  // trip and one Zod parse, not two. Additional extension kinds are\n  // reachable through the registry but invisible to the type system —\n  // see `mergeGraphExtension`.\n  const {\n    graph: merged,\n    activeRow,\n    storedSchema,\n  } = await loadAndMergeGraphExtensionDocument(backend, graph);\n\n  const identityProfileChanged =\n    activeRow !== undefined &&\n    storedSchema?.identity?.sameIdAcrossKinds !==\n      merged.identity?.sameIdAcrossKinds;\n  // The very first schema commit is an enablement too: a legacy database\n  // populated through an unmanaged `createStore` can already hold same-id\n  // peers and assertions, so initialization must run the same fold scan,\n  // contradiction validation, and closure build as a later enablement\n  // migration — an empty database just makes them cheap no-ops.\n  const identityInitialization =\n    activeRow === undefined && merged.identity !== undefined;\n  const identityEnablement =\n    identityInitialization ||\n    (identityProfileChanged &&\n      storedSchema?.identity === undefined &&\n      merged.identity !== undefined);\n  const identitySemanticsChanged =\n    identityProfileChanged ||\n    (activeRow !== undefined &&\n      storedSchema !== undefined &&\n      merged.identity !== undefined &&\n      identityOntologyChanged(\n        storedSchema,\n        serializeSchema(merged, activeRow.version + 1),\n      ));\n\n  // Resolved before the provisioning below, which asks whether a schema commit\n  // is already going to rebuild the derived identity relations.\n  const identityGate: IdentitySchemaGate | undefined =\n    identitySemanticsChanged ?\n      identityEnablement ? \"enablement\"\n      : identityProfileChanged ? \"profile\"\n      : \"ontology\"\n    : undefined;\n\n  // First enablement over an existing populated database: createStore /\n  // createSqliteBackend / createPostgresBackend ran no DDL, so the identity\n  // relations the enablement preflight reads/writes may not exist yet.\n  // Ensure them BEFORE the schema-commit transaction — running enablement DDL\n  // inside the preflight would re-enter the backend's per-graph write lock the\n  // commit already holds. Idempotent (CREATE TABLE / CREATE INDEX IF NOT\n  // EXISTS), so it is a harmless no-op when the schema turns out to be pending\n  // (finding: enablement requires an applied migration) or the tables already\n  // exist.\n  const identityProfile = merged.identity;\n  if (identityProfile !== undefined) {\n    // Brand-validate BEFORE the DDL: a counterfeit schema-shaped object must\n    // reject with INVALID_SQL_SCHEMA and leave no tables behind — and must\n    // not surface as IDENTITY_STORAGE_MISSING on an already enabled graph.\n    const resolvedIdentitySchema =\n      options?.schema === undefined ?\n        createSqlSchema(backend.tableNames)\n      : requireSqlSchema(options.schema, \"store schema\");\n    // One registry for the decision and the derivation it predicts: the\n    // predicate must scope the ledger by exactly the kinds the rebuild below\n    // derives through, or it asks for a rebuild that cannot converge.\n    const identityRegistry = buildKindRegistry(merged);\n    // THE RETURNED OBLIGATION IS DISCARDED HERE, DELIBERATELY. It is non-empty\n    // only on the gated path below (recompute withheld), and it names DDL that\n    // must be issued INSIDE the schema-commit transaction — which this call\n    // site does not own. `prepareIdentitySchemaCommit` re-derives it by calling\n    // `ensureIdentitySchemaStorage` again, from the same backend, schema,\n    // registry and enablement flag, and hands it to the commit preflight that\n    // can honor it. What keeps that safe is the equality of those four inputs,\n    // so a change that lets this site resolve the schema or build the registry\n    // differently from `prepareIdentitySchemaCommit` breaks it — silently, by\n    // provisioning for one shape and filling for another. The call is still\n    // load-bearing for its EFFECT: it runs the idempotent identity DDL before\n    // the commit takes the per-graph write lock.\n    await ensureIdentitySchemaStorage(backend, resolvedIdentitySchema, {\n      graphId: merged.id,\n      enablement: identityEnablement,\n      registry: identityRegistry,\n      // A derived relation this library version added, absent from (or left\n      // empty in) a database that predates it, is created and FILLED as one\n      // unit here — never created now and filled at the end of boot. Between\n      // those two points sit the schema commit, the history assertion, three\n      // materialization steps and an index build, and for that whole window an\n      // empty separation relation would answer \"not separated\" to every\n      // concurrent `assertSame`. See `ensureIdentitySchemaStorage`.\n      //\n      // Withheld when a schema commit is gated on an identity SEMANTICS\n      // change: that commit's own preflight creates AND rebuilds inside the\n      // commit transaction, under the semantics being committed. Filling here\n      // would instead derive classes from semantics this database has not\n      // accepted yet — and would keep them if the commit were then refused.\n      // Nothing is provisioned on that path either, so a refused commit leaves\n      // the relation absent rather than readable-empty, and the next open of a\n      // graph whose semantics ARE committed heals it here.\n      ...(identityGate === undefined ?\n        {\n          // The registry was resolved before this transaction. Pin its schema\n          // version before taking the identity lock: a concurrent migration\n          // may already have rebuilt under different semantics, and a stale\n          // startup must not overwrite that closure even if boot later fails.\n          recomputeDerivedRelations: (target) =>\n            rebuildIdentityClosureWithSchemaFence(\n              {\n                backend: target,\n                graphId: merged.id,\n                registry: identityRegistry,\n                schema: resolvedIdentitySchema,\n                sameIdAcrossKinds: identityProfile.sameIdAcrossKinds,\n              },\n              {\n                graphId: merged.id,\n                schemaVersion: activeRow?.version,\n                historyEnabled: false,\n                revisionTrackingEnabled: false,\n                revisionSchema: resolvedIdentitySchema,\n              },\n            ),\n        }\n      : {}),\n    });\n  }\n\n  // No identity preflight is passed here — the schema manager derives the\n  // mandatory one itself (from `options.schema` when supplied), so no public\n  // caller can substitute or suppress the closure rebuild.\n  const ensureOptions = {\n    // The fallback is not useless: spreading `options` while it is possibly\n    // undefined makes TypeScript distribute the StoreOptions union through\n    // the literal and reject the call below.\n    // eslint-disable-next-line unicorn/no-useless-fallback-in-spread\n    ...(options ?? {}),\n    preloaded: { activeRow, storedSchema },\n  };\n\n  // An identity semantic change reaches the store only after the preflight\n  // (closure materialization + same-id fold) has COMMITTED with the schema\n  // version; otherwise `store.identity` would answer from an empty or stale\n  // closure — silently wrong reads. Two blockers stop that commit, and each\n  // must surface the identity-specific code rather than a generic failure:\n  // an unapplied breaking change (a `sameIdAcrossKinds` flip or a disable),\n  // and `autoMigrate: false` leaving a safe change pending.\n  const result = await ensureSchemaWithIdentityPrecedence(\n    backend,\n    merged,\n    ensureOptions,\n    identityGate,\n  );\n\n  if (identityGate !== undefined && result.status === \"pending\") {\n    throw identityMigrationRequiredError(merged.id, identityGate, {\n      blockedBy: \"auto-migrate-disabled\",\n      pendingVersion: result.version,\n    });\n  }\n\n  await assertHistorySchemaOnOpen(backend, merged, options);\n\n  // #135/#143: this is the single durable-marker writer, and it MUST\n  // run after ensureSchemaImpl so the breaking-change gate is reached\n  // first — otherwise contribution DDL derived from the new code graph\n  // would hit a stale table shape and mask `MigrationError`.\n  await materializeRuntimeContributions(backend, merged.id);\n  // Provision every embedding field's per-`(kind, field)` vector table +\n  // durable marker under the privileged role, so a least-privilege runtime\n  // asserts the markers (SELECT) and writes embeddings without `CREATE`.\n  await materializeVectorContributions(backend, merged);\n  // Bring the base-relation system indexes up to this library version.\n  // Bootstrap DDL only runs on first boot, so an index shipped in a newer\n  // version reaches already-initialized databases here — this is the same\n  // privileged-boot step the contributions above use. `systemIndexes:\n  // \"skip\"` defers to an out-of-band store.materializeSystemIndexes()\n  // for deployments that must not run index builds inline at boot.\n  if (options?.systemIndexes !== \"skip\") {\n    await materializeSystemIndexesOnBoot(backend, merged.id, result);\n  }\n\n  // No late derived-relation fill runs here, and that absence is the point.\n  // Boot has exactly two provisioning sites now, each of which publishes a\n  // CREATE and its fill as one transaction: the fence above (no identity\n  // semantics change) and the schema commit's own preflight (there is one).\n  // A fill deferred to this point would have spent the whole commit + history\n  // + materialization + index-build sequence answering \"not separated\" for\n  // every pair — and would have been skipped entirely whenever the commit it\n  // belonged to was refused, leaving that answer permanent.\n\n  return {\n    graph: merged,\n    result,\n    schemaMetadata: schemaMetadataForResult(activeRow, result),\n  };\n}\n\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: HistoryStoreOptions & SchemaManagerOptions,\n): Promise<\n  [AdapterHistoryStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: RecordedReadStoreOptions & SchemaManagerOptions,\n): Promise<\n  [AdapterRecordedReadStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: UnboundLiveStoreOptions & SchemaManagerOptions,\n): Promise<[AdapterStore<G, TNativeTransaction>, SchemaValidationResult]>;\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: (LiveStoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n>;\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterHistoryStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n>;\nexport async function createAdapterStoreWithSchema<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: StoreOptions & SchemaManagerOptions,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterHistoryStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n> {\n  const prepared = await prepareStoreWithSchema(graph, backend, options);\n  return [\n    asAdapterStoreSurface(\n      new AdapterStoreImplementation(\n        prepared.graph,\n        backend,\n        options,\n        prepared.schemaMetadata,\n      ),\n    ),\n    prepared.result,\n  ];\n}\n\n/**\n * Boot-path system-index materialization. Lenient where the explicit\n * `store.materializeSystemIndexes()` API is strict:\n *\n * - Backends without `executeDdl` / status primitives are skipped —\n *   their deployments keep the bootstrap-only behavior they had before\n *   system indexes were materialized at boot, instead of failing to boot.\n * - Skipped when the schema gate did not pass (`\"breaking\"`).\n * - Individual index failures degrade to a warning: system indexes are a\n *   performance concern, and a store that cannot build one must still\n *   come up (the operator retries via `store.materializeSystemIndexes()`).\n */\nasync function materializeSystemIndexesOnBoot(\n  backend: GraphBackend,\n  graphId: string,\n  result: SchemaValidationResult,\n): Promise<void> {\n  if (result.status === \"breaking\") return;\n  if (!backendSupportsIndexMaterialization(backend)) return;\n  const schemaVersion =\n    result.status === \"migrated\" ? result.toVersion : result.version;\n  try {\n    const { results } = await materializeSystemIndexesImpl(\n      { backend: asRawBackend(backend), graphId, schemaVersion },\n      {},\n    );\n    const failed = results.filter(\n      (entryResult) => entryResult.status === \"failed\",\n    );\n    if (failed.length === 0) return;\n    console.warn(\n      `[typegraph] ${String(failed.length)} system index(es) failed to ` +\n        `materialize at boot (${failed\n          .map((entryResult) => entryResult.indexName)\n          .join(\", \")}); the store is usable but the affected access paths ` +\n        \"fall back to scans. Retry via store.materializeSystemIndexes().\",\n      failed[0]?.error,\n    );\n  } catch (error) {\n    // Leniency must hold for infrastructure throws too (status-table\n    // ensure/preload/record failures, claim writes) — not only per-index\n    // build failures. A store that booted on the previous version must\n    // still come up after an upgrade; the operator retries explicitly.\n    console.warn(\n      \"[typegraph] system-index materialization failed at boot; the store \" +\n        \"is usable but new system indexes were not adopted. Retry via \" +\n        \"store.materializeSystemIndexes().\",\n      error,\n    );\n  }\n}\n\n/**\n * Creates a Store after **verifying** that the database is at the same\n * schema version as the code graph — without running any DDL, bootstrap,\n * or marker writes. The runtime counterpart of `createStoreWithSchema`\n * for the deployment model in \"Database roles & least privilege\":\n *\n * - **`createStoreWithSchema(graph, backend)`** runs DDL (bootstrap,\n *   safe auto-migrations, durable contribution materialization). Run it\n *   once at startup under a privileged role that holds `CREATE` / DDL.\n * - **`createVerifiedStore(graph, backend)`** is the zero-DDL runtime\n *   attach with a verification gate. Throws `MigrationError` when the\n *   persisted schema is behind the code graph (any pending change, safe\n *   or breaking), `ConfigurationError` when no schema has been\n *   initialized, or `StoreNotInitializedError` when the schema is\n *   current but the runtime-contribution markers are missing/stale.\n *   The runtime can use a least-privilege, DML-only database role.\n *   Managed writes are fenced against concurrent schema-version commits just like\n *   `createStoreWithSchema`; a stale verified Store fails before writing.\n *   Runtime backends must support transactions and the schema-write fence;\n *   unsupported custom or HTTP backends attach for reads but fail closed on a\n *   managed write.\n * - **`createStore(graph, backend)`** is the same zero-DDL attach\n *   *without* the verification gate — fastest, but schema drift goes\n *   undetected until a hot-path operation trips.\n *\n * Folds any persisted graph-extension document into the supplied graph\n * before building the Store, just like `createStoreWithSchema`.\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Optional store configuration\n * @returns A tuple of [store, validationResult] — `result.status` is\n *   always `\"unchanged\"` on success\n *\n * @example\n * ```typescript\n * // Runtime — least-privilege, DML-only role. Zero DDL.\n * const [store, result] = await createVerifiedStore(graph, backend);\n * // result.status === \"unchanged\" — the privileged migrator is current.\n * ```\n *\n * @throws ConfigurationError if no schema has been initialized.\n * @throws MigrationError if the persisted schema is behind the code graph.\n * @throws StoreNotInitializedError if runtime-contribution markers are\n *   missing/stale/failed for this graph on this connection.\n */\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: HistoryStoreOptions,\n): Promise<[HistoryStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: RecordedReadStoreOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: UnboundLiveStoreOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: LiveStoreOptions | undefined,\n): Promise<[Store<G> | RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: StoreOptions | undefined,\n): Promise<\n  [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n>;\nexport async function createVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options?: StoreOptions,\n): Promise<\n  [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n> {\n  const prepared = await prepareVerifiedStore(graph, backend, options);\n  const store = new StoreImplementation(\n    prepared.graph,\n    backend,\n    options,\n    prepared.schemaMetadata,\n  );\n  await store.validateIdentity();\n  return [store, prepared.result];\n}\n\nasync function prepareVerifiedStore<G extends GraphDef>(\n  graph: G,\n  backend: GraphBackend,\n  options: StoreOptions | undefined,\n): Promise<PreparedStore<G>> {\n  const {\n    graph: merged,\n    activeRow,\n    result,\n  } = await loadAndVerifyGraph(backend, graph);\n  await assertHistorySchemaOnOpen(backend, merged, options);\n  return {\n    graph: merged,\n    result,\n    schemaMetadata: schemaMetadataFromRow(activeRow),\n  };\n}\n\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: HistoryStoreOptions,\n): Promise<\n  [AdapterHistoryStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: RecordedReadStoreOptions,\n): Promise<\n  [AdapterRecordedReadStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: UnboundLiveStoreOptions,\n): Promise<[AdapterStore<G, TNativeTransaction>, SchemaValidationResult]>;\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: LiveStoreOptions | undefined,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n>;\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options: StoreOptions | undefined,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterHistoryStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n>;\nexport async function createVerifiedAdapterStore<\n  G extends GraphDef,\n  TNativeTransaction,\n>(\n  graph: G,\n  backend: AdapterBackend<TNativeTransaction>,\n  options?: StoreOptions,\n): Promise<\n  [\n    (\n      | AdapterStore<G, TNativeTransaction>\n      | AdapterHistoryStore<G, TNativeTransaction>\n      | AdapterRecordedReadStore<G, TNativeTransaction>\n    ),\n    SchemaValidationResult,\n  ]\n> {\n  const prepared = await prepareVerifiedStore(graph, backend, options);\n  const store = new AdapterStoreImplementation(\n    prepared.graph,\n    backend,\n    options,\n    prepared.schemaMetadata,\n  );\n  await store.validateIdentity();\n  return [asAdapterStoreSurface(store), prepared.result];\n}\n"]}