@nicia-ai/typegraph 0.31.0 → 0.33.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 (188) hide show
  1. package/README.md +31 -0
  2. package/dist/backend/postgres/index.cjs +31 -18
  3. package/dist/backend/postgres/index.d.cts +6 -6
  4. package/dist/backend/postgres/index.d.ts +6 -6
  5. package/dist/backend/postgres/index.js +9 -8
  6. package/dist/backend/postgres/pglite.cjs +13 -12
  7. package/dist/backend/postgres/pglite.cjs.map +1 -1
  8. package/dist/backend/postgres/pglite.d.cts +3 -3
  9. package/dist/backend/postgres/pglite.d.ts +3 -3
  10. package/dist/backend/postgres/pglite.js +9 -8
  11. package/dist/backend/postgres/pglite.js.map +1 -1
  12. package/dist/backend/sqlite/index.cjs +29 -16
  13. package/dist/backend/sqlite/index.d.cts +7 -7
  14. package/dist/backend/sqlite/index.d.ts +7 -7
  15. package/dist/backend/sqlite/index.js +8 -7
  16. package/dist/backend/sqlite/libsql.cjs +13 -12
  17. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  18. package/dist/backend/sqlite/libsql.d.cts +3 -3
  19. package/dist/backend/sqlite/libsql.d.ts +3 -3
  20. package/dist/backend/sqlite/libsql.js +9 -8
  21. package/dist/backend/sqlite/libsql.js.map +1 -1
  22. package/dist/backend/sqlite/local.cjs +14 -13
  23. package/dist/backend/sqlite/local.cjs.map +1 -1
  24. package/dist/backend/sqlite/local.d.cts +3 -3
  25. package/dist/backend/sqlite/local.d.ts +3 -3
  26. package/dist/backend/sqlite/local.js +9 -8
  27. package/dist/backend/sqlite/local.js.map +1 -1
  28. package/dist/{chunk-SFFJ2IKN.cjs → chunk-3642VBVC.cjs} +70 -68
  29. package/dist/chunk-3642VBVC.cjs.map +1 -0
  30. package/dist/chunk-3E7SNSIA.cjs +55 -0
  31. package/dist/chunk-3E7SNSIA.cjs.map +1 -0
  32. package/dist/{chunk-6RMLO5O4.cjs → chunk-3IR2GEMJ.cjs} +8 -7
  33. package/dist/chunk-3IR2GEMJ.cjs.map +1 -0
  34. package/dist/{chunk-6SA7UIQJ.cjs → chunk-3QRBXYT5.cjs} +6 -6
  35. package/dist/{chunk-6SA7UIQJ.cjs.map → chunk-3QRBXYT5.cjs.map} +1 -1
  36. package/dist/{chunk-54JVNOAQ.cjs → chunk-4RBAJVEC.cjs} +128 -6
  37. package/dist/chunk-4RBAJVEC.cjs.map +1 -0
  38. package/dist/{chunk-IJORSAC3.js → chunk-6NRFUHMS.js} +4 -3
  39. package/dist/chunk-6NRFUHMS.js.map +1 -0
  40. package/dist/{chunk-FLOI7QOT.cjs → chunk-BF3ZDEUE.cjs} +104 -72
  41. package/dist/chunk-BF3ZDEUE.cjs.map +1 -0
  42. package/dist/{chunk-2HZGWCB4.js → chunk-C4C4Q7A6.js} +3 -3
  43. package/dist/chunk-C4C4Q7A6.js.map +1 -0
  44. package/dist/{chunk-O4VUR6SI.js → chunk-CEF2QOTO.js} +3 -3
  45. package/dist/{chunk-O4VUR6SI.js.map → chunk-CEF2QOTO.js.map} +1 -1
  46. package/dist/{chunk-V4IQYOQ4.cjs → chunk-CFNT3ITG.cjs} +3 -3
  47. package/dist/chunk-CFNT3ITG.cjs.map +1 -0
  48. package/dist/{chunk-LJLMDDCW.js → chunk-CWFPJ3RC.js} +3 -3
  49. package/dist/{chunk-LJLMDDCW.js.map → chunk-CWFPJ3RC.js.map} +1 -1
  50. package/dist/{chunk-RZ4DH4E7.cjs → chunk-D3EWZ67S.cjs} +3348 -2030
  51. package/dist/chunk-D3EWZ67S.cjs.map +1 -0
  52. package/dist/{chunk-GKFWM3DS.js → chunk-DJYRRDHA.js} +124 -5
  53. package/dist/chunk-DJYRRDHA.js.map +1 -0
  54. package/dist/{chunk-YQGLVWB2.cjs → chunk-EF3Z645U.cjs} +2 -52
  55. package/dist/chunk-EF3Z645U.cjs.map +1 -0
  56. package/dist/{chunk-ASYQDPPU.cjs → chunk-FDN43KXV.cjs} +19 -19
  57. package/dist/{chunk-ASYQDPPU.cjs.map → chunk-FDN43KXV.cjs.map} +1 -1
  58. package/dist/chunk-GYVBEZAO.js +120 -0
  59. package/dist/chunk-GYVBEZAO.js.map +1 -0
  60. package/dist/chunk-I4W7MKVG.cjs +1526 -0
  61. package/dist/chunk-I4W7MKVG.cjs.map +1 -0
  62. package/dist/{chunk-MXE2U3EX.js → chunk-IZ4PCL47.js} +3 -52
  63. package/dist/chunk-IZ4PCL47.js.map +1 -0
  64. package/dist/{chunk-4A4GUZTQ.js → chunk-JHOBXD7O.js} +10 -8
  65. package/dist/chunk-JHOBXD7O.js.map +1 -0
  66. package/dist/{chunk-CIINW6PS.cjs → chunk-KY5SDVA7.cjs} +676 -635
  67. package/dist/chunk-KY5SDVA7.cjs.map +1 -0
  68. package/dist/{chunk-N2MBPTAF.cjs → chunk-LM2IC4ZJ.cjs} +14 -14
  69. package/dist/{chunk-N2MBPTAF.cjs.map → chunk-LM2IC4ZJ.cjs.map} +1 -1
  70. package/dist/{chunk-7JGLPAFV.cjs → chunk-MBLXCV2Y.cjs} +16 -16
  71. package/dist/chunk-MBLXCV2Y.cjs.map +1 -0
  72. package/dist/{chunk-5DTPBFX5.cjs → chunk-NG5N7R45.cjs} +28 -28
  73. package/dist/{chunk-5DTPBFX5.cjs.map → chunk-NG5N7R45.cjs.map} +1 -1
  74. package/dist/chunk-OIE2UPVG.cjs +126 -0
  75. package/dist/chunk-OIE2UPVG.cjs.map +1 -0
  76. package/dist/{chunk-STP7QVUB.js → chunk-OS6KS3HV.js} +43 -11
  77. package/dist/chunk-OS6KS3HV.js.map +1 -0
  78. package/dist/{chunk-2ZY4K43M.js → chunk-PIHXFF73.js} +3 -3
  79. package/dist/{chunk-2ZY4K43M.js.map → chunk-PIHXFF73.js.map} +1 -1
  80. package/dist/{chunk-ATTXBMAX.js → chunk-PRMKPFN5.js} +3 -3
  81. package/dist/{chunk-ATTXBMAX.js.map → chunk-PRMKPFN5.js.map} +1 -1
  82. package/dist/chunk-PYD3UCDU.js +1480 -0
  83. package/dist/chunk-PYD3UCDU.js.map +1 -0
  84. package/dist/{chunk-MAQJYNJR.js → chunk-QBYTJSAY.js} +14 -16
  85. package/dist/chunk-QBYTJSAY.js.map +1 -0
  86. package/dist/{chunk-THX25XW6.js → chunk-SPT5JMME.js} +27 -7
  87. package/dist/chunk-SPT5JMME.js.map +1 -0
  88. package/dist/{chunk-3JBJEYWE.cjs → chunk-SST7XDY6.cjs} +32 -12
  89. package/dist/chunk-SST7XDY6.cjs.map +1 -0
  90. package/dist/{chunk-VZX2KSY3.js → chunk-UPDMJEW6.js} +608 -563
  91. package/dist/chunk-UPDMJEW6.js.map +1 -0
  92. package/dist/{chunk-UIFEEPME.js → chunk-WLP6TKFB.js} +3141 -1823
  93. package/dist/chunk-WLP6TKFB.js.map +1 -0
  94. package/dist/{chunk-VMEWZU2N.cjs → chunk-WWVV44DY.cjs} +11 -11
  95. package/dist/{chunk-VMEWZU2N.cjs.map → chunk-WWVV44DY.cjs.map} +1 -1
  96. package/dist/{chunk-UJ4V3YUQ.js → chunk-XKNAK27R.js} +3 -3
  97. package/dist/{chunk-UJ4V3YUQ.js.map → chunk-XKNAK27R.js.map} +1 -1
  98. package/dist/chunk-XLUNB2TZ.js +53 -0
  99. package/dist/chunk-XLUNB2TZ.js.map +1 -0
  100. package/dist/{chunk-XKJQQQVR.js → chunk-XVUJY72M.js} +6 -6
  101. package/dist/{chunk-XKJQQQVR.js.map → chunk-XVUJY72M.js.map} +1 -1
  102. package/dist/{chunk-5CN7B4CZ.cjs → chunk-YW7GHMF4.cjs} +17 -17
  103. package/dist/{chunk-5CN7B4CZ.cjs.map → chunk-YW7GHMF4.cjs.map} +1 -1
  104. package/dist/{ddl-BJcPrB4L.d.ts → ddl-CVnHJcar.d.ts} +3 -3
  105. package/dist/{ddl-CPZ7mB7X.d.cts → ddl-Dxt_fBHr.d.cts} +3 -3
  106. package/dist/{extension-types-D1k0inWU.d.cts → extension-types-YGFJPrzK.d.cts} +1 -1
  107. package/dist/{extension-types-D1k0inWU.d.ts → extension-types-YGFJPrzK.d.ts} +1 -1
  108. package/dist/graph-extension/index.d.cts +4 -4
  109. package/dist/graph-extension/index.d.ts +4 -4
  110. package/dist/graph-merge/index.cjs +200 -55
  111. package/dist/graph-merge/index.cjs.map +1 -1
  112. package/dist/graph-merge/index.d.cts +6 -6
  113. package/dist/graph-merge/index.d.ts +6 -6
  114. package/dist/graph-merge/index.js +185 -40
  115. package/dist/graph-merge/index.js.map +1 -1
  116. package/dist/{index-BEK0VtNB.d.ts → index-DGX6D9j1.d.ts} +2 -2
  117. package/dist/{index-C8sSTErx.d.cts → index-SEvUHDA6.d.cts} +2 -2
  118. package/dist/index.cjs +145 -116
  119. package/dist/index.cjs.map +1 -1
  120. package/dist/index.d.cts +25 -55
  121. package/dist/index.d.ts +25 -55
  122. package/dist/index.js +19 -17
  123. package/dist/index.js.map +1 -1
  124. package/dist/indexes/index.cjs +15 -14
  125. package/dist/indexes/index.d.cts +5 -5
  126. package/dist/indexes/index.d.ts +5 -5
  127. package/dist/indexes/index.js +6 -5
  128. package/dist/interchange/index.cjs +15 -15
  129. package/dist/interchange/index.d.cts +9 -9
  130. package/dist/interchange/index.d.ts +9 -9
  131. package/dist/interchange/index.js +2 -2
  132. package/dist/{manager-Np7VVSlE.d.cts → manager-BYl_zyZR.d.cts} +2 -2
  133. package/dist/{manager-By-WEd8M.d.ts → manager-C0_r0ALf.d.ts} +2 -2
  134. package/dist/{materialize-indexes-CAGhqPHQ.d.ts → materialize-indexes-CAkIYFV-.d.ts} +1 -1
  135. package/dist/{materialize-indexes-DEYkU-wr.d.cts → materialize-indexes-D20xNluI.d.cts} +1 -1
  136. package/dist/{postgres-4J2tmauh.d.cts → postgres-MzBPkYzq.d.ts} +2651 -596
  137. package/dist/{postgres-BdIb7tS_.d.ts → postgres-_9psmVGm.d.cts} +2651 -596
  138. package/dist/profiler/index.cjs +4 -3
  139. package/dist/profiler/index.cjs.map +1 -1
  140. package/dist/profiler/index.d.cts +7 -7
  141. package/dist/profiler/index.d.ts +7 -7
  142. package/dist/profiler/index.js +2 -1
  143. package/dist/profiler/index.js.map +1 -1
  144. package/dist/schema/index.cjs +30 -29
  145. package/dist/schema/index.cjs.map +1 -1
  146. package/dist/schema/index.d.cts +7 -7
  147. package/dist/schema/index.d.ts +7 -7
  148. package/dist/schema/index.js +7 -6
  149. package/dist/schema/index.js.map +1 -1
  150. package/dist/{sqlite-aM_PAz-O.d.ts → sqlite-BfksSb45.d.cts} +2726 -455
  151. package/dist/{sqlite-Gatk_iw_.d.cts → sqlite-gm44dShb.d.ts} +2726 -455
  152. package/dist/{store-DuCbdqsh.d.cts → store-view-9jQ2rPum.d.cts} +1101 -465
  153. package/dist/{store-MloRPwb9.d.ts → store-view-FfE5_7eo.d.ts} +1101 -465
  154. package/dist/{types-DoByHGyU.d.cts → types-B6mhrcLv.d.cts} +2 -2
  155. package/dist/{types-C1CYxWrL.d.cts → types-C_UnQOQp.d.cts} +154 -23
  156. package/dist/{types-K3vpaJAL.d.ts → types-CdWxK-nD.d.ts} +2 -2
  157. package/dist/{types-BKQljXom.d.ts → types-DGylBhWo.d.ts} +154 -23
  158. package/dist/{where-DydZjGOb.d.cts → where-Bpp2ul_z.d.cts} +2 -2
  159. package/dist/{where-Dt49bvo6.d.ts → where-BsEXraKW.d.ts} +2 -2
  160. package/package.json +2 -2
  161. package/dist/chunk-2HZGWCB4.js.map +0 -1
  162. package/dist/chunk-3JBJEYWE.cjs.map +0 -1
  163. package/dist/chunk-4A4GUZTQ.js.map +0 -1
  164. package/dist/chunk-54JVNOAQ.cjs.map +0 -1
  165. package/dist/chunk-6G35I3VW.cjs +0 -40
  166. package/dist/chunk-6G35I3VW.cjs.map +0 -1
  167. package/dist/chunk-6RMLO5O4.cjs.map +0 -1
  168. package/dist/chunk-7JGLPAFV.cjs.map +0 -1
  169. package/dist/chunk-CIINW6PS.cjs.map +0 -1
  170. package/dist/chunk-FLOI7QOT.cjs.map +0 -1
  171. package/dist/chunk-GKFWM3DS.js.map +0 -1
  172. package/dist/chunk-IJORSAC3.js.map +0 -1
  173. package/dist/chunk-M6OC455F.js +0 -65
  174. package/dist/chunk-M6OC455F.js.map +0 -1
  175. package/dist/chunk-MAQJYNJR.js.map +0 -1
  176. package/dist/chunk-MXE2U3EX.js.map +0 -1
  177. package/dist/chunk-RP7YITHX.cjs +0 -70
  178. package/dist/chunk-RP7YITHX.cjs.map +0 -1
  179. package/dist/chunk-RZ4DH4E7.cjs.map +0 -1
  180. package/dist/chunk-SAJSMR2B.js +0 -35
  181. package/dist/chunk-SAJSMR2B.js.map +0 -1
  182. package/dist/chunk-SFFJ2IKN.cjs.map +0 -1
  183. package/dist/chunk-STP7QVUB.js.map +0 -1
  184. package/dist/chunk-THX25XW6.js.map +0 -1
  185. package/dist/chunk-UIFEEPME.js.map +0 -1
  186. package/dist/chunk-V4IQYOQ4.cjs.map +0 -1
  187. package/dist/chunk-VZX2KSY3.js.map +0 -1
  188. package/dist/chunk-YQGLVWB2.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/temporal.ts","../src/query/sql-intent.ts","../src/query/compiler/schema.ts","../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/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/temporal.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/row-mappers.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/id.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/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-sync.ts","../src/store/fulltext-rebuild.ts","../src/store/embedding-sync.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/registry/builders.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/row-fetch.ts","../src/store/edge-fetch.ts","../src/store/collections/edge-collection.ts","../src/store/node-fetch.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/insert-dispatch.ts","../src/store/recorded-capture/guards.ts","../src/store/recorded-capture/clock.ts","../src/store/recorded-capture/relations.ts","../src/store/recorded-capture/flush.ts","../src/store/recorded-capture.ts","../src/store/materialize-removals.ts","../src/constraints/index.ts","../src/store/constraints.ts","../src/store/operations/edge-operations.ts","../src/store/uniqueness.ts","../src/store/operations/node-operations.ts","../src/store/recorded-read-service.ts","../src/store/store.ts"],"names":["validateCanonicalIsoDate","ValidationError","ConfigurationError","MAX_PG_IDENTIFIER_LENGTH","quoteIdentifier","sql","nowIso","target","CompilerInvariantError","NODE_COLUMNS","shouldProjectColumn","EDGE_COLUMNS","compileKindFilter","compilePredicateClauses","getPredicatesForAlias","EMPTY_REQUIRED_COLUMNS","getNodeKindsForAlias","field","compileFieldValue","UnsupportedPredicateError","isAggregateExpr","mapSelectiveSystemFieldToColumn","jsonPointer","getHybridTargetAlias","compilePredicateExpression","vectorScoreExpression","vectorMinScoreCondition","extractFulltextMatchPredicates","extractVectorSimilarityPredicates","hasVariableLengthTraversal","getDialect","compileRecursiveBranch","addRequiredColumn","markSelectiveFieldAsRequired","markFieldRefAsRequired","nullToUndefined","filterReservedKeys","RESERVED_NODE_KEYS","RESERVED_EDGE_KEYS","fnv1aBase36","createSchemaIntrospector","validateProjectionField","compileQuery","collectRequiredColumnsByAlias","isIdFieldRef","buildPredicateIndex","compileSetOperation","groupBy","having","nanoid","SQLITE_PATH_DELIMITER","PG_ARRAY_START","PG_ARRAY_END","PG_PATH_ELEMENT_SEPARATOR","resolveJsonPointer","DEFAULT_STREAM_BATCH_SIZE","NODE_META_KEYS","EDGE_META_KEYS","value","isParameterRef","Placeholder","rawRows","resolveEmbeddingFields","fieldRef","withRecordedRelationsPrecondition","parseJsonPointer","outputName","aliasObject","DEFAULT_PAGINATION_LIMIT","NOT_COMPUTED","buildFieldBuilderForTypeInfo","max","min","stringField","numberField","baseField","dateField","arrayField","objectField","KindNotFoundError","EndpointError","coordinate","createFulltextAccessor","getSearchableMetadata","DEFAULT_SEARCHABLE_LANGUAGE","runOptionallyInTransaction","entry","rank","assertVectorMinScore","IncompatibleChangeError","canonicalEqual","extensionKindNames","RemoveCompileTimeKindError","KindHasReferentsError","buildGraphExtensionOntologyKeySet","compileTimeOntologyKey","getTypeName","computeClosuresFromOntology","createEmptyClosures","KindRegistry","getNodeKinds","getEdgeKinds","rows","rowToEdge","executeEdgeCreate","executeEdgeCreateNoReturnBatch","executeEdgeCreateBatch","executeEdgeUpdate","executeEdgeUpsertUpdate","executeEdgeDelete","executeEdgeHardDelete","results","rowToNode","executeNodeCreate","executeNodeCreateNoReturnBatch","executeNodeCreateBatch","executeNodeUpdate","executeNodeUpsertUpdate","executeNodeDelete","executeNodeHardDelete","result","serializeSchemaProperties","isKnownKind","generateIndexDDL","sortedReplacer","sha256Hex","sqlNull","sqlValueList","isPresent","chunk","createBackendOverlay","materializeOne","parseSerializedSchema","isMissingTableError","CardinalityError","DisjointError","count","EndpointNotFoundError","validateEdgeProps","validateOptionalCanonicalIsoDate","DatabaseOperationError","EdgeNotFoundError","edge","UniquenessError","NodeConstraintNotFoundError","validateNodeProps","NodeNotFoundError","RestrictedDeleteError","NodeIndexNotFoundError","compileNodeIndexFieldKeys","compileIndexWhere","POSTGRES_ROW_MAPPER_CONFIG","SQLITE_ROW_MAPPER_CONFIG","createNodeRowMapper","createEdgeRowMapper","mergeGraphExtension","commitNewSchemaVersion","EagerMaterializationError","applyDeprecatedKinds","ensureSchema","loadActiveSchemaWithBootstrap","loadAndMergeGraphExtensionDocument","loadAndVerifyGraph"],"mappings":";;;;;;;;;;;;;;;;;;;;AAYO,IAAM,YAAA,GAAe,0BAAA;AAsBrB,SAAS,0BAAA,CAA2B,OAAe,IAAA,EAAoB;AAC5E,EAAAA,0CAAA,CAAyB,OAAO,IAAI,CAAA;AACpC,EAAA,IAAI,SAAS,YAAA,EAAc;AACzB,IAAA,MAAM,IAAIC,iCAAA;AAAA,MACR,CAAA,EAAG,IAAI,CAAA,gDAAA,EAAmD,YAAY,CAAA,CAAA,CAAA;AAAA,MACtE;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA;AAAA,YACA,OAAA,EAAS,CAAA,4BAAA,EAA+B,YAAY,CAAA,OAAA,EAAU,KAAK,CAAA,CAAA;AAAA;AACrE;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EACE;AAAA;AACJ,KACF;AAAA,EACF;AACF;AAeO,SAAS,kBAAkB,KAAA,EAAgC;AAChE,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AA,MAAM;AAAA,IACJ,KAAA,EAAO,MAAA;AAAA,IACP,SAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAM2E,oDAAA,CAAmC,OAAA,EAAS,KAAK,CAAA;AAE3D,EAAA,MAAM,MAAA,GAAS,MAAMF,8BAAA,CAAiB,OAAA,EAAS,MAAA,EAAQ;AAAA,IACrD,GAAG,OAAA;AAAA,IACH,SAAA,EAAW,EAAE,SAAA,EAAW,YAAA;AAAa,GACtC,CAAA;AAMD,EAAA,MAAM,+BAAA,CAAgC,OAAA,EAAS,MAAA,CAAO,EAAE,CAAA;AAExD,EAAA,MAAM,QAAQ,IAAI,KAAA;AAAA,IAChB,MAAA;AAAA,IACA,OAAA;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-D3EWZ67S.cjs","sourcesContent":["/**\n * Shared temporal coordinate + validation.\n */\nimport { ValidationError } from \"../errors\";\nimport { validateCanonicalIsoDate } from \"../utils/date\";\nimport { type TemporalMode } from \"./types\";\n\n/**\n * Open-ended recorded-time sentinel. Chosen so SQLite text ordering and\n * PostgreSQL `timestamptz` ordering both put every real commit instant before\n * the open interval end.\n */\nexport const RECORDED_MAX = \"9999-12-31T23:59:59.999Z\";\n\ndeclare const RECORDED_INSTANT_BRAND: unique symbol;\n\n/**\n * A canonical UTC ISO-8601 recorded-time instant (`YYYY-MM-DDTHH:mm:ss.sssZ`),\n * nominally branded so it can only originate from a recorded-time source —\n * {@link Store.recordedNow} or an explicit {@link asRecordedInstant} — never an\n * ad-hoc wall-clock string.\n *\n * The recorded commit clock is a logical, monotonic per-graph instant that can\n * run briefly ahead of wall time under bursty same-millisecond writes, so a raw\n * `new Date().toISOString()` may sort *before* the most recent commits and\n * silently omit them. The brand turns that footgun into a compile error:\n * `store.asOfRecorded` accepts only a `RecordedInstant`, so a bare wall-clock\n * string no longer type-checks — callers reach for `await store.recordedNow()`\n * (the monotonic high-water mark) or {@link asRecordedInstant} instead.\n */\nexport type RecordedInstant = string & {\n readonly [RECORDED_INSTANT_BRAND]: \"RecordedInstant\";\n};\n\nexport function assertValidRecordedInstant(value: string, path: string): void {\n validateCanonicalIsoDate(value, path);\n if (value >= RECORDED_MAX) {\n throw new ValidationError(\n `${path} must be before the recorded-time open sentinel ${RECORDED_MAX}.`,\n {\n issues: [\n {\n path,\n message: `Expected a timestamp before ${RECORDED_MAX}, got \"${value}\"`,\n },\n ],\n },\n {\n suggestion:\n \"Use a real recorded-time commit instant, not the open-interval sentinel.\",\n },\n );\n }\n}\n\n/**\n * Brands a canonical UTC ISO-8601 string as a {@link RecordedInstant}.\n *\n * The escape hatch for an instant that round-trips through untyped storage:\n * captured from {@link Store.recordedNow}, persisted as a plain string, read\n * back, and replayed into `asOfRecorded`. Validates the canonical form eagerly —\n * the same check `asOfRecorded` applies — so a malformed value fails here, at the\n * brand site, rather than deeper in a read. Does *not* assert the instant is a\n * real captured commit; it only guarantees the value is well-formed enough to\n * compare correctly against the recorded relations.\n *\n * @throws {ValidationError} when `value` is not a canonical UTC ISO-8601 string.\n */\nexport function asRecordedInstant(value: string): RecordedInstant {\n assertValidRecordedInstant(value, \"asRecordedInstant\");\n return value as RecordedInstant;\n}\n\n/**\n * The single opaque temporal coordinate every pinned read is resolved\n * against. It carries the valid-time axis plus an optional recorded/system-time\n * axis, so every surface can inject one coordinate object instead of threading\n * each temporal dimension separately.\n */\nexport type ReadCoordinate = Readonly<{\n /**\n * The valid-time axis: a resolved temporal mode and (only for `\"asOf\"`) the\n * instant it is pinned to.\n */\n valid: Readonly<{\n mode: TemporalMode;\n /** Defined only when `mode` is `\"asOf\"`. */\n asOf?: string;\n }>;\n /** The recorded/system-time axis. Defined only for recorded-pinned views. */\n recorded?: Readonly<{ asOf: RecordedInstant }>;\n}>;\n\n/**\n * Resolves and validates a `(mode, asOf)` pair into a {@link ReadCoordinate}.\n * Rejects an `asOf` paired with any non-`\"asOf\"` mode rather than silently\n * dropping it — pinning an instant is only meaningful in `\"asOf\"` mode, so a\n * `view({ mode: \"current\", asOf })` is a caller mistake, not a coordinate to\n * quietly discard. Then validates via {@link assertValidAsOf}.\n *\n * @param mode - The temporal mode to pin.\n * @param asOf - The supplied timestamp. Required for `\"asOf\"`; rejected for\n * every other mode.\n * @param suggestion - Caller-specific remediation hint for the\n * missing/invalid-timestamp case.\n */\nexport function resolveReadCoordinate(\n mode: TemporalMode,\n asOf: string | undefined,\n suggestion?: string,\n): ReadCoordinate {\n if (mode !== \"asOf\" && asOf !== undefined) {\n throw new ValidationError(\n `Temporal mode \"${mode}\" does not take an asOf timestamp.`,\n {\n issues: [\n {\n path: \"asOf\",\n message: `asOf is only valid with mode \"asOf\", not \"${mode}\"`,\n },\n ],\n },\n {\n suggestion:\n 'Pin an instant with store.asOf(timestamp) or store.view({ mode: \"asOf\", asOf }); drop asOf for other modes.',\n },\n );\n }\n assertValidAsOf(\n mode,\n asOf,\n suggestion === undefined ? undefined : { suggestion },\n );\n return { valid: asOf === undefined ? { mode } : { mode, asOf } };\n}\n\n/**\n * Adds a recorded/system-time pin to an existing valid-time coordinate.\n * Direct `store.asOfRecorded(T)` passes the diagonal valid-time coordinate\n * (`mode: \"asOf\", asOf: T`); `store.asOf(vt).asOfRecorded(rt)` passes the\n * already-resolved valid coordinate and adds the recorded sibling.\n */\nexport function withRecordedCoordinate(\n coordinate: ReadCoordinate,\n recordedAsOf: RecordedInstant,\n): ReadCoordinate {\n assertValidRecordedInstant(recordedAsOf, \"asOfRecorded\");\n return {\n ...coordinate,\n recorded: { asOf: recordedAsOf },\n };\n}\n\n/**\n * Validates the `asOf` coordinate of a temporal read: `\"asOf\"` mode\n * requires a timestamp, and any supplied timestamp must be a canonical\n * fixed-width UTC ISO-8601 string (`YYYY-MM-DDTHH:mm:ss.sssZ`). The latter\n * is load-bearing — temporal filters compare `asOf` against `valid_from` /\n * `valid_to` as text on SQLite, so a non-canonical value (date-only, an\n * offset, natural language, or variable-width / missing milliseconds like\n * `.1Z`) would sort and compare wrong rather than error. Reached only through\n * {@link resolveReadCoordinate}, which every temporal read entry point routes\n * through (direct reads, queries, subgraphs, algorithms, and StoreView), so\n * they all fail identically.\n *\n * @param mode - The resolved temporal mode.\n * @param asOf - The supplied timestamp (may be `undefined`).\n * @param options.suggestion - A caller-specific remediation hint for the\n * missing-timestamp case.\n *\n * @throws {ValidationError} when `mode` is `\"asOf\"` and `asOf` is missing, or\n * when any supplied `asOf` is not a canonical UTC ISO-8601 timestamp. The\n * canonical check runs for *every* mode that consumes `asOf`, so a\n * non-canonical value can never reach a text comparison.\n */\nfunction assertValidAsOf(\n mode: TemporalMode,\n asOf: string | undefined,\n options?: Readonly<{ suggestion?: string }>,\n): void {\n if (mode === \"asOf\" && asOf === undefined) {\n throw new ValidationError(\n 'Temporal mode \"asOf\" requires a timestamp',\n {\n issues: [\n { path: \"asOf\", message: \"Timestamp is required for asOf mode\" },\n ],\n },\n {\n suggestion:\n options?.suggestion ??\n 'Provide an ISO-8601 timestamp for asOf mode, e.g. \"2026-01-01T00:00:00.000Z\".',\n },\n );\n }\n if (asOf !== undefined) {\n validateCanonicalIsoDate(asOf, \"asOf\");\n }\n}\n\n/**\n * A human-readable description of a coordinate for error messages, e.g.\n * `mode \"current\"` or `mode \"asOf\" asOf 2026-01-01T00:00:00.000Z`. Shared by\n * every refusal path (the `StoreView` read-only / current-only / search facades\n * and the sealed-query builder) so they describe a coordinate identically — and\n * a future axis (recorded time) is reflected everywhere from one place.\n */\nexport function describeCoordinate(coordinate: ReadCoordinate): string {\n const { mode, asOf } = coordinate.valid;\n const valid =\n asOf === undefined ? `mode \"${mode}\"` : `mode \"${mode}\" asOf ${asOf}`;\n return coordinate.recorded === undefined ?\n valid\n : `${valid}, recorded asOf ${coordinate.recorded.asOf}`;\n}\n\n/**\n * The structured error-context fields describing a coordinate, shared by the\n * same refusal paths as {@link describeCoordinate}.\n */\nexport function coordinateContext(\n coordinate: ReadCoordinate,\n): Record<string, unknown> {\n const { mode, asOf } = coordinate.valid;\n return {\n temporalMode: mode,\n ...(asOf !== undefined && { asOf }),\n ...(coordinate.recorded === undefined ?\n {}\n : { recordedAsOf: coordinate.recorded.asOf }),\n };\n}\n","import { type SQL } from \"drizzle-orm\";\n\ndeclare const SqlIntentBrand: unique symbol;\n\nexport type SqlIntent = \"rows\" | \"statement\";\n\nexport type IntentSql<I extends SqlIntent> = SQL &\n Readonly<{ [SqlIntentBrand]: I }>;\n\nexport type CompiledRowsSql = IntentSql<\"rows\">;\nexport type CompiledSelectSql = CompiledRowsSql;\nexport type CompiledStatementSql = IntentSql<\"statement\">;\n\nexport function asCompiledRowsSql(query: SQL): CompiledRowsSql {\n return query as CompiledRowsSql;\n}\n\nexport function asCompiledSelectSql(query: SQL): CompiledSelectSql {\n return asCompiledRowsSql(query);\n}\n\nexport function asCompiledStatementSql(query: SQL): CompiledStatementSql {\n return query as CompiledStatementSql;\n}\n","/**\n * SQL Schema Configuration for Query Compilation\n *\n * Provides table and column identifiers that the query compiler uses.\n * This allows the compiler to work with custom table names instead of\n * hard-coded defaults.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type VectorIndexType, type VectorMetric } from \"../../backend/types\";\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../../constants\";\nimport { ConfigurationError } from \"../../errors\";\n\n/**\n * Table names for TypeGraph SQL schema.\n *\n * Carries every customizable physical-table name the backend exposes,\n * including the secondary tables (`uniques`) that the query compiler\n * itself doesn't reference but `materializeRemovals` and other\n * cleanup paths need to address by name. Backends without a\n * `uniques` table (custom embeddings-only stores) leave it as the\n * default — the cleanup path is a no-op for kinds with no unique\n * rows.\n */\nexport type SqlTableNames = Readonly<{\n /** Nodes table name (default: \"typegraph_nodes\") */\n nodes: string;\n /** Edges table name (default: \"typegraph_edges\") */\n edges: string;\n /** Recorded node relation table name (default: \"typegraph_recorded_nodes\") */\n recordedNodes?: string | undefined;\n /** Recorded edge relation table name (default: \"typegraph_recorded_edges\") */\n recordedEdges?: string | undefined;\n /** Recorded-time commit clock table name (default: \"typegraph_recorded_clock\") */\n recordedClock?: string | undefined;\n /** Node fulltext table name (default: \"typegraph_node_fulltext\") */\n fulltext: string;\n /** Node uniques table name (default: \"typegraph_node_uniques\") */\n uniques: string;\n}>;\n\nexport type ResolvedSqlTableNames = Readonly<{\n /** Nodes table name */\n nodes: string;\n /** Edges table name */\n edges: string;\n /** Recorded node relation table name */\n recordedNodes: string;\n /** Recorded edge relation table name */\n recordedEdges: string;\n /** Recorded-time commit clock table name */\n recordedClock: string;\n /** Node fulltext table name */\n fulltext: string;\n /** Node uniques table name */\n uniques: string;\n}>;\n\ntype SqlSchemaFields = Readonly<{\n /** Table names */\n tables: ResolvedSqlTableNames;\n /** Get a SQL reference to the nodes table */\n nodesTable: SQL;\n /** Get a SQL reference to the edges table */\n edgesTable: SQL;\n /** Get a SQL reference to the recorded node relation */\n recordedNodesTable: SQL;\n /** Get a SQL reference to the recorded edge relation */\n recordedEdgesTable: SQL;\n /** Get a SQL reference to the recorded-time commit clock */\n recordedClockTable: SQL;\n /** Get a SQL reference to the fulltext table */\n fulltextTable: SQL;\n}>;\n\n/**\n * SQL schema configuration for query compilation.\n * Contains table identifiers and utility methods for generating SQL references.\n *\n * Branded and frozen by {@link createSqlSchema}; callers should not construct\n * schema-shaped objects by hand.\n */\nexport type SqlSchema = SqlSchemaDescriptor;\n\nclass SqlSchemaDescriptor implements SqlSchemaFields {\n // Private field gives SqlSchema nominal identity; runtime checks use instanceof.\n readonly #brand = true;\n readonly tables: ResolvedSqlTableNames;\n readonly nodesTable: SQL;\n readonly edgesTable: SQL;\n readonly recordedNodesTable: SQL;\n readonly recordedEdgesTable: SQL;\n readonly recordedClockTable: SQL;\n readonly fulltextTable: SQL;\n\n constructor(fields: SqlSchemaFields) {\n this.tables = fields.tables;\n this.nodesTable = fields.nodesTable;\n this.edgesTable = fields.edgesTable;\n this.recordedNodesTable = fields.recordedNodesTable;\n this.recordedEdgesTable = fields.recordedEdgesTable;\n this.recordedClockTable = fields.recordedClockTable;\n this.fulltextTable = fields.fulltextTable;\n void this.#brand;\n Object.freeze(this);\n }\n}\n\n/**\n * Default table names matching the standard TypeGraph schema.\n */\nconst DEFAULT_TABLE_NAMES: ResolvedSqlTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n recordedNodes: \"typegraph_recorded_nodes\",\n recordedEdges: \"typegraph_recorded_edges\",\n recordedClock: \"typegraph_recorded_clock\",\n fulltext: \"typegraph_node_fulltext\",\n uniques: \"typegraph_node_uniques\",\n};\n\nfunction resolveTableNames(\n names: Partial<SqlTableNames>,\n): ResolvedSqlTableNames {\n return {\n nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,\n edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,\n recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,\n recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,\n recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,\n fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,\n uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques,\n };\n}\n\n/**\n * Regex for valid SQL identifiers.\n * Must start with a letter or underscore.\n * Can contain letters, digits, underscores, and dollar signs.\n * Dollar signs are a PostgreSQL extension but commonly supported.\n */\nconst VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;\n\n/**\n * Validates that a table name is a valid SQL identifier.\n *\n * @throws Error if the table name is invalid\n */\nfunction validateTableName(name: string, label: string): void {\n if (!name || name.length === 0) {\n throw new ConfigurationError(`${label} table name cannot be empty`);\n }\n if (name.length > MAX_PG_IDENTIFIER_LENGTH) {\n throw new ConfigurationError(\n `${label} table name exceeds maximum length of ${MAX_PG_IDENTIFIER_LENGTH} characters`,\n );\n }\n if (!VALID_IDENTIFIER_PATTERN.test(name)) {\n throw new ConfigurationError(\n `${label} table name \"${name}\" is not a valid SQL identifier. ` +\n `Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`,\n );\n }\n}\n\n/**\n * Quotes a SQL identifier using ANSI SQL standard double quotes.\n * Escapes any embedded double quotes by doubling them.\n *\n * This works for both SQLite and PostgreSQL.\n */\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction freezeSqlSchema(fields: SqlSchemaFields): SqlSchema {\n return new SqlSchemaDescriptor(fields);\n}\n\nfunction isSqlSchema(schema: unknown): schema is SqlSchema {\n return schema instanceof SqlSchemaDescriptor && Object.isFrozen(schema);\n}\n\nexport function requireSqlSchema(\n schema: unknown,\n surface = \"SqlSchema\",\n): SqlSchema {\n if (isSqlSchema(schema)) return schema;\n throw new ConfigurationError(\n `${surface} must be created with createSqlSchema(...).`,\n { code: \"INVALID_SQL_SCHEMA\", surface },\n {\n suggestion:\n \"Pass the result of createSqlSchema(...) instead of a plain schema-shaped object.\",\n },\n );\n}\n\n/**\n * Creates a SqlSchema configuration from table names.\n *\n * Table names are validated to ensure they are valid SQL identifiers.\n * This prevents SQL injection and ensures compatibility across databases.\n *\n * @param names - Optional custom table names (defaults to standard names)\n * @returns SqlSchema configuration for query compilation\n * @throws Error if any table name is invalid\n *\n * @example\n * ```typescript\n * // Use default table names\n * const schema = createSqlSchema();\n *\n * // Use custom table names\n * const schema = createSqlSchema({\n * nodes: \"myapp_nodes\",\n * edges: \"myapp_edges\",\n * fulltext: \"myapp_fulltext\",\n * });\n * ```\n */\nexport function createSqlSchema(names: Partial<SqlTableNames> = {}): SqlSchema {\n const tables = resolveTableNames(names);\n\n // Validate all table names\n validateTableName(tables.nodes, \"nodes\");\n validateTableName(tables.edges, \"edges\");\n validateTableName(tables.recordedNodes, \"recordedNodes\");\n validateTableName(tables.recordedEdges, \"recordedEdges\");\n validateTableName(tables.recordedClock, \"recordedClock\");\n validateTableName(tables.fulltext, \"fulltext\");\n validateTableName(tables.uniques, \"uniques\");\n\n return freezeSqlSchema({\n tables: Object.freeze(tables),\n nodesTable: sql.raw(quoteIdentifier(tables.nodes)),\n edgesTable: sql.raw(quoteIdentifier(tables.edges)),\n recordedNodesTable: sql.raw(quoteIdentifier(tables.recordedNodes)),\n recordedEdgesTable: sql.raw(quoteIdentifier(tables.recordedEdges)),\n recordedClockTable: sql.raw(quoteIdentifier(tables.recordedClock)),\n fulltextTable: sql.raw(quoteIdentifier(tables.fulltext)),\n });\n}\n\n/**\n * The recorded/system-time relation a read coordinate may reconstruct from.\n *\n * TypeGraph's built-in capture relation is bound by `createStore(..., {\n * history: true })`. Hosts can also bind externally populated row-compatible\n * recorded relations through `recordedRelation({ schema })`. Keeping both as\n * explicit values separates the read contract from the write-capture mechanism\n * so future external/TMS-owned recorded relations can feed the same query\n * machinery without changing StoreView or ReadCoordinate.\n */\nconst EXTERNAL_RECORDED_READ_SOURCE: unique symbol = Symbol(\n \"ExternalRecordedReadSource\",\n);\n\nexport type ExternalRecordedReadSource = Readonly<{\n source: \"external\";\n schema: SqlSchema;\n [EXTERNAL_RECORDED_READ_SOURCE]: true;\n}>;\n\ntype ExternalRecordedReadSourceCandidate = Readonly<{\n source?: unknown;\n schema?: unknown;\n [EXTERNAL_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nconst TYPEGRAPH_RECORDED_READ_SOURCE: unique symbol = Symbol(\n \"TypeGraphRecordedReadSource\",\n);\n\nexport type TypeGraphRecordedReadSource = Readonly<{\n source: \"typegraph-capture\";\n schema: SqlSchema;\n [TYPEGRAPH_RECORDED_READ_SOURCE]: true;\n}>;\n\ntype RecordedReadSource =\n | ExternalRecordedReadSource\n | TypeGraphRecordedReadSource;\n\nexport type RecordedReadBinding = RecordedReadSource;\n\nexport type RecordedRelationOptions = Readonly<{\n schema: SqlSchema;\n}>;\n\nexport function recordedRelation(\n options: RecordedRelationOptions,\n): ExternalRecordedReadSource {\n const schema = requireSqlSchema(options.schema, \"recordedRelation schema\");\n return Object.freeze({\n source: \"external\",\n schema,\n [EXTERNAL_RECORDED_READ_SOURCE]: true as const,\n });\n}\n\nexport function requireExternalRecordedReadSource(\n source: unknown,\n): ExternalRecordedReadSource | undefined {\n if (source === undefined) return undefined;\n if (isExternalRecordedReadSource(source)) return source;\n throw new ConfigurationError(\n \"recordedRead must be created with recordedRelation({ schema }).\",\n { code: \"INVALID_RECORDED_READ_SOURCE\" },\n {\n suggestion:\n \"Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes.\",\n },\n );\n}\n\nfunction isExternalRecordedReadSource(\n source: unknown,\n): source is ExternalRecordedReadSource {\n if (typeof source !== \"object\" || source === null) return false;\n const candidate = source as ExternalRecordedReadSourceCandidate;\n return (\n candidate.source === \"external\" &&\n candidate[EXTERNAL_RECORDED_READ_SOURCE] === true &&\n isSqlSchema(candidate.schema) &&\n Object.isFrozen(candidate)\n );\n}\n\nexport function createRecordedReadBinding(\n schema: SqlSchema,\n): TypeGraphRecordedReadSource {\n const readSchema = requireSqlSchema(schema, \"recorded read binding schema\");\n return Object.freeze({\n source: \"typegraph-capture\",\n schema: readSchema,\n [TYPEGRAPH_RECORDED_READ_SOURCE]: true as const,\n });\n}\n\nexport function requireRecordedReadBinding(\n binding: unknown,\n surface: string,\n): RecordedReadBinding {\n if (isRecordedReadBinding(binding)) return binding;\n if (binding !== undefined) {\n throw new ConfigurationError(\n \"Recorded-time reads require a recorded read relation created by TypeGraph.\",\n { code: \"INVALID_RECORDED_READ_BINDING\", surface },\n {\n suggestion:\n \"Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object.\",\n },\n );\n }\n throw new ConfigurationError(\n \"Recorded-time reads require a recorded read relation.\",\n { code: \"RECORDED_READ_REQUIRES_BINDING\", surface },\n {\n suggestion:\n \"Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n },\n );\n}\n\ntype TypeGraphRecordedReadSourceCandidate = Readonly<{\n source?: unknown;\n schema?: unknown;\n [TYPEGRAPH_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nfunction isTypeGraphRecordedReadSource(\n source: unknown,\n): source is TypeGraphRecordedReadSource {\n if (typeof source !== \"object\" || source === null) return false;\n const candidate = source as TypeGraphRecordedReadSourceCandidate;\n return (\n candidate.source === \"typegraph-capture\" &&\n candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true &&\n isSqlSchema(candidate.schema) &&\n Object.isFrozen(candidate)\n );\n}\n\nfunction isRecordedReadBinding(\n binding: unknown,\n): binding is RecordedReadBinding {\n return (\n isExternalRecordedReadSource(binding) ||\n isTypeGraphRecordedReadSource(binding)\n );\n}\n\n/**\n * Returns a schema view whose primary node/edge sources are the recorded-time\n * relations. The recorded relations are row-compatible with the live tables\n * for every column the query compiler, subgraph extractor, and algorithms\n * already read; the temporal filter adds the `recorded_from/to` predicate.\n */\nexport function recordedReadSqlSchema(binding: RecordedReadBinding): SqlSchema {\n const { schema } = requireRecordedReadBinding(\n binding,\n \"recorded-read-schema\",\n );\n return freezeSqlSchema({\n tables: schema.tables,\n nodesTable: schema.recordedNodesTable,\n edgesTable: schema.recordedEdgesTable,\n recordedNodesTable: schema.recordedNodesTable,\n recordedEdgesTable: schema.recordedEdgesTable,\n recordedClockTable: schema.recordedClockTable,\n fulltextTable: schema.fulltextTable,\n });\n}\n\n/**\n * Resolves the read schema for a coordinate: the live schema when no recorded\n * pin is set, or the recorded-relation view when `recordedAsOf` is present. The\n * single place every read path decides whether to source the recorded tables.\n */\nexport function recordedReadSchemaFor(\n schema: SqlSchema,\n recordedAsOf: string | undefined,\n binding: RecordedReadBinding | undefined,\n surface: string,\n): SqlSchema {\n const baseSchema = requireSqlSchema(schema, `${surface} schema`);\n if (recordedAsOf === undefined) return baseSchema;\n return recordedReadSqlSchema(requireRecordedReadBinding(binding, surface));\n}\n\n/**\n * Default SqlSchema using standard TypeGraph table names.\n */\nexport const DEFAULT_SQL_SCHEMA: SqlSchema = createSqlSchema();\n\n/**\n * The compiler's resolved view of one declared embedding field — the\n * `(dimensions, metric, indexType)` a {@link VectorStrategy} needs to\n * name and scan the field's typed per-`(kind, field)` storage. Sourced\n * from the registered node schema's `embedding()` declaration when the\n * store builds its compile options.\n */\nexport type VectorSlotDescriptor = Readonly<{\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Map of declared embedding slots keyed by {@link vectorSlotKey} -\n * `\"<nodeKind>\\0<fieldPath>\"` (NUL-separated). Carries every `(concrete kind,\n * fieldPath)` that declares an embedding field, so the compiler's\n * `field.similarTo(...)` CTE can UNION ALL the per-field tables for the\n * kinds in an alias that actually declare the field (only\n * `includeSubClasses` yields more than one).\n */\nexport type VectorSlotMap = ReadonlyMap<string, VectorSlotDescriptor>;\n\n/** NUL-delimited composite key for {@link VectorSlotMap}. */\nexport function vectorSlotKey(nodeKind: string, fieldPath: string): string {\n return `${nodeKind}\\u0000${fieldPath}`;\n}\n\n/**\n * CTE aliases used by the standard query emitter. Joining on these names\n * across multiple builder files is fragile when typed as raw strings —\n * import these constants instead.\n */\nexport const ALIAS_CTE_PREFIX = \"cte_\" as const;\nexport const EMBEDDINGS_CTE_ALIAS = \"cte_embeddings\" as const;\nexport const FULLTEXT_CTE_ALIAS = \"cte_fulltext\" as const;\nexport const HYBRID_CANDIDATES_CTE_ALIAS = \"cte_relevance_candidates\" as const;\n","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;\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;\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 [Method in (typeof NODE_TEMPORAL_READ_NAMES)[number]]: StoreViewNodeCollection<NodeType>[Method];\n }> = {\n getById: (id) => live.getById(id, temporal),\n getByIds: (ids) => live.getByIds(ids, temporal),\n // `live.find` is the NodeCollection read, not Array#find — the\n // (filter, temporal) shape trips the array-method heuristics.\n // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-method-this-argument\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 [Method in (typeof EDGE_TEMPORAL_READ_NAMES)[number]]: StoreViewEdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n >[Method];\n }> = {\n getById: (id) => live.getById(id, temporal),\n getByIds: (ids) => live.getByIds(ids, temporal),\n // `live.find` is the EdgeCollection read, not Array#find — the\n // (filter, temporal) shape trips the array-method heuristics.\n // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-method-this-argument\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 [Method in (typeof RECORDED_POINT_READ_NAMES)[number]]: 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 [Method in (typeof RECORDED_POINT_READ_NAMES)[number]]: 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 * 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\"\n | \"neq\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"in\"\n | \"notIn\";\n\n/**\n * String operators.\n */\nexport type StringOp =\n | \"contains\"\n | \"startsWith\"\n | \"endsWith\"\n | \"like\"\n | \"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\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\"\n | \"countDistinct\"\n | \"sum\"\n | \"avg\"\n | \"min\"\n | \"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// 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 * 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 DialectAdapter } from \"../dialect/types\";\nimport { type 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","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { UnsupportedPredicateError } from \"../../../errors\";\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 { jsonPointer } from \"../../json-pointer\";\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 { compileTypedJsonExtract } from \"../typed-json-extract\";\nimport {\n EDGE_COLUMNS,\n EMPTY_REQUIRED_COLUMNS,\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\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\nfunction compileNodeSelectColumns(\n tableAlias: string | undefined,\n alias: string,\n requiredColumns: ReadonlySet<string> | undefined,\n): SQL[] {\n return 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}\n\nfunction compileEdgeSelectColumns(\n tableAlias: string | undefined,\n alias: string,\n requiredColumns: ReadonlySet<string> | undefined,\n): SQL[] {\n return EDGE_COLUMNS.filter((column) =>\n shouldProjectColumn(requiredColumns, column),\n ).map(\n (column) =>\n sql`${compileColumnReference(tableAlias, column)} AS ${sql.raw(`${alias}_${column}`)}`,\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(undefined, alias, effectiveRequiredColumns),\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(\"e\", edgeAlias, requiredEdgeColumns),\n ...compileNodeSelectColumns(\"n\", nodeAlias, requiredNodeColumns),\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 dialect,\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 dialect: DialectAdapter,\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 const propsColumn = `${field.alias}_props`;\n const column = sql`${sql.raw(cteAlias)}.${sql.raw(propsColumn)}`;\n const pointer = jsonPointer([field.field]);\n const extracted = compileTypedJsonExtract({\n column,\n dialect,\n pointer,\n valueType: field.valueType,\n });\n return sql`${extracted} AS ${quoteIdentifier(field.outputName)}`;\n });\n\n return sql.join(columns, sql`, `);\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 if (!ast.orderBy || ast.orderBy.length === 0) {\n return undefined;\n }\n\n const aliasToCte = buildAliasToCteMap(ast);\n const parts: 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 collapsedTraversalCteAlias ??\n aliasToCte.get(orderSpec.field.alias) ??\n `cte_${orderSpec.field.alias}`;\n const field = compileFieldValue(\n orderSpec.field,\n dialect,\n valueType,\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 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. NOTE: this path is exact-but-brute-force — it splices the strategy's\n * `distanceExpression` and full-scans each declaring kind's per-field table\n * (`ORDER BY distance LIMIT k`); it does NOT use a strategy's engine-native ANN\n * (vec0 `MATCH … k=`, libSQL `vector_top_k`, pgvector's HNSW scan), which is\n * only reachable through the `store.search.vector` / `store.search.hybrid`\n * facade. For ANN-accelerated retrieval at scale use the facade; use\n * `.where(similarTo())` when you need to compose vector similarity with\n * arbitrary predicates / traversals in one query and exact ranking is fine.\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 // 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 =\n metric ??\n vectorSlots?.get(vectorSlotKey(kind, fieldPath))?.metric ??\n \"cosine\";\n const distanceExpr = vectorStrategy.distanceExpression(\n qualifyColumn(tableName, \"embedding\"),\n queryEmbedding,\n branchMetric,\n );\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 ${distanceExpr} 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 const matchCondition = fulltextStrategy.matchCondition(\n tableName,\n query,\n mode,\n language,\n );\n const rankExpression = fulltextStrategy.rankExpression(\n tableName,\n query,\n mode,\n language,\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\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 = compileFieldValue(\n orderSpec.field,\n dialect,\n valueType,\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 `localeCompare(nodeId)` tiebreak so\n // the two paths produce identical top-k under ties.\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","/**\n * Temporal Filter Compilation\n *\n * Generates SQL clauses for temporal filtering based on valid_from/valid_to\n * and deleted_at timestamps. Consolidates the previously duplicated temporal\n * filter functions into a single, parameterized implementation.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type TemporalMode } from \"../../core/types\";\n\n/**\n * Temporal filter options.\n */\nexport type TemporalFilterOptions = Readonly<{\n /** The temporal mode to apply */\n mode: TemporalMode;\n /** Timestamp for asOf queries (required when mode is \"asOf\") */\n asOf?: string | undefined;\n /** Optional table alias prefix for column references */\n tableAlias?: string | undefined;\n /** Optional execution-time current timestamp SQL expression */\n currentTimestamp?: SQL | undefined;\n /** Recorded/system-time timestamp for recorded-pinned reads. */\n recordedAsOf?: string | undefined;\n}>;\n\n/**\n * Compiles a temporal filter to SQL.\n *\n * This is the unified temporal filter function that handles all temporal modes\n * and optional table alias prefixes. It replaces the previous three separate\n * functions (compileTemporalFilter, compileEdgeTemporalFilter, compileNodeTemporalFilter).\n *\n * @param options - Temporal filter configuration\n * @returns SQL clause for the temporal filter\n *\n * @example\n * ```typescript\n * // Without table alias (for CTEs)\n * compileTemporalFilter({ mode: \"current\" })\n * // → deleted_at IS NULL AND (valid_from IS NULL OR ...) AND ...\n *\n * // With table alias (for JOINs)\n * compileTemporalFilter({ mode: \"current\", tableAlias: \"e\" })\n * // → e.deleted_at IS NULL AND (e.valid_from IS NULL OR ...) AND ...\n *\n * // AsOf mode\n * compileTemporalFilter({ mode: \"asOf\", asOf: \"2024-01-01T00:00:00.000Z\" })\n * // → deleted_at IS NULL AND (valid_from IS NULL OR valid_from <= '2024-01-01...') AND ...\n * ```\n */\nexport function compileTemporalFilter(options: TemporalFilterOptions): SQL {\n const { mode, asOf, tableAlias, currentTimestamp, recordedAsOf } = options;\n\n // Build column references with optional prefix\n const prefix = tableAlias ? sql.raw(`${tableAlias}.`) : sql.raw(\"\");\n const deletedAt = sql`${prefix}deleted_at`;\n const validFrom = sql`${prefix}valid_from`;\n const validTo = sql`${prefix}valid_to`;\n\n const validFilter = (() => {\n switch (mode) {\n case \"current\": {\n // When pinned to a recorded instant, \"current\" valid-time means\n // valid-current *as of that recorded instant* — not the wall clock at\n // read time. Pinning here collapses\n // view({mode:'current'}).asOfRecorded(rt) to the diagonal\n // store.asOfRecorded(rt) and stops silently dropping rows that were\n // valid-current when recorded but ended before the read.\n const now =\n recordedAsOf === undefined ?\n (currentTimestamp ?? sql`CURRENT_TIMESTAMP`)\n : sql`${recordedAsOf}`;\n return sql`${deletedAt} IS NULL AND (${validFrom} IS NULL OR ${validFrom} <= ${now}) AND (${validTo} IS NULL OR ${validTo} > ${now})`;\n }\n\n case \"asOf\": {\n if (asOf === undefined) {\n throw new Error(\n `asOf timestamp is required for temporal mode \"asOf\"`,\n );\n }\n const timestamp = asOf;\n return sql`${deletedAt} IS NULL AND (${validFrom} IS NULL OR ${validFrom} <= ${timestamp}) AND (${validTo} IS NULL OR ${validTo} > ${timestamp})`;\n }\n\n case \"includeEnded\": {\n // Include records that have ended but not been deleted\n return sql`${deletedAt} IS NULL`;\n }\n\n case \"includeTombstones\": {\n // Include everything, no filter\n return sql.raw(\"1=1\");\n }\n }\n })();\n\n if (recordedAsOf === undefined) return validFilter;\n\n const recordedFrom = sql`${prefix}recorded_from`;\n const recordedTo = sql`${prefix}recorded_to`;\n return sql`(${validFilter}) AND ${recordedFrom} <= ${recordedAsOf} AND ${recordedAsOf} < ${recordedTo}`;\n}\n\n/**\n * Extracts temporal options from a query AST.\n *\n * @param ast - Query AST with temporalMode\n * @param tableAlias - Optional table alias for column references\n * @returns TemporalFilterOptions for use with compileTemporalFilter\n */\nexport function extractTemporalOptions(\n ast: {\n temporalMode: { mode: TemporalMode; asOf?: string };\n recordedAsOf?: string;\n },\n tableAlias?: string,\n): TemporalFilterOptions {\n return {\n mode: ast.temporalMode.mode,\n asOf: ast.temporalMode.asOf,\n recordedAsOf: ast.recordedAsOf,\n tableAlias,\n };\n}\n","import { type SQL } from \"drizzle-orm\";\n\nimport type { QueryAst } from \"../../ast\";\nimport { compileTemporalFilter, extractTemporalOptions } 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 and timestamp source.\n *\n * Invariant:\n * - All temporal clauses for a query use the same timestamp expression.\n */\nexport function createTemporalFilterPass(\n ast: QueryAst,\n currentTimestamp: SQL,\n): TemporalFilterPass {\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 if (ast.orderBy !== undefined && ast.orderBy.length > 0) {\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 { jsonPointer } from \"../json-pointer\";\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 { compileTypedJsonExtract } 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.dialect.currentTimestamp(),\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 = compileTypedJsonExtract({\n column,\n dialect,\n pointer: jsonPointer([field.field]),\n valueType: field.valueType,\n });\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 { compileTemporalFilter } 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 = options.dialect.currentTimestamp();\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 * Row Mappers for Store\n *\n * Transforms database rows into typed Node and Edge objects.\n */\nimport {\n type EdgeRow as BackendEdgeRow,\n type NodeRow as BackendNodeRow,\n} from \"../backend/types\";\nimport {\n filterReservedKeys,\n RESERVED_EDGE_KEYS,\n RESERVED_NODE_KEYS,\n} from \"./reserved-keys\";\nimport { type Edge, type EdgeMeta, type Node, type NodeMeta } from \"./types\";\n\n/**\n * Raw node row from database (without graph_id).\n * Derived from BackendNodeRow so BackendNodeRow is assignable without casts.\n */\nexport type NodeRow = Omit<BackendNodeRow, \"graph_id\">;\n\n/**\n * Raw edge row from database (without graph_id).\n * Derived from BackendEdgeRow so BackendEdgeRow is assignable without casts.\n */\nexport type EdgeRow = Omit<BackendEdgeRow, \"graph_id\">;\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 * Transforms a database row into a typed Node object.\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 rowToNode(row: NodeRow): Node {\n const rawProps = JSON.parse(row.props) as Record<string, unknown>;\n const props = filterReservedKeys(rawProps, RESERVED_NODE_KEYS);\n return {\n kind: row.kind,\n id: row.id as Node[\"id\"],\n meta: rowToNodeMeta(row),\n ...props,\n };\n}\n\nexport function rowToNodeMeta(\n row: Pick<\n NodeRow,\n | \"version\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\"\n | \"updated_at\"\n | \"deleted_at\"\n >,\n): NodeMeta {\n return {\n version: row.version,\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\n}\n\n/**\n * Transforms a database row into a typed Edge object.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function rowToEdge(row: EdgeRow): Edge {\n const rawProps = JSON.parse(row.props) as Record<string, unknown>;\n const props = filterReservedKeys(rawProps, RESERVED_EDGE_KEYS);\n return {\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 meta: rowToEdgeMeta(row),\n ...props,\n } as Edge;\n}\n\nexport function rowToEdgeMeta(\n row: Pick<\n EdgeRow,\n \"valid_from\" | \"valid_to\" | \"created_at\" | \"updated_at\" | \"deleted_at\"\n >,\n): EdgeMeta {\n return {\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\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 { compileTemporalFilter } 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 } from \"../query/sql-intent\";\nimport { fnv1aBase36 } from \"../utils/hash\";\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\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 */\nfunction 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 * 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>\n | \"meta\";\n\ntype SubgraphEdgeProjectionField<E extends AnyEdgeType = AnyEdgeType> =\n | EdgeProjectionPropertyKey<E>\n | \"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 const [nodeRows, edgeRows] = await Promise.all([\n fetchSubgraphNodes(ctx, reachableCte, includedIdsCte, nodeProjectionPlan),\n fetchSubgraphEdges(ctx, reachableCte, includedIdsCte, 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>>\n | 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\nasync function fetchSubgraphNodes(\n ctx: SubgraphContext,\n reachableCte: SQL,\n includedIdsCte: SQL,\n projectionPlan: ProjectionPlan,\n): Promise<SubgraphNodeFetchRow[]> {\n const nodeTemporalFilter = compileTemporalFilter({\n mode: ctx.temporalMode,\n asOf: ctx.asOf,\n recordedAsOf: ctx.recordedAsOf,\n tableAlias: \"n\",\n currentTimestamp: ctx.dialect.currentTimestamp(),\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`${reachableCte}${includedIdsCte} SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND ${nodeTemporalFilter} AND n.id IN (SELECT id FROM included_ids)`;\n\n return ctx.backend.execute<SubgraphNodeFetchRow>(\n asCompiledRowsSql(query),\n ) as Promise<SubgraphNodeFetchRow[]>;\n}\n\nasync function fetchSubgraphEdges(\n ctx: SubgraphContext,\n reachableCte: SQL,\n includedIdsCte: SQL,\n projectionPlan: ProjectionPlan,\n): Promise<SubgraphEdgeFetchRow[]> {\n const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), ctx.edgeKinds);\n const edgeTemporalFilter = compileTemporalFilter({\n mode: ctx.temporalMode,\n asOf: ctx.asOf,\n recordedAsOf: ctx.recordedAsOf,\n tableAlias: \"e\",\n currentTimestamp: ctx.dialect.currentTimestamp(),\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`${reachableCte}${includedIdsCte} SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.edgesTable} e WHERE e.graph_id = ${ctx.graphId} AND ${edgeKindFilter} AND ${edgeTemporalFilter} AND e.from_id IN (SELECT id FROM included_ids) AND e.to_id IN (SELECT id FROM included_ids)`;\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 isIdFieldRef,\n markFieldRefAsRequired,\n markSelectiveFieldAsRequired,\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 if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n for (const field of ast.selectiveFields) {\n markSelectiveFieldAsRequired(requiredColumnsByAlias, field);\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 markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n }\n }\n\n if (ast.having) {\n markPredicateFieldsAsRequired(requiredColumnsByAlias, ast.having);\n }\n\n for (const predicate of ast.predicates) {\n markPredicateFieldsAsRequired(requiredColumnsByAlias, predicate.expression);\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(\n currentState.ast,\n currentState.ctx.dialect.currentTimestamp(),\n );\n },\n update(currentState, temporalFilterPass): StandardQueryPassState {\n return {\n ...currentState,\n temporalFilterPass,\n };\n },\n });\n state = temporalPass.state;\n\n const columnPruningPass = runCompilerPass(state, {\n name: \"column_pruning\",\n execute(currentState): RequiredColumnsByAlias | undefined {\n return isColumnPruningEnabled(currentState.ast) ?\n collectRequiredColumnsByAlias(currentState.ast)\n : undefined;\n },\n update(currentState, requiredColumnsByAlias): StandardQueryPassState {\n return {\n ...currentState,\n requiredColumnsByAlias,\n };\n },\n });\n state = columnPruningPass.state;\n\n const selectiveTraversalRowsetPass = runCompilerPass(state, {\n name: \"selective_traversal_rowset\",\n execute(currentState): Readonly<{\n collapsedTraversalCteAlias: string | undefined;\n shouldCollapseSelectiveTraversalRowset: boolean;\n }> {\n const shouldCollapseSelectiveTraversalRowset =\n canCollapseSelectiveTraversalRowset(\n currentState.ast,\n currentState.vectorPredicate,\n currentState.fulltextPredicate,\n );\n const lastTraversal = currentState.ast.traversals.at(-1);\n const collapsedTraversalCteAlias =\n shouldCollapseSelectiveTraversalRowset && lastTraversal !== undefined ?\n `cte_${lastTraversal.nodeAlias}`\n : undefined;\n\n return {\n collapsedTraversalCteAlias,\n shouldCollapseSelectiveTraversalRowset,\n };\n },\n update(\n currentState,\n { collapsedTraversalCteAlias, shouldCollapseSelectiveTraversalRowset },\n ): StandardQueryPassState {\n return {\n ...currentState,\n collapsedTraversalCteAlias,\n shouldCollapseSelectiveTraversalRowset,\n };\n },\n });\n state = selectiveTraversalRowsetPass.state;\n\n const traversalLimitPass = runCompilerPass(state, {\n name: \"traversal_limit\",\n execute(currentState): number | undefined {\n return resolveTraversalCteLimit(\n currentState.ast,\n currentState.predicateIndex,\n );\n },\n update(currentState, traversalCteLimit): StandardQueryPassState {\n return {\n ...currentState,\n traversalCteLimit,\n };\n },\n });\n state = traversalLimitPass.state;\n\n // 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\";\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 { asCompiledSelectSql, type CompiledSelectSql } 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 /**\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\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 const ctx: PredicateCompilerContext = {\n dialect: adapter,\n schema,\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 };\n\n // Check for variable-length traversals\n if (hasVariableLengthTraversal(ast)) {\n const lowered = tryLowerSingleHopRecursiveTraversal(ast);\n if (lowered !== undefined) {\n return asCompiledSelectSql(compileStandardQuery(lowered, graphId, ctx));\n }\n return asCompiledSelectSql(compileVariableLengthQuery(ast, graphId, ctx));\n }\n\n // Standard query compilation\n return asCompiledSelectSql(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 return asCompiledSelectSql(\n compileSetOp(\n op,\n graphId,\n adapter,\n (ast, gid) => compileQuery(ast, gid, propagateOptions(options_)),\n options_.vectorStrategy,\n ),\n );\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_.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: options_.recordedReadBinding }),\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. ORDER BY over the full result requires the full result.\n // (The fast path already restricts ORDER BY to the start alias, but we\n // still need every row to sort correctly.)\n // - LIMIT is defined. OFFSET is carried with it.\n const startCteLimit =\n traversal.optional && ast.orderBy === undefined && ast.limit !== undefined ?\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 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","import { nanoid } from \"nanoid\";\n\n/**\n * ID generation utilities.\n *\n * Default implementation uses nanoid.\n * Benefits:\n * - URL-safe\n * - Compact (21 characters by default)\n * - Secure random generation\n */\n\n/**\n * Generates a new unique ID.\n */\nexport function generateId(): string {\n return nanoid();\n}\n\n/**\n * ID generator function type.\n */\nexport type IdGenerator = () => string;\n\n/**\n * Default ID generator configuration.\n */\nexport type IdConfig = Readonly<{\n /** Generator for node IDs */\n nodeIdGenerator: IdGenerator;\n /** Generator for edge IDs */\n edgeIdGenerator: IdGenerator;\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 { 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 = a.alias.localeCompare(b.alias);\n if (aliasCompare !== 0) return aliasCompare;\n return a.field.localeCompare(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 { 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) => a.alias.localeCompare(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 * PreparedQuery — a pre-compiled, parameterized query.\n *\n * Created via `ExecutableQuery.prepare()`. Compiles the query AST to SQL once\n * at prepare time, then executes with different parameter bindings on each call.\n *\n * Fast path: when `backend.executeRaw` is available, executes pre-compiled SQL\n * text directly with substituted parameter values.\n *\n * Fallback: substitutes parameter refs in the AST, recompiles to SQL, and\n * executes via the standard `backend.execute` path.\n */\nimport { Placeholder } from \"drizzle-orm\";\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 { getDialect } from \"../dialect\";\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 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// Placeholder Substitution for executeRaw Fast Path\n// ============================================================\n\n/**\n * Fills placeholder values in a parameter array.\n *\n * Drizzle's `sql.placeholder()` produces `Placeholder` objects in the params\n * array. This function replaces them with the actual bound values.\n */\nfunction fillPlaceholders(\n params: readonly unknown[],\n bindings: Readonly<Record<string, unknown>>,\n dialect: SqlDialect,\n): unknown[] {\n const adapter = getDialect(dialect);\n return params.map((parameter) => {\n if (parameter instanceof Placeholder) {\n const name = parameter.name as string;\n const value = bindings[name];\n if (value === undefined) {\n throw new ConfigurationError(\n `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 return parameter;\n });\n}\n\n// ============================================================\n// PreparedQuery\n// ============================================================\n\ntype PreparedQueryConfig<R> = Readonly<{\n ast: QueryAst;\n unoptimizedAst: QueryAst;\n sqlText: string | undefined;\n sqlParams: readonly unknown[] | undefined;\n unoptimizedSqlText: string | undefined;\n unoptimizedSqlParams: readonly unknown[] | undefined;\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-compiled, parameterized query.\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 #sqlText: string | undefined;\n readonly #sqlParams: readonly unknown[] | undefined;\n readonly #unoptimizedSqlText: string | undefined;\n readonly #unoptimizedSqlParams: readonly unknown[] | undefined;\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 constructor(config: PreparedQueryConfig<R>) {\n this.#ast = config.ast;\n this.#unoptimizedAst = config.unoptimizedAst;\n this.#sqlText = config.sqlText;\n this.#sqlParams = config.sqlParams;\n this.#unoptimizedSqlText = config.unoptimizedSqlText;\n this.#unoptimizedSqlParams = config.unoptimizedSqlParams;\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 /** 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 if (\n this.#sqlText !== undefined &&\n this.#sqlParams !== undefined &&\n this.#backend.executeRaw !== undefined\n ) {\n const filledParams = fillPlaceholders(\n this.#sqlParams,\n bindings,\n this.#dialect,\n );\n const rawRows = await this.#backend.executeRaw<Record<string, unknown>>(\n this.#sqlText,\n filledParams,\n );\n return transformPathColumns(rawRows, this.#state, this.#dialect);\n }\n\n const concreteAst = substituteParameters(this.#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 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 if (\n this.#unoptimizedSqlText !== undefined &&\n this.#unoptimizedSqlParams !== undefined &&\n this.#backend.executeRaw !== undefined\n ) {\n const filledParams = fillPlaceholders(\n this.#unoptimizedSqlParams,\n bindings,\n this.#dialect,\n );\n const rawRows = await this.#backend.executeRaw<Record<string, unknown>>(\n this.#unoptimizedSqlText,\n filledParams,\n );\n return transformPathColumns(rawRows, this.#state, this.#dialect);\n }\n\n const concreteAst = substituteParameters(this.#unoptimizedAst, 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.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 { 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 ? {} : { fulltextStrategy }),\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 * 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 { 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 {\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 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 #cachedCompiled: CompiledSelectSql | typeof NOT_COMPUTED = NOT_COMPUTED;\n #cachedOptimizedCompiled: CompiledSelectSql | typeof NOT_COMPUTED =\n NOT_COMPUTED;\n #cachedSelectiveFieldsForExecute:\n | readonly SelectiveField[]\n | typeof NOT_COMPUTED\n | undefined = NOT_COMPUTED;\n #cachedSelectiveFieldsForPagination:\n | readonly SelectiveField[]\n | typeof NOT_COMPUTED\n | undefined = 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.\n */\n toAst(): QueryAst {\n return buildQueryAst(this.#config, this.#state);\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 if (this.#cachedCompiled !== NOT_COMPUTED) return this.#cachedCompiled;\n const ast = this.toAst();\n const compiled = compileQuery(\n ast,\n this.#config.graphId,\n this.#compileOptions(),\n );\n this.#cachedCompiled = compiled;\n return compiled;\n }\n\n /**\n * Creates a prepared (pre-compiled) query that can be executed\n * multiple times with different parameter bindings.\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 = buildQueryAst(this.#config, this.#state);\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\n const compileOptions = this.#compileOptions();\n const compiled = compileQuery(ast, this.#config.graphId, compileOptions);\n\n // Pre-compile to SQL text if the backend supports it\n let sqlText: string | undefined;\n let sqlParams: readonly unknown[] | undefined;\n let unoptimizedSqlText: string | undefined;\n let unoptimizedSqlParams: readonly unknown[] | undefined;\n if (this.#config.backend.compileSql !== undefined) {\n const result = this.#config.backend.compileSql(compiled);\n sqlText = result.sql;\n sqlParams = result.params;\n\n const unoptimizedCompiled = compileQuery(\n unoptimizedAst,\n this.#config.graphId,\n compileOptions,\n );\n const unoptimizedResult =\n this.#config.backend.compileSql(unoptimizedCompiled);\n unoptimizedSqlText = unoptimizedResult.sql;\n unoptimizedSqlParams = unoptimizedResult.params;\n }\n\n return new PreparedQuery({\n ast,\n unoptimizedAst,\n sqlText,\n sqlParams,\n unoptimizedSqlText,\n unoptimizedSqlParams,\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 /**\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 if (hasParameterReferences(this.toAst())) {\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 (existing behavior)\n const compiled = this.compile();\n const rawRows = await this.#executeOnBackend(\n backend,\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-query\",\n );\n\n // Transform path columns for SQLite (converts \"|id1|id2|\" to [\"id1\", \"id2\"])\n const dialect = this.#config.dialect ?? \"sqlite\";\n const rows = transformPathColumns(rawRows, this.#state, dialect);\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 (hasParameterReferences(ast)) {\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\n const compiled = this.compile();\n const rawRows = await this.#executeOnBackend(\n backend,\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-batch-query\",\n );\n const dialect = this.#config.dialect ?? \"sqlite\";\n const rows = transformPathColumns(rawRows, this.#state, dialect);\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 // Build and compile optimized query (cached per instance)\n let compiled: CompiledSelectSql;\n if (this.#cachedOptimizedCompiled === NOT_COMPUTED) {\n const baseAst = buildQueryAst(this.#config, this.#state);\n const selectiveAst = {\n ...baseAst,\n selectiveFields,\n };\n compiled = compileQuery(\n selectiveAst,\n this.#config.graphId,\n this.#compileOptions(),\n );\n this.#cachedOptimizedCompiled = compiled;\n } else {\n compiled = this.#cachedOptimizedCompiled;\n }\n\n const backend = this.#requireBackend();\n const rawSelectiveRows = await this.#executeOnBackend(\n backend,\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-query\",\n );\n const dialect = this.#config.dialect ?? \"sqlite\";\n const rows = transformPathColumns(rawSelectiveRows, this.#state, dialect);\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 this.#cachedOptimizedCompiled = NOT_COMPUTED;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n this.#cachedOptimizedCompiled = NOT_COMPUTED;\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 let compiled: CompiledSelectSql;\n if (this.#cachedOptimizedCompiled === NOT_COMPUTED) {\n const baseAst = buildQueryAst(this.#config, this.#state);\n const selectiveAst = {\n ...baseAst,\n selectiveFields,\n };\n compiled = compileQuery(\n selectiveAst,\n this.#config.graphId,\n this.#compileOptions(),\n );\n this.#cachedOptimizedCompiled = compiled;\n } else {\n compiled = this.#cachedOptimizedCompiled;\n }\n\n const rawSelectiveRows = await this.#executeOnBackend(\n backend,\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-batch-query\",\n );\n const dialect = this.#config.dialect ?? \"sqlite\";\n const rows = transformPathColumns(rawSelectiveRows, this.#state, dialect);\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 this.#cachedOptimizedCompiled = NOT_COMPUTED;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n this.#cachedOptimizedCompiled = NOT_COMPUTED;\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 = a.alias.localeCompare(b.alias);\n if (aliasCompare !== 0) return aliasCompare;\n return a.field.localeCompare(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.#state.orderBy) {\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.#state.orderBy, 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.#state.orderBy) {\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 * 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.#state.orderBy);\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.#state.orderBy,\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.#state.orderBy;\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.#state.orderBy,\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 { type AggregateExpr, type FieldRef, type QueryAst } 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 {\n type AliasMap,\n type QueryBuilderConfig,\n type QueryBuilderState,\n} from \"./types\";\n\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 #cachedCompiled: CompiledSelectSql | typeof NOT_COMPUTED = 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 * 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 if (this.#cachedCompiled !== NOT_COMPUTED) {\n return this.#cachedCompiled;\n }\n const ast = this.toAst();\n const compiled = compileQuery(\n ast,\n this.#config.graphId,\n this.#compileOptions(),\n );\n this.#cachedCompiled = compiled;\n return compiled;\n }\n\n #compileOptions(): CompileQueryOptions {\n return buildCompileOptions(this.#config);\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 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 const compiled = this.compile();\n const rows =\n await this.#config.backend.execute<Record<string, unknown>>(compiled);\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 type AliasMap,\n type EdgeAliasMap,\n type QueryBuilderConfig,\n type SelectContext,\n} from \"./types\";\n\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\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 */\nexport class UnionableQuery<G extends GraphDef, R> {\n readonly #config: QueryBuilderConfig;\n readonly #state: UnionableQueryState;\n #cachedCompiled: CompiledSelectSql | typeof NOT_COMPUTED = 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 if (this.#cachedCompiled !== NOT_COMPUTED) {\n return this.#cachedCompiled;\n }\n\n const compiled = compileSetOperation(\n this.toAst(),\n this.#config.graphId,\n this.#compileOptions(),\n );\n this.#cachedCompiled = compiled;\n return compiled;\n }\n\n #compileOptions(): CompileQueryOptions {\n return buildCompileOptions(this.#config);\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 const compiled = this.compile();\n const rows = await executeOnBackend(\n backend,\n recordedAsOfForComposableQuery(ast),\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-query\",\n );\n\n // Apply select function transformation if available\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\n return rows as readonly R[];\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 const compiled = this.compile();\n const recordedAsOf = recordedAsOfForComposableQuery(ast);\n const rows = await executeOnBackend(\n backend,\n recordedAsOf,\n backend.execute<Record<string, unknown>>(compiled),\n \"recorded-batch-query\",\n );\n\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\n return rows as readonly R[];\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 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 * Keeps the fulltext index in sync with node data. One row per node:\n * the values of every `searchable()` field are concatenated (joined by\n * `\\n`) and stored as the indexed `content`, so a single FTS query can\n * match terms spanning multiple source fields — which a per-field\n * layout cannot, since FTS5 / Postgres MATCH require all terms in one\n * indexed document.\n *\n * Sync runs inline in the node-operation call path, so it inherits the\n * caller's transaction context.\n */\nimport { type z } from \"zod\";\n\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n DEFAULT_SEARCHABLE_LANGUAGE,\n getSearchableMetadata,\n type SearchableMetadata,\n} from \"../core/searchable\";\n\ntype SearchableFieldInfo = Readonly<{\n fieldPath: string;\n metadata: SearchableMetadata;\n}>;\n\nexport type FulltextSyncContext = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n/**\n * Cache keyed by the Zod schema *instance*. Schemas are immutable at\n * runtime and the same `nodeKind.schema` reference is reused across\n * every CRUD call, so this collapses the per-write introspection cost\n * to one walk per schema for the lifetime of the process.\n */\nconst searchableFieldsCache = new WeakMap<\n z.ZodType,\n readonly SearchableFieldInfo[]\n>();\n\n/**\n * Extracts searchable field information from a Zod schema.\n *\n * Handles top-level searchable() strings as well as wrapped variants\n * (optional / nullable / default / readonly / pipe).\n */\nexport function getSearchableFields(\n schema: z.ZodType,\n): readonly SearchableFieldInfo[] {\n const cached = searchableFieldsCache.get(schema);\n if (cached) return cached;\n\n const fields = computeSearchableFields(schema);\n searchableFieldsCache.set(schema, fields);\n return fields;\n}\n\nfunction computeSearchableFields(\n schema: z.ZodType,\n): readonly SearchableFieldInfo[] {\n if (schema.type !== \"object\") return [];\n\n const def = schema.def as { shape?: Record<string, z.ZodType> };\n const shape = def.shape;\n if (!shape) return [];\n\n const fields: SearchableFieldInfo[] = [];\n for (const [fieldPath, fieldSchema] of Object.entries(shape)) {\n const metadata = getSearchableMetadata(fieldSchema);\n if (metadata !== undefined) {\n fields.push({ fieldPath, metadata });\n }\n }\n warnIfConflictingLanguages(fields);\n return fields;\n}\n\n/**\n * Emits a one-time warning per schema when searchable fields declare\n * different `language` values. The first field's language wins on the\n * stored row; true per-field multilingual indexing is not supported\n * today. This fires from `computeSearchableFields`, which is memoized\n * via a WeakMap keyed by schema instance — so the warning is emitted\n * at most once per schema for the lifetime of the process.\n */\nfunction warnIfConflictingLanguages(\n fields: readonly SearchableFieldInfo[],\n): void {\n if (fields.length < 2) return;\n const languages = new Set(fields.map((field) => field.metadata.language));\n if (languages.size < 2) return;\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n const fieldSummary = fields\n .map((field) => `${field.fieldPath}=${field.metadata.language}`)\n .join(\", \");\n const winning = fields[0]?.metadata.language ?? DEFAULT_SEARCHABLE_LANGUAGE;\n console.warn(\n `[typegraph] searchable() fields declare conflicting languages ` +\n `(${fieldSummary}). The first field's language (\"${winning}\") is ` +\n `recorded on the fulltext row; true multilingual indexing requires ` +\n `a dedicated node kind per language.`,\n );\n}\n\nconst FIELD_SEPARATOR = \"\\n\";\n\n/**\n * Picks a representative language when a node has searchable fields with\n * different language settings. Users who need true per-field\n * multilingual indexing should split the data across node kinds.\n */\nfunction resolveCombinedLanguage(\n fields: readonly SearchableFieldInfo[],\n): string {\n return fields[0]?.metadata.language ?? DEFAULT_SEARCHABLE_LANGUAGE;\n}\n\n/**\n * Computes the combined fulltext content for a node, or `undefined`\n * if the node has no non-empty searchable fields.\n *\n * Shared between `syncFulltext` (per-write) and `rebuildFulltextIndex`\n * (bulk) so the two never drift.\n */\nexport function computeFulltextContent(\n schema: z.ZodType,\n props: Record<string, unknown>,\n): { content: string; language: string } | undefined {\n const searchableFields = getSearchableFields(schema);\n if (searchableFields.length === 0) return undefined;\n\n const parts: string[] = [];\n for (const field of searchableFields) {\n const value = props[field.fieldPath];\n if (typeof value === \"string\" && value.length > 0) {\n parts.push(value);\n }\n }\n if (parts.length === 0) return undefined;\n\n return {\n content: parts.join(FIELD_SEPARATOR),\n language: resolveCombinedLanguage(searchableFields),\n };\n}\n\n/**\n * Syncs the fulltext index row after a node create or update.\n *\n * Concatenates the values of all searchable fields into a single content\n * string and upserts it. If every field is empty / undefined, deletes\n * any existing row for the node.\n */\nexport async function syncFulltext(\n ctx: FulltextSyncContext,\n schema: z.ZodType,\n props: Record<string, unknown>,\n): Promise<void> {\n const { backend } = ctx;\n\n if (!backend.upsertFulltext || !backend.deleteFulltext) {\n return;\n }\n\n // `computeFulltextContent` returns `undefined` both when the schema has\n // no `searchable()` fields and when every value is empty — either case\n // means the row should not exist. Delete any stale row only when the\n // schema declares searchable fields (nothing to clean up otherwise).\n const computed = computeFulltextContent(schema, props);\n if (computed !== undefined) {\n await backend.upsertFulltext({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\n content: computed.content,\n language: computed.language,\n });\n return;\n }\n if (getSearchableFields(schema).length === 0) return;\n await backend.deleteFulltext({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\n });\n}\n\n/**\n * Deletes the fulltext row for a node.\n * Called on soft-delete; hard-delete is handled by the backend cascade.\n */\nexport async function deleteNodeFulltext(\n ctx: FulltextSyncContext,\n schema: z.ZodType,\n): Promise<void> {\n const { backend } = ctx;\n\n if (!backend.deleteFulltext) {\n return;\n }\n\n if (getSearchableFields(schema).length === 0) {\n return;\n }\n\n await backend.deleteFulltext({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\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 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 = JSON.parse(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 * Embedding Sync Utilities\n *\n * Handles automatic synchronization of embedding fields with the embeddings table.\n * When nodes with embedding properties are created, updated, or deleted,\n * these utilities ensure the embeddings table stays in sync.\n */\nimport { type z } from \"zod\";\n\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n type ResolvedEmbeddingField,\n resolveEmbeddingFields,\n} from \"../core/embedding\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Information about an embedding field in a node schema.\n *\n * Re-exports the canonical {@link ResolvedEmbeddingField} so the backend\n * gets `dimensions` plus the resolved index `(metric, indexType)` — all\n * three needed to address the field's typed per-`(kind, field)` storage\n * slot when upserting.\n */\ntype EmbeddingFieldInfo = ResolvedEmbeddingField;\n\n/**\n * Context for embedding sync operations.\n */\nexport type EmbeddingSyncContext = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n// ============================================================\n// Schema Introspection\n// ============================================================\n\n/**\n * Cache keyed by the Zod schema instance. Schemas are immutable at\n * runtime; the same reference recurs across every CRUD call.\n */\nconst embeddingFieldsCache = new WeakMap<\n z.ZodType,\n readonly EmbeddingFieldInfo[]\n>();\n\n/**\n * Extracts embedding field information from a Zod schema.\n * Returns all embedding fields found at the top level of an object schema.\n *\n * Thin per-schema-instance memoization over the canonical\n * {@link resolveEmbeddingFields}; the same schema reference recurs across\n * every CRUD call, so caching avoids re-walking the shape each time.\n */\nexport function getEmbeddingFields(\n schema: z.ZodType,\n): readonly EmbeddingFieldInfo[] {\n const cached = embeddingFieldsCache.get(schema);\n if (cached) return cached;\n const fields = resolveEmbeddingFields(schema);\n embeddingFieldsCache.set(schema, fields);\n return fields;\n}\n\n// ============================================================\n// Embedding Sync Operations\n// ============================================================\n\n/**\n * Syncs embeddings after a node create or update operation.\n *\n * For each embedding field in the schema:\n * - If the props contain an embedding value, upsert it to the embeddings table\n * - If the props don't contain an embedding value (undefined), delete any existing embedding\n */\nexport async function syncEmbeddings(\n ctx: EmbeddingSyncContext,\n schema: z.ZodType,\n props: Record<string, unknown>,\n): Promise<void> {\n const { backend } = ctx;\n\n // Check if backend supports embedding operations\n if (!backend.upsertEmbedding || !backend.deleteEmbedding) {\n return;\n }\n\n const embeddingFields = getEmbeddingFields(schema);\n if (embeddingFields.length === 0) {\n return;\n }\n\n for (const field of embeddingFields) {\n const value = props[field.fieldPath];\n\n if (isValidEmbeddingValue(value)) {\n // Upsert the embedding\n await backend.upsertEmbedding({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\n fieldPath: field.fieldPath,\n embedding: value,\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n });\n } else if (value === undefined) {\n // Delete any existing embedding for this field\n await backend.deleteEmbedding({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\n fieldPath: field.fieldPath,\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n });\n }\n // If value is null or invalid, skip (validation should have caught this)\n }\n}\n\n/**\n * Deletes a node's embeddings for the embedding fields its kind CURRENTLY\n * declares. A field dropped from the schema after the node was written is\n * intentionally NOT swept here — its entire per-field table is reclaimed\n * wholesale by `store.materializeRemovals()` (the deferred-cleanup verb), which\n * also covers live (never-deleted) nodes' rows. So a hard/soft delete can leave\n * a transient orphan row in a removed field's table until the next reclaim pass;\n * that is the deferred-cleanup design, not a leak.\n */\nexport async function deleteNodeEmbeddings(\n ctx: EmbeddingSyncContext,\n schema: z.ZodType,\n): Promise<void> {\n const { backend } = ctx;\n\n // Check if backend supports embedding operations\n if (!backend.deleteEmbedding) {\n return;\n }\n\n const embeddingFields = getEmbeddingFields(schema);\n if (embeddingFields.length === 0) {\n return;\n }\n\n for (const field of embeddingFields) {\n await backend.deleteEmbedding({\n graphId: ctx.graphId,\n nodeKind: ctx.nodeKind,\n nodeId: ctx.nodeId,\n fieldPath: field.fieldPath,\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n });\n }\n}\n\n// ============================================================\n// Validation Helpers\n// ============================================================\n\n/**\n * Checks if a value is a valid embedding (array of numbers).\n */\nfunction isValidEmbeddingValue(value: unknown): value is readonly number[] {\n if (!Array.isArray(value)) {\n return false;\n }\n return value.every((n) => typeof n === \"number\" && Number.isFinite(n));\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 {\n type FulltextCapabilities,\n type FulltextQueryMode,\n type GraphBackend,\n type VectorIndexType,\n type VectorMetric,\n} from \"../backend/types\";\nimport { ConfigurationError } from \"../errors\";\nimport {\n DEFAULT_RRF_K,\n DEFAULT_RRF_WEIGHT,\n type HybridFusionOptions,\n} from \"../query/ast\";\nimport { validateHybridFusionOptions } from \"../query/builder/validation\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { assertVectorMinScore } from \"../query/dialect/vector-strategy\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\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\nexport type FulltextSearchOptions = 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: per-row language as\n * stored at insert time.\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 = 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 = 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\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 resolveSearchSlot(\n ctx: StoreSearchContext,\n nodeKind: string,\n fieldPath: string,\n): ResolvedSearchSlot {\n const nodeType = ctx.registry.getNodeType(nodeKind);\n if (nodeType !== undefined) {\n const fields = getEmbeddingFields(nodeType.schema);\n const field = fields.find((entry) => entry.fieldPath === fieldPath);\n if (field !== undefined) {\n return {\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n };\n }\n }\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 validateFulltextCallOptions(backend, {\n mode: options.mode,\n includeSnippets: options.includeSnippets,\n language: options.language,\n });\n\n const params: Parameters<NonNullable<GraphBackend[\"fulltextSearch\"]>>[0] = {\n graphId,\n nodeKind,\n query: options.query,\n limit: options.limit,\n ...(options.mode ? { mode: options.mode } : {}),\n ...(options.language ? { language: options.language } : {}),\n ...(options.minScore === undefined ? {} : { minScore: options.minScore }),\n ...(options.includeSnippets === undefined ?\n {}\n : { includeSnippets: options.includeSnippets }),\n };\n\n const rows = await backend.fulltextSearch(params);\n if (rows.length === 0) return [];\n\n const ids = rows.map((row) => row.nodeId);\n const nodeMap = await fetchNodesByIds(backend, graphId, nodeKind, ids);\n\n const hits: FulltextSearchHit<N>[] = [];\n let rank = 1;\n for (const row of rows) {\n const node = nodeMap.get(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\n const slot = resolveSearchSlot(ctx, nodeKind, options.fieldPath);\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 const rows = await backend.vectorSearch({\n graphId,\n nodeKind,\n fieldPath: options.fieldPath,\n queryEmbedding: options.queryEmbedding,\n // Default to the field's DECLARED metric (the metric its index was built\n // for); only an explicit caller override changes it. Defaulting to cosine\n // here would mis-rank l2 / inner_product fields and bypass their ANN index.\n metric: options.metric ?? slot.metric,\n dimensions: slot.dimensions,\n indexType: slot.indexType,\n limit: options.limit,\n ...(options.minScore === undefined ? {} : { minScore: options.minScore }),\n ...(options.efSearch === undefined ? {} : { efSearch: options.efSearch }),\n });\n if (rows.length === 0) return [];\n\n const ids = rows.map((row) => row.nodeId);\n const nodeMap = await fetchNodesByIds(backend, graphId, nodeKind, ids);\n\n const hits: VectorSearchHit<N>[] = [];\n let rank = 1;\n for (const row of rows) {\n const node = nodeMap.get(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\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 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 overFetchMultiplier = 4;\n const vectorK = options.vector.k ?? options.limit * overFetchMultiplier;\n const fulltextK = options.fulltext.k ?? options.limit * overFetchMultiplier;\n\n const vectorSlot = resolveSearchSlot(ctx, nodeKind, options.vector.fieldPath);\n assertVectorQueryCompatible(\n backend,\n vectorSlot,\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 ?? vectorSlot.metric,\n \"hybridSearch.vector.minScore\",\n );\n const vectorPromise = backend.vectorSearch({\n graphId,\n nodeKind,\n fieldPath: options.vector.fieldPath,\n queryEmbedding: options.vector.queryEmbedding,\n // Default to the field's declared metric (see executeVectorSearch).\n metric: options.vector.metric ?? vectorSlot.metric,\n dimensions: vectorSlot.dimensions,\n indexType: vectorSlot.indexType,\n limit: 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\n const fulltextPromise = backend.fulltextSearch({\n graphId,\n nodeKind,\n query: options.fulltext.query,\n limit: fulltextK,\n ...(options.fulltext.mode ? { mode: options.fulltext.mode } : {}),\n ...(options.fulltext.language ?\n { language: options.fulltext.language }\n : {}),\n ...(options.fulltext.minScore === undefined ?\n {}\n : { minScore: options.fulltext.minScore }),\n ...(options.fulltext.includeSnippets === undefined ?\n {}\n : { includeSnippets: options.fulltext.includeSnippets }),\n });\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 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 entry = fused.get(row.nodeId) ?? {\n nodeId: row.nodeId,\n fusedScore: 0,\n };\n entry.fusedScore += contribution;\n entry.vectorRank = rank;\n entry.vectorScore = row.score;\n fused.set(row.nodeId, entry);\n }\n\n for (const [index, row] of fulltextRows.entries()) {\n const rank = index + 1;\n const contribution = fulltextWeight / (fusionK + rank);\n const entry = fused.get(row.nodeId) ?? {\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(row.nodeId, entry);\n }\n\n const ranked = [...fused.values()]\n .toSorted(\n (a, b) => b.fusedScore - a.fusedScore || a.nodeId.localeCompare(b.nodeId),\n )\n .slice(0, options.limit);\n\n const ids = ranked.map((entry) => entry.nodeId);\n const nodeMap = await fetchNodesByIds(backend, graphId, nodeKind, ids);\n\n const hits: HybridSearchHit<N>[] = [];\n let rank = 1;\n for (const entry of ranked) {\n const node = nodeMap.get(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. If the fulltext\n // or embedding index has drifted (a stale row for a soft-deleted\n // node), skip it here so search never resurrects tombstones.\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 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\ntype StoreSearchContext = Readonly<{\n graphId: string;\n backend: GraphBackend;\n registry: KindRegistry;\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,\n ): Promise<readonly FulltextSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeFulltextSearch<ResolveNode<G, K>>(\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 /**\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,\n ): Promise<readonly VectorSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeVectorSearch<ResolveNode<G, K>>(\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 /**\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,\n ): Promise<readonly HybridSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeHybridSearch<ResolveNode<G, K>>(\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 /**\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","/**\n * Builder functions for creating KindRegistry from GraphDef.\n */\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport {\n type AnyEdgeType,\n type EdgeRegistration,\n type NodeRegistration,\n type NodeType,\n} from \"../core/types\";\nimport {\n computeClosuresFromOntology,\n createEmptyClosures,\n KindRegistry,\n} from \"./kind-registry\";\n\n// ============================================================\n// Build Registry from GraphDef\n// ============================================================\n\n/**\n * Builds a KindRegistry from a GraphDef.\n *\n * This precomputes all transitive closures for efficient runtime queries.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: { Person: { type: Person }, Company: { type: Company } },\n * edges: { worksAt: { type: worksAt, from: [Person], to: [Company] } },\n * ontology: [subClassOf(Company, Organization)],\n * });\n *\n * const registry = buildKindRegistry(graph);\n * registry.isSubClassOf(\"Company\", \"Organization\"); // true\n * ```\n */\nexport function buildKindRegistry<G extends GraphDef>(graph: G): KindRegistry {\n // Extract node types\n const nodeTypes = extractNodeTypes(graph);\n\n // Extract edge types\n const edgeTypes = extractEdgeTypes(graph);\n\n // Compute closures from ontology\n const closures =\n graph.ontology.length > 0 ?\n computeClosuresFromOntology(graph.ontology)\n : createEmptyClosures();\n\n return new KindRegistry(nodeTypes, edgeTypes, closures);\n}\n\n// ============================================================\n// Node Kind Extraction\n// ============================================================\n\n/**\n * Extracts all node types from a GraphDef into a Map.\n */\nfunction extractNodeTypes<G extends GraphDef>(\n graph: G,\n): ReadonlyMap<string, NodeType> {\n const result = new Map<string, NodeType>();\n\n for (const typeName of getNodeKinds(graph)) {\n const registration = graph.nodes[typeName] as NodeRegistration;\n result.set(typeName, registration.type);\n }\n\n return result;\n}\n\n// ============================================================\n// Edge Type Extraction\n// ============================================================\n\n/**\n * Extracts all edge types from a GraphDef into a Map.\n */\nfunction extractEdgeTypes<G extends GraphDef>(\n graph: G,\n): ReadonlyMap<string, AnyEdgeType> {\n const result = new Map<string, AnyEdgeType>();\n\n for (const typeName of getEdgeKinds(graph)) {\n const registration = graph.edges[typeName] as EdgeRegistration;\n result.set(typeName, registration.type);\n }\n\n return result;\n}\n","import { type GraphBackend } from \"../../backend/types\";\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 type TemporalFilterOptions,\n} from \"../../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\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 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: ctx.dialect.currentTimestamp(),\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\n const whereClauses: SQL[] = [\n sql`graph_id = ${ctx.graphId}`,\n resolveTemporalFilter(ctx, options),\n compileDirectionFilter(direction, nodeId),\n ];\n if (options.edges !== undefined) {\n whereClauses.push(compileKindFilter(sql.raw(\"kind\"), options.edges));\n }\n const schema = resolveReadSchema(ctx, options);\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\nfunction compileDirectionFilter(\n direction: TraversalDirection,\n nodeId: string,\n): ReturnType<typeof sql> {\n switch (direction) {\n case \"out\": {\n return sql`from_id = ${nodeId}`;\n }\n case \"in\": {\n return sql`to_id = ${nodeId}`;\n }\n case \"both\": {\n return sql`(from_id = ${nodeId} OR to_id = ${nodeId})`;\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 { 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 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 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","type RowWithId = Readonly<{ id: string }>;\n\nexport type RowFetchPolicy<Row extends RowWithId> = Readonly<{\n batch?: ((ids: readonly string[]) => Promise<readonly Row[]>) | undefined;\n one: (id: string) => Promise<Row | undefined>;\n}>;\n\n/**\n * Shared \"batch if available, otherwise deduped single reads\" policy for\n * store row hydration. Node and edge callers supply only the backend-specific\n * read functions, so future bind-limit/chunking changes land in one place.\n */\nexport async function getRowsByIds<Row extends RowWithId>(\n ids: readonly string[],\n policy: RowFetchPolicy<Row>,\n): Promise<Map<string, Row>> {\n const rowsById = new Map<string, Row>();\n if (ids.length === 0) return rowsById;\n\n if (policy.batch !== undefined) {\n const rows = await policy.batch(ids);\n for (const row of rows) {\n rowsById.set(row.id, row);\n }\n return rowsById;\n }\n\n const uniqueIds = [...new Set(ids)];\n const rows = await Promise.all(uniqueIds.map((id) => policy.one(id)));\n for (const row of rows) {\n if (row !== undefined) rowsById.set(row.id, row);\n }\n return rowsById;\n}\n","/**\n * Shared edge-row fetching.\n *\n * The edge twin of {@link ./node-fetch}: collection reads (`getByIds`), bulk\n * upsert existence probes, and recorded-time after-image capture all need to\n * fetch many edge rows by id, preferring the backend's batch `getEdges` and\n * falling back to parallel `getEdge` calls. Centralizing the fetch mechanics\n * keeps the copies from drifting; each caller layers its own filtering\n * (temporal mode, kind narrowing) on top.\n */\nimport {\n type EdgeRow,\n type GraphBackend,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { getRowsByIds } from \"./row-fetch\";\n\n/**\n * Fetches edge rows by id into a Map keyed by id. Uses `backend.getEdges`\n * when available, otherwise issues parallel `getEdge` calls for the distinct\n * ids. Missing ids are simply absent from the returned Map.\n */\nexport async function getEdgeRowsByIds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n ids: readonly string[],\n): Promise<Map<string, EdgeRow>> {\n return getRowsByIds(ids, {\n batch:\n backend.getEdges === undefined ?\n undefined\n : (batchIds) => backend.getEdges!(graphId, batchIds),\n one: (id) => backend.getEdge(graphId, id),\n });\n}\n","/**\n * EdgeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific edge type.\n */\nimport { type z } from \"zod\";\n\nimport {\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 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 return narrowEdges<E>(results);\n }\n const results = await executeEdgeCreateBatch(batchInputs, backend);\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 if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) => upsertAll(txBackend));\n }\n return upsertAll(backend);\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 return;\n }\n\n await executeEdgeCreateNoReturnBatch(batchInputs, backend);\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 * Shared node-row fetching.\n *\n * Both collection reads (`getByIds`) and declared-index lookup hydration need\n * to fetch many node rows by id, preferring the backend's batch `getNodes`\n * and falling back to parallel `getNode` calls. Centralizing the fetch\n * mechanics keeps the two paths from drifting; each caller layers its own\n * filtering (temporal mode vs. live-only) on top.\n */\nimport {\n type GraphBackend,\n type NodeRow as BackendNodeRow,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { getRowsByIds } from \"./row-fetch\";\n\n/**\n * Fetches node rows by id into a Map keyed by id. Uses `backend.getNodes`\n * when available, otherwise issues parallel `getNode` calls for the distinct\n * ids. Missing ids are simply absent from the returned Map.\n */\nexport async function getNodeRowsByIds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n ids: readonly string[],\n): Promise<Map<string, BackendNodeRow>> {\n return getRowsByIds(ids, {\n batch:\n backend.getNodes === undefined ?\n undefined\n : (batchIds) => backend.getNodes!(graphId, kind, batchIds),\n one: (id) => backend.getNode(graphId, kind, id),\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 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 return narrowNodes<N>(results);\n }\n const results = await executeNodeCreateBatch(batchInputs, backend);\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 if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) => upsertAll(txBackend));\n }\n return upsertAll(backend);\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 return;\n }\n\n await executeNodeCreateNoReturnBatch(batchInputs, backend);\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 const execute = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<NodeGetOrCreateByConstraintResult<N>> => {\n const result = await executeGetOrCreateByConstraint(\n kind,\n constraintName,\n props,\n target,\n options,\n );\n return result as NodeGetOrCreateByConstraintResult<N>;\n };\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) => execute(txBackend));\n }\n return execute(backend);\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 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 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`). v1 surfaces this as a `failed`\n * result; the operator must drop the invalid index manually before\n * retry.\n */\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 { type SqlDialect } from \"../query/dialect/types\";\nimport { sortedReplacer } from \"../schema/canonical\";\nimport { nowIso } from \"../utils/date\";\nimport { sha256Hex } from \"../utils/hash\";\nimport { ensureFocusedStatusTable } from \"./materialize-shared\";\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\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 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 )\n : materializeRelationalIndex(\n declaration,\n backend,\n dialect,\n ddlOptions,\n graphId,\n schemaVersion,\n existingByStatusKey,\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 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 return {\n results: candidates.map((declaration) => byDeclaration.get(declaration)!),\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): Promise<MaterializeIndexesEntry> {\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: () => backend.executeDdl!(ddl),\n existingByStatusKey,\n });\n}\n\nasync function materializeVectorIndex(\n declaration: VectorIndexDeclaration,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>,\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 });\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 }>,\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 const existing = existingByStatusKey.get(statusKey);\n if (existing?.materializedAt !== undefined) {\n if (existing.signature === signature) {\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 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 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\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 */\nexport async function computeIndexSignature(\n dialect: SqlDialect,\n targetTableName: string,\n declaration: IndexDeclaration,\n): Promise<string> {\n const hashable = { dialect, targetTableName, declaration };\n const json = JSON.stringify(hashable, sortedReplacer);\n return sha256Hex(json, 16);\n}\n","import {\n type EdgeRow,\n type GraphBackend,\n type InsertEdgeParams,\n type InsertNodeParams,\n type NodeRow,\n type TransactionBackend,\n} from \"../backend/types\";\n\nexport type InsertDispatch<Params, Row> = Readonly<{\n one: (params: Params) => Promise<Row>;\n oneNoReturn?: ((params: Params) => Promise<void>) | undefined;\n batch?: ((params: readonly Params[]) => Promise<void>) | undefined;\n batchReturning?:\n | ((params: readonly Params[]) => Promise<readonly Row[]>)\n | undefined;\n}>;\n\ntype InsertBackend = GraphBackend | TransactionBackend;\n\nexport function nodeInsertDispatch(\n backend: InsertBackend,\n): InsertDispatch<InsertNodeParams, NodeRow> {\n return {\n one: (params) => backend.insertNode(params),\n oneNoReturn:\n backend.insertNodeNoReturn === undefined ?\n undefined\n : (params) => backend.insertNodeNoReturn!(params),\n batch:\n backend.insertNodesBatch === undefined ?\n undefined\n : (params) => backend.insertNodesBatch!(params),\n batchReturning:\n backend.insertNodesBatchReturning === undefined ?\n undefined\n : (params) => backend.insertNodesBatchReturning!(params),\n };\n}\n\nexport function edgeInsertDispatch(\n backend: InsertBackend,\n): InsertDispatch<InsertEdgeParams, EdgeRow> {\n return {\n one: (params) => backend.insertEdge(params),\n oneNoReturn:\n backend.insertEdgeNoReturn === undefined ?\n undefined\n : (params) => backend.insertEdgeNoReturn!(params),\n batch:\n backend.insertEdgesBatch === undefined ?\n undefined\n : (params) => backend.insertEdgesBatch!(params),\n batchReturning:\n backend.insertEdgesBatchReturning === undefined ?\n undefined\n : (params) => backend.insertEdgesBatchReturning!(params),\n };\n}\n\nexport async function runInsertNoReturn<Params, Row>(\n dispatch: InsertDispatch<Params, Row>,\n params: Params,\n): Promise<void> {\n if (dispatch.oneNoReturn !== undefined) {\n await dispatch.oneNoReturn(params);\n return;\n }\n await dispatch.one(params);\n}\n\nexport async function runInsertBatch<Params, Row>(\n dispatch: InsertDispatch<Params, Row>,\n params: readonly Params[],\n): Promise<void> {\n if (params.length === 0) return;\n if (dispatch.batch !== undefined) {\n await dispatch.batch(params);\n return;\n }\n for (const insertParams of params) {\n await runInsertNoReturn(dispatch, insertParams);\n }\n}\n\nexport async function runInsertBatchReturning<Params, Row>(\n dispatch: InsertDispatch<Params, Row>,\n params: readonly Params[],\n): Promise<readonly Row[]> {\n if (dispatch.batchReturning !== undefined) {\n return dispatch.batchReturning(params);\n }\n const rows: Row[] = [];\n for (const insertParams of params) {\n rows.push(await dispatch.one(insertParams));\n }\n return rows;\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n type AdoptedTransaction,\n type GraphBackend,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../../backend/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { createSqlSchema, type SqlSchema } from \"../../query/compiler/schema\";\nimport {\n asCompiledRowsSql,\n asCompiledStatementSql,\n type CompiledStatementSql,\n} from \"../../query/sql-intent\";\nexport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\n\ntype IsolationRow = Readonly<{ transaction_isolation: unknown }>;\n\n/**\n * Resolves the recorded-relation schema for a capture target, failing loud when\n * the backend does not expose `tableNames`. Without this guard a custom backend\n * that omits `tableNames` would silently fall back to {@link createSqlSchema}'s\n * defaults and write/close recorded rows against the wrong tables.\n */\nexport function requireRecordedSchema(\n target: Pick<GraphBackend, \"tableNames\" | \"dialect\">,\n): SqlSchema {\n if (target.tableNames === undefined) {\n throw new ConfigurationError(\n \"Recorded-time capture requires the backend to expose tableNames.\",\n { dialect: target.dialect },\n {\n suggestion:\n \"Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture targets the configured relations.\",\n },\n );\n }\n return createSqlSchema(target.tableNames);\n}\n\n/**\n * Asserts the transaction target can run capture's non-row-returning\n * statements. Checked once when a capture scope opens so the failure surfaces\n * before any write, not mid-flush after the live row is already written —\n * `assertCapturableBackend` only validates the outer backend, and a custom\n * backend's transaction target can differ from it.\n */\nexport function requireCaptureStatements(\n target: TransactionBackend,\n): asserts target is TransactionBackend &\n Readonly<{\n executeStatement: NonNullable<TransactionBackend[\"executeStatement\"]>;\n }> {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Recorded-time capture requires backend.executeStatement support on the transaction backend.\",\n { dialect: target.dialect },\n {\n suggestion:\n \"Use the built-in SQLite/PostgreSQL backends or provide executeStatement on the custom backend's transaction target.\",\n },\n );\n }\n}\n\nexport async function executeStatement(\n target: TransactionBackend,\n query: SQL,\n): Promise<void> {\n requireCaptureStatements(target);\n await target.executeStatement(asCompiledStatementSql(query));\n}\n\nfunction unsupportedPostgresIsolationError(\n isolationLevel: string | undefined,\n): ConfigurationError {\n return new ConfigurationError(\n \"Recorded-time capture on PostgreSQL requires read_committed isolation.\",\n { isolationLevel: isolationLevel ?? \"unknown\" },\n {\n suggestion:\n \"Omit the transaction isolation option or use read_committed. PostgreSQL repeatable_read/serializable snapshots cannot safely allocate the per-graph recorded clock inside the captured transaction.\",\n },\n );\n}\n\nfunction isSupportedRecordedIsolationLevel(\n isolationLevel: string | undefined,\n): boolean {\n return (\n isolationLevel === undefined ||\n isolationLevel === \"read_committed\" ||\n isolationLevel === \"read_uncommitted\"\n );\n}\n\nexport function assertRequestedRecordedIsolation(\n backend: Pick<GraphBackend, \"dialect\">,\n options: TransactionOptions | undefined,\n): void {\n if (backend.dialect !== \"postgres\") return;\n const isolationLevel = options?.isolationLevel;\n if (isSupportedRecordedIsolationLevel(isolationLevel)) return;\n\n throw unsupportedPostgresIsolationError(isolationLevel);\n}\n\nfunction normalizeIsolationLevel(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value.replaceAll(\" \", \"_\").toLowerCase();\n}\n\nexport async function assertRecordedCaptureTransactionIsolation(\n target: Pick<TransactionBackend, \"dialect\" | \"execute\">,\n): Promise<void> {\n if (target.dialect !== \"postgres\") return;\n\n const rows = await target.execute<IsolationRow>(\n asCompiledRowsSql(sql`\n SELECT current_setting('transaction_isolation') AS transaction_isolation\n `),\n );\n const isolationLevel = normalizeIsolationLevel(\n rows[0]?.transaction_isolation,\n );\n if (isSupportedRecordedIsolationLevel(isolationLevel)) return;\n\n throw unsupportedPostgresIsolationError(isolationLevel);\n}\n\n/**\n * The single error raised when a caller tries to adopt a context-returning\n * external transaction while history capture is on — there is no flush point\n * before the caller commits. `details` carries the call-site-specific context.\n */\nexport function recordedCaptureRequiresCallbackTransactionError(\n details: Record<string, unknown>,\n): ConfigurationError {\n return new ConfigurationError(\n \"withTransaction() has no recorded-time capture flush point when history is enabled.\",\n details,\n {\n suggestion:\n \"Use store.withRecordedTransaction(externalTx, async (tx) => ...) so TypeGraph can flush capture before the caller commits.\",\n },\n );\n}\n\n/**\n * Raw SQL surfaces (`tx.sql`, `backend.executeStatement`) write relational rows\n * without advancing recorded-time capture, so they are disabled on a\n * history-enabled store. `surface` names the escape the caller reached for.\n */\nfunction historyUnsafeRawWriteError(surface: string): ConfigurationError {\n return new ConfigurationError(\n `${surface} is not available when history capture is enabled because raw SQL writes bypass recorded-time capture.`,\n { code: \"RECORDED_CAPTURE_RAW_SQL_DISABLED\" },\n {\n suggestion:\n \"Run graph writes through store.nodes/store.edges (or tx.nodes/tx.edges inside a transaction), or perform raw relational writes outside a history-enabled TypeGraph store.\",\n },\n );\n}\n\nfunction failHistoryUnsafeSqlRef(): never {\n throw historyUnsafeRawWriteError(\"tx.sql\");\n}\n\n/**\n * A stand-in for the raw transaction SQL handle that throws on any access —\n * including `then`, so `await tx.sql` fail-louds rather than silently resolving\n * to the proxy. The history-enabled store hands this to transaction callbacks\n * in place of the real handle so raw writes can't slip past recorded-time\n * capture.\n */\nexport function createHistoryUnsafeSqlRef(): AdoptedTransaction {\n return new Proxy(\n function historyUnsafeSqlRef(): never {\n return failHistoryUnsafeSqlRef();\n },\n {\n get(): never {\n return failHistoryUnsafeSqlRef();\n },\n apply(): never {\n return failHistoryUnsafeSqlRef();\n },\n set(): never {\n return failHistoryUnsafeSqlRef();\n },\n defineProperty(): never {\n return failHistoryUnsafeSqlRef();\n },\n deleteProperty(): never {\n return failHistoryUnsafeSqlRef();\n },\n // Enumeration / inspection traps too, so spreading (`{...tx.sql}`),\n // `Object.keys`, `in`, and prototype reads also fail loudly rather than\n // silently yielding an empty object that reads as \"no raw handle\".\n has(): never {\n return failHistoryUnsafeSqlRef();\n },\n ownKeys(): never {\n return failHistoryUnsafeSqlRef();\n },\n getOwnPropertyDescriptor(): never {\n return failHistoryUnsafeSqlRef();\n },\n getPrototypeOf(): never {\n return failHistoryUnsafeSqlRef();\n },\n },\n ) as unknown as AdoptedTransaction;\n}\n\n/**\n * Disables the raw, non-row-returning write escapes on a history-enabled\n * backend: `executeStatement` and `executeDdl` both return `Promise<void>` and\n * exist solely to run relational writes/DDL that would bypass recorded-time\n * capture. The row-returning raw read path (`executeRaw`, the prepared-query\n * fast path) and `execute` are left intact — they are read contracts, treated\n * identically, and must not be used to route writes (e.g. `DELETE ...\n * RETURNING`); that invariant is documented, not policed by inspecting SQL text.\n */\nexport function rawWriteGuards(\n target: Pick<GraphBackend, \"executeStatement\" | \"executeDdl\">,\n prefix: string,\n): Pick<Partial<GraphBackend>, \"executeStatement\" | \"executeDdl\"> {\n return {\n ...(target.executeStatement === undefined ?\n {}\n : {\n executeStatement(_query: CompiledStatementSql): Promise<void> {\n return Promise.reject(\n historyUnsafeRawWriteError(`${prefix}.executeStatement`),\n );\n },\n }),\n ...(target.executeDdl === undefined ?\n {}\n : {\n executeDdl(_ddl: string): Promise<void> {\n return Promise.reject(\n historyUnsafeRawWriteError(`${prefix}.executeDdl`),\n );\n },\n }),\n };\n}\n\nexport function assertCapturableBackend(backend: GraphBackend): void {\n if (!backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"history: true requires a backend with transaction support.\",\n { dialect: backend.dialect },\n {\n suggestion:\n \"Use a transactional SQLite/PostgreSQL backend or disable recorded-time capture for this store.\",\n },\n );\n }\n if (backend.executeStatement === undefined) {\n throw new ConfigurationError(\n \"history: true requires a backend that supports executeStatement.\",\n { dialect: backend.dialect },\n {\n suggestion:\n \"Use a built-in SQLite/PostgreSQL backend, or implement executeStatement on the custom backend so recorded-time capture can write history rows.\",\n },\n );\n }\n if (backend.capabilities.returning === false) {\n throw new ConfigurationError(\n \"history: true requires a backend that supports UPDATE … RETURNING.\",\n { dialect: backend.dialect },\n {\n suggestion:\n \"Use a built-in SQLite/PostgreSQL backend, or run recorded-time capture on a backend whose engine supports UPDATE … RETURNING — capture closes recorded intervals with a RETURNING statement on its hot path.\",\n },\n );\n }\n if (backend.tableNames === undefined) {\n throw new ConfigurationError(\n \"history: true requires a backend that exposes tableNames.\",\n { dialect: backend.dialect },\n {\n suggestion:\n \"Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture can resolve the recorded relations instead of silently falling back to defaults.\",\n },\n );\n }\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { RECORDED_MAX } from \"../../core/temporal\";\nimport { ConfigurationError } from \"../../errors\";\nimport { type SqlSchema } from \"../../query/compiler/schema\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { nowIso } from \"../../utils/date\";\nimport { executeStatement } from \"./guards\";\n\ntype ClockRow = Readonly<{ recorded_at: unknown }>;\n\n/**\n * Floor sentinel used only to seed-and-lock a graph's clock row before the\n * read/advance/write sequence on SQLite-family backends. Always overwritten by\n * the real commit within the same transaction; chosen so every real wall-clock\n * instant sorts after it on both text and timestamp ordering.\n */\nconst RECORDED_MIN = \"1970-01-01T00:00:00.000Z\";\nconst RECORDED_MAX_TIME = new Date(RECORDED_MAX).getTime();\nconst RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE = \"typegraph:recorded-clock\";\n\nexport function recordedClockAdvisoryLockSql(graphId: string): SQL {\n return sql`\n SELECT pg_advisory_xact_lock(\n hashtext(${RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE}),\n hashtext(${graphId})\n )\n `;\n}\n\nfunction failInvalidClockTimestamp(value: unknown): never {\n throw new ConfigurationError(\n \"Recorded clock row contained an invalid timestamp\",\n { value },\n );\n}\n\n/**\n * A `YYYY-MM-DD[ T]HH:MM:SS[.fff]` timestamp carrying no timezone designator\n * (no trailing `Z` and no `±HH:MM` offset). `new Date()` would parse such a\n * value in the host's *local* zone, so it must be pinned to UTC explicitly.\n */\nconst ZONELESS_DATETIME_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?$/;\nconst OFFSET_DATETIME_PATTERN =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)(Z|[+-]\\d{2}(?::?\\d{2})?)$/i;\n\nfunction normalizeOffsetDesignator(offset: string): string {\n if (offset.toUpperCase() === \"Z\") return \"Z\";\n if (/^[+-]\\d{2}$/.test(offset)) return `${offset}:00`;\n if (/^[+-]\\d{4}$/.test(offset)) {\n return `${offset.slice(0, 3)}:${offset.slice(3)}`;\n }\n return offset;\n}\n\n/**\n * Milliseconds since the epoch for a recorded-clock timestamp string. A\n * zoneless timestamp is interpreted as UTC — not the host's local zone — so\n * `recordedNow()` never drifts by the server's offset (or by a DST transition)\n * on a backend whose driver yields a naive timestamp for the recorded columns.\n * Timezone-aware and date-only strings are parsed as-is (already unambiguous).\n */\nfunction clockTimestampMs(value: string): number {\n if (ZONELESS_DATETIME_PATTERN.test(value)) {\n return Date.parse(`${value.replace(\" \", \"T\")}Z`);\n }\n const offsetMatch = OFFSET_DATETIME_PATTERN.exec(value);\n if (offsetMatch) {\n const [, date, time, offset] = offsetMatch;\n return Date.parse(`${date}T${time}${normalizeOffsetDesignator(offset!)}`);\n }\n return Date.parse(value);\n}\n\n/**\n * Canonicalizes a recorded-clock value (a driver `Date` or an ISO string) to a\n * canonical UTC ISO string. Both branches guard against an unrepresentable\n * instant: a `Date` whose `getTime()` is `NaN` would otherwise make\n * `toISOString()` throw a bare `RangeError`, masking the typed\n * {@link ConfigurationError} the string branch already raises for an\n * unparseable value. Exported for focused unit coverage of that guard.\n */\nexport function toCanonicalIso(value: unknown): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return failInvalidClockTimestamp(value);\n return value.toISOString();\n }\n if (typeof value === \"string\") {\n const timestamp = clockTimestampMs(value);\n if (Number.isNaN(timestamp)) return failInvalidClockTimestamp(value);\n return new Date(timestamp).toISOString();\n }\n return failInvalidClockTimestamp(value);\n}\n\n/**\n * The next monotonic recorded-commit instant (ms since epoch) for a graph: the\n * wall clock, or one millisecond past the previous commit when the wall clock\n * has not advanced. Returned as a number so the caller range-checks it against\n * the open sentinel before formatting — one parse in, one format out.\n */\nfunction nextRecordedCommitTime(previous: string | undefined): number {\n // `nowIso()` (not `Date.now()`) so a mocked wall clock still drives capture;\n // `Date.parse` of its canonical-Z string avoids the extra Date allocation +\n // re-parse of `new Date(nowIso()).getTime()` on this per-commit hot path.\n const wallTime = Date.parse(nowIso());\n return previous === undefined ? wallTime : (\n Math.max(wallTime, Date.parse(previous) + 1)\n );\n}\n\n/**\n * Reads the recorded-time high-water mark for a graph — the latest committed\n * recorded instant. Exported so {@link Store.recordedNow} can hand callers a\n * deterministic `asOfRecorded` anchor. Accepts any read-capable backend or\n * transaction.\n */\nexport async function readRecordedClock(\n target: Pick<GraphBackend, \"execute\">,\n schema: SqlSchema,\n graphId: string,\n): Promise<string | undefined> {\n const rows = await target.execute<ClockRow>(\n asCompiledRowsSql(sql`\n SELECT recorded_at\n FROM ${schema.recordedClockTable}\n WHERE graph_id = ${graphId}\n `),\n );\n const first = rows[0];\n return first === undefined ? undefined : toCanonicalIso(first.recorded_at);\n}\n\nasync function writeRecordedClock(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n recordedAt: string,\n): Promise<void> {\n await executeStatement(\n target,\n sql`\n INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)\n VALUES (${graphId}, ${recordedAt})\n ON CONFLICT (graph_id) DO UPDATE SET recorded_at = ${recordedAt}\n `,\n );\n}\n\nasync function lockRecordedClock(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n ownsWriteLock: boolean,\n): Promise<void> {\n // Serialize the read/advance/write sequence per graph. Without this,\n // concurrent transactions can read the same previous clock value and\n // allocate the same recorded instant.\n if (target.dialect === \"postgres\") {\n await target.execute(\n asCompiledRowsSql(recordedClockAdvisoryLockSql(graphId)),\n );\n return;\n }\n\n // SQLite family: the seed-UPSERT exists only to take the clock row's write\n // lock before reading when the enclosing transaction did NOT already hold one\n // — an adopted external transaction (withRecordedTransaction) may have begun\n // in deferred mode, where two concurrent commits could otherwise both read\n // the same previous value. The bundled transaction paths open BEGIN IMMEDIATE\n // (ownsWriteLock), so the lock is already held and the seed is a redundant\n // write; skip it there. The seeded floor is overwritten by writeRecordedClock\n // in the same transaction when it does run.\n if (ownsWriteLock) return;\n await executeStatement(\n target,\n sql`\n INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)\n VALUES (${graphId}, ${RECORDED_MIN})\n ON CONFLICT (graph_id) DO UPDATE SET recorded_at = recorded_at\n `,\n );\n}\n\nexport async function allocateRecordedCommit(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n ownsWriteLock: boolean,\n): Promise<string> {\n await lockRecordedClock(target, schema, graphId, ownsWriteLock);\n const previous = await readRecordedClock(target, schema, graphId);\n const recordedCommitTime = nextRecordedCommitTime(previous);\n if (\n !Number.isFinite(recordedCommitTime) ||\n recordedCommitTime >= RECORDED_MAX_TIME\n ) {\n throw new ConfigurationError(\n `Recorded commit clock reached the open sentinel ${RECORDED_MAX}`,\n { graphId, recordedCommitTime },\n {\n suggestion:\n \"Use a graph with a normal recorded-time clock; the open sentinel is reserved for relation intervals.\",\n },\n );\n }\n const recordedCommit = new Date(recordedCommitTime).toISOString();\n await writeRecordedClock(target, schema, graphId, recordedCommit);\n return recordedCommit;\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { sqlNull } from \"../../backend/drizzle/operations/shared\";\nimport {\n type EdgeRow,\n type NodeRow,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { RECORDED_MAX } from \"../../core/temporal\";\nimport { ConfigurationError } from \"../../errors\";\nimport { generateId } from \"../../utils/id\";\nimport { executeStatement } from \"./guards\";\n\nexport type RecordedOperation = \"create\" | \"update\" | \"delete\";\n\nexport type RecordedInsert<Row> = Readonly<{\n row: Row;\n operation: RecordedOperation;\n}>;\n\n/**\n * `meta`, `schema_version`, and `tx_id` are reserved SQL:2011 audit columns of\n * the recorded relations. They are not yet populated by a writer, so every\n * captured row stamps `meta` with this empty object and leaves `schema_version`\n * / `tx_id` NULL; they are carried now so the relation shape is stable when a\n * populator lands.\n */\nconst RECORDED_HISTORY_META = \"{}\";\n\n/**\n * Recorded-relation column order. The same list builds each INSERT's column\n * clause and derives the per-statement chunk size, so adding a column updates\n * both in lockstep instead of relying on a hand-counted bind-parameter count.\n */\nexport const RECORDED_NODE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"kind\",\n \"id\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nexport const RECORDED_EDGE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"id\",\n \"kind\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nconst RECORDED_NODE_COLUMN_LIST = sql.raw(RECORDED_NODE_COLUMNS.join(\", \"));\nconst RECORDED_EDGE_COLUMN_LIST = sql.raw(RECORDED_EDGE_COLUMNS.join(\", \"));\n\n/**\n * Conservative per-statement bound-parameter budget, used only as the fallback\n * when a backend does not advertise `capabilities.maxBindParameters`.\n */\nconst RECORDED_BIND_PARAM_BUDGET = 900;\n\nexport function recordedBindParamBudget(\n target: Pick<TransactionBackend, \"capabilities\">,\n): number {\n const budget =\n target.capabilities.maxBindParameters ?? RECORDED_BIND_PARAM_BUDGET;\n if (!Number.isSafeInteger(budget) || budget < 1) {\n throw new ConfigurationError(\n `backend capabilities.maxBindParameters must be a positive integer, got: ${String(budget)}`,\n {\n code: \"INVALID_BACKEND_CAPABILITY\",\n capability: \"maxBindParameters\",\n value: budget,\n },\n );\n }\n return budget;\n}\n\n/**\n * Rows per recorded INSERT statement: the backend's real bound-parameter ceiling\n * divided by the per-row column count.\n */\nfunction recordedChunkSize(\n target: Pick<TransactionBackend, \"capabilities\">,\n columnCount: number,\n): number {\n const budget = recordedBindParamBudget(target);\n return Math.max(1, Math.floor(budget / columnCount));\n}\n\n/**\n * Builds one recorded column's value from an after-image row, the commit\n * instant, and the operation. Each recorded relation maps every column name to\n * one of these, so VALUES tuples are derived from the column list.\n */\ntype RecordedCellBuilder<Row> = (\n row: Row,\n recordedCommit: string,\n operation: RecordedOperation,\n) => SQL;\n\ntype RecordedCommonColumn =\n | \"history_id\"\n | \"graph_id\"\n | \"id\"\n | \"kind\"\n | \"props\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\"\n | \"updated_at\"\n | \"deleted_at\"\n | \"recorded_from\"\n | \"recorded_to\"\n | \"op\"\n | \"schema_version\"\n | \"tx_id\"\n | \"meta\";\n\nfunction recordedCommonCells<Row extends NodeRow | EdgeRow>(): Record<\n RecordedCommonColumn,\n RecordedCellBuilder<Row>\n> {\n return {\n history_id: () => sql`${generateId()}`,\n graph_id: (row) => sql`${row.graph_id}`,\n id: (row) => sql`${row.id}`,\n kind: (row) => sql`${row.kind}`,\n props: (row) => sql`${row.props}`,\n valid_from: (row) => sql`${sqlNull(row.valid_from)}`,\n valid_to: (row) => sql`${sqlNull(row.valid_to)}`,\n created_at: (row) => sql`${row.created_at}`,\n updated_at: (row) => sql`${row.updated_at}`,\n deleted_at: (row) => sql`${sqlNull(row.deleted_at)}`,\n recorded_from: (_row, recordedCommit) => sql`${recordedCommit}`,\n recorded_to: () => sql`${RECORDED_MAX}`,\n op: (_row, _recordedCommit, operation) => sql`${operation}`,\n schema_version: () => sql`NULL`,\n tx_id: () => sql`NULL`,\n meta: () => sql`${RECORDED_HISTORY_META}`,\n };\n}\n\nconst recordedNodeCells: Record<\n (typeof RECORDED_NODE_COLUMNS)[number],\n RecordedCellBuilder<NodeRow>\n> = {\n ...recordedCommonCells<NodeRow>(),\n version: (row) => sql`${row.version}`,\n};\n\nconst recordedEdgeCells: Record<\n (typeof RECORDED_EDGE_COLUMNS)[number],\n RecordedCellBuilder<EdgeRow>\n> = {\n ...recordedCommonCells<EdgeRow>(),\n from_kind: (row) => sql`${row.from_kind}`,\n from_id: (row) => sql`${row.from_id}`,\n to_kind: (row) => sql`${row.to_kind}`,\n to_id: (row) => sql`${row.to_id}`,\n};\n\nfunction recordedValuesTuple<Row, Column extends string>(\n columns: readonly Column[],\n cells: Record<Column, RecordedCellBuilder<Row>>,\n row: Row,\n recordedCommit: string,\n operation: RecordedOperation,\n): SQL {\n const tuple = columns.map((column) =>\n cells[column](row, recordedCommit, operation),\n );\n return sql`(${sql.join(tuple, sql`, `)})`;\n}\n\nasync function insertRecordedRows<Row, Column extends string>(\n target: TransactionBackend,\n table: SQL,\n columnList: SQL,\n columns: readonly Column[],\n cells: Record<Column, RecordedCellBuilder<Row>>,\n inserts: readonly RecordedInsert<Row>[],\n recordedCommit: string,\n): Promise<void> {\n if (inserts.length === 0) return;\n const values = inserts.map((insert) =>\n recordedValuesTuple(\n columns,\n cells,\n insert.row,\n recordedCommit,\n insert.operation,\n ),\n );\n await executeStatement(\n target,\n sql`\n INSERT INTO ${table} (${columnList})\n VALUES ${sql.join(values, sql`, `)}\n `,\n );\n}\n\nexport function recordedNodeChunkSize(target: TransactionBackend): number {\n return recordedChunkSize(target, RECORDED_NODE_COLUMNS.length);\n}\n\nexport function recordedEdgeChunkSize(target: TransactionBackend): number {\n return recordedChunkSize(target, RECORDED_EDGE_COLUMNS.length);\n}\n\nexport function insertRecordedNodeRows(\n target: TransactionBackend,\n table: SQL,\n inserts: readonly RecordedInsert<NodeRow>[],\n recordedCommit: string,\n): Promise<void> {\n return insertRecordedRows(\n target,\n table,\n RECORDED_NODE_COLUMN_LIST,\n RECORDED_NODE_COLUMNS,\n recordedNodeCells,\n inserts,\n recordedCommit,\n );\n}\n\nexport function insertRecordedEdgeRows(\n target: TransactionBackend,\n table: SQL,\n inserts: readonly RecordedInsert<EdgeRow>[],\n recordedCommit: string,\n): Promise<void> {\n return insertRecordedRows(\n target,\n table,\n RECORDED_EDGE_COLUMN_LIST,\n RECORDED_EDGE_COLUMNS,\n recordedEdgeCells,\n inserts,\n recordedCommit,\n );\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n type EdgeRow,\n type HardDeleteNodeParams,\n type NodeRow,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { RECORDED_MAX } from \"../../core/temporal\";\nimport { sqlValueList } from \"../../query/compiler/predicate-utils\";\nimport { type SqlSchema } from \"../../query/compiler/schema\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { chunk } from \"../../utils/array\";\nimport { isPresent } from \"../../utils/presence\";\nimport { getEdgeRowsByIds } from \"../edge-fetch\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport { allocateRecordedCommit } from \"./clock\";\nimport { executeStatement } from \"./guards\";\nimport {\n insertRecordedEdgeRows,\n insertRecordedNodeRows,\n recordedEdgeChunkSize,\n type RecordedInsert,\n recordedNodeChunkSize,\n type RecordedOperation,\n} from \"./relations\";\n\nexport type TouchedNode = Readonly<{\n entity: \"node\";\n graphId: string;\n kind: string;\n id: string;\n // The after-image returned by the live write, when it returned one. Carried so\n // flush can build the recorded row without re-reading a row the write already\n // handed back. Absent for writes that return no row.\n afterImage?: NodeRow | undefined;\n}>;\n\nexport type TouchedEdge = Readonly<{\n entity: \"edge\";\n graphId: string;\n id: string;\n afterImage?: EdgeRow | undefined;\n}>;\n\nexport type TouchedEntity = TouchedNode | TouchedEdge;\n\ntype IdRow = Readonly<{ id: string }>;\ntype ClosedRow = Readonly<{ id: string; deleted_at: unknown }>;\n\nexport function entityKey(entity: TouchedEntity): string {\n switch (entity.entity) {\n case \"node\": {\n return `node\\u0000${entity.graphId}\\u0000${entity.kind}\\u0000${entity.id}`;\n }\n case \"edge\": {\n return `edge\\u0000${entity.graphId}\\u0000${entity.id}`;\n }\n }\n}\n\n/**\n * Closes every open recorded interval for the given ids in one statement and\n * returns, per id, whether the row it just closed was a soft-delete tombstone.\n */\nasync function closeOpenReturning(\n target: TransactionBackend,\n table: SQL,\n graphId: string,\n ids: readonly string[],\n recordedCommit: string,\n kind?: string,\n): Promise<ReadonlyMap<string, boolean>> {\n const kindFilter = kind === undefined ? sql`` : sql`AND kind = ${kind}`;\n const rows = await target.execute<ClosedRow>(\n asCompiledRowsSql(sql`\n UPDATE ${table}\n SET recorded_to = ${recordedCommit}\n WHERE graph_id = ${graphId}\n ${kindFilter}\n AND recorded_to = ${RECORDED_MAX}\n AND id IN (${sqlValueList(ids)})\n RETURNING id, deleted_at\n `),\n );\n return new Map(rows.map((row) => [row.id, isPresent(row.deleted_at)]));\n}\n\nfunction recordedOp(\n hadOpenRow: boolean,\n priorRowWasTombstone: boolean,\n after: Readonly<{ deleted_at: string | undefined }>,\n): RecordedOperation {\n if (isPresent(after.deleted_at)) return \"delete\";\n if (!hadOpenRow || priorRowWasTombstone) return \"create\";\n return \"update\";\n}\n\nfunction groupNodesByKind(\n entities: readonly TouchedNode[],\n): ReadonlyMap<string, TouchedNode[]> {\n const byKind = new Map<string, TouchedNode[]>();\n for (const entity of entities) {\n const group = byKind.get(entity.kind) ?? [];\n group.push(entity);\n byKind.set(entity.kind, group);\n }\n return byKind;\n}\n\nasync function resolveAfterImages<Row>(\n entities: readonly Readonly<{ id: string; afterImage?: Row | undefined }>[],\n readMissing: (ids: readonly string[]) => Promise<ReadonlyMap<string, Row>>,\n): Promise<ReadonlyMap<string, Row>> {\n const afterById = new Map<string, Row>();\n const needRead: string[] = [];\n for (const entity of entities) {\n if (entity.afterImage === undefined) {\n needRead.push(entity.id);\n } else {\n afterById.set(entity.id, entity.afterImage);\n }\n }\n if (needRead.length > 0) {\n for (const [id, row] of await readMissing(needRead)) afterById.set(id, row);\n }\n return afterById;\n}\n\nfunction recordedInsertsFor<\n Row extends Readonly<{ id: string; deleted_at: string | undefined }>,\n>(\n afterById: ReadonlyMap<string, Row>,\n closed: ReadonlyMap<string, boolean>,\n): readonly RecordedInsert<Row>[] {\n return [...afterById.values()].map((row) => ({\n row,\n operation: recordedOp(closed.has(row.id), closed.get(row.id) ?? false, row),\n }));\n}\n\nexport async function flushNodes(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n entities: readonly TouchedNode[],\n recordedCommit: string,\n): Promise<void> {\n const chunkSize = recordedNodeChunkSize(target);\n for (const [kind, group] of groupNodesByKind(entities)) {\n for (const entityChunk of chunk(group, chunkSize)) {\n const ids = entityChunk.map((entity) => entity.id);\n const closed = await closeOpenReturning(\n target,\n schema.recordedNodesTable,\n graphId,\n ids,\n recordedCommit,\n kind,\n );\n const afterById = await resolveAfterImages(entityChunk, (missing) =>\n getNodeRowsByIds(target, graphId, kind, missing),\n );\n await insertRecordedNodeRows(\n target,\n schema.recordedNodesTable,\n recordedInsertsFor(afterById, closed),\n recordedCommit,\n );\n }\n }\n}\n\nexport async function flushEdges(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n entities: readonly TouchedEdge[],\n recordedCommit: string,\n): Promise<void> {\n const chunkSize = recordedEdgeChunkSize(target);\n for (const entityChunk of chunk(entities, chunkSize)) {\n const ids = entityChunk.map((entity) => entity.id);\n const closed = await closeOpenReturning(\n target,\n schema.recordedEdgesTable,\n graphId,\n ids,\n recordedCommit,\n );\n const afterById = await resolveAfterImages(entityChunk, (missing) =>\n getEdgeRowsByIds(target, graphId, missing),\n );\n await insertRecordedEdgeRows(\n target,\n schema.recordedEdgesTable,\n recordedInsertsFor(afterById, closed),\n recordedCommit,\n );\n }\n}\n\nasync function closeOpenByKind(\n target: TransactionBackend,\n table: SQL,\n graphId: string,\n kind: string,\n recordedCommit: string,\n): Promise<void> {\n await executeStatement(\n target,\n sql`\n UPDATE ${table}\n SET recorded_to = ${recordedCommit}\n WHERE graph_id = ${graphId}\n AND kind = ${kind}\n AND recorded_to = ${RECORDED_MAX}\n `,\n );\n}\n\nasync function closeOpenEdgesByNodeKind(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n nodeKind: string,\n recordedCommit: string,\n): Promise<void> {\n await executeStatement(\n target,\n sql`\n UPDATE ${schema.recordedEdgesTable}\n SET recorded_to = ${recordedCommit}\n WHERE graph_id = ${graphId}\n AND (from_kind = ${nodeKind} OR to_kind = ${nodeKind})\n AND recorded_to = ${RECORDED_MAX}\n `,\n );\n}\n\nexport async function closeRecordedHardDeletedKind(\n target: TransactionBackend,\n schema: SqlSchema,\n graphId: string,\n removal: Readonly<{ entity: \"node\" | \"edge\"; kind: string }>,\n ownsWriteLock: boolean,\n): Promise<void> {\n const recordedCommit = await allocateRecordedCommit(\n target,\n schema,\n graphId,\n ownsWriteLock,\n );\n if (removal.entity === \"node\") {\n await closeOpenByKind(\n target,\n schema.recordedNodesTable,\n graphId,\n removal.kind,\n recordedCommit,\n );\n await closeOpenEdgesByNodeKind(\n target,\n schema,\n graphId,\n removal.kind,\n recordedCommit,\n );\n return;\n }\n await closeOpenByKind(\n target,\n schema.recordedEdgesTable,\n graphId,\n removal.kind,\n recordedCommit,\n );\n}\n\nexport async function queryConnectedEdgeIds(\n target: TransactionBackend,\n schema: SqlSchema,\n params: HardDeleteNodeParams,\n): Promise<readonly string[]> {\n const rows = await target.execute<IdRow>(\n asCompiledRowsSql(sql`\n SELECT id\n FROM ${schema.edgesTable}\n WHERE graph_id = ${params.graphId}\n AND (\n (from_kind = ${params.kind} AND from_id = ${params.id})\n OR (to_kind = ${params.kind} AND to_id = ${params.id})\n )\n `),\n );\n return rows.map((row) => row.id);\n}\n","import {\n createBackendOverlay,\n type EdgeRow,\n type GraphBackend,\n type InsertEdgeParams,\n type InsertNodeParams,\n type NodeRow,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../backend/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { groupBy } from \"../utils/array\";\nimport {\n edgeInsertDispatch,\n nodeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"./insert-dispatch\";\nimport { allocateRecordedCommit } from \"./recorded-capture/clock\";\nimport {\n entityKey,\n flushEdges,\n flushNodes,\n queryConnectedEdgeIds,\n type TouchedEdge,\n type TouchedEntity,\n type TouchedNode,\n} from \"./recorded-capture/flush\";\nimport {\n assertCapturableBackend,\n assertRecordedCaptureTransactionIsolation,\n assertRequestedRecordedIsolation,\n createHistoryUnsafeSqlRef,\n rawWriteGuards,\n recordedCaptureRequiresCallbackTransactionError,\n requireCaptureStatements,\n requireRecordedSchema,\n withRecordedRelationsPrecondition,\n} from \"./recorded-capture/guards\";\n\nexport {\n readRecordedClock,\n recordedClockAdvisoryLockSql,\n toCanonicalIso,\n} from \"./recorded-capture/clock\";\nexport { closeRecordedHardDeletedKind } from \"./recorded-capture/flush\";\nexport {\n assertRecordedCaptureTransactionIsolation,\n createHistoryUnsafeSqlRef,\n recordedCaptureRequiresCallbackTransactionError,\n withRecordedRelationsPrecondition,\n} from \"./recorded-capture/guards\";\nexport {\n RECORDED_EDGE_COLUMNS,\n RECORDED_NODE_COLUMNS,\n} from \"./recorded-capture/relations\";\nexport {\n RECORDED_OPTIONAL_WRITE_METHODS,\n RECORDED_REQUIRED_WRITE_METHODS,\n} from \"./recorded-capture/write-surface\";\n\ntype RecordedCaptureSession = Readonly<{\n touchNode: (\n graphId: string,\n kind: string,\n id: string,\n afterImage?: NodeRow,\n ) => void;\n touchEdge: (graphId: string, id: string, afterImage?: EdgeRow) => void;\n flush: (\n target: TransactionBackend,\n schema: SqlSchema,\n ownsWriteLock: boolean,\n ) => Promise<void>;\n}>;\n\ntype RecordedTransactionScope = Readonly<{\n backend: TransactionBackend;\n flush: () => Promise<void>;\n}>;\n\ndeclare const NODE_IDENTITY_KEY_BRAND: unique symbol;\ndeclare const EDGE_IDENTITY_KEY_BRAND: unique symbol;\n\ntype NodeIdentityKey = string &\n Readonly<{ [NODE_IDENTITY_KEY_BRAND]: \"node-identity-key\" }>;\ntype EdgeIdentityKey = string &\n Readonly<{ [EDGE_IDENTITY_KEY_BRAND]: \"edge-identity-key\" }>;\n\ntype NodeIdentityParams = Pick<InsertNodeParams, \"graphId\" | \"kind\" | \"id\">;\ntype NodeIdentityRow = Pick<NodeRow, \"graph_id\" | \"kind\" | \"id\">;\ntype EdgeIdentityParams = Pick<InsertEdgeParams, \"graphId\" | \"id\">;\ntype EdgeIdentityRow = Pick<EdgeRow, \"graph_id\" | \"id\">;\n\nfunction nodeIdentityKey(\n graphId: string,\n kind: string,\n id: string,\n): NodeIdentityKey {\n return `${graphId}\\u0000${kind}\\u0000${id}` as NodeIdentityKey;\n}\n\nfunction nodeParamsIdentityKey(params: NodeIdentityParams): NodeIdentityKey {\n return nodeIdentityKey(params.graphId, params.kind, params.id);\n}\n\nfunction nodeRowIdentityKey(row: NodeIdentityRow): NodeIdentityKey {\n return nodeIdentityKey(row.graph_id, row.kind, row.id);\n}\n\nfunction edgeIdentityKey(graphId: string, id: string): EdgeIdentityKey {\n return `${graphId}\\u0000${id}` as EdgeIdentityKey;\n}\n\nfunction edgeParamsIdentityKey(params: EdgeIdentityParams): EdgeIdentityKey {\n return edgeIdentityKey(params.graphId, params.id);\n}\n\nfunction edgeRowIdentityKey(row: EdgeIdentityRow): EdgeIdentityKey {\n return edgeIdentityKey(row.graph_id, row.id);\n}\n\nfunction createRecordedCaptureSession(): RecordedCaptureSession {\n const touched = new Map<string, TouchedEntity>();\n // Sealed by flush(): a scope flushes exactly once, at its terminal point, so\n // any touch afterward means a graph write happened after capture lost its\n // flush window (e.g. a caller reused the withRecordedTransaction context after\n // it returned). Fail loud rather than let that write commit uncaptured and\n // silently diverge history from live state.\n let sealed = false;\n\n function touch(entity: TouchedEntity): void {\n if (sealed) {\n throw new ConfigurationError(\n \"Recorded-time capture session is sealed: a graph write happened after the transaction's capture was flushed.\",\n { entity: entity.entity, graphId: entity.graphId, id: entity.id },\n {\n suggestion:\n \"Perform all writes inside the withRecordedTransaction callback; do not reuse the transaction context after it returns.\",\n },\n );\n }\n touched.set(entityKey(entity), entity);\n }\n\n return {\n touchNode(\n graphId: string,\n kind: string,\n id: string,\n afterImage?: NodeRow,\n ): void {\n touch({ entity: \"node\", graphId, kind, id, afterImage });\n },\n\n touchEdge(graphId: string, id: string, afterImage?: EdgeRow): void {\n touch({ entity: \"edge\", graphId, id, afterImage });\n },\n\n async flush(\n target: TransactionBackend,\n schema: SqlSchema,\n ownsWriteLock: boolean,\n ): Promise<void> {\n if (sealed) {\n throw new ConfigurationError(\n \"Recorded-time capture session was already flushed.\",\n {},\n {\n suggestion:\n \"A capture scope flushes once at its terminal point; do not flush it twice.\",\n },\n );\n }\n // Seal before the early-return so a no-write scope is sealed too, and\n // before any awaits so a re-entrant touch during flush also fails loud.\n // flush() writes recorded rows directly (never via touch), so sealing here\n // does not block its own work.\n sealed = true;\n if (touched.size === 0) return;\n const byGraph = groupBy(touched.values(), (entity) => entity.graphId);\n for (const [graphId, entities] of byGraph) {\n const recordedCommit = await allocateRecordedCommit(\n target,\n schema,\n graphId,\n ownsWriteLock,\n );\n const nodes = entities.filter(\n (entity): entity is TouchedNode => entity.entity === \"node\",\n );\n const edges = entities.filter(\n (entity): entity is TouchedEdge => entity.entity === \"edge\",\n );\n await flushNodes(target, schema, graphId, nodes, recordedCommit);\n await flushEdges(target, schema, graphId, edges, recordedCommit);\n }\n touched.clear();\n },\n };\n}\n\nfunction createRecordedTransactionBackend(\n target: TransactionBackend,\n session: RecordedCaptureSession,\n schema: SqlSchema,\n): TransactionBackend {\n const nodeDispatch = nodeInsertDispatch(target);\n const edgeDispatch = edgeInsertDispatch(target);\n\n return createBackendOverlay(target, {\n ...rawWriteGuards(target, \"tx.backend\"),\n\n async insertNode(params) {\n const row = await target.insertNode(params);\n session.touchNode(params.graphId, params.kind, params.id, row);\n return row;\n },\n\n ...(target.insertNodeNoReturn === undefined ?\n {}\n : {\n async insertNodeNoReturn(params: InsertNodeParams): Promise<void> {\n await runInsertNoReturn(nodeDispatch, params);\n session.touchNode(params.graphId, params.kind, params.id);\n },\n }),\n\n ...(target.insertNodesBatch === undefined ?\n {}\n : {\n async insertNodesBatch(\n params: readonly InsertNodeParams[],\n ): Promise<void> {\n await runInsertBatch(nodeDispatch, params);\n for (const node of params) {\n session.touchNode(node.graphId, node.kind, node.id);\n }\n },\n }),\n\n ...(target.insertNodesBatchReturning === undefined ?\n {}\n : {\n async insertNodesBatchReturning(\n params: readonly InsertNodeParams[],\n ): Promise<readonly NodeRow[]> {\n const rows = await runInsertBatchReturning(nodeDispatch, params);\n const rowsByIdentity = new Map(\n rows.map((row) => [nodeRowIdentityKey(row), row] as const),\n );\n for (const node of params) {\n session.touchNode(\n node.graphId,\n node.kind,\n node.id,\n rowsByIdentity.get(nodeParamsIdentityKey(node)),\n );\n }\n return rows;\n },\n }),\n\n async updateNode(params) {\n const row = await target.updateNode(params);\n session.touchNode(params.graphId, params.kind, params.id, row);\n return row;\n },\n\n async deleteNode(params) {\n await target.deleteNode(params);\n session.touchNode(params.graphId, params.kind, params.id);\n },\n\n async hardDeleteNode(params) {\n const connectedEdgeIds = await queryConnectedEdgeIds(\n target,\n schema,\n params,\n );\n await target.hardDeleteNode(params);\n session.touchNode(params.graphId, params.kind, params.id);\n for (const edgeId of connectedEdgeIds) {\n session.touchEdge(params.graphId, edgeId);\n }\n },\n\n async insertEdge(params) {\n const row = await target.insertEdge(params);\n session.touchEdge(params.graphId, params.id, row);\n return row;\n },\n\n ...(target.insertEdgeNoReturn === undefined ?\n {}\n : {\n async insertEdgeNoReturn(params: InsertEdgeParams): Promise<void> {\n await runInsertNoReturn(edgeDispatch, params);\n session.touchEdge(params.graphId, params.id);\n },\n }),\n\n ...(target.insertEdgesBatch === undefined ?\n {}\n : {\n async insertEdgesBatch(\n params: readonly InsertEdgeParams[],\n ): Promise<void> {\n await runInsertBatch(edgeDispatch, params);\n for (const edge of params) {\n session.touchEdge(edge.graphId, edge.id);\n }\n },\n }),\n\n ...(target.insertEdgesBatchReturning === undefined ?\n {}\n : {\n async insertEdgesBatchReturning(\n params: readonly InsertEdgeParams[],\n ): Promise<readonly EdgeRow[]> {\n const rows = await runInsertBatchReturning(edgeDispatch, params);\n const rowsByIdentity = new Map(\n rows.map((row) => [edgeRowIdentityKey(row), row] as const),\n );\n for (const edge of params) {\n session.touchEdge(\n edge.graphId,\n edge.id,\n rowsByIdentity.get(edgeParamsIdentityKey(edge)),\n );\n }\n return rows;\n },\n }),\n\n async updateEdge(params) {\n const row = await target.updateEdge(params);\n session.touchEdge(params.graphId, params.id, row);\n return row;\n },\n\n async deleteEdge(params) {\n await target.deleteEdge(params);\n session.touchEdge(params.graphId, params.id);\n },\n\n async hardDeleteEdge(params) {\n await target.hardDeleteEdge(params);\n session.touchEdge(params.graphId, params.id);\n },\n });\n}\n\nexport function createRecordedTransactionScope(\n target: TransactionBackend,\n schema?: SqlSchema,\n // True only when the enclosing transaction already holds a SQLite write lock\n // (the bundled BEGIN IMMEDIATE paths), letting clock allocation skip the\n // redundant seed-UPSERT. Defaults to false so an adopted (possibly deferred)\n // external transaction still seeds the lock — the safe choice.\n ownsWriteLock = false,\n): RecordedTransactionScope {\n // Fail fast — before any write runs in the adopted/opened transaction — if\n // the transaction target cannot execute the statements capture flush needs,\n // rather than throwing mid-flush after the live write has already happened.\n requireCaptureStatements(target);\n const session = createRecordedCaptureSession();\n // Table names are fixed for the transaction's lifetime, so resolve the schema\n // once and thread it through capture instead of rebuilding it per flush. The\n // store passes its resolved schema so capture targets the same recorded\n // relations recorded reads do; the fallback covers standalone capture.\n const resolvedSchema = schema ?? requireRecordedSchema(target);\n return {\n backend: createRecordedTransactionBackend(target, session, resolvedSchema),\n async flush(): Promise<void> {\n // By flush time the live write has committed within this transaction, so a\n // missing-table error can only be a recorded relation — surface it as the\n // typed precondition the constructor gate could not check.\n await withRecordedRelationsPrecondition(\n session.flush(target, resolvedSchema, ownsWriteLock),\n { dialect: target.dialect, surface: \"capture-flush\" },\n );\n },\n };\n}\n\nasync function runCapturedAutocommit<T>(\n backend: GraphBackend,\n schema: SqlSchema | undefined,\n fn: (target: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n): Promise<T> {\n assertRequestedRecordedIsolation(backend, options);\n return backend.transaction(async (target) => {\n await assertRecordedCaptureTransactionIsolation(target);\n // The bundled transaction opened BEGIN IMMEDIATE, so the write lock is held.\n const scope = createRecordedTransactionScope(target, schema, true);\n const result = await fn(scope.backend);\n await scope.flush();\n return result;\n }, options);\n}\n\nexport function createRecordedBackend(\n backend: GraphBackend,\n schema?: SqlSchema,\n): GraphBackend {\n assertCapturableBackend(backend);\n const capture = <T>(\n fn: (target: TransactionBackend) => Promise<T>,\n ): Promise<T> => runCapturedAutocommit(backend, schema, fn);\n\n return createBackendOverlay(backend, {\n ...rawWriteGuards(backend, \"backend\"),\n\n async insertNode(params) {\n return capture((target) => target.insertNode(params));\n },\n\n ...(backend.insertNodeNoReturn === undefined ?\n {}\n : {\n async insertNodeNoReturn(params: InsertNodeParams): Promise<void> {\n await capture((target) =>\n runInsertNoReturn(nodeInsertDispatch(target), params),\n );\n },\n }),\n\n ...(backend.insertNodesBatch === undefined ?\n {}\n : {\n async insertNodesBatch(\n params: readonly InsertNodeParams[],\n ): Promise<void> {\n await capture((target) =>\n runInsertBatch(nodeInsertDispatch(target), params),\n );\n },\n }),\n\n ...(backend.insertNodesBatchReturning === undefined ?\n {}\n : {\n async insertNodesBatchReturning(\n params: readonly InsertNodeParams[],\n ): Promise<readonly NodeRow[]> {\n return capture((target) =>\n runInsertBatchReturning(nodeInsertDispatch(target), params),\n );\n },\n }),\n\n async updateNode(params) {\n return capture((target) => target.updateNode(params));\n },\n\n async deleteNode(params) {\n await capture((target) => target.deleteNode(params));\n },\n\n async hardDeleteNode(params) {\n await capture((target) => target.hardDeleteNode(params));\n },\n\n async insertEdge(params) {\n return capture((target) => target.insertEdge(params));\n },\n\n ...(backend.insertEdgeNoReturn === undefined ?\n {}\n : {\n async insertEdgeNoReturn(params: InsertEdgeParams): Promise<void> {\n await capture((target) =>\n runInsertNoReturn(edgeInsertDispatch(target), params),\n );\n },\n }),\n\n ...(backend.insertEdgesBatch === undefined ?\n {}\n : {\n async insertEdgesBatch(\n params: readonly InsertEdgeParams[],\n ): Promise<void> {\n await capture((target) =>\n runInsertBatch(edgeInsertDispatch(target), params),\n );\n },\n }),\n\n ...(backend.insertEdgesBatchReturning === undefined ?\n {}\n : {\n async insertEdgesBatchReturning(\n params: readonly InsertEdgeParams[],\n ): Promise<readonly EdgeRow[]> {\n return capture((target) =>\n runInsertBatchReturning(edgeInsertDispatch(target), params),\n );\n },\n }),\n\n async updateEdge(params) {\n return capture((target) => target.updateEdge(params));\n },\n\n async deleteEdge(params) {\n await capture((target) => target.deleteEdge(params));\n },\n\n async hardDeleteEdge(params) {\n await capture((target) => target.hardDeleteEdge(params));\n },\n\n async transaction(fn, options) {\n assertRequestedRecordedIsolation(backend, options);\n return backend.transaction(async (target) => {\n await assertRecordedCaptureTransactionIsolation(target);\n // Bundled BEGIN IMMEDIATE transaction — the write lock is already held.\n const scope = createRecordedTransactionScope(target, schema, true);\n const result = await fn(scope.backend, createHistoryUnsafeSqlRef());\n await scope.flush();\n return result;\n }, options);\n },\n\n ...(backend.adoptTransaction === undefined ?\n {}\n : {\n adoptTransaction(externalTx): TransactionBackend {\n throw recordedCaptureRequiresCallbackTransactionError({\n externalTxType: typeof externalTx,\n });\n },\n }),\n });\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 * Constraint validation module.\n *\n * Provides validation functions for enforcing graph constraints:\n * - Uniqueness constraints on node properties\n * - Cardinality constraints on edges\n * - Endpoint type constraints on edges\n * - Disjointness constraints between node kinds\n */\n\n/**\n * Separator used between field values in composite unique keys.\n * Uses ASCII Record Separator (0x1E) — valid UTF-8 and safe for PostgreSQL\n * TEXT columns (unlike \\0 which PostgreSQL rejects).\n */\nconst UNIQUE_KEY_SEPARATOR = \"\\u001E\";\n\n/** Marker for undefined/null field values in unique keys. */\nconst UNIQUE_KEY_NULL_MARKER = \"\\u001F\"; // ASCII Unit Separator\nimport {\n type Cardinality,\n type Collation,\n type EdgeRegistration,\n type NullCheckOp,\n type UniqueConstraint,\n type UniquenessScope,\n} from \"../core/types\";\nimport {\n CardinalityError,\n DisjointError,\n EndpointError,\n UniquenessError,\n} from \"../errors\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { isPresent } from \"../utils/presence\";\n\n// ============================================================\n// Uniqueness Validation\n// ============================================================\n\n/**\n * Computes the unique key for a node's uniqueness constraint.\n *\n * The key is built by concatenating the specified field values,\n * optionally normalized for case-insensitive comparison.\n */\nexport function computeUniqueKey(\n props: Record<string, unknown>,\n fields: readonly string[],\n collation: Collation,\n): string {\n const values = fields.map((field) => {\n const value = props[field];\n if (value === undefined || value === null) {\n return UNIQUE_KEY_NULL_MARKER;\n }\n // Convert to string, handling primitives safely\n const stringValue =\n typeof value === \"string\" ? value\n : typeof value === \"number\" || typeof value === \"boolean\" ?\n value.toString()\n : JSON.stringify(value);\n return collation === \"caseInsensitive\" ?\n stringValue.toLowerCase()\n : stringValue;\n });\n return values.join(UNIQUE_KEY_SEPARATOR);\n}\n\n/**\n * Checks if a uniqueness constraint's where predicate passes.\n */\nexport function checkWherePredicate(\n constraint: UniqueConstraint,\n props: Record<string, unknown>,\n): boolean {\n if (!constraint.where) {\n return true; // No where clause, always applies\n }\n\n // Build predicate context\n const predicateBuilder = buildPredicateContext(props);\n const predicate = constraint.where(predicateBuilder);\n\n // Evaluate predicate\n return evaluatePredicate(predicate, props);\n}\n\ntype UniquePredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\ntype PredicateContext = Readonly<\n Record<\n string,\n Readonly<{\n isNull: () => UniquePredicate;\n isNotNull: () => UniquePredicate;\n }>\n >\n>;\n\n/**\n * Builds a predicate context for where clause evaluation.\n */\nfunction buildPredicateContext(\n props: Record<string, unknown>,\n): PredicateContext {\n const context: Record<\n string,\n { isNull: () => UniquePredicate; isNotNull: () => UniquePredicate }\n > = {};\n\n for (const key of Object.keys(props)) {\n context[key] = {\n isNull: () => ({\n __type: \"unique_predicate\" as const,\n field: key,\n op: \"isNull\" as const,\n }),\n isNotNull: () => ({\n __type: \"unique_predicate\" as const,\n field: key,\n op: \"isNotNull\" as const,\n }),\n };\n }\n\n return context;\n}\n\n/**\n * Evaluates a uniqueness predicate.\n */\nfunction evaluatePredicate(\n predicate: unknown,\n props: Record<string, unknown>,\n): boolean {\n if (\n typeof predicate !== \"object\" ||\n predicate === null ||\n !(\"__type\" in predicate)\n ) {\n return true;\n }\n\n const pred = predicate as {\n __type: string;\n field: string;\n op: NullCheckOp;\n };\n\n if (pred.__type !== \"unique_predicate\") {\n return true;\n }\n\n const value = props[pred.field];\n if (pred.op === \"isNull\") {\n return value === null || value === undefined;\n }\n return isPresent(value);\n}\n\n/**\n * Gets all kinds that should be checked for a uniqueness constraint.\n *\n * For \"kindWithSubClasses\" scope, includes the entire subclass hierarchy:\n * - The kind itself\n * - All ancestors (parent classes)\n * - All descendants of those ancestors (sibling classes)\n *\n * For \"kind\" scope, only the specific kind.\n */\nexport function getKindsForUniquenessCheck(\n baseKind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): readonly string[] {\n if (scope === \"kind\") {\n return [baseKind];\n }\n\n // Get the entire connected subclass hierarchy by finding the root ancestor\n const root = findRootAncestor(baseKind, registry);\n\n // Return the root and all its descendants (which includes baseKind and siblings)\n return registry.expandSubClasses(root);\n}\n\n/**\n * Finds the topmost ancestor of a kind, or the kind itself if it has no ancestors.\n */\nfunction findRootAncestor(kind: string, registry: KindRegistry): string {\n const ancestors = registry.getAncestors(kind);\n\n if (ancestors.size === 0) {\n return kind;\n }\n\n // Find an ancestor with no ancestors (the root)\n for (const ancestor of ancestors) {\n if (registry.getAncestors(ancestor).size === 0) {\n return ancestor;\n }\n }\n\n // If all ancestors have ancestors, recurse up\n const firstAncestor = [...ancestors][0];\n return firstAncestor ? findRootAncestor(firstAncestor, registry) : kind;\n}\n\n/**\n * Creates a uniqueness error.\n */\nexport function createUniquenessError(\n constraintName: string,\n kind: string,\n existingId: string,\n newId: string,\n fields: readonly string[],\n): UniquenessError {\n return new UniquenessError({\n constraintName,\n kind,\n existingId,\n newId,\n fields: [...fields],\n });\n}\n\n// ============================================================\n// Cardinality Validation\n// ============================================================\n\n/**\n * Checks if adding an edge would violate cardinality constraints.\n *\n * @param edgeKind - The edge kind being added\n * @param fromKind - The source node kind\n * @param fromId - The source node ID\n * @param cardinality - The cardinality constraint\n * @param existingEdgeCount - Number of existing edges of this kind from this source\n * @param hasActiveEdge - Whether there's an active (valid_to IS NULL) edge\n * @returns Error if violation, undefined if valid\n */\nexport function checkCardinality(\n edgeKind: string,\n fromKind: string,\n fromId: string,\n cardinality: Cardinality,\n existingEdgeCount: number,\n hasActiveEdge: boolean,\n): CardinalityError | undefined {\n switch (cardinality) {\n case \"many\": {\n // No constraint\n return undefined;\n }\n case \"one\": {\n // At most one edge of this kind from any source node\n if (existingEdgeCount > 0) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"one\",\n existingCount: existingEdgeCount,\n });\n }\n return undefined;\n }\n case \"unique\": {\n // unique is checked separately per (source, target) pair\n return undefined;\n }\n case \"oneActive\": {\n // At most one edge with valid_to IS NULL from any source\n if (hasActiveEdge) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"oneActive\",\n existingCount: 1,\n });\n }\n return undefined;\n }\n }\n}\n\n/**\n * Checks unique edge constraint (at most one edge between any source-target pair).\n */\nexport function checkUniqueEdge(\n edgeKind: string,\n fromKind: string,\n fromId: string,\n _toKind: string,\n _toId: string,\n existingCount: number,\n): CardinalityError | undefined {\n if (existingCount > 0) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"unique\",\n existingCount,\n });\n }\n return undefined;\n}\n\n// ============================================================\n// Endpoint Validation\n// ============================================================\n\n/**\n * Validates that an edge's endpoints are valid node kinds.\n */\nexport function validateEdgeEndpoints(\n edgeKind: string,\n fromKind: string,\n toKind: string,\n registration: EdgeRegistration,\n registry: KindRegistry,\n): EndpointError | undefined {\n // Check from kinds\n const validFromKinds = registration.from.map((node) => node.kind);\n const fromValid = validFromKinds.some((validKind) =>\n registry.isAssignableTo(fromKind, validKind),\n );\n\n if (!fromValid) {\n return new EndpointError({\n edgeKind,\n endpoint: \"from\",\n actualKind: fromKind,\n expectedKinds: validFromKinds,\n });\n }\n\n // Check to kinds\n const validToKinds = registration.to.map((node) => node.kind);\n const toValid = validToKinds.some((validKind) =>\n registry.isAssignableTo(toKind, validKind),\n );\n\n if (!toValid) {\n return new EndpointError({\n edgeKind,\n endpoint: \"to\",\n actualKind: toKind,\n expectedKinds: validToKinds,\n });\n }\n\n return undefined;\n}\n\n// ============================================================\n// Disjointness Validation\n// ============================================================\n\n/**\n * Checks if creating a node would violate disjointness constraints.\n *\n * @param nodeId - The node ID being created\n * @param nodeKind - The kind of the new node\n * @param existingKinds - Kinds of existing nodes with the same ID\n * @param registry - The kind registry for disjointness checks\n * @returns Error if disjoint violation, undefined if valid\n */\nexport function checkDisjointness(\n nodeId: string,\n nodeKind: string,\n existingKinds: readonly string[],\n registry: KindRegistry,\n): DisjointError | undefined {\n for (const existingKind of existingKinds) {\n if (registry.areDisjoint(nodeKind, existingKind)) {\n return new DisjointError({\n nodeId,\n attemptedKind: nodeKind,\n conflictingKind: existingKind,\n });\n }\n }\n return undefined;\n}\n\n/**\n * Gets all disjoint kinds for a given kind.\n */\nexport function getDisjointKinds(\n kind: string,\n registry: KindRegistry,\n): readonly string[] {\n return registry.getDisjointKinds(kind);\n}\n","/**\n * Constraint Checking for Store Operations\n *\n * Handles checking disjointness and cardinality constraints.\n */\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n checkCardinality,\n checkDisjointness,\n checkUniqueEdge,\n} from \"../constraints\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\n\n/**\n * Context for constraint operations.\n */\nexport type ConstraintContext = Readonly<{\n graphId: string;\n registry: KindRegistry;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n/**\n * Checks disjointness constraints for a node.\n *\n * Ensures that a node with a given ID doesn't exist in any disjoint kinds.\n *\n * @throws ValidationError if disjointness constraint is violated\n */\nexport async function checkDisjointnessConstraint(\n ctx: ConstraintContext,\n kind: string,\n id: string,\n): Promise<void> {\n // Get all kinds that are disjoint with this kind\n const disjointKinds = ctx.registry.getDisjointKinds(kind);\n\n // For each disjoint kind, check if a node with this ID exists\n for (const disjointKind of disjointKinds) {\n const existing = await ctx.backend.getNode(ctx.graphId, disjointKind, id);\n if (existing && !existing.deleted_at) {\n const error = checkDisjointness(id, kind, [disjointKind], ctx.registry);\n if (error) throw error;\n }\n }\n}\n\n/**\n * Checks cardinality constraints for an edge.\n *\n * @throws CardinalityError if cardinality constraint is violated\n */\nexport async function checkCardinalityConstraint(\n ctx: ConstraintContext,\n edgeKind: string,\n cardinality: \"many\" | \"one\" | \"unique\" | \"oneActive\",\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n validTo: string | undefined,\n): Promise<void> {\n switch (cardinality) {\n case \"many\": {\n // No constraint - allow any number of edges\n return;\n }\n\n case \"one\": {\n // At most one edge of this kind from this source\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"one\",\n count,\n false,\n );\n if (error) throw error;\n return;\n }\n\n case \"unique\": {\n // At most one edge between this specific source-target pair\n const exists = await ctx.backend.edgeExistsBetween({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n });\n const error = checkUniqueEdge(\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n exists ? 1 : 0,\n );\n if (error) throw error;\n return;\n }\n\n case \"oneActive\": {\n // At most one active edge (valid_to IS NULL) from this source\n // Only check if the new edge will be active (validTo is not set)\n if (validTo !== undefined) {\n // New edge is already ended, no active constraint to check\n return;\n }\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n activeOnly: true,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"oneActive\",\n count,\n count > 0,\n );\n if (error) throw error;\n return;\n }\n }\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 InsertEdgeParams,\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 DatabaseOperationError,\n EdgeNotFoundError,\n EndpointNotFoundError,\n KindNotFoundError,\n ValidationError,\n} from \"../../errors\";\nimport { validateEdgeProps } from \"../../errors/validation\";\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\";\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 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}> {\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 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 };\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 ctx.withOperationHooks(opContext, async () => {\n const prepared = await validateAndPrepareEdgeCreate(\n ctx,\n input,\n id,\n backend,\n );\n\n let row: BackendEdgeRow | undefined;\n if (shouldReturnRow) {\n row = await backend.insertEdge(prepared.insertParams);\n } else {\n await runInsertNoReturn(\n edgeInsertDispatch(backend),\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 * Executes batched edge creates without returning inserted edge payloads.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateNoReturnBatch<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n if (inputs.length === 0) {\n return;\n }\n\n const { backend: validationBackend, registerPendingEdgeForCardinality } =\n createEdgeBatchValidationBackend(backend);\n const preparedCreates: EdgeCreatePrepared[] = [];\n\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 await runInsertBatch(edgeInsertDispatch(backend), batchInsertParams);\n}\n\n/**\n * Executes batched edge creates and returns the inserted edge payloads.\n *\n * Uses batch validation caching and a single multi-row INSERT with RETURNING\n * when the backend supports it. Falls back to sequential inserts otherwise.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateBatch<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<readonly Edge[]> {\n if (inputs.length === 0) {\n return [];\n }\n\n const { backend: validationBackend, registerPendingEdgeForCardinality } =\n createEdgeBatchValidationBackend(backend);\n const preparedCreates: EdgeCreatePrepared[] = [];\n\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 const rows = await runInsertBatchReturning(\n edgeInsertDispatch(backend),\n batchInsertParams,\n );\n\n return rows.map((row) => 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 // Get existing edge first to get the kind for the hook context\n const existing = await backend.getEdge(ctx.graphId, id);\n if (!existing || existing.deleted_at) {\n throw new EdgeNotFoundError(\"unknown\", id);\n }\n\n const opContext = ctx.createOperationContext(\n \"update\",\n \"edge\",\n existing.kind,\n id,\n );\n\n return ctx.withOperationHooks(opContext, async () => {\n // Get registration for schema validation\n const registration = getEdgeRegistration(ctx.graph, existing.kind);\n const edgeKind = registration.type;\n\n // Merge props\n const existingProps = JSON.parse(existing.props) as Record<string, unknown>;\n const mergedProps = { ...existingProps, ...input.props };\n\n // Validate merged props with full context\n const validatedProps = validateEdgeProps(edgeKind.schema, mergedProps, {\n kind: existing.kind,\n operation: \"update\",\n id,\n });\n\n // Validate temporal fields\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n // Update edge - conditionally include optional fields\n const updateParams: {\n graphId: string;\n id: string;\n props: Record<string, unknown>;\n validTo?: string;\n } = {\n graphId: ctx.graphId,\n id,\n props: validatedProps,\n };\n if (validTo !== undefined) updateParams.validTo = validTo;\n\n const row = await backend.updateEdge(updateParams);\n\n return rowToEdge(row);\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 const id = input.id;\n\n const existing = await backend.getEdge(ctx.graphId, id);\n if (!existing) {\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 = JSON.parse(existing.props) as Record<string, unknown>;\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 backend.updateEdge(updateParams);\n\n return rowToEdge(row);\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 // Get edge first to know the kind for the hook context\n const existing = await backend.getEdge(ctx.graphId, id);\n if (!existing || existing.deleted_at) {\n // Already deleted - nothing to do\n return;\n }\n\n const opContext = ctx.createOperationContext(\n \"delete\",\n \"edge\",\n existing.kind,\n id,\n );\n\n return ctx.withOperationHooks(opContext, async () => {\n await backend.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 // Get edge first to know the kind for the hook context\n const existing = await backend.getEdge(ctx.graphId, id);\n if (!existing) {\n // Doesn't exist - nothing to do\n return;\n }\n\n const opContext = ctx.createOperationContext(\n \"delete\",\n \"edge\",\n existing.kind,\n id,\n );\n\n return ctx.withOperationHooks(opContext, async () => {\n await backend.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 = JSON.parse(row.props) as Record<string, unknown>;\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: 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 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 // 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/**\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 and query edges\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\n const rowsByEndpoint = new Map<string, readonly BackendEdgeRow[]>();\n for (const [endpointKey, endpoint] of uniqueEndpoints) {\n const rows = await backend.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\n // Step 3: Partition into toCreate, toFetch, and duplicates\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\n const toCreate: CreateEntry[] = [];\n const toFetch: FetchEntry[] = [];\n const duplicateOf: { index: number; sourceIndex: number }[] = [];\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 interface Result {\n readonly edge: Edge;\n readonly action: GetOrCreateAction;\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 backend,\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,\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 backend,\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 backend,\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 * Uniqueness Constraint Management\n *\n * Handles checking, inserting, updating, and deleting uniqueness constraint entries.\n */\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n checkWherePredicate,\n computeUniqueKey,\n getKindsForUniquenessCheck,\n} from \"../constraints\";\nimport { type UniqueConstraint } from \"../core/types\";\nimport { UniquenessError } from \"../errors\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\n\n/**\n * Context for uniqueness operations.\n */\nexport type UniquenessContext = Readonly<{\n graphId: string;\n registry: KindRegistry;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n/**\n * Checks uniqueness constraints for a new or existing node.\n *\n * @throws ValidationError if any constraint is violated\n */\nexport async function checkUniquenessConstraints(\n ctx: UniquenessContext,\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n): Promise<void> {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) {\n continue;\n }\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n for (const kindToCheck of kindsToCheck) {\n const existing = await ctx.backend.checkUnique({\n graphId: ctx.graphId,\n nodeKind: kindToCheck,\n constraintName: constraint.name,\n key,\n });\n\n if (existing && existing.node_id !== id) {\n throw new UniquenessError({\n constraintName: constraint.name,\n kind: kindToCheck,\n existingId: existing.node_id,\n newId: id,\n fields: constraint.fields,\n });\n }\n }\n }\n}\n\n/**\n * Inserts uniqueness entries for a newly created node.\n */\nexport async function insertUniquenessEntries(\n ctx: UniquenessContext,\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n): Promise<void> {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) {\n continue;\n }\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n\n await ctx.backend.insertUnique({\n graphId: ctx.graphId,\n nodeKind: kind,\n constraintName: constraint.name,\n key,\n nodeId: id,\n concreteKind: kind,\n });\n }\n}\n\n/**\n * Deletes uniqueness entries for a node being deleted.\n */\nexport async function deleteUniquenessEntries(\n ctx: UniquenessContext,\n kind: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n): Promise<void> {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) {\n continue;\n }\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n\n await ctx.backend.deleteUnique({\n graphId: ctx.graphId,\n nodeKind: kind,\n constraintName: constraint.name,\n key,\n });\n }\n}\n\n/**\n * Updates uniqueness entries when a node's props change.\n * Handles cases where:\n * - Constraint now applies (wasn't before)\n * - Constraint no longer applies (was before)\n * - Key value changed\n *\n * @throws ValidationError if updated value violates a constraint\n */\nexport async function updateUniquenessEntries(\n ctx: UniquenessContext,\n kind: string,\n id: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n): Promise<void> {\n for (const constraint of constraints) {\n const oldApplies = checkWherePredicate(constraint, oldProps);\n const newApplies = checkWherePredicate(constraint, newProps);\n\n const oldKey =\n oldApplies ?\n computeUniqueKey(oldProps, constraint.fields, constraint.collation)\n : undefined;\n const newKey =\n newApplies ?\n computeUniqueKey(newProps, constraint.fields, constraint.collation)\n : undefined;\n\n // No change - constraint didn't apply and still doesn't\n if (!oldApplies && !newApplies) {\n continue;\n }\n\n // Keys are the same and constraint still applies - nothing to do\n if (oldApplies && newApplies && oldKey === newKey) {\n continue;\n }\n\n // Delete old entry if constraint used to apply\n if (oldApplies && oldKey !== undefined) {\n await ctx.backend.deleteUnique({\n graphId: ctx.graphId,\n nodeKind: kind,\n constraintName: constraint.name,\n key: oldKey,\n });\n }\n\n // Check and insert new entry if constraint now applies\n if (newApplies && newKey !== undefined) {\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n // Check for conflicts with other nodes\n for (const kindToCheck of kindsToCheck) {\n const existing = await ctx.backend.checkUnique({\n graphId: ctx.graphId,\n nodeKind: kindToCheck,\n constraintName: constraint.name,\n key: newKey,\n });\n\n if (existing && existing.node_id !== id) {\n throw new UniquenessError({\n constraintName: constraint.name,\n kind: kindToCheck,\n existingId: existing.node_id,\n newId: id,\n fields: constraint.fields,\n });\n }\n }\n\n // Insert new uniqueness entry\n await ctx.backend.insertUnique({\n graphId: ctx.graphId,\n nodeKind: kind,\n constraintName: constraint.name,\n key: newKey,\n nodeId: id,\n concreteKind: kind,\n });\n }\n }\n}\n","/**\n * Node Operations for Store\n *\n * Handles node CRUD operations: create, update, delete.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport {\n createBackendOverlay,\n type GraphBackend,\n type InsertNodeParams,\n type NodeRow as BackendNodeRow,\n runOptionallyInTransaction,\n type TransactionBackend,\n type UniqueRow,\n} from \"../../backend/types\";\nimport {\n checkWherePredicate,\n computeUniqueKey,\n getKindsForUniquenessCheck,\n} from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n type KindEntity,\n type NodeType,\n type UniqueConstraint,\n} from \"../../core/types\";\nimport {\n ConfigurationError,\n DatabaseOperationError,\n KindNotFoundError,\n NodeConstraintNotFoundError,\n NodeIndexNotFoundError,\n NodeNotFoundError,\n RestrictedDeleteError,\n ValidationError,\n} from \"../../errors\";\nimport { validateNodeProps } from \"../../errors/validation\";\nimport {\n compileIndexWhere,\n compileNodeIndexFieldKeys,\n type IndexCompilationContext,\n} from \"../../indexes/compiler\";\nimport { type NodeIndexDeclaration } from \"../../indexes/types\";\nimport { type ValueType } from \"../../query/ast\";\nimport {\n createSqlSchema,\n DEFAULT_SQL_SCHEMA,\n} from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { type JsonPointer, resolveJsonPointer } from \"../../query/json-pointer\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { validateOptionalCanonicalIsoDate } from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport {\n checkDisjointnessConstraint,\n type ConstraintContext,\n} from \"../constraints\";\nimport {\n deleteNodeEmbeddings,\n type EmbeddingSyncContext,\n syncEmbeddings,\n} from \"../embedding-sync\";\nimport {\n deleteNodeFulltext,\n type FulltextSyncContext,\n syncFulltext,\n} from \"../fulltext-sync\";\nimport {\n nodeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"../insert-dispatch\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport { rowToNode } from \"../row-mappers\";\nimport {\n type CreateNodeInput,\n type GetOrCreateAction,\n type Node,\n type NodeBulkFindByIndexOptions,\n type NodeGetOrCreateByConstraintOptions,\n type OperationHookContext,\n type UpdateNodeInput,\n} from \"../types\";\nimport {\n checkUniquenessConstraints,\n deleteUniquenessEntries,\n insertUniquenessEntries,\n type UniquenessContext,\n updateUniquenessEntries,\n} from \"../uniqueness\";\n\n// ============================================================\n// Types\n// ============================================================\n\nexport type NodeOperationContext<G extends GraphDef> = Readonly<{\n graph: G;\n graphId: string;\n historyEnabled: boolean;\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\ntype NodeCreatePrepared = Readonly<{\n kind: string;\n id: string;\n nodeKind: NodeType;\n validatedProps: Record<string, unknown>;\n uniqueConstraints: readonly UniqueConstraint[];\n insertParams: InsertNodeParams;\n}>;\n\ntype CachedNodeRow = Awaited<ReturnType<GraphBackend[\"getNode\"]>>;\ntype CachedUniqueRow = Awaited<ReturnType<GraphBackend[\"checkUnique\"]>>;\n\ntype DeleteMode = \"soft\" | \"hard\";\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\nfunction getNodeRegistration<G extends GraphDef>(graph: G, kind: string) {\n const registration = graph.nodes[kind];\n if (registration === undefined) throw new KindNotFoundError(kind, \"node\");\n return registration;\n}\n\nconst CACHE_KEY_SEPARATOR = \"\\u0000\";\n\nfunction buildNodeCacheKey(graphId: string, kind: string, id: string): string {\n return `${graphId}${CACHE_KEY_SEPARATOR}${kind}${CACHE_KEY_SEPARATOR}${id}`;\n}\n\nfunction runInTopLevelTransactionForHistory<G extends GraphDef, T>(\n ctx: NodeOperationContext<G>,\n backend: GraphBackend | TransactionBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n): Promise<T> {\n return ctx.historyEnabled ?\n runOptionallyInTransaction(backend, fn)\n : fn(backend);\n}\n\nfunction buildUniqueCacheKey(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n): string {\n return `${graphId}${CACHE_KEY_SEPARATOR}${nodeKind}${CACHE_KEY_SEPARATOR}${constraintName}${CACHE_KEY_SEPARATOR}${key}`;\n}\n\nfunction createNodeAlreadyExistsError(\n kind: string,\n id: string,\n): ValidationError {\n return new ValidationError(\n `Node already exists: ${kind}/${id}`,\n {\n entityType: \"node\",\n kind,\n operation: \"create\",\n id,\n issues: [{ path: \"id\", message: \"A node with this ID already exists\" }],\n },\n { suggestion: `Use a different ID or update the existing node.` },\n );\n}\n\nfunction buildInsertNodeParams(\n graphId: string,\n kind: string,\n id: string,\n props: Record<string, unknown>,\n validFrom: string | undefined,\n validTo: string | undefined,\n): InsertNodeParams {\n const insertParams: {\n graphId: string;\n kind: string;\n id: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = {\n graphId,\n kind,\n id,\n props,\n };\n if (validFrom !== undefined) insertParams.validFrom = validFrom;\n if (validTo !== undefined) insertParams.validTo = validTo;\n return insertParams;\n}\n\nfunction createPendingUniqueRow(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n nodeId: string,\n): UniqueRow {\n return {\n graph_id: graphId,\n node_kind: nodeKind,\n constraint_name: constraintName,\n key,\n node_id: nodeId,\n concrete_kind: nodeKind,\n deleted_at: undefined,\n };\n}\n\nfunction resolveConstraint<G extends GraphDef>(\n graph: G,\n kind: string,\n constraintName: string,\n): UniqueConstraint {\n const registration = getNodeRegistration(graph, kind);\n const constraints = registration.unique ?? [];\n const constraint = constraints.find(\n (candidate) => candidate.name === constraintName,\n );\n if (constraint === undefined) {\n throw new NodeConstraintNotFoundError(constraintName, kind);\n }\n return constraint;\n}\n\nfunction createUniquenessContext(\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n): UniquenessContext {\n return { graphId, registry, backend };\n}\n\nfunction createEmbeddingSyncContext(\n graphId: string,\n nodeKind: string,\n nodeId: string,\n backend: GraphBackend | TransactionBackend,\n): EmbeddingSyncContext {\n return { graphId, nodeKind, nodeId, backend };\n}\n\nfunction createFulltextSyncContext(\n graphId: string,\n nodeKind: string,\n nodeId: string,\n backend: GraphBackend | TransactionBackend,\n): FulltextSyncContext {\n return { graphId, nodeKind, nodeId, backend };\n}\n\n// ============================================================\n// Batch Validation Cache\n//\n// During batch operations, multiple items may reference the same\n// nodes/unique keys. This cache avoids redundant backend lookups\n// and tracks pending (not-yet-flushed) inserts so that later items\n// in the batch can see earlier ones during validation.\n// ============================================================\n\nfunction createNodeBatchValidationBackend(\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n): Readonly<{\n backend: GraphBackend | TransactionBackend;\n registerPendingNode: (params: InsertNodeParams) => void;\n registerPendingUniqueEntries: (\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ) => void;\n}> {\n const nodeCache = new Map<string, CachedNodeRow>();\n const pendingNodes = new Map<string, NonNullable<CachedNodeRow>>();\n const uniqueCache = new Map<string, CachedUniqueRow>();\n const pendingUniqueOwners = new Map<string, string>();\n\n async function getNodeCached(\n lookupGraphId: string,\n kind: string,\n id: string,\n ): Promise<CachedNodeRow> {\n const cacheKey = buildNodeCacheKey(lookupGraphId, kind, id);\n const pendingNode = pendingNodes.get(cacheKey);\n if (pendingNode !== undefined) return pendingNode;\n if (nodeCache.has(cacheKey)) return nodeCache.get(cacheKey);\n const existing = await backend.getNode(lookupGraphId, kind, id);\n nodeCache.set(cacheKey, existing);\n return existing;\n }\n\n async function checkUniqueCached(\n params: Parameters<GraphBackend[\"checkUnique\"]>[0],\n ): Promise<CachedUniqueRow> {\n const cacheKey = buildUniqueCacheKey(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n );\n const pendingOwner = pendingUniqueOwners.get(cacheKey);\n if (pendingOwner !== undefined) {\n return createPendingUniqueRow(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n pendingOwner,\n );\n }\n if (uniqueCache.has(cacheKey)) return uniqueCache.get(cacheKey);\n const existing = await backend.checkUnique(params);\n uniqueCache.set(cacheKey, existing);\n return existing;\n }\n\n function registerPendingNode(params: InsertNodeParams): void {\n const cacheKey = buildNodeCacheKey(params.graphId, params.kind, params.id);\n pendingNodes.set(cacheKey, {\n graph_id: params.graphId,\n kind: params.kind,\n id: params.id,\n props: JSON.stringify(params.props),\n version: 1,\n valid_from: params.validFrom,\n valid_to: params.validTo,\n created_at: \"\",\n updated_at: \"\",\n deleted_at: undefined,\n });\n }\n\n function registerPendingUniqueEntries(\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ): void {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) continue;\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n const concreteEntryKey = buildUniqueCacheKey(\n graphId,\n kind,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(concreteEntryKey, id);\n\n if (constraint.scope !== \"kind\") {\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n registry,\n );\n for (const kindToCheck of kindsToCheck) {\n const inheritedEntryKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(inheritedEntryKey, id);\n }\n }\n }\n }\n\n const validationBackend = createBackendOverlay(backend, {\n getNode: getNodeCached,\n checkUnique: checkUniqueCached,\n } satisfies Partial<GraphBackend | TransactionBackend>);\n\n return {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n };\n}\n\n// ============================================================\n// Shared Create Pipeline\n// ============================================================\n\nasync function validateAndPrepareNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<NodeCreatePrepared> {\n const kind = input.kind;\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n\n const validatedProps = validateNodeProps(nodeKind.schema, input.props, {\n kind,\n operation: \"create\",\n });\n\n const validFrom = validateOptionalCanonicalIsoDate(\n input.validFrom,\n \"validFrom\",\n );\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n const existingNode = await backend.getNode(ctx.graphId, kind, id);\n if (existingNode && !existingNode.deleted_at) {\n throw createNodeAlreadyExistsError(kind, id);\n }\n\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkDisjointnessConstraint(constraintContext, kind, id);\n\n const uniqueConstraints = registration.unique ?? [];\n await checkUniquenessConstraints(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n kind,\n id,\n validatedProps,\n uniqueConstraints,\n );\n\n return {\n kind,\n id,\n nodeKind,\n validatedProps,\n uniqueConstraints,\n insertParams: buildInsertNodeParams(\n ctx.graphId,\n kind,\n id,\n validatedProps,\n validFrom,\n validTo,\n ),\n };\n}\n\nasync function finalizeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n prepared: NodeCreatePrepared,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await insertUniquenessEntries(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n prepared.kind,\n prepared.id,\n prepared.validatedProps,\n prepared.uniqueConstraints,\n );\n\n await syncEmbeddings(\n createEmbeddingSyncContext(\n ctx.graphId,\n prepared.kind,\n prepared.id,\n backend,\n ),\n prepared.nodeKind.schema,\n prepared.validatedProps,\n );\n\n await syncFulltext(\n createFulltextSyncContext(ctx.graphId, prepared.kind, prepared.id, backend),\n prepared.nodeKind.schema,\n prepared.validatedProps,\n );\n}\n\n// ============================================================\n// Shared Update Pipeline\n//\n// executeNodeUpdate wraps this in operation hooks.\n// executeNodeUpsertUpdate calls it directly (no hooks) for\n// getOrCreate resurrections.\n// ============================================================\n\nasync function performNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const { kind, id } = input;\n const registration = getNodeRegistration(ctx.graph, kind);\n\n const existing = await backend.getNode(ctx.graphId, kind, id);\n if (!existing || (existing.deleted_at && !options?.clearDeleted)) {\n throw new NodeNotFoundError(kind, id);\n }\n\n const existingProps = JSON.parse(existing.props) as Record<string, unknown>;\n const mergedProps = { ...existingProps, ...input.props };\n\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, mergedProps, {\n kind,\n operation: \"update\",\n id,\n });\n\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n await updateUniquenessEntries(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n kind,\n id,\n existingProps,\n validatedProps,\n registration.unique ?? [],\n );\n\n const updateParams: {\n graphId: string;\n kind: string;\n id: string;\n props: Record<string, unknown>;\n validTo?: string;\n incrementVersion?: boolean;\n clearDeleted?: boolean;\n } = {\n graphId: ctx.graphId,\n kind,\n id,\n props: validatedProps,\n incrementVersion: true,\n };\n if (validTo !== undefined) updateParams.validTo = validTo;\n if (options?.clearDeleted) updateParams.clearDeleted = true;\n\n const row = await backend.updateNode(updateParams);\n\n await syncEmbeddings(\n createEmbeddingSyncContext(ctx.graphId, kind, id, backend),\n nodeKind.schema,\n validatedProps,\n );\n\n await syncFulltext(\n createFulltextSyncContext(ctx.graphId, kind, id, backend),\n nodeKind.schema,\n validatedProps,\n );\n\n return rowToNode(row);\n}\n\n// ============================================================\n// Shared Delete Pipeline\n//\n// Soft and hard delete share the same delete-behavior logic\n// (restrict / cascade / disconnect). The only differences are:\n// - whether soft-deleted nodes are skippable (soft) or deletable (hard)\n// - which backend method removes edges and the node itself\n// ============================================================\n\nasync function enforceDeleteBehavior<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n mode: DeleteMode,\n backend: GraphBackend | TransactionBackend,\n registration: ReturnType<typeof getNodeRegistration>,\n): Promise<void> {\n const deleteBehavior = registration.onDelete ?? \"restrict\";\n const connectedEdges = await backend.findEdgesConnectedTo({\n graphId: ctx.graphId,\n nodeKind: kind,\n nodeId: id,\n });\n\n if (connectedEdges.length === 0) return;\n\n switch (deleteBehavior) {\n case \"restrict\": {\n const edgeKinds = [...new Set(connectedEdges.map((edge) => edge.kind))];\n throw new RestrictedDeleteError({\n nodeKind: kind,\n nodeId: id,\n edgeCount: connectedEdges.length,\n edgeKinds,\n });\n }\n\n case \"cascade\":\n case \"disconnect\": {\n // Both behaviors remove connected edges. \"cascade\" signals intent to\n // remove dependent data; \"disconnect\" signals intent to sever the\n // relationship. The effect is identical because edges cannot exist\n // without both endpoints.\n for (const edge of connectedEdges) {\n await (mode === \"hard\" ?\n backend.hardDeleteEdge({\n graphId: ctx.graphId,\n id: edge.id,\n })\n : backend.deleteEdge({\n graphId: ctx.graphId,\n id: edge.id,\n }));\n }\n break;\n }\n }\n}\n\n// ============================================================\n// Shared Batch Preparation\n//\n// Both returning and non-returning batch creates share the same\n// validate-and-register loop. This extracts it.\n// ============================================================\n\nasync function prepareBatchCreates<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<{\n preparedCreates: NodeCreatePrepared[];\n batchInsertParams: InsertNodeParams[];\n}> {\n const {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n } = createNodeBatchValidationBackend(ctx.graphId, ctx.registry, backend);\n\n const preparedCreates: NodeCreatePrepared[] = [];\n\n for (const input of inputs) {\n const id = input.id ?? generateId();\n const prepared = await validateAndPrepareNodeCreate(\n ctx,\n input,\n id,\n validationBackend,\n );\n preparedCreates.push(prepared);\n registerPendingNode(prepared.insertParams);\n registerPendingUniqueEntries(\n prepared.kind,\n prepared.id,\n prepared.validatedProps,\n prepared.uniqueConstraints,\n );\n }\n\n const batchInsertParams = preparedCreates.map(\n (prepared) => prepared.insertParams,\n );\n\n return { preparedCreates, batchInsertParams };\n}\n\n// ============================================================\n// Shared Constraint Lookup\n//\n// Both single and bulk find/getOrCreate operations need to look up\n// unique constraint entries across all applicable kinds.\n// ============================================================\n\nasync function findUniqueRowAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n key: string,\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<\n | { node_id: string; concrete_kind: string; deleted_at: string | undefined }\n | undefined\n> {\n for (const kindToCheck of kindsToCheck) {\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) return row;\n }\n return undefined;\n}\n\ninterface UniqueMatchRow {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}\n\nasync function batchCheckUniqueAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n uniqueKeys: readonly string[],\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<Map<string, UniqueMatchRow>> {\n const existingByKey = new Map<string, UniqueMatchRow>();\n\n for (const kindToCheck of kindsToCheck) {\n if (backend.checkUniqueBatch === undefined) {\n for (const key of uniqueKeys) {\n if (existingByKey.has(key)) continue;\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) {\n existingByKey.set(row.key, row);\n }\n }\n } else {\n const rows = await backend.checkUniqueBatch({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n keys: uniqueKeys,\n includeDeleted,\n });\n for (const row of rows) {\n if (!existingByKey.has(row.key)) {\n existingByKey.set(row.key, row);\n }\n }\n }\n }\n\n return existingByKey;\n}\n\n// ============================================================\n// Node Create Operations\n// ============================================================\n\nasync function executeNodeCreateInternal<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ returnRow?: boolean }>,\n): Promise<Node | undefined> {\n const kind = input.kind;\n const id = input.id ?? generateId();\n const opContext = ctx.createOperationContext(\"create\", \"node\", kind, id);\n const shouldReturnRow = options?.returnRow ?? true;\n\n return ctx.withOperationHooks(opContext, () =>\n runInTopLevelTransactionForHistory(ctx, backend, async (target) => {\n const prepared = await validateAndPrepareNodeCreate(\n ctx,\n input,\n id,\n target,\n );\n\n let row: BackendNodeRow | undefined;\n if (shouldReturnRow) {\n row = await target.insertNode(prepared.insertParams);\n } else {\n await runInsertNoReturn(\n nodeInsertDispatch(target),\n prepared.insertParams,\n );\n }\n\n await finalizeNodeCreate(ctx, prepared, target);\n\n if (row === undefined) return;\n return rowToNode(row);\n }),\n );\n}\n\nexport async function executeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<Node> {\n const result = await executeNodeCreateInternal(ctx, input, backend, {\n returnRow: true,\n });\n if (!result) {\n throw new DatabaseOperationError(\n \"Node create failed: expected created node row\",\n { operation: \"insert\", entity: \"node\" },\n );\n }\n return result;\n}\n\nexport async function executeNodeCreateNoReturn<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await executeNodeCreateInternal(ctx, input, backend, { returnRow: false });\n}\n\n/**\n * Executes batched node creates without returning inserted node 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 executeNodeCreateNoReturnBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n if (inputs.length === 0) return;\n\n await runInTopLevelTransactionForHistory(ctx, backend, async (target) => {\n const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n target,\n );\n\n await runInsertBatch(nodeInsertDispatch(target), batchInsertParams);\n\n for (const prepared of preparedCreates) {\n await finalizeNodeCreate(ctx, prepared, target);\n }\n });\n}\n\n/**\n * Executes batched node creates and returns the inserted node 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 executeNodeCreateBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<readonly Node[]> {\n if (inputs.length === 0) return [];\n\n return runInTopLevelTransactionForHistory(ctx, backend, async (target) => {\n const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n target,\n );\n\n const rows = await runInsertBatchReturning(\n nodeInsertDispatch(target),\n batchInsertParams,\n );\n\n for (const prepared of preparedCreates) {\n await finalizeNodeCreate(ctx, prepared, target);\n }\n\n return rows.map((row) => rowToNode(row));\n });\n}\n\n// ============================================================\n// Node Update Operations\n// ============================================================\n\nexport async function executeNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const opContext = ctx.createOperationContext(\n \"update\",\n \"node\",\n input.kind,\n input.id,\n );\n return ctx.withOperationHooks(opContext, () =>\n runInTopLevelTransactionForHistory(ctx, backend, (target) =>\n performNodeUpdate(ctx, input, target, options),\n ),\n );\n}\n\n/**\n * Executes a node update for upsert — bypasses operation hooks\n * and allows updating soft-deleted nodes when clearDeleted is set.\n */\nexport async function executeNodeUpsertUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n return runInTopLevelTransactionForHistory(ctx, backend, (target) =>\n performNodeUpdate(ctx, input, target, options),\n );\n}\n\n// ============================================================\n// Node Delete Operations\n// ============================================================\n\nexport async function executeNodeDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return ctx.withOperationHooks(opContext, async () => {\n const registration = getNodeRegistration(ctx.graph, kind);\n const preflight = await backend.getNode(ctx.graphId, kind, id);\n if (!preflight || preflight.deleted_at) return;\n\n // The cascade (connected edges, uniques, embeddings, fulltext, node) is not\n // individually atomic, so wrap it in a transaction when the backend supports\n // one — mirroring executeNodeHardDelete. Under recorded-time capture this\n // also collapses the whole cascade into a single recorded commit instant\n // instead of one instant per sub-write.\n const softDelete = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n const existing = await target.getNode(ctx.graphId, kind, id);\n if (!existing || existing.deleted_at) return;\n\n const existingProps = JSON.parse(existing.props) as Record<\n string,\n unknown\n >;\n\n await enforceDeleteBehavior(ctx, kind, id, \"soft\", target, registration);\n\n await target.deleteNode({ graphId: ctx.graphId, kind, id });\n\n await deleteUniquenessEntries(\n createUniquenessContext(ctx.graphId, ctx.registry, target),\n kind,\n existingProps,\n registration.unique ?? [],\n );\n\n const nodeKind = registration.type;\n await deleteNodeEmbeddings(\n createEmbeddingSyncContext(ctx.graphId, kind, id, target),\n nodeKind.schema,\n );\n await deleteNodeFulltext(\n createFulltextSyncContext(ctx.graphId, kind, id, target),\n nodeKind.schema,\n );\n };\n\n await runOptionallyInTransaction(backend, (target) => softDelete(target));\n });\n}\n\n/**\n * Executes a node hard delete operation (permanent removal).\n *\n * Unlike soft delete, this permanently removes the node and all\n * associated data (uniqueness entries, embeddings) from the database.\n */\nexport async function executeNodeHardDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return ctx.withOperationHooks(opContext, async () => {\n const registration = getNodeRegistration(ctx.graph, kind);\n const preflight = await backend.getNode(ctx.graphId, kind, id);\n if (!preflight) return;\n\n // The cascade (uniques, embeddings, edges, node) is not individually atomic,\n // so wrap in a transaction when the backend supports it. Embeddings live in\n // strategy-owned per-`(kind, field)` tables, so they are cleaned up here —\n // through `deleteNodeEmbeddings` → `backend.deleteEmbedding` — rather than\n // in the backend's graph-agnostic `hardDeleteNode` cascade.\n const hardDelete = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n const existing = await target.getNode(ctx.graphId, kind, id);\n if (!existing) return;\n\n await enforceDeleteBehavior(ctx, kind, id, \"hard\", target, registration);\n await target.hardDeleteNode({ graphId: ctx.graphId, kind, id });\n await deleteNodeEmbeddings(\n createEmbeddingSyncContext(ctx.graphId, kind, id, target),\n registration.type.schema,\n );\n };\n\n await runOptionallyInTransaction(backend, (target) => hardDelete(target));\n });\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\nexport async function executeNodeGetOrCreateByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\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 const ifExists = options?.ifExists ?? \"return\";\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n if (!checkWherePredicate(constraint, validatedProps)) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n );\n return { node, action: \"created\" };\n }\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n true,\n );\n\n if (existingUniqueRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n );\n return { node, action: \"created\" };\n }\n\n // Fetch using concrete_kind (may differ from requested kind\n // when scope is \"kindWithSubClasses\" and the match is on a sibling/parent kind)\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n );\n return { node, action: \"created\" };\n }\n\n const isSoftDeleted = existingRow.deleted_at !== undefined;\n\n if (isSoftDeleted || ifExists === \"update\") {\n const concreteKind = existingUniqueRow.concrete_kind;\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n return { node, action: isSoftDeleted ? \"resurrected\" : \"updated\" };\n }\n\n return { node: rowToNode(existingRow), action: \"found\" };\n}\n\n// ============================================================\n// Find-By-Constraint Operations\n// ============================================================\n\nexport async function executeNodeFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n): Promise<Node | undefined> {\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n if (!checkWherePredicate(constraint, validatedProps)) return undefined;\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n false,\n );\n\n if (existingUniqueRow === undefined) return undefined;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined)\n return undefined;\n\n return rowToNode(existingRow);\n}\n\n// ============================================================\n// Bulk Find-By-Constraint\n// ============================================================\n\n/**\n * Validates all items and computes unique constraint keys.\n * Shared by both bulk find and bulk getOrCreate.\n */\nfunction validateAndComputeKeys(\n nodeKind: NodeType,\n kind: string,\n constraint: UniqueConstraint,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n): { validatedProps: Record<string, unknown>; key: string | undefined }[] {\n const validated: {\n validatedProps: Record<string, unknown>;\n key: string | undefined;\n }[] = [];\n\n for (const item of items) {\n const validatedProps = validateNodeProps(nodeKind.schema, item.props, {\n kind,\n operation: \"create\",\n });\n const applies = checkWherePredicate(constraint, validatedProps);\n const key =\n applies ?\n computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n )\n : undefined;\n validated.push({ validatedProps, key });\n }\n\n return validated;\n}\n\nfunction collectUniqueKeys(\n validated: readonly { key: string | undefined }[],\n): string[] {\n return [\n ...new Set(\n validated\n .map((entry) => entry.key)\n .filter((key): key is string => key !== undefined),\n ),\n ];\n}\n\nexport async function executeNodeBulkFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n): Promise<(Node | undefined)[]> {\n if (items.length === 0) return [];\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n false,\n )\n : new Map<string, { node_id: string; concrete_kind: string }>();\n\n // Assemble results, deduplicating keys seen within the batch\n const results: (Node | undefined)[] = Array.from({ length: items.length });\n const seenKeys = new Map<string, number>();\n\n for (const [index, { key }] of validated.entries()) {\n if (key === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n results[index] = results[previousIndex];\n continue;\n }\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existing.concrete_kind,\n existing.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined) {\n results[index] = undefined;\n continue;\n }\n\n results[index] = rowToNode(existingRow);\n }\n\n return results;\n}\n\n// ============================================================\n// Bulk Find-By-Index\n// ============================================================\n\n/**\n * Resolves a declared node index by name, validating the kind first.\n *\n * @throws {KindNotFoundError} when the node kind is not registered\n * @throws {NodeIndexNotFoundError} when no node index of that name exists\n */\nfunction resolveNodeIndex<G extends GraphDef>(\n graph: G,\n kind: string,\n indexName: string,\n): NodeIndexDeclaration {\n getNodeRegistration(graph, kind);\n\n const declaration = graph.indexes?.find(\n (candidate) =>\n candidate.entity === \"node\" &&\n candidate.kind === kind &&\n candidate.name === indexName,\n );\n\n if (declaration?.entity !== \"node\") {\n throw new NodeIndexNotFoundError(indexName, kind);\n }\n\n return declaration;\n}\n\nconst INDEX_PROBE_EXPECTED_TYPEOF: Partial<Record<ValueType, string>> = {\n string: \"string\",\n number: \"number\",\n boolean: \"boolean\",\n};\n\n/**\n * Validates a single probe value against its declared index-field type.\n * Missing/null values are valid (null probes); only a present, scalar\n * value of the wrong type is rejected.\n */\nfunction validateIndexProbeValue(\n value: unknown,\n valueType: ValueType | undefined,\n pointer: JsonPointer,\n kind: string,\n): void {\n if (value === undefined || value === null) return;\n\n // Index keys are scalar; a non-scalar probe can't be bound and must fail\n // with a typed error rather than a cryptic driver bind error downstream.\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n !(value instanceof Date)\n ) {\n throw indexProbeTypeError(\n pointer,\n kind,\n \"a scalar (string, number, boolean, or Date)\",\n value,\n );\n }\n\n if (valueType === \"date\") {\n if (value instanceof Date || typeof value === \"string\") return;\n throw indexProbeTypeError(\n pointer,\n kind,\n \"date (Date or ISO string)\",\n value,\n );\n }\n\n const expected = INDEX_PROBE_EXPECTED_TYPEOF[valueType ?? \"unknown\"];\n if (expected === undefined) return;\n if (typeof value !== expected) {\n throw indexProbeTypeError(pointer, kind, expected, value);\n }\n}\n\nfunction indexProbeTypeError(\n pointer: JsonPointer,\n kind: string,\n expected: string,\n value: unknown,\n): ValidationError {\n return new ValidationError(\n `Index probe value for \"${pointer}\" on node kind \"${kind}\" has an incompatible type`,\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: pointer,\n message: `Expected ${expected}, received ${typeof value}`,\n code: \"invalid_type\",\n },\n ],\n },\n );\n}\n\n/** Coerces a non-null probe value into a driver-bindable scalar. */\nfunction coerceIndexProbeBind(\n value: unknown,\n adapter: DialectAdapter,\n): unknown {\n return adapter.bindValue(normalizeProbeScalar(value as ProbeScalar));\n}\n\ntype ProbeScalar = string | number | boolean | Date;\n\n/**\n * Canonical scalar form of a validated probe value, shared by the dedup key\n * and the bound SQL value so the two can never drift (a Date and its ISO\n * string normalize identically — and produce identical predicates).\n */\nfunction normalizeProbeScalar(value: ProbeScalar): string | number | boolean {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nconst PROBE_NULL_TAG = 0;\nconst PROBE_VALUE_TAG = 1;\n\n/**\n * Stable dedup key for a probe tuple. Each slot is tagged so a null/undefined\n * value can never collide with a string that happens to equal a sentinel -\n * null maps to [0], a present scalar to [1, normalized].\n */\nfunction canonicalIndexProbeKey(probe: readonly unknown[]): string {\n return JSON.stringify(\n probe.map((value) =>\n value === undefined || value === null ?\n [PROBE_NULL_TAG]\n : [PROBE_VALUE_TAG, normalizeProbeScalar(value as ProbeScalar)],\n ),\n );\n}\n\n/**\n * Batched candidate retrieval against a declared node index.\n *\n * Emits a single query against the nodes table: each input's indexed-field\n * values become a probe predicate (null-safe equality, reusing the index's\n * own extraction expressions so the planner can use the physical index), and\n * a `CASE` selector tags each matched row with the deduped probe group it\n * satisfies. Rows are grouped back to input positions in order; each input's\n * candidate set is ordered by node id.\n */\nexport async function executeNodeBulkFindByIndex<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\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 if (items.length === 0) return [];\n\n const index = resolveNodeIndex(ctx.graph, kind, indexName);\n\n // Date-typed lookup keys can't satisfy the cross-backend parity guarantee:\n // SQLite compares stored ISO text byte-wise while Postgres compares\n // timestamptz instants, so equal instants in different ISO forms diverge.\n // Declare the gap rather than return backend-dependent results.\n if (index.fieldValueTypes.includes(\"date\")) {\n throw new ConfigurationError(\n `bulkFindByIndex does not support date-typed key fields on index \"${indexName}\" (node kind \"${kind}\")`,\n { indexName, kind },\n {\n suggestion:\n \"Date index keys compare differently across SQLite and PostgreSQL. Use a string-encoded key field, or query date predicates via store.query(...).where(...).\",\n },\n );\n }\n\n const limitPerInput = options?.limitPerInput;\n if (\n limitPerInput !== undefined &&\n (!Number.isInteger(limitPerInput) || limitPerInput <= 0)\n ) {\n throw new ValidationError(\n \"bulkFindByIndex limitPerInput must be a positive integer\",\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: \"limitPerInput\",\n message: `Expected a positive integer, received ${String(limitPerInput)}`,\n code: \"invalid_value\",\n },\n ],\n },\n );\n }\n\n const adapter = getDialect(backend.dialect);\n\n // 1. Extract + validate each input's indexed-field probe tuple.\n const probes: unknown[][] = items.map((item) =>\n index.fields.map((pointer, position) => {\n const value = resolveJsonPointer(item.props, pointer);\n validateIndexProbeValue(\n value,\n index.fieldValueTypes[position],\n pointer,\n kind,\n );\n return value;\n }),\n );\n\n // 2. Dedupe probe tuples; map each distinct tuple to its input positions.\n const groupByKey = new Map<string, number>();\n const groupProbes: unknown[][] = [];\n const groupToInputs: number[][] = [];\n for (const [inputIndex, probe] of probes.entries()) {\n const key = canonicalIndexProbeKey(probe);\n const existing = groupByKey.get(key);\n if (existing === undefined) {\n groupByKey.set(key, groupProbes.length);\n groupProbes.push(probe);\n groupToInputs.push([inputIndex]);\n continue;\n }\n groupToInputs[existing]?.push(inputIndex);\n }\n\n // 3. Build probe predicates shared by the CASE selector and WHERE filter.\n const schema =\n backend.tableNames ?\n createSqlSchema(backend.tableNames)\n : DEFAULT_SQL_SCHEMA;\n const compileContext: IndexCompilationContext = {\n dialect: backend.dialect,\n propsColumn: sql.raw(`\"props\"`),\n systemColumn: (column) => sql.raw(`\"${column}\"`),\n };\n const fieldKeys = compileNodeIndexFieldKeys(index, compileContext);\n\n const groupPredicates = groupProbes.map(\n (probe) =>\n sql`(${sql.join(\n fieldKeys.map((fieldKey, position) => {\n const value = probe[position];\n if (value === undefined || value === null) {\n return sql`${fieldKey} IS NULL`;\n }\n return adapter.nullSafeEquals(\n fieldKey,\n sql`${coerceIndexProbeBind(value, adapter)}`,\n );\n }),\n sql` AND `,\n )})`,\n );\n\n const caseBranches = groupPredicates.map(\n (predicate, group) => sql`WHEN ${predicate} THEN ${sql.raw(String(group))}`,\n );\n const probeIndexExpr = sql`CASE ${sql.join(caseBranches, sql` `)} ELSE NULL END`;\n\n const conditions: SQL[] = [\n sql`\"graph_id\" = ${ctx.graphId}`,\n sql`\"kind\" = ${kind}`,\n sql`\"deleted_at\" IS NULL`,\n ];\n if (index.where !== undefined) {\n conditions.push(compileIndexWhere(compileContext, index.where));\n }\n conditions.push(sql`(${sql.join(groupPredicates, sql` OR `)})`);\n const whereClause = sql.join(conditions, sql` AND `);\n\n // The probe matching runs against the nodes table; rows are hydrated\n // separately via the backend's normalized node reads so the returned\n // shape is identical to every other node API (props/timestamp\n // normalization is backend-owned, not re-derived from raw driver rows).\n const probedSelect = sql`SELECT \"id\", ${probeIndexExpr} AS probe_idx FROM ${schema.nodesTable} WHERE ${whereClause}`;\n\n // limitPerInput caps each input's candidates per probe group. When the\n // backend supports window functions we cap in SQL (`ROW_NUMBER()`), which\n // also avoids transferring excess ids on low-selectivity keys. Otherwise we\n // degrade gracefully: fetch all matching ids and cap per group in JS before\n // hydration — the cap stays correct, only the id transfer is unbounded.\n const capInSql =\n limitPerInput !== undefined && backend.capabilities.windowFunctions;\n\n const query =\n capInSql ?\n sql`SELECT \"id\", probe_idx FROM (SELECT \"id\", probe_idx, ROW_NUMBER() OVER (PARTITION BY probe_idx ORDER BY \"id\") AS probe_rank FROM (${probedSelect}) AS probed) AS ranked WHERE probe_rank <= ${limitPerInput} ORDER BY probe_idx, \"id\"`\n : sql`${probedSelect} ORDER BY probe_idx, \"id\"`;\n\n // 4. Execute, hydrate matched nodes, and group back to input positions.\n const rawMatches = await backend.execute<ProbeMatch>(\n asCompiledRowsSql(query),\n );\n const matches =\n limitPerInput !== undefined && !capInSql ?\n capMatchesPerGroup(rawMatches, limitPerInput)\n : rawMatches;\n\n const nodesById = await hydrateNodesById(\n backend,\n ctx.graphId,\n kind,\n matches.map((match) => match.id),\n );\n\n const results: Node[][] = Array.from({ length: items.length }, () => []);\n for (const match of matches) {\n const node = nodesById.get(match.id);\n if (node === undefined) continue;\n const inputs = groupToInputs[match.probe_idx];\n if (inputs === undefined) continue;\n for (const inputIndex of inputs) {\n results[inputIndex]?.push(node);\n }\n }\n\n return results;\n}\n\ntype ProbeMatch = Readonly<{ id: string; probe_idx: number }>;\n\n/**\n * Caps matches to the first `limitPerInput` per probe group (the JS-side\n * equivalent of the `ROW_NUMBER()` window). Relies on `matches` already being\n * ordered by `(probe_idx, id)`, so the kept rows are the lowest ids per group.\n */\nfunction capMatchesPerGroup(\n matches: readonly ProbeMatch[],\n limitPerInput: number,\n): ProbeMatch[] {\n const perGroupCount = new Map<number, number>();\n const capped: ProbeMatch[] = [];\n for (const match of matches) {\n const count = perGroupCount.get(match.probe_idx) ?? 0;\n if (count >= limitPerInput) continue;\n perGroupCount.set(match.probe_idx, count + 1);\n capped.push(match);\n }\n return capped;\n}\n\n/** Hydrates live nodes by id via the backend's normalized node reads. */\nasync function hydrateNodesById(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n ids: readonly string[],\n): Promise<Map<string, Node>> {\n const rowsById = await getNodeRowsByIds(backend, graphId, kind, ids);\n const nodesById = new Map<string, Node>();\n for (const [id, row] of rowsById) {\n if (row.deleted_at !== undefined) continue;\n nodesById.set(id, rowToNode(row));\n }\n return nodesById;\n}\n\n// ============================================================\n// Bulk Get-Or-Create-By-Constraint\n// ============================================================\n\nexport async function executeNodeBulkGetOrCreateByConstraint<\n G extends GraphDef,\n>(\n ctx: NodeOperationContext<G>,\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 if (items.length === 0) return [];\n\n const ifExists = options?.ifExists ?? \"return\";\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n // Step 1: Validate all props and compute keys\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n // Step 2: Batch-check existing keys\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n true,\n )\n : new Map<\n string,\n {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n }\n >();\n\n // Step 3: Partition into toCreate, toFetch, and duplicates\n const toCreate: { index: number; input: CreateNodeInput }[] = [];\n const toFetch: {\n index: number;\n nodeId: string;\n concreteKind: string;\n validatedProps: Record<string, unknown>;\n isSoftDeleted: boolean;\n }[] = [];\n const duplicateOf: { index: number; sourceIndex: number }[] = [];\n const seenKeys = new Map<string, number>();\n\n for (const [index, { validatedProps, key }] of validated.entries()) {\n if (key === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n duplicateOf.push({ index, sourceIndex: previousIndex });\n continue;\n }\n\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n } else {\n toFetch.push({\n index,\n nodeId: existing.node_id,\n concreteKind: existing.concrete_kind,\n validatedProps,\n isSoftDeleted: existing.deleted_at !== undefined,\n });\n }\n }\n\n type Result = Readonly<{ node: Node; action: GetOrCreateAction }>;\n const results: Result[] = Array.from({ length: items.length });\n\n // Step 4: Execute creates\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const createdNodes = await executeNodeCreateBatch(\n ctx,\n createInputs,\n backend,\n );\n for (const [batchIndex, entry] of toCreate.entries()) {\n results[entry.index] = {\n node: createdNodes[batchIndex]!,\n action: \"created\",\n };\n }\n }\n\n // Step 5: Handle existing nodes (fetch/update/resurrect)\n for (const entry of toFetch) {\n const { index, concreteKind, validatedProps, isSoftDeleted, nodeId } =\n entry;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n concreteKind,\n nodeId,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n );\n results[index] = { node, action: \"created\" };\n continue;\n }\n\n if (isSoftDeleted || ifExists === \"update\") {\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n results[index] = {\n node,\n action: isSoftDeleted ? \"resurrected\" : \"updated\",\n };\n } else {\n results[index] = { node: rowToNode(existingRow), action: \"found\" };\n }\n }\n\n // Step 6: Resolve within-batch duplicates by copying the first occurrence's result\n for (const { index, sourceIndex } of duplicateOf) {\n const sourceResult = results[sourceIndex]!;\n results[index] = { node: sourceResult.node, action: \"found\" };\n }\n\n return results;\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 { compileTemporalFilter } from \"../query/compiler/temporal\";\nimport { getDialect } from \"../query/dialect\";\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: getDialect(backend.dialect).currentTimestamp(),\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","/**\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 assertRecordedCaptureTransactionIsolation,\n createHistoryUnsafeSqlRef,\n createRecordedBackend,\n createRecordedTransactionScope,\n readRecordedClock,\n recordedCaptureRequiresCallbackTransactionError,\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 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} from \"./types\";\n\ntype StoreSchemaMetadata = Readonly<{\n schemaVersion: number | undefined;\n schemaHash: string | undefined;\n}>;\n\nconst UNKNOWN_SCHEMA_METADATA: StoreSchemaMetadata = Object.freeze({\n schemaVersion: undefined,\n schemaHash: undefined,\n});\n\ntype CaughtUpVerb =\n | \"evolve\"\n | \"materialize\"\n | \"deprecate\"\n | \"undeprecate\"\n | \"remove\"\n | \"reembed\";\n\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\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 #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 // 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 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 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 * 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 if (!Object.hasOwn(this.#graph.nodes, kind)) return undefined;\n return this.nodes[\n kind as keyof G[\"nodes\"] & string\n ] as unknown as DynamicNodeCollection;\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 const ctx = this.#createNodeOperationContext();\n return {\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n rowToNode: (row) => rowToNode(row),\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 const ctx = this.#createEdgeOperationContext();\n return {\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n rowToEdge: (row) => rowToEdge(row),\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 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 });\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 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 }`, `tx.sql` is\n * replaced by a fail-loud guard because raw SQL would bypass\n * recorded-time capture; 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 * **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 // 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 `options` is equally meaningless here.\n if (!this.#backend.capabilities.transactions) {\n return invoke({\n nodes: this.nodes,\n edges: this.edges,\n backend: this.#backend,\n });\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 return this.#backend.transaction(\n async (txBackend, sql) =>\n invoke(this.#buildTransactionContext(txBackend, sql)),\n options,\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 * 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 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 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 ): TransactionContext<G> {\n const txNodeOperations: NodeOperations = {\n ...this.#nodeOperations,\n createQuery: () => this.#createQueryForBackend(txBackend),\n };\n const txEdgeOperations: EdgeOperations = {\n ...this.#edgeOperations,\n createQuery: () => this.#createQueryForBackend(txBackend),\n };\n\n const nodes = createNodeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txNodeOperations,\n );\n\n const edges = createEdgeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txEdgeOperations,\n );\n\n if (sql === undefined) return { nodes, edges, backend: txBackend };\n const exposedSql = this.#captureEnabled ? createHistoryUnsafeSqlRef() : sql;\n return { nodes, edges, sql: exposedSql, backend: txBackend };\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 await target.clearGraph(this.graphId);\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 #createNodeOperationContext(): NodeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n historyEnabled: this.#captureEnabled,\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => this.#withOperationHooks(ctx, fn),\n };\n }\n\n #createEdgeOperationContext(): EdgeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => this.#withOperationHooks(ctx, fn),\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?.(\n ctx,\n error instanceof Error ? error : new Error(String(error)),\n );\n throw error;\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"]}