@nicia-ai/typegraph 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/backend/postgres/index.cjs +19 -19
  2. package/dist/backend/postgres/index.d.cts +5 -5
  3. package/dist/backend/postgres/index.d.ts +5 -5
  4. package/dist/backend/postgres/index.js +9 -9
  5. package/dist/backend/postgres/pglite.cjs +14 -14
  6. package/dist/backend/postgres/pglite.d.cts +2 -2
  7. package/dist/backend/postgres/pglite.d.ts +2 -2
  8. package/dist/backend/postgres/pglite.js +9 -9
  9. package/dist/backend/sqlite/index.cjs +17 -17
  10. package/dist/backend/sqlite/index.d.cts +11 -6
  11. package/dist/backend/sqlite/index.d.ts +11 -6
  12. package/dist/backend/sqlite/index.js +8 -8
  13. package/dist/backend/sqlite/libsql.cjs +13 -13
  14. package/dist/backend/sqlite/libsql.d.cts +2 -2
  15. package/dist/backend/sqlite/libsql.d.ts +2 -2
  16. package/dist/backend/sqlite/libsql.js +9 -9
  17. package/dist/backend/sqlite/local.cjs +16 -15
  18. package/dist/backend/sqlite/local.cjs.map +1 -1
  19. package/dist/backend/sqlite/local.d.cts +8 -2
  20. package/dist/backend/sqlite/local.d.ts +8 -2
  21. package/dist/backend/sqlite/local.js +11 -10
  22. package/dist/backend/sqlite/local.js.map +1 -1
  23. package/dist/{chunk-UP4QAJND.cjs → chunk-26HWIIVS.cjs} +65 -65
  24. package/dist/{chunk-UP4QAJND.cjs.map → chunk-26HWIIVS.cjs.map} +1 -1
  25. package/dist/{chunk-GPUNAJFH.js → chunk-2QA5EHEN.js} +3 -3
  26. package/dist/{chunk-GPUNAJFH.js.map → chunk-2QA5EHEN.js.map} +1 -1
  27. package/dist/{chunk-CUZGBWFT.js → chunk-3IRMLJEK.js} +3 -3
  28. package/dist/{chunk-CUZGBWFT.js.map → chunk-3IRMLJEK.js.map} +1 -1
  29. package/dist/{chunk-MRMD7S7E.js → chunk-3JLRHQ67.js} +7 -7
  30. package/dist/{chunk-MRMD7S7E.js.map → chunk-3JLRHQ67.js.map} +1 -1
  31. package/dist/{chunk-UPBXUOW7.cjs → chunk-4BXHVEFB.cjs} +15 -15
  32. package/dist/{chunk-UPBXUOW7.cjs.map → chunk-4BXHVEFB.cjs.map} +1 -1
  33. package/dist/{chunk-RU5BBUU2.cjs → chunk-4LBO6KIF.cjs} +70 -67
  34. package/dist/chunk-4LBO6KIF.cjs.map +1 -0
  35. package/dist/{chunk-HKN622O4.js → chunk-633N7DSE.js} +9 -5
  36. package/dist/chunk-633N7DSE.js.map +1 -0
  37. package/dist/{chunk-R2LA6MKR.cjs → chunk-7JGLPAFV.cjs} +8 -8
  38. package/dist/{chunk-R2LA6MKR.cjs.map → chunk-7JGLPAFV.cjs.map} +1 -1
  39. package/dist/{chunk-7KLVFWXR.js → chunk-AI3RNREM.js} +30 -4
  40. package/dist/chunk-AI3RNREM.js.map +1 -0
  41. package/dist/{chunk-SFNUHFON.js → chunk-ENDUY2CD.js} +4 -4
  42. package/dist/{chunk-SFNUHFON.js.map → chunk-ENDUY2CD.js.map} +1 -1
  43. package/dist/{chunk-7V335GHG.cjs → chunk-FLRCVI2G.cjs} +12 -2
  44. package/dist/chunk-FLRCVI2G.cjs.map +1 -0
  45. package/dist/{chunk-IE2TPFBT.js → chunk-FVIGJTS7.js} +3 -3
  46. package/dist/{chunk-IE2TPFBT.js.map → chunk-FVIGJTS7.js.map} +1 -1
  47. package/dist/{chunk-Q5ASTPM4.cjs → chunk-FWBVPATK.cjs} +19 -19
  48. package/dist/{chunk-Q5ASTPM4.cjs.map → chunk-FWBVPATK.cjs.map} +1 -1
  49. package/dist/{chunk-KGAJ5HFO.cjs → chunk-IE6GN7L3.cjs} +17 -17
  50. package/dist/{chunk-KGAJ5HFO.cjs.map → chunk-IE6GN7L3.cjs.map} +1 -1
  51. package/dist/{chunk-A4H6QMV4.js → chunk-IUIJJYPI.js} +14 -11
  52. package/dist/chunk-IUIJJYPI.js.map +1 -0
  53. package/dist/{chunk-BMDF2S7S.js → chunk-IX7RE7CG.js} +3 -3
  54. package/dist/{chunk-BMDF2S7S.js.map → chunk-IX7RE7CG.js.map} +1 -1
  55. package/dist/{chunk-G6P3OVDY.cjs → chunk-JIEJCTDS.cjs} +18 -2
  56. package/dist/chunk-JIEJCTDS.cjs.map +1 -0
  57. package/dist/{chunk-XTQHSOIC.cjs → chunk-K4N35E7B.cjs} +86 -86
  58. package/dist/{chunk-XTQHSOIC.cjs.map → chunk-K4N35E7B.cjs.map} +1 -1
  59. package/dist/{chunk-NZ5PMBTG.js → chunk-K5P5OZXS.js} +12 -3
  60. package/dist/chunk-K5P5OZXS.js.map +1 -0
  61. package/dist/{chunk-Y52UNT66.js → chunk-K5VREXMZ.js} +7 -7
  62. package/dist/{chunk-Y52UNT66.js.map → chunk-K5VREXMZ.js.map} +1 -1
  63. package/dist/chunk-LUHU4T2F.cjs +12 -0
  64. package/dist/{chunk-Q3ZZLU3O.cjs.map → chunk-LUHU4T2F.cjs.map} +1 -1
  65. package/dist/{chunk-Z36W5WUM.js → chunk-MAQJYNJR.js} +3 -3
  66. package/dist/{chunk-Z36W5WUM.js.map → chunk-MAQJYNJR.js.map} +1 -1
  67. package/dist/{chunk-N3VVQDMA.js → chunk-MXE2U3EX.js} +3 -3
  68. package/dist/{chunk-N3VVQDMA.js.map → chunk-MXE2U3EX.js.map} +1 -1
  69. package/dist/{chunk-3DTLDGIM.js → chunk-N2OEOGBB.js} +6 -6
  70. package/dist/{chunk-3DTLDGIM.js.map → chunk-N2OEOGBB.js.map} +1 -1
  71. package/dist/{chunk-OGUH56BB.js → chunk-R4JOBEJU.js} +4 -4
  72. package/dist/{chunk-OGUH56BB.js.map → chunk-R4JOBEJU.js.map} +1 -1
  73. package/dist/{chunk-HM6XMR3E.cjs → chunk-SGPXKJ4A.cjs} +18 -18
  74. package/dist/{chunk-HM6XMR3E.cjs.map → chunk-SGPXKJ4A.cjs.map} +1 -1
  75. package/dist/{chunk-MB363HT5.js → chunk-TQOYM4LN.js} +18 -3
  76. package/dist/chunk-TQOYM4LN.js.map +1 -0
  77. package/dist/{chunk-C2RWFIYP.cjs → chunk-UESTHN47.cjs} +34 -6
  78. package/dist/chunk-UESTHN47.cjs.map +1 -0
  79. package/dist/{chunk-4K6IHUW6.cjs → chunk-VFX3LC76.cjs} +14 -14
  80. package/dist/{chunk-4K6IHUW6.cjs.map → chunk-VFX3LC76.cjs.map} +1 -1
  81. package/dist/{chunk-F2Q76CQ4.cjs → chunk-WEMZM7J7.cjs} +11 -7
  82. package/dist/chunk-WEMZM7J7.cjs.map +1 -0
  83. package/dist/{chunk-ZYQEXGYC.cjs → chunk-WFCECD6Q.cjs} +84 -84
  84. package/dist/{chunk-ZYQEXGYC.cjs.map → chunk-WFCECD6Q.cjs.map} +1 -1
  85. package/dist/{chunk-VGU26WIU.cjs → chunk-YQGLVWB2.cjs} +4 -4
  86. package/dist/{chunk-VGU26WIU.cjs.map → chunk-YQGLVWB2.cjs.map} +1 -1
  87. package/dist/{ddl-D3o-RmsV.d.cts → ddl-BSFlbGQF.d.cts} +3 -3
  88. package/dist/{ddl-BwH00BB6.d.ts → ddl-EdkIiFVU.d.ts} +3 -3
  89. package/dist/graph-extension/index.cjs +19 -19
  90. package/dist/graph-extension/index.d.cts +1 -1
  91. package/dist/graph-extension/index.d.ts +1 -1
  92. package/dist/graph-extension/index.js +4 -4
  93. package/dist/{index-CapHwi1a.d.ts → index-DzeIiMO3.d.ts} +9 -1
  94. package/dist/{index-jPPexxM5.d.cts → index-Ln_KHTGA.d.cts} +9 -1
  95. package/dist/index.cjs +780 -515
  96. package/dist/index.cjs.map +1 -1
  97. package/dist/index.d.cts +8 -8
  98. package/dist/index.d.ts +8 -8
  99. package/dist/index.js +314 -53
  100. package/dist/index.js.map +1 -1
  101. package/dist/indexes/index.cjs +18 -18
  102. package/dist/indexes/index.d.cts +4 -4
  103. package/dist/indexes/index.d.ts +4 -4
  104. package/dist/indexes/index.js +4 -4
  105. package/dist/interchange/index.cjs +7 -7
  106. package/dist/interchange/index.d.cts +3 -3
  107. package/dist/interchange/index.d.ts +3 -3
  108. package/dist/interchange/index.js +2 -2
  109. package/dist/{manager-BUugwCYz.d.ts → manager-BbdyNhkv.d.ts} +1 -1
  110. package/dist/{manager-DpIpn1HQ.d.cts → manager-wTDgjoXG.d.cts} +1 -1
  111. package/dist/{postgres-CQL9UIn2.d.cts → postgres-CK2ByP1q.d.cts} +1 -1
  112. package/dist/{postgres-CcRLaxz0.d.ts → postgres-ymXYC6Rr.d.ts} +1 -1
  113. package/dist/profiler/index.cjs +9 -9
  114. package/dist/profiler/index.d.cts +5 -5
  115. package/dist/profiler/index.d.ts +5 -5
  116. package/dist/profiler/index.js +2 -2
  117. package/dist/schema/index.cjs +31 -31
  118. package/dist/schema/index.d.cts +5 -5
  119. package/dist/schema/index.d.ts +5 -5
  120. package/dist/schema/index.js +8 -8
  121. package/dist/{sqlite-Rj3xu4It.d.cts → sqlite-DxH1lrwD.d.cts} +1 -1
  122. package/dist/{sqlite-CZDFUfHS.d.ts → sqlite-R8YGOqVQ.d.ts} +1 -1
  123. package/dist/{store-B43FpOVX.d.cts → store--z1Tmk7U.d.cts} +43 -3
  124. package/dist/{store-De0Y33wP.d.ts → store-CNKM334w.d.ts} +43 -3
  125. package/dist/{types-CmAT-Z47.d.ts → types-BBiDqJCU.d.ts} +2 -0
  126. package/dist/{types-B5GSeE3t.d.ts → types-CMvxx2kd.d.ts} +1 -1
  127. package/dist/{types-Bwlp_yvu.d.cts → types-D5B6Be5c.d.cts} +1 -1
  128. package/dist/{types-DXCSyxac.d.cts → types-dL-clxO3.d.cts} +2 -0
  129. package/dist/{where-CP4qGIHd.d.ts → where-CAo6wsBZ.d.ts} +1 -1
  130. package/dist/{where-2dsyYt3d.d.cts → where-bJjuOCeV.d.cts} +1 -1
  131. package/package.json +1 -1
  132. package/dist/chunk-7KLVFWXR.js.map +0 -1
  133. package/dist/chunk-7V335GHG.cjs.map +0 -1
  134. package/dist/chunk-A4H6QMV4.js.map +0 -1
  135. package/dist/chunk-C2RWFIYP.cjs.map +0 -1
  136. package/dist/chunk-F2Q76CQ4.cjs.map +0 -1
  137. package/dist/chunk-G6P3OVDY.cjs.map +0 -1
  138. package/dist/chunk-HKN622O4.js.map +0 -1
  139. package/dist/chunk-MB363HT5.js.map +0 -1
  140. package/dist/chunk-NZ5PMBTG.js.map +0 -1
  141. package/dist/chunk-Q3ZZLU3O.cjs +0 -12
  142. package/dist/chunk-RU5BBUU2.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkC2RWFIYP_cjs = require('./chunk-C2RWFIYP.cjs');
