@stupidloud/codegraph 0.7.7

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