@nicia-ai/typegraph 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/backend/postgres/index.cjs +19 -19
  2. package/dist/backend/postgres/index.js +6 -6
  3. package/dist/backend/postgres/pglite.cjs +11 -11
  4. package/dist/backend/postgres/pglite.js +6 -6
  5. package/dist/backend/sqlite/index.cjs +9 -9
  6. package/dist/backend/sqlite/index.js +6 -6
  7. package/dist/backend/sqlite/libsql.cjs +8 -8
  8. package/dist/backend/sqlite/libsql.js +6 -6
  9. package/dist/backend/sqlite/local.cjs +16 -16
  10. package/dist/backend/sqlite/local.js +6 -6
  11. package/dist/{chunk-VPYHY3LJ.cjs → chunk-2THZ3TQI.cjs} +11 -11
  12. package/dist/{chunk-VPYHY3LJ.cjs.map → chunk-2THZ3TQI.cjs.map} +1 -1
  13. package/dist/{chunk-EM3CWPND.cjs → chunk-456Z2U7Y.cjs} +51 -51
  14. package/dist/{chunk-EM3CWPND.cjs.map → chunk-456Z2U7Y.cjs.map} +1 -1
  15. package/dist/{chunk-GSQ6NPH6.cjs → chunk-4BCU6VFZ.cjs} +7 -7
  16. package/dist/{chunk-GSQ6NPH6.cjs.map → chunk-4BCU6VFZ.cjs.map} +1 -1
  17. package/dist/chunk-4BMPGT35.cjs +12 -0
  18. package/dist/{chunk-GUR2FNB5.cjs.map → chunk-4BMPGT35.cjs.map} +1 -1
  19. package/dist/{chunk-WJT7OU7E.cjs → chunk-4CAXEB2F.cjs} +124 -92
  20. package/dist/chunk-4CAXEB2F.cjs.map +1 -0
  21. package/dist/{chunk-WDBCBWC4.js → chunk-4GX2JJXS.js} +6 -6
  22. package/dist/{chunk-WDBCBWC4.js.map → chunk-4GX2JJXS.js.map} +1 -1
  23. package/dist/{chunk-UES55P7G.js → chunk-5DIPR3L3.js} +284 -154
  24. package/dist/chunk-5DIPR3L3.js.map +1 -0
  25. package/dist/{chunk-CZQ3FO2Q.js → chunk-5VTR2F2K.js} +49 -16
  26. package/dist/chunk-5VTR2F2K.js.map +1 -0
  27. package/dist/{chunk-CTTSDJLY.cjs → chunk-5W4L6DLF.cjs} +11 -11
  28. package/dist/{chunk-CTTSDJLY.cjs.map → chunk-5W4L6DLF.cjs.map} +1 -1
  29. package/dist/{chunk-J7WFGBJR.cjs → chunk-7BQLPXK6.cjs} +865 -735
  30. package/dist/chunk-7BQLPXK6.cjs.map +1 -0
  31. package/dist/{chunk-3TWF3SH4.js → chunk-BJVEU3ZL.js} +7 -7
  32. package/dist/{chunk-3TWF3SH4.js.map → chunk-BJVEU3ZL.js.map} +1 -1
  33. package/dist/{chunk-LGEALRC6.cjs → chunk-DIK74MXX.cjs} +18 -2
  34. package/dist/chunk-DIK74MXX.cjs.map +1 -0
  35. package/dist/{chunk-QNKSQTKQ.js → chunk-DN5VP4JC.js} +48 -17
  36. package/dist/chunk-DN5VP4JC.js.map +1 -0
  37. package/dist/{chunk-4JEZZJ6S.cjs → chunk-HW3LW7DH.cjs} +39 -39
  38. package/dist/{chunk-4JEZZJ6S.cjs.map → chunk-HW3LW7DH.cjs.map} +1 -1
  39. package/dist/{chunk-JBTOYDMN.js → chunk-IU46OHVW.js} +4 -4
  40. package/dist/{chunk-JBTOYDMN.js.map → chunk-IU46OHVW.js.map} +1 -1
  41. package/dist/{chunk-FL472AMI.cjs → chunk-J3LEGNQB.cjs} +8 -8
  42. package/dist/{chunk-FL472AMI.cjs.map → chunk-J3LEGNQB.cjs.map} +1 -1
  43. package/dist/{chunk-O7UN7OXA.cjs → chunk-JFMEONLG.cjs} +80 -80
  44. package/dist/{chunk-O7UN7OXA.cjs.map → chunk-JFMEONLG.cjs.map} +1 -1
  45. package/dist/{chunk-I7ZUZKFD.js → chunk-JFUPDJXD.js} +3 -3
  46. package/dist/{chunk-I7ZUZKFD.js.map → chunk-JFUPDJXD.js.map} +1 -1
  47. package/dist/{chunk-K3PPLHY7.js → chunk-M75SUBFG.js} +7 -7
  48. package/dist/{chunk-K3PPLHY7.js.map → chunk-M75SUBFG.js.map} +1 -1
  49. package/dist/{chunk-CK5BVQOW.cjs → chunk-PWGX5DF5.cjs} +79 -79
  50. package/dist/{chunk-CK5BVQOW.cjs.map → chunk-PWGX5DF5.cjs.map} +1 -1
  51. package/dist/{chunk-KMI7LYAF.js → chunk-PZKNKG5M.js} +8 -8
  52. package/dist/{chunk-KMI7LYAF.js.map → chunk-PZKNKG5M.js.map} +1 -1
  53. package/dist/{chunk-55MZDDZV.js → chunk-RAXU3RMB.js} +4 -4
  54. package/dist/{chunk-55MZDDZV.js.map → chunk-RAXU3RMB.js.map} +1 -1
  55. package/dist/{chunk-BLZDPRXT.cjs → chunk-RSSQKPSZ.cjs} +5 -5
  56. package/dist/{chunk-BLZDPRXT.cjs.map → chunk-RSSQKPSZ.cjs.map} +1 -1
  57. package/dist/{chunk-RGPG7EOJ.js → chunk-S5F7ZLP2.js} +3 -3
  58. package/dist/{chunk-RGPG7EOJ.js.map → chunk-S5F7ZLP2.js.map} +1 -1
  59. package/dist/{chunk-QWEUYILR.js → chunk-SKCOUWAX.js} +3 -3
  60. package/dist/{chunk-QWEUYILR.js.map → chunk-SKCOUWAX.js.map} +1 -1
  61. package/dist/{chunk-QOTI55H7.js → chunk-SXGE7ITL.js} +4 -4
  62. package/dist/{chunk-QOTI55H7.js.map → chunk-SXGE7ITL.js.map} +1 -1
  63. package/dist/{chunk-RGP33ZJ5.js → chunk-VQEXF5D4.js} +7 -7
  64. package/dist/{chunk-RGP33ZJ5.js.map → chunk-VQEXF5D4.js.map} +1 -1
  65. package/dist/{chunk-MP2JQKSG.js → chunk-WI7ISNQF.js} +17 -3
  66. package/dist/chunk-WI7ISNQF.js.map +1 -0
  67. package/dist/{chunk-4TOD4LBZ.cjs → chunk-X4JBT642.cjs} +29 -29
  68. package/dist/{chunk-4TOD4LBZ.cjs.map → chunk-X4JBT642.cjs.map} +1 -1
  69. package/dist/{chunk-EMF62TZG.cjs → chunk-ZAMFOJ5P.cjs} +86 -86
  70. package/dist/{chunk-EMF62TZG.cjs.map → chunk-ZAMFOJ5P.cjs.map} +1 -1
  71. package/dist/{chunk-VSPCZAXF.js → chunk-ZIGXMKQQ.js} +3 -3
  72. package/dist/{chunk-VSPCZAXF.js.map → chunk-ZIGXMKQQ.js.map} +1 -1
  73. package/dist/{chunk-XOX22WHL.cjs → chunk-ZUNQ5BEP.cjs} +104 -71
  74. package/dist/chunk-ZUNQ5BEP.cjs.map +1 -0
  75. package/dist/graph-extension/index.cjs +19 -19
  76. package/dist/graph-extension/index.d.cts +1 -1
  77. package/dist/graph-extension/index.d.ts +1 -1
  78. package/dist/graph-extension/index.js +4 -4
  79. package/dist/graph-merge/index.cjs +82 -82
  80. package/dist/graph-merge/index.cjs.map +1 -1
  81. package/dist/graph-merge/index.d.cts +2 -2
  82. package/dist/graph-merge/index.d.ts +2 -2
  83. package/dist/graph-merge/index.js +13 -13
  84. package/dist/graph-merge/index.js.map +1 -1
  85. package/dist/{index-6CSUAq-x.d.ts → index-BFvdmBPV.d.ts} +68 -1
  86. package/dist/{index-Bks_3HHK.d.cts → index-BLtQWKRj.d.cts} +68 -1
  87. package/dist/index.cjs +144 -136
  88. package/dist/index.d.cts +3 -3
  89. package/dist/index.d.ts +3 -3
  90. package/dist/index.js +14 -14
  91. package/dist/interchange/index.cjs +27 -26
  92. package/dist/interchange/index.d.cts +1 -1
  93. package/dist/interchange/index.d.ts +1 -1
  94. package/dist/interchange/index.js +9 -8
  95. package/dist/profiler/index.d.cts +1 -1
  96. package/dist/profiler/index.d.ts +1 -1
  97. package/dist/provenance/index.cjs +31 -31
  98. package/dist/provenance/index.d.cts +1 -1
  99. package/dist/provenance/index.d.ts +1 -1
  100. package/dist/provenance/index.js +4 -4
  101. package/dist/schema/index.cjs +31 -31
  102. package/dist/schema/index.d.cts +1 -1
  103. package/dist/schema/index.d.ts +1 -1
  104. package/dist/schema/index.js +7 -7
  105. package/dist/{store-view-BSpqvAxK.d.cts → store-view-9KDOpZzF.d.cts} +250 -36
  106. package/dist/{store-view-CKbHFRnn.d.ts → store-view-DplHC3Nt.d.ts} +250 -36
  107. package/package.json +1 -1
  108. package/dist/chunk-CZQ3FO2Q.js.map +0 -1
  109. package/dist/chunk-GUR2FNB5.cjs +0 -12
  110. package/dist/chunk-J7WFGBJR.cjs.map +0 -1
  111. package/dist/chunk-LGEALRC6.cjs.map +0 -1
  112. package/dist/chunk-MP2JQKSG.js.map +0 -1
  113. package/dist/chunk-QNKSQTKQ.js.map +0 -1
  114. package/dist/chunk-UES55P7G.js.map +0 -1
  115. package/dist/chunk-WJT7OU7E.cjs.map +0 -1
  116. package/dist/chunk-XOX22WHL.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"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/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/typed-json-extract.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/recursive.ts","../src/query/execution/value-decoder.ts","../src/store/recursive-cte.ts","../src/store/subgraph.ts","../src/query/compiler/set-operations.ts","../src/query/compiler/standard-pass-pipeline.ts","../src/query/compiler/index.ts","../src/utils/path.ts","../src/query/execution/result-mapper.ts","../src/query/cursor.ts","../src/query/execution/pagination.ts","../src/query/execution/field-tracker.ts","../src/query/execution/selective-result-mapper.ts","../src/query/builder/read-instant-template.ts","../src/query/builder/prepared-query.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/executable-query.ts","../src/query/builder/executable-aggregate-query.ts","../src/query/builder/dynamic.ts","../src/query/builder/traversal-builder.ts","../src/query/builder/query-builder.ts","../src/query/builder/unionable-query.ts","../src/query/builder/aggregates.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/backend/branded.ts","../src/graph-extension/classify.ts","../src/graph-extension/remove.ts","../src/store/algorithms/context.ts","../src/store/algorithms/degree.ts","../src/store/algorithms/reachable.ts","../src/store/algorithms/shortest-path.ts","../src/store/algorithms/index.ts","../src/store/collections/edge-collection.ts","../src/store/collections/node-collection.ts","../src/store/collection-factory.ts","../src/store/introspect.ts","../src/store/materialize-shared.ts","../src/store/materialize-indexes.ts","../src/store/materialize-removals.ts","../src/store/operations/edge-operations.ts","../src/store/recorded-read-service.ts","../src/store/transaction-receipt.ts","../src/store/types.ts","../src/store/store.ts"],"names":["ConfigurationError","resolveReadCoordinate","nowIso","describeCoordinate","coordinateContext","target","withRecordedCoordinate","CompilerInvariantError","sql","MAX_PG_IDENTIFIER_LENGTH","fnv1aBase36","field","jsonPointer","quoteIdentifier","ALIAS_CTE_PREFIX","NODE_COLUMNS","shouldProjectColumn","EDGE_COLUMNS","compileKindFilter","compilePredicateClauses","getPredicatesForAlias","EMPTY_REQUIRED_COLUMNS","getNodeKindsForAlias","compileFieldValue","UnsupportedPredicateError","isAggregateExpr","mapSelectiveSystemFieldToColumn","findSelectivePropsFieldForFieldRef","getHybridTargetAlias","EMBEDDINGS_CTE_ALIAS","FULLTEXT_CTE_ALIAS","HYBRID_CANDIDATES_CTE_ALIAS","compilePredicateExpression","vectorSlotKey","vectorScoreExpression","vectorMinScoreCondition","extractFulltextMatchPredicates","currentReadInstantFor","compileTemporalFilter","extractTemporalOptions","extractVectorSimilarityPredicates","hasVariableLengthTraversal","getDialect","compileRecursiveBranch","addRequiredColumn","markSelectiveFieldAsRequired","markFieldRefAsRequired","currentReadInstant","recordedReadSchemaFor","DEFAULT_SQL_SCHEMA","createSchemaIntrospector","validateProjectionField","asCompiledRowsSql","markForceCustomPlan","rowToNode","rowToNodeMeta","rowToEdge","rowToEdgeMeta","compileQuery","collectRequiredColumnsByAlias","isIdFieldRef","buildPredicateIndex","requireSqlSchema","markAnnIndexScan","asCompiledSelectSql","compileSetOperation","annIndexScanTypes","withPinnedReadInstant","having","SQLITE_PATH_DELIMITER","PG_ARRAY_START","PG_ARRAY_END","PG_PATH_ELEMENT_SEPARATOR","nullToUndefined","ValidationError","resolveJsonPointer","DEFAULT_STREAM_BATCH_SIZE","NODE_META_KEYS","EDGE_META_KEYS","compareStrings","value","Placeholder","CURRENT_READ_INSTANT_PLACEHOLDER","isRawExecutable","isParameterRef","rawRows","resolveDeclaredFulltextLanguage","resolveEmbeddingFields","fieldRef","withRecordedRelationsPrecondition","parseJsonPointer","outputName","aliasObject","DEFAULT_PAGINATION_LIMIT","NOT_COMPUTED","buildFieldBuilderForTypeInfo","max","min","stringField","numberField","baseField","dateField","arrayField","objectField","KindNotFoundError","EndpointError","coordinate","createFulltextAccessor","getSearchableFields","runOptionallyInTransaction","rowPropsToObject","computeFulltextContent","getEmbeddingFields","entry","compareCodePoints","rank","assertVectorMinScore","IncompatibleChangeError","canonicalEqual","extensionKindNames","RemoveCompileTimeKindError","KindHasReferentsError","buildGraphExtensionOntologyKeySet","compileTimeOntologyKey","getTypeName","assertValidRecordedInstant","createSqlSchema","executeEdgeCreate","executeEdgeCreateNoReturnBatch","executeEdgeCreateBatch","executeEdgeUpdate","executeEdgeUpsertUpdate","executeEdgeDelete","executeEdgeHardDelete","getEdgeRowsByIds","results","executeNodeCreate","executeNodeCreateNoReturnBatch","executeNodeCreateBatch","executeNodeUpdate","executeNodeUpsertUpdate","executeNodeDelete","executeNodeHardDelete","getNodeRowsByIds","result","serializeSchemaProperties","isKnownKind","generateIndexDDL","sqlValueList","rows","serializeIndexDeclaration","sortedReplacer","sha256Hex","materializeOne","parseSerializedSchema","closeRecordedHardDeletedKind","isMissingTableError","asCompiledStatementSql","createBackendOverlay","validateEdgeEndpoints","EndpointNotFoundError","validateEdgeProps","validateOptionalCanonicalIsoDate","checkCardinalityConstraint","generateId","runHookedWriteOperation","DatabaseOperationError","runInWriteTransaction","runInsertBatch","edgeInsertDispatch","runInsertBatchReturning","EdgeNotFoundError","edge","CardinalityError","recordedBindParamBudget","recordedReadSqlSchema","chunk","requireRecordedReadBinding","count","POSTGRES_ROW_MAPPER_CONFIG","SQLITE_ROW_MAPPER_CONFIG","asRecordedInstant","assertRevisionTrackableBackend","requireExternalRecordedReadSource","createRecordedReadBinding","createRecordedBackend","createNodeRowMapper","createEdgeRowMapper","buildKindRegistry","executeNodeGetOrCreateByConstraint","executeNodeBulkGetOrCreateByConstraint","executeNodeFindByConstraint","executeNodeBulkFindByConstraint","executeNodeBulkFindByIndex","readRecordedClock","ensureRevisionOrigin","withRecordedFlushObserver","recordedCaptureRequiresCallbackTransactionError","assertRecordedCaptureTransactionIsolation","createRecordedTransactionScope","lockRecordedGraphWrite","createHistoryUnsafeSqlRef","createRevisionTrackingUnsafeSqlRef","advanceRevisionClock","mergeGraphExtension","commitNewSchemaVersion","EagerMaterializationError","applyDeprecatedKinds","ensureSchema","loadActiveSchemaWithBootstrap","loadAndMergeGraphExtensionDocument","loadAndVerifyGraph"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkCO,IAAM,uBAAA,GAA0B;AAAA,EACrC,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA;AACF,CAAA;AAGO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,QAAA;AAAA,EACA,kBAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,sBAAA;AAAA,EACA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA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AAA;AAAA,IACA,OAAA;AAAA,IACA,uBAAA,CAAwB,WAAW,MAAM;AAAA,GAC3C;AACA,EAAA,OAAO,CAAC,OAAO,MAAM,CAAA;AACvB;AA0DA,eAAsB,mBAAA,CACpB,KAAA,EACA,OAAA,EACA,OAAA,EAGA;AACA,EAAA,MAAM;AAAA,IACJ,KAAA,EAAO,MAAA;AAAA,IACP,SAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAMG,oCAAA,CAAmB,OAAA,EAAS,KAAK,CAAA;AAC3C,EAAA,MAAM,QAAQ,IAAI,KAAA;AAAA,IAChB,MAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,sBAAsB,SAAS;AAAA,GACjC;AACA,EAAA,OAAO,CAAC,OAAO,MAAM,CAAA;AACvB","file":"chunk-J7WFGBJR.cjs","sourcesContent":["import { type AnyEdgeType, type NodeType } from \"../core/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 \"delete\",\n \"hardDelete\",\n \"upsertById\",\n \"upsertByIdFromRecord\",\n \"bulkCreate\",\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 \"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/** 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 {\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 InitialQueryBuilder } from \"../query/builder\";\nimport {\n type BaseTraversalOptions,\n type DegreeOptions,\n type InternalGraphAlgorithms,\n type NeighborsOptions,\n type NodeIdentifier,\n type ReachableNode,\n type ReachableOptions,\n type ShortestPathOptions,\n type ShortestPathResult,\n type TemporalAlgorithmOptions,\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 { type StoreSearch } from \"./search-facade\";\nimport { type Store } from \"./store\";\nimport {\n type InternalSubgraphOptions,\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\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/** `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\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 resolve through `store.batch(...)` — a DataLoader context\n * a view 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 loader, 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 point getById/getByIds collection 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 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 (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) => store.recordedNodeGetById(kind, id, coordinate),\n getByIds: (ids) => store.recordedNodeGetByIds(kind, ids, coordinate),\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) => store.recordedEdgeGetById(kind, id, coordinate),\n getByIds: (ids) => store.recordedEdgeGetByIds(kind, ids, coordinate),\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 #algorithms: InternalGraphAlgorithms<G> | undefined;\n\n constructor(store: Store<G>, coordinate: ReadCoordinate) {\n this.store = store;\n this.coordinate = coordinate;\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 this.store.sealedQuery(this.coordinate);\n }\n\n protected algorithms(): InternalGraphAlgorithms<G> {\n this.#algorithms ??= this.store.algorithmsAtCoordinate(this.coordinate);\n return this.#algorithms;\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 this.store.subgraphAtCoordinate(rootId, internalOptions);\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.algorithms().shortestPath(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.algorithms().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.algorithms().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.algorithms().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.algorithms().degree(node, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n}\n\n// ============================================================\n// StoreView\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 * @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 class StoreView<G extends GraphDef> 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 /** 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 /**\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 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 are intentionally limited to point reconstruction; 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 */\nexport class RecordedStoreView<\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\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 timestamp this view reconstructs. */\n get asOfRecorded(): string {\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 point-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 point-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","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 \"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 \"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 \"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 \"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 { type SQL, sql } from \"drizzle-orm\";\n\nimport { CompilerInvariantError } from \"../../../errors\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectRecursiveProjectPlan } from \"./plan-inspector\";\n\nexport type RecursiveQueryEmitterInput = Readonly<{\n depthFilter: SQL;\n limitOffset?: SQL;\n logicalPlan: LogicalPlan;\n orderBy?: SQL;\n projection: SQL;\n recursiveCte: SQL;\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(input: RecursiveQueryEmitterInput): SQL {\n assertRecursiveEmitterClauseAlignment(input.logicalPlan, input);\n\n const parts: SQL[] = [\n sql`WITH RECURSIVE`,\n input.recursiveCte,\n sql`SELECT ${input.projection}`,\n sql`FROM recursive_cte`,\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 { type SQL, sql } from \"drizzle-orm\";\n\nimport { CompilerInvariantError } from \"../../../errors\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectSetOperationPlan } from \"./plan-inspector\";\n\nexport type SetOperationQueryEmitterInput = Readonly<{\n baseQuery: SQL;\n ctes?: readonly SQL[];\n logicalPlan: LogicalPlan;\n suffixClauses?: readonly SQL[];\n}>;\n\nfunction assertSetOperationEmitterClauseAlignment(\n logicalPlan: LogicalPlan,\n suffixClauses: readonly SQL[] | 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): SQL {\n assertSetOperationEmitterClauseAlignment(\n input.logicalPlan,\n input.suffixClauses,\n );\n\n const parts: SQL[] = [];\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 { type SQL, sql } from \"drizzle-orm\";\n\nimport { CompilerInvariantError } from \"../../../errors\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectStandardProjectPlan } from \"./plan-inspector\";\n\nexport type StandardQueryEmitterInput = Readonly<{\n ctes: readonly SQL[];\n fromClause: SQL;\n groupBy?: SQL;\n having?: SQL;\n limitOffset?: SQL;\n logicalPlan: LogicalPlan;\n orderBy?: SQL;\n projection: SQL;\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(input: StandardQueryEmitterInput): SQL {\n assertStandardEmitterClauseAlignment(input.logicalPlan, input);\n\n const parts: SQL[] = [];\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.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\";\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 (end > 0 && encoded[end]! >= 0x80 && encoded[end]! < 0xc0) {\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 JsonPointer } from \"./json-pointer\";\n\n// ============================================================\n// Predicate Expressions\n// ============================================================\n\n/**\n * A field reference in a predicate.\n */\nexport type FieldRef = Readonly<{\n __type: \"field_ref\";\n alias: string;\n path: readonly string[]; // [\"props\", \"name\"] or [\"id\"]\n jsonPointer?: JsonPointer | undefined; // JSON Pointer into props\n valueType?: ValueType | undefined;\n elementType?: ValueType | 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: LiteralValue | LiteralValue[] | ParameterRef;\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/**\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 | 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\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 /** Optional column alias for projected traversal depth */\n depthAlias?: string;\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 /** 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 = Readonly<{\n __type: \"aggregate\";\n function: AggregateFunction;\n field: FieldRef;\n}>;\n\n/**\n * A GROUP BY specification.\n */\nexport type GroupBySpec = Readonly<{\n fields: readonly 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: FieldRef | AggregateExpr;\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: 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 /** 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 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 { type SQL } from \"drizzle-orm\";\n\nimport { type SelectiveField } from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type JsonPointer, jsonPointer } from \"../json-pointer\";\n\ntype JsonExtractFallback = \"json\" | \"text\";\n\ntype TypedJsonExtractInput = Readonly<{\n column: SQL;\n dialect: DialectAdapter;\n fallback?: JsonExtractFallback;\n pointer: JsonPointer;\n valueType: string | undefined;\n}>;\n\nexport function compileTypedJsonExtract(input: TypedJsonExtractInput): SQL {\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: SQL,\n dialect: DialectAdapter,\n): SQL {\n return compileTypedJsonExtract({\n column,\n dialect,\n pointer: jsonPointer([field.field]),\n valueType: field.valueType,\n });\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { UnsupportedPredicateError } from \"../../../errors\";\nimport { boundPgIdentifier } from \"../../../utils/identifier\";\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 vectorMinScoreCondition,\n vectorScoreExpression,\n} from \"../../dialect/vector-strategy\";\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): SQL {\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): SQL {\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): SQL {\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): SQL[] {\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 SQL[],\n input: CompileSelectivePropsSelectColumnsInput,\n): SQL[] {\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(input: CompileNodeSelectColumnsInput): SQL[] {\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(input: CompileEdgeSelectColumnsInput): SQL[] {\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(input: BuildStandardStartCteInput): SQL {\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): SQL {\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 = 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 function compileTraversalBranch(\n branch: Readonly<{\n duplicateGuard?: SQL | 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 ): SQL {\n const whereClauses = [\n ...baseWhereClauses,\n compileKindFilter(sql.raw(\"e.kind\"), branch.edgeKinds),\n compileKindFilter(\n sql.raw(`e.${branch.joinKindField}`),\n previousNodeKinds,\n ),\n compileKindFilter(sql.raw(`e.${branch.targetKindField}`), nodeKinds),\n ];\n\n if (branch.duplicateGuard !== undefined) {\n whereClauses.push(branch.duplicateGuard);\n }\n\n return sql`\n SELECT ${sql.join(selectColumns, sql`, `)}\n FROM cte_${sql.raw(previousAlias)}\n JOIN ${ctx.schema.edgesTable} e ON cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id = e.${sql.raw(branch.joinField)}\n AND cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind = e.${sql.raw(branch.joinKindField)}\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 overlappingKinds = inverseEdgeKinds.filter((kind) =>\n directEdgeKinds.includes(kind),\n );\n\n const duplicateGuard =\n overlappingKinds.length > 0 ?\n sql`NOT (e.from_id = e.to_id AND ${compileKindFilter(\n sql.raw(\"e.kind\"),\n overlappingKinds,\n )})`\n : undefined;\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): SQL {\n const { field } = expr;\n const fn = expr.function;\n\n switch (fn) {\n case \"count\":\n case \"countDistinct\":\n case \"sum\":\n case \"avg\":\n case \"min\":\n case \"max\": {\n const cteAlias = `cte_${field.alias}`;\n const column = compileFieldValue(\n field,\n dialect,\n field.valueType,\n cteAlias,\n );\n if (fn === \"countDistinct\") {\n return sql`COUNT(DISTINCT ${column})`;\n }\n return sql`${sql.raw(fn.toUpperCase())}(${column})`;\n }\n default: {\n throw new UnsupportedPredicateError(\n `Unknown aggregate function: ${String(fn)}`,\n );\n }\n }\n}\n\nfunction compileProjectedSource(\n field: {\n cteAlias?: string;\n source: FieldRef | AggregateExpr;\n },\n dialect: DialectAdapter,\n): SQL {\n if (isAggregateExpr(field.source)) {\n return compileAggregateExprFromSource(field.source, dialect);\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 dialect: DialectAdapter;\n}>;\n\nexport function buildStandardProjection(\n input: BuildStandardProjectionInput,\n): SQL {\n const { ast, collapsedTraversalCteAlias, dialect } = 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, dialect);\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): SQL {\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: FieldRef,\n dialect: DialectAdapter,\n cteAlias: string,\n): SQL {\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 buildRelevanceJoins(\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): SQL[] {\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: SQL[] = [];\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): SQL {\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): SQL {\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): SQL {\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: SQL[] = [];\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): SQL | 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: SQL[] = [];\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 aliasToCte?.get(orderSpec.field.alias) ??\n `cte_${orderSpec.field.alias}`;\n const field = compileOrderFieldValue(\n ast,\n orderSpec.field,\n dialect,\n cteAlias,\n );\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n parts.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\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 // Nulls ordering can't reuse the `(field IS NULL) direction, field\n // direction` trick above: unlike a source-table field reference, an\n // output alias is only resolved by either dialect when the ORDER BY term\n // is the bare identifier itself — wrapping it in `(alias IS NULL)`\n // makes both SQLite and PostgreSQL look for a real column named\n // `alias` and fail. The standard `NULLS FIRST`/`NULLS LAST` suffix\n // (supported by both dialects) sidesteps that: it attaches to the bare\n // identifier rather than embedding it in a larger expression.\n for (const orderSpec of aggregateOrderBy) {\n const column = quoteIdentifier(orderSpec.outputName);\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsKeyword = sql.raw(\n nulls === \"first\" ? \"NULLS FIRST\" : \"NULLS LAST\",\n );\n parts.push(sql`${column} ${direction} ${nullsKeyword}`);\n }\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): SQL | 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: 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 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 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\ntype BuildStandardHavingInput = Readonly<{\n ast: QueryAst;\n ctx: PredicateCompilerContext;\n}>;\n\nexport function buildStandardHaving(\n input: BuildStandardHavingInput,\n): SQL | undefined {\n const { ast, ctx } = input;\n if (!ast.having) {\n return undefined;\n }\n\n const condition = compilePredicateExpression(ast.having, ctx);\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.\n */\nexport function buildStandardEmbeddingsCte(\n input: BuildStandardEmbeddingsCteInput,\n): SQL {\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. A mismatched override falls back to the\n // exact scan below — correct for any metric, like `indexType: \"none\"`.\n // Engines whose `buildSearch` is EXACT (vec0's brute-force C KNN)\n // serve the non-approximate branch through it as well: identical\n // results to the SQL distance scan at engine speed (489ms -> 113ms\n // at 50k on the SQLite lane). The metric gate stays: the engine\n // form is built for the slot's declared metric.\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: SQL[] = [\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(): SQL {\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): SQL {\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: SQL[] = [\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(): SQL {\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 SQL fragments 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 SQL[] {\n if (!ast.orderBy || ast.orderBy.length === 0) return [];\n\n const aliasToCte = buildAliasToCteMap(ast);\n const fragments: SQL[] = [];\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 aliasToCte.get(orderSpec.field.alias) ??\n `${ALIAS_CTE_PREFIX}${orderSpec.field.alias}`;\n const field = compileOrderFieldValue(\n ast,\n orderSpec.field,\n dialect,\n cteAlias,\n );\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n fragments.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\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): SQL {\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): SQL {\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 const rrfOrder = sql.raw(\n `(COALESCE(${vectorWeight} / (${k} + ${EMBEDDINGS_CTE_ALIAS}.ord), 0) + ` +\n `COALESCE(${fulltextWeight} / (${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): SQL {\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 limit: number | undefined;\n offset: number | undefined;\n}>;\n\nexport function buildLimitOffsetClause(\n input: BuildLimitOffsetClauseInput,\n): SQL | undefined {\n const { limit, offset } = input;\n const parts: SQL[] = [];\n\n if (limit !== undefined) {\n parts.push(sql`LIMIT ${limit}`);\n }\n if (offset !== undefined) {\n parts.push(sql`OFFSET ${offset}`);\n }\n\n return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\n}\n","import { UnsupportedPredicateError } 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 UnsupportedPredicateError(\n `Fulltext match predicates are not supported for dialect \"${dialect.name}\"`,\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\n/**\n * Resolves query LIMIT in the presence of a fulltext predicate.\n *\n * Mirrors resolveVectorAwareLimit. When a fulltext predicate is present\n * without an explicit AST limit, the predicate's own limit bounds the\n * result set; when both are present the tighter wins.\n */\nexport function resolveFulltextAwareLimit(\n astLimit?: number,\n fulltextPredicate?: FulltextMatchPredicate,\n): number | undefined {\n if (fulltextPredicate === undefined) {\n return astLimit;\n }\n if (astLimit === undefined) {\n return fulltextPredicate.limit;\n }\n return Math.min(astLimit, fulltextPredicate.limit);\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 SQL } from \"drizzle-orm\";\n\nimport type { QueryAst } from \"../../ast\";\nimport {\n compileTemporalFilter,\n currentReadInstantFor,\n extractTemporalOptions,\n type ReadInstantMode,\n} from \"../temporal\";\n\nexport type TemporalFilterPass = Readonly<{\n forAlias: (tableAlias?: string) => SQL;\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): TemporalFilterPass {\n const currentTimestamp = currentReadInstantFor(readInstant);\n return {\n forAlias(tableAlias?: string): SQL {\n return compileTemporalFilter({\n ...extractTemporalOptions(ast, tableAlias),\n currentTimestamp,\n });\n },\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\n/**\n * Resolves the query LIMIT in the presence of vector similarity.\n *\n * If a vector predicate is present and AST limit is omitted, use the\n * predicate's built-in limit to bound nearest-neighbor search.\n */\nexport function resolveVectorAwareLimit(\n astLimit?: number,\n vectorPredicate?: VectorSimilarityPredicate,\n): number | undefined {\n if (vectorPredicate === undefined) {\n return astLimit;\n }\n if (astLimit === undefined) {\n return vectorPredicate.limit;\n }\n return Math.min(astLimit, vectorPredicate.limit);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\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 resolveFulltextAwareLimit,\n resolveVectorAwareLimit,\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} 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 = currentNode;\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 limitAfterVector = resolveVectorAwareLimit(\n query.limit,\n vectorPredicate,\n );\n const effectiveLimit = resolveFulltextAwareLimit(\n limitAfterVector,\n fulltextPredicate,\n );\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: 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","/**\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 { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n CompilerInvariantError,\n UnsupportedPredicateError,\n} from \"../../errors\";\nimport { type QueryAst, type SelectiveField } from \"../ast\";\nimport {\n type DialectAdapter,\n type DialectRecursiveQueryStrategy,\n} from \"../dialect\";\nimport { emitRecursiveQuerySql } from \"./emitter\";\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 compileFieldValue,\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"./predicates\";\nimport { assertRecordedQueryAstDoesNotUseCurrentIndexes } from \"./recorded-current-index-guard\";\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 call .maxHops(N)\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\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 );\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 SQL for the recursive query\n */\nexport function compileVariableLengthQuery(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SQL {\n const strategy = ctx.dialect.capabilities.recursiveQueryStrategy;\n const handler = RECURSIVE_QUERY_STRATEGY_HANDLERS[strategy];\n return handler(ast, graphId, ctx);\n}\n\ntype RecursiveQueryStrategyHandler = (\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n) => SQL;\n\nconst RECURSIVE_QUERY_STRATEGY_HANDLERS: Record<\n DialectRecursiveQueryStrategy,\n RecursiveQueryStrategyHandler\n> = {\n recursive_cte: compileVariableLengthQueryWithRecursiveCteStrategy,\n};\n\nfunction compileVariableLengthQueryWithRecursiveCteStrategy(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SQL {\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 );\n\n // Build projection\n const projection = compileRecursiveProjection(ast, vlTraversal, dialect);\n\n // Build final SELECT\n const minDepth = vlTraversal.variableLength.minDepth;\n const depthFilter =\n minDepth > 0 ? sql`WHERE depth >= ${minDepth}` : sql.raw(\"\");\n\n // Order by and limit/offset\n const orderBy = compileRecursiveOrderBy(ast, dialect);\n const limitOffset = compileLimitOffset(ast);\n\n return emitRecursiveQuerySql({\n depthFilter,\n ...(limitOffset === undefined ? {} : { limitOffset }),\n logicalPlan,\n ...(orderBy === undefined ? {} : { orderBy }),\n projection,\n recursiveCte,\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): SQL {\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 = shouldEnforceCycleCheck || vl.pathAlias !== undefined;\n const recursiveJoinRequiredColumns = new Set<string>([\"id\"]);\n if (previousNodeKinds.length > 1) {\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\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 const cycleCheck =\n shouldEnforceCycleCheck ?\n dialect.cycleCheck(sql.raw(\"n.id\"), sql.raw(\"r.path\"))\n : undefined;\n const initialPath =\n shouldTrackPath ? dialect.initializePath(sql.raw(\"n0.id\")) : undefined;\n const pathExtension =\n shouldTrackPath ?\n dialect.extendPath(sql.raw(\"r.path\"), sql.raw(\"n.id\"))\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 const recursiveBaseWhereClauses: SQL[] = [\n sql`e.graph_id = ${graphId}`,\n nodeKindFilter,\n edgeTemporalFilter,\n nodeTemporalFilter,\n maxDepthCondition,\n ];\n if (cycleCheck !== undefined) {\n recursiveBaseWhereClauses.push(cycleCheck);\n }\n recursiveBaseWhereClauses.push(...edgePredicates, ...targetNodePredicates);\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?: SQL | undefined;\n }>,\n ): SQL {\n const recursiveFilterClauses = [\n ...recursiveBaseWhereClauses,\n compileKindFilter(branch.edgeKinds, \"e.kind\"),\n compileKindFilter(previousNodeKinds, `e.${branch.joinKindField}`),\n compileKindFilter(nodeKinds, `e.${branch.targetKindField}`),\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 (pathExtension !== undefined) {\n recursiveSelectColumns.push(sql`${pathExtension} AS path`);\n }\n const recursiveJoinClauses: SQL[] = [\n sql`e.${sql.raw(branch.joinField)} = r.${sql.raw(nodeAlias)}_id`,\n ];\n if (previousNodeKinds.length > 1) {\n recursiveJoinClauses.push(\n sql`e.${sql.raw(branch.joinKindField)} = r.${sql.raw(nodeAlias)}_kind`,\n );\n }\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 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 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(): SQL {\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 overlappingKinds = inverseEdgeKinds.filter((kind) =>\n directEdgeKinds.includes(kind),\n );\n\n const duplicateGuard =\n overlappingKinds.length > 0 ?\n sql`NOT (e.from_id = e.to_id AND ${compileKindFilter(overlappingKinds, \"e.kind\")})`\n : undefined;\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 (initialPath !== undefined) {\n baseSelectColumns.push(sql`${initialPath} AS path`);\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(kinds: readonly string[], columnExpr: string): SQL {\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): SQL[] {\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): SQL[] {\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 if (ast.orderBy) {\n for (const orderSpec of ast.orderBy) {\n markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n }\n }\n\n return requiredColumnsByAlias;\n}\n\nfunction compileNodeSelectColumnsFromTable(\n tableAlias: string,\n alias: string,\n requiredColumns: ReadonlySet<string> | undefined,\n alwaysRequiredColumns: ReadonlySet<string>,\n): SQL[] {\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): SQL[] {\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 dialect: DialectAdapter,\n): SQL {\n if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n return compileRecursiveSelectiveProjection(\n ast.selectiveFields,\n ast,\n traversal,\n dialect,\n );\n }\n\n const startAlias = ast.start.alias;\n const nodeAlias = traversal.nodeAlias;\n const vl = traversal.variableLength;\n\n const fields: SQL[] = [\n // Start alias fields with metadata\n sql`${sql.raw(startAlias)}_id`,\n sql`${sql.raw(startAlias)}_kind`,\n sql`${sql.raw(startAlias)}_props`,\n sql`${sql.raw(startAlias)}_version`,\n sql`${sql.raw(startAlias)}_valid_from`,\n sql`${sql.raw(startAlias)}_valid_to`,\n sql`${sql.raw(startAlias)}_created_at`,\n sql`${sql.raw(startAlias)}_updated_at`,\n sql`${sql.raw(startAlias)}_deleted_at`,\n // Node alias fields with metadata\n sql`${sql.raw(nodeAlias)}_id`,\n sql`${sql.raw(nodeAlias)}_kind`,\n sql`${sql.raw(nodeAlias)}_props`,\n sql`${sql.raw(nodeAlias)}_version`,\n sql`${sql.raw(nodeAlias)}_valid_from`,\n sql`${sql.raw(nodeAlias)}_valid_to`,\n sql`${sql.raw(nodeAlias)}_created_at`,\n sql`${sql.raw(nodeAlias)}_updated_at`,\n sql`${sql.raw(nodeAlias)}_deleted_at`,\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(sql`path AS ${quoteIdentifier(vl.pathAlias)}`);\n }\n\n return sql.join(fields, sql`, `);\n}\n\nfunction compileRecursiveSelectiveProjection(\n fields: readonly SelectiveField[],\n ast: QueryAst,\n traversal: VariableLengthTraversal,\n dialect: DialectAdapter,\n): SQL {\n const allowedAliases = new Set([ast.start.alias, traversal.nodeAlias]);\n\n const columns: SQL[] = fields.map((field) => {\n if (!allowedAliases.has(field.alias)) {\n throw new UnsupportedPredicateError(\n `Selective projection for recursive traversals does not support alias \"${field.alias}\"`,\n );\n }\n\n if (field.isSystemField) {\n const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n return sql`${sql.raw(`${field.alias}_${dbColumn}`)} AS ${quoteIdentifier(field.outputName)}`;\n }\n\n const column = sql.raw(`${field.alias}_props`);\n const extracted = compileSelectivePropsExtraction(field, column, dialect);\n return sql`${extracted} AS ${quoteIdentifier(field.outputName)}`;\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(sql`path AS ${quoteIdentifier(vl.pathAlias)}`);\n }\n\n return sql.join(columns, sql`, `);\n}\n\n/**\n * Compiles ORDER BY for recursive query.\n */\nfunction compileRecursiveOrderBy(\n ast: QueryAst,\n dialect: DialectAdapter,\n): SQL | undefined {\n if (!ast.orderBy || ast.orderBy.length === 0) {\n return undefined;\n }\n\n const parts: SQL[] = [];\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 = compileFieldValue(orderSpec.field, dialect, valueType);\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n\n parts.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\n }\n\n return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\n/**\n * Compiles LIMIT and OFFSET clauses.\n */\nfunction compileLimitOffset(ast: QueryAst): SQL | undefined {\n const parts: SQL[] = [];\n\n if (ast.limit !== undefined) {\n parts.push(sql`LIMIT ${ast.limit}`);\n }\n if (ast.offset !== undefined) {\n parts.push(sql`OFFSET ${ast.offset}`);\n }\n\n return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\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 { type SQL, sql } from \"drizzle-orm\";\n\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 { type TraversalDirection } from \"./algorithms/types\";\n\ntype BuildReachableCteOptions = Readonly<{\n graphId: string;\n sourceId: 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 /** 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}>;\n\nexport function buildReachableCte(options: BuildReachableCteOptions): SQL {\n const trackPath = options.cyclePolicy === \"prevent\" || options.includePath;\n const edgeKindFilter = compileKindFilter(\n sql.raw(\"e.kind\"),\n options.edgeKinds,\n );\n const currentTimestamp = currentReadInstant();\n const nodeTemporalFilter = compileTemporalFilter({\n mode: options.temporalMode,\n asOf: options.asOf,\n recordedAsOf: options.recordedAsOf,\n tableAlias: \"n\",\n currentTimestamp,\n });\n const edgeTemporalFilter = compileTemporalFilter({\n mode: options.temporalMode,\n asOf: options.asOf,\n recordedAsOf: options.recordedAsOf,\n tableAlias: \"e\",\n currentTimestamp,\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\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: SQL[] = [sql`n.id`, sql`n.kind`, sql`0 AS depth`];\n if (initialPath !== undefined) {\n baseColumns.push(sql`${initialPath} AS path`);\n }\n\n const baseCase = sql`SELECT ${sql.join(baseColumns, sql`, `)} FROM ${schema.nodesTable} n WHERE n.graph_id = ${options.graphId} AND n.id = ${options.sourceId} AND ${nodeTemporalFilter}`;\n\n const recursiveColumns: SQL[] = [\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 const recursiveWhere: SQL[] = [\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 recursiveCase = compileRecursiveBranch({\n recursiveColumns,\n whereClauses: recursiveWhere,\n direction: options.direction,\n forceWorktableOuterJoinOrder,\n schema,\n });\n\n return sql`WITH RECURSIVE reachable AS (${baseCase} UNION ALL ${recursiveCase})`;\n}\n\ntype CompileRecursiveBranchOptions = Readonly<{\n recursiveColumns: readonly SQL[];\n whereClauses: readonly SQL[];\n direction: TraversalDirection;\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction compileRecursiveBranch(options: CompileRecursiveBranchOptions): SQL {\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: \"from_id\",\n targetField: \"to_id\",\n targetKindField: \"to_kind\",\n forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n schema: options.schema,\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 });\n }\n case \"both\": {\n return buildBidirectionalBranch({\n selectClause,\n whereClauses: options.whereClauses,\n forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n schema: options.schema,\n });\n }\n }\n}\n\ntype DirectionalBranchOptions = Readonly<{\n selectClause: SQL;\n whereClauses: readonly SQL[];\n joinField: \"from_id\" | \"to_id\";\n targetField: \"from_id\" | \"to_id\";\n targetKindField: \"from_kind\" | \"to_kind\";\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction buildDirectionalBranch(options: DirectionalBranchOptions): SQL {\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.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n }\n\n return sql`${options.selectClause} FROM reachable r JOIN ${options.schema.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: SQL;\n whereClauses: readonly SQL[];\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction buildBidirectionalBranch(options: BidirectionalBranchOptions): SQL {\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.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n }\n\n return sql`${options.selectClause} FROM reachable r JOIN ${options.schema.edgesTable} e ON (e.from_id = r.id OR e.to_id = r.id) ${nodeJoin} WHERE ${sql.join([...options.whereClauses], sql` AND `)}`;\n}\n","/**\n * Subgraph Extraction\n *\n * Extracts a typed subgraph from a root node by traversing a set of edge kinds.\n * Uses a recursive CTE for BFS traversal with cycle detection, then hydrates\n * the reachable nodes and connecting edges in two parallel queries.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\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 type { RecursiveCyclePolicy } from \"../query/ast\";\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 { asCompiledRowsSql, markForceCustomPlan } from \"../query/sql-intent\";\nimport { fnv1aBase36 } from \"../utils/hash\";\nimport { truncateToBytes } from \"../utils/identifier\";\nimport { buildReachableCte } 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\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 asOf: string | undefined;\n recordedAsOf: RecordedInstant | undefined;\n dialect: DialectAdapter;\n schema: SqlSchema;\n recordedReadBinding: RecordedReadBinding | undefined;\n backend: GraphBackend;\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\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>(params: {\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}): Promise<SubgraphResult<G, NK, EK, P>> {\n const { options } = params;\n const { valid: coordinate } = resolveReadCoordinate(\n options.temporalMode ?? params.graph.defaults.temporalMode,\n options.asOf,\n );\n const temporalMode = coordinate.mode;\n // `recordedAsOf` reaches here only via the internal `subgraphAtCoordinate`\n // seam; the public `store.subgraph` rejects it (typed `never`, runtime-guarded\n // for JS callers) before this executor is reached.\n const recordedAsOf = options.recordedAsOf;\n const baseSchema = params.schema ?? DEFAULT_SQL_SCHEMA;\n\n const maxDepth = Math.min(\n options.maxDepth ?? DEFAULT_SUBGRAPH_MAX_DEPTH,\n MAX_EXPLICIT_RECURSIVE_DEPTH,\n );\n\n const ctx: SubgraphContext = {\n graphId: params.graphId,\n rootId: params.rootId,\n edgeKinds: options.edges,\n maxDepth,\n includeKinds: options.includeKinds,\n excludeRoot: options.excludeRoot ?? false,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n temporalMode,\n asOf: coordinate.asOf,\n recordedAsOf,\n dialect: params.dialect,\n schema: recordedReadSchemaFor(\n baseSchema,\n recordedAsOf,\n params.recordedReadBinding,\n \"recorded-subgraph\",\n ),\n recordedReadBinding: params.recordedReadBinding,\n backend: params.backend,\n };\n\n const schemaIntrospector = getSubgraphSchemaIntrospector(params.graph);\n const nodeProjectionPlan = buildProjectionPlan(\n getIncludedNodeKinds(params.graph, options.includeKinds),\n options.project?.nodes,\n (kind, field) => schemaIntrospector.getFieldTypeInfo(kind, field),\n \"node\",\n );\n const edgeProjectionPlan = buildProjectionPlan(\n dedupeStrings(options.edges),\n options.project?.edges,\n (kind, field) => schemaIntrospector.getEdgeFieldTypeInfo(kind, field),\n \"edge\",\n );\n\n const reachableCte = buildReachableCte({\n graphId: ctx.graphId,\n sourceId: ctx.rootId,\n edgeKinds: ctx.edgeKinds,\n maxHops: ctx.maxDepth,\n direction: ctx.direction,\n cyclePolicy: ctx.cyclePolicy,\n includePath: false,\n temporalMode: ctx.temporalMode,\n ...(ctx.asOf !== undefined && { asOf: ctx.asOf }),\n ...(ctx.recordedAsOf !== undefined && { recordedAsOf: ctx.recordedAsOf }),\n dialect: ctx.dialect,\n // Base schema: buildReachableCte derives the recorded swap from recordedAsOf.\n schema: baseSchema,\n ...(ctx.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: ctx.recordedReadBinding }),\n });\n const includedIdsCte = buildIncludedIdsCte(ctx);\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 if (ctx.dialect.name === \"postgres\") {\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 } else {\n membership = {\n prefix: sql`${reachableCte}${includedIdsCte} `,\n // SQLite: `column IN (subquery)` evaluates via a transient index —\n // optimal as-is. (Postgres takes the parameterized text[] form above.)\n idFilter: (column) => sql`${column} IN (SELECT id FROM included_ids)`,\n parameterDependentPlan: false,\n };\n }\n\n const [nodeRows, edgeRows] = await Promise.all([\n fetchSubgraphNodes(ctx, membership, nodeProjectionPlan),\n fetchSubgraphEdges(ctx, membership, edgeProjectionPlan),\n ]);\n\n const nodesMap = new Map<string, Node>();\n for (const row of nodeRows) {\n const node = mapSubgraphNodeRow(row, nodeProjectionPlan);\n nodesMap.set(node.id, node);\n }\n\n const adjacency = new Map<string, Map<string, Edge[]>>();\n const reverseAdjacency = new Map<string, Map<string, Edge[]>>();\n for (const row of edgeRows) {\n const edge = mapSubgraphEdgeRow(row, edgeProjectionPlan);\n insertAdjacencyEntry(adjacency, edge.fromId, edge.kind, edge);\n insertAdjacencyEntry(reverseAdjacency, edge.toId, edge.kind, edge);\n }\n\n const root = nodesMap.get(ctx.rootId);\n\n return {\n root,\n nodes: nodesMap,\n adjacency,\n reverseAdjacency,\n } as unknown as SubgraphResult<G, NK, EK, P>;\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 const selection = projectionMap?.[kind];\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): SQL {\n const filters: SQL[] = [];\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\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: SQL;\n idFilter: (column: SQL) => SQL;\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[]): SQL {\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: SQL,\n includedIdsCte: SQL,\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\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: currentReadInstant(),\n });\n const columns: SQL[] = [\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: currentReadInstant(),\n });\n const columns: SQL[] = [\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 query = sql`${membership.prefix}SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.edgesTable} 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 buildMetadataColumns(\n alias: \"n\" | \"e\",\n plan: ProjectionPlan,\n columns: readonly string[],\n): readonly SQL[] {\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(alias: \"n\" | \"e\", plan: ProjectionPlan): SQL {\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 SQL[] {\n const columns: SQL[] = [];\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 mapSubgraphNodeRow(\n row: SubgraphNodeFetchRow,\n projectionPlan: ProjectionPlan,\n): Node {\n const kindPlan = projectionPlan.projectedKinds.get(row.kind);\n if (kindPlan === undefined) {\n return rowToNode({\n ...row,\n props: normalizeProps(row.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(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 return rowToEdge({\n ...row,\n props: normalizeProps(row.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(row);\n }\n\n applyProjectedFields(projectedEdge, row, kindPlan);\n return projectedEdge as Edge;\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 { type SQL, sql } from \"drizzle-orm\";\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 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 { emitSetOperationQuerySql } from \"./emitter\";\nimport { runCompilerPass } from \"./passes\";\nimport { type LogicalPlan, lowerSetOperationToLogicalPlan } from \"./plan\";\n\n/**\n * Type for the query compiler function.\n */\nexport type QueryCompilerFunction = (ast: QueryAst, graphId: string) => SQL;\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\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 SQL for the set operation\n */\nexport function compileSetOperation(\n op: SetOperation,\n graphId: string,\n dialect: DialectAdapter,\n compileQuery: QueryCompilerFunction,\n vectorStrategy?: VectorStrategy,\n): SQL {\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): SQL {\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(OPERATOR_MAP[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): SQL {\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): SQL {\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: FieldRef,\n projection: Projection,\n): ProjectedField | undefined {\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. Uses IS NULL emulation for consistent NULLS FIRST/LAST across dialects\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): SQL[] {\n const clauses: SQL[] = [];\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: SQL[] = [];\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.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 const dir = sql.raw(orderSpec.direction.toUpperCase());\n\n // Handle nulls with IS NULL emulation for cross-dialect consistency\n // Default: ASC → NULLS LAST, DESC → NULLS FIRST\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDir = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n\n // Emulate NULLS FIRST/LAST: (col IS NULL) ASC/DESC, col DIR\n orderParts.push(\n sql`(${columnRef} IS NULL) ${nullsDir}`,\n sql`${columnRef} ${dir}`,\n );\n }\n\n clauses.push(sql`ORDER BY ${sql.join(orderParts, sql`, `)}`);\n }\n\n // Handle LIMIT\n if (op.limit !== undefined) {\n clauses.push(sql`LIMIT ${op.limit}`);\n }\n\n // Handle OFFSET\n if (op.offset !== undefined) {\n clauses.push(sql`OFFSET ${op.offset}`);\n }\n\n return clauses;\n}\n","import type {\n FulltextMatchPredicate,\n HybridFusionOptions,\n PredicateExpression,\n QueryAst,\n VectorSimilarityPredicate,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport {\n createTemporalFilterPass,\n resolveFulltextAwareLimit,\n resolveVectorAwareLimit,\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) => field.source.__type === \"aggregate\",\n );\n}\n\nfunction 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 \"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 }\n}\n\nfunction collectRequiredColumnsByAlias(ast: QueryAst): RequiredColumnsByAlias {\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 (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 {\n addRequiredColumn(requiredColumnsByAlias, source.field.alias, \"id\");\n markFieldRefAsRequired(requiredColumnsByAlias, source.field);\n }\n }\n }\n\n if (ast.groupBy) {\n for (const field of ast.groupBy.fields) {\n markFieldRefAsRequired(requiredColumnsByAlias, field);\n }\n }\n\n if (ast.orderBy) {\n for (const orderSpec of ast.orderBy) {\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.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 \"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 }\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) {\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) {\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(currentState.ast, ctx.readInstant);\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 // Compute effectiveLimit once — used by both logical plan lowering and SQL LIMIT/OFFSET.\n // Both vector and fulltext predicates carry their own LIMITs; the tightest wins.\n state = {\n ...state,\n effectiveLimit: resolveFulltextAwareLimit(\n resolveVectorAwareLimit(state.ast.limit, state.vectorPredicate),\n state.fulltextPredicate,\n ),\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 * 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 { type SQL, sql } from \"drizzle-orm\";\n\nimport { CompilerInvariantError, ConfigurationError } from \"../../errors\";\nimport {\n type AggregateExpr,\n type FulltextMatchPredicate,\n type HybridFusionOptions,\n type QueryAst,\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 {\n annIndexScanTypes,\n asCompiledSelectSql,\n type CompiledSelectSql,\n markAnnIndexScan,\n} from \"../sql-intent\";\nimport { emitStandardQuerySql } from \"./emitter\";\nimport {\n buildLimitOffsetClause,\n buildStandardEmbeddingsCte,\n buildStandardFromClause,\n buildStandardFulltextCte,\n buildStandardFulltextOrderBy,\n buildStandardGroupBy,\n buildStandardHaving,\n buildStandardHybridCandidateCte,\n buildStandardHybridRrfOrderBy,\n buildStandardOrderBy,\n buildStandardProjection,\n buildStandardStartCte,\n buildStandardTraversalCte,\n buildStandardVectorOrderBy,\n} from \"./emitter\";\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 {\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 runStandardQueryPassPipeline,\n shouldMaterializeTraversalCte,\n} from \"./standard-pass-pipeline\";\nimport {\n isAggregateExpr,\n isIdFieldRef,\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 `backend.fulltextStrategy` so a\n * backend-declared strategy (e.g. ParadeDB) wins over the dialect\n * default (tsvector).\n */\n fulltextStrategy?: FulltextStrategy | 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 /**\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}>;\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 Drizzle SQL object ready for 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 // 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 // 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 SQL 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 compileQuery: (subAst, subGraphId) =>\n compileQuery(\n inheritRecordedAsOf(subAst, ast.recordedAsOf),\n subGraphId,\n propagateOptions(options_),\n ),\n ...(options_.vectorStrategy === undefined ?\n {}\n : { vectorStrategy: options_.vectorStrategy }),\n windowFunctions: options_.windowFunctions ?? true,\n ...(options_.vectorSlots === undefined ?\n {}\n : { vectorSlots: options_.vectorSlots }),\n ...(options_.fulltextLanguages === undefined ?\n {}\n : { fulltextLanguages: options_.fulltextLanguages }),\n };\n\n function finish(compiled: SQL): 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 (hasVariableLengthTraversal(ast)) {\n const lowered = tryLowerSingleHopRecursiveTraversal(ast);\n if (lowered !== undefined) {\n return finish(compileStandardQuery(lowered, graphId, ctx));\n }\n return finish(compileVariableLengthQuery(ast, graphId, ctx));\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 = 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 ) {\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 Drizzle SQL object\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 SQL 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 */\nfunction resolveDialectAdapter(\n dialect: SqlDialect,\n fulltextStrategy: FulltextStrategy | undefined,\n): DialectAdapter {\n const baseAdapter = getDialect(dialect);\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. */\nfunction propagateOptions(options_: CompileQueryOptions): 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 ...(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 };\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((orderSpec) => orderSpec.field.alias !== ast.start.alias)\n ) {\n return undefined;\n }\n\n const traversal = ast.traversals[0]!;\n if ((traversal.inverseEdgeKinds?.length ?? 0) > 0) {\n return undefined;\n }\n\n const groupField = ast.groupBy.fields[0]!;\n if (groupField.alias !== ast.start.alias || !isIdFieldRef(groupField)) {\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 (!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): SQL | 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: SQL[] = [];\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 (!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 })\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 * Compiles a standard (non-recursive) query to SQL using CTEs.\n */\ntype StandardQueryStrategyHandler = (\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n) => SQL;\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): SQL {\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): SQL | 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): SQL {\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\n // Build CTEs\n const ctes: SQL[] = [\n buildStandardStartCte({\n ast,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n }),\n ];\n\n // Traversal CTEs\n for (let index = 0; index < ast.traversals.length; index++) {\n const materializeTraversalCte = shouldMaterializeTraversalCte(\n dialect,\n ast.traversals.length,\n index,\n );\n ctes.push(\n buildStandardTraversalCte({\n ast,\n carryForwardPreviousColumns: shouldCollapseSelectiveTraversalRowset,\n ctx,\n graphId,\n materializeCte: materializeTraversalCte,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversalIndex: index,\n traversalLimit: traversalCteLimit,\n }),\n );\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 dialect,\n });\n const fromClause = buildStandardFromClause({\n ast,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n ...(vectorPredicate === undefined ? {} : { vectorPredicate }),\n ...(fulltextPredicate === undefined ? {} : { fulltextPredicate }),\n });\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 });\n\n return emitStandardQuerySql({\n ctes,\n fromClause,\n ...(groupBy === undefined ? {} : { groupBy }),\n ...(having === undefined ? {} : { having }),\n ...(orderBy === undefined ? {} : { orderBy }),\n ...(limitOffset === undefined ? {} : { limitOffset }),\n logicalPlan,\n projection,\n });\n}\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 * 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","/**\n * Result mapping utilities for query execution.\n *\n * Transforms raw database rows into typed SelectContext and result objects.\n */\nimport { type NodeType } from \"../../core/types\";\nimport { normalizePath } from \"../../utils\";\nimport { type Traversal } from \"../ast\";\nimport type {\n AliasMap,\n EdgeAliasMap,\n QueryBuilderState,\n RecursiveAliasMap,\n SelectableEdge,\n SelectableNode,\n SelectContext,\n} from \"../builder/types\";\nimport { type SqlDialect } from \"../dialect/types\";\n\n/**\n * Transforms SQLite path columns from pipe-delimited strings to arrays.\n * PostgreSQL returns native arrays, so no transformation needed.\n */\nexport function transformPathColumns(\n rows: readonly Record<string, unknown>[],\n state: QueryBuilderState,\n _dialect: SqlDialect,\n): readonly Record<string, unknown>[] {\n // Find path columns from variable-length traversals\n const pathAliases: string[] = [];\n for (const traversal of state.traversals) {\n if (traversal.variableLength?.pathAlias !== undefined) {\n pathAliases.push(traversal.variableLength.pathAlias);\n }\n }\n\n if (pathAliases.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 of pathAliases) {\n const value = row[alias];\n if (value !== undefined && !Array.isArray(value)) {\n transformed ??= { ...row };\n transformed[alias] = normalizePath(value);\n }\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\n// Reserved keys that cannot be overwritten by user props\nconst RESERVED_NODE_KEYS = new Set([\"id\", \"kind\", \"meta\"]);\nconst RESERVED_EDGE_KEYS = new Set([\"id\", \"kind\", \"fromId\", \"toId\", \"meta\"]);\n\n/**\n * Converts null to undefined for consistent typing.\n * Database backends return null for missing values, but our types use undefined.\n */\nfunction nullToUndefined<T>(value: T | null | undefined): T | undefined {\n return value === null ? undefined : value;\n}\n\n/**\n * Assigns props to a target object, excluding reserved keys to prevent runtime\n * collisions with system fields (id, kind, meta, etc).\n */\nfunction assignPropsExcludingReserved(\n target: Record<string, unknown>,\n props: Record<string, unknown>,\n reservedKeys: Set<string>,\n): void {\n for (const [key, value] of Object.entries(props)) {\n if (!reservedKeys.has(key)) {\n target[key] = value;\n }\n }\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 = nullToUndefined(\n row[`${alias}_valid_from`] as string | null,\n );\n const validTo = nullToUndefined(row[`${alias}_valid_to`] as string | null);\n const createdAt = row[`${alias}_created_at`] as string;\n const updatedAt = row[`${alias}_updated_at`] as string;\n const deletedAt = nullToUndefined(\n row[`${alias}_deleted_at`] as string | null,\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 };\n\n assignPropsExcludingReserved(result, rawProps, RESERVED_NODE_KEYS);\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 = nullToUndefined(\n row[`${alias}_valid_from`] as string | null,\n );\n const validTo = nullToUndefined(row[`${alias}_valid_to`] as string | null);\n const createdAt = row[`${alias}_created_at`] as string;\n const updatedAt = row[`${alias}_updated_at`] as string;\n const deletedAt = nullToUndefined(\n row[`${alias}_deleted_at`] as string | null,\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 };\n\n assignPropsExcludingReserved(result, rawProps, RESERVED_EDGE_KEYS);\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 // Build the start node as initial context entry\n const context: Record<\n string,\n | SelectableNode<NodeType>\n | SelectableEdge\n | number\n | readonly string[]\n | undefined\n > = {\n [startAlias]: buildSelectableNode(row, startAlias),\n };\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] = row[vl.depthAlias] as number;\n }\n if (vl.pathAlias !== undefined) {\n context[vl.pathAlias] = row[vl.pathAlias] as readonly string[];\n }\n }\n }\n\n return context as SelectContext<Aliases, EdgeAliases, RecursiveAliases>;\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","/**\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 { ValidationError } from \"../errors\";\nimport { 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(`Invalid cursor direction: ${String(raw.d)}`, {\n issues: [\n {\n path: \"cursor\",\n message: `Direction must be \"f\" (forward) or \"b\" (backward)`,\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 } = 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 } = 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/**\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-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 {\n type FieldRef,\n type NodePredicate,\n type OrderSpec,\n type PredicateExpression,\n} from \"../ast\";\nimport type {\n AliasMap,\n EdgeAliasMap,\n PaginatedResult,\n PaginateOptions,\n SelectContext,\n StreamOptions,\n} from \"../builder/types\";\nimport {\n buildCursorFromRow,\n type CursorData,\n decodeCursor,\n validateCursorColumns,\n} from \"../cursor\";\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 }));\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 // 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 = orderBy[index_]!;\n const value = values[index_];\n andConditions.push(buildEqualityPredicate(spec.field, value));\n }\n\n // Current column uses comparison\n const currentSpec = orderBy[index]!;\n const currentValue = values[index];\n const isAsc = currentSpec.direction === \"asc\";\n const isForward = direction === \"forward\";\n // ASC + forward = gt | ASC + backward = lt\n // DESC + forward = lt | DESC + backward = gt\n const op = isAsc === isForward ? \"gt\" : \"lt\";\n\n andConditions.push(\n buildComparisonPredicate(currentSpec.field, op, currentValue),\n );\n\n // Combine with AND\n if (andConditions.length === 1) {\n orConditions.push(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 === 1 ?\n orConditions[0]!\n : { __type: \"or\", predicates: orConditions };\n\n return {\n targetAlias,\n expression,\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 buildComparisonPredicate(\n field: FieldRef,\n op: \"gt\" | \"lt\",\n value: unknown,\n): PredicateExpression {\n if (value === null || value === undefined) {\n // For null, the comparison depends on NULLS FIRST/LAST behavior\n // For simplicity, treat as IS NOT NULL for forward, fail for backward\n return { __type: \"null_check\", op: \"isNotNull\", field };\n }\n return {\n __type: \"comparison\",\n op,\n left: field,\n right: { __type: \"literal\", value: value as string | number | boolean },\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 let nextCursor: string | undefined;\n let previousCursor: string | undefined;\n\n if (orderedRows.length > 0) {\n const firstRow = orderedRows[0]!;\n const lastRow = orderedRows.at(-1)!;\n\n // Build cursors using mapped result context\n const firstContext = buildContext(firstRow);\n const lastContext = buildContext(lastRow);\n\n // Extract values for ORDER BY columns from the context\n previousCursor = buildCursorFromContext(firstContext, orderBy, \"b\");\n nextCursor = buildCursorFromContext(lastContext, orderBy, \"f\");\n }\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","/**\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 */\n\nimport type { KindEntity } from \"../../core/types\";\nimport { EDGE_META_KEYS, NODE_META_KEYS } from \"../../system-fields\";\nimport { compareStrings } from \"../../utils/compare\";\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\";\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\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 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 const context: Record<string, unknown> = {\n [state.startAlias]: createNodeTrackingProxy(\n state.startAlias,\n state.startKinds,\n tracker,\n options,\n ),\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] = options.mode === \"falsy\" ? [] : [\"placeholder\"];\n }\n }\n }\n\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 {},\n {\n get: (_, property: string | symbol) => {\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n if (OBJECT_PROTOTYPE_PROPERTIES.has(property)) {\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 {},\n {\n get: (_, property: string | symbol) => {\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n if (OBJECT_PROTOTYPE_PROPERTIES.has(property)) {\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 */\n\nimport type { KindEntity } from \"../../core/types\";\nimport { compareStrings, normalizePath } from \"../../utils\";\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 { 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\n// ============================================================\n// Marker for \"whole alias object\" detection\n// ============================================================\n\nconst SELECTABLE_ALIAS_MARKER = Symbol(\"selectable_alias_marker\");\n\ntype SelectableAliasMarker = Readonly<{\n alias: string;\n kind: AliasKind;\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\nfunction 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 (Array.isArray(current)) {\n for (const item of current) {\n if (walk(item)) return true;\n }\n return false;\n }\n\n if (typeof current !== \"object\" || current === null) {\n return false;\n }\n\n if (visited.has(current)) return false;\n visited.add(current);\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// ============================================================\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 const context: Record<string, 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] = row[vl.depthAlias];\n }\n if (vl.pathAlias !== undefined) {\n context[vl.pathAlias] = normalizePath(row[vl.pathAlias]);\n }\n }\n }\n\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 const base: Record<string, unknown> = {\n [SELECTABLE_ALIAS_MARKER]: {\n alias: plan.alias,\n kind: plan.kind,\n } satisfies SelectableAliasMarker,\n };\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: Record<string, unknown> = {};\n for (const field of plan.metaFields) {\n meta[field.metaKey] = nullToUndefined(row[field.outputName]);\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\nfunction createGuardedProxy(\n target: Record<string, unknown>,\n debugPath: string,\n): unknown {\n return new Proxy(target, {\n get: (object, property: string | symbol, receiver) => {\n if (typeof property === \"symbol\") {\n return Reflect.get(object, property, receiver) as unknown;\n }\n\n if (property === \"then\" || property === \"toJSON\") {\n return;\n }\n\n if (property in object) {\n return Reflect.get(object, property, receiver);\n }\n\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 * 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 Drizzle SQL object\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 { Placeholder, type SQL } from \"drizzle-orm\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { nowIso } from \"../../utils/date\";\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 { type SqlDialect } from \"../dialect/types\";\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 {@link 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 Drizzle SQL object to `{ sql, params }` without executing. */\ntype CompileSqlFunction = (query: SQL) => CompiledTemplate;\n\n/**\n * The slice of a backend used to build a template. Passed whole (not as a bare\n * `compileSql` reference) so `compileSql` is invoked as a method — a custom\n * backend may implement it with `this`, which a detached call would lose.\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 parameter instanceof Placeholder &&\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). `asOf`, `includeEnded`, and `includeTombstones` reads bind no\n * read instant at all, so their compiled statement is stable and cacheable\n * verbatim.\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 // Method call (not a detached reference) so a this-using compileSql works.\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\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 */\nexport function fillTemplateParams(\n params: readonly unknown[],\n bindings: Readonly<Record<string, unknown>>,\n dialect: SqlDialect,\n): unknown[] {\n const adapter = getDialect(dialect);\n let readInstant: string | undefined;\n return params.map((parameter) => {\n if (!(parameter instanceof Placeholder)) return parameter;\n\n // drizzle types Placeholder#name as `any`; it is always a string.\n const name = parameter.name as string;\n if (name === CURRENT_READ_INSTANT_PLACEHOLDER) {\n readInstant ??= nowIso();\n return readInstant;\n }\n\n const value = bindings[name];\n if (value === undefined) {\n throw new ConfigurationError(`Missing binding for parameter \"${name}\"`, {\n parameterName: name,\n });\n }\n if (value instanceof Date) return value.toISOString();\n return adapter.bindValue(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`), the statement is compiled ONCE 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: on a backend without raw execution (custom/async), substitutes\n * parameter refs into the AST, compiles fresh per call, and executes via the\n * standard `backend.execute` path.\n */\nimport { type GraphBackend } from \"../../backend/types\";\nimport { ConfigurationError, UnsupportedPredicateError } from \"../../errors\";\nimport {\n type BetweenPredicate,\n type ComparisonPredicate,\n type ComposableQuery,\n type LiteralValue,\n type PredicateExpression,\n type QueryAst,\n type SelectiveField,\n type StringPredicate,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n mapResults,\n mapSelectiveResults,\n MissingSelectiveFieldError,\n transformPathColumns,\n} from \"../execution\";\nimport { isParameterRef } from \"../predicates\";\nimport { type SchemaIntrospector } from \"../schema-introspector\";\nimport {\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/**\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 = bindings[expr.right.name];\n if (value === undefined) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${expr.right.name}\"`,\n { parameterName: expr.right.name },\n );\n }\n return {\n ...expr,\n right: toLiteral(value),\n } satisfies ComparisonPredicate;\n }\n return expr;\n }\n\n case \"string_op\": {\n if (isParameterRef(expr.pattern)) {\n const value = 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 // 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\nfunction resolveBinding(\n bindings: Readonly<Record<string, unknown>>,\n name: string,\n): unknown {\n const value = 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 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 };\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 /**\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 }\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 (this.#selectiveFields !== undefined) {\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 (\n error instanceof MissingSelectiveFieldError ||\n error instanceof UnsupportedPredicateError\n ) {\n // Fall back per-call without permanently disabling the optimized path,\n // since different bindings may succeed on the optimized path.\n // Note: this fallback is observable via query profiler hooks (onQueryStart\n // fires twice — once for the optimized attempt, once for the fallback).\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 );\n // Method call (not the detached `executeRaw` local) so a this-using\n // backend implementation keeps its receiver.\n const rawRows = await this.#backend.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\ntype ParameterMetadata = Readonly<{\n names: ReadonlySet<string>;\n /** Parameters used in string_op predicates (must receive string values). */\n stringOpParameters: ReadonlySet<string>;\n}>;\n\nfunction collectParameterMetadata(ast: QueryAst): ParameterMetadata {\n const names = new Set<string>();\n const stringOpParameters = new Set<string>();\n\n collectParameterMetadataFromAst(ast, names, stringOpParameters);\n\n return { names, stringOpParameters };\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 names: Set<string>,\n stringOpParameters: Set<string>,\n): void {\n for (const predicate of ast.predicates) {\n collectParameterMetadataFromExpression(\n predicate.expression,\n names,\n stringOpParameters,\n );\n }\n if (ast.having !== undefined) {\n collectParameterMetadataFromExpression(\n ast.having,\n names,\n stringOpParameters,\n );\n }\n}\n\nfunction collectParameterMetadataFromExpression(\n expression: PredicateExpression,\n names: Set<string>,\n stringOpParameters: Set<string>,\n): void {\n switch (expression.__type) {\n case \"comparison\": {\n if (isParameterRef(expression.right)) {\n names.add(expression.right.name);\n }\n return;\n }\n case \"string_op\": {\n if (isParameterRef(expression.pattern)) {\n names.add(expression.pattern.name);\n stringOpParameters.add(expression.pattern.name);\n }\n return;\n }\n case \"between\": {\n if (isParameterRef(expression.lower)) {\n names.add(expression.lower.name);\n }\n if (isParameterRef(expression.upper)) {\n names.add(expression.upper.name);\n }\n return;\n }\n case \"and\":\n case \"or\": {\n for (const predicate of expression.predicates) {\n collectParameterMetadataFromExpression(\n predicate,\n names,\n stringOpParameters,\n );\n }\n return;\n }\n case \"not\": {\n collectParameterMetadataFromExpression(\n expression.predicate,\n names,\n stringOpParameters,\n );\n return;\n }\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;\n }\n case \"exists\": {\n collectParameterMetadataFromAst(\n expression.subquery,\n names,\n stringOpParameters,\n );\n return;\n }\n case \"in_subquery\": {\n collectParameterMetadataFromAst(\n expression.subquery,\n names,\n stringOpParameters,\n );\n return;\n }\n }\n}\n\nfunction validateBindings(\n bindings: Readonly<Record<string, unknown>>,\n metadata: ParameterMetadata,\n): void {\n const { names: expectedNames, stringOpParameters } = metadata;\n\n const missing: string[] = [];\n for (const name of expectedNames) {\n if (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 = bindings[name];\n validateBindingValue(name, value, stringOpParameters.has(name));\n }\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 (\n value instanceof Date ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\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 * SQL Identifier Validation\n *\n * Validates aliases and identifiers to prevent SQL injection.\n */\nimport { ValidationError } from \"../../errors\";\nimport { type HybridFusionOptions, type PredicateExpression } from \"../ast\";\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 \"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;\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 * 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 type { QueryBuilderConfig, QueryBuilderState } from \"./types\";\nimport {\n validateFulltextPredicatePlacement,\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 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 start: {\n alias: state.startAlias,\n kinds: state.startKinds,\n includeSubClasses: state.includeSubClasses,\n },\n traversals: state.traversals,\n predicates: state.predicates,\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 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}>;\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 ) {\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 { resolveEmbeddingFields } from \"../../core/embedding\";\nimport { resolveDeclaredFulltextLanguage } from \"../../core/searchable\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { type CompileQueryOptions } 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 = config.backend?.fulltextStrategy;\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 ...(fulltextStrategy === undefined ?\n {}\n : {\n fulltextStrategy,\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","/**\n * ExecutableQuery - A query that can be executed, paginated, or streamed.\n */\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 { UnsupportedPredicateError, ValidationError } from \"../../errors\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport {\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 type CursorData,\n decodeCursor,\n validateCursorColumns,\n} from \"../cursor\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n buildCursorPredicate,\n buildPaginatedResult,\n buildSelectContext,\n buildSelectiveFields,\n createStreamIterable,\n createTrackingContext,\n decodeSelectedValue,\n FieldAccessTracker,\n getStreamBatchSize,\n mapResults,\n mapSelectiveResults,\n MissingSelectiveFieldError,\n nullToUndefined,\n transformPathColumns,\n} from \"../execution\";\nimport { jsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { fieldRef } from \"../predicates\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { hasParameterReferences, PreparedQuery } from \"./prepared-query\";\nimport {\n buildQueryTemplate,\n type CompiledTemplate,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type EdgeAliasMap,\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\";\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 isSystem =\n field === \"id\" ||\n field === \"kind\" ||\n (isEdge && (field === \"from_id\" || field === \"to_id\"));\n\n let typeInfo: FieldTypeInfo | undefined;\n if (!isSystem) {\n if (isEdge) {\n const edgeKindNames = mergeEdgeKinds(edgeTraversal);\n typeInfo = this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n field,\n );\n } else {\n const kindNames =\n alias === this.#state.startAlias ?\n this.#state.startKinds\n : this.#state.traversals.find(\n (traversal) => traversal.nodeAlias === alias,\n )?.nodeKinds;\n typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n field,\n )\n : undefined;\n }\n }\n\n const orderSpec: OrderSpec =\n isSystem ?\n {\n field: fieldRef(alias, [field], { valueType: \"string\" }),\n direction,\n }\n : {\n field: fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([field]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n }),\n direction,\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 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 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 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 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 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 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 a Drizzle SQL object.\n *\n * Returns a Drizzle SQL object that can be executed directly\n * with db.all(), db.get(), etc.\n */\n compile(): CompiledSelectSql {\n // Emits a directly-runnable statement with the read instant as a literal\n // (a caller may hand the result straight to db.all()), 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 * 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.\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 (!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 // Method call (not the detached `executeRaw` local) so a this-using\n // backend implementation keeps its receiver.\n backend.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 // 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 /**\n * Executes the query against a provided backend.\n *\n * Used by `store.batch()` to run multiple queries over a single connection\n * (e.g., within a transaction). The full compile → execute → transform\n * pipeline runs identically to `execute()`, but against the given backend.\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 // 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 /**\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 trackingRuns =\n hasOptionalTraversal ?\n ([\n {\n mode: \"truthy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"absent\" as const,\n },\n ] as const)\n : ([\n {\n mode: \"truthy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n ] as const);\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 // We intentionally ignore the return value: we only need accessed fields.\n void this.#selectFn(\n trackingContext as SelectContext<\n Aliases,\n EdgeAliases,\n RecursiveAliases\n >,\n );\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 (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 (!this.#recordOrderByFieldsForPagination(tracker)) {\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 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 let nextCursor: string | undefined;\n let previousCursor: string | undefined;\n\n if (orderedRows.length > 0) {\n try {\n previousCursor = this.#buildCursorFromSelectiveRow(\n orderedRows[0]!,\n selectiveFields,\n \"b\",\n );\n nextCursor = this.#buildCursorFromSelectiveRow(\n orderedRows.at(-1)!,\n selectiveFields,\n \"f\",\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 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 #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, 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, 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 const cursorContext: 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 = 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 = 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 = 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> = {};\n current[segment] = created;\n current = created;\n }\n }\n current[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> = {};\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 * unique tiebreaker on the start alias's `id`. 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. The start node's `id` is unique and\n * always projected, so appending it gives a total order that page boundaries\n * can split cleanly. Skipped when the caller already orders by the start\n * alias's `id` (the sort is already total). Every pagination read of ORDER BY\n * — the emitted sort, the cursor predicate, cursor encoding, and cursor\n * validation — routes through here so the extra column stays consistent across\n * the standard and selective-field-optimized paths.\n */\n #paginationOrderBy(): readonly OrderSpec[] {\n const orderBy = this.#state.orderBy;\n const startAlias = this.#state.startAlias;\n const alreadyTotal = orderBy.some(\n (spec) =>\n spec.field.alias === startAlias &&\n spec.field.path.length === 1 &&\n spec.field.path[0] === \"id\" &&\n spec.field.jsonPointer === undefined,\n );\n if (alreadyTotal) return orderBy;\n const tiebreaker: OrderSpec = {\n field: { __type: \"field_ref\", alias: startAlias, path: [\"id\"] },\n direction: \"asc\",\n };\n return [...orderBy, tiebreaker];\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 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 * 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 // 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 /**\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 // Adjust ORDER BY for backward pagination (reverse all directions)\n let orderBy = this.#paginationOrderBy();\n if (direction === \"backward\") {\n orderBy = orderBy.map((spec) => ({\n ...spec,\n direction:\n spec.direction === \"asc\" ? (\"desc\" as const) : (\"asc\" as const),\n }));\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","/**\n * ExecutableAggregateQuery - A query with aggregate functions that can be executed.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n type AggregateExpr,\n type AggregateOrderSpec,\n type FieldRef,\n type QueryAst,\n type SortDirection,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { hasParameterReferences } from \"./prepared-query\";\nimport {\n buildQueryTemplate,\n type CompiledTemplate,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type QueryBuilderConfig,\n type QueryBuilderState,\n} from \"./types\";\n\n/** Sentinel distinguishing \"template not yet built\" from a built `undefined`. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\n/**\n * Result type for aggregate queries.\n * Maps field refs to their value types and aggregates to numbers.\n */\nexport type AggregateResult<\n R extends Record<string, FieldRef | AggregateExpr>,\n> = {\n [K in keyof R]: R[K] extends AggregateExpr ? number\n : R[K] extends FieldRef ? unknown\n : never;\n};\n\n/**\n * An aggregate query that can be executed.\n */\nexport class ExecutableAggregateQuery<\n G extends GraphDef,\n Aliases extends AliasMap,\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 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 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 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 a Drizzle SQL object.\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 #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>[]> {\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 // Method call (not the detached `executeRaw` local) so a this-using\n // backend implementation keeps its receiver.\n await backend.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>[] {\n return rows.map((row) => {\n const result: Record<string, 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 // PostgreSQL returns aggregate bigint/numeric as strings.\n result[key] = typeof value === \"string\" ? Number(value) : value;\n continue;\n }\n\n result[key] = normalizeFieldValue(field, value);\n }\n return result as AggregateResult<R>;\n });\n }\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 (field.valueType === \"boolean\") {\n return normalizeBooleanValue(value);\n }\n\n return value === null ? undefined : value;\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\nexport type DynamicNodeType = NodeType &\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","/**\n * TraversalBuilder - Intermediate builder for edge traversals.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../../core/types\";\nimport { EndpointError, KindNotFoundError } from \"../../errors\";\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 { 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 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 `traverseDynamic(...)`, `EK` is\n * widened to `string` — `string extends EK` distinguishes that case and\n * resolves to `DynamicEdgeType`, so the conditional accessor types fire.\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\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 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 option;\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 = false,\n RecAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n CoordinateState extends QueryCoordinateState = \"open\",\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 #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 ) {\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.#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 { path: infer P extends boolean | string } ? P : PC,\n RecAliases,\n CoordinateState\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 pathAlias = resolveAliasOption(options?.path);\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\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 { path: infer P extends boolean | string } ? P : PC,\n RecAliases,\n CoordinateState\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 ...this.#variableLength,\n enabled: true,\n minDepth,\n maxDepth,\n cyclePolicy,\n ...(options?.path !== undefined && {\n pathEnabled: options.path !== false,\n ...(pathAlias !== undefined && { pathAlias }),\n }),\n ...(options?.depth !== undefined && {\n depthEnabled: options.depth !== false,\n ...(depthAlias !== undefined && { depthAlias }),\n }),\n },\n this.#pendingEdgePredicates,\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<EdgeTypeForKey<G, EK>>) => 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 > {\n const accessor = this.#createEdgeAccessor(alias);\n const predicate = predicateFunction(\n accessor as EdgeAccessor<EdgeTypeForKey<G, EK>>,\n );\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 >(\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 );\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);\n }\n case \"number\": {\n return numberField(ref);\n }\n case \"boolean\": {\n return baseField(ref);\n }\n case \"date\": {\n return dateField(ref);\n }\n case \"array\": {\n return arrayField(ref);\n }\n case \"object\": {\n return objectField(ref);\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 if (property === \"then\") return;\n if (property === \"toJSON\") 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 // 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>,\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>,\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>,\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>,\n CoordinateState\n >;\n }\n\n /**\n * String-keyed sibling of `to` for runtime-declared target kinds.\n * Throws `KindNotFoundError` if the kind is not registered.\n */\n toDynamic<A extends string>(\n kind: string,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<DynamicNodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<EdgeTypeForKey<G, EK>, Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n > {\n validateSqlIdentifier(alias);\n if (!this.#config.registry.hasNodeType(kind)) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.#config.graphId,\n });\n }\n this.#assertValidEndpoint(kind);\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\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<DynamicNodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<EdgeTypeForKey<G, EK>, Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\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 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 };\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 }),\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 for (const endpoint of endpoints) {\n expectedKinds.add(endpoint.kind);\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 { type GraphDef } from \"../../core/define-graph\";\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 {\n type AggregateExpr,\n type FieldRef,\n type GroupBySpec,\n type HybridFusionOptions,\n mergeEdgeKinds,\n type OrderSpec,\n type PredicateExpression,\n type ProjectedField,\n type SortDirection,\n type TraversalDirection,\n type TraversalExpansion,\n} from \"../ast\";\nimport { jsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport {\n buildFieldBuilderForTypeInfo,\n createFulltextAccessor,\n fieldRef,\n type Predicate,\n stringField,\n} from \"../predicates\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\nimport {\n createDynamicFieldBuilder,\n type DynamicEdgeType,\n type DynamicNodeType,\n} from \"./dynamic\";\nimport { ExecutableAggregateQuery } from \"./executable-aggregate-query\";\nimport { ExecutableQuery } from \"./executable-query\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\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 validateSqlIdentifier,\n} from \"./validation\";\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 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 a node kind.\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<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,\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 // Validate alias to prevent SQL injection\n validateSqlIdentifier(alias);\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n\n // Expand kinds if including subclasses\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\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 * String-keyed sibling of `from` for runtime-declared kinds. Throws\n * `KindNotFoundError` if the kind is not registered. Predicates use\n * the `n.field(\"name\").number().gte(...)` discriminator.\n */\n fromDynamic<A extends string>(\n kind: string,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<DynamicNodeType>>,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n > {\n validateSqlIdentifier(alias);\n if (!this.#config.registry.hasNodeType(kind)) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.#config.graphId,\n });\n }\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\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 /**\n * Adds a WHERE clause for a node.\n */\n whereNode<A extends keyof Aliases & string>(\n alias: A,\n predicateFunction: (n: NodeAccessor<Aliases[A][\"type\"]>) => Predicate,\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 );\n\n const newState: QueryBuilderState = {\n ...this.#state,\n predicates: [\n ...this.#state.predicates,\n {\n targetAlias: alias,\n expression: predicate.__expr,\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 ) => Predicate,\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 );\n\n const newState: QueryBuilderState = {\n ...this.#state,\n predicates: [\n ...this.#state.predicates,\n {\n targetAlias: alias,\n targetType: \"edge\",\n expression: predicate.__expr,\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 },\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 },\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 },\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 const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\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 );\n }\n\n /**\n * String-keyed sibling of `traverse` for runtime-declared edge kinds.\n * Throws `KindNotFoundError` if the edge kind is not registered.\n */\n traverseDynamic<EA extends string>(\n edgeKind: string,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType>>,\n string,\n EA,\n TraversalDirection,\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\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 },\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 },\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 },\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 const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\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 );\n }\n\n /**\n * String-keyed sibling of `optionalTraverse` for runtime-declared edge\n * kinds. LEFT JOIN semantics — non-matching rows produce a null edge\n * alias instead of dropping. Throws `KindNotFoundError` if the edge\n * kind is not registered.\n */\n optionalTraverseDynamic<EA extends string>(\n edgeKind: string,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType, true>>,\n string,\n EA,\n TraversalDirection,\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\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<EA extends string, Optional extends boolean>(\n edgeKind: string,\n edgeAlias: EA,\n optional: Optional,\n options:\n | {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n }\n | undefined,\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType, Optional>>,\n string,\n EA,\n TraversalDirection,\n Optional,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n validateSqlIdentifier(edgeAlias);\n if (!this.#config.registry.hasEdgeType(edgeKind)) {\n throw new KindNotFoundError(edgeKind, \"edge\", {\n graphId: this.#config.graphId,\n });\n }\n\n const direction = options?.direction ?? \"out\";\n const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\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 edgeKind,\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<DynamicEdgeType, Optional>>,\n string,\n EA,\n TraversalDirection,\n Optional,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >(\n this.#config,\n newState,\n edgeKinds,\n edgeAlias,\n direction,\n fromAlias,\n inverseEdgeKinds,\n optional,\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<R extends Record<string, FieldRef | AggregateExpr>>(\n fields: R,\n ): ExecutableAggregateQuery<G, Aliases, R> {\n const resolvedFields = Object.fromEntries(\n Object.entries(fields).map(([outputName, source]) => {\n if (source.__type !== \"field_ref\") {\n return [outputName, source];\n }\n\n if (\n source.valueType !== undefined ||\n source.path.length !== 1 ||\n source.path[0] !== \"props\" ||\n source.jsonPointer === undefined\n ) {\n return [outputName, source];\n }\n\n const segments = parseJsonPointer(source.jsonPointer);\n if (segments.length !== 1) {\n return [outputName, source];\n }\n\n const propertyName = segments[0];\n if (propertyName === undefined) {\n return [outputName, source];\n }\n\n const kindNames = this.#getKindNamesForAlias(source.alias);\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n propertyName,\n )\n : undefined;\n\n if (!typeInfo) {\n return [outputName, source];\n }\n\n return [\n outputName,\n {\n ...source,\n valueType: typeInfo.valueType,\n elementType: typeInfo.elementType,\n } satisfies FieldRef,\n ];\n }),\n ) as R;\n\n const projection: ProjectedField[] = Object.entries(resolvedFields).map(\n ([outputName, source]) => ({\n outputName,\n source,\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<A extends (keyof Aliases | keyof EdgeAliases) & string>(\n alias: A,\n field: string,\n direction: SortDirection = \"asc\",\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const edgeKindNames = this.#getEdgeKindNamesForAlias(alias);\n const isEdge = edgeKindNames !== undefined;\n const isSystem =\n field === \"id\" ||\n field === \"kind\" ||\n (isEdge && (field === \"from_id\" || field === \"to_id\"));\n const typeInfo =\n isSystem ? undefined\n : isEdge ?\n this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n field,\n )\n : this.#getOrderByTypeInfo(alias, field);\n const orderSpec: OrderSpec =\n isSystem ?\n {\n field: fieldRef(alias, [field], { valueType: \"string\" }),\n direction,\n }\n : {\n field: fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([field]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n }),\n direction,\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 #getOrderByTypeInfo(alias: string, field: string): FieldTypeInfo | undefined {\n const kindNames = this.#getKindNamesForAlias(alias);\n return kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(kindNames, field)\n : undefined;\n }\n\n /**\n * Limits the number of results.\n */\n limit(\n n: number,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\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 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<A extends keyof Aliases & string>(\n alias: A,\n field: string,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const kindNames = this.#getKindNamesForAlias(alias);\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(kindNames, field)\n : undefined;\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 predicate: PredicateExpression,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n 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 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 if (property === \"then\") return;\n if (property === \"toJSON\") 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 // 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 #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 if (property === \"then\") return;\n if (property === \"toJSON\") 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 // Schema properties\n return this.#getFieldBuilderForEdgeProperty(\n edgeKindNames,\n property,\n alias,\n );\n },\n });\n }\n}\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 { 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 { 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\";\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}\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 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 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 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 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 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 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 /**\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 // Method call (not the detached `executeRaw` local) so a this-using\n // backend implementation keeps its receiver.\n backend.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 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 \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\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 multiple queries over a single connection.\n */\n async executeOn(\n backend: GraphBackend | TransactionBackend,\n ): Promise<readonly R[]> {\n const ast = this.toAst();\n if (composableQueryHasParameterReferences(ast)) {\n throw new Error(\n \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n );\n }\n\n return this.#mapRows(\n await this.#fetchRows(backend, ast, \"recorded-batch-query\"),\n );\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(alias: string, field?: string): AggregateExpr {\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(alias: string, field?: string): AggregateExpr {\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(edgeAlias: string): AggregateExpr {\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(edgeAlias: string): AggregateExpr {\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(alias: string, field: string): AggregateExpr {\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(alias: string, field: string): AggregateExpr {\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(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"min\",\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 MAX aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The field to find maximum of\n */\nexport function max(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"max\",\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 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(alias: string, ...path: string[]): FieldRef {\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","/**\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 EmptyRecursiveAliasMap,\n type QueryCoordinateState,\n type RecursiveAliasMap,\n} from \"./types\";\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 = AliasMap,\n RequiredEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n AddedEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\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 Aliases & AddedAliases,\n 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 { PreparedQuery } from \"./prepared-query\";\nexport { QueryBuilder } from \"./query-builder\";\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 CreateQueryBuilderOptions,\n type DateFieldAccessor,\n type EdgeAccessor,\n type EmbeddingFieldAccessor,\n type EmptyAliasMap,\n type EmptyEdgeAliasMap,\n type EmptyRecursiveAliasMap,\n type FieldAccessor,\n type NodeAccessor,\n type NodeAlias,\n type NumberFieldAccessor,\n type ObjectFieldAccessor,\n type PaginatedResult,\n type PaginateOptions,\n type PropsAccessor,\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 DynamicNodeType,\n type DynamicSelectableEdge,\n type DynamicSelectableNode,\n} from \"./dynamic\";\n\n// Validation utilities\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 { 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 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 DynamicEdgeAccessor,\n DynamicEdgeType,\n DynamicFieldBuilder,\n DynamicNodeAccessor,\n DynamicNodeType,\n DynamicSelectableEdge,\n DynamicSelectableNode,\n EdgeAccessor,\n EmptyAliasMap,\n EmptyEdgeAliasMap,\n EmptyRecursiveAliasMap,\n FieldAccessor,\n NodeAccessor,\n NodeAlias,\n PaginatedResult,\n PaginateOptions,\n PropsAccessor,\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\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 ...(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 });\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 {\n type GraphBackend,\n type NodeRow,\n rowPropsToObject,\n runOptionallyInTransaction,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport { type KindRegistry } from \"../registry\";\nimport { computeFulltextContent, getSearchableFields } 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\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, registry } = ctx;\n\n if (!backend.upsertFulltext || !backend.deleteFulltext) {\n throw new ConfigurationError(\n \"Backend does not support fulltext; cannot rebuild index\",\n { backend: backend.dialect, capability: \"fulltext\" },\n );\n }\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: GraphBackend | TransactionBackend,\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 }\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 }\n }\n };\n\n // Wrapped in a transaction when supported so a partial failure\n // mid-page doesn't leave the index half-rebuilt. On backends without\n // transactions, refusing to rebuild would be worse than the lost\n // atomicity (the index would stay permanently stale).\n await runOptionallyInTransaction(backend, 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 { type SQL, sql } from \"drizzle-orm\";\n\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 { ConfigurationError } 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 { type KindRegistry } from \"../registry/kind-registry\";\nimport { compareCodePoints } from \"../utils/compare\";\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. Postgres HNSW\n * only — no-op elsewhere. 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 * Postgres HNSW only: applied transaction-locally via `SET LOCAL`.\n * sqlite-vec has no equivalent frontier knob and ignores it; Postgres\n * backends without transactions (`drizzle-orm/neon-http`) ignore it\n * with a one-time warning. Must be a positive integer; pgvector caps\n * 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\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): SQL | 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 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(backend, graphId, kind, [...ids]);\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 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 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 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(backend, graphId, merged);\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 ?? 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 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 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(backend, graphId, merged);\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 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 = options.vector.metric ?? vectorKinds[0]!.slot.metric;\n\n // One candidate subquery per kind, shared by both halves.\n const candidatesByKind = new Map<string, SQL | 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] === vectorKinds[0]!.kind\n ) {\n const kind = fulltextKinds[0];\n const { slot } = 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 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 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 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\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 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 if (backend.getNodes) {\n const rows = await backend.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 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\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 = context;\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","/**\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 * 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 { 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 for (const [name, nextNode] of Object.entries(next.nodes ?? {})) {\n const existingNode = existing.nodes?.[name];\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 existingEdge = existing.edges?.[name];\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 classifyEdgeEndpoints(\n kind: string,\n existing: ExtensionEdgeDef,\n next: ExtensionEdgeDef,\n recorders: Recorders,\n): void {\n // Adding kinds to from/to is broadening — always allowed.\n // Removing kinds with no existing edges of that endpoint 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 fromExisting = new Set(existing.from);\n const toExisting = new Set(existing.to);\n const fromNext = new Set(next.from);\n const toNext = new Set(next.to);\n\n for (const removed of [...fromExisting].filter(\n (entry) => !fromNext.has(entry),\n )) {\n recorders.recordRequireEmpty({\n kind,\n type: \"TIGHTEN_EDGE_ENDPOINTS\",\n detail: `removed \"${removed}\" from \\`from\\``,\n });\n }\n for (const removed of [...toExisting].filter((entry) => !toNext.has(entry))) {\n recorders.recordRequireEmpty({\n kind,\n type: \"TIGHTEN_EDGE_ENDPOINTS\",\n detail: `removed \"${removed}\" from \\`to\\``,\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 = 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(kind, name, existing[name]!, next[name]!, recorders);\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","/**\n * Graph-extension removal: mutate a `GraphExtension` to drop a\n * set of graph-extension kinds with cascading edge / ontology cleanup.\n *\n * Pure function — no I/O, no compilation. The caller (`store.removeKinds`)\n * handles persistence (CAS commit of the resulting document) and the\n * deferred data-cleanup phase via `materializeRemovals`. This module\n * answers two questions:\n *\n * 1. Is it valid to remove these names? Compile-time kinds are\n * rejected (compile-time kinds are removed by recompiling and\n * redeploying — persisting \"removed-compile-time-kind\" state in\n * `schema_doc` is incoherent). Graph-extension kinds referenced by a\n * compile-time edge or ontology relation are also rejected\n * (removing them would orphan compile-time references at the\n * next deploy).\n *\n * 2. What does the new document look like? Edges whose endpoint\n * list becomes empty after removal are cascading-removed; edges\n * with surviving endpoints are retained with the removed name\n * dropped from `from`/`to`. Ontology relations referencing any\n * removed kind are also cascading-removed.\n */\nimport { type GraphDef } from \"../core/define-graph\";\nimport { getTypeName } from \"../ontology/types\";\nimport {\n KindHasReferentsError,\n type KindReferent,\n RemoveCompileTimeKindError,\n} from \"./errors\";\nimport {\n type ExtensionEdgeDef,\n type ExtensionIndex,\n type ExtensionNodeDef,\n type ExtensionOntologyRelation,\n type GraphExtension,\n} from \"./extension-types\";\nimport {\n buildGraphExtensionOntologyKeySet,\n compileTimeOntologyKey,\n extensionKindNames,\n} from \"./ontology-keys\";\n\ntype RemovalPlan = Readonly<{\n /**\n * The new extension after applying the removals. When the input\n * list contained only absent names, the document is structurally\n * equal to the existing extension and the caller short-circuits\n * the schema commit.\n */\n document: GraphExtension | undefined;\n /** Kinds actually removed (extension kinds present in the document). */\n removedNodeKinds: readonly string[];\n /** Edge kinds dropped because every endpoint they connected was removed. */\n removedEdgeKinds: readonly string[];\n}>;\n\n/**\n * Plans the removal of a set of names from a host graph's\n * extension, validating against the host graph's compile-time\n * kinds and graph-extension kinds. Throws on the rejection cases:\n *\n * - `RemoveCompileTimeKindError` if any name is a compile-time kind.\n * - `KindHasReferentsError` if a graph-extension kind is referenced\n * by a compile-time edge endpoint or ontology relation.\n *\n * Returns a plan describing the new document and which kinds will be\n * cascading-removed alongside the explicitly named ones.\n */\nexport function planRemovals<G extends GraphDef>(\n graph: G,\n names: readonly string[],\n): RemovalPlan {\n const document = graph.extension;\n const namesSet = new Set(names);\n if (namesSet.size === 0) {\n return { document, removedNodeKinds: [], removedEdgeKinds: [] };\n }\n\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(document);\n const compileTimeNodeNames = new Set(\n Object.keys(graph.nodes).filter((name) => !runtimeNodeNames.has(name)),\n );\n const compileTimeEdgeNames = new Set(\n Object.keys(graph.edges).filter((name) => !runtimeEdgeNames.has(name)),\n );\n\n // Reject compile-time names first — same shape across the API\n // surface even when the call also references absent runtime names.\n for (const name of namesSet) {\n if (compileTimeNodeNames.has(name)) {\n throw new RemoveCompileTimeKindError(name, \"node\", graph.id);\n }\n if (compileTimeEdgeNames.has(name)) {\n throw new RemoveCompileTimeKindError(name, \"edge\", graph.id);\n }\n }\n\n const removedNodeKinds = [...namesSet].filter((name) =>\n runtimeNodeNames.has(name),\n );\n const explicitlyRemovedEdgeKinds = [...namesSet].filter((name) =>\n runtimeEdgeNames.has(name),\n );\n\n // Compile-time-edge referent check: a graph-extension kind being\n // removed cannot remain a target of any compile-time edge or ontology\n // relation, because the compile-time declaration would resurrect the\n // reference on the next deploy. Pre-build an inverted index of\n // `kindName → referents` once so the per-kind check is O(1) instead\n // of walking all edges + ontology per removed kind.\n const referentsByKind = buildCompileTimeReferentIndex(\n graph,\n runtimeEdgeNames,\n );\n for (const kindName of removedNodeKinds) {\n const referents = referentsByKind.get(kindName);\n if (referents !== undefined && referents.length > 0) {\n throw new KindHasReferentsError(kindName, referents, graph.id);\n }\n }\n\n if (document === undefined) {\n return {\n document: undefined,\n removedNodeKinds: [],\n removedEdgeKinds: [],\n };\n }\n\n // Build the cascading-edges set: any graph-extension edge whose `from` or\n // `to` becomes empty after removal is also removed; edges with\n // surviving endpoints are retained with the removed name pruned.\n const removedNodeKindsSet = new Set(removedNodeKinds);\n const explicitlyRemovedEdgeKindsSet = new Set(explicitlyRemovedEdgeKinds);\n const cascadeEdges = new Set<string>();\n const updatedEdges: Record<string, ExtensionEdgeDef> = {};\n\n for (const [edgeName, edgeDocument] of Object.entries(document.edges ?? {})) {\n if (explicitlyRemovedEdgeKindsSet.has(edgeName)) {\n cascadeEdges.add(edgeName);\n continue;\n }\n const newFrom = edgeDocument.from.filter(\n (kind) => !removedNodeKindsSet.has(kind),\n );\n const newTo = edgeDocument.to.filter(\n (kind) => !removedNodeKindsSet.has(kind),\n );\n if (newFrom.length === 0 || newTo.length === 0) {\n cascadeEdges.add(edgeName);\n continue;\n }\n updatedEdges[edgeName] = {\n ...edgeDocument,\n from: newFrom,\n to: newTo,\n };\n }\n\n // Filter nodes — explicit removals are dropped.\n const updatedNodes: Record<string, ExtensionNodeDef> = {};\n for (const [nodeName, nodeDocument] of Object.entries(document.nodes ?? {})) {\n if (removedNodeKindsSet.has(nodeName)) continue;\n updatedNodes[nodeName] = nodeDocument;\n }\n\n // Drop ontology relations referencing any removed kind. The compile-\n // time-referent check above already rejects compile-time-side\n // ontology referencing the removed kind, so any remaining ontology\n // is safe to filter.\n const survivingOntology: ExtensionOntologyRelation[] = (\n document.ontology ?? []\n ).filter(\n (relation) =>\n !removedNodeKindsSet.has(relation.from) &&\n !removedNodeKindsSet.has(relation.to),\n );\n\n // Drop graph-extension indexes referencing removed kinds (relational + edge\n // entries; the auto-derived vector indexes follow the graph-extension nodes\n // they were derived from, so dropping the graph-extension node implicitly\n // drops the index when `mergeGraphExtension` re-runs auto-derive\n // against the smaller node set).\n const allRemovedKinds = new Set([\n ...removedNodeKindsSet,\n ...cascadeEdges,\n ...explicitlyRemovedEdgeKindsSet,\n ]);\n const survivingIndexes: ExtensionIndex[] = (document.indexes ?? []).filter(\n (index) => !allRemovedKinds.has(index.kind),\n );\n\n const newDocument: GraphExtension = Object.freeze({\n ...(document.version === undefined ? {} : { version: document.version }),\n ...(Object.keys(updatedNodes).length === 0 ? {} : { nodes: updatedNodes }),\n ...(Object.keys(updatedEdges).length === 0 ? {} : { edges: updatedEdges }),\n ...(survivingOntology.length === 0 ? {} : { ontology: survivingOntology }),\n ...(survivingIndexes.length === 0 ? {} : { indexes: survivingIndexes }),\n });\n\n return {\n document: newDocument,\n removedNodeKinds,\n removedEdgeKinds: [\n ...explicitlyRemovedEdgeKinds,\n ...[...cascadeEdges].filter(\n (name) => !explicitlyRemovedEdgeKindsSet.has(name),\n ),\n ],\n };\n}\n\n/**\n * Returns a graph with the graph-extension slice stripped: nodes and edges\n * registered by `mergeGraphExtension` are dropped along with the\n * `extension` itself, leaving the compile-time-only graph.\n *\n * Used by `removeKinds` as the base for re-merging the post-removal\n * graph-extension document — the alternative (mutating `graph.nodes` /\n * `graph.edges` in-place) would skip the merge step's validation\n * (collision checks, endpoint resolution).\n */\nexport function stripGraphExtension<G extends GraphDef>(graph: G): G {\n const document = graph.extension;\n if (document === undefined) return graph;\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(document);\n const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(document);\n\n const compileNodes: Record<string, (typeof graph.nodes)[string]> = {};\n for (const [name, registration] of Object.entries(graph.nodes)) {\n if (runtimeNodeNames.has(name)) continue;\n compileNodes[name] = registration;\n }\n const compileEdges: Record<string, (typeof graph.edges)[string]> = {};\n for (const [name, registration] of Object.entries(graph.edges)) {\n if (runtimeEdgeNames.has(name)) continue;\n compileEdges[name] = registration;\n }\n const compileOntology = graph.ontology.filter(\n (relation) => !runtimeOntologyKeys.has(compileTimeOntologyKey(relation)),\n );\n // Drop runtime-origin indexes too — `mergeGraphExtension` re-runs\n // auto-derivation against the new (smaller) graph-extension kind set.\n const compileIndexes = (graph.indexes ?? []).filter(\n (index) => index.origin !== \"runtime\",\n );\n\n return Object.freeze({\n ...graph,\n nodes: compileNodes,\n edges: compileEdges,\n ontology: compileOntology,\n indexes: compileIndexes.length === 0 ? undefined : compileIndexes,\n extension: undefined,\n });\n}\n\n/**\n * Builds an inverted index `kindName → KindReferent[]` over the\n * compile-time edges and ontology relations of `graph`. One walk per\n * graph instead of one walk per removed kind, dropping the cost of the\n * referent check from O(K × (E + O)) to O(K + E + O).\n */\nfunction buildCompileTimeReferentIndex<G extends GraphDef>(\n graph: G,\n runtimeEdgeNames: ReadonlySet<string>,\n): ReadonlyMap<string, readonly KindReferent[]> {\n const index = new Map<string, KindReferent[]>();\n const append = (kindName: string, referent: KindReferent): void => {\n const existing = index.get(kindName);\n if (existing === undefined) index.set(kindName, [referent]);\n else existing.push(referent);\n };\n\n for (const [edgeName, registration] of Object.entries(graph.edges)) {\n if (runtimeEdgeNames.has(edgeName)) continue;\n const reg = registration as {\n from?: readonly { kind: string }[];\n to?: readonly { kind: string }[];\n };\n const referent: KindReferent = {\n type: \"compile-time-edge\",\n name: edgeName,\n };\n const seen = new Set<string>();\n for (const endpoint of reg.from ?? []) {\n if (seen.has(endpoint.kind)) continue;\n seen.add(endpoint.kind);\n append(endpoint.kind, referent);\n }\n for (const endpoint of reg.to ?? []) {\n if (seen.has(endpoint.kind)) continue;\n seen.add(endpoint.kind);\n append(endpoint.kind, referent);\n }\n }\n\n const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(\n graph.extension,\n );\n for (const relation of graph.ontology) {\n if (runtimeOntologyKeys.has(compileTimeOntologyKey(relation))) continue;\n const fromName = getTypeName(relation.from);\n const toName = getTypeName(relation.to);\n const referent: KindReferent = {\n type: \"compile-time-ontology\",\n name: `${relation.metaEdge.name}(${fromName}, ${toName})`,\n };\n append(fromName, referent);\n if (toName !== fromName) append(toName, referent);\n }\n\n return index;\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 { ConfigurationError } 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 }>;\n\n/**\n * Resolves per-call temporal overrides against the graph's default mode into\n * a plain `{ temporalMode, asOf? }` object. Shared by callers that forward\n * the pair to `buildReachableCte`. An `asOf` is rejected unless the mode is\n * `\"asOf\"` (via {@link resolveReadCoordinate}), 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 timestamp 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 };\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\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","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { compileKindFilter } from \"../../query/compiler/predicate-utils\";\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: SQL[] = [\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: SQL,\n): SQL {\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: SQL,\n): SQL {\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 { sql } from \"drizzle-orm\";\n\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { buildReachableCte } from \"../recursive-cte\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n DEFAULT_ALGORITHM_MAX_HOPS,\n DEFAULT_NEIGHBOR_DEPTH,\n type InternalTraversalOptions,\n resolveMaxHops,\n resolveTemporalOptions,\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\ntype ReachableRow = Readonly<{\n id: string;\n kind: string;\n depth: number | string;\n}>;\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 cte = buildReachableCte({\n graphId: ctx.graphId,\n sourceId,\n edgeKinds: options.edges,\n maxHops,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n includePath: false,\n ...resolveTemporalOptions(ctx, options),\n dialect: ctx.dialect,\n schema: ctx.schema,\n ...(ctx.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: ctx.recordedReadBinding }),\n });\n\n const sourceFilter =\n options.excludeSource === true ? sql` WHERE id != ${sourceId}` : sql``;\n\n const query = sql`${cte} SELECT id, kind, MIN(depth) AS depth FROM reachable${sourceFilter} GROUP BY id, kind ORDER BY depth ASC, id ASC`;\n\n const rows = await ctx.backend.execute<ReachableRow>(\n asCompiledRowsSql(query),\n );\n return rows.map((row) => ({\n id: row.id,\n kind: row.kind,\n depth: Number(row.depth),\n }));\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 // Self-case (sourceId === targetId) is not short-circuited: the CTE base\n // case emits the source row only if it passes the temporal filter, so\n // `canReach(a, a)` correctly returns false when `a` is not visible under\n // the resolved mode — consistent with `shortestPath(a, a)`.\n const cte = buildReachableCte({\n graphId: ctx.graphId,\n sourceId,\n edgeKinds: options.edges,\n maxHops,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n includePath: false,\n ...resolveTemporalOptions(ctx, options),\n dialect: ctx.dialect,\n schema: ctx.schema,\n ...(ctx.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: ctx.recordedReadBinding }),\n });\n\n const query = sql`${cte} SELECT 1 AS hit FROM reachable WHERE id = ${targetId} LIMIT 1`;\n\n const rows = await ctx.backend.execute<Readonly<{ hit: number }>>(\n asCompiledRowsSql(query),\n );\n return rows.length > 0;\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 ...(options.temporalMode !== undefined && {\n temporalMode: options.temporalMode,\n }),\n ...(options.asOf !== undefined && { asOf: options.asOf }),\n ...(options.recordedAsOf !== undefined && {\n recordedAsOf: options.recordedAsOf,\n }),\n excludeSource: true,\n });\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { normalizePath } from \"../../utils\";\nimport { buildReachableCte } from \"../recursive-cte\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n DEFAULT_ALGORITHM_MAX_HOPS,\n type InternalTraversalOptions,\n resolveMaxHops,\n resolveReadSchema,\n resolveTemporalFilter,\n resolveTemporalOptions,\n} from \"./context\";\nimport type { PathNode, ShortestPathResult } from \"./types\";\n\ntype ShortestPathRow = Readonly<{\n hit_id: string;\n hit_kind: string;\n hit_depth: number | string;\n hit_path: unknown;\n node_id: string | undefined;\n node_kind: string | undefined;\n}>;\n\ntype NodeKindRow = Readonly<{ id: string; kind: string }>;\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\n // Self-path short-circuit: avoids the recursive CTE entirely while still\n // honouring the configured temporal mode via a lightweight existence check.\n if (sourceId === targetId) {\n const source = await fetchNodeKind(ctx, sourceId, options);\n if (source === undefined) return undefined;\n return { nodes: [source], depth: 0 };\n }\n\n const cte = buildReachableCte({\n graphId: ctx.graphId,\n sourceId,\n edgeKinds: options.edges,\n maxHops,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n includePath: true,\n ...resolveTemporalOptions(ctx, options),\n dialect: ctx.dialect,\n schema: ctx.schema,\n ...(ctx.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: ctx.recordedReadBinding }),\n });\n\n // `cycleCheck` returns TRUE when id is NOT in path; negating it yields the\n // \"id is in path\" predicate needed to hydrate every hop's kind in one query.\n //\n // Cost model: the LEFT JOIN scans `reachable` with an O(path length) check\n // per row. Under cyclePolicy: \"prevent\" (default), |reachable| ≤ V, so this\n // is bounded by V × p. Under \"allow\" + high maxHops, |reachable| grows with\n // the CTE itself (O(V × maxHops)) — but that cost is proportional to the\n // CTE materialization the user already opted into, not a new asymptotic\n // class. If this ever dominates in a real workload, the path-unpack +\n // nodes-PK join variant is the likely next step.\n const pathContainsCheck = sql`NOT (${ctx.dialect.cycleCheck(sql.raw(\"r.id\"), sql.raw(\"h.path\"))})`;\n\n const query = sql`${cte}, hit AS (SELECT id, kind, depth, path FROM reachable WHERE id = ${targetId} ORDER BY depth ASC LIMIT 1) SELECT h.id AS hit_id, h.kind AS hit_kind, h.depth AS hit_depth, h.path AS hit_path, r.id AS node_id, r.kind AS node_kind FROM hit h LEFT JOIN reachable r ON ${pathContainsCheck}`;\n\n const rows = await ctx.backend.execute<ShortestPathRow>(\n asCompiledRowsSql(query),\n );\n const first = rows[0];\n if (first === undefined) return undefined;\n\n const pathIds = normalizePath(first.hit_path);\n const kindById = buildKindIndex(rows);\n\n const pathNodes: PathNode[] = pathIds.map((id) => ({\n id,\n kind: kindById.get(id) ?? \"\",\n }));\n\n return { nodes: pathNodes, depth: Number(first.hit_depth) };\n}\n\nfunction buildKindIndex(\n rows: readonly ShortestPathRow[],\n): ReadonlyMap<string, string> {\n const map = new Map<string, string>();\n for (const row of rows) {\n if (row.node_id !== undefined && row.node_kind !== undefined) {\n map.set(row.node_id, row.node_kind);\n }\n }\n return map;\n}\n\nasync function fetchNodeKind(\n ctx: AlgorithmContext,\n nodeId: string,\n options: InternalTraversalOptions,\n): Promise<PathNode | undefined> {\n const temporalFilter = resolveTemporalFilter(ctx, options);\n const schema = resolveReadSchema(ctx, options);\n const query: SQL = sql`SELECT id, kind FROM ${schema.nodesTable} WHERE graph_id = ${ctx.graphId} AND id = ${nodeId} AND ${temporalFilter} LIMIT 1`;\n const rows = await ctx.backend.execute<NodeKindRow>(asCompiledRowsSql(query));\n const row = rows[0];\n if (row === undefined) return undefined;\n return { id: row.id, kind: row.kind };\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 {\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 InternalNeighborsOptions,\n InternalReachableOptions,\n InternalShortestPathOptions,\n NeighborsOptions,\n ReachableNode,\n ReachableOptions,\n ShortestPathOptions,\n ShortestPathResult,\n} from \"./types\";\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 * 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? Short-circuits the underlying recursive CTE with `LIMIT 1`.\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\nexport type InternalGraphAlgorithms<G extends GraphDef> = Readonly<{\n shortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: InternalShortestPathOptions<G>,\n ) => Promise<ShortestPathResult | 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}>;\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).reachable/shortestPath/canReach/neighbors/degree(...) 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 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 };\n}\n\nexport type {\n AlgorithmCyclePolicy,\n BaseTraversalOptions,\n DegreeOptions,\n InternalBaseTraversalOptions,\n InternalDegreeOptions,\n InternalNeighborsOptions,\n InternalReachableOptions,\n InternalShortestPathOptions,\n InternalTemporalAlgorithmOptions,\n NeighborsOptions,\n PathNode,\n ReachableNode,\n ReachableOptions,\n ShortestPathOptions,\n ShortestPathResult,\n TemporalAlgorithmOptions,\n TraversalDirection,\n} from \"./types\";\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 {\n type FindEdgesByKindParams,\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type TemporalMode } from \"../../core/types\";\nimport { UnsupportedPredicateError } from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport type { BatchableQuery } from \"../../query/builder/types\";\nimport { getEdgeRowsByIds } from \"../edge-fetch\";\nimport { type EdgeRow } from \"../row-mappers\";\nimport {\n type CreateEdgeInput,\n type Edge,\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} from \"../types\";\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 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 props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeUpsertUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Edge>;\n executeDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\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 }>,\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 }>[],\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<{ id?: string; validFrom?: string; validTo?: string }>,\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;\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\ntype EdgeUpdateInput = Readonly<{\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n}>;\n\nfunction buildUpdateEdgeInput(\n id: string,\n props: Record<string, unknown>,\n options?: Readonly<{ validTo?: string }>,\n): EdgeUpdateInput {\n const input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n } = { id, props };\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input;\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;\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 defaultTemporalMode,\n rowToEdge,\n executeCreate: executeEdgeCreate,\n executeCreateNoReturnBatch: executeEdgeCreateNoReturnBatch,\n executeCreateBatch: executeEdgeCreateBatch,\n executeUpdate: executeEdgeUpdate,\n executeUpsertUpdate: executeEdgeUpsertUpdate,\n executeDelete: executeEdgeDelete,\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 function buildEndpointFindParams(\n endpoint:\n | Readonly<{ fromKind: string; fromId: string }>\n | Readonly<{ toKind: string; toId: string }>,\n options: QueryOptions | undefined,\n ): FindEdgesByKindParams {\n return {\n graphId,\n kind,\n ...endpoint,\n ...resolveTemporalReadParams(options, defaultTemporalMode),\n };\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 options,\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({ toKind: to.kind, toId: to.id }, options),\n );\n return mapRows(rows);\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<{ id?: string; validFrom?: string; validTo?: string }>,\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(backend, graphId, ids);\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?: Readonly<{ validTo?: string }>,\n ): Promise<Edge<E>> {\n const result = await executeEdgeUpdate(\n buildUpdateEdgeInput(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 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(id, backend);\n },\n\n async hardDelete(id: string): Promise<void> {\n await executeEdgeHardDelete(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;\n validTo?: string;\n }>[],\n ): Promise<Edge<E>[]> {\n const batchInputs = mapBulkEdgeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n const results = await backend.transaction(async (txBackend) =>\n executeEdgeCreateBatch(batchInputs, txBackend),\n );\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowEdges<E>(results);\n }\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;\n validTo?: string;\n }>[],\n ): Promise<Edge<E>[]> {\n if (items.length === 0) return [];\n\n const upsertAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<Edge<E>[]> => {\n const ids = items.map((item) => item.id);\n const existingMap = await getEdgeRowsByIds(target, graphId, ids);\n\n // Bucket items into creates and updates\n const toCreate: { index: number; input: CreateEdgeInput }[] = [];\n const toUpdate: {\n index: number;\n input: EdgeUpdateInput;\n clearDeleted: boolean;\n }[] = [];\n\n let itemIndex = 0;\n for (const item of items) {\n const existing = existingMap.get(item.id);\n\n if (existing) {\n toUpdate.push({\n index: itemIndex,\n input: buildUpdateEdgeInput(item.id, item.props ?? {}, item),\n clearDeleted: existing.deleted_at !== undefined,\n });\n } else {\n toCreate.push({\n index: itemIndex,\n input: buildCreateEdgeInput(\n kind,\n item.from,\n item.to,\n item.props ?? {},\n item,\n ),\n });\n }\n itemIndex++;\n }\n\n // Hookless batch create\n const results: Edge<E>[] = Array.from({ length: items.length });\n\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const created = await executeEdgeCreateBatch(createInputs, target);\n for (const [index, entry] of toCreate.entries()) {\n results[entry.index] = narrowEdge<E>(created[index]!);\n }\n }\n\n // Hookless individual updates (executeEdgeUpsertUpdate is already hookless)\n for (const entry of toUpdate) {\n const result = await executeEdgeUpsertUpdate(entry.input, target, {\n clearDeleted: entry.clearDeleted,\n });\n results[entry.index] = narrowEdge<E>(result);\n }\n\n return results;\n };\n\n const results =\n backend.capabilities.transactions && \"transaction\" in backend ?\n await backend.transaction(async (txBackend) => upsertAll(txBackend))\n : await upsertAll(backend);\n // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n // autocommit bulk write. Threshold-gated, and a no-op inside a caller\n // transaction (the hook is intentionally undefined there).\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\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;\n validTo?: string;\n }>[],\n ): Promise<void> {\n const batchInputs = mapBulkEdgeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => {\n await executeEdgeCreateNoReturnBatch(batchInputs, txBackend);\n });\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n return;\n }\n\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 const deleteAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n for (const id of ids) {\n await executeEdgeDelete(id, target);\n }\n };\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => deleteAll(txBackend));\n return;\n }\n await deleteAll(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 const getOrCreateOptions: {\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n } = {};\n if (options?.matchOn !== undefined)\n getOrCreateOptions.matchOn = options.matchOn as readonly string[];\n if (options?.ifExists !== undefined)\n getOrCreateOptions.ifExists = options.ifExists;\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 }>[],\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ): Promise<EdgeGetOrCreateByEndpointsResult<E>[]> {\n if (items.length === 0) return [];\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 }));\n\n const getOrCreateOptions: {\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n } = {};\n if (options?.matchOn !== undefined)\n getOrCreateOptions.matchOn = options.matchOn as readonly string[];\n if (options?.ifExists !== undefined)\n getOrCreateOptions.ifExists = options.ifExists;\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 if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) =>\n getOrCreateAll(txBackend),\n );\n }\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 {\n type GraphBackend,\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 { ConfigurationError } from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\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} from \"../types\";\nimport {\n resolveTemporalReadParams,\n type TemporalReadParams,\n} from \"./temporal-read-params\";\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/**\n * Config for creating a NodeCollection.\n */\nexport type NodeCollectionConfig = Readonly<{\n graphId: string;\n kind: string;\n backend: GraphBackend | TransactionBackend;\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 ) => Promise<readonly Node[]>;\n executeUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeUpsertUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeDelete: (\n kind: string,\n id: 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<{ id?: string; validFrom?: string; validTo?: string }>,\n): CreateNodeInput {\n const input: {\n kind: string;\n id?: string;\n props: Record<string, unknown>;\n validFrom?: string;\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?: Readonly<{ validTo?: string }>,\n): UpdateNodeInput {\n const input: {\n kind: string;\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n } = { kind, id, props };\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input as UpdateNodeInput;\n}\n\nfunction mapBulkNodeInputs(\n kind: string,\n items: readonly Readonly<{\n props: Record<string, unknown>;\n id?: string;\n validFrom?: string;\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 defaultTemporalMode,\n rowToNode,\n executeCreate: executeNodeCreate,\n executeCreateNoReturnBatch: executeNodeCreateNoReturnBatch,\n executeCreateBatch: executeNodeCreateBatch,\n executeUpdate: executeNodeUpdate,\n executeUpsertUpdate: executeNodeUpsertUpdate,\n executeDelete: executeNodeDelete,\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<{ id?: string; validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n return this.createFromRecord(props, options);\n },\n\n async createFromRecord(\n data: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\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(backend, graphId, kind, ids);\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?: Readonly<{ validTo?: string }>,\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 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?: Readonly<{ validFrom?: string; validTo?: string }>,\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?: Readonly<{ validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n const existing = await backend.getNode(graphId, kind, id);\n\n if (existing) {\n const clearDeleted = existing.deleted_at !== undefined;\n const result = await executeNodeUpdate(\n buildUpdateInput(kind, id, data, options),\n backend,\n { clearDeleted },\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;\n validTo?: string;\n }>[],\n ): Promise<Node<N>[]> {\n const batchInputs = mapBulkNodeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n const results = await backend.transaction(async (txBackend) =>\n executeNodeCreateBatch(batchInputs, txBackend),\n );\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowNodes<N>(results);\n }\n const results = await executeNodeCreateBatch(batchInputs, backend);\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowNodes<N>(results);\n },\n\n async bulkUpsertById(\n items: readonly Readonly<{\n id: string;\n props: z.input<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<Node<N>[]> {\n if (items.length === 0) return [];\n\n const upsertAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<Node<N>[]> => {\n const ids = items.map((item) => item.id);\n const existingMap = new Map<\n string,\n {\n deleted_at: string | undefined;\n }\n >();\n\n if (target.getNodes === 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 target.getNodes(graphId, kind, ids);\n for (const row of rows) {\n existingMap.set(row.id, row);\n }\n }\n\n // Bucket items into creates and updates\n const toCreate: { index: number; input: CreateNodeInput }[] = [];\n const toUpdate: {\n index: number;\n input: UpdateNodeInput;\n clearDeleted: boolean;\n }[] = [];\n\n let itemIndex = 0;\n for (const item of items) {\n const existing = existingMap.get(item.id);\n\n if (existing) {\n toUpdate.push({\n index: itemIndex,\n input: buildUpdateInput(kind, item.id, item.props, item),\n clearDeleted: existing.deleted_at !== undefined,\n });\n } else {\n toCreate.push({\n index: itemIndex,\n input: buildCreateInput(kind, item.props, item),\n });\n }\n itemIndex++;\n }\n\n // Hookless batch create\n const results: Node<N>[] = Array.from({ length: items.length });\n\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const created = await executeNodeCreateBatch(createInputs, target);\n for (const [index, entry] of toCreate.entries()) {\n results[entry.index] = narrowNode<N>(created[index]!);\n }\n }\n\n // Hookless individual updates\n for (const entry of toUpdate) {\n const result = await executeNodeUpsertUpdate(entry.input, target, {\n clearDeleted: entry.clearDeleted,\n });\n results[entry.index] = narrowNode<N>(result);\n }\n\n return results;\n };\n\n const results =\n backend.capabilities.transactions && \"transaction\" in backend ?\n await backend.transaction(async (txBackend) => upsertAll(txBackend))\n : await upsertAll(backend);\n // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n // autocommit bulk write. Threshold-gated, and a no-op inside a caller\n // transaction (the hook is intentionally undefined there).\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return results;\n },\n\n async bulkInsert(\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<void> {\n const batchInputs = mapBulkNodeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => {\n await executeNodeCreateNoReturnBatch(batchInputs, txBackend);\n });\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n return;\n }\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 const deleteAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n for (const id of ids) {\n await executeNodeDelete(kind, id, target);\n }\n };\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => deleteAll(txBackend));\n return;\n }\n await deleteAll(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 (backend.capabilities.transactions && \"transaction\" in backend) {\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 { 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 KindRegistry } from \"../registry/kind-registry\";\nimport { createEdgeCollection, createNodeCollection } from \"./collections\";\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 type UpdateNodeInput,\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 ) => Promise<readonly Node[]>;\n executeCreateNoReturnBatch: (\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeUpsertUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeDelete: (\n kind: string,\n id: 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 props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeUpsertUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Edge>;\n executeDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\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 }>,\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 }>[],\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 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 ...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 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 ...operations,\n });\n collectionCache.set(kind, collection);\n return collection;\n },\n });\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 {\n type Cardinality,\n type Collation,\n type EdgeType,\n type EndpointExistence,\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 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: reg.to.map((entry) => (entry as AllNodeTypes<G> & NodeType).kind),\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 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 the materialize-* verbs (`materializeIndexes`\n * and `materializeRemovals`) and `Store.removeKinds`. Each verb owns a\n * per-deployment status table (`typegraph_index_materializations`,\n * `typegraph_kind_removals`) and bootstraps it lazily; this module\n * centralizes the bootstrap dispatch + parallel orchestration shape so\n * the runners stay thin.\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 race —\n * concurrent `CREATE TABLE IF NOT EXISTS` for one specific table is\n * well-behaved on Postgres.\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 * Best-effort vs strict orchestration for materialization runners.\n * `stopOnError === true` runs sequentially and short-circuits on the\n * first `failed` entry (mirrors typical schema-migration safety\n * semantics); the default best-effort path runs `runOne` over `items`\n * concurrently. Custom orchestrators (e.g. `materializeIndexes`'s\n * per-relation bucketing) bypass this helper and assemble their own\n * Promise topology.\n */\nexport async function runMaterialization<\n TInput,\n TEntry extends { status: string },\n>(\n items: readonly TInput[],\n options: Readonly<{ stopOnError?: boolean }>,\n runOne: (item: TInput) => 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 return Promise.all(items.map((item) => runOne(item)));\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 dropInvalidIndexLeftover).\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 */\n\nimport { sql } from \"drizzle-orm\";\n\nimport { type RawBackend } from \"../backend/branded\";\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 type IndexDeclaration,\n type RelationalIndexDeclaration,\n type VectorIndexDeclaration,\n} from \"../indexes/types\";\nimport { sqlValueList } from \"../query/compiler/predicate-utils\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { sortedReplacer } from \"../schema/canonical\";\nimport { serializeIndexDeclaration } from \"../schema/serializer\";\nimport { nowIso } from \"../utils/date\";\nimport { sha256Hex } from \"../utils/hash\";\nimport { ensureFocusedStatusTable } 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;\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\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\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 if (backend.executeDdl === undefined) {\n throw new ConfigurationError(\n \"store.materializeIndexes() requires a backend with `executeDdl` \" +\n \"support. The bundled SQLite and Postgres backends provide it; \" +\n \"a custom backend without `executeDdl` cannot run index DDL.\",\n { code: \"MATERIALIZE_BACKEND_UNSUPPORTED\" },\n );\n }\n if (\n backend.getIndexMaterialization === undefined ||\n backend.recordIndexMaterialization === undefined\n ) {\n throw new ConfigurationError(\n \"store.materializeIndexes() requires a backend with index \" +\n \"materialization status primitives. The bundled SQLite and \" +\n \"Postgres backends provide them; a custom backend must implement \" +\n \"`getIndexMaterialization` and `recordIndexMaterialization`.\",\n { code: \"MATERIALIZE_BACKEND_UNSUPPORTED\" },\n );\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 dialect = backend.dialect;\n const tableNames = backend.tableNames;\n const ddlOptions = {\n ifNotExists: true,\n concurrent: dialect === \"postgres\",\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 backend,\n relationalPhysicalNames,\n );\n\n const materializeEntry = (\n declaration: IndexDeclaration,\n ): Promise<MaterializeIndexesEntry> =>\n declaration.entity === \"vector\" ?\n materializeVectorIndex(\n declaration,\n backend,\n graphId,\n schemaVersion,\n existingByStatusKey,\n invalidLeftovers,\n )\n : materializeRelationalIndex(\n declaration,\n backend,\n dialect,\n ddlOptions,\n graphId,\n schemaVersion,\n existingByStatusKey,\n invalidLeftovers,\n );\n\n if (options.stopOnError === true) {\n const results: MaterializeIndexesEntry[] = [];\n for (const declaration of candidates) {\n const entry = await materializeEntry(declaration);\n results.push(entry);\n if (entry.status === \"failed\") break;\n }\n await refreshStatisticsAfterCreation(\n backend,\n results,\n options,\n ddlOptions.concurrent,\n );\n return { results };\n }\n\n // Postgres restricts `CREATE INDEX CONCURRENTLY` to one in-flight\n // build per relation, so we group declarations by target table and\n // run each group sequentially while running the groups 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 buckets = new Map<IndexEntity, IndexDeclaration[]>();\n for (const declaration of candidates) {\n const key = parallelBucketKey(declaration);\n const list = buckets.get(key);\n if (list === undefined) buckets.set(key, [declaration]);\n else list.push(declaration);\n }\n\n const bucketResults = await Promise.all(\n [...buckets.values()].map(async (group) => {\n const out: MaterializeIndexesEntry[] = [];\n for (const declaration of group) {\n out.push(await materializeEntry(declaration));\n }\n return out;\n }),\n );\n\n // Flatten in declaration order so callers see a stable result shape\n // regardless of how the buckets resolved.\n const byDeclaration = new Map<IndexDeclaration, MaterializeIndexesEntry>();\n let bucketIndex = 0;\n for (const group of buckets.values()) {\n const entries = bucketResults[bucketIndex]!;\n for (const [declarationIndex, declaration] of group.entries()) {\n byDeclaration.set(declaration, entries[declarationIndex]!);\n }\n bucketIndex += 1;\n }\n const results = candidates.map((declaration) =>\n byDeclaration.get(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 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 (declaration.method !== undefined && dialect !== \"postgres\") {\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, 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 await backend.executeDdl!(\"CREATE EXTENSION IF NOT EXISTS pg_trgm;\");\n }\n await backend.executeDdl!(ddl);\n },\n existingByStatusKey,\n invalidLeftovers,\n });\n}\n\nasync function materializeVectorIndex(\n declaration: VectorIndexDeclaration,\n backend: GraphBackend,\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: backend.dialect === \"postgres\",\n };\n return materializeOne(declaration, backend, 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: () => backend.createVectorIndex!(params),\n existingByStatusKey,\n invalidLeftovers,\n });\n}\n\n/**\n * Shared \"check existing → run → record\" frame for both relational and\n * vector materialization. Both 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: IndexDeclaration,\n backend: GraphBackend,\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 invalidLeftovers: ReadonlySet<string>;\n }>,\n): Promise<MaterializeIndexesEntry> {\n // Narrowed by callsite — guaranteed defined when this is reached\n // (validated in `materializeIndexes`).\n const recordIndexMaterialization = backend.recordIndexMaterialization!;\n\n const { statusKey, signature, driftLabel, run, existingByStatusKey } = action;\n const statusOverride =\n statusKey === declaration.name ? undefined : { statusName: statusKey };\n\n // Pre-claim leftover check reads the bulk-preloaded set (one `pg_index`\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 isInvalidLeftover: (physicalIndexName) =>\n action.invalidLeftovers.has(physicalIndexName),\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(declaration, backend, graphId, schemaVersion, {\n statusKey,\n signature,\n driftLabel,\n run,\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: IndexDeclaration,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n action: Readonly<{\n statusKey: string;\n signature: string;\n driftLabel: string;\n /**\n * Whether a physical index with this name exists but is INVALID. The\n * pre-claim caller reads a bulk-preloaded set (one query for all\n * candidates); the post-claim caller reads fresh (the preload is stale\n * after waiting on another builder's claim).\n */\n isInvalidLeftover: (\n physicalIndexName: string,\n ) => boolean | Promise<boolean>;\n }>,\n): Promise<MaterializeIndexesEntry | undefined> {\n if (existing?.materializedAt === undefined) return undefined;\n const { statusKey, signature, driftLabel, isInvalidLeftover } = action;\n if (existing.signature === signature) {\n // A recorded success is only trustworthy while the physical index is\n // valid: 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), leaving a poisoned status row. Fall through to\n // the build path — under the claim it drops the leftover and rebuilds.\n if (\n declaration.entity !== \"vector\" &&\n hasIndexBuildClaimProtocol(backend) &&\n (await isInvalidLeftover(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 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 * 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: IndexDeclaration,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n action: Readonly<{\n statusKey: string;\n signature: string;\n driftLabel: string;\n run: () => Promise<void>;\n }>,\n): Promise<MaterializeIndexesEntry> {\n const { statusKey, signature, driftLabel, run } = action;\n const statusOverride =\n statusKey === declaration.name ? undefined : { statusName: statusKey };\n const recordIndexMaterialization = backend.recordIndexMaterialization!;\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 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 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 backend.getIndexMaterialization!(statusKey);\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 isInvalidLeftover: (physicalIndexName) =>\n hasInvalidIndexLeftover(backend, physicalIndexName),\n },\n );\n if (settled !== undefined) return settled;\n\n if (declaration.entity !== \"vector\") {\n await dropInvalidIndexLeftover(backend, declaration.name);\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 =\n 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 } 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 backend.releaseIndexMaterializationClaim!({\n indexName: statusKey,\n token,\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 non-Postgres dialects.\n */\nasync function hasInvalidIndexLeftover(\n backend: GraphBackend,\n physicalIndexName: string,\n): Promise<boolean> {\n if (backend.dialect !== \"postgres\") return false;\n const rows = await backend.execute<{ invalid: boolean }>(\n asCompiledRowsSql(sql`\n SELECT NOT i.indisvalid AS invalid\n FROM pg_class c\n JOIN pg_index i ON i.indexrelid = c.oid\n WHERE c.relname = ${physicalIndexName}\n `),\n );\n return rows[0]?.invalid === true;\n}\n\n/**\n * Bulk variant of `hasInvalidIndexLeftover`: the set of INVALID leftover\n * index names among `physicalIndexNames`, resolved in ONE `pg_index` query.\n * Empty set on non-Postgres dialects or 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 `pg_index` 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 backend: GraphBackend,\n physicalIndexNames: readonly string[],\n): Promise<ReadonlySet<string>> {\n if (backend.dialect !== \"postgres\" || physicalIndexNames.length === 0) {\n return new Set();\n }\n const rows = await backend.execute<{ name: string }>(\n asCompiledRowsSql(sql`\n SELECT c.relname AS name\n FROM pg_class c\n JOIN pg_index i ON i.indexrelid = c.oid\n WHERE c.relname IN (${sqlValueList(physicalIndexNames)})\n AND NOT i.indisvalid\n `),\n );\n return new Set(rows.map((row) => row.name));\n}\n\n/**\n * Self-heals an interrupted CONCURRENTLY build: a crashed CIC leaves an\n * INVALID index behind, and a later `CREATE INDEX CONCURRENTLY IF NOT\n * EXISTS` would see the name and silently no-op — recording success over an\n * index the planner will never use. Detect via `hasInvalidIndexLeftover` and\n * drop (also CONCURRENTLY — same no-transaction rule). Valid indexes are\n * never touched.\n */\nasync function dropInvalidIndexLeftover(\n backend: GraphBackend,\n physicalIndexName: string,\n): Promise<void> {\n if (backend.executeDdl === undefined) return;\n if (!(await hasInvalidIndexLeftover(backend, physicalIndexName))) return;\n const quoted = `\"${physicalIndexName.replaceAll('\"', '\"\"')}\"`;\n await backend.executeDdl(`DROP INDEX CONCURRENTLY IF EXISTS ${quoted};`);\n}\n\nfunction entry(\n declaration: IndexDeclaration,\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 = 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(statusKeys[index]!, row);\n }\n return map;\n}\n\nfunction buildAttempt(\n args: Readonly<{\n declaration: IndexDeclaration;\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 * 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, data work is bounded by row count and\n * deferrable / parallelizable.\n */\nimport { sql } from \"drizzle-orm\";\n\nimport { type RawBackend } from \"../backend/branded\";\nimport {\n type GraphBackend,\n type KindRemovalRow,\n type RecordKindRemovalParams,\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 { asCompiledStatementSql } from \"../query/sql-intent\";\nimport { parseSerializedSchema } from \"../schema/manager\";\nimport { nowIso } from \"../utils/date\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport {\n ensureFocusedStatusTable,\n runMaterialization,\n} 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\nexport type MaterializeRemovalsEntry = Readonly<{\n kind: string;\n entity: KindEntity;\n status: \"removed\" | \"failed\";\n error?: Error;\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 fulltextTable: string;\n uniquesTable: 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.executeDdl === undefined ||\n backend.recordKindRemoval === undefined ||\n backend.getPendingKindRemovals === undefined\n ) {\n throw new ConfigurationError(\n \"store.materializeRemovals() requires a backend with kind-removal \" +\n \"primitives (executeDdl, 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 const reclaimedVectorFields = await reclaimRemovedVectorFieldTables(context);\n\n const pending = await backend.getPendingKindRemovals(graphId);\n\n const kindFilter =\n options.kinds === undefined ? undefined : new Set(options.kinds);\n const candidates = pending.filter((row) =>\n kindFilter === undefined ? true : kindFilter.has(row.kindName),\n );\n\n if (candidates.length === 0) return { results: [], reclaimedVectorFields };\n\n const tableNames = backend.tableNames;\n const nodesTable = tableNames?.nodes ?? \"typegraph_nodes\";\n const edgesTable = tableNames?.edges ?? \"typegraph_edges\";\n const fulltextTable = tableNames?.fulltext ?? \"typegraph_node_fulltext\";\n const uniquesTable = tableNames?.uniques ?? \"typegraph_node_uniques\";\n\n const captureRecordedRemovals = context.captureRecordedRemovals === true;\n const ctx = {\n backend,\n graphId,\n nodesTable,\n edgesTable,\n fulltextTable,\n uniquesTable,\n captureRecordedRemovals,\n recordedSchema:\n captureRecordedRemovals ?\n (context.recordedSchema ?? createSqlSchema(backend.tableNames))\n : undefined,\n } as const;\n\n // Each kind targets a disjoint row set (DELETEs filtered by kindName),\n // so the default best-effort path runs them concurrently — Postgres\n // parallelizes round-trips across pool connections, SQLite serializes\n // writes at the engine level either way. `stopOnError` honors strict\n // sequential semantics; the first failure short-circuits the rest.\n return {\n results: await runMaterialization(candidates, options, (removal) =>\n materializeOne(removal, ctx),\n ),\n reclaimedVectorFields,\n };\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 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 (kindName in currentEntries) 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\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 = ctx.backend.recordKindRemoval!;\n try {\n await closeRecordedAndDeleteLiveRows(ctx, row);\n await Promise.all(buildEmbeddingTableCleanup(ctx, row));\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 no-op close when\n * recorded-removal capture is off.\n */\nasync function closeRecordedAndDeleteLiveRows(\n ctx: MaterializeOneContext,\n row: KindRemovalRow,\n): Promise<void> {\n const deleteStatements = buildRemovedKindLiveDeleteStatements(ctx, row);\n if (!ctx.captureRecordedRemovals || ctx.recordedSchema === undefined) {\n await executeDeleteStatements(ctx.backend, deleteStatements);\n return;\n }\n\n const recordedSchema = ctx.recordedSchema;\n try {\n await ctx.backend.transaction(async (target) => {\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 } catch (error) {\n if (!isMissingTableError(error)) throw error;\n await executeDeleteStatements(ctx.backend, deleteStatements);\n }\n}\n\nfunction buildRemovedKindLiveDeleteStatements(\n ctx: MaterializeOneContext,\n row: KindRemovalRow,\n): readonly string[] {\n const graphLit = literal(ctx.graphId);\n const kindLit = literal(row.kindName);\n if (row.entity === \"node\") {\n return [\n `DELETE FROM ${quote(ctx.nodesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND (from_kind = ${kindLit} OR to_kind = ${kindLit})`,\n `DELETE FROM ${quote(ctx.fulltextTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n `DELETE FROM ${quote(ctx.uniquesTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n ];\n }\n return [\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n ];\n}\n\nasync function executeDeleteStatements(\n target: GraphBackend | TransactionBackend,\n statements: readonly string[],\n): Promise<void> {\n if (target.executeStatement !== undefined) {\n await Promise.all(\n statements.map((statement) =>\n target.executeStatement!(asCompiledStatementSql(sql.raw(statement))),\n ),\n );\n return;\n }\n\n if (target.executeDdl === undefined) {\n throw new ConfigurationError(\n \"store.materializeRemovals() requires a backend that can execute cleanup statements.\",\n { code: \"MATERIALIZE_REMOVALS_BACKEND_UNSUPPORTED\" },\n );\n }\n await Promise.all(\n statements.map((statement) => target.executeDdl!(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 * Returned as a single combined promise so the caller can issue it\n * alongside the other disjoint DELETEs.\n */\nfunction buildEmbeddingTableCleanup(\n ctx: Readonly<{\n backend: GraphBackend;\n graphId: string;\n }>,\n row: KindRemovalRow,\n): readonly Promise<void>[] {\n const vectorStrategy = ctx.backend.vectorStrategy;\n if (vectorStrategy === undefined) return [];\n\n const executeDdl = ctx.backend.executeDdl!;\n const cleanup = (async () => {\n const slots = await resolveRemovedKindEmbeddingSlots(ctx.backend, row);\n await Promise.all(\n slots.map((slot) =>\n dropVectorSlotStorage(vectorStrategy, executeDdl, slot),\n ),\n );\n })();\n return [cleanup];\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. Runs as autocommit statements, so swallowing a missing-table\n * failure can't poison a sibling drop. Shared by removed-kind cleanup and\n * removed-field reclamation so both reclaim storage 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,\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\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 * Using the active schema as the \"still declared\" source of truth makes\n * remove-then-re-add safe — a re-added field is current, so it is never\n * dropped. `buildDropStorage` emits `DROP ... IF EXISTS`, so the pass is\n * idempotent and a never-materialized field is a clean no-op; deriving from\n * full history each call also reclaims tables orphaned before this shipped.\n *\n * Backends without a vector strategy or `executeDdl` have no per-field tables\n * to reclaim and yield an empty result.\n */\nasync function reclaimRemovedVectorFieldTables(\n context: MaterializeRemovalsContext,\n): Promise<readonly ReclaimedVectorFieldEntry[]> {\n const { backend, graphId } = context;\n const vectorStrategy = backend.vectorStrategy;\n const executeDdl = backend.executeDdl;\n if (vectorStrategy === undefined || executeDdl === undefined) return [];\n\n const activeRow = await backend.getActiveSchema(graphId);\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 = new Set<string>();\n for (const declaration of activeSchema.indexes ?? []) {\n if (declaration.entity === \"vector\") {\n activeVectorFields.add(\n vectorFieldKey(declaration.kind, declaration.fieldPath),\n );\n }\n }\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 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 for (const field of orphans) {\n // dropVectorSlotStorage swallows the missing-table case (a never-\n // materialized field has nothing to reclaim), so reaching the catch means\n // a genuine failure.\n try {\n await dropVectorSlotStorage(vectorStrategy, executeDdl, field.slot);\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 (results.every((entry) => entry.status === \"reclaimed\")) {\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// `executeDdl` accepts a raw SQL string. The DELETE statements built\n// here are dialect-neutral (no SQLite/Postgres-specific syntax) and\n// use single-quote string literals for 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 * Edge Operations for Store\n *\n * Handles edge CRUD operations: create, update, delete.\n */\nimport {\n createBackendOverlay,\n type EdgeRow as BackendEdgeRow,\n type GraphBackend,\n type GraphReadBackend,\n type InsertEdgeParams,\n rowPropsToObject,\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 DatabaseOperationError,\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 { validateOptionalCanonicalIsoDate } from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport {\n checkCardinalityConstraint,\n type ConstraintContext,\n} from \"../constraints\";\nimport {\n edgeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"../insert-dispatch\";\nimport { 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 runHookedWriteOperation,\n runInWriteTransaction,\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 historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n revisionSchema: SqlSchema;\n registry: KindRegistry;\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 ) => Promise<T>;\n}>;\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\nfunction getEdgeRegistration<G extends GraphDef>(graph: G, kind: string) {\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\nfunction buildEdgeEndpointCacheKey(\n graphId: string,\n kind: string,\n id: string,\n): string {\n return `${graphId}\\u0000${kind}\\u0000${id}`;\n}\n\nfunction buildEdgeFromCacheKey(\n graphId: string,\n edgeKind: string,\n fromKind: string,\n fromId: string,\n): string {\n return `${graphId}\\u0000${edgeKind}\\u0000${fromKind}\\u0000${fromId}`;\n}\n\nfunction buildEdgeBetweenCacheKey(\n graphId: string,\n edgeKind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n): string {\n return `${graphId}\\u0000${edgeKind}\\u0000${fromKind}\\u0000${fromId}\\u0000${toKind}\\u0000${toId}`;\n}\n\nfunction buildCountEdgesFromCacheKey(\n params: Parameters<GraphBackend[\"countEdgesFrom\"]>[0],\n): string {\n const activeOnly = params.activeOnly === true ? \"1\" : \"0\";\n return `${params.graphId}\\u0000${params.edgeKind}\\u0000${params.fromKind}\\u0000${params.fromId}\\u0000${activeOnly}`;\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 | undefined,\n validTo: string | undefined,\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;\n validTo?: 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 return insertParams;\n}\n\nfunction incrementPendingCount(counts: Map<string, number>, key: string): void {\n const previous = counts.get(key) ?? 0;\n counts.set(key, previous + 1);\n}\n\nfunction createEdgeBatchValidationBackend(\n backend: GraphBackend | TransactionBackend,\n): Readonly<{\n backend: GraphBackend | TransactionBackend;\n registerPendingEdgeForCardinality: (\n insertParams: InsertEdgeParams,\n cardinality: Cardinality,\n ) => void;\n seedEndpointRow: (\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ) => void;\n}> {\n const endpointCache = new Map<\n string,\n Awaited<ReturnType<GraphBackend[\"getNode\"]>>\n >();\n const countEdgesFromCache = new Map<string, number>();\n const edgeExistsCache = new Map<string, boolean>();\n const pendingOneCounts = new Map<string, number>();\n const pendingOneActiveCounts = new Map<string, number>();\n const pendingUniquePairs = new Set<string>();\n\n async function getNodeCached(\n graphId: string,\n kind: string,\n id: string,\n ): Promise<Awaited<ReturnType<GraphBackend[\"getNode\"]>>> {\n const cacheKey = buildEdgeEndpointCacheKey(graphId, kind, id);\n if (endpointCache.has(cacheKey)) {\n return endpointCache.get(cacheKey);\n }\n const node = await backend.getNode(graphId, kind, id);\n endpointCache.set(cacheKey, node);\n return node;\n }\n\n // Lets batch preparation prime the endpoint cache from one getNodes\n // round trip per (kind) instead of a per-edge getNode probe for each\n // from/to endpoint — mirrors seedNodeRow in createNodeBatchValidationBackend.\n // Seeding an absent result (`undefined`) is meaningful — it marks the key\n // as known-missing so the per-edge check skips the backend read. An\n // earlier lookup or seed always wins; seeding never overwrites.\n function seedEndpointRow(\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ): void {\n const cacheKey = buildEdgeEndpointCacheKey(graphId, kind, id);\n if (endpointCache.has(cacheKey)) return;\n endpointCache.set(cacheKey, row);\n }\n\n async function countEdgesFromCached(\n params: Parameters<GraphBackend[\"countEdgesFrom\"]>[0],\n ): Promise<number> {\n const cacheKey = buildCountEdgesFromCacheKey(params);\n let baseCount = countEdgesFromCache.get(cacheKey);\n if (baseCount === undefined) {\n baseCount = await backend.countEdgesFrom(params);\n countEdgesFromCache.set(cacheKey, baseCount);\n }\n const pendingKey = buildEdgeFromCacheKey(\n params.graphId,\n params.edgeKind,\n params.fromKind,\n params.fromId,\n );\n const pendingCount =\n params.activeOnly === true ?\n (pendingOneActiveCounts.get(pendingKey) ?? 0)\n : (pendingOneCounts.get(pendingKey) ?? 0);\n return baseCount + pendingCount;\n }\n\n async function edgeExistsBetweenCached(\n params: Parameters<GraphBackend[\"edgeExistsBetween\"]>[0],\n ): Promise<boolean> {\n const cacheKey = buildEdgeBetweenCacheKey(\n params.graphId,\n params.edgeKind,\n params.fromKind,\n params.fromId,\n params.toKind,\n params.toId,\n );\n if (pendingUniquePairs.has(cacheKey)) {\n return true;\n }\n if (edgeExistsCache.has(cacheKey)) {\n return edgeExistsCache.get(cacheKey) ?? false;\n }\n const exists = await backend.edgeExistsBetween(params);\n edgeExistsCache.set(cacheKey, exists);\n return exists;\n }\n\n function registerPendingEdgeForCardinality(\n insertParams: InsertEdgeParams,\n cardinality: Cardinality,\n ): void {\n const fromCacheKey = buildEdgeFromCacheKey(\n insertParams.graphId,\n insertParams.kind,\n insertParams.fromKind,\n insertParams.fromId,\n );\n if (cardinality === \"one\") {\n incrementPendingCount(pendingOneCounts, fromCacheKey);\n return;\n }\n if (cardinality === \"oneActive\") {\n if (insertParams.validTo === undefined) {\n incrementPendingCount(pendingOneActiveCounts, fromCacheKey);\n }\n return;\n }\n if (cardinality === \"unique\") {\n const uniqueCacheKey = buildEdgeBetweenCacheKey(\n insertParams.graphId,\n insertParams.kind,\n insertParams.fromKind,\n insertParams.fromId,\n insertParams.toKind,\n insertParams.toId,\n );\n pendingUniquePairs.add(uniqueCacheKey);\n }\n }\n\n const validationBackend = createBackendOverlay(backend, {\n getNode: getNodeCached,\n countEdgesFrom: countEdgesFromCached,\n edgeExistsBetween: edgeExistsBetweenCached,\n } satisfies Partial<GraphBackend | TransactionBackend>);\n\n return {\n backend: validationBackend,\n registerPendingEdgeForCardinality,\n seedEndpointRow,\n };\n}\n\nasync function validateAndPrepareEdgeCreate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: CreateEdgeInput,\n id: string,\n backend: GraphBackend | TransactionBackend,\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\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 // Validate source node exists\n const fromNode = await backend.getNode(ctx.graphId, fromKind, input.fromId);\n if (!fromNode || fromNode.deleted_at) {\n throw new EndpointNotFoundError({\n edgeKind: kind,\n endpoint: \"from\",\n nodeKind: fromKind,\n nodeId: input.fromId,\n });\n }\n\n // Validate target node exists\n const toNode = await backend.getNode(ctx.graphId, toKind, input.toId);\n if (!toNode || toNode.deleted_at) {\n throw new EndpointNotFoundError({\n edgeKind: kind,\n endpoint: \"to\",\n nodeKind: toKind,\n nodeId: input.toId,\n });\n }\n\n // Validate props with full context\n const validatedProps = validateEdgeProps(edgeKind.schema, input.props, {\n kind,\n operation: \"create\",\n });\n\n // Validate temporal fields\n const validFrom = validateOptionalCanonicalIsoDate(\n input.validFrom,\n \"validFrom\",\n );\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"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 await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n fromKind,\n input.fromId,\n toKind,\n input.toId,\n validTo,\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 ),\n };\n}\n\n// ============================================================\n// Edge Operations\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<{ returnRow?: boolean }>,\n): Promise<Edge | undefined> {\n const kind = input.kind;\n const id = input.id ?? generateId();\n const opContext = ctx.createOperationContext(\"create\", \"edge\", kind, id);\n const shouldReturnRow = options?.returnRow ?? true;\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n const prepared = await validateAndPrepareEdgeCreate(ctx, input, id, target);\n\n let row: BackendEdgeRow | undefined;\n if (shouldReturnRow) {\n row = await target.insertEdge(prepared.insertParams);\n } else {\n await runInsertNoReturn(\n edgeInsertDispatch(target),\n prepared.insertParams,\n );\n }\n\n if (row === undefined) return;\n return rowToEdge(row);\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) {\n throw new DatabaseOperationError(\n \"Edge create failed: expected created edge row\",\n { operation: \"insert\", entity: \"edge\" },\n );\n }\n return result;\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 */\nasync function primeEdgeBatchValidationCache<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n seedEndpointRow: (\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ) => void,\n): Promise<void> {\n if (backend.getNodes === undefined) return;\n\n const idsByKind = new Map<string, Set<string>>();\n const addEndpoint = (kind: string, id: string): void => {\n const ids = idsByKind.get(kind) ?? new Set<string>();\n ids.add(id);\n idsByKind.set(kind, ids);\n };\n for (const input of inputs) {\n addEndpoint(input.fromKind, input.fromId);\n addEndpoint(input.toKind, input.toId);\n }\n\n for (const [kind, ids] of idsByKind) {\n const orderedIds = [...ids];\n const rows = await backend.getNodes(ctx.graphId, 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: GraphBackend | TransactionBackend,\n): Promise<{\n preparedCreates: EdgeCreatePrepared[];\n batchInsertParams: InsertEdgeParams[];\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 const batchInsertParams = preparedCreates.map(\n (prepared) => prepared.insertParams,\n );\n\n return { preparedCreates, batchInsertParams };\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 await runInWriteTransaction(ctx, backend, async (target) => {\n const { batchInsertParams } = await prepareEdgeBatchCreates(\n ctx,\n inputs,\n target,\n );\n await runInsertBatch(edgeInsertDispatch(target), batchInsertParams);\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 return runInWriteTransaction(ctx, backend, async (target) => {\n const { batchInsertParams } = await prepareEdgeBatchCreates(\n ctx,\n inputs,\n target,\n );\n\n const rows = await runInsertBatchReturning(\n edgeInsertDispatch(target),\n batchInsertParams,\n );\n\n return rows.map((row) => rowToEdge(row));\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: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n target: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Edge> {\n const id = input.id;\n\n const existing = await target.getEdge(ctx.graphId, id);\n if (!existing || (!options?.clearDeleted && existing.deleted_at)) {\n throw new EdgeNotFoundError(\"unknown\", id);\n }\n\n const registration = getEdgeRegistration(ctx.graph, existing.kind);\n const edgeKind = registration.type;\n\n const existingProps = rowPropsToObject(existing.props);\n const mergedProps = { ...existingProps, ...input.props };\n\n const validatedProps = validateEdgeProps(edgeKind.schema, mergedProps, {\n kind: existing.kind,\n operation: \"update\",\n id,\n });\n\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n const updateParams: {\n graphId: string;\n id: string;\n props: Record<string, unknown>;\n validTo?: string;\n clearDeleted?: boolean;\n } = {\n graphId: ctx.graphId,\n id,\n props: validatedProps,\n };\n if (validTo !== undefined) updateParams.validTo = validTo;\n if (options?.clearDeleted) updateParams.clearDeleted = true;\n\n const row = await target.updateEdge(updateParams);\n\n return rowToEdge(row);\n}\n\n/**\n * Executes an edge update operation.\n */\nexport async function executeEdgeUpdate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n): Promise<Edge> {\n const id = input.id;\n\n // Read outside the transaction: the hook context needs the edge kind, and\n // hooks must WRAP the transaction (matching node operations and edge\n // create) so onOperationEnd reports success only after COMMIT — a hook\n // that fires inside the transaction would report success for a write that\n // a failed commit then rolls back. An absent edge also never opens an empty\n // transaction. The body re-reads inside the transaction, so a concurrent\n // delete between this gate 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(\"unknown\", id);\n }\n\n const opContext = ctx.createOperationContext(\"update\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, (target) =>\n performEdgeUpdate(ctx, input, target),\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: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Edge> {\n return runInWriteTransaction(ctx, backend, (target) =>\n performEdgeUpdate(ctx, input, target, options),\n );\n}\n\n/**\n * Executes an edge delete operation.\n */\nexport async function executeEdgeDelete<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside the transaction so an absent/tombstoned edge never opens an\n // empty one; the gate row also supplies the kind for the hook context,\n // because hooks must WRAP the transaction (matching node operations and\n // edge create) so onOperationEnd reports success only after COMMIT.\n const gate = await backend.getEdge(ctx.graphId, id);\n if (!gate || gate.deleted_at) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n // No in-transaction preflight: the tombstone UPDATE is guarded by\n // `deleted_at IS NULL`, so a concurrent delete between the gate and\n // the write lock is a 0-row no-op — the statement itself is the\n // concurrency-correct check, and nothing here consumes the row.\n await target.deleteEdge({\n graphId: ctx.graphId,\n id,\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 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\n const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n // No in-transaction preflight: DELETE by primary key is idempotent\n // (0 rows when concurrently removed) and nothing here consumes the\n // row.\n await target.hardDeleteEdge({\n graphId: ctx.graphId,\n id,\n });\n });\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\n// Delimiters for composite match keys\nconst RECORD_SEP = \"\\u001E\";\nconst UNIT_SEP = \"\\u001F\";\nconst UNDEFINED_SENTINEL = \"\\u001D\";\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) => !(field in shape));\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/**\n * Serializes a value for composite key construction.\n * Sorts object keys for deterministic ordering of nested values.\n */\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return UNDEFINED_SENTINEL;\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const sorted = Object.keys(value).toSorted();\n const entries = sorted.map(\n (key) =>\n `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`,\n );\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * Builds a deterministic composite key for edge matching.\n *\n * Format: `fromKind\\u001EfromId\\u001EtoKind\\u001EtoId[\\u001Efield\\u001Fvalue]*`\n */\nfunction buildEdgeCompositeKey(\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n matchOn: readonly string[],\n): string {\n const endpointPart = `${fromKind}${RECORD_SEP}${fromId}${RECORD_SEP}${toKind}${RECORD_SEP}${toId}`;\n if (matchOn.length === 0) return endpointPart;\n\n const sortedFields = [...matchOn].toSorted();\n const propertyParts = sortedFields.map(\n (field) =>\n `${RECORD_SEP}${field}${UNIT_SEP}${stableStringify(props[field])}`,\n );\n return endpointPart + propertyParts.join(\"\");\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 `${fromKind}${RECORD_SEP}${fromId}${RECORD_SEP}${toKind}${RECORD_SEP}${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 stableStringify(rowProps[field]) ===\n stableStringify(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/**\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 props = 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(candidateRows[0]!);\n\n const { liveRow } = findMatchingEdge(candidateRows, matchOn, props);\n return liveRow === undefined ? undefined : rowToEdge(liveRow);\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 }>,\n): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>> {\n const ifExists = options?.ifExists ?? \"return\";\n const matchOn = options?.matchOn ?? [];\n\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n\n // Validate props\n const validatedProps = validateEdgeProps(edgeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n // Validate matchOn fields\n validateMatchOnFields(edgeKind.schema, matchOn, kind);\n\n // Probe outside the transaction: with ifExists \"return\", the common found\n // path performs no write, so it must not pay for a write transaction\n // (BEGIN IMMEDIATE on SQLite, the per-graph advisory lock under history).\n // The transactional body re-queries, so a concurrent create between this\n // probe and the write lock is still handled correctly.\n if (ifExists === \"return\") {\n const probeRows = await backend.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n excludeDeleted: false,\n temporalMode: \"includeTombstones\",\n });\n const { liveRow: probedLiveRow } = findMatchingEdge(\n probeRows,\n matchOn,\n validatedProps,\n );\n if (probedLiveRow !== undefined) {\n return { edge: rowToEdge(probedLiveRow), action: \"found\" };\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 // A concurrent create that wins between the lookup and the write surfaces\n // as a cardinality conflict and is converged by one retry of the lookup.\n async function attempt(): Promise<\n Readonly<{ edge: Edge; action: GetOrCreateAction }>\n > {\n // Query all edges of this kind between (from, to) including tombstones\n const candidateRows = await backend.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n excludeDeleted: false,\n temporalMode: \"includeTombstones\",\n });\n\n const { liveRow, deletedRow } = findMatchingEdge(\n candidateRows,\n matchOn,\n validatedProps,\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 };\n const edge = await executeEdgeCreate(ctx, input, backend);\n return { edge, action: \"created\" };\n }\n\n // Live match found\n if (liveRow !== undefined) {\n if (ifExists === \"return\") {\n return { edge: rowToEdge(liveRow), action: \"found\" };\n }\n // ifExists === \"update\"\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: liveRow.id, props: validatedProps },\n backend,\n );\n return { edge, action: \"updated\" };\n }\n\n // Deleted match only → check cardinality before resurrect\n const cardinality = registration.cardinality ?? \"many\";\n if (deletedRow === undefined) {\n throw new Error(\"Expected deletedRow to be defined\");\n }\n const matchedDeletedRow = deletedRow;\n const effectiveValidTo = matchedDeletedRow.valid_to;\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n fromKind,\n fromId,\n toKind,\n toId,\n effectiveValidTo,\n );\n\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: matchedDeletedRow.id, props: validatedProps },\n backend,\n { clearDeleted: true },\n );\n return { edge, action: \"resurrected\" };\n }\n\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof CardinalityError)) throw error;\n return attempt();\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 }>[],\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 const matchOn = options?.matchOn ?? [];\n\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n const cardinality = registration.cardinality ?? \"many\";\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 compositeKey: string;\n endpointKey: string;\n }[] = [];\n\n for (const item of items) {\n const validatedProps = validateEdgeProps(edgeKind.schema, item.props, {\n kind,\n operation: \"create\",\n });\n\n const compositeKey = buildEdgeCompositeKey(\n item.fromKind,\n item.fromId,\n item.toKind,\n item.toId,\n validatedProps,\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 compositeKey,\n endpointKey,\n });\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 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 interface DuplicateEntry {\n index: number;\n sourceIndex: number;\n }\n interface Result {\n readonly edge: Edge;\n readonly action: GetOrCreateAction;\n }\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 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.validatedProps,\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 },\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 });\n }\n }\n\n return { toCreate, toFetch, duplicateOf };\n }\n\n // Probe outside the transaction: with ifExists \"return\" and every entry\n // matching a live edge, the whole call performs no write, so it must not\n // pay for a write transaction (BEGIN IMMEDIATE on SQLite, the per-graph\n // advisory lock under history). The transactional body re-queries, so a\n // concurrent write between this probe and the write lock is still handled\n // correctly.\n if (ifExists === \"return\") {\n const probe = partitionEntries(await fetchRowsByEndpoint(backend));\n const allFoundLive =\n probe.toCreate.length === 0 &&\n probe.toFetch.every((entry) => !entry.isDeleted);\n if (allFoundLive) {\n const found: Result[] = Array.from({ length: items.length });\n for (const entry of probe.toFetch) {\n found[entry.index] = { edge: rowToEdge(entry.row), action: \"found\" };\n }\n for (const { index, sourceIndex } of probe.duplicateOf) {\n found[index] = { edge: found[sourceIndex]!.edge, action: \"found\" };\n }\n return found;\n }\n }\n\n return runInWriteTransaction(ctx, backend, async (target) => {\n const { toCreate, toFetch, duplicateOf } = partitionEntries(\n await fetchRowsByEndpoint(target),\n );\n const results: Result[] = Array.from({ length: items.length });\n\n // Step 4: Execute creates in batch\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const createdEdges = await executeEdgeCreateBatch(\n ctx,\n createInputs,\n target,\n );\n for (const [batchIndex, entry] of toCreate.entries()) {\n results[entry.index] = {\n edge: createdEdges[batchIndex]!,\n action: \"created\",\n };\n }\n }\n\n // Step 5: Handle existing edges (update/skip/resurrect)\n for (const entry of toFetch) {\n if (entry.isDeleted) {\n // Check cardinality before resurrect\n const effectiveValidTo = entry.row.valid_to;\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend: target,\n };\n await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n entry.fromKind,\n entry.fromId,\n entry.toKind,\n entry.toId,\n effectiveValidTo,\n );\n\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: entry.row.id, props: entry.validatedProps },\n target,\n { clearDeleted: true },\n );\n results[entry.index] = { edge, action: \"resurrected\" };\n } else if (ifExists === \"update\") {\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: entry.row.id, props: entry.validatedProps },\n target,\n );\n results[entry.index] = { edge, action: \"updated\" };\n } else {\n results[entry.index] = { edge: rowToEdge(entry.row), action: \"found\" };\n }\n }\n\n // Step 6: Resolve within-batch duplicates\n for (const { index, sourceIndex } of duplicateOf) {\n const sourceResult = results[sourceIndex]!;\n results[index] = { edge: sourceResult.edge, action: \"found\" };\n }\n\n return results;\n });\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n createBackendOverlay,\n type EdgeRow,\n type GraphBackend,\n type NodeRow,\n} from \"../backend/types\";\nimport { type ReadCoordinate } from \"../core/temporal\";\nimport {\n type AnyEdgeType,\n type EdgeId,\n type NodeId,\n type NodeType,\n} from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { sqlValueList } from \"../query/compiler/predicate-utils\";\nimport {\n type RecordedReadBinding,\n recordedReadSqlSchema,\n requireRecordedReadBinding,\n} from \"../query/compiler/schema\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { asCompiledRowsSql, type CompiledRowsSql } from \"../query/sql-intent\";\nimport { chunk } from \"../utils/array\";\nimport { withRecordedRelationsPrecondition } from \"../utils/sql-errors\";\nimport { recordedBindParamBudget } from \"./recorded-capture/relations\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport { type Edge, type Node } from \"./types\";\n\nconst RECORDED_POINT_READ_FIXED_BIND_PARAMS = 8;\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: SQL;\n alias: string;\n kind: string;\n ids: readonly string[];\n coordinate: ReadCoordinate;\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 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}>;\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 return createBackendOverlay(backend, {\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 backend.executeRaw!<T>(sqlText, params),\n surface,\n ),\n }),\n });\n}\n\nfunction recordedTemporalFilter(\n backend: GraphBackend,\n coordinate: ReadCoordinate,\n tableAlias: string,\n): SQL {\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 compileTemporalFilter({\n mode: coordinate.valid.mode,\n asOf: coordinate.valid.asOf,\n recordedAsOf,\n tableAlias,\n currentTimestamp: currentReadInstant(),\n });\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 point 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\nexport function createRecordedReadService(\n params: RecordedReadServiceParams,\n): RecordedReadService {\n const {\n graphId,\n backend,\n recordedReadBinding,\n mapRecordedNodeRow,\n mapRecordedEdgeRow,\n } = params;\n const recordedSchema =\n recordedReadBinding === undefined ? undefined : (\n recordedReadSqlSchema(recordedReadBinding)\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 temporalFilter = recordedTemporalFilter(backend, coordinate, alias);\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 ORDER BY ${aliasSql}.recorded_from\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 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 =\n recordedSchema ??\n recordedReadSqlSchema(\n requireRecordedReadBinding(recordedReadBinding, \"recorded-point-read\"),\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 =\n recordedSchema ??\n recordedReadSqlSchema(\n requireRecordedReadBinding(recordedReadBinding, \"recorded-point-read\"),\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 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\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 };\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { type Assert, type Equal } from \"../utils/type-assert\";\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\nexport type TransactionReceiptRecorder = Readonly<{\n recordNode: (kind: string, count: number) => void;\n recordEdge: (kind: string, count: number) => void;\n snapshot: (recorded?: TransactionReceipt[\"recorded\"]) => TransactionReceipt;\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 delete: countSingleWrite,\n hardDelete: countSingleWrite,\n upsertById: countSingleWrite,\n upsertByIdFromRecord: countSingleWrite,\n bulkCreate: 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\nexport function createTransactionReceiptRecorder(): TransactionReceiptRecorder {\n const nodes = createCountBucket();\n const edges = createCountBucket();\n let total = 0;\n\n return {\n recordNode(kind, count): void {\n increment(nodes, kind, count);\n total += count;\n },\n\n recordEdge(kind, count): void {\n increment(edges, kind, count);\n total += count;\n },\n\n snapshot(recorded): TransactionReceipt {\n // Object.assign onto a fresh null-prototype bucket (rather than spread)\n // keeps prototype-colliding kind names readable on the returned receipt.\n return Object.freeze({\n writes: Object.freeze({\n nodes: Object.freeze(Object.assign(createCountBucket(), nodes)),\n edges: Object.freeze(Object.assign(createCountBucket(), edges)),\n total,\n }),\n ...(recorded === undefined ? {} : { recorded }),\n });\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`) counts its intent through `record` before\n * resolving.\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): 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 // 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 ),\n ),\n edges: wrapCollections(edges, (collection, kind) =>\n wrapWriteCollection(\n collection,\n kind,\n EDGE_WRITE_SURFACE,\n recorder.recordEdge,\n ),\n ),\n };\n}\n","/**\n * Store types for TypeGraph operations.\n */\nimport { type z } from \"zod\";\n\nimport {\n type AdoptedTransaction,\n type EdgeRow,\n type NodeRow,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { type RecordedInstant } from \"../core/temporal\";\nimport {\n type AnyEdgeType,\n type EdgeId,\n type EdgeRegistration,\n type EdgeType,\n type KindEntity,\n type NodeId,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"../core/types\";\nimport type { TraversalExpansion } from \"../query/ast\";\nimport type { BatchableQuery, NodeAccessor } from \"../query/builder/types\";\nimport {\n type ExternalRecordedReadSource,\n type SqlSchema,\n} from \"../query/compiler/schema\";\nimport type { Predicate } from \"../query/predicates\";\nimport type {\n CURRENT_ONLY_READ_NAMES,\n EDGE_BATCH_READ_NAMES,\n EDGE_TEMPORAL_READ_NAMES,\n EDGE_WRITE_NAMES,\n NODE_TEMPORAL_READ_NAMES,\n NODE_WRITE_NAMES,\n RECORDED_POINT_READ_NAMES,\n} from \"./collection-surface\";\n\n// ============================================================\n// Row-to-Meta Field Mapping\n// ============================================================\n\n/**\n * Canonical mapping from snake_case row fields to camelCase meta fields.\n *\n * This is the single source of truth for which row columns become metadata.\n * Both the Meta types and the row-to-meta functions in row-mappers.ts must\n * stay in sync with this mapping. If you add a temporal/audit column to a\n * row type, add the mapping here — the compiler will then force you to\n * update the row mapper functions as well (since their return type is\n * NodeMeta/EdgeMeta, which is derived from this mapping).\n */\ntype TemporalMetaFieldMap = Readonly<{\n valid_from: \"validFrom\";\n valid_to: \"validTo\";\n created_at: \"createdAt\";\n updated_at: \"updatedAt\";\n deleted_at: \"deletedAt\";\n}>;\n\n/**\n * Maps row fields to their camelCase meta counterparts, preserving types.\n */\ntype MapRowToMeta<\n R extends Readonly<Record<string, unknown>>,\n M extends Readonly<Record<string, string>>,\n> = Readonly<{\n [SnakeKey in keyof M as M[SnakeKey] & string]: SnakeKey extends keyof R ?\n R[SnakeKey]\n : never;\n}>;\n\n// ============================================================\n// Node Instance Types\n// ============================================================\n\n/**\n * Metadata for a node instance.\n * Derived from NodeRow via TemporalMetaFieldMap + version.\n *\n * Adding a new metadata column requires:\n * 1. Add the column to NodeRow in backend/types.ts\n * 2. Add the mapping to TemporalMetaFieldMap above\n * 3. The compiler will error in rowToNodeMeta() until you add the field there\n */\nexport type NodeMeta = MapRowToMeta<NodeRow, TemporalMetaFieldMap> &\n Readonly<{ version: NodeRow[\"version\"] }>;\n\n/**\n * A node instance in the graph.\n *\n * Properties from the schema are spread at the top level for ergonomic access:\n * - `node.name` instead of `node.props.name`\n * - System metadata is under `node.meta.*`\n */\nexport type Node<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id: NodeId<N>;\n meta: NodeMeta;\n}> &\n Readonly<z.infer<N[\"schema\"]>>;\n\n/**\n * Input for creating a node.\n */\nexport type CreateNodeInput<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id?: string; // Optional - will generate ULID if not provided\n props: z.infer<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Input for updating a node.\n */\nexport type UpdateNodeInput<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id: NodeId<N>;\n props: Partial<z.infer<N[\"schema\"]>>;\n validTo?: string;\n}>;\n\n// ============================================================\n// Edge Instance Types\n// ============================================================\n\n/**\n * Metadata for an edge instance.\n * Derived from EdgeRow via TemporalMetaFieldMap (edges have no version).\n */\nexport type EdgeMeta = MapRowToMeta<EdgeRow, TemporalMetaFieldMap>;\n\n/**\n * An edge instance in the graph.\n *\n * Properties from the schema are spread at the top level for ergonomic access:\n * - `edge.role` instead of `edge.props.role`\n * - System metadata is under `edge.meta.*`\n */\nexport type Edge<\n E extends AnyEdgeType = EdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n id: EdgeId<E>;\n kind: E[\"kind\"];\n fromKind: From[\"kind\"];\n fromId: NodeId<From>;\n toKind: To[\"kind\"];\n toId: NodeId<To>;\n meta: EdgeMeta;\n}> &\n Readonly<z.infer<E[\"schema\"]>>;\n\n/**\n * Input for creating an edge.\n */\nexport type CreateEdgeInput<E extends AnyEdgeType = EdgeType> = Readonly<{\n kind: E[\"kind\"];\n id?: string; // Optional - will generate ULID if not provided\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: z.infer<E[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Input for updating an edge.\n */\nexport type UpdateEdgeInput<E extends AnyEdgeType = EdgeType> = Readonly<{\n id: EdgeId<E>;\n props: Partial<z.infer<E[\"schema\"]>>;\n validTo?: string;\n}>;\n\n// ============================================================\n// Query Options\n// ============================================================\n\n/**\n * Options for node and edge queries.\n */\nexport type NoRecordedCoordinate = Readonly<{\n /**\n * Recorded/system-time coordinates are internal-only and supplied by\n * RecordedStoreView. A public options object carrying this key is a type\n * error even when the object is pre-bound before the call site.\n */\n recordedAsOf?: never;\n}>;\n\nexport type QueryOptions = NoRecordedCoordinate &\n Readonly<{\n /** Temporal mode for the query */\n temporalMode?: TemporalMode;\n /** Specific timestamp for asOf queries */\n asOf?: string;\n }>;\n\n// ============================================================\n// Observability Hooks\n// ============================================================\n\n/**\n * Context passed to observability hooks.\n */\nexport type HookContext = Readonly<{\n /** Unique ID for this operation */\n operationId: string;\n /** Graph ID */\n graphId: string;\n /** Timestamp when operation started */\n startedAt: Date;\n}>;\n\n/**\n * Query hook context with SQL information.\n */\nexport type QueryHookContext = HookContext &\n Readonly<{\n /** The SQL query being executed */\n sql: string;\n /** Query parameters */\n params: readonly unknown[];\n }>;\n\n/**\n * Operation hook context for CRUD operations.\n */\nexport type OperationHookContext = HookContext &\n Readonly<{\n /** Operation type */\n operation: \"create\" | \"update\" | \"delete\";\n /** Entity type */\n entity: KindEntity;\n /** Kind of node or edge */\n kind: string;\n /** Entity ID */\n id: string;\n }>;\n\n/**\n * Observability hooks for monitoring store operations.\n *\n * Note: Batch operations (`bulkCreate`, `bulkInsert`, `bulkUpsertById`) skip\n * per-item operation hooks for throughput. Query hooks still fire normally.\n *\n * @example\n * ```typescript\n * const hooks: StoreHooks = {\n * onQueryStart: (ctx) => {\n * console.log(`[${ctx.operationId}] Query: ${ctx.sql}`);\n * },\n * onQueryEnd: (ctx, result) => {\n * const duration = Date.now() - ctx.startedAt.getTime();\n * console.log(`[${ctx.operationId}] Completed in ${duration}ms`);\n * },\n * onError: (ctx, error) => {\n * console.error(`[${ctx.operationId}] Error:`, error);\n * },\n * };\n *\n * const store = createStore(graph, backend, { hooks });\n * ```\n */\nexport type StoreHooks = Readonly<{\n /** Called before a query is executed */\n onQueryStart?: (ctx: QueryHookContext) => void;\n /** Called after a query completes successfully */\n onQueryEnd?: (\n ctx: QueryHookContext,\n result: Readonly<{ rowCount: number; durationMs: number }>,\n ) => void;\n /** Called before a CRUD operation starts */\n onOperationStart?: (ctx: OperationHookContext) => void;\n /**\n * Called after a CRUD operation completes AND is durably committed. For a\n * top-level operation that is when its own transaction commits; for an\n * operation inside `store.transaction`, emission is deferred until the\n * enclosing transaction commits — if that commit fails, the operation is\n * reported through `onError` instead. (Inside an adopted transaction —\n * `withTransaction` / `withRecordedTransaction` — the commit belongs to\n * the caller and cannot be observed, so this fires when the operation\n * completes within the still-open transaction.)\n */\n onOperationEnd?: (\n ctx: OperationHookContext,\n result: Readonly<{ durationMs: number }>,\n ) => void;\n /**\n * Called when an operation fails — including an operation that completed\n * inside a `store.transaction` whose commit then failed and rolled it\n * back.\n */\n onError?: (ctx: HookContext, error: Error) => void;\n}>;\n\n// ============================================================\n// Store Configuration\n// ============================================================\n\n/**\n * Default row count at which an autocommit bulk write triggers an\n * automatic planner-statistics refresh. Below this, the refresh cost is\n * not worth paying per call and autovacuum/PRAGMA optimize cover it.\n */\nexport const AUTO_REFRESH_STATISTICS_ROW_THRESHOLD = 1000;\n\ntype BaseStoreOptions = Readonly<{\n /** Observability hooks for monitoring */\n hooks?: StoreHooks;\n /**\n * Maintain a durable, graph-wide revision anchor for TypeGraph writes:\n * a random per-graph origin plus a monotonic revision clock. `branch()` uses\n * this anchor to validate that its base has not moved without\n * re-fingerprinting every live row, and cannot confuse a coincident clock in\n * a separately created store for its original base. `history: true` enables\n * the same tracking automatically through its recorded-time commit clock.\n *\n * This is intentionally opt-in for live stores: each successful graph write\n * advances the anchor inside its write transaction. On PostgreSQL, those\n * transactions take a graph-scoped advisory lock until commit; writes to the\n * same graph therefore serialize. Enable it for branchable graphs, but size\n * high-throughput multi-writer workloads for that trade-off.\n *\n * Writes performed directly through a backend — including raw graph-table\n * writes through `tx.sql` — bypass the anchor and are outside the\n * revision-tracking contract.\n */\n revisionTracking?: boolean;\n /**\n * Automatic planner-statistics refresh after large autocommit bulk\n * writes (bulkCreate and bulkInsert on nodes and edges). Stale statistics after a\n * bulk load are a whole class of planner cliffs: the planner keeps\n * pre-load row estimates until ANALYZE runs. When a single\n * autocommit bulk write reaches the threshold\n * ({@link AUTO_REFRESH_STATISTICS_ROW_THRESHOLD} rows by default),\n * the store runs `refreshStatistics()` after the write commits.\n * Pass a number to change the threshold, or `false` to disable.\n * Bulk writes inside a caller-provided transaction never\n * auto-refresh (statistics cannot see uncommitted rows); refresh\n * manually after commit. `importGraph` handles its own refresh.\n */\n autoRefreshStatistics?: false | number;\n /** SQL schema configuration from createSqlSchema(...) for custom table names */\n schema?: SqlSchema;\n /** Query default behaviors. */\n queryDefaults?: Readonly<{\n /** Default traversal ontology expansion mode (default: \"inverse\"). */\n traversalExpansion?: TraversalExpansion;\n }>;\n}>;\n\n/**\n * Store options without built-in recorded-time capture. A recorded read relation\n * can still be bound explicitly for hosts that populate history externally.\n */\nexport type LiveStoreOptions = BaseStoreOptions &\n Readonly<{\n history?: false | undefined;\n recordedRead?: ExternalRecordedReadSource | undefined;\n }>;\n\n/**\n * Store options with TypeGraph-managed recorded-time capture. `history: true`\n * captures TypeGraph writes and binds TypeGraph's built-in recorded relation\n * internally. Externally populated recorded read sources are read-only bindings\n * and are intentionally accepted only by {@link LiveStoreOptions}.\n */\nexport type HistoryStoreOptions = BaseStoreOptions &\n Readonly<{\n history: true;\n recordedRead?: never;\n }>;\n\n/**\n * Options for creating a store.\n */\nexport type StoreOptions = LiveStoreOptions | HistoryStoreOptions;\n\n/**\n * A mutable handle to the current `Store`, used by `store.evolve(...)`\n * so long-lived consumers can dereference through the ref and pick up\n * the new store after each evolve call. `current` is overwritten by\n * `evolve()` atomically with the schema commit when the ref is passed\n * via `evolve(extension, { ref })`.\n *\n * **Mid-request semantics.** `ref.current` flips on the *next* call\n * after evolve, not mid-handler. Dereference once at request entry and\n * reuse the captured `Store` for the duration:\n *\n * ```ts\n * async function handleRequest(): Promise<void> {\n * const store = ref.current; // capture once\n * const tag = await store.nodes.Tag?.create({ label: \"...\" });\n * // ...further work on the same `store`...\n * }\n * ```\n *\n * Pure dereferenceable handle — no event/subscription machinery. If\n * consumers need eventing, they wrap the ref themselves.\n *\n * Generic over the held value (typically `Store<G>`) so the store\n * module can refer to it without importing the `Store` class into\n * `types.ts`.\n */\nexport interface StoreRef<T> {\n current: T;\n}\n\n// ============================================================\n// Transaction Receipt Types\n// ============================================================\n\n/**\n * Summary returned by `store.transactionWithReceipt(fn)`.\n */\nexport type TransactionOutcome<T> = Readonly<{\n result: T;\n receipt: TransactionReceipt;\n}>;\n\n/**\n * Transaction write summary.\n *\n * Receipt counts are completed write intents at the collection surface, not\n * rows affected:\n *\n * 1. Every successful completion of a write method on `tx.nodes.*` /\n * `tx.edges.*` counts. The authoritative method list is\n * {@link NodeWrites} / {@link EdgeWrites}.\n * 2. Bulk methods count by input length; an empty bulk call (`bulkCreate([])`)\n * counts 0.\n * 3. Single-row methods count 1 on resolve — including `delete` of an absent\n * id and `getOrCreate*` that found an existing row. Consumers that need\n * \"did anything actually change\" semantics apply their own per-operation\n * policy.\n * 4. A method that rejects counts 0 — even when the backend applied part of a\n * bulk input before failing. On SQLite a failed statement does not abort\n * the surrounding transaction, so a caller that catches the rejection and\n * commits can persist rows the receipt never counted. Do not read the\n * receipt as rows-affected in that scenario.\n * 5. A node `delete` under `cascade` / `disconnect` removes connected edges\n * through the backend, not the edge-collection surface; those removals do\n * not appear in `edges`.\n * 6. Rows-affected fidelity is intentionally out of scope for this first\n * version; a future extension could ask backends to return row counts.\n */\nexport type TransactionReceipt = Readonly<{\n writes: Readonly<{\n /** Completed node write intents by node kind. */\n nodes: Readonly<Record<string, number>>;\n /** Completed edge write intents by edge kind. */\n edges: Readonly<Record<string, number>>;\n /** Sum of all node and edge write intents. */\n total: number;\n }>;\n /**\n * The recorded commit instant allocated for this store's graph by this\n * transaction. Undefined when history capture is off, the transaction is\n * read-only, or no captured writes were flushed.\n */\n recorded?: RecordedInstant;\n}>;\n\n// ============================================================\n// Get-Or-Create Types\n// ============================================================\n\n/**\n * Behavior when a get-or-create operation matches an existing record.\n */\nexport type IfExistsMode = \"return\" | \"update\";\n\n/**\n * Action taken by a get-or-create operation.\n */\nexport type GetOrCreateAction = \"created\" | \"found\" | \"updated\" | \"resurrected\";\n\n/**\n * Result of a node getOrCreateByConstraint operation.\n */\nexport type NodeGetOrCreateByConstraintResult<N extends NodeType> = Readonly<{\n node: Node<N>;\n action: GetOrCreateAction;\n}>;\n\n/**\n * Options for node getOrCreateByConstraint operations.\n */\nexport type NodeGetOrCreateByConstraintOptions = Readonly<{\n /** Existing record behavior. Default: \"return\" */\n ifExists?: IfExistsMode;\n}>;\n\n/**\n * Options for node bulkFindByIndex operations.\n */\nexport type NodeBulkFindByIndexOptions = Readonly<{\n /**\n * Maximum number of candidate nodes returned per input item. When omitted,\n * each input's candidate set is unbounded. Must be a positive integer.\n *\n * Candidates are ordered deterministically by node id, so the cap is stable\n * across calls. Use this to bound fan-out on low-selectivity index keys.\n */\n limitPerInput?: number;\n}>;\n\n/**\n * Result of an edge getOrCreateByEndpoints operation.\n */\nexport type EdgeGetOrCreateByEndpointsResult<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n edge: Edge<E, From, To>;\n action: GetOrCreateAction;\n}>;\n\n/**\n * Options for edge findByEndpoints operations.\n */\nexport type EdgeFindByEndpointsOptions<E extends AnyEdgeType> = Readonly<{\n /**\n * Edge property fields to include in the match alongside the (from, to) endpoints.\n * When omitted, matches on endpoints only (returns the first edge at the read coordinate).\n */\n matchOn?: readonly (keyof z.input<E[\"schema\"]>)[];\n /** Property values to match against when matchOn is specified. */\n props?: Partial<z.input<E[\"schema\"]>>;\n}>;\n\n/**\n * Options for edge getOrCreateByEndpoints operations.\n */\nexport type EdgeGetOrCreateByEndpointsOptions<E extends AnyEdgeType> =\n Readonly<{\n /**\n * Edge property fields to include in the match key alongside the (from, to) endpoints.\n * Default: `[]` — match on endpoints only.\n */\n matchOn?: readonly (keyof z.input<E[\"schema\"]>)[];\n /** Existing record behavior. Default: \"return\" */\n ifExists?: IfExistsMode;\n }>;\n\n// ============================================================\n// Collection Interfaces\n// ============================================================\n\n/**\n * A collection of nodes of a specific type.\n *\n * Provides ergonomic CRUD operations for a single node type.\n */\nexport type NodeCollection<\n N extends NodeType,\n CN extends string = string,\n> = Readonly<{\n /**\n * Create a new node.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n create: (\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /** Get a node by ID */\n getById: (\n id: NodeId<N>,\n options?: QueryOptions,\n ) => Promise<Node<N> | undefined>;\n\n /** Get multiple nodes by ID, preserving input order (undefined for missing) */\n getByIds: (\n ids: readonly NodeId<N>[],\n options?: QueryOptions,\n ) => Promise<readonly (Node<N> | undefined)[]>;\n\n /** Update a node */\n update: (\n id: NodeId<N>,\n props: Partial<z.input<N[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /** Delete a node (soft delete - sets deletedAt timestamp) */\n delete: (id: NodeId<N>) => Promise<void>;\n\n /**\n * Permanently delete a node from the database.\n *\n * Unlike `delete()` which performs a soft delete, this permanently\n * removes the node and its associated data (uniqueness entries, embeddings).\n *\n * **Warning:** This operation is irreversible and should be used carefully.\n * Consider using soft delete (`delete()`) for most use cases.\n *\n * @throws Error if edges are still connected to this node (delete edges first)\n */\n hardDelete: (id: NodeId<N>) => Promise<void>;\n\n /**\n * Find nodes matching criteria.\n *\n * Supports predicate filtering via the `where` option for SQL-level filtering.\n * For simple queries. Use store.query() for complex traversals.\n */\n find: (\n filter?: Readonly<{\n where?: (accessor: NodeAccessor<N>) => Predicate;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ) => Promise<Node<N>[]>;\n\n /** Count nodes matching criteria */\n count: (temporal?: QueryOptions) => Promise<number>;\n\n /**\n * Create a node from untyped data, relying on runtime Zod validation.\n *\n * Use this for dynamic dispatch (changesets, migrations, imports) where\n * the data shape is determined at runtime, not compile time.\n * The return type is fully typed — only the input gate is relaxed.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n createFromRecord: (\n data: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Create or update a node.\n *\n * If a node with the given ID exists, updates it with the provided props.\n * Otherwise, creates a new node with that ID.\n *\n * `validFrom` only applies on the create branch, defaulting to the\n * operation's creation timestamp when omitted; it has no effect on update.\n */\n upsertById: (\n id: string,\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Upsert a node from untyped data, relying on runtime Zod validation.\n *\n * Use this for dynamic dispatch (changesets, migrations, imports) where\n * the data shape is determined at runtime, not compile time.\n * The return type is fully typed — only the input gate is relaxed.\n *\n * `validFrom` only applies on the create branch, defaulting to the\n * operation's creation timestamp when omitted; it has no effect on update.\n */\n upsertByIdFromRecord: (\n id: string,\n data: Record<string, unknown>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Create multiple nodes in a batch.\n *\n * More efficient than calling create() multiple times.\n * Use `bulkInsert` for the dedicated fast path that skips returning results.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n bulkCreate: (\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Node<N>[]>;\n\n /**\n * Create or update multiple nodes in a batch.\n *\n * For each item, if a node with the given ID exists, updates it.\n * Otherwise, creates a new node with that ID.\n *\n * `validFrom` only applies on the create branch, defaulting to the\n * operation's creation timestamp when omitted; it has no effect on update.\n */\n bulkUpsertById: (\n items: readonly Readonly<{\n id: string;\n props: z.input<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Node<N>[]>;\n\n /**\n * Insert multiple nodes without returning results.\n *\n * This is the dedicated fast path for bulk inserts. Unlike `bulkCreate`\n * with `returnResults: false`, the intent is unambiguous: no results\n * are returned and the operation is wrapped in a transaction.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n bulkInsert: (\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<void>;\n\n /**\n * Delete multiple nodes by ID.\n *\n * Atomic when the backend supports transactions. Silently ignores IDs\n * that don't exist.\n */\n bulkDelete: (ids: readonly NodeId<N>[]) => Promise<void>;\n\n /**\n * Find a node by uniqueness constraint.\n *\n * Looks up a live node by the named constraint key computed from `props`.\n * Returns the node if found, or undefined. Soft-deleted nodes are excluded.\n *\n * @param constraintName - Name of the uniqueness constraint to match on\n * @param props - Properties to compute the constraint key from\n */\n findByConstraint: (\n constraintName: CN,\n props: z.input<N[\"schema\"]>,\n ) => Promise<Node<N> | undefined>;\n\n /**\n * Batch version of findByConstraint.\n *\n * Results are returned in the same order as the input items.\n * Returns undefined for entries that don't match.\n */\n bulkFindByConstraint: (\n constraintName: CN,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n ) => Promise<(Node<N> | undefined)[]>;\n\n /**\n * Batched candidate retrieval against a declared node index.\n *\n * For each input item, TypeGraph computes the index lookup key from\n * `index.fields` (JSON-pointer extraction, partial-`where` applied to\n * stored rows, null-safe matching) and returns the live, non-soft-deleted\n * nodes that share that key. Unlike {@link bulkFindByConstraint}, the index\n * may be non-unique, so each input yields a (possibly empty) array.\n *\n * Results preserve input order; each inner array is ordered by node id.\n * Empty input returns `[]`. An unknown index name throws\n * `NodeIndexNotFoundError`; a type-incompatible indexed field throws\n * `ValidationError`. This is candidate retrieval, not a uniqueness or\n * identity guarantee.\n *\n * @param indexName - Name of the declared node index to match on\n * @param items - Records whose `props` supply the indexed-field values\n * @param options - Optional `limitPerInput` to bound per-input fan-out\n */\n 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\n /**\n * Get an existing node by uniqueness constraint, or create a new one.\n *\n * Looks up a node by the named constraint key computed from `props`.\n * If found, returns it (optionally updating with `ifExists: \"update\"`).\n * If not found, creates a new node. Soft-deleted matches are always resurrected.\n *\n * @param constraintName - Name of the uniqueness constraint to match on\n * @param props - Full properties for create, or merge source for update\n * @param options - Existing record behavior (default: \"return\")\n */\n getOrCreateByConstraint: (\n constraintName: CN,\n props: z.input<N[\"schema\"]>,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<NodeGetOrCreateByConstraintResult<N>>;\n\n /**\n * Batch version of getOrCreateByConstraint.\n *\n * Results are returned in the same order as the input items.\n * Atomic when the backend supports transactions.\n */\n bulkGetOrCreateByConstraint: (\n constraintName: CN,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<NodeGetOrCreateByConstraintResult<N>[]>;\n}>;\n\n/**\n * Reference to a node of a specific kind.\n *\n * Accepts either:\n * - A Node instance of the correct kind\n * - An explicit { kind, id } object with the correct kind name\n *\n * This provides compile-time checking that edge endpoints match the\n * allowed node kinds defined in the edge registration.\n */\nexport type NodeRef<N extends NodeType = NodeType> =\n Node<N> | Readonly<{ kind: N[\"kind\"]; id: string }>;\n\n/**\n * Options for creating an edge.\n */\ntype EdgeCreateOptions = Readonly<{\n id?: string;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Arguments for edge creation, with props optional when schema allows empty object.\n *\n * Uses `{}` to check if an empty object literal satisfies the schema input type.\n */\n/* eslint-disable @typescript-eslint/no-empty-object-type -- {} is intentional: checking if empty object satisfies schema */\ntype EdgeCreateArguments<E extends AnyEdgeType> =\n {} extends z.input<E[\"schema\"]> ?\n [props?: z.input<E[\"schema\"]>, options?: EdgeCreateOptions]\n : [props: z.input<E[\"schema\"]>, options?: EdgeCreateOptions];\n/* eslint-enable @typescript-eslint/no-empty-object-type */\n\n/**\n * A collection of edges of a specific type.\n *\n * Provides ergonomic CRUD operations for a single edge type.\n * The From and To type parameters enforce that edge endpoints\n * match the allowed node types at compile time.\n *\n * @example\n * ```typescript\n * // Create an edge - pass Node objects directly\n * const edge = await store.edges.worksAt.create(alice, acme, { role: \"Engineer\" });\n *\n * // TypeScript error: Company is not a valid 'from' type for worksAt\n * // store.edges.worksAt.create(acme, alice, { role: \"Engineer\" });\n *\n * // For edges with empty schemas, props is optional\n * await store.edges.wrote.create(author, book);\n *\n * // Find edges from a node\n * const edges = await store.edges.worksAt.findFrom(alice);\n * ```\n */\nexport type EdgeCollection<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n /**\n * Create a new edge.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n *\n * @param from - Source node (must be one of the allowed 'from' types)\n * @param to - Target node (must be one of the allowed 'to' types)\n * @param args - Edge properties (optional if schema is empty) and creation options\n */\n create: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n ...args: EdgeCreateArguments<E>\n ) => Promise<Edge<E, From, To>>;\n\n /** Get an edge by ID */\n getById: (\n id: EdgeId<E>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To> | undefined>;\n\n /** Get multiple edges by ID, preserving input order (undefined for missing) */\n getByIds: (\n ids: readonly EdgeId<E>[],\n options?: QueryOptions,\n ) => Promise<readonly (Edge<E, From, To> | undefined)[]>;\n\n /** Update an edge's properties */\n update: (\n id: EdgeId<E>,\n props: Partial<z.input<E[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ) => Promise<Edge<E, From, To>>;\n\n /**\n * Find edges from a specific node.\n *\n * Honors the same temporal model as `getById` / `find`: with no\n * `options`, the graph's default `temporalMode` applies (excluding\n * soft-deleted edges and, in `current` / `asOf` modes, edges outside\n * their validity window). Pass `temporalMode` / `asOf` to read the\n * endpoint's edges at another temporal coordinate.\n */\n findFrom: (\n from: NodeRef<From>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Find edges to a specific node.\n *\n * Temporal semantics mirror {@link EdgeCollection.findFrom}.\n */\n findTo: (\n to: NodeRef<To>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Deferred variant of `findFrom` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` instead of executing immediately. Accepts\n * the same temporal `options` as {@link EdgeCollection.findFrom}.\n */\n batchFindFrom: (\n from: NodeRef<From>,\n options?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /**\n * Deferred variant of `findTo` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` instead of executing immediately. Accepts\n * the same temporal `options` as {@link EdgeCollection.findTo}.\n */\n batchFindTo: (\n to: NodeRef<To>,\n options?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /**\n * Deferred variant of `findByEndpoints` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` that yields a 0-or-1 element array\n * (matching `findByEndpoints`' at-most-one semantics).\n */\n batchFindByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /** Delete an edge (soft delete - sets deletedAt timestamp) */\n delete: (id: EdgeId<E>) => Promise<void>;\n\n /**\n * Permanently delete an edge from the database.\n *\n * Unlike `delete()` which performs a soft delete, this permanently\n * removes the edge record.\n *\n * **Warning:** This operation is irreversible and should be used carefully.\n * Consider using soft delete (`delete()`) for most use cases.\n */\n hardDelete: (id: EdgeId<E>) => Promise<void>;\n\n /** Find edges matching endpoint and pagination criteria */\n find: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /** Count edges matching criteria */\n count: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n }>,\n temporal?: QueryOptions,\n ) => Promise<number>;\n\n /**\n * Create multiple edges in a batch.\n *\n * More efficient than calling create() multiple times.\n * Use `bulkInsert` for the dedicated fast path that skips returning results.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n bulkCreate: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Create or update multiple edges in a batch.\n *\n * For each item, if an edge with the given ID exists, updates it.\n * Otherwise, creates a new edge with that ID.\n *\n * `validFrom` only applies on the create branch, defaulting to the\n * operation's creation timestamp when omitted; it has no effect on update.\n */\n bulkUpsertById: (\n items: readonly Readonly<{\n id: EdgeId<E>;\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Insert multiple edges without returning results.\n *\n * This is the dedicated fast path for bulk inserts. Unlike `bulkCreate`\n * with `returnResults: false`, the intent is unambiguous: no results\n * are returned and the operation is wrapped in a transaction.\n *\n * `validFrom` defaults to the operation's creation timestamp when omitted.\n */\n bulkInsert: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<void>;\n\n /**\n * Delete multiple edges by ID.\n *\n * Atomic when the backend supports transactions. Silently ignores IDs\n * that don't exist.\n */\n bulkDelete: (ids: readonly EdgeId<E>[]) => Promise<void>;\n\n /**\n * Find an edge by endpoints and optional property fields.\n *\n * Returns the first matching edge at the read coordinate, or undefined.\n * Honors the temporal model like `findFrom` / `findTo`: by default\n * (`current` mode) soft-deleted and out-of-window edges are excluded; under\n * `includeTombstones` a soft-deleted edge can be returned.\n *\n * @param from - Source node\n * @param to - Target node\n * @param options - Match criteria (matchOn fields and property values)\n * @param temporal - Temporal coordinate. With no `temporal`, the graph's\n * default `temporalMode` applies (so under the default `\"current\"` mode,\n * edges outside their validity window are excluded). Pass\n * `temporalMode` / `asOf` to read the edge as of another coordinate.\n */\n findByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ) => Promise<Edge<E, From, To> | undefined>;\n\n /**\n * Get an existing edge by endpoints and optional property fields, or create a new one.\n *\n * Matches edges of this kind between `(from, to)`. When `matchOn` specifies\n * property fields, only edges whose properties match on those fields are considered.\n * Soft-deleted matches are resurrected when cardinality allows.\n *\n * @param from - Source node\n * @param to - Target node\n * @param props - Full properties for create, or merge source for update\n * @param options - Match criteria and conflict resolution\n */\n getOrCreateByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n props: z.input<E[\"schema\"]>,\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ) => Promise<EdgeGetOrCreateByEndpointsResult<E, From, To>>;\n\n /**\n * Batch version of getOrCreateByEndpoints.\n *\n * Results are returned in the same order as the input items.\n * Atomic when the backend supports transactions.\n */\n bulkGetOrCreateByEndpoints: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props: z.input<E[\"schema\"]>;\n }>[],\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ) => Promise<EdgeGetOrCreateByEndpointsResult<E, From, To>[]>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract uniqueness constraint names from a NodeRegistration.\n *\n * - Returns `never` when no uniqueness constraints are configured.\n * - Returns a literal union when names are inferred via `defineGraph` const params.\n * - Falls back to `string` when names are widened/dynamic.\n */\nexport type ConstraintNames<R extends NodeRegistration> =\n \"unique\" extends keyof R ?\n R[\"unique\"] extends readonly { readonly name: infer N }[] ?\n N & string\n : string\n : never;\n\n/**\n * Extract the union of 'from' node types from an EdgeRegistration.\n */\ntype EdgeFromTypes<R extends EdgeRegistration> =\n R[\"from\"] extends readonly (infer N)[] ? N : never;\n\n/**\n * Extract the union of 'to' node types from an EdgeRegistration.\n */\ntype EdgeToTypes<R extends EdgeRegistration> =\n R[\"to\"] extends readonly (infer N)[] ? N : never;\n\n/**\n * Create a type-safe EdgeCollection from an EdgeRegistration.\n * Extracts the edge type and from/to node types automatically.\n */\nexport type TypedEdgeCollection<R extends EdgeRegistration> = EdgeCollection<\n R[\"type\"],\n EdgeFromTypes<R> extends NodeType ? EdgeFromTypes<R> : NodeType,\n EdgeToTypes<R> extends NodeType ? EdgeToTypes<R> : NodeType\n>;\n\n// ============================================================\n// Transaction Types\n// ============================================================\n\n// ============================================================\n// Graph Collection Maps\n// ============================================================\n\n/** Mapped type of all node collections for a graph. */\nexport type GraphNodeCollections<G extends GraphDef> = {\n [K in keyof G[\"nodes\"] & string]-?: NodeCollection<\n G[\"nodes\"][K][\"type\"],\n ConstraintNames<G[\"nodes\"][K]>\n >;\n};\n\n/** Mapped type of all edge collections for a graph. */\nexport type GraphEdgeCollections<G extends GraphDef> = {\n [K in keyof G[\"edges\"] & string]-?: TypedEdgeCollection<G[\"edges\"][K]>;\n};\n\n// ============================================================\n// StoreView read-only collection surfaces\n// ============================================================\n\n/** Temporal-aware node reads — a {@link StoreView} pins these. */\nexport type NodeTemporalReads<\n N extends NodeType,\n CN extends string = string,\n> = Pick<NodeCollection<N, CN>, (typeof NODE_TEMPORAL_READ_NAMES)[number]>;\n\n/**\n * Current-state-only node reads (constraint / index lookups). No temporal\n * axis, so a {@link StoreView} delegates them on a `current` pin and refuses\n * them on a temporal pin.\n */\nexport type NodeCurrentReads<\n N extends NodeType,\n CN extends string = string,\n> = Pick<NodeCollection<N, CN>, (typeof CURRENT_ONLY_READ_NAMES)[number]>;\n\n/** Node writes — never available on a read-only {@link StoreView}. */\nexport type NodeWrites<N extends NodeType, CN extends string = string> = Pick<\n NodeCollection<N, CN>,\n (typeof NODE_WRITE_NAMES)[number]\n>;\n\n/** Temporal-aware edge reads — a {@link StoreView} pins these. */\nexport type EdgeTemporalReads<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<\n EdgeCollection<E, From, To>,\n (typeof EDGE_TEMPORAL_READ_NAMES)[number]\n>;\n\n/**\n * Deferred edge reads for `store.batch()` — absent from a {@link StoreView},\n * which has no batch context.\n */\nexport type EdgeBatchReads<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<EdgeCollection<E, From, To>, (typeof EDGE_BATCH_READ_NAMES)[number]>;\n\n/** Edge writes — never available on a read-only {@link StoreView}. */\nexport type EdgeWrites<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<EdgeCollection<E, From, To>, (typeof EDGE_WRITE_NAMES)[number]>;\n\n/**\n * The read-only node surface a {@link StoreView} exposes for one node kind.\n * The temporal reads drop the per-call temporal argument — the pin owns the\n * axis; the current reads ({@link NodeCurrentReads}) are exposed as-is\n * (delegated on a `current` view, refused on a temporal pin). Writes live on\n * the live `Store`. The conformance test asserts the temporal part equals the\n * pinned form of {@link NodeTemporalReads}.\n */\nexport type StoreViewNodeCollection<\n N extends NodeType,\n CN extends string = string,\n> = Readonly<{\n /** Get a node by ID at the view's pinned coordinate. */\n getById: (id: NodeId<N>) => Promise<Node<N> | undefined>;\n\n /** Get multiple nodes by ID, preserving input order (undefined for missing). */\n getByIds: (\n ids: readonly NodeId<N>[],\n ) => Promise<readonly (Node<N> | undefined)[]>;\n\n /** Find nodes matching criteria at the view's pinned coordinate. */\n find: (\n filter?: Readonly<{\n where?: (accessor: NodeAccessor<N>) => Predicate;\n limit?: number;\n offset?: number;\n }>,\n ) => Promise<Node<N>[]>;\n\n /** Count nodes at the view's pinned coordinate. */\n count: () => Promise<number>;\n}> &\n NodeCurrentReads<N, CN>;\n\n/**\n * The read-only edge surface a {@link StoreView} exposes for one edge\n * kind, mirroring {@link StoreViewNodeCollection}. Every edge read —\n * including `findByEndpoints` — honors the pin via the same temporal model,\n * so (unlike nodes) there are no current-state-only edge reads.\n */\nexport type StoreViewEdgeCollection<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n /** Get an edge by ID at the view's pinned coordinate. */\n getById: (id: EdgeId<E>) => Promise<Edge<E, From, To> | undefined>;\n\n /** Get multiple edges by ID, preserving input order (undefined for missing). */\n getByIds: (\n ids: readonly EdgeId<E>[],\n ) => Promise<readonly (Edge<E, From, To> | undefined)[]>;\n\n /** Find edges matching endpoint and pagination criteria. */\n find: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n limit?: number;\n offset?: number;\n }>,\n ) => Promise<Edge<E, From, To>[]>;\n\n /** Count edges matching criteria at the view's pinned coordinate. */\n count: (\n filter?: Readonly<{ from?: NodeRef<From>; to?: NodeRef<To> }>,\n ) => Promise<number>;\n\n /** Find edges from a specific node at the view's pinned coordinate. */\n findFrom: (from: NodeRef<From>) => Promise<Edge<E, From, To>[]>;\n\n /** Find edges to a specific node at the view's pinned coordinate. */\n findTo: (to: NodeRef<To>) => Promise<Edge<E, From, To>[]>;\n\n /** Find the edge between two endpoints at the view's pinned coordinate. */\n findByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n ) => Promise<Edge<E, From, To> | undefined>;\n}>;\n\n/**\n * Read-only view edge collection derived from an `EdgeRegistration`,\n * extracting the edge type and from/to node types — the read-only\n * counterpart of {@link TypedEdgeCollection}.\n */\nexport type TypedStoreViewEdgeCollection<R extends EdgeRegistration> =\n StoreViewEdgeCollection<\n R[\"type\"],\n EdgeFromTypes<R> extends NodeType ? EdgeFromTypes<R> : NodeType,\n EdgeToTypes<R> extends NodeType ? EdgeToTypes<R> : NodeType\n >;\n\n/** Mapped type of all read-only view node collections for a graph. */\nexport type StoreViewNodeCollections<G extends GraphDef> = {\n [K in keyof G[\"nodes\"] & string]-?: StoreViewNodeCollection<\n G[\"nodes\"][K][\"type\"]\n >;\n};\n\n/** Mapped type of all read-only view edge collections for a graph. */\nexport type StoreViewEdgeCollections<G extends GraphDef> = {\n [K in keyof G[\"edges\"] & string]-?: TypedStoreViewEdgeCollection<\n G[\"edges\"][K]\n >;\n};\n\n/** Recorded-time node point reads for one node kind. */\nexport type RecordedStoreViewNodeCollection<N extends NodeType> = Pick<\n StoreViewNodeCollection<N>,\n (typeof RECORDED_POINT_READ_NAMES)[number]\n>;\n\n/** Recorded-time edge point reads for one edge kind. */\nexport type RecordedStoreViewEdgeCollection<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<\n StoreViewEdgeCollection<E, From, To>,\n (typeof RECORDED_POINT_READ_NAMES)[number]\n>;\n\n/** Recorded-time edge collection derived from an `EdgeRegistration`. */\nexport type TypedRecordedStoreViewEdgeCollection<R extends EdgeRegistration> =\n RecordedStoreViewEdgeCollection<\n R[\"type\"],\n EdgeFromTypes<R> extends NodeType ? EdgeFromTypes<R> : NodeType,\n EdgeToTypes<R> extends NodeType ? EdgeToTypes<R> : NodeType\n >;\n\n/** Mapped type of all recorded-time node point-read collections. */\nexport type RecordedStoreViewNodeCollections<G extends GraphDef> = {\n [K in keyof G[\"nodes\"] & string]-?: RecordedStoreViewNodeCollection<\n G[\"nodes\"][K][\"type\"]\n >;\n};\n\n/** Mapped type of all recorded-time edge point-read collections. */\nexport type RecordedStoreViewEdgeCollections<G extends GraphDef> = {\n [K in keyof G[\"edges\"] & string]-?: TypedRecordedStoreViewEdgeCollection<\n G[\"edges\"][K]\n >;\n};\n\n// ============================================================\n// Transaction Context\n// ============================================================\n\n/**\n * A typed transaction context with collection API.\n *\n * Provides the same `tx.nodes.*` and `tx.edges.*` API as the Store,\n * but operations are executed within the transaction scope.\n *\n * `tx.sql` is the raw Drizzle handle **bound to this same\n * transaction** — use it to write the caller's own relational tables\n * inside the graph-owned transaction so both layers commit or roll\n * back together (the graph-owned counterpart of\n * {@link Store.withTransaction}, where the caller owns the boundary):\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await tx.nodes.Document.update(documentId, props);\n * // `tx.sql` is the `AdoptedTransaction` union — cast to your\n * // concrete Drizzle database type at the call site.\n * const sqlTx = tx.sql as NodePgDatabase;\n * await sqlTx.insert(documentVersions).values(versionRow);\n * await sqlTx.insert(changeEvents).values(eventRow);\n * });\n * ```\n *\n * Per-backend semantics:\n * - **Postgres / libsql** (async drivers): `tx.sql` is the Drizzle\n * transaction handle. Using the outer `db` instead would write on a\n * *different* connection and silently escape the transaction — so\n * `tx.sql` is a correctness requirement there.\n * - **better-sqlite3**: the single connection, framed by TypeGraph's\n * `BEGIN`/`COMMIT`/`ROLLBACK`.\n * - **Durable Objects (`do-sqlite`)**: the bound Drizzle handle; the\n * storage transaction is ambient, so writing the outer `db` also\n * enlists — `tx.sql` is the explicit, portable form.\n *\n * It is `undefined` only on the non-transactional fallback\n * (`backend.capabilities.transactions === false` — e.g. Cloudflare\n * D1, `drizzle-orm/neon-http`), where `store.transaction()` runs the\n * callback with no atomicity and there is no transaction to enlist.\n * Its type is the `AdoptedTransaction` union; cast to your concrete\n * Drizzle database type at the call site.\n *\n * When the store was created with `{ history: true }` or\n * `{ revisionTracking: true }`, `tx.sql` is present but replaced by a fail-loud\n * guard because raw SQL would bypass recorded-time capture or the revision\n * anchor. Use the typed `tx.nodes` / `tx.edges` collections inside\n * `transaction()`, or use `store.withRecordedTransaction(externalTx, fn)` when\n * the relational layer owns the transaction boundary.\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(person, company, { role: \"Engineer\" });\n * });\n * ```\n */\nexport type TransactionContext<G extends GraphDef> = Readonly<{\n nodes: GraphNodeCollections<G>;\n edges: GraphEdgeCollections<G>;\n sql?: AdoptedTransaction;\n /**\n * The transaction-scoped backend the collections are bound to, for advanced\n * raw reads that must observe the transaction's snapshot (e.g. graph-merge's\n * in-transaction base@V re-validation). On the non-transactional fallback it\n * is the store's plain backend — reads work, but there is no snapshot.\n */\n backend: TransactionBackend;\n /**\n * Runtime string-keyed node collection access, mirroring\n * `Store.getNodeCollection` — for callers (e.g. provenance) that resolve a\n * kind dynamically rather than through the static `nodes.<Kind>` property.\n * Returns `undefined` when `kind` is not registered in this graph.\n */\n getNodeCollection(kind: string): DynamicNodeCollection | undefined;\n /**\n * @internal Runs a graph-owned node mutation through this transaction's\n * operation-hook lifecycle when the mutation cannot use a public collection\n * verb directly (provenance fact close/reopen). Routed through the\n * transaction's hook runner, so a successful operation's `onOperationEnd`\n * is deferred until the transaction commits.\n */\n runNodeOperationHooks<T>(\n operation: \"create\" | \"update\" | \"delete\",\n kind: string,\n id: string,\n fn: () => Promise<T>,\n ): Promise<T>;\n}>;\n\n// ============================================================\n// Dynamic Collection Types (widened for runtime dispatch)\n// ============================================================\n\n/**\n * Replace branded `NodeId` / `EdgeId` with plain `string` in each\n * method's parameter list. Return types are preserved unchanged.\n *\n * Handles three shapes:\n * 1. Direct branded ID parameter → `string`\n * 2. `readonly NodeId[]` / `readonly EdgeId[]` → `readonly string[]`\n * 3. Branded IDs nested one level inside bulk-item object arrays\n */\ntype WidenBrandedIds<T> = {\n readonly [K in keyof T]: T[K] extends (...args: infer A) => infer R ?\n (...args: { [P in keyof A]: UnbrandParam<A[P]> }) => R\n : T[K];\n};\n\n/** Replace a branded ID with `string`, recursing one level into arrays. */\ntype UnbrandParam<T> =\n T extends NodeId<NodeType> ? string\n : T extends EdgeId<AnyEdgeType> ? string\n : T extends readonly NodeId<NodeType>[] ? readonly string[]\n : T extends readonly EdgeId<AnyEdgeType>[] ? readonly string[]\n : T extends readonly (infer Item extends Record<string, unknown>)[] ?\n readonly UnbrandRecord<Item>[]\n : T;\n\n/** Replace branded ID values in object properties (does not recurse into nested structures). */\ntype UnbrandRecord<T extends Record<string, unknown>> = {\n readonly [K in keyof T]: T[K] extends NodeId<NodeType> ? string\n : T[K] extends EdgeId<AnyEdgeType> ? string\n : T[K];\n};\n\n/**\n * A node collection with widened generics for runtime string-keyed access.\n *\n * This is the return type of `store.getNodeCollection(kind)`. It exposes\n * the full `NodeCollection` API but with `NodeType` and `string` constraint\n * names instead of the specific generic parameters, since the concrete type\n * is not known at compile time.\n *\n * ID parameters accept plain `string` instead of branded `NodeId<N>`, since\n * the dynamic path typically receives IDs from edge metadata, snapshots,\n * or external input where the brand is not available.\n */\nexport type DynamicNodeCollection = WidenBrandedIds<\n NodeCollection<NodeType, string>\n>;\n\n/**\n * An edge collection with widened generics for runtime string-keyed access.\n *\n * This is the return type of `store.getEdgeCollection(kind)`. It exposes\n * the full `EdgeCollection` API but with `NodeType` endpoint types, since\n * the concrete from/to types are not known at compile time.\n *\n * ID parameters accept plain `string` instead of branded `EdgeId<E>`, since\n * the dynamic path typically receives IDs from edge metadata, snapshots,\n * or external input where the brand is not available.\n */\nexport type DynamicEdgeCollection = WidenBrandedIds<\n EdgeCollection<AnyEdgeType, NodeType, NodeType>\n>;\n\n// ============================================================\n// Store Projection\n// ============================================================\n\n/**\n * A type-level projection of a store's surface onto a subset of its\n * node and edge collections.\n *\n * Node collections are projected with constraint names erased (`never`),\n * so constraint-based methods like `findByConstraint` become uncallable.\n * This is intentional: unique constraints are graph-registration-level\n * details that differ between graphs sharing the same node types.\n *\n * @example\n * ```typescript\n * type CoreStore = StoreProjection<\n * typeof myGraph,\n * \"Document\" | \"Chunk\",\n * \"hasChunk\"\n * >;\n *\n * async function ingestChunk(\n * store: CoreStore,\n * document: Node<typeof Document>,\n * text: string,\n * ) {\n * const chunk = await store.nodes.Chunk.create({ text });\n * await store.edges.hasChunk.create(document, chunk);\n * return chunk;\n * }\n * ```\n *\n * Both `Store<G>` and `TransactionContext<G>` are structurally assignable\n * to a `StoreProjection` whose keys are a subset of `G`.\n */\nexport type StoreProjection<\n G extends GraphDef,\n N extends keyof G[\"nodes\"] & string = never,\n E extends keyof G[\"edges\"] & string = never,\n> = Readonly<{\n nodes: { [K in N]-?: NodeCollection<G[\"nodes\"][K][\"type\"], never> };\n edges: Pick<GraphEdgeCollections<G>, E>;\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 {\n createEdgeRowMapper,\n createNodeRowMapper,\n POSTGRES_ROW_MAPPER_CONFIG,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../backend/drizzle/row-mappers\";\nimport {\n type AdoptedTransaction,\n type GraphBackend,\n runOptionallyInTransaction,\n type SchemaVersionRow,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../backend/types\";\nimport {\n type AllNodeTypes,\n type EdgeKinds,\n type GraphDef,\n isKnownKind,\n type NodeKinds,\n} from \"../core/define-graph\";\nimport { resolveEmbeddingFields } from \"../core/embedding\";\nimport {\n asRecordedInstant,\n type ReadCoordinate,\n type RecordedInstant,\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 EagerMaterializationError,\n KindNotFoundError,\n} from \"../errors\";\nimport {\n buildIncompatibleChangeError,\n classifyModifications,\n type RequireEmptyEntry,\n} 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 { planRemovals, stripGraphExtension } from \"../graph-extension/remove\";\nimport { type VectorIndexDeclaration } from \"../indexes/types\";\nimport type { TraversalExpansion } from \"../query/ast\";\nimport {\n type BatchableQuery,\n type BatchResults,\n createInternalQueryBuilder,\n type InitialQueryBuilder,\n type QueryCoordinateState,\n} from \"../query/builder\";\nimport {\n createRecordedReadBinding,\n createSqlSchema,\n type RecordedReadBinding,\n requireExternalRecordedReadSource,\n requireSqlSchema,\n type SqlSchema,\n} from \"../query/compiler/schema\";\nimport { getDialect } from \"../query/dialect\";\nimport { type VectorSlot } from \"../query/dialect/vector-strategy\";\nimport { buildKindRegistry, type KindRegistry } from \"../registry\";\nimport {\n applyDeprecatedKinds,\n commitNewSchemaVersion,\n ensureSchema as ensureSchemaImpl,\n loadActiveSchemaWithBootstrap,\n loadAndMergeGraphExtensionDocument,\n loadAndVerifyGraph,\n parseSerializedSchema,\n type SchemaManagerOptions,\n type SchemaValidationResult,\n} from \"../schema/manager\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { nowIso } from \"../utils/date\";\nimport { generateId } from \"../utils/id\";\nimport {\n createGraphAlgorithms,\n type GraphAlgorithms,\n type InternalGraphAlgorithms,\n} from \"./algorithms\";\nimport {\n createEdgeCollectionsProxy,\n createNodeCollectionsProxy,\n type EdgeOperations,\n type NodeOperations,\n} from \"./collection-factory\";\nimport { resolveTemporalReadParams } from \"./collections/temporal-read-params\";\nimport { introspectSchema, type SchemaIntrospection } from \"./introspect\";\nimport {\n computeIndexSignature,\n materializeIndexes as materializeIndexesImpl,\n type MaterializeIndexesOptions,\n type MaterializeIndexesResult,\n vectorStatusKey,\n} from \"./materialize-indexes\";\nimport {\n buildPendingKindRemoval,\n materializeRemovals as materializeRemovalsImpl,\n type MaterializeRemovalsOptions,\n type MaterializeRemovalsResult,\n} from \"./materialize-removals\";\nimport {\n type EdgeOperationContext,\n executeEdgeBulkGetOrCreateByEndpoints,\n executeEdgeCreate,\n executeEdgeCreateBatch,\n executeEdgeCreateNoReturnBatch,\n executeEdgeDelete,\n executeEdgeFindByEndpoints,\n executeEdgeGetOrCreateByEndpoints,\n executeEdgeHardDelete,\n executeEdgeUpdate,\n executeEdgeUpsertUpdate,\n executeNodeBulkFindByConstraint,\n executeNodeBulkFindByIndex,\n executeNodeBulkGetOrCreateByConstraint,\n executeNodeCreate,\n executeNodeCreateBatch,\n executeNodeCreateNoReturnBatch,\n executeNodeDelete,\n executeNodeFindByConstraint,\n executeNodeGetOrCreateByConstraint,\n executeNodeHardDelete,\n executeNodeUpdate,\n executeNodeUpsertUpdate,\n type NodeOperationContext,\n} from \"./operations\";\nimport {\n advanceRevisionClock,\n assertRecordedCaptureTransactionIsolation,\n assertRevisionTrackableBackend,\n createHistoryUnsafeSqlRef,\n createRecordedBackend,\n createRecordedTransactionScope,\n createRevisionTrackingUnsafeSqlRef,\n ensureRevisionOrigin,\n lockRecordedGraphWrite,\n readRecordedClock,\n recordedCaptureRequiresCallbackTransactionError,\n type RecordedFlushInstants,\n withRecordedFlushObserver,\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 { StoreSearch } from \"./search-facade\";\nimport {\n RecordedStoreView,\n StoreView,\n type StoreViewCoordinate,\n} from \"./store-view\";\nimport {\n executeSubgraph,\n type InternalSubgraphOptions,\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\n createTransactionReceiptRecorder,\n type TransactionReceiptRecorder,\n wrapTransactionCollections,\n} from \"./transaction-receipt\";\nimport {\n AUTO_REFRESH_STATISTICS_ROW_THRESHOLD,\n type DynamicEdgeCollection,\n type DynamicNodeCollection,\n type Edge,\n type GraphEdgeCollections,\n type GraphNodeCollections,\n type HistoryStoreOptions,\n type HookContext,\n type LiveStoreOptions,\n type Node,\n type OperationHookContext,\n type QueryOptions,\n type StoreHooks,\n type StoreOptions,\n type StoreRef,\n type TransactionContext,\n type TransactionOutcome,\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\" | \"materialize\" | \"deprecate\" | \"undeprecate\" | \"remove\" | \"reembed\";\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};\n\nfunction rowMapperConfigFor(backend: GraphBackend | TransactionBackend) {\n return backend.dialect === \"postgres\" ?\n POSTGRES_ROW_MAPPER_CONFIG\n : SQLITE_ROW_MAPPER_CONFIG;\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/** 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) => Promise<T>;\n\n/** A committed-inside-the-transaction operation awaiting the outer COMMIT. */\ntype PendingOperationOutcome = Readonly<{\n ctx: OperationHookContext;\n durationMs: number;\n}>;\n\ntype TransactionRunResult<T> = Readonly<{\n result: T;\n recordedByGraph: RecordedFlushInstants | undefined;\n}>;\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\nexport class Store<G extends GraphDef> {\n readonly #graph: G;\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 readonly #captureEnabled: boolean;\n readonly #revisionTrackingEnabled: boolean;\n #revisionOrigin: Promise<string> | undefined;\n readonly #recordedReadBinding: RecordedReadBinding | undefined;\n readonly #registry: KindRegistry;\n readonly #hooks: StoreHooks;\n readonly #schema: StoreOptions[\"schema\"];\n readonly #recordedReads: RecordedReadService;\n readonly #schemaMetadata: StoreSchemaMetadata;\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\n constructor(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n schemaMetadata?: StoreSchemaMetadata,\n ) {\n this.#graph = graph;\n this.#baseBackend = asRawBackend(backend);\n this.#captureEnabled = options?.history === true;\n this.#revisionTrackingEnabled =\n this.#captureEnabled || options?.revisionTracking === true;\n if (this.#revisionTrackingEnabled) {\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 ?\n createRecordedReadBinding(readSchema)\n : externalRecordedRead;\n this.#backend =\n this.#captureEnabled ?\n asGraphWriteBackend(createRecordedBackend(backend, resolvedSchema))\n : asGraphWriteBackend(backend);\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 }\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 /** The kind registry for ontology lookups */\n get registry(): KindRegistry {\n return this.#registry;\n }\n\n /** The database backend */\n get backend(): GraphBackend {\n return this.#backend;\n }\n\n /**\n * Whether recorded-time capture is enabled for this store.\n *\n * @internal\n */\n get historyEnabled(): boolean {\n return this.#captureEnabled;\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 // === 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.#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.#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 * Each call compiles to a single recursive-CTE query against the backend.\n * The facade is built lazily on first access and cached for the lifetime\n * 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 /**\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(\n collections: GraphNodeCollections<G>,\n kind: string,\n ): DynamicNodeCollection | 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;\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(kind: string): DynamicNodeCollection | 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 a new store, the caller immediately operates on the new\n * kind, and the null-check the optional variant requires is busywork.\n */\n getNodeCollectionOrThrow(kind: string): DynamicNodeCollection {\n const collection = this.getNodeCollection(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(kind: string): DynamicEdgeCollection | undefined {\n if (!Object.hasOwn(this.#graph.edges, kind)) return undefined;\n return this.edges[\n kind as keyof G[\"edges\"] & string\n ] as unknown as DynamicEdgeCollection;\n }\n\n /**\n * Returns the edge collection for the given kind. Throws\n * `KindNotFoundError` when the kind is not registered.\n */\n getEdgeCollectionOrThrow(kind: string): DynamicEdgeCollection {\n const collection = this.getEdgeCollection(kind);\n if (collection === undefined) {\n throw new KindNotFoundError(kind, \"edge\", {\n graphId: this.graphId,\n });\n }\n return collection;\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 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 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 * 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) =>\n executeNodeCreateBatch(ctx, inputs, backend),\n executeCreateNoReturnBatch: (inputs, backend) =>\n executeNodeCreateNoReturnBatch(ctx, inputs, backend),\n executeUpdate: (input, backend, options) =>\n executeNodeUpdate(ctx, { ...input, id: input.id }, backend, options),\n executeUpsertUpdate: (input, backend, options) =>\n executeNodeUpsertUpdate(\n ctx,\n { ...input, id: input.id },\n backend,\n options,\n ),\n executeDelete: (kind, id, backend) =>\n executeNodeDelete(ctx, kind, id, 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 executeUpsertUpdate: (input, backend, options) =>\n executeEdgeUpsertUpdate(ctx, input, backend, options),\n executeDelete: (id, backend) => executeEdgeDelete(ctx, id, backend),\n executeHardDelete: (id, backend) =>\n executeEdgeHardDelete(ctx, 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 * 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 /**\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 // === 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 as of `T` and uses the same `T` for the valid-time\n * axis. Use `store.asOf(validT).asOfRecorded(recordedT)` when the valid and\n * recorded 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()` as the anchor over a wall-clock\n * timestamp: recorded instants are monotonic and can run briefly ahead of the\n * wall clock under bursty writes, so a `new Date().toISOString()` passed here\n * may sort before the most recent commits and silently omit them.\n */\n asOfRecorded(recordedAsOf: RecordedInstant): RecordedStoreView<G> {\n const validCoordinate = resolveReadCoordinate(\n \"asOf\",\n 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 (recorded\n * instants are monotonic and can run briefly ahead of wall-clock time under\n * bursty writes). Capture each anchor right 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.#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 * 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 * @internal\n */\n async revisionNow(): Promise<string | undefined> {\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 * @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 const pendingOrigin =\n this.#revisionOrigin ??\n ensureRevisionOrigin(this.#baseBackend, this.#sqlSchema(), this.graphId);\n this.#revisionOrigin = pendingOrigin;\n try {\n return await pendingOrigin;\n } catch (error) {\n // A transient DDL/connection failure must not permanently poison this\n // Store's cached initialization promise. Preserve a newer in-flight\n // attempt if another caller replaced it before this rejection arrived.\n if (this.#revisionOrigin === pendingOrigin) {\n this.#revisionOrigin = undefined;\n }\n throw error;\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 });\n }\n return this.#search;\n }\n\n // === Batch Query Execution ===\n\n /**\n * Executes multiple queries and returns a typed tuple of results.\n *\n * Each query preserves its own result type, projection, filtering, sorting,\n * and pagination.\n *\n * **Snapshot consistency is conditional.** When\n * `backend.capabilities.transactions` is `true`, queries run sequentially\n * on a single connection inside an implicit transaction and observe the\n * same database snapshot. When transactions are unavailable\n * (Cloudflare D1, `drizzle-orm/neon-http`), queries run sequentially over\n * independent connections and may observe writes that landed between them.\n * Branch on `backend.capabilities.transactions` if you need a guaranteed\n * snapshot.\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 results: unknown[] = [];\n for (const query of queries) {\n const result = await query.executeOn(target);\n results.push(result);\n }\n return results as BatchResults<Queries>;\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 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 // 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 /**\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.sql` - the raw Drizzle handle **bound to this same\n * transaction**, for writing the caller's own relational tables in\n * the same atomic boundary (the graph-owned counterpart of\n * {@link Store.withTransaction}). See {@link TransactionContext}\n * for per-backend semantics; it is `undefined` only on the\n * non-transactional fallback.\n * When the store was created with `{ history: true }` or\n * `{ revisionTracking: true }`, `tx.sql` is replaced by a fail-loud guard\n * because raw SQL would bypass recorded-time capture or revision tracking;\n * use the typed collections inside\n * `transaction()` or {@link Store.withRecordedTransaction}.\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 * // cast `tx.sql` to your concrete Drizzle database type\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.transactions`\n * is `false` (Cloudflare D1, `drizzle-orm/neon-http`), this method runs the\n * callback against the same backend used outside `transaction()` — writes\n * are applied as they happen and a thrown error does **not** roll back\n * earlier writes inside the callback. Branch on\n * `backend.capabilities.transactions` if you require atomicity:\n *\n * ```typescript\n * if (backend.capabilities.transactions) {\n * await store.transaction(async (tx) => { ... });\n * } else {\n * // sequential, non-atomic — handle partial-failure recovery yourself\n * }\n * ```\n *\n * @param fn The callback run inside the transaction boundary.\n * @param options Optional {@link TransactionOptions} forwarded to the\n * backend (e.g. `isolationLevel: \"serializable\"` on Postgres). Backends\n * without isolation-level support ignore it; the non-transactional\n * fallback ignores it entirely. Stores created with `{ history: true }`\n * require read-committed semantics for PostgreSQL recorded-clock capture and\n * reject stronger snapshot isolation levels.\n */\n transaction<T>(\n this: HistoryStore<G>,\n fn: (tx: HistoryTransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T>;\n\n transaction<T>(\n fn: (tx: TransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T>;\n\n async transaction<T>(\n fn:\n | ((tx: TransactionContext<G>) => Promise<T>)\n | ((tx: HistoryTransactionContext<G>) => Promise<T>),\n options?: TransactionOptions,\n ): Promise<T> {\n const invoke = fn as (tx: TransactionContext<G>) => Promise<T>;\n const { result } = await this.#runTransaction(invoke, options, undefined);\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. Adopted transactions (`withTransaction` /\n * `withRecordedTransaction`) do not produce receipts in this version\n * because their commit belongs to the caller. On non-transactional\n * backends, the receipt is still returned, but it describes operations\n * that individually committed rather than one atomic commit; if the\n * callback rejects on such a backend, no receipt is returned even though\n * earlier operations committed individually.\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.\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: HistoryStore<G>,\n fn: (tx: HistoryTransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>>;\n\n transactionWithReceipt<T>(\n fn: (tx: TransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>>;\n\n async transactionWithReceipt<T>(\n fn:\n | ((tx: TransactionContext<G>) => Promise<T>)\n | ((tx: HistoryTransactionContext<G>) => Promise<T>),\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>> {\n const invoke = fn as (tx: TransactionContext<G>) => Promise<T>;\n const receiptRecorder = createTransactionReceiptRecorder();\n const { result, recordedByGraph } = await this.#runTransaction(\n invoke,\n options,\n receiptRecorder,\n );\n return transactionOutcome(\n result,\n receiptRecorder,\n recordedByGraph,\n this.graphId,\n );\n }\n\n async #runTransaction<T>(\n invoke: (tx: TransactionContext<G>) => Promise<T>,\n backendOptions: TransactionOptions | undefined,\n receiptRecorder: TransactionReceiptRecorder | undefined,\n ): Promise<TransactionRunResult<T>> {\n // Without a real transaction the tx-scoped collections would be\n // bound to the same backend as this.nodes/this.edges and exposing\n // the cached versions avoids rebuilding the proxies on every call.\n // An isolation-level request in the options is equally meaningless here.\n if (!this.#backend.capabilities.transactions) {\n let nodes = this.nodes;\n let edges = this.edges;\n if (receiptRecorder !== undefined) {\n ({ nodes, edges } = wrapTransactionCollections(\n nodes,\n edges,\n receiptRecorder,\n ));\n }\n const result = await invoke({\n nodes,\n edges,\n backend: this.#backend,\n getNodeCollection: (kind) =>\n this.#resolveDynamicNodeCollection(nodes, kind),\n // No transaction, no deferral: operations apply as they happen, so\n // their hooks fire immediately.\n runNodeOperationHooks: (operation, kind, id, hookedFunction) =>\n this.#withOperationHooks(\n this.#createOperationContext(operation, \"node\", kind, id),\n hookedFunction,\n ),\n });\n return { result, recordedByGraph: undefined };\n }\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 // No per-graph write lock here either: under history capture the lock is\n // taken at each write boundary (runInWriteTransaction before any row work;\n // the recorded overlay before each row write), so a transaction whose\n // callback only reads never serializes against writers. Callers that need\n // read-before-write serialization across the whole callback (provenance\n // transitions) acquire the lock explicitly at callback start.\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 const pending: PendingOperationOutcome[] = [];\n const runHooks = this.#createBufferedHookRunner(pending);\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 result = await this.#backend.transaction(\n async (txBackend, sql) =>\n invoke(\n this.#buildTransactionContext(\n txBackend,\n sql,\n runHooks,\n receiptRecorder,\n ),\n ),\n transactionOptions,\n );\n for (const outcome of pending) {\n this.#hooks.onOperationEnd?.(outcome.ctx, {\n durationMs: outcome.durationMs,\n });\n }\n return { result, recordedByGraph };\n } catch (error) {\n const failure = asError(error);\n for (const outcome of pending) {\n this.#hooks.onError?.(outcome.ctx, failure);\n }\n throw error;\n }\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 * `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 `createStoreWithSchema` 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, so this throws `ConfigurationError`\n * (`RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`). Use\n * {@link Store.withRecordedTransaction} on a history-enabled store, which\n * adopts the same external transaction but flushes recorded-time capture\n * before the caller commits.\n *\n * @throws {ConfigurationError} when the store has history capture enabled\n * (use {@link Store.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.transactions` 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 * `createStoreWithSchema`). Rolls back the caller's transaction\n * without emitting any DDL.\n */\n withTransaction(externalTx: AdoptedTransaction): TransactionContext<G> {\n if (this.#captureEnabled) {\n throw recordedCaptureRequiresCallbackTransactionError({\n code: \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n });\n }\n const adopt = this.#backend.adoptTransaction;\n if (!adopt) {\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.transactions, 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.\n *\n * Like {@link Store.withTransaction}, the graph writes and any raw `tx.sql`\n * statements share the caller's one pinned connection. TypeGraph serializes\n * the statements its collections issue; sequence your own raw statements (and\n * don't `Promise.all` them with graph writes) so two queries never race on\n * that connection.\n */\n withRecordedTransaction<T>(\n this: HistoryStore<G>,\n externalTx: AdoptedTransaction,\n fn: (tx: HistoryTransactionContext<G>) => Promise<T>,\n ): Promise<T>;\n\n withRecordedTransaction<T>(\n externalTx: AdoptedTransaction,\n fn: (tx: TransactionContext<G>) => Promise<T>,\n ): Promise<T>;\n\n async withRecordedTransaction<T>(\n externalTx: AdoptedTransaction,\n fn:\n | ((tx: TransactionContext<G>) => Promise<T>)\n | ((tx: HistoryTransactionContext<G>) => Promise<T>),\n ): Promise<T> {\n const adopt = this.#baseBackend.adoptTransaction;\n if (!adopt) {\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 with transaction support, or run writes through store.transaction(...).\",\n },\n );\n }\n const txBackend = adopt(externalTx);\n if (this.#captureEnabled) {\n await assertRecordedCaptureTransactionIsolation(txBackend);\n }\n const scope =\n this.#captureEnabled ?\n createRecordedTransactionScope(txBackend, this.#sqlSchema())\n : {\n backend: txBackend,\n flush: () => Promise.resolve(),\n };\n if (this.#captureEnabled) {\n await lockRecordedGraphWrite(scope.backend, this.graphId);\n }\n const invoke = fn as (tx: TransactionContext<G>) => Promise<T>;\n const result = await invoke(\n this.#buildTransactionContext(scope.backend, externalTx),\n );\n await scope.flush();\n return result;\n }\n\n /**\n * Builds the `{ nodes, edges, sql }` projection bound to a\n * transaction-scoped 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?: AdoptedTransaction,\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n receiptRecorder?: TransactionReceiptRecorder,\n ): TransactionContext<G> {\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(this.#createNodeOperationContext(runHooks)),\n createQuery: () => this.#createQueryForBackend(txBackend),\n maybeRefreshStatisticsAfterBulk: undefined,\n };\n const txEdgeOperations: EdgeOperations = {\n ...this.#buildEdgeOperations(this.#createEdgeOperationContext(runHooks)),\n createQuery: () => this.#createQueryForBackend(txBackend),\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(this.#createOperationContext(operation, \"node\", kind, id), fn);\n\n let nodes = createNodeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txNodeOperations,\n );\n\n let edges = createEdgeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txEdgeOperations,\n );\n\n if (receiptRecorder !== undefined) {\n ({ nodes, edges } = wrapTransactionCollections(\n nodes,\n edges,\n receiptRecorder,\n ));\n }\n\n const getNodeCollection = (\n kind: string,\n ): DynamicNodeCollection | undefined =>\n this.#resolveDynamicNodeCollection(nodes, kind);\n\n if (sql === undefined) {\n return {\n nodes,\n edges,\n backend: txBackend,\n getNodeCollection,\n runNodeOperationHooks,\n };\n }\n const exposedSql =\n this.#captureEnabled ? createHistoryUnsafeSqlRef()\n : this.#revisionTrackingEnabled ? createRevisionTrackingUnsafeSqlRef()\n : sql;\n return {\n nodes,\n edges,\n sql: exposedSql,\n backend: txBackend,\n getNodeCollection,\n runNodeOperationHooks,\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 const doClear = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n if (this.#revisionTrackingEnabled) {\n await lockRecordedGraphWrite(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 // `clearGraph` deletes the recorded-clock row alongside graph data.\n // Live revision tracking immediately seeds a fresh anchor so a pre-clear\n // branch cannot match a now-empty graph. History capture intentionally\n // preserves its long-standing `recordedNow() === undefined` clear\n // contract; a pre-clear history branch already carries a non-empty clock\n // value and therefore still fails the base-version precondition.\n if (this.#revisionTrackingEnabled && !this.#captureEnabled) {\n await advanceRevisionClock(\n target,\n this.#sqlSchema(),\n this.graphId,\n this.#baseBackend.capabilities.transactions,\n previousRevision,\n );\n }\n };\n\n await (this.#baseBackend.capabilities.transactions ?\n this.#baseBackend.transaction(async (tx) => doClear(tx))\n : doClear(this.#baseBackend));\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 // 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 /**\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 a fresh `Store` constructed against the merged graph.\n *\n * The `Store` is immutable — its registry, collections, and operation\n * contexts close over the graph at construction time — so callers\n * must use the returned store (or pass a `ref` to be re-pointed) for\n * any work involving the new kinds.\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\n * atomically with the schema commit. Long-lived consumers\n * (request handlers, background workers) that dereference through\n * the ref see the new kinds on the *next* call.\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(\n extension: GraphExtension,\n options?: Readonly<{\n ref?: StoreRef<Store<G>>;\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<Store<G>> {\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, baseline } = 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 if (options?.ref !== undefined) options.ref.current = 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 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 if (classification.requireEmpty.length > 0) {\n const nonEmpty = await this.#probeEmptyKinds(classification.requireEmpty);\n const error = buildIncompatibleChangeError(\n classification,\n nonEmpty,\n this.graphId,\n );\n if (error !== undefined) throw error;\n }\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 const committed = await commitNewSchemaVersion(\n this.#backend,\n merged,\n activeRow.version,\n );\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: Store<G>,\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 atomically\n * with the schema commit, 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(\n names: readonly string[],\n options?: Readonly<{ ref?: StoreRef<Store<G>> }>,\n ): Promise<Store<G>> {\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 atomically\n * with the schema commit.\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(\n names: readonly string[],\n options?: Readonly<{ ref?: StoreRef<Store<G>> }>,\n ): Promise<Store<G>> {\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 * 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-emit the table DDL\n // the strategy owns (libSQL/sqlite-vec also (re)create their index/vtable\n // here; pgvector's index is built via createVectorIndex below). Run via\n // executeDdl directly so it bypasses the ensure-latch, which may still\n // record the pre-drop slot as ensured.\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 // 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 * 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(\n names: readonly string[],\n options?: Readonly<{\n ref?: StoreRef<Store<G>>;\n eager?: MaterializeRemovalsOptions;\n }>,\n ): Promise<Store<G>> {\n const { activeRow, baseline } = 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 if (options?.ref !== undefined) options.ref.current = 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 committedRow = await commitNewSchemaVersion(\n this.#backend,\n finalGraph,\n activeRow.version,\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 if (this.#backend.ensureKindRemovalsTable !== undefined) {\n await 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 * 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(\n direction: \"add\" | \"remove\",\n names: readonly string[],\n options: Readonly<{ ref?: StoreRef<Store<G>> }> | undefined,\n ): Promise<Store<G>> {\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 if (options?.ref !== undefined) options.ref.current = 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 * Probes each `requireEmpty` entry for any rows. Returns the set of\n * composite keys (`${entity}:${kindName}`) that have at least one\n * row — those entries need to be promoted from \"allowed-on-empty\"\n * to incompatible. Dispatches to `countNodesByKind` for `node`\n * entries and `countEdgesByKind` for `edge` entries (a single-\n * primitive probe would always return 0 for the wrong-entity case\n * and silently bypass the gate).\n *\n * Probes run in parallel; each entry is independent. Race window\n * (probe → CAS commit): another writer can insert a row into a\n * previously-empty kind. The schema commit still succeeds (CAS\n * guards on schema version, not row count); the new schema rejects\n * the inserted row at next read, which the operator inspects and\n * either deletes or reverts. Rare in practice; tighter elimination\n * would require `SELECT FOR UPDATE` on the rows table, too\n * heavyweight for a millisecond-budget operation.\n */\n async #probeEmptyKinds(\n requireEmpty: readonly RequireEmptyEntry[],\n ): Promise<Set<RequireEmptyEntry>> {\n const probes = requireEmpty.map(\n async (entry): Promise<readonly [RequireEmptyEntry, number]> => {\n const count =\n entry.entity === \"node\" ?\n await this.#backend.countNodesByKind({\n graphId: this.graphId,\n kind: entry.kindName,\n })\n : await this.#backend.countEdgesByKind({\n graphId: this.graphId,\n kind: entry.kindName,\n });\n return [entry, count];\n },\n );\n const results = await Promise.all(probes);\n const nonEmpty = new Set<RequireEmptyEntry>();\n for (const [entry, count] of results) {\n if (count > 0) nonEmpty.add(entry);\n }\n return nonEmpty;\n }\n\n #cloneWithGraph(\n graph: G,\n ref: StoreRef<Store<G>> | undefined,\n schemaMetadata: StoreSchemaMetadata = this.#schemaMetadata,\n ): Store<G> {\n const next = new Store(\n graph,\n this.#baseBackend,\n this.#options,\n schemaMetadata,\n );\n if (ref !== undefined) ref.current = 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>(ctx: OperationHookContext, fn: () => Promise<T>) =>\n this.#withOperationHooks(ctx, fn);\n }\n\n #createNodeOperationContext(\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n ): NodeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n historyEnabled: this.#captureEnabled,\n revisionTrackingEnabled: this.#revisionTrackingEnabled,\n revisionSchema: this.#sqlSchema(),\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: runHooks,\n };\n }\n\n #createEdgeOperationContext(\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n ): EdgeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n historyEnabled: this.#captureEnabled,\n revisionTrackingEnabled: this.#revisionTrackingEnabled,\n revisionSchema: this.#sqlSchema(),\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: runHooks,\n };\n }\n\n // === Internal: Hook Helpers ===\n\n #createHookContext(): HookContext {\n return {\n operationId: generateId(),\n graphId: this.graphId,\n startedAt: new Date(),\n };\n }\n\n #createOperationContext(\n operation: \"create\" | \"update\" | \"delete\",\n entity: KindEntity,\n kind: string,\n id: string,\n ): OperationHookContext {\n return {\n ...this.#createHookContext(),\n operation,\n entity,\n kind,\n id,\n };\n }\n\n async #withOperationHooks<T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\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 });\n return result;\n } catch (error) {\n this.#hooks.onError?.(ctx, asError(error));\n throw error;\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 ): Promise<T> => {\n this.#hooks.onOperationStart?.(ctx);\n const startTime = Date.now();\n try {\n const result = await fn();\n pending.push({ ctx, durationMs: Date.now() - startTime });\n return result;\n } catch (error) {\n this.#hooks.onError?.(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) return false;\n if (asOf !== undefined && row.valid_from && asOf < row.valid_from)\n return false;\n if (asOf !== undefined && row.valid_to && asOf >= row.valid_to)\n return false;\n return true;\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 ): InitialQueryBuilder<G, CoordinateState> {\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: backend as GraphBackend,\n dialect: backend.dialect,\n defaultTraversalExpansion: this.#defaultTraversalExpansion,\n ...(this.#schema !== undefined && { schema: this.#schema }),\n ...(this.#recordedReadBinding !== undefined && {\n recordedReadBinding: this.#recordedReadBinding,\n }),\n ...(sealedCoordinate !== undefined && { sealedCoordinate }),\n },\n );\n }\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\nexport type HistorySafeBackend = Omit<\n GraphBackend,\n \"executeStatement\" | \"executeDdl\"\n> &\n Readonly<{\n executeStatement?: never;\n executeDdl?: never;\n }>;\n\nexport type HistorySafeTransactionBackend = Omit<\n TransactionBackend,\n \"executeStatement\" | \"executeDdl\"\n> &\n Readonly<{\n executeStatement?: never;\n executeDdl?: never;\n }>;\n\nexport type HistoryTransactionContext<G extends GraphDef> = Omit<\n TransactionContext<G>,\n \"backend\" | \"sql\"\n> &\n Readonly<{\n backend: HistorySafeTransactionBackend;\n sql?: never;\n }>;\n\nexport type RecordedReadStore<G extends GraphDef> = Store<G> &\n Readonly<{\n recordedReadBound: true;\n }>;\n\nexport type HistoryStore<G extends GraphDef> = Store<G> &\n Readonly<{\n backend: HistorySafeBackend;\n historyEnabled: true;\n recordedReadBound: true;\n }>;\n\ntype ExplicitRecordedReadLiveOptions = LiveStoreOptions &\n Readonly<{ recordedRead: NonNullable<LiveStoreOptions[\"recordedRead\"]> }>;\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: ExplicitRecordedReadLiveOptions,\n): RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n): Store<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 Store(graph, backend, options);\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 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// 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 *\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: ExplicitRecordedReadLiveOptions & SchemaManagerOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions & SchemaManagerOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\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 // 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 result = await ensureSchemaImpl(backend, merged, {\n ...options,\n preloaded: { activeRow, storedSchema },\n });\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\n const store = new Store(\n merged,\n backend,\n options,\n schemaMetadataForResult(activeRow, result),\n );\n return [store, result];\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 * - **`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: ExplicitRecordedReadLiveOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\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 {\n graph: merged,\n activeRow,\n result,\n } = await loadAndVerifyGraph(backend, graph);\n const store = new Store(\n merged,\n backend,\n options,\n schemaMetadataFromRow(activeRow),\n );\n return [store, result];\n}\n"]}