3
+ var chunkUESTHN47_cjs = require('./chunk-UESTHN47.cjs');
4
4
  var drizzleOrm = require('drizzle-orm');
5
5
 
6
6
  var TABLE_PREFIX = "tg_vec";
@@ -37,7 +37,7 @@ function sqliteVecMetricToken(metric) {
37
37
  }
38
38
  }
39
39
  function vecF32Literal(embedding, name) {
40
- chunkC2RWFIYP_cjs.assertFiniteEmbedding(embedding, name);
40
+ chunkUESTHN47_cjs.assertFiniteEmbedding(embedding, name);
41
41
  return drizzleOrm.sql`vec_f32(${JSON.stringify(embedding)})`;
42
42
  }
43
43
  function distanceExpression(embeddingColumn, queryEmbedding, metric) {
@@ -64,15 +64,15 @@ var sqliteVecStrategy = {
64
64
  name: "sqlite-vec",
65
65
  capabilities: SQLITE_VEC_CAPABILITIES,
66
66
  tableName(graphId, nodeKind, fieldPath) {
67
- return chunkC2RWFIYP_cjs.vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);
67
+ return chunkUESTHN47_cjs.vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);
68
68
  },
69
69
  ownedTables(slot) {
70
70
  const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);
71
- const name = chunkC2RWFIYP_cjs.quoteIdentifier(table);
71
+ const name = chunkUESTHN47_cjs.quoteIdentifier(table);
72
72
  const metric = sqliteVecMetricToken(slot.metric);
