@saluzi/codegraph 0.2.0 → 0.2.2

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 (658) hide show
  1. package/README.md +2 -2
  2. package/dist/bin/codegraph.d.ts +26 -0
  3. package/dist/bin/codegraph.d.ts.map +1 -0
  4. package/dist/bin/codegraph.js +2249 -0
  5. package/dist/bin/codegraph.js.map +1 -0
  6. package/dist/bin/command-supervision.d.ts +49 -0
  7. package/dist/bin/command-supervision.d.ts.map +1 -0
  8. package/dist/bin/command-supervision.js +95 -0
  9. package/dist/bin/command-supervision.js.map +1 -0
  10. package/dist/bin/fatal-handler.d.ts +20 -0
  11. package/dist/bin/fatal-handler.d.ts.map +1 -0
  12. package/dist/bin/fatal-handler.js +118 -0
  13. package/dist/bin/fatal-handler.js.map +1 -0
  14. package/dist/bin/node-version-check.d.ts +37 -0
  15. package/dist/bin/node-version-check.d.ts.map +1 -0
  16. package/dist/bin/node-version-check.js +79 -0
  17. package/dist/bin/node-version-check.js.map +1 -0
  18. package/dist/bin/uninstall.d.ts +14 -0
  19. package/dist/bin/uninstall.d.ts.map +1 -0
  20. package/dist/bin/uninstall.js +36 -0
  21. package/dist/bin/uninstall.js.map +1 -0
  22. package/dist/context/formatter.d.ts +30 -0
  23. package/dist/context/formatter.d.ts.map +1 -0
  24. package/dist/context/formatter.js +263 -0
  25. package/dist/context/formatter.js.map +1 -0
  26. package/dist/context/index.d.ts +119 -0
  27. package/dist/context/index.d.ts.map +1 -0
  28. package/dist/context/index.js +1296 -0
  29. package/dist/context/index.js.map +1 -0
  30. package/dist/context/markers.d.ts +19 -0
  31. package/dist/context/markers.d.ts.map +1 -0
  32. package/dist/context/markers.js +22 -0
  33. package/dist/context/markers.js.map +1 -0
  34. package/dist/db/index.d.ts +201 -0
  35. package/dist/db/index.d.ts.map +1 -0
  36. package/dist/db/index.js +493 -0
  37. package/dist/db/index.js.map +1 -0
  38. package/dist/db/migrations.d.ts +44 -0
  39. package/dist/db/migrations.d.ts.map +1 -0
  40. package/dist/db/migrations.js +212 -0
  41. package/dist/db/migrations.js.map +1 -0
  42. package/dist/db/queries.d.ts +513 -0
  43. package/dist/db/queries.d.ts.map +1 -0
  44. package/dist/db/queries.js +1886 -0
  45. package/dist/db/queries.js.map +1 -0
  46. package/dist/db/schema.sql +194 -0
  47. package/dist/db/sqlite-adapter.d.ts +65 -0
  48. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  49. package/dist/db/sqlite-adapter.js +274 -0
  50. package/dist/db/sqlite-adapter.js.map +1 -0
  51. package/dist/db/wal-valve.d.ts +106 -0
  52. package/dist/db/wal-valve.d.ts.map +1 -0
  53. package/dist/db/wal-valve.js +208 -0
  54. package/dist/db/wal-valve.js.map +1 -0
  55. package/dist/directory.d.ts +183 -0
  56. package/dist/directory.d.ts.map +1 -0
  57. package/dist/directory.js +797 -0
  58. package/dist/directory.js.map +1 -0
  59. package/dist/errors.d.ts +136 -0
  60. package/dist/errors.d.ts.map +1 -0
  61. package/dist/errors.js +219 -0
  62. package/dist/errors.js.map +1 -0
  63. package/dist/extraction/astro-extractor.d.ts +79 -0
  64. package/dist/extraction/astro-extractor.d.ts.map +1 -0
  65. package/dist/extraction/astro-extractor.js +320 -0
  66. package/dist/extraction/astro-extractor.js.map +1 -0
  67. package/dist/extraction/cfml-extractor.d.ts +107 -0
  68. package/dist/extraction/cfml-extractor.d.ts.map +1 -0
  69. package/dist/extraction/cfml-extractor.js +494 -0
  70. package/dist/extraction/cfml-extractor.js.map +1 -0
  71. package/dist/extraction/dfm-extractor.d.ts +31 -0
  72. package/dist/extraction/dfm-extractor.d.ts.map +1 -0
  73. package/dist/extraction/dfm-extractor.js +151 -0
  74. package/dist/extraction/dfm-extractor.js.map +1 -0
  75. package/dist/extraction/extraction-version.d.ts +25 -0
  76. package/dist/extraction/extraction-version.d.ts.map +1 -0
  77. package/dist/extraction/extraction-version.js +28 -0
  78. package/dist/extraction/extraction-version.js.map +1 -0
  79. package/dist/extraction/function-ref.d.ts +118 -0
  80. package/dist/extraction/function-ref.d.ts.map +1 -0
  81. package/dist/extraction/function-ref.js +727 -0
  82. package/dist/extraction/function-ref.js.map +1 -0
  83. package/dist/extraction/generated-detection.d.ts +30 -0
  84. package/dist/extraction/generated-detection.d.ts.map +1 -0
  85. package/dist/extraction/generated-detection.js +83 -0
  86. package/dist/extraction/generated-detection.js.map +1 -0
  87. package/dist/extraction/grammars.d.ts +138 -0
  88. package/dist/extraction/grammars.d.ts.map +1 -0
  89. package/dist/extraction/grammars.js +631 -0
  90. package/dist/extraction/grammars.js.map +1 -0
  91. package/dist/extraction/index.d.ts +232 -0
  92. package/dist/extraction/index.d.ts.map +1 -0
  93. package/dist/extraction/index.js +2409 -0
  94. package/dist/extraction/index.js.map +1 -0
  95. package/dist/extraction/languages/arkts.d.ts +3 -0
  96. package/dist/extraction/languages/arkts.d.ts.map +1 -0
  97. package/dist/extraction/languages/arkts.js +127 -0
  98. package/dist/extraction/languages/arkts.js.map +1 -0
  99. package/dist/extraction/languages/c-cpp.d.ts +110 -0
  100. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  101. package/dist/extraction/languages/c-cpp.js +837 -0
  102. package/dist/extraction/languages/c-cpp.js.map +1 -0
  103. package/dist/extraction/languages/cfquery.d.ts +12 -0
  104. package/dist/extraction/languages/cfquery.d.ts.map +1 -0
  105. package/dist/extraction/languages/cfquery.js +28 -0
  106. package/dist/extraction/languages/cfquery.js.map +1 -0
  107. package/dist/extraction/languages/cfscript.d.ts +3 -0
  108. package/dist/extraction/languages/cfscript.d.ts.map +1 -0
  109. package/dist/extraction/languages/cfscript.js +73 -0
  110. package/dist/extraction/languages/cfscript.js.map +1 -0
  111. package/dist/extraction/languages/cobol.d.ts +33 -0
  112. package/dist/extraction/languages/cobol.d.ts.map +1 -0
  113. package/dist/extraction/languages/cobol.js +499 -0
  114. package/dist/extraction/languages/cobol.js.map +1 -0
  115. package/dist/extraction/languages/csharp.d.ts +25 -0
  116. package/dist/extraction/languages/csharp.d.ts.map +1 -0
  117. package/dist/extraction/languages/csharp.js +175 -0
  118. package/dist/extraction/languages/csharp.js.map +1 -0
  119. package/dist/extraction/languages/dart.d.ts +3 -0
  120. package/dist/extraction/languages/dart.d.ts.map +1 -0
  121. package/dist/extraction/languages/dart.js +374 -0
  122. package/dist/extraction/languages/dart.js.map +1 -0
  123. package/dist/extraction/languages/erlang.d.ts +3 -0
  124. package/dist/extraction/languages/erlang.d.ts.map +1 -0
  125. package/dist/extraction/languages/erlang.js +350 -0
  126. package/dist/extraction/languages/erlang.js.map +1 -0
  127. package/dist/extraction/languages/go.d.ts +3 -0
  128. package/dist/extraction/languages/go.d.ts.map +1 -0
  129. package/dist/extraction/languages/go.js +111 -0
  130. package/dist/extraction/languages/go.js.map +1 -0
  131. package/dist/extraction/languages/index.d.ts +10 -0
  132. package/dist/extraction/languages/index.d.ts.map +1 -0
  133. package/dist/extraction/languages/index.js +71 -0
  134. package/dist/extraction/languages/index.js.map +1 -0
  135. package/dist/extraction/languages/java.d.ts +3 -0
  136. package/dist/extraction/languages/java.d.ts.map +1 -0
  137. package/dist/extraction/languages/java.js +315 -0
  138. package/dist/extraction/languages/java.js.map +1 -0
  139. package/dist/extraction/languages/javascript.d.ts +3 -0
  140. package/dist/extraction/languages/javascript.d.ts.map +1 -0
  141. package/dist/extraction/languages/javascript.js +106 -0
  142. package/dist/extraction/languages/javascript.js.map +1 -0
  143. package/dist/extraction/languages/kotlin.d.ts +3 -0
  144. package/dist/extraction/languages/kotlin.d.ts.map +1 -0
  145. package/dist/extraction/languages/kotlin.js +379 -0
  146. package/dist/extraction/languages/kotlin.js.map +1 -0
  147. package/dist/extraction/languages/lua.d.ts +3 -0
  148. package/dist/extraction/languages/lua.d.ts.map +1 -0
  149. package/dist/extraction/languages/lua.js +150 -0
  150. package/dist/extraction/languages/lua.js.map +1 -0
  151. package/dist/extraction/languages/luau.d.ts +3 -0
  152. package/dist/extraction/languages/luau.d.ts.map +1 -0
  153. package/dist/extraction/languages/luau.js +37 -0
  154. package/dist/extraction/languages/luau.js.map +1 -0
  155. package/dist/extraction/languages/nix.d.ts +3 -0
  156. package/dist/extraction/languages/nix.d.ts.map +1 -0
  157. package/dist/extraction/languages/nix.js +294 -0
  158. package/dist/extraction/languages/nix.js.map +1 -0
  159. package/dist/extraction/languages/objc.d.ts +3 -0
  160. package/dist/extraction/languages/objc.d.ts.map +1 -0
  161. package/dist/extraction/languages/objc.js +175 -0
  162. package/dist/extraction/languages/objc.js.map +1 -0
  163. package/dist/extraction/languages/pascal.d.ts +3 -0
  164. package/dist/extraction/languages/pascal.d.ts.map +1 -0
  165. package/dist/extraction/languages/pascal.js +77 -0
  166. package/dist/extraction/languages/pascal.js.map +1 -0
  167. package/dist/extraction/languages/php.d.ts +3 -0
  168. package/dist/extraction/languages/php.d.ts.map +1 -0
  169. package/dist/extraction/languages/php.js +196 -0
  170. package/dist/extraction/languages/php.js.map +1 -0
  171. package/dist/extraction/languages/python.d.ts +3 -0
  172. package/dist/extraction/languages/python.d.ts.map +1 -0
  173. package/dist/extraction/languages/python.js +56 -0
  174. package/dist/extraction/languages/python.js.map +1 -0
  175. package/dist/extraction/languages/r.d.ts +3 -0
  176. package/dist/extraction/languages/r.d.ts.map +1 -0
  177. package/dist/extraction/languages/r.js +314 -0
  178. package/dist/extraction/languages/r.js.map +1 -0
  179. package/dist/extraction/languages/ruby.d.ts +3 -0
  180. package/dist/extraction/languages/ruby.d.ts.map +1 -0
  181. package/dist/extraction/languages/ruby.js +149 -0
  182. package/dist/extraction/languages/ruby.js.map +1 -0
  183. package/dist/extraction/languages/rust.d.ts +3 -0
  184. package/dist/extraction/languages/rust.d.ts.map +1 -0
  185. package/dist/extraction/languages/rust.js +142 -0
  186. package/dist/extraction/languages/rust.js.map +1 -0
  187. package/dist/extraction/languages/scala.d.ts +3 -0
  188. package/dist/extraction/languages/scala.d.ts.map +1 -0
  189. package/dist/extraction/languages/scala.js +209 -0
  190. package/dist/extraction/languages/scala.js.map +1 -0
  191. package/dist/extraction/languages/solidity.d.ts +3 -0
  192. package/dist/extraction/languages/solidity.d.ts.map +1 -0
  193. package/dist/extraction/languages/solidity.js +293 -0
  194. package/dist/extraction/languages/solidity.js.map +1 -0
  195. package/dist/extraction/languages/swift.d.ts +3 -0
  196. package/dist/extraction/languages/swift.d.ts.map +1 -0
  197. package/dist/extraction/languages/swift.js +152 -0
  198. package/dist/extraction/languages/swift.js.map +1 -0
  199. package/dist/extraction/languages/terraform.d.ts +3 -0
  200. package/dist/extraction/languages/terraform.d.ts.map +1 -0
  201. package/dist/extraction/languages/terraform.js +641 -0
  202. package/dist/extraction/languages/terraform.js.map +1 -0
  203. package/dist/extraction/languages/typescript.d.ts +16 -0
  204. package/dist/extraction/languages/typescript.d.ts.map +1 -0
  205. package/dist/extraction/languages/typescript.js +167 -0
  206. package/dist/extraction/languages/typescript.js.map +1 -0
  207. package/dist/extraction/languages/vbnet.d.ts +11 -0
  208. package/dist/extraction/languages/vbnet.d.ts.map +1 -0
  209. package/dist/extraction/languages/vbnet.js +141 -0
  210. package/dist/extraction/languages/vbnet.js.map +1 -0
  211. package/dist/extraction/liquid-extractor.d.ts +59 -0
  212. package/dist/extraction/liquid-extractor.d.ts.map +1 -0
  213. package/dist/extraction/liquid-extractor.js +357 -0
  214. package/dist/extraction/liquid-extractor.js.map +1 -0
  215. package/dist/extraction/mybatis-extractor.d.ts +68 -0
  216. package/dist/extraction/mybatis-extractor.d.ts.map +1 -0
  217. package/dist/extraction/mybatis-extractor.js +300 -0
  218. package/dist/extraction/mybatis-extractor.js.map +1 -0
  219. package/dist/extraction/parse-pool.d.ts +152 -0
  220. package/dist/extraction/parse-pool.d.ts.map +1 -0
  221. package/dist/extraction/parse-pool.js +387 -0
  222. package/dist/extraction/parse-pool.js.map +1 -0
  223. package/dist/extraction/parse-worker.d.ts +8 -0
  224. package/dist/extraction/parse-worker.d.ts.map +1 -0
  225. package/dist/extraction/parse-worker.js +104 -0
  226. package/dist/extraction/parse-worker.js.map +1 -0
  227. package/dist/extraction/razor-extractor.d.ts +42 -0
  228. package/dist/extraction/razor-extractor.d.ts.map +1 -0
  229. package/dist/extraction/razor-extractor.js +285 -0
  230. package/dist/extraction/razor-extractor.js.map +1 -0
  231. package/dist/extraction/svelte-extractor.d.ts +56 -0
  232. package/dist/extraction/svelte-extractor.d.ts.map +1 -0
  233. package/dist/extraction/svelte-extractor.js +275 -0
  234. package/dist/extraction/svelte-extractor.js.map +1 -0
  235. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  236. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  237. package/dist/extraction/tree-sitter-helpers.js +153 -0
  238. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  239. package/dist/extraction/tree-sitter-types.d.ts +258 -0
  240. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  241. package/dist/extraction/tree-sitter-types.js +10 -0
  242. package/dist/extraction/tree-sitter-types.js.map +1 -0
  243. package/dist/extraction/tree-sitter.d.ts +706 -0
  244. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  245. package/dist/extraction/tree-sitter.js +6506 -0
  246. package/dist/extraction/tree-sitter.js.map +1 -0
  247. package/dist/extraction/vue-extractor.d.ts +51 -0
  248. package/dist/extraction/vue-extractor.d.ts.map +1 -0
  249. package/dist/extraction/vue-extractor.js +254 -0
  250. package/dist/extraction/vue-extractor.js.map +1 -0
  251. package/dist/extraction/wasm/tree-sitter-arkts.wasm +0 -0
  252. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  253. package/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  254. package/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  255. package/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  256. package/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  257. package/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  258. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  259. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  260. package/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  261. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  262. package/dist/extraction/wasm/tree-sitter-r.wasm +0 -0
  263. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  264. package/dist/extraction/wasm/tree-sitter-terraform.wasm +0 -0
  265. package/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  266. package/dist/extraction/wasm-runtime-flags.d.ts +38 -0
  267. package/dist/extraction/wasm-runtime-flags.d.ts.map +1 -0
  268. package/dist/extraction/wasm-runtime-flags.js +106 -0
  269. package/dist/extraction/wasm-runtime-flags.js.map +1 -0
  270. package/dist/graph/index.d.ts +8 -0
  271. package/dist/graph/index.d.ts.map +1 -0
  272. package/dist/graph/index.js +13 -0
  273. package/dist/graph/index.js.map +1 -0
  274. package/dist/graph/queries.d.ts +106 -0
  275. package/dist/graph/queries.d.ts.map +1 -0
  276. package/dist/graph/queries.js +339 -0
  277. package/dist/graph/queries.js.map +1 -0
  278. package/dist/graph/traversal.d.ts +127 -0
  279. package/dist/graph/traversal.d.ts.map +1 -0
  280. package/dist/graph/traversal.js +599 -0
  281. package/dist/graph/traversal.js.map +1 -0
  282. package/dist/index.d.ts +644 -0
  283. package/dist/index.d.ts.map +1 -0
  284. package/dist/index.js +1492 -0
  285. package/dist/index.js.map +1 -0
  286. package/dist/installer/config-writer.d.ts +28 -0
  287. package/dist/installer/config-writer.d.ts.map +1 -0
  288. package/dist/installer/config-writer.js +91 -0
  289. package/dist/installer/config-writer.js.map +1 -0
  290. package/dist/installer/index.d.ts +142 -0
  291. package/dist/installer/index.d.ts.map +1 -0
  292. package/dist/installer/index.js +619 -0
  293. package/dist/installer/index.js.map +1 -0
  294. package/dist/installer/instructions-template.d.ts +41 -0
  295. package/dist/installer/instructions-template.d.ts.map +1 -0
  296. package/dist/installer/instructions-template.js +53 -0
  297. package/dist/installer/instructions-template.js.map +1 -0
  298. package/dist/installer/targets/antigravity.d.ts +57 -0
  299. package/dist/installer/targets/antigravity.d.ts.map +1 -0
  300. package/dist/installer/targets/antigravity.js +308 -0
  301. package/dist/installer/targets/antigravity.js.map +1 -0
  302. package/dist/installer/targets/claude.d.ts +62 -0
  303. package/dist/installer/targets/claude.d.ts.map +1 -0
  304. package/dist/installer/targets/claude.js +454 -0
  305. package/dist/installer/targets/claude.js.map +1 -0
  306. package/dist/installer/targets/codex.d.ts +18 -0
  307. package/dist/installer/targets/codex.d.ts.map +1 -0
  308. package/dist/installer/targets/codex.js +185 -0
  309. package/dist/installer/targets/codex.js.map +1 -0
  310. package/dist/installer/targets/cursor.d.ts +35 -0
  311. package/dist/installer/targets/cursor.d.ts.map +1 -0
  312. package/dist/installer/targets/cursor.js +254 -0
  313. package/dist/installer/targets/cursor.js.map +1 -0
  314. package/dist/installer/targets/gemini.d.ts +26 -0
  315. package/dist/installer/targets/gemini.d.ts.map +1 -0
  316. package/dist/installer/targets/gemini.js +165 -0
  317. package/dist/installer/targets/gemini.js.map +1 -0
  318. package/dist/installer/targets/hermes.d.ts +18 -0
  319. package/dist/installer/targets/hermes.d.ts.map +1 -0
  320. package/dist/installer/targets/hermes.js +359 -0
  321. package/dist/installer/targets/hermes.js.map +1 -0
  322. package/dist/installer/targets/kiro.d.ts +27 -0
  323. package/dist/installer/targets/kiro.d.ts.map +1 -0
  324. package/dist/installer/targets/kiro.js +178 -0
  325. package/dist/installer/targets/kiro.js.map +1 -0
  326. package/dist/installer/targets/opencode.d.ts +38 -0
  327. package/dist/installer/targets/opencode.d.ts.map +1 -0
  328. package/dist/installer/targets/opencode.js +288 -0
  329. package/dist/installer/targets/opencode.js.map +1 -0
  330. package/dist/installer/targets/registry.d.ts +35 -0
  331. package/dist/installer/targets/registry.d.ts.map +1 -0
  332. package/dist/installer/targets/registry.js +91 -0
  333. package/dist/installer/targets/registry.js.map +1 -0
  334. package/dist/installer/targets/shared.d.ts +101 -0
  335. package/dist/installer/targets/shared.d.ts.map +1 -0
  336. package/dist/installer/targets/shared.js +264 -0
  337. package/dist/installer/targets/shared.js.map +1 -0
  338. package/dist/installer/targets/toml.d.ts +52 -0
  339. package/dist/installer/targets/toml.d.ts.map +1 -0
  340. package/dist/installer/targets/toml.js +147 -0
  341. package/dist/installer/targets/toml.js.map +1 -0
  342. package/dist/installer/targets/types.d.ts +108 -0
  343. package/dist/installer/targets/types.d.ts.map +1 -0
  344. package/dist/installer/targets/types.js +16 -0
  345. package/dist/installer/targets/types.js.map +1 -0
  346. package/dist/mcp/daemon-manager.d.ts +42 -0
  347. package/dist/mcp/daemon-manager.d.ts.map +1 -0
  348. package/dist/mcp/daemon-manager.js +129 -0
  349. package/dist/mcp/daemon-manager.js.map +1 -0
  350. package/dist/mcp/daemon-paths.d.ts +73 -0
  351. package/dist/mcp/daemon-paths.d.ts.map +1 -0
  352. package/dist/mcp/daemon-paths.js +165 -0
  353. package/dist/mcp/daemon-paths.js.map +1 -0
  354. package/dist/mcp/daemon-registry.d.ts +47 -0
  355. package/dist/mcp/daemon-registry.d.ts.map +1 -0
  356. package/dist/mcp/daemon-registry.js +233 -0
  357. package/dist/mcp/daemon-registry.js.map +1 -0
  358. package/dist/mcp/daemon.d.ts +290 -0
  359. package/dist/mcp/daemon.d.ts.map +1 -0
  360. package/dist/mcp/daemon.js +862 -0
  361. package/dist/mcp/daemon.js.map +1 -0
  362. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  363. package/dist/mcp/dynamic-boundaries.d.ts.map +1 -0
  364. package/dist/mcp/dynamic-boundaries.js +360 -0
  365. package/dist/mcp/dynamic-boundaries.js.map +1 -0
  366. package/dist/mcp/early-ppid.d.ts +26 -0
  367. package/dist/mcp/early-ppid.d.ts.map +1 -0
  368. package/dist/mcp/early-ppid.js +29 -0
  369. package/dist/mcp/early-ppid.js.map +1 -0
  370. package/dist/mcp/engine.d.ts +122 -0
  371. package/dist/mcp/engine.d.ts.map +1 -0
  372. package/dist/mcp/engine.js +350 -0
  373. package/dist/mcp/engine.js.map +1 -0
  374. package/dist/mcp/index.d.ts +113 -0
  375. package/dist/mcp/index.d.ts.map +1 -0
  376. package/dist/mcp/index.js +506 -0
  377. package/dist/mcp/index.js.map +1 -0
  378. package/dist/mcp/liveness-watchdog.d.ts +35 -0
  379. package/dist/mcp/liveness-watchdog.d.ts.map +1 -0
  380. package/dist/mcp/liveness-watchdog.js +267 -0
  381. package/dist/mcp/liveness-watchdog.js.map +1 -0
  382. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  383. package/dist/mcp/ppid-watchdog.d.ts.map +1 -0
  384. package/dist/mcp/ppid-watchdog.js +64 -0
  385. package/dist/mcp/ppid-watchdog.js.map +1 -0
  386. package/dist/mcp/proxy.d.ts +87 -0
  387. package/dist/mcp/proxy.d.ts.map +1 -0
  388. package/dist/mcp/proxy.js +667 -0
  389. package/dist/mcp/proxy.js.map +1 -0
  390. package/dist/mcp/query-pool.d.ts +108 -0
  391. package/dist/mcp/query-pool.d.ts.map +1 -0
  392. package/dist/mcp/query-pool.js +315 -0
  393. package/dist/mcp/query-pool.js.map +1 -0
  394. package/dist/mcp/query-worker.d.ts +24 -0
  395. package/dist/mcp/query-worker.d.ts.map +1 -0
  396. package/dist/mcp/query-worker.js +87 -0
  397. package/dist/mcp/query-worker.js.map +1 -0
  398. package/dist/mcp/server-instructions.d.ts +34 -0
  399. package/dist/mcp/server-instructions.d.ts.map +1 -0
  400. package/dist/mcp/server-instructions.js +106 -0
  401. package/dist/mcp/server-instructions.js.map +1 -0
  402. package/dist/mcp/session.d.ts +93 -0
  403. package/dist/mcp/session.d.ts.map +1 -0
  404. package/dist/mcp/session.js +357 -0
  405. package/dist/mcp/session.js.map +1 -0
  406. package/dist/mcp/startup-handshake.d.ts +44 -0
  407. package/dist/mcp/startup-handshake.d.ts.map +1 -0
  408. package/dist/mcp/startup-handshake.js +73 -0
  409. package/dist/mcp/startup-handshake.js.map +1 -0
  410. package/dist/mcp/stdin-teardown.d.ts +27 -0
  411. package/dist/mcp/stdin-teardown.d.ts.map +1 -0
  412. package/dist/mcp/stdin-teardown.js +49 -0
  413. package/dist/mcp/stdin-teardown.js.map +1 -0
  414. package/dist/mcp/tools.d.ts +613 -0
  415. package/dist/mcp/tools.d.ts.map +1 -0
  416. package/dist/mcp/tools.js +4477 -0
  417. package/dist/mcp/tools.js.map +1 -0
  418. package/dist/mcp/transport.d.ts +188 -0
  419. package/dist/mcp/transport.d.ts.map +1 -0
  420. package/dist/mcp/transport.js +377 -0
  421. package/dist/mcp/transport.js.map +1 -0
  422. package/dist/mcp/version.d.ts +19 -0
  423. package/dist/mcp/version.d.ts.map +1 -0
  424. package/dist/mcp/version.js +71 -0
  425. package/dist/mcp/version.js.map +1 -0
  426. package/dist/project-config.d.ts +94 -0
  427. package/dist/project-config.d.ts.map +1 -0
  428. package/dist/project-config.js +374 -0
  429. package/dist/project-config.js.map +1 -0
  430. package/dist/resolution/c-fnptr-synthesizer.d.ts +6 -0
  431. package/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -0
  432. package/dist/resolution/c-fnptr-synthesizer.js +1062 -0
  433. package/dist/resolution/c-fnptr-synthesizer.js.map +1 -0
  434. package/dist/resolution/callback-synthesizer.d.ts +15 -0
  435. package/dist/resolution/callback-synthesizer.d.ts.map +1 -0
  436. package/dist/resolution/callback-synthesizer.js +3938 -0
  437. package/dist/resolution/callback-synthesizer.js.map +1 -0
  438. package/dist/resolution/cooperative-yield.d.ts +32 -0
  439. package/dist/resolution/cooperative-yield.d.ts.map +1 -0
  440. package/dist/resolution/cooperative-yield.js +42 -0
  441. package/dist/resolution/cooperative-yield.js.map +1 -0
  442. package/dist/resolution/frameworks/astro.d.ts +9 -0
  443. package/dist/resolution/frameworks/astro.d.ts.map +1 -0
  444. package/dist/resolution/frameworks/astro.js +169 -0
  445. package/dist/resolution/frameworks/astro.js.map +1 -0
  446. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  447. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  448. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  449. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  450. package/dist/resolution/frameworks/cics.d.ts +20 -0
  451. package/dist/resolution/frameworks/cics.d.ts.map +1 -0
  452. package/dist/resolution/frameworks/cics.js +90 -0
  453. package/dist/resolution/frameworks/cics.js.map +1 -0
  454. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  455. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  456. package/dist/resolution/frameworks/csharp.js +241 -0
  457. package/dist/resolution/frameworks/csharp.js.map +1 -0
  458. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  459. package/dist/resolution/frameworks/drupal.d.ts.map +1 -0
  460. package/dist/resolution/frameworks/drupal.js +367 -0
  461. package/dist/resolution/frameworks/drupal.js.map +1 -0
  462. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  463. package/dist/resolution/frameworks/expo-modules.d.ts.map +1 -0
  464. package/dist/resolution/frameworks/expo-modules.js +148 -0
  465. package/dist/resolution/frameworks/expo-modules.js.map +1 -0
  466. package/dist/resolution/frameworks/express.d.ts +8 -0
  467. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  468. package/dist/resolution/frameworks/express.js +308 -0
  469. package/dist/resolution/frameworks/express.js.map +1 -0
  470. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  471. package/dist/resolution/frameworks/fabric.d.ts.map +1 -0
  472. package/dist/resolution/frameworks/fabric.js +354 -0
  473. package/dist/resolution/frameworks/fabric.js.map +1 -0
  474. package/dist/resolution/frameworks/go.d.ts +8 -0
  475. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  476. package/dist/resolution/frameworks/go.js +161 -0
  477. package/dist/resolution/frameworks/go.js.map +1 -0
  478. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  479. package/dist/resolution/frameworks/goframe.d.ts.map +1 -0
  480. package/dist/resolution/frameworks/goframe.js +112 -0
  481. package/dist/resolution/frameworks/goframe.js.map +1 -0
  482. package/dist/resolution/frameworks/index.d.ts +50 -0
  483. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  484. package/dist/resolution/frameworks/index.js +175 -0
  485. package/dist/resolution/frameworks/index.js.map +1 -0
  486. package/dist/resolution/frameworks/java.d.ts +8 -0
  487. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  488. package/dist/resolution/frameworks/java.js +517 -0
  489. package/dist/resolution/frameworks/java.js.map +1 -0
  490. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  491. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  492. package/dist/resolution/frameworks/laravel.js +257 -0
  493. package/dist/resolution/frameworks/laravel.js.map +1 -0
  494. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  495. package/dist/resolution/frameworks/nestjs.d.ts.map +1 -0
  496. package/dist/resolution/frameworks/nestjs.js +698 -0
  497. package/dist/resolution/frameworks/nestjs.js.map +1 -0
  498. package/dist/resolution/frameworks/play.d.ts +19 -0
  499. package/dist/resolution/frameworks/play.d.ts.map +1 -0
  500. package/dist/resolution/frameworks/play.js +111 -0
  501. package/dist/resolution/frameworks/play.js.map +1 -0
  502. package/dist/resolution/frameworks/python.d.ts +10 -0
  503. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  504. package/dist/resolution/frameworks/python.js +400 -0
  505. package/dist/resolution/frameworks/python.js.map +1 -0
  506. package/dist/resolution/frameworks/react-native.d.ts +3 -0
  507. package/dist/resolution/frameworks/react-native.d.ts.map +1 -0
  508. package/dist/resolution/frameworks/react-native.js +410 -0
  509. package/dist/resolution/frameworks/react-native.js.map +1 -0
  510. package/dist/resolution/frameworks/react.d.ts +8 -0
  511. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  512. package/dist/resolution/frameworks/react.js +334 -0
  513. package/dist/resolution/frameworks/react.js.map +1 -0
  514. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  515. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  516. package/dist/resolution/frameworks/ruby.js +302 -0
  517. package/dist/resolution/frameworks/ruby.js.map +1 -0
  518. package/dist/resolution/frameworks/rust.d.ts +8 -0
  519. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  520. package/dist/resolution/frameworks/rust.js +304 -0
  521. package/dist/resolution/frameworks/rust.js.map +1 -0
  522. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  523. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  524. package/dist/resolution/frameworks/svelte.js +253 -0
  525. package/dist/resolution/frameworks/svelte.js.map +1 -0
  526. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  527. package/dist/resolution/frameworks/swift-objc.d.ts.map +1 -0
  528. package/dist/resolution/frameworks/swift-objc.js +252 -0
  529. package/dist/resolution/frameworks/swift-objc.js.map +1 -0
  530. package/dist/resolution/frameworks/swift.d.ts +10 -0
  531. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  532. package/dist/resolution/frameworks/swift.js +400 -0
  533. package/dist/resolution/frameworks/swift.js.map +1 -0
  534. package/dist/resolution/frameworks/terraform.d.ts +38 -0
  535. package/dist/resolution/frameworks/terraform.d.ts.map +1 -0
  536. package/dist/resolution/frameworks/terraform.js +277 -0
  537. package/dist/resolution/frameworks/terraform.js.map +1 -0
  538. package/dist/resolution/frameworks/vue.d.ts +9 -0
  539. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  540. package/dist/resolution/frameworks/vue.js +303 -0
  541. package/dist/resolution/frameworks/vue.js.map +1 -0
  542. package/dist/resolution/go-module.d.ts +26 -0
  543. package/dist/resolution/go-module.d.ts.map +1 -0
  544. package/dist/resolution/go-module.js +78 -0
  545. package/dist/resolution/go-module.js.map +1 -0
  546. package/dist/resolution/goframe-synthesizer.d.ts +29 -0
  547. package/dist/resolution/goframe-synthesizer.d.ts.map +1 -0
  548. package/dist/resolution/goframe-synthesizer.js +163 -0
  549. package/dist/resolution/goframe-synthesizer.js.map +1 -0
  550. package/dist/resolution/import-resolver.d.ts +85 -0
  551. package/dist/resolution/import-resolver.d.ts.map +1 -0
  552. package/dist/resolution/import-resolver.js +1974 -0
  553. package/dist/resolution/import-resolver.js.map +1 -0
  554. package/dist/resolution/index.d.ts +258 -0
  555. package/dist/resolution/index.d.ts.map +1 -0
  556. package/dist/resolution/index.js +1746 -0
  557. package/dist/resolution/index.js.map +1 -0
  558. package/dist/resolution/lru-cache.d.ts +24 -0
  559. package/dist/resolution/lru-cache.d.ts.map +1 -0
  560. package/dist/resolution/lru-cache.js +62 -0
  561. package/dist/resolution/lru-cache.js.map +1 -0
  562. package/dist/resolution/name-matcher.d.ts +112 -0
  563. package/dist/resolution/name-matcher.d.ts.map +1 -0
  564. package/dist/resolution/name-matcher.js +1830 -0
  565. package/dist/resolution/name-matcher.js.map +1 -0
  566. package/dist/resolution/path-aliases.d.ts +68 -0
  567. package/dist/resolution/path-aliases.d.ts.map +1 -0
  568. package/dist/resolution/path-aliases.js +238 -0
  569. package/dist/resolution/path-aliases.js.map +1 -0
  570. package/dist/resolution/strip-comments.d.ts +27 -0
  571. package/dist/resolution/strip-comments.d.ts.map +1 -0
  572. package/dist/resolution/strip-comments.js +492 -0
  573. package/dist/resolution/strip-comments.js.map +1 -0
  574. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  575. package/dist/resolution/swift-objc-bridge.d.ts.map +1 -0
  576. package/dist/resolution/swift-objc-bridge.js +256 -0
  577. package/dist/resolution/swift-objc-bridge.js.map +1 -0
  578. package/dist/resolution/types.d.ts +262 -0
  579. package/dist/resolution/types.d.ts.map +1 -0
  580. package/dist/resolution/types.js +8 -0
  581. package/dist/resolution/types.js.map +1 -0
  582. package/dist/resolution/workspace-packages.d.ts +58 -0
  583. package/dist/resolution/workspace-packages.d.ts.map +1 -0
  584. package/dist/resolution/workspace-packages.js +346 -0
  585. package/dist/resolution/workspace-packages.js.map +1 -0
  586. package/dist/search/identifier-segments.d.ts +60 -0
  587. package/dist/search/identifier-segments.d.ts.map +1 -0
  588. package/dist/search/identifier-segments.js +176 -0
  589. package/dist/search/identifier-segments.js.map +1 -0
  590. package/dist/search/query-parser.d.ts +57 -0
  591. package/dist/search/query-parser.d.ts.map +1 -0
  592. package/dist/search/query-parser.js +177 -0
  593. package/dist/search/query-parser.js.map +1 -0
  594. package/dist/search/query-utils.d.ts +87 -0
  595. package/dist/search/query-utils.d.ts.map +1 -0
  596. package/dist/search/query-utils.js +449 -0
  597. package/dist/search/query-utils.js.map +1 -0
  598. package/dist/sync/git-hooks.d.ts +45 -0
  599. package/dist/sync/git-hooks.d.ts.map +1 -0
  600. package/dist/sync/git-hooks.js +227 -0
  601. package/dist/sync/git-hooks.js.map +1 -0
  602. package/dist/sync/index.d.ts +19 -0
  603. package/dist/sync/index.d.ts.map +1 -0
  604. package/dist/sync/index.js +35 -0
  605. package/dist/sync/index.js.map +1 -0
  606. package/dist/sync/watch-policy.d.ts +48 -0
  607. package/dist/sync/watch-policy.d.ts.map +1 -0
  608. package/dist/sync/watch-policy.js +124 -0
  609. package/dist/sync/watch-policy.js.map +1 -0
  610. package/dist/sync/watcher.d.ts +355 -0
  611. package/dist/sync/watcher.d.ts.map +1 -0
  612. package/dist/sync/watcher.js +848 -0
  613. package/dist/sync/watcher.js.map +1 -0
  614. package/dist/sync/worktree.d.ts +63 -0
  615. package/dist/sync/worktree.d.ts.map +1 -0
  616. package/dist/sync/worktree.js +182 -0
  617. package/dist/sync/worktree.js.map +1 -0
  618. package/dist/telemetry/index.d.ts +143 -0
  619. package/dist/telemetry/index.d.ts.map +1 -0
  620. package/dist/telemetry/index.js +541 -0
  621. package/dist/telemetry/index.js.map +1 -0
  622. package/dist/types.d.ts +415 -0
  623. package/dist/types.d.ts.map +1 -0
  624. package/dist/types.js +91 -0
  625. package/dist/types.js.map +1 -0
  626. package/dist/ui/glyphs.d.ts +42 -0
  627. package/dist/ui/glyphs.d.ts.map +1 -0
  628. package/dist/ui/glyphs.js +78 -0
  629. package/dist/ui/glyphs.js.map +1 -0
  630. package/dist/ui/shimmer-progress.d.ts +11 -0
  631. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  632. package/dist/ui/shimmer-progress.js +90 -0
  633. package/dist/ui/shimmer-progress.js.map +1 -0
  634. package/dist/ui/shimmer-worker.d.ts +2 -0
  635. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  636. package/dist/ui/shimmer-worker.js +118 -0
  637. package/dist/ui/shimmer-worker.js.map +1 -0
  638. package/dist/ui/types.d.ts +17 -0
  639. package/dist/ui/types.d.ts.map +1 -0
  640. package/dist/ui/types.js +3 -0
  641. package/dist/ui/types.js.map +1 -0
  642. package/dist/upgrade/index.d.ts +164 -0
  643. package/dist/upgrade/index.d.ts.map +1 -0
  644. package/dist/upgrade/index.js +646 -0
  645. package/dist/upgrade/index.js.map +1 -0
  646. package/dist/upgrade/remove-binary.d.ts +87 -0
  647. package/dist/upgrade/remove-binary.d.ts.map +1 -0
  648. package/dist/upgrade/remove-binary.js +289 -0
  649. package/dist/upgrade/remove-binary.js.map +1 -0
  650. package/dist/upgrade/update-check.d.ts +92 -0
  651. package/dist/upgrade/update-check.d.ts.map +1 -0
  652. package/dist/upgrade/update-check.js +258 -0
  653. package/dist/upgrade/update-check.js.map +1 -0
  654. package/dist/utils.d.ts +224 -0
  655. package/dist/utils.d.ts.map +1 -0
  656. package/dist/utils.js +583 -0
  657. package/dist/utils.js.map +1 -0
  658. package/package.json +1 -1
