@quolu/lattice 0.1.0

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