@saluzi/codegraph 0.1.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 (189) hide show
  1. package/dist/bin/codegraph.d.ts +25 -0
  2. package/dist/bin/node-version-check.d.ts +37 -0
  3. package/dist/bin/uninstall.d.ts +14 -0
  4. package/dist/context/formatter.d.ts +33 -0
  5. package/dist/context/formatter.js +244 -0
  6. package/dist/context/index.d.ts +117 -0
  7. package/dist/context/index.js +1050 -0
  8. package/dist/db/index.d.ts +101 -0
  9. package/dist/db/index.js +250 -0
  10. package/dist/db/migrations.d.ts +47 -0
  11. package/dist/db/migrations.js +131 -0
  12. package/dist/db/queries.d.ts +291 -0
  13. package/dist/db/queries.js +1349 -0
  14. package/dist/db/schema.sql +151 -0
  15. package/dist/db/sqlite-adapter.d.ts +49 -0
  16. package/dist/db/sqlite-adapter.js +141 -0
  17. package/dist/directory.d.ts +62 -0
  18. package/dist/directory.js +264 -0
  19. package/dist/errors.d.ts +149 -0
  20. package/dist/errors.js +219 -0
  21. package/dist/extraction/dfm-extractor.d.ts +31 -0
  22. package/dist/extraction/dfm-extractor.js +151 -0
  23. package/dist/extraction/grammars.d.ts +94 -0
  24. package/dist/extraction/grammars.js +357 -0
  25. package/dist/extraction/index.d.ts +148 -0
  26. package/dist/extraction/index.js +1286 -0
  27. package/dist/extraction/languages/c-cpp.d.ts +4 -0
  28. package/dist/extraction/languages/c-cpp.js +126 -0
  29. package/dist/extraction/languages/csharp.d.ts +3 -0
  30. package/dist/extraction/languages/csharp.js +72 -0
  31. package/dist/extraction/languages/dart.d.ts +3 -0
  32. package/dist/extraction/languages/dart.js +192 -0
  33. package/dist/extraction/languages/go.d.ts +3 -0
  34. package/dist/extraction/languages/go.js +58 -0
  35. package/dist/extraction/languages/index.d.ts +10 -0
  36. package/dist/extraction/languages/index.js +49 -0
  37. package/dist/extraction/languages/java.d.ts +3 -0
  38. package/dist/extraction/languages/java.js +64 -0
  39. package/dist/extraction/languages/javascript.d.ts +3 -0
  40. package/dist/extraction/languages/javascript.js +90 -0
  41. package/dist/extraction/languages/kotlin.d.ts +3 -0
  42. package/dist/extraction/languages/kotlin.js +253 -0
  43. package/dist/extraction/languages/lua.d.ts +3 -0
  44. package/dist/extraction/languages/lua.js +150 -0
  45. package/dist/extraction/languages/luau.d.ts +3 -0
  46. package/dist/extraction/languages/luau.js +37 -0
  47. package/dist/extraction/languages/pascal.d.ts +3 -0
  48. package/dist/extraction/languages/pascal.js +66 -0
  49. package/dist/extraction/languages/php.d.ts +3 -0
  50. package/dist/extraction/languages/php.js +107 -0
  51. package/dist/extraction/languages/python.d.ts +3 -0
  52. package/dist/extraction/languages/python.js +56 -0
  53. package/dist/extraction/languages/ruby.d.ts +3 -0
  54. package/dist/extraction/languages/ruby.js +114 -0
  55. package/dist/extraction/languages/rust.d.ts +3 -0
  56. package/dist/extraction/languages/rust.js +109 -0
  57. package/dist/extraction/languages/scala.d.ts +3 -0
  58. package/dist/extraction/languages/scala.js +139 -0
  59. package/dist/extraction/languages/swift.d.ts +3 -0
  60. package/dist/extraction/languages/swift.js +91 -0
  61. package/dist/extraction/languages/typescript.d.ts +3 -0
  62. package/dist/extraction/languages/typescript.js +129 -0
  63. package/dist/extraction/liquid-extractor.d.ts +52 -0
  64. package/dist/extraction/liquid-extractor.js +313 -0
  65. package/dist/extraction/parse-worker.d.ts +8 -0
  66. package/dist/extraction/parse-worker.js +94 -0
  67. package/dist/extraction/svelte-extractor.d.ts +56 -0
  68. package/dist/extraction/svelte-extractor.js +272 -0
  69. package/dist/extraction/tree-sitter-helpers.d.ts +39 -0
  70. package/dist/extraction/tree-sitter-helpers.js +103 -0
  71. package/dist/extraction/tree-sitter-types.d.ts +191 -0
  72. package/dist/extraction/tree-sitter-types.js +10 -0
  73. package/dist/extraction/tree-sitter.d.ts +238 -0
  74. package/dist/extraction/tree-sitter.js +2430 -0
  75. package/dist/extraction/vue-extractor.d.ts +36 -0
  76. package/dist/extraction/vue-extractor.js +163 -0
  77. package/dist/extraction/wasm/tree-sitter-c.wasm +0 -0
  78. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  79. package/dist/extraction/wasm/tree-sitter-cpp.wasm +0 -0
  80. package/dist/extraction/wasm/tree-sitter-dart.wasm +0 -0
  81. package/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  82. package/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  83. package/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  84. package/dist/extraction/wasm/tree-sitter-kotlin.wasm +0 -0
  85. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  86. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  87. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  88. package/dist/extraction/wasm/tree-sitter-php.wasm +0 -0
  89. package/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  90. package/dist/extraction/wasm/tree-sitter-ruby.wasm +0 -0
  91. package/dist/extraction/wasm/tree-sitter-rust.wasm +0 -0
  92. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  93. package/dist/extraction/wasm/tree-sitter-swift.wasm +0 -0
  94. package/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  95. package/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  96. package/dist/extraction/wasm-runtime-flags.d.ts +46 -0
  97. package/dist/extraction/wasm-runtime-flags.js +105 -0
  98. package/dist/graph/index.d.ts +8 -0
  99. package/dist/graph/index.js +13 -0
  100. package/dist/graph/queries.d.ts +109 -0
  101. package/dist/graph/queries.js +366 -0
  102. package/dist/graph/traversal.d.ts +137 -0
  103. package/dist/graph/traversal.js +528 -0
  104. package/dist/index.d.ts +509 -0
  105. package/dist/index.js +800 -0
  106. package/dist/installer/claude-md-template.d.ts +19 -0
  107. package/dist/installer/config-writer.d.ts +29 -0
  108. package/dist/installer/index.d.ts +140 -0
  109. package/dist/installer/instructions-template.d.ts +30 -0
  110. package/dist/installer/targets/claude.d.ts +55 -0
  111. package/dist/installer/targets/codex.d.ts +18 -0
  112. package/dist/installer/targets/cursor.d.ts +35 -0
  113. package/dist/installer/targets/hermes.d.ts +18 -0
  114. package/dist/installer/targets/opencode.d.ts +30 -0
  115. package/dist/installer/targets/registry.d.ts +38 -0
  116. package/dist/installer/targets/shared.d.ts +92 -0
  117. package/dist/installer/targets/toml.d.ts +64 -0
  118. package/dist/installer/targets/types.d.ts +122 -0
  119. package/dist/mcp/index.d.ts +98 -0
  120. package/dist/mcp/server-instructions.d.ts +20 -0
  121. package/dist/mcp/tools.d.ts +269 -0
  122. package/dist/mcp/transport.d.ts +117 -0
  123. package/dist/resolution/frameworks/cargo-workspace.d.ts +20 -0
  124. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  125. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  126. package/dist/resolution/frameworks/csharp.js +213 -0
  127. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  128. package/dist/resolution/frameworks/drupal.js +335 -0
  129. package/dist/resolution/frameworks/express.d.ts +8 -0
  130. package/dist/resolution/frameworks/express.js +225 -0
  131. package/dist/resolution/frameworks/go.d.ts +8 -0
  132. package/dist/resolution/frameworks/go.js +158 -0
  133. package/dist/resolution/frameworks/index.d.ts +52 -0
  134. package/dist/resolution/frameworks/index.js +137 -0
  135. package/dist/resolution/frameworks/java.d.ts +8 -0
  136. package/dist/resolution/frameworks/java.js +177 -0
  137. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  138. package/dist/resolution/frameworks/laravel.js +248 -0
  139. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  140. package/dist/resolution/frameworks/nestjs.js +374 -0
  141. package/dist/resolution/frameworks/python.d.ts +10 -0
  142. package/dist/resolution/frameworks/python.js +278 -0
  143. package/dist/resolution/frameworks/react.d.ts +8 -0
  144. package/dist/resolution/frameworks/react.js +272 -0
  145. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  146. package/dist/resolution/frameworks/ruby.js +198 -0
  147. package/dist/resolution/frameworks/rust.d.ts +8 -0
  148. package/dist/resolution/frameworks/rust.js +207 -0
  149. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  150. package/dist/resolution/frameworks/svelte.js +249 -0
  151. package/dist/resolution/frameworks/swift.d.ts +10 -0
  152. package/dist/resolution/frameworks/swift.js +376 -0
  153. package/dist/resolution/frameworks/vue.d.ts +9 -0
  154. package/dist/resolution/frameworks/vue.js +306 -0
  155. package/dist/resolution/import-resolver.d.ts +61 -0
  156. package/dist/resolution/import-resolver.js +663 -0
  157. package/dist/resolution/index.d.ts +118 -0
  158. package/dist/resolution/index.js +744 -0
  159. package/dist/resolution/lru-cache.d.ts +24 -0
  160. package/dist/resolution/lru-cache.js +62 -0
  161. package/dist/resolution/name-matcher.d.ts +50 -0
  162. package/dist/resolution/name-matcher.js +384 -0
  163. package/dist/resolution/path-aliases.d.ts +72 -0
  164. package/dist/resolution/path-aliases.js +238 -0
  165. package/dist/resolution/strip-comments.d.ts +40 -0
  166. package/dist/resolution/strip-comments.js +441 -0
  167. package/dist/resolution/types.d.ts +181 -0
  168. package/dist/resolution/types.js +8 -0
  169. package/dist/search/query-parser.d.ts +61 -0
  170. package/dist/search/query-parser.js +177 -0
  171. package/dist/search/query-utils.d.ts +59 -0
  172. package/dist/search/query-utils.js +383 -0
  173. package/dist/sync/git-hooks.d.ts +54 -0
  174. package/dist/sync/git-hooks.js +223 -0
  175. package/dist/sync/index.d.ts +25 -0
  176. package/dist/sync/index.js +28 -0
  177. package/dist/sync/watch-policy.d.ts +51 -0
  178. package/dist/sync/watch-policy.js +124 -0
  179. package/dist/sync/watcher.d.ts +83 -0
  180. package/dist/sync/watcher.js +192 -0
  181. package/dist/types.d.ts +433 -0
  182. package/dist/types.js +75 -0
  183. package/dist/ui/glyphs.d.ts +42 -0
  184. package/dist/ui/shimmer-progress.d.ts +11 -0
  185. package/dist/ui/shimmer-worker.d.ts +2 -0
  186. package/dist/ui/types.d.ts +20 -0
  187. package/dist/utils.d.ts +231 -0
  188. package/dist/utils.js +549 -0
  189. package/package.json +24 -0