@@ -0,0 +1,1886 @@
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
+ const generated_detection_1 = require("../extraction/generated-detection");
13
+ const identifier_segments_1 = require("../search/identifier-segments");
14
+ /**
15
+ * Path-only heuristic for files that should not be candidates for
16
+ * "dominant file" detection: test/spec files and tool-generated files.
17
+ * Generated files (`*.pb.go`, `*.pulsar.go`, mock outputs, …) often
18
+ * have huge in-file edge counts that dwarf the real source — etcd's
19
+ * `rpc.pb.go` has 4× the in-file edges of `server.go`.
20
+ */
21
+ function isLowValueFile(filePath) {
22
+ const lp = filePath.toLowerCase();
23
+ return (/(?:^|\/)(tests?|__tests?__|spec)\//.test(lp) ||
24
+ /_test\.go$/.test(lp) ||
25
+ /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
26
+ /_test\.py$/.test(lp) ||
27
+ /_spec\.rb$/.test(lp) ||
28
+ /_test\.rb$/.test(lp) ||
29
+ /\.(test|spec)\.[jt]sx?$/.test(lp) ||
30
+ /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
31
+ /(tests?|spec)\.cs$/.test(lp) ||
32
+ /tests?\.swift$/.test(lp) ||
33
+ /_test\.dart$/.test(lp) ||
34
+ (0, generated_detection_1.isGeneratedFile)(filePath));
35
+ }
36
+ const SQLITE_PARAM_CHUNK_SIZE = 500;
37
+ /**
38
+ * Last segment of a (possibly dotted/qualified) reference name — the part a
39
+ * new symbol's plain node name could match: 'util.greet' → 'greet',
40
+ * 'mod::fn' → 'fn', 'greet' → 'greet'. Written to unresolved_refs.name_tail
41
+ * when a ref is marked failed, so the #1240 retry lookup can match dotted
42
+ * refs against newly-added node names.
43
+ */
44
+ function referenceNameTail(referenceName) {
45
+ const idx = Math.max(referenceName.lastIndexOf('.'), referenceName.lastIndexOf(':'));
46
+ return idx >= 0 ? referenceName.slice(idx + 1) : referenceName;
47
+ }
48
+ /**
49
+ * Convert database row to Node object
50
+ */
51
+ function rowToNode(row) {
52
+ return {
53
+ id: row.id,
54
+ kind: row.kind,
55
+ name: row.name,
56
+ qualifiedName: row.qualified_name,
57
+ filePath: row.file_path,
58
+ language: row.language,
59
+ startLine: row.start_line,
60
+ endLine: row.end_line,
61
+ startColumn: row.start_column,
62
+ endColumn: row.end_column,
63
+ docstring: row.docstring ?? undefined,
64
+ signature: row.signature ?? undefined,
65
+ visibility: row.visibility,
66
+ isExported: row.is_exported === 1,
67
+ isAsync: row.is_async === 1,
68
+ isStatic: row.is_static === 1,
69
+ isAbstract: row.is_abstract === 1,
70
+ decorators: row.decorators ? (0, utils_1.safeJsonParse)(row.decorators, undefined) : undefined,
71
+ typeParameters: row.type_parameters ? (0, utils_1.safeJsonParse)(row.type_parameters, undefined) : undefined,
72
+ returnType: row.return_type ?? undefined,
73
+ updatedAt: row.updated_at,
74
+ };
75
+ }
76
+ /**
77
+ * Convert database row to Edge object
78
+ */
79
+ function rowToEdge(row) {
80
+ return {
81
+ source: row.source,
82
+ target: row.target,
83
+ kind: row.kind,
84
+ metadata: row.metadata ? (0, utils_1.safeJsonParse)(row.metadata, undefined) : undefined,
85
+ line: row.line ?? undefined,
86
+ column: row.col ?? undefined,
87
+ provenance: row.provenance,
88
+ };
89
+ }
90
+ /**
91
+ * Convert database row to FileRecord object
92
+ */
93
+ function rowToFileRecord(row) {
94
+ return {
95
+ path: row.path,
96
+ contentHash: row.content_hash,
97
+ language: row.language,
98
+ size: row.size,
99
+ modifiedAt: row.modified_at,
100
+ indexedAt: row.indexed_at,
101
+ nodeCount: row.node_count,
102
+ errors: row.errors ? (0, utils_1.safeJsonParse)(row.errors, undefined) : undefined,
103
+ };
104
+ }
105
+ /**
106
+ * Query builder for the knowledge graph database
107
+ */
108
+ class QueryBuilder {
109
+ db;
110
+ // Project-name tokens (go.mod / package.json / repo dir), normalized. A query
111
+ // word matching one is dropped from path-relevance scoring — it names the
112
+ // whole project, not a symbol, so it carries no discriminative signal (#720).
113
+ // Set once by the CodeGraph instance; empty by default (no down-weighting).
114
+ projectNameTokens = new Set();
115
+ // Node cache for frequently accessed nodes (LRU-style, max 1000 entries)
116
+ nodeCache = new Map();
117
+ maxCacheSize = 1000;
118
+ // Prepared statements (lazily initialized)
119
+ stmts = {};
120
+ // Names whose segments were already written this session — skips re-splitting
121
+ // and re-inserting for the same-named nodes that repeat across files ("get",
122
+ // "render", …). Purely a write-path fast path; INSERT OR IGNORE is the
123
+ // correctness backstop. Bounded so a pathological repo can't grow it forever.
124
+ segmentedNames = new Set();
125
+ static MAX_SEGMENTED_NAMES = 65536;
126
+ constructor(db) {
127
+ this.db = db;
128
+ }
129
+ /** Set the normalized project-name tokens used to down-weight non-discriminative
130
+ * query words in path scoring (#720). Called once when the project opens. */
131
+ setProjectNameTokens(tokens) {
132
+ this.projectNameTokens = tokens;
133
+ }
134
+ /** The normalized project-name tokens (#720); empty if none were derived. */
135
+ getProjectNameTokens() {
136
+ return this.projectNameTokens;
137
+ }
138
+ // ===========================================================================
139
+ // Node Operations
140
+ // ===========================================================================
141
+ /**
142
+ * Insert a new node
143
+ */
144
+ insertNode(node) {
145
+ if (!this.stmts.insertNode) {
146
+ this.stmts.insertNode = this.db.prepare(`
147
+ INSERT OR REPLACE INTO nodes (
148
+ id, kind, name, qualified_name, file_path, language,
149
+ start_line, end_line, start_column, end_column,
150
+ docstring, signature, visibility,
151
+ is_exported, is_async, is_static, is_abstract,
152
+ decorators, type_parameters, return_type, updated_at
153
+ ) VALUES (
154
+ @id, @kind, @name, @qualifiedName, @filePath, @language,
155
+ @startLine, @endLine, @startColumn, @endColumn,
156
+ @docstring, @signature, @visibility,
157
+ @isExported, @isAsync, @isStatic, @isAbstract,
158
+ @decorators, @typeParameters, @returnType, @updatedAt
159
+ )
160
+ `);
161
+ }
162
+ // Validate required fields to prevent SQLite bind errors
163
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
164
+ console.error('[CodeGraph] Skipping node with missing required fields:', {
165
+ id: node.id,
166
+ kind: node.kind,
167
+ name: node.name,
168
+ filePath: node.filePath,
169
+ language: node.language,
170
+ });
171
+ return;
172
+ }
173
+ // INSERT OR REPLACE may overwrite a node we have cached. Drop the
174
+ // stale entry so the next getNodeById sees the new row, not the old
175
+ // one (matches the cache-invalidation pattern used by updateNode and
176
+ // deleteNode below).
177
+ this.nodeCache.delete(node.id);
178
+ this.stmts.insertNode.run({
179
+ id: node.id,
180
+ kind: node.kind,
181
+ name: node.name,
182
+ qualifiedName: node.qualifiedName ?? node.name,
183
+ filePath: node.filePath,
184
+ language: node.language,
185
+ startLine: node.startLine ?? 0,
186
+ endLine: node.endLine ?? 0,
187
+ startColumn: node.startColumn ?? 0,
188
+ endColumn: node.endColumn ?? 0,
189
+ docstring: node.docstring ?? null,
190
+ signature: node.signature ?? null,
191
+ visibility: node.visibility ?? null,
192
+ isExported: node.isExported ? 1 : 0,
193
+ isAsync: node.isAsync ? 1 : 0,
194
+ isStatic: node.isStatic ? 1 : 0,
195
+ isAbstract: node.isAbstract ? 1 : 0,
196
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
197
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
198
+ returnType: node.returnType ?? null,
199
+ updatedAt: node.updatedAt ?? Date.now(),
200
+ });
201
+ // Segment vocabulary rides the same write path (and transaction) so it can
202
+ // never drift ahead of the nodes it describes. Deletes intentionally leave
203
+ // orphans behind — vocab rows are proposals re-verified against nodes
204
+ // before use, and a full index clears the table at its start. File nodes
205
+ // are excluded: a file's basename duplicates the symbols inside it
206
+ // (state-machine.ts / OrderStateMachine), which double-counts every
207
+ // concept and defeats the singleton-vs-cluster rarity statistics. Import
208
+ // nodes are excluded too (#1144): they're named after module specifiers
209
+ // ("external-unindexed-pkg", "./utils/helpers"), not symbols — an
210
+ // import-only name can never be surfaced (getSegmentMatches requires a
211
+ // real definition), so its rows would only inflate the rarity statistics.
212
+ if (this.isSegmentableKind(node.kind))
213
+ this.insertNameSegments(node.name);
214
+ }
215
+ /** Which node kinds contribute their name to the segment vocabulary — the
216
+ * single gate shared by insertNode, updateNode, and the rebuild page query
217
+ * (getDistinctNodeNames), so the write paths can't drift apart. */
218
+ isSegmentableKind(kind) {
219
+ return kind !== 'file' && kind !== 'import';
220
+ }
221
+ /** Write `name`'s segments into name_segment_vocab (idempotent). */
222
+ insertNameSegments(name) {
223
+ if (this.segmentedNames.has(name))
224
+ return;
225
+ if (this.segmentedNames.size >= QueryBuilder.MAX_SEGMENTED_NAMES)
226
+ this.segmentedNames.clear();
227
+ this.segmentedNames.add(name);
228
+ if (!this.stmts.insertNameSegment) {
229
+ this.stmts.insertNameSegment = this.db.prepare('INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)');
230
+ }
231
+ for (const segment of (0, identifier_segments_1.splitIdentifierSegments)(name)) {
232
+ this.stmts.insertNameSegment.run(segment, name);
233
+ }
234
+ }
235
+ /**
236
+ * Insert multiple nodes in a transaction
237
+ */
238
+ insertNodes(nodes) {
239
+ this.db.transaction(() => {
240
+ for (const node of nodes) {
241
+ this.insertNode(node);
242
+ }
243
+ })();
244
+ }
245
+ /**
246
+ * Update an existing node
247
+ */
248
+ updateNode(node) {
249
+ if (!this.stmts.updateNode) {
250
+ this.stmts.updateNode = this.db.prepare(`
251
+ UPDATE nodes SET
252
+ kind = @kind,
253
+ name = @name,
254
+ qualified_name = @qualifiedName,
255
+ file_path = @filePath,
256
+ language = @language,
257
+ start_line = @startLine,
258
+ end_line = @endLine,
259
+ start_column = @startColumn,
260
+ end_column = @endColumn,
261
+ docstring = @docstring,
262
+ signature = @signature,
263
+ visibility = @visibility,
264
+ is_exported = @isExported,
265
+ is_async = @isAsync,
266
+ is_static = @isStatic,
267
+ is_abstract = @isAbstract,
268
+ decorators = @decorators,
269
+ type_parameters = @typeParameters,
270
+ return_type = @returnType,
271
+ updated_at = @updatedAt
272
+ WHERE id = @id
273
+ `);
274
+ }
275
+ // Invalidate cache before update
276
+ this.nodeCache.delete(node.id);
277
+ // Validate required fields
278
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
279
+ console.error('[CodeGraph] Skipping node update with missing required fields:', node.id);
280
+ return;
281
+ }
282
+ this.stmts.updateNode.run({
283
+ id: node.id,
284
+ kind: node.kind,
285
+ name: node.name,
286
+ qualifiedName: node.qualifiedName ?? node.name,
287
+ filePath: node.filePath,
288
+ language: node.language,
289
+ startLine: node.startLine ?? 0,
290
+ endLine: node.endLine ?? 0,
291
+ startColumn: node.startColumn ?? 0,
292
+ endColumn: node.endColumn ?? 0,
293
+ docstring: node.docstring ?? null,
294
+ signature: node.signature ?? null,
295
+ visibility: node.visibility ?? null,
296
+ isExported: node.isExported ? 1 : 0,
297
+ isAsync: node.isAsync ? 1 : 0,
298
+ isStatic: node.isStatic ? 1 : 0,
299
+ isAbstract: node.isAbstract ? 1 : 0,
300
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
301
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
302
+ returnType: node.returnType ?? null,
303
+ updatedAt: node.updatedAt ?? Date.now(),
304
+ });
305
+ // updateNode is a second real write path to `nodes` — framework
306
+ // post-extract passes rewrite names through it (NestJS route prefixing),
307
+ // and a renamed node's new name must reach the segment vocabulary just
308
+ // like an inserted one's (#1141). Without this the rename left the new
309
+ // name permanently unsearchable: the old name's rows became honest-gate
310
+ // orphans and the only backfill is gated on the vocab being EMPTY.
311
+ // insertNameSegments is idempotent (in-memory set + INSERT OR IGNORE),
312
+ // so no name-changed check is needed.
313
+ if (this.isSegmentableKind(node.kind))
314
+ this.insertNameSegments(node.name);
315
+ }
316
+ /**
317
+ * Delete a node by ID
318
+ */
319
+ deleteNode(id) {
320
+ if (!this.stmts.deleteNode) {
321
+ this.stmts.deleteNode = this.db.prepare('DELETE FROM nodes WHERE id = ?');
322
+ }
323
+ // Invalidate cache
324
+ this.nodeCache.delete(id);
325
+ this.stmts.deleteNode.run(id);
326
+ }
327
+ /**
328
+ * Delete all nodes for a file
329
+ */
330
+ deleteNodesByFile(filePath) {
331
+ if (!this.stmts.deleteNodesByFile) {
332
+ this.stmts.deleteNodesByFile = this.db.prepare('DELETE FROM nodes WHERE file_path = ?');
333
+ }
334
+ // Invalidate cache for nodes in this file
335
+ for (const [id, node] of this.nodeCache) {
336
+ if (node.filePath === filePath) {
337
+ this.nodeCache.delete(id);
338
+ }
339
+ }
340
+ this.stmts.deleteNodesByFile.run(filePath);
341
+ }
342
+ // ===========================================================================
343
+ // Name-segment vocabulary (prompt-hook graph-derived gate)
344
+ // ===========================================================================
345
+ /** Wipe the segment vocabulary. A full index calls this at its start; the
346
+ * node write path repopulates it as files (re-)index, so the end state is
347
+ * exactly the current names with no orphan rows. */
348
+ clearNameSegmentVocab() {
349
+ this.db.exec('DELETE FROM name_segment_vocab');
350
+ this.segmentedNames.clear();
351
+ }
352
+ /** True when the vocab has no rows — an index built before the table existed.
353
+ * `sync` uses this to heal such databases (see rebuildNameSegmentVocabFrom). */
354
+ isNameSegmentVocabEmpty() {
355
+ const row = this.db.prepare('SELECT 1 FROM name_segment_vocab LIMIT 1').get();
356
+ return row === undefined;
357
+ }
358
+ /** One page of distinct segmentable node names, for batched vocab rebuilds
359
+ * (file basenames and import specifiers are excluded from the vocab — see
360
+ * insertNode). */
361
+ getDistinctNodeNames(limit, offset) {
362
+ const rows = this.db
363
+ .prepare("SELECT DISTINCT name FROM nodes WHERE kind NOT IN ('file', 'import') ORDER BY name LIMIT ? OFFSET ?")
364
+ .all(limit, offset);
365
+ return rows.map((r) => r.name);
366
+ }
367
+ /** Insert segments for a batch of names in one transaction (vocab heal path). */
368
+ insertNameSegmentsBatch(names) {
369
+ this.db.transaction(() => {
370
+ for (const name of names)
371
+ this.insertNameSegments(name);
372
+ })();
373
+ }
374
+ /**
375
+ * Names whose segments cover at least `minWords` distinct PROMPT WORDS —
376
+ * the co-occurrence probe behind the prompt hook's medium tier: the words
377
+ * "state" and "machine" both being segments of `OrderStateMachine` is strong
378
+ * evidence the prompt names that symbol in prose. Ordered by coverage.
379
+ *
380
+ * Takes (segment variant → original word) pairs and folds variants back to
381
+ * their word INSIDE the SQL: a name matching both `service` and `services`
382
+ * counts ONE word, not two. Counting raw variants let plural-variant pairs
383
+ * of a single word tie with genuine two-word matches and — because ORDER
384
+ * BY/LIMIT run here, before any JS-side re-check — crowd a real match past
385
+ * the LIMIT on vocab-heavy repos (#1146).
386
+ */
387
+ getSegmentCoOccurrence(variants, minWords, limit) {
388
+ if (variants.length === 0)
389
+ return [];
390
+ const placeholders = variants.map(() => '?').join(', ');
391
+ const whens = variants.map(() => 'WHEN ? THEN ?').join(' ');
392
+ const rows = this.db
393
+ .prepare(`SELECT name, COUNT(DISTINCT CASE segment ${whens} END) AS matches
394
+ FROM name_segment_vocab
395
+ WHERE segment IN (${placeholders})
396
+ GROUP BY name
397
+ HAVING matches >= ?
398
+ ORDER BY matches DESC, length(name) ASC
399
+ LIMIT ?`)
400
+ .all(...variants.flatMap((v) => [v.segment, v.word]), ...variants.map((v) => v.segment), minWords, limit);
401
+ return rows;
402
+ }
403
+ /** How many distinct names each segment appears in — the rarity signal that
404
+ * separates a discriminative word ("checkout") from a ubiquitous one ("state"). */
405
+ getSegmentNameCounts(segments) {
406
+ if (segments.length === 0)
407
+ return new Map();
408
+ const placeholders = segments.map(() => '?').join(', ');
409
+ const rows = this.db
410
+ .prepare(`SELECT segment, COUNT(*) AS n FROM name_segment_vocab
411
+ WHERE segment IN (${placeholders}) GROUP BY segment`)
412
+ .all(...segments);
413
+ return new Map(rows.map((r) => [r.segment, r.n]));
414
+ }
415
+ /** Names containing the given segment (rare-single-word tier). */
416
+ getNamesForSegment(segment, limit) {
417
+ const rows = this.db
418
+ .prepare('SELECT name FROM name_segment_vocab WHERE segment = ? ORDER BY length(name) ASC LIMIT ?')
419
+ .all(segment, limit);
420
+ return rows.map((r) => r.name);
421
+ }
422
+ /**
423
+ * Get a node by ID
424
+ */
425
+ getNodeById(id) {
426
+ // Check cache first
427
+ if (this.nodeCache.has(id)) {
428
+ const cached = this.nodeCache.get(id);
429
+ // Move to end to implement LRU (delete and re-add)
430
+ this.nodeCache.delete(id);
431
+ this.nodeCache.set(id, cached);
432
+ return cached;
433
+ }
434
+ if (!this.stmts.getNodeById) {
435
+ this.stmts.getNodeById = this.db.prepare('SELECT * FROM nodes WHERE id = ?');
436
+ }
437
+ const row = this.stmts.getNodeById.get(id);
438
+ if (!row) {
439
+ return null;
440
+ }
441
+ const node = rowToNode(row);
442
+ this.cacheNode(node);
443
+ return node;
444
+ }
445
+ /**
446
+ * Batch lookup: fetch many nodes by ID in a single SQL round-trip.
447
+ *
448
+ * Replaces the N+1 pattern in graph traversal where every edge would
449
+ * trigger its own `getNodeById` call. For a function with 50 callers
450
+ * this collapses 50 point reads into one IN-list query (~10-50x
451
+ * faster end-to-end).
452
+ *
453
+ * Returns a Map keyed by id so callers can preserve their own ordering
454
+ * (typically the order edges were returned from the graph). Missing IDs
455
+ * are simply absent from the map.
456
+ *
457
+ * Cache-aware: ids already in the LRU cache are served from memory and
458
+ * the SQL query only touches the misses.
459
+ */
460
+ getNodesByIds(ids) {
461
+ const out = new Map();
462
+ if (ids.length === 0)
463
+ return out;
464
+ // Serve cache hits first; build the miss list for SQL.
465
+ const misses = [];
466
+ for (const id of ids) {
467
+ const cached = this.nodeCache.get(id);
468
+ if (cached !== undefined) {
469
+ // LRU touch
470
+ this.nodeCache.delete(id);
471
+ this.nodeCache.set(id, cached);
472
+ out.set(id, cached);
473
+ }
474
+ else {
475
+ misses.push(id);
476
+ }
477
+ }
478
+ if (misses.length === 0)
479
+ return out;
480
+ // Chunk under SQLite's parameter limit (default 999, raised to 32766
481
+ // in better-sqlite3 builds — chunk at 500 for safety across both
482
+ // backends and to keep the query plan simple).
483
+ for (let i = 0; i < misses.length; i += SQLITE_PARAM_CHUNK_SIZE) {
484
+ const chunk = misses.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
485
+ const placeholders = chunk.map(() => '?').join(',');
486
+ const rows = this.db
487
+ .prepare(`SELECT * FROM nodes WHERE id IN (${placeholders})`)
488
+ .all(...chunk);
489
+ for (const row of rows) {
490
+ const node = rowToNode(row);
491
+ out.set(node.id, node);
492
+ this.cacheNode(node);
493
+ }
494
+ }
495
+ return out;
496
+ }
497
+ getExistingNodeIds(ids) {
498
+ const out = new Set();
499
+ if (ids.length === 0)
500
+ return out;
501
+ const uniqueIds = [...new Set(ids)];
502
+ for (let i = 0; i < uniqueIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
503
+ const chunk = uniqueIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
504
+ const placeholders = chunk.map(() => '?').join(',');
505
+ const rows = this.db
506
+ .prepare(`SELECT id FROM nodes WHERE id IN (${placeholders})`)
507
+ .all(...chunk);
508
+ for (const row of rows) {
509
+ out.add(row.id);
510
+ }
511
+ }
512
+ return out;
513
+ }
514
+ /**
515
+ * Add a node to the cache, evicting oldest if needed
516
+ */
517
+ cacheNode(node) {
518
+ if (this.nodeCache.size >= this.maxCacheSize) {
519
+ // Evict oldest (first) entry
520
+ const firstKey = this.nodeCache.keys().next().value;
521
+ if (firstKey) {
522
+ this.nodeCache.delete(firstKey);
523
+ }
524
+ }
525
+ this.nodeCache.set(node.id, node);
526
+ }
527
+ /**
528
+ * Clear the node cache
529
+ */
530
+ clearCache() {
531
+ this.nodeCache.clear();
532
+ }
533
+ /**
534
+ * Get all nodes in a file
535
+ */
536
+ getNodesByFile(filePath) {
537
+ if (!this.stmts.getNodesByFile) {
538
+ this.stmts.getNodesByFile = this.db.prepare('SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line');
539
+ }
540
+ const rows = this.stmts.getNodesByFile.all(filePath);
541
+ return rows.map(rowToNode);
542
+ }
543
+ /**
544
+ * Find the file that holds the densest concentration of the project's
545
+ * internal call graph — the "core" file. Used by context-builder to
546
+ * boost ranking of symbols in that file's directory (so e.g. sinatra
547
+ * queries surface `lib/sinatra/base.rb`'s `route!` instead of
548
+ * `sinatra-contrib/lib/sinatra/multi_route.rb`'s `route` extension).
549
+ *
550
+ * Returns null if no file has a meaningful concentration (e.g. spread
551
+ * evenly across many files, or empty index).
552
+ *
553
+ * "Internal" = source and target are in the same file. Cross-file
554
+ * edges aren't useful here — they don't tell us which file is the
555
+ * functional center.
556
+ *
557
+ * Excludes test/spec files from candidacy via path-pattern. The agent's
558
+ * typical question is "how does X work", not "how is X tested", so
559
+ * boosting a test file's directory would be a misfire.
560
+ */
561
+ getDominantFile() {
562
+ if (!this.stmts.getDominantFile) {
563
+ // Pull top 20 candidates; we then filter out test/generated files
564
+ // in code (regex-grade matching that SQL LIKE can't express). The
565
+ // generated-file filter is critical — without it, etcd's
566
+ // `api/etcdserverpb/rpc.pb.go` (1916 in-file edges, generated
567
+ // protobuf stub) outranks the real `server/etcdserver/server.go`
568
+ // (470 edges) by 4×, and the boost would push the agent toward
569
+ // generated code.
570
+ this.stmts.getDominantFile = this.db.prepare(`
571
+ SELECT n.file_path AS file_path, COUNT(*) AS edge_count
572
+ FROM edges e
573
+ JOIN nodes n ON e.source = n.id
574
+ JOIN nodes m ON e.target = m.id
575
+ WHERE n.file_path = m.file_path
576
+ GROUP BY n.file_path
577
+ ORDER BY edge_count DESC
578
+ LIMIT 20
579
+ `);
580
+ }
581
+ const rows = this.stmts.getDominantFile.all();
582
+ const filtered = rows.filter(r => !isLowValueFile(r.file_path));
583
+ if (filtered.length === 0 || filtered[0].edge_count < 20)
584
+ return null;
585
+ return {
586
+ filePath: filtered[0].file_path,
587
+ edgeCount: filtered[0].edge_count,
588
+ nextEdgeCount: filtered[1]?.edge_count ?? 0,
589
+ };
590
+ }
591
+ /**
592
+ * Find the file that holds the densest concentration of the project's
593
+ * `route` nodes (framework-emitted: Express/Gin/Flask/Rails/Drupal/etc.).
594
+ * Used by handleContext on small repos to inline the project's routing
595
+ * config when the agent's query is about request flow — eliminating the
596
+ * "Glob + Read routes.rb" pattern that beats codegraph on tiny realworld
597
+ * template repos.
598
+ *
599
+ * Excludes test/generated files from candidacy. Returns null if there
600
+ * are fewer than 3 non-test routes total, or if no file holds at least
601
+ * 30% of them (diffuse routing → no single answer file).
602
+ */
603
+ getTopRouteFile() {
604
+ if (!this.stmts.getTopRouteFile) {
605
+ this.stmts.getTopRouteFile = this.db.prepare(`
606
+ SELECT file_path, COUNT(*) AS cnt
607
+ FROM nodes
608
+ WHERE kind = 'route'
609
+ GROUP BY file_path
610
+ ORDER BY cnt DESC
611
+ LIMIT 20
612
+ `);
613
+ }
614
+ const rows = this.stmts.getTopRouteFile.all();
615
+ const filtered = rows.filter(r => !isLowValueFile(r.file_path));
616
+ if (filtered.length === 0)
617
+ return null;
618
+ const totalRoutes = filtered.reduce((sum, r) => sum + r.cnt, 0);
619
+ const top = filtered[0];
620
+ if (totalRoutes < 3 || top.cnt < 3)
621
+ return null;
622
+ if (top.cnt / totalRoutes < 0.30)
623
+ return null;
624
+ return { filePath: top.file_path, routeCount: top.cnt, totalRoutes };
625
+ }
626
+ /**
627
+ * Build a URL → handler manifest from the index. Each route node's
628
+ * `references` edge points at the function/method that handles the
629
+ * request. We join them in one pass; the agent gets the canonical
630
+ * routing answer ("POST /users/login → AuthController#login") without
631
+ * having to parse the framework's route DSL itself.
632
+ *
633
+ * Also returns the file with the most handler endpoints — used as the
634
+ * "top handler file" to inline source for, so the agent has both the
635
+ * mapping AND the handler implementations.
636
+ */
637
+ getRoutingManifest(limit = 40) {
638
+ if (!this.stmts.getRoutingManifest) {
639
+ // Edge kind varies across framework resolvers: Spring/Rails/
640
+ // Laravel/Drupal emit `references`, Express emits `calls`. Accept
641
+ // both — the semantic is the same (route → its handler).
642
+ this.stmts.getRoutingManifest = this.db.prepare(`
643
+ SELECT
644
+ r.name AS url,
645
+ h.name AS handler,
646
+ h.file_path AS handler_file,
647
+ h.start_line AS handler_line,
648
+ h.kind AS handler_kind
649
+ FROM nodes r
650
+ JOIN edges e ON e.source = r.id
651
+ JOIN nodes h ON e.target = h.id
652
+ WHERE r.kind = 'route'
653
+ AND e.kind IN ('references', 'calls')
654
+ AND h.kind IN ('function', 'method', 'class')
655
+ ORDER BY r.file_path, r.start_line
656
+ LIMIT ?
657
+ `);
658
+ }
659
+ const rows = this.stmts.getRoutingManifest.all(limit);
660
+ // Drop test/generated handlers — same hygiene as elsewhere.
661
+ const filtered = rows.filter(r => !isLowValueFile(r.handler_file));
662
+ if (filtered.length < 3)
663
+ return null;
664
+ // Identify the file holding the most handlers (the "primary handler file").
665
+ const fileCounts = new Map();
666
+ for (const r of filtered) {
667
+ fileCounts.set(r.handler_file, (fileCounts.get(r.handler_file) ?? 0) + 1);
668
+ }
669
+ let topHandlerFile = null;
670
+ let topHandlerFileCount = 0;
671
+ for (const [file, count] of fileCounts) {
672
+ if (count > topHandlerFileCount) {
673
+ topHandlerFile = file;
674
+ topHandlerFileCount = count;
675
+ }
676
+ }
677
+ return {
678
+ entries: filtered.map(r => ({
679
+ url: r.url,
680
+ handler: r.handler,
681
+ handlerFile: r.handler_file,
682
+ handlerLine: r.handler_line,
683
+ handlerKind: r.handler_kind,
684
+ })),
685
+ topHandlerFile,
686
+ topHandlerFileCount,
687
+ totalRoutes: filtered.length,
688
+ };
689
+ }
690
+ /**
691
+ * Get all nodes of a specific kind
692
+ */
693
+ getNodesByKind(kind) {
694
+ if (!this.stmts.getNodesByKind) {
695
+ this.stmts.getNodesByKind = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
696
+ }
697
+ const rows = this.stmts.getNodesByKind.all(kind);
698
+ return rows.map(rowToNode);
699
+ }
700
+ /**
701
+ * Stream every node of a kind one at a time (lazy) instead of materializing
702
+ * them all like {@link getNodesByKind}. For unbounded kinds (`function`,
703
+ * `method`) on a symbol-dense project the full array is gigabytes; the
704
+ * dynamic-edge synthesizers only scan-and-filter, so they iterate to keep
705
+ * memory O(1) in the node count rather than O(nodes) (#610).
706
+ */
707
+ *iterateNodesByKind(kind) {
708
+ // Fresh statement per call (not a cached one): an iterator holds an open
709
+ // cursor, so a shared statement would conflict across overlapping scans.
710
+ const stmt = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
711
+ for (const row of stmt.iterate(kind)) {
712
+ yield rowToNode(row);
713
+ }
714
+ }
715
+ /**
716
+ * Get all nodes in the database
717
+ */
718
+ getAllNodes() {
719
+ const rows = this.db.prepare('SELECT * FROM nodes').all();
720
+ return rows.map(rowToNode);
721
+ }
722
+ /**
723
+ * Stream nodes of one language whose `decorators` JSON array contains
724
+ * `decorator`. The LIKE on the JSON text is a cheap index-free pre-filter
725
+ * (a decorator name can appear as a substring of another), so callers must
726
+ * still exact-check `node.decorators.includes(decorator)`. Exists so the
727
+ * kotlin expect/actual synthesizer never materializes the whole node table
728
+ * the way `getAllNodes().filter(...)` did — that array alone OOM'd Node's
729
+ * default heap on a 2M-node graph (#1212).
730
+ */
731
+ *iterateNodesByLanguageWithDecorator(language, decorator) {
732
+ // Fresh statement per call — an iterator holds an open cursor (see
733
+ // iterateNodesByKind).
734
+ const stmt = this.db.prepare("SELECT * FROM nodes WHERE language = ? AND decorators LIKE '%' || ? || '%'");
735
+ for (const row of stmt.iterate(language, `"${decorator}"`)) {
736
+ yield rowToNode(row);
737
+ }
738
+ }
739
+ /**
740
+ * Distinct languages present in the files table. One indexed aggregate —
741
+ * lets the dynamic-edge synthesizers skip passes for languages the project
742
+ * doesn't contain at all (a Kotlin pass has no work on a pure-C repo), so
743
+ * their cost is zero rather than a full-graph scan that finds nothing (#1212).
744
+ */
745
+ getDistinctFileLanguages() {
746
+ const rows = this.db.prepare('SELECT DISTINCT language FROM files').all();
747
+ return new Set(rows.map((r) => r.language));
748
+ }
749
+ /**
750
+ * Get nodes by exact name match (uses idx_nodes_name index)
751
+ */
752
+ getNodesByName(name) {
753
+ if (!this.stmts.getNodesByName) {
754
+ this.stmts.getNodesByName = this.db.prepare('SELECT * FROM nodes WHERE name = ?');
755
+ }
756
+ const rows = this.stmts.getNodesByName.all(name);
757
+ return rows.map(rowToNode);
758
+ }
759
+ /**
760
+ * Nodes whose name starts with `prefix`, by index range scan (a LIKE would
761
+ * skip idx_nodes_name under SQLite's default case-insensitive LIKE).
762
+ */
763
+ getNodesByNamePrefix(prefix, limit = 20) {
764
+ if (!this.stmts.getNodesByNamePrefix) {
765
+ this.stmts.getNodesByNamePrefix = this.db.prepare('SELECT * FROM nodes WHERE name >= ? AND name < ? ORDER BY name LIMIT ?');
766
+ }
767
+ const rows = this.stmts.getNodesByNamePrefix.all(prefix, prefix + '￿', limit);
768
+ return rows.map(rowToNode);
769
+ }
770
+ /**
771
+ * Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
772
+ */
773
+ getNodesByQualifiedNameExact(qualifiedName) {
774
+ if (!this.stmts.getNodesByQualifiedNameExact) {
775
+ this.stmts.getNodesByQualifiedNameExact = this.db.prepare('SELECT * FROM nodes WHERE qualified_name = ?');
776
+ }
777
+ const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName);
778
+ return rows.map(rowToNode);
779
+ }
780
+ /**
781
+ * Get nodes by lowercase name match (uses idx_nodes_lower_name expression index)
782
+ */
783
+ getNodesByLowerName(lowerName) {
784
+ if (!this.stmts.getNodesByLowerName) {
785
+ this.stmts.getNodesByLowerName = this.db.prepare('SELECT * FROM nodes WHERE lower(name) = ?');
786
+ }
787
+ const rows = this.stmts.getNodesByLowerName.all(lowerName);
788
+ return rows.map(rowToNode);
789
+ }
790
+ /**
791
+ * Search nodes by name using FTS with fallback to LIKE for better matching
792
+ *
793
+ * Search strategy:
794
+ * 1. Try FTS5 prefix match (query*) for word-start matching
795
+ * 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
796
+ * 3. Score results based on match quality
797
+ */
798
+ searchNodes(query, options = {}) {
799
+ const { limit = 100, offset = 0 } = options;
800
+ // Parse field-qualified bits out of the raw query (kind:, lang:,
801
+ // path:, name:). Anything not recognised stays in `text` and goes
802
+ // to FTS unchanged. Filters compose with the SearchOptions arg —
803
+ // both are applied (intersection-style).
804
+ const parsed = (0, query_parser_1.parseQuery)(query);
805
+ const mergedKinds = parsed.kinds.length > 0
806
+ ? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
807
+ : options.kinds;
808
+ const mergedLanguages = parsed.languages.length > 0
809
+ ? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
810
+ : options.languages;
811
+ const pathFilters = parsed.pathFilters;
812
+ const nameFilters = parsed.nameFilters;
813
+ // The text portion drives FTS/LIKE; if all the user typed was
814
+ // filters (`kind:function`), we still need *some* candidate set,
815
+ // so synthesise an empty-text path that returns everything matching
816
+ // the filters.
817
+ const text = parsed.text;
818
+ const kinds = mergedKinds;
819
+ const languages = mergedLanguages;
820
+ // First try FTS5 with prefix matching
821
+ let results = text
822
+ ? this.searchNodesFTS(text, { kinds, languages, limit, offset })
823
+ // Over-fetch by 5× when running filter-only (no text). The
824
+ // post-scoring path: + name: filters can be very selective, so
825
+ // a smaller multiplier risks returning fewer than `limit`
826
+ // results despite the DB having plenty of matches.
827
+ : this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
828
+ // If no FTS results, try LIKE-based substring search
829
+ if (results.length === 0 && text.length >= 2) {
830
+ results = this.searchNodesLike(text, { kinds, languages, limit, offset });
831
+ }
832
+ // Final fuzzy fallback: scan all known names and keep those within
833
+ // a tight Levenshtein distance. Only fires when both FTS and LIKE
834
+ // returned nothing AND there's a text portion long enough to be
835
+ // worth fuzzing (1-char queries would match too much).
836
+ if (results.length === 0 && text.length >= 3) {
837
+ results = this.searchNodesFuzzy(text, { kinds, languages, limit });
838
+ }
839
+ // Supplement: ensure exact name matches are always candidates.
840
+ // BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
841
+ // compound names (e.g. "getBeanDescriptor") in large codebases,
842
+ // pushing them past the FTS fetch limit before post-hoc scoring can help.
843
+ // Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
844
+ // prefix=20) actually differentiates them after rescoring.
845
+ if (results.length > 0 && query) {
846
+ const existingIds = new Set(results.map(r => r.node.id));
847
+ const maxFtsScore = Math.max(...results.map(r => r.score));
848
+ const terms = query.split(/\s+/).filter(t => t.length >= 2);
849
+ for (const term of terms) {
850
+ let sql = 'SELECT * FROM nodes WHERE name = ? COLLATE NOCASE';
851
+ const params = [term];
852
+ if (kinds && kinds.length > 0) {
853
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
854
+ params.push(...kinds);
855
+ }
856
+ if (languages && languages.length > 0) {
857
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
858
+ params.push(...languages);
859
+ }
860
+ sql += ' LIMIT 20';
861
+ const rows = this.db.prepare(sql).all(...params);
862
+ for (const row of rows) {
863
+ if (!existingIds.has(row.id)) {
864
+ results.push({ node: rowToNode(row), score: maxFtsScore });
865
+ existingIds.add(row.id);
866
+ }
867
+ }
868
+ }
869
+ }
870
+ // Apply multi-signal scoring
871
+ if (results.length > 0 && (text || query)) {
872
+ const scoringQuery = text || query;
873
+ results = results.map(r => ({
874
+ ...r,
875
+ score: r.score
876
+ + (0, query_utils_1.kindBonus)(r.node.kind)
877
+ + (0, query_utils_1.scorePathRelevance)(r.node.filePath, scoringQuery, this.projectNameTokens)
878
+ + (0, query_utils_1.nameMatchBonus)(r.node.name, scoringQuery),
879
+ }));
880
+ results.sort((a, b) => b.score - a.score);
881
+ // Trim to requested limit after rescoring
882
+ if (results.length > limit) {
883
+ results = results.slice(0, limit);
884
+ }
885
+ }
886
+ // Apply path: + name: filters AFTER scoring. Scoring already uses
887
+ // path/name as a soft signal; the explicit filters here are a hard
888
+ // gate. Done last so the FTS limit fetched plenty of candidates to
889
+ // narrow from.
890
+ if (pathFilters.length > 0) {
891
+ const lowered = pathFilters.map((p) => p.toLowerCase());
892
+ results = results.filter((r) => {
893
+ const fp = r.node.filePath.toLowerCase();
894
+ return lowered.some((p) => fp.includes(p));
895
+ });
896
+ }
897
+ if (nameFilters.length > 0) {
898
+ const lowered = nameFilters.map((n) => n.toLowerCase());
899
+ results = results.filter((r) => {
900
+ const nm = r.node.name.toLowerCase();
901
+ return lowered.some((n) => nm.includes(n));
902
+ });
903
+ }
904
+ return results;
905
+ }
906
+ /**
907
+ * Match-everything path used when the user supplied only field
908
+ * filters (`kind:function lang:typescript`) with no text. Returns
909
+ * candidates ordered by name; the caller's filter pass narrows to
910
+ * what was asked for.
911
+ */
912
+ searchAllByFilters(options) {
913
+ const { kinds, languages, limit } = options;
914
+ let sql = 'SELECT * FROM nodes WHERE 1=1';
915
+ const params = [];
916
+ if (kinds && kinds.length > 0) {
917
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
918
+ params.push(...kinds);
919
+ }
920
+ if (languages && languages.length > 0) {
921
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
922
+ params.push(...languages);
923
+ }
924
+ sql += ' ORDER BY name LIMIT ?';
925
+ params.push(limit);
926
+ const rows = this.db.prepare(sql).all(...params);
927
+ return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
928
+ }
929
+ /**
930
+ * Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
931
+ * sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
932
+ * `getUssr` finds `getUser` but `process` doesn't match `prosody`.
933
+ * Bounded edit distance keeps each comparison cheap; the per-query
934
+ * scan is O(distinct-name-count) which is far smaller than total
935
+ * node count on any real codebase.
936
+ */
937
+ searchNodesFuzzy(text, options) {
938
+ const { kinds, languages, limit } = options;
939
+ const lowered = text.toLowerCase();
940
+ const maxDist = lowered.length <= 4 ? 1 : 2;
941
+ // Pull the distinct name list once. The set is cached on QueryBuilder
942
+ // by getAllNodeNames(); even on a 200k-node project the distinct
943
+ // name set is typically O(10k) because most names repeat. The
944
+ // candidate-cap below bounds memory regardless.
945
+ const allNames = this.getAllNodeNames();
946
+ const candidates = [];
947
+ for (const name of allNames) {
948
+ const dist = (0, query_parser_1.boundedEditDistance)(name.toLowerCase(), lowered, maxDist);
949
+ if (dist <= maxDist)
950
+ candidates.push({ name, dist });
951
+ }
952
+ candidates.sort((a, b) => a.dist - b.dist);
953
+ // Cap the per-name follow-up queries. Each survivor triggers a
954
+ // separate `SELECT * FROM nodes WHERE name = ?`; without this cap
955
+ // a project with many similar names (`getUser1`, `getUser2`...)
956
+ // could fan out far beyond `limit` queries before the inner-loop
957
+ // limit kicks in.
958
+ const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
959
+ const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
960
+ const results = [];
961
+ const seen = new Set();
962
+ for (const c of cappedCandidates) {
963
+ if (results.length >= limit)
964
+ break;
965
+ let sql = 'SELECT * FROM nodes WHERE name = ?';
966
+ const params = [c.name];
967
+ if (kinds && kinds.length > 0) {
968
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
969
+ params.push(...kinds);
970
+ }
971
+ if (languages && languages.length > 0) {
972
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
973
+ params.push(...languages);
974
+ }
975
+ sql += ' LIMIT 5';
976
+ const rows = this.db.prepare(sql).all(...params);
977
+ for (const row of rows) {
978
+ if (seen.has(row.id))
979
+ continue;
980
+ seen.add(row.id);
981
+ // Lower the score for each edit step away from the query so
982
+ // exact-match fallbacks (dist 0) outrank dist-2 typos.
983
+ results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
984
+ if (results.length >= limit)
985
+ break;
986
+ }
987
+ }
988
+ return results;
989
+ }
990
+ /**
991
+ * FTS5 search with prefix matching
992
+ */
993
+ searchNodesFTS(query, options) {
994
+ const { kinds, languages, limit = 100, offset = 0 } = options;
995
+ // Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
996
+ // Escape special FTS5 characters and add prefix wildcard.
997
+ //
998
+ // `::` is a qualifier separator in Rust/C++/Ruby, not a token char,
999
+ // so treat it as whitespace before the strip step. Otherwise queries
1000
+ // like `stage_apply::run` collapse to `stage_applyrun` (the colons
1001
+ // are stripped without splitting) and find nothing. See #173.
1002
+ const ftsQuery = query
1003
+ .replace(/::/g, ' ') // Rust/C++/Ruby qualifier separator
1004
+ .replace(/['"*():^]/g, '') // Remove FTS5 special chars
1005
+ .split(/\s+/)
1006
+ .filter(term => term.length > 0)
1007
+ // Strip FTS5 boolean operators to prevent query manipulation
1008
+ .filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
1009
+ .map(term => `"${term}"*`) // Prefix match each term
1010
+ .join(' OR ');
1011
+ if (!ftsQuery) {
1012
+ return [];
1013
+ }
1014
+ // BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
1015
+ // Heavy name weight ensures exact/prefix name matches rank above incidental
1016
+ // mentions in long docstrings or qualified names of nested symbols.
1017
+ // Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
1018
+ // nameMatchBonus) can promote results that BM25 alone undervalues.
1019
+ const ftsLimit = Math.max(limit * 5, 100);
1020
+ let sql = `
1021
+ SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
1022
+ FROM nodes_fts
1023
+ JOIN nodes ON nodes_fts.id = nodes.id
1024
+ WHERE nodes_fts MATCH ?
1025
+ `;
1026
+ const params = [ftsQuery];
1027
+ if (kinds && kinds.length > 0) {
1028
+ sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
1029
+ params.push(...kinds);
1030
+ }
1031
+ if (languages && languages.length > 0) {
1032
+ sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
1033
+ params.push(...languages);
1034
+ }
1035
+ sql += ' ORDER BY score LIMIT ? OFFSET ?';
1036
+ params.push(ftsLimit, offset);
1037
+ try {
1038
+ const rows = this.db.prepare(sql).all(...params);
1039
+ return rows.map((row) => ({
1040
+ node: rowToNode(row),
1041
+ score: Math.abs(row.score), // bm25 returns negative scores
1042
+ }));
1043
+ }
1044
+ catch {
1045
+ // FTS query failed, return empty
1046
+ return [];
1047
+ }
1048
+ }
1049
+ /**
1050
+ * LIKE-based substring search for cases where FTS doesn't match
1051
+ * Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
1052
+ */
1053
+ searchNodesLike(query, options) {
1054
+ const { kinds, languages, limit = 100, offset = 0 } = options;
1055
+ let sql = `
1056
+ SELECT nodes.*,
1057
+ CASE
1058
+ WHEN name = ? THEN 1.0
1059
+ WHEN name LIKE ? THEN 0.9
1060
+ WHEN name LIKE ? THEN 0.8
1061
+ WHEN qualified_name LIKE ? THEN 0.7
1062
+ ELSE 0.5
1063
+ END as score
1064
+ FROM nodes
1065
+ WHERE (
1066
+ name LIKE ? OR
1067
+ qualified_name LIKE ? OR
1068
+ name LIKE ?
1069
+ )
1070
+ `;
1071
+ // Pattern variants for better matching
1072
+ const exactMatch = query;
1073
+ const startsWith = `${query}%`;
1074
+ const contains = `%${query}%`;
1075
+ const params = [
1076
+ exactMatch, // Exact match score
1077
+ startsWith, // Starts with score
1078
+ contains, // Contains score
1079
+ contains, // Qualified name score
1080
+ contains, // WHERE: name contains
1081
+ contains, // WHERE: qualified_name contains
1082
+ startsWith, // WHERE: name starts with
1083
+ ];
1084
+ if (kinds && kinds.length > 0) {
1085
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1086
+ params.push(...kinds);
1087
+ }
1088
+ if (languages && languages.length > 0) {
1089
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1090
+ params.push(...languages);
1091
+ }
1092
+ sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
1093
+ params.push(limit, offset);
1094
+ const rows = this.db.prepare(sql).all(...params);
1095
+ return rows.map((row) => ({
1096
+ node: rowToNode(row),
1097
+ score: row.score,
1098
+ }));
1099
+ }
1100
+ /**
1101
+ * Find nodes by exact name match
1102
+ *
1103
+ * Used for hybrid search - looks up symbols by exact name or case-insensitive match.
1104
+ * Returns high-confidence matches for known symbol names extracted from query.
1105
+ *
1106
+ * @param names - Array of symbol names to look up
1107
+ * @param options - Search options (kinds, languages, limit)
1108
+ * @returns SearchResult array with exact matches scored at 1.0
1109
+ */
1110
+ findNodesByExactName(names, options = {}) {
1111
+ if (names.length === 0)
1112
+ return [];
1113
+ const { kinds, languages, limit = 50 } = options;
1114
+ // Two-pass approach to handle common names (e.g., "run" has 40+ matches):
1115
+ // Pass 1: Find which files contain distinctive (rare) symbols from the query.
1116
+ // Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
1117
+ // Pass 1: Find files containing each queried name, identify distinctive names
1118
+ const nameToFiles = new Map();
1119
+ for (const name of names) {
1120
+ let sql = 'SELECT DISTINCT file_path FROM nodes WHERE name COLLATE NOCASE = ?';
1121
+ const params = [name];
1122
+ if (kinds && kinds.length > 0) {
1123
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1124
+ params.push(...kinds);
1125
+ }
1126
+ sql += ' LIMIT 100';
1127
+ const rows = this.db.prepare(sql).all(...params);
1128
+ nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
1129
+ }
1130
+ // Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
1131
+ const distinctiveFiles = new Set();
1132
+ for (const [, files] of nameToFiles) {
1133
+ if (files.size > 0 && files.size < 10) {
1134
+ for (const f of files)
1135
+ distinctiveFiles.add(f);
1136
+ }
1137
+ }
1138
+ // Pass 2: Query each name with per-name limit, scoring by co-location
1139
+ const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
1140
+ const allResults = [];
1141
+ const seenIds = new Set();
1142
+ for (const name of names) {
1143
+ let sql = `
1144
+ SELECT nodes.*, 1.0 as score
1145
+ FROM nodes
1146
+ WHERE name COLLATE NOCASE = ?
1147
+ `;
1148
+ const params = [name];
1149
+ if (kinds && kinds.length > 0) {
1150
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1151
+ params.push(...kinds);
1152
+ }
1153
+ if (languages && languages.length > 0) {
1154
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1155
+ params.push(...languages);
1156
+ }
1157
+ // Fetch enough to find co-located results among common names
1158
+ sql += ' LIMIT ?';
1159
+ params.push(Math.max(perNameLimit * 3, 50));
1160
+ const rows = this.db.prepare(sql).all(...params);
1161
+ const nameResults = [];
1162
+ for (const row of rows) {
1163
+ const node = rowToNode(row);
1164
+ if (seenIds.has(node.id))
1165
+ continue;
1166
+ // Boost results in files that also contain distinctive symbols
1167
+ const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
1168
+ nameResults.push({ node, score: row.score + coLocationBoost });
1169
+ }
1170
+ // Sort by score (co-located first), take per-name limit
1171
+ nameResults.sort((a, b) => b.score - a.score);
1172
+ for (const r of nameResults.slice(0, perNameLimit)) {
1173
+ seenIds.add(r.node.id);
1174
+ allResults.push(r);
1175
+ }
1176
+ }
1177
+ // Sort all results by score so co-located results bubble up
1178
+ allResults.sort((a, b) => b.score - a.score);
1179
+ return allResults.slice(0, limit);
1180
+ }
1181
+ /**
1182
+ * Find nodes whose name contains a substring (LIKE-based).
1183
+ * Useful for CamelCase-part matching where FTS fails because
1184
+ * e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
1185
+ *
1186
+ * Results are ordered by name length (shorter = more likely to be the core type).
1187
+ */
1188
+ findNodesByNameSubstring(substring, options = {}) {
1189
+ const { kinds, languages, limit = 30, excludePrefix } = options;
1190
+ let sql = `
1191
+ SELECT nodes.*, 1.0 as score
1192
+ FROM nodes
1193
+ WHERE name LIKE ?
1194
+ `;
1195
+ const params = [`%${substring}%`];
1196
+ // Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
1197
+ if (excludePrefix) {
1198
+ sql += ` AND name NOT LIKE ?`;
1199
+ params.push(`${substring}%`);
1200
+ }
1201
+ if (kinds && kinds.length > 0) {
1202
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1203
+ params.push(...kinds);
1204
+ }
1205
+ if (languages && languages.length > 0) {
1206
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1207
+ params.push(...languages);
1208
+ }
1209
+ sql += ' ORDER BY length(name) ASC LIMIT ?';
1210
+ params.push(limit);
1211
+ const rows = this.db.prepare(sql).all(...params);
1212
+ return rows.map((row) => ({
1213
+ node: rowToNode(row),
1214
+ score: row.score,
1215
+ }));
1216
+ }
1217
+ // ===========================================================================
1218
+ // Edge Operations
1219
+ // ===========================================================================
1220
+ /**
1221
+ * Insert a new edge
1222
+ */
1223
+ insertEdge(edge) {
1224
+ if (!this.stmts.insertEdge) {
1225
+ this.stmts.insertEdge = this.db.prepare(`
1226
+ INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
1227
+ VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
1228
+ `);
1229
+ }
1230
+ this.stmts.insertEdge.run({
1231
+ source: edge.source,
1232
+ target: edge.target,
1233
+ kind: edge.kind,
1234
+ metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
1235
+ line: edge.line ?? null,
1236
+ col: edge.column ?? null,
1237
+ provenance: edge.provenance ?? null,
1238
+ });
1239
+ }
1240
+ /**
1241
+ * Insert multiple edges in a transaction
1242
+ */
1243
+ insertEdges(edges) {
1244
+ if (edges.length === 0)
1245
+ return;
1246
+ this.db.transaction(() => {
1247
+ const endpointIds = new Set();
1248
+ for (const edge of edges) {
1249
+ endpointIds.add(edge.source);
1250
+ endpointIds.add(edge.target);
1251
+ }
1252
+ const existingNodeIds = this.getExistingNodeIds([...endpointIds]);
1253
+ for (const edge of edges) {
1254
+ if (!existingNodeIds.has(edge.source) || !existingNodeIds.has(edge.target)) {
1255
+ continue;
1256
+ }
1257
+ this.insertEdge(edge);
1258
+ }
1259
+ })();
1260
+ }
1261
+ /**
1262
+ * Delete all edges from a source node
1263
+ */
1264
+ deleteEdgesBySource(sourceId) {
1265
+ if (!this.stmts.deleteEdgesBySource) {
1266
+ this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
1267
+ }
1268
+ this.stmts.deleteEdgesBySource.run(sourceId);
1269
+ }
1270
+ /**
1271
+ * Get outgoing edges from a node
1272
+ */
1273
+ getOutgoingEdges(sourceId, kinds, provenance) {
1274
+ if ((kinds && kinds.length > 0) || provenance) {
1275
+ let sql = 'SELECT * FROM edges WHERE source = ?';
1276
+ const params = [sourceId];
1277
+ if (kinds && kinds.length > 0) {
1278
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1279
+ params.push(...kinds);
1280
+ }
1281
+ if (provenance) {
1282
+ sql += ' AND provenance = ?';
1283
+ params.push(provenance);
1284
+ }
1285
+ const rows = this.db.prepare(sql).all(...params);
1286
+ return rows.map(rowToEdge);
1287
+ }
1288
+ if (!this.stmts.getEdgesBySource) {
1289
+ this.stmts.getEdgesBySource = this.db.prepare('SELECT * FROM edges WHERE source = ?');
1290
+ }
1291
+ const rows = this.stmts.getEdgesBySource.all(sourceId);
1292
+ return rows.map(rowToEdge);
1293
+ }
1294
+ /**
1295
+ * Get incoming edges to a node
1296
+ */
1297
+ getIncomingEdges(targetId, kinds) {
1298
+ if (kinds && kinds.length > 0) {
1299
+ const sql = `SELECT * FROM edges WHERE target = ? AND kind IN (${kinds.map(() => '?').join(',')})`;
1300
+ const rows = this.db.prepare(sql).all(targetId, ...kinds);
1301
+ return rows.map(rowToEdge);
1302
+ }
1303
+ if (!this.stmts.getEdgesByTarget) {
1304
+ this.stmts.getEdgesByTarget = this.db.prepare('SELECT * FROM edges WHERE target = ?');
1305
+ }
1306
+ const rows = this.stmts.getEdgesByTarget.all(targetId);
1307
+ return rows.map(rowToEdge);
1308
+ }
1309
+ /**
1310
+ * Find all edges where both source and target are in the given node set.
1311
+ * Useful for recovering inter-node connectivity after BFS.
1312
+ */
1313
+ findEdgesBetweenNodes(nodeIds, kinds) {
1314
+ if (nodeIds.length === 0)
1315
+ return [];
1316
+ const idsJson = JSON.stringify(nodeIds);
1317
+ let sql = `SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?)) AND target IN (SELECT value FROM json_each(?))`;
1318
+ const params = [idsJson, idsJson];
1319
+ if (kinds && kinds.length > 0) {
1320
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1321
+ params.push(...kinds);
1322
+ }
1323
+ const rows = this.db.prepare(sql).all(...params);
1324
+ return rows.map(rowToEdge);
1325
+ }
1326
+ /**
1327
+ * Distinct file paths that DEPEND ON `filePath`: every file containing a
1328
+ * symbol with a cross-file edge (any kind except `contains`) into a symbol
1329
+ * of this file. This is the file-level projection of the symbol dependency
1330
+ * graph and the basis for blast-radius / `affected` test selection.
1331
+ *
1332
+ * It deliberately does NOT restrict to `imports` edges. In this graph an
1333
+ * `imports` edge connects a file to its own local import declarations
1334
+ * (it is always same-file), so an imports-only lookup returns zero
1335
+ * cross-file dependents for every file. The real cross-file dependency
1336
+ * signal is the resolved call/reference graph — calls, references,
1337
+ * instantiates, extends, implements, overrides, type_of, returns,
1338
+ * decorates — exactly what {@link GraphTraverser.getImpactRadius} traverses.
1339
+ * `contains` is excluded: a parent containing a symbol does not *depend* on
1340
+ * it. One indexed query (idx_nodes_file_path + idx_edges_target_kind).
1341
+ */
1342
+ getDependentFilePaths(filePath) {
1343
+ const sql = `SELECT DISTINCT src.file_path AS fp
1344
+ FROM edges e
1345
+ JOIN nodes tgt ON tgt.id = e.target
1346
+ JOIN nodes src ON src.id = e.source
1347
+ WHERE tgt.file_path = ?
1348
+ AND e.kind != 'contains'
1349
+ AND src.file_path != ?`;
1350
+ const rows = this.db.prepare(sql).all(filePath, filePath);
1351
+ return rows.map((r) => r.fp);
1352
+ }
1353
+ /**
1354
+ * Distinct file paths that `filePath` DEPENDS ON — the inverse of
1355
+ * {@link getDependentFilePaths}: every file containing a symbol that a
1356
+ * symbol of this file has a cross-file edge into. Same edge-kind rules
1357
+ * (all kinds except `contains`); same reason imports-only is insufficient.
1358
+ */
1359
+ getDependencyFilePaths(filePath) {
1360
+ const sql = `SELECT DISTINCT tgt.file_path AS fp
1361
+ FROM edges e
1362
+ JOIN nodes src ON src.id = e.source
1363
+ JOIN nodes tgt ON tgt.id = e.target
1364
+ WHERE src.file_path = ?
1365
+ AND e.kind != 'contains'
1366
+ AND tgt.file_path != ?`;
1367
+ const rows = this.db.prepare(sql).all(filePath, filePath);
1368
+ return rows.map((r) => r.fp);
1369
+ }
1370
+ /**
1371
+ * Cross-file edges whose TARGET is a node in `filePath` and whose SOURCE is a
1372
+ * node in a *different* file, paired with the target node's (name, kind) so a
1373
+ * caller can re-resolve the edge to the re-indexed target's new ID (node IDs
1374
+ * are `sha256(filePath:kind:name:line)`, so any line shift in the callee file
1375
+ * changes target IDs and a naive re-insert by old ID silently drops them).
1376
+ * Used by `storeExtractionResult` to preserve incoming edges across a file
1377
+ * re-index (issue #899). Same edge-kind rules as
1378
+ * {@link getDependentFilePaths}: all kinds except `contains`.
1379
+ */
1380
+ getCrossFileIncomingEdgesWithTarget(filePath) {
1381
+ const sql = `SELECT e.*, tgt.name AS target_name, tgt.kind AS target_kind,
1382
+ src.file_path AS source_file_path, src.language AS source_language
1383
+ FROM edges e
1384
+ JOIN nodes tgt ON tgt.id = e.target
1385
+ JOIN nodes src ON src.id = e.source
1386
+ WHERE tgt.file_path = ?
1387
+ AND e.kind != 'contains'
1388
+ AND src.file_path != ?`;
1389
+ const rows = this.db.prepare(sql).all(filePath, filePath);
1390
+ return rows.map(row => ({
1391
+ ...rowToEdge(row),
1392
+ targetName: row.target_name,
1393
+ targetKind: row.target_kind,
1394
+ sourceFilePath: row.source_file_path,
1395
+ sourceLanguage: row.source_language,
1396
+ }));
1397
+ }
1398
+ // ===========================================================================
1399
+ // File Operations
1400
+ // ===========================================================================
1401
+ /**
1402
+ * Insert or update a file record
1403
+ */
1404
+ upsertFile(file) {
1405
+ if (!this.stmts.upsertFile) {
1406
+ this.stmts.upsertFile = this.db.prepare(`
1407
+ INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
1408
+ VALUES (@path, @contentHash, @language, @size, @modifiedAt, @indexedAt, @nodeCount, @errors)
1409
+ ON CONFLICT(path) DO UPDATE SET
1410
+ content_hash = @contentHash,
1411
+ language = @language,
1412
+ size = @size,
1413
+ modified_at = @modifiedAt,
1414
+ indexed_at = @indexedAt,
1415
+ node_count = @nodeCount,
1416
+ errors = @errors
1417
+ `);
1418
+ }
1419
+ this.stmts.upsertFile.run({
1420
+ path: file.path,
1421
+ contentHash: file.contentHash,
1422
+ language: file.language,
1423
+ size: file.size,
1424
+ modifiedAt: file.modifiedAt,
1425
+ indexedAt: file.indexedAt,
1426
+ nodeCount: file.nodeCount,
1427
+ errors: file.errors ? JSON.stringify(file.errors) : null,
1428
+ });
1429
+ }
1430
+ /**
1431
+ * Delete a file record and its nodes
1432
+ */
1433
+ deleteFile(filePath) {
1434
+ this.db.transaction(() => {
1435
+ this.deleteNodesByFile(filePath);
1436
+ if (!this.stmts.deleteFile) {
1437
+ this.stmts.deleteFile = this.db.prepare('DELETE FROM files WHERE path = ?');
1438
+ }
1439
+ this.stmts.deleteFile.run(filePath);
1440
+ })();
1441
+ }
1442
+ /**
1443
+ * Get a file record by path
1444
+ */
1445
+ getFileByPath(filePath) {
1446
+ if (!this.stmts.getFileByPath) {
1447
+ this.stmts.getFileByPath = this.db.prepare('SELECT * FROM files WHERE path = ?');
1448
+ }
1449
+ const row = this.stmts.getFileByPath.get(filePath);
1450
+ return row ? rowToFileRecord(row) : null;
1451
+ }
1452
+ /**
1453
+ * Get all tracked files
1454
+ */
1455
+ getAllFiles() {
1456
+ if (!this.stmts.getAllFiles) {
1457
+ this.stmts.getAllFiles = this.db.prepare('SELECT * FROM files ORDER BY path');
1458
+ }
1459
+ const rows = this.stmts.getAllFiles.all();
1460
+ return rows.map(rowToFileRecord);
1461
+ }
1462
+ /**
1463
+ * Most recent index timestamp (ms since epoch) across all tracked files, or
1464
+ * null when nothing is indexed yet. One indexed aggregate, no per-row scan. (#329)
1465
+ */
1466
+ getLastIndexedAt() {
1467
+ const row = this.db
1468
+ .prepare('SELECT MAX(indexed_at) AS last FROM files')
1469
+ .get();
1470
+ return row?.last ?? null;
1471
+ }
1472
+ /**
1473
+ * Get files that need re-indexing (hash changed)
1474
+ */
1475
+ getStaleFiles(currentHashes) {
1476
+ const files = this.getAllFiles();
1477
+ return files.filter((f) => {
1478
+ const currentHash = currentHashes.get(f.path);
1479
+ return currentHash && currentHash !== f.contentHash;
1480
+ });
1481
+ }
1482
+ // ===========================================================================
1483
+ // Unresolved References
1484
+ // ===========================================================================
1485
+ /**
1486
+ * Insert an unresolved reference
1487
+ */
1488
+ insertUnresolvedRef(ref) {
1489
+ if (!this.stmts.insertUnresolved) {
1490
+ this.stmts.insertUnresolved = this.db.prepare(`
1491
+ INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language)
1492
+ VALUES (@fromNodeId, @referenceName, @referenceKind, @line, @col, @candidates, @filePath, @language)
1493
+ `);
1494
+ }
1495
+ this.stmts.insertUnresolved.run({
1496
+ fromNodeId: ref.fromNodeId,
1497
+ referenceName: ref.referenceName,
1498
+ referenceKind: ref.referenceKind,
1499
+ line: ref.line,
1500
+ col: ref.column,
1501
+ candidates: ref.candidates ? JSON.stringify(ref.candidates) : null,
1502
+ filePath: ref.filePath ?? '',
1503
+ language: ref.language ?? 'unknown',
1504
+ });
1505
+ }
1506
+ /**
1507
+ * Insert multiple unresolved references in a transaction
1508
+ */
1509
+ insertUnresolvedRefsBatch(refs) {
1510
+ if (refs.length === 0)
1511
+ return;
1512
+ const insert = this.db.transaction(() => {
1513
+ for (const ref of refs) {
1514
+ this.insertUnresolvedRef(ref);
1515
+ }
1516
+ });
1517
+ insert();
1518
+ }
1519
+ /**
1520
+ * Delete unresolved references from a node
1521
+ */
1522
+ deleteUnresolvedByNode(nodeId) {
1523
+ if (!this.stmts.deleteUnresolvedByNode) {
1524
+ this.stmts.deleteUnresolvedByNode = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ?');
1525
+ }
1526
+ this.stmts.deleteUnresolvedByNode.run(nodeId);
1527
+ }
1528
+ /**
1529
+ * Get unresolved references by name (for resolution)
1530
+ */
1531
+ getUnresolvedByName(name) {
1532
+ if (!this.stmts.getUnresolvedByName) {
1533
+ this.stmts.getUnresolvedByName = this.db.prepare('SELECT * FROM unresolved_refs WHERE reference_name = ?');
1534
+ }
1535
+ const rows = this.stmts.getUnresolvedByName.all(name);
1536
+ return rows.map((row) => ({
1537
+ fromNodeId: row.from_node_id,
1538
+ referenceName: row.reference_name,
1539
+ referenceKind: row.reference_kind,
1540
+ line: row.line,
1541
+ column: row.col,
1542
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1543
+ filePath: row.file_path,
1544
+ language: row.language,
1545
+ }));
1546
+ }
1547
+ /**
1548
+ * Get all unresolved references
1549
+ */
1550
+ getUnresolvedReferences() {
1551
+ const rows = this.db.prepare('SELECT * FROM unresolved_refs').all();
1552
+ return rows.map((row) => ({
1553
+ fromNodeId: row.from_node_id,
1554
+ referenceName: row.reference_name,
1555
+ referenceKind: row.reference_kind,
1556
+ line: row.line,
1557
+ column: row.col,
1558
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1559
+ filePath: row.file_path,
1560
+ language: row.language,
1561
+ }));
1562
+ }
1563
+ /**
1564
+ * Get the count of PENDING (never-attempted) references without loading
1565
+ * them into memory. Rows marked status='failed' — attempted by a completed
1566
+ * pass, no match — are excluded: they are not outstanding work, only retry
1567
+ * candidates for the #1240 sweep, so they must not trip the #1187 orphan
1568
+ * sweep or the `status` pending-refs warning.
1569
+ */
1570
+ getUnresolvedReferencesCount() {
1571
+ if (!this.stmts.getUnresolvedCount) {
1572
+ this.stmts.getUnresolvedCount = this.db.prepare("SELECT COUNT(*) as count FROM unresolved_refs WHERE status = 'pending'");
1573
+ }
1574
+ const row = this.stmts.getUnresolvedCount.get();
1575
+ return row.count;
1576
+ }
1577
+ /**
1578
+ * Get a batch of PENDING unresolved references using LIMIT/OFFSET
1579
+ * pagination. Used to process references in bounded memory chunks; failed
1580
+ * rows are excluded so the batched drain loop terminates once every row
1581
+ * has been attempted.
1582
+ */
1583
+ getUnresolvedReferencesBatch(offset, limit) {
1584
+ if (!this.stmts.getUnresolvedBatch) {
1585
+ this.stmts.getUnresolvedBatch = this.db.prepare("SELECT * FROM unresolved_refs WHERE status = 'pending' LIMIT ? OFFSET ?");
1586
+ }
1587
+ const rows = this.stmts.getUnresolvedBatch.all(limit, offset);
1588
+ return rows.map((row) => ({
1589
+ fromNodeId: row.from_node_id,
1590
+ referenceName: row.reference_name,
1591
+ referenceKind: row.reference_kind,
1592
+ line: row.line,
1593
+ column: row.col,
1594
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1595
+ filePath: row.file_path,
1596
+ language: row.language,
1597
+ }));
1598
+ }
1599
+ /**
1600
+ * Get all tracked file paths (lightweight — no full FileRecord objects)
1601
+ */
1602
+ getAllFilePaths() {
1603
+ if (!this.stmts.getAllFilePaths) {
1604
+ this.stmts.getAllFilePaths = this.db.prepare('SELECT path FROM files ORDER BY path');
1605
+ }
1606
+ const rows = this.stmts.getAllFilePaths.all();
1607
+ return rows.map((r) => r.path);
1608
+ }
1609
+ /**
1610
+ * Get all distinct node names (lightweight — just name strings for pre-filtering)
1611
+ */
1612
+ getAllNodeNames() {
1613
+ if (!this.stmts.getAllNodeNames) {
1614
+ this.stmts.getAllNodeNames = this.db.prepare('SELECT DISTINCT name FROM nodes');
1615
+ }
1616
+ const rows = this.stmts.getAllNodeNames.all();
1617
+ return rows.map((r) => r.name);
1618
+ }
1619
+ /**
1620
+ * Stream the distinct node names one row at a time — the incremental
1621
+ * counterpart to {@link getAllNodeNames} for callers that need to yield
1622
+ * to the event loop mid-scan (resolver cache warm-up on multi-million-node
1623
+ * indexes). Fresh statement per call: the iterator holds an open cursor.
1624
+ */
1625
+ *iterateNodeNames() {
1626
+ const stmt = this.db.prepare('SELECT DISTINCT name FROM nodes');
1627
+ for (const row of stmt.iterate()) {
1628
+ yield row.name;
1629
+ }
1630
+ }
1631
+ /**
1632
+ * Get unresolved references scoped to specific file paths.
1633
+ * Uses the idx_unresolved_file_path index for efficient lookup.
1634
+ */
1635
+ getUnresolvedReferencesByFiles(filePaths) {
1636
+ if (filePaths.length === 0)
1637
+ return [];
1638
+ // Chunk under SQLite's parameter limit: the first sync of a very large repo
1639
+ // passes every changed file here, which an unbounded `IN (...)` would bind
1640
+ // as one parameter each — exceeding MAX_VARIABLE_NUMBER and aborting with
1641
+ // "too many SQL variables". (#540)
1642
+ const rows = [];
1643
+ for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1644
+ const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1645
+ const placeholders = chunk.map(() => '?').join(',');
1646
+ const chunkRows = this.db
1647
+ .prepare(`SELECT * FROM unresolved_refs WHERE status = 'pending' AND file_path IN (${placeholders})`)
1648
+ .all(...chunk);
1649
+ rows.push(...chunkRows);
1650
+ }
1651
+ return rows.map((row) => ({
1652
+ fromNodeId: row.from_node_id,
1653
+ referenceName: row.reference_name,
1654
+ referenceKind: row.reference_kind,
1655
+ line: row.line,
1656
+ column: row.col,
1657
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1658
+ filePath: row.file_path,
1659
+ language: row.language,
1660
+ }));
1661
+ }
1662
+ /**
1663
+ * Delete all unresolved references (after resolution)
1664
+ */
1665
+ clearUnresolvedReferences() {
1666
+ this.db.exec('DELETE FROM unresolved_refs');
1667
+ }
1668
+ /**
1669
+ * Delete resolved references by their IDs
1670
+ */
1671
+ deleteResolvedReferences(fromNodeIds) {
1672
+ if (fromNodeIds.length === 0)
1673
+ return;
1674
+ // Chunk under SQLite's parameter limit, matching every other IN-list in
1675
+ // this file. The internal resolution path uses deleteSpecificResolvedReferences
1676
+ // instead, but QueryBuilder is part of the public API, so a library consumer
1677
+ // passing more ids than SQLITE_MAX_VARIABLE_NUMBER (32766 on the bundled
1678
+ // node:sqlite) would otherwise hit "too many SQL variables". (#540, #1001)
1679
+ for (let i = 0; i < fromNodeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1680
+ const chunk = fromNodeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1681
+ const placeholders = chunk.map(() => '?').join(',');
1682
+ this.db.prepare(`DELETE FROM unresolved_refs WHERE from_node_id IN (${placeholders})`).run(...chunk);
1683
+ }
1684
+ }
1685
+ /**
1686
+ * Delete specific resolved references by (fromNodeId, referenceName, referenceKind) tuples.
1687
+ * More precise than deleteResolvedReferences — only removes refs that were actually resolved.
1688
+ */
1689
+ deleteSpecificResolvedReferences(refs) {
1690
+ if (refs.length === 0)
1691
+ return;
1692
+ const stmt = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?');
1693
+ const deleteMany = this.db.transaction((items) => {
1694
+ for (const ref of items) {
1695
+ stmt.run(ref.fromNodeId, ref.referenceName, ref.referenceKind);
1696
+ }
1697
+ });
1698
+ deleteMany(refs);
1699
+ }
1700
+ /**
1701
+ * Mark refs a completed resolution pass could not resolve as status='failed'
1702
+ * instead of deleting them (#1240). Failed rows are invisible to the pending
1703
+ * count/batch readers (so drain loops and the #1187 orphan sweep still
1704
+ * terminate) but stay queryable by name_tail so a later sync can retry them
1705
+ * when a changed file introduces a symbol that could satisfy them. name_tail
1706
+ * is (re)written here so rows inserted before the v8 migration get their
1707
+ * tail the first time they're attempted.
1708
+ */
1709
+ markReferencesFailed(refs) {
1710
+ if (refs.length === 0)
1711
+ return;
1712
+ const stmt = this.db.prepare("UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?");
1713
+ const markMany = this.db.transaction((items) => {
1714
+ for (const ref of items) {
1715
+ stmt.run(referenceNameTail(ref.referenceName), ref.fromNodeId, ref.referenceName, ref.referenceKind);
1716
+ }
1717
+ });
1718
+ markMany(refs);
1719
+ }
1720
+ /**
1721
+ * Failed refs whose name tail matches one of the given symbol names — the
1722
+ * candidates a sync should retry after files carrying those names changed
1723
+ * (#1240). Names matching more than `perNameCeiling` failed refs are
1724
+ * skipped entirely: at that population a name is external/builtin noise
1725
+ * (`get`, `map`, …) that one new definition won't resolve — the same
1726
+ * rationale as resolution's AMBIGUOUS_NAME_CEILING (#999) — and retrying an
1727
+ * arbitrary subset would be both wasted work and incoherent coverage.
1728
+ */
1729
+ getRetryableFailedReferences(names, perNameCeiling = 500) {
1730
+ if (names.length === 0)
1731
+ return [];
1732
+ // Pass 1: per-tail counts, chunked under the SQLite parameter limit.
1733
+ const retryNames = [];
1734
+ for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1735
+ const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1736
+ const placeholders = chunk.map(() => '?').join(',');
1737
+ const counts = this.db
1738
+ .prepare(`SELECT name_tail, COUNT(*) as count FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders}) GROUP BY name_tail`)
1739
+ .all(...chunk);
1740
+ for (const row of counts) {
1741
+ if (row.count <= perNameCeiling)
1742
+ retryNames.push(row.name_tail);
1743
+ }
1744
+ }
1745
+ if (retryNames.length === 0)
1746
+ return [];
1747
+ // Pass 2: load the surviving rows.
1748
+ const rows = [];
1749
+ for (let i = 0; i < retryNames.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1750
+ const chunk = retryNames.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1751
+ const placeholders = chunk.map(() => '?').join(',');
1752
+ const chunkRows = this.db
1753
+ .prepare(`SELECT * FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders})`)
1754
+ .all(...chunk);
1755
+ rows.push(...chunkRows);
1756
+ }
1757
+ return rows.map((row) => ({
1758
+ fromNodeId: row.from_node_id,
1759
+ referenceName: row.reference_name,
1760
+ referenceKind: row.reference_kind,
1761
+ line: row.line,
1762
+ column: row.col,
1763
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
1764
+ filePath: row.file_path,
1765
+ language: row.language,
1766
+ }));
1767
+ }
1768
+ /**
1769
+ * Distinct node names present in the given files — the symbol names a sync
1770
+ * pass uses to look up retryable failed refs after those files changed.
1771
+ */
1772
+ getNodeNamesByFiles(filePaths) {
1773
+ if (filePaths.length === 0)
1774
+ return [];
1775
+ const names = new Set();
1776
+ for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1777
+ const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1778
+ const placeholders = chunk.map(() => '?').join(',');
1779
+ const rows = this.db
1780
+ .prepare(`SELECT DISTINCT name FROM nodes WHERE file_path IN (${placeholders})`)
1781
+ .all(...chunk);
1782
+ for (const row of rows)
1783
+ names.add(row.name);
1784
+ }
1785
+ return [...names];
1786
+ }
1787
+ // ===========================================================================
1788
+ // Statistics
1789
+ // ===========================================================================
1790
+ /**
1791
+ * Lightweight (nodes, edges) count snapshot. Used around an index/sync
1792
+ * run to compute true additions across extraction + resolution +
1793
+ * synthesis — the per-phase counter in the orchestrator only sees
1794
+ * extraction's contribution, which is why the CLI summary under-reported
1795
+ * the edge count (resolution + synthesizer edges were invisible).
1796
+ */
1797
+ getNodeAndEdgeCount() {
1798
+ return this.db
1799
+ .prepare('SELECT (SELECT COUNT(*) FROM nodes) AS nodes, (SELECT COUNT(*) FROM edges) AS edges')
1800
+ .get();
1801
+ }
1802
+ /**
1803
+ * Get graph statistics
1804
+ */
1805
+ getStats() {
1806
+ // Single query for all three aggregate counts
1807
+ const counts = this.db.prepare(`
1808
+ SELECT
1809
+ (SELECT COUNT(*) FROM nodes) AS node_count,
1810
+ (SELECT COUNT(*) FROM edges) AS edge_count,
1811
+ (SELECT COUNT(*) FROM files) AS file_count
1812
+ `).get();
1813
+ const nodesByKind = {};
1814
+ const nodeKindRows = this.db
1815
+ .prepare('SELECT kind, COUNT(*) as count FROM nodes GROUP BY kind')
1816
+ .all();
1817
+ for (const row of nodeKindRows) {
1818
+ nodesByKind[row.kind] = row.count;
1819
+ }
1820
+ const edgesByKind = {};
1821
+ const edgeKindRows = this.db
1822
+ .prepare('SELECT kind, COUNT(*) as count FROM edges GROUP BY kind')
1823
+ .all();
1824
+ for (const row of edgeKindRows) {
1825
+ edgesByKind[row.kind] = row.count;
1826
+ }
1827
+ const filesByLanguage = {};
1828
+ const languageRows = this.db
1829
+ .prepare('SELECT language, COUNT(*) as count FROM files GROUP BY language')
1830
+ .all();
1831
+ for (const row of languageRows) {
1832
+ filesByLanguage[row.language] = row.count;
1833
+ }
1834
+ return {
1835
+ nodeCount: counts.node_count,
1836
+ edgeCount: counts.edge_count,
1837
+ fileCount: counts.file_count,
1838
+ nodesByKind,
1839
+ edgesByKind,
1840
+ filesByLanguage,
1841
+ dbSizeBytes: 0, // Set by caller using DatabaseConnection.getSize()
1842
+ lastUpdated: Date.now(),
1843
+ };
1844
+ }
1845
+ // ===========================================================================
1846
+ // Project Metadata
1847
+ // ===========================================================================
1848
+ /**
1849
+ * Get a metadata value by key
1850
+ */
1851
+ getMetadata(key) {
1852
+ const row = this.db.prepare('SELECT value FROM project_metadata WHERE key = ?').get(key);
1853
+ return row?.value ?? null;
1854
+ }
1855
+ /**
1856
+ * Set a metadata key-value pair (upsert)
1857
+ */
1858
+ setMetadata(key, value) {
1859
+ 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());
1860
+ }
1861
+ /**
1862
+ * Get all metadata as a key-value record
1863
+ */
1864
+ getAllMetadata() {
1865
+ const rows = this.db.prepare('SELECT key, value FROM project_metadata').all();
1866
+ const result = {};
1867
+ for (const row of rows) {
1868
+ result[row.key] = row.value;
1869
+ }
1870
+ return result;
1871
+ }
1872
+ /**
1873
+ * Clear all data from the database
1874
+ */
1875
+ clear() {
1876
+ this.nodeCache.clear();
1877
+ this.db.transaction(() => {
1878
+ this.db.exec('DELETE FROM unresolved_refs');
1879
+ this.db.exec('DELETE FROM edges');
1880
+ this.db.exec('DELETE FROM nodes');
1881
+ this.db.exec('DELETE FROM files');
1882
+ })();
1883
+ }
1884
+ }
1885
+ exports.QueryBuilder = QueryBuilder;
1886
+ //# sourceMappingURL=queries.js.map