73
73
  return [
74
74
  {
75
- logicalName: `${chunkC2RWFIYP_cjs.VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,
75
+ logicalName: `${chunkUESTHN47_cjs.VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,
76
76
  owner: "sqlite-vec",
77
77
  tableName: table,
78
78
  createDdl: [
@@ -89,7 +89,7 @@ var sqliteVecStrategy = {
89
89
  ];
90
90
  },
91
91
  buildUpsert(slot, params, timestamp) {
92
- const table = chunkC2RWFIYP_cjs.quotedTableName(
92
+ const table = chunkUESTHN47_cjs.quotedTableName(
93
93
  this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
94
94
  );
95
95
  const value = vecF32Literal(params.embedding, "embedding");
@@ -105,7 +105,7 @@ var sqliteVecStrategy = {
105
105
  ];
106
106
  },
107
107
  buildDelete(slot, params) {
108
- const table = chunkC2RWFIYP_cjs.quotedTableName(
108
+ const table = chunkUESTHN47_cjs.quotedTableName(
109
109
  this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
110
110
  );
111
111
  return [
@@ -116,7 +116,7 @@ var sqliteVecStrategy = {
116
116
  ];
117
117
  },
118
118
  buildSearch(slot, params) {
119
- const table = chunkC2RWFIYP_cjs.quotedTableName(
119
+ const table = chunkUESTHN47_cjs.quotedTableName(
120
120
  this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
121
121
  );
122
122
  const embeddingColumn = drizzleOrm.sql`${table}."embedding"`;
@@ -125,7 +125,7 @@ var sqliteVecStrategy = {
125
125
  params.queryEmbedding,
126
126
  params.metric
127
127
  );
128
- const score = chunkC2RWFIYP_cjs.vectorScoreExpression(distance, params.metric);
128
+ const score = chunkUESTHN47_cjs.vectorScoreExpression(distance, params.metric);
129
129
  if (usesAnnIndex(slot)) {
130
130
  const query = vecF32Literal(params.queryEmbedding, "queryEmbedding");
131
131
  const conditions2 = [
@@ -135,7 +135,7 @@ var sqliteVecStrategy = {
135
135
  ];
136
136
  if (params.minScore !== void 0) {
137
137
  conditions2.push(
138
- chunkC2RWFIYP_cjs.vectorMinScoreCondition(distance, params.metric, params.minScore)
138
+ chunkUESTHN47_cjs.vectorMinScoreCondition(distance, params.metric, params.minScore)
139
139
  );
140
140
  }
141
141
  return drizzleOrm.sql`
@@ -148,7 +148,7 @@ var sqliteVecStrategy = {
148
148
  const conditions = [drizzleOrm.sql`${table}."graph_id" = ${params.graphId}`];
149
149
  if (params.minScore !== void 0) {
150
150
  conditions.push(
151
- chunkC2RWFIYP_cjs.vectorMinScoreCondition(distance, params.metric, params.minScore)
151
+ chunkUESTHN47_cjs.vectorMinScoreCondition(distance, params.metric, params.minScore)
152
152
  );
153
153
  }
154
154
  return drizzleOrm.sql`
@@ -171,7 +171,7 @@ var sqliteVecStrategy = {
171
171
  return void 0;
172
172
  },
173
173
  buildDropStorage(slot) {
174
- const table = chunkC2RWFIYP_cjs.quoteIdentifier(
174
+ const table = chunkUESTHN47_cjs.quoteIdentifier(
175
175
  this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
176
176
  );
177
177
  return [`DROP TABLE IF EXISTS ${table}`];
@@ -179,5 +179,5 @@ var sqliteVecStrategy = {
179
179
  };
180
180
 
181
181
  exports.sqliteVecStrategy = sqliteVecStrategy;
182
- //# sourceMappingURL=chunk-4K6IHUW6.cjs.map
183
- //# sourceMappingURL=chunk-4K6IHUW6.cjs.map
182
+ //# sourceMappingURL=chunk-VFX3LC76.cjs.map
183
+ //# sourceMappingURL=chunk-VFX3LC76.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/query/dialect/vector/sqlite-vec-strategy.ts"],"names":["assertFiniteEmbedding","sql","vectorPhysicalName","quoteIdentifier","VECTOR_CONTRIBUTION_PREFIX","quotedTableName","vectorScoreExpression","conditions","vectorMinScoreCondition"],"mappings":";;;;;AA6EA,IAAM,YAAA,GAAe,QAAA;A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,CAAA,cAAA,EAAiB,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AACvE,IAAA,IAAI,MAAA,CAAO,aAAa,MAAA,EAAW;AACjC,MAAA,UAAA,CAAW,IAAA;AAAA,QACTO,yCAAA,CAAwB,QAAA,EAAU,MAAA,CAAO,MAAA,EAAQ,OAAO,QAAQ;AAAA,OAClE;AAAA,IACF;AACA,IAAA,OAAOP,cAAA;AAAA,aAAA,EACI,KAAK,0BAA0B,KAAK,CAAA;AAAA,WAAA,EACtC,KAAK;AAAA,YAAA,EACJA,cAAA,CAAI,IAAA,CAAK,UAAA,EAAYA,cAAA,CAAA,KAAA,CAAU,CAAC;AAAA,eAAA,EAC7B,QAAQ,CAAA;AAAA,YAAA,EACX,OAAO,KAAK;AAAA,IAAA,CAAA;AAAA,EAExB,CAAA;AAAA,EAEA,kBAAA,CAAmB,eAAA,EAAiB,cAAA,EAAgB,MAAA,EAAQ;AAC1D,IAAA,OAAO,kBAAA,CAAmB,eAAA,EAAiB,cAAA,EAAgB,MAAM,CAAA;AAAA,EACnE,CAAA;AAAA;AAAA;AAAA,EAIA,gBAAA,GAAoC;AAClC,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AAAA,EAEA,cAAA,GAAkC;AAChC,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AAAA,EAEA,iBAAiB,IAAA,EAAyB;AACxC,IAAA,MAAM,KAAA,GAAQE,iCAAA;AAAA,MACZ,KAAK,SAAA,CAAU,IAAA,CAAK,SAAS,IAAA,CAAK,QAAA,EAAU,KAAK,SAAS;AAAA,KAC5D;AAEA,IAAA,OAAO,CAAC,CAAA,qBAAA,EAAwB,KAAK,CAAA,CAAE,CAAA;AAAA,EACzC;AACF","file":"chunk-4K6IHUW6.cjs","sourcesContent":["/**\n * sqlite-vec strategy — real `vec0` KNN for local SQLite.\n *\n * This upgrades `createLocalSqliteBackend` (better-sqlite3 + the sqlite-vec\n * extension) from the legacy brute-force-on-a-shared-table model to genuine\n * approximate-nearest-neighbor search on per-`(nodeKind, fieldPath)` storage.\n *\n * ## Storage choice: a `vec0` virtual table per field\n *\n * Each slot is backed by its own `vec0` virtual table:\n *\n * ```sql\n * CREATE VIRTUAL TABLE tg_vec_<kind>_<field> USING vec0(\n * node_id TEXT PRIMARY KEY,\n * graph_id TEXT PARTITION KEY,\n * +created_at TEXT,\n * +updated_at TEXT,\n * embedding float[<N>] distance_metric=<cosine|l2>\n * );\n * ```\n *\n * Verified against the installed `sqlite-vec` `v0.1.9`:\n *\n * - **vec0 over a plain `vec_f32` BLOB column.** The shipped option (a) — a\n * `vec0` virtual table — is chosen over option (b) — a regular table whose\n * `vec_f32` BLOB column is brute-forced — because vec0 is the *only* form\n * that gives local SQLite a real ANN index (today's code only ever\n * brute-forces). vec0 indexes inline (the virtual table *is* the index), so\n * there is no separate `CREATE INDEX` step.\n * - **KNN with partition-correct filtering.** `WHERE embedding MATCH vec_f32(q)\n * AND k = ? AND graph_id = ?` returns the nearest `k`, ordered by `distance`,\n * scoped to one graph — a near vector in another `graph_id` partition does\n * not leak. This is strictly better than libSQL's table-global `vector_top_k`\n * (which over-fetches for multi-graph correctness): vec0's `PARTITION KEY`\n * makes the per-graph KNN exact.\n * - **One table serves both read paths.** The same `embedding` column answers\n * the compiler's brute-force `distanceExpression` (`vec_distance_cosine` /\n * `vec_distance_l2` over the column, `ORDER BY … LIMIT`, no `MATCH`), so the\n * `.where(field.similarTo(...))` CTE path needs no second structure.\n * - **`k` and `LIMIT` are mutually exclusive** in a vec0 `MATCH` query, so the\n * ANN path uses `k = <limit>` with no `LIMIT`, and the brute-force path uses\n * `LIMIT <limit>` with no `MATCH`.\n * - **No `ON CONFLICT` / `INSERT OR REPLACE`** on a vec0 primary key, so upsert\n * is `DELETE` + `INSERT` (atomic under the caller's outer transaction),\n * mirroring the FTS5 strategy.\n *\n * Metric support is `cosine` + `l2` (no `inner_product` — sqlite-vec has no\n * `vec_distance_ip`), advertised as data on `capabilities`. The table's\n * `distance_metric` is fixed at creation from the slot's metric, alongside its\n * fixed dimension `N`.\n *\n * The libSQL and pgvector siblings implement the same `VectorStrategy`\n * contract for their engines.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { quotedTableName } from \"../../../backend/drizzle/operations/shared\";\nimport { type StrategyTableContribution } from \"../../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../../backend/types\";\nimport {\n assertFiniteEmbedding,\n quoteIdentifier,\n VECTOR_CONTRIBUTION_PREFIX,\n vectorMinScoreCondition,\n vectorPhysicalName,\n vectorScoreExpression,\n type VectorSlot,\n type VectorStrategy,\n} from \"../vector-strategy\";\n\n/** Physical-name prefix for the per-field `vec0` virtual table. */\nconst TABLE_PREFIX = \"tg_vec\";\n\n/**\n * sqlite-vec stores each dimension as a 32-bit float; `float[N]` accepts\n * large `N`, but we advertise the same conservative ceiling the legacy\n * SQLite path used so capability discovery is stable across the swap.\n */\nconst SQLITE_VEC_MAX_DIMENSIONS = 8000;\n\nconst SQLITE_VEC_CAPABILITIES: VectorCapabilities = {\n supported: true,\n metrics: [\"cosine\", \"l2\"],\n // vec0 always indexes inline, so the portable ANN intent (\"hnsw\", the\n // `embedding()` default) is honored by real KNN; \"none\" stays brute-force.\n // Both map to the same vec0 table — only `buildSearch` differs.\n indexTypes: [\"hnsw\", \"none\"],\n maxDimensions: SQLITE_VEC_MAX_DIMENSIONS,\n};\n\n/** Whether a slot's declared index type maps to vec0's `MATCH … k =` KNN. */\nfunction usesAnnIndex(slot: VectorSlot): boolean {\n return slot.indexType === \"hnsw\";\n}\n\n/** vec0 `distance_metric` token accepted in the virtual-table definition. */\nfunction sqliteVecMetricToken(metric: VectorMetric): string {\n switch (metric) {\n case \"cosine\": {\n return \"cosine\";\n }\n case \"l2\": {\n return \"l2\";\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Formats an embedding as the bound JSON argument to `vec_f32(...)`. The\n * value rides as a parameter (not interpolated) — `vec_f32` parses the JSON\n * array into the packed float blob. Finiteness is validated first so a\n * NaN/Infinity names its index before JSON.stringify masks it as `null`.\n */\nfunction vecF32Literal(embedding: readonly number[], name: string): SQL {\n assertFiniteEmbedding(embedding, name);\n return sql`vec_f32(${JSON.stringify(embedding)})`;\n}\n\nfunction distanceExpression(\n embeddingColumn: SQL,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n): SQL {\n const query = vecF32Literal(queryEmbedding, \"queryEmbedding\");\n switch (metric) {\n case \"cosine\": {\n return sql`vec_distance_cosine(${embeddingColumn}, ${query})`;\n }\n case \"l2\": {\n return sql`vec_distance_l2(${embeddingColumn}, ${query})`;\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const sqliteVecStrategy: VectorStrategy = {\n name: \"sqlite-vec\",\n capabilities: SQLITE_VEC_CAPABILITIES,\n\n tableName(graphId, nodeKind, fieldPath) {\n return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);\n },\n\n ownedTables(slot): readonly StrategyTableContribution[] {\n const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);\n const name = quoteIdentifier(table);\n const metric = sqliteVecMetricToken(slot.metric);\n\n // vec0 virtual tables cannot be modeled as a Drizzle table, so this is a\n // raw-ddl contribution — emitted verbatim and invisible to drizzle-kit.\n // `graph_id` is a PARTITION KEY so per-graph KNN is exact; `created_at` /\n // `updated_at` are auxiliary (`+`) columns (stored, not filtered on). The\n // virtual table *is* the index — no separate CREATE INDEX is emitted.\n return [\n {\n logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,\n owner: \"sqlite-vec\",\n tableName: table,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING vec0(\n node_id TEXT PRIMARY KEY,\n graph_id TEXT PARTITION KEY,\n +created_at TEXT,\n +updated_at TEXT,\n embedding float[${slot.dimensions}] distance_metric=${metric}\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(slot, params: UpsertEmbeddingParams, timestamp): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const value = vecF32Literal(params.embedding, \"embedding\");\n // vec0 rejects ON CONFLICT / INSERT OR REPLACE on its primary key —\n // emulate upsert with DELETE + INSERT, atomic under the caller's\n // outer transaction (mirrors the FTS5 fulltext strategy).\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n sql`\n INSERT INTO ${table} (\"node_id\", \"graph_id\", \"created_at\", \"updated_at\", \"embedding\")\n VALUES (${params.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${value})\n `,\n ];\n },\n\n buildDelete(slot, params: DeleteEmbeddingParams): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n ];\n },\n\n buildSearch(slot, params: VectorSearchParams): SQL {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const embeddingColumn = sql`${table}.\"embedding\"`;\n const distance = distanceExpression(\n embeddingColumn,\n params.queryEmbedding,\n params.metric,\n );\n const score = vectorScoreExpression(distance, params.metric);\n\n if (usesAnnIndex(slot)) {\n // vec0 KNN. `k` and `LIMIT` are mutually exclusive in a MATCH query, so\n // bound `k = limit` and omit LIMIT. `graph_id` filters by the partition\n // key (exact, no recall loss). Order by vec0's own `distance` column —\n // the recomputed `distance` expression is reused only for score/minScore\n // so the math matches the brute-force path and the shared helpers.\n const query = vecF32Literal(params.queryEmbedding, \"queryEmbedding\");\n const conditions: SQL[] = [\n sql`${table}.\"embedding\" MATCH ${query}`,\n sql`k = ${params.limit}`,\n sql`${table}.\"graph_id\" = ${params.graphId}`,\n ];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY distance ASC\n `;\n }\n\n // Brute-force scan: no MATCH, so LIMIT is allowed (and required).\n const conditions: SQL[] = [sql`${table}.\"graph_id\" = ${params.graphId}`];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY ${distance} ASC\n LIMIT ${params.limit}\n `;\n },\n\n distanceExpression(embeddingColumn, queryEmbedding, metric) {\n return distanceExpression(embeddingColumn, queryEmbedding, metric);\n },\n\n // vec0 indexes inline (the virtual table is the index), so there is no\n // standalone ANN index to create or drop — both return undefined.\n buildCreateIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropStorage(slot): readonly string[] {\n const table = quoteIdentifier(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // Dropping the vec0 virtual table removes its backing shadow tables too.\n return [`DROP TABLE IF EXISTS ${table}`];\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/query/dialect/vector/sqlite-vec-strategy.ts"],"names":["assertFiniteEmbedding","sql","vectorPhysicalName","quoteIdentifier","VECTOR_CONTRIBUTION_PREFIX","quotedTableName","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alSqliteBackend` (better-sqlite3 + the sqlite-vec\n * extension) from the legacy brute-force-on-a-shared-table model to genuine\n * approximate-nearest-neighbor search on per-`(nodeKind, fieldPath)` storage.\n *\n * ## Storage choice: a `vec0` virtual table per field\n *\n * Each slot is backed by its own `vec0` virtual table:\n *\n * ```sql\n * CREATE VIRTUAL TABLE tg_vec_<kind>_<field> USING vec0(\n * node_id TEXT PRIMARY KEY,\n * graph_id TEXT PARTITION KEY,\n * +created_at TEXT,\n * +updated_at TEXT,\n * embedding float[<N>] distance_metric=<cosine|l2>\n * );\n * ```\n *\n * Verified against the installed `sqlite-vec` `v0.1.9`:\n *\n * - **vec0 over a plain `vec_f32` BLOB column.** The shipped option (a) — a\n * `vec0` virtual table — is chosen over option (b) — a regular table whose\n * `vec_f32` BLOB column is brute-forced — because vec0 is the *only* form\n * that gives local SQLite a real ANN index (today's code only ever\n * brute-forces). vec0 indexes inline (the virtual table *is* the index), so\n * there is no separate `CREATE INDEX` step.\n * - **KNN with partition-correct filtering.** `WHERE embedding MATCH vec_f32(q)\n * AND k = ? AND graph_id = ?` returns the nearest `k`, ordered by `distance`,\n * scoped to one graph — a near vector in another `graph_id` partition does\n * not leak. This is strictly better than libSQL's table-global `vector_top_k`\n * (which over-fetches for multi-graph correctness): vec0's `PARTITION KEY`\n * makes the per-graph KNN exact.\n * - **One table serves both read paths.** The same `embedding` column answers\n * the compiler's brute-force `distanceExpression` (`vec_distance_cosine` /\n * `vec_distance_l2` over the column, `ORDER BY … LIMIT`, no `MATCH`), so the\n * `.where(field.similarTo(...))` CTE path needs no second structure.\n * - **`k` and `LIMIT` are mutually exclusive** in a vec0 `MATCH` query, so the\n * ANN path uses `k = <limit>` with no `LIMIT`, and the brute-force path uses\n * `LIMIT <limit>` with no `MATCH`.\n * - **No `ON CONFLICT` / `INSERT OR REPLACE`** on a vec0 primary key, so upsert\n * is `DELETE` + `INSERT` (atomic under the caller's outer transaction),\n * mirroring the FTS5 strategy.\n *\n * Metric support is `cosine` + `l2` (no `inner_product` — sqlite-vec has no\n * `vec_distance_ip`), advertised as data on `capabilities`. The table's\n * `distance_metric` is fixed at creation from the slot's metric, alongside its\n * fixed dimension `N`.\n *\n * The libSQL and pgvector siblings implement the same `VectorStrategy`\n * contract for their engines.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { quotedTableName } from \"../../../backend/drizzle/operations/shared\";\nimport { type StrategyTableContribution } from \"../../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../../backend/types\";\nimport {\n assertFiniteEmbedding,\n quoteIdentifier,\n VECTOR_CONTRIBUTION_PREFIX,\n vectorMinScoreCondition,\n vectorPhysicalName,\n vectorScoreExpression,\n type VectorSlot,\n type VectorStrategy,\n} from \"../vector-strategy\";\n\n/** Physical-name prefix for the per-field `vec0` virtual table. */\nconst TABLE_PREFIX = \"tg_vec\";\n\n/**\n * sqlite-vec stores each dimension as a 32-bit float; `float[N]` accepts\n * large `N`, but we advertise the same conservative ceiling the legacy\n * SQLite path used so capability discovery is stable across the swap.\n */\nconst SQLITE_VEC_MAX_DIMENSIONS = 8000;\n\nconst SQLITE_VEC_CAPABILITIES: VectorCapabilities = {\n supported: true,\n metrics: [\"cosine\", \"l2\"],\n // vec0 always indexes inline, so the portable ANN intent (\"hnsw\", the\n // `embedding()` default) is honored by real KNN; \"none\" stays brute-force.\n // Both map to the same vec0 table — only `buildSearch` differs.\n indexTypes: [\"hnsw\", \"none\"],\n maxDimensions: SQLITE_VEC_MAX_DIMENSIONS,\n};\n\n/** Whether a slot's declared index type maps to vec0's `MATCH … k =` KNN. */\nfunction usesAnnIndex(slot: VectorSlot): boolean {\n return slot.indexType === \"hnsw\";\n}\n\n/** vec0 `distance_metric` token accepted in the virtual-table definition. */\nfunction sqliteVecMetricToken(metric: VectorMetric): string {\n switch (metric) {\n case \"cosine\": {\n return \"cosine\";\n }\n case \"l2\": {\n return \"l2\";\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Formats an embedding as the bound JSON argument to `vec_f32(...)`. The\n * value rides as a parameter (not interpolated) — `vec_f32` parses the JSON\n * array into the packed float blob. Finiteness is validated first so a\n * NaN/Infinity names its index before JSON.stringify masks it as `null`.\n */\nfunction vecF32Literal(embedding: readonly number[], name: string): SQL {\n assertFiniteEmbedding(embedding, name);\n return sql`vec_f32(${JSON.stringify(embedding)})`;\n}\n\nfunction distanceExpression(\n embeddingColumn: SQL,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n): SQL {\n const query = vecF32Literal(queryEmbedding, \"queryEmbedding\");\n switch (metric) {\n case \"cosine\": {\n return sql`vec_distance_cosine(${embeddingColumn}, ${query})`;\n }\n case \"l2\": {\n return sql`vec_distance_l2(${embeddingColumn}, ${query})`;\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const sqliteVecStrategy: VectorStrategy = {\n name: \"sqlite-vec\",\n capabilities: SQLITE_VEC_CAPABILITIES,\n\n tableName(graphId, nodeKind, fieldPath) {\n return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);\n },\n\n ownedTables(slot): readonly StrategyTableContribution[] {\n const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);\n const name = quoteIdentifier(table);\n const metric = sqliteVecMetricToken(slot.metric);\n\n // vec0 virtual tables cannot be modeled as a Drizzle table, so this is a\n // raw-ddl contribution — emitted verbatim and invisible to drizzle-kit.\n // `graph_id` is a PARTITION KEY so per-graph KNN is exact; `created_at` /\n // `updated_at` are auxiliary (`+`) columns (stored, not filtered on). The\n // virtual table *is* the index — no separate CREATE INDEX is emitted.\n return [\n {\n logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,\n owner: \"sqlite-vec\",\n tableName: table,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING vec0(\n node_id TEXT PRIMARY KEY,\n graph_id TEXT PARTITION KEY,\n +created_at TEXT,\n +updated_at TEXT,\n embedding float[${slot.dimensions}] distance_metric=${metric}\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(slot, params: UpsertEmbeddingParams, timestamp): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const value = vecF32Literal(params.embedding, \"embedding\");\n // vec0 rejects ON CONFLICT / INSERT OR REPLACE on its primary key —\n // emulate upsert with DELETE + INSERT, atomic under the caller's\n // outer transaction (mirrors the FTS5 fulltext strategy).\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n sql`\n INSERT INTO ${table} (\"node_id\", \"graph_id\", \"created_at\", \"updated_at\", \"embedding\")\n VALUES (${params.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${value})\n `,\n ];\n },\n\n buildDelete(slot, params: DeleteEmbeddingParams): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n ];\n },\n\n buildSearch(slot, params: VectorSearchParams): SQL {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const embeddingColumn = sql`${table}.\"embedding\"`;\n const distance = distanceExpression(\n embeddingColumn,\n params.queryEmbedding,\n params.metric,\n );\n const score = vectorScoreExpression(distance, params.metric);\n\n if (usesAnnIndex(slot)) {\n // vec0 KNN. `k` and `LIMIT` are mutually exclusive in a MATCH query, so\n // bound `k = limit` and omit LIMIT. `graph_id` filters by the partition\n // key (exact, no recall loss). Order by vec0's own `distance` column —\n // the recomputed `distance` expression is reused only for score/minScore\n // so the math matches the brute-force path and the shared helpers.\n const query = vecF32Literal(params.queryEmbedding, \"queryEmbedding\");\n const conditions: SQL[] = [\n sql`${table}.\"embedding\" MATCH ${query}`,\n sql`k = ${params.limit}`,\n sql`${table}.\"graph_id\" = ${params.graphId}`,\n ];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY distance ASC\n `;\n }\n\n // Brute-force scan: no MATCH, so LIMIT is allowed (and required).\n const conditions: SQL[] = [sql`${table}.\"graph_id\" = ${params.graphId}`];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY ${distance} ASC\n LIMIT ${params.limit}\n `;\n },\n\n distanceExpression(embeddingColumn, queryEmbedding, metric) {\n return distanceExpression(embeddingColumn, queryEmbedding, metric);\n },\n\n // vec0 indexes inline (the virtual table is the index), so there is no\n // standalone ANN index to create or drop — both return undefined.\n buildCreateIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropStorage(slot): readonly string[] {\n const table = quoteIdentifier(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // Dropping the vec0 virtual table removes its backing shadow tables too.\n return [`DROP TABLE IF EXISTS ${table}`];\n },\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkC2RWFIYP_cjs = require('./chunk-C2RWFIYP.cjs');
3
+ var chunkUESTHN47_cjs = require('./chunk-UESTHN47.cjs');
4
4
  var drizzleOrm = require('drizzle-orm');
5
5
  var sqliteCore = require('drizzle-orm/sqlite-core');
6
6
 
@@ -44,7 +44,7 @@ function createSqliteTables(names = {}, options = {}) {
44
44
  ),
45
45
  sqliteCore.index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),
46
46
  sqliteCore.index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),
47
- ...chunkC2RWFIYP_cjs.buildSqliteNodeIndexBuilders(t, indexes)
47
+ ...chunkUESTHN47_cjs.buildSqliteNodeIndexBuilders(t, indexes)
48
48
  ]
49
49
  );
50
50
  const edges2 = sqliteCore.sqliteTable(
@@ -103,7 +103,7 @@ function createSqliteTables(names = {}, options = {}) {
103
103
  t.fromId,
104
104
  t.validTo
105
105
  ),
106
- ...chunkC2RWFIYP_cjs.buildSqliteEdgeIndexBuilders(t, indexes)
106
+ ...chunkUESTHN47_cjs.buildSqliteEdgeIndexBuilders(t, indexes)
107
107
  ]
108
108
  );
109
109
  const uniques2 = sqliteCore.sqliteTable(
@@ -243,12 +243,16 @@ async function runOptionallyInTransaction(backend, fn, fallback) {
243
243
  return backend.transaction((tx) => fn(tx));
244
244
  }
245
245
  var SQLITE_CAPABILITIES = {
246
- transactions: true
246
+ transactions: true,
247
247
  // SQLite supports transactions
248
+ windowFunctions: true
249
+ // SQLite has supported window functions since 3.25.0
248
250
  };
249
251
  var POSTGRES_CAPABILITIES = {
250
- transactions: true
252
+ transactions: true,
251
253
  // PostgreSQL supports transactions
254
+ windowFunctions: true
255
+ // PostgreSQL supports ROW_NUMBER() and related windows
252
256
  };
253
257
 
254
258
  exports.LEGACY_EMBEDDINGS_TABLE_NAME = LEGACY_EMBEDDINGS_TABLE_NAME;
@@ -262,5 +266,5 @@ exports.schemaVersions = schemaVersions;
262
266
  exports.tables = tables;
263
267
  exports.uniques = uniques;
264
268
  exports.wrapWithManagedClose = wrapWithManagedClose;
265
- //# sourceMappingURL=chunk-F2Q76CQ4.cjs.map
266
- //# sourceMappingURL=chunk-F2Q76CQ4.cjs.map
269
+ //# sourceMappingURL=chunk-WEMZM7J7.cjs.map
270
+ //# sourceMappingURL=chunk-WEMZM7J7.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/drizzle/schema/sqlite.ts","../src/backend/types.ts"],"names":["nodes","sqliteTable","text","integer","primaryKey","index","buildSqliteNodeIndexBuilders","edges","buildSqliteEdgeIndexBuilders","uniques","schemaVersions","uniqueIndex","sql"],"mappings":";;;;;;AAyDO,IAAM,4BAAA,GAA+B;AAY5C,IAAM,mBAAA,GAAwC;AAAA,EAC5C,KAAA,EAAO,iBAAA;AAAA,EACP,KAAA,EAAO,iBAAA;AAAA,EACP,OAAA,EAAS,wBAAA;AAAA,EACT,cAAA,EAAgB,2BAAA;AAAA,EAChB,QAAA,EAAU,yBAAA;AAAA,EACV,qBAAA,EAAuB,kCAAA;AAAA,EACvB,4BAAA,EAA8B,yCAAA;AAAA,EAC9B,YAAA,EAAc,yBAAA;AAAA,EACd,qBAAA,EAAuB;AACzB,CAAA;AAMO,SAAS,mBACd,KAAA,GAAmC,EAAC,EACpC,OAAA,GAAqC,EAAC,EACtC;AACA,EAAA,MAAM,CAAA,GAAsB,EAAE,GAAG,mBAAA,EAAqB,GAAG,KAAA,EAAM;AAC/D,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,IAAW,EAAC;AAEpC,EAAA,MAAMA,MAAAA,GAAQC,sBAAA;AAAA,IACZ,CAAA,CAAE,KAAA;AAAA,IACF;AAAA,MACE,OAAA,EAASC,eAAA,CAAK,UAAU,CAAA,CAAE,OAAA,EAAQ;AAAA,MAClC,IAAA,EAAMA,eAAA,CAAK,MAAM,CAAA,CAAE,OAAA,EAAQ;AAAA,MAC3B,EAAA,EAAIA,eAAA,CAAK,IAAI,CAAA,CAAE,OAAA,EAAQ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,MAAAA;AAAA,IACA,KAAA,EAAAO,MAAAA;AAAA,IACA,OAAA,EAAAE,QAAAA;AAAA,IACA,cAAA,EAAAC,eAAAA;AAAA,IACA,qBAAA;AAAA,IACA,4BAAA;AAAA,IACA,YAAA;AAAA,IACA,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,mBAAmB,CAAA,CAAE;AAAA,GACvB;AACF;AAKO,IAAM,SAAS,kBAAA;AAKf,IAAM,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,gBAAe,GAAI;;;ACk1BlD,SAAS,oBAAA,CACd,SACA,QAAA,EACc;AACd,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,GAAG,OAAA;AAAA,IACH,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAM,QAAQ,KAAA,EAAM;AACpB,MAAA,MAAM,QAAA,EAAS;AAAA,IACjB;AAAA,GACF;AACF;AAeA,eAAsB,0BAAA,CACpB,OAAA,EACA,EAAA,EACA,QAAA,EACY;AACZ,EAAA,IAAI,CAAC,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc;AACtC,IAAA,OAAO,EAAA,CAAG,YAAY,OAAO,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,QAAQ,WAAA,CAAY,CAAC,EAAA,KAAO,EAAA,CAAG,EAAE,CAAC,CAAA;AAC3C;AA4OO,IAAM,mBAAA,GAA2C;AAAA,EACtD,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB;AAAA;AACnB;AAKO,IAAM,qBAAA,GAA6C;AAAA,EACxD,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB;AAAA;AACnB","file":"chunk-WEMZM7J7.cjs","sourcesContent":["/**\n * Drizzle SQLite schema for TypeGraph.\n *\n * Provides table definitions that can be customized via the factory function.\n * Users import these tables into their Drizzle schema and use drizzle-kit\n * for migrations.\n *\n * @example\n * ```typescript\n * // Default table names\n * import { tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * // Custom table names\n * import { createSqliteTables } from \"@nicia-ai/typegraph/sqlite\";\n * const tables = createSqliteTables({\n * nodes: \"myapp_nodes\",\n * edges: \"myapp_edges\",\n * });\n * ```\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nimport {\n buildSqliteEdgeIndexBuilders,\n buildSqliteNodeIndexBuilders,\n type IndexDeclaration,\n} from \"../../../indexes\";\n\n/**\n * Table name configuration.\n */\nexport type SqliteTableNames = Readonly<{\n nodes: string;\n edges: string;\n uniques: string;\n schemaVersions: string;\n fulltext: string;\n indexMaterializations: string;\n contributionMaterializations: string;\n kindRemovals: string;\n reconciliationMarkers: string;\n}>;\n\n/**\n * Physical name of the legacy single shared embeddings table, dropped in\n * the cross-backend vector cutover (the clean cut of #157). Strategies now\n * own per-`(nodeKind, fieldPath)` typed storage. Retained only so the\n * one-time migration utility can address and drain the old table.\n */\nexport const LEGACY_EMBEDDINGS_TABLE_NAME = \"typegraph_node_embeddings\";\n\nexport type CreateSqliteTablesOptions = Readonly<{\n /**\n * Additional TypeGraph indexes to include in the Drizzle schema.\n *\n * These become first-class Drizzle indexes, so drizzle-kit migrations will\n * pick them up automatically.\n */\n indexes?: readonly IndexDeclaration[] | undefined;\n}>;\n\nconst DEFAULT_TABLE_NAMES: SqliteTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n uniques: \"typegraph_node_uniques\",\n schemaVersions: \"typegraph_schema_versions\",\n fulltext: \"typegraph_node_fulltext\",\n indexMaterializations: \"typegraph_index_materializations\",\n contributionMaterializations: \"typegraph_contribution_materializations\",\n kindRemovals: \"typegraph_kind_removals\",\n reconciliationMarkers: \"typegraph_reconciliation_markers\",\n};\n\n/**\n * Creates SQLite table definitions with customizable table names.\n * Index names are derived from table names.\n */\nexport function createSqliteTables(\n names: Partial<SqliteTableNames> = {},\n options: CreateSqliteTablesOptions = {},\n) {\n const n: SqliteTableNames = { ...DEFAULT_TABLE_NAMES, ...names };\n const indexes = options.indexes ?? [];\n\n const nodes = sqliteTable(\n n.nodes,\n {\n graphId: text(\"graph_id\").notNull(),\n kind: text(\"kind\").notNull(),\n id: text(\"id\").notNull(),\n props: text(\"props\").notNull(),\n version: integer(\"version\").notNull().default(1),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.kind, t.id] }),\n index(`${n.nodes}_kind_idx`).on(t.graphId, t.kind),\n index(`${n.nodes}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n ...buildSqliteNodeIndexBuilders(t, indexes),\n ],\n );\n\n const edges = sqliteTable(\n n.edges,\n {\n graphId: text(\"graph_id\").notNull(),\n id: text(\"id\").notNull(),\n kind: text(\"kind\").notNull(),\n fromKind: text(\"from_kind\").notNull(),\n fromId: text(\"from_id\").notNull(),\n toKind: text(\"to_kind\").notNull(),\n toId: text(\"to_id\").notNull(),\n props: text(\"props\").notNull(),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.id] }),\n index(`${n.edges}_kind_idx`).on(t.graphId, t.kind),\n // Directional traversal index (outgoing): supports endpoint lookups\n // and extra filtering by edge kind / target kind.\n index(`${n.edges}_from_idx`).on(\n t.graphId,\n t.fromKind,\n t.fromId,\n t.kind,\n t.toKind,\n t.deletedAt,\n t.validTo,\n ),\n // Directional traversal index (incoming): mirrors from_idx for reverse traversals.\n index(`${n.edges}_to_idx`).on(\n t.graphId,\n t.toKind,\n t.toId,\n t.kind,\n t.fromKind,\n t.deletedAt,\n t.validTo,\n ),\n index(`${n.edges}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.edges}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.edges}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n index(`${n.edges}_cardinality_idx`).on(\n t.graphId,\n t.kind,\n t.fromKind,\n t.fromId,\n t.validTo,\n ),\n ...buildSqliteEdgeIndexBuilders(t, indexes),\n ],\n );\n\n const uniques = sqliteTable(\n n.uniques,\n {\n graphId: text(\"graph_id\").notNull(),\n nodeKind: text(\"node_kind\").notNull(),\n constraintName: text(\"constraint_name\").notNull(),\n key: text(\"key\").notNull(),\n nodeId: text(\"node_id\").notNull(),\n concreteKind: text(\"concrete_kind\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.nodeKind, t.constraintName, t.key],\n }),\n index(`${n.uniques}_node_idx`).on(t.graphId, t.concreteKind, t.nodeId),\n ],\n );\n\n const schemaVersions = sqliteTable(\n n.schemaVersions,\n {\n graphId: text(\"graph_id\").notNull(),\n version: integer(\"version\").notNull(),\n schemaHash: text(\"schema_hash\").notNull(),\n schemaDoc: text(\"schema_doc\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n isActive: integer(\"is_active\", { mode: \"boolean\" })\n .notNull()\n .default(false),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.version] }),\n index(`${n.schemaVersions}_active_idx`).on(t.graphId, t.isActive),\n // Partial unique index enforcing the \"at most one active version\n // per graph\" invariant at the storage layer. Defense in depth\n // against buggy backend implementations or out-of-band writes.\n // Forces the deactivate-then-activate ordering used by\n // `commitSchemaVersion` and `setActiveVersion`.\n uniqueIndex(`${n.schemaVersions}_one_active_per_graph_idx`)\n .on(t.graphId)\n .where(sql`${t.isActive} = 1`),\n ],\n );\n\n /**\n * Per-deployment record of which declared indexes have been\n * materialized against this database. Owned and written by\n * `store.materializeIndexes()`. Keyed on `index_name` because SQL\n * index names are physical, database-global identifiers — `graphId`\n * is provenance, not identity.\n */\n const indexMaterializations = sqliteTable(\n n.indexMaterializations,\n {\n indexName: text(\"index_name\").notNull(),\n graphId: text(\"graph_id\").notNull(),\n entity: text(\"entity\").notNull(),\n kind: text(\"kind\").notNull(),\n signature: text(\"signature\").notNull(),\n schemaVersion: integer(\"schema_version\").notNull(),\n materializedAt: text(\"materialized_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [primaryKey({ columns: [t.indexName] })],\n );\n\n /**\n * Per-deployment record of extension kinds removed via\n * `store.removeKinds()` whose data has not yet been cleaned up by\n * `store.materializeRemovals()`. Keyed on `(graph_id, kind_name,\n * entity, schema_version)` — each remove operation is its own row.\n * `entity` separates a node and an edge that share a kind name; the\n * `schema_version` discriminator keeps a re-add-then-re-remove cycle\n * (Foo removed at v=N, re-added, then removed again at v=N+2) from\n * collapsing onto the prior row, where the COALESCE-on-failure rule\n * would preserve the earlier `removed_at` and silently skip the new\n * pending cleanup. `removed_at` is null until the data-cleanup pass\n * succeeds; the pending set is \"rows where removed_at IS NULL\".\n */\n const kindRemovals = sqliteTable(\n n.kindRemovals,\n {\n graphId: text(\"graph_id\").notNull(),\n kindName: text(\"kind_name\").notNull(),\n entity: text(\"entity\").notNull(),\n schemaVersion: integer(\"schema_version\").notNull(),\n removedAt: text(\"removed_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n }),\n ],\n );\n\n /**\n * Per-deployment high-water mark for the `materializeRemovals`\n * reconciliation walk. One row per `graph_id` carrying the schema\n * version up to which the historical \"did every removal land in\n * `kindRemovals`?\" walk has been verified. Lets subsequent calls\n * skip already-checked transitions instead of re-walking from\n * version 1 every time.\n */\n const reconciliationMarkers = sqliteTable(\n n.reconciliationMarkers,\n {\n graphId: text(\"graph_id\").notNull(),\n reconciledToVersion: integer(\"reconciled_to_version\").notNull(),\n },\n (t) => [primaryKey({ columns: [t.graphId] })],\n );\n\n /**\n * Per-deployment durable marker that a strategy-owned table\n * contribution (#129 — the FTS5 virtual table today) has been\n * materialized against this database (#135). Replaces the in-memory\n * per-backend `fulltextEnsured` latch with a queryable database fact.\n * Keyed on `(graph_id, logical_name, owner, table_name)`; `signature`\n * stays out of the key so same-identity drift is a loud error, not a\n * silent re-materialize. Same COALESCE-on-failure preservation rule\n * as `indexMaterializations`.\n */\n const contributionMaterializations = sqliteTable(\n n.contributionMaterializations,\n {\n graphId: text(\"graph_id\").notNull(),\n logicalName: text(\"logical_name\").notNull(),\n owner: text(\"owner\").notNull(),\n tableName: text(\"table_name\").notNull(),\n signature: text(\"signature\").notNull(),\n materializedAt: text(\"materialized_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.logicalName, t.owner, t.tableName],\n }),\n ],\n );\n\n return {\n nodes,\n edges,\n uniques,\n schemaVersions,\n indexMaterializations,\n contributionMaterializations,\n kindRemovals,\n reconciliationMarkers,\n /**\n * The fulltext storage is a FTS5 virtual table which Drizzle cannot\n * represent. DDL is emitted as raw SQL and operations query it via\n * `sql.raw()`.\n */\n fulltextTableName: n.fulltext,\n } as const;\n}\n\n/**\n * Default tables with standard TypeGraph table names.\n */\nexport const tables = createSqliteTables();\n\n/**\n * Convenience exports for default tables.\n */\nexport const { nodes, edges, uniques, schemaVersions } = tables;\n\n/**\n * Type representing the tables object returned by createSqliteTables.\n */\nexport type SqliteTables = ReturnType<typeof createSqliteTables>;\n","/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport { type SQL } from \"drizzle-orm\";\n\nimport {\n type IndexEntity,\n type KindEntity,\n type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { type VectorStrategy } from \"../query/dialect/vector-strategy\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport {\n type AnyPgDatabase,\n type AnySqliteDatabase,\n} from \"./drizzle/execution\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Whether the backend supports SQL window functions such as ROW_NUMBER() */\n windowFunctions: boolean;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n}>;\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: string; // JSON string\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: string; // JSON string\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n /**\n * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n * slot. The store populates it from the schema's `embedding()`\n * declaration via `getEmbeddingDimensions()`; the backend uses it to\n * construct the `VectorSlot` whose typed storage the strategy scans.\n */\n dimensions: number;\n /**\n * Index type materialized for this slot. `\"none\"` means brute-force\n * only; otherwise the strategy may route through its ANN structure.\n * The store populates it from `getEmbeddingIndex()`.\n */\n indexType: VectorIndexType;\n limit: number;\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 over-fetch to fill its\n * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n * HNSW path only. No-op on backends without an HNSW frontier knob\n * (sqlite-vec) and ignored — with a one-time warning — on Postgres\n * backends without transactions (e.g. `drizzle-orm/neon-http`).\n */\n efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n /**\n * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language override. Default: per-row language (as stored at insert time).\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n | \"read_uncommitted\"\n | \"read_committed\"\n | \"repeatable_read\"\n | \"serializable\";\n}>;\n\n/**\n * A caller-owned, already-open Drizzle transaction handle that a\n * TypeGraph store can adopt so both layers commit/rollback together.\n *\n * The literal client the caller's transaction runs on — a `PgDatabase`\n * transaction (node-postgres / `neon-serverless` Pool) or a\n * `BaseSQLiteDatabase` connection. Async drivers obtain it from\n * `db.transaction(async (tx) => …)`; synchronous `better-sqlite3` (whose\n * driver rejects an `async` transaction callback) passes the connection\n * itself under an explicit `BEGIN`/`COMMIT`/`ROLLBACK`. Passing it to\n * {@link GraphBackend.adoptTransaction} threads that *literal* client\n * through TypeGraph's SQL, so graph writes and the caller's own\n * relational writes share one Postgres/SQLite transaction (#134).\n */\nexport type AdoptedTransaction = AnyPgDatabase | AnySqliteDatabase;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * `commitSchemaVersion` and `setActiveVersion` are intentionally omitted:\n * the atomicity / CAS guarantees of those primitives depend on\n * dialect-specific write-locking (BEGIN IMMEDIATE on SQLite,\n * `pg_advisory_xact_lock` on Postgres) acquired by the top-level\n * backend wrappers, not the transaction itself. Calling them from a\n * user-supplied `backend.transaction(...)` callback would bypass that\n * locking and silently weaken the orphan-row crash window the primitive\n * exists to eliminate. Schema commits go through the top-level backend\n * methods only.\n */\nexport type TransactionBackend = Omit<\n GraphBackend,\n | \"transaction\"\n | \"adoptTransaction\"\n | \"close\"\n | \"refreshStatistics\"\n | \"commitSchemaVersion\"\n | \"setActiveVersion\"\n>;\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Optional vector strategy this backend is wired with. The query\n * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n * field)` relevance scans for `field.similarTo(...)` predicates, and\n * the index-materialization / removal paths read its deterministic\n * `tableName(...)` to address the right physical per-field storage.\n * `undefined` when the backend has no vector support (e.g. a generic\n * SQLite backend without sqlite-vec).\n */\n vectorStrategy?: VectorStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertNodesBatchReturning?: (\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (params: readonly InsertEdgeParams[]) => Promise<void>;\n insertEdgesBatchReturning?: (\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (params: HardDeleteEdgeParams) => Promise<void>;\n getEdge: (graphId: string, id: string) => Promise<EdgeRow | undefined>;\n getEdges?: (\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (params: EdgeExistsBetweenParams) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (params: CountNodesByKindParams) => Promise<number>;\n findEdgesByKind: (\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (params: CountEdgesByKindParams) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (params: InsertUniqueParams) => Promise<void>;\n deleteUnique: (params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (params: CheckUniqueParams) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (graphId: string) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (params: SetActiveVersionParams) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (params: UpsertEmbeddingParams) => Promise<void>;\n deleteEmbedding?: (params: DeleteEmbeddingParams) => Promise<void>;\n vectorSearch?: (\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (params: CreateVectorIndexParams) => Promise<void>;\n dropVectorIndex?: (params: DropVectorIndexParams) => Promise<void>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (params: UpsertFulltextBatchParams) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (params: DeleteFulltextBatchParams) => Promise<void>;\n fulltextSearch?: (\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n\n // === Contribution Materialization (#135 — durable strategy-owned\n // storage marker, sibling of the index status table) ===\n\n /**\n * Idempotently ensure ONLY the\n * `typegraph_contribution_materializations` table exists. Same\n * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n * replica startup, where the full `bootstrapTables` set risks a\n * Postgres SHARE-lock deadlock.\n */\n ensureContributionMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up the durable materialization marker for one strategy-owned\n * contribution identity. Returns `undefined` when no row exists\n * (\"never initialized\").\n */\n getContributionMaterialization?: (\n identity: ContributionMaterializationIdentity,\n ) => Promise<ContributionMaterializationRow | undefined>;\n\n /**\n * Upsert a contribution-materialization attempt — success or failure.\n * Failure rows preserve any prior `materializedAt` via COALESCE so a\n * later failed re-attempt doesn't erase the historical success.\n */\n recordContributionMaterialization?: (\n params: RecordContributionMaterializationParams,\n ) => Promise<void>;\n\n /**\n * Resolve (once per backend instance, cached) and assert the durable\n * materialization markers for every `runtimeEnsure` contribution this\n * backend's strategy declares, for `graphId`. Throws\n * `StoreNotInitializedError` when a marker is missing, stale\n * (signature drift), or recorded a failed last attempt.\n *\n * This is the single read-side gate the fulltext hot-path wrappers\n * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n * marker writes — initialization is the exclusive job of the async\n * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n */\n assertRuntimeContributionsInitialized?: (graphId: string) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.removeKinds()` and `store.materializeRemovals()` can persist\n * removal status. Mirrors the focused-bootstrap rationale documented\n * on `ensureIndexMaterializationsTable` — the full `bootstrapTables`\n * touches every base table and risks Postgres SHARE-lock deadlock\n * under concurrent replica startup.\n */\n ensureKindRemovalsTable?: () => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (graphId: string) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (params: RecordKindRemovalParams) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: () => Promise<void>;\n\n // === Table Contributions (#129) ===\n\n /**\n * Materializes every contribution flagged `runtimeEnsure` — the\n * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n * managed setups don't create. Called once after a successful schema\n * load. Deliberately scoped: base/drizzle-visible tables are\n * `runtimeEnsure: false`, so this does not regress startup into\n * broad DDL/probing across every table.\n *\n * The canonical durable-marker writer (#135): for each runtime\n * contribution it short-circuits when the marker already records a\n * matching signature, otherwise runs the idempotent `createDdl` and\n * records the marker (success or failure) keyed by `graphId`.\n */\n ensureRuntimeContributions?: (graphId: string) => Promise<void>;\n\n /**\n * Bootstraps the fulltext storage table the active `FulltextStrategy`\n * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n * methods: idempotent and concurrency-safe under replica startup.\n *\n * Superseded by `ensureRuntimeContributions()` (#129); retained as\n * a thin back-compat wrapper for backends/callers predating #129. Not\n * machine-`@deprecated` because the manager still calls it as the\n * pre-#129 fallback. #135 removed the remaining hot-path callers and\n * routed this through the durable-marker writer.\n */\n ensureFulltextTable?: (graphId: string) => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (graphId: string) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (graphId: string, version: number) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: () => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: () => Promise<void>;\n\n // === Query Execution ===\n execute: <T>(query: SQL) => Promise<readonly T[]>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a Drizzle SQL object to { sql, params } without executing. */\n compileSql?: (\n query: SQL,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (ddl: string) => Promise<void>;\n\n // === Transaction ===\n /**\n * `fn` receives the tx-scoped backend and the raw Drizzle handle\n * **bound to that same transaction** (`AdoptedTransaction`). The\n * store surfaces the second argument as `TransactionContext.sql` so\n * callers can write their own relational tables inside the\n * graph-owned transaction. Implementations MUST pass the *exact*\n * handle the tx-scoped backend writes through (the Postgres/libsql\n * tx handle; for better-sqlite3 / do-sqlite the bound connection),\n * never a fresh one.\n */\n transaction: <T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n /**\n * Adopt a caller-owned, already-open transaction (#134).\n *\n * Returns a transaction-scoped backend bound to the *exact*\n * `externalTx` client, reusing this backend's already-resolved\n * schema/strategy config — no `createStoreWithSchema` / `evolve` /\n * `migrateSchema`, and **no DDL inside the caller's business\n * transaction**. The caller owns `BEGIN`/`COMMIT`/`ROLLBACK`; this\n * method neither opens nor closes a transaction. Async drivers\n * (node-postgres, `neon-serverless` Pool, libsql) wrap with\n * `db.transaction(async …)`; synchronous `better-sqlite3` must instead\n * issue explicit `BEGIN`/`COMMIT`/`ROLLBACK` (its driver rejects an\n * `async` transaction callback).\n *\n * Optional and presence-detected like the other capability-scoped\n * members: only the Drizzle Postgres/SQLite backends provide it.\n * Implementations MUST throw (not silently degrade) when\n * `capabilities.transactions` is `false` — a non-atomic fallback is\n * safe for graph-only writes but dangerous for cross-store flows,\n * where the caller's relational write *would* still commit.\n *\n * Fulltext stays safe by construction: the returned backend's\n * fulltext methods assert the durable materialization marker (a\n * cached SELECT, never DDL) at point of use and throw\n * `StoreNotInitializedError` on a missing/stale/failed marker rather\n * than migrating mid-transaction. Prefer booting the parent store via\n * `createStoreWithSchema` so that assertion is a warm-cache no-op.\n */\n adoptTransaction?: (externalTx: AdoptedTransaction) => TransactionBackend;\n\n // === Lifecycle ===\n close: () => Promise<void>;\n}>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let isClosed = false;\n return {\n ...backend,\n async close(): Promise<void> {\n if (isClosed) return;\n isClosed = true;\n await backend.close();\n await teardown();\n },\n };\n}\n\n/**\n * Runs `fn` inside a transaction when the backend supports one, falling\n * through to a direct invocation otherwise. Lets call sites benefit from\n * atomicity on backends that have transactions while staying functional\n * on backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over\n * HTTP). The single-statement race window is already implicit on any\n * backend that reports `transactions: false`; callers that cannot\n * tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (!backend.capabilities.transactions) {\n return fn(fallback ?? backend);\n }\n return backend.transaction((tx) => fn(tx));\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n | Readonly<{ kind: \"initial\" }>\n | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\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 /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = {\n transactions: true, // SQLite supports transactions\n windowFunctions: true, // SQLite has supported window functions since 3.25.0\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n transactions: true, // PostgreSQL supports transactions\n windowFunctions: true, // PostgreSQL supports ROW_NUMBER() and related windows\n};\n"]}