codegraph-java 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 (866) hide show
  1. package/README.md +131 -0
  2. package/dist/base-graph/index.d.ts +57 -0
  3. package/dist/base-graph/index.d.ts.map +1 -0
  4. package/dist/base-graph/index.js +175 -0
  5. package/dist/base-graph/index.js.map +1 -0
  6. package/dist/bin/codegraph.d.ts +28 -0
  7. package/dist/bin/codegraph.d.ts.map +1 -0
  8. package/dist/bin/codegraph.js +2615 -0
  9. package/dist/bin/codegraph.js.map +1 -0
  10. package/dist/bin/command-supervision.d.ts +49 -0
  11. package/dist/bin/command-supervision.d.ts.map +1 -0
  12. package/dist/bin/command-supervision.js +95 -0
  13. package/dist/bin/command-supervision.js.map +1 -0
  14. package/dist/bin/fatal-handler.d.ts +20 -0
  15. package/dist/bin/fatal-handler.d.ts.map +1 -0
  16. package/dist/bin/fatal-handler.js +118 -0
  17. package/dist/bin/fatal-handler.js.map +1 -0
  18. package/dist/bin/node-version-check.d.ts +45 -0
  19. package/dist/bin/node-version-check.d.ts.map +1 -0
  20. package/dist/bin/node-version-check.js +98 -0
  21. package/dist/bin/node-version-check.js.map +1 -0
  22. package/dist/bin/uninstall.d.ts +14 -0
  23. package/dist/bin/uninstall.d.ts.map +1 -0
  24. package/dist/bin/uninstall.js +36 -0
  25. package/dist/bin/uninstall.js.map +1 -0
  26. package/dist/context/formatter.d.ts +36 -0
  27. package/dist/context/formatter.d.ts.map +1 -0
  28. package/dist/context/formatter.js +269 -0
  29. package/dist/context/formatter.js.map +1 -0
  30. package/dist/context/index.d.ts +131 -0
  31. package/dist/context/index.d.ts.map +1 -0
  32. package/dist/context/index.js +1378 -0
  33. package/dist/context/index.js.map +1 -0
  34. package/dist/context/markers.d.ts +19 -0
  35. package/dist/context/markers.d.ts.map +1 -0
  36. package/dist/context/markers.js +22 -0
  37. package/dist/context/markers.js.map +1 -0
  38. package/dist/db/index.d.ts +380 -0
  39. package/dist/db/index.d.ts.map +1 -0
  40. package/dist/db/index.js +854 -0
  41. package/dist/db/index.js.map +1 -0
  42. package/dist/db/migrations.d.ts +44 -0
  43. package/dist/db/migrations.d.ts.map +1 -0
  44. package/dist/db/migrations.js +255 -0
  45. package/dist/db/migrations.js.map +1 -0
  46. package/dist/db/queries.d.ts +1060 -0
  47. package/dist/db/queries.d.ts.map +1 -0
  48. package/dist/db/queries.js +3191 -0
  49. package/dist/db/queries.js.map +1 -0
  50. package/dist/db/schema.sql +209 -0
  51. package/dist/db/sqlite-adapter.d.ts +55 -0
  52. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  53. package/dist/db/sqlite-adapter.js +135 -0
  54. package/dist/db/sqlite-adapter.js.map +1 -0
  55. package/dist/db/wal-valve.d.ts +119 -0
  56. package/dist/db/wal-valve.d.ts.map +1 -0
  57. package/dist/db/wal-valve.js +290 -0
  58. package/dist/db/wal-valve.js.map +1 -0
  59. package/dist/directory.d.ts +213 -0
  60. package/dist/directory.d.ts.map +1 -0
  61. package/dist/directory.js +781 -0
  62. package/dist/directory.js.map +1 -0
  63. package/dist/errors.d.ts +150 -0
  64. package/dist/errors.d.ts.map +1 -0
  65. package/dist/errors.js +234 -0
  66. package/dist/errors.js.map +1 -0
  67. package/dist/extraction/extraction-version.d.ts +25 -0
  68. package/dist/extraction/extraction-version.d.ts.map +1 -0
  69. package/dist/extraction/extraction-version.js +28 -0
  70. package/dist/extraction/extraction-version.js.map +1 -0
  71. package/dist/extraction/function-ref.d.ts +118 -0
  72. package/dist/extraction/function-ref.d.ts.map +1 -0
  73. package/dist/extraction/function-ref.js +746 -0
  74. package/dist/extraction/function-ref.js.map +1 -0
  75. package/dist/extraction/generated-detection.d.ts +66 -0
  76. package/dist/extraction/generated-detection.d.ts.map +1 -0
  77. package/dist/extraction/generated-detection.js +248 -0
  78. package/dist/extraction/generated-detection.js.map +1 -0
  79. package/dist/extraction/grammars.d.ts +148 -0
  80. package/dist/extraction/grammars.d.ts.map +1 -0
  81. package/dist/extraction/grammars.js +558 -0
  82. package/dist/extraction/grammars.js.map +1 -0
  83. package/dist/extraction/index.d.ts +367 -0
  84. package/dist/extraction/index.d.ts.map +1 -0
  85. package/dist/extraction/index.js +2833 -0
  86. package/dist/extraction/index.js.map +1 -0
  87. package/dist/extraction/kernel/decode.d.ts +9 -0
  88. package/dist/extraction/kernel/decode.d.ts.map +1 -0
  89. package/dist/extraction/kernel/decode.js +162 -0
  90. package/dist/extraction/kernel/decode.js.map +1 -0
  91. package/dist/extraction/kernel/index.d.ts +64 -0
  92. package/dist/extraction/kernel/index.d.ts.map +1 -0
  93. package/dist/extraction/kernel/index.js +204 -0
  94. package/dist/extraction/kernel/index.js.map +1 -0
  95. package/dist/extraction/kernel/layout.d.ts +101 -0
  96. package/dist/extraction/kernel/layout.d.ts.map +1 -0
  97. package/dist/extraction/kernel/layout.js +104 -0
  98. package/dist/extraction/kernel/layout.js.map +1 -0
  99. package/dist/extraction/kernel/loader.d.ts +103 -0
  100. package/dist/extraction/kernel/loader.d.ts.map +1 -0
  101. package/dist/extraction/kernel/loader.js +146 -0
  102. package/dist/extraction/kernel/loader.js.map +1 -0
  103. package/dist/extraction/languages/c-cpp.d.ts +124 -0
  104. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  105. package/dist/extraction/languages/c-cpp.js +1689 -0
  106. package/dist/extraction/languages/c-cpp.js.map +1 -0
  107. package/dist/extraction/languages/index.d.ts +11 -0
  108. package/dist/extraction/languages/index.d.ts.map +1 -0
  109. package/dist/extraction/languages/index.js +15 -0
  110. package/dist/extraction/languages/index.js.map +1 -0
  111. package/dist/extraction/languages/java.d.ts +3 -0
  112. package/dist/extraction/languages/java.d.ts.map +1 -0
  113. package/dist/extraction/languages/java.js +315 -0
  114. package/dist/extraction/languages/java.js.map +1 -0
  115. package/dist/extraction/languages/rust.d.ts +23 -0
  116. package/dist/extraction/languages/rust.d.ts.map +1 -0
  117. package/dist/extraction/languages/rust.js +169 -0
  118. package/dist/extraction/languages/rust.js.map +1 -0
  119. package/dist/extraction/parse-pool.d.ts +167 -0
  120. package/dist/extraction/parse-pool.d.ts.map +1 -0
  121. package/dist/extraction/parse-pool.js +421 -0
  122. package/dist/extraction/parse-pool.js.map +1 -0
  123. package/dist/extraction/parse-worker.d.ts +8 -0
  124. package/dist/extraction/parse-worker.d.ts.map +1 -0
  125. package/dist/extraction/parse-worker.js +138 -0
  126. package/dist/extraction/parse-worker.js.map +1 -0
  127. package/dist/extraction/store-worker.d.ts +24 -0
  128. package/dist/extraction/store-worker.d.ts.map +1 -0
  129. package/dist/extraction/store-worker.js +139 -0
  130. package/dist/extraction/store-worker.js.map +1 -0
  131. package/dist/extraction/store-writer.d.ts +63 -0
  132. package/dist/extraction/store-writer.d.ts.map +1 -0
  133. package/dist/extraction/store-writer.js +174 -0
  134. package/dist/extraction/store-writer.js.map +1 -0
  135. package/dist/extraction/syntax-tokens.d.ts +103 -0
  136. package/dist/extraction/syntax-tokens.d.ts.map +1 -0
  137. package/dist/extraction/syntax-tokens.js +381 -0
  138. package/dist/extraction/syntax-tokens.js.map +1 -0
  139. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  140. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  141. package/dist/extraction/tree-sitter-helpers.js +153 -0
  142. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  143. package/dist/extraction/tree-sitter-types.d.ts +260 -0
  144. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  145. package/dist/extraction/tree-sitter-types.js +10 -0
  146. package/dist/extraction/tree-sitter-types.js.map +1 -0
  147. package/dist/extraction/tree-sitter.d.ts +745 -0
  148. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  149. package/dist/extraction/tree-sitter.js +6725 -0
  150. package/dist/extraction/tree-sitter.js.map +1 -0
  151. package/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  152. package/dist/extraction/wasm-runtime-flags.d.ts +53 -0
  153. package/dist/extraction/wasm-runtime-flags.d.ts.map +1 -0
  154. package/dist/extraction/wasm-runtime-flags.js +130 -0
  155. package/dist/extraction/wasm-runtime-flags.js.map +1 -0
  156. package/dist/graph/branch-guards.d.ts +248 -0
  157. package/dist/graph/branch-guards.d.ts.map +1 -0
  158. package/dist/graph/branch-guards.js +2231 -0
  159. package/dist/graph/branch-guards.js.map +1 -0
  160. package/dist/graph/dead-code.d.ts +251 -0
  161. package/dist/graph/dead-code.d.ts.map +1 -0
  162. package/dist/graph/dead-code.js +756 -0
  163. package/dist/graph/dead-code.js.map +1 -0
  164. package/dist/graph/dynamic-boundary-report.d.ts +121 -0
  165. package/dist/graph/dynamic-boundary-report.d.ts.map +1 -0
  166. package/dist/graph/dynamic-boundary-report.js +283 -0
  167. package/dist/graph/dynamic-boundary-report.js.map +1 -0
  168. package/dist/graph/index.d.ts +12 -0
  169. package/dist/graph/index.d.ts.map +1 -0
  170. package/dist/graph/index.js +28 -0
  171. package/dist/graph/index.js.map +1 -0
  172. package/dist/graph/named-symbol-flow.d.ts +153 -0
  173. package/dist/graph/named-symbol-flow.d.ts.map +1 -0
  174. package/dist/graph/named-symbol-flow.js +609 -0
  175. package/dist/graph/named-symbol-flow.js.map +1 -0
  176. package/dist/graph/queries.d.ts +106 -0
  177. package/dist/graph/queries.d.ts.map +1 -0
  178. package/dist/graph/queries.js +341 -0
  179. package/dist/graph/queries.js.map +1 -0
  180. package/dist/graph/traversal.d.ts +127 -0
  181. package/dist/graph/traversal.d.ts.map +1 -0
  182. package/dist/graph/traversal.js +599 -0
  183. package/dist/graph/traversal.js.map +1 -0
  184. package/dist/graph/type-hierarchy.d.ts +155 -0
  185. package/dist/graph/type-hierarchy.d.ts.map +1 -0
  186. package/dist/graph/type-hierarchy.js +382 -0
  187. package/dist/graph/type-hierarchy.js.map +1 -0
  188. package/dist/index.d.ts +886 -0
  189. package/dist/index.d.ts.map +1 -0
  190. package/dist/index.js +2019 -0
  191. package/dist/index.js.map +1 -0
  192. package/dist/installer/beta-signup.d.ts +54 -0
  193. package/dist/installer/beta-signup.d.ts.map +1 -0
  194. package/dist/installer/beta-signup.js +178 -0
  195. package/dist/installer/beta-signup.js.map +1 -0
  196. package/dist/installer/config-writer.d.ts +28 -0
  197. package/dist/installer/config-writer.d.ts.map +1 -0
  198. package/dist/installer/config-writer.js +91 -0
  199. package/dist/installer/config-writer.js.map +1 -0
  200. package/dist/installer/index.d.ts +143 -0
  201. package/dist/installer/index.d.ts.map +1 -0
  202. package/dist/installer/index.js +632 -0
  203. package/dist/installer/index.js.map +1 -0
  204. package/dist/installer/instructions-template.d.ts +41 -0
  205. package/dist/installer/instructions-template.d.ts.map +1 -0
  206. package/dist/installer/instructions-template.js +53 -0
  207. package/dist/installer/instructions-template.js.map +1 -0
  208. package/dist/installer/targets/antigravity.d.ts +57 -0
  209. package/dist/installer/targets/antigravity.d.ts.map +1 -0
  210. package/dist/installer/targets/antigravity.js +308 -0
  211. package/dist/installer/targets/antigravity.js.map +1 -0
  212. package/dist/installer/targets/claude.d.ts +62 -0
  213. package/dist/installer/targets/claude.d.ts.map +1 -0
  214. package/dist/installer/targets/claude.js +486 -0
  215. package/dist/installer/targets/claude.js.map +1 -0
  216. package/dist/installer/targets/codex.d.ts +32 -0
  217. package/dist/installer/targets/codex.d.ts.map +1 -0
  218. package/dist/installer/targets/codex.js +202 -0
  219. package/dist/installer/targets/codex.js.map +1 -0
  220. package/dist/installer/targets/copilot-cli.d.ts +32 -0
  221. package/dist/installer/targets/copilot-cli.d.ts.map +1 -0
  222. package/dist/installer/targets/copilot-cli.js +209 -0
  223. package/dist/installer/targets/copilot-cli.js.map +1 -0
  224. package/dist/installer/targets/copilot-jetbrains.d.ts +42 -0
  225. package/dist/installer/targets/copilot-jetbrains.d.ts.map +1 -0
  226. package/dist/installer/targets/copilot-jetbrains.js +238 -0
  227. package/dist/installer/targets/copilot-jetbrains.js.map +1 -0
  228. package/dist/installer/targets/copilot-vscode.d.ts +47 -0
  229. package/dist/installer/targets/copilot-vscode.d.ts.map +1 -0
  230. package/dist/installer/targets/copilot-vscode.js +219 -0
  231. package/dist/installer/targets/copilot-vscode.js.map +1 -0
  232. package/dist/installer/targets/cursor.d.ts +35 -0
  233. package/dist/installer/targets/cursor.d.ts.map +1 -0
  234. package/dist/installer/targets/cursor.js +254 -0
  235. package/dist/installer/targets/cursor.js.map +1 -0
  236. package/dist/installer/targets/gemini.d.ts +26 -0
  237. package/dist/installer/targets/gemini.d.ts.map +1 -0
  238. package/dist/installer/targets/gemini.js +165 -0
  239. package/dist/installer/targets/gemini.js.map +1 -0
  240. package/dist/installer/targets/hermes.d.ts +18 -0
  241. package/dist/installer/targets/hermes.d.ts.map +1 -0
  242. package/dist/installer/targets/hermes.js +359 -0
  243. package/dist/installer/targets/hermes.js.map +1 -0
  244. package/dist/installer/targets/kiro.d.ts +27 -0
  245. package/dist/installer/targets/kiro.d.ts.map +1 -0
  246. package/dist/installer/targets/kiro.js +178 -0
  247. package/dist/installer/targets/kiro.js.map +1 -0
  248. package/dist/installer/targets/opencode.d.ts +38 -0
  249. package/dist/installer/targets/opencode.d.ts.map +1 -0
  250. package/dist/installer/targets/opencode.js +288 -0
  251. package/dist/installer/targets/opencode.js.map +1 -0
  252. package/dist/installer/targets/registry.d.ts +35 -0
  253. package/dist/installer/targets/registry.d.ts.map +1 -0
  254. package/dist/installer/targets/registry.js +101 -0
  255. package/dist/installer/targets/registry.js.map +1 -0
  256. package/dist/installer/targets/shared.d.ts +101 -0
  257. package/dist/installer/targets/shared.d.ts.map +1 -0
  258. package/dist/installer/targets/shared.js +264 -0
  259. package/dist/installer/targets/shared.js.map +1 -0
  260. package/dist/installer/targets/toml.d.ts +53 -0
  261. package/dist/installer/targets/toml.d.ts.map +1 -0
  262. package/dist/installer/targets/toml.js +226 -0
  263. package/dist/installer/targets/toml.js.map +1 -0
  264. package/dist/installer/targets/trae.d.ts +30 -0
  265. package/dist/installer/targets/trae.d.ts.map +1 -0
  266. package/dist/installer/targets/trae.js +164 -0
  267. package/dist/installer/targets/trae.js.map +1 -0
  268. package/dist/installer/targets/types.d.ts +108 -0
  269. package/dist/installer/targets/types.d.ts.map +1 -0
  270. package/dist/installer/targets/types.js +16 -0
  271. package/dist/installer/targets/types.js.map +1 -0
  272. package/dist/installer/targets/workbuddy.d.ts +29 -0
  273. package/dist/installer/targets/workbuddy.d.ts.map +1 -0
  274. package/dist/installer/targets/workbuddy.js +163 -0
  275. package/dist/installer/targets/workbuddy.js.map +1 -0
  276. package/dist/mcp/daemon-manager.d.ts +42 -0
  277. package/dist/mcp/daemon-manager.d.ts.map +1 -0
  278. package/dist/mcp/daemon-manager.js +129 -0
  279. package/dist/mcp/daemon-manager.js.map +1 -0
  280. package/dist/mcp/daemon-paths.d.ts +79 -0
  281. package/dist/mcp/daemon-paths.d.ts.map +1 -0
  282. package/dist/mcp/daemon-paths.js +219 -0
  283. package/dist/mcp/daemon-paths.js.map +1 -0
  284. package/dist/mcp/daemon-registry.d.ts +57 -0
  285. package/dist/mcp/daemon-registry.d.ts.map +1 -0
  286. package/dist/mcp/daemon-registry.js +281 -0
  287. package/dist/mcp/daemon-registry.js.map +1 -0
  288. package/dist/mcp/daemon.d.ts +293 -0
  289. package/dist/mcp/daemon.d.ts.map +1 -0
  290. package/dist/mcp/daemon.js +864 -0
  291. package/dist/mcp/daemon.js.map +1 -0
  292. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  293. package/dist/mcp/dynamic-boundaries.d.ts.map +1 -0
  294. package/dist/mcp/dynamic-boundaries.js +360 -0
  295. package/dist/mcp/dynamic-boundaries.js.map +1 -0
  296. package/dist/mcp/early-ppid.d.ts +26 -0
  297. package/dist/mcp/early-ppid.d.ts.map +1 -0
  298. package/dist/mcp/early-ppid.js +29 -0
  299. package/dist/mcp/early-ppid.js.map +1 -0
  300. package/dist/mcp/engine.d.ts +125 -0
  301. package/dist/mcp/engine.d.ts.map +1 -0
  302. package/dist/mcp/engine.js +392 -0
  303. package/dist/mcp/engine.js.map +1 -0
  304. package/dist/mcp/explore-dedup.d.ts +137 -0
  305. package/dist/mcp/explore-dedup.d.ts.map +1 -0
  306. package/dist/mcp/explore-dedup.js +236 -0
  307. package/dist/mcp/explore-dedup.js.map +1 -0
  308. package/dist/mcp/explore-diagnostics.d.ts +289 -0
  309. package/dist/mcp/explore-diagnostics.d.ts.map +1 -0
  310. package/dist/mcp/explore-diagnostics.js +558 -0
  311. package/dist/mcp/explore-diagnostics.js.map +1 -0
  312. package/dist/mcp/explore-session-state.d.ts +217 -0
  313. package/dist/mcp/explore-session-state.d.ts.map +1 -0
  314. package/dist/mcp/explore-session-state.js +322 -0
  315. package/dist/mcp/explore-session-state.js.map +1 -0
  316. package/dist/mcp/index.d.ts +137 -0
  317. package/dist/mcp/index.d.ts.map +1 -0
  318. package/dist/mcp/index.js +567 -0
  319. package/dist/mcp/index.js.map +1 -0
  320. package/dist/mcp/liveness-watchdog.d.ts +35 -0
  321. package/dist/mcp/liveness-watchdog.d.ts.map +1 -0
  322. package/dist/mcp/liveness-watchdog.js +269 -0
  323. package/dist/mcp/liveness-watchdog.js.map +1 -0
  324. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  325. package/dist/mcp/ppid-watchdog.d.ts.map +1 -0
  326. package/dist/mcp/ppid-watchdog.js +64 -0
  327. package/dist/mcp/ppid-watchdog.js.map +1 -0
  328. package/dist/mcp/proxy.d.ts +87 -0
  329. package/dist/mcp/proxy.d.ts.map +1 -0
  330. package/dist/mcp/proxy.js +672 -0
  331. package/dist/mcp/proxy.js.map +1 -0
  332. package/dist/mcp/query-pool.d.ts +108 -0
  333. package/dist/mcp/query-pool.d.ts.map +1 -0
  334. package/dist/mcp/query-pool.js +315 -0
  335. package/dist/mcp/query-pool.js.map +1 -0
  336. package/dist/mcp/query-worker.d.ts +24 -0
  337. package/dist/mcp/query-worker.d.ts.map +1 -0
  338. package/dist/mcp/query-worker.js +87 -0
  339. package/dist/mcp/query-worker.js.map +1 -0
  340. package/dist/mcp/server-instructions.d.ts +34 -0
  341. package/dist/mcp/server-instructions.d.ts.map +1 -0
  342. package/dist/mcp/server-instructions.js +111 -0
  343. package/dist/mcp/server-instructions.js.map +1 -0
  344. package/dist/mcp/session.d.ts +109 -0
  345. package/dist/mcp/session.d.ts.map +1 -0
  346. package/dist/mcp/session.js +380 -0
  347. package/dist/mcp/session.js.map +1 -0
  348. package/dist/mcp/startup-handshake.d.ts +44 -0
  349. package/dist/mcp/startup-handshake.d.ts.map +1 -0
  350. package/dist/mcp/startup-handshake.js +73 -0
  351. package/dist/mcp/startup-handshake.js.map +1 -0
  352. package/dist/mcp/stdin-teardown.d.ts +27 -0
  353. package/dist/mcp/stdin-teardown.d.ts.map +1 -0
  354. package/dist/mcp/stdin-teardown.js +49 -0
  355. package/dist/mcp/stdin-teardown.js.map +1 -0
  356. package/dist/mcp/tools.d.ts +877 -0
  357. package/dist/mcp/tools.d.ts.map +1 -0
  358. package/dist/mcp/tools.js +6371 -0
  359. package/dist/mcp/tools.js.map +1 -0
  360. package/dist/mcp/transport.d.ts +188 -0
  361. package/dist/mcp/transport.d.ts.map +1 -0
  362. package/dist/mcp/transport.js +377 -0
  363. package/dist/mcp/transport.js.map +1 -0
  364. package/dist/mcp/version.d.ts +19 -0
  365. package/dist/mcp/version.d.ts.map +1 -0
  366. package/dist/mcp/version.js +71 -0
  367. package/dist/mcp/version.js.map +1 -0
  368. package/dist/project-config.d.ts +158 -0
  369. package/dist/project-config.d.ts.map +1 -0
  370. package/dist/project-config.js +489 -0
  371. package/dist/project-config.js.map +1 -0
  372. package/dist/resolution/c-fnptr-synthesizer.d.ts +6 -0
  373. package/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -0
  374. package/dist/resolution/c-fnptr-synthesizer.js +1506 -0
  375. package/dist/resolution/c-fnptr-synthesizer.js.map +1 -0
  376. package/dist/resolution/callback-synthesizer.d.ts +59 -0
  377. package/dist/resolution/callback-synthesizer.d.ts.map +1 -0
  378. package/dist/resolution/callback-synthesizer.js +4066 -0
  379. package/dist/resolution/callback-synthesizer.js.map +1 -0
  380. package/dist/resolution/cooperative-yield.d.ts +40 -0
  381. package/dist/resolution/cooperative-yield.d.ts.map +1 -0
  382. package/dist/resolution/cooperative-yield.js +44 -0
  383. package/dist/resolution/cooperative-yield.js.map +1 -0
  384. package/dist/resolution/expo-router-synthesizer.d.ts +32 -0
  385. package/dist/resolution/expo-router-synthesizer.d.ts.map +1 -0
  386. package/dist/resolution/expo-router-synthesizer.js +189 -0
  387. package/dist/resolution/expo-router-synthesizer.js.map +1 -0
  388. package/dist/resolution/frameworks/astro.d.ts +9 -0
  389. package/dist/resolution/frameworks/astro.d.ts.map +1 -0
  390. package/dist/resolution/frameworks/astro.js +169 -0
  391. package/dist/resolution/frameworks/astro.js.map +1 -0
  392. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  393. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  394. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  395. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  396. package/dist/resolution/frameworks/cics.d.ts +20 -0
  397. package/dist/resolution/frameworks/cics.d.ts.map +1 -0
  398. package/dist/resolution/frameworks/cics.js +90 -0
  399. package/dist/resolution/frameworks/cics.js.map +1 -0
  400. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  401. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  402. package/dist/resolution/frameworks/csharp.js +335 -0
  403. package/dist/resolution/frameworks/csharp.js.map +1 -0
  404. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  405. package/dist/resolution/frameworks/drupal.d.ts.map +1 -0
  406. package/dist/resolution/frameworks/drupal.js +367 -0
  407. package/dist/resolution/frameworks/drupal.js.map +1 -0
  408. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  409. package/dist/resolution/frameworks/expo-modules.d.ts.map +1 -0
  410. package/dist/resolution/frameworks/expo-modules.js +148 -0
  411. package/dist/resolution/frameworks/expo-modules.js.map +1 -0
  412. package/dist/resolution/frameworks/expo-router.d.ts +189 -0
  413. package/dist/resolution/frameworks/expo-router.d.ts.map +1 -0
  414. package/dist/resolution/frameworks/expo-router.js +785 -0
  415. package/dist/resolution/frameworks/expo-router.js.map +1 -0
  416. package/dist/resolution/frameworks/express.d.ts +8 -0
  417. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  418. package/dist/resolution/frameworks/express.js +540 -0
  419. package/dist/resolution/frameworks/express.js.map +1 -0
  420. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  421. package/dist/resolution/frameworks/fabric.d.ts.map +1 -0
  422. package/dist/resolution/frameworks/fabric.js +354 -0
  423. package/dist/resolution/frameworks/fabric.js.map +1 -0
  424. package/dist/resolution/frameworks/go.d.ts +8 -0
  425. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  426. package/dist/resolution/frameworks/go.js +184 -0
  427. package/dist/resolution/frameworks/go.js.map +1 -0
  428. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  429. package/dist/resolution/frameworks/goframe.d.ts.map +1 -0
  430. package/dist/resolution/frameworks/goframe.js +112 -0
  431. package/dist/resolution/frameworks/goframe.js.map +1 -0
  432. package/dist/resolution/frameworks/index.d.ts +30 -0
  433. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  434. package/dist/resolution/frameworks/index.js +72 -0
  435. package/dist/resolution/frameworks/index.js.map +1 -0
  436. package/dist/resolution/frameworks/java.d.ts +8 -0
  437. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  438. package/dist/resolution/frameworks/java.js +517 -0
  439. package/dist/resolution/frameworks/java.js.map +1 -0
  440. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  441. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  442. package/dist/resolution/frameworks/laravel.js +257 -0
  443. package/dist/resolution/frameworks/laravel.js.map +1 -0
  444. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  445. package/dist/resolution/frameworks/nestjs.d.ts.map +1 -0
  446. package/dist/resolution/frameworks/nestjs.js +690 -0
  447. package/dist/resolution/frameworks/nestjs.js.map +1 -0
  448. package/dist/resolution/frameworks/nextjs.d.ts +76 -0
  449. package/dist/resolution/frameworks/nextjs.d.ts.map +1 -0
  450. package/dist/resolution/frameworks/nextjs.js +328 -0
  451. package/dist/resolution/frameworks/nextjs.js.map +1 -0
  452. package/dist/resolution/frameworks/object-literal.d.ts +32 -0
  453. package/dist/resolution/frameworks/object-literal.d.ts.map +1 -0
  454. package/dist/resolution/frameworks/object-literal.js +139 -0
  455. package/dist/resolution/frameworks/object-literal.js.map +1 -0
  456. package/dist/resolution/frameworks/package-deps.d.ts +14 -0
  457. package/dist/resolution/frameworks/package-deps.d.ts.map +1 -0
  458. package/dist/resolution/frameworks/package-deps.js +78 -0
  459. package/dist/resolution/frameworks/package-deps.js.map +1 -0
  460. package/dist/resolution/frameworks/play.d.ts +19 -0
  461. package/dist/resolution/frameworks/play.d.ts.map +1 -0
  462. package/dist/resolution/frameworks/play.js +111 -0
  463. package/dist/resolution/frameworks/play.js.map +1 -0
  464. package/dist/resolution/frameworks/python.d.ts +10 -0
  465. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  466. package/dist/resolution/frameworks/python.js +566 -0
  467. package/dist/resolution/frameworks/python.js.map +1 -0
  468. package/dist/resolution/frameworks/react-native.d.ts +29 -0
  469. package/dist/resolution/frameworks/react-native.d.ts.map +1 -0
  470. package/dist/resolution/frameworks/react-native.js +549 -0
  471. package/dist/resolution/frameworks/react-native.js.map +1 -0
  472. package/dist/resolution/frameworks/react-router.d.ts +46 -0
  473. package/dist/resolution/frameworks/react-router.d.ts.map +1 -0
  474. package/dist/resolution/frameworks/react-router.js +187 -0
  475. package/dist/resolution/frameworks/react-router.js.map +1 -0
  476. package/dist/resolution/frameworks/react.d.ts +9 -0
  477. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  478. package/dist/resolution/frameworks/react.js +257 -0
  479. package/dist/resolution/frameworks/react.js.map +1 -0
  480. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  481. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  482. package/dist/resolution/frameworks/ruby.js +302 -0
  483. package/dist/resolution/frameworks/ruby.js.map +1 -0
  484. package/dist/resolution/frameworks/rust.d.ts +8 -0
  485. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  486. package/dist/resolution/frameworks/rust.js +304 -0
  487. package/dist/resolution/frameworks/rust.js.map +1 -0
  488. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  489. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  490. package/dist/resolution/frameworks/svelte.js +258 -0
  491. package/dist/resolution/frameworks/svelte.js.map +1 -0
  492. package/dist/resolution/frameworks/sveltekit-router.d.ts +36 -0
  493. package/dist/resolution/frameworks/sveltekit-router.d.ts.map +1 -0
  494. package/dist/resolution/frameworks/sveltekit-router.js +156 -0
  495. package/dist/resolution/frameworks/sveltekit-router.js.map +1 -0
  496. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  497. package/dist/resolution/frameworks/swift-objc.d.ts.map +1 -0
  498. package/dist/resolution/frameworks/swift-objc.js +252 -0
  499. package/dist/resolution/frameworks/swift-objc.js.map +1 -0
  500. package/dist/resolution/frameworks/swift.d.ts +10 -0
  501. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  502. package/dist/resolution/frameworks/swift.js +410 -0
  503. package/dist/resolution/frameworks/swift.js.map +1 -0
  504. package/dist/resolution/frameworks/tanstack-router.d.ts +84 -0
  505. package/dist/resolution/frameworks/tanstack-router.d.ts.map +1 -0
  506. package/dist/resolution/frameworks/tanstack-router.js +437 -0
  507. package/dist/resolution/frameworks/tanstack-router.js.map +1 -0
  508. package/dist/resolution/frameworks/terraform.d.ts +38 -0
  509. package/dist/resolution/frameworks/terraform.d.ts.map +1 -0
  510. package/dist/resolution/frameworks/terraform.js +277 -0
  511. package/dist/resolution/frameworks/terraform.js.map +1 -0
  512. package/dist/resolution/frameworks/vue-router.d.ts +82 -0
  513. package/dist/resolution/frameworks/vue-router.d.ts.map +1 -0
  514. package/dist/resolution/frameworks/vue-router.js +377 -0
  515. package/dist/resolution/frameworks/vue-router.js.map +1 -0
  516. package/dist/resolution/frameworks/vue.d.ts +9 -0
  517. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  518. package/dist/resolution/frameworks/vue.js +303 -0
  519. package/dist/resolution/frameworks/vue.js.map +1 -0
  520. package/dist/resolution/go-module.d.ts +26 -0
  521. package/dist/resolution/go-module.d.ts.map +1 -0
  522. package/dist/resolution/go-module.js +78 -0
  523. package/dist/resolution/go-module.js.map +1 -0
  524. package/dist/resolution/goframe-synthesizer.d.ts +29 -0
  525. package/dist/resolution/goframe-synthesizer.d.ts.map +1 -0
  526. package/dist/resolution/goframe-synthesizer.js +163 -0
  527. package/dist/resolution/goframe-synthesizer.js.map +1 -0
  528. package/dist/resolution/import-resolver.d.ts +84 -0
  529. package/dist/resolution/import-resolver.d.ts.map +1 -0
  530. package/dist/resolution/import-resolver.js +2240 -0
  531. package/dist/resolution/import-resolver.js.map +1 -0
  532. package/dist/resolution/index.d.ts +343 -0
  533. package/dist/resolution/index.d.ts.map +1 -0
  534. package/dist/resolution/index.js +2352 -0
  535. package/dist/resolution/index.js.map +1 -0
  536. package/dist/resolution/lru-cache.d.ts +24 -0
  537. package/dist/resolution/lru-cache.d.ts.map +1 -0
  538. package/dist/resolution/lru-cache.js +62 -0
  539. package/dist/resolution/lru-cache.js.map +1 -0
  540. package/dist/resolution/memory-budget.d.ts +48 -0
  541. package/dist/resolution/memory-budget.d.ts.map +1 -0
  542. package/dist/resolution/memory-budget.js +162 -0
  543. package/dist/resolution/memory-budget.js.map +1 -0
  544. package/dist/resolution/name-matcher.d.ts +153 -0
  545. package/dist/resolution/name-matcher.d.ts.map +1 -0
  546. package/dist/resolution/name-matcher.js +2412 -0
  547. package/dist/resolution/name-matcher.js.map +1 -0
  548. package/dist/resolution/next-router-synthesizer.d.ts +27 -0
  549. package/dist/resolution/next-router-synthesizer.d.ts.map +1 -0
  550. package/dist/resolution/next-router-synthesizer.js +113 -0
  551. package/dist/resolution/next-router-synthesizer.js.map +1 -0
  552. package/dist/resolution/path-aliases.d.ts +70 -0
  553. package/dist/resolution/path-aliases.d.ts.map +1 -0
  554. package/dist/resolution/path-aliases.js +346 -0
  555. package/dist/resolution/path-aliases.js.map +1 -0
  556. package/dist/resolution/react-router-synthesizer.d.ts +33 -0
  557. package/dist/resolution/react-router-synthesizer.d.ts.map +1 -0
  558. package/dist/resolution/react-router-synthesizer.js +126 -0
  559. package/dist/resolution/react-router-synthesizer.js.map +1 -0
  560. package/dist/resolution/resolver-pool.d.ts +106 -0
  561. package/dist/resolution/resolver-pool.d.ts.map +1 -0
  562. package/dist/resolution/resolver-pool.js +344 -0
  563. package/dist/resolution/resolver-pool.js.map +1 -0
  564. package/dist/resolution/resolver-worker.d.ts +17 -0
  565. package/dist/resolution/resolver-worker.d.ts.map +1 -0
  566. package/dist/resolution/resolver-worker.js +141 -0
  567. package/dist/resolution/resolver-worker.js.map +1 -0
  568. package/dist/resolution/strip-comments.d.ts +27 -0
  569. package/dist/resolution/strip-comments.d.ts.map +1 -0
  570. package/dist/resolution/strip-comments.js +492 -0
  571. package/dist/resolution/strip-comments.js.map +1 -0
  572. package/dist/resolution/sveltekit-synthesizer.d.ts +58 -0
  573. package/dist/resolution/sveltekit-synthesizer.d.ts.map +1 -0
  574. package/dist/resolution/sveltekit-synthesizer.js +173 -0
  575. package/dist/resolution/sveltekit-synthesizer.js.map +1 -0
  576. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  577. package/dist/resolution/swift-objc-bridge.d.ts.map +1 -0
  578. package/dist/resolution/swift-objc-bridge.js +256 -0
  579. package/dist/resolution/swift-objc-bridge.js.map +1 -0
  580. package/dist/resolution/synth-utils.d.ts +26 -0
  581. package/dist/resolution/synth-utils.d.ts.map +1 -0
  582. package/dist/resolution/synth-utils.js +75 -0
  583. package/dist/resolution/synth-utils.js.map +1 -0
  584. package/dist/resolution/tanstack-router-synthesizer.d.ts +31 -0
  585. package/dist/resolution/tanstack-router-synthesizer.d.ts.map +1 -0
  586. package/dist/resolution/tanstack-router-synthesizer.js +114 -0
  587. package/dist/resolution/tanstack-router-synthesizer.js.map +1 -0
  588. package/dist/resolution/tier-synthesizer.d.ts +48 -0
  589. package/dist/resolution/tier-synthesizer.d.ts.map +1 -0
  590. package/dist/resolution/tier-synthesizer.js +907 -0
  591. package/dist/resolution/tier-synthesizer.js.map +1 -0
  592. package/dist/resolution/types.d.ts +290 -0
  593. package/dist/resolution/types.d.ts.map +1 -0
  594. package/dist/resolution/types.js +8 -0
  595. package/dist/resolution/types.js.map +1 -0
  596. package/dist/resolution/vue-router-synthesizer.d.ts +30 -0
  597. package/dist/resolution/vue-router-synthesizer.d.ts.map +1 -0
  598. package/dist/resolution/vue-router-synthesizer.js +115 -0
  599. package/dist/resolution/vue-router-synthesizer.js.map +1 -0
  600. package/dist/resolution/workspace-packages.d.ts +58 -0
  601. package/dist/resolution/workspace-packages.d.ts.map +1 -0
  602. package/dist/resolution/workspace-packages.js +346 -0
  603. package/dist/resolution/workspace-packages.js.map +1 -0
  604. package/dist/search/identifier-segments.d.ts +70 -0
  605. package/dist/search/identifier-segments.d.ts.map +1 -0
  606. package/dist/search/identifier-segments.js +205 -0
  607. package/dist/search/identifier-segments.js.map +1 -0
  608. package/dist/search/query-parser.d.ts +57 -0
  609. package/dist/search/query-parser.d.ts.map +1 -0
  610. package/dist/search/query-parser.js +177 -0
  611. package/dist/search/query-parser.js.map +1 -0
  612. package/dist/search/query-paths.d.ts +57 -0
  613. package/dist/search/query-paths.d.ts.map +1 -0
  614. package/dist/search/query-paths.js +298 -0
  615. package/dist/search/query-paths.js.map +1 -0
  616. package/dist/search/query-utils.d.ts +102 -0
  617. package/dist/search/query-utils.d.ts.map +1 -0
  618. package/dist/search/query-utils.js +487 -0
  619. package/dist/search/query-utils.js.map +1 -0
  620. package/dist/sync/git-hooks.d.ts +45 -0
  621. package/dist/sync/git-hooks.d.ts.map +1 -0
  622. package/dist/sync/git-hooks.js +227 -0
  623. package/dist/sync/git-hooks.js.map +1 -0
  624. package/dist/sync/index.d.ts +19 -0
  625. package/dist/sync/index.d.ts.map +1 -0
  626. package/dist/sync/index.js +35 -0
  627. package/dist/sync/index.js.map +1 -0
  628. package/dist/sync/watch-policy.d.ts +48 -0
  629. package/dist/sync/watch-policy.d.ts.map +1 -0
  630. package/dist/sync/watch-policy.js +124 -0
  631. package/dist/sync/watch-policy.js.map +1 -0
  632. package/dist/sync/watcher.d.ts +401 -0
  633. package/dist/sync/watcher.d.ts.map +1 -0
  634. package/dist/sync/watcher.js +967 -0
  635. package/dist/sync/watcher.js.map +1 -0
  636. package/dist/sync/worktree.d.ts +63 -0
  637. package/dist/sync/worktree.d.ts.map +1 -0
  638. package/dist/sync/worktree.js +182 -0
  639. package/dist/sync/worktree.js.map +1 -0
  640. package/dist/telemetry/index.d.ts +143 -0
  641. package/dist/telemetry/index.d.ts.map +1 -0
  642. package/dist/telemetry/index.js +541 -0
  643. package/dist/telemetry/index.js.map +1 -0
  644. package/dist/types.d.ts +486 -0
  645. package/dist/types.d.ts.map +1 -0
  646. package/dist/types.js +118 -0
  647. package/dist/types.js.map +1 -0
  648. package/dist/ui/color.d.ts +21 -0
  649. package/dist/ui/color.d.ts.map +1 -0
  650. package/dist/ui/color.js +42 -0
  651. package/dist/ui/color.js.map +1 -0
  652. package/dist/ui/glyphs.d.ts +67 -0
  653. package/dist/ui/glyphs.d.ts.map +1 -0
  654. package/dist/ui/glyphs.js +125 -0
  655. package/dist/ui/glyphs.js.map +1 -0
  656. package/dist/ui/shimmer-progress.d.ts +11 -0
  657. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  658. package/dist/ui/shimmer-progress.js +164 -0
  659. package/dist/ui/shimmer-progress.js.map +1 -0
  660. package/dist/ui/shimmer-worker.d.ts +2 -0
  661. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  662. package/dist/ui/shimmer-worker.js +126 -0
  663. package/dist/ui/shimmer-worker.js.map +1 -0
  664. package/dist/ui/types.d.ts +15 -0
  665. package/dist/ui/types.d.ts.map +1 -0
  666. package/dist/ui/types.js +3 -0
  667. package/dist/ui/types.js.map +1 -0
  668. package/dist/ui-server/api/deadcode.d.ts +84 -0
  669. package/dist/ui-server/api/deadcode.d.ts.map +1 -0
  670. package/dist/ui-server/api/deadcode.js +136 -0
  671. package/dist/ui-server/api/deadcode.js.map +1 -0
  672. package/dist/ui-server/api/effects.d.ts +87 -0
  673. package/dist/ui-server/api/effects.d.ts.map +1 -0
  674. package/dist/ui-server/api/effects.js +499 -0
  675. package/dist/ui-server/api/effects.js.map +1 -0
  676. package/dist/ui-server/api/entrypoints.d.ts +86 -0
  677. package/dist/ui-server/api/entrypoints.d.ts.map +1 -0
  678. package/dist/ui-server/api/entrypoints.js +279 -0
  679. package/dist/ui-server/api/entrypoints.js.map +1 -0
  680. package/dist/ui-server/api/events.d.ts +183 -0
  681. package/dist/ui-server/api/events.d.ts.map +1 -0
  682. package/dist/ui-server/api/events.js +430 -0
  683. package/dist/ui-server/api/events.js.map +1 -0
  684. package/dist/ui-server/api/file.d.ts +66 -0
  685. package/dist/ui-server/api/file.d.ts.map +1 -0
  686. package/dist/ui-server/api/file.js +222 -0
  687. package/dist/ui-server/api/file.js.map +1 -0
  688. package/dist/ui-server/api/filecode.d.ts +126 -0
  689. package/dist/ui-server/api/filecode.d.ts.map +1 -0
  690. package/dist/ui-server/api/filecode.js +205 -0
  691. package/dist/ui-server/api/filecode.js.map +1 -0
  692. package/dist/ui-server/api/flow.d.ts +226 -0
  693. package/dist/ui-server/api/flow.d.ts.map +1 -0
  694. package/dist/ui-server/api/flow.js +611 -0
  695. package/dist/ui-server/api/flow.js.map +1 -0
  696. package/dist/ui-server/api/hierarchy.d.ts +81 -0
  697. package/dist/ui-server/api/hierarchy.d.ts.map +1 -0
  698. package/dist/ui-server/api/hierarchy.js +92 -0
  699. package/dist/ui-server/api/hierarchy.js.map +1 -0
  700. package/dist/ui-server/api/index.d.ts +90 -0
  701. package/dist/ui-server/api/index.d.ts.map +1 -0
  702. package/dist/ui-server/api/index.js +332 -0
  703. package/dist/ui-server/api/index.js.map +1 -0
  704. package/dist/ui-server/api/map.d.ts +187 -0
  705. package/dist/ui-server/api/map.d.ts.map +1 -0
  706. package/dist/ui-server/api/map.js +498 -0
  707. package/dist/ui-server/api/map.js.map +1 -0
  708. package/dist/ui-server/api/node.d.ts +81 -0
  709. package/dist/ui-server/api/node.d.ts.map +1 -0
  710. package/dist/ui-server/api/node.js +388 -0
  711. package/dist/ui-server/api/node.js.map +1 -0
  712. package/dist/ui-server/api/nodes.d.ts +25 -0
  713. package/dist/ui-server/api/nodes.d.ts.map +1 -0
  714. package/dist/ui-server/api/nodes.js +45 -0
  715. package/dist/ui-server/api/nodes.js.map +1 -0
  716. package/dist/ui-server/api/program.d.ts +139 -0
  717. package/dist/ui-server/api/program.d.ts.map +1 -0
  718. package/dist/ui-server/api/program.js +315 -0
  719. package/dist/ui-server/api/program.js.map +1 -0
  720. package/dist/ui-server/api/respond.d.ts +76 -0
  721. package/dist/ui-server/api/respond.d.ts.map +1 -0
  722. package/dist/ui-server/api/respond.js +186 -0
  723. package/dist/ui-server/api/respond.js.map +1 -0
  724. package/dist/ui-server/api/route-roots.d.ts +39 -0
  725. package/dist/ui-server/api/route-roots.d.ts.map +1 -0
  726. package/dist/ui-server/api/route-roots.js +96 -0
  727. package/dist/ui-server/api/route-roots.js.map +1 -0
  728. package/dist/ui-server/api/routes.d.ts +59 -0
  729. package/dist/ui-server/api/routes.d.ts.map +1 -0
  730. package/dist/ui-server/api/routes.js +112 -0
  731. package/dist/ui-server/api/routes.js.map +1 -0
  732. package/dist/ui-server/api/screens.d.ts +117 -0
  733. package/dist/ui-server/api/screens.d.ts.map +1 -0
  734. package/dist/ui-server/api/screens.js +611 -0
  735. package/dist/ui-server/api/screens.js.map +1 -0
  736. package/dist/ui-server/api/search.d.ts +29 -0
  737. package/dist/ui-server/api/search.d.ts.map +1 -0
  738. package/dist/ui-server/api/search.js +232 -0
  739. package/dist/ui-server/api/search.js.map +1 -0
  740. package/dist/ui-server/api/session.d.ts +52 -0
  741. package/dist/ui-server/api/session.d.ts.map +1 -0
  742. package/dist/ui-server/api/session.js +196 -0
  743. package/dist/ui-server/api/session.js.map +1 -0
  744. package/dist/ui-server/api/source.d.ts +200 -0
  745. package/dist/ui-server/api/source.d.ts.map +1 -0
  746. package/dist/ui-server/api/source.js +419 -0
  747. package/dist/ui-server/api/source.js.map +1 -0
  748. package/dist/ui-server/api/stats.d.ts +27 -0
  749. package/dist/ui-server/api/stats.d.ts.map +1 -0
  750. package/dist/ui-server/api/stats.js +164 -0
  751. package/dist/ui-server/api/stats.js.map +1 -0
  752. package/dist/ui-server/api/steps.d.ts +274 -0
  753. package/dist/ui-server/api/steps.d.ts.map +1 -0
  754. package/dist/ui-server/api/steps.js +1446 -0
  755. package/dist/ui-server/api/steps.js.map +1 -0
  756. package/dist/ui-server/api/trail-store.d.ts +142 -0
  757. package/dist/ui-server/api/trail-store.d.ts.map +1 -0
  758. package/dist/ui-server/api/trail-store.js +323 -0
  759. package/dist/ui-server/api/trail-store.js.map +1 -0
  760. package/dist/ui-server/api/trails.d.ts +163 -0
  761. package/dist/ui-server/api/trails.d.ts.map +1 -0
  762. package/dist/ui-server/api/trails.js +369 -0
  763. package/dist/ui-server/api/trails.js.map +1 -0
  764. package/dist/ui-server/api/when.d.ts +125 -0
  765. package/dist/ui-server/api/when.d.ts.map +1 -0
  766. package/dist/ui-server/api/when.js +251 -0
  767. package/dist/ui-server/api/when.js.map +1 -0
  768. package/dist/ui-server/api/wire.d.ts +179 -0
  769. package/dist/ui-server/api/wire.d.ts.map +1 -0
  770. package/dist/ui-server/api/wire.js +231 -0
  771. package/dist/ui-server/api/wire.js.map +1 -0
  772. package/dist/ui-server/assets.d.ts +40 -0
  773. package/dist/ui-server/assets.d.ts.map +1 -0
  774. package/dist/ui-server/assets.js +110 -0
  775. package/dist/ui-server/assets.js.map +1 -0
  776. package/dist/ui-server/constants.d.ts +32 -0
  777. package/dist/ui-server/constants.d.ts.map +1 -0
  778. package/dist/ui-server/constants.js +35 -0
  779. package/dist/ui-server/constants.js.map +1 -0
  780. package/dist/ui-server/highlight/index.d.ts +113 -0
  781. package/dist/ui-server/highlight/index.d.ts.map +1 -0
  782. package/dist/ui-server/highlight/index.js +307 -0
  783. package/dist/ui-server/highlight/index.js.map +1 -0
  784. package/dist/ui-server/highlight/languages.d.ts +36 -0
  785. package/dist/ui-server/highlight/languages.d.ts.map +1 -0
  786. package/dist/ui-server/highlight/languages.js +50 -0
  787. package/dist/ui-server/highlight/languages.js.map +1 -0
  788. package/dist/ui-server/index.d.ts +92 -0
  789. package/dist/ui-server/index.d.ts.map +1 -0
  790. package/dist/ui-server/index.js +399 -0
  791. package/dist/ui-server/index.js.map +1 -0
  792. package/dist/ui-server/open-browser.d.ts +31 -0
  793. package/dist/ui-server/open-browser.d.ts.map +1 -0
  794. package/dist/ui-server/open-browser.js +79 -0
  795. package/dist/ui-server/open-browser.js.map +1 -0
  796. package/dist/ui-server/security.d.ts +127 -0
  797. package/dist/ui-server/security.d.ts.map +1 -0
  798. package/dist/ui-server/security.js +332 -0
  799. package/dist/ui-server/security.js.map +1 -0
  800. package/dist/ui-server/static.d.ts +45 -0
  801. package/dist/ui-server/static.d.ts.map +1 -0
  802. package/dist/ui-server/static.js +165 -0
  803. package/dist/ui-server/static.js.map +1 -0
  804. package/dist/upgrade/index.d.ts +177 -0
  805. package/dist/upgrade/index.d.ts.map +1 -0
  806. package/dist/upgrade/index.js +665 -0
  807. package/dist/upgrade/index.js.map +1 -0
  808. package/dist/upgrade/remove-binary.d.ts +87 -0
  809. package/dist/upgrade/remove-binary.d.ts.map +1 -0
  810. package/dist/upgrade/remove-binary.js +289 -0
  811. package/dist/upgrade/remove-binary.js.map +1 -0
  812. package/dist/upgrade/update-check.d.ts +92 -0
  813. package/dist/upgrade/update-check.d.ts.map +1 -0
  814. package/dist/upgrade/update-check.js +258 -0
  815. package/dist/upgrade/update-check.js.map +1 -0
  816. package/dist/utils.d.ts +224 -0
  817. package/dist/utils.d.ts.map +1 -0
  818. package/dist/utils.js +583 -0
  819. package/dist/utils.js.map +1 -0
  820. package/dist/viewer/assets/archivo-latin-ext-wght-normal-C4zznr8T.woff2 +0 -0
  821. package/dist/viewer/assets/archivo-latin-wght-normal-E0tuGl4L.woff2 +0 -0
  822. package/dist/viewer/assets/archivo-vietnamese-wght-normal-XAtsl5Q_.woff2 +0 -0
  823. package/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-2syK4fUT.woff +0 -0
  824. package/dist/viewer/assets/ibm-plex-mono-cyrillic-400-italic-CBJ8pzag.woff2 +0 -0
  825. package/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  826. package/dist/viewer/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  827. package/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  828. package/dist/viewer/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  829. package/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  830. package/dist/viewer/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  831. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-B4oTjJdl.woff +0 -0
  832. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-italic-CBjNughH.woff2 +0 -0
  833. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  834. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  835. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  836. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  837. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  838. package/dist/viewer/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  839. package/dist/viewer/assets/ibm-plex-mono-latin-400-italic-66oory27.woff +0 -0
  840. package/dist/viewer/assets/ibm-plex-mono-latin-400-italic-BqAiT5Ww.woff2 +0 -0
  841. package/dist/viewer/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  842. package/dist/viewer/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  843. package/dist/viewer/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  844. package/dist/viewer/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  845. package/dist/viewer/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  846. package/dist/viewer/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  847. package/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-B7_fu1kp.woff2 +0 -0
  848. package/dist/viewer/assets/ibm-plex-mono-latin-ext-400-italic-Bg0ZHwF4.woff +0 -0
  849. package/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  850. package/dist/viewer/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  851. package/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  852. package/dist/viewer/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  853. package/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  854. package/dist/viewer/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  855. package/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-D6eaYXMU.woff +0 -0
  856. package/dist/viewer/assets/ibm-plex-mono-vietnamese-400-italic-DRuN92E5.woff2 +0 -0
  857. package/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  858. package/dist/viewer/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  859. package/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  860. package/dist/viewer/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  861. package/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  862. package/dist/viewer/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  863. package/dist/viewer/assets/index-2IPslW5t.js +13 -0
  864. package/dist/viewer/assets/index-DSwi2Seu.css +1 -0
  865. package/dist/viewer/index.html +16 -0
  866. package/package.json +67 -0