@@ -0,0 +1,1349 @@
1
+ "use strict";
2
+ /**
3
+ * Database Queries
4
+ *
5
+ * Prepared statements for CRUD operations on the knowledge graph.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.QueryBuilder = void 0;
9
+ const utils_1 = require("../utils");
10
+ const query_utils_1 = require("../search/query-utils");
11
+ const query_parser_1 = require("../search/query-parser");
12
+ /**
13
+ * Convert database row to Node object
14
+ */
15
+ function rowToNode(row) {
16
+ return {
17
+ id: row.id,
18
+ kind: row.kind,
19
+ name: row.name,
20
+ qualifiedName: row.qualified_name,
21
+ filePath: row.file_path,
22
+ language: row.language,
23
+ startLine: row.start_line,
24
+ endLine: row.end_line,
25
+ startColumn: row.start_column,
26
+ endColumn: row.end_column,
27
+ docstring: row.docstring ?? undefined,
28
+ signature: row.signature ?? undefined,
29
+ visibility: row.visibility,
30
+ isExported: row.is_exported === 1,
31
+ isAsync: row.is_async === 1,
32
+ isStatic: row.is_static === 1,
33
+ isAbstract: row.is_abstract === 1,
34
+ decorators: row.decorators ? (0, utils_1.safeJsonParse)(row.decorators, undefined) : undefined,
35
+ typeParameters: row.type_parameters ? (0, utils_1.safeJsonParse)(row.type_parameters, undefined) : undefined,
36
+ updatedAt: row.updated_at,
37
+ };
38
+ }
39
+ /**
40
+ * Convert database row to Edge object
41
+ */
42
+ function rowToEdge(row) {
43
+ return {
44
+ source: row.source,
45
+ target: row.target,
46
+ kind: row.kind,
47
+ metadata: row.metadata ? (0, utils_1.safeJsonParse)(row.metadata, undefined) : undefined,
48
+ line: row.line ?? undefined,
49
+ column: row.col ?? undefined,
50
+ provenance: row.provenance,
51
+ };
52
+ }
53
+ /**
54
+ * Convert database row to FileRecord object
55
+ */
56
+ function rowToFileRecord(row) {
57
+ return {
58
+ path: row.path,
59
+ contentHash: row.content_hash,
60
+ language: row.language,
61
+ size: row.size,
62
+ modifiedAt: row.modified_at,
63
+ indexedAt: row.indexed_at,
64
+ nodeCount: row.node_count,
65
+ errors: row.errors ? (0, utils_1.safeJsonParse)(row.errors, undefined) : undefined,
66
+ };
67
+ }
68
+ /**
69
+ * Query builder for the knowledge graph database
70
+ */
71
+ class QueryBuilder {
72
+ db;
73
+ // Node cache for frequently accessed nodes (LRU-style, max 1000 entries)
74
+ nodeCache = new Map();
75
+ maxCacheSize = 1000;
76
+ // Prepared statements (lazily initialized)
77
+ stmts = {};
78
+ constructor(db) {
79
+ this.db = db;
80
+ }
81
+ // ===========================================================================
82
+ // Node Operations
83
+ // ===========================================================================
84
+ /**
85
+ * Insert a new node
86
+ */
87
+ insertNode(node) {
88
+ if (!this.stmts.insertNode) {
89
+ this.stmts.insertNode = this.db.prepare(`
90
+ INSERT OR REPLACE INTO nodes (
91
+ id, kind, name, qualified_name, file_path, language,
92
+ start_line, end_line, start_column, end_column,
93
+ docstring, signature, visibility,
94
+ is_exported, is_async, is_static, is_abstract,
95
+ decorators, type_parameters, updated_at
96
+ ) VALUES (
97
+ @id, @kind, @name, @qualifiedName, @filePath, @language,
98
+ @startLine, @endLine, @startColumn, @endColumn,
99
+ @docstring, @signature, @visibility,
100
+ @isExported, @isAsync, @isStatic, @isAbstract,
101
+ @decorators, @typeParameters, @updatedAt
102
+ )
103
+ `);
104
+ }
105
+ // Validate required fields to prevent SQLite bind errors
106
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
107
+ console.error('[CodeGraph] Skipping node with missing required fields:', {
108
+ id: node.id,
109
+ kind: node.kind,
110
+ name: node.name,
111
+ filePath: node.filePath,
112
+ language: node.language,
113
+ });
114
+ return;
115
+ }
116
+ // INSERT OR REPLACE may overwrite a node we have cached. Drop the
117
+ // stale entry so the next getNodeById sees the new row, not the old
118
+ // one (matches the cache-invalidation pattern used by updateNode and
119
+ // deleteNode below).
120
+ this.nodeCache.delete(node.id);
121
+ this.stmts.insertNode.run({
122
+ id: node.id,
123
+ kind: node.kind,
124
+ name: node.name,
125
+ qualifiedName: node.qualifiedName ?? node.name,
126
+ filePath: node.filePath,
127
+ language: node.language,
128
+ startLine: node.startLine ?? 0,
129
+ endLine: node.endLine ?? 0,
130
+ startColumn: node.startColumn ?? 0,
131
+ endColumn: node.endColumn ?? 0,
132
+ docstring: node.docstring ?? null,
133
+ signature: node.signature ?? null,
134
+ visibility: node.visibility ?? null,
135
+ isExported: node.isExported ? 1 : 0,
136
+ isAsync: node.isAsync ? 1 : 0,
137
+ isStatic: node.isStatic ? 1 : 0,
138
+ isAbstract: node.isAbstract ? 1 : 0,
139
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
140
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
141
+ updatedAt: node.updatedAt ?? Date.now(),
142
+ });
143
+ }
144
+ /**
145
+ * Insert multiple nodes in a transaction
146
+ */
147
+ insertNodes(nodes) {
148
+ this.db.transaction(() => {
149
+ for (const node of nodes) {
150
+ this.insertNode(node);
151
+ }
152
+ })();
153
+ }
154
+ /**
155
+ * Update an existing node
156
+ */
157
+ updateNode(node) {
158
+ if (!this.stmts.updateNode) {
159
+ this.stmts.updateNode = this.db.prepare(`
160
+ UPDATE nodes SET
161
+ kind = @kind,
162
+ name = @name,
163
+ qualified_name = @qualifiedName,
164
+ file_path = @filePath,
165
+ language = @language,
166
+ start_line = @startLine,
167
+ end_line = @endLine,
168
+ start_column = @startColumn,
169
+ end_column = @endColumn,
170
+ docstring = @docstring,
171
+ signature = @signature,
172
+ visibility = @visibility,
173
+ is_exported = @isExported,
174
+ is_async = @isAsync,
175
+ is_static = @isStatic,
176
+ is_abstract = @isAbstract,
177
+ decorators = @decorators,
178
+ type_parameters = @typeParameters,
179
+ updated_at = @updatedAt
180
+ WHERE id = @id
181
+ `);
182
+ }
183
+ // Invalidate cache before update
184
+ this.nodeCache.delete(node.id);
185
+ // Validate required fields
186
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
187
+ console.error('[CodeGraph] Skipping node update with missing required fields:', node.id);
188
+ return;
189
+ }
190
+ this.stmts.updateNode.run({
191
+ id: node.id,
192
+ kind: node.kind,
193
+ name: node.name,
194
+ qualifiedName: node.qualifiedName ?? node.name,
195
+ filePath: node.filePath,
196
+ language: node.language,
197
+ startLine: node.startLine ?? 0,
198
+ endLine: node.endLine ?? 0,
199
+ startColumn: node.startColumn ?? 0,
200
+ endColumn: node.endColumn ?? 0,
201
+ docstring: node.docstring ?? null,
202
+ signature: node.signature ?? null,
203
+ visibility: node.visibility ?? null,
204
+ isExported: node.isExported ? 1 : 0,
205
+ isAsync: node.isAsync ? 1 : 0,
206
+ isStatic: node.isStatic ? 1 : 0,
207
+ isAbstract: node.isAbstract ? 1 : 0,
208
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
209
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
210
+ updatedAt: node.updatedAt ?? Date.now(),
211
+ });
212
+ }
213
+ /**
214
+ * Delete a node by ID
215
+ */
216
+ deleteNode(id) {
217
+ if (!this.stmts.deleteNode) {
218
+ this.stmts.deleteNode = this.db.prepare('DELETE FROM nodes WHERE id = ?');
219
+ }
220
+ // Invalidate cache
221
+ this.nodeCache.delete(id);
222
+ this.stmts.deleteNode.run(id);
223
+ }
224
+ /**
225
+ * Delete all nodes for a file
226
+ */
227
+ deleteNodesByFile(filePath) {
228
+ if (!this.stmts.deleteNodesByFile) {
229
+ this.stmts.deleteNodesByFile = this.db.prepare('DELETE FROM nodes WHERE file_path = ?');
230
+ }
231
+ // Invalidate cache for nodes in this file
232
+ for (const [id, node] of this.nodeCache) {
233
+ if (node.filePath === filePath) {
234
+ this.nodeCache.delete(id);
235
+ }
236
+ }
237
+ this.stmts.deleteNodesByFile.run(filePath);
238
+ }
239
+ /**
240
+ * Get a node by ID
241
+ */
242
+ getNodeById(id) {
243
+ // Check cache first
244
+ if (this.nodeCache.has(id)) {
245
+ const cached = this.nodeCache.get(id);
246
+ // Move to end to implement LRU (delete and re-add)
247
+ this.nodeCache.delete(id);
248
+ this.nodeCache.set(id, cached);
249
+ return cached;
250
+ }
251
+ if (!this.stmts.getNodeById) {
252
+ this.stmts.getNodeById = this.db.prepare('SELECT * FROM nodes WHERE id = ?');
253
+ }
254
+ const row = this.stmts.getNodeById.get(id);
255
+ if (!row) {
256
+ return null;
257
+ }
258
+ const node = rowToNode(row);
259
+ this.cacheNode(node);
260
+ return node;
261
+ }
262
+ /**
263
+ * Batch lookup: fetch many nodes by ID in a single SQL round-trip.
264
+ *
265
+ * Replaces the N+1 pattern in graph traversal where every edge would
266
+ * trigger its own `getNodeById` call. For a function with 50 callers
267
+ * this collapses 50 point reads into one IN-list query (~10-50x
268
+ * faster end-to-end).
269
+ *
270
+ * Returns a Map keyed by id so callers can preserve their own ordering
271
+ * (typically the order edges were returned from the graph). Missing IDs
272
+ * are simply absent from the map.
273
+ *
274
+ * Cache-aware: ids already in the LRU cache are served from memory and
275
+ * the SQL query only touches the misses.
276
+ */
277
+ getNodesByIds(ids) {
278
+ const out = new Map();
279
+ if (ids.length === 0)
280
+ return out;
281
+ // Serve cache hits first; build the miss list for SQL.
282
+ const misses = [];
283
+ for (const id of ids) {
284
+ const cached = this.nodeCache.get(id);
285
+ if (cached !== undefined) {
286
+ // LRU touch
287
+ this.nodeCache.delete(id);
288
+ this.nodeCache.set(id, cached);
289
+ out.set(id, cached);
290
+ }
291
+ else {
292
+ misses.push(id);
293
+ }
294
+ }
295
+ if (misses.length === 0)
296
+ return out;
297
+ // Chunk under SQLite's parameter limit (default 999, raised to 32766
298
+ // in better-sqlite3 builds — chunk at 500 for safety across both
299
+ // backends and to keep the query plan simple).
300
+ const CHUNK = 500;
301
+ for (let i = 0; i < misses.length; i += CHUNK) {
302
+ const chunk = misses.slice(i, i + CHUNK);
303
+ const placeholders = chunk.map(() => '?').join(',');
304
+ const rows = this.db
305
+ .prepare(`SELECT * FROM nodes WHERE id IN (${placeholders})`)
306
+ .all(...chunk);
307
+ for (const row of rows) {
308
+ const node = rowToNode(row);
309
+ out.set(node.id, node);
310
+ this.cacheNode(node);
311
+ }
312
+ }
313
+ return out;
314
+ }
315
+ /**
316
+ * Add a node to the cache, evicting oldest if needed
317
+ */
318
+ cacheNode(node) {
319
+ if (this.nodeCache.size >= this.maxCacheSize) {
320
+ // Evict oldest (first) entry
321
+ const firstKey = this.nodeCache.keys().next().value;
322
+ if (firstKey) {
323
+ this.nodeCache.delete(firstKey);
324
+ }
325
+ }
326
+ this.nodeCache.set(node.id, node);
327
+ }
328
+ /**
329
+ * Clear the node cache
330
+ */
331
+ clearCache() {
332
+ this.nodeCache.clear();
333
+ }
334
+ /**
335
+ * Get all nodes in a file
336
+ */
337
+ getNodesByFile(filePath) {
338
+ if (!this.stmts.getNodesByFile) {
339
+ this.stmts.getNodesByFile = this.db.prepare('SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line');
340
+ }
341
+ const rows = this.stmts.getNodesByFile.all(filePath);
342
+ return rows.map(rowToNode);
343
+ }
344
+ /**
345
+ * Get all nodes of a specific kind
346
+ */
347
+ getNodesByKind(kind) {
348
+ if (!this.stmts.getNodesByKind) {
349
+ this.stmts.getNodesByKind = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
350
+ }
351
+ const rows = this.stmts.getNodesByKind.all(kind);
352
+ return rows.map(rowToNode);
353
+ }
354
+ /**
355
+ * Get all nodes in the database
356
+ */
357
+ getAllNodes() {
358
+ const rows = this.db.prepare('SELECT * FROM nodes').all();
359
+ return rows.map(rowToNode);
360
+ }
361
+ /**
362
+ * Get nodes by exact name match (uses idx_nodes_name index)
363
+ */
364
+ getNodesByName(name) {
365
+ if (!this.stmts.getNodesByName) {
366
+ this.stmts.getNodesByName = this.db.prepare('SELECT * FROM nodes WHERE name = ?');
367
+ }
368
+ const rows = this.stmts.getNodesByName.all(name);
369
+ return rows.map(rowToNode);
370
+ }
371
+ /**
372
+ * Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
373
+ */
374
+ getNodesByQualifiedNameExact(qualifiedName) {
375
+ if (!this.stmts.getNodesByQualifiedNameExact) {
376
+ this.stmts.getNodesByQualifiedNameExact = this.db.prepare('SELECT * FROM nodes WHERE qualified_name = ?');
377
+ }
378
+ const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName);
379
+ return rows.map(rowToNode);
380
+ }
381
+ /**
382
+ * Get nodes by lowercase name match (uses idx_nodes_lower_name expression index)
383
+ */
384
+ getNodesByLowerName(lowerName) {
385
+ if (!this.stmts.getNodesByLowerName) {
386
+ this.stmts.getNodesByLowerName = this.db.prepare('SELECT * FROM nodes WHERE lower(name) = ?');
387
+ }
388
+ const rows = this.stmts.getNodesByLowerName.all(lowerName);
389
+ return rows.map(rowToNode);
390
+ }
391
+ /**
392
+ * Search nodes by name using FTS with fallback to LIKE for better matching
393
+ *
394
+ * Search strategy:
395
+ * 1. Try FTS5 prefix match (query*) for word-start matching
396
+ * 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
397
+ * 3. Score results based on match quality
398
+ */
399
+ searchNodes(query, options = {}) {
400
+ const { limit = 100, offset = 0 } = options;
401
+ // Parse field-qualified bits out of the raw query (kind:, lang:,
402
+ // path:, name:). Anything not recognised stays in `text` and goes
403
+ // to FTS unchanged. Filters compose with the SearchOptions arg —
404
+ // both are applied (intersection-style).
405
+ const parsed = (0, query_parser_1.parseQuery)(query);
406
+ const mergedKinds = parsed.kinds.length > 0
407
+ ? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
408
+ : options.kinds;
409
+ const mergedLanguages = parsed.languages.length > 0
410
+ ? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
411
+ : options.languages;
412
+ const pathFilters = parsed.pathFilters;
413
+ const nameFilters = parsed.nameFilters;
414
+ // The text portion drives FTS/LIKE; if all the user typed was
415
+ // filters (`kind:function`), we still need *some* candidate set,
416
+ // so synthesise an empty-text path that returns everything matching
417
+ // the filters.
418
+ const text = parsed.text;
419
+ const kinds = mergedKinds;
420
+ const languages = mergedLanguages;
421
+ // Detect CJK content in query for specialised search path
422
+ const cjkPattern = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/;
423
+ const hasCJK = text ? cjkPattern.test(text) : false;
424
+ // First try FTS5 with prefix matching (best for English identifiers)
425
+ let results = text
426
+ ? this.searchNodesFTS(text, { kinds, languages, limit, offset })
427
+ // Over-fetch by 5× when running filter-only (no text). The
428
+ // post-scoring path: + name: filters can be very selective, so
429
+ // a smaller multiplier risks returning fewer than `limit`
430
+ // results despite the DB having plenty of matches.
431
+ : this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
432
+ // If query has CJK characters and FTS found nothing (FTS5 unicode61
433
+ // can't tokenize CJK), search name + docstring with LIKE
434
+ if (results.length === 0 && hasCJK) {
435
+ results = this.searchNodesCJK(text, { kinds, languages, limit, offset });
436
+ }
437
+ // If no FTS results, try LIKE-based substring search
438
+ if (results.length === 0 && text.length >= 2) {
439
+ results = this.searchNodesLike(text, { kinds, languages, limit, offset });
440
+ }
441
+ // Final fuzzy fallback: scan all known names and keep those within
442
+ // a tight Levenshtein distance. Only fires when both FTS and LIKE
443
+ // returned nothing AND there's a text portion long enough to be
444
+ // worth fuzzing (1-char queries would match too much).
445
+ if (results.length === 0 && text.length >= 3) {
446
+ results = this.searchNodesFuzzy(text, { kinds, languages, limit });
447
+ }
448
+ // Supplement: ensure exact name matches are always candidates.
449
+ // BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
450
+ // compound names (e.g. "getBeanDescriptor") in large codebases,
451
+ // pushing them past the FTS fetch limit before post-hoc scoring can help.
452
+ // Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
453
+ // prefix=20) actually differentiates them after rescoring.
454
+ if (results.length > 0 && query) {
455
+ const existingIds = new Set(results.map(r => r.node.id));
456
+ const maxFtsScore = Math.max(...results.map(r => r.score));
457
+ const terms = query.split(/\s+/).filter(t => t.length >= 2);
458
+ for (const term of terms) {
459
+ let sql = 'SELECT * FROM nodes WHERE name = ? COLLATE NOCASE';
460
+ const params = [term];
461
+ if (kinds && kinds.length > 0) {
462
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
463
+ params.push(...kinds);
464
+ }
465
+ if (languages && languages.length > 0) {
466
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
467
+ params.push(...languages);
468
+ }
469
+ sql += ' LIMIT 20';
470
+ const rows = this.db.prepare(sql).all(...params);
471
+ for (const row of rows) {
472
+ if (!existingIds.has(row.id)) {
473
+ results.push({ node: rowToNode(row), score: maxFtsScore });
474
+ existingIds.add(row.id);
475
+ }
476
+ }
477
+ }
478
+ }
479
+ // Apply multi-signal scoring
480
+ if (results.length > 0 && (text || query)) {
481
+ const scoringQuery = text || query;
482
+ results = results.map(r => ({
483
+ ...r,
484
+ score: r.score
485
+ + (0, query_utils_1.kindBonus)(r.node.kind)
486
+ + (0, query_utils_1.scorePathRelevance)(r.node.filePath, scoringQuery)
487
+ + (0, query_utils_1.nameMatchBonus)(r.node.name, scoringQuery),
488
+ }));
489
+ results.sort((a, b) => b.score - a.score);
490
+ // Trim to requested limit after rescoring
491
+ if (results.length > limit) {
492
+ results = results.slice(0, limit);
493
+ }
494
+ }
495
+ // Apply path: + name: filters AFTER scoring. Scoring already uses
496
+ // path/name as a soft signal; the explicit filters here are a hard
497
+ // gate. Done last so the FTS limit fetched plenty of candidates to
498
+ // narrow from.
499
+ if (pathFilters.length > 0) {
500
+ const lowered = pathFilters.map((p) => p.toLowerCase());
501
+ results = results.filter((r) => {
502
+ const fp = r.node.filePath.toLowerCase();
503
+ return lowered.some((p) => fp.includes(p));
504
+ });
505
+ }
506
+ if (nameFilters.length > 0) {
507
+ const lowered = nameFilters.map((n) => n.toLowerCase());
508
+ results = results.filter((r) => {
509
+ const nm = r.node.name.toLowerCase();
510
+ return lowered.some((n) => nm.includes(n));
511
+ });
512
+ }
513
+ return results;
514
+ }
515
+ /**
516
+ * Match-everything path used when the user supplied only field
517
+ * filters (`kind:function lang:typescript`) with no text. Returns
518
+ * candidates ordered by name; the caller's filter pass narrows to
519
+ * what was asked for.
520
+ */
521
+ searchAllByFilters(options) {
522
+ const { kinds, languages, limit } = options;
523
+ let sql = 'SELECT * FROM nodes WHERE 1=1';
524
+ const params = [];
525
+ if (kinds && kinds.length > 0) {
526
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
527
+ params.push(...kinds);
528
+ }
529
+ if (languages && languages.length > 0) {
530
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
531
+ params.push(...languages);
532
+ }
533
+ sql += ' ORDER BY name LIMIT ?';
534
+ params.push(limit);
535
+ const rows = this.db.prepare(sql).all(...params);
536
+ return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
537
+ }
538
+ /**
539
+ * Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
540
+ * sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
541
+ * `getUssr` finds `getUser` but `process` doesn't match `prosody`.
542
+ * Bounded edit distance keeps each comparison cheap; the per-query
543
+ * scan is O(distinct-name-count) which is far smaller than total
544
+ * node count on any real codebase.
545
+ */
546
+ searchNodesFuzzy(text, options) {
547
+ const { kinds, languages, limit } = options;
548
+ const lowered = text.toLowerCase();
549
+ const maxDist = lowered.length <= 4 ? 1 : 2;
550
+ // Pull the distinct name list once. The set is cached on QueryBuilder
551
+ // by getAllNodeNames(); even on a 200k-node project the distinct
552
+ // name set is typically O(10k) because most names repeat. The
553
+ // candidate-cap below bounds memory regardless.
554
+ const allNames = this.getAllNodeNames();
555
+ const candidates = [];
556
+ for (const name of allNames) {
557
+ const dist = (0, query_parser_1.boundedEditDistance)(name.toLowerCase(), lowered, maxDist);
558
+ if (dist <= maxDist)
559
+ candidates.push({ name, dist });
560
+ }
561
+ candidates.sort((a, b) => a.dist - b.dist);
562
+ // Cap the per-name follow-up queries. Each survivor triggers a
563
+ // separate `SELECT * FROM nodes WHERE name = ?`; without this cap
564
+ // a project with many similar names (`getUser1`, `getUser2`...)
565
+ // could fan out far beyond `limit` queries before the inner-loop
566
+ // limit kicks in.
567
+ const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
568
+ const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
569
+ const results = [];
570
+ const seen = new Set();
571
+ for (const c of cappedCandidates) {
572
+ if (results.length >= limit)
573
+ break;
574
+ let sql = 'SELECT * FROM nodes WHERE name = ?';
575
+ const params = [c.name];
576
+ if (kinds && kinds.length > 0) {
577
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
578
+ params.push(...kinds);
579
+ }
580
+ if (languages && languages.length > 0) {
581
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
582
+ params.push(...languages);
583
+ }
584
+ sql += ' LIMIT 5';
585
+ const rows = this.db.prepare(sql).all(...params);
586
+ for (const row of rows) {
587
+ if (seen.has(row.id))
588
+ continue;
589
+ seen.add(row.id);
590
+ // Lower the score for each edit step away from the query so
591
+ // exact-match fallbacks (dist 0) outrank dist-2 typos.
592
+ results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
593
+ if (results.length >= limit)
594
+ break;
595
+ }
596
+ }
597
+ return results;
598
+ }
599
+ /**
600
+ * FTS5 search with prefix matching
601
+ */
602
+ searchNodesFTS(query, options) {
603
+ const { kinds, languages, limit = 100, offset = 0 } = options;
604
+ // Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
605
+ // Escape special FTS5 characters and add prefix wildcard.
606
+ //
607
+ // `::` is a qualifier separator in Rust/C++/Ruby, not a token char,
608
+ // so treat it as whitespace before the strip step. Otherwise queries
609
+ // like `stage_apply::run` collapse to `stage_applyrun` (the colons
610
+ // are stripped without splitting) and find nothing. See #173.
611
+ const ftsQuery = query
612
+ .replace(/::/g, ' ') // Rust/C++/Ruby qualifier separator
613
+ .replace(/['"*():^]/g, '') // Remove FTS5 special chars
614
+ .split(/\s+/)
615
+ .filter(term => term.length > 0)
616
+ // Strip FTS5 boolean operators to prevent query manipulation
617
+ .filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
618
+ .map(term => `"${term}"*`) // Prefix match each term
619
+ .join(' OR ');
620
+ if (!ftsQuery) {
621
+ return [];
622
+ }
623
+ // BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
624
+ // Heavy name weight ensures exact/prefix name matches rank above incidental
625
+ // mentions in long docstrings or qualified names of nested symbols.
626
+ // Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
627
+ // nameMatchBonus) can promote results that BM25 alone undervalues.
628
+ const ftsLimit = Math.max(limit * 5, 100);
629
+ let sql = `
630
+ SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
631
+ FROM nodes_fts
632
+ JOIN nodes ON nodes_fts.id = nodes.id
633
+ WHERE nodes_fts MATCH ?
634
+ `;
635
+ const params = [ftsQuery];
636
+ if (kinds && kinds.length > 0) {
637
+ sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
638
+ params.push(...kinds);
639
+ }
640
+ if (languages && languages.length > 0) {
641
+ sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
642
+ params.push(...languages);
643
+ }
644
+ sql += ' ORDER BY score LIMIT ? OFFSET ?';
645
+ params.push(ftsLimit, offset);
646
+ try {
647
+ const rows = this.db.prepare(sql).all(...params);
648
+ return rows.map((row) => ({
649
+ node: rowToNode(row),
650
+ score: Math.abs(row.score), // bm25 returns negative scores
651
+ }));
652
+ }
653
+ catch {
654
+ // FTS query failed, return empty
655
+ return [];
656
+ }
657
+ }
658
+ /**
659
+ * LIKE-based substring search for cases where FTS doesn't match
660
+ * Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
661
+ */
662
+ searchNodesLike(query, options) {
663
+ const { kinds, languages, limit = 100, offset = 0 } = options;
664
+ let sql = `
665
+ SELECT nodes.*,
666
+ CASE
667
+ WHEN name = ? THEN 1.0
668
+ WHEN name LIKE ? THEN 0.9
669
+ WHEN name LIKE ? THEN 0.8
670
+ WHEN qualified_name LIKE ? THEN 0.7
671
+ ELSE 0.5
672
+ END as score
673
+ FROM nodes
674
+ WHERE (
675
+ name LIKE ? OR
676
+ qualified_name LIKE ? OR
677
+ name LIKE ?
678
+ )
679
+ `;
680
+ // Pattern variants for better matching
681
+ const exactMatch = query;
682
+ const startsWith = `${query}%`;
683
+ const contains = `%${query}%`;
684
+ const params = [
685
+ exactMatch, // Exact match score
686
+ startsWith, // Starts with score
687
+ contains, // Contains score
688
+ contains, // Qualified name score
689
+ contains, // WHERE: name contains
690
+ contains, // WHERE: qualified_name contains
691
+ startsWith, // WHERE: name starts with
692
+ ];
693
+ if (kinds && kinds.length > 0) {
694
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
695
+ params.push(...kinds);
696
+ }
697
+ if (languages && languages.length > 0) {
698
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
699
+ params.push(...languages);
700
+ }
701
+ sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
702
+ params.push(limit, offset);
703
+ const rows = this.db.prepare(sql).all(...params);
704
+ return rows.map((row) => ({
705
+ node: rowToNode(row),
706
+ score: row.score,
707
+ }));
708
+ }
709
+ /**
710
+ * CJK-aware search using LIKE on name + docstring.
711
+ *
712
+ * FTS5 unicode61 cannot tokenize CJK characters — it treats entire CJK
713
+ * sequences as opaque tokens that never match. This method bypasses FTS
714
+ * and searches the name, qualified_name, and docstring columns directly
715
+ * with LIKE, matching CJK bigrams/trigrams extracted by extractSearchTerms.
716
+ *
717
+ * Scoring priority:
718
+ * name match (1.0) > qualified_name (0.8) > docstring (0.6)
719
+ */
720
+ searchNodesCJK(query, options) {
721
+ const { kinds, languages, limit = 100, offset = 0 } = options;
722
+ // Extract CJK terms (bigrams, trigrams, full sequences)
723
+ const cjkPattern = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]+/g;
724
+ const cjkTerms = new Set();
725
+ let m;
726
+ while ((m = cjkPattern.exec(query)) !== null) {
727
+ const text = m[0];
728
+ if (text.length >= 2) cjkTerms.add(text);
729
+ for (let i = 0; i < text.length - 1; i++) cjkTerms.add(text.slice(i, i + 2));
730
+ for (let i = 0; i < text.length - 2; i++) cjkTerms.add(text.slice(i, i + 3));
731
+ }
732
+ // Also extract ASCII terms for combined matching
733
+ const asciiTerms = query
734
+ .replace(cjkPattern, ' ')
735
+ .split(/\s+/)
736
+ .filter(t => t.length >= 2);
737
+ const allTerms = [...cjkTerms, ...asciiTerms];
738
+ if (allTerms.length === 0) return [];
739
+ // Build OR conditions: each term searches name, qualified_name, docstring
740
+ const whereClauses = [];
741
+ const whereParams = [];
742
+ for (const term of allTerms.slice(0, 10)) { // cap at 10 terms to avoid huge queries
743
+ const pattern = `%${term}%`;
744
+ whereClauses.push('(name LIKE ? OR qualified_name LIKE ? OR docstring LIKE ?)');
745
+ whereParams.push(pattern, pattern, pattern);
746
+ }
747
+ let sql = `
748
+ SELECT *,
749
+ CASE
750
+ WHEN name LIKE ? THEN 1.0
751
+ WHEN qualified_name LIKE ? THEN 0.8
752
+ WHEN docstring LIKE ? THEN 0.6
753
+ ELSE 0.4
754
+ END as score
755
+ FROM nodes
756
+ WHERE (${whereClauses.join(' OR ')})
757
+ `;
758
+ // First term for the CASE scoring (use the longest CJK term)
759
+ const primaryTerm = allTerms.reduce((a, b) => a.length >= b.length ? a : b);
760
+ const primaryPattern = `%${primaryTerm}%`;
761
+ const params = [primaryPattern, primaryPattern, primaryPattern, ...whereParams];
762
+ if (kinds && kinds.length > 0) {
763
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
764
+ params.push(...kinds);
765
+ }
766
+ if (languages && languages.length > 0) {
767
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
768
+ params.push(...languages);
769
+ }
770
+ sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
771
+ params.push(limit, offset);
772
+ try {
773
+ const rows = this.db.prepare(sql).all(...params);
774
+ return rows.map((row) => ({
775
+ node: rowToNode(row),
776
+ score: row.score,
777
+ }));
778
+ }
779
+ catch {
780
+ return [];
781
+ }
782
+ }
783
+ /**
784
+ * Find nodes by exact name match
785
+ *
786
+ * Used for hybrid search - looks up symbols by exact name or case-insensitive match.
787
+ * Returns high-confidence matches for known symbol names extracted from query.
788
+ *
789
+ * @param names - Array of symbol names to look up
790
+ * @param options - Search options (kinds, languages, limit)
791
+ * @returns SearchResult array with exact matches scored at 1.0
792
+ */
793
+ findNodesByExactName(names, options = {}) {
794
+ if (names.length === 0)
795
+ return [];
796
+ const { kinds, languages, limit = 50 } = options;
797
+ // Two-pass approach to handle common names (e.g., "run" has 40+ matches):
798
+ // Pass 1: Find which files contain distinctive (rare) symbols from the query.
799
+ // Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
800
+ // Pass 1: Find files containing each queried name, identify distinctive names
801
+ const nameToFiles = new Map();
802
+ for (const name of names) {
803
+ let sql = 'SELECT DISTINCT file_path FROM nodes WHERE name COLLATE NOCASE = ?';
804
+ const params = [name];
805
+ if (kinds && kinds.length > 0) {
806
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
807
+ params.push(...kinds);
808
+ }
809
+ sql += ' LIMIT 100';
810
+ const rows = this.db.prepare(sql).all(...params);
811
+ nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
812
+ }
813
+ // Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
814
+ const distinctiveFiles = new Set();
815
+ for (const [, files] of nameToFiles) {
816
+ if (files.size > 0 && files.size < 10) {
817
+ for (const f of files)
818
+ distinctiveFiles.add(f);
819
+ }
820
+ }
821
+ // Pass 2: Query each name with per-name limit, scoring by co-location
822
+ const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
823
+ const allResults = [];
824
+ const seenIds = new Set();
825
+ for (const name of names) {
826
+ let sql = `
827
+ SELECT nodes.*, 1.0 as score
828
+ FROM nodes
829
+ WHERE name COLLATE NOCASE = ?
830
+ `;
831
+ const params = [name];
832
+ if (kinds && kinds.length > 0) {
833
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
834
+ params.push(...kinds);
835
+ }
836
+ if (languages && languages.length > 0) {
837
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
838
+ params.push(...languages);
839
+ }
840
+ // Fetch enough to find co-located results among common names
841
+ sql += ' LIMIT ?';
842
+ params.push(Math.max(perNameLimit * 3, 50));
843
+ const rows = this.db.prepare(sql).all(...params);
844
+ const nameResults = [];
845
+ for (const row of rows) {
846
+ const node = rowToNode(row);
847
+ if (seenIds.has(node.id))
848
+ continue;
849
+ // Boost results in files that also contain distinctive symbols
850
+ const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
851
+ nameResults.push({ node, score: row.score + coLocationBoost });
852
+ }
853
+ // Sort by score (co-located first), take per-name limit
854
+ nameResults.sort((a, b) => b.score - a.score);
855
+ for (const r of nameResults.slice(0, perNameLimit)) {
856
+ seenIds.add(r.node.id);
857
+ allResults.push(r);
858
+ }
859
+ }
860
+ // Sort all results by score so co-located results bubble up
861
+ allResults.sort((a, b) => b.score - a.score);
862
+ return allResults.slice(0, limit);
863
+ }
864
+ /**
865
+ * Find nodes whose name contains a substring (LIKE-based).
866
+ * Useful for CamelCase-part matching where FTS fails because
867
+ * e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
868
+ *
869
+ * Results are ordered by name length (shorter = more likely to be the core type).
870
+ */
871
+ findNodesByNameSubstring(substring, options = {}) {
872
+ const { kinds, languages, limit = 30, excludePrefix } = options;
873
+ let sql = `
874
+ SELECT nodes.*, 1.0 as score
875
+ FROM nodes
876
+ WHERE name LIKE ?
877
+ `;
878
+ const params = [`%${substring}%`];
879
+ // Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
880
+ if (excludePrefix) {
881
+ sql += ` AND name NOT LIKE ?`;
882
+ params.push(`${substring}%`);
883
+ }
884
+ if (kinds && kinds.length > 0) {
885
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
886
+ params.push(...kinds);
887
+ }
888
+ if (languages && languages.length > 0) {
889
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
890
+ params.push(...languages);
891
+ }
892
+ sql += ' ORDER BY length(name) ASC LIMIT ?';
893
+ params.push(limit);
894
+ const rows = this.db.prepare(sql).all(...params);
895
+ return rows.map((row) => ({
896
+ node: rowToNode(row),
897
+ score: row.score,
898
+ }));
899
+ }
900
+ // ===========================================================================
901
+ // Edge Operations
902
+ // ===========================================================================
903
+ /**
904
+ * Insert a new edge
905
+ */
906
+ insertEdge(edge) {
907
+ if (!this.stmts.insertEdge) {
908
+ this.stmts.insertEdge = this.db.prepare(`
909
+ INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
910
+ VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
911
+ `);
912
+ }
913
+ this.stmts.insertEdge.run({
914
+ source: edge.source,
915
+ target: edge.target,
916
+ kind: edge.kind,
917
+ metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
918
+ line: edge.line ?? null,
919
+ col: edge.column ?? null,
920
+ provenance: edge.provenance ?? null,
921
+ });
922
+ }
923
+ /**
924
+ * Insert multiple edges in a transaction
925
+ */
926
+ insertEdges(edges) {
927
+ this.db.transaction(() => {
928
+ for (const edge of edges) {
929
+ this.insertEdge(edge);
930
+ }
931
+ })();
932
+ }
933
+ /**
934
+ * Delete all edges from a source node
935
+ */
936
+ deleteEdgesBySource(sourceId) {
937
+ if (!this.stmts.deleteEdgesBySource) {
938
+ this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
939
+ }
940
+ this.stmts.deleteEdgesBySource.run(sourceId);
941
+ }
942
+ /**
943
+ * Get outgoing edges from a node
944
+ */
945
+ getOutgoingEdges(sourceId, kinds, provenance) {
946
+ if ((kinds && kinds.length > 0) || provenance) {
947
+ let sql = 'SELECT * FROM edges WHERE source = ?';
948
+ const params = [sourceId];
949
+ if (kinds && kinds.length > 0) {
950
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
951
+ params.push(...kinds);
952
+ }
953
+ if (provenance) {
954
+ sql += ' AND provenance = ?';
955
+ params.push(provenance);
956
+ }
957
+ const rows = this.db.prepare(sql).all(...params);
958
+ return rows.map(rowToEdge);
959
+ }
960
+ if (!this.stmts.getEdgesBySource) {
961
+ this.stmts.getEdgesBySource = this.db.prepare('SELECT * FROM edges WHERE source = ?');
962
+ }
963
+ const rows = this.stmts.getEdgesBySource.all(sourceId);
964
+ return rows.map(rowToEdge);
965
+ }
966
+ /**
967
+ * Get incoming edges to a node
968
+ */
969
+ getIncomingEdges(targetId, kinds) {
970
+ if (kinds && kinds.length > 0) {
971
+ const sql = `SELECT * FROM edges WHERE target = ? AND kind IN (${kinds.map(() => '?').join(',')})`;
972
+ const rows = this.db.prepare(sql).all(targetId, ...kinds);
973
+ return rows.map(rowToEdge);
974
+ }
975
+ if (!this.stmts.getEdgesByTarget) {
976
+ this.stmts.getEdgesByTarget = this.db.prepare('SELECT * FROM edges WHERE target = ?');
977
+ }
978
+ const rows = this.stmts.getEdgesByTarget.all(targetId);
979
+ return rows.map(rowToEdge);
980
+ }
981
+ /**
982
+ * Find all edges where both source and target are in the given node set.
983
+ * Useful for recovering inter-node connectivity after BFS.
984
+ */
985
+ findEdgesBetweenNodes(nodeIds, kinds) {
986
+ if (nodeIds.length === 0)
987
+ return [];
988
+ const idsJson = JSON.stringify(nodeIds);
989
+ let sql = `SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?)) AND target IN (SELECT value FROM json_each(?))`;
990
+ const params = [idsJson, idsJson];
991
+ if (kinds && kinds.length > 0) {
992
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
993
+ params.push(...kinds);
994
+ }
995
+ const rows = this.db.prepare(sql).all(...params);
996
+ return rows.map(rowToEdge);
997
+ }
998
+ // ===========================================================================
999
+ // File Operations
1000
+ // ===========================================================================
1001
+ /**
1002
+ * Insert or update a file record
1003
+ */
1004
+ upsertFile(file) {
1005
+ if (!this.stmts.upsertFile) {
1006
+ this.stmts.upsertFile = this.db.prepare(`
1007
+ INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
1008
+ VALUES (@path, @contentHash, @language, @size, @modifiedAt, @indexedAt, @nodeCount, @errors)
1009
+ ON CONFLICT(path) DO UPDATE SET
1010
+ content_hash = @contentHash,
1011
+ language = @language,
1012
+ size = @size,
1013
+ modified_at = @modifiedAt,
1014
+ indexed_at = @indexedAt,
1015
+ node_count = @nodeCount,
1016
+ errors = @errors
1017
+ `);
1018
+ }
1019
+ this.stmts.upsertFile.run({
1020
+ path: file.path,
1021
+ contentHash: file.contentHash,
1022
+ language: file.language,
1023
+ size: file.size,
1024
+ modifiedAt: file.modifiedAt,
1025
+ indexedAt: file.indexedAt,
1026
+ nodeCount: file.nodeCount,
1027
+ errors: file.errors ? JSON.stringify(file.errors) : null,
1028
+ });
1029
+ }
1030
+ /**
1031
+ * Delete a file record and its nodes
1032
+ */
1033
+ deleteFile(filePath) {
1034
+ this.db.transaction(() => {
1035
+ this.deleteNodesByFile(filePath);
1036
+ if (!this.stmts.deleteFile) {
1037
+ this.stmts.deleteFile = this.db.prepare('DELETE FROM files WHERE path = ?');
1038
+ }
1039
+ this.stmts.deleteFile.run(filePath);
1040
+ })();
1041
+ }
1042
+ /**
1043
+ * Get a file record by path
1044
+ */
1045
+ getFileByPath(filePath) {
1046
+ if (!this.stmts.getFileByPath) {
1047
+ this.stmts.getFileByPath = this.db.prepare('SELECT * FROM files WHERE path = ?');
1048
+ }
1049
+ const row = this.stmts.getFileByPath.get(filePath);
1050
+ return row ? rowToFileRecord(row) : null;
1051
+ }
1052
+ /**
1053
+ * Get all tracked files
1054
+ */
1055
+ getAllFiles() {
1056
+ if (!this.stmts.getAllFiles) {
1057
+ this.stmts.getAllFiles = this.db.prepare('SELECT * FROM files ORDER BY path');
1058
+ }
1059
+ const rows = this.stmts.getAllFiles.all();
1060
+ return rows.map(rowToFileRecord);
1061
+ }
1062
+ /**
1063
+ * Get files that need re-indexing (hash changed)
1064
+ */
1065
+ getStaleFiles(currentHashes) {
1066
+ const files = this.getAllFiles();
1067
+ return files.filter((f) => {
1068
+ const currentHash = currentHashes.get(f.path);
1069
+ return currentHash && currentHash !== f.contentHash;
1070
+ });
1071
+ }
1072
+ // ===========================================================================
1073
+ // Unresolved References
1074
+ // ===========================================================================
1075
+ /**
1076
+ * Insert an unresolved reference
1077
+ */
1078
+ insertUnresolvedRef(ref) {
1079
+ if (!this.stmts.insertUnresolved) {
1080
+ this.stmts.insertUnresolved = this.db.prepare(`
1081
+ INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language)
1082
+ VALUES (@fromNodeId, @referenceName, @referenceKind, @line, @col, @candidates, @filePath, @language)
1083
+ `);
1084
+ }
1085
+ this.stmts.insertUnresolved.run({
1086
+ fromNodeId: ref.fromNodeId,
1087
+ referenceName: ref.referenceName,
1088
+ referenceKind: ref.referenceKind,
1089
+ line: ref.line,
1090
+ col: ref.column,
1091
+ candidates: ref.candidates ? JSON.stringify(ref.candidates) : null,
1092
+ filePath: ref.filePath ?? '',
1093
+ language: ref.language ?? 'unknown',
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Insert multiple unresolved references in a transaction
1098
+ */
1099
+ insertUnresolvedRefsBatch(refs) {
1100
+ if (refs.length === 0)
1101
+ return;
1102
+ const insert = this.db.transaction(() => {
1103
+ for (const ref of refs) {
1104
+ this.insertUnresolvedRef(ref);
1105
+ }
1106
+ });
1107
+ insert();
1108
+ }
1109
+ /**
1110
+ * Delete unresolved references from a node
1111
+ */
1112
+ deleteUnresolvedByNode(nodeId) {
1113
+ if (!this.stmts.deleteUnresolvedByNode) {
1114
+ this.stmts.deleteUnresolvedByNode = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ?');
1115
+ }
1116
+ this.stmts.deleteUnresolvedByNode.run(nodeId);
1117
+ }
1118
+ /**
1119
+ * Get unresolved references by name (for resolution)
1120
+ */
1121
+ getUnresolvedByName(name) {
1122
+ if (!this.stmts.getUnresolvedByName) {
1123
+ this.stmts.getUnresolvedByName = this.db.prepare('SELECT * FROM unresolved_refs WHERE reference_name = ?');
1124
+ }
1125
+ const rows = this.stmts.getUnresolvedByName.all(name);
1126
+ return rows.map((row) => ({
1127
+ fromNodeId: row.from_node_id,
1128
+ referenceName: row.reference_name,
1129
+ referenceKind: row.reference_kind,
1130
+ line: row.line,
1131
+ column: row.col,
1132
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1133
+ filePath: row.file_path,
1134
+ language: row.language,
1135
+ }));
1136
+ }
1137
+ /**
1138
+ * Get all unresolved references
1139
+ */
1140
+ getUnresolvedReferences() {
1141
+ const rows = this.db.prepare('SELECT * FROM unresolved_refs').all();
1142
+ return rows.map((row) => ({
1143
+ fromNodeId: row.from_node_id,
1144
+ referenceName: row.reference_name,
1145
+ referenceKind: row.reference_kind,
1146
+ line: row.line,
1147
+ column: row.col,
1148
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1149
+ filePath: row.file_path,
1150
+ language: row.language,
1151
+ }));
1152
+ }
1153
+ /**
1154
+ * Get the count of unresolved references without loading them into memory
1155
+ */
1156
+ getUnresolvedReferencesCount() {
1157
+ if (!this.stmts.getUnresolvedCount) {
1158
+ this.stmts.getUnresolvedCount = this.db.prepare('SELECT COUNT(*) as count FROM unresolved_refs');
1159
+ }
1160
+ const row = this.stmts.getUnresolvedCount.get();
1161
+ return row.count;
1162
+ }
1163
+ /**
1164
+ * Get a batch of unresolved references using LIMIT/OFFSET pagination.
1165
+ * Used to process references in bounded memory chunks.
1166
+ */
1167
+ getUnresolvedReferencesBatch(offset, limit) {
1168
+ if (!this.stmts.getUnresolvedBatch) {
1169
+ this.stmts.getUnresolvedBatch = this.db.prepare('SELECT * FROM unresolved_refs LIMIT ? OFFSET ?');
1170
+ }
1171
+ const rows = this.stmts.getUnresolvedBatch.all(limit, offset);
1172
+ return rows.map((row) => ({
1173
+ fromNodeId: row.from_node_id,
1174
+ referenceName: row.reference_name,
1175
+ referenceKind: row.reference_kind,
1176
+ line: row.line,
1177
+ column: row.col,
1178
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1179
+ filePath: row.file_path,
1180
+ language: row.language,
1181
+ }));
1182
+ }
1183
+ /**
1184
+ * Get all tracked file paths (lightweight — no full FileRecord objects)
1185
+ */
1186
+ getAllFilePaths() {
1187
+ if (!this.stmts.getAllFilePaths) {
1188
+ this.stmts.getAllFilePaths = this.db.prepare('SELECT path FROM files ORDER BY path');
1189
+ }
1190
+ const rows = this.stmts.getAllFilePaths.all();
1191
+ return rows.map((r) => r.path);
1192
+ }
1193
+ /**
1194
+ * Get all distinct node names (lightweight — just name strings for pre-filtering)
1195
+ */
1196
+ getAllNodeNames() {
1197
+ if (!this.stmts.getAllNodeNames) {
1198
+ this.stmts.getAllNodeNames = this.db.prepare('SELECT DISTINCT name FROM nodes');
1199
+ }
1200
+ const rows = this.stmts.getAllNodeNames.all();
1201
+ return rows.map((r) => r.name);
1202
+ }
1203
+ /**
1204
+ * Get unresolved references scoped to specific file paths.
1205
+ * Uses the idx_unresolved_file_path index for efficient lookup.
1206
+ */
1207
+ getUnresolvedReferencesByFiles(filePaths) {
1208
+ if (filePaths.length === 0)
1209
+ return [];
1210
+ const placeholders = filePaths.map(() => '?').join(',');
1211
+ const rows = this.db
1212
+ .prepare(`SELECT * FROM unresolved_refs WHERE file_path IN (${placeholders})`)
1213
+ .all(...filePaths);
1214
+ return rows.map((row) => ({
1215
+ fromNodeId: row.from_node_id,
1216
+ referenceName: row.reference_name,
1217
+ referenceKind: row.reference_kind,
1218
+ line: row.line,
1219
+ column: row.col,
1220
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1221
+ filePath: row.file_path,
1222
+ language: row.language,
1223
+ }));
1224
+ }
1225
+ /**
1226
+ * Delete all unresolved references (after resolution)
1227
+ */
1228
+ clearUnresolvedReferences() {
1229
+ this.db.exec('DELETE FROM unresolved_refs');
1230
+ }
1231
+ /**
1232
+ * Delete resolved references by their IDs
1233
+ */
1234
+ deleteResolvedReferences(fromNodeIds) {
1235
+ if (fromNodeIds.length === 0)
1236
+ return;
1237
+ const placeholders = fromNodeIds.map(() => '?').join(',');
1238
+ this.db.prepare(`DELETE FROM unresolved_refs WHERE from_node_id IN (${placeholders})`).run(...fromNodeIds);
1239
+ }
1240
+ /**
1241
+ * Delete unresolved refs with null/empty reference_name to prevent
1242
+ * infinite batch loops (patched by Saluzi for v0.9.4 compatibility).
1243
+ */
1244
+ deleteNullReferenceNames() {
1245
+ this.db.prepare("DELETE FROM unresolved_refs WHERE reference_name IS NULL OR reference_name = ''").run();
1246
+ }
1247
+ /**
1248
+ * Delete specific resolved references by (fromNodeId, referenceName, referenceKind) tuples.
1249
+ * More precise than deleteResolvedReferences — only removes refs that were actually resolved.
1250
+ */
1251
+ deleteSpecificResolvedReferences(refs) {
1252
+ if (refs.length === 0)
1253
+ return;
1254
+ const stmt = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?');
1255
+ const deleteMany = this.db.transaction((items) => {
1256
+ for (const ref of items) {
1257
+ stmt.run(ref.fromNodeId, ref.referenceName, ref.referenceKind);
1258
+ }
1259
+ });
1260
+ deleteMany(refs);
1261
+ }
1262
+ // ===========================================================================
1263
+ // Statistics
1264
+ // ===========================================================================
1265
+ /**
1266
+ * Get graph statistics
1267
+ */
1268
+ getStats() {
1269
+ // Single query for all three aggregate counts
1270
+ const counts = this.db.prepare(`
1271
+ SELECT
1272
+ (SELECT COUNT(*) FROM nodes) AS node_count,
1273
+ (SELECT COUNT(*) FROM edges) AS edge_count,
1274
+ (SELECT COUNT(*) FROM files) AS file_count
1275
+ `).get();
1276
+ const nodesByKind = {};
1277
+ const nodeKindRows = this.db
1278
+ .prepare('SELECT kind, COUNT(*) as count FROM nodes GROUP BY kind')
1279
+ .all();
1280
+ for (const row of nodeKindRows) {
1281
+ nodesByKind[row.kind] = row.count;
1282
+ }
1283
+ const edgesByKind = {};
1284
+ const edgeKindRows = this.db
1285
+ .prepare('SELECT kind, COUNT(*) as count FROM edges GROUP BY kind')
1286
+ .all();
1287
+ for (const row of edgeKindRows) {
1288
+ edgesByKind[row.kind] = row.count;
1289
+ }
1290
+ const filesByLanguage = {};
1291
+ const languageRows = this.db
1292
+ .prepare('SELECT language, COUNT(*) as count FROM files GROUP BY language')
1293
+ .all();
1294
+ for (const row of languageRows) {
1295
+ filesByLanguage[row.language] = row.count;
1296
+ }
1297
+ return {
1298
+ nodeCount: counts.node_count,
1299
+ edgeCount: counts.edge_count,
1300
+ fileCount: counts.file_count,
1301
+ nodesByKind,
1302
+ edgesByKind,
1303
+ filesByLanguage,
1304
+ dbSizeBytes: 0, // Set by caller using DatabaseConnection.getSize()
1305
+ lastUpdated: Date.now(),
1306
+ };
1307
+ }
1308
+ // ===========================================================================
1309
+ // Project Metadata
1310
+ // ===========================================================================
1311
+ /**
1312
+ * Get a metadata value by key
1313
+ */
1314
+ getMetadata(key) {
1315
+ const row = this.db.prepare('SELECT value FROM project_metadata WHERE key = ?').get(key);
1316
+ return row?.value ?? null;
1317
+ }
1318
+ /**
1319
+ * Set a metadata key-value pair (upsert)
1320
+ */
1321
+ setMetadata(key, value) {
1322
+ this.db.prepare('INSERT INTO project_metadata (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at').run(key, value, Date.now());
1323
+ }
1324
+ /**
1325
+ * Get all metadata as a key-value record
1326
+ */
1327
+ getAllMetadata() {
1328
+ const rows = this.db.prepare('SELECT key, value FROM project_metadata').all();
1329
+ const result = {};
1330
+ for (const row of rows) {
1331
+ result[row.key] = row.value;
1332
+ }
1333
+ return result;
1334
+ }
1335
+ /**
1336
+ * Clear all data from the database
1337
+ */
1338
+ clear() {
1339
+ this.nodeCache.clear();
1340
+ this.db.transaction(() => {
1341
+ this.db.exec('DELETE FROM unresolved_refs');
1342
+ this.db.exec('DELETE FROM edges');
1343
+ this.db.exec('DELETE FROM nodes');
1344
+ this.db.exec('DELETE FROM files');
1345
+ })();
1346
+ }
1347
+ }
1348
+ exports.QueryBuilder = QueryBuilder;
1349
+ //# sourceMappingURL=queries.js.map