@nicia-ai/typegraph 0.32.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -0
- package/dist/backend/postgres/index.cjs +36 -19
- package/dist/backend/postgres/index.d.cts +6 -6
- package/dist/backend/postgres/index.d.ts +6 -6
- package/dist/backend/postgres/index.js +14 -9
- package/dist/backend/postgres/pglite.cjs +18 -13
- package/dist/backend/postgres/pglite.cjs.map +1 -1
- package/dist/backend/postgres/pglite.d.cts +3 -3
- package/dist/backend/postgres/pglite.d.ts +3 -3
- package/dist/backend/postgres/pglite.js +14 -9
- package/dist/backend/postgres/pglite.js.map +1 -1
- package/dist/backend/sqlite/index.cjs +34 -17
- package/dist/backend/sqlite/index.d.cts +7 -7
- package/dist/backend/sqlite/index.d.ts +7 -7
- package/dist/backend/sqlite/index.js +13 -8
- package/dist/backend/sqlite/libsql.cjs +19 -14
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +12 -5
- package/dist/backend/sqlite/libsql.d.ts +12 -5
- package/dist/backend/sqlite/libsql.js +15 -10
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +19 -14
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.d.cts +3 -3
- package/dist/backend/sqlite/local.d.ts +3 -3
- package/dist/backend/sqlite/local.js +14 -9
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/chunk-2EBMPJBO.js +16 -0
- package/dist/chunk-2EBMPJBO.js.map +1 -0
- package/dist/{chunk-CFNT3ITG.cjs → chunk-2JXB3NYJ.cjs} +15 -35
- package/dist/chunk-2JXB3NYJ.cjs.map +1 -0
- package/dist/chunk-2MRAX3UE.js +105 -0
- package/dist/chunk-2MRAX3UE.js.map +1 -0
- package/dist/{chunk-2LAT5BIK.cjs → chunk-3BRVBQQD.cjs} +2328 -3131
- package/dist/chunk-3BRVBQQD.cjs.map +1 -0
- package/dist/chunk-3E7SNSIA.cjs +55 -0
- package/dist/chunk-3E7SNSIA.cjs.map +1 -0
- package/dist/{chunk-FDN43KXV.cjs → chunk-3Z6TW3CT.cjs} +20 -19
- package/dist/chunk-3Z6TW3CT.cjs.map +1 -0
- package/dist/{chunk-IJORSAC3.js → chunk-4DIBPQNJ.js} +6 -4
- package/dist/chunk-4DIBPQNJ.js.map +1 -0
- package/dist/chunk-4S2FXGBJ.js +9 -0
- package/dist/chunk-4S2FXGBJ.js.map +1 -0
- package/dist/chunk-5IQIX7LU.cjs +2070 -0
- package/dist/chunk-5IQIX7LU.cjs.map +1 -0
- package/dist/{chunk-CWFPJ3RC.js → chunk-6GNSY7AV.js} +3 -3
- package/dist/{chunk-CWFPJ3RC.js.map → chunk-6GNSY7AV.js.map} +1 -1
- package/dist/{chunk-LAZGHOZW.cjs → chunk-6HVOHZHS.cjs} +184 -117
- package/dist/chunk-6HVOHZHS.cjs.map +1 -0
- package/dist/chunk-6SCVW4AS.js +20 -0
- package/dist/chunk-6SCVW4AS.js.map +1 -0
- package/dist/chunk-A7SZZFAG.js +2010 -0
- package/dist/chunk-A7SZZFAG.js.map +1 -0
- package/dist/chunk-ACSVZPK7.cjs +21 -0
- package/dist/chunk-ACSVZPK7.cjs.map +1 -0
- package/dist/{chunk-MXE2U3EX.js → chunk-BVTWD66D.js} +4 -115
- package/dist/chunk-BVTWD66D.js.map +1 -0
- package/dist/{chunk-W4ZX2GCP.js → chunk-CHXTTSC6.js} +5 -39
- package/dist/chunk-CHXTTSC6.js.map +1 -0
- package/dist/{chunk-XQFAJVYW.js → chunk-CYX2JTDG.js} +124 -5
- package/dist/chunk-CYX2JTDG.js.map +1 -0
- package/dist/{chunk-PRMKPFN5.js → chunk-DEQFL35G.js} +4 -3
- package/dist/chunk-DEQFL35G.js.map +1 -0
- package/dist/chunk-DI74SMXS.cjs +29 -0
- package/dist/chunk-DI74SMXS.cjs.map +1 -0
- package/dist/{chunk-WWVV44DY.cjs → chunk-G6SOJEDI.cjs} +11 -11
- package/dist/{chunk-WWVV44DY.cjs.map → chunk-G6SOJEDI.cjs.map} +1 -1
- package/dist/{chunk-LM2IC4ZJ.cjs → chunk-GQANNXXT.cjs} +15 -14
- package/dist/chunk-GQANNXXT.cjs.map +1 -0
- package/dist/chunk-GZCNZ7QW.js +24 -0
- package/dist/chunk-GZCNZ7QW.js.map +1 -0
- package/dist/{chunk-KTIEB7VH.cjs → chunk-HK5SATYM.cjs} +35 -58
- package/dist/chunk-HK5SATYM.cjs.map +1 -0
- package/dist/chunk-HMFK4BXR.cjs +12 -0
- package/dist/{chunk-6ZR4QC3O.cjs.map → chunk-HMFK4BXR.cjs.map} +1 -1
- package/dist/chunk-ITE4IXAK.js +25 -0
- package/dist/chunk-ITE4IXAK.js.map +1 -0
- package/dist/chunk-JJRCLAUN.cjs +155 -0
- package/dist/chunk-JJRCLAUN.cjs.map +1 -0
- package/dist/{chunk-ZFWNO3GE.cjs → chunk-JQGIPGVL.cjs} +66 -2
- package/dist/chunk-JQGIPGVL.cjs.map +1 -0
- package/dist/{chunk-2BVHPOIG.js → chunk-K2TGS3EN.js} +105 -38
- package/dist/chunk-K2TGS3EN.js.map +1 -0
- package/dist/chunk-K34OPSJK.js +29 -0
- package/dist/chunk-K34OPSJK.js.map +1 -0
- package/dist/{chunk-YW7GHMF4.cjs → chunk-KGC4LY5T.cjs} +18 -17
- package/dist/chunk-KGC4LY5T.cjs.map +1 -0
- package/dist/{chunk-SB65GJNY.cjs → chunk-KNHYNQQ3.cjs} +111 -72
- package/dist/chunk-KNHYNQQ3.cjs.map +1 -0
- package/dist/{chunk-C4C4Q7A6.js → chunk-KUTNI6SI.js} +6 -21
- package/dist/chunk-KUTNI6SI.js.map +1 -0
- package/dist/{chunk-NDM5PXEH.js → chunk-LANHCOXB.js} +44 -11
- package/dist/chunk-LANHCOXB.js.map +1 -0
- package/dist/chunk-N6WTUSBV.cjs +23 -0
- package/dist/chunk-N6WTUSBV.cjs.map +1 -0
- package/dist/{chunk-73KASJGO.cjs → chunk-NAUA4PW5.cjs} +4 -28
- package/dist/chunk-NAUA4PW5.cjs.map +1 -0
- package/dist/chunk-QV245VMN.js +145 -0
- package/dist/chunk-QV245VMN.js.map +1 -0
- package/dist/{chunk-CEF2QOTO.js → chunk-RBV7YCQD.js} +4 -3
- package/dist/chunk-RBV7YCQD.js.map +1 -0
- package/dist/chunk-RHZWOJVA.cjs +109 -0
- package/dist/chunk-RHZWOJVA.cjs.map +1 -0
- package/dist/{chunk-6RMLO5O4.cjs → chunk-RRKQAKD6.cjs} +13 -11
- package/dist/chunk-RRKQAKD6.cjs.map +1 -0
- package/dist/{chunk-TUA3MEJJ.js → chunk-RY2VIWAM.js} +612 -564
- package/dist/chunk-RY2VIWAM.js.map +1 -0
- package/dist/{chunk-PIHXFF73.js → chunk-SHLY4MCM.js} +3 -3
- package/dist/{chunk-PIHXFF73.js.map → chunk-SHLY4MCM.js.map} +1 -1
- package/dist/{chunk-HFBRAOF7.js → chunk-T2DWPQNE.js} +103 -64
- package/dist/chunk-T2DWPQNE.js.map +1 -0
- package/dist/{chunk-WYTUF3QO.js → chunk-T46GR2VY.js} +3 -3
- package/dist/{chunk-WYTUF3QO.js.map → chunk-T46GR2VY.js.map} +1 -1
- package/dist/{chunk-EEYV6UOE.cjs → chunk-T6SPUYLX.cjs} +5 -43
- package/dist/chunk-T6SPUYLX.cjs.map +1 -0
- package/dist/{chunk-3QRBXYT5.cjs → chunk-TGJE22RM.cjs} +6 -6
- package/dist/{chunk-3QRBXYT5.cjs.map → chunk-TGJE22RM.cjs.map} +1 -1
- package/dist/{chunk-YL4F3CMD.cjs → chunk-TOTPVGOG.cjs} +105 -72
- package/dist/chunk-TOTPVGOG.cjs.map +1 -0
- package/dist/{chunk-3HQDMOBK.cjs → chunk-UJLOZYKT.cjs} +680 -636
- package/dist/chunk-UJLOZYKT.cjs.map +1 -0
- package/dist/chunk-UNNPKQUG.cjs +1390 -0
- package/dist/chunk-UNNPKQUG.cjs.map +1 -0
- package/dist/chunk-UR7W5YQK.js +18 -0
- package/dist/chunk-UR7W5YQK.js.map +1 -0
- package/dist/chunk-V3QNTB7Z.js +1351 -0
- package/dist/chunk-V3QNTB7Z.js.map +1 -0
- package/dist/{chunk-XKNAK27R.js → chunk-VCGO4V26.js} +4 -3
- package/dist/chunk-VCGO4V26.js.map +1 -0
- package/dist/{chunk-YQGLVWB2.cjs → chunk-WL2SG7ZV.cjs} +6 -122
- package/dist/chunk-WL2SG7ZV.cjs.map +1 -0
- package/dist/{chunk-WNORITK6.js → chunk-WLRIWYHQ.js} +2041 -2834
- package/dist/chunk-WLRIWYHQ.js.map +1 -0
- package/dist/{chunk-JKRKIEVA.cjs → chunk-WVC2Q2FD.cjs} +128 -6
- package/dist/chunk-WVC2Q2FD.cjs.map +1 -0
- package/dist/chunk-XLUNB2TZ.js +53 -0
- package/dist/chunk-XLUNB2TZ.js.map +1 -0
- package/dist/chunk-XXVEULWX.js +39 -0
- package/dist/chunk-XXVEULWX.js.map +1 -0
- package/dist/chunk-YAZE7QZR.cjs +32 -0
- package/dist/chunk-YAZE7QZR.cjs.map +1 -0
- package/dist/chunk-YC6PWTHY.cjs +44 -0
- package/dist/chunk-YC6PWTHY.cjs.map +1 -0
- package/dist/chunk-Z5HBYM7U.cjs +11 -0
- package/dist/chunk-Z5HBYM7U.cjs.map +1 -0
- package/dist/{chunk-454I6GDF.js → chunk-Z5XBMDXU.js} +63 -3
- package/dist/chunk-Z5XBMDXU.js.map +1 -0
- package/dist/{chunk-CAMMC3E4.cjs → chunk-ZP5WHI4C.cjs} +109 -81
- package/dist/chunk-ZP5WHI4C.cjs.map +1 -0
- package/dist/{chunk-YCV72E6L.js → chunk-ZURTTSCM.js} +4 -25
- package/dist/chunk-ZURTTSCM.js.map +1 -0
- package/dist/{chunk-7WW3WL6E.js → chunk-ZV5N4DBG.js} +49 -21
- package/dist/chunk-ZV5N4DBG.js.map +1 -0
- package/dist/chunk-ZY4GXIVN.cjs +32 -0
- package/dist/chunk-ZY4GXIVN.cjs.map +1 -0
- package/dist/{ddl-C8e8zDAE.d.ts → ddl-BrmPg61z.d.ts} +3 -3
- package/dist/{ddl-CwyG4HoQ.d.cts → ddl-j1-sH6lE.d.cts} +3 -3
- package/dist/{extension-types-D1k0inWU.d.cts → extension-types-YGFJPrzK.d.cts} +1 -1
- package/dist/{extension-types-D1k0inWU.d.ts → extension-types-YGFJPrzK.d.ts} +1 -1
- package/dist/graph-extension/index.cjs +18 -17
- package/dist/graph-extension/index.d.cts +4 -4
- package/dist/graph-extension/index.d.ts +4 -4
- package/dist/graph-extension/index.js +3 -2
- package/dist/graph-merge/index.cjs +295 -146
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +6 -6
- package/dist/graph-merge/index.d.ts +6 -6
- package/dist/graph-merge/index.js +173 -24
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/{index-BEK0VtNB.d.ts → index-DGX6D9j1.d.ts} +2 -2
- package/dist/{index-C8sSTErx.d.cts → index-SEvUHDA6.d.cts} +2 -2
- package/dist/index.cjs +206 -172
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -55
- package/dist/index.d.ts +25 -55
- package/dist/index.js +32 -22
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +28 -25
- package/dist/indexes/index.d.cts +5 -5
- package/dist/indexes/index.d.ts +5 -5
- package/dist/indexes/index.js +10 -7
- package/dist/interchange/index.cjs +25 -16
- package/dist/interchange/index.d.cts +5 -5
- package/dist/interchange/index.d.ts +5 -5
- package/dist/interchange/index.js +12 -3
- package/dist/{manager-8htmuGr-.d.ts → manager-BZUeN_BU.d.ts} +2 -2
- package/dist/{manager-aVgxbGt-.d.cts → manager-ms9cKdc6.d.cts} +2 -2
- package/dist/{materialize-indexes-CAGhqPHQ.d.ts → materialize-indexes-CAkIYFV-.d.ts} +1 -1
- package/dist/{materialize-indexes-DEYkU-wr.d.cts → materialize-indexes-D20xNluI.d.cts} +1 -1
- package/dist/{postgres-Dhom7iiX.d.ts → postgres-BhpxGMC5.d.cts} +2651 -596
- package/dist/{postgres-jgXmD45C.d.cts → postgres-CWHLwNl1.d.ts} +2651 -596
- package/dist/profiler/index.cjs +5 -4
- package/dist/profiler/index.cjs.map +1 -1
- package/dist/profiler/index.d.cts +7 -7
- package/dist/profiler/index.d.ts +7 -7
- package/dist/profiler/index.js +3 -2
- package/dist/profiler/index.js.map +1 -1
- package/dist/provenance/index.cjs +591 -0
- package/dist/provenance/index.cjs.map +1 -0
- package/dist/provenance/index.d.cts +73 -0
- package/dist/provenance/index.d.ts +73 -0
- package/dist/provenance/index.js +589 -0
- package/dist/provenance/index.js.map +1 -0
- package/dist/schema/index.cjs +37 -32
- package/dist/schema/index.cjs.map +1 -1
- package/dist/schema/index.d.cts +7 -7
- package/dist/schema/index.d.ts +7 -7
- package/dist/schema/index.js +14 -9
- package/dist/schema/index.js.map +1 -1
- package/dist/{sqlite-DcQ_BCUW.d.cts → sqlite-CGu5SLsw.d.ts} +2726 -455
- package/dist/{sqlite-BfLsCEqO.d.ts → sqlite-XrDxNaa7.d.cts} +2726 -455
- package/dist/{store-view-pBOUrQte.d.ts → store-view-BlgnhEYf.d.ts} +467 -131
- package/dist/{store-view-lTcb_cnp.d.cts → store-view-D09po4H6.d.cts} +467 -131
- package/dist/{types-DGDiXAYc.d.ts → types-B1TbZJYS.d.ts} +2 -2
- package/dist/{types-Dk8r09KY.d.ts → types-D1Sqeyxy.d.ts} +161 -26
- package/dist/{types-5RQwzWXx.d.cts → types-DiE1AO7p.d.cts} +2 -2
- package/dist/{types-Dvmn-eal.d.cts → types-DkNnF-7K.d.cts} +161 -26
- package/dist/{where-Cx_glEEB.d.cts → where-DKjuofPr.d.cts} +2 -2
- package/dist/{where-CHZFELX0.d.ts → where-DrUIIWHb.d.ts} +2 -2
- package/package.json +8 -2
- package/dist/chunk-2BVHPOIG.js.map +0 -1
- package/dist/chunk-2LAT5BIK.cjs.map +0 -1
- package/dist/chunk-2YMGNYXY.js +0 -40
- package/dist/chunk-2YMGNYXY.js.map +0 -1
- package/dist/chunk-3HQDMOBK.cjs.map +0 -1
- package/dist/chunk-454I6GDF.js.map +0 -1
- package/dist/chunk-6G35I3VW.cjs +0 -40
- package/dist/chunk-6G35I3VW.cjs.map +0 -1
- package/dist/chunk-6RMLO5O4.cjs.map +0 -1
- package/dist/chunk-6ZR4QC3O.cjs +0 -12
- package/dist/chunk-73KASJGO.cjs.map +0 -1
- package/dist/chunk-7WW3WL6E.js.map +0 -1
- package/dist/chunk-C4C4Q7A6.js.map +0 -1
- package/dist/chunk-CAMMC3E4.cjs.map +0 -1
- package/dist/chunk-CEF2QOTO.js.map +0 -1
- package/dist/chunk-CFNT3ITG.cjs.map +0 -1
- package/dist/chunk-EEYV6UOE.cjs.map +0 -1
- package/dist/chunk-FDN43KXV.cjs.map +0 -1
- package/dist/chunk-HFBRAOF7.js.map +0 -1
- package/dist/chunk-IJORSAC3.js.map +0 -1
- package/dist/chunk-JKRKIEVA.cjs.map +0 -1
- package/dist/chunk-KTIEB7VH.cjs.map +0 -1
- package/dist/chunk-LAZGHOZW.cjs.map +0 -1
- package/dist/chunk-LM2IC4ZJ.cjs.map +0 -1
- package/dist/chunk-M6OC455F.js +0 -65
- package/dist/chunk-M6OC455F.js.map +0 -1
- package/dist/chunk-MXE2U3EX.js.map +0 -1
- package/dist/chunk-NDM5PXEH.js.map +0 -1
- package/dist/chunk-PRMKPFN5.js.map +0 -1
- package/dist/chunk-RP7YITHX.cjs +0 -70
- package/dist/chunk-RP7YITHX.cjs.map +0 -1
- package/dist/chunk-SAJSMR2B.js +0 -35
- package/dist/chunk-SAJSMR2B.js.map +0 -1
- package/dist/chunk-SB65GJNY.cjs.map +0 -1
- package/dist/chunk-TUA3MEJJ.js.map +0 -1
- package/dist/chunk-W4ZX2GCP.js.map +0 -1
- package/dist/chunk-WNORITK6.js.map +0 -1
- package/dist/chunk-XKNAK27R.js.map +0 -1
- package/dist/chunk-XQFAJVYW.js.map +0 -1
- package/dist/chunk-YCV72E6L.js.map +0 -1
- package/dist/chunk-YL4F3CMD.cjs.map +0 -1
- package/dist/chunk-YQGLVWB2.cjs.map +0 -1
- package/dist/chunk-YW7GHMF4.cjs.map +0 -1
- package/dist/chunk-ZFWNO3GE.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/temporal.ts","../src/store/collections/temporal-read-params.ts","../src/store/types.ts","../src/store/store-view.ts","../src/query/subquery-utils.ts","../src/query/predicates.ts","../src/query/compiler/schema.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/predicates.ts","../src/query/compiler/predicate-utils.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/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/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/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/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/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/store.ts"],"names":["target","field","expr","quoteIdentifier","sql","qualifier","normalizeValueType","literal","pattern","left","opSql","arrayField","predicate","hasVariableLengthTraversal","compileKindFilter","compileRecursiveBranch","nullToUndefined","compileQuery","collectRequiredColumnsByAlias","compileSetOperation","having","RESERVED_NODE_KEYS","RESERVED_EDGE_KEYS","jsonPointer","value","rawRows","outputName","aliasObject","NOT_COMPUTED","max","min","coordinate","entry","rank","rowToEdge","executeEdgeCreate","executeEdgeCreateNoReturnBatch","executeEdgeCreateBatch","executeEdgeUpdate","executeEdgeUpsertUpdate","executeEdgeDelete","executeEdgeHardDelete","results","rows","rowToNode","executeNodeCreate","executeNodeCreateNoReturnBatch","executeNodeCreateBatch","executeNodeUpdate","executeNodeUpsertUpdate","executeNodeDelete","executeNodeHardDelete","result","materializeOne","count","exists","edge"],"mappings":";;;;;;;;;;;;;;;;;;AAwCO,SAAS,qBAAA,CACd,IAAA,EACA,IAAA,EACA,UAAA,EACgB;AAChB,EAAA,IAAI,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,MAAA,EAAW;AACzC,IAAA,M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OAAA,CAAQ,sBAAsB,OAAO,CAAA;AAC7C;AAwCA,eAAsB,qBAAA,CACpB,KAAA,EACA,OAAA,EACA,OAAA,EAC6C;AAO7C,EAAA,MAAM;AAAA,IACJ,KAAA,EAAO,MAAA;AAAA,IACP,SAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAM,kCAAA,CAAmC,OAAA,EAAS,KAAK,CAAA;AAE3D,EAAA,MAAM,MAAA,GAAS,MAAM,YAAA,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;AA2CA,eAAsB,mBAAA,CACpB,KAAA,EACA,OAAA,EACA,OAAA,EAC6C;AAC7C,EAAA,MAAM;AAAA,IACJ,KAAA,EAAO,MAAA;AAAA,IACP,SAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAM,kBAAA,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-WNORITK6.js","sourcesContent":["/**\n * Shared temporal coordinate + validation.\n */\nimport { ValidationError } from \"../errors\";\nimport { validateCanonicalIsoDate } from \"../utils/date\";\nimport { type TemporalMode } from \"./types\";\n\n/**\n * The single opaque temporal coordinate every pinned read is resolved\n * against. Today it carries only the valid-time axis; Unit 2 adds a sibling\n * `recorded` axis here, and because every surface injects the coordinate\n * through one helper ({@link withCoordinate}), a new axis lands on all\n * surfaces at once instead of splitting by surface.\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 // Unit 2 (recorded / system time): recorded?: Readonly<{ asOf?: string }>;\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 * 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 return asOf === undefined ? `mode \"${mode}\"` : `mode \"${mode}\" asOf ${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 { temporalMode: mode, ...(asOf !== undefined && { asOf }) };\n}\n","/**\n * Shared temporal read-parameter resolution for collection reads.\n */\nimport {\n type ReadCoordinate,\n resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport { nowIso } from \"../../utils/date\";\nimport { type QueryOptions } from \"../types\";\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): QueryOptions {\n const { mode, asOf } = coordinate.valid;\n return asOf === undefined ?\n { temporalMode: mode }\n : { temporalMode: mode, 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: Readonly<{ temporalMode?: TemporalMode; asOf?: string }> | undefined,\n defaultTemporalMode: TemporalMode,\n): TemporalReadParams {\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 { ...base, asOf: asOf ?? nowIso() };\n }\n return base;\n}\n","/**\n * Store types for TypeGraph operations.\n */\nimport { type z } from \"zod\";\n\nimport {\n type AdoptedTransaction,\n type EdgeRow,\n type NodeRow,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport {\n type AnyEdgeType,\n type EdgeId,\n type EdgeRegistration,\n type EdgeType,\n type KindEntity,\n type NodeId,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"../core/types\";\nimport type { TraversalExpansion } from \"../query/ast\";\nimport type { BatchableQuery, NodeAccessor } from \"../query/builder/types\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport type { Predicate } from \"../query/predicates\";\n\n// ============================================================\n// Row-to-Meta Field Mapping\n// ============================================================\n\n/**\n * Canonical mapping from snake_case row fields to camelCase meta fields.\n *\n * This is the single source of truth for which row columns become metadata.\n * Both the Meta types and the row-to-meta functions in row-mappers.ts must\n * stay in sync with this mapping. If you add a temporal/audit column to a\n * row type, add the mapping here — the compiler will then force you to\n * update the row mapper functions as well (since their return type is\n * NodeMeta/EdgeMeta, which is derived from this mapping).\n */\ntype TemporalMetaFieldMap = Readonly<{\n valid_from: \"validFrom\";\n valid_to: \"validTo\";\n created_at: \"createdAt\";\n updated_at: \"updatedAt\";\n deleted_at: \"deletedAt\";\n}>;\n\n/**\n * Maps row fields to their camelCase meta counterparts, preserving types.\n */\ntype MapRowToMeta<\n R extends Readonly<Record<string, unknown>>,\n M extends Readonly<Record<string, string>>,\n> = Readonly<{\n [SnakeKey in keyof M as M[SnakeKey] & string]: SnakeKey extends keyof R ?\n R[SnakeKey]\n : never;\n}>;\n\n// ============================================================\n// Node Instance Types\n// ============================================================\n\n/**\n * Metadata for a node instance.\n * Derived from NodeRow via TemporalMetaFieldMap + version.\n *\n * Adding a new metadata column requires:\n * 1. Add the column to NodeRow in backend/types.ts\n * 2. Add the mapping to TemporalMetaFieldMap above\n * 3. The compiler will error in rowToNodeMeta() until you add the field there\n */\nexport type NodeMeta = MapRowToMeta<NodeRow, TemporalMetaFieldMap> &\n Readonly<{ version: NodeRow[\"version\"] }>;\n\n/**\n * A node instance in the graph.\n *\n * Properties from the schema are spread at the top level for ergonomic access:\n * - `node.name` instead of `node.props.name`\n * - System metadata is under `node.meta.*`\n */\nexport type Node<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id: NodeId<N>;\n meta: NodeMeta;\n}> &\n Readonly<z.infer<N[\"schema\"]>>;\n\n/**\n * Input for creating a node.\n */\nexport type CreateNodeInput<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id?: string; // Optional - will generate ULID if not provided\n props: z.infer<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Input for updating a node.\n */\nexport type UpdateNodeInput<N extends NodeType = NodeType> = Readonly<{\n kind: N[\"kind\"];\n id: NodeId<N>;\n props: Partial<z.infer<N[\"schema\"]>>;\n validTo?: string;\n}>;\n\n// ============================================================\n// Edge Instance Types\n// ============================================================\n\n/**\n * Metadata for an edge instance.\n * Derived from EdgeRow via TemporalMetaFieldMap (edges have no version).\n */\nexport type EdgeMeta = MapRowToMeta<EdgeRow, TemporalMetaFieldMap>;\n\n/**\n * An edge instance in the graph.\n *\n * Properties from the schema are spread at the top level for ergonomic access:\n * - `edge.role` instead of `edge.props.role`\n * - System metadata is under `edge.meta.*`\n */\nexport type Edge<\n E extends AnyEdgeType = EdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n id: EdgeId<E>;\n kind: E[\"kind\"];\n fromKind: From[\"kind\"];\n fromId: NodeId<From>;\n toKind: To[\"kind\"];\n toId: NodeId<To>;\n meta: EdgeMeta;\n}> &\n Readonly<z.infer<E[\"schema\"]>>;\n\n/**\n * Input for creating an edge.\n */\nexport type CreateEdgeInput<E extends AnyEdgeType = EdgeType> = Readonly<{\n kind: E[\"kind\"];\n id?: string; // Optional - will generate ULID if not provided\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: z.infer<E[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Input for updating an edge.\n */\nexport type UpdateEdgeInput<E extends AnyEdgeType = EdgeType> = Readonly<{\n id: EdgeId<E>;\n props: Partial<z.infer<E[\"schema\"]>>;\n validTo?: string;\n}>;\n\n// ============================================================\n// Query Options\n// ============================================================\n\n/**\n * Options for node and edge queries.\n */\nexport type QueryOptions = Readonly<{\n /** Temporal mode for the query */\n temporalMode?: TemporalMode;\n /** Specific timestamp for asOf queries */\n asOf?: string;\n}>;\n\n// ============================================================\n// Observability Hooks\n// ============================================================\n\n/**\n * Context passed to observability hooks.\n */\nexport type HookContext = Readonly<{\n /** Unique ID for this operation */\n operationId: string;\n /** Graph ID */\n graphId: string;\n /** Timestamp when operation started */\n startedAt: Date;\n}>;\n\n/**\n * Query hook context with SQL information.\n */\nexport type QueryHookContext = HookContext &\n Readonly<{\n /** The SQL query being executed */\n sql: string;\n /** Query parameters */\n params: readonly unknown[];\n }>;\n\n/**\n * Operation hook context for CRUD operations.\n */\nexport type OperationHookContext = HookContext &\n Readonly<{\n /** Operation type */\n operation: \"create\" | \"update\" | \"delete\";\n /** Entity type */\n entity: KindEntity;\n /** Kind of node or edge */\n kind: string;\n /** Entity ID */\n id: string;\n }>;\n\n/**\n * Observability hooks for monitoring store operations.\n *\n * Note: Batch operations (`bulkCreate`, `bulkInsert`, `bulkUpsertById`) skip\n * per-item operation hooks for throughput. Query hooks still fire normally.\n *\n * @example\n * ```typescript\n * const hooks: StoreHooks = {\n * onQueryStart: (ctx) => {\n * console.log(`[${ctx.operationId}] Query: ${ctx.sql}`);\n * },\n * onQueryEnd: (ctx, result) => {\n * const duration = Date.now() - ctx.startedAt.getTime();\n * console.log(`[${ctx.operationId}] Completed in ${duration}ms`);\n * },\n * onError: (ctx, error) => {\n * console.error(`[${ctx.operationId}] Error:`, error);\n * },\n * };\n *\n * const store = createStore(graph, backend, { hooks });\n * ```\n */\nexport type StoreHooks = Readonly<{\n /** Called before a query is executed */\n onQueryStart?: (ctx: QueryHookContext) => void;\n /** Called after a query completes successfully */\n onQueryEnd?: (\n ctx: QueryHookContext,\n result: Readonly<{ rowCount: number; durationMs: number }>,\n ) => void;\n /** Called before a CRUD operation starts */\n onOperationStart?: (ctx: OperationHookContext) => void;\n /** Called after a CRUD operation completes */\n onOperationEnd?: (\n ctx: OperationHookContext,\n result: Readonly<{ durationMs: number }>,\n ) => void;\n /** Called when an error occurs */\n onError?: (ctx: HookContext, error: Error) => void;\n}>;\n\n// ============================================================\n// Store Configuration\n// ============================================================\n\n/**\n * Options for creating a store.\n */\nexport type StoreOptions = Readonly<{\n /** Observability hooks for monitoring */\n hooks?: StoreHooks;\n /** SQL schema configuration for custom table names */\n schema?: SqlSchema;\n /** Query default behaviors. */\n queryDefaults?: Readonly<{\n /** Default traversal ontology expansion mode (default: \"inverse\"). */\n traversalExpansion?: TraversalExpansion;\n }>;\n}>;\n\n/**\n * A mutable handle to the current `Store`, used by `store.evolve(...)`\n * so long-lived consumers can dereference through the ref and pick up\n * the new store after each evolve call. `current` is overwritten by\n * `evolve()` atomically with the schema commit when the ref is passed\n * via `evolve(extension, { ref })`.\n *\n * **Mid-request semantics.** `ref.current` flips on the *next* call\n * after evolve, not mid-handler. Dereference once at request entry and\n * reuse the captured `Store` for the duration:\n *\n * ```ts\n * async function handleRequest(): Promise<void> {\n * const store = ref.current; // capture once\n * const tag = await store.nodes.Tag?.create({ label: \"...\" });\n * // ...further work on the same `store`...\n * }\n * ```\n *\n * Pure dereferenceable handle — no event/subscription machinery. If\n * consumers need eventing, they wrap the ref themselves.\n *\n * Generic over the held value (typically `Store<G>`) so the store\n * module can refer to it without importing the `Store` class into\n * `types.ts`.\n */\nexport interface StoreRef<T> {\n current: T;\n}\n\n// ============================================================\n// Get-Or-Create Types\n// ============================================================\n\n/**\n * Behavior when a get-or-create operation matches an existing record.\n */\nexport type IfExistsMode = \"return\" | \"update\";\n\n/**\n * Action taken by a get-or-create operation.\n */\nexport type GetOrCreateAction = \"created\" | \"found\" | \"updated\" | \"resurrected\";\n\n/**\n * Result of a node getOrCreateByConstraint operation.\n */\nexport type NodeGetOrCreateByConstraintResult<N extends NodeType> = Readonly<{\n node: Node<N>;\n action: GetOrCreateAction;\n}>;\n\n/**\n * Options for node getOrCreateByConstraint operations.\n */\nexport type NodeGetOrCreateByConstraintOptions = Readonly<{\n /** Existing record behavior. Default: \"return\" */\n ifExists?: IfExistsMode;\n}>;\n\n/**\n * Options for node bulkFindByIndex operations.\n */\nexport type NodeBulkFindByIndexOptions = Readonly<{\n /**\n * Maximum number of candidate nodes returned per input item. When omitted,\n * each input's candidate set is unbounded. Must be a positive integer.\n *\n * Candidates are ordered deterministically by node id, so the cap is stable\n * across calls. Use this to bound fan-out on low-selectivity index keys.\n */\n limitPerInput?: number;\n}>;\n\n/**\n * Result of an edge getOrCreateByEndpoints operation.\n */\nexport type EdgeGetOrCreateByEndpointsResult<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n edge: Edge<E, From, To>;\n action: GetOrCreateAction;\n}>;\n\n/**\n * Options for edge findByEndpoints operations.\n */\nexport type EdgeFindByEndpointsOptions<E extends AnyEdgeType> = Readonly<{\n /**\n * Edge property fields to include in the match alongside the (from, to) endpoints.\n * When omitted, matches on endpoints only (returns the first edge at the read coordinate).\n */\n matchOn?: readonly (keyof z.input<E[\"schema\"]>)[];\n /** Property values to match against when matchOn is specified. */\n props?: Partial<z.input<E[\"schema\"]>>;\n}>;\n\n/**\n * Options for edge getOrCreateByEndpoints operations.\n */\nexport type EdgeGetOrCreateByEndpointsOptions<E extends AnyEdgeType> =\n Readonly<{\n /**\n * Edge property fields to include in the match key alongside the (from, to) endpoints.\n * Default: `[]` — match on endpoints only.\n */\n matchOn?: readonly (keyof z.input<E[\"schema\"]>)[];\n /** Existing record behavior. Default: \"return\" */\n ifExists?: IfExistsMode;\n }>;\n\n// ============================================================\n// Collection Interfaces\n// ============================================================\n\n/**\n * A collection of nodes of a specific type.\n *\n * Provides ergonomic CRUD operations for a single node type.\n */\nexport type NodeCollection<\n N extends NodeType,\n CN extends string = string,\n> = Readonly<{\n /** Create a new node */\n create: (\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /** Get a node by ID */\n getById: (\n id: NodeId<N>,\n options?: QueryOptions,\n ) => Promise<Node<N> | undefined>;\n\n /** Get multiple nodes by ID, preserving input order (undefined for missing) */\n getByIds: (\n ids: readonly NodeId<N>[],\n options?: QueryOptions,\n ) => Promise<readonly (Node<N> | undefined)[]>;\n\n /** Update a node */\n update: (\n id: NodeId<N>,\n props: Partial<z.input<N[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /** Delete a node (soft delete - sets deletedAt timestamp) */\n delete: (id: NodeId<N>) => Promise<void>;\n\n /**\n * Permanently delete a node from the database.\n *\n * Unlike `delete()` which performs a soft delete, this permanently\n * removes the node and its associated data (uniqueness entries, embeddings).\n *\n * **Warning:** This operation is irreversible and should be used carefully.\n * Consider using soft delete (`delete()`) for most use cases.\n *\n * @throws Error if edges are still connected to this node (delete edges first)\n */\n hardDelete: (id: NodeId<N>) => Promise<void>;\n\n /**\n * Find nodes matching criteria.\n *\n * Supports predicate filtering via the `where` option for SQL-level filtering.\n * For simple queries. Use store.query() for complex traversals.\n */\n find: (\n filter?: Readonly<{\n where?: (accessor: NodeAccessor<N>) => Predicate;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ) => Promise<Node<N>[]>;\n\n /** Count nodes matching criteria */\n count: (temporal?: QueryOptions) => Promise<number>;\n\n /**\n * Create a node from untyped data, relying on runtime Zod validation.\n *\n * Use this for dynamic dispatch (changesets, migrations, imports) where\n * the data shape is determined at runtime, not compile time.\n * The return type is fully typed — only the input gate is relaxed.\n */\n createFromRecord: (\n data: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Create or update a node.\n *\n * If a node with the given ID exists, updates it with the provided props.\n * Otherwise, creates a new node with that ID.\n */\n upsertById: (\n id: string,\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Upsert a node from untyped data, relying on runtime Zod validation.\n *\n * Use this for dynamic dispatch (changesets, migrations, imports) where\n * the data shape is determined at runtime, not compile time.\n * The return type is fully typed — only the input gate is relaxed.\n */\n upsertByIdFromRecord: (\n id: string,\n data: Record<string, unknown>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ) => Promise<Node<N>>;\n\n /**\n * Create multiple nodes in a batch.\n *\n * More efficient than calling create() multiple times.\n * Use `bulkInsert` for the dedicated fast path that skips returning results.\n */\n bulkCreate: (\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Node<N>[]>;\n\n /**\n * Create or update multiple nodes in a batch.\n *\n * For each item, if a node with the given ID exists, updates it.\n * Otherwise, creates a new node with that ID.\n */\n bulkUpsertById: (\n items: readonly Readonly<{\n id: string;\n props: z.input<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Node<N>[]>;\n\n /**\n * Insert multiple nodes without returning results.\n *\n * This is the dedicated fast path for bulk inserts. Unlike `bulkCreate`\n * with `returnResults: false`, the intent is unambiguous: no results\n * are returned and the operation is wrapped in a transaction.\n */\n bulkInsert: (\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<void>;\n\n /**\n * Delete multiple nodes by ID.\n *\n * Atomic when the backend supports transactions. Silently ignores IDs\n * that don't exist.\n */\n bulkDelete: (ids: readonly NodeId<N>[]) => Promise<void>;\n\n /**\n * Find a node by uniqueness constraint.\n *\n * Looks up a live node by the named constraint key computed from `props`.\n * Returns the node if found, or undefined. Soft-deleted nodes are excluded.\n *\n * @param constraintName - Name of the uniqueness constraint to match on\n * @param props - Properties to compute the constraint key from\n */\n findByConstraint: (\n constraintName: CN,\n props: z.input<N[\"schema\"]>,\n ) => Promise<Node<N> | undefined>;\n\n /**\n * Batch version of findByConstraint.\n *\n * Results are returned in the same order as the input items.\n * Returns undefined for entries that don't match.\n */\n bulkFindByConstraint: (\n constraintName: CN,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n ) => Promise<(Node<N> | undefined)[]>;\n\n /**\n * Batched candidate retrieval against a declared node index.\n *\n * For each input item, TypeGraph computes the index lookup key from\n * `index.fields` (JSON-pointer extraction, partial-`where` applied to\n * stored rows, null-safe matching) and returns the live, non-soft-deleted\n * nodes that share that key. Unlike {@link bulkFindByConstraint}, the index\n * may be non-unique, so each input yields a (possibly empty) array.\n *\n * Results preserve input order; each inner array is ordered by node id.\n * Empty input returns `[]`. An unknown index name throws\n * `NodeIndexNotFoundError`; a type-incompatible indexed field throws\n * `ValidationError`. This is candidate retrieval, not a uniqueness or\n * identity guarantee.\n *\n * @param indexName - Name of the declared node index to match on\n * @param items - Records whose `props` supply the indexed-field values\n * @param options - Optional `limitPerInput` to bound per-input fan-out\n */\n bulkFindByIndex: (\n indexName: string,\n items: readonly Readonly<{\n props: Partial<z.input<N[\"schema\"]>>;\n }>[],\n options?: NodeBulkFindByIndexOptions,\n ) => Promise<readonly Node<N>[][]>;\n\n /**\n * Get an existing node by uniqueness constraint, or create a new one.\n *\n * Looks up a node by the named constraint key computed from `props`.\n * If found, returns it (optionally updating with `ifExists: \"update\"`).\n * If not found, creates a new node. Soft-deleted matches are always resurrected.\n *\n * @param constraintName - Name of the uniqueness constraint to match on\n * @param props - Full properties for create, or merge source for update\n * @param options - Existing record behavior (default: \"return\")\n */\n getOrCreateByConstraint: (\n constraintName: CN,\n props: z.input<N[\"schema\"]>,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<NodeGetOrCreateByConstraintResult<N>>;\n\n /**\n * Batch version of getOrCreateByConstraint.\n *\n * Results are returned in the same order as the input items.\n * Atomic when the backend supports transactions.\n */\n bulkGetOrCreateByConstraint: (\n constraintName: CN,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<NodeGetOrCreateByConstraintResult<N>[]>;\n}>;\n\n/**\n * Reference to a node of a specific kind.\n *\n * Accepts either:\n * - A Node instance of the correct kind\n * - An explicit { kind, id } object with the correct kind name\n *\n * This provides compile-time checking that edge endpoints match the\n * allowed node kinds defined in the edge registration.\n */\nexport type NodeRef<N extends NodeType = NodeType> =\n | Node<N>\n | Readonly<{ kind: N[\"kind\"]; id: string }>;\n\n/**\n * Options for creating an edge.\n */\ntype EdgeCreateOptions = Readonly<{\n id?: string;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Arguments for edge creation, with props optional when schema allows empty object.\n *\n * Uses `{}` to check if an empty object literal satisfies the schema input type.\n */\n/* eslint-disable @typescript-eslint/no-empty-object-type -- {} is intentional: checking if empty object satisfies schema */\ntype EdgeCreateArguments<E extends AnyEdgeType> =\n {} extends z.input<E[\"schema\"]> ?\n [props?: z.input<E[\"schema\"]>, options?: EdgeCreateOptions]\n : [props: z.input<E[\"schema\"]>, options?: EdgeCreateOptions];\n/* eslint-enable @typescript-eslint/no-empty-object-type */\n\n/**\n * A collection of edges of a specific type.\n *\n * Provides ergonomic CRUD operations for a single edge type.\n * The From and To type parameters enforce that edge endpoints\n * match the allowed node types at compile time.\n *\n * @example\n * ```typescript\n * // Create an edge - pass Node objects directly\n * const edge = await store.edges.worksAt.create(alice, acme, { role: \"Engineer\" });\n *\n * // TypeScript error: Company is not a valid 'from' type for worksAt\n * // store.edges.worksAt.create(acme, alice, { role: \"Engineer\" });\n *\n * // For edges with empty schemas, props is optional\n * await store.edges.wrote.create(author, book);\n *\n * // Find edges from a node\n * const edges = await store.edges.worksAt.findFrom(alice);\n * ```\n */\nexport type EdgeCollection<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n /**\n * Create a new edge.\n *\n * @param from - Source node (must be one of the allowed 'from' types)\n * @param to - Target node (must be one of the allowed 'to' types)\n * @param args - Edge properties (optional if schema is empty) and creation options\n */\n create: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n ...args: EdgeCreateArguments<E>\n ) => Promise<Edge<E, From, To>>;\n\n /** Get an edge by ID */\n getById: (\n id: EdgeId<E>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To> | undefined>;\n\n /** Get multiple edges by ID, preserving input order (undefined for missing) */\n getByIds: (\n ids: readonly EdgeId<E>[],\n options?: QueryOptions,\n ) => Promise<readonly (Edge<E, From, To> | undefined)[]>;\n\n /** Update an edge's properties */\n update: (\n id: EdgeId<E>,\n props: Partial<z.input<E[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ) => Promise<Edge<E, From, To>>;\n\n /**\n * Find edges from a specific node.\n *\n * Honors the same temporal model as `getById` / `find`: with no\n * `options`, the graph's default `temporalMode` applies (excluding\n * soft-deleted edges and, in `current` / `asOf` modes, edges outside\n * their validity window). Pass `temporalMode` / `asOf` to read the\n * endpoint's edges at another temporal coordinate.\n */\n findFrom: (\n from: NodeRef<From>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Find edges to a specific node.\n *\n * Temporal semantics mirror {@link EdgeCollection.findFrom}.\n */\n findTo: (\n to: NodeRef<To>,\n options?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Deferred variant of `findFrom` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` instead of executing immediately. Accepts\n * the same temporal `options` as {@link EdgeCollection.findFrom}.\n */\n batchFindFrom: (\n from: NodeRef<From>,\n options?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /**\n * Deferred variant of `findTo` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` instead of executing immediately. Accepts\n * the same temporal `options` as {@link EdgeCollection.findTo}.\n */\n batchFindTo: (\n to: NodeRef<To>,\n options?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /**\n * Deferred variant of `findByEndpoints` for use with `store.batch()`.\n *\n * Returns a `BatchableQuery` that yields a 0-or-1 element array\n * (matching `findByEndpoints`' at-most-one semantics).\n */\n batchFindByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ) => BatchableQuery<Edge<E, From, To>>;\n\n /** Delete an edge (soft delete - sets deletedAt timestamp) */\n delete: (id: EdgeId<E>) => Promise<void>;\n\n /**\n * Permanently delete an edge from the database.\n *\n * Unlike `delete()` which performs a soft delete, this permanently\n * removes the edge record.\n *\n * **Warning:** This operation is irreversible and should be used carefully.\n * Consider using soft delete (`delete()`) for most use cases.\n */\n hardDelete: (id: EdgeId<E>) => Promise<void>;\n\n /** Find edges matching endpoint and pagination criteria */\n find: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ) => Promise<Edge<E, From, To>[]>;\n\n /** Count edges matching criteria */\n count: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n }>,\n temporal?: QueryOptions,\n ) => Promise<number>;\n\n /**\n * Create multiple edges in a batch.\n *\n * More efficient than calling create() multiple times.\n * Use `bulkInsert` for the dedicated fast path that skips returning results.\n */\n bulkCreate: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Create or update multiple edges in a batch.\n *\n * For each item, if an edge with the given ID exists, updates it.\n * Otherwise, creates a new edge with that ID.\n */\n bulkUpsertById: (\n items: readonly Readonly<{\n id: EdgeId<E>;\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<Edge<E, From, To>[]>;\n\n /**\n * Insert multiple edges without returning results.\n *\n * This is the dedicated fast path for bulk inserts. Unlike `bulkCreate`\n * with `returnResults: false`, the intent is unambiguous: no results\n * are returned and the operation is wrapped in a transaction.\n */\n bulkInsert: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ) => Promise<void>;\n\n /**\n * Delete multiple edges by ID.\n *\n * Atomic when the backend supports transactions. Silently ignores IDs\n * that don't exist.\n */\n bulkDelete: (ids: readonly EdgeId<E>[]) => Promise<void>;\n\n /**\n * Find an edge by endpoints and optional property fields.\n *\n * Returns the first matching edge at the read coordinate, or undefined.\n * Honors the temporal model like `findFrom` / `findTo`: by default\n * (`current` mode) soft-deleted and out-of-window edges are excluded; under\n * `includeTombstones` a soft-deleted edge can be returned.\n *\n * @param from - Source node\n * @param to - Target node\n * @param options - Match criteria (matchOn fields and property values)\n * @param temporal - Temporal coordinate. With no `temporal`, the graph's\n * default `temporalMode` applies (so under the default `\"current\"` mode,\n * edges outside their validity window are excluded). Pass\n * `temporalMode` / `asOf` to read the edge as of another coordinate.\n */\n findByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ) => Promise<Edge<E, From, To> | undefined>;\n\n /**\n * Get an existing edge by endpoints and optional property fields, or create a new one.\n *\n * Matches edges of this kind between `(from, to)`. When `matchOn` specifies\n * property fields, only edges whose properties match on those fields are considered.\n * Soft-deleted matches are resurrected when cardinality allows.\n *\n * @param from - Source node\n * @param to - Target node\n * @param props - Full properties for create, or merge source for update\n * @param options - Match criteria and conflict resolution\n */\n getOrCreateByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n props: z.input<E[\"schema\"]>,\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ) => Promise<EdgeGetOrCreateByEndpointsResult<E, From, To>>;\n\n /**\n * Batch version of getOrCreateByEndpoints.\n *\n * Results are returned in the same order as the input items.\n * Atomic when the backend supports transactions.\n */\n bulkGetOrCreateByEndpoints: (\n items: readonly Readonly<{\n from: NodeRef<From>;\n to: NodeRef<To>;\n props: z.input<E[\"schema\"]>;\n }>[],\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ) => Promise<EdgeGetOrCreateByEndpointsResult<E, From, To>[]>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract uniqueness constraint names from a NodeRegistration.\n *\n * - Returns `never` when no uniqueness constraints are configured.\n * - Returns a literal union when names are inferred via `defineGraph` const params.\n * - Falls back to `string` when names are widened/dynamic.\n */\nexport type ConstraintNames<R extends NodeRegistration> =\n \"unique\" extends keyof R ?\n R[\"unique\"] extends readonly { readonly name: infer N }[] ?\n N & string\n : string\n : never;\n\n/**\n * Extract the union of 'from' node types from an EdgeRegistration.\n */\ntype EdgeFromTypes<R extends EdgeRegistration> =\n R[\"from\"] extends readonly (infer N)[] ? N : never;\n\n/**\n * Extract the union of 'to' node types from an EdgeRegistration.\n */\ntype EdgeToTypes<R extends EdgeRegistration> =\n R[\"to\"] extends readonly (infer N)[] ? N : never;\n\n/**\n * Create a type-safe EdgeCollection from an EdgeRegistration.\n * Extracts the edge type and from/to node types automatically.\n */\nexport type TypedEdgeCollection<R extends EdgeRegistration> = EdgeCollection<\n R[\"type\"],\n EdgeFromTypes<R> extends NodeType ? EdgeFromTypes<R> : NodeType,\n EdgeToTypes<R> extends NodeType ? EdgeToTypes<R> : NodeType\n>;\n\n// ============================================================\n// Transaction Types\n// ============================================================\n\n// ============================================================\n// Graph Collection Maps\n// ============================================================\n\n/** Mapped type of all node collections for a graph. */\nexport type GraphNodeCollections<G extends GraphDef> = {\n [K in keyof G[\"nodes\"] & string]-?: NodeCollection<\n G[\"nodes\"][K][\"type\"],\n ConstraintNames<G[\"nodes\"][K]>\n >;\n};\n\n/** Mapped type of all edge collections for a graph. */\nexport type GraphEdgeCollections<G extends GraphDef> = {\n [K in keyof G[\"edges\"] & string]-?: TypedEdgeCollection<G[\"edges\"][K]>;\n};\n\n// ============================================================\n// StoreView read-only collection surfaces\n// ============================================================\n\n// ------------------------------------------------------------\n// Collection read / write split\n// ------------------------------------------------------------\n//\n// The live NodeCollection / EdgeCollection partition into buckets a\n// StoreView treats differently:\n//\n// - temporal reads — honor the pinned coordinate (the view pins them, with\n// the per-call temporal argument dropped);\n// - current reads — have no temporal axis, so the view delegates them on a\n// `current` pin and refuses them on a temporal pin (they would otherwise\n// silently return current data);\n// - writes — never available on a read-only view; and\n// - batch reads — deferred reads for `store.batch()`, absent from a view\n// (no batch context).\n//\n// `Pick` validates every key against the live collection, and a `test-d`\n// conformance check asserts the buckets exactly partition it — so a new\n// method cannot be silently omitted from the view's surface decision, and a\n// new temporal read auto-appears (pinned) in the derived view type.\n\n/** Temporal-aware node reads — a {@link StoreView} pins these. */\nexport type NodeTemporalReads<\n N extends NodeType,\n CN extends string = string,\n> = Pick<NodeCollection<N, CN>, \"getById\" | \"getByIds\" | \"find\" | \"count\">;\n\n/**\n * The method names of the current-state-only node reads (constraint / index\n * lookups). Single source of truth: {@link NodeCurrentReads} (the type) and the\n * `StoreView`'s runtime routing Set are both derived from this array, so adding\n * a current-only read here updates both at once — a new read cannot pass the\n * type partition yet be misrouted at runtime (refused as a write).\n */\nexport const CURRENT_ONLY_READ_NAMES = [\n \"findByConstraint\",\n \"bulkFindByConstraint\",\n \"bulkFindByIndex\",\n] as const;\n\n/**\n * Current-state-only node reads (constraint / index lookups). No temporal\n * axis, so a {@link StoreView} delegates them on a `current` pin and refuses\n * them on a temporal pin.\n */\nexport type NodeCurrentReads<\n N extends NodeType,\n CN extends string = string,\n> = Pick<NodeCollection<N, CN>, (typeof CURRENT_ONLY_READ_NAMES)[number]>;\n\n/** Node writes — never available on a read-only {@link StoreView}. */\nexport type NodeWrites<N extends NodeType, CN extends string = string> = Pick<\n NodeCollection<N, CN>,\n | \"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>;\n\n/**\n * Temporal-aware edge reads — a {@link StoreView} pins these. Unlike the node\n * collection, edges have no current-state-only reads: `findByEndpoints` honors\n * the temporal coordinate like `findFrom` / `findTo`, so every edge read is\n * pinnable.\n */\nexport type EdgeTemporalReads<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<\n EdgeCollection<E, From, To>,\n | \"getById\"\n | \"getByIds\"\n | \"find\"\n | \"count\"\n | \"findFrom\"\n | \"findTo\"\n | \"findByEndpoints\"\n>;\n\n/**\n * Deferred edge reads for `store.batch()` — absent from a {@link StoreView},\n * which has no batch context.\n */\nexport type EdgeBatchReads<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<\n EdgeCollection<E, From, To>,\n \"batchFindFrom\" | \"batchFindTo\" | \"batchFindByEndpoints\"\n>;\n\n/** Edge writes — never available on a read-only {@link StoreView}. */\nexport type EdgeWrites<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Pick<\n EdgeCollection<E, From, To>,\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"hardDelete\"\n | \"bulkCreate\"\n | \"bulkUpsertById\"\n | \"bulkInsert\"\n | \"bulkDelete\"\n | \"getOrCreateByEndpoints\"\n | \"bulkGetOrCreateByEndpoints\"\n>;\n\n/**\n * The read-only node surface a {@link StoreView} exposes for one node kind.\n * The temporal reads drop the per-call temporal argument — the pin owns the\n * axis; the current reads ({@link NodeCurrentReads}) are exposed as-is\n * (delegated on a `current` view, refused on a temporal pin). Writes live on\n * the live `Store`. The conformance test asserts the temporal part equals the\n * pinned form of {@link NodeTemporalReads}.\n */\nexport type StoreViewNodeCollection<\n N extends NodeType,\n CN extends string = string,\n> = Readonly<{\n /** Get a node by ID at the view's pinned coordinate. */\n getById: (id: NodeId<N>) => Promise<Node<N> | undefined>;\n\n /** Get multiple nodes by ID, preserving input order (undefined for missing). */\n getByIds: (\n ids: readonly NodeId<N>[],\n ) => Promise<readonly (Node<N> | undefined)[]>;\n\n /** Find nodes matching criteria at the view's pinned coordinate. */\n find: (\n filter?: Readonly<{\n where?: (accessor: NodeAccessor<N>) => Predicate;\n limit?: number;\n offset?: number;\n }>,\n ) => Promise<Node<N>[]>;\n\n /** Count nodes at the view's pinned coordinate. */\n count: () => Promise<number>;\n}> &\n NodeCurrentReads<N, CN>;\n\n/**\n * The read-only edge surface a {@link StoreView} exposes for one edge\n * kind, mirroring {@link StoreViewNodeCollection}. Every edge read —\n * including `findByEndpoints` — honors the pin via the same temporal model,\n * so (unlike nodes) there are no current-state-only edge reads.\n */\nexport type StoreViewEdgeCollection<\n E extends AnyEdgeType,\n From extends NodeType = NodeType,\n To extends NodeType = NodeType,\n> = Readonly<{\n /** Get an edge by ID at the view's pinned coordinate. */\n getById: (id: EdgeId<E>) => Promise<Edge<E, From, To> | undefined>;\n\n /** Get multiple edges by ID, preserving input order (undefined for missing). */\n getByIds: (\n ids: readonly EdgeId<E>[],\n ) => Promise<readonly (Edge<E, From, To> | undefined)[]>;\n\n /** Find edges matching endpoint and pagination criteria. */\n find: (\n filter?: Readonly<{\n from?: NodeRef<From>;\n to?: NodeRef<To>;\n limit?: number;\n offset?: number;\n }>,\n ) => Promise<Edge<E, From, To>[]>;\n\n /** Count edges matching criteria at the view's pinned coordinate. */\n count: (\n filter?: Readonly<{ from?: NodeRef<From>; to?: NodeRef<To> }>,\n ) => Promise<number>;\n\n /** Find edges from a specific node at the view's pinned coordinate. */\n findFrom: (from: NodeRef<From>) => Promise<Edge<E, From, To>[]>;\n\n /** Find edges to a specific node at the view's pinned coordinate. */\n findTo: (to: NodeRef<To>) => Promise<Edge<E, From, To>[]>;\n\n /** Find the edge between two endpoints at the view's pinned coordinate. */\n findByEndpoints: (\n from: NodeRef<From>,\n to: NodeRef<To>,\n options?: EdgeFindByEndpointsOptions<E>,\n ) => Promise<Edge<E, From, To> | undefined>;\n}>;\n\n/**\n * Read-only view edge collection derived from an `EdgeRegistration`,\n * extracting the edge type and from/to node types — the read-only\n * counterpart of {@link TypedEdgeCollection}.\n */\nexport type TypedStoreViewEdgeCollection<R extends EdgeRegistration> =\n StoreViewEdgeCollection<\n R[\"type\"],\n EdgeFromTypes<R> extends NodeType ? EdgeFromTypes<R> : NodeType,\n EdgeToTypes<R> extends NodeType ? EdgeToTypes<R> : NodeType\n >;\n\n/** Mapped type of all read-only view node collections for a graph. */\nexport type StoreViewNodeCollections<G extends GraphDef> = {\n [K in keyof G[\"nodes\"] & string]-?: StoreViewNodeCollection<\n G[\"nodes\"][K][\"type\"]\n >;\n};\n\n/** Mapped type of all read-only view edge collections for a graph. */\nexport type StoreViewEdgeCollections<G extends GraphDef> = {\n [K in keyof G[\"edges\"] & string]-?: TypedStoreViewEdgeCollection<\n G[\"edges\"][K]\n >;\n};\n\n// ============================================================\n// Transaction Context\n// ============================================================\n\n/**\n * A typed transaction context with collection API.\n *\n * Provides the same `tx.nodes.*` and `tx.edges.*` API as the Store,\n * but operations are executed within the transaction scope.\n *\n * `tx.sql` is the raw Drizzle handle **bound to this same\n * transaction** — use it to write the caller's own relational tables\n * inside the graph-owned transaction so both layers commit or roll\n * back together (the graph-owned counterpart of\n * {@link Store.withTransaction}, where the caller owns the boundary):\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await tx.nodes.Document.update(documentId, props);\n * // `tx.sql` is the `AdoptedTransaction` union — cast to your\n * // concrete Drizzle database type at the call site.\n * const sqlTx = tx.sql as NodePgDatabase;\n * await sqlTx.insert(documentVersions).values(versionRow);\n * await sqlTx.insert(changeEvents).values(eventRow);\n * });\n * ```\n *\n * Per-backend semantics:\n * - **Postgres / libsql** (async drivers): `tx.sql` is the Drizzle\n * transaction handle. Using the outer `db` instead would write on a\n * *different* connection and silently escape the transaction — so\n * `tx.sql` is a correctness requirement there.\n * - **better-sqlite3**: the single connection, framed by TypeGraph's\n * `BEGIN`/`COMMIT`/`ROLLBACK`.\n * - **Durable Objects (`do-sqlite`)**: the bound Drizzle handle; the\n * storage transaction is ambient, so writing the outer `db` also\n * enlists — `tx.sql` is the explicit, portable form.\n *\n * It is `undefined` only on the non-transactional fallback\n * (`backend.capabilities.transactions === false` — e.g. Cloudflare\n * D1, `drizzle-orm/neon-http`), where `store.transaction()` runs the\n * callback with no atomicity and there is no transaction to enlist.\n * Its type is the `AdoptedTransaction` union; cast to your concrete\n * Drizzle database type at the call site.\n *\n * @example\n * ```typescript\n * await store.transaction(async (tx) => {\n * const person = await tx.nodes.Person.create({ name: \"Alice\" });\n * const company = await tx.nodes.Company.create({ name: \"Acme\" });\n * await tx.edges.worksAt.create(person, company, { role: \"Engineer\" });\n * });\n * ```\n */\nexport type TransactionContext<G extends GraphDef> = Readonly<{\n nodes: GraphNodeCollections<G>;\n edges: GraphEdgeCollections<G>;\n sql?: AdoptedTransaction;\n /**\n * The transaction-scoped backend the collections are bound to, for advanced\n * raw reads that must observe the transaction's snapshot (e.g. graph-merge's\n * in-transaction base@V re-validation). On the non-transactional fallback it\n * is the store's plain backend — reads work, but there is no snapshot.\n */\n backend: TransactionBackend;\n}>;\n\n// ============================================================\n// Dynamic Collection Types (widened for runtime dispatch)\n// ============================================================\n\n/**\n * Replace branded `NodeId` / `EdgeId` with plain `string` in each\n * method's parameter list. Return types are preserved unchanged.\n *\n * Handles three shapes:\n * 1. Direct branded ID parameter → `string`\n * 2. `readonly NodeId[]` / `readonly EdgeId[]` → `readonly string[]`\n * 3. Branded IDs nested one level inside bulk-item object arrays\n */\ntype WidenBrandedIds<T> = {\n readonly [K in keyof T]: T[K] extends (...args: infer A) => infer R ?\n (...args: { [P in keyof A]: UnbrandParam<A[P]> }) => R\n : T[K];\n};\n\n/** Replace a branded ID with `string`, recursing one level into arrays. */\ntype UnbrandParam<T> =\n T extends NodeId<NodeType> ? string\n : T extends EdgeId<AnyEdgeType> ? string\n : T extends readonly NodeId<NodeType>[] ? readonly string[]\n : T extends readonly EdgeId<AnyEdgeType>[] ? readonly string[]\n : T extends readonly (infer Item extends Record<string, unknown>)[] ?\n readonly UnbrandRecord<Item>[]\n : T;\n\n/** Replace branded ID values in object properties (does not recurse into nested structures). */\ntype UnbrandRecord<T extends Record<string, unknown>> = {\n readonly [K in keyof T]: T[K] extends NodeId<NodeType> ? string\n : T[K] extends EdgeId<AnyEdgeType> ? string\n : T[K];\n};\n\n/**\n * A node collection with widened generics for runtime string-keyed access.\n *\n * This is the return type of `store.getNodeCollection(kind)`. It exposes\n * the full `NodeCollection` API but with `NodeType` and `string` constraint\n * names instead of the specific generic parameters, since the concrete type\n * is not known at compile time.\n *\n * ID parameters accept plain `string` instead of branded `NodeId<N>`, since\n * the dynamic path typically receives IDs from edge metadata, snapshots,\n * or external input where the brand is not available.\n */\nexport type DynamicNodeCollection = WidenBrandedIds<\n NodeCollection<NodeType, string>\n>;\n\n/**\n * An edge collection with widened generics for runtime string-keyed access.\n *\n * This is the return type of `store.getEdgeCollection(kind)`. It exposes\n * the full `EdgeCollection` API but with `NodeType` endpoint types, since\n * the concrete from/to types are not known at compile time.\n *\n * ID parameters accept plain `string` instead of branded `EdgeId<E>`, since\n * the dynamic path typically receives IDs from edge metadata, snapshots,\n * or external input where the brand is not available.\n */\nexport type DynamicEdgeCollection = WidenBrandedIds<\n EdgeCollection<AnyEdgeType, NodeType, NodeType>\n>;\n\n// ============================================================\n// Store Projection\n// ============================================================\n\n/**\n * A type-level projection of a store's surface onto a subset of its\n * node and edge collections.\n *\n * Node collections are projected with constraint names erased (`never`),\n * so constraint-based methods like `findByConstraint` become uncallable.\n * This is intentional: unique constraints are graph-registration-level\n * details that differ between graphs sharing the same node types.\n *\n * @example\n * ```typescript\n * type CoreStore = StoreProjection<\n * typeof myGraph,\n * \"Document\" | \"Chunk\",\n * \"hasChunk\"\n * >;\n *\n * async function ingestChunk(\n * store: CoreStore,\n * document: Node<typeof Document>,\n * text: string,\n * ) {\n * const chunk = await store.nodes.Chunk.create({ text });\n * await store.edges.hasChunk.create(document, chunk);\n * return chunk;\n * }\n * ```\n *\n * Both `Store<G>` and `TransactionContext<G>` are structurally assignable\n * to a `StoreProjection` whose keys are a subset of `G`.\n */\nexport type StoreProjection<\n G extends GraphDef,\n N extends keyof G[\"nodes\"] & string = never,\n E extends keyof G[\"edges\"] & string = never,\n> = Readonly<{\n nodes: { [K in N]-?: NodeCollection<G[\"nodes\"][K][\"type\"], never> };\n edges: Pick<GraphEdgeCollections<G>, E>;\n}>;\n","/**\n * 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 resolveReadCoordinate,\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 QueryBuilder } from \"../query/builder\";\nimport {\n type BaseTraversalOptions,\n type DegreeOptions,\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 { withCoordinate } from \"./collections/temporal-read-params\";\nimport { type StoreSearch } from \"./search-facade\";\nimport { type Store } from \"./store\";\nimport {\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\n CURRENT_ONLY_READ_NAMES,\n type EdgeCollection,\n type NodeCollection,\n type NodeCurrentReads,\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<SubgraphOptions<G, EK, NK, P>, \"temporalMode\" | \"asOf\">;\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\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 * 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 * Wraps a `reads` object so its supported reads pass through while any\n * other method that exists on the live collection refuses. Writes refuse\n * synchronously ({@link createReadOnlyRefusal}); current-state-only reads\n * refuse via Promise rejection on a temporal pin but are delegated to the\n * live collection on a `current` view ({@link CURRENT_ONLY_READS}).\n *\n * The supported set is exactly `reads`' own keys, so it can never drift\n * from the methods actually implemented. The target is frozen and the\n * `set` / `defineProperty` / `deleteProperty` traps reject, so the view is\n * read-only by construction at runtime, not only at the type level.\n * `Object.hasOwn` — not `in` — so inherited `Object.prototype` members\n * (`toString`, `valueOf`, …) pass straight through and coercion / logging\n * of a view collection still works.\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 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 if (CURRENT_ONLY_READS.has(property)) {\n return isCurrent ?\n (live as Record<string, unknown>)[property]\n : createCurrentOnlyRefusal(entity, property, coordinate);\n }\n return createReadOnlyRefusal(entity, property, coordinate);\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\nfunction pinnedNodeCollection(\n live: NodeCollection<NodeType, string>,\n coordinate: ReadCoordinate,\n): StoreViewNodeCollection<NodeType> {\n const temporal = withCoordinate(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 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 = withCoordinate(coordinate);\n const reads: StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> = {\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 `nodes` and `edges`: indexing the live proxy\n * throws `KindNotFoundError` for an unknown kind, so the view refuses an\n * unknown kind the same way the live store does — while interop probes\n * ({@link NON_KIND_KEYS}) resolve to `undefined`.\n */\nfunction pinnedCollections<L, W>(\n live: object,\n coordinate: ReadCoordinate,\n wrap: (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) {\n if (typeof kind !== \"string\" || NON_KIND_KEYS.has(kind)) return;\n const cached = cache.get(kind);\n if (cached !== undefined) return cached;\n const wrapped = wrap((live as Record<string, L>)[kind]!, coordinate);\n cache.set(kind, wrapped);\n return wrapped;\n },\n },\n );\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\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<\n string,\n (...args: readonly unknown[]) => unknown\n >)\n : undefined;\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 if (live !== undefined && READ_SEARCH_METHODS.has(method)) {\n return (...args: readonly unknown[]) => live[method]!(...args);\n }\n return () => Promise.reject(searchRefusal(method, coordinate, isCurrent));\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> {\n readonly #store: Store<G>;\n readonly #coordinate: ReadCoordinate;\n #nodes: StoreViewNodeCollections<G> | undefined;\n #edges: StoreViewEdgeCollections<G> | undefined;\n #search: StoreSearch<G> | undefined;\n\n constructor(store: Store<G>, coordinate: StoreViewCoordinate) {\n this.#store = store;\n this.#coordinate = 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 /** The temporal mode this view reads in. */\n get mode(): TemporalMode {\n return this.#coordinate.valid.mode;\n }\n\n /** The pinned `asOf` timestamp, or `undefined` for non-`asOf` modes. */\n get asOf(): string | undefined {\n return this.#coordinate.valid.asOf;\n }\n\n /** Read-only node collections pinned to this view's coordinate. */\n get nodes(): StoreViewNodeCollections<G> {\n this.#nodes ??= pinnedCollections(\n this.#store.nodes,\n this.#coordinate,\n pinnedNodeCollection,\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 ??= pinnedCollections(\n this.#store.edges,\n this.#coordinate,\n pinnedEdgeCollection,\n ) as unknown as StoreViewEdgeCollections<G>;\n return this.#edges;\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(): QueryBuilder<G> {\n return this.#store.sealedQuery(this.#coordinate);\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 return this.#store.subgraph(rootId, {\n ...options,\n ...withCoordinate(this.#coordinate),\n });\n }\n\n /** Shortest path between two nodes at this view's pinned coordinate. */\n shortestPath(\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewShortestPathOptions<G>,\n ): Promise<ShortestPathResult | undefined> {\n return this.#store.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.#store.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.#store.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.#store.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.#store.algorithms.degree(node, {\n ...options,\n ...withCoordinate(this.#coordinate),\n });\n }\n\n /**\n * Read-only search facade. On a `current` view the read methods\n * (`fulltext` / `vector` / `hybrid`) delegate to the live `store.search`,\n * while the mutating `rebuildFulltext` is refused — the view is read-only.\n * On any non-`current` pin every search method refuses: the fulltext /\n * vector index reflects current state only, so historical relevance is\n * out of scope.\n */\n get search(): StoreSearch<G> {\n this.#search ??= pinnedSearch<G>(this.#store, this.#coordinate);\n return this.#search;\n }\n}\n","/**\n * Shared utilities for subquery projection shape and type handling.\n */\nimport { type AggregateExpr, type QueryAst, type ValueType } from \"./ast\";\n\n/**\n * Normalizes a value type by treating \"unknown\" as undefined.\n */\nfunction normalizeValueType(valueType?: ValueType): ValueType | undefined {\n if (valueType === undefined || valueType === \"unknown\") {\n return undefined;\n }\n return valueType;\n}\n\n/**\n * Returns true when the type cannot be compared with IN/NOT IN.\n */\nexport function isUnsupportedInSubqueryValueType(\n valueType?: ValueType,\n): boolean {\n const normalized = normalizeValueType(valueType);\n return (\n normalized === \"array\" ||\n normalized === \"object\" ||\n normalized === \"embedding\"\n );\n}\n\n/**\n * Returns true when two value types are compatible for IN/NOT IN.\n *\n * Unknown types are treated as compatible (deferred to runtime) to preserve\n * flexibility for untyped fields.\n */\nexport function isInSubqueryTypeCompatible(\n left?: ValueType,\n right?: ValueType,\n): boolean {\n const normalizedLeft = normalizeValueType(left);\n const normalizedRight = normalizeValueType(right);\n\n if (normalizedLeft === undefined || normalizedRight === undefined) {\n return true;\n }\n\n return normalizedLeft === normalizedRight;\n}\n\n/**\n * Resolves the value type produced by an aggregate projection.\n */\nfunction getAggregateValueType(\n aggregate: AggregateExpr,\n): ValueType | undefined {\n switch (aggregate.function) {\n case \"count\":\n case \"countDistinct\":\n case \"sum\":\n case \"avg\": {\n return \"number\";\n }\n case \"min\":\n case \"max\": {\n return normalizeValueType(aggregate.field.valueType);\n }\n }\n}\n\n/**\n * Returns effective projected column value types for a subquery.\n *\n * If selective fields are present, they represent the effective projection.\n * Otherwise, falls back to the explicit projection fields.\n */\nfunction getProjectedValueTypes(\n subquery: QueryAst,\n): readonly (ValueType | undefined)[] {\n if (subquery.selectiveFields && subquery.selectiveFields.length > 0) {\n return subquery.selectiveFields.map((field) =>\n normalizeValueType(field.valueType),\n );\n }\n\n return subquery.projection.fields.map((field) => {\n if (field.source.__type === \"aggregate\") {\n return getAggregateValueType(field.source);\n }\n return normalizeValueType(field.source.valueType);\n });\n}\n\n/**\n * Returns the effective number of columns projected by a subquery.\n */\nexport function getSubqueryColumnCount(subquery: QueryAst): number {\n return getProjectedValueTypes(subquery).length;\n}\n\n/**\n * Returns the value type when a subquery projects exactly one column.\n */\nexport function getSingleSubqueryColumnValueType(\n subquery: QueryAst,\n): ValueType | undefined {\n const valueTypes = getProjectedValueTypes(subquery);\n if (valueTypes.length !== 1) {\n return undefined;\n }\n return valueTypes[0];\n}\n","/**\n * Predicate builders for TypeGraph queries.\n *\n * Provides a fluent API for building type-safe predicates.\n */\nimport { type FulltextQueryMode } from \"../backend/types\";\nimport { type NullCheckOp } from \"../core/types\";\nimport { UnsupportedPredicateError } from \"../errors\";\nimport {\n type ArrayOp,\n type ArrayPredicate,\n type BetweenPredicate,\n type ComparisonOp,\n type ComparisonPredicate,\n type ExistsSubquery,\n type FieldRef,\n type FulltextMatchPredicate,\n type InSubquery,\n type LiteralValue,\n type NullPredicate,\n type ObjectOp,\n type ObjectPredicate,\n type ParameterRef,\n type PredicateExpression,\n type QueryAst,\n type StringOp,\n type StringPredicate,\n type ValueType,\n type VectorMetricType,\n type VectorSimilarityPredicate,\n} from \"./ast\";\nimport { resolveFieldTypeInfoAtJsonPointer } from \"./field-type-info\";\nimport {\n joinJsonPointers,\n type JsonPointer,\n jsonPointer,\n type JsonPointerInput,\n type JsonPointerSegment,\n normalizeJsonPointer,\n type ResolveJsonPointer,\n type ResolveJsonPointerSegments,\n} from \"./json-pointer\";\nimport { type FieldTypeInfo } from \"./schema-introspector\";\nimport {\n getSingleSubqueryColumnValueType,\n getSubqueryColumnCount,\n isInSubqueryTypeCompatible,\n isUnsupportedInSubqueryValueType,\n} from \"./subquery-utils\";\n\n// ============================================================\n// Predicate Builder\n// ============================================================\n\n/**\n * A chainable predicate that can be combined with AND/OR.\n */\nexport type Predicate = Readonly<{\n __expr: PredicateExpression;\n and: (other: Predicate) => Predicate;\n or: (other: Predicate) => Predicate;\n not: () => Predicate;\n}>;\n\n/**\n * Creates a predicate wrapper with chainable methods.\n */\nfunction predicate(expr: PredicateExpression): Predicate {\n return {\n __expr: expr,\n and: (other: Predicate): Predicate =>\n predicate({\n __type: \"and\",\n predicates: [expr, other.__expr],\n }),\n or: (other: Predicate): Predicate =>\n predicate({\n __type: \"or\",\n predicates: [expr, other.__expr],\n }),\n not: (): Predicate =>\n predicate({\n __type: \"not\",\n predicate: expr,\n }),\n };\n}\n\n// ============================================================\n// Parameter References\n// ============================================================\n\n/**\n * Creates a named parameter reference for prepared queries.\n *\n * Use with `query.prepare()` to create reusable parameterized queries.\n * Only supported in scalar comparison positions (eq, neq, gt, etc.),\n * string operations, and between bounds. Not supported in `in()`/`notIn()`.\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 * const results = await prepared.execute({ name: \"Alice\" });\n * ```\n */\n// eslint-disable-next-line unicorn/prevent-abbreviations -- concise public API\nexport function param(name: string): ParameterRef {\n return { __type: \"parameter\", name };\n}\n\n/**\n * Type guard for ParameterRef values.\n */\nexport function isParameterRef(value: unknown): value is ParameterRef {\n if (typeof value !== \"object\" || value === null) return false;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard for untyped input\n return (value as ParameterRef).__type === \"parameter\";\n}\n\n// ============================================================\n// Field Builder\n// ============================================================\n\n/**\n * A typed field builder for creating predicates.\n */\ntype FieldBuilder<T> =\n [T] extends [string] ? StringFieldBuilder\n : [T] extends [number] ? NumberFieldBuilder\n : [T] extends [boolean] ? BooleanFieldBuilder\n : [T] extends [Date] ? DateFieldBuilder\n : [T] extends [readonly (infer U)[]] ? ArrayFieldBuilder<U>\n : [T] extends [Record<string, unknown>] ? ObjectFieldBuilder<T>\n : BaseFieldBuilder;\n\n/**\n * Base field operations available on all types.\n */\ntype BaseFieldBuilder = Readonly<{\n eq: (value: unknown) => Predicate;\n neq: (value: unknown) => Predicate;\n isNull: () => Predicate;\n isNotNull: () => Predicate;\n in: (values: readonly unknown[]) => Predicate;\n notIn: (values: readonly unknown[]) => Predicate;\n}>;\n\n/**\n * Options for the `$fulltext.matches()` predicate.\n *\n * Note the term glossary used throughout TypeGraph search:\n * - **`k`** (the positional argument on `.matches(query, k)`) is the\n * per-predicate top-k cap applied inside the fulltext CTE.\n * - **`limit`** (on store-level `search.fulltext` / `search.hybrid` and\n * on the query builder) is the final result count returned to the\n * caller after any fusion.\n */\ntype MatchesOptions = Readonly<{\n /**\n * Parse mode for the query string. Default: \"websearch\".\n *\n * - \"websearch\": Google-style syntax (quoted phrases, `-excluded`, `OR`).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\n mode?: FulltextQueryMode;\n /**\n * Language override. Default: per-row language as stored at insert time.\n */\n language?: string;\n /** Minimum relevance score to include. */\n minScore?: number;\n}>;\n\n/**\n * String-specific field operations.\n *\n * Fulltext match is exposed on `n.$fulltext.matches(...)` at the node\n * level (gated by `searchable()` declarations in the schema), not on\n * individual string fields.\n */\ntype StringFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: string | ParameterRef) => Predicate;\n gte: (value: string | ParameterRef) => Predicate;\n lt: (value: string | ParameterRef) => Predicate;\n lte: (value: string | ParameterRef) => Predicate;\n contains: (pattern: string | ParameterRef) => Predicate;\n startsWith: (pattern: string | ParameterRef) => Predicate;\n endsWith: (pattern: string | ParameterRef) => Predicate;\n like: (pattern: string | ParameterRef) => Predicate;\n ilike: (pattern: string | ParameterRef) => Predicate;\n }>;\n\n/**\n * Number-specific field operations.\n */\ntype NumberFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: number | ParameterRef) => Predicate;\n gte: (value: number | ParameterRef) => Predicate;\n lt: (value: number | ParameterRef) => Predicate;\n lte: (value: number | ParameterRef) => Predicate;\n between: (\n lower: number | ParameterRef,\n upper: number | ParameterRef,\n ) => Predicate;\n }>;\n\n/**\n * Boolean-specific field operations.\n */\ntype BooleanFieldBuilder = BaseFieldBuilder;\n\n/**\n * Date-specific field operations.\n */\ntype DateFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: Date | string | ParameterRef) => Predicate;\n gte: (value: Date | string | ParameterRef) => Predicate;\n lt: (value: Date | string | ParameterRef) => Predicate;\n lte: (value: Date | string | ParameterRef) => Predicate;\n between: (\n lower: Date | string | ParameterRef,\n upper: Date | string | ParameterRef,\n ) => Predicate;\n }>;\n\ntype ScalarValue = string | number | boolean | Date;\n\ntype ArrayPredicateOps<T> =\n [T] extends [ScalarValue] ?\n Readonly<{\n /** Check if array contains a specific value */\n contains: (value: T) => Predicate;\n /** Check if array contains all specified values */\n containsAll: (values: readonly T[]) => Predicate;\n /** Check if array contains any of the specified values (overlaps) */\n containsAny: (values: readonly T[]) => Predicate;\n }>\n : Readonly<Record<string, never>>;\n\n/**\n * Array-specific field operations.\n */\ntype ArrayFieldBuilder<T = unknown> = BaseFieldBuilder &\n Readonly<{\n /** Check if array is empty */\n isEmpty: () => Predicate;\n /** Check if array is not empty */\n isNotEmpty: () => Predicate;\n /** Check if array length equals a value */\n lengthEq: (length: number) => Predicate;\n /** Check if array length is greater than a value */\n lengthGt: (length: number) => Predicate;\n /** Check if array length is greater than or equal to a value */\n lengthGte: (length: number) => Predicate;\n /** Check if array length is less than a value */\n lengthLt: (length: number) => Predicate;\n /** Check if array length is less than or equal to a value */\n lengthLte: (length: number) => Predicate;\n }> &\n ArrayPredicateOps<T>;\n\n/**\n * Object/JSON-specific field operations.\n */\ntype ResolvedPointerInput<T, Pointer> =\n Pointer extends string ? ResolveJsonPointer<T, Pointer>\n : Pointer extends readonly JsonPointerSegment[] ?\n ResolveJsonPointerSegments<T, Pointer>\n : unknown;\n\n/**\n * Resolves the type of a nested key access on an object type.\n * Returns ObjectFieldBuilder for nested objects, FieldBuilder for scalars.\n */\ntype NestedFieldBuilder<T, K extends keyof T> =\n NonNullable<T[K]> extends Record<string, unknown> ?\n ObjectFieldBuilder<NonNullable<T[K]>>\n : FieldBuilder<T[K]>;\n\ntype ObjectFieldBuilder<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = BaseFieldBuilder &\n Readonly<{\n /** Access a nested field by key for fluent chaining */\n get: <K extends keyof T & string>(key: K) => NestedFieldBuilder<T, K>;\n /** Check if object has a specific key at root level */\n hasKey: (key: string) => Predicate;\n /** Check if object has a nested path (JSON Pointer) */\n hasPath: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Check if value at path equals a value */\n pathEquals: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => Predicate;\n /** Check if value at path (array) contains a value */\n pathContains: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => Predicate;\n /** Check if value at path is null */\n pathIsNull: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Check if value at path is not null */\n pathIsNotNull: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Access a nested field to get a typed field builder */\n field: <P extends JsonPointerInput<T>>(\n pointer: P,\n ) => FieldBuilder<ResolvedPointerInput<T, P>>;\n }>;\n\n/**\n * Options for the similarTo method.\n */\nexport type SimilarToOptions = Readonly<{\n /** Similarity metric to use. Default: \"cosine\" */\n metric?: VectorMetricType;\n /**\n * Minimum similarity score to include results.\n * For cosine: 0-1 where 1 is identical.\n * For L2: maximum distance to include.\n * For inner_product: minimum inner product value.\n */\n minScore?: number;\n}>;\n\n/**\n * Embedding-specific field operations for vector similarity search.\n */\ntype EmbeddingFieldBuilder = BaseFieldBuilder &\n Readonly<{\n /**\n * Find nodes with similar embeddings.\n * Returns results ordered by similarity (most similar first).\n *\n * @param queryEmbedding - The embedding vector to compare against\n * @param k - Maximum number of results to return (top-k)\n * @param options - Optional configuration (metric, minScore)\n *\n * @example\n * ```typescript\n * store.query()\n * .from(\"Document\", \"d\")\n * .whereNode(\"d\", (d) =>\n * d.embedding.similarTo(queryVector, 10, { metric: \"cosine\" })\n * )\n * .select((ctx) => ({ doc: ctx.d }))\n * .execute()\n * ```\n */\n similarTo: (\n queryEmbedding: readonly number[],\n k: number,\n options?: SimilarToOptions,\n ) => Predicate;\n }>;\n\n// ============================================================\n// Field Builder Factory\n// ============================================================\n\n/**\n * Creates a field reference.\n */\ntype FieldRefOptions = Readonly<{\n jsonPointer?: JsonPointer | undefined;\n valueType?: ValueType | undefined;\n elementType?: ValueType | undefined;\n}>;\n\nexport function fieldRef(\n alias: string,\n path: readonly string[],\n options?: FieldRefOptions,\n): FieldRef {\n return {\n __type: \"field_ref\",\n alias,\n path,\n ...(options?.jsonPointer !== undefined && {\n jsonPointer: options.jsonPointer,\n }),\n ...(options?.valueType !== undefined && { valueType: options.valueType }),\n ...(options?.elementType !== undefined && {\n elementType: options.elementType,\n }),\n };\n}\n\nfunction coerceLiteralValue(value: unknown): string | number | boolean | Date {\n if (value instanceof Date) {\n return value;\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n throw new Error(`Unsupported literal value type: ${typeof value}`);\n}\n\nfunction inferLiteralValueType(value: string | number | boolean): ValueType {\n if (typeof value === \"string\") {\n return \"string\";\n }\n if (typeof value === \"number\") {\n return \"number\";\n }\n return \"boolean\";\n}\n\n/**\n * Creates a literal value.\n */\nfunction literal(value: string | number | boolean | Date): LiteralValue {\n if (value instanceof Date) {\n return { __type: \"literal\", value: value.toISOString(), valueType: \"date\" };\n }\n const valueType = inferLiteralValueType(value);\n return {\n __type: \"literal\",\n value,\n valueType,\n };\n}\n\n/**\n * Creates a comparison predicate.\n */\nfunction comparison(\n op: ComparisonOp,\n field: FieldRef,\n value: unknown,\n): Predicate {\n if (isParameterRef(value)) {\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: value,\n };\n return predicate(expr);\n }\n const coercedValue = coerceLiteralValue(value);\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: literal(coercedValue),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an IN comparison predicate.\n */\nfunction inComparison(\n op: \"in\" | \"notIn\",\n field: FieldRef,\n values: readonly unknown[],\n): Predicate {\n const literals = values.map((value) => literal(coerceLiteralValue(value)));\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: literals,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a string operation predicate.\n */\nfunction stringOp(\n op: StringOp,\n field: FieldRef,\n pattern: string | ParameterRef,\n): Predicate {\n if (isParameterRef(pattern)) {\n const expr: StringPredicate = {\n __type: \"string_op\",\n op,\n field,\n pattern,\n };\n return predicate(expr);\n }\n const expr: StringPredicate = {\n __type: \"string_op\",\n op,\n field,\n pattern,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a null check predicate.\n */\nfunction nullCheck(op: NullCheckOp, field: FieldRef): Predicate {\n const expr: NullPredicate = {\n __type: \"null_check\",\n op,\n field,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a between predicate.\n */\nfunction between(\n field: FieldRef,\n lower: string | number | boolean | Date | ParameterRef,\n upper: string | number | boolean | Date | ParameterRef,\n): Predicate {\n const expr: BetweenPredicate = {\n __type: \"between\",\n field,\n lower: isParameterRef(lower) ? lower : literal(lower),\n upper: isParameterRef(upper) ? upper : literal(upper),\n };\n return predicate(expr);\n}\n\n/**\n * Creates a base field builder with common operations.\n */\nfunction baseFieldBuilder(field: FieldRef): BaseFieldBuilder {\n return {\n eq: (value) => comparison(\"eq\", field, value),\n neq: (value) => comparison(\"neq\", field, value),\n isNull: () => nullCheck(\"isNull\", field),\n isNotNull: () => nullCheck(\"isNotNull\", field),\n in: (values) => inComparison(\"in\", field, values),\n notIn: (values) => inComparison(\"notIn\", field, values),\n };\n}\n\n/**\n * Creates a string field builder.\n *\n * Fulltext match is not a string-field operation — use\n * `n.$fulltext.matches(...)` at the node level. `searchable()`\n * declarations determine which node kinds expose `$fulltext`.\n */\nexport function stringField(field: FieldRef): StringFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n contains: (pattern) => stringOp(\"contains\", field, pattern),\n startsWith: (pattern) => stringOp(\"startsWith\", field, pattern),\n endsWith: (pattern) => stringOp(\"endsWith\", field, pattern),\n like: (pattern) => stringOp(\"like\", field, pattern),\n ilike: (pattern) => stringOp(\"ilike\", field, pattern),\n };\n}\n\n/**\n * Default top-k for `$fulltext.matches()` when the caller does not pass\n * one. Large enough to leave headroom for downstream `.and()` filters,\n * small enough to keep latency reasonable on any dialect.\n */\nconst DEFAULT_FULLTEXT_MATCH_K = 50;\n\n/**\n * Node-level fulltext accessor. Always present on the `NodeAccessor`\n * type — a runtime check throws a clear error if the node kind has no\n * `searchable()` fields. `k` is the top-k cap applied inside the\n * fulltext CTE; defaults to `DEFAULT_FULLTEXT_MATCH_K`. Use a larger\n * value when feeding the result into RRF (`.fuseWith()` /\n * `store.search.hybrid()`).\n */\nexport type FulltextAccessor = Readonly<{\n matches: (query: string, k?: number, options?: MatchesOptions) => Predicate;\n}>;\n\n/**\n * Creates a node-level fulltext accessor. The runtime check throws for\n * aliases whose node kind has no `searchable()` content, catching the\n * case where the field tag was dropped (e.g. by a schema refactor)\n * after the query was written.\n */\nexport function createFulltextAccessor(\n alias: string,\n hasSearchableField: () => boolean,\n): FulltextAccessor {\n return {\n matches: (query, k, options) => {\n if (!hasSearchableField()) {\n throw new UnsupportedPredicateError(\n `Cannot call .$fulltext.matches() on alias \"${alias}\" — its ` +\n `node kind has no fields declared with searchable(). Add at ` +\n `least one: \\`title: searchable({ language: \"english\" })\\`.`,\n );\n }\n return fulltextMatch(\n fieldRef(alias, [\"$fulltext\"]),\n query,\n k ?? DEFAULT_FULLTEXT_MATCH_K,\n options,\n );\n },\n };\n}\n\n/**\n * Creates a fulltext match predicate.\n */\nfunction fulltextMatch(\n field: FieldRef,\n query: string,\n limit: number,\n options?: MatchesOptions,\n): Predicate {\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new UnsupportedPredicateError(\n `matches() limit must be a positive finite number, got ${String(limit)}`,\n );\n }\n const expr: FulltextMatchPredicate = {\n __type: \"fulltext_match\",\n field,\n query,\n mode: options?.mode ?? \"websearch\",\n limit,\n ...(options?.language === undefined ? {} : { language: options.language }),\n ...(options?.minScore === undefined ? {} : { minScore: options.minScore }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates a number field builder.\n */\nexport function numberField(field: FieldRef): NumberFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n between: (lower, upper) => between(field, lower, upper),\n };\n}\n\n/**\n * Creates a date field builder.\n */\nexport function dateField(field: FieldRef): DateFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n between: (lower, upper) => between(field, lower, upper),\n };\n}\n\n/**\n * Creates a base field builder (for booleans, enums, and unknown types).\n * Only provides the fundamental operations: eq, neq, isNull, isNotNull, in, notIn.\n */\nexport function baseField(field: FieldRef): BaseFieldBuilder {\n return baseFieldBuilder(field);\n}\n\n/**\n * Creates an array operation predicate.\n */\nfunction arrayOp(\n op: ArrayOp,\n field: FieldRef,\n values?: readonly unknown[],\n length?: number,\n): Predicate {\n const expr: ArrayPredicate = {\n __type: \"array_op\",\n op,\n field,\n ...(values !== undefined && {\n values: values.map((value) => literal(coerceLiteralValue(value))),\n }),\n ...(length !== undefined && { length }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an array field builder.\n */\nexport function arrayField<T = unknown>(field: FieldRef): ArrayFieldBuilder<T> {\n // The type assertion is needed because ArrayFieldBuilder conditionally includes\n // contains/containsAll/containsAny based on whether T extends ScalarValue.\n // At runtime we always provide them - they just won't type-check if T isn't scalar.\n return {\n ...baseFieldBuilder(field),\n contains: (value: T) => arrayOp(\"contains\", field, [value]),\n containsAll: (values: readonly T[]) =>\n arrayOp(\"containsAll\", field, values),\n containsAny: (values: readonly T[]) =>\n arrayOp(\"containsAny\", field, values),\n isEmpty: () => arrayOp(\"isEmpty\", field),\n isNotEmpty: () => arrayOp(\"isNotEmpty\", field),\n lengthEq: (length: number) => arrayOp(\"lengthEq\", field, undefined, length),\n lengthGt: (length: number) => arrayOp(\"lengthGt\", field, undefined, length),\n lengthGte: (length: number) =>\n arrayOp(\"lengthGte\", field, undefined, length),\n lengthLt: (length: number) => arrayOp(\"lengthLt\", field, undefined, length),\n lengthLte: (length: number) =>\n arrayOp(\"lengthLte\", field, undefined, length),\n } as unknown as ArrayFieldBuilder<T>;\n}\n\n/**\n * Creates a vector similarity predicate.\n */\nfunction vectorSimilarity(\n field: FieldRef,\n queryEmbedding: readonly number[],\n limit: number,\n options?: SimilarToOptions,\n): Predicate {\n const expr: VectorSimilarityPredicate = {\n __type: \"vector_similarity\",\n field,\n queryEmbedding,\n // Leave metric unset when the caller didn't specify one, so the compiler\n // resolves the field's declared metric per kind. Defaulting to \"cosine\"\n // here would mis-rank l2/inner_product fields and bypass their ANN index.\n ...(options?.metric !== undefined && { metric: options.metric }),\n limit,\n ...(options?.minScore !== undefined && { minScore: options.minScore }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an embedding field builder for vector similarity search.\n */\nexport function embeddingField(field: FieldRef): EmbeddingFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n similarTo: (queryEmbedding, k, options) =>\n vectorSimilarity(field, queryEmbedding, k, options),\n };\n}\n\nexport function buildFieldBuilderForTypeInfo(\n field: FieldRef,\n typeInfo: FieldTypeInfo | undefined,\n): BaseFieldBuilder {\n if (!typeInfo) {\n return baseField(field);\n }\n\n switch (typeInfo.valueType) {\n case \"string\": {\n return stringField(field);\n }\n case \"number\": {\n return numberField(field);\n }\n case \"boolean\": {\n return baseField(field);\n }\n case \"date\": {\n return dateField(field);\n }\n case \"array\": {\n return arrayField(field);\n }\n case \"object\": {\n return objectField(field, { typeInfo });\n }\n case \"embedding\": {\n return embeddingField(field);\n }\n case \"unknown\": {\n return baseField(field);\n }\n }\n}\n\nfunction resolvePointerTypeInfo(\n typeInfo: FieldTypeInfo | undefined,\n pointer: JsonPointer,\n): FieldTypeInfo | undefined {\n return resolveFieldTypeInfoAtJsonPointer(typeInfo, pointer);\n}\n\n/**\n * Creates an object operation predicate.\n */\ntype ObjectPredicateOptions = Readonly<{\n valueType?: ValueType;\n elementType?: ValueType;\n}>;\n\nfunction objectOp(\n op: ObjectOp,\n field: FieldRef,\n pointer: JsonPointer,\n value?: unknown,\n options?: ObjectPredicateOptions,\n): Predicate {\n const expr: ObjectPredicate = {\n __type: \"object_op\",\n op,\n field,\n pointer,\n ...(value !== undefined && {\n value: literal(coerceLiteralValue(value)),\n }),\n ...(options?.valueType !== undefined && { valueType: options.valueType }),\n ...(options?.elementType !== undefined && {\n elementType: options.elementType,\n }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an object/JSON field builder.\n */\ntype ObjectFieldOptions = Readonly<{\n typeInfo?: FieldTypeInfo;\n}>;\n\nexport function objectField<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(field: FieldRef, options?: ObjectFieldOptions): ObjectFieldBuilder<T> {\n const basePointer = field.jsonPointer;\n\n return {\n ...baseFieldBuilder(field),\n get: <K extends keyof T & string>(key: K) => {\n const pointer = jsonPointer([key]);\n const nestedPointer = joinJsonPointers(basePointer, pointer);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, pointer);\n const nestedRef = fieldRef(field.alias, field.path, {\n jsonPointer: nestedPointer,\n ...(resolved?.valueType !== undefined && {\n valueType: resolved.valueType,\n }),\n ...(resolved?.elementType !== undefined && {\n elementType: resolved.elementType,\n }),\n });\n return buildFieldBuilderForTypeInfo(nestedRef, resolved) as ReturnType<\n ObjectFieldBuilder<T>[\"get\"]\n >;\n },\n hasKey: (key) => {\n const pointer = jsonPointer([key]);\n resolvePointerTypeInfo(options?.typeInfo, pointer);\n return objectOp(\"hasKey\", field, pointer);\n },\n hasPath: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n resolvePointerTypeInfo(options?.typeInfo, normalized);\n return objectOp(\"hasPath\", field, normalized);\n },\n pathEquals: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n if (\n resolved &&\n (resolved.valueType === \"array\" || resolved.valueType === \"object\")\n ) {\n throw new Error(\"pathEquals is only supported for scalar JSON values\");\n }\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\"pathEquals\", field, normalized, value, predicateOptions);\n },\n pathContains: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n if (resolved && resolved.valueType !== \"array\") {\n throw new Error(\"pathContains is only supported for JSON array values\");\n }\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.elementType === undefined ?\n undefined\n : { elementType: resolved.elementType };\n return objectOp(\n \"pathContains\",\n field,\n normalized,\n value,\n predicateOptions,\n );\n },\n pathIsNull: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\n \"pathIsNull\",\n field,\n normalized,\n undefined,\n predicateOptions,\n );\n },\n pathIsNotNull: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\n \"pathIsNotNull\",\n field,\n normalized,\n undefined,\n predicateOptions,\n );\n },\n field: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const nestedPointer = joinJsonPointers(basePointer, normalized);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const nestedRef = fieldRef(field.alias, field.path, {\n jsonPointer: nestedPointer,\n ...(resolved?.valueType !== undefined && {\n valueType: resolved.valueType,\n }),\n ...(resolved?.elementType !== undefined && {\n elementType: resolved.elementType,\n }),\n });\n return buildFieldBuilderForTypeInfo(nestedRef, resolved) as FieldBuilder<\n ResolvedPointerInput<T, P>\n >;\n },\n };\n}\n\n// ============================================================\n// Subquery Predicates\n// ============================================================\n\n/**\n * Creates an EXISTS subquery predicate.\n * Returns true if the subquery returns at least one row.\n *\n * @param subquery - The subquery AST to check for existence\n *\n * @example\n * ```typescript\n * // Find persons who have at least one order\n * query\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", () =>\n * exists(\n * query.from(\"Order\", \"o\")\n * .whereNode(\"o\", (o) => o.customerId.eq(field(\"p.id\")))\n * .select((ctx) => ({ id: ctx.o.id }))\n * .toAst()\n * )\n * )\n * ```\n */\nexport function exists(subquery: QueryAst): Predicate {\n const expr: ExistsSubquery = {\n __type: \"exists\",\n subquery,\n negated: false,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a NOT EXISTS subquery predicate.\n * Returns true if the subquery returns no rows.\n *\n * @param subquery - The subquery AST to check for non-existence\n */\nexport function notExists(subquery: QueryAst): Predicate {\n const expr: ExistsSubquery = {\n __type: \"exists\",\n subquery,\n negated: true,\n };\n return predicate(expr);\n}\n\n/**\n * Creates an IN subquery predicate.\n * Returns true if the field value is in the subquery results.\n *\n * @param field - The field to check\n * @param subquery - The subquery AST that returns a single column\n *\n * @example\n * ```typescript\n * // Find persons whose ID is in the VIP list\n * query\n * .from(\"Person\", \"p\")\n * .where(() =>\n * inSubquery(\n * fieldRef(\"p\", [\"id\"]),\n * query.from(\"VIPMember\", \"v\")\n * .aggregate({\n * id: fieldRef(\"v\", [\"props\", \"personId\"], { valueType: \"string\" }),\n * })\n * .toAst()\n * )\n * )\n * ```\n */\nexport function inSubquery(field: FieldRef, subquery: QueryAst): Predicate {\n assertSingleColumnSubquery(subquery);\n assertCompatibleSubqueryValueTypes(field, subquery);\n const expr: InSubquery = {\n __type: \"in_subquery\",\n field,\n subquery,\n negated: false,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a NOT IN subquery predicate.\n * Returns true if the field value is not in the subquery results.\n *\n * @param field - The field to check\n * @param subquery - The subquery AST that returns a single column\n */\nexport function notInSubquery(field: FieldRef, subquery: QueryAst): Predicate {\n assertSingleColumnSubquery(subquery);\n assertCompatibleSubqueryValueTypes(field, subquery);\n const expr: InSubquery = {\n __type: \"in_subquery\",\n field,\n subquery,\n negated: true,\n };\n return predicate(expr);\n}\n\n/**\n * Ensures IN/NOT IN subqueries project exactly one column.\n */\nfunction assertSingleColumnSubquery(subquery: QueryAst): void {\n const columnCount = getSubqueryColumnCount(subquery);\n if (columnCount === 1) return;\n\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery must project exactly 1 column, but got ${columnCount}`,\n { subqueryColumnCount: columnCount },\n {\n suggestion:\n \"Use aggregate() with exactly one projected field for scalar IN/NOT IN subqueries.\",\n },\n );\n}\n\n/**\n * Ensures IN/NOT IN subquery and field value types are compatible when known.\n */\nfunction assertCompatibleSubqueryValueTypes(\n field: FieldRef,\n subquery: QueryAst,\n): void {\n const fieldValueType = field.valueType;\n const subqueryValueType = getSingleSubqueryColumnValueType(subquery);\n const resolvedValueType = fieldValueType ?? subqueryValueType;\n\n if (isUnsupportedInSubqueryValueType(resolvedValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery does not support ${String(resolvedValueType)} values`,\n { valueType: resolvedValueType },\n {\n suggestion:\n \"Use scalar fields (string/number/boolean/date) in IN/NOT IN predicates.\",\n },\n );\n }\n\n if (isInSubqueryTypeCompatible(fieldValueType, subqueryValueType)) {\n return;\n }\n\n throw new UnsupportedPredicateError(\n `IN/NOT IN type mismatch: field type \"${String(fieldValueType)}\" does not match subquery column type \"${String(subqueryValueType)}\"`,\n {\n fieldValueType,\n subqueryValueType,\n },\n );\n}\n","/**\n * SQL Schema Configuration for Query Compilation\n *\n * Provides table and column identifiers that the query compiler uses.\n * This allows the compiler to work with custom table names instead of\n * hard-coded defaults.\n */\nimport { 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 /** 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\n/**\n * SQL schema configuration for query compilation.\n * Contains table identifiers and utility methods for generating SQL references.\n */\nexport type SqlSchema = Readonly<{\n /** Table names */\n tables: SqlTableNames;\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 fulltext table */\n fulltextTable: SQL;\n}>;\n\n/**\n * Default table names matching the standard TypeGraph schema.\n */\nconst DEFAULT_TABLE_NAMES: SqlTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n fulltext: \"typegraph_node_fulltext\",\n uniques: \"typegraph_node_uniques\",\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\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: SqlTableNames = { ...DEFAULT_TABLE_NAMES, ...names };\n\n // Validate all table names\n validateTableName(tables.nodes, \"nodes\");\n validateTableName(tables.edges, \"edges\");\n validateTableName(tables.fulltext, \"fulltext\");\n validateTableName(tables.uniques, \"uniques\");\n\n return {\n tables,\n nodesTable: sql.raw(quoteIdentifier(tables.nodes)),\n edgesTable: sql.raw(quoteIdentifier(tables.edges)),\n fulltextTable: sql.raw(quoteIdentifier(tables.fulltext)),\n };\n}\n\n/**\n * Default SqlSchema using standard TypeGraph table names.\n */\nexport const DEFAULT_SQL_SCHEMA: SqlSchema = createSqlSchema();\n\n/**\n * The compiler's resolved view of one declared embedding field — the\n * `(dimensions, metric, indexType)` a {@link VectorStrategy} needs to\n * name and scan the field's typed per-`(kind, field)` storage. Sourced\n * from the registered node schema's `embedding()` declaration when the\n * store builds its compile options.\n */\nexport type VectorSlotDescriptor = Readonly<{\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Map of declared embedding slots keyed by {@link vectorSlotKey} -\n * `\"<nodeKind>\\0<fieldPath>\"` (NUL-separated). Carries every `(concrete kind,\n * fieldPath)` that declares an embedding field, so the compiler's\n * `field.similarTo(...)` CTE can UNION ALL the per-field tables for the\n * kinds in an alias that actually declare the field (only\n * `includeSubClasses` yields more than one).\n */\nexport type VectorSlotMap = ReadonlyMap<string, VectorSlotDescriptor>;\n\n/** NUL-delimited composite key for {@link VectorSlotMap}. */\nexport function vectorSlotKey(nodeKind: string, fieldPath: string): string {\n return `${nodeKind}\\u0000${fieldPath}`;\n}\n\n/**\n * CTE aliases used by the standard query emitter. Joining on these names\n * across multiple builder files is fragile when typed as raw strings —\n * import these constants instead.\n */\nexport const ALIAS_CTE_PREFIX = \"cte_\" as const;\nexport const EMBEDDINGS_CTE_ALIAS = \"cte_embeddings\" as const;\nexport const FULLTEXT_CTE_ALIAS = \"cte_fulltext\" as const;\nexport const HYBRID_CANDIDATES_CTE_ALIAS = \"cte_relevance_candidates\" as const;\n","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 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","/**\n * Predicate Expression Compilation\n *\n * Compiles predicate AST nodes to SQL using dialect adapters.\n * Handles comparisons, string operations, null checks, array/object predicates,\n * and subqueries.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { UnsupportedPredicateError } from \"../../errors\";\nimport {\n type ArrayPredicate,\n type ExistsSubquery,\n type FieldRef,\n type FulltextMatchPredicate,\n type InSubquery,\n type LiteralValue,\n type ObjectPredicate,\n type ParameterRef,\n type PredicateExpression,\n type QueryAst,\n type ValueType,\n type VectorSimilarityPredicate,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport {\n joinJsonPointers,\n type JsonPointer,\n jsonPointer,\n} from \"../json-pointer\";\nimport { isParameterRef } from \"../predicates\";\nimport {\n getSingleSubqueryColumnValueType,\n getSubqueryColumnCount,\n isInSubqueryTypeCompatible,\n isUnsupportedInSubqueryValueType,\n} from \"../subquery-utils\";\nimport { type SqlSchema, type VectorSlotMap } from \"./schema\";\n\nconst COMPARISON_OP_SQL: Record<string, string> = {\n eq: \"=\",\n neq: \"!=\",\n gt: \">\",\n gte: \">=\",\n lt: \"<\",\n lte: \"<=\",\n};\n\n// ============================================================\n// Field Reference Compilation\n// ============================================================\n\n/**\n * Compiles a field reference to a base column name.\n *\n * @param field - The field reference to compile\n * @param cteAlias - Optional CTE alias for main query context (e.g., \"cte_p\")\n * @param cteColumnPrefix - Optional prefix for CTE WHERE context:\n * - undefined: Use aliased column names (e.g., \"p_props\")\n * - \"\": Use raw column names (e.g., \"props\") for start CTE\n * - \"n\": Use table-qualified names (e.g., \"n.props\") for traversal CTE\n */\nexport function compileFieldColumn(\n field: FieldRef,\n cteAlias?: string,\n cteColumnPrefix?: string,\n): SQL {\n // When cteColumnPrefix is defined (including empty string), use raw column names\n // This is for CTE WHERE clauses which operate on raw table columns\n if (cteColumnPrefix !== undefined) {\n const qualifier = cteColumnPrefix === \"\" ? \"\" : `${cteColumnPrefix}.`;\n\n if (field.path.length === 1 && field.path[0] === \"id\") {\n return sql.raw(`${qualifier}id`);\n }\n if (field.path.length === 1 && field.path[0] === \"kind\") {\n return sql.raw(`${qualifier}kind`);\n }\n if (field.path.length > 0 && field.path[0] === \"props\") {\n return sql.raw(`${qualifier}props`);\n }\n\n return sql.raw(`${qualifier}${field.path.join(\"_\")}`);\n }\n\n // Default behavior: use aliased column names (e.g., \"p_props\")\n const prefix = field.alias;\n const qualifier = cteAlias ? `${cteAlias}.` : \"\";\n\n if (field.path.length === 1 && field.path[0] === \"id\") {\n return sql.raw(`${qualifier}${prefix}_id`);\n }\n if (field.path.length === 1 && field.path[0] === \"kind\") {\n return sql.raw(`${qualifier}${prefix}_kind`);\n }\n if (field.path.length > 0 && field.path[0] === \"props\") {\n return sql.raw(`${qualifier}${prefix}_props`);\n }\n\n return sql.raw(`${qualifier}${prefix}_${field.path.join(\"_\")}`);\n}\n\n/**\n * Gets the JSON pointer for a field reference.\n */\nfunction getFieldPointer(field: FieldRef): JsonPointer | undefined {\n if (field.jsonPointer !== undefined) {\n return field.jsonPointer;\n }\n\n if (field.path.length > 1 && field.path[0] === \"props\") {\n return jsonPointer(field.path.slice(1));\n }\n\n return undefined;\n}\n\n/**\n * Checks if a field reference points to a JSON props column.\n */\nfunction isJsonField(field: FieldRef): boolean {\n return field.path.length > 0 && field.path[0] === \"props\";\n}\n\n/**\n * Normalizes a value type, treating \"unknown\" as undefined.\n */\nfunction normalizeValueType(\n valueType: ValueType | undefined,\n): ValueType | undefined {\n if (!valueType || valueType === \"unknown\") {\n return undefined;\n }\n return valueType;\n}\n\n/**\n * Compiles a field reference to SQL with appropriate type extraction.\n */\nexport function compileFieldValue(\n field: FieldRef,\n dialect: DialectAdapter,\n valueType?: ValueType,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const resolved = normalizeValueType(valueType);\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n switch (resolved) {\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 // Embeddings are stored in a separate table, but if we need to\n // extract from JSON, treat like a regular JSON value\n return dialect.jsonExtract(column, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return dialect.jsonExtractText(column, pointer);\n }\n }\n}\n\n/**\n * Compiles a field reference for text comparison.\n */\nfunction compileFieldTextValue(\n field: FieldRef,\n dialect: DialectAdapter,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n return dialect.jsonExtractText(column, pointer);\n}\n\n/**\n * Compiles a field reference for JSON value extraction.\n */\nfunction compileFieldJsonValue(\n field: FieldRef,\n dialect: DialectAdapter,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n return dialect.jsonExtract(column, pointer);\n}\n\n// ============================================================\n// Value Type Resolution\n// ============================================================\n\n/**\n * Resolves literal value types from an array of literals.\n */\nfunction resolveLiteralValueTypes(\n literals: readonly LiteralValue[],\n): ValueType | undefined {\n const resolved = new Set<ValueType>();\n\n for (const literal of literals) {\n const valueType = normalizeValueType(literal.valueType);\n if (valueType) {\n resolved.add(valueType);\n }\n }\n\n if (resolved.size > 1) {\n throw new UnsupportedPredicateError(\n \"Mixed literal value types are not supported in predicates\",\n { valueTypes: [...resolved] },\n );\n }\n\n return resolved.values().next().value;\n}\n\n/**\n * Resolves the value type for a comparison predicate.\n */\nfunction resolveComparisonValueType(\n field: FieldRef,\n right: LiteralValue | readonly LiteralValue[] | ParameterRef,\n): ValueType | undefined {\n if (isParameterRef(right)) {\n return (\n normalizeValueType(right.valueType) ?? normalizeValueType(field.valueType)\n );\n }\n const literals = Array.isArray(right) ? right : [right];\n const literalType = resolveLiteralValueTypes(literals);\n const fieldType = normalizeValueType(field.valueType);\n\n // Date fields compared with string literals should use date type\n if (fieldType === \"date\" && literalType === \"string\") {\n return fieldType;\n }\n\n if (literalType) {\n return literalType;\n }\n\n return fieldType;\n}\n\n/**\n * Resolves value type with preference for explicit type.\n */\nfunction resolvePredicateValueType(\n preferred: ValueType | undefined,\n literal: LiteralValue | undefined,\n): ValueType | undefined {\n const normalizedPreferred = normalizeValueType(preferred);\n if (normalizedPreferred) {\n return normalizedPreferred;\n }\n\n return literal ? normalizeValueType(literal.valueType) : undefined;\n}\n\n// ============================================================\n// Value Conversion\n// ============================================================\n\n/**\n * Converts a literal value for SQL binding.\n * Delegates to dialect adapter for proper type conversion (e.g., boolean → 0/1 for SQLite).\n */\nfunction convertValueForSql(value: unknown, dialect: DialectAdapter): unknown {\n return dialect.bindValue(value);\n}\n\n// ============================================================\n// String Pattern Compilation\n// ============================================================\n\n/**\n * Compiles a string pattern for LIKE operations.\n */\nfunction compileStringPattern(op: string, pattern: string): string {\n const escaped = pattern\n .replaceAll(\"%\", String.raw`\\%`)\n .replaceAll(\"_\", String.raw`\\_`);\n\n switch (op) {\n case \"contains\": {\n return `%${escaped}%`;\n }\n case \"startsWith\": {\n return `${escaped}%`;\n }\n case \"endsWith\": {\n return `%${escaped}`;\n }\n case \"like\":\n case \"ilike\": {\n return pattern;\n }\n default: {\n return escaped;\n }\n }\n}\n\n/**\n * Escapes wildcard characters in a SQL pattern parameter.\n */\nfunction escapeLikePatternParameter(parameter: SQL): SQL {\n return sql`REPLACE(REPLACE(REPLACE(${parameter}, '\\\\', '\\\\\\\\'), '%', '\\\\%'), '_', '\\\\_')`;\n}\n\n/**\n * Builds a SQL pattern expression for parameterized string operations.\n */\nfunction compileParameterizedStringPattern(op: string, parameter: SQL): SQL {\n switch (op) {\n case \"contains\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`'%' || ${escaped} || '%'`;\n }\n case \"startsWith\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`${escaped} || '%'`;\n }\n case \"endsWith\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`'%' || ${escaped}`;\n }\n case \"like\":\n case \"ilike\": {\n return parameter;\n }\n default: {\n return escapeLikePatternParameter(parameter);\n }\n }\n}\n\n// ============================================================\n// Predicate Compilation\n// ============================================================\n\n/**\n * Compiler context passed to recursive compilation functions.\n *\n * When compiling predicates inside CTE WHERE clauses, `cteColumnPrefix` specifies\n * how to reference columns:\n * - undefined: Use aliased column names (e.g., \"p_props\") - for main query context\n * - \"\": Use raw column names (e.g., \"props\") - for start CTE WHERE clause\n * - \"n\": Use table-qualified names (e.g., \"n.props\") - for traversal CTE WHERE clause\n */\nexport type PredicateCompilerContext = Readonly<{\n dialect: DialectAdapter;\n schema: SqlSchema;\n compileQuery: (ast: QueryAst, graphId: string) => SQL;\n cteColumnPrefix?: string;\n /**\n * Active vector strategy for `field.similarTo(...)` compilation. When\n * present, the embeddings CTE scans the strategy's per-`(kind, field)`\n * tables and uses its `distanceExpression`; absent on backends without\n * vector support (the vector pass rejects the predicate before the CTE\n * builder runs).\n */\n vectorStrategy?: VectorStrategy;\n /**\n * Whether the active backend supports SQL window functions such as\n * `ROW_NUMBER()`.\n */\n windowFunctions: boolean;\n /**\n * Declared embedding slots `(kind, fieldPath) -> {dimensions, metric,\n * indexType}`. The embeddings CTE consults it to know which kinds in\n * an alias actually declare the field — only those get a per-field\n * table scan in the UNION ALL.\n */\n vectorSlots?: VectorSlotMap;\n}>;\n\n/**\n * Compiles a predicate expression to SQL.\n */\nexport function compilePredicateExpression(\n expr: PredicateExpression,\n ctx: PredicateCompilerContext,\n): SQL {\n const { dialect } = ctx;\n\n const cteColumnPrefix = ctx.cteColumnPrefix;\n\n switch (expr.__type) {\n case \"comparison\": {\n return compileComparisonPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"string_op\": {\n const field = compileFieldTextValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n\n if (isParameterRef(expr.pattern)) {\n const placeholder = sql`${sql.placeholder(expr.pattern.name)}`;\n const pattern = compileParameterizedStringPattern(expr.op, placeholder);\n if (\n expr.op === \"ilike\" ||\n expr.op === \"contains\" ||\n expr.op === \"startsWith\" ||\n expr.op === \"endsWith\"\n ) {\n return dialect.ilike(field, pattern);\n }\n return sql`${field} LIKE ${pattern}`;\n }\n\n const pattern = compileStringPattern(expr.op, expr.pattern);\n // Use case-insensitive matching for contains, startsWith, endsWith, and ilike\n // This ensures consistent behavior across PostgreSQL (case-sensitive LIKE)\n // and SQLite (case-insensitive LIKE for ASCII)\n if (\n expr.op === \"ilike\" ||\n expr.op === \"contains\" ||\n expr.op === \"startsWith\" ||\n expr.op === \"endsWith\"\n ) {\n return dialect.ilike(field, pattern);\n }\n // Use case-sensitive LIKE only for explicit 'like' operator\n return sql`${field} LIKE ${pattern}`;\n }\n\n case \"null_check\": {\n const field = compileFieldTextValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n return expr.op === \"isNull\" ?\n sql`${field} IS NULL`\n : sql`${field} IS NOT NULL`;\n }\n\n case \"between\": {\n const lowerIsParam = isParameterRef(expr.lower);\n const upperIsParam = isParameterRef(expr.upper);\n\n // Resolve value type from non-param bounds\n const boundsForType: LiteralValue[] = [];\n if (!lowerIsParam) boundsForType.push(expr.lower);\n if (!upperIsParam) boundsForType.push(expr.upper);\n\n const valueType =\n boundsForType.length > 0 ?\n resolveComparisonValueType(expr.field, boundsForType)\n : normalizeValueType(expr.field.valueType);\n\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"Between comparisons are not supported for JSON arrays or objects\",\n );\n }\n const field = compileFieldValue(\n expr.field,\n dialect,\n valueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const lower =\n lowerIsParam ?\n sql.placeholder(expr.lower.name)\n : convertValueForSql(expr.lower.value, dialect);\n const upper =\n upperIsParam ?\n sql.placeholder(expr.upper.name)\n : convertValueForSql(expr.upper.value, dialect);\n return sql`${field} BETWEEN ${lower} AND ${upper}`;\n }\n\n case \"and\": {\n const parts = expr.predicates.map((p) =>\n compilePredicateExpression(p, ctx),\n );\n return sql`(${sql.join(parts, sql` AND `)})`;\n }\n\n case \"or\": {\n const parts = expr.predicates.map((p) =>\n compilePredicateExpression(p, ctx),\n );\n return sql`(${sql.join(parts, sql` OR `)})`;\n }\n\n case \"not\": {\n const inner = compilePredicateExpression(expr.predicate, ctx);\n return sql`NOT (${inner})`;\n }\n\n case \"array_op\": {\n return compileArrayPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"object_op\": {\n return compileObjectPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"aggregate_comparison\": {\n return compileAggregatePredicate(expr, dialect);\n }\n\n case \"exists\": {\n return compileExistsSubquery(expr, ctx);\n }\n\n case \"in_subquery\": {\n return compileInSubquery(expr, ctx);\n }\n\n case \"vector_similarity\":\n case \"fulltext_match\": {\n // Structural predicates — handled by the main compiler via JOINs,\n // ORDER BY, and LIMIT. Compile to 1=1 so they compose safely with\n // surrounding AND branches.\n return STRUCTURAL_PREDICATE_NOOP;\n }\n }\n}\n\nconst STRUCTURAL_PREDICATE_NOOP = sql.raw(\"1=1\");\n\n/**\n * Compiles a comparison predicate.\n */\nfunction compileComparisonPredicate(\n expr: {\n __type: \"comparison\";\n op: string;\n left: FieldRef;\n right: LiteralValue | readonly LiteralValue[] | ParameterRef;\n },\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n // Handle ParameterRef on the right side\n if (isParameterRef(expr.right)) {\n const parameterValueType =\n normalizeValueType(expr.right.valueType) ??\n normalizeValueType(expr.left.valueType);\n const left = compileFieldValue(\n expr.left,\n dialect,\n parameterValueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const opSql = COMPARISON_OP_SQL[expr.op];\n if (!opSql) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for parameterized predicates`,\n );\n }\n return sql`${left} ${sql.raw(opSql)} ${sql.placeholder(expr.right.name)}`;\n }\n\n const valueType = resolveComparisonValueType(expr.left, expr.right);\n\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for ${valueType} values`,\n );\n }\n\n const left = compileFieldValue(\n expr.left,\n dialect,\n valueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n\n if (expr.op === \"in\" || expr.op === \"notIn\") {\n const values: readonly LiteralValue[] =\n Array.isArray(expr.right) ? expr.right : [expr.right as LiteralValue];\n if (values.length === 0) {\n return expr.op === \"in\" ? sql.raw(\"1=0\") : sql.raw(\"1=1\");\n }\n const placeholders = values.map(\n (v) => sql`${convertValueForSql(v.value, dialect)}`,\n );\n const op = expr.op === \"in\" ? sql.raw(\"IN\") : sql.raw(\"NOT IN\");\n return sql`${left} ${op} (${sql.join(placeholders, sql`, `)})`;\n }\n\n // For single-value comparisons, extract the literal value\n const right = expr.right;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Type narrowing with Array.isArray\n const rightValue: LiteralValue = Array.isArray(right) ? right[0]! : right;\n\n const convertedRight = convertValueForSql(rightValue.value, dialect);\n const opSql = COMPARISON_OP_SQL[expr.op];\n if (!opSql) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported`,\n );\n }\n return sql`${left} ${sql.raw(opSql)} ${convertedRight}`;\n}\n\n/**\n * Compiles an array predicate.\n */\nfunction compileArrayPredicate(\n expr: ArrayPredicate,\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n const field = compileFieldJsonValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const values =\n expr.values?.map((v) => convertValueForSql(v.value, dialect)) ?? [];\n\n switch (expr.op) {\n case \"isEmpty\": {\n return sql`(${field} IS NULL OR ${dialect.jsonArrayLength(field)} = 0)`;\n }\n case \"isNotEmpty\": {\n return sql`(${field} IS NOT NULL AND ${dialect.jsonArrayLength(field)} > 0)`;\n }\n case \"lengthEq\": {\n return sql`${dialect.jsonArrayLength(field)} = ${expr.length}`;\n }\n case \"lengthGt\": {\n return sql`${dialect.jsonArrayLength(field)} > ${expr.length}`;\n }\n case \"lengthGte\": {\n return sql`${dialect.jsonArrayLength(field)} >= ${expr.length}`;\n }\n case \"lengthLt\": {\n return sql`${dialect.jsonArrayLength(field)} < ${expr.length}`;\n }\n case \"lengthLte\": {\n return sql`${dialect.jsonArrayLength(field)} <= ${expr.length}`;\n }\n case \"contains\": {\n const value = values[0];\n if (value === undefined) {\n return sql.raw(\"1=0\");\n }\n return dialect.jsonArrayContains(field, value);\n }\n case \"containsAll\": {\n return dialect.jsonArrayContainsAll(field, values);\n }\n case \"containsAny\": {\n return dialect.jsonArrayContainsAny(field, values);\n }\n }\n}\n\n/**\n * Compiles an object/JSON predicate.\n */\nfunction compileObjectPredicate(\n expr: ObjectPredicate,\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n const basePointer = getFieldPointer(expr.field);\n const pointer = joinJsonPointers(basePointer, expr.pointer);\n const column = compileFieldColumn(expr.field, undefined, cteColumnPrefix);\n\n switch (expr.op) {\n case \"hasKey\":\n case \"hasPath\": {\n return dialect.jsonHasPath(column, pointer);\n }\n\n case \"pathEquals\": {\n if (!expr.value) {\n throw new UnsupportedPredicateError(\n \"pathEquals requires a comparison value\",\n );\n }\n const valueType = resolvePredicateValueType(expr.valueType, expr.value);\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"pathEquals is not supported for JSON arrays or objects\",\n );\n }\n const left = compileFieldValue(\n expr.field,\n dialect,\n valueType,\n undefined,\n pointer,\n cteColumnPrefix,\n );\n return sql`${left} = ${convertValueForSql(expr.value.value, dialect)}`;\n }\n\n case \"pathContains\": {\n if (!expr.value) {\n throw new UnsupportedPredicateError(\n \"pathContains requires a comparison value\",\n );\n }\n const arrayField = compileFieldJsonValue(\n expr.field,\n dialect,\n undefined,\n pointer,\n cteColumnPrefix,\n );\n return dialect.jsonArrayContains(\n arrayField,\n convertValueForSql(expr.value.value, dialect),\n );\n }\n\n case \"pathIsNull\": {\n return dialect.jsonPathIsNull(column, pointer);\n }\n\n case \"pathIsNotNull\": {\n return dialect.jsonPathIsNotNull(column, pointer);\n }\n }\n}\n\n/**\n * AggregateExpr structure from AST.\n */\ntype AggregateExprInput = Readonly<{\n __type: \"aggregate\";\n function: string;\n field: FieldRef;\n}>;\n\n/**\n * Compiles an aggregate comparison predicate.\n */\nfunction compileAggregatePredicate(\n expr: {\n __type: \"aggregate_comparison\";\n op: string;\n aggregate: AggregateExprInput;\n value: LiteralValue;\n },\n dialect: DialectAdapter,\n): SQL {\n const aggregate = compileAggregateExpr(expr.aggregate, dialect);\n\n const op = COMPARISON_OP_SQL[expr.op];\n if (!op) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for aggregate predicates`,\n );\n }\n\n const convertedValue = convertValueForSql(expr.value.value, dialect);\n return sql`${aggregate} ${sql.raw(op)} ${convertedValue}`;\n}\n\n/**\n * Compiles an aggregate expression.\n */\nfunction compileAggregateExpr(\n expr: AggregateExprInput,\n dialect: DialectAdapter,\n): SQL {\n const cteAlias = `cte_${expr.field.alias}`;\n const field = compileFieldValue(\n expr.field,\n dialect,\n expr.field.valueType,\n cteAlias,\n );\n\n switch (expr.function) {\n case \"count\": {\n return sql`COUNT(${field})`;\n }\n case \"countDistinct\": {\n return sql`COUNT(DISTINCT ${field})`;\n }\n case \"sum\": {\n return sql`SUM(${field})`;\n }\n case \"avg\": {\n return sql`AVG(${field})`;\n }\n case \"min\": {\n return sql`MIN(${field})`;\n }\n case \"max\": {\n return sql`MAX(${field})`;\n }\n default: {\n throw new UnsupportedPredicateError(\n `Unknown aggregate function: ${expr.function}`,\n );\n }\n }\n}\n\n/**\n * Compiles an EXISTS subquery predicate.\n */\nfunction compileExistsSubquery(\n expr: ExistsSubquery,\n ctx: PredicateCompilerContext,\n): SQL {\n if (expr.subquery.graphId === undefined) {\n throw new UnsupportedPredicateError(\"EXISTS subquery must have a graphId\");\n }\n const subSql = ctx.compileQuery(expr.subquery, expr.subquery.graphId);\n return expr.negated ? sql`NOT EXISTS (${subSql})` : sql`EXISTS (${subSql})`;\n}\n\n/**\n * Compiles an IN subquery predicate.\n */\nfunction compileInSubquery(\n expr: InSubquery,\n ctx: PredicateCompilerContext,\n): SQL {\n const subqueryColumnCount = getSubqueryColumnCount(expr.subquery);\n if (subqueryColumnCount !== 1) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery must project exactly 1 column, but got ${subqueryColumnCount}`,\n { subqueryColumnCount },\n );\n }\n\n const fieldValueType = normalizeValueType(expr.field.valueType);\n const subqueryValueType = getSingleSubqueryColumnValueType(expr.subquery);\n const resolvedValueType = fieldValueType ?? subqueryValueType;\n\n if (isUnsupportedInSubqueryValueType(resolvedValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery does not support ${String(resolvedValueType)} values`,\n { valueType: resolvedValueType },\n );\n }\n\n if (!isInSubqueryTypeCompatible(fieldValueType, subqueryValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN type mismatch: field type \"${String(fieldValueType)}\" does not match subquery column type \"${String(subqueryValueType)}\"`,\n {\n fieldValueType,\n subqueryValueType,\n },\n );\n }\n\n const valueType = fieldValueType ?? subqueryValueType;\n if (expr.subquery.graphId === undefined) {\n throw new UnsupportedPredicateError(\n \"IN/NOT IN subquery must have a graphId\",\n );\n }\n const fieldSql = compileFieldValue(\n expr.field,\n ctx.dialect,\n valueType,\n undefined,\n undefined,\n ctx.cteColumnPrefix,\n );\n const subSql = ctx.compileQuery(expr.subquery, expr.subquery.graphId);\n return expr.negated ?\n sql`${fieldSql} NOT IN (${subSql})`\n : sql`${fieldSql} IN (${subSql})`;\n}\n\n/**\n * Compiles a vector similarity predicate.\n *\n * Vector similarity predicates require special handling at the query compilation\n * level to handle:\n * - JOIN to embeddings table\n * - ORDER BY distance ASC\n * - LIMIT k\n *\n * This function handles the minScore filter if present. The main query compiler\n * must detect vector_similarity predicates and set up the appropriate JOINs\n * and ordering.\n */\n\n// ============================================================\n// Structural Predicate Extraction\n// ============================================================\n\n/**\n * Extracts all instances of a \"structural\" predicate (one that rewrites\n * the query into JOIN + ORDER BY + LIMIT, rather than acting as a\n * boolean WHERE clause). Both `vector_similarity` and `fulltext_match`\n * have the same placement rules: top-level or under AND only — nesting\n * under OR/NOT is rejected because the rewrite is incompatible with\n * disjunction and negation.\n */\nfunction extractStructuralPredicates<T extends PredicateExpression>(\n predicates: readonly { expression: PredicateExpression }[],\n isMatch: (expr: PredicateExpression) => expr is T,\n rejectionMessage: string,\n): T[] {\n const results: T[] = [];\n\n function visit(expr: PredicateExpression, inDisallowedBranch: boolean): void {\n if (isMatch(expr)) {\n if (inDisallowedBranch) {\n throw new UnsupportedPredicateError(rejectionMessage);\n }\n results.push(expr);\n return;\n }\n switch (expr.__type) {\n case \"and\": {\n for (const child of expr.predicates) visit(child, inDisallowedBranch);\n return;\n }\n case \"or\": {\n for (const child of expr.predicates) visit(child, true);\n return;\n }\n case \"not\": {\n visit(expr.predicate, true);\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\n for (const pred of predicates) visit(pred.expression, false);\n return results;\n}\n\nexport function extractVectorSimilarityPredicates(\n predicates: readonly { expression: PredicateExpression }[],\n): VectorSimilarityPredicate[] {\n return extractStructuralPredicates(\n predicates,\n (expr): expr is VectorSimilarityPredicate =>\n expr.__type === \"vector_similarity\",\n \"Vector similarity predicates cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n );\n}\n\nexport function extractFulltextMatchPredicates(\n predicates: readonly { expression: PredicateExpression }[],\n): FulltextMatchPredicate[] {\n return extractStructuralPredicates(\n predicates,\n (expr): expr is FulltextMatchPredicate => expr.__type === \"fulltext_match\",\n \"Fulltext match predicates cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n );\n}\n\n// ============================================================\n// Exports for aggregate compilation\n// ============================================================\n\nexport { compileAggregateExpr };\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport type { KindEntity } from \"../../core/types\";\nimport { CompilerInvariantError } from \"../../errors\";\nimport {\n type FulltextMatchPredicate,\n type NodePredicate,\n type QueryAst,\n type VectorSimilarityPredicate,\n} from \"../ast\";\nimport {\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"./predicates\";\n\nconst EMPTY_PREDICATES: readonly NodePredicate[] = [];\n\nexport type PredicateIndex = Readonly<{\n byAliasAndType: ReadonlyMap<string, readonly NodePredicate[]>;\n}>;\n\nfunction buildPredicateIndexKey(alias: string, targetType: KindEntity): string {\n return `${alias}\\u0000${targetType}`;\n}\n\nfunction resolvePredicateTargetType(predicate: NodePredicate): KindEntity {\n return predicate.targetType === \"edge\" ? \"edge\" : \"node\";\n}\n\nexport function buildPredicateIndex(ast: QueryAst): PredicateIndex {\n const byAliasAndType = new Map<string, NodePredicate[]>();\n for (const predicate of ast.predicates) {\n const key = buildPredicateIndexKey(\n predicate.targetAlias,\n resolvePredicateTargetType(predicate),\n );\n const existing = byAliasAndType.get(key);\n if (existing === undefined) {\n byAliasAndType.set(key, [predicate]);\n } else {\n existing.push(predicate);\n }\n }\n return { byAliasAndType };\n}\n\nexport function getPredicatesForAlias(\n predicateIndex: PredicateIndex,\n alias: string,\n targetType: KindEntity,\n): readonly NodePredicate[] {\n return (\n predicateIndex.byAliasAndType.get(\n buildPredicateIndexKey(alias, targetType),\n ) ?? EMPTY_PREDICATES\n );\n}\n\nexport function compilePredicateClauses(\n predicates: readonly NodePredicate[],\n predicateContext: PredicateCompilerContext,\n): SQL[] {\n return predicates.map((predicate) =>\n compilePredicateExpression(predicate.expression, predicateContext),\n );\n}\n\nexport function compileKindFilter(column: SQL, kinds: readonly string[]): SQL {\n if (kinds.length === 0) {\n return sql`1 = 0`;\n }\n if (kinds.length === 1) {\n return sql`${column} = ${kinds[0]}`;\n }\n return sql`${column} IN (${sql.join(\n kinds.map((kind) => sql`${kind}`),\n sql`, `,\n )})`;\n}\n\nexport function getNodeKindsForAlias(\n ast: QueryAst,\n alias: string,\n): readonly string[] {\n if (alias === ast.start.alias) {\n return ast.start.kinds;\n }\n\n for (const traversal of ast.traversals) {\n if (traversal.nodeAlias === alias) {\n return traversal.nodeKinds;\n }\n }\n\n throw new CompilerInvariantError(`Unknown traversal source alias: ${alias}`);\n}\n\n/**\n * Returns the shared alias when a hybrid (vector + fulltext) query has\n * both predicates targeting the same alias — that's the case where the\n * emitter can fuse ranks via `HYBRID_CANDIDATES_CTE_ALIAS` / RRF.\n * Returns `undefined` when either predicate is missing or the two\n * predicates target different aliases.\n */\nexport function getHybridTargetAlias(\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): string | undefined {\n if (!vectorPredicate || !fulltextPredicate) return undefined;\n return vectorPredicate.field.alias === fulltextPredicate.field.alias ?\n vectorPredicate.field.alias\n : undefined;\n}\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}>;\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 } = 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 switch (mode) {\n case \"current\": {\n const now = currentTimestamp ?? sql`CURRENT_TIMESTAMP`;\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(`asOf timestamp is required for temporal mode \"asOf\"`);\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/**\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: { temporalMode: { mode: TemporalMode; asOf?: string } },\n tableAlias?: string,\n): TemporalFilterOptions {\n return {\n mode: ast.temporalMode.mode,\n asOf: ast.temporalMode.asOf,\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","/**\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 { 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 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 TemporalMode } from \"../core/types\";\nimport { type RecursiveCyclePolicy } from \"../query/ast\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport { type SqlSchema } 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 dialect: DialectAdapter;\n schema: SqlSchema;\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 tableAlias: \"n\",\n currentTimestamp,\n });\n const edgeTemporalFilter = compileTemporalFilter({\n mode: options.temporalMode,\n asOf: options.asOf,\n tableAlias: \"e\",\n currentTimestamp,\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 ${options.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: options.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 { 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 { DEFAULT_SQL_SCHEMA, type SqlSchema } 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 { 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 /**\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 * 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 dialect: DialectAdapter;\n schema: SqlSchema;\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 options: SubgraphOptions<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\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 dialect: params.dialect,\n schema: params.schema ?? DEFAULT_SQL_SCHEMA,\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 dialect: ctx.dialect,\n schema: ctx.schema,\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 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 n.id IN (SELECT id FROM included_ids)`;\n\n return ctx.backend.execute<SubgraphNodeFetchRow>(query) as Promise<\n SubgraphNodeFetchRow[]\n >;\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 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>(query) as Promise<\n SubgraphEdgeFetchRow[]\n >;\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 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\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 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 {\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 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 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 { 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 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 for table names. 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\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): SQL {\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 schema = options_.schema ?? DEFAULT_SQL_SCHEMA;\n\n const adapter = resolveDialectAdapter(dialect, options_.fulltextStrategy);\n const ctx: PredicateCompilerContext = {\n dialect: adapter,\n schema,\n compileQuery: (subAst, subGraphId) =>\n compileQuery(subAst, subGraphId, propagateOptions(options_)),\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 compileStandardQuery(lowered, graphId, ctx);\n }\n return compileVariableLengthQuery(ast, graphId, ctx);\n }\n\n // Standard query compilation\n return 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): SQL {\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 compileSetOp(\n op,\n graphId,\n adapter,\n (ast, gid) => compileQuery(ast, gid, propagateOptions(options_)),\n options_.vectorStrategy,\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/** 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 };\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.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 * 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 { 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 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 };\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 { type SQL } from \"drizzle-orm\";\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 {\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 { 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: SQL | typeof NOT_COMPUTED = NOT_COMPUTED;\n #cachedOptimizedCompiled: SQL | typeof NOT_COMPUTED = 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(): SQL {\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 /**\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\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 =\n await this.#config.backend.execute<Record<string, unknown>>(compiled);\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 // 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 // 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 backend.execute<Record<string, unknown>>(compiled);\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: SQL;\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 =\n await this.#requireBackend().execute<Record<string, unknown>>(compiled);\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: SQL;\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 =\n await backend.execute<Record<string, unknown>>(compiled);\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 SQL } from \"drizzle-orm\";\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 { 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: SQL | 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(): SQL {\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 NodeAlias,\n type QueryBuilderConfig,\n type QueryBuilderState,\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 // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty object for initial empty edge alias map\n EdgeAliases extends EdgeAliasMap = {},\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 // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases accumulated\n RecAliases extends RecursiveAliasMap = {},\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 > {\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 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 > {\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 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 >;\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 >;\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 > {\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 >;\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 > {\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 >;\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 { TraversalBuilder } from \"./traversal-builder\";\nimport {\n type AliasMap,\n type BaseFieldAccessor,\n type EdgeAccessor,\n type EdgeAlias,\n type EdgeAliasMap,\n type NodeAccessor,\n type NodeAlias,\n type QueryBuilderConfig,\n type QueryBuilderState,\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\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 // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty object for initial empty alias map\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> {\n readonly #config: QueryBuilderConfig;\n readonly #state: QueryBuilderState;\n\n constructor(config: QueryBuilderConfig, state: QueryBuilderState) {\n this.#config = config;\n this.#state = state;\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 >;\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 >;\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 > {\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 > {\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> {\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> {\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 >;\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 >;\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 > {\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 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 > {\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 >;\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 >;\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 > {\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 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 > {\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 > {\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 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> {\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: number): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n limit: n,\n });\n }\n\n /**\n * Offsets the results.\n */\n offset(n: number): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n offset: n,\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 temporal(\n mode: TemporalMode,\n asOf?: string,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases> {\n if (this.#config.sealedCoordinate !== undefined) {\n const coordinate = this.#config.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 * 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> {\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> {\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> {\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> {\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<G, Aliases, EdgeAliases, RecursiveAliases>,\n ) => QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases>,\n ): QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases> {\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 { type SQL } from \"drizzle-orm\";\n\nimport {\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\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 { 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\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: SQL | 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(): SQL {\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\n if (composableQueryHasParameterReferences(this.toAst())) {\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 =\n await this.#config.backend.execute<Record<string, unknown>>(compiled);\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 if (composableQueryHasParameterReferences(this.toAst())) {\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 backend.execute<Record<string, unknown>>(compiled);\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 QueryBuilder } from \"./query-builder\";\nimport { type TraversalBuilder } from \"./traversal-builder\";\nimport { type AliasMap, type EdgeAliasMap } 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 */\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> = (\n builder: QueryBuilder<G, InAliases, InEdgeAliases>,\n) => QueryBuilder<G, OutAliases, OutEdgeAliases>;\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> = <Aliases extends RequiredAliases, EdgeAliases extends RequiredEdgeAliases>(\n builder: QueryBuilder<G, Aliases, EdgeAliases>,\n) => QueryBuilder<G, Aliases & AddedAliases, EdgeAliases & AddedEdgeAliases>;\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Direction type is context-dependent\n builder: TraversalBuilder<G, InAliases, InEdgeAliases, EK, EA, any>,\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>(\n fn: (\n builder: QueryBuilder<G, InAliases, InEdgeAliases>,\n ) => QueryBuilder<G, OutAliases, OutEdgeAliases>,\n): QueryFragment<G, InAliases, OutAliases, InEdgeAliases, OutEdgeAliases> {\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>(\n fn: (\n builder: QueryBuilder<G, InAliases, InEdgeAliases>,\n ) => QueryBuilder<G, OutAliases, OutEdgeAliases>,\n) => QueryFragment<G, InAliases, OutAliases, InEdgeAliases, OutEdgeAliases> {\n return fragmentIdentity;\n}\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>(f1: QueryFragment<G, A1, A2, E1, E2>): QueryFragment<G, A1, A2, E1, E2>;\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>(\n f1: QueryFragment<G, A1, A2, E1, E2>,\n f2: QueryFragment<G, A2, A3, E2, E3>,\n): QueryFragment<G, A1, A3, E1, E3>;\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>(\n f1: QueryFragment<G, A1, A2, E1, E2>,\n f2: QueryFragment<G, A2, A3, E2, E3>,\n f3: QueryFragment<G, A3, A4, E3, E4>,\n): QueryFragment<G, A1, A4, E1, E4>;\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>(\n f1: QueryFragment<G, A1, A2, E1, E2>,\n f2: QueryFragment<G, A2, A3, E2, E3>,\n f3: QueryFragment<G, A3, A4, E3, E4>,\n f4: QueryFragment<G, A4, A5, E4, E5>,\n): QueryFragment<G, A1, A5, E1, E5>;\n\nexport function composeFragments<G extends GraphDef>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Variadic composition requires any\n ...fragments: QueryFragment<G, any, any, any, any>[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Return type depends on input types\n): QueryFragment<G, any, any, any, any> {\n return (builder) => {\n let result = builder;\n for (const fragment of fragments) {\n result = fragment(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 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Flexible alias types\n): QueryFragment<G, any, any, any, any> {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Flexible alias types\n): QueryFragment<G, any, any, any, any> {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Flexible alias types\n): QueryFragment<G, any, any, any, any> {\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 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 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 QueryBuilder,\n type QueryBuilderConfig,\n type QueryBuilderState,\n} from \"./builder/index\";\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 FieldAccessor,\n NodeAccessor,\n NodeAlias,\n PaginatedResult,\n PaginateOptions,\n PropsAccessor,\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 */\nexport function createQueryBuilder<G extends GraphDef>(\n graphId: string,\n registry: KindRegistry,\n options?: CreateQueryBuilderOptions,\n): QueryBuilder<G> {\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 ...(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\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 groupBy: undefined,\n having: undefined,\n fusion: undefined,\n dynamicNodeAliases: new Set(),\n dynamicEdgeAliases: new Set(),\n };\n\n return new QueryBuilder(config, initialState);\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 * 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 { resolveReadCoordinate } from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../../query/compiler/recursive\";\nimport { type SqlSchema } 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 defaultTemporalMode: TemporalMode;\n}>;\n\nexport type InternalTemporalOptions = Readonly<{\n temporalMode?: TemporalMode;\n asOf?: string;\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<{ temporalMode: TemporalMode; asOf?: string }> {\n const { valid } = resolveReadCoordinate(\n options.temporalMode ?? ctx.defaultTemporalMode,\n options.asOf,\n );\n return {\n temporalMode: valid.mode,\n ...(valid.asOf !== undefined && { asOf: valid.asOf }),\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 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 {\n type AlgorithmContext,\n type InternalTemporalOptions,\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\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 ${ctx.schema.edgesTable} WHERE ${sql.join(whereClauses, sql` AND `)}`;\n\n const rows =\n await ctx.backend.execute<Readonly<{ count: number | string }>>(query);\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 { 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 });\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>(query);\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 });\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 }>>(query);\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 excludeSource: true,\n });\n}\n","import { type SQL, sql } from \"drizzle-orm\";\n\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 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 });\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>(query);\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 query: SQL = sql`SELECT id, kind FROM ${ctx.schema.nodesTable} WHERE graph_id = ${ctx.graphId} AND id = ${nodeId} AND ${temporalFilter} LIMIT 1`;\n const rows = await ctx.backend.execute<NodeKindRow>(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 { createSqlSchema, type SqlSchema } from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\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 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 CreateGraphAlgorithmsParams = Readonly<{\n graphId: string;\n backend: GraphBackend;\n schema: SqlSchema | undefined;\n defaultTemporalMode: TemporalMode;\n}>;\n\nexport function createGraphAlgorithms<G extends GraphDef>(\n params: CreateGraphAlgorithmsParams,\n): GraphAlgorithms<G> {\n const ctx: AlgorithmContext = {\n graphId: params.graphId,\n backend: params.backend,\n dialect: getDialect(params.backend.dialect),\n schema:\n params.schema ??\n (params.backend.tableNames ?\n createSqlSchema(params.backend.tableNames)\n : createSqlSchema()),\n defaultTemporalMode: params.defaultTemporalMode,\n };\n\n return {\n shortestPath(from, to, options) {\n return executeShortestPath(\n ctx,\n resolveNodeId(from),\n resolveNodeId(to),\n options,\n );\n },\n reachable(from, options) {\n return executeReachable(ctx, resolveNodeId(from), options);\n },\n canReach(from, to, options) {\n return executeCanReach(\n ctx,\n resolveNodeId(from),\n resolveNodeId(to),\n options,\n );\n },\n neighbors(node, options) {\n return executeNeighbors(ctx, resolveNodeId(node), options);\n },\n degree(node, options) {\n return executeDegree(ctx, resolveNodeId(node), options ?? {});\n },\n };\n}\n\nexport type {\n AlgorithmCyclePolicy,\n BaseTraversalOptions,\n DegreeOptions,\n NeighborsOptions,\n PathNode,\n ReachableNode,\n ReachableOptions,\n ShortestPathOptions,\n ShortestPathResult,\n TemporalAlgorithmOptions,\n TraversalDirection,\n} from \"./types\";\n","/**\n * EdgeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific edge type.\n */\nimport { type z } from \"zod\";\n\nimport {\n type FindEdgesByKindParams,\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type TemporalMode } from \"../../core/types\";\nimport { UnsupportedPredicateError } from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport type { BatchableQuery } from \"../../query/builder/types\";\nimport { 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 // Resolve the coordinate once so the whole batch observes one instant.\n const matches = temporalRowMatcher(options);\n\n if (backend.getEdges !== undefined) {\n const rows = await backend.getEdges(graphId, ids);\n const rowMap = new Map<string, (typeof rows)[number]>();\n for (const row of rows) {\n rowMap.set(row.id, row);\n }\n return ids.map((id) => {\n const row = rowMap.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 return Promise.all(\n ids.map(async (id) => {\n const row = await backend.getEdge(graphId, 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\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 = new Map<\n string,\n { deleted_at: string | undefined }\n >();\n\n if (target.getEdges === undefined) {\n const rows = await Promise.all(\n ids.map((id) => target.getEdge(graphId, 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.getEdges(graphId, 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: 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\";\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 const rowsById = new Map<string, BackendNodeRow>();\n if (ids.length === 0) return rowsById;\n\n if (backend.getNodes !== undefined) {\n const rows = await backend.getNodes(graphId, kind, 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(\n uniqueIds.map((id) => backend.getNode(graphId, kind, id)),\n );\n for (const row of rows) {\n if (row !== undefined) rowsById.set(row.id, row);\n }\n return rowsById;\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 {\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 backend: GraphBackend;\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","/**\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 {\n type GraphBackend,\n type KindRemovalRow,\n type RecordKindRemovalParams,\n} from \"../backend/types\";\nimport type { KindEntity } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport type {\n VectorSlot,\n VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\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\";\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 backend: GraphBackend;\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 ctx = {\n backend,\n graphId,\n nodesTable,\n edgesTable,\n fulltextTable,\n uniquesTable,\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: Readonly<{\n backend: GraphBackend;\n graphId: string;\n nodesTable: string;\n edgesTable: string;\n fulltextTable: string;\n uniquesTable: string;\n }>,\n): Promise<MaterializeRemovalsEntry> {\n const executeDdl = ctx.backend.executeDdl!;\n const recordKindRemoval = ctx.backend.recordKindRemoval!;\n try {\n // Build the per-row DELETEs. For a removed node kind: drop the\n // primary rows, every edge referencing it (via from_kind / to_kind\n // — those would otherwise dangle), the secondary tables that\n // partition by node_kind (fulltext, uniques), plus the strategy's\n // typed per-`(kind, field)` embedding tables. Without the secondary\n // cleanup, repeated remove/re-add cycles accumulate dead rows that\n // fulltext / unique / vector lookups still scan. For a removed edge\n // kind: only the edges table needs cleanup. All statements target\n // disjoint row sets — issued in parallel.\n const deletes: Promise<void>[] = [];\n const graphLit = literal(ctx.graphId);\n const kindLit = literal(row.kindName);\n if (row.entity === \"node\") {\n deletes.push(\n executeDdl(\n `DELETE FROM ${quote(ctx.nodesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n ),\n executeDdl(\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND (from_kind = ${kindLit} OR to_kind = ${kindLit})`,\n ),\n executeDdl(\n `DELETE FROM ${quote(ctx.fulltextTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n ),\n executeDdl(\n `DELETE FROM ${quote(ctx.uniquesTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n ),\n ...buildEmbeddingTableCleanup(ctx, row),\n );\n } else {\n deletes.push(\n executeDdl(\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n ),\n );\n }\n await Promise.all(deletes);\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 * 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\";\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 value !== null && value !== undefined;\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 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 { 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 // Override specific methods on the backend for validation caching.\n // The cast is necessary because spreading a union type (GraphBackend | TransactionBackend)\n // produces an intersection of their members, which TypeScript can't narrow back to the union.\n const validationBackend = {\n ...backend,\n getNode: getNodeCached,\n countEdgesFrom: countEdgesFromCached,\n edgeExistsBetween: edgeExistsBetweenCached,\n } as 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 (backend.insertEdgeNoReturn?.(prepared.insertParams) ??\n backend.insertEdge(prepared.insertParams));\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 if (backend.insertEdgesBatch === undefined) {\n for (const insertParams of batchInsertParams) {\n await (backend.insertEdgeNoReturn?.(insertParams) ??\n backend.insertEdge(insertParams));\n }\n return;\n }\n await backend.insertEdgesBatch(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 let rows: readonly BackendEdgeRow[];\n if (backend.insertEdgesBatchReturning === undefined) {\n const sequentialRows: BackendEdgeRow[] = [];\n for (const insertParams of batchInsertParams) {\n sequentialRows.push(await backend.insertEdge(insertParams));\n }\n rows = sequentialRows;\n } else {\n rows = await backend.insertEdgesBatchReturning(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 type GraphBackend,\n type InsertNodeParams,\n type NodeRow as BackendNodeRow,\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 { 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 { 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 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 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 // The cast is necessary because spreading a union type (GraphBackend | TransactionBackend)\n // produces an intersection of their members, which TypeScript can't narrow back to the union.\n const validationBackend = {\n ...backend,\n getNode: getNodeCached,\n checkUnique: checkUniqueCached,\n } as 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, async () => {\n const prepared = await validateAndPrepareNodeCreate(\n ctx,\n input,\n id,\n backend,\n );\n\n let row: BackendNodeRow | undefined;\n if (shouldReturnRow) {\n row = await backend.insertNode(prepared.insertParams);\n } else {\n await (backend.insertNodeNoReturn?.(prepared.insertParams) ??\n backend.insertNode(prepared.insertParams));\n }\n\n await finalizeNodeCreate(ctx, prepared, backend);\n\n if (row === undefined) return;\n return rowToNode(row);\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 const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n backend,\n );\n\n if (backend.insertNodesBatch === undefined) {\n for (const insertParams of batchInsertParams) {\n await (backend.insertNodeNoReturn?.(insertParams) ??\n backend.insertNode(insertParams));\n }\n } else {\n await backend.insertNodesBatch(batchInsertParams);\n }\n\n for (const prepared of preparedCreates) {\n await finalizeNodeCreate(ctx, prepared, backend);\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 const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n backend,\n );\n\n let rows: readonly BackendNodeRow[];\n if (backend.insertNodesBatchReturning === undefined) {\n const sequentialRows: BackendNodeRow[] = [];\n for (const insertParams of batchInsertParams) {\n sequentialRows.push(await backend.insertNode(insertParams));\n }\n rows = sequentialRows;\n } else {\n rows = await backend.insertNodesBatchReturning(batchInsertParams);\n }\n\n for (const prepared of preparedCreates) {\n await finalizeNodeCreate(ctx, prepared, backend);\n }\n\n return rows.map((row) => rowToNode(row));\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 performNodeUpdate(ctx, input, backend, options),\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 performNodeUpdate(ctx, input, backend, options);\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\n const existing = await backend.getNode(ctx.graphId, kind, id);\n if (!existing || existing.deleted_at) return;\n\n const existingProps = JSON.parse(existing.props) as Record<string, unknown>;\n\n await enforceDeleteBehavior(ctx, kind, id, \"soft\", backend, registration);\n\n await backend.deleteNode({ graphId: ctx.graphId, kind, id });\n\n await deleteUniquenessEntries(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n kind,\n existingProps,\n registration.unique ?? [],\n );\n\n const nodeKind = registration.type;\n await deleteNodeEmbeddings(\n createEmbeddingSyncContext(ctx.graphId, kind, id, backend),\n nodeKind.schema,\n );\n await deleteNodeFulltext(\n createFulltextSyncContext(ctx.graphId, kind, id, backend),\n nodeKind.schema,\n );\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\n const existing = await backend.getNode(ctx.graphId, kind, id);\n if (!existing) return;\n\n await enforceDeleteBehavior(ctx, kind, id, \"hard\", backend, registration);\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 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 (\"transaction\" in backend && backend.capabilities.transactions ?\n backend.transaction(async (tx) => hardDelete(tx))\n : hardDelete(backend));\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>(query);\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","/**\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 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 { type ReadCoordinate } from \"../core/temporal\";\nimport type { KindEntity, NodeId } 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 createQueryBuilder,\n type QueryBuilder,\n} from \"../query/builder\";\nimport { createSqlSchema } 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 { createGraphAlgorithms, type GraphAlgorithms } 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 { rowToEdge, rowToNode } from \"./row-mappers\";\nimport { StoreSearch } from \"./search-facade\";\nimport { StoreView, type StoreViewCoordinate } from \"./store-view\";\nimport {\n executeSubgraph,\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\n type DynamicEdgeCollection,\n type DynamicNodeCollection,\n type GraphEdgeCollections,\n type GraphNodeCollections,\n type HookContext,\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\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 readonly #backend: GraphBackend;\n readonly #registry: KindRegistry;\n readonly #hooks: StoreHooks;\n readonly #schema: StoreOptions[\"schema\"];\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.#backend = backend;\n this.#registry = buildKindRegistry(graph);\n this.#hooks = options?.hooks ?? {};\n this.#schema =\n options?.schema ??\n (backend.tableNames ? createSqlSchema(backend.tableNames) : undefined);\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 // === 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 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(): QueryBuilder<G> {\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): QueryBuilder<G> {\n return this.#createQueryForBackend(this.#backend, 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 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 return runOptionallyInTransaction(this.#backend, 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 return executeSubgraph({\n graph: this.#graph,\n graphId: this.graphId,\n rootId,\n backend: this.#backend,\n dialect: getDialect(this.#backend.dialect),\n schema: this.#schema,\n options,\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 *\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.\n */\n async transaction<T>(\n fn: (tx: TransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ): 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 fn({\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 fn(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 * @throws {ConfigurationError} when the backend cannot adopt an\n * external transaction — either it is not a Drizzle Postgres/SQLite\n * 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 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 * 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. `sql` is the\n * raw Drizzle handle bound to the same transaction (#140);\n * `undefined` only on the non-transactional fallback.\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 return sql === undefined ?\n { nodes, edges, backend: txBackend }\n : { nodes, edges, sql, 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.#backend.capabilities.transactions ?\n this.#backend.transaction(async (tx) => doClear(tx))\n : doClear(this.#backend));\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.#backend;\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.#backend,\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.#backend;\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 { graphId: this.graphId, backend: this.#backend },\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(graph, this.#backend, this.#options, schemaMetadata);\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 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(\n backend: GraphBackend | TransactionBackend,\n sealedCoordinate?: ReadCoordinate,\n ): QueryBuilder<G> {\n return createQueryBuilder<G>(this.graphId, this.#registry, {\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 ...(sealedCoordinate !== undefined && { sealedCoordinate }),\n });\n }\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a new Store instance.\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Optional store configuration including observability hooks\n * @returns A new Store instance\n *\n * @example\n * ```typescript\n * // Basic usage\n * const store = createStore(graph, backend);\n *\n * // With observability hooks\n * const store = createStore(graph, backend, {\n * hooks: {\n * onOperationStart: (ctx) => {\n * console.log(`Starting ${ctx.operation} on ${ctx.entity}:${ctx.kind}`);\n * },\n * onOperationEnd: (ctx, result) => {\n * console.log(`Completed in ${result.durationMs}ms`);\n * },\n * onError: (ctx, error) => {\n * console.error(`Operation ${ctx.operationId} failed:`, error);\n * },\n * },\n * });\n * ```\n */\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n): Store<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?: StoreOptions & SchemaManagerOptions,\n): Promise<[Store<G>, SchemaValidationResult]> {\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?: StoreOptions,\n): Promise<[Store<G>, SchemaValidationResult]> {\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"]}
|