@@ -0,0 +1,3191 @@
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 = exports.DEPRIORITIZED_NAME_BONUS_SCALE = 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
+ * Files that should not be candidates for "dominant file" detection: test/spec
16
+ * files and tool-generated files. Generated files (`*.pb.go`, `*.pulsar.go`,
17
+ * mock outputs, …) often have huge in-file edge counts that dwarf the real
18
+ * source — etcd's `rpc.pb.go` has 4× the in-file edges of `server.go`.
19
+ *
20
+ * Path patterns plus, when the caller passes the indexed set, files whose
21
+ * HEADER declares them generated — a `payroll.go` full of generated CRUD has
22
+ * exactly the same edge-density problem as `rpc.pb.go` and nothing in its name
23
+ * to catch it (#1500).
24
+ */
25
+ function isLowValueFile(filePath, generated) {
26
+ if (generated?.has(filePath))
27
+ return true;
28
+ const lp = filePath.toLowerCase();
29
+ return (/(?:^|\/)(tests?|__tests?__|spec)\//.test(lp) ||
30
+ /_test\.go$/.test(lp) ||
31
+ /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
32
+ /_test\.py$/.test(lp) ||
33
+ /_spec\.rb$/.test(lp) ||
34
+ /_test\.rb$/.test(lp) ||
35
+ /\.(test|spec)\.[jt]sx?$/.test(lp) ||
36
+ /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
37
+ /(tests?|spec)\.cs$/.test(lp) ||
38
+ /tests?\.swift$/.test(lp) ||
39
+ /_test\.dart$/.test(lp) ||
40
+ (0, generated_detection_1.isGeneratedFile)(filePath));
41
+ }
42
+ const SQLITE_PARAM_CHUNK_SIZE = 500;
43
+ /**
44
+ * How much of the exact-name bonus a `deprioritize`d path keeps (#982). Damped
45
+ * rather than zeroed: a query that genuinely targets that tree must still rank
46
+ * it, the same "discount, don't erase" rule the path penalty follows.
47
+ *
48
+ * Derived rather than picked. `nameMatchBonus`'s prefix arm tops out below
49
+ * `10 + 30 = 40`, and a de-prioritized node also takes the -15 path penalty, so
50
+ * `80 * SCALE - 15 > 40` is what stops a damped WHOLE-QUERY exact match from
51
+ * losing to a mere prefix match. 0.75 clears it (45). Measured on a 62k-node
52
+ * django index: at 0.25 that invariant breaks in practice — `child`, `parent`
53
+ * and `method` lose rank 1 to `children`, `all_parents` and `method_decorator`
54
+ * — while crowd-out removal is almost flat between 0.75 and 0.5 (39 vs 40 of 88
55
+ * peripheral top-10 slots cleared), so a deeper discount buys little and costs
56
+ * the invariant. Pinned by a test.
57
+ */
58
+ exports.DEPRIORITIZED_NAME_BONUS_SCALE = 0.75;
59
+ /**
60
+ * Last segment of a (possibly dotted/qualified) reference name — the part a
61
+ * new symbol's plain node name could match: 'util.greet' → 'greet',
62
+ * 'mod::fn' → 'fn', 'greet' → 'greet'. Written to unresolved_refs.name_tail
63
+ * when a ref is marked failed, so the #1240 retry lookup can match dotted
64
+ * refs against newly-added node names.
65
+ */
66
+ function referenceNameTail(referenceName) {
67
+ // Erlang refs carry a written arity (`f/1`, `mod::fn/2` — #1610); the tail a
68
+ // new symbol's plain name could match is the arity-less function name.
69
+ const base = referenceName.replace(/\/\d{1,3}$/, '') || referenceName;
70
+ const idx = Math.max(base.lastIndexOf('.'), base.lastIndexOf(':'));
71
+ return idx >= 0 ? base.slice(idx + 1) : base;
72
+ }
73
+ /**
74
+ * Convert database row to Node object
75
+ */
76
+ function rowToNode(row) {
77
+ return {
78
+ id: row.id,
79
+ kind: row.kind,
80
+ name: row.name,
81
+ qualifiedName: row.qualified_name,
82
+ filePath: row.file_path,
83
+ language: row.language,
84
+ startLine: row.start_line,
85
+ endLine: row.end_line,
86
+ startColumn: row.start_column,
87
+ endColumn: row.end_column,
88
+ docstring: row.docstring ?? undefined,
89
+ signature: row.signature ?? undefined,
90
+ visibility: row.visibility,
91
+ isExported: row.is_exported === 1,
92
+ isAsync: row.is_async === 1,
93
+ isStatic: row.is_static === 1,
94
+ isAbstract: row.is_abstract === 1,
95
+ decorators: row.decorators ? (0, utils_1.safeJsonParse)(row.decorators, undefined) : undefined,
96
+ typeParameters: row.type_parameters ? (0, utils_1.safeJsonParse)(row.type_parameters, undefined) : undefined,
97
+ returnType: row.return_type ?? undefined,
98
+ updatedAt: row.updated_at,
99
+ };
100
+ }
101
+ /**
102
+ * Convert database row to Edge object
103
+ */
104
+ function rowToEdge(row) {
105
+ return {
106
+ source: row.source,
107
+ target: row.target,
108
+ kind: row.kind,
109
+ metadata: row.metadata ? (0, utils_1.safeJsonParse)(row.metadata, undefined) : undefined,
110
+ line: row.line ?? undefined,
111
+ column: row.col ?? undefined,
112
+ provenance: row.provenance,
113
+ };
114
+ }
115
+ /**
116
+ * Convert database row to FileRecord object
117
+ */
118
+ function rowToFileRecord(row) {
119
+ return {
120
+ path: row.path,
121
+ contentHash: row.content_hash,
122
+ language: row.language,
123
+ size: row.size,
124
+ modifiedAt: row.modified_at,
125
+ indexedAt: row.indexed_at,
126
+ nodeCount: row.node_count,
127
+ errors: row.errors ? (0, utils_1.safeJsonParse)(row.errors, undefined) : undefined,
128
+ generated: row.generated === 1,
129
+ };
130
+ }
131
+ /**
132
+ * Query builder for the knowledge graph database
133
+ */
134
+ class QueryBuilder {
135
+ db;
136
+ // Project-name tokens (go.mod / package.json / repo dir), normalized. A query
137
+ // word matching one is dropped from path-relevance scoring — it names the
138
+ // whole project, not a symbol, so it carries no discriminative signal (#720).
139
+ // Set once by the CodeGraph instance; empty by default (no down-weighting).
140
+ projectNameTokens = new Set();
141
+ isDeprioritizedPath;
142
+ // Node cache for frequently accessed nodes (LRU-style, max 1000 entries)
143
+ nodeCache = new Map();
144
+ maxCacheSize = 1000;
145
+ // Prepared statements (lazily initialized)
146
+ stmts = {};
147
+ // Names whose segments were already written this session — skips re-splitting
148
+ // and re-inserting for the same-named nodes that repeat across files ("get",
149
+ // "render", …). Purely a write-path fast path; INSERT OR IGNORE is the
150
+ // correctness backstop. Bounded so a pathological repo can't grow it forever.
151
+ segmentedNames = new Set();
152
+ static MAX_SEGMENTED_NAMES = 65536;
153
+ // Multi-row INSERT statements, cached per (statement kind × row count). The
154
+ // bulk write path decomposes N rows into a few fixed batch sizes so each
155
+ // size's statement is prepared once and reused — one .run() binds a whole
156
+ // chunk instead of one row, which is where the per-call overhead lives.
157
+ // Row order within and across chunks is the input order, so rowid assignment
158
+ // (and therefore resolution's insertion-order disambiguation) is identical
159
+ // to the one-row-per-run path.
160
+ batchStmts = new Map();
161
+ static BATCH_SIZES = [128, 32, 8, 1];
162
+ /**
163
+ * Run `rows` through a multi-row `INSERT` built as `head + (tuple,)*n`,
164
+ * decomposed greedily into the cached batch sizes. Preserves row order.
165
+ */
166
+ runBatched(kind, head, tuple, rows) {
167
+ if (rows.length === 0)
168
+ return;
169
+ let i = 0;
170
+ for (const size of QueryBuilder.BATCH_SIZES) {
171
+ while (rows.length - i >= size) {
172
+ const key = `${kind}:${size}`;
173
+ let stmt = this.batchStmts.get(key);
174
+ if (!stmt) {
175
+ stmt = this.db.prepare(head + new Array(size).fill(tuple).join(','));
176
+ this.batchStmts.set(key, stmt);
177
+ }
178
+ if (size === 1) {
179
+ stmt.run(...rows[i]);
180
+ }
181
+ else {
182
+ const params = [];
183
+ for (let r = 0; r < size; r++) {
184
+ const row = rows[i + r];
185
+ for (let c = 0; c < row.length; c++)
186
+ params.push(row[c]);
187
+ }
188
+ stmt.run(...params);
189
+ }
190
+ i += size;
191
+ }
192
+ }
193
+ }
194
+ constructor(db) {
195
+ this.db = db;
196
+ }
197
+ /**
198
+ * Swap the underlying connection in place. Used by pool workers'
199
+ * connection recycling (plan §7a.6, writes-under-readers): a long-lived
200
+ * read connection pins WAL checkpoint progress, and the deep WAL that
201
+ * accumulates behind it taxes every main-thread B-tree page operation
202
+ * (deletes measured 42.6s → 118.8s from 0 to 4 attached readers on
203
+ * identical hardware). Workers therefore close and reopen their read-only
204
+ * connection at the pool-idle boundary; everything above the connection —
205
+ * this QueryBuilder, the resolver and its warm caches — survives, and only
206
+ * connection-derived state (prepared statements) resets, re-preparing
207
+ * lazily on next use.
208
+ */
209
+ rebind(db) {
210
+ this.db = db;
211
+ this.stmts = {};
212
+ this.batchStmts.clear();
213
+ }
214
+ /** Set the normalized project-name tokens used to down-weight non-discriminative
215
+ * query words in path scoring (#720). Called once when the project opens. */
216
+ setProjectNameTokens(tokens) {
217
+ this.projectNameTokens = tokens;
218
+ }
219
+ /** The normalized project-name tokens (#720); empty if none were derived. */
220
+ getProjectNameTokens() {
221
+ return this.projectNameTokens;
222
+ }
223
+ /**
224
+ * Set the predicate that marks a path as de-prioritized by the project's
225
+ * `codegraph.json` `deprioritize` patterns (#982). Ranking-only: those paths
226
+ * stay indexed and findable, they just stop outranking first-party code.
227
+ * Called once when the project opens; undefined disables the lever.
228
+ */
229
+ setDeprioritizedPathMatcher(matcher) {
230
+ this.isDeprioritizedPath = matcher;
231
+ }
232
+ /** The `deprioritize` predicate (#982), so other rankers apply the same lever. */
233
+ getDeprioritizedPathMatcher() {
234
+ return this.isDeprioritizedPath;
235
+ }
236
+ // ===========================================================================
237
+ // Node Operations
238
+ // ===========================================================================
239
+ /**
240
+ * Insert a new node
241
+ */
242
+ insertNode(node) {
243
+ if (!this.stmts.insertNode) {
244
+ this.stmts.insertNode = this.db.prepare(`
245
+ INSERT OR REPLACE INTO nodes (
246
+ id, kind, name, qualified_name, file_path, language,
247
+ start_line, end_line, start_column, end_column,
248
+ docstring, signature, visibility,
249
+ is_exported, is_async, is_static, is_abstract,
250
+ decorators, type_parameters, return_type, updated_at
251
+ ) VALUES (
252
+ @id, @kind, @name, @qualifiedName, @filePath, @language,
253
+ @startLine, @endLine, @startColumn, @endColumn,
254
+ @docstring, @signature, @visibility,
255
+ @isExported, @isAsync, @isStatic, @isAbstract,
256
+ @decorators, @typeParameters, @returnType, @updatedAt
257
+ )
258
+ `);
259
+ }
260
+ // Validate required fields to prevent SQLite bind errors
261
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
262
+ console.error('[CodeGraph] Skipping node with missing required fields:', {
263
+ id: node.id,
264
+ kind: node.kind,
265
+ name: node.name,
266
+ filePath: node.filePath,
267
+ language: node.language,
268
+ });
269
+ return;
270
+ }
271
+ // INSERT OR REPLACE may overwrite a node we have cached. Drop the
272
+ // stale entry so the next getNodeById sees the new row, not the old
273
+ // one (matches the cache-invalidation pattern used by updateNode and
274
+ // deleteNode below).
275
+ this.nodeCache.delete(node.id);
276
+ this.stmts.insertNode.run({
277
+ id: node.id,
278
+ kind: node.kind,
279
+ name: node.name,
280
+ qualifiedName: node.qualifiedName ?? node.name,
281
+ filePath: node.filePath,
282
+ language: node.language,
283
+ startLine: node.startLine ?? 0,
284
+ endLine: node.endLine ?? 0,
285
+ startColumn: node.startColumn ?? 0,
286
+ endColumn: node.endColumn ?? 0,
287
+ docstring: node.docstring ?? null,
288
+ signature: node.signature ?? null,
289
+ visibility: node.visibility ?? null,
290
+ isExported: node.isExported ? 1 : 0,
291
+ isAsync: node.isAsync ? 1 : 0,
292
+ isStatic: node.isStatic ? 1 : 0,
293
+ isAbstract: node.isAbstract ? 1 : 0,
294
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
295
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
296
+ returnType: node.returnType ?? null,
297
+ updatedAt: node.updatedAt ?? Date.now(),
298
+ });
299
+ // Segment vocabulary rides the same write path (and transaction) so it can
300
+ // never drift ahead of the nodes it describes. Deletes intentionally leave
301
+ // orphans behind — vocab rows are proposals re-verified against nodes
302
+ // before use, and a full index clears the table at its start. File nodes
303
+ // are excluded: a file's basename duplicates the symbols inside it
304
+ // (state-machine.ts / OrderStateMachine), which double-counts every
305
+ // concept and defeats the singleton-vs-cluster rarity statistics. Import
306
+ // nodes are excluded too (#1144): they're named after module specifiers
307
+ // ("external-unindexed-pkg", "./utils/helpers"), not symbols — an
308
+ // import-only name can never be surfaced (getSegmentMatches requires a
309
+ // real definition), so its rows would only inflate the rarity statistics.
310
+ if (this.isSegmentableKind(node.kind))
311
+ this.insertNameSegments(node.name);
312
+ }
313
+ /** Which node kinds contribute their name to the segment vocabulary — the
314
+ * single gate shared by insertNode, updateNode, and the rebuild page query
315
+ * (getDistinctNodeNames), so the write paths can't drift apart. */
316
+ isSegmentableKind(kind) {
317
+ return kind !== 'file' && kind !== 'import';
318
+ }
319
+ /** Write `name`'s segments into name_segment_vocab (idempotent). */
320
+ insertNameSegments(name) {
321
+ const rows = [];
322
+ this.collectNameSegmentRows(name, rows);
323
+ this.runBatched('insertNameSegments', 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ', '(?,?)', rows);
324
+ }
325
+ /**
326
+ * Insert multiple nodes in a transaction
327
+ */
328
+ insertNodes(nodes) {
329
+ this.db.transaction(() => {
330
+ // Bulk path: same semantics as insertNode() per row (validation, cache
331
+ // invalidation, segment vocab), but bound as multi-row INSERTs — the
332
+ // per-.run() call overhead dominates the store phase on full indexes.
333
+ const rows = [];
334
+ const segmentRows = [];
335
+ for (const node of nodes) {
336
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
337
+ console.error('[CodeGraph] Skipping node with missing required fields:', {
338
+ id: node.id,
339
+ kind: node.kind,
340
+ name: node.name,
341
+ filePath: node.filePath,
342
+ language: node.language,
343
+ });
344
+ continue;
345
+ }
346
+ this.nodeCache.delete(node.id);
347
+ rows.push([
348
+ node.id,
349
+ node.kind,
350
+ node.name,
351
+ node.qualifiedName ?? node.name,
352
+ node.filePath,
353
+ node.language,
354
+ node.startLine ?? 0,
355
+ node.endLine ?? 0,
356
+ node.startColumn ?? 0,
357
+ node.endColumn ?? 0,
358
+ node.docstring ?? null,
359
+ node.signature ?? null,
360
+ node.visibility ?? null,
361
+ node.isExported ? 1 : 0,
362
+ node.isAsync ? 1 : 0,
363
+ node.isStatic ? 1 : 0,
364
+ node.isAbstract ? 1 : 0,
365
+ node.decorators ? JSON.stringify(node.decorators) : null,
366
+ node.typeParameters ? JSON.stringify(node.typeParameters) : null,
367
+ node.returnType ?? null,
368
+ node.updatedAt ?? Date.now(),
369
+ ]);
370
+ if (this.isSegmentableKind(node.kind))
371
+ this.collectNameSegmentRows(node.name, segmentRows);
372
+ }
373
+ this.runBatched('insertNodes', `INSERT OR REPLACE INTO nodes (
374
+ id, kind, name, qualified_name, file_path, language,
375
+ start_line, end_line, start_column, end_column,
376
+ docstring, signature, visibility,
377
+ is_exported, is_async, is_static, is_abstract,
378
+ decorators, type_parameters, return_type, updated_at
379
+ ) VALUES `, '(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', rows);
380
+ this.runBatched('insertNameSegments', 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ', '(?,?)', segmentRows);
381
+ })();
382
+ }
383
+ /**
384
+ * Store one file's whole extraction bundle — nodes, edges, unresolved refs,
385
+ * and the file record — in a SINGLE transaction. The bulk-index path calls
386
+ * this once per file instead of opening one transaction per table (#1015
387
+ * file-order commit discipline is unchanged: callers still invoke it in file
388
+ * order, and row order within is input order).
389
+ *
390
+ * Edges MUST already be endpoint-filtered by the caller (the store path
391
+ * filters to the file's own inserted node ids), so the per-file existence
392
+ * SELECT that insertEdges() pays is skipped here.
393
+ */
394
+ storeFileBundle(bundle) {
395
+ this.db.transaction(() => {
396
+ this.insertNodes(bundle.nodes);
397
+ if (bundle.edges.length > 0) {
398
+ const rows = [];
399
+ for (const edge of bundle.edges) {
400
+ rows.push([
401
+ edge.source,
402
+ edge.target,
403
+ edge.kind,
404
+ edge.metadata ? JSON.stringify(edge.metadata) : null,
405
+ edge.line ?? null,
406
+ edge.column ?? null,
407
+ edge.provenance ?? null,
408
+ ]);
409
+ }
410
+ this.runBatched('insertEdges', 'INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance) VALUES ', '(?,?,?,?,?,?,?)', rows);
411
+ }
412
+ if (bundle.refs.length > 0)
413
+ this.insertUnresolvedRefsBatch(bundle.refs);
414
+ this.upsertFile(bundle.file);
415
+ })();
416
+ }
417
+ /**
418
+ * Collect (segment, name) rows for a name, honouring the same session-dedupe
419
+ * semantics as insertNameSegments(). Shared by the bulk write paths.
420
+ */
421
+ collectNameSegmentRows(name, out) {
422
+ if (this.segmentedNames.has(name))
423
+ return;
424
+ if (this.segmentedNames.size >= QueryBuilder.MAX_SEGMENTED_NAMES)
425
+ this.segmentedNames.clear();
426
+ this.segmentedNames.add(name);
427
+ for (const segment of (0, identifier_segments_1.splitIdentifierSegments)(name))
428
+ out.push([segment, name]);
429
+ }
430
+ /**
431
+ * Update an existing node
432
+ */
433
+ updateNode(node) {
434
+ if (!this.stmts.updateNode) {
435
+ this.stmts.updateNode = this.db.prepare(`
436
+ UPDATE nodes SET
437
+ kind = @kind,
438
+ name = @name,
439
+ qualified_name = @qualifiedName,
440
+ file_path = @filePath,
441
+ language = @language,
442
+ start_line = @startLine,
443
+ end_line = @endLine,
444
+ start_column = @startColumn,
445
+ end_column = @endColumn,
446
+ docstring = @docstring,
447
+ signature = @signature,
448
+ visibility = @visibility,
449
+ is_exported = @isExported,
450
+ is_async = @isAsync,
451
+ is_static = @isStatic,
452
+ is_abstract = @isAbstract,
453
+ decorators = @decorators,
454
+ type_parameters = @typeParameters,
455
+ return_type = @returnType,
456
+ updated_at = @updatedAt
457
+ WHERE id = @id
458
+ `);
459
+ }
460
+ // Invalidate cache before update
461
+ this.nodeCache.delete(node.id);
462
+ // Validate required fields
463
+ if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
464
+ console.error('[CodeGraph] Skipping node update with missing required fields:', node.id);
465
+ return;
466
+ }
467
+ this.stmts.updateNode.run({
468
+ id: node.id,
469
+ kind: node.kind,
470
+ name: node.name,
471
+ qualifiedName: node.qualifiedName ?? node.name,
472
+ filePath: node.filePath,
473
+ language: node.language,
474
+ startLine: node.startLine ?? 0,
475
+ endLine: node.endLine ?? 0,
476
+ startColumn: node.startColumn ?? 0,
477
+ endColumn: node.endColumn ?? 0,
478
+ docstring: node.docstring ?? null,
479
+ signature: node.signature ?? null,
480
+ visibility: node.visibility ?? null,
481
+ isExported: node.isExported ? 1 : 0,
482
+ isAsync: node.isAsync ? 1 : 0,
483
+ isStatic: node.isStatic ? 1 : 0,
484
+ isAbstract: node.isAbstract ? 1 : 0,
485
+ decorators: node.decorators ? JSON.stringify(node.decorators) : null,
486
+ typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
487
+ returnType: node.returnType ?? null,
488
+ updatedAt: node.updatedAt ?? Date.now(),
489
+ });
490
+ // updateNode is a second real write path to `nodes` — framework
491
+ // post-extract passes rewrite names through it (NestJS route prefixing),
492
+ // and a renamed node's new name must reach the segment vocabulary just
493
+ // like an inserted one's (#1141). Without this the rename left the new
494
+ // name permanently unsearchable: the old name's rows became honest-gate
495
+ // orphans and the only backfill is gated on the vocab being EMPTY.
496
+ // insertNameSegments is idempotent (in-memory set + INSERT OR IGNORE),
497
+ // so no name-changed check is needed.
498
+ if (this.isSegmentableKind(node.kind))
499
+ this.insertNameSegments(node.name);
500
+ }
501
+ /**
502
+ * Delete a node by ID
503
+ */
504
+ deleteNode(id) {
505
+ if (!this.stmts.deleteNode) {
506
+ this.stmts.deleteNode = this.db.prepare('DELETE FROM nodes WHERE id = ?');
507
+ }
508
+ // Invalidate cache
509
+ this.nodeCache.delete(id);
510
+ this.stmts.deleteNode.run(id);
511
+ }
512
+ /**
513
+ * Delete all nodes for a file
514
+ */
515
+ deleteNodesByFile(filePath) {
516
+ if (!this.stmts.deleteNodesByFile) {
517
+ this.stmts.deleteNodesByFile = this.db.prepare('DELETE FROM nodes WHERE file_path = ?');
518
+ }
519
+ // Invalidate cache for nodes in this file
520
+ for (const [id, node] of this.nodeCache) {
521
+ if (node.filePath === filePath) {
522
+ this.nodeCache.delete(id);
523
+ }
524
+ }
525
+ this.stmts.deleteNodesByFile.run(filePath);
526
+ }
527
+ // ===========================================================================
528
+ // Name-segment vocabulary (prompt-hook graph-derived gate)
529
+ // ===========================================================================
530
+ /** Wipe the segment vocabulary. A full index calls this at its start; the
531
+ * node write path repopulates it as files (re-)index, so the end state is
532
+ * exactly the current names with no orphan rows. */
533
+ clearNameSegmentVocab() {
534
+ this.db.exec('DELETE FROM name_segment_vocab');
535
+ this.segmentedNames.clear();
536
+ }
537
+ /** True when the vocab has no rows — an index built before the table existed.
538
+ * `sync` uses this to heal such databases (see rebuildNameSegmentVocabFrom). */
539
+ isNameSegmentVocabEmpty() {
540
+ const row = this.db.prepare('SELECT 1 FROM name_segment_vocab LIMIT 1').get();
541
+ return row === undefined;
542
+ }
543
+ /** One page of distinct segmentable node names, for batched vocab rebuilds
544
+ * (file basenames and import specifiers are excluded from the vocab — see
545
+ * insertNode). */
546
+ getDistinctNodeNames(limit, offset) {
547
+ const rows = this.db
548
+ .prepare("SELECT DISTINCT name FROM nodes WHERE kind NOT IN ('file', 'import') ORDER BY name LIMIT ? OFFSET ?")
549
+ .all(limit, offset);
550
+ return rows.map((r) => r.name);
551
+ }
552
+ /** Insert segments for a batch of names in one transaction (vocab heal path). */
553
+ insertNameSegmentsBatch(names) {
554
+ this.db.transaction(() => {
555
+ const rows = [];
556
+ for (const name of names)
557
+ this.collectNameSegmentRows(name, rows);
558
+ this.runBatched('insertNameSegments', 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ', '(?,?)', rows);
559
+ })();
560
+ }
561
+ /**
562
+ * Names whose segments cover at least `minWords` distinct PROMPT WORDS —
563
+ * the co-occurrence probe behind the prompt hook's medium tier: the words
564
+ * "state" and "machine" both being segments of `OrderStateMachine` is strong
565
+ * evidence the prompt names that symbol in prose. Ordered by coverage.
566
+ *
567
+ * Takes (segment variant → original word) pairs and folds variants back to
568
+ * their word INSIDE the SQL: a name matching both `service` and `services`
569
+ * counts ONE word, not two. Counting raw variants let plural-variant pairs
570
+ * of a single word tie with genuine two-word matches and — because ORDER
571
+ * BY/LIMIT run here, before any JS-side re-check — crowd a real match past
572
+ * the LIMIT on vocab-heavy repos (#1146).
573
+ */
574
+ getSegmentCoOccurrence(variants, minWords, limit) {
575
+ if (variants.length === 0)
576
+ return [];
577
+ const placeholders = variants.map(() => '?').join(', ');
578
+ const whens = variants.map(() => 'WHEN ? THEN ?').join(' ');
579
+ const rows = this.db
580
+ .prepare(`SELECT name, COUNT(DISTINCT CASE segment ${whens} END) AS matches
581
+ FROM name_segment_vocab
582
+ WHERE segment IN (${placeholders})
583
+ GROUP BY name
584
+ HAVING matches >= ?
585
+ ORDER BY matches DESC, length(name) ASC
586
+ LIMIT ?`)
587
+ .all(...variants.flatMap((v) => [v.segment, v.word]), ...variants.map((v) => v.segment), minWords, limit);
588
+ return rows;
589
+ }
590
+ /** How many distinct names each segment appears in — the rarity signal that
591
+ * separates a discriminative word ("checkout") from a ubiquitous one ("state"). */
592
+ getSegmentNameCounts(segments) {
593
+ if (segments.length === 0)
594
+ return new Map();
595
+ const placeholders = segments.map(() => '?').join(', ');
596
+ const rows = this.db
597
+ .prepare(`SELECT segment, COUNT(*) AS n FROM name_segment_vocab
598
+ WHERE segment IN (${placeholders}) GROUP BY segment`)
599
+ .all(...segments);
600
+ return new Map(rows.map((r) => [r.segment, r.n]));
601
+ }
602
+ /** Names containing the given segment (rare-single-word tier). */
603
+ getNamesForSegment(segment, limit) {
604
+ const rows = this.db
605
+ .prepare('SELECT name FROM name_segment_vocab WHERE segment = ? ORDER BY length(name) ASC LIMIT ?')
606
+ .all(segment, limit);
607
+ return rows.map((r) => r.name);
608
+ }
609
+ /**
610
+ * Get a node by ID
611
+ */
612
+ getNodeById(id) {
613
+ // Check cache first
614
+ if (this.nodeCache.has(id)) {
615
+ const cached = this.nodeCache.get(id);
616
+ // Move to end to implement LRU (delete and re-add)
617
+ this.nodeCache.delete(id);
618
+ this.nodeCache.set(id, cached);
619
+ return cached;
620
+ }
621
+ if (!this.stmts.getNodeById) {
622
+ this.stmts.getNodeById = this.db.prepare('SELECT * FROM nodes WHERE id = ?');
623
+ }
624
+ const row = this.stmts.getNodeById.get(id);
625
+ if (!row) {
626
+ return null;
627
+ }
628
+ const node = rowToNode(row);
629
+ this.cacheNode(node);
630
+ return node;
631
+ }
632
+ /**
633
+ * Batch lookup: fetch many nodes by ID in a single SQL round-trip.
634
+ *
635
+ * Replaces the N+1 pattern in graph traversal where every edge would
636
+ * trigger its own `getNodeById` call. For a function with 50 callers
637
+ * this collapses 50 point reads into one IN-list query (~10-50x
638
+ * faster end-to-end).
639
+ *
640
+ * Returns a Map keyed by id so callers can preserve their own ordering
641
+ * (typically the order edges were returned from the graph). Missing IDs
642
+ * are simply absent from the map.
643
+ *
644
+ * Cache-aware: ids already in the LRU cache are served from memory and
645
+ * the SQL query only touches the misses.
646
+ */
647
+ getNodesByIds(ids) {
648
+ const out = new Map();
649
+ if (ids.length === 0)
650
+ return out;
651
+ // Serve cache hits first; build the miss list for SQL.
652
+ const misses = [];
653
+ for (const id of ids) {
654
+ const cached = this.nodeCache.get(id);
655
+ if (cached !== undefined) {
656
+ // LRU touch
657
+ this.nodeCache.delete(id);
658
+ this.nodeCache.set(id, cached);
659
+ out.set(id, cached);
660
+ }
661
+ else {
662
+ misses.push(id);
663
+ }
664
+ }
665
+ if (misses.length === 0)
666
+ return out;
667
+ // Chunk under SQLite's parameter limit (default 999, raised to 32766
668
+ // in better-sqlite3 builds — chunk at 500 for safety across both
669
+ // backends and to keep the query plan simple).
670
+ for (let i = 0; i < misses.length; i += SQLITE_PARAM_CHUNK_SIZE) {
671
+ const chunk = misses.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
672
+ const placeholders = chunk.map(() => '?').join(',');
673
+ const rows = this.db
674
+ .prepare(`SELECT * FROM nodes WHERE id IN (${placeholders})`)
675
+ .all(...chunk);
676
+ for (const row of rows) {
677
+ const node = rowToNode(row);
678
+ out.set(node.id, node);
679
+ this.cacheNode(node);
680
+ }
681
+ }
682
+ return out;
683
+ }
684
+ getExistingNodeIds(ids) {
685
+ const out = new Set();
686
+ if (ids.length === 0)
687
+ return out;
688
+ const uniqueIds = [...new Set(ids)];
689
+ for (let i = 0; i < uniqueIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
690
+ const chunk = uniqueIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
691
+ const placeholders = chunk.map(() => '?').join(',');
692
+ const rows = this.db
693
+ .prepare(`SELECT id FROM nodes WHERE id IN (${placeholders})`)
694
+ .all(...chunk);
695
+ for (const row of rows) {
696
+ out.add(row.id);
697
+ }
698
+ }
699
+ return out;
700
+ }
701
+ /**
702
+ * Add a node to the cache, evicting oldest if needed
703
+ */
704
+ cacheNode(node) {
705
+ if (this.nodeCache.size >= this.maxCacheSize) {
706
+ // Evict oldest (first) entry
707
+ const firstKey = this.nodeCache.keys().next().value;
708
+ if (firstKey) {
709
+ this.nodeCache.delete(firstKey);
710
+ }
711
+ }
712
+ this.nodeCache.set(node.id, node);
713
+ }
714
+ /**
715
+ * Clear the node cache
716
+ */
717
+ clearCache() {
718
+ this.nodeCache.clear();
719
+ }
720
+ /**
721
+ * Get all nodes in a file
722
+ */
723
+ getNodesByFile(filePath) {
724
+ if (!this.stmts.getNodesByFile) {
725
+ this.stmts.getNodesByFile = this.db.prepare('SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line');
726
+ }
727
+ const rows = this.stmts.getNodesByFile.all(filePath);
728
+ return rows.map(rowToNode);
729
+ }
730
+ /**
731
+ * Find the file that holds the densest concentration of the project's
732
+ * internal call graph — the "core" file. Used by context-builder to
733
+ * boost ranking of symbols in that file's directory (so e.g. sinatra
734
+ * queries surface `lib/sinatra/base.rb`'s `route!` instead of
735
+ * `sinatra-contrib/lib/sinatra/multi_route.rb`'s `route` extension).
736
+ *
737
+ * Returns null if no file has a meaningful concentration (e.g. spread
738
+ * evenly across many files, or empty index).
739
+ *
740
+ * "Internal" = source and target are in the same file. Cross-file
741
+ * edges aren't useful here — they don't tell us which file is the
742
+ * functional center.
743
+ *
744
+ * Excludes test/spec files from candidacy via path-pattern. The agent's
745
+ * typical question is "how does X work", not "how is X tested", so
746
+ * boosting a test file's directory would be a misfire.
747
+ */
748
+ getDominantFile() {
749
+ if (!this.stmts.getDominantFile) {
750
+ // Pull top 20 candidates; we then filter out test/generated files
751
+ // in code (regex-grade matching that SQL LIKE can't express). The
752
+ // generated-file filter is critical — without it, etcd's
753
+ // `api/etcdserverpb/rpc.pb.go` (1916 in-file edges, generated
754
+ // protobuf stub) outranks the real `server/etcdserver/server.go`
755
+ // (470 edges) by 4×, and the boost would push the agent toward
756
+ // generated code.
757
+ this.stmts.getDominantFile = this.db.prepare(`
758
+ SELECT n.file_path AS file_path, COUNT(*) AS edge_count
759
+ FROM edges e
760
+ JOIN nodes n ON e.source = n.id
761
+ JOIN nodes m ON e.target = m.id
762
+ WHERE n.file_path = m.file_path
763
+ GROUP BY n.file_path
764
+ ORDER BY edge_count DESC
765
+ LIMIT 20
766
+ `);
767
+ }
768
+ const rows = this.stmts.getDominantFile.all();
769
+ const generated = this.getGeneratedPathsAmong(rows.map(r => r.file_path));
770
+ const filtered = rows.filter(r => !isLowValueFile(r.file_path, generated));
771
+ if (filtered.length === 0 || filtered[0].edge_count < 20)
772
+ return null;
773
+ return {
774
+ filePath: filtered[0].file_path,
775
+ edgeCount: filtered[0].edge_count,
776
+ nextEdgeCount: filtered[1]?.edge_count ?? 0,
777
+ };
778
+ }
779
+ /**
780
+ * Find the file that holds the densest concentration of the project's
781
+ * `route` nodes (framework-emitted: Express/Gin/Flask/Rails/Drupal/etc.).
782
+ * Used by handleContext on small repos to inline the project's routing
783
+ * config when the agent's query is about request flow — eliminating the
784
+ * "Glob + Read routes.rb" pattern that beats codegraph on tiny realworld
785
+ * template repos.
786
+ *
787
+ * Excludes test/generated files from candidacy. Returns null if there
788
+ * are fewer than 3 non-test routes total, or if no file holds at least
789
+ * 30% of them (diffuse routing → no single answer file).
790
+ */
791
+ getTopRouteFile() {
792
+ if (!this.stmts.getTopRouteFile) {
793
+ this.stmts.getTopRouteFile = this.db.prepare(`
794
+ SELECT file_path, COUNT(*) AS cnt
795
+ FROM nodes
796
+ WHERE kind = 'route'
797
+ GROUP BY file_path
798
+ ORDER BY cnt DESC
799
+ LIMIT 20
800
+ `);
801
+ }
802
+ const rows = this.stmts.getTopRouteFile.all();
803
+ const generated = this.getGeneratedPathsAmong(rows.map(r => r.file_path));
804
+ const filtered = rows.filter(r => !isLowValueFile(r.file_path, generated));
805
+ if (filtered.length === 0)
806
+ return null;
807
+ const totalRoutes = filtered.reduce((sum, r) => sum + r.cnt, 0);
808
+ const top = filtered[0];
809
+ if (totalRoutes < 3 || top.cnt < 3)
810
+ return null;
811
+ if (top.cnt / totalRoutes < 0.30)
812
+ return null;
813
+ return { filePath: top.file_path, routeCount: top.cnt, totalRoutes };
814
+ }
815
+ /**
816
+ * Build a URL → handler manifest from the index. Each route node's
817
+ * `references` edge points at the function/method that handles the
818
+ * request. We join them in one pass; the agent gets the canonical
819
+ * routing answer ("POST /users/login → AuthController#login") without
820
+ * having to parse the framework's route DSL itself.
821
+ *
822
+ * Also returns the file with the most handler endpoints — used as the
823
+ * "top handler file" to inline source for, so the agent has both the
824
+ * mapping AND the handler implementations.
825
+ */
826
+ getRoutingManifest(limit = 40) {
827
+ if (!this.stmts.getRoutingManifest) {
828
+ // Edge kind varies across framework resolvers: Spring/Rails/
829
+ // Laravel/Drupal emit `references`, Express emits `calls`. Accept
830
+ // both — the semantic is the same (route → its handler).
831
+ this.stmts.getRoutingManifest = this.db.prepare(`
832
+ SELECT
833
+ r.name AS url,
834
+ r.id AS route_id,
835
+ r.file_path AS route_file,
836
+ r.start_line AS route_line,
837
+ h.name AS handler,
838
+ h.file_path AS handler_file,
839
+ h.start_line AS handler_line,
840
+ h.kind AS handler_kind
841
+ FROM nodes r
842
+ JOIN edges e ON e.source = r.id
843
+ JOIN nodes h ON e.target = h.id
844
+ WHERE r.kind = 'route'
845
+ AND e.kind IN ('references', 'calls')
846
+ AND h.kind IN ('function', 'method', 'class', 'constant', 'variable')
847
+ ORDER BY r.file_path, r.start_line
848
+ LIMIT ?
849
+ `);
850
+ }
851
+ const rows = this.stmts.getRoutingManifest.all(limit);
852
+ // Drop test/generated handlers — same hygiene as elsewhere.
853
+ const generated = this.getGeneratedPathsAmong(rows.map(r => r.handler_file));
854
+ const filtered = rows.filter(r => !isLowValueFile(r.handler_file, generated));
855
+ if (filtered.length < 3)
856
+ return null;
857
+ // Identify the file holding the most handlers (the "primary handler file").
858
+ const fileCounts = new Map();
859
+ for (const r of filtered) {
860
+ fileCounts.set(r.handler_file, (fileCounts.get(r.handler_file) ?? 0) + 1);
861
+ }
862
+ let topHandlerFile = null;
863
+ let topHandlerFileCount = 0;
864
+ for (const [file, count] of fileCounts) {
865
+ if (count > topHandlerFileCount) {
866
+ topHandlerFile = file;
867
+ topHandlerFileCount = count;
868
+ }
869
+ }
870
+ return {
871
+ entries: filtered.map(r => ({
872
+ url: r.url,
873
+ handler: r.handler,
874
+ handlerFile: r.handler_file,
875
+ handlerLine: r.handler_line,
876
+ handlerKind: r.handler_kind,
877
+ routeId: r.route_id,
878
+ routeFile: r.route_file,
879
+ routeLine: r.route_line,
880
+ })),
881
+ topHandlerFile,
882
+ topHandlerFileCount,
883
+ totalRoutes: filtered.length,
884
+ };
885
+ }
886
+ /**
887
+ * Get all nodes of a specific kind
888
+ */
889
+ getNodesByKind(kind) {
890
+ if (!this.stmts.getNodesByKind) {
891
+ this.stmts.getNodesByKind = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
892
+ }
893
+ const rows = this.stmts.getNodesByKind.all(kind);
894
+ return rows.map(rowToNode);
895
+ }
896
+ /**
897
+ * Stream every node of a kind one at a time (lazy) instead of materializing
898
+ * them all like {@link getNodesByKind}. For unbounded kinds (`function`,
899
+ * `method`) on a symbol-dense project the full array is gigabytes; the
900
+ * dynamic-edge synthesizers only scan-and-filter, so they iterate to keep
901
+ * memory O(1) in the node count rather than O(nodes) (#610).
902
+ */
903
+ *iterateNodesByKind(kind) {
904
+ // Fresh statement per call (not a cached one): an iterator holds an open
905
+ // cursor, so a shared statement would conflict across overlapping scans.
906
+ const stmt = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
907
+ for (const row of stmt.iterate(kind)) {
908
+ yield rowToNode(row);
909
+ }
910
+ }
911
+ /**
912
+ * Get all nodes in the database
913
+ */
914
+ getAllNodes() {
915
+ const rows = this.db.prepare('SELECT * FROM nodes').all();
916
+ return rows.map(rowToNode);
917
+ }
918
+ /**
919
+ * Stream nodes of one language whose `decorators` JSON array contains
920
+ * `decorator`. The LIKE on the JSON text is a cheap index-free pre-filter
921
+ * (a decorator name can appear as a substring of another), so callers must
922
+ * still exact-check `node.decorators.includes(decorator)`. Exists so the
923
+ * kotlin expect/actual synthesizer never materializes the whole node table
924
+ * the way `getAllNodes().filter(...)` did — that array alone OOM'd Node's
925
+ * default heap on a 2M-node graph (#1212).
926
+ */
927
+ *iterateNodesByLanguageWithDecorator(language, decorator) {
928
+ // Fresh statement per call — an iterator holds an open cursor (see
929
+ // iterateNodesByKind).
930
+ const stmt = this.db.prepare("SELECT * FROM nodes WHERE language = ? AND decorators LIKE '%' || ? || '%'");
931
+ for (const row of stmt.iterate(language, `"${decorator}"`)) {
932
+ yield rowToNode(row);
933
+ }
934
+ }
935
+ /**
936
+ * Distinct languages present in the files table. One indexed aggregate —
937
+ * lets the dynamic-edge synthesizers skip passes for languages the project
938
+ * doesn't contain at all (a Kotlin pass has no work on a pure-C repo), so
939
+ * their cost is zero rather than a full-graph scan that finds nothing (#1212).
940
+ */
941
+ getDistinctFileLanguages() {
942
+ const rows = this.db.prepare('SELECT DISTINCT language FROM files').all();
943
+ return new Set(rows.map((r) => r.language));
944
+ }
945
+ /**
946
+ * Get nodes by exact name match (uses idx_nodes_name index).
947
+ *
948
+ * This is resolution's candidate list, and the ORDER BY is load-bearing for
949
+ * index correctness, not cosmetic (CG-33). When a reference names a symbol
950
+ * that several files define and nothing disambiguates them, resolution binds
951
+ * to the first candidate — so without an ORDER BY the winner was decided by
952
+ * rowid, i.e. by the order files happened to be WRITTEN. A full index writes
953
+ * them in scan order; an incremental sync appends each file as it changes, so
954
+ * the same tree resolved to different edges depending on how the index was
955
+ * built, and a long-lived synced index drifted away from a rebuild of itself
956
+ * (measured at 4.3% of distinct edges, mostly `calls`).
957
+ *
958
+ * `(file_path, start_line)` is a property of the CODE, so both paths now pick
959
+ * the same candidate. The sort is paid once per distinct name per resolution
960
+ * run — ReferenceResolver memoizes this in its nameCache — and the population
961
+ * is capped by AMBIGUOUS_NAME_CEILING (#999).
962
+ */
963
+ getNodesByName(name) {
964
+ if (!this.stmts.getNodesByName) {
965
+ this.stmts.getNodesByName = this.db.prepare('SELECT * FROM nodes WHERE name = ? ORDER BY file_path, start_line');
966
+ }
967
+ const rows = this.stmts.getNodesByName.all(name);
968
+ return rows.map(rowToNode);
969
+ }
970
+ /**
971
+ * Nodes whose name starts with `prefix`, by index range scan (a LIKE would
972
+ * skip idx_nodes_name under SQLite's default case-insensitive LIKE).
973
+ */
974
+ getNodesByNamePrefix(prefix, limit = 20) {
975
+ if (!this.stmts.getNodesByNamePrefix) {
976
+ this.stmts.getNodesByNamePrefix = this.db.prepare('SELECT * FROM nodes WHERE name >= ? AND name < ? ORDER BY name LIMIT ?');
977
+ }
978
+ const rows = this.stmts.getNodesByNamePrefix.all(prefix, prefix + '￿', limit);
979
+ return rows.map(rowToNode);
980
+ }
981
+ /**
982
+ * Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
983
+ */
984
+ getNodesByQualifiedNameExact(qualifiedName) {
985
+ if (!this.stmts.getNodesByQualifiedNameExact) {
986
+ this.stmts.getNodesByQualifiedNameExact = this.db.prepare('SELECT * FROM nodes WHERE qualified_name = ?');
987
+ }
988
+ const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName);
989
+ return rows.map(rowToNode);
990
+ }
991
+ /**
992
+ * Get nodes by name, case-insensitively (seeks the idx_nodes_lower_name
993
+ * expression index).
994
+ *
995
+ * The parameter is lowered in SQL rather than trusted to arrive lowered, so
996
+ * the lookup means the same thing whatever casing a caller hands it. Written
997
+ * as a bare `lower(name) = ?` it silently returned nothing for any input
998
+ * carrying an uppercase letter, and — because SQLite's `lower()` folds ASCII
999
+ * only while JavaScript's `.toLowerCase()` folds Unicode — a caller that
1000
+ * pre-lowered in JavaScript could not match a non-ASCII name at all.
1001
+ *
1002
+ * Note this hardens the query, not its one caller: `matchFuzzy` still lowers
1003
+ * in JavaScript before calling, so the non-ASCII gap remains open there.
1004
+ */
1005
+ getNodesByLowerName(name) {
1006
+ if (!this.stmts.getNodesByLowerName) {
1007
+ this.stmts.getNodesByLowerName = this.db.prepare('SELECT * FROM nodes WHERE lower(name) = lower(?)');
1008
+ }
1009
+ const rows = this.stmts.getNodesByLowerName.all(name);
1010
+ return rows.map(rowToNode);
1011
+ }
1012
+ /**
1013
+ * Search nodes by name using FTS with fallback to LIKE for better matching
1014
+ *
1015
+ * Search strategy:
1016
+ * 1. Try FTS5 prefix match (query*) for word-start matching
1017
+ * 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
1018
+ * 3. Score results based on match quality
1019
+ */
1020
+ searchNodes(query, options = {}) {
1021
+ const { limit = 100, offset = 0 } = options;
1022
+ // Parse field-qualified bits out of the raw query (kind:, lang:,
1023
+ // path:, name:). Anything not recognised stays in `text` and goes
1024
+ // to FTS unchanged. Filters compose with the SearchOptions arg —
1025
+ // both are applied (intersection-style).
1026
+ const parsed = (0, query_parser_1.parseQuery)(query);
1027
+ const mergedKinds = parsed.kinds.length > 0
1028
+ ? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
1029
+ : options.kinds;
1030
+ const mergedLanguages = parsed.languages.length > 0
1031
+ ? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
1032
+ : options.languages;
1033
+ const pathFilters = parsed.pathFilters;
1034
+ const nameFilters = parsed.nameFilters;
1035
+ // The text portion drives FTS/LIKE; if all the user typed was
1036
+ // filters (`kind:function`), we still need *some* candidate set,
1037
+ // so synthesise an empty-text path that returns everything matching
1038
+ // the filters.
1039
+ const text = parsed.text;
1040
+ const kinds = mergedKinds;
1041
+ const languages = mergedLanguages;
1042
+ // First try FTS5 with prefix matching
1043
+ let results = text
1044
+ ? this.searchNodesFTS(text, { kinds, languages, limit, offset })
1045
+ // Over-fetch by 5× when running filter-only (no text). The
1046
+ // post-scoring path: + name: filters can be very selective, so
1047
+ // a smaller multiplier risks returning fewer than `limit`
1048
+ // results despite the DB having plenty of matches.
1049
+ : this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
1050
+ // If no FTS results, try LIKE-based substring search
1051
+ if (results.length === 0 && text.length >= 2) {
1052
+ results = this.searchNodesLike(text, { kinds, languages, limit, offset });
1053
+ }
1054
+ // Final fuzzy fallback: scan all known names and keep those within
1055
+ // a tight Levenshtein distance. Only fires when both FTS and LIKE
1056
+ // returned nothing AND there's a text portion long enough to be
1057
+ // worth fuzzing (1-char queries would match too much).
1058
+ if (results.length === 0 && text.length >= 3) {
1059
+ results = this.searchNodesFuzzy(text, { kinds, languages, limit });
1060
+ }
1061
+ // Supplement: ensure exact name matches are always candidates.
1062
+ // BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
1063
+ // compound names (e.g. "getBeanDescriptor") in large codebases,
1064
+ // pushing them past the FTS fetch limit before post-hoc scoring can help.
1065
+ // Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
1066
+ // prefix=20) actually differentiates them after rescoring.
1067
+ //
1068
+ // Whole-name equality MUST be written as `lower(name) = lower(?)` so it
1069
+ // seeks `idx_nodes_lower_name`. The equivalent `name = ? COLLATE NOCASE`
1070
+ // matches no index — `idx_nodes_name` is BINARY-collated and the expression
1071
+ // index only matches the same expression — and degrades to a full table
1072
+ // scan. The `LIMIT 20` does not rescue it: SQLite can only stop early once
1073
+ // it has produced 20 rows, and this runs once per query term, most of which
1074
+ // name nothing in the corpus. Measured per term on an unmatched term:
1075
+ // 0.08ms on gin (2.5k nodes), 0.39ms on excalidraw (11k), 2.4ms on django
1076
+ // (62k) — and growing with the corpus, where the seek is flat at ~0.002ms.
1077
+ // Lowering the parameter in SQL rather than in JS is deliberate: SQLite's
1078
+ // `lower()` and NOCASE both fold ASCII only, while JS `.toLowerCase()`
1079
+ // folds Unicode, which would silently stop matching non-ASCII names.
1080
+ if (results.length > 0 && query) {
1081
+ const existingIds = new Set(results.map(r => r.node.id));
1082
+ const maxFtsScore = Math.max(...results.map(r => r.score));
1083
+ const terms = query.split(/\s+/).filter(t => t.length >= 2);
1084
+ for (const term of terms) {
1085
+ let sql = 'SELECT * FROM nodes WHERE lower(name) = lower(?)';
1086
+ const params = [term];
1087
+ if (kinds && kinds.length > 0) {
1088
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1089
+ params.push(...kinds);
1090
+ }
1091
+ if (languages && languages.length > 0) {
1092
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1093
+ params.push(...languages);
1094
+ }
1095
+ sql += ' LIMIT 20';
1096
+ const rows = this.db.prepare(sql).all(...params);
1097
+ for (const row of rows) {
1098
+ if (!existingIds.has(row.id)) {
1099
+ results.push({ node: rowToNode(row), score: maxFtsScore });
1100
+ existingIds.add(row.id);
1101
+ }
1102
+ }
1103
+ }
1104
+ }
1105
+ // Apply multi-signal scoring
1106
+ if (results.length > 0 && (text || query)) {
1107
+ const scoringQuery = text || query;
1108
+ results = results.map(r => {
1109
+ // A path the project de-prioritized is saying its symbol NAMES are not
1110
+ // the answer, so the exact-name bonus has to be damped too. The -15 path
1111
+ // penalty alone cannot do it: the bonus is additive and larger (measured
1112
+ // on #982's repro, a `usage()` helper sat at 74.8 vs 51.2 for the top
1113
+ // product symbol — -15 lands at 59.8, still ahead). Damped, not zeroed,
1114
+ // so the tree stays findable when it genuinely is what you asked for.
1115
+ // Evaluated once and reused: the predicate stats the config file.
1116
+ const deprioritized = this.isDeprioritizedPath?.(r.node.filePath) ?? false;
1117
+ const nameBonus = (0, query_utils_1.nameMatchBonus)(r.node.name, scoringQuery);
1118
+ return {
1119
+ ...r,
1120
+ score: r.score
1121
+ + (0, query_utils_1.kindBonus)(r.node.kind)
1122
+ + (0, query_utils_1.scorePathRelevance)(r.node.filePath, scoringQuery, this.projectNameTokens, deprioritized)
1123
+ + (deprioritized ? Math.round(nameBonus * exports.DEPRIORITIZED_NAME_BONUS_SCALE) : nameBonus),
1124
+ };
1125
+ });
1126
+ results.sort((a, b) => b.score - a.score);
1127
+ // Trim to requested limit after rescoring
1128
+ if (results.length > limit) {
1129
+ results = results.slice(0, limit);
1130
+ }
1131
+ }
1132
+ // Apply path: + name: filters AFTER scoring. Scoring already uses
1133
+ // path/name as a soft signal; the explicit filters here are a hard
1134
+ // gate. Done last so the FTS limit fetched plenty of candidates to
1135
+ // narrow from.
1136
+ if (pathFilters.length > 0) {
1137
+ const lowered = pathFilters.map((p) => p.toLowerCase());
1138
+ results = results.filter((r) => {
1139
+ const fp = r.node.filePath.toLowerCase();
1140
+ return lowered.some((p) => fp.includes(p));
1141
+ });
1142
+ }
1143
+ if (nameFilters.length > 0) {
1144
+ const lowered = nameFilters.map((n) => n.toLowerCase());
1145
+ results = results.filter((r) => {
1146
+ const nm = r.node.name.toLowerCase();
1147
+ return lowered.some((n) => nm.includes(n));
1148
+ });
1149
+ }
1150
+ return results;
1151
+ }
1152
+ /**
1153
+ * Match-everything path used when the user supplied only field
1154
+ * filters (`kind:function lang:typescript`) with no text. Returns
1155
+ * candidates ordered by name; the caller's filter pass narrows to
1156
+ * what was asked for.
1157
+ */
1158
+ searchAllByFilters(options) {
1159
+ const { kinds, languages, limit } = options;
1160
+ let sql = 'SELECT * FROM nodes WHERE 1=1';
1161
+ const params = [];
1162
+ if (kinds && kinds.length > 0) {
1163
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1164
+ params.push(...kinds);
1165
+ }
1166
+ if (languages && languages.length > 0) {
1167
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1168
+ params.push(...languages);
1169
+ }
1170
+ sql += ' ORDER BY name LIMIT ?';
1171
+ params.push(limit);
1172
+ const rows = this.db.prepare(sql).all(...params);
1173
+ return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
1174
+ }
1175
+ /**
1176
+ * Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
1177
+ * sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
1178
+ * `getUssr` finds `getUser` but `process` doesn't match `prosody`.
1179
+ * Bounded edit distance keeps each comparison cheap; the per-query
1180
+ * scan is O(distinct-name-count) which is far smaller than total
1181
+ * node count on any real codebase.
1182
+ */
1183
+ searchNodesFuzzy(text, options) {
1184
+ const { kinds, languages, limit } = options;
1185
+ const lowered = text.toLowerCase();
1186
+ const maxDist = lowered.length <= 4 ? 1 : 2;
1187
+ // Pull the distinct name list once. The set is cached on QueryBuilder
1188
+ // by getAllNodeNames(); even on a 200k-node project the distinct
1189
+ // name set is typically O(10k) because most names repeat. The
1190
+ // candidate-cap below bounds memory regardless.
1191
+ const allNames = this.getAllNodeNames();
1192
+ const candidates = [];
1193
+ for (const name of allNames) {
1194
+ const dist = (0, query_parser_1.boundedEditDistance)(name.toLowerCase(), lowered, maxDist);
1195
+ if (dist <= maxDist)
1196
+ candidates.push({ name, dist });
1197
+ }
1198
+ candidates.sort((a, b) => a.dist - b.dist);
1199
+ // Cap the per-name follow-up queries. Each survivor triggers a
1200
+ // separate `SELECT * FROM nodes WHERE name = ?`; without this cap
1201
+ // a project with many similar names (`getUser1`, `getUser2`...)
1202
+ // could fan out far beyond `limit` queries before the inner-loop
1203
+ // limit kicks in.
1204
+ const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
1205
+ const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
1206
+ const results = [];
1207
+ const seen = new Set();
1208
+ for (const c of cappedCandidates) {
1209
+ if (results.length >= limit)
1210
+ break;
1211
+ let sql = 'SELECT * FROM nodes WHERE name = ?';
1212
+ const params = [c.name];
1213
+ if (kinds && kinds.length > 0) {
1214
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1215
+ params.push(...kinds);
1216
+ }
1217
+ if (languages && languages.length > 0) {
1218
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1219
+ params.push(...languages);
1220
+ }
1221
+ sql += ' LIMIT 5';
1222
+ const rows = this.db.prepare(sql).all(...params);
1223
+ for (const row of rows) {
1224
+ if (seen.has(row.id))
1225
+ continue;
1226
+ seen.add(row.id);
1227
+ // Lower the score for each edit step away from the query so
1228
+ // exact-match fallbacks (dist 0) outrank dist-2 typos.
1229
+ results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
1230
+ if (results.length >= limit)
1231
+ break;
1232
+ }
1233
+ }
1234
+ return results;
1235
+ }
1236
+ /**
1237
+ * FTS5 search with prefix matching
1238
+ */
1239
+ searchNodesFTS(query, options) {
1240
+ const { kinds, languages, limit = 100, offset = 0 } = options;
1241
+ // Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
1242
+ // Escape special FTS5 characters and add prefix wildcard.
1243
+ //
1244
+ // `::` is a qualifier separator in Rust/C++/Ruby, not a token char,
1245
+ // so treat it as whitespace before the strip step. Otherwise queries
1246
+ // like `stage_apply::run` collapse to `stage_applyrun` (the colons
1247
+ // are stripped without splitting) and find nothing. See #173.
1248
+ const ftsQuery = query
1249
+ .replace(/::/g, ' ') // Rust/C++/Ruby qualifier separator
1250
+ .replace(/['"*():^]/g, '') // Remove FTS5 special chars
1251
+ .split(/\s+/)
1252
+ .filter(term => term.length > 0)
1253
+ // Strip FTS5 boolean operators to prevent query manipulation
1254
+ .filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
1255
+ .map(term => `"${term}"*`) // Prefix match each term
1256
+ .join(' OR ');
1257
+ if (!ftsQuery) {
1258
+ return [];
1259
+ }
1260
+ // BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
1261
+ // Heavy name weight ensures exact/prefix name matches rank above incidental
1262
+ // mentions in long docstrings or qualified names of nested symbols.
1263
+ // Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
1264
+ // nameMatchBonus) can promote results that BM25 alone undervalues.
1265
+ const ftsLimit = Math.max(limit * 5, 100);
1266
+ let sql = `
1267
+ SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
1268
+ FROM nodes_fts
1269
+ JOIN nodes ON nodes_fts.id = nodes.id
1270
+ WHERE nodes_fts MATCH ?
1271
+ `;
1272
+ const params = [ftsQuery];
1273
+ if (kinds && kinds.length > 0) {
1274
+ sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
1275
+ params.push(...kinds);
1276
+ }
1277
+ if (languages && languages.length > 0) {
1278
+ sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
1279
+ params.push(...languages);
1280
+ }
1281
+ sql += ' ORDER BY score LIMIT ? OFFSET ?';
1282
+ params.push(ftsLimit, offset);
1283
+ try {
1284
+ const rows = this.db.prepare(sql).all(...params);
1285
+ return rows.map((row) => ({
1286
+ node: rowToNode(row),
1287
+ score: Math.abs(row.score), // bm25 returns negative scores
1288
+ }));
1289
+ }
1290
+ catch {
1291
+ // FTS query failed, return empty
1292
+ return [];
1293
+ }
1294
+ }
1295
+ /**
1296
+ * LIKE-based substring search for cases where FTS doesn't match
1297
+ * Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
1298
+ */
1299
+ searchNodesLike(query, options) {
1300
+ const { kinds, languages, limit = 100, offset = 0 } = options;
1301
+ let sql = `
1302
+ SELECT nodes.*,
1303
+ CASE
1304
+ WHEN name = ? THEN 1.0
1305
+ WHEN name LIKE ? THEN 0.9
1306
+ WHEN name LIKE ? THEN 0.8
1307
+ WHEN qualified_name LIKE ? THEN 0.7
1308
+ ELSE 0.5
1309
+ END as score
1310
+ FROM nodes
1311
+ WHERE (
1312
+ name LIKE ? OR
1313
+ qualified_name LIKE ? OR
1314
+ name LIKE ?
1315
+ )
1316
+ `;
1317
+ // Pattern variants for better matching
1318
+ const exactMatch = query;
1319
+ const startsWith = `${query}%`;
1320
+ const contains = `%${query}%`;
1321
+ const params = [
1322
+ exactMatch, // Exact match score
1323
+ startsWith, // Starts with score
1324
+ contains, // Contains score
1325
+ contains, // Qualified name score
1326
+ contains, // WHERE: name contains
1327
+ contains, // WHERE: qualified_name contains
1328
+ startsWith, // WHERE: name starts with
1329
+ ];
1330
+ if (kinds && kinds.length > 0) {
1331
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1332
+ params.push(...kinds);
1333
+ }
1334
+ if (languages && languages.length > 0) {
1335
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1336
+ params.push(...languages);
1337
+ }
1338
+ sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
1339
+ params.push(limit, offset);
1340
+ const rows = this.db.prepare(sql).all(...params);
1341
+ return rows.map((row) => ({
1342
+ node: rowToNode(row),
1343
+ score: row.score,
1344
+ }));
1345
+ }
1346
+ /**
1347
+ * Find nodes by exact name match
1348
+ *
1349
+ * Used for hybrid search - looks up symbols by exact name or case-insensitive match.
1350
+ * Returns high-confidence matches for known symbol names extracted from query.
1351
+ *
1352
+ * @param names - Array of symbol names to look up
1353
+ * @param options - Search options (kinds, languages, limit)
1354
+ * @returns SearchResult array with exact matches scored at 1.0
1355
+ */
1356
+ findNodesByExactName(names, options = {}) {
1357
+ if (names.length === 0)
1358
+ return [];
1359
+ const { kinds, languages, limit = 50 } = options;
1360
+ // Two-pass approach to handle common names (e.g., "run" has 40+ matches):
1361
+ // Pass 1: Find which files contain distinctive (rare) symbols from the query.
1362
+ // Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
1363
+ // Pass 1: Find files containing each queried name, identify distinctive names
1364
+ //
1365
+ // Both passes spell whole-name equality as `lower(name) = lower(?)` so they
1366
+ // seek `idx_nodes_lower_name` — see the note in `searchNodes` for why the
1367
+ // `name = ? COLLATE NOCASE` form full-scans instead. This path is the one
1368
+ // that hurts most: it runs both passes for every symbol extracted from the
1369
+ // query, and extraction is generous, so most of those names are absent from
1370
+ // the corpus and never reach either LIMIT.
1371
+ const nameToFiles = new Map();
1372
+ for (const name of names) {
1373
+ let sql = 'SELECT DISTINCT file_path FROM nodes WHERE lower(name) = lower(?)';
1374
+ const params = [name];
1375
+ if (kinds && kinds.length > 0) {
1376
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1377
+ params.push(...kinds);
1378
+ }
1379
+ sql += ' LIMIT 100';
1380
+ const rows = this.db.prepare(sql).all(...params);
1381
+ nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
1382
+ }
1383
+ // Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
1384
+ const distinctiveFiles = new Set();
1385
+ for (const [, files] of nameToFiles) {
1386
+ if (files.size > 0 && files.size < 10) {
1387
+ for (const f of files)
1388
+ distinctiveFiles.add(f);
1389
+ }
1390
+ }
1391
+ // Pass 2: Query each name with per-name limit, scoring by co-location
1392
+ const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
1393
+ const allResults = [];
1394
+ const seenIds = new Set();
1395
+ for (const name of names) {
1396
+ let sql = `
1397
+ SELECT nodes.*, 1.0 as score
1398
+ FROM nodes
1399
+ WHERE lower(name) = lower(?)
1400
+ `;
1401
+ const params = [name];
1402
+ if (kinds && kinds.length > 0) {
1403
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1404
+ params.push(...kinds);
1405
+ }
1406
+ if (languages && languages.length > 0) {
1407
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1408
+ params.push(...languages);
1409
+ }
1410
+ // Fetch enough to find co-located results among common names
1411
+ sql += ' LIMIT ?';
1412
+ params.push(Math.max(perNameLimit * 3, 50));
1413
+ const rows = this.db.prepare(sql).all(...params);
1414
+ const nameResults = [];
1415
+ for (const row of rows) {
1416
+ const node = rowToNode(row);
1417
+ if (seenIds.has(node.id))
1418
+ continue;
1419
+ // Boost results in files that also contain distinctive symbols
1420
+ const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
1421
+ nameResults.push({ node, score: row.score + coLocationBoost });
1422
+ }
1423
+ // Sort by score (co-located first), take per-name limit
1424
+ nameResults.sort((a, b) => b.score - a.score);
1425
+ for (const r of nameResults.slice(0, perNameLimit)) {
1426
+ seenIds.add(r.node.id);
1427
+ allResults.push(r);
1428
+ }
1429
+ }
1430
+ // Sort all results by score so co-located results bubble up
1431
+ allResults.sort((a, b) => b.score - a.score);
1432
+ return allResults.slice(0, limit);
1433
+ }
1434
+ /**
1435
+ * Find nodes whose name contains a substring (LIKE-based).
1436
+ * Useful for CamelCase-part matching where FTS fails because
1437
+ * e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
1438
+ *
1439
+ * Results are ordered by name length (shorter = more likely to be the core type).
1440
+ */
1441
+ findNodesByNameSubstring(substring, options = {}) {
1442
+ const { kinds, languages, limit = 30, excludePrefix } = options;
1443
+ let sql = `
1444
+ SELECT nodes.*, 1.0 as score
1445
+ FROM nodes
1446
+ WHERE name LIKE ?
1447
+ `;
1448
+ const params = [`%${substring}%`];
1449
+ // Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
1450
+ if (excludePrefix) {
1451
+ sql += ` AND name NOT LIKE ?`;
1452
+ params.push(`${substring}%`);
1453
+ }
1454
+ if (kinds && kinds.length > 0) {
1455
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1456
+ params.push(...kinds);
1457
+ }
1458
+ if (languages && languages.length > 0) {
1459
+ sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
1460
+ params.push(...languages);
1461
+ }
1462
+ sql += ' ORDER BY length(name) ASC LIMIT ?';
1463
+ params.push(limit);
1464
+ const rows = this.db.prepare(sql).all(...params);
1465
+ return rows.map((row) => ({
1466
+ node: rowToNode(row),
1467
+ score: row.score,
1468
+ }));
1469
+ }
1470
+ // ===========================================================================
1471
+ // Edge Operations
1472
+ // ===========================================================================
1473
+ /**
1474
+ * Insert a new edge
1475
+ */
1476
+ insertEdge(edge) {
1477
+ if (!this.stmts.insertEdge) {
1478
+ this.stmts.insertEdge = this.db.prepare(`
1479
+ INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
1480
+ VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
1481
+ `);
1482
+ }
1483
+ this.stmts.insertEdge.run({
1484
+ source: edge.source,
1485
+ target: edge.target,
1486
+ kind: edge.kind,
1487
+ metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
1488
+ line: edge.line ?? null,
1489
+ col: edge.column ?? null,
1490
+ provenance: edge.provenance ?? null,
1491
+ });
1492
+ }
1493
+ /**
1494
+ * Insert multiple edges in a transaction
1495
+ */
1496
+ insertEdges(edges) {
1497
+ if (edges.length === 0)
1498
+ return;
1499
+ this.db.transaction(() => {
1500
+ const endpointIds = new Set();
1501
+ for (const edge of edges) {
1502
+ endpointIds.add(edge.source);
1503
+ endpointIds.add(edge.target);
1504
+ }
1505
+ const existingNodeIds = this.getExistingNodeIds([...endpointIds]);
1506
+ const rows = [];
1507
+ for (const edge of edges) {
1508
+ if (!existingNodeIds.has(edge.source) || !existingNodeIds.has(edge.target)) {
1509
+ continue;
1510
+ }
1511
+ rows.push([
1512
+ edge.source,
1513
+ edge.target,
1514
+ edge.kind,
1515
+ edge.metadata ? JSON.stringify(edge.metadata) : null,
1516
+ edge.line ?? null,
1517
+ edge.column ?? null,
1518
+ edge.provenance ?? null,
1519
+ ]);
1520
+ }
1521
+ this.runBatched('insertEdges', 'INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance) VALUES ', '(?,?,?,?,?,?,?)', rows);
1522
+ })();
1523
+ }
1524
+ /**
1525
+ * Delete all edges from a source node
1526
+ */
1527
+ deleteEdgesBySource(sourceId) {
1528
+ if (!this.stmts.deleteEdgesBySource) {
1529
+ this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
1530
+ }
1531
+ this.stmts.deleteEdgesBySource.run(sourceId);
1532
+ }
1533
+ /**
1534
+ * Get outgoing edges from a node
1535
+ */
1536
+ getOutgoingEdges(sourceId, kinds, provenance) {
1537
+ if ((kinds && kinds.length > 0) || provenance) {
1538
+ let sql = 'SELECT * FROM edges WHERE source = ?';
1539
+ const params = [sourceId];
1540
+ if (kinds && kinds.length > 0) {
1541
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1542
+ params.push(...kinds);
1543
+ }
1544
+ if (provenance) {
1545
+ sql += ' AND provenance = ?';
1546
+ params.push(provenance);
1547
+ }
1548
+ const rows = this.db.prepare(sql).all(...params);
1549
+ return rows.map(rowToEdge);
1550
+ }
1551
+ if (!this.stmts.getEdgesBySource) {
1552
+ this.stmts.getEdgesBySource = this.db.prepare('SELECT * FROM edges WHERE source = ?');
1553
+ }
1554
+ const rows = this.stmts.getEdgesBySource.all(sourceId);
1555
+ return rows.map(rowToEdge);
1556
+ }
1557
+ /**
1558
+ * Get incoming edges to a node
1559
+ */
1560
+ getIncomingEdges(targetId, kinds) {
1561
+ if (kinds && kinds.length > 0) {
1562
+ const sql = `SELECT * FROM edges WHERE target = ? AND kind IN (${kinds.map(() => '?').join(',')})`;
1563
+ const rows = this.db.prepare(sql).all(targetId, ...kinds);
1564
+ return rows.map(rowToEdge);
1565
+ }
1566
+ if (!this.stmts.getEdgesByTarget) {
1567
+ this.stmts.getEdgesByTarget = this.db.prepare('SELECT * FROM edges WHERE target = ?');
1568
+ }
1569
+ const rows = this.stmts.getEdgesByTarget.all(targetId);
1570
+ return rows.map(rowToEdge);
1571
+ }
1572
+ /**
1573
+ * Outgoing edges for MANY source nodes in one query.
1574
+ *
1575
+ * The batch form of {@link getOutgoingEdges}. Building a nested outline needs
1576
+ * the `contains` edges of every container in a file at once; doing that one
1577
+ * source at a time is a query per symbol on files that have hundreds.
1578
+ */
1579
+ getOutgoingEdgesFrom(sourceIds, kinds) {
1580
+ if (sourceIds.length === 0)
1581
+ return [];
1582
+ const unique = [...new Set(sourceIds)];
1583
+ const out = [];
1584
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1585
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1586
+ const placeholders = chunk.map(() => '?').join(',');
1587
+ let sql = `SELECT * FROM edges WHERE source IN (${placeholders})`;
1588
+ const params = [...chunk];
1589
+ if (kinds && kinds.length > 0) {
1590
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1591
+ params.push(...kinds);
1592
+ }
1593
+ const rows = this.db.prepare(sql).all(...params);
1594
+ for (const row of rows)
1595
+ out.push(rowToEdge(row));
1596
+ }
1597
+ return out;
1598
+ }
1599
+ /**
1600
+ * Fan-in (total incoming edge count) for MANY nodes in one query.
1601
+ *
1602
+ * The per-node alternative — `getIncomingEdges(id).length` — is an indexed
1603
+ * lookup each, but a symbol screen rendering a couple of hundred callees
1604
+ * would issue a couple of hundred of them. Ids with no incoming edges are
1605
+ * absent from the map rather than present as 0, so callers can tell "no
1606
+ * edges" from "not asked about".
1607
+ */
1608
+ countIncomingEdges(ids) {
1609
+ const out = new Map();
1610
+ if (ids.length === 0)
1611
+ return out;
1612
+ const unique = [...new Set(ids)];
1613
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1614
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1615
+ const placeholders = chunk.map(() => '?').join(',');
1616
+ const rows = this.db
1617
+ .prepare(`SELECT target, COUNT(*) AS count FROM edges WHERE target IN (${placeholders}) GROUP BY target`)
1618
+ .all(...chunk);
1619
+ for (const row of rows)
1620
+ out.set(row.target, row.count);
1621
+ }
1622
+ return out;
1623
+ }
1624
+ /**
1625
+ * Incoming edges for MANY target nodes in one query — the mirror of
1626
+ * {@link getOutgoingEdgesFrom}. Needed wherever a whole file's inbound edges
1627
+ * are wanted at once ("which files import anything in this one?").
1628
+ */
1629
+ getIncomingEdgesTo(targetIds, kinds) {
1630
+ if (targetIds.length === 0)
1631
+ return [];
1632
+ const unique = [...new Set(targetIds)];
1633
+ const out = [];
1634
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1635
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1636
+ const placeholders = chunk.map(() => '?').join(',');
1637
+ let sql = `SELECT * FROM edges WHERE target IN (${placeholders})`;
1638
+ const params = [...chunk];
1639
+ if (kinds && kinds.length > 0) {
1640
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
1641
+ params.push(...kinds);
1642
+ }
1643
+ const rows = this.db.prepare(sql).all(...params);
1644
+ for (const row of rows)
1645
+ out.push(rowToEdge(row));
1646
+ }
1647
+ return out;
1648
+ }
1649
+ /**
1650
+ * Fan-out (total outgoing edge count) for MANY nodes in one query — the
1651
+ * mirror of {@link countIncomingEdges}. Ids with no outgoing edges are absent
1652
+ * from the map rather than present as 0.
1653
+ */
1654
+ countOutgoingEdges(ids) {
1655
+ const out = new Map();
1656
+ if (ids.length === 0)
1657
+ return out;
1658
+ const unique = [...new Set(ids)];
1659
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1660
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1661
+ const placeholders = chunk.map(() => '?').join(',');
1662
+ const rows = this.db
1663
+ .prepare(`SELECT source, COUNT(*) AS count FROM edges WHERE source IN (${placeholders}) GROUP BY source`)
1664
+ .all(...chunk);
1665
+ for (const row of rows)
1666
+ out.set(row.source, row.count);
1667
+ }
1668
+ return out;
1669
+ }
1670
+ /**
1671
+ * Symbols nothing in the index points at — the candidate set behind the dead
1672
+ * code list (`src/graph/dead-code.ts`).
1673
+ *
1674
+ * "Points at" is every edge kind EXCEPT `contains`: a class containing a
1675
+ * method is structure, not use, and counting it would make every member look
1676
+ * reached by its own container. A self-edge is excluded for the same reason
1677
+ * a recursive function is not its own caller.
1678
+ *
1679
+ * One scan, one index probe per candidate. `NOT EXISTS` over
1680
+ * `idx_edges_target_kind` is what keeps it that way — the alternative
1681
+ * (`LEFT JOIN edges … GROUP BY`) builds a row per edge for the whole table
1682
+ * before discarding all but the empty groups. Ordered by position so the
1683
+ * answer is stable across runs and groups by file without a second sort.
1684
+ *
1685
+ * The result is deliberately NOT called dead code: an unreferenced symbol is
1686
+ * a symbol with no STATIC reference, and the caller applies the exclusions
1687
+ * (tests, generated files, overrides, unresolved names) that turn the
1688
+ * candidate set into a claim worth making.
1689
+ */
1690
+ getUnreferencedNodes(kinds, limit) {
1691
+ if (kinds.length === 0 || limit <= 0)
1692
+ return [];
1693
+ const placeholders = kinds.map(() => '?').join(',');
1694
+ const rows = this.db
1695
+ .prepare(`SELECT n.*, COALESCE(f.generated, 0) AS file_generated
1696
+ FROM nodes n
1697
+ LEFT JOIN files f ON f.path = n.file_path
1698
+ WHERE n.kind IN (${placeholders})
1699
+ AND NOT EXISTS (
1700
+ SELECT 1 FROM edges e
1701
+ WHERE e.target = n.id
1702
+ AND e.kind != 'contains'
1703
+ AND e.source != n.id
1704
+ )
1705
+ ORDER BY n.file_path, n.start_line, n.name
1706
+ LIMIT ?`)
1707
+ .all(...kinds, limit);
1708
+ return rows.map((row) => ({ node: rowToNode(row), generated: row.file_generated === 1 }));
1709
+ }
1710
+ /**
1711
+ * Which of `names` the index holds an UNRESOLVED reference to.
1712
+ *
1713
+ * The point is honesty about our own blind spots. A `failed` row in
1714
+ * `unresolved_refs` records that some file referenced a name and the resolver
1715
+ * could not decide what it meant — so a symbol with that name cannot be
1716
+ * called unreferenced, whatever the edge table says. It is deliberately
1717
+ * matched loosely, on the reference name AND on its tail (`util.greet` →
1718
+ * `greet`), because the question being asked is "could this name be the one
1719
+ * we failed to follow", and a maybe has to count as a yes.
1720
+ *
1721
+ * Bounded-lookup like {@link getGeneratedPathsAmong}: the caller holds a
1722
+ * candidate list, so this is a chunked probe over `idx_unresolved_name`, not
1723
+ * a scan of the table.
1724
+ */
1725
+ getUnresolvedNamesAmong(names) {
1726
+ const unique = [...new Set(names)].filter((name) => name.length > 0);
1727
+ const found = new Set();
1728
+ if (unique.length === 0)
1729
+ return found;
1730
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1731
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1732
+ const placeholders = chunk.map(() => '?').join(',');
1733
+ const rows = this.db
1734
+ .prepare(`SELECT DISTINCT reference_name AS name FROM unresolved_refs
1735
+ WHERE reference_name IN (${placeholders})
1736
+ UNION
1737
+ SELECT DISTINCT name_tail AS name FROM unresolved_refs
1738
+ WHERE name_tail IN (${placeholders})`)
1739
+ .all(...chunk, ...chunk);
1740
+ for (const row of rows)
1741
+ found.add(row.name);
1742
+ }
1743
+ return found;
1744
+ }
1745
+ /**
1746
+ * Which of `names` are carried by MORE THAN ONE symbol, at least one of which
1747
+ * something points at.
1748
+ *
1749
+ * The false positive this exists to kill: `CodeGraph.getTopRouteFile` calls
1750
+ * `this.queries.getTopRouteFile()`, and the resolver — which prefers a
1751
+ * same-name definition in the call site's own file — attaches that edge to
1752
+ * the *calling* method. One of the two ends up with a self-edge and the other
1753
+ * with nothing at all, and neither is unreferenced. From the edge table the
1754
+ * mis-resolution and a genuinely unused twin are the same picture, so the
1755
+ * claim is not made about either.
1756
+ *
1757
+ * Both halves of the condition are load-bearing. **More than one symbol**:
1758
+ * a uniquely-named function that only calls itself is genuinely dead, and
1759
+ * excluding every recursive function would gut the list. **Self-edges
1760
+ * counted**: the self-edge IS the fingerprint of the mis-resolution above, so
1761
+ * it has to count as evidence that this name resolves somewhere.
1762
+ *
1763
+ * Chunked probe over `idx_nodes_name`, bounded by the caller's candidate list.
1764
+ */
1765
+ getAmbiguousReferencedNames(names) {
1766
+ const unique = [...new Set(names)].filter((name) => name.length > 0);
1767
+ const found = new Set();
1768
+ if (unique.length === 0)
1769
+ return found;
1770
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1771
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1772
+ const placeholders = chunk.map(() => '?').join(',');
1773
+ const rows = this.db
1774
+ .prepare(`SELECT name FROM (
1775
+ SELECT n.name AS name,
1776
+ EXISTS (
1777
+ SELECT 1 FROM edges e
1778
+ WHERE e.target = n.id AND e.kind != 'contains'
1779
+ ) AS referenced
1780
+ FROM nodes n
1781
+ WHERE n.name IN (${placeholders})
1782
+ )
1783
+ GROUP BY name
1784
+ HAVING COUNT(*) > 1 AND SUM(referenced) > 0`)
1785
+ .all(...chunk);
1786
+ for (const row of rows)
1787
+ found.add(row.name);
1788
+ }
1789
+ return found;
1790
+ }
1791
+ /**
1792
+ * Which of the given languages the index records an EXPORT marker for.
1793
+ *
1794
+ * A self-measurement, and the honest basis for a whole class of exclusion.
1795
+ * The dead code report's strongest filter is "exported symbols may be reached
1796
+ * from outside this repository" — and that filter silently does nothing for a
1797
+ * language whose exports are not recorded, either because the extractor does
1798
+ * not record them (Rust `pub`) or because the language has no such concept at
1799
+ * all (Python, C, Ruby: the header or the module IS the surface). Rather than
1800
+ * carry a table of which is which, ask the index: if nothing in this language
1801
+ * is marked exported, the filter did not run, and no claim about outside
1802
+ * reachability can be made for it.
1803
+ *
1804
+ * `idx_nodes_language` covers the grouping; the caller passes the handful of
1805
+ * languages its candidates are actually in.
1806
+ */
1807
+ getLanguagesWithExports(languages) {
1808
+ const unique = [...new Set(languages)].filter((language) => language.length > 0);
1809
+ const found = new Set();
1810
+ if (unique.length === 0)
1811
+ return found;
1812
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
1813
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
1814
+ const placeholders = chunk.map(() => '?').join(',');
1815
+ const rows = this.db
1816
+ .prepare(`SELECT language, MAX(is_exported) AS any_exported
1817
+ FROM nodes
1818
+ WHERE language IN (${placeholders})
1819
+ GROUP BY language`)
1820
+ .all(...chunk);
1821
+ for (const row of rows)
1822
+ if (row.any_exported === 1)
1823
+ found.add(row.language);
1824
+ }
1825
+ return found;
1826
+ }
1827
+ /**
1828
+ * The nodes with the most DISTINCT dependents, most first.
1829
+ *
1830
+ * "Distinct" is the difference that matters: a helper called forty times from
1831
+ * one function has a fan-in of 40 but exactly one dependent. This counts the
1832
+ * second thing — the number a reader means by "N callers" — so the top of
1833
+ * this list is the set of symbols a change actually radiates furthest from.
1834
+ *
1835
+ * `contains` is excluded because it is structure, not dependency: counting it
1836
+ * would rank every file and class above the code they hold.
1837
+ */
1838
+ getTopDependedOn(limit) {
1839
+ if (limit <= 0)
1840
+ return [];
1841
+ const rows = this.db
1842
+ .prepare(`SELECT target AS nodeId, COUNT(DISTINCT source) AS dependents
1843
+ FROM edges
1844
+ WHERE kind != 'contains' AND source != target
1845
+ GROUP BY target
1846
+ ORDER BY dependents DESC
1847
+ LIMIT ?`)
1848
+ .all(limit);
1849
+ return rows;
1850
+ }
1851
+ /**
1852
+ * The graph's executable roots — files that RUN something at module level,
1853
+ * ranked by how much of the project they set in motion.
1854
+ *
1855
+ * The engine records a statement at the top level of a file as an edge from
1856
+ * the *file* node, so `src/bin/codegraph.ts` calling `program.parse()` at
1857
+ * module scope is a `calls` edge out of a `file`. That set is what makes the
1858
+ * roots of a dependency graph visible: a library module holds definitions and
1859
+ * runs nothing until someone imports it, while a CLI, a worker entry or a
1860
+ * build script does its work on the way down the file. `instantiates` counts
1861
+ * the same way — `new Server(...)` at module scope is the same act.
1862
+ *
1863
+ * Ranking multiplies the two things an entry point does: it runs (calls), and
1864
+ * it wires the project together (distinct other files its symbols reach). One
1865
+ * alone is misleading — a registration table makes hundreds of module-level
1866
+ * calls into itself, and a barrel file imports everything and runs nothing.
1867
+ * The product puts the file that does both at the top.
1868
+ */
1869
+ getTopCallingFiles(limit) {
1870
+ if (limit <= 0)
1871
+ return [];
1872
+ return this.db
1873
+ .prepare(`WITH runs AS (
1874
+ SELECT e.source AS id, COUNT(*) AS calls
1875
+ FROM edges e
1876
+ JOIN nodes n ON n.id = e.source
1877
+ WHERE n.kind = 'file' AND e.kind IN ('calls', 'instantiates')
1878
+ GROUP BY e.source
1879
+ ),
1880
+ cand AS (
1881
+ SELECT r.id AS id, n.file_path AS fp, r.calls AS calls
1882
+ FROM runs r JOIN nodes n ON n.id = r.id
1883
+ ),
1884
+ wires AS (
1885
+ SELECT sn.file_path AS fp, COUNT(DISTINCT tn.file_path) AS reaches
1886
+ FROM edges e
1887
+ JOIN nodes sn ON sn.id = e.source
1888
+ JOIN nodes tn ON tn.id = e.target
1889
+ WHERE e.kind != 'contains'
1890
+ AND sn.file_path <> tn.file_path
1891
+ AND sn.file_path IN (SELECT fp FROM cand)
1892
+ GROUP BY sn.file_path
1893
+ )
1894
+ SELECT c.id AS nodeId,
1895
+ c.fp AS filePath,
1896
+ c.calls AS calls,
1897
+ COALESCE(w.reaches, 0) AS reaches,
1898
+ c.calls * (1 + COALESCE(w.reaches, 0)) AS score
1899
+ FROM cand c LEFT JOIN wires w ON w.fp = c.fp
1900
+ ORDER BY score DESC, calls DESC, filePath
1901
+ LIMIT ?`)
1902
+ .all(limit);
1903
+ }
1904
+ /**
1905
+ * How many OTHER files depend on each of the given files.
1906
+ *
1907
+ * Counted through the symbols, not the file nodes: an `imports` edge points
1908
+ * at the imported symbol, so a file node almost never receives one and
1909
+ * counting edges into it would report every file as depended on by nobody.
1910
+ * Same-file edges are excluded, which is what makes zero mean "nothing else
1911
+ * in the index reaches into this file" — the honest reading of a root.
1912
+ */
1913
+ getFileDependentCounts(filePaths) {
1914
+ if (filePaths.length === 0)
1915
+ return [];
1916
+ return this.db
1917
+ .prepare(`SELECT tn.file_path AS filePath, COUNT(DISTINCT sn.file_path) AS dependents
1918
+ FROM edges e
1919
+ JOIN nodes tn ON tn.id = e.target
1920
+ JOIN nodes sn ON sn.id = e.source
1921
+ WHERE e.kind != 'contains'
1922
+ AND tn.file_path IN (SELECT value FROM json_each(?))
1923
+ AND sn.file_path <> tn.file_path
1924
+ GROUP BY tn.file_path`)
1925
+ .all(JSON.stringify(filePaths));
1926
+ }
1927
+ /**
1928
+ * How far each of the given files reaches OUT: distinct other files its
1929
+ * symbols touch, and how many references that is.
1930
+ *
1931
+ * The mirror of {@link getFileDependentCounts}, and the same reasoning about
1932
+ * `contains` and same-file edges applies. It is driven from `nodes` rather
1933
+ * than from `edges` so the work is proportional to the files asked about —
1934
+ * the entry-points endpoint asks it about every test file in the index, and
1935
+ * an edge-first plan would scan the whole table to answer a question about a
1936
+ * tenth of it.
1937
+ */
1938
+ getFileReachCounts(filePaths) {
1939
+ if (filePaths.length === 0)
1940
+ return [];
1941
+ return this.db
1942
+ .prepare(`SELECT sn.file_path AS filePath,
1943
+ COUNT(DISTINCT tn.file_path) AS reaches,
1944
+ COUNT(*) AS refs
1945
+ FROM nodes sn
1946
+ JOIN edges e ON e.source = sn.id
1947
+ JOIN nodes tn ON tn.id = e.target
1948
+ WHERE sn.file_path IN (SELECT value FROM json_each(?))
1949
+ AND e.kind != 'contains'
1950
+ AND tn.file_path <> sn.file_path
1951
+ GROUP BY sn.file_path`)
1952
+ .all(JSON.stringify(filePaths));
1953
+ }
1954
+ /**
1955
+ * The `file` nodes for the given paths, in one query.
1956
+ *
1957
+ * A file's own node is what makes a file row navigable, and looking it up
1958
+ * with {@link getNodesInFile} means materialising every symbol in the file to
1959
+ * throw all but one away.
1960
+ */
1961
+ getFileNodes(filePaths) {
1962
+ if (filePaths.length === 0)
1963
+ return [];
1964
+ const rows = this.db
1965
+ .prepare(`SELECT * FROM nodes
1966
+ WHERE kind = 'file'
1967
+ AND file_path IN (SELECT value FROM json_each(?))`)
1968
+ .all(JSON.stringify(filePaths));
1969
+ return rows.map(rowToNode);
1970
+ }
1971
+ /**
1972
+ * Roll the whole edge table up to module granularity in one pass.
1973
+ *
1974
+ * The caller decides what a module IS — it hands in a file → module
1975
+ * assignment and gets back the cross-module traffic. That split is
1976
+ * deliberate: naming modules is a *policy* (top-level directories, a façade
1977
+ * file kept separate, a monorepo root) that belongs where the reader lives,
1978
+ * while grouping a million edges by it is *mechanics* that must happen in
1979
+ * SQLite. Doing the fold in JavaScript instead means materialising every
1980
+ * cross-file edge in memory; doing the naming in SQL means a tower of
1981
+ * `instr`/`substr` no one can read.
1982
+ *
1983
+ * The assignment lands in a TEMP table with a primary key, so the join is
1984
+ * indexed and the result set is bounded by modules², not by edges. Temp
1985
+ * tables live in SQLite's own temp database, so this stays valid against a
1986
+ * read-only main.
1987
+ *
1988
+ * Two result sets, because they need two different groupings over the same
1989
+ * join: `links` counts edges per (module, module, kind), and `pairs` names
1990
+ * the busiest symbol pairs behind each link (the map's tooltip). `pairs` is
1991
+ * ranked and cut inside SQLite — the un-cut grouping is the one thing here
1992
+ * that scales with distinct symbol names rather than with modules. Pairs are
1993
+ * ranked by `declared` before raw count, so a link's tooltip names the
1994
+ * symbols the source actually points at rather than whichever `has`/`get`
1995
+ * happened to name-match most often.
1996
+ *
1997
+ * `declared` is the subset of a link's edges that came from something the
1998
+ * source *writes down*: an import, a qualified name, an inheritance clause,
1999
+ * or a call through a typed receiver. It exists because bare name matching
2000
+ * (`resolvedBy: 'exact-match'`) is what invents cross-module links out of
2001
+ * common method names — `run`, `push`, `finish` — and a map that lets those
2002
+ * decide the layering puts the storage layer above the CLI.
2003
+ */
2004
+ aggregateModuleGraph(assignments, options) {
2005
+ if (assignments.length === 0 || options.kinds.length === 0)
2006
+ return { links: [], pairs: [] };
2007
+ const CONFIDENCE = `COALESCE(json_extract(e.metadata, '$.confidence'), 1)`;
2008
+ const DECLARED = `(json_extract(e.metadata, '$.resolvedBy') IN ('import', 'qualified-name')
2009
+ OR e.kind IN ('extends', 'implements')
2010
+ OR (json_extract(e.metadata, '$.resolvedBy') = 'instance-method'
2011
+ AND ${CONFIDENCE} >= 0.9))`;
2012
+ this.db.exec('DROP TABLE IF EXISTS temp.cg_module_map');
2013
+ this.db.exec('CREATE TEMP TABLE cg_module_map (path TEXT PRIMARY KEY, mod TEXT NOT NULL)');
2014
+ try {
2015
+ const insert = this.db.prepare('INSERT OR REPLACE INTO cg_module_map (path, mod) VALUES (?, ?)');
2016
+ this.db.exec('BEGIN');
2017
+ try {
2018
+ for (const row of assignments)
2019
+ insert.run(row.filePath, row.module);
2020
+ this.db.exec('COMMIT');
2021
+ }
2022
+ catch (err) {
2023
+ this.db.exec('ROLLBACK');
2024
+ throw err;
2025
+ }
2026
+ // ONE pass over the edge table. Grouping by the symbol names as well as
2027
+ // the modules costs nothing extra in scan time — the join is what is
2028
+ // expensive — and it buys both results from a single scan. Measured on
2029
+ // this index inflated to 1.6M edges: 1.66s for this query against 3.0s
2030
+ // for the module-level and name-level queries run separately, which is
2031
+ // the difference between meeting and missing the map's cold budget on a
2032
+ // ten-thousand-file repository.
2033
+ const rows = this.db
2034
+ .prepare(`SELECT ms.mod AS source, mt.mod AS target, e.kind AS kind,
2035
+ sn.name AS "from", tn.name AS "to",
2036
+ SUM(CASE WHEN ${CONFIDENCE} >= ? THEN 1 ELSE 0 END) AS count,
2037
+ SUM(CASE WHEN ${CONFIDENCE} >= ? AND ${DECLARED} THEN 1 ELSE 0 END) AS declared,
2038
+ SUM(CASE WHEN ${CONFIDENCE} < ? THEN 1 ELSE 0 END) AS uncertain
2039
+ FROM edges e
2040
+ JOIN nodes sn ON sn.id = e.source
2041
+ JOIN nodes tn ON tn.id = e.target
2042
+ JOIN cg_module_map ms ON ms.path = sn.file_path
2043
+ JOIN cg_module_map mt ON mt.path = tn.file_path
2044
+ WHERE e.kind IN (SELECT value FROM json_each(?))
2045
+ AND ms.mod <> mt.mod
2046
+ GROUP BY ms.mod, mt.mod, e.kind, sn.name, tn.name`)
2047
+ .all(options.minConfidence, options.minConfidence, options.minConfidence, JSON.stringify(options.kinds));
2048
+ return foldModuleRows(rows, options);
2049
+ }
2050
+ finally {
2051
+ this.db.exec('DROP TABLE IF EXISTS temp.cg_module_map');
2052
+ }
2053
+ }
2054
+ /**
2055
+ * Every ordered pair of files where one reaches into the other, once each.
2056
+ *
2057
+ * The input a cycle finder wants: file-level circular dependencies are the
2058
+ * strongly connected components of this graph. One query instead of the
2059
+ * dependency lookup per file that {@link GraphQueryManager.findCircularDependencies}
2060
+ * does — which matters because a cycle report is only interesting on a large
2061
+ * repo, and that is exactly where a query per file stops being affordable.
2062
+ *
2063
+ * `contains` is excluded (a file "contains" its own symbols, which is not a
2064
+ * dependency), and so are same-file edges and low-confidence name matches:
2065
+ * a cycle conjured by a common method name is a false alarm a reader cannot
2066
+ * check.
2067
+ */
2068
+ getCrossFileDependencyPairs(minConfidence) {
2069
+ return this.db
2070
+ .prepare(`SELECT DISTINCT sn.file_path AS source, tn.file_path AS target
2071
+ FROM edges e
2072
+ JOIN nodes sn ON sn.id = e.source
2073
+ JOIN nodes tn ON tn.id = e.target
2074
+ WHERE e.kind <> 'contains'
2075
+ AND sn.file_path <> tn.file_path
2076
+ AND COALESCE(json_extract(e.metadata, '$.confidence'), 1) >= ?`)
2077
+ .all(minConfidence);
2078
+ }
2079
+ /**
2080
+ * Every unresolved reference recorded in one FILE, ordered by line.
2081
+ *
2082
+ * The per-symbol form above answers "what does this body reach that the
2083
+ * index does not hold". A whole-file reader asks the same question of every
2084
+ * line at once, and asking it one symbol at a time is a query per symbol —
2085
+ * 153 of them on this repo's largest file. `unresolved_refs.file_path` is
2086
+ * indexed, so this is one lookup whatever the file holds.
2087
+ *
2088
+ * `limit` bounds the answer rather than the work: the caller draws a marker
2089
+ * per row, and a generated file with fifty thousand of them would ship
2090
+ * megabytes to say something a count already says. Rows come back in line
2091
+ * order, so a cap trims the END of the file, which is at least legible.
2092
+ */
2093
+ getUnresolvedReferencesInFile(filePath, limit = 5000) {
2094
+ if (!this.stmts.getUnresolvedInFile) {
2095
+ this.stmts.getUnresolvedInFile = this.db.prepare('SELECT * FROM unresolved_refs WHERE file_path = ? ORDER BY line, col LIMIT ?');
2096
+ }
2097
+ const rows = this.stmts.getUnresolvedInFile.all(filePath, limit);
2098
+ return rows.map((row) => ({
2099
+ fromNodeId: row.from_node_id,
2100
+ referenceName: row.reference_name,
2101
+ referenceKind: row.reference_kind,
2102
+ line: row.line,
2103
+ column: row.col,
2104
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2105
+ filePath: row.file_path,
2106
+ language: row.language,
2107
+ rowId: row.id,
2108
+ }));
2109
+ }
2110
+ /**
2111
+ * References recorded against a symbol that never resolved to a node — the
2112
+ * calls and type mentions that leave the index (a third-party package, a
2113
+ * runtime builtin, a language construct extraction doesn't model).
2114
+ *
2115
+ * Read-only. It exists so a reader can say "N calls into symbols outside the
2116
+ * index" instead of silently showing a callee list shorter than the body's
2117
+ * call sites, which reads as "nothing else happens here".
2118
+ */
2119
+ getUnresolvedReferencesFrom(fromNodeId) {
2120
+ if (!this.stmts.getUnresolvedFromNode) {
2121
+ this.stmts.getUnresolvedFromNode = this.db.prepare('SELECT * FROM unresolved_refs WHERE from_node_id = ?');
2122
+ }
2123
+ const rows = this.stmts.getUnresolvedFromNode.all(fromNodeId);
2124
+ return rows.map((row) => ({
2125
+ fromNodeId: row.from_node_id,
2126
+ referenceName: row.reference_name,
2127
+ referenceKind: row.reference_kind,
2128
+ line: row.line,
2129
+ column: row.col,
2130
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2131
+ filePath: row.file_path,
2132
+ language: row.language,
2133
+ rowId: row.id,
2134
+ }));
2135
+ }
2136
+ /**
2137
+ * Find all edges where both source and target are in the given node set.
2138
+ * Useful for recovering inter-node connectivity after BFS.
2139
+ */
2140
+ findEdgesBetweenNodes(nodeIds, kinds) {
2141
+ if (nodeIds.length === 0)
2142
+ return [];
2143
+ const idsJson = JSON.stringify(nodeIds);
2144
+ let sql = `SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?)) AND target IN (SELECT value FROM json_each(?))`;
2145
+ const params = [idsJson, idsJson];
2146
+ if (kinds && kinds.length > 0) {
2147
+ sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
2148
+ params.push(...kinds);
2149
+ }
2150
+ const rows = this.db.prepare(sql).all(...params);
2151
+ return rows.map(rowToEdge);
2152
+ }
2153
+ /**
2154
+ * Distinct file paths that DEPEND ON `filePath`: every file containing a
2155
+ * symbol with a cross-file edge (any kind except `contains`) into a symbol
2156
+ * of this file. This is the file-level projection of the symbol dependency
2157
+ * graph and the basis for blast-radius / `affected` test selection.
2158
+ *
2159
+ * It deliberately does NOT restrict to `imports` edges. In this graph an
2160
+ * `imports` edge connects a file to its own local import declarations
2161
+ * (it is always same-file), so an imports-only lookup returns zero
2162
+ * cross-file dependents for every file. The real cross-file dependency
2163
+ * signal is the resolved call/reference graph — calls, references,
2164
+ * instantiates, extends, implements, overrides, type_of, returns,
2165
+ * decorates — exactly what {@link GraphTraverser.getImpactRadius} traverses.
2166
+ * `contains` is excluded: a parent containing a symbol does not *depend* on
2167
+ * it. One indexed query (idx_nodes_file_path + idx_edges_target_kind).
2168
+ */
2169
+ getDependentFilePaths(filePath) {
2170
+ const sql = `SELECT DISTINCT src.file_path AS fp
2171
+ FROM edges e
2172
+ JOIN nodes tgt ON tgt.id = e.target
2173
+ JOIN nodes src ON src.id = e.source
2174
+ WHERE tgt.file_path = ?
2175
+ AND e.kind != 'contains'
2176
+ AND src.file_path != ?`;
2177
+ const rows = this.db.prepare(sql).all(filePath, filePath);
2178
+ return rows.map((r) => r.fp);
2179
+ }
2180
+ /**
2181
+ * Distinct file paths that `filePath` DEPENDS ON — the inverse of
2182
+ * {@link getDependentFilePaths}: every file containing a symbol that a
2183
+ * symbol of this file has a cross-file edge into. Same edge-kind rules
2184
+ * (all kinds except `contains`); same reason imports-only is insufficient.
2185
+ */
2186
+ getDependencyFilePaths(filePath) {
2187
+ const sql = `SELECT DISTINCT tgt.file_path AS fp
2188
+ FROM edges e
2189
+ JOIN nodes src ON src.id = e.source
2190
+ JOIN nodes tgt ON tgt.id = e.target
2191
+ WHERE src.file_path = ?
2192
+ AND e.kind != 'contains'
2193
+ AND tgt.file_path != ?`;
2194
+ const rows = this.db.prepare(sql).all(filePath, filePath);
2195
+ return rows.map((r) => r.fp);
2196
+ }
2197
+ /**
2198
+ * Cross-file edges whose TARGET is a node in `filePath` and whose SOURCE is a
2199
+ * node in a *different* file, paired with the target node's (name, kind) so a
2200
+ * caller can re-resolve the edge to the re-indexed target's new ID (node IDs
2201
+ * are `sha256(filePath:kind:name:line)`, so any line shift in the callee file
2202
+ * changes target IDs and a naive re-insert by old ID silently drops them).
2203
+ * Used by `storeExtractionResult` to preserve incoming edges across a file
2204
+ * re-index (issue #899). Same edge-kind rules as
2205
+ * {@link getDependentFilePaths}: all kinds except `contains`.
2206
+ */
2207
+ getCrossFileIncomingEdgesWithTarget(filePath) {
2208
+ const sql = `SELECT e.*, tgt.name AS target_name, tgt.kind AS target_kind,
2209
+ src.file_path AS source_file_path, src.language AS source_language
2210
+ FROM edges e
2211
+ JOIN nodes tgt ON tgt.id = e.target
2212
+ JOIN nodes src ON src.id = e.source
2213
+ WHERE tgt.file_path = ?
2214
+ AND e.kind != 'contains'
2215
+ AND src.file_path != ?`;
2216
+ const rows = this.db.prepare(sql).all(filePath, filePath);
2217
+ return rows.map(row => ({
2218
+ ...rowToEdge(row),
2219
+ targetName: row.target_name,
2220
+ targetKind: row.target_kind,
2221
+ sourceFilePath: row.source_file_path,
2222
+ sourceLanguage: row.source_language,
2223
+ }));
2224
+ }
2225
+ // ===========================================================================
2226
+ // File Operations
2227
+ // ===========================================================================
2228
+ /**
2229
+ * Insert or update a file record
2230
+ */
2231
+ upsertFile(file) {
2232
+ if (!this.stmts.upsertFile) {
2233
+ this.stmts.upsertFile = this.db.prepare(`
2234
+ INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors, generated)
2235
+ VALUES (@path, @contentHash, @language, @size, @modifiedAt, @indexedAt, @nodeCount, @errors, @generated)
2236
+ ON CONFLICT(path) DO UPDATE SET
2237
+ content_hash = @contentHash,
2238
+ language = @language,
2239
+ size = @size,
2240
+ modified_at = @modifiedAt,
2241
+ indexed_at = @indexedAt,
2242
+ node_count = @nodeCount,
2243
+ errors = @errors,
2244
+ generated = @generated
2245
+ `);
2246
+ }
2247
+ this.stmts.upsertFile.run({
2248
+ path: file.path,
2249
+ contentHash: file.contentHash,
2250
+ language: file.language,
2251
+ size: file.size,
2252
+ modifiedAt: file.modifiedAt,
2253
+ indexedAt: file.indexedAt,
2254
+ nodeCount: file.nodeCount,
2255
+ errors: file.errors ? JSON.stringify(file.errors) : null,
2256
+ // The upsert always REWRITES the flag: a file that loses its banner in an
2257
+ // edit must lose the flag on the next sync, not keep a stale 1.
2258
+ generated: file.generated ? 1 : 0,
2259
+ });
2260
+ }
2261
+ /**
2262
+ * Which of `filePaths` the index flagged as tool-generated (schema v9+).
2263
+ *
2264
+ * Bounded-lookup by design: every consumer already holds a short candidate
2265
+ * list (a ranked file group, an FTS result page, a LIMIT-20 aggregate), so
2266
+ * this stays a partial-index probe over a handful of paths — no whole-repo
2267
+ * set to materialize, and no cache to invalidate, which means a ranking call
2268
+ * can never serve a verdict the last sync already replaced.
2269
+ *
2270
+ * Returns ONLY the content/index signal; callers union it with
2271
+ * {@link isGeneratedFile} so pre-v9 databases (column present, all zeros
2272
+ * until a re-index) keep the path-only behavior rather than regressing.
2273
+ */
2274
+ getGeneratedPathsAmong(filePaths) {
2275
+ const unique = [...new Set(filePaths)];
2276
+ const found = new Set();
2277
+ if (unique.length === 0)
2278
+ return found;
2279
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2280
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2281
+ const placeholders = chunk.map(() => '?').join(',');
2282
+ const rows = this.db
2283
+ .prepare(`SELECT path FROM files WHERE generated = 1 AND path IN (${placeholders})`)
2284
+ .all(...chunk);
2285
+ for (const row of rows)
2286
+ found.add(row.path);
2287
+ }
2288
+ return found;
2289
+ }
2290
+ /**
2291
+ * A reusable `(path) => boolean` over a bounded candidate list, unioning the
2292
+ * indexed flag with the path convention. This is the shape every ranking
2293
+ * comparator wants: one query up front, then O(1) per comparison.
2294
+ */
2295
+ generatedPredicateFor(filePaths) {
2296
+ const flagged = this.getGeneratedPathsAmong(filePaths);
2297
+ return (filePath) => flagged.has(filePath) || (0, generated_detection_1.isGeneratedFile)(filePath);
2298
+ }
2299
+ /**
2300
+ * Which of `filePaths` are AMBIENT DECLARATION files — they declare nothing
2301
+ * but types, and nothing in the index depends on them (CG-28). A hand-written
2302
+ * ambient `.d.ts` of global shims, a vendored typings file, module
2303
+ * augmentation: reachable only by name, structurally attached to nothing.
2304
+ *
2305
+ * Structural, not extension-based, so a hand-written `types.ts` and a `.d.ts`
2306
+ * are judged by the same rule and a `.d.ts` that does declare a class or a
2307
+ * const is (correctly) not caught. Four conditions, all required:
2308
+ *
2309
+ * 1. it declares at least one symbol — an empty or unparsed file is not a
2310
+ * declaration file, it is a file we know nothing about;
2311
+ * 2. EVERY declared symbol is a type-level kind (interface / type alias /
2312
+ * enum / namespace). The narrowness is deliberate and measured: a rule
2313
+ * of "no callables" alone flags 1–18% of a repo, including Kotlin sealed
2314
+ * classes, Rust `mod.rs` re-exports and django's locale constant tables —
2315
+ * real source that must not be demoted. This rule flags 0–4%;
2316
+ * 3. no symbol in it originates a `calls`/`instantiates` edge — the direct
2317
+ * evidence that nothing here has a body;
2318
+ * 4. NOTHING ELSE IN THE INDEX points at it. This is the condition that
2319
+ * separates an ambient shim from a working type module, and it is why
2320
+ * the flag is narrow enough to be safe: `displacement-ts`'s pipeline
2321
+ * `types.ts` passes 1–3 identically but carries 13 inbound imports and
2322
+ * 21 references, so the files that answer a query about the pipeline are
2323
+ * typed BY it — it is part of that answer's structure. An ambient
2324
+ * `declare global` shim has zero. Deliberately index-wide rather than
2325
+ * restricted to the candidate list: the file that imports it is usually
2326
+ * not itself a candidate.
2327
+ *
2328
+ * Bounded-lookup like {@link getGeneratedPathsAmong}: callers hold a ranked
2329
+ * candidate list, so this is a partial-index probe over a handful of paths.
2330
+ */
2331
+ getAmbientDeclarationPathsAmong(filePaths) {
2332
+ const unique = [...new Set(filePaths)];
2333
+ const found = new Set();
2334
+ if (unique.length === 0)
2335
+ return found;
2336
+ for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2337
+ const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2338
+ const placeholders = chunk.map(() => '?').join(',');
2339
+ // `file`/`import`/`export`/`parameter` are structural bookkeeping, not
2340
+ // things the file declares, so they neither qualify nor disqualify.
2341
+ const rows = this.db
2342
+ .prepare(`
2343
+ SELECT file_path,
2344
+ SUM(CASE WHEN kind NOT IN ('file','import','export','parameter')
2345
+ THEN 1 ELSE 0 END) AS declared,
2346
+ SUM(CASE WHEN kind IN ('interface','type_alias','enum','enum_member','namespace')
2347
+ THEN 1 ELSE 0 END) AS typeDeclared
2348
+ FROM nodes
2349
+ WHERE file_path IN (${placeholders})
2350
+ GROUP BY file_path
2351
+ `)
2352
+ .all(...chunk);
2353
+ let candidates = rows
2354
+ .filter((r) => r.declared > 0 && r.declared === r.typeDeclared)
2355
+ .map((r) => r.file_path);
2356
+ if (candidates.length === 0)
2357
+ continue;
2358
+ const disqualify = (sql) => {
2359
+ if (candidates.length === 0)
2360
+ return;
2361
+ const hit = new Set(this.db
2362
+ .prepare(sql.replace('$IN$', candidates.map(() => '?').join(',')))
2363
+ .all(...candidates).map((r) => r.file_path));
2364
+ candidates = candidates.filter((p) => !hit.has(p));
2365
+ };
2366
+ // (3) originates behaviour
2367
+ disqualify(`
2368
+ SELECT DISTINCT n.file_path AS file_path
2369
+ FROM edges e JOIN nodes n ON n.id = e.source
2370
+ WHERE e.kind IN ('calls','instantiates') AND n.file_path IN ($IN$)
2371
+ `);
2372
+ // (4) something outside the file depends on it
2373
+ disqualify(`
2374
+ SELECT DISTINCT t.file_path AS file_path
2375
+ FROM edges e JOIN nodes t ON t.id = e.target JOIN nodes s ON s.id = e.source
2376
+ WHERE t.file_path IN ($IN$) AND s.file_path <> t.file_path
2377
+ `);
2378
+ for (const path of candidates)
2379
+ found.add(path);
2380
+ }
2381
+ return found;
2382
+ }
2383
+ /**
2384
+ * A reusable `(path) => boolean` ambient-declaration test over a bounded
2385
+ * candidate list — the shape a ranking comparator wants: one query up front,
2386
+ * O(1) per comparison.
2387
+ */
2388
+ ambientDeclarationPredicateFor(filePaths) {
2389
+ const flagged = this.getAmbientDeclarationPathsAmong(filePaths);
2390
+ return (filePath) => flagged.has(filePath);
2391
+ }
2392
+ /** How many indexed files carry the generated flag. Surfaced by `status`. */
2393
+ countGeneratedFiles() {
2394
+ const row = this.db
2395
+ .prepare('SELECT COUNT(*) AS n FROM files WHERE generated = 1')
2396
+ .get();
2397
+ return row?.n ?? 0;
2398
+ }
2399
+ /**
2400
+ * Delete a file record and its nodes
2401
+ */
2402
+ deleteFile(filePath) {
2403
+ this.db.transaction(() => {
2404
+ this.deleteNodesByFile(filePath);
2405
+ if (!this.stmts.deleteFile) {
2406
+ this.stmts.deleteFile = this.db.prepare('DELETE FROM files WHERE path = ?');
2407
+ }
2408
+ this.stmts.deleteFile.run(filePath);
2409
+ })();
2410
+ }
2411
+ /**
2412
+ * Get a file record by path
2413
+ */
2414
+ getFileByPath(filePath) {
2415
+ if (!this.stmts.getFileByPath) {
2416
+ this.stmts.getFileByPath = this.db.prepare('SELECT * FROM files WHERE path = ?');
2417
+ }
2418
+ const row = this.stmts.getFileByPath.get(filePath);
2419
+ return row ? rowToFileRecord(row) : null;
2420
+ }
2421
+ /**
2422
+ * Get all tracked files
2423
+ */
2424
+ getAllFiles() {
2425
+ if (!this.stmts.getAllFiles) {
2426
+ this.stmts.getAllFiles = this.db.prepare('SELECT * FROM files ORDER BY path');
2427
+ }
2428
+ const rows = this.stmts.getAllFiles.all();
2429
+ return rows.map(rowToFileRecord);
2430
+ }
2431
+ /**
2432
+ * Most recent index timestamp (ms since epoch) across all tracked files, or
2433
+ * null when nothing is indexed yet. One indexed aggregate, no per-row scan. (#329)
2434
+ */
2435
+ getLastIndexedAt() {
2436
+ const row = this.db
2437
+ .prepare('SELECT MAX(indexed_at) AS last FROM files')
2438
+ .get();
2439
+ return row?.last ?? null;
2440
+ }
2441
+ /**
2442
+ * The index's revision marker: how far the last sync got, and how many files
2443
+ * it left behind — one query, both numbers.
2444
+ *
2445
+ * This is the cheapest honest answer to "has the index moved since I last
2446
+ * looked". `MAX(indexed_at)` alone is not enough: a sync that only DELETES
2447
+ * files (a branch checkout that removed a directory) advances nothing, and
2448
+ * the graph the viewer is showing has still changed underneath it. The row
2449
+ * count catches exactly that case.
2450
+ */
2451
+ getIndexRevision() {
2452
+ const row = this.db
2453
+ .prepare('SELECT MAX(indexed_at) AS last, COUNT(*) AS files FROM files')
2454
+ .get();
2455
+ return { lastIndexedAt: row?.last ?? null, fileCount: row?.files ?? 0 };
2456
+ }
2457
+ /**
2458
+ * Files re-indexed strictly after `since` (ms since epoch), newest first.
2459
+ *
2460
+ * `total` is the real count; `paths` is capped at `limit`. Used by the
2461
+ * viewer's live channel to name what a sync just picked up. A file the same
2462
+ * sync DELETED cannot appear here — it has no row left — which is why the
2463
+ * caller compares {@link getIndexRevision} as well rather than treating an
2464
+ * empty list as "nothing happened".
2465
+ */
2466
+ getFilesIndexedSince(since, limit) {
2467
+ const count = this.db
2468
+ .prepare('SELECT COUNT(*) AS n FROM files WHERE indexed_at > ?')
2469
+ .get(since);
2470
+ const rows = this.db
2471
+ .prepare('SELECT path FROM files WHERE indexed_at > ? ORDER BY indexed_at DESC, path LIMIT ?')
2472
+ .all(since, Math.max(0, limit));
2473
+ return { paths: rows.map((r) => r.path), total: count?.n ?? rows.length };
2474
+ }
2475
+ /**
2476
+ * Get files that need re-indexing (hash changed)
2477
+ */
2478
+ getStaleFiles(currentHashes) {
2479
+ const files = this.getAllFiles();
2480
+ return files.filter((f) => {
2481
+ const currentHash = currentHashes.get(f.path);
2482
+ return currentHash && currentHash !== f.contentHash;
2483
+ });
2484
+ }
2485
+ // ===========================================================================
2486
+ // Unresolved References
2487
+ // ===========================================================================
2488
+ /**
2489
+ * Insert an unresolved reference
2490
+ */
2491
+ insertUnresolvedRef(ref) {
2492
+ if (!this.stmts.insertUnresolved) {
2493
+ this.stmts.insertUnresolved = this.db.prepare(`
2494
+ INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language)
2495
+ VALUES (@fromNodeId, @referenceName, @referenceKind, @line, @col, @candidates, @filePath, @language)
2496
+ `);
2497
+ }
2498
+ this.stmts.insertUnresolved.run({
2499
+ fromNodeId: ref.fromNodeId,
2500
+ referenceName: ref.referenceName,
2501
+ referenceKind: ref.referenceKind,
2502
+ line: ref.line,
2503
+ col: ref.column,
2504
+ candidates: ref.candidates ? JSON.stringify(ref.candidates) : null,
2505
+ filePath: ref.filePath ?? '',
2506
+ language: ref.language ?? 'unknown',
2507
+ });
2508
+ }
2509
+ /**
2510
+ * Insert multiple unresolved references in a transaction
2511
+ */
2512
+ insertUnresolvedRefsBatch(refs) {
2513
+ if (refs.length === 0)
2514
+ return;
2515
+ const insert = this.db.transaction(() => {
2516
+ const rows = [];
2517
+ for (const ref of refs) {
2518
+ rows.push([
2519
+ ref.fromNodeId,
2520
+ ref.referenceName,
2521
+ ref.referenceKind,
2522
+ ref.line,
2523
+ ref.column,
2524
+ ref.candidates ? JSON.stringify(ref.candidates) : null,
2525
+ ref.filePath ?? '',
2526
+ ref.language ?? 'unknown',
2527
+ ]);
2528
+ }
2529
+ this.runBatched('insertUnresolvedRefs', 'INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language) VALUES ', '(?,?,?,?,?,?,?,?)', rows);
2530
+ });
2531
+ insert();
2532
+ }
2533
+ /**
2534
+ * Delete unresolved references from a node
2535
+ */
2536
+ deleteUnresolvedByNode(nodeId) {
2537
+ if (!this.stmts.deleteUnresolvedByNode) {
2538
+ this.stmts.deleteUnresolvedByNode = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ?');
2539
+ }
2540
+ this.stmts.deleteUnresolvedByNode.run(nodeId);
2541
+ }
2542
+ /**
2543
+ * Get unresolved references by name (for resolution)
2544
+ */
2545
+ getUnresolvedByName(name) {
2546
+ if (!this.stmts.getUnresolvedByName) {
2547
+ this.stmts.getUnresolvedByName = this.db.prepare('SELECT * FROM unresolved_refs WHERE reference_name = ?');
2548
+ }
2549
+ const rows = this.stmts.getUnresolvedByName.all(name);
2550
+ return rows.map((row) => ({
2551
+ fromNodeId: row.from_node_id,
2552
+ referenceName: row.reference_name,
2553
+ referenceKind: row.reference_kind,
2554
+ line: row.line,
2555
+ column: row.col,
2556
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2557
+ filePath: row.file_path,
2558
+ language: row.language,
2559
+ rowId: row.id,
2560
+ }));
2561
+ }
2562
+ /**
2563
+ * Get all unresolved references
2564
+ */
2565
+ getUnresolvedReferences() {
2566
+ const rows = this.db.prepare('SELECT * FROM unresolved_refs').all();
2567
+ return rows.map((row) => ({
2568
+ fromNodeId: row.from_node_id,
2569
+ referenceName: row.reference_name,
2570
+ referenceKind: row.reference_kind,
2571
+ line: row.line,
2572
+ column: row.col,
2573
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2574
+ filePath: row.file_path,
2575
+ language: row.language,
2576
+ rowId: row.id,
2577
+ }));
2578
+ }
2579
+ /**
2580
+ * Get the count of PENDING (never-attempted) references without loading
2581
+ * them into memory. Rows marked status='failed' — attempted by a completed
2582
+ * pass, no match — are excluded: they are not outstanding work, only retry
2583
+ * candidates for the #1240 sweep, so they must not trip the #1187 orphan
2584
+ * sweep or the `status` pending-refs warning.
2585
+ */
2586
+ getUnresolvedReferencesCount() {
2587
+ if (!this.stmts.getUnresolvedCount) {
2588
+ this.stmts.getUnresolvedCount = this.db.prepare("SELECT COUNT(*) as count FROM unresolved_refs WHERE status = 'pending'");
2589
+ }
2590
+ const row = this.stmts.getUnresolvedCount.get();
2591
+ return row.count;
2592
+ }
2593
+ /**
2594
+ * Get a batch of PENDING unresolved references using LIMIT/OFFSET
2595
+ * pagination. Used to process references in bounded memory chunks; failed
2596
+ * rows are excluded so the batched drain loop terminates once every row
2597
+ * has been attempted.
2598
+ */
2599
+ getUnresolvedReferencesBatch(offset, limit) {
2600
+ if (!this.stmts.getUnresolvedBatch) {
2601
+ // ORDER BY rowid is load-bearing for the pipelined resolution loop: it
2602
+ // prefetches batch k+1 at OFFSET batch_k.length while batch k's rows are
2603
+ // still pending, which is only exact under a stable enumeration. (A plain
2604
+ // scan and the status index both return rowid order anyway — this pins
2605
+ // it.)
2606
+ this.stmts.getUnresolvedBatch = this.db.prepare("SELECT * FROM unresolved_refs WHERE status = 'pending' ORDER BY rowid LIMIT ? OFFSET ?");
2607
+ }
2608
+ const rows = this.stmts.getUnresolvedBatch.all(limit, offset);
2609
+ return rows.map((row) => ({
2610
+ fromNodeId: row.from_node_id,
2611
+ referenceName: row.reference_name,
2612
+ referenceKind: row.reference_kind,
2613
+ line: row.line,
2614
+ column: row.col,
2615
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2616
+ filePath: row.file_path,
2617
+ language: row.language,
2618
+ rowId: row.id,
2619
+ }));
2620
+ }
2621
+ /**
2622
+ * Keyset variant of {@link getUnresolvedReferencesBatch} for the batched
2623
+ * resolution loop: seek past the last-seen row id instead of OFFSET-walking.
2624
+ * OFFSET reads re-scan the accumulated failed-row prefix on every batch —
2625
+ * O(failed rows) per read, measured at 54.6s of the kernel-scale batch loop
2626
+ * (§7a.2) — while the seek is O(batch) forever. `id` is the rowid alias, so
2627
+ * the enumeration order is identical to the OFFSET reader's.
2628
+ */
2629
+ getUnresolvedReferencesBatchAfter(afterRowId, limit) {
2630
+ if (!this.stmts.getUnresolvedBatchAfter) {
2631
+ this.stmts.getUnresolvedBatchAfter = this.db.prepare("SELECT * FROM unresolved_refs WHERE status = 'pending' AND id > ? ORDER BY id LIMIT ?");
2632
+ }
2633
+ const rows = this.stmts.getUnresolvedBatchAfter.all(afterRowId, limit);
2634
+ return rows.map((row) => ({
2635
+ fromNodeId: row.from_node_id,
2636
+ referenceName: row.reference_name,
2637
+ referenceKind: row.reference_kind,
2638
+ line: row.line,
2639
+ column: row.col,
2640
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2641
+ filePath: row.file_path,
2642
+ language: row.language,
2643
+ rowId: row.id,
2644
+ }));
2645
+ }
2646
+ /**
2647
+ * Get all tracked file paths (lightweight — no full FileRecord objects)
2648
+ */
2649
+ getAllFilePaths() {
2650
+ if (!this.stmts.getAllFilePaths) {
2651
+ this.stmts.getAllFilePaths = this.db.prepare('SELECT path FROM files ORDER BY path');
2652
+ }
2653
+ const rows = this.stmts.getAllFilePaths.all();
2654
+ return rows.map((r) => r.path);
2655
+ }
2656
+ /**
2657
+ * Get all distinct node names (lightweight — just name strings for pre-filtering)
2658
+ */
2659
+ getAllNodeNames() {
2660
+ if (!this.stmts.getAllNodeNames) {
2661
+ this.stmts.getAllNodeNames = this.db.prepare('SELECT DISTINCT name FROM nodes');
2662
+ }
2663
+ const rows = this.stmts.getAllNodeNames.all();
2664
+ return rows.map((r) => r.name);
2665
+ }
2666
+ /**
2667
+ * Stream the distinct node names one row at a time — the incremental
2668
+ * counterpart to {@link getAllNodeNames} for callers that need to yield
2669
+ * to the event loop mid-scan (resolver cache warm-up on multi-million-node
2670
+ * indexes). Fresh statement per call: the iterator holds an open cursor.
2671
+ */
2672
+ *iterateNodeNames() {
2673
+ const stmt = this.db.prepare('SELECT DISTINCT name FROM nodes');
2674
+ for (const row of stmt.iterate()) {
2675
+ yield row.name;
2676
+ }
2677
+ }
2678
+ /**
2679
+ * Get unresolved references scoped to specific file paths.
2680
+ * Uses the idx_unresolved_file_path index for efficient lookup.
2681
+ */
2682
+ getUnresolvedReferencesByFiles(filePaths) {
2683
+ if (filePaths.length === 0)
2684
+ return [];
2685
+ // Chunk under SQLite's parameter limit: the first sync of a very large repo
2686
+ // passes every changed file here, which an unbounded `IN (...)` would bind
2687
+ // as one parameter each — exceeding MAX_VARIABLE_NUMBER and aborting with
2688
+ // "too many SQL variables". (#540)
2689
+ const rows = [];
2690
+ for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2691
+ const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2692
+ const placeholders = chunk.map(() => '?').join(',');
2693
+ const chunkRows = this.db
2694
+ .prepare(`SELECT * FROM unresolved_refs WHERE status = 'pending' AND file_path IN (${placeholders})`)
2695
+ .all(...chunk);
2696
+ // Append with a loop, never a spread: the INPUT chunk is bounded, but
2697
+ // the RESULT rows per chunk are not — a dense recovery sync (e.g. the
2698
+ // #1541 self-heal re-indexing hundreds of files) returns more rows than
2699
+ // V8 allows as arguments, and `push(...chunkRows)` dies with "Maximum
2700
+ // call stack size exceeded", aborting resolution mid-sync (#1558).
2701
+ for (const row of chunkRows)
2702
+ rows.push(row);
2703
+ }
2704
+ return rows.map((row) => ({
2705
+ fromNodeId: row.from_node_id,
2706
+ referenceName: row.reference_name,
2707
+ referenceKind: row.reference_kind,
2708
+ line: row.line,
2709
+ column: row.col,
2710
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2711
+ filePath: row.file_path,
2712
+ language: row.language,
2713
+ rowId: row.id,
2714
+ }));
2715
+ }
2716
+ /**
2717
+ * Delete all unresolved references (after resolution)
2718
+ */
2719
+ clearUnresolvedReferences() {
2720
+ this.db.exec('DELETE FROM unresolved_refs');
2721
+ }
2722
+ /**
2723
+ * Delete resolved references by their IDs
2724
+ */
2725
+ deleteResolvedReferences(fromNodeIds) {
2726
+ if (fromNodeIds.length === 0)
2727
+ return;
2728
+ // Chunk under SQLite's parameter limit, matching every other IN-list in
2729
+ // this file. The internal resolution path uses deleteSpecificResolvedReferences
2730
+ // instead, but QueryBuilder is part of the public API, so a library consumer
2731
+ // passing more ids than SQLITE_MAX_VARIABLE_NUMBER (32766 on the bundled
2732
+ // node:sqlite) would otherwise hit "too many SQL variables". (#540, #1001)
2733
+ for (let i = 0; i < fromNodeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2734
+ const chunk = fromNodeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2735
+ const placeholders = chunk.map(() => '?').join(',');
2736
+ this.db.prepare(`DELETE FROM unresolved_refs WHERE from_node_id IN (${placeholders})`).run(...chunk);
2737
+ }
2738
+ }
2739
+ /**
2740
+ * Delete specific resolved references by (fromNodeId, referenceName, referenceKind) tuples.
2741
+ * More precise than deleteResolvedReferences — only removes refs that were actually resolved.
2742
+ */
2743
+ deleteSpecificResolvedReferences(refs) {
2744
+ if (refs.length === 0)
2745
+ return 0;
2746
+ const stmt = this.db.prepare('DELETE FROM unresolved_refs WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?');
2747
+ // Returns rows actually removed (SQLite `changes`, summed): the batched
2748
+ // resolution loop's non-progress guard keys on this — zero removals from
2749
+ // a batch that claimed work is the direct runaway signal (§7a.2).
2750
+ let changed = 0;
2751
+ const deleteMany = this.db.transaction((items) => {
2752
+ for (const ref of items) {
2753
+ changed += stmt.run(ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
2754
+ }
2755
+ });
2756
+ deleteMany(refs);
2757
+ return changed;
2758
+ }
2759
+ /**
2760
+ * Delete unresolved-ref rows by row id — the precise cleanup for refs a
2761
+ * resolution pass actually processed. The key-tuple variant above also
2762
+ * deletes SIBLING rows (same caller calling the same callee at other lines)
2763
+ * that a later batch hasn't attempted yet, so when a batch boundary split a
2764
+ * caller's same-named call sites, the later sites' edges were silently never
2765
+ * created (#1269).
2766
+ */
2767
+ deleteReferencesByRowIds(rowIds) {
2768
+ if (rowIds.length === 0)
2769
+ return 0;
2770
+ // One transaction for all chunks (each chunk was previously its own
2771
+ // implicit transaction = its own WAL commit — measurable on 100k+-ref
2772
+ // resolution persists), and the full-size chunk statement is cached so
2773
+ // repeat calls skip the re-prepare; only the final partial chunk (if any)
2774
+ // prepares ad hoc. Returns rows actually removed (summed `changes`) for
2775
+ // the batched loop's non-progress guard (§7a.2).
2776
+ let changed = 0;
2777
+ this.db.transaction(() => {
2778
+ for (let i = 0; i < rowIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2779
+ const chunk = rowIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2780
+ if (chunk.length === SQLITE_PARAM_CHUNK_SIZE) {
2781
+ if (!this.stmts.deleteRefsByRowIdsFull) {
2782
+ const placeholders = new Array(SQLITE_PARAM_CHUNK_SIZE).fill('?').join(',');
2783
+ this.stmts.deleteRefsByRowIdsFull = this.db.prepare(`DELETE FROM unresolved_refs WHERE id IN (${placeholders})`);
2784
+ }
2785
+ changed += this.stmts.deleteRefsByRowIdsFull.run(...chunk).changes;
2786
+ }
2787
+ else {
2788
+ const placeholders = chunk.map(() => '?').join(',');
2789
+ changed += this.db.prepare(`DELETE FROM unresolved_refs WHERE id IN (${placeholders})`).run(...chunk).changes;
2790
+ }
2791
+ }
2792
+ })();
2793
+ return changed;
2794
+ }
2795
+ /**
2796
+ * Mark refs a completed resolution pass could not resolve as status='failed'
2797
+ * instead of deleting them (#1240). Failed rows are invisible to the pending
2798
+ * count/batch readers (so drain loops and the #1187 orphan sweep still
2799
+ * terminate) but stay queryable by name_tail so a later sync can retry them
2800
+ * when a changed file introduces a symbol that could satisfy them. name_tail
2801
+ * is (re)written here so rows inserted before the v8 migration get their
2802
+ * tail the first time they're attempted.
2803
+ */
2804
+ markReferencesFailed(refs) {
2805
+ if (refs.length === 0)
2806
+ return 0;
2807
+ const stmt = this.db.prepare("UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?");
2808
+ let changed = 0;
2809
+ const markMany = this.db.transaction((items) => {
2810
+ for (const ref of items) {
2811
+ changed += stmt.run(referenceNameTail(ref.referenceName), ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
2812
+ }
2813
+ });
2814
+ markMany(refs);
2815
+ return changed;
2816
+ }
2817
+ /**
2818
+ * Park refs as status='failed' by row id — the precise counterpart of
2819
+ * markReferencesFailed, for the same reason as deleteReferencesByRowIds:
2820
+ * the key-tuple variant also flips same-key sibling rows in later batches
2821
+ * to 'failed' before they were ever attempted (#1269). Resolution outcome
2822
+ * can differ per call site (receiver-type inference reads the ref's line),
2823
+ * so a sibling must not inherit this row's failure.
2824
+ */
2825
+ markReferencesFailedByRowIds(refs) {
2826
+ if (refs.length === 0)
2827
+ return 0;
2828
+ const stmt = this.db.prepare("UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE id = ?");
2829
+ let changed = 0;
2830
+ const markMany = this.db.transaction((items) => {
2831
+ for (const ref of items) {
2832
+ changed += stmt.run(referenceNameTail(ref.referenceName), ref.rowId).changes;
2833
+ }
2834
+ });
2835
+ markMany(refs);
2836
+ return changed;
2837
+ }
2838
+ /**
2839
+ * Failed refs whose name tail matches one of the given symbol names — the
2840
+ * candidates a sync should retry after files carrying those names changed
2841
+ * (#1240). Names matching more than `perNameCeiling` failed refs are
2842
+ * skipped entirely: at that population a name is external/builtin noise
2843
+ * (`get`, `map`, …) that one new definition won't resolve — the same
2844
+ * rationale as resolution's AMBIGUOUS_NAME_CEILING (#999) — and retrying an
2845
+ * arbitrary subset would be both wasted work and incoherent coverage.
2846
+ */
2847
+ getRetryableFailedReferences(names, perNameCeiling = 500) {
2848
+ if (names.length === 0)
2849
+ return [];
2850
+ // Pass 1: per-tail counts, chunked under the SQLite parameter limit.
2851
+ const retryNames = [];
2852
+ for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2853
+ const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2854
+ const placeholders = chunk.map(() => '?').join(',');
2855
+ const counts = this.db
2856
+ .prepare(`SELECT name_tail, COUNT(*) as count FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders}) GROUP BY name_tail`)
2857
+ .all(...chunk);
2858
+ for (const row of counts) {
2859
+ if (row.count <= perNameCeiling)
2860
+ retryNames.push(row.name_tail);
2861
+ }
2862
+ }
2863
+ if (retryNames.length === 0)
2864
+ return [];
2865
+ // Pass 2: load the surviving rows.
2866
+ const rows = [];
2867
+ for (let i = 0; i < retryNames.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2868
+ const chunk = retryNames.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2869
+ const placeholders = chunk.map(() => '?').join(',');
2870
+ const chunkRows = this.db
2871
+ .prepare(`SELECT * FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders})`)
2872
+ .all(...chunk);
2873
+ // Loop, not spread — same V8 argument-limit hazard as
2874
+ // getUnresolvedReferencesByFiles (#1558): a large definition delta can
2875
+ // select an unbounded number of failed rows per chunk.
2876
+ for (const row of chunkRows)
2877
+ rows.push(row);
2878
+ }
2879
+ return rows.map((row) => ({
2880
+ fromNodeId: row.from_node_id,
2881
+ referenceName: row.reference_name,
2882
+ referenceKind: row.reference_kind,
2883
+ line: row.line,
2884
+ column: row.col,
2885
+ candidates: row.candidates ? (0, utils_1.safeJsonParse)(row.candidates, undefined) : undefined,
2886
+ filePath: row.file_path,
2887
+ language: row.language,
2888
+ rowId: row.id,
2889
+ }));
2890
+ }
2891
+ /**
2892
+ * Resolution edges whose TARGET symbol is named one of `names` — the edges a
2893
+ * sync must re-resolve after `names` gained or lost a definition (CG-33).
2894
+ *
2895
+ * Resolution binds a reference to a node whose name matches the reference's
2896
+ * tail, and it picks among ALL same-named definitions project-wide. So adding
2897
+ * or removing one definition of `pct` changes the answer for every `pct(...)`
2898
+ * reference in the repo — including references in files this sync never
2899
+ * touches, whose edges nothing else revisits. Those edges' current target is,
2900
+ * by that same rule, a node named `pct`, which is why the target's name is a
2901
+ * sufficient (and index-backed, via idx_nodes_name) way to find them without
2902
+ * a schema change or a scan of edge metadata.
2903
+ *
2904
+ * Returns the source file/language alongside each edge so the caller can
2905
+ * resurrect it as its original reference. Excludes `provenance='heuristic'`
2906
+ * (synthesized dispatch edges are not resolution output and carry no refName
2907
+ * stamp to resurrect from — deleting one would be a permanent loss).
2908
+ *
2909
+ * Names matching more than `perNameCeiling` edges are skipped entirely, same
2910
+ * rationale and same default as {@link getRetryableFailedReferences}: at that
2911
+ * population the name is generic (`get`, `clear`, …), one definition changing
2912
+ * won't flip most of them, and rebinding an arbitrary subset is both wasted
2913
+ * work and incoherent coverage.
2914
+ */
2915
+ getResolutionEdgesByTargetName(names, perNameCeiling = 500) {
2916
+ if (names.length === 0)
2917
+ return [];
2918
+ // Pass 1: per-name edge counts, chunked under the SQLite parameter limit.
2919
+ const keep = [];
2920
+ for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2921
+ const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2922
+ const placeholders = chunk.map(() => '?').join(',');
2923
+ const counts = this.db
2924
+ .prepare(`SELECT tgt.name AS name, COUNT(*) AS count
2925
+ FROM edges e
2926
+ JOIN nodes tgt ON tgt.id = e.target
2927
+ WHERE tgt.name IN (${placeholders})
2928
+ AND (e.provenance IS NULL OR e.provenance != 'heuristic')
2929
+ GROUP BY tgt.name`)
2930
+ .all(...chunk);
2931
+ for (const row of counts) {
2932
+ if (row.count <= perNameCeiling)
2933
+ keep.push(row.name);
2934
+ }
2935
+ }
2936
+ if (keep.length === 0)
2937
+ return [];
2938
+ // Pass 2: load the surviving edges with the source file context a
2939
+ // resurrection needs.
2940
+ const out = [];
2941
+ for (let i = 0; i < keep.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2942
+ const chunk = keep.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2943
+ const placeholders = chunk.map(() => '?').join(',');
2944
+ const rows = this.db
2945
+ .prepare(`SELECT e.*, src.file_path AS source_file_path, src.language AS source_language
2946
+ FROM edges e
2947
+ JOIN nodes tgt ON tgt.id = e.target
2948
+ JOIN nodes src ON src.id = e.source
2949
+ WHERE tgt.name IN (${placeholders})
2950
+ AND (e.provenance IS NULL OR e.provenance != 'heuristic')`)
2951
+ .all(...chunk);
2952
+ for (const row of rows) {
2953
+ out.push({
2954
+ ...rowToEdge(row),
2955
+ edgeId: row.id,
2956
+ sourceFilePath: row.source_file_path,
2957
+ sourceLanguage: row.source_language,
2958
+ });
2959
+ }
2960
+ }
2961
+ return out;
2962
+ }
2963
+ /** Delete edges by primary key — the rebind pass's half of a re-resolution. */
2964
+ deleteEdgesByIds(edgeIds) {
2965
+ if (edgeIds.length === 0)
2966
+ return 0;
2967
+ let changed = 0;
2968
+ this.db.transaction(() => {
2969
+ for (let i = 0; i < edgeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2970
+ const chunk = edgeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2971
+ const placeholders = chunk.map(() => '?').join(',');
2972
+ changed += this.db.prepare(`DELETE FROM edges WHERE id IN (${placeholders})`).run(...chunk).changes;
2973
+ }
2974
+ })();
2975
+ return changed;
2976
+ }
2977
+ /**
2978
+ * Distinct node names present in the given files — the symbol names a sync
2979
+ * pass uses to look up retryable failed refs after those files changed.
2980
+ */
2981
+ getNodeNamesByFiles(filePaths) {
2982
+ if (filePaths.length === 0)
2983
+ return [];
2984
+ const names = new Set();
2985
+ for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
2986
+ const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
2987
+ const placeholders = chunk.map(() => '?').join(',');
2988
+ const rows = this.db
2989
+ .prepare(`SELECT DISTINCT name FROM nodes WHERE file_path IN (${placeholders})`)
2990
+ .all(...chunk);
2991
+ for (const row of rows)
2992
+ names.add(row.name);
2993
+ }
2994
+ return [...names];
2995
+ }
2996
+ /**
2997
+ * Distinct `file\0name` pairs defined by the given files — the shape sync's
2998
+ * definition delta needs (CG-33).
2999
+ *
3000
+ * Deliberately NOT `getNodeNamesByFiles`: a bare name set is taken over the
3001
+ * WHOLE changed batch, so a name that moves between two files in one commit
3002
+ * (or exists in one changed file and is newly added to another) appears on
3003
+ * both sides and cancels out of the symmetric difference — even though a
3004
+ * definition genuinely appeared or vanished and every reference to that name
3005
+ * repo-wide may now bind elsewhere. Keying by file makes each definition its
3006
+ * own fact, so the move is seen as one removal plus one addition.
3007
+ */
3008
+ getNodeNamePairsByFiles(filePaths) {
3009
+ const pairs = new Set();
3010
+ if (filePaths.length === 0)
3011
+ return pairs;
3012
+ for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
3013
+ const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
3014
+ const placeholders = chunk.map(() => '?').join(',');
3015
+ const rows = this.db
3016
+ .prepare(`SELECT DISTINCT file_path, name FROM nodes WHERE file_path IN (${placeholders})`)
3017
+ .all(...chunk);
3018
+ // NUL-joined: a path or a symbol name can contain a space, never a NUL.
3019
+ for (const row of rows)
3020
+ pairs.add(`${row.file_path}\0${row.name}`);
3021
+ }
3022
+ return pairs;
3023
+ }
3024
+ // ===========================================================================
3025
+ // Statistics
3026
+ // ===========================================================================
3027
+ /**
3028
+ * Lightweight (nodes, edges) count snapshot. Used around an index/sync
3029
+ * run to compute true additions across extraction + resolution +
3030
+ * synthesis — the per-phase counter in the orchestrator only sees
3031
+ * extraction's contribution, which is why the CLI summary under-reported
3032
+ * the edge count (resolution + synthesizer edges were invisible).
3033
+ */
3034
+ getNodeAndEdgeCount() {
3035
+ return this.db
3036
+ .prepare('SELECT (SELECT COUNT(*) FROM nodes) AS nodes, (SELECT COUNT(*) FROM edges) AS edges')
3037
+ .get();
3038
+ }
3039
+ /**
3040
+ * Get graph statistics
3041
+ */
3042
+ getStats() {
3043
+ // Single query for all three aggregate counts
3044
+ const counts = this.db.prepare(`
3045
+ SELECT
3046
+ (SELECT COUNT(*) FROM nodes) AS node_count,
3047
+ (SELECT COUNT(*) FROM edges) AS edge_count,
3048
+ (SELECT COUNT(*) FROM files) AS file_count
3049
+ `).get();
3050
+ const nodesByKind = {};
3051
+ const nodeKindRows = this.db
3052
+ .prepare('SELECT kind, COUNT(*) as count FROM nodes GROUP BY kind')
3053
+ .all();
3054
+ for (const row of nodeKindRows) {
3055
+ nodesByKind[row.kind] = row.count;
3056
+ }
3057
+ const edgesByKind = {};
3058
+ const edgeKindRows = this.db
3059
+ .prepare('SELECT kind, COUNT(*) as count FROM edges GROUP BY kind')
3060
+ .all();
3061
+ for (const row of edgeKindRows) {
3062
+ edgesByKind[row.kind] = row.count;
3063
+ }
3064
+ const filesByLanguage = {};
3065
+ const languageRows = this.db
3066
+ .prepare('SELECT language, COUNT(*) as count FROM files GROUP BY language')
3067
+ .all();
3068
+ for (const row of languageRows) {
3069
+ filesByLanguage[row.language] = row.count;
3070
+ }
3071
+ return {
3072
+ nodeCount: counts.node_count,
3073
+ edgeCount: counts.edge_count,
3074
+ fileCount: counts.file_count,
3075
+ nodesByKind,
3076
+ edgesByKind,
3077
+ filesByLanguage,
3078
+ dbSizeBytes: 0, // Set by caller using DatabaseConnection.getSize()
3079
+ walSizeBytes: 0, // Set by caller using DatabaseConnection.getWalSizeBytes()
3080
+ lastUpdated: Date.now(),
3081
+ };
3082
+ }
3083
+ // ===========================================================================
3084
+ // Project Metadata
3085
+ // ===========================================================================
3086
+ /**
3087
+ * Get a metadata value by key
3088
+ */
3089
+ getMetadata(key) {
3090
+ const row = this.db.prepare('SELECT value FROM project_metadata WHERE key = ?').get(key);
3091
+ return row?.value ?? null;
3092
+ }
3093
+ /**
3094
+ * Set a metadata key-value pair (upsert)
3095
+ */
3096
+ setMetadata(key, value) {
3097
+ 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());
3098
+ }
3099
+ /**
3100
+ * Get all metadata as a key-value record
3101
+ */
3102
+ getAllMetadata() {
3103
+ const rows = this.db.prepare('SELECT key, value FROM project_metadata').all();
3104
+ const result = {};
3105
+ for (const row of rows) {
3106
+ result[row.key] = row.value;
3107
+ }
3108
+ return result;
3109
+ }
3110
+ /**
3111
+ * Clear all data from the database
3112
+ */
3113
+ clear() {
3114
+ this.nodeCache.clear();
3115
+ this.db.transaction(() => {
3116
+ this.db.exec('DELETE FROM unresolved_refs');
3117
+ this.db.exec('DELETE FROM edges');
3118
+ this.db.exec('DELETE FROM nodes');
3119
+ this.db.exec('DELETE FROM files');
3120
+ })();
3121
+ }
3122
+ }
3123
+ exports.QueryBuilder = QueryBuilder;
3124
+ function foldModuleRows(rows, options) {
3125
+ // A module id is a path and may contain anything printable, so the key
3126
+ // separator has to be something a path cannot hold.
3127
+ const SEP = '\u0000';
3128
+ const links = new Map();
3129
+ const pairKinds = new Set(options.pairKinds);
3130
+ const wantPairs = options.topPairsPerLink > 0 && pairKinds.size > 0;
3131
+ const pairTotals = new Map();
3132
+ for (const row of rows) {
3133
+ const linkKey = `${row.source}${SEP}${row.target}${SEP}${row.kind}`;
3134
+ const link = links.get(linkKey);
3135
+ if (link) {
3136
+ link.count += row.count;
3137
+ link.declared += row.declared;
3138
+ link.uncertain += row.uncertain;
3139
+ }
3140
+ else {
3141
+ links.set(linkKey, {
3142
+ source: row.source,
3143
+ target: row.target,
3144
+ kind: row.kind,
3145
+ count: row.count,
3146
+ declared: row.declared,
3147
+ uncertain: row.uncertain,
3148
+ });
3149
+ }
3150
+ // Only the confident half of a row can be named: an uncertain edge is a
3151
+ // guess, and printing "a to b, 12" for twelve guesses is the map claiming
3152
+ // something it does not know.
3153
+ if (!wantPairs || row.count === 0 || !pairKinds.has(row.kind))
3154
+ continue;
3155
+ const pairKey = `${row.source}${SEP}${row.target}${SEP}${row.from}${SEP}${row.to}`;
3156
+ const pair = pairTotals.get(pairKey);
3157
+ if (pair) {
3158
+ pair.count += row.count;
3159
+ pair.declared += row.declared;
3160
+ }
3161
+ else {
3162
+ pairTotals.set(pairKey, {
3163
+ source: row.source,
3164
+ target: row.target,
3165
+ from: row.from,
3166
+ to: row.to,
3167
+ count: row.count,
3168
+ declared: row.declared,
3169
+ });
3170
+ }
3171
+ }
3172
+ const byLink = new Map();
3173
+ for (const pair of pairTotals.values()) {
3174
+ const key = `${pair.source}${SEP}${pair.target}`;
3175
+ let list = byLink.get(key);
3176
+ if (!list)
3177
+ byLink.set(key, (list = []));
3178
+ list.push(pair);
3179
+ }
3180
+ const pairs = [];
3181
+ for (const list of byLink.values()) {
3182
+ list.sort((a, b) => b.declared - a.declared ||
3183
+ b.count - a.count ||
3184
+ a.from.localeCompare(b.from) ||
3185
+ a.to.localeCompare(b.to));
3186
+ for (const pair of list.slice(0, options.topPairsPerLink))
3187
+ pairs.push(pair);
3188
+ }
3189
+ return { links: [...links.values()], pairs };
3190
+ }
3191
+ //# sourceMappingURL=queries.js.map